// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package auth provides a system for identifying and authenticating
// users through third party cloud systems in Cogent Core apps.
package auth
import (
"context"
"crypto/rand"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io/fs"
"log/slog"
"net"
"net/http"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"time"
"cogentcore.org/core/base/iox/jsonx"
"cogentcore.org/core/core"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/zalando/go-keyring"
"golang.org/x/oauth2"
)
// AuthConfig is the configuration information passed to [Auth].
type AuthConfig struct {
// Ctx is the context to use. It is [context.TODO] if unspecified.
// Canceling it stops waiting for the user to sign in in the browser.
Ctx context.Context
// ProviderName is the name of the provider to authenticate with (eg: "google")
ProviderName string
// ProviderURL is the URL of the provider (eg: "https://accounts.google.com")
ProviderURL string
// ClientID is the client ID for the app, which is typically obtained through a developer oauth
// portal (eg: the Credentials section of https://console.developers.google.com/).
ClientID string
// ClientSecret is the client secret for the app, which is typically obtained through a developer oauth
// portal (eg: the Credentials section of https://console.developers.google.com/).
ClientSecret string
// TokenFile is an optional function that returns the filename at which the token for the given user will be stored as JSON,
// or rather the name of the token in the system keychain, where it is stored if there is one (see [SaveToken]).
// If it is nil or it returns "", the token is not stored. Also, if it is non-nil, Auth skips the user-facing authentication
// step if it finds a valid token at the file (ie: remember me). It checks all [AuthConfig.Accounts] until it finds one
// that works for that step. If [AuthConfig.Accounts] is nil, it checks with a blank ("") email account.
// The token is saved again whenever its access token is refreshed (see [TokenSource]).
TokenFile func(email string) string
// Accounts are optional accounts to check for the remember me feature described in [AuthConfig.TokenFile].
// If it is nil and TokenFile is not, it defaults to contain one blank ("") element.
Accounts []string
// Scopes are additional scopes to request beyond the default "openid", "profile", and "email" scopes
Scopes []string
// SelectAccount is whether to always have the user sign in in the
// browser, choosing the account there, without using a saved token,
// as for adding another account.
SelectAccount bool
// LoginHint, if set, is the email address of the account to suggest
// when the user signs in in the browser, as for signing in to an
// account again.
LoginHint string
// NoPrompt is whether to only use a saved token, returning
// [ErrNoToken] if there is none that works, instead of having the
// user sign in in the browser.
NoPrompt bool
// IssuerURL, if set, is the issuer in the discovery document of the
// provider, when it is not the ProviderURL, as for the endpoint of
// Microsoft for the accounts of all organizations, whose issuer has
// "{tenantid}" in it (each organization has its own).
IssuerURL string
// UserFromIDToken is whether to get the user info (the email address)
// from the ID token of the provider, instead of its user info
// endpoint, as for Microsoft, whose endpoint does not accept the
// access tokens of other resources (as those for mail).
UserFromIDToken bool
// OnePrompt is whether the provider takes only one value of the
// prompt parameter, as Microsoft: "select_account" for
// SelectAccount, and none otherwise (it returns a refresh token for
// the offline_access scope without asking for consent each time).
OnePrompt bool
}
// ScopesError is the error of [Auth] and [TokenSource] when the user did
// not allow all of the access of the requested scopes, as the provider can
// let the user uncheck some of them when signing in.
type ScopesError struct {
// Missing are the requested scopes that were not allowed.
Missing []string
}
func (e *ScopesError) Error() string {
return fmt.Sprintf("not all of the access was allowed when signing in (missing %s): sign in again and allow all of it", strings.Join(e.Missing, ", "))
}
// ErrNoToken is the error of [Auth] and [TokenSource] with
// [AuthConfig.NoPrompt] when there is no saved token that works.
var ErrNoToken = errors.New("auth: no saved token")
// callbackAddress is the address of the local server that gets the
// result of the user signing in in the browser.
const callbackAddress = "127.0.0.1:5556"
// signInMu makes only one sign-in in the browser happen at a time,
// as they use the same local server address.
var signInMu sync.Mutex
// Auth authenticates the user using the given configuration information and returns the
// resulting oauth token and user info. See [AuthConfig] for more information on the
// configuration options. Use [TokenSource] to keep the access token fresh.
func Auth(c *AuthConfig) (*oauth2.Token, *oidc.UserInfo, error) {
ts, userInfo, err := TokenSource(c)
if err != nil {
return nil, nil, err
}
token, err := ts.Token()
if err != nil {
return nil, nil, err
}
return token, userInfo, nil
}
// TokenSource authenticates the user like [Auth], and returns a token
// source whose tokens have a valid access token, refreshed as needed
// (which requires a refresh token, which the provider returns for the
// offline access requested here), and the user info. Each refreshed
// token is saved to the token file (see [AuthConfig.TokenFile]).
func TokenSource(c *AuthConfig) (oauth2.TokenSource, *oidc.UserInfo, error) {
if c.Ctx == nil {
c.Ctx = context.TODO()
}
if c.ClientID == "" || (c.ClientSecret == "" && !c.UserFromIDToken) {
slog.Warn("got empty client id and/or client secret; did you forgot to set env variables?")
}
pctx := c.Ctx
if c.IssuerURL != "" {
pctx = oidc.InsecureIssuerURLContext(pctx, c.IssuerURL)
}
provider, err := oidc.NewProvider(pctx, c.ProviderURL)
if err != nil {
return nil, nil, err
}
config := &oauth2.Config{
ClientID: c.ClientID,
ClientSecret: c.ClientSecret,
RedirectURL: "http://" + callbackAddress + "/auth/" + c.ProviderName + "/callback",
Endpoint: provider.Endpoint(),
Scopes: append([]string{oidc.ScopeOpenID, "profile", "email"}, c.Scopes...),
}
// remember me: the first saved token that still works
if c.TokenFile != nil && !c.SelectAccount {
accounts := c.Accounts
if accounts == nil {
accounts = []string{""}
}
for _, account := range accounts {
tf := c.TokenFile(account)
if tf == "" {
continue
}
token, err := loadToken(tf)
if token == nil && err == nil {
slog.Debug("auth: no saved token", "account", account)
continue
}
slog.Debug("auth: trying the saved token", "account", account, "file", tf,
"hasRefreshToken", token.RefreshToken != "", "expiry", token.Expiry)
if err != nil {
return nil, nil, err
}
if token.RefreshToken != "" {
// refresh now, which checks that the refresh token still
// works, and gets the scopes that it allows
token.Expiry = time.Unix(1, 0)
}
ts, userInfo, err := tokenSource(c, provider, config, token, account)
if err != nil {
var re *oauth2.RetrieveError
var se *ScopesError
if !errors.As(err, &re) && !errors.As(err, &se) {
// not known not to work, as when offline
slog.Debug("auth: could not check the saved token", "account", account, "err", err)
return nil, nil, err
}
// such as a revoked or expired refresh token
slog.Info("auth: saved token does not work", "account", account, "err", err)
continue
}
slog.Debug("auth: the saved token works", "account", account, "email", userInfo.Email)
return ts, userInfo, nil
}
}
if c.NoPrompt {
return nil, nil, ErrNoToken
}
token, err := signIn(c, config)
if err != nil {
slog.Debug("auth: signing in failed", "err", err)
return nil, nil, err
}
ts, userInfo, err := tokenSource(c, provider, config, token, "")
if err != nil {
slog.Debug("auth: the token of signing in does not work", "err", err)
return nil, nil, err
}
slog.Debug("auth: signed in", "email", userInfo.Email)
return ts, userInfo, nil
}
// tokenSource returns the saving token source for the given token and
// the user info, saving the token. The given account, if any, is that of
// a saved token, for [AuthConfig.UserFromIDToken] when a refreshed token
// has no ID token.
func tokenSource(c *AuthConfig, provider *oidc.Provider, config *oauth2.Config, token *oauth2.Token, account string) (oauth2.TokenSource, *oidc.UserInfo, error) {
src := config.TokenSource(c.Ctx, token)
fresh, err := src.Token()
if err != nil {
slog.Debug("auth: getting a fresh token failed", "err", err)
return nil, nil, err
}
slog.Debug("auth: fresh token", "grantedScopes", fresh.Extra("scope"), "expiry", fresh.Expiry,
"hasRefreshToken", fresh.RefreshToken != "", "refreshed", fresh.AccessToken != token.AccessToken)
if err := checkScopes(fresh, c.Scopes); err != nil {
slog.Debug("auth: missing scopes", "err", err)
return nil, nil, err
}
var userInfo *oidc.UserInfo
if c.UserFromIDToken {
userInfo, err = idTokenUser(c, provider, fresh, account)
} else {
userInfo, err = provider.UserInfo(c.Ctx, oauth2.StaticTokenSource(fresh))
}
if err != nil {
slog.Debug("auth: getting the user info failed", "err", err)
return nil, nil, fmt.Errorf("failed to get user info: %w", err)
}
ts := &savingTokenSource{src: src}
if c.TokenFile != nil {
ts.file = c.TokenFile(userInfo.Email)
}
if err := ts.save(fresh); err != nil {
return nil, nil, err
}
return ts, userInfo, nil
}
// idTokenUser returns the user info of the ID token of the given token
// (see [AuthConfig.UserFromIDToken]), which is verified (except for its
// issuer, which is of the organization of the user), with the email
// address of its email claim, or else its preferred username (which is the
// address of a Microsoft account). A token without an ID token, as some
// refreshed ones, is of the given account, if any.
func idTokenUser(c *AuthConfig, provider *oidc.Provider, token *oauth2.Token, account string) (*oidc.UserInfo, error) {
raw, _ := token.Extra("id_token").(string)
if raw == "" {
if account != "" {
return &oidc.UserInfo{Email: account}, nil
}
return nil, errors.New("no ID token")
}
verifier := provider.Verifier(&oidc.Config{ClientID: c.ClientID, SkipIssuerCheck: true})
idt, err := verifier.Verify(c.Ctx, raw)
if err != nil {
return nil, fmt.Errorf("verifying the ID token: %w", err)
}
var claims struct {
Email string `json:"email"`
PreferredUsername string `json:"preferred_username"`
}
if err := idt.Claims(&claims); err != nil {
return nil, err
}
email := claims.Email
if email == "" {
email = claims.PreferredUsername
}
if email == "" {
return nil, errors.New("no email address in the ID token")
}
return &oidc.UserInfo{Subject: idt.Subject, Email: email, EmailVerified: true}, nil
}
// checkScopes returns a [*ScopesError] if the given token, from the
// provider, does not allow all of the given scopes. Tokens that do not say
// which scopes they allow (only those just received do) are not checked.
func checkScopes(token *oauth2.Token, scopes []string) error {
granted, _ := token.Extra("scope").(string)
if granted == "" {
return nil
}
have := strings.Fields(granted)
var missing []string
for _, s := range scopes {
if !slices.Contains(have, s) {
missing = append(missing, s)
}
}
if len(missing) > 0 {
return &ScopesError{Missing: missing}
}
return nil
}
// signIn has the user sign in in the browser, returning the token.
func signIn(c *AuthConfig, config *oauth2.Config) (*oauth2.Token, error) {
signInMu.Lock()
defer signInMu.Unlock()
b := make([]byte, 16)
rand.Read(b)
state := base64.RawURLEncoding.EncodeToString(b)
ln, err := net.Listen("tcp", callbackAddress)
if err != nil {
return nil, fmt.Errorf("starting the local server for signing in: %w", err)
}
code := make(chan string, 1)
sm := http.NewServeMux()
sm.HandleFunc("/auth/"+c.ProviderName+"/callback", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("state") != state {
http.Error(w, "state did not match", http.StatusBadRequest)
return
}
if e := r.URL.Query().Get("error"); e != "" {
slog.Debug("auth: the provider returned an error", "error", e, "description", r.URL.Query().Get("error_description"))
http.Error(w, "Not signed in: "+e, http.StatusBadRequest)
return
}
slog.Debug("auth: got the result of signing in", "scope", r.URL.Query().Get("scope"))
select {
case code <- r.URL.Query().Get("code"):
default:
}
w.Write([]byte("<h1>Signed in</h1><p>You can return to the app</p>"))
})
srv := &http.Server{Handler: sm}
go srv.Serve(ln)
defer srv.Close()
// offline access for a refresh token; consent so that the provider
// returns one even if the user has already allowed the app
prompt := "consent"
if c.SelectAccount {
prompt = "select_account consent"
}
if c.OnePrompt {
prompt = ""
if c.SelectAccount {
prompt = "select_account"
}
}
// with PKCE, which public clients (without a secret, as the desktop
// apps of Microsoft) need, and which protects the code
verifier := oauth2.GenerateVerifier()
opts := []oauth2.AuthCodeOption{oauth2.AccessTypeOffline, oauth2.S256ChallengeOption(verifier)}
if prompt != "" {
opts = append(opts, oauth2.SetAuthURLParam("prompt", prompt))
}
if c.LoginHint != "" {
opts = append(opts, oauth2.SetAuthURLParam("login_hint", c.LoginHint))
}
slog.Debug("auth: opening the browser to sign in", "provider", c.ProviderName, "scopes", config.Scopes,
"prompt", prompt, "loginHint", c.LoginHint)
core.TheApp.OpenURL(config.AuthCodeURL(state, opts...))
var cs string
select {
case cs = <-code:
case <-c.Ctx.Done():
return nil, c.Ctx.Err()
}
token, err := config.Exchange(c.Ctx, cs, oauth2.VerifierOption(verifier))
if err != nil {
slog.Debug("auth: exchanging the code for a token failed", "err", err)
return nil, fmt.Errorf("failed to exchange token: %w", err)
}
slog.Debug("auth: got a token", "grantedScopes", token.Extra("scope"), "hasRefreshToken", token.RefreshToken != "")
return token, nil
}
// savingTokenSource is a token source that saves each new token
// to its file, if any.
type savingTokenSource struct {
src oauth2.TokenSource
file string
mu sync.Mutex
access string // the access token last saved
}
func (ts *savingTokenSource) Token() (*oauth2.Token, error) {
token, err := ts.src.Token()
if err != nil {
return nil, err
}
return token, ts.save(token)
}
// save saves the given token if its access token is new.
func (ts *savingTokenSource) save(token *oauth2.Token) error {
ts.mu.Lock()
defer ts.mu.Unlock()
if ts.file == "" || token.AccessToken == ts.access {
return nil
}
if err := SaveToken(token, ts.file); err != nil {
slog.Debug("auth: saving the token failed", "file", ts.file, "err", err)
return err
}
slog.Debug("auth: saved the token", "file", ts.file, "expiry", token.Expiry)
ts.access = token.AccessToken
return nil
}
// keyringService is the service of the tokens in the system keychain
// (as the macOS Keychain), whose names are their token files.
const keyringService = "Cogent Core auth"
// loadToken returns the token saved for the given token file (see
// [AuthConfig.TokenFile]): from the system keychain, or else from the
// file, which is then moved to the keychain, if there is one. It returns
// nil if there is no saved token.
func loadToken(file string) (*oauth2.Token, error) {
data, err := keyring.Get(keyringService, file)
if err == nil {
token := &oauth2.Token{}
if err := json.Unmarshal([]byte(data), token); err != nil {
return nil, fmt.Errorf("reading the saved token: %w", err)
}
return token, nil
}
if !errors.Is(err, keyring.ErrNotFound) {
slog.Debug("auth: the keychain is not available", "err", err)
}
var token *oauth2.Token
err = jsonx.Open(&token, file)
if errors.Is(err, fs.ErrNotExist) || (err == nil && token == nil) {
return nil, nil
}
if err != nil {
return nil, err
}
if err := SaveToken(token, file); err != nil { // to the keychain
slog.Warn("auth: could not move the saved token", "file", file, "err", err)
}
return token, nil
}
// SaveToken saves the given token for the given token file (see
// [AuthConfig.TokenFile]) in the system keychain (as the macOS Keychain),
// with the name of the file, removing the file if any. Where there is no
// keychain, as on a Linux server, it is saved in the file instead,
// readable only by the user.
func SaveToken(token *oauth2.Token, file string) error {
data, err := json.Marshal(token)
if err != nil {
return err
}
kerr := keyring.Set(keyringService, file, string(data))
if kerr == nil {
if err := os.Remove(file); err != nil && !errors.Is(err, fs.ErrNotExist) {
return err
}
return nil
}
slog.Debug("auth: saving the token in a file, without a keychain", "file", file, "err", kerr)
if err := os.MkdirAll(filepath.Dir(file), 0o700); err != nil {
return err
}
return os.WriteFile(file, data, 0o600)
}
// DeleteToken deletes the token saved for the given token file (see
// [AuthConfig.TokenFile]), from the system keychain and the file.
func DeleteToken(file string) error {
err := keyring.Delete(keyringService, file)
if errors.Is(err, keyring.ErrNotFound) {
err = nil
}
if ferr := os.Remove(file); ferr != nil && !errors.Is(ferr, fs.ErrNotExist) {
return ferr
}
if err != nil {
slog.Debug("auth: deleting the token from the keychain", "file", file, "err", err)
}
return nil
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package auth
import (
"context"
"cogentcore.org/core/base/auth/cicons"
"cogentcore.org/core/base/fsx"
"cogentcore.org/core/base/strcase"
"cogentcore.org/core/colors"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/styles"
"github.com/coreos/go-oidc/v3/oidc"
"golang.org/x/oauth2"
)
// ButtonsConfig is the configuration information passed to [Buttons].
type ButtonsConfig struct {
// SuccessFunc, if non-nil, is the function called after the user successfully
// authenticates. It is passed the user's authentication token and info.
SuccessFunc func(token *oauth2.Token, userInfo *oidc.UserInfo)
// TokenFile, if non-nil, is the function used to determine what token file function is
// used for [AuthConfig.TokenFile]. It is passed the provider being used (eg: "google") and the
// email address of the user authenticating.
TokenFile func(provider, email string) string
// Accounts are optional accounts to check for the remember me feature described in [AuthConfig.TokenFile].
// See [AuthConfig.Accounts] for more information. If it is nil and TokenFile is not, it defaults to contain
// one blank ("") element.
Accounts []string
// Scopes, if non-nil, is a map of scopes to pass to [Auth], keyed by the
// provider being used (eg: "google").
Scopes map[string][]string
}
// Buttons adds a new vertical layout to the given parent with authentication
// buttons for major platforms, using the given configuration options. See
// [ButtonsConfig] for more information on the configuration options. The
// configuration options can be nil, in which case default values will be used.
func Buttons(par core.Widget, c *ButtonsConfig) *core.Frame {
ly := core.NewFrame(par)
ly.Styler(func(s *styles.Style) {
s.Direction = styles.Column
})
GoogleButton(ly, c)
return ly
}
// Button makes a new button for signing in with the provider
// that has the given name and auth func. It should not typically
// be used by end users; instead, use [Buttons] or the platform-specific
// functions (eg: [Google]). The configuration options can be nil, in
// which case default values will be used.
func Button(par core.Widget, c *ButtonsConfig, provider string, authFunc func(c *AuthConfig) (*oauth2.Token, *oidc.UserInfo, error)) *core.Button {
if c == nil {
c = &ButtonsConfig{}
}
if c.SuccessFunc == nil {
c.SuccessFunc = func(token *oauth2.Token, userInfo *oidc.UserInfo) {}
}
if c.Scopes == nil {
c.Scopes = map[string][]string{}
}
bt := core.NewButton(par).SetText("Sign in")
tf := func(email string) string {
if c.TokenFile != nil {
return c.TokenFile(provider, email)
}
return ""
}
ac := &AuthConfig{
Ctx: context.TODO(),
ProviderName: provider,
TokenFile: tf,
Accounts: c.Accounts,
Scopes: c.Scopes[provider],
}
auth := func() {
token, userInfo, err := authFunc(ac)
if err != nil {
core.ErrorDialog(bt, err, "Error signing in with "+strcase.ToSentence(provider))
return
}
c.SuccessFunc(token, userInfo)
}
bt.OnClick(func(e events.Event) {
auth()
})
// if we have a valid token file, we auth immediately without the user clicking on the button
if c.TokenFile != nil {
if c.Accounts == nil {
c.Accounts = []string{""}
}
for _, account := range c.Accounts {
tf := c.TokenFile(provider, account)
if tf != "" {
exists, err := fsx.FileExists(tf)
if err != nil {
core.ErrorDialog(bt, err, "Error searching for saved "+strcase.ToSentence(provider)+" auth token file")
return bt
}
if exists {
// have to wait until the scene is shown in case any dialogs are created
bt.OnShow(func(e events.Event) {
auth()
})
break // auth uses the first that works
}
}
}
}
return bt
}
// GoogleButton adds a new button for signing in with Google
// to the given parent using the given configuration information.
func GoogleButton(par core.Widget, c *ButtonsConfig) *core.Button {
bt := Button(par, c, "google", Google).SetType(core.ButtonOutlined).
SetText("Sign in with Google").SetIcon(cicons.SignInWithGoogle)
bt.Styler(func(s *styles.Style) {
s.Color = colors.Scheme.OnSurface
})
return bt
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"cogentcore.org/core/base/auth"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/core"
"github.com/coreos/go-oidc/v3/oidc"
"golang.org/x/oauth2"
)
func main() {
b := core.NewBody("Auth basic example")
fun := func(token *oauth2.Token, userInfo *oidc.UserInfo) {
d := core.NewBody("User info")
core.NewText(d).SetType(core.TextHeadlineMedium).SetText("Basic info")
core.NewForm(d).SetStruct(userInfo)
core.NewText(d).SetType(core.TextHeadlineMedium).SetText("Detailed info")
claims := map[string]any{}
errors.Log(userInfo.Claims(&claims))
core.NewKeyedList(d).SetMap(&claims)
d.AddOKOnly().RunFullDialog(b)
}
auth.Buttons(b, &auth.ButtonsConfig{SuccessFunc: fun})
b.RunMainWindow()
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"path/filepath"
"cogentcore.org/core/base/auth"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/core"
"github.com/coreos/go-oidc/v3/oidc"
"golang.org/x/oauth2"
)
func main() {
b := core.NewBody("Auth scopes and token file example")
fun := func(token *oauth2.Token, userInfo *oidc.UserInfo) {
d := core.NewBody()
core.NewText(d).SetType(core.TextHeadlineMedium).SetText("Basic info")
core.NewForm(d).SetStruct(userInfo)
core.NewText(d).SetType(core.TextHeadlineMedium).SetText("Detailed info")
claims := map[string]any{}
errors.Log(userInfo.Claims(&claims))
core.NewKeyedList(d).SetMap(&claims)
d.AddOKOnly().RunFullDialog(b)
}
auth.Buttons(b, &auth.ButtonsConfig{
SuccessFunc: fun,
TokenFile: func(provider, email string) string {
return filepath.Join(core.TheApp.AppDataDir(), provider+"-token.json")
},
Scopes: map[string][]string{
"google": {"https://mail.google.com/"},
},
})
b.RunMainWindow()
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package auth
import (
"os"
"slices"
"github.com/coreos/go-oidc/v3/oidc"
"golang.org/x/oauth2"
)
// Google authenticates the user with Google using [Auth] and the given configuration
// information and returns the resulting oauth token and user info. It sets the values
// of [AuthConfig.ProviderName], [AuthConfig.ProviderURL], [AuthConfig.ClientID], and
// [AuthConfig.ClientSecret] if they are not already set.
func Google(c *AuthConfig) (*oauth2.Token, *oidc.UserInfo, error) {
return Auth(googleConfig(c))
}
// GoogleTokenSource authenticates the user with Google using [TokenSource],
// setting the values of the configuration like [Google].
func GoogleTokenSource(c *AuthConfig) (oauth2.TokenSource, *oidc.UserInfo, error) {
return TokenSource(googleConfig(c))
}
// googleConfig sets the Google values of the given configuration,
// if they are not already set, and returns it.
func googleConfig(c *AuthConfig) *AuthConfig {
if c.ProviderName == "" {
c.ProviderName = "google"
}
if c.ProviderURL == "" {
c.ProviderURL = "https://accounts.google.com"
}
if c.ClientID == "" {
c.ClientID = os.Getenv("GOOGLE_OAUTH2_CLIENT_ID")
}
if c.ClientSecret == "" {
c.ClientSecret = os.Getenv("GOOGLE_OAUTH2_CLIENT_SECRET")
}
return c
}
// Microsoft authenticates the user with Microsoft (a work or school
// account of Microsoft 365, or a personal one, as of Outlook.com) using
// [Auth], setting the values of the configuration like [Google], with the
// client ID of the environment variable MICROSOFT_OAUTH2_CLIENT_ID (of an
// app registered in the Microsoft Entra admin center, as a public client,
// of the platform "Mobile and desktop applications", with the redirect URI
// http://127.0.0.1:5556/auth/microsoft/callback), and no client secret.
func Microsoft(c *AuthConfig) (*oauth2.Token, *oidc.UserInfo, error) {
return Auth(microsoftConfig(c))
}
// MicrosoftTokenSource authenticates the user with Microsoft using
// [TokenSource], setting the values of the configuration like [Microsoft].
func MicrosoftTokenSource(c *AuthConfig) (oauth2.TokenSource, *oidc.UserInfo, error) {
return TokenSource(microsoftConfig(c))
}
// microsoftConfig sets the Microsoft values of the given configuration,
// if they are not already set, and returns it: the endpoint for the
// accounts of all organizations, and personal ones, whose issuer is that
// of the organization of the account, the email address from the ID
// token, the offline_access scope for a refresh token, and one prompt.
func microsoftConfig(c *AuthConfig) *AuthConfig {
if c.ProviderName == "" {
c.ProviderName = "microsoft"
}
if c.ProviderURL == "" {
c.ProviderURL = "https://login.microsoftonline.com/common/v2.0"
c.IssuerURL = "https://login.microsoftonline.com/{tenantid}/v2.0"
}
if c.ClientID == "" {
c.ClientID = os.Getenv("MICROSOFT_OAUTH2_CLIENT_ID")
}
if !slices.Contains(c.Scopes, "offline_access") {
c.Scopes = append(slices.Clone(c.Scopes), "offline_access")
}
c.UserFromIDToken = true
c.OnePrompt = true
return c
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on https://github.com/c2h5oh/datasize
// Copyright (c) 2016 Maciej Lisiewski
// Package datasize provides a data size type and constants.
package datasize
import (
"errors"
"fmt"
"strconv"
"strings"
)
// Size represents a data size.
type Size uint64
const (
B Size = 1
KB = B << 10
MB = KB << 10
GB = MB << 10
TB = GB << 10
PB = TB << 10
EB = PB << 10
fnUnmarshalText string = "UnmarshalText"
maxUint64 uint64 = (1 << 64) - 1
cutoff uint64 = maxUint64 / 10
)
var ErrBits = errors.New("unit with capital unit prefix and lower case unit (b) - bits, not bytes")
func (b Size) Bytes() uint64 {
return uint64(b)
}
func (b Size) KBytes() float64 {
v := b / KB
r := b % KB
return float64(v) + float64(r)/float64(KB)
}
func (b Size) MBytes() float64 {
v := b / MB
r := b % MB
return float64(v) + float64(r)/float64(MB)
}
func (b Size) GBytes() float64 {
v := b / GB
r := b % GB
return float64(v) + float64(r)/float64(GB)
}
func (b Size) TBytes() float64 {
v := b / TB
r := b % TB
return float64(v) + float64(r)/float64(TB)
}
func (b Size) PBytes() float64 {
v := b / PB
r := b % PB
return float64(v) + float64(r)/float64(PB)
}
func (b Size) EBytes() float64 {
v := b / EB
r := b % EB
return float64(v) + float64(r)/float64(EB)
}
// String returns a human-readable representation of the data size.
func (b Size) String() string {
switch {
case b >= EB:
return fmt.Sprintf("%.1f EB", b.EBytes())
case b >= PB:
return fmt.Sprintf("%.1f PB", b.PBytes())
case b >= TB:
return fmt.Sprintf("%.1f TB", b.TBytes())
case b >= GB:
return fmt.Sprintf("%.1f GB", b.GBytes())
case b >= MB:
return fmt.Sprintf("%.1f MB", b.MBytes())
case b >= KB:
return fmt.Sprintf("%.1f KB", b.KBytes())
default:
return fmt.Sprintf("%d B", b)
}
}
// MachineString returns a machine-friendly representation of the data size.
func (b Size) MachineString() string {
switch {
case b == 0:
return "0B"
case b%EB == 0:
return fmt.Sprintf("%dEB", b/EB)
case b%PB == 0:
return fmt.Sprintf("%dPB", b/PB)
case b%TB == 0:
return fmt.Sprintf("%dTB", b/TB)
case b%GB == 0:
return fmt.Sprintf("%dGB", b/GB)
case b%MB == 0:
return fmt.Sprintf("%dMB", b/MB)
case b%KB == 0:
return fmt.Sprintf("%dKB", b/KB)
default:
return fmt.Sprintf("%dB", b)
}
}
func (b Size) MarshalText() ([]byte, error) {
return []byte(b.MachineString()), nil
}
func (b *Size) UnmarshalText(t []byte) error {
var val uint64
var unit string
// copy for error message
t0 := t
var c byte
var i int
ParseLoop:
for i < len(t) {
c = t[i]
switch {
case '0' <= c && c <= '9':
if val > cutoff {
goto Overflow
}
c = c - '0'
val *= 10
if val > val+uint64(c) {
// val+v overflows
goto Overflow
}
val += uint64(c)
i++
default:
if i == 0 {
goto SyntaxError
}
break ParseLoop
}
}
unit = strings.TrimSpace(string(t[i:]))
switch unit {
case "Kb", "Mb", "Gb", "Tb", "Pb", "Eb":
goto BitsError
}
unit = strings.ToLower(unit)
switch unit {
case "", "b", "byte":
// do nothing - already in bytes
case "k", "kb", "kilo", "kilobyte", "kilobytes":
if val > maxUint64/uint64(KB) {
goto Overflow
}
val *= uint64(KB)
case "m", "mb", "mega", "megabyte", "megabytes":
if val > maxUint64/uint64(MB) {
goto Overflow
}
val *= uint64(MB)
case "g", "gb", "giga", "gigabyte", "gigabytes":
if val > maxUint64/uint64(GB) {
goto Overflow
}
val *= uint64(GB)
case "t", "tb", "tera", "terabyte", "terabytes":
if val > maxUint64/uint64(TB) {
goto Overflow
}
val *= uint64(TB)
case "p", "pb", "peta", "petabyte", "petabytes":
if val > maxUint64/uint64(PB) {
goto Overflow
}
val *= uint64(PB)
case "e", "eb", "exa", "exabyte", "exabytes", "E", "EB", "eB":
if val > maxUint64/uint64(EB) {
goto Overflow
}
val *= uint64(EB)
default:
goto SyntaxError
}
*b = Size(val)
return nil
Overflow:
*b = Size(maxUint64)
return &strconv.NumError{Func: fnUnmarshalText, Num: string(t0), Err: strconv.ErrRange}
SyntaxError:
*b = 0
return &strconv.NumError{Func: fnUnmarshalText, Num: string(t0), Err: strconv.ErrSyntax}
BitsError:
*b = 0
return &strconv.NumError{Func: fnUnmarshalText, Num: string(t0), Err: ErrBits}
}
func Parse(t []byte) (Size, error) {
var v Size
err := v.UnmarshalText(t)
return v, err
}
func MustParse(t []byte) Size {
v, err := Parse(t)
if err != nil {
panic(err)
}
return v
}
func ParseString(s string) (Size, error) {
return Parse([]byte(s))
}
func MustParseString(s string) Size {
return MustParse([]byte(s))
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package dirsort
import (
"bytes"
"encoding/binary"
"errors"
"math"
"unicode/utf16"
)
// errBplist is the error of a binary property list that is not valid.
var errBplist = errors.New("dirsort: not a valid binary property list")
// decodeBplist decodes the given binary property list (as those of the
// view settings of the Finder), whose values are nil, bool, int64,
// float64 (also for dates), []byte, string, []any and map[string]any.
func decodeBplist(b []byte) (any, error) {
if len(b) < 8+32 || !bytes.HasPrefix(b, []byte("bplist0")) {
return nil, errBplist
}
tr := b[len(b)-32:]
d := &bplist{b: b, offSize: int(tr[6]), refSize: int(tr[7])}
numObjs := binary.BigEndian.Uint64(tr[8:])
top := binary.BigEndian.Uint64(tr[16:])
tableOff := binary.BigEndian.Uint64(tr[24:])
if d.offSize < 1 || d.offSize > 8 || d.refSize < 1 || d.refSize > 8 ||
numObjs > uint64(len(b)) || top >= numObjs ||
tableOff > uint64(len(b)) || numObjs*uint64(d.offSize) > uint64(len(b))-tableOff {
return nil, errBplist
}
d.offsets = make([]int, numObjs)
for i := range d.offsets {
p := int(tableOff) + i*d.offSize
d.offsets[i] = int(readUint(b[p : p+d.offSize]))
}
return d.object(int(top), 0)
}
// bplist is the state of decoding a binary property list.
type bplist struct {
b []byte
offSize, refSize int
offsets []int
}
// readUint returns the big-endian unsigned integer of the given bytes.
func readUint(b []byte) uint64 {
var v uint64
for _, c := range b {
v = v<<8 | uint64(c)
}
return v
}
// object decodes the object of the given index, at the given depth of
// arrays and dictionaries.
func (d *bplist) object(idx, depth int) (any, error) {
if idx < 0 || idx >= len(d.offsets) || depth > 32 {
return nil, errBplist
}
p := d.offsets[idx]
if p < 8 || p >= len(d.b) {
return nil, errBplist
}
marker := d.b[p]
kind, low := marker>>4, int(marker&0xf)
p++
switch kind {
case 0x0:
switch marker {
case 0x08:
return false, nil
case 0x09:
return true, nil
}
return nil, nil
case 0x1: // integer of 2^low bytes
n := 1 << low
if n > 16 || p+n > len(d.b) {
return nil, errBplist
}
if n == 16 { // (the low 8 bytes of a 128-bit integer)
return int64(readUint(d.b[p+8 : p+16])), nil
}
return int64(readUint(d.b[p : p+n])), nil
case 0x2, 0x3: // real, or date (a real in seconds)
n := 1 << low
if kind == 0x3 {
n = 8
}
if p+n > len(d.b) {
return nil, errBplist
}
switch n {
case 4:
return float64(math.Float32frombits(uint32(readUint(d.b[p : p+4])))), nil
case 8:
return math.Float64frombits(readUint(d.b[p : p+8])), nil
}
return nil, errBplist
}
n, p, err := d.count(low, p)
if err != nil {
return nil, err
}
switch kind {
case 0x4: // data
if p+n > len(d.b) {
return nil, errBplist
}
return bytes.Clone(d.b[p : p+n]), nil
case 0x5: // ASCII string
if p+n > len(d.b) {
return nil, errBplist
}
return string(d.b[p : p+n]), nil
case 0x6: // UTF-16 string, of n characters
if p+2*n > len(d.b) {
return nil, errBplist
}
u := make([]uint16, n)
for i := range u {
u[i] = binary.BigEndian.Uint16(d.b[p+2*i:])
}
return string(utf16.Decode(u)), nil
case 0x8: // UID
return int64(readUint(d.b[p : p+min(low+1, len(d.b)-p)])), nil
case 0xa, 0xc: // array, set
refs, err := d.refs(p, n)
if err != nil {
return nil, err
}
arr := make([]any, n)
for i, r := range refs {
if arr[i], err = d.object(r, depth+1); err != nil {
return nil, err
}
}
return arr, nil
case 0xd: // dictionary: the references of the keys, then of the values
refs, err := d.refs(p, 2*n)
if err != nil {
return nil, err
}
m := make(map[string]any, n)
for i := range n {
k, err := d.object(refs[i], depth+1)
if err != nil {
return nil, err
}
v, err := d.object(refs[n+i], depth+1)
if err != nil {
return nil, err
}
if ks, ok := k.(string); ok {
m[ks] = v
}
}
return m, nil
}
return nil, errBplist
}
// count returns the count of an object with the given low nibble of its
// marker, whose content is at the given position, which is after the
// count if it is an integer object that follows (for 15 and more), and
// that position.
func (d *bplist) count(low, p int) (int, int, error) {
if low != 0xf {
return low, p, nil
}
if p >= len(d.b) || d.b[p]>>4 != 0x1 {
return 0, 0, errBplist
}
n := 1 << (d.b[p] & 0xf)
p++
if n > 8 || p+n > len(d.b) {
return 0, 0, errBplist
}
c := readUint(d.b[p : p+n])
if c > uint64(len(d.b)) {
return 0, 0, errBplist
}
return int(c), p + n, nil
}
// refs returns the given number of object references at the given position.
func (d *bplist) refs(p, n int) ([]int, error) {
if n < 0 || p+n*d.refSize > len(d.b) {
return nil, errBplist
}
refs := make([]int, n)
for i := range refs {
q := p + i*d.refSize
refs[i] = int(readUint(d.b[q : q+d.refSize]))
}
return refs, nil
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package dirsort provides the sort order of the files in each directory,
// shared by all of the apps (and all of their processes) that show
// directories: [For] returns the sort order of a directory, which is the
// one last [Set] for it in any app, or else the one that the file manager
// of the operating system uses for it (the Finder on macOS, from its
// .DS_Store files, and Dolphin or Nautilus on Linux; see [Native]), or
// else [Default]. The sort orders that are set are saved in a file in
// [DataDir], which is locked for the changes of each process, and read
// again when another process has changed it.
package dirsort
//go:generate core generate
import (
"cmp"
"io/fs"
"path/filepath"
"slices"
"strings"
"cogentcore.org/core/base/fileinfo"
)
// Fields are the fields of the files in a directory that they can be
// sorted by, which are named as the fields of [fileinfo.FileInfo].
type Fields int32 //enums:enum
const (
// Name sorts the files by their names.
Name Fields = iota
// Size sorts the files by their sizes.
Size
// Kind sorts the files by their kinds (as Folder, or Code: Go).
Kind
// ModTime sorts the files by the time that they were last modified.
ModTime
)
// Sort is a sort order of the files in a directory: by the given field, up
// (ascending: A to Z, smallest or oldest first) or down (descending).
type Sort struct { //types:add
// By is the field that the files are sorted by.
By Fields
// Down is whether the files are sorted down (descending: Z to A,
// largest or newest first), instead of up (ascending).
Down bool
}
// Default is the sort order of a directory that has none (see [For]): by
// name, up.
var Default = Sort{}
// String returns the sort order as the name of its field and :up or :down,
// as [core.Table.SortFieldName] does.
func (s Sort) String() string {
if s.Down {
return s.By.String() + ":down"
}
return s.By.String() + ":up"
}
// Parse returns the sort order of the given string, as returned by
// [Sort.String] (where :up is the default), and whether it is one.
func Parse(str string) (Sort, bool) {
name, dir, _ := strings.Cut(str, ":")
var s Sort
if err := s.By.SetString(name); err != nil {
return Sort{}, false
}
switch dir {
case "", "up":
case "down":
s.Down = true
default:
return Sort{}, false
}
return s, true
}
// For returns the sort order of the given directory: the one last [Set]
// for it, by any app, or else the one of the file manager of the operating
// system (see [Native]), or else [Default].
func For(dir string) Sort {
if s, ok := Saved(dir); ok {
return s
}
if Native != nil {
if s, ok := Native(dir); ok {
return s
}
}
return Default
}
// Saved returns the sort order last [Set] for the given directory, by any
// app, and whether there is one.
func Saved(dir string) (Sort, bool) {
return theStore.get(cleanDir(dir))
}
// Set sets the sort order of the given directory, for all apps, saving it
// in the file shared by them (see [DataDir]).
func Set(dir string, s Sort) error {
return theStore.set(cleanDir(dir), s)
}
// cleanDir returns the absolute, clean path of the given directory, with
// its symbolic links evaluated (so that all of the paths of a directory
// have its sort order), by which its sort order is saved.
func cleanDir(dir string) string {
if abs, err := filepath.Abs(dir); err == nil {
dir = abs
}
if real, err := filepath.EvalSymlinks(dir); err == nil {
return real
}
return filepath.Clean(dir)
}
// Compare compares the given files in the sort order, returning -1 if a
// comes before b, and 1 if after, for [slices.SortFunc]. Files that are
// equal in the field of the sort order are in the order of their names
// (in the direction of the sort order).
func (s Sort) Compare(a, b *fileinfo.FileInfo) int {
return s.compare(a.Name, b.Name, func() int {
switch s.By {
case Size:
return cmp.Compare(a.Size, b.Size)
case Kind:
return compareNames(a.Kind, b.Kind)
case ModTime:
return a.ModTime.Compare(b.ModTime)
}
return 0
})
}
// compare returns the comparison of files of the given names, in the sort
// order, given the comparison of their fields (by the sort order).
func (s Sort) compare(aName, bName string, field func() int) int {
c := 0
if s.By != Name {
c = field()
}
if c == 0 {
c = compareNames(aName, bName)
}
if s.Down {
return -c
}
return c
}
// compareNames compares the given names as file managers do: ignoring case,
// and then by case.
func compareNames(a, b string) int {
if c := strings.Compare(strings.ToLower(a), strings.ToLower(b)); c != 0 {
return c
}
return strings.Compare(a, b)
}
// SortFiles sorts the given files in the sort order.
func (s Sort) SortFiles(files []*fileinfo.FileInfo) {
slices.SortStableFunc(files, s.Compare)
}
// SortInfos sorts the given standard file infos in the sort order, as
// those of a directory listing. Their kinds are those of their names (see
// [fileinfo.FileInfo.MimeFromFilename]), without reading the files.
func (s Sort) SortInfos(infos []fs.FileInfo) {
var kinds map[fs.FileInfo]string
if s.By == Kind {
kinds = make(map[fs.FileInfo]string, len(infos))
for _, info := range infos {
kinds[info] = kindOf(info)
}
}
slices.SortStableFunc(infos, func(a, b fs.FileInfo) int {
return s.compare(a.Name(), b.Name(), func() int {
switch s.By {
case Size:
return cmp.Compare(a.Size(), b.Size())
case Kind:
return compareNames(kinds[a], kinds[b])
case ModTime:
return a.ModTime().Compare(b.ModTime())
}
return 0
})
})
}
// kindOf returns the kind of the given file, from its name.
func kindOf(info fs.FileInfo) string {
if info.IsDir() {
return "Folder"
}
fi := &fileinfo.FileInfo{Path: info.Name(), Name: info.Name()}
fi.MimeFromFilename()
return fi.Kind
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package dirsort
import (
"bytes"
"encoding/binary"
"errors"
"unicode/utf16"
)
// errDSStore is the error of a .DS_Store file that is not valid.
var errDSStore = errors.New("dirsort: not a valid .DS_Store file")
// dsStoreRecords returns the records of the given file name (as "." for
// the directory itself) in the given .DS_Store file of the Finder, by
// their codes (as "lsvP" for the settings of the list view), whose values
// are []byte (blob), string (ustr, and the four characters of type), bool,
// or int64 (long, shor, comp, dutc).
//
// A .DS_Store file is a "buddy allocator" file of blocks, one of which is
// the "DSDB" B-tree of the records of the files, sorted by file name.
func dsStoreRecords(b []byte, name string) (map[string]any, error) {
ds := &dsStore{b: b}
if len(b) < 36 || binary.BigEndian.Uint32(b) != 1 || !bytes.Equal(b[4:8], []byte("Bud1")) {
return nil, errDSStore
}
// the offsets are of the data after the first 4 bytes
rootOff := int(binary.BigEndian.Uint32(b[8:]))
root := ds.reader(rootOff+4, int(binary.BigEndian.Uint32(b[12:])))
nblocks := int(root.u32())
root.u32()
if nblocks <= 0 || nblocks > len(b) {
return nil, errDSStore
}
ds.blocks = make([]uint32, nblocks)
for i := range ds.blocks {
ds.blocks[i] = root.u32()
}
root.skip(4 * ((256 - nblocks%256) % 256)) // (padded to 256 addresses)
dsdb := -1
for range int(root.u32()) {
n := int(root.u8())
key := root.bytes(n)
v := int(root.u32())
if string(key) == "DSDB" {
dsdb = v
}
}
if root.err != nil || dsdb < 0 {
return nil, errDSStore
}
hdr := ds.block(dsdb)
node := int(hdr.u32())
if hdr.err != nil {
return nil, errDSStore
}
recs := map[string]any{}
if err := ds.node(node, name, recs, 0); err != nil {
return nil, err
}
return recs, nil
}
// dsStore is the state of reading a .DS_Store file.
type dsStore struct {
b []byte
// blocks are the addresses of the blocks: the offset of each, with
// its size as a power of 2 in the low 5 bits.
blocks []uint32
}
// block returns a reader of the block of the given number.
func (ds *dsStore) block(n int) *dsReader {
if n < 0 || n >= len(ds.blocks) {
return &dsReader{err: errDSStore}
}
addr := ds.blocks[n]
return ds.reader(int(addr&^0x1f)+4, 1<<(addr&0x1f))
}
// reader returns a reader of the given size of the file at the given offset.
func (ds *dsStore) reader(off, size int) *dsReader {
if off < 0 || size < 0 || off > len(ds.b) || size > len(ds.b)-off {
return &dsReader{err: errDSStore}
}
return &dsReader{b: ds.b[off : off+size]}
}
// node adds the records of the given file name in the node of the B-tree
// in the given block, and its children, to the given records.
func (ds *dsStore) node(n int, name string, recs map[string]any, depth int) error {
if depth > 32 {
return errDSStore
}
r := ds.block(n)
right := int(r.u32()) // the last child of an internal node, else 0
count := int(r.u32())
for range count {
if r.err != nil {
return r.err
}
if right != 0 {
if err := ds.node(int(r.u32()), name, recs, depth+1); err != nil {
return err
}
}
fname, code, v := r.record()
if r.err == nil && fname == name {
recs[code] = v
}
}
if r.err != nil {
return r.err
}
if right != 0 {
return ds.node(right, name, recs, depth+1)
}
return nil
}
// dsReader reads big-endian values from a block of a .DS_Store file,
// with the first error that it has.
type dsReader struct {
b []byte
p int
err error
}
// bytes returns the next n bytes.
func (r *dsReader) bytes(n int) []byte {
if r.err != nil || n < 0 || r.p+n > len(r.b) {
r.err = errDSStore
return nil
}
v := r.b[r.p : r.p+n]
r.p += n
return v
}
// skip skips the next n bytes.
func (r *dsReader) skip(n int) { r.bytes(n) }
// u8 returns the next byte.
func (r *dsReader) u8() uint8 {
if b := r.bytes(1); b != nil {
return b[0]
}
return 0
}
// u32 returns the next 32-bit integer.
func (r *dsReader) u32() uint32 {
if b := r.bytes(4); b != nil {
return binary.BigEndian.Uint32(b)
}
return 0
}
// utf16 returns the next UTF-16 string of n characters.
func (r *dsReader) utf16(n int) string {
b := r.bytes(2 * n)
if b == nil {
return ""
}
u := make([]uint16, n)
for i := range u {
u[i] = binary.BigEndian.Uint16(b[2*i:])
}
return string(utf16.Decode(u))
}
// record returns the next record: the name of its file, its code, and its
// value.
func (r *dsReader) record() (name, code string, v any) {
name = r.utf16(int(r.u32()))
code = string(r.bytes(4))
switch string(r.bytes(4)) {
case "bool":
v = r.u8() != 0
case "long", "shor":
v = int64(int32(r.u32()))
case "type":
v = string(r.bytes(4))
case "comp", "dutc":
v = int64(uint64(r.u32())<<32 | uint64(r.u32()))
case "blob":
v = bytes.Clone(r.bytes(int(r.u32())))
case "ustr":
v = r.utf16(int(r.u32()))
default:
r.err = errDSStore
}
return
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package dirsort
import (
"os"
"path/filepath"
)
// finderPrefs is the path of the preferences of the Finder, relative to
// the home directory, which has its standard view settings.
var finderPrefs = "Library/Preferences/com.apple.finder.plist"
// finderCache caches the sort orders of directories in the Finder.
var finderCache cache[nativeSort]
// finderSort returns the sort order of the given directory in the Finder,
// and whether it has one: that of the view settings in its .DS_Store file
// (see [dsStoreRecords]), for the view that it is shown in (vstl), or else
// that of the standard view settings of the Finder, for its preferred view.
// The list views (lsvC, lsvP, lsvp) have a sort column, with whether each
// column is ascending, and the icon and gallery views (icvp, glvp) arrange
// by a field, or none.
func finderSort(dir string) (Sort, bool) {
ns := finderCache.get(dir, func() nativeSort {
if s, ok := finderDirSort(dir); ok {
return nativeSort{s, true}
}
// (keyed by "", which is not a clean directory)
return finderCache.get("", finderStandardSort)
})
return ns.s, ns.ok
}
// finderDirSort returns the sort order of the given directory in the view
// settings of its .DS_Store file, and whether it has one.
func finderDirSort(dir string) (Sort, bool) {
b, err := os.ReadFile(filepath.Join(dir, ".DS_Store"))
if err != nil {
return Sort{}, false
}
recs, err := dsStoreRecords(b, ".")
if err != nil {
return Sort{}, false
}
style, _ := recs["vstl"].(string)
views := map[string]map[string]any{}
for _, code := range []string{"lsvC", "lsvP", "lsvp", "icvp", "glvp"} {
if blob, ok := recs[code].([]byte); ok {
if pl, err := decodeBplist(blob); err == nil {
if m, ok := pl.(map[string]any); ok {
views[code] = m
}
}
}
}
list := views["lsvC"]
if list == nil {
list = views["lsvP"]
}
if list == nil {
list = views["lsvp"]
}
return viewSort(style, list, views["icvp"], views["glvp"])
}
// finderStandardSort returns the sort order of the standard view settings
// of the Finder, for its preferred view, and whether it has one.
func finderStandardSort() nativeSort {
b, err := os.ReadFile(filepath.Join(homeDir(), finderPrefs))
if err != nil {
return nativeSort{}
}
pl, err := decodeBplist(b)
if err != nil {
return nativeSort{}
}
prefs, _ := pl.(map[string]any)
style, _ := prefs["FXPreferredViewStyle"].(string)
std, _ := prefs["StandardViewSettings"].(map[string]any)
view := func(name string) map[string]any {
m, _ := std[name].(map[string]any)
return m
}
list := view("ExtendedListViewSettingsV2")
if list == nil {
list = view("ListViewSettings")
}
s, ok := viewSort(style, list, view("IconViewSettings"), view("GalleryViewSettings"))
return nativeSort{s, ok}
}
// viewSort returns the sort order of the given view style of the Finder
// (as Nlsv for the list view), from the given view settings of its list,
// icon and gallery views, and whether it has one. The column view (clmv)
// is sorted as the list view, as is a view that is not sorted by itself.
func viewSort(style string, list, icon, gallery map[string]any) (Sort, bool) {
switch style {
case "icnv":
if s, ok := arrangeSort(icon); ok {
return s, true
}
case "glyv":
if s, ok := arrangeSort(gallery); ok {
return s, true
}
}
return listSort(list)
}
// listSort returns the sort order of the given view settings of a list
// view, and whether it has one: its sort column, which is ascending as
// given for it in its columns (an array of them, by identifier, or a
// dictionary of them).
func listSort(list map[string]any) (Sort, bool) {
col, _ := list["sortColumn"].(string)
by, ok := byField(col)
if !ok {
return Sort{}, false
}
s := Sort{By: by, Down: downByDefault(by)}
var colInfo map[string]any
switch cols := list["columns"].(type) {
case []any:
for _, c := range cols {
if cm, ok := c.(map[string]any); ok && cm["identifier"] == col {
colInfo = cm
}
}
case map[string]any:
colInfo, _ = cols[col].(map[string]any)
}
if asc, ok := colInfo["ascending"].(bool); ok {
s.Down = !asc
}
return s, true
}
// arrangeSort returns the sort order of the given view settings of an icon
// or gallery view, and whether it has one: the field that it is arranged
// by, which is not none, in its default direction.
func arrangeSort(view map[string]any) (Sort, bool) {
arr, _ := view["arrangeBy"].(string)
by, ok := byField(arr)
if !ok {
return Sort{}, false
}
return Sort{By: by, Down: downByDefault(by)}, true
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package dirsort
import (
"bufio"
"bytes"
"context"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
// linuxCache caches the sort orders of directories on Linux.
var linuxCache cache[nativeSort]
// linuxSort returns the sort order of the given directory in the file
// managers of Linux, and whether it has one: that of Dolphin (see
// [dolphinSort]) or Nautilus (see [nautilusSort]) for the directory, or
// else the default of the one of the desktop (KDE for Dolphin, else
// Nautilus).
func linuxSort(dir string) (Sort, bool) {
ns := linuxCache.get(dir, func() nativeSort {
if s, ok := dolphinSort(dir); ok {
return nativeSort{s, true}
}
if s, ok := nautilusSort(dir); ok {
return nativeSort{s, true}
}
// (keyed by "", which is not a clean directory)
return linuxCache.get("", func() nativeSort {
kde := strings.Contains(strings.ToUpper(os.Getenv("XDG_CURRENT_DESKTOP")), "KDE")
defaults := []func() (Sort, bool){nautilusDefault, dolphinDefault}
if kde {
defaults[0], defaults[1] = defaults[1], defaults[0]
}
for _, def := range defaults {
if s, ok := def(); ok {
return nativeSort{s, true}
}
}
return nativeSort{}
})
})
return ns.s, ns.ok
}
// dolphinViews is the directory of the view properties of Dolphin,
// relative to the home directory: its global/.directory has those of all
// directories, when they are shared (GlobalViewProps in dolphinrc), and
// local/ those of the directories in which it can not write its .directory
// file, under their absolute paths.
var dolphinViews = ".local/share/dolphin/view_properties"
// dolphinSort returns the sort order of the given directory in Dolphin, in
// the [Dolphin] group of its .directory file, or else of the one for it in
// the view properties of Dolphin, and whether it has one. Dolphin sorts
// the directories that have no SortRole by name.
func dolphinSort(dir string) (Sort, bool) {
if dolphinGlobal() {
return Sort{}, false // (see dolphinDefault)
}
if s, ok := dolphinFile(filepath.Join(dir, ".directory")); ok {
return s, true
}
return dolphinFile(filepath.Join(homeDir(), dolphinViews, "local", dir, ".directory"))
}
// dolphinDefault returns the sort order of all directories in Dolphin,
// when they share their view properties, and whether there is one.
func dolphinDefault() (Sort, bool) {
if !dolphinGlobal() {
return Sort{}, false
}
return dolphinFile(filepath.Join(homeDir(), dolphinViews, "global", ".directory"))
}
// dolphinGlobal returns whether Dolphin uses the same view properties for
// all directories (GlobalViewProps in the [General] group of dolphinrc).
func dolphinGlobal() bool {
cfg := os.Getenv("XDG_CONFIG_HOME")
if cfg == "" {
cfg = filepath.Join(homeDir(), ".config")
}
b, err := os.ReadFile(filepath.Join(cfg, "dolphinrc"))
if err != nil {
return false
}
return strings.EqualFold(iniValues(b, "General")["GlobalViewProps"], "true")
}
// dolphinFile returns the sort order of the [Dolphin] group of the given
// .directory file, and whether it has one: by its SortRole (text being the
// name), down if its SortOrder is 1 (Qt::DescendingOrder).
func dolphinFile(fn string) (Sort, bool) {
b, err := os.ReadFile(fn)
if err != nil {
return Sort{}, false
}
vals := iniValues(b, "Dolphin")
role, order := vals["SortRole"], vals["SortOrder"]
if role == "" && order == "" {
return Sort{}, false
}
var s Sort
if role != "" {
by, ok := byField(role)
if !ok {
return Sort{}, false
}
s.By = by
}
s.Down = order == "1"
return s, true
}
// iniValues returns the values of the given group of the given INI file.
func iniValues(b []byte, group string) map[string]string {
vals := map[string]string{}
in := false
sc := bufio.NewScanner(bytes.NewReader(b))
for sc.Scan() {
line := strings.TrimSpace(sc.Text())
if strings.HasPrefix(line, "[") {
in = line == "["+group+"]"
continue
}
if k, v, ok := strings.Cut(line, "="); in && ok {
vals[strings.TrimSpace(k)] = strings.TrimSpace(v)
}
}
return vals
}
// runCommand runs the given command, which has a second to run, and
// returns its output, or nil if it fails.
var runCommand = func(name string, args ...string) []byte {
if _, err := exec.LookPath(name); err != nil {
return nil
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
out, err := exec.CommandContext(ctx, name, args...).Output()
if err != nil {
return nil
}
return out
}
// nautilusSort returns the sort order of the given directory in Nautilus,
// from the metadata of the directory in GVfs (as gio info shows it), and
// whether it has one: of its list view, or else of its icon (grid) view.
func nautilusSort(dir string) (Sort, bool) {
out := runCommand("gio", "info", "-a", "metadata::*", dir)
if out == nil {
return Sort{}, false
}
meta := map[string]string{}
sc := bufio.NewScanner(bytes.NewReader(out))
for sc.Scan() {
k, v, ok := strings.Cut(strings.TrimSpace(sc.Text()), ": ")
if name, isMeta := strings.CutPrefix(k, "metadata::nautilus-"); ok && isMeta {
meta[name] = v
}
}
for _, view := range []struct{ by, reversed string }{
{"list-view-sort-column", "list-view-sort-reversed"},
{"icon-view-sort-by", "icon-view-sort-reversed"},
} {
if by, ok := byField(meta[view.by]); ok {
return Sort{By: by, Down: meta[view.reversed] == "true"}, true
}
}
return Sort{}, false
}
// nautilusDefault returns the default sort order of Nautilus, in its
// settings (default-sort-order and default-sort-in-reverse-order), and
// whether it has one.
func nautilusDefault() (Sort, bool) {
const schema = "org.gnome.nautilus.preferences"
order := strings.Trim(strings.TrimSpace(string(runCommand("gsettings", "get", schema, "default-sort-order"))), "'")
by, ok := byField(order)
if !ok {
return Sort{}, false
}
rev := strings.TrimSpace(string(runCommand("gsettings", "get", schema, "default-sort-in-reverse-order")))
return Sort{By: by, Down: rev == "true"}, true
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package dirsort
import (
"os"
"runtime"
"strings"
"sync"
"time"
)
// Native returns the sort order that the file manager of the operating
// system uses for the given directory, and whether there is one: that of
// the directory, or else the default of the file manager.
//
// - macOS: the Finder, from the view settings in the .DS_Store file of the
// directory, or else its standard view settings (see [finderSort]).
// - Linux: Dolphin (KDE), from the .directory file of the directory, and
// Nautilus (GNOME), from the metadata of the directory, or else their
// defaults (see [linuxSort]).
// - Windows: none, as Explorer keeps the views of folders in the
// registry, in binary records ("shell bags") that are not documented.
//
// It can be set to nil for none, as core does in tests.
var Native = func(dir string) (Sort, bool) {
dir = cleanDir(dir)
switch runtime.GOOS {
case "darwin":
return finderSort(dir)
case "linux", "freebsd", "openbsd", "netbsd":
return linuxSort(dir)
}
return Sort{}, false
}
// cache caches values for a short time, as the native sort orders, which
// can take running a program to get, of the directories that are read
// again as they change.
type cache[V any] struct {
mu sync.Mutex
entries map[string]cacheEntry[V]
}
// cacheEntry is a value in a [cache], with when it was got.
type cacheEntry[V any] struct {
v V
time time.Time
}
// cacheTime is how long values are cached.
const cacheTime = 5 * time.Second
// get returns the cached value of the given key, or else the value of the
// given function for it, which is cached.
func (c *cache[V]) get(key string, f func() V) V {
c.mu.Lock()
e, ok := c.entries[key]
c.mu.Unlock()
if ok && time.Since(e.time) < cacheTime {
return e.v
}
v := f()
c.mu.Lock()
if c.entries == nil || len(c.entries) > 1000 {
c.entries = map[string]cacheEntry[V]{}
}
c.entries[key] = cacheEntry[V]{v, time.Now()}
c.mu.Unlock()
return v
}
// nativeSort is a sort order of a native file manager, and whether it has
// one, as cached.
type nativeSort struct {
s Sort
ok bool
}
// homeDir returns the home directory of the user, or "".
func homeDir() string {
h, _ := os.UserHomeDir()
return h
}
// byField returns the field of the given name of a column of a file
// manager (as dateModified for the Finder, or date_modified for Nautilus),
// ignoring case and _, and whether it is one: the times of creation,
// addition and opening are sorted by that of modification.
func byField(name string) (Fields, bool) {
switch strings.ToLower(strings.ReplaceAll(name, "_", "")) {
case "name", "text", "filename":
return Name, true
case "size", "physicalsize", "logicalsize":
return Size, true
case "kind", "type":
return Kind, true
case "datemodified", "modificationdate", "modificationtime", "mtime", "modified",
"datecreated", "creationtime", "btime", "dateadded",
"datelastopened", "dateaccessed", "accesstime", "atime", "recency":
return ModTime, true
}
return 0, false
}
// downByDefault returns whether the given field is sorted down by default,
// as file managers do when they arrange by it: newest and largest first.
func downByDefault(by Fields) bool {
return by == ModTime || by == Size
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package dirsort
import (
"path/filepath"
"slices"
"sync"
"time"
"cogentcore.org/core/base/sharedfile"
)
// DataDir is the directory of the file of the sort orders that are [Set],
// which is shared by all apps: core sets it to the Cogent Core data
// directory. If it is empty, the sort orders are only kept in memory.
var DataDir string
// FileName is the name of the file of the sort orders in [DataDir].
const FileName = "dir-sort.json"
// MaxDirs is the maximum number of directories whose sort orders are
// saved: those set least recently are dropped beyond it.
var MaxDirs = 5000
// entry is a sort order of a directory in the file, with when it was set.
type entry struct {
Sort
// Time is when the sort order was set, in Unix seconds.
Time int64
}
// store is the sort orders of the directories, in the file shared by all
// apps, which is read again when another process changes it.
type store struct {
mu sync.Mutex
// file is the file of the sort orders by directory.
file sharedfile.File[map[string]entry]
}
// theStore is the store of the sort orders.
var theStore store
// path returns the path of the file, or "" if there is no [DataDir].
func (st *store) path() string {
if DataDir == "" {
return ""
}
return filepath.Join(DataDir, FileName)
}
// reload reads the file again if it changed since it was read (as another
// process saved it), or if [DataDir] changed, under the mutex. A file that
// is not valid is replaced when a sort order is set.
func (st *store) reload() {
st.file.Path = st.path()
st.file.Reload()
}
// get returns the sort order of the given (clean) directory.
func (st *store) get(dir string) (Sort, bool) {
st.mu.Lock()
defer st.mu.Unlock()
st.reload()
e, ok := st.file.Data[dir]
return e.Sort, ok
}
// set sets the sort order of the given (clean) directory, and saves the
// file, with it locked, after reading the changes of other processes.
func (st *store) set(dir string, s Sort) error {
st.mu.Lock()
defer st.mu.Unlock()
st.file.Path = st.path()
return st.file.Update(func(dirs *map[string]entry) {
if *dirs == nil {
*dirs = map[string]entry{}
}
(*dirs)[dir] = entry{Sort: s, Time: time.Now().Unix()}
prune(*dirs)
})
}
// prune drops the sort orders set least recently beyond [MaxDirs].
func prune(dirs map[string]entry) {
if len(dirs) <= MaxDirs {
return
}
type dirTime struct {
dir string
time int64
}
dts := make([]dirTime, 0, len(dirs))
for d, e := range dirs {
dts = append(dts, dirTime{d, e.Time})
}
slices.SortFunc(dts, func(a, b dirTime) int { return int(b.time - a.time) })
for _, dt := range dts[MaxDirs:] {
delete(dirs, dt.dir)
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package elide provides basic text eliding functions.
package elide
import "strings"
// End elides from the end of the string if it is longer than given
// size parameter, in characters (runes). The resulting string will not
// exceed sz in length, with space reserved for … at the end.
func End(s string, sz int) string {
r := []rune(s)
if len(r) <= sz {
return s
}
if sz <= 0 {
return ""
}
return string(r[:sz-1]) + "…"
}
// Middle elides from the middle of the string if it is longer than given
// size parameter, in characters (runes), so that no character is cut
// (which made the label of a tab with a title with a · blank). The
// resulting string will not exceed sz in length, with space reserved
// for … in the middle
func Middle(s string, sz int) string {
r := []rune(s)
n := len(r)
if n <= sz {
return s
}
if sz <= 0 {
return ""
}
en := sz - 1
mid := en / 2
rest := en - mid
return string(r[:mid]) + "…" + string(r[n-rest:])
}
// AppName elides the given app name to be twelve characters or less
// by removing word(s) from the middle of the string if necessary and possible.
func AppName(s string) string {
if len(s) <= 12 {
return s
}
words := strings.Fields(s)
if len(words) < 3 {
return s
}
return words[0] + " " + words[len(words)-1]
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package errors provides a set of error handling helpers,
// extending the standard library errors package.
package errors
import (
"log/slog"
"runtime"
"strconv"
"sync/atomic"
)
// logHook is the function of [SetLogHook], if any.
var logHook atomic.Pointer[func(err error) bool]
// SetLogHook sets a function that [Log], [Log1] and [Log2] call with each
// error before logging it: if it returns true, the error is not logged.
// It returns the previous one (nil if none), to restore it. An interpreter
// sets it while it runs code, to report the errors that the Go code that
// the code calls logs as errors of the code, at the call.
func SetLogHook(hook func(err error) bool) (prev func(err error) bool) {
var p *func(err error) bool
if hook != nil {
p = &hook
}
if old := logHook.Swap(p); old != nil {
prev = *old
}
return prev
}
// hooked returns whether the function of [SetLogHook] handles the error.
func hooked(err error) bool {
h := logHook.Load()
return h != nil && (*h)(err)
}
// Log takes the given error and logs it if it is non-nil.
// The intended usage is:
//
// errors.Log(MyFunc(v))
// // or
// return errors.Log(MyFunc(v))
func Log(err error) error {
if err != nil && !hooked(err) {
slog.Error(err.Error() + " | " + CallerInfo())
}
return err
}
// LogDepth logs the given error if it is non-nil, as [Log] does, with the
// information of the caller that is depth levels above the caller of
// LogDepth: 0 is its caller, as for Log, and 1 is the caller of that.
// It is for functions that log the errors of their callers, as [Log1]
// and [Log2]: as these generic functions only use exported functions,
// interpreters can run them, with [SetLogHook].
func LogDepth(err error, depth int) error {
if err != nil && !hooked(err) {
pc, file, line, _ := runtime.Caller(depth + 1)
slog.Error(err.Error() + " | " + runtime.FuncForPC(pc).Name() + " " + file + ":" + strconv.Itoa(line))
}
return err
}
// Log1 takes the given value and error and returns the value if
// the error is nil, and logs the error and returns a zero value
// if the error is non-nil. The intended usage is:
//
// a := errors.Log1(MyFunc(v))
func Log1[T any](v T, err error) T {
LogDepth(err, 1)
return v
}
// Log2 takes the given two values and error and returns the values if
// the error is nil, and logs the error and returns zero values
// if the error is non-nil. The intended usage is:
//
// a, b := errors.Log2(MyFunc(v))
func Log2[T1, T2 any](v1 T1, v2 T2, err error) (T1, T2) {
LogDepth(err, 1)
return v1, v2
}
// Must takes the given error and panics if it is non-nil.
// The intended usage is:
//
// errors.Must(MyFunc(v))
func Must(err error) {
if err != nil {
panic(err)
}
}
// Must1 takes the given value and error and returns the value if
// the error is nil, and panics if the error is non-nil. The intended usage is:
//
// a := errors.Must1(MyFunc(v))
func Must1[T any](v T, err error) T {
if err != nil {
panic(err)
}
return v
}
// Must2 takes the given two values and error and returns the values if
// the error is nil, and panics if the error is non-nil. The intended usage is:
//
// a, b := errors.Must2(MyFunc(v))
func Must2[T1, T2 any](v1 T1, v2 T2, err error) (T1, T2) {
if err != nil {
panic(err)
}
return v1, v2
}
// Ignore1 ignores an error return value for a function returning
// a value and an error, allowing direct usage of the value.
// The intended usage is:
//
// a := errors.Ignore1(MyFunc(v))
func Ignore1[T any](v T, err error) T {
return v
}
// Ignore2 ignores an error return value for a function returning
// two values and an error, allowing direct usage of the values.
// The intended usage is:
//
// a, b := errors.Ignore2(MyFunc(v))
func Ignore2[T1, T2 any](v1 T1, v2 T2, err error) (T1, T2) {
return v1, v2
}
// CallerInfo returns string information about the caller
// of the function that called CallerInfo.
func CallerInfo() string {
pc, file, line, _ := runtime.Caller(2)
return runtime.FuncForPC(pc).Name() + " " + file + ":" + strconv.Itoa(line)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package errors
import "errors"
// Aliases for standard library errors package:
// ErrUnsupported indicates that a requested operation cannot be performed,
// because it is unsupported. For example, a call to [os.Link] when using a
// file system that does not support hard links.
//
// Functions and methods should not return this error but should instead
// return an error including appropriate context that satisfies
//
// errors.Is(err, errors.ErrUnsupported)
//
// either by directly wrapping ErrUnsupported or by implementing an [Is] method.
//
// Functions and methods should document the cases in which an error
// wrapping this will be returned.
var ErrUnsupported = errors.ErrUnsupported
// As finds the first error in err's tree that matches target, and if one is found, sets
// target to that error value and returns true. Otherwise, it returns false.
//
// The tree consists of err itself, followed by the errors obtained by repeatedly
// calling its Unwrap() error or Unwrap() []error method. When err wraps multiple
// errors, As examines err followed by a depth-first traversal of its children.
//
// An error matches target if the error's concrete value is assignable to the value
// pointed to by target, or if the error has a method As(interface{}) bool such that
// As(target) returns true. In the latter case, the As method is responsible for
// setting target.
//
// An error type might provide an As method so it can be treated as if it were a
// different error type.
//
// As panics if target is not a non-nil pointer to either a type that implements
// error, or to any interface type.
func As(err error, target any) bool { return errors.As(err, target) }
// Is reports whether any error in err's tree matches target.
//
// The tree consists of err itself, followed by the errors obtained by repeatedly
// calling its Unwrap() error or Unwrap() []error method. When err wraps multiple
// errors, Is examines err followed by a depth-first traversal of its children.
//
// An error is considered to match a target if it is equal to that target or if
// it implements a method Is(error) bool such that Is(target) returns true.
//
// An error type might provide an Is method so it can be treated as equivalent
// to an existing error. For example, if MyError defines
//
// func (m MyError) Is(target error) bool { return target == fs.ErrExist }
//
// then Is(MyError{}, fs.ErrExist) returns true. See [syscall.Errno.Is] for
// an example in the standard library. An Is method should only shallowly
// compare err and the target and not call [Unwrap] on either.
func Is(err, target error) bool { return errors.Is(err, target) }
// Join returns an error that wraps the given errors.
// Any nil error values are discarded.
// Join returns nil if every value in errs is nil.
// The error formats as the concatenation of the strings obtained
// by calling the Error method of each element of errs, with a newline
// between each string.
//
// A non-nil error returned by Join implements the Unwrap() []error method.
func Join(errs ...error) error { return errors.Join(errs...) }
// New returns an error that formats as the given text.
// Each call to New returns a distinct error value even if the text is identical.
func New(text string) error { return errors.New(text) }
// Unwrap returns the result of calling the Unwrap method on err, if err's
// type contains an Unwrap method returning error.
// Otherwise, Unwrap returns nil.
//
// Unwrap only calls a method of the form "Unwrap() error".
// In particular Unwrap does not unwrap errors returned by [Join].
func Unwrap(err error) error { return errors.Unwrap(err) }
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package exec
import (
"bytes"
"context"
"fmt"
"os/exec"
"strings"
)
// Cmd is a type alias for [exec.Cmd].
type Cmd = exec.Cmd
// CmdIO maintains an [exec.Cmd] pointer and IO state saved for the command
type CmdIO struct {
StdIOState
// Cmd is the [exec.Cmd]
Cmd *exec.Cmd
}
func (c *CmdIO) String() string {
if c.Cmd == nil {
return "<nil>"
}
str := ""
if c.Cmd.ProcessState != nil {
str = c.Cmd.ProcessState.String()
} else if c.Cmd.Process != nil {
str = fmt.Sprintf("%d ", c.Cmd.Process.Pid)
} else {
str = "no process info"
}
str += " " + c.Cmd.String()
return str
}
// NewCmdIO returns a new [CmdIO] initialized with StdIO settings from given Config
func NewCmdIO(c *Config) *CmdIO {
cio := &CmdIO{}
cio.StdIO = c.StdIO
return cio
}
// RunIO runs the given command using the given
// configuration information and arguments,
// waiting for it to complete before returning.
// This IO version of [Run] uses specified stdio and sets the
// command in it as well, for easier management of
// dynamically updated IO routing.
func (c *Config) RunIO(cio *CmdIO, cmd string, args ...string) error {
return c.RunIOContext(context.Background(), cio, cmd, args...)
}
// RunIOContext is [Config.RunIO] with a context: if it is not nil, the
// command is interrupted when the context is done, as a shell does for
// Control+C, and killed if it has not ended after [InterruptWait]. On
// Windows, a command in the console of this process is not interrupted, as
// it gets the Control+C typed in the console itself.
func (c *Config) RunIOContext(ctx context.Context, cio *CmdIO, cmd string, args ...string) error {
cm, _, err := c.exec(ctx, &cio.StdIO, false, cmd, args...)
cio.Cmd = cm
return err
}
// StartIO starts the given command using the given
// configuration information and arguments,
// just starting the command but not waiting for it to finish.
// This IO version of [Start] uses specified stdio and sets the
// command in it as well, which should be used to Wait for the
// command to finish (in a separate goroutine).
// For dynamic IO routing uses, call [CmdIO.StackStart] prior to
// setting the IO values using Push commands, and then call
// [PopToStart] after Wait finishes, to close any open IO and reset.
func (c *Config) StartIO(cio *CmdIO, cmd string, args ...string) error {
cm, _, err := c.exec(context.Background(), &cio.StdIO, true, cmd, args...)
cio.Cmd = cm
return err
}
// OutputIO runs the command and returns the text from stdout.
func (c *Config) OutputIO(cio *CmdIO, cmd string, args ...string) (string, error) {
return c.OutputIOContext(context.Background(), cio, cmd, args...)
}
// OutputIOContext is [Config.OutputIO] with a context, with which the
// command is interrupted as for [Config.RunIOContext].
func (c *Config) OutputIOContext(ctx context.Context, cio *CmdIO, cmd string, args ...string) (string, error) {
// need to use buf to capture output
sio := cio.StdIO // copy
buf := &bytes.Buffer{}
sio.Out = buf
_, _, err := c.exec(ctx, &sio, false, cmd, args...)
if cio.Out != nil {
cio.Out.Write(buf.Bytes())
}
return strings.TrimSuffix(buf.String(), "\n"), err
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package exec provides an easy way to execute commands,
// improving the ease-of-use and error handling of the
// standard library os/exec package. For example:
//
// err := exec.Run("git", "commit", "-am")
// // or
// err := exec.RunSh("git commit -am")
// // or
// err := exec.Verbose().Run("git", "commit", "-am")
package exec
//go:generate core generate
import (
"io"
"maps"
"os"
"log/slog"
"cogentcore.org/core/base/logx"
)
// Config contains the configuration information that
// controls the behavior of exec. It is passed to most
// high-level functions, and a default version of it
// can be easily constructed using [DefaultConfig].
type Config struct { //types:add -setters
// Buffer is whether to buffer the output of Stdout and Stderr,
// which is necessary for the correct printing of commands and output
// when there is an error with a command, and for correct coloring
// on Windows. Therefore, it should be kept at the default value of
// true in most cases, except for when a command will run for a log
// time and print output throughout (eg: a log command).
Buffer bool
// PrintOnly is whether to only print commands that would be run and
// not actually run them. It can be used, for example, for safely testing
// an app.
PrintOnly bool
// The directory to execute commands in. If it is unset,
// commands are run in the current directory.
Dir string
// NoExpand is whether not to expand references to environment
// variables in $FOO format in the command and its args, which is
// done by default. It is for a caller that expands them where it
// should, such as goal, which expands those of the words of its
// commands but not those of the values of Go expressions in them.
NoExpand bool
// Env contains any additional environment variables specified.
// The current environment variables will also be passed to the
// command, but they will be overridden by any variables here
// if there are conflicts.
Env map[string]string `set:"-"`
// Echo is the writer for echoing the command string to.
// It can be set to nil to disable echoing.
Echo io.Writer
// Standard Input / Output management
StdIO StdIO
}
// SetStdout sets the standard output
func (c *Config) SetStdout(w io.Writer) *Config {
c.StdIO.Out = w
return c
}
// SetStderr sets the standard error
func (c *Config) SetStderr(w io.Writer) *Config {
c.StdIO.Err = w
return c
}
// SetStdin sets the standard input
func (c *Config) SetStdin(r io.Reader) *Config {
c.StdIO.In = r
return c
}
// major is the config object for [Major] specified through [SetMajor]
var major *Config
// Major returns the default [Config] object for a major command,
// based on [logx.UserLevel]. It should be used for commands that
// are central to an app's logic and are more important for the user
// to know about and be able to see the output of. It results in
// commands and output being printed with a [logx.UserLevel] of
// [slog.LevelInfo] or below, whereas [Minor] results in that when
// it is [slog.LevelDebug] or below. Most commands in a typical use
// case should be Major, which is why the global helper functions
// operate on it. The object returned by Major is guaranteed to be
// unique, so it can be modified directly.
func Major() *Config {
if major != nil {
return major.clone() // a copy, so that the default is not modified
}
if logx.UserLevel <= slog.LevelInfo {
c := &Config{
Buffer: true,
Env: map[string]string{},
Echo: os.Stdout,
}
c.StdIO.SetFromOS()
return c
}
c := &Config{
Buffer: true,
Env: map[string]string{},
}
c.StdIO.SetFromOS()
c.StdIO.Out = nil
return c
}
// SetMajor sets the config object that [Major] returns. It should
// be used sparingly, and only in cases where there is a clear property
// that should be set for all commands. If the given config object is
// nil, [Major] will go back to returning its default value.
func SetMajor(c *Config) {
major = c
}
// minor is the config object for [Minor] specified through [SetMinor]
var minor *Config
// Minor returns the default [Config] object for a minor command,
// based on [logx.UserLevel]. It should be used for commands that
// support an app behind the scenes and are less important for the
// user to know about and be able to see the output of. It results in
// commands and output being printed with a [logx.UserLevel] of
// [slog.LevelDebug] or below, whereas [Major] results in that when
// it is [slog.LevelInfo] or below. The object returned by Minor is
// guaranteed to be unique, so it can be modified directly.
func Minor() *Config {
if minor != nil {
return minor.clone() // a copy, so that the default is not modified
}
if logx.UserLevel <= slog.LevelDebug {
c := &Config{
Buffer: true,
Env: map[string]string{},
Echo: os.Stdout,
}
c.StdIO.SetFromOS()
return c
}
c := &Config{
Buffer: true,
Env: map[string]string{},
}
c.StdIO.SetFromOS()
c.StdIO.Out = nil
return c
}
// SetMinor sets the config object that [Minor] returns. It should
// be used sparingly, and only in cases where there is a clear property
// that should be set for all commands. If the given config object is
// nil, [Minor] will go back to returning its default value.
func SetMinor(c *Config) {
minor = c
}
// verbose is the config object for [Verbose] specified through [SetVerbose]
var verbose *Config
// Verbose returns the default [Config] object for a verbose command,
// based on [logx.UserLevel]. It should be used for commands
// whose output are central to an application; for example, for a
// logger or app runner. It results in commands and output being
// printed with a [logx.UserLevel] of [slog.LevelWarn] or below,
// whereas [Major] and [Minor] result in that when it is [slog.LevelInfo]
// and [slog.levelDebug] or below, respectively. The object returned by
// Verbose is guaranteed to be unique, so it can be modified directly.
func Verbose() *Config {
if verbose != nil {
return verbose.clone() // a copy, so that the default is not modified
}
if logx.UserLevel <= slog.LevelWarn {
c := &Config{
Buffer: true,
Env: map[string]string{},
Echo: os.Stdout,
}
c.StdIO.SetFromOS()
return c
}
c := &Config{
Buffer: true,
Env: map[string]string{},
}
c.StdIO.SetFromOS()
c.StdIO.Out = nil
return c
}
// SetVerbose sets the config object that [Verbose] returns. It should
// be used sparingly, and only in cases where there is a clear property
// that should be set for all commands. If the given config object is
// nil, [Verbose] will go back to returning its default value.
func SetVerbose(c *Config) {
verbose = c
}
// silent is the config object for [Silent] specified through [SetSilent]
var silent *Config
// Silent returns the default [Config] object for a silent command,
// based on [logx.UserLevel]. It should be used for commands that
// whose output/input is private and needs to be always hidden from
// the user; for example, for a command that involves passwords.
// It results in commands and output never being printed. The object
// returned by Silent is guaranteed to be unique, so it can be modified directly.
func Silent() *Config {
if silent != nil {
return silent.clone() // a copy, so that the default is not modified
}
c := &Config{
Buffer: true,
Env: map[string]string{},
}
c.StdIO.In = os.Stdin
return c
}
// SetSilent sets the config object that [Silent] returns. It should
// be used sparingly, and only in cases where there is a clear property
// that should be set for all commands. If the given config object is
// nil, [Silent] will go back to returning its default value.
func SetSilent(c *Config) {
silent = c
}
// GetWriter returns the appropriate writer to use based on the given writer and error.
// If the given error is non-nil, the returned writer is guaranteed to be non-nil,
// with [Config.Stderr] used as a backup. Otherwise, the returned writer will only
// be non-nil if the passed one is.
func (c *Config) GetWriter(w io.Writer, err error) io.Writer {
res := w
if res == nil && err != nil {
res = c.StdIO.Err
}
return res
}
// PrintCmd uses [GetWriter] to print the given command to [Config.Echo]
// or [Config.Stderr], based on the given error and the config settings.
// A newline is automatically inserted.
func (c *Config) PrintCmd(cmd string, err error) {
cmds := c.GetWriter(c.Echo, err)
if cmds != nil {
if c.Dir != "" {
cmds.Write([]byte(logx.SuccessColor(c.Dir) + ": "))
}
cmds.Write([]byte(logx.CmdColor(cmd) + "\n"))
}
}
// PrintCmd calls [Config.PrintCmd] on [Major]
func PrintCmd(cmd string, err error) {
Major().PrintCmd(cmd, err)
}
// clone returns a copy of the config, with its own environment variables,
// which a copy of the struct would share.
func (c *Config) clone() *Config {
res := *c
res.Env = maps.Clone(c.Env)
return &res
}
// SetEnv sets the given environment variable.
func (c *Config) SetEnv(key, val string) *Config {
c.Env[key] = val
return c
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !windows
package exec
import (
"io"
"os"
)
// interruptible returns whether a command that is run with a context
// with the given standard input is interrupted when the context is done
// (see [interrupt]).
func interruptible(_ io.Reader) bool {
return true
}
// interrupt interrupts the given process of a command whose context is
// done, with an interrupt signal, as a shell does for Control+C. It is
// killed if that fails, and otherwise if it has not ended after
// [InterruptWait].
func interrupt(p *os.Process) error {
if err := p.Signal(os.Interrupt); err != nil {
return p.Kill()
}
return nil
}
// saveConsole returns a function that restores the modes of the console
// of the given standard input and output, which is only needed on Windows.
func saveConsole(_ io.Reader, _ io.Writer) func() {
return func() {}
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Adapted in part from: https://github.com/magefile/mage
// Copyright presumably by Nate Finch, primary contributor
// Apache License, Version 2.0, January 2004
package exec
import (
"bytes"
"context"
"errors"
"fmt"
"os"
"os/exec"
"strings"
"time"
"cogentcore.org/core/base/logx"
)
// exec executes the command, piping its stdout and stderr to the config
// writers. If start, uses cmd.Start, else.Run.
// If the command fails, it will return an error with the command output.
// The given cmd and args may include references
// to environment variables in $FOO format, in which case these will be
// expanded before the command is run, unless [Config.NoExpand].
//
// Ran reports if the command ran (rather than was not found or not executable).
// Code reports the exit code the command returned if it ran. If err == nil, ran
// is always true and code is always 0.
//
// If ctx is not nil, a command that is run (not started) is interrupted
// when it is done (see [Config.RunIOContext]).
func (c *Config) exec(ctx context.Context, sio *StdIO, start bool, cmd string, args ...string) (excmd *exec.Cmd, ran bool, err error) {
expand := func(s string) string {
s2, ok := c.Env[s]
if ok {
return s2
}
return os.Getenv(s)
}
if !c.NoExpand {
cmd = os.Expand(cmd, expand)
// the expanded args are a new slice, so the caller's are not changed
eargs := make([]string, len(args))
for i, a := range args {
eargs[i] = os.Expand(a, expand)
}
args = eargs
}
excmd, ran, code, err := c.run(ctx, sio, start, cmd, args...)
_ = code
if err == nil {
return excmd, true, nil
}
return excmd, ran, runError(cmd, args, err)
}
// RunError is an error of running a command, which wraps the error of
// running it, such as [exec.ErrNotFound] or an [exec.ExitError].
type RunError struct {
// Msg is the message of the error.
Msg string
// Err is the error of running the command.
Err error
}
func (e *RunError) Error() string { return e.Msg }
func (e *RunError) Unwrap() error { return e.Err }
// runError returns a [RunError] for the given error of running the given
// command with the given args: one that it was not found, as in a shell,
// or that it failed.
func runError(cmd string, args []string, err error) error {
if errors.Is(err, exec.ErrNotFound) {
return &RunError{Msg: cmd + ": command not found", Err: err}
}
return &RunError{Msg: fmt.Sprintf("%q: %v", strings.Join(append([]string{cmd}, args...), " "), err), Err: err}
}
// InterruptWait is how long a command that is interrupted, when the
// context it is run with is done, has to end, before it is killed.
var InterruptWait = time.Second
func (c *Config) run(ctx context.Context, sio *StdIO, start bool, cmd string, args ...string) (excmd *exec.Cmd, ran bool, code int, err error) {
var cm *exec.Cmd
if ctx != nil && ctx.Done() != nil && !start && interruptible(sio.In) { // (Background is never done)
cm = exec.CommandContext(ctx, cmd, args...)
cm.Cancel = func() error { return interrupt(cm.Process) }
cm.WaitDelay = InterruptWait
} else {
cm = exec.Command(cmd, args...)
}
cm.Env = os.Environ()
for k, v := range c.Env {
cm.Env = append(cm.Env, k+"="+v)
}
// need to store in buffer so we can color and print commands and stdout correctly
// (need to declare regardless even if we aren't using so that it is accessible)
ebuf := &bytes.Buffer{}
obuf := &bytes.Buffer{}
if !start && c.Buffer {
cm.Stderr = ebuf
cm.Stdout = obuf
} else {
cm.Stderr = sio.Err
cm.Stdout = sio.Out
}
// need to do now because we aren't buffering, or we are guaranteed to print them
// regardless of whether there is an error anyway, so we should print it now so
// people can see it earlier (especially important if it runs for a long time).
if !start || !c.Buffer || c.Echo != nil {
c.PrintCmd(cmd+" "+strings.Join(args, " "), err)
}
cm.Stdin = sio.In
cm.Dir = c.Dir
if !c.PrintOnly {
if start {
err = cm.Start()
excmd = cm
} else {
restore := saveConsole(sio.In, sio.Out)
err = cm.Run()
restore()
excmd = cm // for its process state (as in [Config.RunIO])
}
// we must call InitColor after calling a system command
// TODO(kai): maybe figure out a better solution to this
// or expand this list
if cmd == "cp" || cmd == "ls" || cmd == "mv" {
logx.InitColor()
}
}
if !start && c.Buffer {
// if we have an error, we print the commands and stdout regardless of the config info
// (however, we don't print the command if we are guaranteed to print it regardless, as
// we already printed it above in that case)
if c.Echo == nil {
c.PrintCmd(cmd+" "+strings.Join(args, " "), err)
}
sout := c.GetWriter(sio.Out, err)
if sout != nil {
sout.Write(obuf.Bytes())
}
estr := ebuf.String()
if estr != "" && sio.Err != nil {
sio.Err.Write([]byte(logx.ErrorColor(estr)))
}
}
return excmd, CmdRan(err), ExitStatus(err), err
}
// CmdRan examines the error to determine if it was generated as a result of a
// command running via os/exec.Command. If the error is nil, or the command ran
// (even if it exited with a non-zero exit code), CmdRan reports true. If the
// error is an unrecognized type, or it is an error from exec.Command that says
// the command failed to run (usually due to the command not existing or not
// being executable), it reports false.
func CmdRan(err error) bool {
if err == nil {
return true
}
ee, ok := err.(*exec.ExitError)
if ok {
return ee.Exited()
}
return false
}
type exitStatus interface {
ExitStatus() int
}
// ExitStatus returns the exit status of the error if it is an exec.ExitError
// or if it implements ExitStatus() int.
// 0 if it is nil or 1 if it is a different error.
func ExitStatus(err error) int {
if err == nil {
return 0
}
if e, ok := err.(exitStatus); ok {
return e.ExitStatus()
}
if e, ok := err.(*exec.ExitError); ok {
if ex, ok := e.Sys().(exitStatus); ok {
return ex.ExitStatus()
}
}
return 1
}
// ErrorMode specifies whether a command that fails is an error to report:
// [ErrorsFail] or [ErrorsOK].
type ErrorMode bool
const (
// ErrorsOK does not report an error when the command fails.
ErrorsOK ErrorMode = true
// ErrorsFail reports an error when the command fails.
ErrorsFail ErrorMode = false
)
// StartMode specifies whether to start a command in the background without
// waiting for it to finish ([Background]) or wait for it ([Foreground]).
type StartMode bool
const (
// Background starts the command without waiting for it to finish.
Background StartMode = true
// Foreground waits for the command to finish.
Foreground StartMode = false
)
// OutputMode specifies whether to capture the output of a command and
// return it ([CaptureOutput]) or send it to the standard output ([NoCapture]).
type OutputMode bool
const (
// CaptureOutput captures the output and returns it.
CaptureOutput OutputMode = true
// NoCapture sends the output to the standard output.
NoCapture OutputMode = false
)
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package exec
import (
"fmt"
"os"
"os/exec"
)
// LookPath searches for an executable named file in the
// directories named by the PATH environment variable.
// If file contains a slash, it is tried directly and the PATH is not consulted.
// Otherwise, on success, the result is an absolute path.
//
// In older versions of Go, LookPath could return a path relative to the current directory.
// As of Go 1.19, LookPath will instead return that path along with an error satisfying
// errors.Is(err, ErrDot). See the package documentation for more details.
func LookPath(file string) (string, error) { return exec.LookPath(file) }
// RemoveAll is a helper function that calls [os.RemoveAll] and [Config.PrintCmd].
func (c *Config) RemoveAll(path string) error {
var err error
if !c.PrintOnly {
err = os.RemoveAll(path)
}
c.PrintCmd(fmt.Sprintf("rm -rf %q", path), err)
return err
}
// RemoveAll calls [Config.RemoveAll] on [Major]
func RemoveAll(path string) error {
return Major().RemoveAll(path)
}
// MkdirAll is a helper function that calls [os.MkdirAll] and [Config.PrintCmd].
func (c *Config) MkdirAll(path string, perm os.FileMode) error {
var err error
if !c.PrintOnly {
err = os.MkdirAll(path, perm)
}
c.PrintCmd(fmt.Sprintf("mkdir -p %q", path), err)
return err
}
// MkdirAll calls [Config.MkdirAll] on [Major]
func MkdirAll(path string, perm os.FileMode) error {
return Major().MkdirAll(path, perm)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Adapted in part from: https://github.com/magefile/mage
// Copyright presumably by Nate Finch, primary contributor
// Apache License, Version 2.0, January 2004
package exec
import (
"bytes"
"context"
"os/exec"
"strings"
)
// Run runs the given command using the given
// configuration information and arguments,
// waiting for it to complete before returning.
func (c *Config) Run(cmd string, args ...string) error {
_, _, err := c.exec(context.Background(), &c.StdIO, false, cmd, args...)
return err
}
// Start starts the given command using the given
// configuration information and arguments,
// just starting the command but not waiting for it to finish.
// Returns the [exec.Cmd] command on which you can Wait for
// the command to finish (in a separate goroutine).
// See [StartIO] for a version that manages dynamic IO routing for you.
func (c *Config) Start(cmd string, args ...string) (*exec.Cmd, error) {
excmd, _, err := c.exec(context.Background(), &c.StdIO, true, cmd, args...)
return excmd, err
}
// Output runs the command and returns the text from stdout.
func (c *Config) Output(cmd string, args ...string) (string, error) {
// need to use buf to capture output
buf := &bytes.Buffer{}
sio := c.StdIO // copy
sio.Out = buf
_, _, err := c.exec(context.Background(), &sio, false, cmd, args...)
if c.StdIO.Out != nil {
c.StdIO.Out.Write(buf.Bytes())
}
return strings.TrimSuffix(buf.String(), "\n"), err
}
// Run calls [Config.Run] on [Major]
func Run(cmd string, args ...string) error {
return Major().Run(cmd, args...)
}
// Start calls [Config.Start] on [Major]
func Start(cmd string, args ...string) (*exec.Cmd, error) {
return Major().Start(cmd, args...)
}
// Output calls [Config.Output] on [Major]
func Output(cmd string, args ...string) (string, error) {
return Major().Output(cmd, args...)
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package exec
import (
"fmt"
"io"
"io/fs"
"log/slog"
"os"
"cogentcore.org/core/base/stack"
)
// StdIO contains one set of standard input / output Reader / Writers.
type StdIO struct {
// Out is the writer to write the standard output of called commands to.
// It can be set to nil to disable the writing of the standard output.
Out io.Writer
// Err is the writer to write the standard error of called commands to.
// It can be set to nil to disable the writing of the standard error.
Err io.Writer
// In is the reader to use as the standard input.
In io.Reader
}
// SetFromOS sets all our IO to current os.Std*
func (st *StdIO) SetFromOS() {
st.Out, st.Err, st.In = os.Stdout, os.Stderr, os.Stdin
}
// SetAll sets all our IO from given args
func (st *StdIO) SetAll(out, err io.Writer, in io.Reader) {
st.Out, st.Err, st.In = out, err, in
}
// Set sets our values from other StdIO, returning
// the current values at time of call, to restore later.
func (st *StdIO) Set(o *StdIO) *StdIO {
cur := *st
*st = *o
return &cur
}
// SetToOS sets the current IO to os.Std*, returning
// a StdIO with the current IO settings prior to this call,
// which can be used to restore.
// Note: os.Std* are *os.File types, and this function will do nothing
// if the current IO are not actually *os.Files.
// The results of a prior SetToOS call will do the right thing for
// saving and restoring the os state.
func (st *StdIO) SetToOS() *StdIO {
cur := &StdIO{}
cur.SetFromOS()
if sif, ok := st.In.(*os.File); ok {
os.Stdin = sif
}
if st.Out != nil {
if so, ok := st.Out.(*os.File); ok {
os.Stdout = so
}
}
if st.Err != nil {
if so, ok := st.Err.(*os.File); ok {
os.Stderr = so
}
}
return cur
}
// Print prints to the [StdIO.Out]
func (st *StdIO) Print(v ...any) {
fmt.Fprint(st.Out, v...)
}
// Println prints to the [StdIO.Out]
func (st *StdIO) Println(v ...any) {
fmt.Fprintln(st.Out, v...)
}
// Printf prints to the [StdIO.Out]
func (st *StdIO) Printf(f string, v ...any) {
fmt.Fprintf(st.Out, f, v...)
}
// ErrPrint prints to the [StdIO.Err]
func (st *StdIO) ErrPrint(v ...any) {
fmt.Fprint(st.Err, v...)
}
// ErrPrintln prints to the [StdIO.Err]
func (st *StdIO) ErrPrintln(v ...any) {
fmt.Fprintln(st.Err, v...)
}
// ErrPrintf prints to the [StdIO.Err]
func (st *StdIO) ErrPrintf(f string, v ...any) {
fmt.Fprintf(st.Err, f, v...)
}
// IsPipe returns true if the given object is an os.File corresponding to a Pipe,
// which is also not the same as the current os.Stdout, in case that is a Pipe.
func IsPipe(rw any) bool {
if rw == nil {
return false
}
_, ok := rw.(io.Writer)
if !ok {
return false
}
of, ok := rw.(*os.File)
if !ok {
return false
}
st, err := of.Stat()
if err != nil {
return false
}
md := st.Mode()
if md&fs.ModeNamedPipe != 0 {
return true
}
return md&fs.ModeCharDevice == 0
}
// OutIsPipe returns true if current Out is a Pipe
func (st *StdIO) OutIsPipe() bool { return IsPipe(st.Out) }
// StdIOState maintains a stack of StdIO settings for easier management
// of dynamic IO routing. Call [StackStart] prior to
// setting the IO values using Push commands, and then call
// [PopToStart] when done to close any open IO and reset.
type StdIOState struct {
StdIO
// OutStack is stack of out
OutStack stack.Stack[io.Writer]
// ErrStack is stack of err
ErrStack stack.Stack[io.Writer]
// InStack is stack of in
InStack stack.Stack[io.Reader]
// PipeIn is a stack of the os.File to use for reading from the Out,
// when Out is a Pipe, created by [PushOutPipe].
// Use [OutIsPipe] function to determine if the current output is a Pipe
// in order to determine whether to use the current [PipeIn.Peek()].
// These will be automatically closed during [PopToStart] whenever the
// corresponding Out is a Pipe.
PipeIn stack.Stack[*os.File]
// Starting depths of the respective stacks, for unwinding the stack
// to a defined starting point.
OutStart, ErrStart, InStart int
}
// PushOut pushes a new io.Writer as the current [Out],
// saving the current one on a stack, which can be restored using [PopOut].
func (st *StdIOState) PushOut(out io.Writer) {
st.OutStack.Push(st.Out)
st.Out = out
}
// PushOutPipe calls os.Pipe() and pushes the writer side
// as the new [Out], and pushes the Reader side to [PipeIn]
// which should then be used as the [In] for any other relevant process.
// Call [OutIsPipe] to determine if the current Out is a Pipe, to know
// whether to use the PipeIn.Peek() value.
func (st *StdIOState) PushOutPipe() {
r, w, err := os.Pipe()
if err != nil {
slog.Error(err.Error())
}
st.PushOut(w)
st.PipeIn.Push(r)
}
// PopOut restores previous io.Writer as [Out] from the stack,
// saved during [PushOut], returning the current Out at time of call.
// Pops and closes corresponding PipeIn if current Out is a Pipe.
// This does NOT close the current one, in case you need to use it before closing,
// so that is your responsibility (see [PopToStart] that does this for you).
func (st *StdIOState) PopOut() io.Writer {
if st.OutIsPipe() && len(st.PipeIn) > 0 {
CloseReader(st.PipeIn.Pop())
}
cur := st.Out
st.Out = st.OutStack.Pop()
return cur
}
// PushErr pushes a new io.Writer as the current [Err],
// saving the current one on a stack, which can be restored using [PopErr].
func (st *StdIOState) PushErr(err io.Writer) {
st.ErrStack.Push(st.Err)
st.Err = err
}
// PopErr restores previous io.Writer as [Err] from the stack,
// saved during [PushErr], returning the current Err at time of call.
// This does NOT close the current one, in case you need to use it before closing,
// so that is your responsibility (see [PopToStart] that does this for you).
// Note that Err is often the same as Out, in which case only Out should be closed.
func (st *StdIOState) PopErr() io.Writer {
cur := st.Err
st.Err = st.ErrStack.Pop()
return cur
}
// PushIn pushes a new [io.Reader] as the current [In],
// saving the current one on a stack, which can be restored using [PopIn].
func (st *StdIOState) PushIn(in io.Reader) {
st.InStack.Push(st.In)
st.In = in
}
// PopIn restores previous io.Reader as [In] from the stack,
// saved during [PushIn], returning the current In at time of call.
// This does NOT close the current one, in case you need to use it before closing,
// so that is your responsibility (see [PopToStart] that does this for you).
func (st *StdIOState) PopIn() io.Reader {
cur := st.In
st.In = st.InStack.Pop()
return cur
}
// StackStart records the starting depths of the IO stacks
func (st *StdIOState) StackStart() {
st.OutStart = len(st.OutStack)
st.ErrStart = len(st.ErrStack)
st.InStart = len(st.InStack)
}
// PopToStart unwinds the IO stacks to the depths recorded at [StackStart],
// automatically closing the ones that are popped, such as the files and
// pipes that were pushed.
// It automatically checks if any of the Err items are the same as Out
// and does not redundantly close those.
func (st *StdIOState) PopToStart() {
for len(st.ErrStack) > st.ErrStart {
er := st.PopErr()
if !st.ErrIsInOut(er) {
CloseWriter(er)
}
}
for len(st.OutStack) > st.OutStart {
CloseWriter(st.PopOut())
}
for len(st.InStack) > st.InStart {
CloseReader(st.PopIn())
}
for len(st.PipeIn) > 0 {
CloseReader(st.PipeIn.Pop())
}
}
// ErrIsInOut returns true if the given Err writer is the current Out, or
// present within the stack of Outs from [OutStart] on.
// If this is true, then Err should not be closed, as it will be closed
// when the Out is closed.
func (st *StdIOState) ErrIsInOut(er io.Writer) bool {
if st.Out == er {
return true
}
for i := st.OutStart; i < len(st.OutStack); i++ {
if st.OutStack[i] == er {
return true
}
}
return false
}
// CloseWriter closes given Writer, if it has a Close() method
func CloseWriter(w io.Writer) {
if st, ok := w.(io.Closer); ok {
st.Close()
}
}
// CloseReader closes given Reader, if it has a Close() method
func CloseReader(r io.Reader) {
if st, ok := r.(io.Closer); ok {
st.Close()
}
}
// WriteWrapper is an io.Writer that wraps another io.Writer
type WriteWrapper struct {
io.Writer
}
// ReadWrapper is an io.Reader that wraps another io.Reader
type ReadWrapper struct {
io.Reader
}
// NewWrappers initializes this StdIO with wrappers around given StdIO
func (st *StdIO) NewWrappers(o *StdIO) {
st.Out = &WriteWrapper{Writer: o.Out}
st.Err = &WriteWrapper{Writer: o.Err}
st.In = &ReadWrapper{Reader: o.In}
}
// SetWrappers sets the wrappers to current values from given StdIO,
// returning a copy of the wrapped values previously in place at start of call,
// which can be used in restoring state later.
// The wrappers must have been created using NewWrappers initially.
func (st *StdIO) SetWrappers(o *StdIO) *StdIO {
if o == nil {
return nil
}
cur := st.GetWrapped()
if cur == nil {
return nil
}
st.Out.(*WriteWrapper).Writer = o.Out
st.Err.(*WriteWrapper).Writer = o.Err
st.In.(*ReadWrapper).Reader = o.In
return cur
}
// SetWrappedOut sets the wrapped Out to given writer.
// The wrappers must have been created using NewWrappers initially.
func (st *StdIO) SetWrappedOut(w io.Writer) {
st.Out.(*WriteWrapper).Writer = w
}
// SetWrappedErr sets the wrapped Err to given writer.
// The wrappers must have been created using NewWrappers initially.
func (st *StdIO) SetWrappedErr(w io.Writer) {
st.Err.(*WriteWrapper).Writer = w
}
// SetWrappedIn sets the wrapped In to given reader.
// The wrappers must have been created using NewWrappers initially.
func (st *StdIO) SetWrappedIn(r io.Reader) {
st.In.(*ReadWrapper).Reader = r
}
// GetWrapped returns the current wrapped values as a StdIO.
// The wrappers must have been created using NewWrappers initially.
func (st *StdIO) GetWrapped() *StdIO {
_, ok := st.Out.(*WriteWrapper)
if !ok {
return nil
}
o := &StdIO{}
o.Out = st.Out.(*WriteWrapper).Writer
o.Err = st.Err.(*WriteWrapper).Writer
o.In = st.In.(*ReadWrapper).Reader
return o
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package apps provides access to the apps of the system that open files:
// the apps that can open a file, its default app, opening it with another
// app, and changing the default app for its type of file, using the
// facilities of each platform: NSWorkspace on macOS, and the freedesktop
// (XDG) desktop entries and mimeapps.list files on Linux and other unix
// systems. Other platforms return [errors.ErrUnsupported].
package apps
import (
"errors"
"path/filepath"
"slices"
"strings"
)
// App is an app of the system that can open files.
type App struct {
// Name is the name of the app shown to the user.
Name string
// ID identifies the app to the system: the path of its app bundle
// on macOS, and the ID of its desktop entry on Linux, as in
// org.gnome.TextEditor.desktop.
ID string
// Default is whether the app is the default app for the type of file.
Default bool
}
// For returns the apps that can open the given file, with its default app,
// if any, first.
func For(file string) ([]App, error) {
return forFile(abs(file))
}
// Default returns the default app for the given file, and false if it has none.
func Default(file string) (App, bool, error) {
as, err := For(file)
if err != nil || len(as) == 0 || !as[0].Default {
return App{}, false, err
}
return as[0], true, nil
}
// All returns all of the apps of the system that open files, sorted by
// name, as for choosing one that does not declare that it opens a file,
// which can still open it.
func All() ([]App, error) {
as, err := allApps()
slices.SortFunc(as, func(a, b App) int {
return strings.Compare(strings.ToLower(a.Name), strings.ToLower(b.Name))
})
return as, err
}
// OpenWith opens the given file with the given app.
func OpenWith(file string, app App) error {
if app.ID == "" {
return errors.New("apps: no app to open " + file + " with")
}
return openWith(abs(file), app)
}
// SetDefault makes the given app the default app for the type of the given
// file, as for all files with its extension.
func SetDefault(file string, app App) error {
if app.ID == "" {
return errors.New("apps: no app to make the default for " + file)
}
return setDefault(abs(file), app)
}
// abs returns the absolute path of the given file.
func abs(file string) string {
if a, err := filepath.Abs(file); err == nil {
return a
}
return file
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build (linux && !android) || freebsd || openbsd || netbsd || dragonfly
package apps
import (
"errors"
"os/exec"
"strings"
"cogentcore.org/core/base/fileinfo"
)
// mimeType returns the MIME type of the given file, as the desktop knows
// it (xdg-mime), or else as [fileinfo] does.
func mimeType(file string) (string, error) {
if out, err := exec.Command("xdg-mime", "query", "filetype", file).Output(); err == nil {
if mt, _, _ := strings.Cut(strings.TrimSpace(string(out)), ";"); mt != "" {
return mt, nil
}
}
mt, _, err := fileinfo.MimeFromFile(file)
return mt, err
}
func forFile(file string) ([]App, error) {
mt, err := mimeType(file)
if err != nil {
return nil, err
}
return xdgApps(mt), nil
}
func openWith(file string, app App) error {
de := desktopEntries()[app.ID]
if de == nil {
return errors.New("apps: no desktop entry for " + app.ID)
}
args, err := execArgs(de.Exec, file)
if err != nil {
return err
}
cmd := exec.Command(args[0], args[1:]...)
if err := cmd.Start(); err != nil {
return err
}
go cmd.Wait()
return nil
}
func setDefault(file string, app App) error {
mt, err := mimeType(file)
if err != nil {
return err
}
return setXDGDefault(mt, app.ID)
}
func allApps() ([]App, error) {
return xdgAllApps(), nil
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package apps
import (
"bufio"
"errors"
"io/fs"
"log/slog"
"net/url"
"os"
"path/filepath"
"slices"
"strings"
)
// This file has the freedesktop (XDG) implementation, used on Linux and
// other unix systems: the apps are the desktop entries in the applications
// directories of the XDG data directories, and the default apps are in the
// mimeapps.list files of the XDG config directories, as in
// https://specifications.freedesktop.org/mime-apps-spec.
// desktopEntry is the freedesktop desktop entry of an app.
type desktopEntry struct {
// ID is the desktop file ID, as in org.gnome.TextEditor.desktop.
ID string
// Name is the name of the app.
Name string
// Exec is the command line that opens files.
Exec string
// MimeTypes are the MIME types of the files that the app opens.
MimeTypes []string
// Hidden is whether the entry is deleted.
Hidden bool
// NoDisplay is whether the app is not shown in the menus of apps,
// although it can open the files of its MimeTypes.
NoDisplay bool
}
// envDirs returns the directories in the given XDG environment variables:
// the one for the user, with the given default under the home directory,
// and the list of the system ones, with the given defaults.
func envDirs(home, homeDefault, list string, listDefault ...string) []string {
var dirs []string
if d := os.Getenv(home); d != "" {
dirs = append(dirs, d)
} else if hd, err := os.UserHomeDir(); err == nil {
dirs = append(dirs, filepath.Join(hd, homeDefault))
}
if l := os.Getenv(list); l != "" {
return append(dirs, filepath.SplitList(l)...)
}
return append(dirs, listDefault...)
}
// dataDirs returns the XDG data directories, the user's first.
func dataDirs() []string {
return envDirs("XDG_DATA_HOME", ".local/share", "XDG_DATA_DIRS", "/usr/local/share", "/usr/share")
}
// configDirs returns the XDG config directories, the user's first.
func configDirs() []string {
return envDirs("XDG_CONFIG_HOME", ".config", "XDG_CONFIG_DIRS", "/etc/xdg")
}
// readDesktopEntry reads the desktop entry of an app with the given ID
// from the given file, returning nil if it is not one.
func readDesktopEntry(id, file string) *desktopEntry {
f, err := os.Open(file)
if err != nil {
return nil
}
defer f.Close()
de := &desktopEntry{ID: id}
inEntry, isApp := false, false
sc := bufio.NewScanner(f)
for sc.Scan() {
ln := strings.TrimSpace(sc.Text())
if strings.HasPrefix(ln, "[") {
inEntry = ln == "[Desktop Entry]"
continue
}
key, val, ok := strings.Cut(ln, "=")
if !inEntry || !ok {
continue
}
switch strings.TrimSpace(key) {
case "Type":
isApp = strings.TrimSpace(val) == "Application"
case "Name":
de.Name = strings.TrimSpace(val)
case "Exec":
de.Exec = strings.TrimSpace(val)
case "MimeType":
for mt := range strings.SplitSeq(val, ";") {
if mt = strings.TrimSpace(mt); mt != "" {
de.MimeTypes = append(de.MimeTypes, mt)
}
}
case "Hidden":
de.Hidden = strings.TrimSpace(val) == "true"
case "NoDisplay":
de.NoDisplay = strings.TrimSpace(val) == "true"
}
}
if !isApp || sc.Err() != nil {
return nil
}
return de
}
// desktopEntries returns the desktop entries of the apps by ID, from the
// applications directories of the data directories, of which the first
// has precedence. The ID of an entry in a subdirectory has its path,
// with - instead of /.
func desktopEntries() map[string]*desktopEntry {
des := map[string]*desktopEntry{}
for _, dd := range dataDirs() {
ad := filepath.Join(dd, "applications")
filepath.WalkDir(ad, func(path string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() || !strings.HasSuffix(path, ".desktop") {
return nil
}
rel, _ := filepath.Rel(ad, path)
id := strings.ReplaceAll(filepath.ToSlash(rel), "/", "-")
if _, has := des[id]; has {
return nil
}
if de := readDesktopEntry(id, path); de != nil {
des[id] = de
}
return nil
})
}
return des
}
// mimeApps are the associations of the mimeapps.list files.
type mimeApps struct {
// defaults are the default apps for each MIME type, in order of preference.
defaults map[string][]string
// added and removed are the apps associated with each MIME type,
// and those not associated with it, in addition to the desktop entries.
added, removed map[string][]string
}
// mimeAppsFiles returns the mimeapps.list files, in order of precedence.
func mimeAppsFiles() []string {
var files []string
for _, cd := range configDirs() {
files = append(files, filepath.Join(cd, "mimeapps.list"))
}
for _, dd := range dataDirs() {
files = append(files, filepath.Join(dd, "applications", "mimeapps.list"))
}
return files
}
// readMimeApps reads the associations of the mimeapps.list files.
func readMimeApps() *mimeApps {
ma := &mimeApps{defaults: map[string][]string{}, added: map[string][]string{}, removed: map[string][]string{}}
for _, file := range mimeAppsFiles() {
f, err := os.Open(file)
if err != nil {
continue
}
var sect map[string][]string
sc := bufio.NewScanner(f)
for sc.Scan() {
ln := strings.TrimSpace(sc.Text())
switch ln {
case "[Default Applications]":
sect = ma.defaults
continue
case "[Added Associations]":
sect = ma.added
continue
case "[Removed Associations]":
sect = ma.removed
continue
}
if strings.HasPrefix(ln, "[") {
sect = nil
continue
}
mt, ids, ok := strings.Cut(ln, "=")
if sect == nil || !ok {
continue
}
for id := range strings.SplitSeq(ids, ";") {
if id = strings.TrimSpace(id); id != "" {
sect[mt] = append(sect[mt], id) // earlier files first
}
}
}
if err := sc.Err(); err != nil { // the associations read before it are used
slog.Warn("apps: reading a MIME apps file", "file", file, "err", err)
}
f.Close()
}
return ma
}
// xdgApps returns the apps for the given MIME type, with the default first.
func xdgApps(mime string) []App {
des := desktopEntries()
ma := readMimeApps()
var as []App
has := func(id string) bool {
return slices.ContainsFunc(as, func(a App) bool { return a.ID == id })
}
add := func(id string, def bool) {
de := des[id]
if de == nil || de.Hidden || has(id) || slices.Contains(ma.removed[mime], id) {
return
}
as = append(as, App{Name: de.Name, ID: id, Default: def})
}
for _, id := range ma.defaults[mime] {
if len(as) == 0 {
add(id, true) // the first one that is installed
}
}
for _, id := range ma.added[mime] {
add(id, false)
}
ids := make([]string, 0, len(des))
for id := range des {
ids = append(ids, id)
}
slices.SortFunc(ids, func(a, b string) int { return strings.Compare(des[a].Name, des[b].Name) })
for _, id := range ids {
if slices.Contains(des[id].MimeTypes, mime) {
add(id, false)
}
}
return as
}
// xdgAllApps returns all of the apps that open files, those of the
// desktop entries that are shown in the menus of apps and have a
// command line.
func xdgAllApps() []App {
var as []App
for id, de := range desktopEntries() {
if de.Hidden || de.NoDisplay || de.Exec == "" {
continue
}
as = append(as, App{Name: de.Name, ID: id})
}
return as
}
// execArgs returns the command line of the given Exec value of a desktop
// entry to open the given file, splitting it into arguments as the shell
// does with double quotes and backslashes, and replacing the field codes:
// %f, %F, %u and %U by the file (or its URL), and the others by nothing.
func execArgs(exec, file string) ([]string, error) {
var args []string
var cur strings.Builder
inArg, quoted, hasFile := false, false, false
rs := []rune(exec)
for i := 0; i < len(rs); i++ {
r := rs[i]
switch {
case r == '"':
quoted = !quoted
inArg = true
case r == '\\' && i+1 < len(rs):
i++
cur.WriteRune(rs[i])
inArg = true
case r == '%' && i+1 < len(rs):
i++
switch rs[i] {
case 'f', 'F':
cur.WriteString(file)
hasFile, inArg = true, true
case 'u', 'U':
cur.WriteString((&url.URL{Scheme: "file", Path: file}).String())
hasFile, inArg = true, true
case '%':
cur.WriteRune('%')
inArg = true
}
case (r == ' ' || r == '\t') && !quoted:
if inArg {
args = append(args, cur.String())
cur.Reset()
inArg = false
}
default:
cur.WriteRune(r)
inArg = true
}
}
if inArg {
args = append(args, cur.String())
}
if len(args) == 0 {
return nil, errors.New("apps: empty Exec command")
}
if !hasFile {
args = append(args, file)
}
return args, nil
}
// setXDGDefault makes the app with the given ID the default app for the
// given MIME type in the user's mimeapps.list file, keeping its other
// contents.
func setXDGDefault(mime, id string) error {
file := filepath.Join(configDirs()[0], "mimeapps.list")
var lines []string
if b, err := os.ReadFile(file); err == nil {
lines = strings.Split(strings.TrimRight(string(b), "\n"), "\n")
}
entry := mime + "=" + id + ";"
sect := slices.Index(lines, "[Default Applications]")
if sect < 0 {
if len(lines) > 0 {
lines = append(lines, "")
}
lines = append(lines, "[Default Applications]", entry)
} else {
end := len(lines)
set := false
for i := sect + 1; i < len(lines); i++ {
ln := strings.TrimSpace(lines[i])
if strings.HasPrefix(ln, "[") {
end = i
break
}
if strings.HasPrefix(ln, mime+"=") {
lines[i] = entry
set = true
break
}
}
if !set {
lines = slices.Insert(lines, end, entry)
}
}
if err := os.MkdirAll(filepath.Dir(file), 0o755); err != nil {
return err
}
return os.WriteFile(file, []byte(strings.Join(lines, "\n")+"\n"), 0o644)
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package fileinfo
// Categories is a functional category for files; a broad functional
// categorization that can help decide what to do with the file.
//
// It is computed in part from the mime type, but some types require
// other information.
//
// No single categorization scheme is perfect, so any given use
// may require examination of the full mime type etc, but this
// provides a useful broad-scope categorization of file types.
type Categories int32 //enums:enum
const (
// UnknownCategory is an unknown file category
UnknownCategory Categories = iota
// Folder is a folder / directory
Folder
// Archive is a collection of files, e.g., zip tar
Archive
// Backup is a backup file (# ~ etc)
Backup
// Code is a programming language file
Code
// Doc is an editable word processing file including latex, markdown, html, css, etc
Doc
// Sheet is a spreadsheet file (.xls etc)
Sheet
// Data is some kind of data format (csv, json, database, etc)
Data
// Text is some other kind of text file
Text
// Image is an image (jpeg, png, svg, etc) *including* PDF
Image
// Model is a 3D model
Model
// Audio is an audio file
Audio
// Video is a video file
Video
// Font is a font file
Font
// Exe is a binary executable file (scripts go in Code)
Exe
// Bin is some other type of binary (object files, libraries, etc)
Bin
)
// CategoryFromMime returns the file category based on the mime type;
// not all Categories can be inferred from file types
func CategoryFromMime(mime string) Categories {
if mime == "" {
return UnknownCategory
}
mime = MimeNoChar(mime)
if mt, has := AvailableMimes[mime]; has {
return mt.Cat // must be set!
}
// try from type:
ms := MimeTop(mime)
if ms == "" {
return UnknownCategory
}
switch ms {
case "image":
return Image
case "audio":
return Audio
case "video":
return Video
case "font":
return Font
case "model":
return Model
}
if ms == "text" {
return Text
}
return UnknownCategory
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package fileinfo manages file information and categorizes file types;
// it is the single, consolidated place where file info, mimetypes, and
// filetypes are managed in Cogent Core.
//
// This whole space is a bit of a heterogenous mess; most file types
// we care about are not registered on the official iana registry, which
// seems mainly to have paid registrations in application/ category,
// and doesn't have any of the main programming languages etc.
//
// The official Go std library support depends on different platform
// libraries and mac doesn't have one, so it has very limited support
//
// So we sucked it up and made a full list of all the major file types
// that we really care about and also provide a broader category-level organization
// that is useful for functionally organizing / operating on files.
//
// As fallback, we are this Go package:
// github.com/h2non/filetype
package fileinfo
import (
"errors"
"fmt"
"io/fs"
"log"
"os"
"path"
"path/filepath"
"strings"
"testing"
"time"
"cogentcore.org/core/base/datasize"
"cogentcore.org/core/base/fsx"
"cogentcore.org/core/base/vcs"
"cogentcore.org/core/icons"
"github.com/Bios-Marcel/wastebasket/v2"
)
// FileInfo represents the information about a given file / directory,
// including icon, mimetype, etc
type FileInfo struct { //types:add
// icon for file
Ic icons.Icon `table:"no-header"`
// name of the file, without any path
Name string `width:"40"`
// size of the file
Size datasize.Size
// type of file / directory; shorter, more user-friendly
// version of mime type, based on category
Kind string `width:"20" max-width:"20"`
// full official mime type of the contents
Mime string `table:"-"`
// functional category of the file, based on mime data etc
Cat Categories `table:"-"`
// known file type
Known Known `table:"-"`
// file mode bits
Mode fs.FileMode `table:"-"`
// time that contents (only) were last modified
ModTime time.Time `label:"Last modified"`
// version control system status, when enabled
VCS vcs.FileStatus `table:"-"`
// Generated indicates that the file is generated and should not be edited.
// For Go files, this regex: `^// Code generated .* DO NOT EDIT\.$` is used.
Generated bool `table:"-"`
// full path to file, including name; for file functions
Path string `table:"-"`
}
// NewFileInfo returns a new FileInfo for given file.
func NewFileInfo(fname string) (*FileInfo, error) {
fi := &FileInfo{}
err := fi.InitFile(fname)
return fi, err
}
// NewFileInfoType returns a new FileInfo representing the given file type.
func NewFileInfoType(ftyp Known) *FileInfo {
fi := &FileInfo{}
fi.SetType(ftyp)
return fi
}
// InitFile initializes a FileInfo for os file based on a filename,
// which is updated to full path using filepath.Abs.
// Returns error from filepath.Abs and / or fs.Stat error on the given file,
// but file info will be updated based on the filename even if
// the file does not exist.
func (fi *FileInfo) InitFile(fname string) error {
fi.Cat = UnknownCategory
fi.Known = Unknown
fi.Generated = false
fi.Kind = ""
var errs []error
path, err := filepath.Abs(fname)
if err == nil {
fi.Path = path
} else {
fi.Path = fname
}
_, fi.Name = filepath.Split(path)
info, err := os.Stat(fi.Path)
if err != nil {
errs = append(errs, err)
fi.MimeFromFilename()
} else {
fi.SetFileInfo(info)
}
return errors.Join(errs...)
}
// InitFileFS initializes a FileInfo based on filename in given fs.FS.
// Returns error from fs.Stat error on the given file,
// but file info will be updated based on the filename even if
// the file does not exist.
func (fi *FileInfo) InitFileFS(fsys fs.FS, fname string) error {
fi.Cat = UnknownCategory
fi.Known = Unknown
fi.Generated = false
fi.Kind = ""
var errs []error
fi.Path = fname
_, fi.Name = path.Split(fname)
info, err := fs.Stat(fsys, fi.Path)
if err != nil {
errs = append(errs, err)
fi.MimeFromFilename()
} else {
fi.SetFileInfo(info)
}
return errors.Join(errs...)
}
// MimeFromFilename sets the mime data based only on the filename
// without attempting to open the file.
func (fi *FileInfo) MimeFromFilename() error {
ext := strings.ToLower(filepath.Ext(fi.Path))
if mtype, has := ExtMimeMap[ext]; has { // only use our filename ext map
fi.SetMimeFromType(mtype)
return nil
}
return errors.New("FileInfo MimeFromFilename: Filename extension not known: " + ext)
}
// MimeFromFile sets the mime data for a valid file (i.e., os.Stat works).
// Use MimeFromFilename to only examine the filename.
func (fi *FileInfo) MimeFromFile() error {
if fi.Path == "" || fi.Path == "." || fi.IsDir() {
return nil
}
fi.Generated = IsGeneratedFile(fi.Path)
mtype, _, err := MimeFromFile(fi.Path)
if err != nil {
return err
}
fi.SetMimeFromType(mtype)
return nil
}
// SetMimeFromType sets file info fields from given mime type string.
func (fi *FileInfo) SetMimeFromType(mtype string) {
fi.Mime = mtype
fi.Cat = CategoryFromMime(mtype)
fi.Known = MimeKnown(mtype)
if fi.Cat != UnknownCategory {
fi.Kind = fi.Cat.String() + ": "
}
if fi.Known != Unknown {
fi.Kind += fi.Known.String()
} else {
fi.Kind += MimeSub(fi.Mime)
}
}
// SetFileInfo updates from given [fs.FileInfo]. It uses a canonical
// [FileInfo.ModTime] when testing to ensure consistent results.
func (fi *FileInfo) SetFileInfo(info fs.FileInfo) {
fi.Size = datasize.Size(info.Size())
fi.Mode = info.Mode()
if testing.Testing() {
// We use a canonical time when testing to ensure consistent results.
fi.ModTime = time.Unix(1500000000, 0)
} else {
fi.ModTime = info.ModTime()
}
if info.IsDir() {
fi.Kind = "Folder"
fi.Cat = Folder
fi.Known = AnyFolder
} else {
if fi.Mode.IsRegular() {
fi.MimeFromFile()
}
if fi.Cat == UnknownCategory {
if fi.IsExec() {
fi.Cat = Exe
fi.Known = AnyExe
}
}
}
icn, _ := fi.FindIcon()
fi.Ic = icn
}
// SetType sets file type information for given Known file type
func (fi *FileInfo) SetType(ftyp Known) {
mt := MimeFromKnown(ftyp)
fi.Mime = mt.Mime
fi.Cat = mt.Cat
fi.Known = mt.Known
if ftyp == Unknown { // (with no mime type, whose zero category is Audio)
fi.Cat = UnknownCategory
fi.Known = Unknown
}
if fi.Name == "" && len(mt.Exts) > 0 {
fi.Name = "_fake" + mt.Exts[0]
fi.Path = fi.Name
}
fi.Kind = fi.Cat.String() + ": "
if fi.Known != Unknown {
fi.Kind += fi.Known.String()
}
}
// IsDir returns true if file is a directory (folder)
func (fi *FileInfo) IsDir() bool {
return fi.Mode.IsDir()
}
// IsExec returns true if file is an executable file
func (fi *FileInfo) IsExec() bool {
if fi.Mode&0111 != 0 {
return true
}
ext := filepath.Ext(fi.Path)
return ext == ".exe"
}
// IsSymlink returns true if file is a symbolic link
func (fi *FileInfo) IsSymlink() bool {
return fi.Mode&os.ModeSymlink != 0
}
// IsHidden returns true if file name starts with . or _ which are typically hidden
func (fi *FileInfo) IsHidden() bool {
return fi.Name == "" || fi.Name[0] == '.' || fi.Name[0] == '_'
}
//////////////////////////////////////////////////////////////////////////////
// File ops
// Duplicate creates a copy of the file or directory (with all of its contents)
// in the same directory, named with a _Copy suffix before the extension
// (_Copy1, _Copy2, etc if that exists), and returns its path.
func (fi *FileInfo) Duplicate() (string, error) { //types:add
ext := filepath.Ext(fi.Name)
if fi.IsDir() || ext == fi.Name { // no extension for directories and .gitignore etc
ext = ""
}
noext := strings.TrimSuffix(fi.Path, ext)
dst := noext + "_Copy" + ext
for i := 1; ; i++ {
if _, err := os.Lstat(dst); errors.Is(err, fs.ErrNotExist) {
break
}
dst = noext + fmt.Sprintf("_Copy%d", i) + ext
}
return dst, fsx.CopyPath(dst, fi.Path)
}
// Delete moves the file to the trash / recycling bin.
// On mobile and web, and when testing, it deletes it directly.
func (fi *FileInfo) Delete() error { //types:add
if testing.Testing() { // not filling the trash with test files
return os.RemoveAll(fi.Path)
}
err := wastebasket.Trash(fi.Path)
if errors.Is(err, wastebasket.ErrPlatformNotSupported) {
return os.RemoveAll(fi.Path)
}
return err
}
// Filenames recursively adds fullpath filenames within the starting directory to the "names" slice.
// Directory names within the starting directory are not added.
func Filenames(d os.File, names *[]string) (err error) {
return filepath.WalkDir(d.Name(), func(path string, de fs.DirEntry, err error) error {
if err != nil {
return err
}
if !de.IsDir() {
*names = append(*names, path)
}
return nil
})
}
// Filenames returns a slice of file names from the starting directory and its subdirectories
func (fi *FileInfo) Filenames(names *[]string) (err error) {
if !fi.IsDir() {
err = errors.New("not a directory: Filenames returns a list of files within a directory")
return err
}
path := fi.Path
d, err := os.Open(path)
if err != nil {
return err
}
defer d.Close()
err = Filenames(*d, names)
return err
}
// RenamePath returns the new full path for renaming this file to the given
// path, which is relative to the directory of the file if not absolute.
// It returns "" if the path is the same as the current one, and an error
// if a different file already exists at the new path (a change of case
// only is OK on case-insensitive file systems).
// Does not actually do the renaming -- see Rename method.
func (fi *FileInfo) RenamePath(path string) (newpath string, err error) {
if path == "" {
err = errors.New("core.Rename: new name is empty")
log.Println(err)
return path, err
}
newpath = path
if !filepath.IsAbs(newpath) {
newpath = filepath.Join(filepath.Dir(fi.Path), newpath)
}
if newpath == filepath.Clean(fi.Path) {
return "", nil
}
if ninfo, err := os.Lstat(newpath); err == nil {
if oinfo, err := os.Lstat(fi.Path); err != nil || !os.SameFile(ninfo, oinfo) {
return "", fmt.Errorf("cannot rename %s: %s already exists", fi.Name, newpath)
}
}
return newpath, nil
}
// Rename renames (moves) this file to given new path name.
// Updates the FileInfo setting to the new name, although it might
// be out of scope if it moved into a new path
func (fi *FileInfo) Rename(path string) (newpath string, err error) { //types:add
orgpath := fi.Path
newpath, err = fi.RenamePath(path)
if err != nil || newpath == "" {
return
}
err = os.Rename(string(orgpath), newpath)
if err == nil {
fi.Path = newpath
_, fi.Name = filepath.Split(newpath)
}
return
}
// FindIcon uses file info to find an appropriate icon for this file -- uses
// Kind string first to find a correspondingly named icon, and then tries the
// extension. Returns true on success.
func (fi *FileInfo) FindIcon() (icons.Icon, bool) {
if fi.IsDir() {
return icons.Folder, true
}
return Icons[fi.Known], true
}
// Note: can get all the detailed birth, access, change times from this package
// "github.com/djherbis/times"
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package fileinfo
//go:generate core generate
import (
"fmt"
)
// Known is an enumerated list of known file types, for which
// appropriate actions can be taken etc.
type Known int32 //enums:enum
// KnownMimes maps from the known type into the MimeType info for each
// known file type; the known MimeType may be just one of
// multiple that correspond to the known type; it should be first in list
// and have extensions defined
var KnownMimes map[Known]MimeType
// MimeString gives the string representation of the canonical mime type
// associated with given known mime type.
func MimeString(kn Known) string {
mt, has := KnownMimes[kn]
if !has {
// log.Printf("fileinfo.MimeString called with unrecognized 'Known' type: %v\n", sup)
return ""
}
return mt.Mime
}
// Cat returns the Cat category for given known file type
func (kn Known) Cat() Categories {
if kn == Unknown {
return UnknownCategory
}
mt, has := KnownMimes[kn]
if !has {
// log.Printf("fileinfo.KnownCat called with unrecognized 'Known' type: %v\n", sup)
return UnknownCategory
}
return mt.Cat
}
// IsMatch returns true if given file type matches target type,
// which could be any of the Any options
func IsMatch(targ, typ Known) bool {
if targ == Any {
return true
}
if targ == AnyKnown {
return typ != Unknown
}
if targ == typ {
return true
}
cat := typ.Cat()
switch targ {
case AnyFolder:
return cat == Folder
case AnyArchive:
return cat == Archive
case AnyBackup:
return cat == Backup
case AnyCode:
return cat == Code
case AnyDoc:
return cat == Doc
case AnySheet:
return cat == Sheet
case AnyData:
return cat == Data
case AnyText:
return cat == Text
case AnyImage:
return cat == Image
case AnyModel:
return cat == Model
case AnyAudio:
return cat == Audio
case AnyVideo:
return cat == Video
case AnyFont:
return cat == Font
case AnyExe:
return cat == Exe
case AnyBin:
return cat == Bin
}
return false
}
// IsMatchList returns true if given file type matches any of a list of targets
// if list is empty, then always returns true
func IsMatchList(targs []Known, typ Known) bool {
if len(targs) == 0 {
return true
}
for _, trg := range targs {
if IsMatch(trg, typ) {
return true
}
}
return false
}
// KnownByName looks up known file type by caps or lowercase name
func KnownByName(name string) (Known, error) {
var kn Known
err := kn.SetString(name)
if err != nil {
err = fmt.Errorf("fileinfo.KnownByName: doesn't look like that is a known file type: %v", name)
return kn, err
}
return kn, nil
}
// These are the super high-frequency used mime types, to have very quick const level support
const (
TextPlain = "text/plain"
DataJSON = "application/json"
DataXML = "application/xml"
DataCSV = "text/csv"
)
// These are the known file types, organized by category
const (
// Unknown = a non-known file type
Unknown Known = iota
// Any is used when selecting a file type, if any type is OK (including Unknown)
// see also AnyKnown and the Any options for each category
Any
// AnyKnown is used when selecting a file type, if any Known
// file type is OK (excludes Unknown) -- see Any and Any options for each category
AnyKnown
// Folder is a folder / directory
AnyFolder
// Archive is a collection of files, e.g., zip tar
AnyArchive
Multipart
Tar
Zip
GZip
SevenZ
XZ
BZip
DMG
Shar
// Backup files
AnyBackup
Trash
// Code is a programming language file
AnyCode
Ada
Bash
Cosh
Csh
C // includes C++
CSharp
D
Diff
Eiffel
Erlang
Forth
Fortran
FSharp
GLSL // OpenGL Shading Language
Go
Goal
Haskell
HLSL // High-Level Shader Language of DirectX
Java
JavaScript
TypeScript
Lisp
Lua
Makefile
Mathematica
Matlab
Metal // Metal Shading Language
ObjC
OCaml
Pascal
Perl
PHP
Prolog
Python
R
Ruby
Rust
Scala
SPIRV // SPIR-V assembly, the text form of the shaders of Vulkan
SQL
Tcl
WGSL // WebGPU Shading Language
// Doc is an editable word processing file including latex, markdown, html, css, etc
AnyDoc
BibTeX
TeX
Texinfo
Troff
HTML
CSS
Markdown
RTF
MSWord
OpenText
OpenPres
MSPowerPoint
EBook
EPUB
// Sheet is a spreadsheet file (.xls etc)
AnySheet
MSExcel
OpenSheet
// Data is some kind of data format (csv, json, database, etc)
AnyData
CSV
JSON
XML
Protobuf
INI
TSV
URI
Color
YAML
TOML
// special support for data fs
Number
String
Tensor
Table
// Text is some other kind of text file
AnyText
PlainText // text/plain mimetype -- used for clipboard
ICal
VCal
VCard
// Image is an image (jpeg, png, svg, etc) *including* PDF
AnyImage
PDF
PostScript
GIMP
Graphviz
GIF
JPEG
PNG
SVG
TIFF
PNM
PBM
PGM
PPM
XBM
XPM
BMP
HEIC
HEIF
// Model is a 3D model
AnyModel
VRML
X3D
OBJ
// Audio is an audio file
AnyAudio
AAC
FLAC
MP3
Ogg
MIDI
WAV
// Video is a video file
AnyVideo
MPEG
MP4
MOV
OGV
WMV
AVI
// Font is a font file
AnyFont
TrueType
WebOpenFont
// Exe is a binary executable file
AnyExe
// Bin is some other unrecognized binary type
AnyBin
)
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package mimedata defines MIME data support used in clipboard and
// drag-and-drop functions in the Cogent Core GUI. mimedata.Data struct contains
// format and []byte data, and multiple representations of the same data are
// encoded in mimedata.Mimes which is just a []mimedata.Data slice -- it can
// be encoded / decoded from mime multipart.
//
// See the fileinfo package for known mimetypes.
package mimedata
import (
"bytes"
"log"
"mime"
"strings"
)
const (
MIMEVersion1 = "MIME-Version: 1.0"
ContentType = "Content-Type"
ContentTransferEncoding = "Content-Transfer-Encoding"
TextPlain = "text/plain"
DataJson = "application/json"
DataXml = "application/xml"
)
var (
MIMEVersion1B = ([]byte)(MIMEVersion1)
ContentTypeB = ([]byte)(ContentType)
ContentTransferEncodingB = ([]byte)(ContentTransferEncoding)
)
// Data represents one element of MIME data as a type string and byte slice
type Data struct {
// MIME Type string representing the data, e.g., text/plain, text/html, text/xml, text/uri-list, image/jpg, png etc
Type string
// Data for the item
Data []byte
}
// NewTextData returns a Data representation of the string -- good idea to
// always have a text/plain representation of everything on clipboard /
// drag-n-drop
func NewTextData(text string) *Data {
return &Data{TextPlain, []byte(text)}
}
// NewTextDataBytes returns a Data representation of the bytes string
func NewTextDataBytes(text []byte) *Data {
return &Data{TextPlain, text}
}
// IsText returns true if type is any of the text/ types (literally looks for that
// at start of Type) or is another known text type (e.g., AppJSON, XML)
func IsText(typ string) bool {
if strings.HasPrefix(typ, "text/") {
return true
}
return typ == DataJson || typ == DataXml
}
////////////////////////////////////////////////////////////////////////////////
// Mimes
// Mimes is a slice of mime data, potentially encoding the same data in
// different formats -- this is used for all system APIs for maximum
// flexibility
type Mimes []*Data
// NewMimes returns a new Mimes slice of given length and capacity
func NewMimes(ln, cp int) Mimes {
return make(Mimes, ln, cp)
}
// NewText returns a Mimes representation of the string as a single text/plain Data
func NewText(text string) Mimes {
md := NewTextData(text)
mi := make(Mimes, 1)
mi[0] = md
return mi
}
// NewTextBytes returns a Mimes representation of the bytes string as a single text/plain Data
func NewTextBytes(text []byte) Mimes {
md := NewTextDataBytes(text)
mi := make(Mimes, 1)
mi[0] = md
return mi
}
// NewTextPlus returns a Mimes representation of an item as a text string plus
// a more specific type
func NewTextPlus(text, typ string, data []byte) Mimes {
md := NewTextData(text)
mi := make(Mimes, 2)
mi[0] = md
mi[1] = &Data{typ, data}
return mi
}
// NewMime returns a Mimes representation of one element
func NewMime(typ string, data []byte) Mimes {
mi := make(Mimes, 1)
mi[0] = &Data{typ, data}
return mi
}
// HasType returns true if Mimes has given type of data available
func (mi Mimes) HasType(typ string) bool {
for _, d := range mi {
if d.Type == typ {
return true
}
}
return false
}
// TypeData returns data associated with given MIME type
func (mi Mimes) TypeData(typ string) []byte {
for _, d := range mi {
if d.Type == typ {
return d.Data
}
}
return nil
}
// Text extracts all the text elements of given type as a string
func (mi Mimes) Text(typ string) string {
str := ""
for _, d := range mi {
if d.Type == typ {
str = str + string(d.Data)
}
}
return str
}
// IsMultipart examines data bytes to see if it has a MIME-Version: 1.0
// ContentType: multipart/* header -- returns the actual multipart media type,
// body of the data string after the header (assumed to be a single \n
// terminated line at start of string, and the boundary separating multipart
// elements (all from mime.ParseMediaType) -- mediaType is the mediaType if it
// is another MIME type -- can check that for non-empty string
func IsMultipart(str []byte) (isMulti bool, mediaType, boundary string, body []byte) {
isMulti = false
mediaType = ""
boundary = ""
body = ([]byte)("")
var pars map[string]string
var err error
if bytes.HasPrefix(str, MIMEVersion1B) {
_, after, ok := bytes.Cut(str, []byte{'\n'})
if !ok { // shouldn't happen
return
}
ctln := after
if bytes.HasPrefix(ctln, ContentTypeB) { // should
cri2 := bytes.IndexByte(ctln, '\n')
if cri2 < 0 { // shouldn't happen
return
}
hdr := ctln[len(ContentTypeB)+1 : cri2]
mediaType, pars, err = mime.ParseMediaType(string(hdr))
if err != nil { // shouldn't happen
log.Printf("mimedata.IsMultipart: malformed MIME header: %v\n", err)
return
}
if strings.HasPrefix(mediaType, "multipart/") {
isMulti = true
body = str[cri2+1:]
boundary = pars["boundary"]
}
}
}
return
}
// todo: image, etc extractors
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !js
package mimedata
import (
"bytes"
"encoding/base64"
"fmt"
"io"
"log"
"mime/multipart"
"net/textproto"
)
// ToMultipart produces a MIME multipart representation of multiple data
// elements present in the stream -- this should be used in system.Clipboard
// whenever there are multiple elements to be pasted, because windows doesn't
// support multiple clip elements, and linux isn't very convenient either
func (mi Mimes) ToMultipart() []byte {
var b bytes.Buffer
mpw := multipart.NewWriter(io.Writer(&b))
hdr := fmt.Sprintf("%v\n%v: multipart/mixed; boundary=%v\n", MIMEVersion1, ContentType, mpw.Boundary())
b.Write(([]byte)(hdr))
for _, d := range mi {
mh := textproto.MIMEHeader{ContentType: {d.Type}}
bin := false
if !IsText(d.Type) {
mh.Add(ContentTransferEncoding, "base64")
bin = true
}
wp, _ := mpw.CreatePart(mh)
if bin {
eb := make([]byte, base64.StdEncoding.EncodedLen(len(d.Data)))
base64.StdEncoding.Encode(eb, d.Data)
wp.Write(eb)
} else {
wp.Write(d.Data)
}
}
mpw.Close()
return b.Bytes()
}
// FromMultipart parses a MIME multipart representation of multiple data
// elements into corresponding mime data components
func FromMultipart(body []byte, boundary string) Mimes {
mi := make(Mimes, 0, 10)
sr := bytes.NewReader(body)
mr := multipart.NewReader(sr, boundary)
for {
p, err := mr.NextPart()
if err == io.EOF {
return mi
}
if err != nil {
log.Printf("mimedata.IsMultipart: malformed multipart MIME: %v\n", err)
return mi
}
b, err := io.ReadAll(p)
if err != nil {
log.Printf("mimedata.IsMultipart: bad ReadAll of multipart MIME: %v\n", err)
return mi
}
d := Data{}
d.Type = p.Header.Get(ContentType)
cte := p.Header.Get(ContentTransferEncoding)
if cte != "" {
switch cte {
case "base64":
eb := make([]byte, base64.StdEncoding.DecodedLen(len(b)))
n, _ := base64.StdEncoding.Decode(eb, b)
b = eb[:n]
}
}
d.Data = b
mi = append(mi, &d)
}
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mimedata
import (
"bytes"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"fmt"
"strings"
)
// The web versions of [Mimes.ToMultipart] and [FromMultipart] read and write
// the MIME multipart format without the mime/multipart package, which needs
// net/textproto and with it the net package (most of a megabyte of a web app).
// They write the same format as mime/multipart, and read what it writes.
// writeMultipart returns the MIME multipart representation of the given data
// with a new random boundary, as [Mimes.ToMultipart] does with mime/multipart.
func writeMultipart(mi Mimes) []byte {
// A random boundary, as made by multipart.Writer.
var rb [30]byte
rand.Read(rb[:])
boundary := hex.EncodeToString(rb[:])
// The header line, then each part with its sorted header fields.
var b bytes.Buffer
fmt.Fprintf(&b, "%v\n%v: multipart/mixed; boundary=%v\n", MIMEVersion1, ContentType, boundary)
for i, d := range mi {
if i > 0 {
b.WriteString("\r\n")
}
fmt.Fprintf(&b, "--%s\r\n", boundary)
data := d.Data
if !IsText(d.Type) {
fmt.Fprintf(&b, "%s: base64\r\n", ContentTransferEncoding)
data = []byte(base64.StdEncoding.EncodeToString(d.Data))
}
fmt.Fprintf(&b, "%s: %s\r\n\r\n", ContentType, d.Type)
b.Write(data)
}
// The closing boundary.
fmt.Fprintf(&b, "\r\n--%s--\r\n", boundary)
return b.Bytes()
}
// readMultipart parses the MIME multipart body with the given boundary, as
// [FromMultipart] does with mime/multipart.
func readMultipart(body []byte, boundary string) Mimes {
mi := make(Mimes, 0, 10)
str := string(body)
delim := "--" + boundary
// Skip the preamble up to the first boundary line.
start := strings.Index(str, delim)
if start < 0 {
return mi
}
str = str[start:]
for {
// Each boundary line ends the previous part; "--" ends the last one.
str = str[len(delim):]
if strings.HasPrefix(str, "--") {
return mi
}
nl := strings.IndexByte(str, '\n')
if nl < 0 {
return mi
}
str = str[nl+1:]
// The content of the part ends at the line break before the next boundary.
end := strings.Index(str, "\n"+delim)
if end < 0 {
return mi
}
part := strings.TrimSuffix(str[:end], "\r")
str = str[end+1:]
mi = append(mi, readPart(part))
}
}
// readPart returns the data of one part of a MIME multipart body:
// its header fields, an empty line, then its content.
func readPart(part string) *Data {
d := &Data{}
cte := ""
for {
// Each header line until the empty line.
nl := strings.IndexByte(part, '\n')
if nl < 0 {
nl = len(part) - 1
}
line := strings.TrimRight(part[:nl+1], "\r\n")
part = part[nl+1:]
if line == "" {
break
}
key, value, _ := strings.Cut(line, ":")
value = strings.TrimSpace(value)
switch {
case strings.EqualFold(key, ContentType):
d.Type = value
case strings.EqualFold(key, ContentTransferEncoding):
cte = value
}
}
// The content, base64 decoded as by FromMultipart.
b := []byte(part)
if cte == "base64" {
eb := make([]byte, base64.StdEncoding.DecodedLen(len(b)))
n, _ := base64.StdEncoding.Decode(eb, b)
b = eb[:n]
}
d.Data = b
return d
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package fileinfo
import (
"fmt"
"mime"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/h2non/filetype"
)
// MimeNoChar returns the mime string without any charset
// encoding information, or anything else after a ;
// in lowercase, as mime types are case-insensitive,
// and they are lowercase in [AvailableMimes].
func MimeNoChar(mime string) string {
if sidx := strings.Index(mime, ";"); sidx > 0 {
mime = strings.TrimSpace(mime[:sidx])
}
return strings.ToLower(mime)
}
// MimeTop returns the top-level main type category from mime type
// i.e., the thing before the / -- returns empty if no /
func MimeTop(mime string) string {
if sidx := strings.Index(mime, "/"); sidx > 0 {
return mime[:sidx]
}
return ""
}
// MimeSub returns the sub-level subtype category from mime type
// i.e., the thing after the / -- returns empty if no /
// also trims off any charset encoding stuff
func MimeSub(mime string) string {
mime = MimeNoChar(mime)
if sidx := strings.Index(mime, "/"); sidx > 0 {
return mime[sidx+1:]
}
return ""
}
// MimeFromFile gets mime type from file, using Gabriel Vasile's mimetype
// package, mime.TypeByExtension, the chroma syntax highlighter,
// CustomExtMimeMap, and finally FileExtMimeMap. Use the mimetype package's
// extension mechanism to add further content-based matchers as needed, and
// set CustomExtMimeMap to your own map or call AddCustomExtMime for
// extension-based ones.
func MimeFromFile(fname string) (mtype, ext string, err error) {
ext = strings.ToLower(filepath.Ext(fname))
if mtyp, has := ExtMimeMap[ext]; has { // use our map first: very fast!
return mtyp, ext, nil
}
_, fn := filepath.Split(fname)
var fc, lc byte
if len(fn) > 0 {
fc = fn[0]
lc = fn[len(fn)-1]
}
if fc == '~' || fc == '%' || fc == '#' || lc == '~' || lc == '%' || lc == '#' {
return MimeString(Trash), ext, nil
}
mtypt, err := filetype.MatchFile(fname) // h2non next -- has good coverage (the path, not just the name)
ptyp := ""
isplain := false
if err == nil && mtypt.MIME.Value != "" { // (an unknown type has no mime type)
mtyp := mtypt.MIME.Value
ext = mtypt.Extension
if strings.HasPrefix(mtyp, "text/plain") {
isplain = true
ptyp = mtyp
} else {
return mtyp, ext, nil
}
}
mtyp := mime.TypeByExtension(ext)
if mtyp != "" {
return mtyp, ext, nil
}
// TODO(kai/binsize): figure out how to do this without dragging in chroma dependency
// lexer := lexers.Match(fn) // todo: could get start of file and pass to
// // Analyze, but might be too slow..
// if lexer != nil {
// config := lexer.Config()
// if len(config.MimeTypes) > 0 {
// mtyp = config.MimeTypes[0]
// return mtyp, ext, nil
// }
// mtyp := "application/" + strings.ToLower(config.Name)
// return mtyp, ext, nil
// }
if isplain {
return ptyp, ext, nil
}
if strings.ToLower(fn) == "makefile" {
return MimeString(Makefile), ext, nil
}
return "", ext, fmt.Errorf("fileinfo.MimeFromFile could not find mime type for ext: %v file: %v", ext, fn)
}
var generatedRe = regexp.MustCompile(`^// Code generated .* DO NOT EDIT`)
func IsGeneratedFile(fname string) bool {
file, err := os.Open(fname)
if err != nil {
return false
}
head := make([]byte, 2048)
file.Read(head)
return generatedRe.Match(head)
}
// todo: use this to check against mime types!
// MimeToKindMapInit makes sure the MimeToKindMap is initialized from
// InitMimeToKindMap plus chroma lexer types.
// func MimeToKindMapInit() {
// if MimeToKindMap != nil {
// return
// }
// MimeToKindMap = InitMimeToKindMap
// for _, l := range lexers.Registry.Lexers {
// config := l.Config()
// nm := strings.ToLower(config.Name)
// if len(config.MimeTypes) > 0 {
// mtyp := config.MimeTypes[0]
// MimeToKindMap[mtyp] = nm
// } else {
// MimeToKindMap["application/"+nm] = nm
// }
// }
// }
//////////////////////////////////////////////////////////////////////////////
// Mime types
// ExtMimeMap is the map from extension to mime type, built from AvailMimes
var ExtMimeMap = map[string]string{}
// MimeType contains all the information associated with a given mime type
type MimeType struct {
// mimetype string: type/subtype
Mime string
// file extensions associated with this file type
Exts []string
// category of file
Cat Categories
// if known, the name of the known file type, else NoSupporUnknown
Known Known
}
// CustomMimes can be set by other apps to contain custom mime types that
// go beyond what is in the standard ones, and can also redefine and
// override the standard one
var CustomMimes []MimeType
// AvailableMimes is the full list (as a map from mimetype) of available defined mime types
// built from StdMimes (compiled in) and then CustomMimes can override
var AvailableMimes map[string]MimeType
// MimeKnown returns the known type for given mime key,
// or Unknown if not found or not a known file type
func MimeKnown(mime string) Known {
mt, has := AvailableMimes[MimeNoChar(mime)]
if !has {
return Unknown
}
return mt.Known
}
// ExtKnown returns the known type for given file extension,
// or Unknown if not found or not a known file type
func ExtKnown(ext string) Known {
mime, has := ExtMimeMap[ext]
if !has {
return Unknown
}
mt, has := AvailableMimes[mime]
if !has {
return Unknown
}
return mt.Known
}
// KnownFromFile returns the known type for given file,
// or Unknown if not found or not a known file type
func KnownFromFile(fname string) Known {
mtyp, _, err := MimeFromFile(fname)
if err != nil {
return Unknown
}
return MimeKnown(mtyp)
}
// MimeFromKnown returns MimeType info for given known file type.
func MimeFromKnown(ftyp Known) MimeType {
for _, mt := range AvailableMimes {
if mt.Known == ftyp {
return mt
}
}
return MimeType{}
}
// MergeAvailableMimes merges the StdMimes and CustomMimes into AvailMimes
// if CustomMimes is updated, then this should be called -- initially
// it just has StdMimes.
// It also builds the ExtMimeMap to map from extension to mime type
// and KnownMimes map of known file types onto their full
// mime type entry
func MergeAvailableMimes() {
AvailableMimes = make(map[string]MimeType, len(StandardMimes)+len(CustomMimes))
for _, mt := range StandardMimes {
AvailableMimes[strings.ToLower(mt.Mime)] = mt
}
for _, mt := range CustomMimes {
AvailableMimes[strings.ToLower(mt.Mime)] = mt // overwrite automatically
}
ExtMimeMap = make(map[string]string) // start over
KnownMimes = make(map[Known]MimeType)
for _, mt := range AvailableMimes {
if len(mt.Exts) > 0 { // first pass add only ext guys to support
for _, ex := range mt.Exts {
if ex[0] != '.' {
fmt.Printf("fileinfo.MergeAvailMimes: ext: %v does not start with a . in type: %v\n", ex, mt.Mime)
}
if pmt, has := ExtMimeMap[ex]; has {
fmt.Printf("fileinfo.MergeAvailMimes: non-unique ext: %v assigned to mime type: %v AND %v\n", ex, pmt, mt.Mime)
} else {
ExtMimeMap[ex] = mt.Mime
}
}
if mt.Known != Unknown {
if hsp, has := KnownMimes[mt.Known]; has {
fmt.Printf("fileinfo.MergeAvailMimes: more-than-one mimetype has extensions for same known file type: %v -- one: %v other %v\n", mt.Known, hsp.Mime, mt.Mime)
} else {
KnownMimes[mt.Known] = mt
}
}
}
}
// second pass to get any known guys that don't have exts
for _, mt := range AvailableMimes {
if mt.Known != Unknown {
if _, has := KnownMimes[mt.Known]; !has {
KnownMimes[mt.Known] = mt
}
}
}
}
func init() {
MergeAvailableMimes()
}
// http://www.iana.org/assignments/media-types/media-types.xhtml
// https://github.com/mirage/ocaml-magic-mime/blob/master/x-mime.types
// https://www.apt-browse.org/browse/debian/stretch/main/all/mime-support/3.60/file/etc/mime.types
// https://developer.apple.com/library/archive/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types
// StandardMimes is the full list of standard mime types compiled into our code
// various other maps etc are constructed from it.
// When there are multiple types associated with the same real type, pick one
// to be the canonical one and give it, and *only* it, the extensions!
var StandardMimes = []MimeType{
// Folder
{"text/directory", nil, Folder, Unknown},
// Archive
{"multipart/mixed", nil, Archive, Multipart},
{"application/tar", []string{".tar", ".tar.gz", ".tgz", ".taz", ".taZ", ".tar.bz2", ".tz2", ".tbz2", ".tbz", ".tar.lz", ".tar.lzma", ".tlz", ".tar.lzop", ".tar.xz"}, Archive, Tar},
{"application/x-gtar", nil, Archive, Tar},
{"application/x-gtar-compressed", nil, Archive, Tar},
{"application/x-tar", nil, Archive, Tar},
{"application/zip", []string{".zip"}, Archive, Zip},
{"application/gzip", []string{".gz"}, Archive, GZip},
{"application/x-7z-compressed", []string{".7z"}, Archive, SevenZ},
{"application/x-xz", []string{".xz"}, Archive, XZ},
{"application/x-bzip", []string{".bz", ".bz2"}, Archive, BZip},
{"application/x-bzip2", nil, Archive, BZip},
{"application/x-apple-diskimage", []string{".dmg"}, Archive, DMG},
{"application/x-shar", []string{".shar"}, Archive, Shar},
{"application/x-bittorrent", []string{".torrent"}, Archive, Unknown},
{"application/rar", []string{".rar"}, Archive, Unknown},
{"application/x-stuffit", []string{".sit", ".sitx"}, Archive, Unknown},
{"application/vnd.android.package-archive", []string{".apk"}, Archive, Unknown},
{"application/vnd.debian.binary-package", []string{".deb", ".ddeb", ".udeb"}, Archive, Unknown},
{"application/x-debian-package", nil, Archive, Unknown},
{"application/x-redhat-package-manager", []string{".rpm"}, Archive, Unknown},
{"text/x-rpm-spec", nil, Archive, Unknown},
// Backup
{"application/x-trash", []string{".bak", ".old", ".sik"}, Backup, Trash}, // also "~", "%", "#",
// Code -- use text/ as main instead of application as there are more text
{"text/x-ada", []string{".adb", ".ads", ".ada"}, Code, Ada},
{"text/x-asp", []string{".aspx", ".asax", ".ascx", ".ashx", ".asmx", ".axd"}, Code, Unknown},
{"text/x-sh", []string{".bash", ".sh"}, Code, Bash},
{"application/x-sh", nil, Code, Bash},
{"text/x-csrc", []string{".c", ".C", ".c++", ".cpp", ".cxx", ".cc", ".h", ".h++", ".hpp", ".hxx", ".hh", ".mm"}, Code, C}, // this is apparently the main one now
{"text/x-glslsrc", []string{".glsl", ".vert", ".frag", ".geom", ".tesc", ".tese", ".comp", ".gsl"}, Code, GLSL},
{"text/x-hlsl", []string{".hlsl", ".hlsli", ".fx", ".fxh"}, Code, HLSL},
{"text/x-metal", []string{".metal"}, Code, Metal},
{"text/x-spirv", []string{".spvasm"}, Code, SPIRV},
{"application/x-spirv", []string{".spv"}, Bin, Unknown}, // the binary of SPIR-V
{"text/wgsl", []string{".wgsl"}, Code, WGSL},
{"text/x-chdr", nil, Code, C},
{"text/x-c", nil, Code, C},
{"text/x-c++hdr", nil, Code, C},
{"text/x-c++src", nil, Code, C},
{"text/x-chdr", nil, Code, C},
{"text/x-cpp", nil, Code, C},
{"text/x-csh", []string{".csh"}, Code, Csh},
{"application/x-csh", nil, Code, Csh},
{"text/x-csharp", []string{".cs"}, Code, CSharp},
{"text/x-dsrc", []string{".d"}, Code, D},
{"text/x-diff", []string{".diff", ".patch"}, Code, Diff},
{"text/x-eiffel", []string{".e"}, Code, Eiffel},
{"text/x-erlang", []string{".erl", ".hrl", ".escript"}, Code, Erlang}, // note: ".es" conflicts with ecmascript
{"text/x-forth", []string{".frt"}, Code, Forth}, // note: ".fs" conflicts with fsharp
{"text/x-fortran", []string{".f", ".F"}, Code, Fortran},
{"text/x-fsharp", []string{".fs", ".fsi"}, Code, FSharp},
{"text/x-gosrc", []string{".go", ".mod", ".work", ".goal"}, Code, Go},
{"text/x-haskell", []string{".hs", ".lhs"}, Code, Haskell},
{"text/x-literate-haskell", nil, Code, Haskell}, // todo: not sure if same or not
{"text/x-java", []string{".java"}, Code, Java},
{"application/java-archive", []string{".jar"}, Archive, Unknown},
{"application/javascript", []string{".js", ".es"}, Code, JavaScript},
{"application/ecmascript", nil, Code, JavaScript},
{"application/typescript", []string{".ts"}, Code, TypeScript},
{"text/x-common-lisp", []string{".lisp", ".cl", ".el"}, Code, Lisp},
{"text/elisp", nil, Code, Lisp},
{"text/x-elisp", nil, Code, Lisp},
{"application/emacs-lisp", nil, Code, Lisp},
{"text/x-lua", []string{".lua", ".wlua"}, Code, Lua},
{"text/x-makefile", nil, Code, Makefile},
{"text/x-autoconf", nil, Code, Makefile},
{"text/x-moc", []string{".moc"}, Code, Unknown},
{"application/mathematica", []string{".nb", ".nbp"}, Code, Mathematica},
{"text/x-matlab", []string{".m"}, Code, Matlab},
{"text/matlab", nil, Code, Matlab},
{"text/octave", nil, Code, Matlab},
{"text/scilab", []string{".sci", ".sce", ".tst"}, Code, Unknown},
{"text/x-modelica", []string{".mo"}, Code, Unknown},
{"text/x-nemerle", []string{".n"}, Code, Unknown},
{"text/x-objcsrc", nil, Code, ObjC}, // doesn't have chroma support -- use C instead
{"text/x-objective-j", nil, Code, Unknown},
{"text/x-ocaml", []string{".ml", ".mli", ".mll", ".mly"}, Code, OCaml},
{"text/x-pascal", []string{".p", ".pas"}, Code, Pascal},
{"text/x-perl", []string{".pl", ".pm"}, Code, Perl},
{"text/x-php", []string{".php", ".php3", ".php4", ".php5", ".inc"}, Code, PHP},
{"text/x-prolog", []string{".ecl", ".prolog", ".pro"}, Code, Prolog}, // note: ".pl" conflicts
{"text/x-python", []string{".py", ".pyw"}, Code, Python},
{"application/x-python-code", []string{".pyc", ".pyo"}, Bin, Unknown},
{"text/x-rust", []string{".rs"}, Code, Rust},
{"text/rust", nil, Code, Rust},
{"text/x-r", []string{".r", ".S", ".R", ".Rhistory", ".Rprofile", ".Renviron"}, Code, R},
{"text/x-r", nil, Code, R},
{"text/s-plus", nil, Code, R},
{"text/s", nil, Code, R},
{"text/x-r-source", nil, Code, R},
{"text/x-r-history", nil, Code, R},
{"text/x-r-profile", nil, Code, R},
{"text/x-ruby", []string{".rb"}, Code, Ruby},
{"application/x-ruby", nil, Code, Ruby},
{"text/x-scala", []string{".scala"}, Code, Scala},
{"text/x-tcl", []string{".tcl", ".tk"}, Code, Tcl},
{"application/x-tcl", nil, Code, Tcl},
// Doc
{"text/x-bibtex", []string{".bib"}, Doc, BibTeX},
{"text/x-tex", []string{".tex", ".ltx", ".sty", ".cls", ".latex"}, Doc, TeX},
{"application/x-latex", nil, Doc, TeX},
{"application/x-texinfo", []string{".texinfo", ".texi"}, Doc, Texinfo},
{"application/x-troff", []string{".t", ".tr", ".roff", ".man", ".me", ".ms"}, Doc, Troff},
{"application/x-troff-man", nil, Doc, Troff},
{"application/x-troff-me", nil, Doc, Troff},
{"application/x-troff-ms", nil, Doc, Troff},
{"text/html", []string{".html", ".htm", ".shtml", ".xhtml", ".xht"}, Doc, HTML},
{"application/xhtml+xml", nil, Doc, HTML},
{"text/mathml", []string{".mml"}, Doc, Unknown},
{"text/css", []string{".css"}, Doc, CSS},
{"text/markdown", []string{".md", ".markdown"}, Doc, Markdown},
{"text/x-markdown", nil, Doc, Markdown},
{"application/rtf", []string{".rtf"}, Doc, RTF},
{"text/richtext", []string{".rtx"}, Doc, Unknown},
{"application/mbox", []string{".mbox"}, Doc, Unknown},
{"application/x-rss+xml", []string{".rss"}, Doc, Unknown},
{"application/msword", []string{".doc", ".dot", ".docx", ".dotx"}, Doc, MSWord},
{"application/vnd.ms-word", nil, Doc, MSWord},
{"application/vnd.openxmlformats-officedocument.wordprocessingml.document", nil, Doc, MSWord},
{"application/vnd.openxmlformats-officedocument.wordprocessingml.template", nil, Doc, MSWord},
{"application/vnd.oasis.opendocument.text", []string{".odt", ".odm", ".ott", ".oth", ".sxw", ".sxg", ".stw", ".sxm"}, Doc, OpenText},
{"application/vnd.oasis.opendocument.text-master", nil, Doc, OpenText},
{"application/vnd.oasis.opendocument.text-template", nil, Doc, OpenText},
{"application/vnd.oasis.opendocument.text-web", nil, Doc, OpenText},
{"application/vnd.sun.xml.writer", nil, Doc, OpenText},
{"application/vnd.sun.xml.writer.global", nil, Doc, OpenText},
{"application/vnd.sun.xml.writer.template", nil, Doc, OpenText},
{"application/vnd.sun.xml.math", nil, Doc, OpenText},
{"application/vnd.oasis.opendocument.presentation", []string{".odp", ".otp", ".sxi", ".sti"}, Doc, OpenPres},
{"application/vnd.oasis.opendocument.presentation-template", nil, Doc, OpenPres},
{"application/vnd.sun.xml.impress", nil, Doc, OpenPres},
{"application/vnd.sun.xml.impress.template", nil, Doc, OpenPres},
{"application/vnd.ms-powerpoint", []string{".ppt", ".pps", ".pptx", ".sldx", ".ppsx", ".potx"}, Doc, MSPowerPoint},
{"application/vnd.openxmlformats-officedocument.presentationml.presentation", nil, Doc, MSPowerPoint},
{"application/vnd.openxmlformats-officedocument.presentationml.slide", nil, Doc, MSPowerPoint},
{"application/vnd.openxmlformats-officedocument.presentationml.slideshow", nil, Doc, MSPowerPoint},
{"application/vnd.openxmlformats-officedocument.presentationml.template", nil, Doc, MSPowerPoint},
{"application/ms-tnef", nil, Doc, Unknown},
{"application/vnd.ms-tnef", nil, Doc, Unknown},
{"application/onenote", []string{".one", ".onetoc2", ".onetmp", ".onepkg"}, Doc, Unknown},
{"application/pgp-encrypted", []string{".pgp"}, Doc, Unknown},
{"application/pgp-keys", []string{".key"}, Doc, Unknown},
{"application/pgp-signature", []string{".sig"}, Doc, Unknown},
{"application/vnd.amazon.ebook", []string{".azw"}, Doc, EBook},
{"application/epub+zip", []string{".epub"}, Doc, EPUB},
// Sheet
{"application/vnd.ms-excel", []string{".xls", ".xlb", ".xlt", ".xlsx", ".xltx"}, Sheet, MSExcel},
{"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", nil, Sheet, MSExcel},
{"application/vnd.openxmlformats-officedocument.spreadsheetml.template", nil, Sheet, MSExcel},
{"application/vnd.oasis.opendocument.spreadsheet", []string{".ods", ".ots", ".sxc", ".stc", ".odf"}, Sheet, OpenSheet},
{"application/vnd.oasis.opendocument.spreadsheet-template", nil, Sheet, OpenSheet},
{"application/vnd.oasis.opendocument.formula", nil, Sheet, OpenSheet}, // todo: could be separate
{"application/vnd.sun.xml.calc", nil, Sheet, OpenSheet},
{"application/vnd.sun.xml.calc.template", nil, Sheet, OpenSheet},
// Data
{"text/csv", []string{".csv"}, Data, CSV},
{"application/json", []string{".json"}, Data, JSON},
{"application/xml", []string{".xml", ".xsd"}, Data, XML},
{"text/xml", nil, Data, XML},
{"text/x-protobuf", []string{".proto"}, Data, Protobuf},
{"text/x-ini", []string{".ini", ".cfg", ".inf"}, Data, INI},
{"text/x-ini-file", nil, Data, INI},
{"text/uri-list", nil, Data, URI},
{"application/x-color", nil, Data, Color},
{"text/toml", []string{".toml"}, Data, TOML},
{"application/toml", nil, Data, TOML},
{"application/yaml", []string{".yaml"}, Data, YAML},
{"application/rdf+xml", []string{".rdf"}, Data, Unknown},
{"application/msaccess", []string{".mdb"}, Data, Unknown},
{"application/vnd.oasis.opendocument.database", []string{".odb"}, Data, Unknown},
{"text/tab-separated-values", []string{".tsv"}, Data, TSV},
{"application/vnd.google-earth.kml+xml", []string{".kml"}, Data, Unknown},
{"application/vnd.google-earth.kmz", []string{".kmz"}, Data, Unknown},
{"application/vnd.google-earth.kmz", nil, Data, Unknown},
{"application/x-sql", []string{".sql"}, Data, Unknown},
// Text
{"text/plain", []string{".asc", ".txt", ".text", ".pot", ".brf", ".srt"}, Text, PlainText},
{"text/cache-manifest", []string{".appcache"}, Text, Unknown},
{"text/calendar", []string{".ics", ".icz"}, Text, ICal},
{"text/x-vcalendar", []string{".vcs"}, Text, VCal},
{"text/vcard", []string{".vcf", ".vcard"}, Text, VCard},
// Image
{"application/pdf", []string{".pdf"}, Image, PDF},
{"application/postscript", []string{".ps", ".ai", ".eps", ".epsi", ".epsf", ".eps2", ".eps3"}, Image, PostScript},
{"application/vnd.oasis.opendocument.graphics", []string{".odc", ".odg", ".otg", ".odi", ".sxd", ".std"}, Image, Unknown},
{"application/vnd.oasis.opendocument.chart", nil, Image, Unknown},
{"application/vnd.oasis.opendocument.graphics-template", nil, Image, Unknown},
{"application/vnd.oasis.opendocument.image", nil, Image, Unknown},
{"application/vnd.sun.xml.draw", nil, Image, Unknown},
{"application/vnd.sun.xml.draw.template", nil, Image, Unknown},
{"application/x-xfig", []string{".fig"}, Image, Unknown},
{"application/x-xcf", []string{".xcf"}, Image, GIMP},
{"text/vnd.graphviz", []string{".gv"}, Image, Graphviz},
{"image/gif", []string{".gif"}, Image, GIF},
{"image/ief", []string{".ief"}, Image, Unknown},
{"image/jp2", []string{".jp2", ".jpg2"}, Image, Unknown},
{"image/jpeg", []string{".jpeg", ".jpg", ".jpe"}, Image, JPEG},
{"image/jpm", []string{".jpm"}, Image, Unknown},
{"image/jpx", []string{".jpx", ".jpf"}, Image, Unknown},
{"image/pcx", []string{".pcx"}, Image, Unknown},
{"image/png", []string{".png"}, Image, PNG},
{"image/heic", []string{".heic"}, Image, HEIC},
{"image/heif", []string{".heif"}, Image, HEIF},
{"image/svg+xml", []string{".svg", ".svgz"}, Image, SVG},
{"image/tiff", []string{".tiff", ".tif"}, Image, TIFF},
{"image/vnd.djvu", []string{".djvu", ".djv"}, Image, Unknown},
{"image/vnd.microsoft.icon", []string{".ico"}, Image, Unknown},
{"image/vnd.wap.wbmp", []string{".wbmp"}, Image, Unknown},
{"image/x-canon-cr2", []string{".cr2"}, Image, Unknown},
{"image/x-canon-crw", []string{".crw"}, Image, Unknown},
{"image/x-cmu-raster", []string{".ras"}, Image, Unknown},
{"image/x-coreldraw", []string{".cdr", ".pat", ".cdt", ".cpt"}, Image, Unknown},
{"image/x-coreldrawpattern", nil, Image, Unknown},
{"image/x-coreldrawtemplate", nil, Image, Unknown},
{"image/x-corelphotopaint", nil, Image, Unknown},
{"image/x-epson-erf", []string{".erf"}, Image, Unknown},
{"image/x-jg", []string{".art"}, Image, Unknown},
{"image/x-jng", []string{".jng"}, Image, Unknown},
{"image/x-ms-bmp", []string{".bmp"}, Image, BMP},
{"image/x-nikon-nef", []string{".nef"}, Image, Unknown},
{"image/x-olympus-orf", []string{".orf"}, Image, Unknown},
{"image/x-photoshop", []string{".psd"}, Image, Unknown},
{"image/x-portable-anymap", []string{".pnm"}, Image, PNM},
{"image/x-portable-bitmap", []string{".pbm"}, Image, PBM},
{"image/x-portable-graymap", []string{".pgm"}, Image, PGM},
{"image/x-portable-pixmap", []string{".ppm"}, Image, PPM},
{"image/x-rgb", []string{".rgb"}, Image, Unknown},
{"image/x-xbitmap", []string{".xbm"}, Image, XBM},
{"image/x-xpixmap", []string{".xpm"}, Image, XPM},
{"image/x-xwindowdump", []string{".xwd"}, Image, Unknown},
// Model
{"model/iges", []string{".igs", ".iges"}, Model, Unknown},
{"model/mesh", []string{".msh", ".mesh", ".silo"}, Model, Unknown},
{"model/vrml", []string{".wrl", ".vrml", ".vrm"}, Model, VRML},
{"x-world/x-vrml", nil, Model, VRML},
{"model/x3d+xml", []string{".x3dv", ".x3d", ".x3db"}, Model, X3D},
{"model/x3d+vrml", nil, Model, X3D},
{"model/x3d+binary", nil, Model, X3D},
{"application/object", []string{".obj", ".mtl"}, Model, OBJ},
// Audio
{"audio/aac", []string{".aac"}, Audio, AAC},
{"audio/flac", []string{".flac"}, Audio, FLAC},
{"audio/mpeg", []string{".mpga", ".mpega", ".mp2", ".mp3", ".m4a"}, Audio, MP3},
{"audio/mpegurl", []string{".m3u"}, Audio, Unknown},
{"audio/x-mpegurl", nil, Audio, Unknown},
{"audio/ogg", []string{".oga", ".ogg", ".opus", ".spx"}, Audio, Ogg},
{"audio/amr", []string{".amr"}, Audio, Unknown},
{"audio/amr-wb", []string{".awb"}, Audio, Unknown},
{"audio/annodex", []string{".axa"}, Audio, Unknown},
{"audio/basic", []string{".au", ".snd"}, Audio, Unknown},
{"audio/csound", []string{".csd", ".orc", ".sco"}, Audio, Unknown},
{"audio/midi", []string{".mid", ".midi", ".kar"}, Audio, MIDI},
{"audio/prs.sid", []string{".sid"}, Audio, Unknown},
{"audio/x-aiff", []string{".aif", ".aiff", ".aifc"}, Audio, Unknown},
{"audio/x-gsm", []string{".gsm"}, Audio, Unknown},
{"audio/x-ms-wma", []string{".wma"}, Audio, Unknown},
{"audio/x-ms-wax", []string{".wax"}, Audio, Unknown},
{"audio/x-pn-realaudio", []string{".ra", ".rm", ".ram"}, Audio, Unknown},
{"audio/x-realaudio", nil, Audio, Unknown},
{"audio/x-scpls", []string{".pls"}, Audio, Unknown},
{"audio/x-sd2", []string{".sd2"}, Audio, Unknown},
{"audio/x-wav", []string{".wav"}, Audio, WAV},
// Video
{"video/3gpp", []string{".3gp"}, Video, Unknown},
{"video/annodex", []string{".axv"}, Video, Unknown},
{"video/dl", []string{".dl"}, Video, Unknown},
{"video/dv", []string{".dif", ".dv"}, Video, Unknown},
{"video/fli", []string{".fli"}, Video, Unknown},
{"video/gl", []string{".gl"}, Video, Unknown},
{"video/h264", nil, Video, Unknown},
{"video/mpeg", []string{".mpeg", ".mpg", ".mpe"}, Video, MPEG},
{"video/mp2t", nil, Video, Unknown},
{"video/mp4", []string{".mp4"}, Video, MP4},
{"video/quicktime", []string{".qt", ".mov"}, Video, MOV},
{"video/ogg", []string{".ogv"}, Video, OGV},
{"video/webm", []string{".webm"}, Video, Unknown},
{"video/vnd.mpegurl", []string{".mxu"}, Video, Unknown},
{"video/x-flv", []string{".flv"}, Video, Unknown},
{"video/x-la-asf", []string{".lsf", ".lsx"}, Video, Unknown},
{"video/x-mng", []string{".mng"}, Video, Unknown},
{"video/x-ms-asf", []string{".asf", ".asx"}, Video, Unknown},
{"video/x-ms-wm", []string{".wm"}, Video, Unknown},
{"video/x-ms-wmv", []string{".wmv"}, Video, WMV},
{"video/x-ms-wmx", []string{".wmx"}, Video, Unknown},
{"video/x-ms-wvx", []string{".wvx"}, Video, Unknown},
{"video/x-msvideo", []string{".avi"}, Video, AVI},
{"video/x-sgi-movie", []string{".movie"}, Video, Unknown},
{"video/x-matroska", []string{".mpv", ".mkv"}, Video, Unknown},
{"application/x-shockwave-flash", []string{".swf"}, Video, Unknown},
// Font
{"font/ttf", []string{".otf", ".ttf", ".ttc"}, Font, TrueType},
{"font/otf", nil, Font, TrueType},
{"application/font-sfnt", nil, Font, TrueType},
{"application/x-font-ttf", nil, Font, TrueType},
{"application/x-font", []string{".pfa", ".pfb", ".gsf", ".pcf", ".pcf.Z"}, Font, Unknown},
{"application/x-font-pcf", nil, Font, Unknown},
{"application/vnd.ms-fontobject", []string{".eot"}, Font, Unknown},
{"font/woff", []string{".woff", ".woff2"}, Font, WebOpenFont},
{"font/woff2", nil, Font, WebOpenFont},
{"application/font-woff", nil, Font, WebOpenFont},
// Exe
{"application/x-executable", nil, Exe, Unknown},
{"application/x-msdos-program", []string{".com", ".exe", ".bat", ".dll"}, Exe, Unknown},
// Binary
{"application/octet-stream", []string{".bin"}, Bin, Unknown},
{"application/x-object", []string{".o"}, Bin, Unknown},
{"text/x-libtool", nil, Bin, Unknown},
}
// below are entries from official /etc/mime.types that we don't recognize
// or consider to be old / obsolete / not relevant -- please file an issue
// or a pull-request to add to main list or add yourself in your own app
// application/activemessage
// application/andrew-insetez
// application/annodexanx
// application/applefile
// application/atom+xmlatom
// application/atomcat+xmlatomcat
// application/atomicmail
// application/atomserv+xmlatomsrv
// application/batch-SMTP
// application/bbolinlin
// application/beep+xml
// application/cals-1840
// application/commonground
// application/cu-seemecu
// application/cybercash
// application/davmount+xmldavmount
// application/dca-rft
// application/dec-dx
// application/dicomdcm
// application/docbook+xml
// application/dsptypetsp
// application/dvcs
// application/edi-consent
// application/edi-x12
// application/edifact
// application/eshop
// application/font-tdpfrpfr
// application/futuresplashspl
// application/ghostview
// application/htahta
// application/http
// application/hyperstudio
// application/iges
// application/index
// application/index.cmd
// application/index.obj
// application/index.response
// application/index.vnd
// application/iotp
// application/ipp
// application/isup
// application/java-serialized-objectser
// application/java-vmclass
// application/m3gm3g
// application/mac-binhex40hqx
// application/mac-compactprocpt
// application/macwriteii
// application/marc
// application/mxfmxf
// application/news-message-id
// application/news-transmission
// application/ocsp-request
// application/ocsp-response
// application/octet-streambin deploy msu msp
// application/odaoda
// application/oebps-package+xmlopf
// application/oggogx
// application/parityfec
// application/pics-rulesprf
// application/pkcs10
// application/pkcs7-mime
// application/pkcs7-signature
// application/pkix-cert
// application/pkix-crl
// application/pkixcmp
// application/prs.alvestrand.titrax-sheet
// application/prs.cww
// application/prs.nprend
// application/qsig
// application/remote-printing
// application/riscos
// application/sdp
// application/set-payment
// application/set-payment-initiation
// application/set-registration
// application/set-registration-initiation
// application/sgml
// application/sgml-open-catalog
// application/sieve
// application/slastl
// application/slate
// application/smil+xmlsmi smil
// application/timestamp-query
// application/timestamp-reply
// application/vemmi
// application/whoispp-query
// application/whoispp-response
// application/wita
// application/x400-bp
// application/xml-dtd
// application/xml-external-parsed-entity
// application/xslt+xmlxsl xslt
// application/xspf+xmlxspf
// application/vnd.3M.Post-it-Notes
// application/vnd.accpac.simply.aso
// application/vnd.accpac.simply.imp
// application/vnd.acucobol
// application/vnd.aether.imp
// application/vnd.anser-web-certificate-issue-initiation
// application/vnd.anser-web-funds-transfer-initiation
// application/vnd.audiograph
// application/vnd.bmi
// application/vnd.businessobjects
// application/vnd.canon-cpdl
// application/vnd.canon-lips
// application/vnd.cinderellacdy
// application/vnd.claymore
// application/vnd.commerce-battelle
// application/vnd.commonspace
// application/vnd.comsocaller
// application/vnd.contact.cmsg
// application/vnd.cosmocaller
// application/vnd.ctc-posml
// application/vnd.cups-postscript
// application/vnd.cups-raster
// application/vnd.cups-raw
// application/vnd.cybank
// application/vnd.dna
// application/vnd.dpgraph
// application/vnd.dxr
// application/vnd.ecdis-update
// application/vnd.ecowin.chart
// application/vnd.ecowin.filerequest
// application/vnd.ecowin.fileupdate
// application/vnd.ecowin.series
// application/vnd.ecowin.seriesrequest
// application/vnd.ecowin.seriesupdate
// application/vnd.enliven
// application/vnd.epson.esf
// application/vnd.epson.msf
// application/vnd.epson.quickanime
// application/vnd.epson.salt
// application/vnd.epson.ssf
// application/vnd.ericsson.quickcall
// application/vnd.eudora.data
// application/vnd.fdf
// application/vnd.ffsns
// application/vnd.flographit
// application/vnd.font-fontforge-sfdsfd
// application/vnd.framemaker
// application/vnd.fsc.weblaunch
// application/vnd.fujitsu.oasys
// application/vnd.fujitsu.oasys2
// application/vnd.fujitsu.oasys3
// application/vnd.fujitsu.oasysgp
// application/vnd.fujitsu.oasysprs
// application/vnd.fujixerox.ddd
// application/vnd.fujixerox.docuworks
// application/vnd.fujixerox.docuworks.binder
// application/vnd.fut-misnet
// application/vnd.grafeq
// application/vnd.groove-account
// application/vnd.groove-identity-message
// application/vnd.groove-injector
// application/vnd.groove-tool-message
// application/vnd.groove-tool-template
// application/vnd.groove-vcard
// application/vnd.hhe.lesson-player
// application/vnd.hp-HPGL
// application/vnd.hp-PCL
// application/vnd.hp-PCLXL
// application/vnd.hp-hpid
// application/vnd.hp-hps
// application/vnd.httphone
// application/vnd.hzn-3d-crossword
// application/vnd.ibm.MiniPay
// application/vnd.ibm.afplinedata
// application/vnd.ibm.modcap
// application/vnd.informix-visionary
// application/vnd.intercon.formnet
// application/vnd.intertrust.digibox
// application/vnd.intertrust.nncp
// application/vnd.intu.qbo
// application/vnd.intu.qfx
// application/vnd.irepository.package+xml
// application/vnd.is-xpr
// application/vnd.japannet-directory-service
// application/vnd.japannet-jpnstore-wakeup
// application/vnd.japannet-payment-wakeup
// application/vnd.japannet-registration
// application/vnd.japannet-registration-wakeup
// application/vnd.japannet-setstore-wakeup
// application/vnd.japannet-verification
// application/vnd.japannet-verification-wakeup
// application/vnd.koan
// application/vnd.lotus-1-2-3
// application/vnd.lotus-approach
// application/vnd.lotus-freelance
// application/vnd.lotus-notes
// application/vnd.lotus-organizer
// application/vnd.lotus-screencam
// application/vnd.lotus-wordpro
// application/vnd.mcd
// application/vnd.mediastation.cdkey
// application/vnd.meridian-slingshot
// application/vnd.mif
// application/vnd.minisoft-hp3000-save
// application/vnd.mitsubishi.misty-guard.trustweb
// application/vnd.mobius.daf
// application/vnd.mobius.dis
// application/vnd.mobius.msl
// application/vnd.mobius.plc
// application/vnd.mobius.txf
// application/vnd.motorola.flexsuite
// application/vnd.motorola.flexsuite.adsi
// application/vnd.motorola.flexsuite.fis
// application/vnd.motorola.flexsuite.gotap
// application/vnd.motorola.flexsuite.kmr
// application/vnd.motorola.flexsuite.ttc
// application/vnd.motorola.flexsuite.wem
// application/vnd.mozilla.xul+xmlxul
// application/vnd.ms-artgalry
// application/vnd.ms-asf
// application/vnd.ms-excel.addin.macroEnabled.12xlam
// application/vnd.ms-excel.sheet.binary.macroEnabled.12xlsb
// application/vnd.ms-excel.sheet.macroEnabled.12xlsm
// application/vnd.ms-excel.template.macroEnabled.12xltm
// application/vnd.ms-fontobjecteot
// application/vnd.ms-lrm
// application/vnd.ms-officethemethmx
// application/vnd.ms-pki.seccatcat
// #application/vnd.ms-pki.stlstl
// application/vnd.ms-powerpoint.addin.macroEnabled.12ppam
// application/vnd.ms-powerpoint.presentation.macroEnabled.12pptm
// application/vnd.ms-powerpoint.slide.macroEnabled.12sldm
// application/vnd.ms-powerpoint.slideshow.macroEnabled.12ppsm
// application/vnd.ms-powerpoint.template.macroEnabled.12potm
// application/vnd.ms-project
// application/vnd.ms-word.document.macroEnabled.12docm
// application/vnd.ms-word.template.macroEnabled.12dotm
// application/vnd.ms-works
// application/vnd.mseq
// application/vnd.msign
// application/vnd.music-niff
// application/vnd.musician
// application/vnd.netfpx
// application/vnd.noblenet-directory
// application/vnd.noblenet-sealer
// application/vnd.noblenet-web
// application/vnd.novadigm.EDM
// application/vnd.novadigm.EDX
// application/vnd.novadigm.EXT
// application/vnd.osa.netdeploy
// application/vnd.palm
// application/vnd.pg.format
// application/vnd.pg.osasli
// application/vnd.powerbuilder6
// application/vnd.powerbuilder6-s
// application/vnd.powerbuilder7
// application/vnd.powerbuilder7-s
// application/vnd.powerbuilder75
// application/vnd.powerbuilder75-s
// application/vnd.previewsystems.box
// application/vnd.publishare-delta-tree
// application/vnd.pvi.ptid1
// application/vnd.pwg-xhtml-print+xml
// application/vnd.rapid
// application/vnd.rim.codcod
// application/vnd.s3sms
// application/vnd.seemail
// application/vnd.shana.informed.formdata
// application/vnd.shana.informed.formtemplate
// application/vnd.shana.informed.interchange
// application/vnd.shana.informed.package
// application/vnd.smafmmf
// application/vnd.sss-cod
// application/vnd.sss-dtf
// application/vnd.sss-ntf
// application/vnd.stardivision.calcsdc
// application/vnd.stardivision.chartsds
// application/vnd.stardivision.drawsda
// application/vnd.stardivision.impresssdd
// application/vnd.stardivision.mathsdf
// application/vnd.stardivision.writersdw
// application/vnd.stardivision.writer-globalsgl
// application/vnd.street-stream
// application/vnd.svd
// application/vnd.swiftview-ics
// application/vnd.symbian.installsis
// application/vnd.tcpdump.pcapcap pcap
// application/vnd.triscape.mxs
// application/vnd.trueapp
// application/vnd.truedoc
// application/vnd.tve-trigger
// application/vnd.ufdl
// application/vnd.uplanet.alert
// application/vnd.uplanet.alert-wbxml
// application/vnd.uplanet.bearer-choice
// application/vnd.uplanet.bearer-choice-wbxml
// application/vnd.uplanet.cacheop
// application/vnd.uplanet.cacheop-wbxml
// application/vnd.uplanet.channel
// application/vnd.uplanet.channel-wbxml
// application/vnd.uplanet.list
// application/vnd.uplanet.list-wbxml
// application/vnd.uplanet.listcmd
// application/vnd.uplanet.listcmd-wbxml
// application/vnd.uplanet.signal
// application/vnd.vcx
// application/vnd.vectorworks
// application/vnd.vidsoft.vidconference
// application/vnd.visiovsd vst vsw vss
// application/vnd.vividence.scriptfile
// application/vnd.wap.sic
// application/vnd.wap.slc
// application/vnd.wap.wbxmlwbxml
// application/vnd.wap.wmlcwmlc
// application/vnd.wap.wmlscriptcwmlsc
// application/vnd.webturbo
// application/vnd.wordperfectwpd
// application/vnd.wordperfect5.1wp5
// application/vnd.wrq-hp3000-labelled
// application/vnd.wt.stf
// application/vnd.xara
// application/vnd.xfdl
// application/vnd.yellowriver-custom-menu
// application/zlib
// application/x-123wk
// application/x-abiwordabw
// application/x-bcpiobcpio
// application/x-cabcab
// application/x-cbrcbr
// application/x-cbzcbz
// application/x-cdfcdf cda
// application/x-cdlinkvcd
// application/x-chess-pgnpgn
// application/x-comsolmph
// application/x-core
// application/x-cpiocpio
// application/x-directordcr dir dxr
// application/x-dmsdms
// application/x-doomwad
// application/x-dvidvi
// application/x-freemindmm
// application/x-futuresplashspl
// application/x-ganttprojectgan
// application/x-gnumericgnumeric
// application/x-go-sgfsgf
// application/x-graphing-calculatorgcf
// application/x-hdfhdf
// #application/x-httpd-erubyrhtml
// #application/x-httpd-phpphtml pht php
// #application/x-httpd-php-sourcephps
// #application/x-httpd-php3php3
// #application/x-httpd-php3-preprocessedphp3p
// #application/x-httpd-php4php4
// #application/x-httpd-php5php5
// application/x-hwphwp
// application/x-icaica
// application/x-infoinfo
// application/x-internet-signupins isp
// application/x-iphoneiii
// application/x-iso9660-imageiso
// application/x-jamjam
// application/x-java-applet
// application/x-java-bean
// application/x-java-jnlp-filejnlp
// application/x-jmoljmz
// application/x-kchartchrt
// application/x-kdelnk
// application/x-killustratorkil
// application/x-koanskp skd skt skm
// application/x-kpresenterkpr kpt
// application/x-kspreadksp
// application/x-kwordkwd kwt
// application/x-lhalha
// application/x-lyxlyx
// application/x-lzhlzh
// application/x-lzxlzx
// application/x-makerfrm maker frame fm fb book fbdoc
// application/x-mifmif
// application/x-mpegURLm3u8
// application/x-ms-applicationapplication
// application/x-ms-manifestmanifest
// application/x-ms-wmdwmd
// application/x-ms-wmzwmz
// application/x-msimsi
// application/x-netcdfnc
// application/x-ns-proxy-autoconfigpac
// application/x-nwcnwc
// application/x-oz-applicationoza
// application/x-pkcs7-certreqrespp7r
// application/x-pkcs7-crlcrl
// application/x-qgisqgs shp shx
// application/x-quicktimeplayerqtl
// application/x-rdprdp
// application/x-rx
// application/x-scilabsci sce
// application/x-scilab-xcosxcos
// application/x-shellscript
// application/x-shockwave-flashswf swfl
// application/x-silverlightscr
// application/x-sv4cpiosv4cpio
// application/x-sv4crcsv4crc
// application/x-tex-gfgf
// application/x-tex-pkpk
// application/x-ustarustar
// application/x-videolan
// application/x-wais-sourcesrc
// application/x-wingzwz
// application/x-x509-ca-certcrt
// application/x-xpinstallxpi
// audio/32kadpcm
// audio/3gpp
// audio/g.722.1
// audio/l16
// audio/mp4a-latm
// audio/mpa-robust
// audio/parityfec
// audio/telephone-event
// audio/tone
// audio/vnd.cisco.nse
// audio/vnd.cns.anp1
// audio/vnd.cns.inf1
// audio/vnd.digital-winds
// audio/vnd.everad.plj
// audio/vnd.lucent.voice
// audio/vnd.nortel.vbk
// audio/vnd.nuera.ecelp4800
// audio/vnd.nuera.ecelp7470
// audio/vnd.nuera.ecelp9600
// audio/vnd.octel.sbc
// audio/vnd.qcelp
// audio/vnd.rhetorex.32kadpcm
// audio/vnd.vmx.cvsd
// chemical/x-alchemyalc
// chemical/x-cachecac cache
// chemical/x-cache-csfcsf
// chemical/x-cactvs-binarycbin cascii ctab
// chemical/x-cdxcdx
// chemical/x-ceriuscer
// chemical/x-chem3dc3d
// chemical/x-chemdrawchm
// chemical/x-cifcif
// chemical/x-cmdfcmdf
// chemical/x-cmlcml
// chemical/x-compasscpa
// chemical/x-crossfirebsd
// chemical/x-csmlcsml csm
// chemical/x-ctxctx
// chemical/x-cxfcxf cef
// #chemical/x-daylight-smilessmi
// chemical/x-embl-dl-nucleotideemb embl
// chemical/x-galactic-spcspc
// chemical/x-gamess-inputinp gam gamin
// chemical/x-gaussian-checkpointfch fchk
// chemical/x-gaussian-cubecub
// chemical/x-gaussian-inputgau gjc gjf
// chemical/x-gaussian-loggal
// chemical/x-gcg8-sequencegcg
// chemical/x-genbankgen
// chemical/x-hinhin
// chemical/x-isostaristr ist
// chemical/x-jcamp-dxjdx dx
// chemical/x-kinemagekin
// chemical/x-macmoleculemcm
// chemical/x-macromodel-inputmmd mmod
// chemical/x-mdl-molfilemol
// chemical/x-mdl-rdfilerd
// chemical/x-mdl-rxnfilerxn
// chemical/x-mdl-sdfilesd sdf
// chemical/x-mdl-tgftgf
// #chemical/x-mifmif
// chemical/x-mmcifmcif
// chemical/x-mol2mol2
// chemical/x-molconn-Zb
// chemical/x-mopac-graphgpt
// chemical/x-mopac-inputmop mopcrt mpc zmt
// chemical/x-mopac-outmoo
// chemical/x-mopac-vibmvb
// chemical/x-ncbi-asn1asn
// chemical/x-ncbi-asn1-asciiprt ent
// chemical/x-ncbi-asn1-binaryval aso
// chemical/x-ncbi-asn1-specasn
// chemical/x-pdbpdb ent
// chemical/x-rosdalros
// chemical/x-swissprotsw
// chemical/x-vamas-iso14976vms
// chemical/x-vmdvmd
// chemical/x-xtelxtel
// chemical/x-xyzxyz
// image/cgm
// image/g3fax
// image/naplps
// image/prs.btif
// image/prs.pti
// image/vnd.cns.inf2
// image/vnd.dwg
// image/vnd.dxf
// image/vnd.fastbidsheet
// image/vnd.fpx
// image/vnd.fst
// image/vnd.fujixerox.edmics-mmr
// image/vnd.fujixerox.edmics-rlc
// image/vnd.mix
// image/vnd.net-fpx
// image/vnd.svf
// image/vnd.xiff
// image/x-icon
// inode/chardevice
// inode/blockdevice
// inode/directory-locked
// inode/directory
// inode/fifo
// inode/socket
// message/delivery-status
// message/disposition-notification
// message/external-body
// message/http
// message/s-http
// message/news
// message/partial
// message/rfc822eml
// model/vnd.dwf
// model/vnd.flatland.3dml
// model/vnd.gdl
// model/vnd.gs-gdl
// model/vnd.gtw
// model/vnd.mts
// model/vnd.vtu
// multipart/alternative
// multipart/appledouble
// multipart/byteranges
// multipart/digest
// multipart/encrypted
// multipart/form-data
// multipart/header-set
// multipart/mixed
// multipart/parallel
// multipart/related
// multipart/report
// multipart/signed
// multipart/voice-message
// text/english
// text/enriched
// {"text/x-gap",
// {"text/x-gtkrc",
// text/h323323
// text/iulsuls
//{"text/x-idl",
//{"text/x-netrexx",
//{"text/x-ocl",
//{"text/x-dtd",
// {"text/x-gettext-translation",
// {"text/x-gettext-translation-template",
// text/parityfec
// text/prs.lines.tag
// text/rfc822-headers
// text/scriptletsct wsc
// text/t140
// text/texmacstm
// text/turtlettl
// text/vnd.abc
// text/vnd.curl
// text/vnd.debian.copyright
// text/vnd.DMClientScript
// text/vnd.flatland.3dml
// text/vnd.fly
// text/vnd.fmi.flexstor
// text/vnd.in3d.3dml
// text/vnd.in3d.spot
// text/vnd.IPTC.NewsML
// text/vnd.IPTC.NITF
// text/vnd.latex-z
// text/vnd.motorola.reflex
// text/vnd.ms-mediapackage
// text/vnd.sun.j2me.app-descriptorjad
// text/vnd.wap.si
// text/vnd.wap.sl
// text/vnd.wap.wmlwml
// text/vnd.wap.wmlscriptwmls
// text/x-booboo
// text/x-componenthtc
// text/x-crontab
// text/x-lilypondly
// text/x-pcs-gcdgcd
// text/x-setextetx
// text/x-sfvsfv
// video/mp4v-es
// video/parityfec
// video/pointer
// video/vnd.fvt
// video/vnd.motorola.video
// video/vnd.motorola.videop
// video/vnd.mts
// video/vnd.nokia.interleaved-multimedia
// video/vnd.vivo
// x-conference/x-cooltalkice
//
// x-epoc/x-sisx-appsisx
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package fsx
import (
"io/fs"
"os"
"path/filepath"
"strings"
"cogentcore.org/core/base/errors"
)
// Sub returns [fs.Sub] with any error automatically logged
// for cases where the directory is hardcoded and there is
// no chance of error.
func Sub(fsys fs.FS, dir string) fs.FS {
return errors.Log1(fs.Sub(fsys, dir))
}
// DirFS returns the directory part of given file path as an os.DirFS
// and the filename as a string. These can then be used to access the file
// using the FS-based interface, consistent with embed and other use-cases.
func DirFS(fpath string) (fs.FS, string, error) {
fabs, err := filepath.Abs(fpath)
if err != nil {
return nil, "", err
}
dir, fname := filepath.Split(fabs)
dfs := os.DirFS(dir)
return dfs, fname, nil
}
// FileExistsFS checks whether given file exists, returning true if so,
// false if not, and error if there is an error in accessing the file.
func FileExistsFS(fsys fs.FS, filePath string) (bool, error) {
if fsys, ok := fsys.(fs.StatFS); ok {
fileInfo, err := fsys.Stat(filePath)
if err == nil {
return !fileInfo.IsDir(), nil
}
if errors.Is(err, fs.ErrNotExist) {
return false, nil
}
return false, err
}
fp, err := fsys.Open(filePath)
if err == nil {
// as with Stat above, a directory is not a file
fi, serr := fp.Stat()
fp.Close()
if serr != nil {
return false, serr
}
return !fi.IsDir(), nil
}
if errors.Is(err, fs.ErrNotExist) {
return false, nil
}
return false, err
}
// SplitRootPathFS returns a split of the given FS path (only / path separators)
// into the root element and everything after that point.
// Examples:
// - "/a/b/c" returns "/", "a/b/c"
// - "a/b/c" returns "a", "b/c" (note removal of intervening "/")
// - "a" returns "a", ""
// - "a/" returns "a", "" (note removal of trailing "/")
func SplitRootPathFS(path string) (root, rest string) {
pi := strings.IndexByte(path, '/')
if pi < 0 {
return path, ""
}
if pi == 0 {
return "/", path[1:]
}
if pi < len(path)-1 {
return path[:pi], path[pi+1:]
}
return path[:pi], ""
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package fsx provides various utility functions for dealing with filesystems.
package fsx
import (
"errors"
"fmt"
"io"
"io/fs"
"net/url"
"os"
"path/filepath"
"sort"
"strings"
"time"
)
// Filename is used to open a file picker dialog when used as an argument
// type in a function, or as a field value.
type Filename string
// GoSrcDir tries to locate dir in GOPATH/src/ or GOROOT/src/pkg/ and returns its
// full path. GOPATH may contain a list of paths. From Robin Elkind github.com/mewkiz/pkg.
func GoSrcDir(dir string) (absDir string, err error) {
for _, srcDir := range GoSrcDirs() {
absDir = filepath.Join(srcDir, dir)
finfo, err := os.Stat(absDir)
if err == nil && finfo.IsDir() {
return absDir, nil
}
}
return "", fmt.Errorf("fsx.GoSrcDir: unable to locate directory (%q) in GOPATH/src/ (%q) or GOROOT/src/pkg/ (%q)", dir, os.Getenv("GOPATH"), os.Getenv("GOROOT"))
}
// Files returns all the DirEntry's for files with given extension(s) in directory
// in sorted order (if extensions are empty then all files are returned).
// In case of error, returns nil.
func Files(path string, extensions ...string) []fs.DirEntry {
files, err := os.ReadDir(path)
if err != nil {
return nil
}
if len(extensions) == 0 {
return files
}
sz := len(files)
if sz == 0 {
return nil
}
for i := sz - 1; i >= 0; i-- {
fn := files[i]
ext := filepath.Ext(fn.Name())
keep := false
for _, ex := range extensions {
if strings.EqualFold(ext, ex) {
keep = true
break
}
}
if !keep {
files = append(files[:i], files[i+1:]...)
}
}
return files
}
// Filenames returns all the file names with given extension(s) in directory
// in sorted order (if extensions is empty then all files are returned)
func Filenames(path string, extensions ...string) []string {
f, err := os.Open(path)
if err != nil {
return nil
}
files, err := f.Readdirnames(-1)
f.Close()
if err != nil {
return nil
}
if len(extensions) == 0 {
sort.StringSlice(files).Sort()
return files
}
sz := len(files)
if sz == 0 {
return nil
}
for i := sz - 1; i >= 0; i-- {
fn := files[i]
ext := filepath.Ext(fn)
keep := false
for _, ex := range extensions {
if strings.EqualFold(ext, ex) {
keep = true
break
}
}
if !keep {
files = append(files[:i], files[i+1:]...)
}
}
sort.StringSlice(files).Sort()
return files
}
// Dirs returns a slice of all the directories within a given directory
func Dirs(path string) []string {
files, err := os.ReadDir(path)
if err != nil {
return nil
}
var fnms []string
for _, fi := range files {
if fi.IsDir() {
fnms = append(fnms, fi.Name())
}
}
return fnms
}
// LatestMod returns the latest (most recent) modification time for any of the
// files in the directory (optionally filtered by extension(s) if exts != nil)
// if no files or error, returns zero time value
func LatestMod(path string, exts ...string) time.Time {
tm := time.Time{}
files := Files(path, exts...)
if len(files) == 0 {
return tm
}
for _, de := range files {
fi, err := de.Info()
if err == nil {
if fi.ModTime().After(tm) {
tm = fi.ModTime()
}
}
}
return tm
}
// HasFile returns true if given directory has given file (exact match)
func HasFile(path, file string) bool {
files, err := os.ReadDir(path)
if err != nil {
return false
}
for _, fn := range files {
if fn.Name() == file {
return true
}
}
return false
}
// FindFilesOnPaths attempts to locate given file(s) on given list of paths,
// returning the full Abs path to each file found (nil if none)
func FindFilesOnPaths(paths []string, files ...string) []string {
var res []string
for _, path := range paths {
for _, fn := range files {
fp := filepath.Join(path, fn)
ok, _ := FileExists(fp)
if ok {
res = append(res, fp)
}
}
}
return res
}
// FileExists checks whether given file exists, returning true if so,
// false if not, and error if there is an error in accessing the file.
func FileExists(filePath string) (bool, error) {
fileInfo, err := os.Stat(filePath)
if err == nil {
return !fileInfo.IsDir(), nil
}
if errors.Is(err, os.ErrNotExist) {
return false, nil
}
return false, err
}
// FileURL returns a file:// URL for the given absolute file path, with
// any special characters escaped, as for opening the file with OpenURL.
// Windows paths such as C:\a\b.txt become file:///C:/a/b.txt.
func FileURL(path string) string {
p := filepath.ToSlash(path)
if !strings.HasPrefix(p, "/") { // Windows drive letter
p = "/" + p
}
return (&url.URL{Scheme: "file", Path: p}).String()
}
// Exists returns whether a file or directory exists at the given path.
func Exists(path string) bool {
_, err := os.Stat(path)
return err == nil
}
// DirExists checks whether given directory exists, returning true if so,
// false if not, and error if there is an error in accessing the file.
func DirExists(filePath string) (bool, error) {
fileInfo, err := os.Stat(filePath)
if err == nil {
return fileInfo.IsDir(), nil
}
return false, err
}
// DirAndFile returns the final dir and file name.
func DirAndFile(file string) string {
dir, fnm := filepath.Split(file)
return filepath.Join(filepath.Base(dir), fnm)
}
// RelativeFilePath returns the file name relative to given root file path, if it is
// under that root; otherwise it returns the final dir and file name.
func RelativeFilePath(file, root string) string {
rp, err := filepath.Rel(root, file)
if err == nil && !strings.HasPrefix(rp, "..") {
return rp
}
return DirAndFile(file)
}
// ExtSplit returns the split between the extension and name before
// the extension, for the given file name. Any path elements in the
// file name are preserved; pass [filepath.Base](file) to extract only the
// last element of the file path if that is what is desired.
func ExtSplit(file string) (base, ext string) {
ext = filepath.Ext(file)
base = strings.TrimSuffix(file, ext)
return
}
// here's all the discussion about why CopyFile is not in std lib:
// https://old.reddit.com/r/golang/comments/3lfqoh/why_golang_does_not_provide_a_copy_file_func/
// https://github.com/golang/go/issues/8868
// CopyFile copies the contents from src to dst atomically.
// If dst does not exist, CopyFile creates it with permissions perm.
// If the copy fails, CopyFile aborts and dst is preserved.
func CopyFile(dst, src string, perm os.FileMode) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
tmp, err := os.CreateTemp(filepath.Dir(dst), "")
if err != nil {
return err
}
_, err = io.Copy(tmp, in)
if err != nil {
tmp.Close()
os.Remove(tmp.Name())
return err
}
if err = tmp.Close(); err != nil {
os.Remove(tmp.Name())
return err
}
if err = os.Chmod(tmp.Name(), perm); err != nil {
os.Remove(tmp.Name())
return err
}
return os.Rename(tmp.Name(), dst)
}
// CopyPath copies the file or directory at src to dst, overwriting
// existing files. A directory is copied with all of its contents,
// merged into dst if that exists. It is an error to copy a directory
// into itself or one of its subdirectories.
func CopyPath(dst, src string) error {
info, err := os.Stat(src)
if err != nil {
return err
}
if !info.IsDir() {
return CopyFile(dst, src, info.Mode())
}
asrc, err := filepath.Abs(src)
if err != nil {
return err
}
adst, err := filepath.Abs(dst)
if err != nil {
return err
}
if rel, err := filepath.Rel(asrc, adst); err == nil && (rel == "." || filepath.IsLocal(rel)) {
return fmt.Errorf("cannot copy directory %s into itself", src)
}
return filepath.WalkDir(src, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
rel, err := filepath.Rel(src, path)
if err != nil {
return err
}
target := filepath.Join(dst, rel)
info, err := d.Info()
if err != nil {
return err
}
switch {
case d.IsDir():
return os.MkdirAll(target, info.Mode().Perm()|0700)
case info.Mode().IsRegular():
return CopyFile(target, path, info.Mode())
}
return nil // skip symlinks and special files
})
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !js
package fsx
import "go/build"
// GoSrcDirs returns the Go source directories: GOROOT/src and GOPATH/src for
// each GOPATH entry. There are none on the web, which also keeps go/build
// and the go/* parsing packages it needs out of web builds.
func GoSrcDirs() []string {
return build.Default.SrcDirs()
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package generate provides utilities for building code generators in Go.
// The standard path for a code generator is: [Load] -> [PrintHeader] -> [Inspect] -> [Write].
package generate
import (
"fmt"
"go/ast"
"io"
"os"
"path/filepath"
"slices"
"strings"
"golang.org/x/tools/go/packages"
"golang.org/x/tools/imports"
)
// Load loads and returns the Go packages named by the given patterns.
// Load calls [packages.Load] and ensures that there is at least one
// package; this means that, if there is a nil error, the length
// of the resulting packages is guaranteed to be greater than zero.
func Load(cfg *packages.Config, patterns ...string) ([]*packages.Package, error) {
pkgs, err := packages.Load(cfg, patterns...)
if err != nil {
return nil, err
}
if len(pkgs) == 0 {
return nil, fmt.Errorf("expected at least one package but got %d", len(pkgs))
}
return pkgs, nil
}
// PrintHeader prints a header to the given writer for a generated
// file in the given package with the given imports. Imports do not
// need to be set if you are running [Format] on the code later,
// but they should be set for any external packages that many not
// be found correctly by goimports.
func PrintHeader(w io.Writer, pkg string, imports ...string) {
cmdstr := strings.TrimSuffix(filepath.Base(os.Args[0]), ".exe")
if len(os.Args) > 1 {
cmdstr += " " + strings.Join(os.Args[1:], " ")
}
fmt.Fprintf(w, "// Code generated by \"%s\"; DO NOT EDIT.\n\n", cmdstr)
fmt.Fprintf(w, "package %s\n", pkg)
if len(imports) > 0 {
fmt.Fprint(w, "import (\n")
for _, imp := range imports {
fmt.Fprintf(w, "\t%q\n", imp)
}
fmt.Fprint(w, ")\n")
}
}
// ExcludeFile returns true if the given file is on the exclude list.
func ExcludeFile(pkg *packages.Package, file *ast.File, exclude ...string) bool {
fpos := pkg.Fset.Position(file.FileStart)
_, fname := filepath.Split(fpos.Filename)
return slices.Contains(exclude, fname)
}
// Inspect goes through all of the files in the given package,
// except those listed in the exclude list, and calls the given
// function on each node. The bool return value from the given function
// indicates whether to continue traversing down the AST tree
// of that node and look at its children. If a non-nil error value
// is returned by the given function, the traversal of the tree is
// stopped and the error value is returned.
func Inspect(pkg *packages.Package, f func(n ast.Node) (bool, error), exclude ...string) error {
for _, file := range pkg.Syntax {
if ExcludeFile(pkg, file, exclude...) {
continue
}
var terr error
var terrNode ast.Node
ast.Inspect(file, func(n ast.Node) bool {
if terr != nil {
return false
}
cont, err := f(n)
if err != nil {
terr = err
terrNode = n
}
return cont
})
if terr != nil {
return fmt.Errorf("generate.Inspect: error while calling inspect function for node %v: %w", terrNode, terr)
}
}
return nil
}
// Filepath returns the filepath of a file in the given
// package with the given filename relative to the package.
// An absolute filename is returned unchanged.
func Filepath(pkg *packages.Package, filename string) string {
if filepath.IsAbs(filename) {
return filename
}
dir := "."
if len(pkg.Syntax) > 0 {
dir = filepath.Dir(pkg.Fset.Position(pkg.Syntax[0].FileStart).Filename)
}
return filepath.Join(dir, filename)
}
// Write writes the given bytes to the given filename after
// applying goimports using the given options.
func Write(filename string, src []byte, opt *imports.Options) error {
b, ferr := Format(filename, src, opt)
// we still write file even if formatting failed, as it is still useful
// then we handle error later
werr := os.WriteFile(filename, b, 0666)
if werr != nil {
return fmt.Errorf("generate.Write: error writing file: %w", werr)
}
if ferr != nil {
return fmt.Errorf("generate.Write: error formatting code: %w", ferr)
}
return nil
}
// Format returns the given bytes with goimports applied.
// It wraps [imports.Process] by wrapping any error with
// additional context.
func Format(filename string, src []byte, opt *imports.Options) ([]byte, error) {
b, err := imports.Process(filename, src, opt)
if err != nil {
// Should never happen, but can arise when developing code.
// The user can compile the output to see the error.
return src, fmt.Errorf("internal/programmer error: generate.Format: invalid Go generated: %w; compile the package to analyze the error", err)
}
return b, nil
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package github is a client of the GitHub REST API for the git data of
// repositories: branches, commits, trees and files, as for storing and
// syncing the files of an app in a repository. It uses only HTTPS
// requests with a token, which work on all platforms, including the web,
// as the API allows requests from browsers, unlike the git protocol.
package github
import (
"bytes"
"crypto/sha1"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"sync"
"time"
)
// DefaultAPI is the URL of the GitHub REST API.
const DefaultAPI = "https://api.github.com"
// Client is a client of the GitHub REST API. Its methods take the
// repository as "owner/name".
type Client struct {
// Token is the token for the requests, such as a fine-grained personal
// access token with read and write access to the contents of the
// repositories, or none for public ones.
Token string
// API is the URL of the API, which is [DefaultAPI] if empty,
// or that of a test server (see package githubtest).
API string
// HTTP is the client for the requests, which is
// [http.DefaultClient] if nil.
HTTP *http.Client
// etags are the ETags and bodies of the last responses to GET requests,
// by path, for conditional requests: a response that is not modified
// does not count against the rate limit of the API.
etags map[string]etagged
mu sync.Mutex
}
// etagged is the ETag and body of the last response to a GET request.
type etagged struct {
etag string
body []byte
}
// Error is an error response of the API.
type Error struct {
// Status is the HTTP status code of the response.
Status int
// Message is the message of the response.
Message string
}
func (e *Error) Error() string {
return fmt.Sprintf("github: %d %s", e.Status, e.Message)
}
// StatusOf returns the HTTP status code of the given error, if it is an
// [Error], and otherwise 0.
func StatusOf(err error) int {
if e, ok := errors.AsType[*Error](err); ok {
return e.Status
}
return 0
}
// ErrNotFastForward is the error of [Client.UpdateRef] when the branch
// has commits that the new commit does not have, as when it was updated
// since it was read.
var ErrNotFastForward = errors.New("github: the update of the branch is not a fast forward")
// Do sends a request with the given method to the given path of the API,
// with the given body as JSON if it is not nil, and decodes the JSON of
// the response into the given result if it is not nil. GET requests are
// conditional on the ETag of the last response to the same path, which
// is used again if it is not modified.
func (c *Client) Do(method, path string, body, result any) error {
var rd io.Reader
if body != nil {
b, err := json.Marshal(body)
if err != nil {
return err
}
rd = bytes.NewReader(b)
}
api := c.API
if api == "" {
api = DefaultAPI
}
req, err := http.NewRequest(method, strings.TrimSuffix(api, "/")+path, rd)
if err != nil {
return err
}
req.Header.Set("Accept", "application/vnd.github+json")
req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
if c.Token != "" {
req.Header.Set("Authorization", "Bearer "+c.Token)
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
c.mu.Lock()
prev, hasPrev := c.etags[path]
c.mu.Unlock()
if method == http.MethodGet && hasPrev {
req.Header.Set("If-None-Match", prev.etag)
}
hc := c.HTTP
if hc == nil {
hc = http.DefaultClient
}
resp, err := hc.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
// a response that is not modified has the body of the last one
switch {
case resp.StatusCode == http.StatusNotModified && hasPrev:
data = prev.body
case resp.StatusCode < 200 || resp.StatusCode >= 300:
var msg struct {
Message string `json:"message"`
}
json.Unmarshal(data, &msg)
return &Error{Status: resp.StatusCode, Message: msg.Message}
case method == http.MethodGet && resp.Header.Get("ETag") != "":
c.mu.Lock()
if c.etags == nil {
c.etags = map[string]etagged{}
}
c.etags[path] = etagged{etag: resp.Header.Get("ETag"), body: data}
c.mu.Unlock()
}
if result == nil || len(data) == 0 {
return nil
}
return json.Unmarshal(data, result)
}
// object is an object of a repository in a response of the API, with
// its SHA. The JSON names of the API are lowercase, and are given in the
// tags of the fields, which encoding/json v2 needs.
type object struct {
SHA string `json:"sha"`
}
// signature is the author or committer of a commit in a response of the
// API, with its time. It is a named type, as goscript cannot decode a
// time.Time in an anonymous struct type.
type signature struct {
Date time.Time `json:"date"`
}
// Commit is a commit of a repository.
type Commit struct {
// SHA is the SHA of the commit.
SHA string
// Tree is the SHA of the tree of the files of the commit.
Tree string
// Parents are the SHAs of the parents of the commit.
Parents []string
// Message is the message of the commit.
Message string
// Date is when the commit was made.
Date time.Time
}
// Head returns the SHA of the last commit of the given branch of the
// given repository. A repository without commits, which the API does not
// support otherwise, has the status 409 (see [StatusOf] and [Client.PutFile]),
// and one without the branch 404.
func (c *Client) Head(repo, branch string) (string, error) {
var ref struct {
Object object `json:"object"`
}
if err := c.Do(http.MethodGet, "/repos/"+repo+"/git/ref/heads/"+branch, nil, &ref); err != nil {
return "", err
}
if ref.Object.SHA == "" {
return "", fmt.Errorf("github: the branch %s of %s has no commit", branch, repo)
}
return ref.Object.SHA, nil
}
// Commit returns the commit with the given SHA of the given repository.
func (c *Client) Commit(repo, sha string) (*Commit, error) {
if sha == "" {
return nil, errors.New("github: no commit SHA")
}
var cm struct {
SHA string `json:"sha"`
Message string `json:"message"`
Tree object `json:"tree"`
Parents []object `json:"parents"`
// the time of the commit, after that of its author for a rebase
Committer signature `json:"committer"`
}
if err := c.Do(http.MethodGet, "/repos/"+repo+"/git/commits/"+sha, nil, &cm); err != nil {
return nil, err
}
res := &Commit{SHA: cm.SHA, Tree: cm.Tree.SHA, Message: cm.Message, Date: cm.Committer.Date}
for _, p := range cm.Parents {
res.Parents = append(res.Parents, p.SHA)
}
return res, nil
}
// TreeEntry is a file or directory in a tree of a repository.
type TreeEntry struct {
// Path is the path of the file in the tree, with slashes.
Path string `json:"path"`
// Type is blob for a file, and tree for a directory.
Type string `json:"type"`
// SHA is the SHA of the blob of a file (see [BlobSHA]),
// or of the tree of a directory.
SHA string `json:"sha"`
}
// Files returns the files of the tree with the given SHA of the given
// repository, with those in its directories, by path.
func (c *Client) Files(repo, tree string) (map[string]TreeEntry, error) {
var tr struct {
Tree []TreeEntry `json:"tree"`
Truncated bool `json:"truncated"`
}
if err := c.Do(http.MethodGet, "/repos/"+repo+"/git/trees/"+tree+"?recursive=1", nil, &tr); err != nil {
return nil, err
}
if tr.Truncated {
return nil, fmt.Errorf("github: the tree %s of %s has too many files", tree, repo)
}
files := map[string]TreeEntry{}
for _, e := range tr.Tree {
if e.Type == "blob" {
files[e.Path] = e
}
}
return files, nil
}
// Blob returns the contents of the blob of a file with the given SHA of
// the given repository.
func (c *Client) Blob(repo, sha string) ([]byte, error) {
var b struct {
Content string `json:"content"`
Encoding string `json:"encoding"`
}
if err := c.Do(http.MethodGet, "/repos/"+repo+"/git/blobs/"+sha, nil, &b); err != nil {
return nil, err
}
if b.Encoding != "base64" {
return []byte(b.Content), nil
}
return base64.StdEncoding.DecodeString(strings.ReplaceAll(b.Content, "\n", ""))
}
// BlobSHA returns the SHA of a blob of a file with the given contents,
// as git computes it, for comparing files with those of a tree
// without getting them.
func BlobSHA(content []byte) string {
// sha1.Sum, not sha1.New, which returns a hash.Hash, which goscript lacks
b := append(fmt.Appendf(nil, "blob %d\x00", len(content)), content...)
h := sha1.Sum(b)
return hex.EncodeToString(h[:])
}
// CreateTree creates a tree of the given repository, with the files of
// the tree with the given SHA, changed by the given files by path: a file
// is added or replaced with its contents, or deleted if they are nil.
// It returns the SHA of the new tree.
func (c *Client) CreateTree(repo, base string, files map[string][]byte) (string, error) {
entries := make([]map[string]any, 0, len(files))
for path, content := range files {
e := map[string]any{"path": path, "mode": "100644", "type": "blob"}
if content == nil {
e["sha"] = nil
} else {
e["content"] = string(content)
}
entries = append(entries, e)
}
var res object
err := c.Do(http.MethodPost, "/repos/"+repo+"/git/trees", map[string]any{"base_tree": base, "tree": entries}, &res)
return res.SHA, err
}
// CreateCommit creates a commit of the given repository with the given
// message, tree and parents, returning its SHA. It does not update a
// branch (see [Client.UpdateRef]).
func (c *Client) CreateCommit(repo, message, tree string, parents ...string) (string, error) {
var res object
err := c.Do(http.MethodPost, "/repos/"+repo+"/git/commits", map[string]any{"message": message, "tree": tree, "parents": parents}, &res)
return res.SHA, err
}
// UpdateRef updates the given branch of the given repository to the commit
// with the given SHA. Unless force, it must be a fast forward, with the
// last commit of the branch in its history, or the error is
// [ErrNotFastForward].
func (c *Client) UpdateRef(repo, branch, sha string, force bool) error {
err := c.Do(http.MethodPatch, "/repos/"+repo+"/git/refs/heads/"+branch, map[string]any{"sha": sha, "force": force}, nil)
if StatusOf(err) == http.StatusUnprocessableEntity {
return fmt.Errorf("%w: %w", ErrNotFastForward, err)
}
return err
}
// CommitFiles commits the given files by path to the given branch of the
// given repository, after the given commit, the last one of the branch,
// as in [Client.CreateTree], returning the SHA of the new commit. It
// returns [ErrNotFastForward] if the branch has commits after the given
// one, which then must be merged.
func (c *Client) CommitFiles(repo, branch, parent, message string, files map[string][]byte) (string, error) {
pc, err := c.Commit(repo, parent)
if err != nil {
return "", err
}
tree, err := c.CreateTree(repo, pc.Tree, files)
if err != nil {
return "", err
}
sha, err := c.CreateCommit(repo, message, tree, parent)
if err != nil {
return "", err
}
return sha, c.UpdateRef(repo, branch, sha, false)
}
// PutFile commits a file with the given path and contents to the given
// branch of the given repository, with the contents API, which also works
// for a repository without commits, for its first commit.
func (c *Client) PutFile(repo, branch, path, message string, content []byte) error {
body := map[string]any{"message": message, "branch": branch, "content": base64.StdEncoding.EncodeToString(content)}
return c.Do(http.MethodPut, "/repos/"+repo+"/contents/"+path, body, nil)
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package githubtest is a test server of the parts of the GitHub REST API
// that package github uses, with repositories in memory.
package githubtest
import (
"crypto/sha1"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"maps"
"net/http"
"net/http/httptest"
"strings"
"sync"
"time"
"cogentcore.org/core/base/github"
)
// Server is a test server of the GitHub REST API, as for a [github.Client]
// with [Server.URL] as its API. The repositories are made when they are
// first used, without commits.
type Server struct {
*httptest.Server
// Token, if set, is the token that the requests must have.
Token string
// Requests is the number of requests to the server, without
// those that are not modified, as for the rate limit.
Requests int
repos map[string]*repo
mu sync.Mutex
}
// repo is a repository of the test server.
type repo struct {
blobs map[string][]byte
trees map[string]map[string]string // the blobs of the files by path
commits map[string]*commit
refs map[string]string // the commits of the branches
}
// commit is a commit of a repository of the test server.
type commit struct {
tree, message string
parents []string
date time.Time
}
// NewServer returns a new running test server, to be closed after use.
func NewServer() *Server {
s := &Server{repos: map[string]*repo{}}
s.Server = httptest.NewServer(http.HandlerFunc(s.handle))
return s
}
// Client returns a new client of the server.
func (s *Server) Client() *github.Client {
return &github.Client{API: s.URL, Token: s.Token}
}
// Files returns the files of the last commit of the given branch of the
// given repository, by path, or nil if it has none.
func (s *Server) Files(repoName, branch string) map[string][]byte {
s.mu.Lock()
defer s.mu.Unlock()
r := s.repo(repoName)
c := r.commits[r.refs[branch]]
if c == nil {
return nil
}
files := map[string][]byte{}
for path, sha := range r.trees[c.tree] {
files[path] = r.blobs[sha]
}
return files
}
// Commits returns the messages of the commits of the given branch of the
// given repository, from the last one, along the first parents.
func (s *Server) Commits(repoName, branch string) []string {
s.mu.Lock()
defer s.mu.Unlock()
r := s.repo(repoName)
var msgs []string
for c := r.commits[r.refs[branch]]; c != nil; {
msgs = append(msgs, c.message)
if len(c.parents) == 0 {
break
}
c = r.commits[c.parents[0]]
}
return msgs
}
// repo returns the repository with the given name, making it if needed.
func (s *Server) repo(name string) *repo {
r := s.repos[name]
if r == nil {
r = &repo{blobs: map[string][]byte{}, trees: map[string]map[string]string{}, commits: map[string]*commit{}, refs: map[string]string{}}
s.repos[name] = r
}
return r
}
// hash returns a SHA for the given object of a repository.
func hash(kind string, v any) string {
b, _ := json.Marshal(v)
h := sha1.Sum(append([]byte(kind+" "), b...))
return hex.EncodeToString(h[:])
}
// addTree adds the tree with the given files to the repository.
func (r *repo) addTree(files map[string]string) string {
sha := hash("tree", files)
r.trees[sha] = files
return sha
}
// addCommit adds the commit to the repository.
func (r *repo) addCommit(c *commit) string {
sha := hash("commit", []any{c.tree, c.message, c.parents, c.date})
r.commits[sha] = c
return sha
}
// addBlob adds the blob with the given contents to the repository.
func (r *repo) addBlob(content []byte) string {
sha := github.BlobSHA(content)
r.blobs[sha] = content
return sha
}
// handle handles a request of the API.
func (s *Server) handle(w http.ResponseWriter, req *http.Request) {
s.mu.Lock()
defer s.mu.Unlock()
if s.Token != "" && req.Header.Get("Authorization") != "Bearer "+s.Token {
writeError(w, http.StatusUnauthorized, "Bad credentials")
return
}
// /repos/owner/name/rest...
parts := strings.SplitN(strings.TrimPrefix(req.URL.Path, "/repos/"), "/", 3)
if len(parts) < 3 {
writeError(w, http.StatusNotFound, "Not Found")
return
}
r := s.repo(parts[0] + "/" + parts[1])
rest := parts[2]
var body map[string]any
if req.Body != nil {
json.NewDecoder(req.Body).Decode(&body)
}
if !strings.HasPrefix(rest, "contents/") && len(r.refs) == 0 {
writeError(w, http.StatusConflict, "Git Repository is empty.")
return
}
switch {
case req.Method == http.MethodGet && strings.HasPrefix(rest, "git/ref/heads/"):
sha, ok := r.refs[strings.TrimPrefix(rest, "git/ref/heads/")]
if !ok {
writeError(w, http.StatusNotFound, "Not Found")
return
}
s.write(w, req, map[string]any{"object": map[string]any{"sha": sha, "type": "commit"}})
case req.Method == http.MethodGet && strings.HasPrefix(rest, "git/commits/"):
c := r.commits[strings.TrimPrefix(rest, "git/commits/")]
if c == nil {
writeError(w, http.StatusNotFound, "Not Found")
return
}
var parents []map[string]any
for _, p := range c.parents {
parents = append(parents, map[string]any{"sha": p})
}
s.write(w, req, map[string]any{"sha": strings.TrimPrefix(rest, "git/commits/"), "message": c.message,
"tree": map[string]any{"sha": c.tree}, "parents": parents, "committer": map[string]any{"date": c.date}})
case req.Method == http.MethodGet && strings.HasPrefix(rest, "git/trees/"):
files, ok := r.trees[strings.TrimPrefix(rest, "git/trees/")]
if !ok {
writeError(w, http.StatusNotFound, "Not Found")
return
}
var entries []map[string]any
for path, sha := range files {
entries = append(entries, map[string]any{"path": path, "type": "blob", "sha": sha})
}
s.write(w, req, map[string]any{"tree": entries})
case req.Method == http.MethodGet && strings.HasPrefix(rest, "git/blobs/"):
b, ok := r.blobs[strings.TrimPrefix(rest, "git/blobs/")]
if !ok {
writeError(w, http.StatusNotFound, "Not Found")
return
}
s.write(w, req, map[string]any{"content": base64.StdEncoding.EncodeToString(b), "encoding": "base64"})
case req.Method == http.MethodPost && rest == "git/trees":
s.createTree(w, req, r, body)
case req.Method == http.MethodPost && rest == "git/commits":
c := &commit{tree: fmt.Sprint(body["tree"]), message: fmt.Sprint(body["message"]), date: time.Now()}
if _, ok := r.trees[c.tree]; !ok {
writeError(w, http.StatusUnprocessableEntity, "Tree SHA does not exist")
return
}
for _, p := range body["parents"].([]any) {
c.parents = append(c.parents, fmt.Sprint(p))
}
s.write(w, req, map[string]any{"sha": r.addCommit(c)})
case req.Method == http.MethodPatch && strings.HasPrefix(rest, "git/refs/heads/"):
branch := strings.TrimPrefix(rest, "git/refs/heads/")
sha := fmt.Sprint(body["sha"])
if r.commits[sha] == nil {
writeError(w, http.StatusUnprocessableEntity, "Object does not exist")
return
}
if force, _ := body["force"].(bool); !force && !r.hasAncestor(sha, r.refs[branch]) {
writeError(w, http.StatusUnprocessableEntity, "Update is not a fast forward")
return
}
r.refs[branch] = sha
s.write(w, req, map[string]any{"object": map[string]any{"sha": sha}})
case req.Method == http.MethodPut && strings.HasPrefix(rest, "contents/"):
s.putFile(w, r, strings.TrimPrefix(rest, "contents/"), body)
default:
writeError(w, http.StatusNotFound, "Not Found")
}
}
// createTree handles a request to create a tree.
func (s *Server) createTree(w http.ResponseWriter, req *http.Request, r *repo, body map[string]any) {
files := map[string]string{}
if base, _ := body["base_tree"].(string); base != "" {
bt, ok := r.trees[base]
if !ok {
writeError(w, http.StatusUnprocessableEntity, "base_tree is not a valid tree")
return
}
files = maps.Clone(bt)
}
for _, e := range body["tree"].([]any) {
e := e.(map[string]any)
path := fmt.Sprint(e["path"])
if content, ok := e["content"].(string); ok {
files[path] = r.addBlob([]byte(content))
} else if sha, ok := e["sha"].(string); ok {
files[path] = sha
} else {
delete(files, path)
}
}
s.write(w, req, map[string]any{"sha": r.addTree(files)})
}
// putFile handles a request to commit a file with the contents API.
func (s *Server) putFile(w http.ResponseWriter, r *repo, path string, body map[string]any) {
branch, _ := body["branch"].(string)
if branch == "" {
branch = "main"
}
content, err := base64.StdEncoding.DecodeString(fmt.Sprint(body["content"]))
if err != nil {
writeError(w, http.StatusUnprocessableEntity, "content is not valid Base64")
return
}
files := map[string]string{}
var parents []string
if head, ok := r.refs[branch]; ok {
files = maps.Clone(r.trees[r.commits[head].tree])
parents = []string{head}
} else if len(r.refs) > 0 {
writeError(w, http.StatusNotFound, "Branch not found")
return
}
files[path] = r.addBlob(content)
c := &commit{tree: r.addTree(files), message: fmt.Sprint(body["message"]), parents: parents, date: time.Now()}
r.refs[branch] = r.addCommit(c)
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(map[string]any{"commit": map[string]any{"sha": r.refs[branch]}})
s.Requests++
}
// hasAncestor returns whether the given commit has the given ancestor,
// or is it, or the ancestor is none.
func (r *repo) hasAncestor(sha, ancestor string) bool {
if ancestor == "" || sha == ancestor {
return true
}
c := r.commits[sha]
if c == nil {
return false
}
for _, p := range c.parents {
if r.hasAncestor(p, ancestor) {
return true
}
}
return false
}
// write writes the given response, with an ETag for a GET request,
// or not modified for one with the same ETag.
func (s *Server) write(w http.ResponseWriter, req *http.Request, v any) {
b, _ := json.Marshal(v)
if req.Method == http.MethodGet {
h := sha1.Sum(b)
etag := `"` + hex.EncodeToString(h[:]) + `"`
w.Header().Set("ETag", etag)
if req.Header.Get("If-None-Match") == etag {
w.WriteHeader(http.StatusNotModified)
return
}
}
s.Requests++
w.Header().Set("Content-Type", "application/json")
w.Write(b)
}
// writeError writes an error response with the given status and message.
func writeError(w http.ResponseWriter, status int, message string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(map[string]any{"message": message})
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package goscript provides support for running Cogent Core code compiled
// to JavaScript by [goscript] (https://github.com/s4wave/goscript), which is
// used for the js platform. Code compiled by goscript is built with
// GOOS=js, GOARCH=wasm, and the goscript build tag.
//
// The main use of this package is [RunTests], which runs the existing Go
// tests of a package compiled to JavaScript, so that the same tests verify
// both the native and the goscript versions of the code. It is run by
// core test js (see the cmd package), for the packages given to it, and,
// for a pattern with ... in it, for the packages that opt in with a
// [Directive] line in one of their test files:
//
// //core:js-test
//
// Tests that do not work in goscript call [Skip].
//
// This package must only import the standard library, so that it can be used
// in the tests of any package without an import cycle.
package goscript
import "testing"
// Skip skips the given test with the given reason if the code is running
// as JavaScript compiled by goscript (see [Enabled]). It is for the
// (ideally rare and temporary) tests that do not work in goscript.
func Skip(t testing.TB, reason string) {
t.Helper()
if Enabled {
t.Skip("goscript: " + reason)
}
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !goscript
package goscript
import (
"bufio"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"
"time"
)
// Directive is the comment directive with which a package opts in to
// having its tests run compiled to JavaScript by core test js for a
// package pattern with ... in it (see [PackageOptions]). It is a line
// comment in any test file of the package, optionally followed by options:
//
// //core:js-test browser timeout=20m
//
// Each such line is one run of the tests, with these options:
// - browser: run the tests in Chrome instead of bun ([Options.Browser]).
// - browser-arg=ARG: an argument for the browser ([Options.BrowserArgs]).
// - run=REGEXP: only run the matching tests ([Options.Run]).
// - timeout=DURATION: the timeout of the run ([Options.Timeout]).
// - skip-typecheck: skip the type checking ([Options.SkipTypecheck]).
// - tags=TAG,...: additional build tags ([Options.Tags]).
const Directive = "//core:js-test"
// Options are the options for [RunTests].
type Options struct {
// Run, if non-empty, only runs the tests matching this regular expression.
Run string
// Bench, if non-empty, also runs the benchmarks matching this regular
// expression, as with go test -bench. The tests are not run in this
// case, unless [Options.Run] is set.
Bench string
// BenchTime is the minimum time to run each benchmark, as a duration
// such as 2s, if [Options.Bench] is set.
BenchTime string
// Timeout is the maximum time for compiling and running the tests.
// It defaults to 5 minutes (30 minutes with [Options.Bench]).
Timeout time.Duration
// Browser runs the tests in a Chromium browser instead of bun.
Browser bool
// BrowserChannel, if non-empty, runs the [Options.Browser] tests in
// this installed browser, such as "chrome", instead of the Chromium
// that Playwright downloads.
BrowserChannel string
// BrowserArgs are additional command-line arguments for the browser,
// such as "--enable-unsafe-webgpu" to enable WebGPU in headless Chrome.
BrowserArgs []string
// Tags are additional build tags (the goscript tag is always added).
Tags []string
// SkipTypecheck skips the TypeScript type checking of the compiled
// code, which goscript test otherwise does before running it, as core
// build js does (bun only strips the types). It is for packages whose
// compiled code has type errors that do not affect what they do, so
// that their tests still run (as mvmcore, whose mvm interpreter the
// docs use on the web).
SkipTypecheck bool
// Verbose makes goscript test print the output of all of the tests,
// as with go test -v.
Verbose bool
}
// RunTests runs the Go tests of the package in the given directory compiled
// to JavaScript by goscript test, writing its output to the given writer.
// It returns an error if the tests could not be run or did not pass, which
// names the failing tests. goscript and bun (https://bun.sh) must be
// installed (as by core setup -js), and tsrs, unless [Options.SkipTypecheck].
func RunTests(dir string, o Options, out io.Writer) error {
if o.Timeout == 0 {
o.Timeout = 5 * time.Minute
if o.Bench != "" {
o.Timeout = 30 * time.Minute
}
}
gs, err := exec.LookPath("goscript")
if err != nil {
return fmt.Errorf("goscript must be installed (core setup -js): %w", err)
}
if _, err := exec.LookPath("bun"); err != nil {
return fmt.Errorf("bun must be installed (core setup -js): %w", err)
}
work, err := os.MkdirTemp("", "goscript-test-")
if err != nil {
return err
}
defer os.RemoveAll(work)
// the options of goscript test
args := []string{"test", "--workdir", work, "--timeout", o.Timeout.String()}
if o.Run != "" {
args = append(args, "--run", o.Run)
} else if o.Bench != "" {
args = append(args, "--run", "^$")
}
if o.Bench != "" {
args = append(args, "--bench", o.Bench)
if o.BenchTime != "" {
args = append(args, "--benchtime", o.BenchTime)
}
}
if o.Browser {
args = append(args, "--browser")
if o.BrowserChannel != "" {
args = append(args, "--browser-channel", o.BrowserChannel)
}
for _, a := range o.BrowserArgs {
args = append(args, "--browser-arg="+a)
}
}
if len(o.Tags) > 0 {
args = append(args, "--tags", strings.Join(o.Tags, ","))
}
// the goscript overrides of the dependencies, as core build js uses
// (such as those of the mvm interpreter)
overrides, err := overrideDirs(dir, append([]string{"goscript"}, o.Tags...))
if err != nil {
return err
}
for _, od := range overrides {
args = append(args, "--gs-path", od)
}
if o.Verbose {
args = append(args, "-v")
}
args = append(args, ".")
// the environment of goscript test
cmd := exec.Command(gs, args...)
cmd.Dir = dir
cmd.Env = append(os.Environ(), "NO_COLOR=1", "FORCE_COLOR=0")
if o.SkipTypecheck {
// goscript type checks with the tsrs it finds first on the PATH,
// so one that checks nothing skips it
bin := filepath.Join(work, "bin")
noop := filepath.Join(bin, "tsrs")
script := "#!/bin/sh\nexit 0\n"
if runtime.GOOS == "windows" {
noop += ".cmd"
script = "@exit /b 0\r\n"
}
if err := os.MkdirAll(bin, 0o755); err != nil {
return err
}
if err := os.WriteFile(noop, []byte(script), 0o755); err != nil {
return err
}
cmd.Env = append(cmd.Env, "PATH="+bin+string(os.PathListSeparator)+os.Getenv("PATH"))
}
// the tests compiled to JavaScript get runtime.GOROOT from the environment
if os.Getenv("GOROOT") == "" {
if goroot, err := exec.Command("go", "env", "GOROOT").Output(); err == nil {
cmd.Env = append(cmd.Env, "GOROOT="+strings.TrimSpace(string(goroot)))
}
}
// the output is also kept to find the failing tests
var buf strings.Builder
cmd.Stdout = io.MultiWriter(out, &buf)
cmd.Stderr = cmd.Stdout
if err := cmd.Run(); err != nil {
// (goscript test can print the output twice)
var failed []string
seen := map[string]bool{}
for _, m := range failRegexp.FindAllStringSubmatch(buf.String(), -1) {
if !seen[m[1]] {
seen[m[1]] = true
failed = append(failed, m[1])
}
}
if len(failed) > 0 {
return fmt.Errorf("goscript tests failed: %s (%w)", strings.Join(failed, ", "), err)
}
return fmt.Errorf("goscript test failed: %w", err)
}
return nil
}
// failRegexp matches the names of failing tests in the output of goscript test.
var failRegexp = regexp.MustCompile(`(?m)^\s*--- FAIL: (\S+)`)
// PackageOptions returns the options of the runs of the tests of the
// package in the given directory that its test files give with [Directive]
// lines, in the order of the files and lines (none if it has no such line).
func PackageOptions(dir string) ([]Options, error) {
files, err := filepath.Glob(filepath.Join(dir, "*_test.go"))
if err != nil {
return nil, err
}
var opts []Options
for _, fn := range files {
f, err := os.Open(fn)
if err != nil {
return nil, err
}
sc := bufio.NewScanner(f)
for sc.Scan() {
rest, ok := strings.CutPrefix(strings.TrimSpace(sc.Text()), Directive)
if !ok || (rest != "" && rest[0] != ' ' && rest[0] != '\t') {
continue
}
o, err := parseDirective(rest)
if err != nil {
f.Close()
return nil, fmt.Errorf("%s: %w", fn, err)
}
opts = append(opts, o)
}
f.Close()
if err := sc.Err(); err != nil {
return nil, err
}
}
return opts, nil
}
// parseDirective returns the options of the given fields of a [Directive].
func parseDirective(s string) (Options, error) {
var o Options
for _, fld := range strings.Fields(s) {
name, value, _ := strings.Cut(fld, "=")
switch name {
case "browser":
o.Browser = true
case "browser-arg":
o.BrowserArgs = append(o.BrowserArgs, value)
case "run":
o.Run = value
case "timeout":
d, err := time.ParseDuration(value)
if err != nil {
return o, fmt.Errorf("%s timeout: %w", Directive, err)
}
o.Timeout = d
case "skip-typecheck":
o.SkipTypecheck = true
case "tags":
o.Tags = append(o.Tags, strings.Split(value, ",")...)
default:
return o, fmt.Errorf("%s: unknown option %q", Directive, fld)
}
}
return o, nil
}
// overrideDirs returns the gsoverride directories of the modules of the
// dependencies of the package in the given directory, built with the
// given tags for js, as core build js does (see cmd/web).
func overrideDirs(dir string, tags []string) ([]string, error) {
cmd := exec.Command("go", "list", "-deps", "-tags", strings.Join(tags, ","), "-f", "{{with .Module}}{{.Dir}}{{end}}", ".")
cmd.Dir = dir
cmd.Env = append(os.Environ(), "GOOS=js", "GOARCH=wasm")
out, err := cmd.Output()
if err != nil {
return nil, fmt.Errorf("goscript: listing the modules of the dependencies: %w", err)
}
var dirs []string
seen := map[string]bool{}
for d := range strings.SplitSeq(string(out), "\n") {
d = strings.TrimSpace(d)
if d == "" || seen[d] {
continue
}
seen[d] = true
gs := filepath.Join(d, "gsoverride")
if info, err := os.Stat(gs); err == nil && info.IsDir() {
dirs = append(dirs, gs)
}
}
return dirs, nil
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package indent provides indentation generation methods.
package indent
//go:generate core generate
import (
"bytes"
"strings"
)
// Character is the type of indentation character to use.
type Character int32 //enums:enum
const (
// Tab indicates to use tabs for indentation.
Tab Character = iota
// Space indicates to use spaces for indentation.
Space
)
// Tabs returns a string of n tabs.
func Tabs(n int) string {
return strings.Repeat("\t", n)
}
// TabBytes returns []byte of n tabs.
func TabBytes(n int) []byte {
return bytes.Repeat([]byte("\t"), n)
}
// Spaces returns a string of n*width spaces.
func Spaces(n, width int) string {
return strings.Repeat(" ", n*width)
}
// SpaceBytes returns a []byte of n*width spaces.
func SpaceBytes(n, width int) []byte {
return bytes.Repeat([]byte(" "), n*width)
}
// String returns a string of n tabs or n*width spaces depending on the indent character.
func String(ich Character, n, width int) string {
if ich == Tab {
return Tabs(n)
}
return Spaces(n, width)
}
// Bytes returns []byte of n tabs or n*width spaces depending on the indent character.
func Bytes(ich Character, n, width int) []byte {
if ich == Tab {
return TabBytes(n)
}
return SpaceBytes(n, width)
}
// Len returns the length of the indent string given indent character and indent level.
func Len(ich Character, n, width int) int {
if ich == Tab {
return n
}
return n * width
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package iox provides boilerplate wrapper functions for the Go standard
// io functions to Read, Open, Write, and Save, with implementations for
// commonly used encoding formats.
package iox
import (
"bufio"
"bytes"
"io"
"io/fs"
"os"
)
// Decoder is an interface for standard decoder types
type Decoder interface {
// Decode decodes from io.Reader specified at creation
Decode(v any) error
}
// DecoderFunc is a function that creates a new Decoder for given reader
type DecoderFunc func(r io.Reader) Decoder
// NewDecoderFunc returns a DecoderFunc for a specific Decoder type
func NewDecoderFunc[T Decoder](f func(r io.Reader) T) DecoderFunc {
return func(r io.Reader) Decoder { return f(r) }
}
// Open reads the given object from the given filename using the given [DecoderFunc]
func Open(v any, filename string, f DecoderFunc) error {
fp, err := os.Open(filename)
if err != nil {
return err
}
defer fp.Close()
return Read(v, bufio.NewReader(fp), f)
}
// OpenFiles reads the given object from the given filenames using the given [DecoderFunc]
func OpenFiles(v any, filenames []string, f DecoderFunc) error {
for _, file := range filenames {
err := Open(v, file, f)
if err != nil {
return err
}
}
return nil
}
// OpenFS reads the given object from the given filename using the given [DecoderFunc],
// using the given [fs.FS] filesystem (e.g., for embed files)
func OpenFS(v any, fsys fs.FS, filename string, f DecoderFunc) error {
fp, err := fsys.Open(filename)
if err != nil {
return err
}
defer fp.Close()
return Read(v, bufio.NewReader(fp), f)
}
// OpenFilesFS reads the given object from the given filenames using the given [DecoderFunc],
// using the given [fs.FS] filesystem (e.g., for embed files)
func OpenFilesFS(v any, fsys fs.FS, filenames []string, f DecoderFunc) error {
for _, file := range filenames {
err := OpenFS(v, fsys, file, f)
if err != nil {
return err
}
}
return nil
}
// Read reads the given object from the given reader,
// using the given [DecoderFunc]
func Read(v any, reader io.Reader, f DecoderFunc) error {
d := f(reader)
return d.Decode(v)
}
// ReadBytes reads the given object from the given bytes,
// using the given [DecoderFunc]
func ReadBytes(v any, data []byte, f DecoderFunc) error {
b := bytes.NewBuffer(data)
return Read(v, b, f)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package iox
import (
"bufio"
"bytes"
"io"
"os"
)
// Encoder is an interface for standard encoder types
type Encoder interface {
// Encode encodes to io.Writer specified at creation
Encode(v any) error
}
// EncoderFunc is a function that creates a new Encoder for given writer
type EncoderFunc func(w io.Writer) Encoder
// NewEncoderFunc returns a EncoderFunc for a specific Encoder type
func NewEncoderFunc[T Encoder](f func(w io.Writer) T) EncoderFunc {
return func(w io.Writer) Encoder { return f(w) }
}
// Save writes the given object to the given filename using the given [EncoderFunc]
func Save(v any, filename string, f EncoderFunc) error {
fp, err := os.Create(filename)
if err != nil {
return err
}
defer fp.Close()
bw := bufio.NewWriter(fp)
err = Write(v, bw, f)
if err != nil {
return err
}
return bw.Flush()
}
// Write writes the given object using the given [EncoderFunc]
func Write(v any, writer io.Writer, f EncoderFunc) error {
e := f(writer)
return e.Encode(v)
}
// WriteBytes writes the given object, returning bytes of the encoding,
// using the given [EncoderFunc]
func WriteBytes(v any, f EncoderFunc) ([]byte, error) {
var b bytes.Buffer
e := f(&b)
err := e.Encode(v)
if err != nil {
return nil, err
}
return b.Bytes(), nil
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package gzipx provides a convenience wrapper for gzip encoding
// for reader and writer.
package gzipx
import (
"compress/gzip"
"io"
"io/fs"
"os"
"path/filepath"
)
// Open opens given file and calls the given function on it,
// first detecting whether the filename has a .gz extension,
// and adding an gzip reader if so.
func Open(filename string, fun func(gzr io.Reader) error) error {
fp, err := os.Open(filename)
if err != nil {
return err
}
defer fp.Close()
ext := filepath.Ext(filename)
if ext == ".gz" {
return Read(fp, fun)
}
return fun(fp)
}
// OpenFS opens given file from filesystem and calls the given function on it,
// first detecting whether the filename has a .gz extension,
// and adding a gzip reader if so.
func OpenFS(fsys fs.FS, filename string, fun func(gzr io.Reader) error) error {
fp, err := fsys.Open(filename)
if err != nil {
return err
}
defer fp.Close()
ext := filepath.Ext(filename)
if ext == ".gz" {
return Read(fp, fun)
}
return fun(fp)
}
// Read adds a gzip reader to the given reader,
// and calls the given function with the unzip reader,
// returning the error from that function.
func Read(r io.Reader, fun func(gzr io.Reader) error) error {
gzr, err := gzip.NewReader(r)
if err != nil {
return err
}
defer gzr.Close()
return fun(gzr)
}
// Save opens given file and calls the given function on it,
// first detecting whether the filename has a .gz extension,
// and adding a gzip writer if so.
func Save(filename string, fun func(gzw io.Writer) error) error {
fp, err := os.Create(filename)
if err != nil {
return err
}
defer fp.Close()
ext := filepath.Ext(filename)
if ext == ".gz" {
return Write(fp, fun)
}
return fun(fp)
}
// Write adds a gzip writer to the given writer,
// and calls the given function with the gzip writer,
// returning the error from that function.
func Write(w io.Writer, fun func(gzw io.Writer) error) error {
gzw := gzip.NewWriter(w)
err := fun(gzw)
// closing writes the end of the gzip data, which can fail
if cerr := gzw.Close(); err == nil {
err = cerr
}
return err
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package imagex
import (
"bytes"
"encoding/base64"
"image"
"strings"
"cogentcore.org/core/base/errors"
)
// ToBase64 returns bytes of image encoded in given format,
// in Base64 encoding with "image/format" mimetype returned
func ToBase64(img image.Image, f Formats) ([]byte, string) {
ibuf := &bytes.Buffer{}
Write(img, ibuf, f)
ib := ibuf.Bytes()
eb := make([]byte, base64.StdEncoding.EncodedLen(len(ib)))
base64.StdEncoding.Encode(eb, ib)
return eb, "image/" + strings.ToLower(f.String())
}
// Base64SplitLines splits the encoded Base64 bytes into standard lines of 76
// chars each. The last line also ends in a newline
func Base64SplitLines(b []byte) []byte {
ll := 76
sz := len(b)
nl := (sz / ll)
rb := make([]byte, sz+nl+1)
for i := range nl {
st := ll * i
rst := ll*i + i
copy(rb[rst:rst+ll], b[st:st+ll])
rb[rst+ll] = '\n'
}
st := ll * nl
rst := ll*nl + nl
ln := sz - st
if ln == 0 && nl > 0 { // the last full line already ends with a newline
return rb[:rst]
}
copy(rb[rst:rst+ln], b[st:st+ln])
rb[rst+ln] = '\n'
return rb
}
// FromBase64 returns image from Base64-encoded bytes
func FromBase64(eb []byte) (image.Image, Formats, error) {
if len(eb) > 76 && eb[76] == ' ' {
eb = bytes.ReplaceAll(eb, []byte(" "), []byte("\n"))
}
db := make([]byte, base64.StdEncoding.DecodedLen(len(eb)))
_, err := base64.StdEncoding.Decode(db, eb)
if err != nil {
return nil, None, errors.Log(err)
}
return Read(bytes.NewReader(db))
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !js
package imagex
import (
"image"
"io"
)
// decode decodes an image from the given reader, turning JPEG images
// upright as their EXIF orientation says (see [decodeOriented]).
func decode(r io.Reader) (image.Image, string, error) {
b, err := io.ReadAll(r)
if err != nil {
return nil, "", err
}
return decodeOriented(b)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package imagex provides utilities for images: opening, saving, and
// encoding them in the standard formats, wrapping them for the web, and
// asserting them in tests.
package imagex
//go:generate core generate
import (
"bufio"
"errors"
"fmt"
"image"
"image/gif"
"image/jpeg"
"image/png"
"io"
"io/fs"
"os"
"path/filepath"
"strings"
"golang.org/x/image/bmp"
"golang.org/x/image/tiff"
_ "golang.org/x/image/webp"
)
// Formats are the supported image encoding / decoding formats
type Formats int32 //enums:enum
// The supported image encoding formats
const (
None Formats = iota
PNG
JPEG
GIF
TIFF
BMP
WebP
)
// ExtToFormat returns a Format based on a filename extension,
// which can start with a . or not
func ExtToFormat(ext string) (Formats, error) {
if len(ext) == 0 {
return None, errors.New("ExtToFormat: ext is empty")
}
if ext[0] == '.' {
ext = ext[1:]
}
ext = strings.ToLower(ext)
switch ext {
case "png":
return PNG, nil
case "jpg", "jpeg":
return JPEG, nil
case "gif":
return GIF, nil
case "tif", "tiff":
return TIFF, nil
case "bmp":
return BMP, nil
case "webp":
return WebP, nil
}
return None, fmt.Errorf("ExtToFormat: extension %q not recognized", ext)
}
// Open opens an image from the given filename.
// The format is inferred automatically,
// and is returned using the Formats enum.
// png, jpeg, gif, tiff, bmp, and webp are supported.
func Open(filename string) (image.Image, Formats, error) {
file, err := os.Open(filename)
if err != nil {
return nil, None, err
}
defer file.Close()
return Read(file)
}
// OpenFS opens an image from the given filename
// using the given [fs.FS] filesystem (e.g., for embed files).
// The format is inferred automatically,
// and is returned using the Formats enum.
// png, jpeg, gif, tiff, bmp, and webp are supported.
func OpenFS(fsys fs.FS, filename string) (image.Image, Formats, error) {
file, err := fsys.Open(filename)
if err != nil {
return nil, None, err
}
defer file.Close()
return Read(file)
}
// Read reads an image to the given reader,
// The format is inferred automatically,
// and is returned using the Formats enum.
// png, jpeg, gif, tiff, bmp, and webp are supported.
// On the web, the browser decodes the formats that it supports,
// which is much faster, and the result is a [JSRGBA].
func Read(r io.Reader) (image.Image, Formats, error) {
im, ext, err := decode(r)
if err != nil {
return im, None, err
}
f, err := ExtToFormat(ext)
return im, f, err
}
// Save saves the image to the given filename,
// with the format inferred from the filename.
// png, jpeg, gif, tiff, and bmp are supported.
func Save(im image.Image, filename string) error {
ext := filepath.Ext(filename)
f, err := ExtToFormat(ext)
if err != nil {
return err
}
file, err := os.Create(filename)
if err != nil {
return err
}
defer file.Close()
bw := bufio.NewWriter(file)
if err := Write(im, bw, f); err != nil {
return err
}
return bw.Flush()
}
// Write writes the image to the given writer using the given foramt.
// png, jpeg, gif, tiff, and bmp are supported.
// It [Unwrap]s any [Wrapped] images.
func Write(im image.Image, w io.Writer, f Formats) error {
im = Unwrap(im)
switch f {
case PNG:
return png.Encode(w, im)
case JPEG:
return jpeg.Encode(w, im, &jpeg.Options{Quality: 90})
case GIF:
return gif.Encode(w, im, nil)
case TIFF:
return tiff.Encode(w, im, nil)
case BMP:
return bmp.Encode(w, im)
default:
return fmt.Errorf("iox/imagex.Save: format %q not valid", f)
}
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package imagex
import (
"bytes"
"encoding/json"
"image"
)
// JSON is a wrapper around an [image.Image] that defines JSON
// Marshal and Unmarshal methods, so that the image will automatically
// be properly saved / loaded when used as a struct field, for example.
// Must be a pointer type to support custom unmarshal function.
// The original image is not anonymously embedded so that you have to
// extract it, otherwise it will be processed inefficiently.
type JSON struct {
Image image.Image
}
// JSONEncoded is a representation of an image encoded into a byte stream,
// using the PNG encoder. This can be Marshal and Unmarshal'd directly.
type JSONEncoded struct {
Width int
Height int
// Image is the encoded byte stream, which will be encoded in JSON
// using Base64
Image []byte
}
// NewJSON returns a new JSON wrapper around given image,
// to support automatic wrapping and unwrapping.
func NewJSON(im image.Image) *JSON {
return &JSON{Image: im}
}
func (js *JSON) MarshalJSON() ([]byte, error) {
id := &JSONEncoded{}
if js.Image != nil {
sz := js.Image.Bounds().Size()
id.Width = sz.X
id.Height = sz.Y
ibuf := &bytes.Buffer{}
Write(js.Image, ibuf, PNG)
id.Image = ibuf.Bytes()
}
return json.Marshal(id)
}
func (js *JSON) UnmarshalJSON(b []byte) error {
id := &JSONEncoded{}
err := json.Unmarshal(b, id)
if err != nil || (id.Width == 0 && id.Height == 0) {
js.Image = nil
return err
}
im, _, err := image.Decode(bytes.NewReader(id.Image))
if err != nil {
js.Image = nil
return err
}
js.Image = im
return nil
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package imagex
import (
"bytes"
"encoding/binary"
"image"
"image/draw"
)
// jpegOrientation returns the EXIF orientation (1 to 8) of the given JPEG
// data, as set by cameras that save the pixels as the sensor has them,
// and say how to turn them to be upright, or 1 (as they are) if it has
// none or it cannot be read.
func jpegOrientation(b []byte) int {
if len(b) < 4 || b[0] != 0xFF || b[1] != 0xD8 {
return 1
}
i := 2
for i+4 <= len(b) {
if b[i] != 0xFF {
return 1
}
marker := b[i+1]
if marker == 0xD8 || (marker >= 0xD0 && marker <= 0xD7) || marker == 0x01 {
i += 2
continue
}
if marker == 0xDA || marker == 0xD9 { // start of scan, end: no more metadata
return 1
}
n := int(binary.BigEndian.Uint16(b[i+2:]))
end := i + 2 + n
if n < 2 || end > len(b) {
return 1
}
seg := b[i+4 : end]
if marker == 0xE1 && bytes.HasPrefix(seg, []byte("Exif\x00\x00")) {
return exifOrientation(seg[6:])
}
i = end
}
return 1
}
// exifOrientation returns the orientation tag of the first IFD of the
// given TIFF data of EXIF, or 1 if it has none.
func exifOrientation(t []byte) int {
if len(t) < 8 {
return 1
}
var bo binary.ByteOrder
switch string(t[:2]) {
case "II":
bo = binary.LittleEndian
case "MM":
bo = binary.BigEndian
default:
return 1
}
off := int(bo.Uint32(t[4:]))
if off < 8 || off+2 > len(t) {
return 1
}
count := int(bo.Uint16(t[off:]))
for k := range count {
e := off + 2 + 12*k
if e+12 > len(t) {
return 1
}
if bo.Uint16(t[e:]) == 0x0112 { // Orientation, a SHORT
o := int(bo.Uint16(t[e+8:]))
if o >= 1 && o <= 8 {
return o
}
return 1
}
}
return 1
}
// orient returns the given image turned upright for the given EXIF
// orientation: 2 mirrored, 3 turned 180°, 4 flipped, 5 transposed,
// 6 turned 90° clockwise, 7 transversed, and 8 turned 90° counterclockwise.
func orient(im image.Image, o int) image.Image {
if o <= 1 || o > 8 {
return im
}
b := im.Bounds()
w, h := b.Dx(), b.Dy()
src := image.NewRGBA(image.Rect(0, 0, w, h))
draw.Draw(src, src.Bounds(), im, b.Min, draw.Src)
dw, dh := w, h
if o >= 5 {
dw, dh = h, w
}
dst := image.NewRGBA(image.Rect(0, 0, dw, dh))
for y := range h {
for x := range w {
var dx, dy int
switch o {
case 2:
dx, dy = w-1-x, y
case 3:
dx, dy = w-1-x, h-1-y
case 4:
dx, dy = x, h-1-y
case 5:
dx, dy = y, x
case 6:
dx, dy = h-1-y, x
case 7:
dx, dy = h-1-y, w-1-x
case 8:
dx, dy = y, w-1-x
}
si := src.PixOffset(x, y)
di := dst.PixOffset(dx, dy)
copy(dst.Pix[di:di+4], src.Pix[si:si+4])
}
}
return dst
}
// decodeOriented decodes the given image data in Go, turning JPEG images
// upright as their EXIF orientation says (see [jpegOrientation]), as
// browsers and image viewers show them.
func decodeOriented(b []byte) (image.Image, string, error) {
im, format, err := image.Decode(bytes.NewReader(b))
if err != nil || format != "jpeg" {
return im, format, err
}
return orient(im, jpegOrientation(b)), format, nil
}
// Copyright 2023 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package imagex
import (
"errors"
"image"
"image/color"
"io/fs"
"os"
"path/filepath"
"strings"
"cogentcore.org/core/base/num"
)
// TestingT is an interface wrapper around *testing.T
type TestingT interface {
Errorf(format string, args ...any)
}
// UpdateTestImages indicates whether to update currently saved test
// images in [AssertImage] instead of comparing against them.
// It is automatically set if the build tag "update" is specified,
// or if the environment variable "CORE_UPDATE_TESTDATA" is set to "true".
// It should typically only be set through those methods. It should only be
// set when behavior has been updated that causes test images to change,
// and it should only be set once and then turned back off.
var UpdateTestImages = updateTestImages
// UpdateTestImagesFor turns on [UpdateTestImages] for the given test, for
// images that are only for looking at, which are not compared, and restores
// its previous value at the end of the test, so that the update mode of the
// build tag or environment variable still applies to the other tests.
func UpdateTestImagesFor(t interface{ Cleanup(func()) }) {
prev := UpdateTestImages
UpdateTestImages = true
t.Cleanup(func() { UpdateTestImages = prev })
}
// Uint8Equal returns true if two numbers are within tol
func Uint8Equal(cc, ic uint8, tol int) bool {
d := int(cc) - int(ic)
if d < -tol {
return false
}
if d > tol {
return false
}
return true
}
// ColorsEqual returns true if two colors equal within tol
func ColorsEqual(cc, ic color.RGBA, tol int) bool {
if !Uint8Equal(cc.R, ic.R, tol) {
return false
}
if !Uint8Equal(cc.G, ic.G, tol) {
return false
}
if !Uint8Equal(cc.B, ic.B, tol) {
return false
}
if !Uint8Equal(cc.A, ic.A, tol) {
return false
}
return true
}
// DiffImage returns the difference between two images,
// with pixels having the abs of the difference between pixels.
// Images must have the same bounds.
func DiffImage(a, b image.Image) image.Image {
ab := a.Bounds()
di := image.NewRGBA(ab)
for y := ab.Min.Y; y < ab.Max.Y; y++ {
for x := ab.Min.X; x < ab.Max.X; x++ {
cc := color.RGBAModel.Convert(a.At(x, y)).(color.RGBA)
ic := color.RGBAModel.Convert(b.At(x, y)).(color.RGBA)
r := uint8(num.Abs(int(cc.R) - int(ic.R)))
g := uint8(num.Abs(int(cc.G) - int(ic.G)))
b := uint8(num.Abs(int(cc.B) - int(ic.B)))
c := color.RGBA{r, g, b, 255}
di.Set(x, y, c)
}
}
return di
}
// ImagesEqual compares two images, returns false if not equal,
// based on bounds or content. If a content difference, then
// the colors and pixel where they first differ are returned.
// The first image is considered the reference, correct one.
// Tol is the color tolerance.
func ImagesEqual(a, b image.Image, tol int) (bounds, content bool, ac, bc color.RGBA, x, y int) {
abounds := a.Bounds()
bbounds := b.Bounds()
if bbounds != abounds {
return
}
bounds = true
for y = abounds.Min.Y; y < abounds.Max.Y; y++ {
for x = abounds.Min.X; x < abounds.Max.X; x++ {
ac = color.RGBAModel.Convert(a.At(x, y)).(color.RGBA)
bc = color.RGBAModel.Convert(b.At(x, y)).(color.RGBA)
if !ColorsEqual(ac, bc, tol) {
return
}
}
}
content = true
return
}
// Assert asserts that the given image is equivalent
// to the image stored at the given filename in the testdata directory,
// with ".png" added to the filename if there is no extension
// (eg: "button" becomes "testdata/button.png"). Forward slashes are
// automatically replaced with backslashes on Windows.
// If it is not, it fails the test with an error, but continues its
// execution. If there is no image at the given filename in the testdata
// directory, it creates the image.
// optional tolerance argument specifies the maximum color difference,
// which defaults to 10.
func Assert(t TestingT, img image.Image, filename string, tols ...int) {
filename = filepath.Join("testdata", filename)
if filepath.Ext(filename) == "" {
filename += ".png"
}
err := os.MkdirAll(filepath.Dir(filename), 0750)
if err != nil {
t.Errorf("error making testdata directory: %v", err)
}
tol := 10
if len(tols) == 1 {
tol = tols[0]
}
ext := filepath.Ext(filename)
failFilename := strings.TrimSuffix(filename, ext) + ".fail" + ext
diffFilename := strings.TrimSuffix(filename, ext) + ".diff" + ext
if UpdateTestImages {
// an existing image with exactly the same pixels is kept, so that
// its file only changes when the image does, not when the png
// encoding does (as with a different version of Go).
if fimg, _, err := Open(filename); err == nil {
if bounds, content, _, _, _, _ := ImagesEqual(fimg, img, 0); bounds && content {
os.RemoveAll(failFilename)
os.RemoveAll(diffFilename)
return
}
}
err := Save(img, filename)
if err != nil {
t.Errorf("AssertImage: error saving updated image: %v", err)
}
err = os.RemoveAll(failFilename)
if err != nil {
t.Errorf("AssertImage: error removing old fail image: %v", err)
}
os.RemoveAll(diffFilename)
return
}
fimg, _, err := Open(filename)
if err != nil {
if !errors.Is(err, fs.ErrNotExist) {
t.Errorf("AssertImage: error opening saved image: %v", err)
return
}
// we don't have the file yet, so we make it
err := Save(img, filename)
if err != nil {
t.Errorf("AssertImage: error saving new image: %v", err)
}
return
}
// TODO(#1456): reduce tolerance to 1 after we fix rendering inconsistencies
bounds, content, ac, bc, x, y := ImagesEqual(fimg, img, tol)
if !bounds || !content {
if !bounds {
t.Errorf("AssertImage: expected bounds %v for image for %s, but got bounds %v; see %s", fimg.Bounds(), filename, img.Bounds(), failFilename)
} else {
t.Errorf("AssertImage: image for %s is not the same as expected; see %s; expected color %v at (%d, %d), but got %v", filename, failFilename, ac, x, y, bc)
}
err := Save(img, failFilename)
if err != nil {
t.Errorf("AssertImage: error saving fail image: %v", err)
}
err = Save(DiffImage(img, fimg), diffFilename)
if err != nil {
t.Errorf("AssertImage: error saving diff image: %v", err)
}
} else {
err := os.RemoveAll(failFilename)
if err != nil {
t.Errorf("AssertImage: error removing old fail image: %v", err)
}
os.RemoveAll(diffFilename)
}
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !js
package imagex
import (
"image"
"image/draw"
"github.com/anthonynsimon/bild/transform"
)
// JSRGBA is a dummy version of this type so code does not have to be
// conditionalized.
type JSRGBA struct {
*image.RGBA
}
// WrapJS returns a JavaScript optimized wrapper around the given
// [image.Image] on web, and just returns the image on other platforms.
func WrapJS(src image.Image) image.Image {
return src
}
// Resize returns a resized version of the source image (which can be
// [Wrapped]), returning a [WrapJS] image handle on web and using web-native
// optimized code. Otherwise, uses medium quality Linear resize.
func Resize(src image.Image, size image.Point) image.Image {
return transform.Resize(src, size.X, size.Y, transform.Linear)
}
// Crop returns a cropped region of the source image (which can be
// [Wrapped]), returning a [WrapJS] image handle on web and using web-native
// optimized code. The rectangle is relative to the origin of the source
// bounds, and the result has its origin at (0, 0); any part of the
// rectangle outside of the source is transparent.
func Crop(src image.Image, rect image.Rectangle) image.Image {
src = Unwrap(src)
dst := image.NewRGBA(image.Rectangle{Max: rect.Size()})
draw.Draw(dst, dst.Bounds(), src, src.Bounds().Min.Add(rect.Min), draw.Src)
return dst
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package imagex
import (
"image"
"github.com/anthonynsimon/bild/clone"
)
// Wrapped extends the [image.Image] interface with two methods that manage
// the wrapping of an underlying Go [image.Image]. This can be used for images that
// are actually GPU textures, and to manage JavaScript pointers on the js platform.
type Wrapped interface {
image.Image
// Update is called whenever the image data has been updated,
// to update any additional data based on the new image.
// This may copy an image to the GPU or update JavaScript pointers.
Update()
// Underlying returns the underlying image.Image, which should
// be called whenever passing the image to some other Go-based
// function that is likely to be optimized for different image types,
// such as [draw.Draw]. Do NOT use this for functions that will
// directly handle the wrapped image!
Underlying() image.Image
}
// Update calls [Wrapped.Update] on a [Wrapped] if it is one.
// It does nothing otherwise.
func Update(src image.Image) {
if wr, ok := src.(Wrapped); ok {
wr.Update()
}
}
// Unwrap calls [Wrapped.Underlying] on a [Wrapped] if it is one.
// It returns the original image otherwise.
func Unwrap(src image.Image) image.Image {
if wr, ok := src.(Wrapped); ok {
return wr.Underlying()
}
return src
}
// CloneAsRGBA returns an [*image.RGBA] copy of the supplied image.
// It calls [Unwrap] first. See also [AsRGBA].
func CloneAsRGBA(src image.Image) *image.RGBA {
return clone.AsRGBA(Unwrap(src))
}
// AsRGBA returns the image as an [*image.RGBA]. If it already is one,
// it returns that image directly. Otherwise it returns a clone.
// It calls [Unwrap] first. See also [CloneAsRGBA].
func AsRGBA(src image.Image) *image.RGBA {
return clone.AsShallowRGBA(Unwrap(src))
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package jsonx provides functions for opening, reading, saving, and writing
// values in JSON.
package jsonx
import (
"encoding/json"
"io"
"io/fs"
"cogentcore.org/core/base/iox"
)
// Open reads the given object from the given filename using JSON encoding
func Open(v any, filename string) error {
return iox.Open(v, filename, iox.NewDecoderFunc(json.NewDecoder))
}
// OpenFiles reads the given object from the given filenames using JSON encoding
func OpenFiles(v any, filenames ...string) error {
return iox.OpenFiles(v, filenames, iox.NewDecoderFunc(json.NewDecoder))
}
// OpenFS reads the given object from the given filename using JSON encoding,
// using the given [fs.FS] filesystem (e.g., for embed files)
func OpenFS(v any, fsys fs.FS, filename string) error {
return iox.OpenFS(v, fsys, filename, iox.NewDecoderFunc(json.NewDecoder))
}
// OpenFilesFS reads the given object from the given filenames using JSON encoding,
// using the given [fs.FS] filesystem (e.g., for embed files)
func OpenFilesFS(v any, fsys fs.FS, filenames ...string) error {
return iox.OpenFilesFS(v, fsys, filenames, iox.NewDecoderFunc(json.NewDecoder))
}
// Read reads the given object from the given reader,
// using JSON encoding
func Read(v any, reader io.Reader) error {
return iox.Read(v, reader, iox.NewDecoderFunc(json.NewDecoder))
}
// ReadBytes reads the given object from the given bytes,
// using JSON encoding
func ReadBytes(v any, data []byte) error {
return iox.ReadBytes(v, data, iox.NewDecoderFunc(json.NewDecoder))
}
// Save writes the given object to the given filename using JSON encoding
func Save(v any, filename string) error {
return iox.Save(v, filename, iox.NewEncoderFunc(json.NewEncoder))
}
// Write writes the given object using JSON encoding
func Write(v any, writer io.Writer) error {
return iox.Write(v, writer, iox.NewEncoderFunc(json.NewEncoder))
}
// WriteBytes writes the given object, returning bytes of the encoding,
// using JSON encoding
func WriteBytes(v any) ([]byte, error) {
return iox.WriteBytes(v, iox.NewEncoderFunc(json.NewEncoder))
}
// IndentEncoderFunc is a [iox.EncoderFunc] that sets indentation
var IndentEncoderFunc = func(w io.Writer) iox.Encoder {
e := json.NewEncoder(w)
e.SetIndent("", "\t")
return e
}
// SaveIndent writes the given object to the given filename using JSON encoding, with indentation
func SaveIndent(v any, filename string) error {
return iox.Save(v, filename, IndentEncoderFunc)
}
// WriteIndent writes the given object using JSON encoding, with indentation
func WriteIndent(v any, writer io.Writer) error {
return iox.Write(v, writer, IndentEncoderFunc)
}
// WriteBytesIndent writes the given object, returning bytes of the encoding,
// using JSON encoding, with indentation
func WriteBytesIndent(v any) ([]byte, error) {
return iox.WriteBytes(v, IndentEncoderFunc)
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tomlx
import (
"encoding"
"fmt"
"io"
"math"
"reflect"
"strconv"
"strings"
"sync"
"time"
"cogentcore.org/core/base/iox"
"github.com/BurntSushi/toml"
)
// The decoder parses TOML with [toml.Decode] into generic values, and then
// sets them on the target value, so that it reads all of the files written
// by the pelletier/go-toml/v2 encoder that tomlx used before: map keys of
// any type with a text form (strings, numbers, and types implementing
// [encoding.TextUnmarshaler], such as enums) are supported, and
// [time.Duration] values can be integer nanoseconds or duration strings.
var (
durationType = reflect.TypeFor[time.Duration]()
textUnmarshalerType = reflect.TypeFor[encoding.TextUnmarshaler]()
)
// decoder implements [iox.Decoder] for TOML.
type decoder struct {
r io.Reader
}
// NewDecoder returns a new [iox.Decoder]
func NewDecoder(r io.Reader) iox.Decoder { return &decoder{r: r} }
// Decode reads all of the TOML data from the reader and sets the
// corresponding values on v, which must be a non-nil pointer.
// Struct fields and map entries that are not in the data are not changed,
// keys that do not match a field are ignored, and slices are replaced.
func (d *decoder) Decode(v any) error {
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Pointer || rv.IsNil() {
return fmt.Errorf("toml: cannot decode into non-pointer or nil %T", v)
}
b, err := io.ReadAll(d.r)
if err != nil {
return err
}
var data map[string]any
if _, err := toml.Decode(string(b), &data); err != nil {
return err
}
return decodeValue(rv, data, "")
}
// decodeValue sets the given value from the given generic TOML data
// (as returned by [toml.Decode]) at the given dotted key path.
func decodeValue(v reflect.Value, data any, path string) error {
switch v.Kind() {
case reflect.Pointer:
if v.IsNil() {
v.Set(reflect.New(v.Type().Elem()))
}
return decodeValue(v.Elem(), data, path)
case reflect.Interface:
return decodeInterface(v, data, path)
}
if s, ok := data.(string); ok && v.CanAddr() && reflect.PointerTo(v.Type()).Implements(textUnmarshalerType) {
if err := v.Addr().Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(s)); err != nil {
return fmt.Errorf("toml: %s: %w", path, err)
}
return nil
}
switch v.Type() {
case durationType:
return decodeDuration(v, data, path)
case timeType:
if t, ok := data.(time.Time); ok {
v.Set(reflect.ValueOf(t))
return nil
}
return typeError(v, data, path)
}
switch v.Kind() {
case reflect.Struct:
return decodeStruct(v, data, path)
case reflect.Map:
return decodeMap(v, data, path)
case reflect.Slice:
return decodeSlice(v, data, path)
case reflect.Array:
return decodeArray(v, data, path)
case reflect.String:
if s, ok := data.(string); ok {
v.SetString(s)
return nil
}
case reflect.Bool:
if b, ok := data.(bool); ok {
v.SetBool(b)
return nil
}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if i, ok := toInt(data); ok {
if v.OverflowInt(i) {
return fmt.Errorf("toml: %s: %d overflows %s", path, i, v.Type())
}
v.SetInt(i)
return nil
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
if i, ok := toInt(data); ok {
if i < 0 || v.OverflowUint(uint64(i)) {
return fmt.Errorf("toml: %s: %d overflows %s", path, i, v.Type())
}
v.SetUint(uint64(i))
return nil
}
case reflect.Float32, reflect.Float64:
switch x := data.(type) {
case float64:
v.SetFloat(x)
return nil
case int64:
v.SetFloat(float64(x))
return nil
}
case reflect.Func, reflect.Chan, reflect.UnsafePointer, reflect.Complex64, reflect.Complex128:
return nil // not represented in TOML
}
return typeError(v, data, path)
}
// typeError returns an error for TOML data that cannot be set on the value.
func typeError(v reflect.Value, data any, path string) error {
return fmt.Errorf("toml: %s: cannot decode TOML %s into %s", path, tomlTypeName(data), v.Type())
}
// tomlTypeName returns the TOML type name of the given generic data.
func tomlTypeName(data any) string {
switch data.(type) {
case string:
return "string"
case int64:
return "integer"
case float64:
return "float"
case bool:
return "boolean"
case time.Time:
return "datetime"
case []any:
return "array"
case []map[string]any:
return "array of tables"
case map[string]any:
return "table"
}
return fmt.Sprintf("%T", data)
}
// toInt returns the given integer data, or float data with an integer value.
func toInt(data any) (int64, bool) {
switch x := data.(type) {
case int64:
return x, true
case float64:
if x == math.Trunc(x) && x >= math.MinInt64 && x < math.MaxInt64 {
return int64(x), true
}
}
return 0, false
}
// decodeDuration sets the given [time.Duration] value from integer
// nanoseconds (as written by tomlx) or a duration string such as "1.5s".
func decodeDuration(v reflect.Value, data any, path string) error {
if s, ok := data.(string); ok {
d, err := time.ParseDuration(s)
if err != nil {
return fmt.Errorf("toml: %s: %w", path, err)
}
v.SetInt(int64(d))
return nil
}
if i, ok := toInt(data); ok {
v.SetInt(i)
return nil
}
return typeError(v, data, path)
}
// decodeInterface sets the given interface value. If it holds a non-nil
// pointer, the data is decoded into that; otherwise, the generic value is
// set, with arrays of tables as []any.
func decodeInterface(v reflect.Value, data any, path string) error {
if !v.IsNil() && v.Elem().Kind() == reflect.Pointer && !v.Elem().IsNil() {
return decodeValue(v.Elem(), data, path)
}
gv := reflect.ValueOf(genericValue(data))
if !gv.Type().AssignableTo(v.Type()) {
return typeError(v, data, path)
}
v.Set(gv)
return nil
}
// genericValue returns the given data with arrays of tables
// converted to []any, so that all arrays are []any.
func genericValue(data any) any {
switch x := data.(type) {
case []map[string]any:
a := make([]any, len(x))
for i, m := range x {
a[i] = genericValue(m)
}
return a
case []any:
for i, e := range x {
x[i] = genericValue(e)
}
case map[string]any:
for k, e := range x {
x[k] = genericValue(e)
}
}
return data
}
// decodeStruct sets the fields of the given struct value from table data.
// Keys match field names (or toml tag names) exactly, or else ignoring case.
func decodeStruct(v reflect.Value, data any, path string) error {
m, ok := data.(map[string]any)
if !ok {
return typeError(v, data, path)
}
fields := structFields(v.Type())
for k, d := range m {
fi, ok := fields.byName[k]
if !ok {
fi, ok = fields.byFold[strings.ToLower(k)]
}
if !ok {
continue
}
f, ok := fieldByIndex(v, fi)
if !ok {
continue
}
if err := decodeValue(f, d, joinPath(path, k)); err != nil {
return err
}
}
return nil
}
// fieldByIndex returns the field of the given struct value with the given
// index path, allocating nil embedded struct pointers along the way.
func fieldByIndex(v reflect.Value, index []int) (reflect.Value, bool) {
for i, x := range index {
if i > 0 && v.Kind() == reflect.Pointer {
if v.IsNil() {
if !v.CanSet() {
return reflect.Value{}, false
}
v.Set(reflect.New(v.Type().Elem()))
}
v = v.Elem()
}
v = v.Field(x)
}
return v, v.CanSet()
}
// fieldMap maps TOML keys to the index paths of struct fields.
type fieldMap struct {
byName map[string][]int
byFold map[string][]int
}
// fieldMaps caches the [fieldMap] for each struct type.
var fieldMaps sync.Map
// structFields returns the [fieldMap] for the given struct type.
// The fields of untagged embedded structs are included as if they
// were fields of the outer struct, unless an outer field has the same name.
// The embedded structs themselves are included by their type names,
// with the lowest priority.
func structFields(typ reflect.Type) *fieldMap {
if fm, ok := fieldMaps.Load(typ); ok {
return fm.(*fieldMap)
}
fm := &fieldMap{byName: map[string][]int{}, byFold: map[string][]int{}}
addStructFields(fm, typ, nil)
fieldMaps.Store(typ, fm)
return fm
}
// addStructFields adds the fields of the given struct type to the field map,
// with the given index path prefix, outer fields before embedded ones.
func addStructFields(fm *fieldMap, typ reflect.Type, prefix []int) {
var embedded []reflect.StructField
for i := range typ.NumField() {
sf := typ.Field(i)
name, _, skip := parseTag(sf)
if skip {
continue
}
if name == "" && sf.Anonymous {
ft := sf.Type
if ft.Kind() == reflect.Pointer && sf.IsExported() {
ft = ft.Elem()
}
if ft.Kind() == reflect.Struct {
embedded = append(embedded, sf)
}
continue
}
if !sf.IsExported() {
continue
}
if name == "" {
name = sf.Name
}
index := append(append([]int{}, prefix...), i)
if _, ok := fm.byName[name]; !ok {
fm.byName[name] = index
}
if _, ok := fm.byFold[strings.ToLower(name)]; !ok {
fm.byFold[strings.ToLower(name)] = index
}
}
for _, sf := range embedded {
ft := sf.Type
if ft.Kind() == reflect.Pointer {
ft = ft.Elem()
}
addStructFields(fm, ft, append(append([]int{}, prefix...), sf.Index...))
}
// An embedded struct can also be set as a table with its type name, as
// reflectx.NonDefaultFields makes for settings, if no field has that name.
for _, sf := range embedded {
if !sf.IsExported() {
continue
}
index := append(append([]int{}, prefix...), sf.Index...)
if _, ok := fm.byName[sf.Name]; !ok {
fm.byName[sf.Name] = index
}
if _, ok := fm.byFold[strings.ToLower(sf.Name)]; !ok {
fm.byFold[strings.ToLower(sf.Name)] = index
}
}
}
// joinPath returns the given dotted key path with the given key added.
func joinPath(path, key string) string {
if path == "" {
return key
}
return path + "." + key
}
// decodeMap sets entries of the given map value from table data,
// making the map if it is nil. Each entry is decoded into a new value.
func decodeMap(v reflect.Value, data any, path string) error {
m, ok := data.(map[string]any)
if !ok {
return typeError(v, data, path)
}
if v.IsNil() {
v.Set(reflect.MakeMapWithSize(v.Type(), len(m)))
}
kt, et := v.Type().Key(), v.Type().Elem()
for k, d := range m {
kv := reflect.New(kt).Elem()
if err := setMapKey(kv, k); err != nil {
return fmt.Errorf("toml: %s: map key %q: %w", path, k, err)
}
ev := reflect.New(et).Elem()
if err := decodeValue(ev, d, joinPath(path, k)); err != nil {
return err
}
v.SetMapIndex(kv, ev)
}
return nil
}
// setMapKey sets the given map key value from its string form.
func setMapKey(k reflect.Value, s string) error {
if reflect.PointerTo(k.Type()).Implements(textUnmarshalerType) {
return k.Addr().Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(s))
}
switch k.Kind() {
case reflect.String:
k.SetString(s)
case reflect.Interface:
k.Set(reflect.ValueOf(s))
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
i, err := strconv.ParseInt(s, 10, k.Type().Bits())
if err != nil {
return err
}
k.SetInt(i)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
i, err := strconv.ParseUint(s, 10, k.Type().Bits())
if err != nil {
return err
}
k.SetUint(i)
case reflect.Float32, reflect.Float64:
f, err := strconv.ParseFloat(s, k.Type().Bits())
if err != nil {
return err
}
k.SetFloat(f)
case reflect.Bool:
b, err := strconv.ParseBool(s)
if err != nil {
return err
}
k.SetBool(b)
default:
return fmt.Errorf("unsupported map key type %s", k.Type())
}
return nil
}
// arrayData returns the elements of the given array data.
func arrayData(data any) ([]any, bool) {
switch x := data.(type) {
case []any:
return x, true
case []map[string]any:
a := make([]any, len(x))
for i, m := range x {
a[i] = m
}
return a, true
}
return nil, false
}
// decodeSlice sets the given slice value to a new slice from array data,
// or from a string for a byte slice.
func decodeSlice(v reflect.Value, data any, path string) error {
if s, ok := data.(string); ok && v.Type().Elem().Kind() == reflect.Uint8 {
v.SetBytes([]byte(s))
return nil
}
a, ok := arrayData(data)
if !ok {
return typeError(v, data, path)
}
sv := reflect.MakeSlice(v.Type(), len(a), len(a))
for i, d := range a {
if err := decodeValue(sv.Index(i), d, path+"["+strconv.Itoa(i)+"]"); err != nil {
return err
}
}
v.Set(sv)
return nil
}
// decodeArray sets the elements of the given array value from array data;
// elements beyond the data are set to zero, and data beyond the array
// length is ignored.
func decodeArray(v reflect.Value, data any, path string) error {
a, ok := arrayData(data)
if !ok {
return typeError(v, data, path)
}
for i := range v.Len() {
ev := v.Index(i)
ev.SetZero()
if i < len(a) {
if err := decodeValue(ev, a[i], path+"["+strconv.Itoa(i)+"]"); err != nil {
return err
}
}
}
return nil
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tomlx
import (
"encoding"
"fmt"
"io"
"math"
"reflect"
"slices"
"strconv"
"strings"
"time"
"cogentcore.org/core/base/iox"
)
// The encoder writes the same format as the pelletier/go-toml/v2 encoder
// (with indented tables and multiline arrays) that tomlx used before,
// so that files written by this version can be read by older versions:
// [time.Duration] values are written as integer nanoseconds, map keys of
// non-string types are written in their text form, strings use literal
// (single-quoted) form when possible, nil slices are written as empty
// arrays, and the simple values of a table come before its sub-tables,
// in struct field order (or sorted key order for maps).
var (
timeType = reflect.TypeFor[time.Time]()
textMarshalerType = reflect.TypeFor[encoding.TextMarshaler]()
)
// indentSymbol is the indentation for each level of nested tables.
const indentSymbol = " "
// encoder implements [iox.Encoder] for TOML.
type encoder struct {
w io.Writer
}
// NewEncoder returns a new [iox.Encoder]
func NewEncoder(w io.Writer) iox.Encoder {
return &encoder{w: w}
}
// Encode writes the TOML encoding of v, which must be a struct or a map
// (or a pointer to one), as TOML documents are tables.
func (e *encoder) Encode(v any) error {
rv := reflect.ValueOf(v)
for rv.Kind() == reflect.Pointer || rv.Kind() == reflect.Interface {
rv = rv.Elem()
}
if (rv.Kind() != reflect.Struct && rv.Kind() != reflect.Map) || isText(rv) {
return fmt.Errorf("toml: cannot encode %T as a TOML document: it must be a struct or a map", v)
}
b, err := encodeTable(nil, encodeContext{}, rv)
if err != nil {
return err
}
_, err = e.w.Write(b)
return err
}
// encodeContext is the context in which a value is encoded.
type encodeContext struct {
// keys is the full key path of the current table.
keys []string
// indent is the current indentation level.
indent int
// inline is whether the value is part of an inline value,
// such that tables are written as inline tables.
inline bool
// nested is whether the value is in an array, which makes
// arrays use a single line.
nested bool
}
// entry is a key and value in a table.
type entry struct {
key string
value reflect.Value
}
// table has the simple key-value entries and the sub-table entries
// (including arrays of tables) of a table, in output order.
type table struct {
kvs []entry
tables []entry
}
// add adds the given entry to the table.
func (t *table) add(ctx encodeContext, key string, v reflect.Value) {
if !ctx.inline && isTableOrArrayTable(v) {
t.tables = append(t.tables, entry{key, v})
} else {
t.kvs = append(t.kvs, entry{key, v})
}
}
// makeTable returns the table entries of the given struct or map value.
func makeTable(ctx encodeContext, v reflect.Value) (*table, error) {
t := &table{}
if v.Kind() == reflect.Struct {
walkStruct(ctx, t, v)
return t, nil
}
iter := v.MapRange()
for iter.Next() {
mv := iter.Value()
if isNil(mv) || isUnsupported(mv) {
continue
}
ks, err := keyToString(iter.Key())
if err != nil {
return nil, err
}
t.add(ctx, ks, mv)
}
byKey := func(a, b entry) int { return strings.Compare(a.key, b.key) }
slices.SortFunc(t.kvs, byKey)
slices.SortFunc(t.tables, byKey)
return t, nil
}
// walkStruct adds the exported fields of the given struct value to the table,
// with untagged embedded structs contributing their fields directly.
func walkStruct(ctx encodeContext, t *table, v reflect.Value) {
typ := v.Type()
for i := range typ.NumField() {
sf := typ.Field(i)
name, omitEmpty, skip := parseTag(sf)
if skip {
continue
}
f := v.Field(i)
if name == "" && sf.Anonymous {
if f.Kind() == reflect.Pointer && sf.IsExported() && !f.IsNil() {
f = f.Elem()
}
if f.Kind() == reflect.Struct {
walkStruct(ctx, t, f)
}
continue
}
if !sf.IsExported() {
continue
}
if name == "" {
name = sf.Name
}
if isNil(f) || isUnsupported(f) || (omitEmpty && f.IsZero()) {
continue
}
t.add(ctx, name, f)
}
}
// parseTag returns the key name from the toml tag of the given field,
// and whether the field is omitted when empty or skipped entirely.
func parseTag(sf reflect.StructField) (name string, omitEmpty, skip bool) {
tag := sf.Tag.Get("toml")
if tag == "-" {
return "", false, true
}
name, opts, _ := strings.Cut(tag, ",")
for opt := range strings.SplitSeq(opts, ",") {
if opt == "omitempty" {
omitEmpty = true
}
}
return name, omitEmpty, false
}
// encodeTable encodes the given struct or map value as a table,
// with a header unless it is the root table.
func encodeTable(b []byte, ctx encodeContext, v reflect.Value) ([]byte, error) {
t, err := makeTable(ctx, v)
if err != nil {
return nil, err
}
if len(ctx.keys) > 0 {
b = appendIndent(b, ctx.indent)
b = appendKeyPath(append(b, '['), ctx.keys)
b = append(b, "]\n"...)
ctx.indent++
}
return encodeTableBody(b, ctx, t)
}
// encodeTableBody encodes the entries of the given table,
// with the simple values first and then the sub-tables.
func encodeTableBody(b []byte, ctx encodeContext, t *table) ([]byte, error) {
var err error
for _, kv := range t.kvs {
b = appendIndent(b, ctx.indent)
b, err = encodeKeyValue(b, ctx, kv)
if err != nil {
return nil, err
}
b = append(b, '\n')
}
for i, st := range t.tables {
if i > 0 || len(t.kvs) > 0 {
b = append(b, '\n')
}
sctx := ctx
sctx.keys = append(slices.Clip(ctx.keys), st.key)
b, err = encodeSubTable(b, sctx, st.value)
if err != nil {
return nil, err
}
}
return b, nil
}
// encodeSubTable encodes the given value, which is a table or an array
// of tables, under the key path of the context.
func encodeSubTable(b []byte, ctx encodeContext, v reflect.Value) ([]byte, error) {
v = indirect(v)
if v.Kind() != reflect.Slice && v.Kind() != reflect.Array {
return encodeTable(b, ctx, v)
}
var header []byte
header = appendIndent(header, ctx.indent)
header = appendKeyPath(append(header, "[["...), ctx.keys)
header = append(header, "]]\n"...)
ctx.indent++
for i := range v.Len() {
if i > 0 {
b = append(b, '\n')
}
b = append(b, header...)
t, err := makeTable(ctx, indirect(v.Index(i)))
if err != nil {
return nil, err
}
b, err = encodeTableBody(b, ctx, t)
if err != nil {
return nil, err
}
}
return b, nil
}
// encodeKeyValue encodes the given entry as a key = value pair.
func encodeKeyValue(b []byte, ctx encodeContext, kv entry) ([]byte, error) {
b = appendKey(b, kv.key)
b = append(b, " = "...)
ctx.inline = true
return encodeValue(b, ctx, kv.value)
}
// encodeValue encodes the given value inline, as the value of a key
// or an element of an array.
func encodeValue(b []byte, ctx encodeContext, v reflect.Value) ([]byte, error) {
if v.Kind() == reflect.Interface {
if v.IsNil() {
return nil, fmt.Errorf("toml: cannot encode a nil interface value at %q", strings.Join(ctx.keys, "."))
}
v = v.Elem()
}
if v.Kind() == reflect.Pointer {
if v.IsNil() {
v = reflect.Zero(v.Type().Elem())
} else {
v = v.Elem()
}
}
if v.Type() == timeType {
t := v.Interface().(time.Time)
if t.Nanosecond() > 0 {
return t.AppendFormat(b, time.RFC3339Nano), nil
}
return t.AppendFormat(b, time.RFC3339), nil
}
if isText(v) {
text, err := textMarshaler(v).MarshalText()
if err != nil {
return nil, err
}
return appendString(b, string(text)), nil
}
switch v.Kind() {
case reflect.Map, reflect.Struct:
return encodeInlineTable(b, ctx, v)
case reflect.Slice, reflect.Array:
return encodeArray(b, ctx, v)
case reflect.String:
return appendString(b, v.String()), nil
case reflect.Bool:
return strconv.AppendBool(b, v.Bool()), nil
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return strconv.AppendInt(b, v.Int(), 10), nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
if v.Uint() > math.MaxInt64 {
return nil, fmt.Errorf("toml: cannot encode uint %d greater than the maximum int64", v.Uint())
}
return strconv.AppendUint(b, v.Uint(), 10), nil
case reflect.Float32:
return appendFloat(b, v.Float(), 32), nil
case reflect.Float64:
return appendFloat(b, v.Float(), 64), nil
}
return nil, fmt.Errorf("toml: cannot encode a value of type %s", v.Type())
}
// encodeInlineTable encodes the given struct or map as an inline table.
func encodeInlineTable(b []byte, ctx encodeContext, v reflect.Value) ([]byte, error) {
t, err := makeTable(ctx, v)
if err != nil {
return nil, err
}
b = append(b, '{')
for i, kv := range t.kvs {
if i > 0 {
b = append(b, ", "...)
}
b, err = encodeKeyValue(b, ctx, kv)
if err != nil {
return nil, err
}
}
return append(b, '}'), nil
}
// encodeArray encodes the given slice or array as an array, with one element
// per line unless it is empty or nested in another array.
func encodeArray(b []byte, ctx encodeContext, v reflect.Value) ([]byte, error) {
n := v.Len()
if n == 0 {
return append(b, "[]"...), nil
}
multiline := !ctx.nested
ectx := ctx
ectx.nested = true
b = append(b, '[')
var err error
for i := range n {
if i > 0 {
b = append(b, ',')
if !multiline {
b = append(b, ' ')
}
}
if multiline {
b = appendIndent(append(b, '\n'), ctx.indent+1)
}
b, err = encodeValue(b, ectx, v.Index(i))
if err != nil {
return nil, err
}
}
if multiline {
b = appendIndent(append(b, '\n'), ctx.indent)
}
return append(b, ']'), nil
}
// isTableOrArrayTable returns whether the given value is encoded as a table
// or as an array of tables: a non-empty array of tables.
func isTableOrArrayTable(v reflect.Value) bool {
v = indirect(v)
if v.Kind() != reflect.Slice && v.Kind() != reflect.Array {
return isTable(v)
}
if v.Len() == 0 {
return false
}
for i := range v.Len() {
if !isTable(v.Index(i)) {
return false
}
}
return true
}
// isTable returns whether the given value is encoded as a table.
func isTable(v reflect.Value) bool {
v = indirect(v)
if !v.IsValid() || v.Type() == timeType || isText(v) {
return false
}
return v.Kind() == reflect.Struct || v.Kind() == reflect.Map
}
// indirect returns the value that the given value points to, following
// pointers and interfaces, or an invalid value for nil.
func indirect(v reflect.Value) reflect.Value {
for v.Kind() == reflect.Pointer || v.Kind() == reflect.Interface {
if v.IsNil() {
return reflect.Value{}
}
v = v.Elem()
}
return v
}
// isText returns whether the given value implements [encoding.TextMarshaler],
// directly or through a pointer if it is addressable.
func isText(v reflect.Value) bool {
return v.Type().Implements(textMarshalerType) || (v.CanAddr() && reflect.PointerTo(v.Type()).Implements(textMarshalerType))
}
// textMarshaler returns the [encoding.TextMarshaler] of the given value,
// for which [isText] is true.
func textMarshaler(v reflect.Value) encoding.TextMarshaler {
if !v.Type().Implements(textMarshalerType) {
v = v.Addr()
}
return v.Interface().(encoding.TextMarshaler)
}
// isNil returns whether the given value is a nil pointer, interface, or map,
// which are not encoded. Nil slices are encoded as empty arrays.
func isNil(v reflect.Value) bool {
switch v.Kind() {
case reflect.Pointer, reflect.Interface, reflect.Map:
return v.IsNil()
}
return false
}
// isUnsupported returns whether the given value has a kind that
// cannot be represented in TOML, so it is skipped.
func isUnsupported(v reflect.Value) bool {
switch v.Kind() {
case reflect.Func, reflect.Chan, reflect.UnsafePointer, reflect.Complex64, reflect.Complex128:
return true
}
return false
}
// keyToString returns the string form of the given map key.
func keyToString(k reflect.Value) (string, error) {
if k.Kind() == reflect.Interface {
k = k.Elem()
}
switch {
case k.Kind() == reflect.String:
return k.String(), nil
case k.Type().Implements(textMarshalerType):
text, err := k.Interface().(encoding.TextMarshaler).MarshalText()
return string(text), err
}
switch k.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return strconv.FormatInt(k.Int(), 10), nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return strconv.FormatUint(k.Uint(), 10), nil
case reflect.Float32:
return strconv.FormatFloat(k.Float(), 'f', -1, 32), nil
case reflect.Float64:
return strconv.FormatFloat(k.Float(), 'f', -1, 64), nil
case reflect.Bool:
return strconv.FormatBool(k.Bool()), nil
}
return "", fmt.Errorf("toml: cannot encode a map key of type %s", k.Type())
}
// appendFloat appends the given float, which always has a decimal point
// so that it is read as a float.
func appendFloat(b []byte, f float64, bits int) []byte {
switch {
case math.IsNaN(f):
return append(b, "nan"...)
case math.IsInf(f, 1):
return append(b, "inf"...)
case math.IsInf(f, -1):
return append(b, "-inf"...)
case math.Trunc(f) == f:
return strconv.AppendFloat(b, f, 'f', 1, bits)
}
return strconv.AppendFloat(b, f, 'f', -1, bits)
}
// appendIndent appends the indentation for the given level.
func appendIndent(b []byte, level int) []byte {
for range level {
b = append(b, indentSymbol...)
}
return b
}
// appendKeyPath appends the given dotted key path.
func appendKeyPath(b []byte, keys []string) []byte {
for i, k := range keys {
if i > 0 {
b = append(b, '.')
}
b = appendKey(b, k)
}
return b
}
// appendKey appends the given key, which is bare if it only has
// letters, digits, - and _, and quoted otherwise.
func appendKey(b []byte, k string) []byte {
bare := k != ""
for _, c := range k {
if (c < 'A' || c > 'Z') && (c < 'a' || c > 'z') && (c < '0' || c > '9') && c != '-' && c != '_' {
bare = false
break
}
}
if bare {
return append(b, k...)
}
return appendString(b, k)
}
// appendString appends the given string as a literal (single-quoted)
// string if possible, and as a basic (double-quoted) string otherwise.
func appendString(b []byte, s string) []byte {
if !needsQuoting(s) {
b = append(b, '\'')
b = append(b, s...)
return append(b, '\'')
}
const hex = "0123456789ABCDEF"
b = append(b, '"')
for i := range len(s) {
c := s[i]
switch c {
case '\\':
b = append(b, `\\`...)
case '"':
b = append(b, `\"`...)
case '\b':
b = append(b, `\b`...)
case '\f':
b = append(b, `\f`...)
case '\n':
b = append(b, `\n`...)
case '\r':
b = append(b, `\r`...)
case '\t':
b = append(b, `\t`...)
default:
if c < 0x20 || c == 0x7f {
b = append(b, `\u00`...)
b = append(b, hex[c>>4], hex[c&0x0f])
} else {
b = append(b, c)
}
}
}
return append(b, '"')
}
// needsQuoting returns whether the given string cannot be
// written as a literal string.
func needsQuoting(s string) bool {
for i := range len(s) {
c := s[i]
if c == '\'' || (c < 0x20 && c != '\t') || c == 0x7f {
return true
}
}
return false
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package tomlx provides functions for reading and writing TOML.
// It parses TOML with github.com/BurntSushi/toml and has its own code for
// setting the parsed values on Go values and for writing TOML, which is
// compatible with the github.com/pelletier/go-toml/v2 based version used
// before (which does not work in JavaScript, as it uses unsafe pointer
// arithmetic): it reads all of the files that version wrote and writes
// the same format, including [time.Duration] values as integer
// nanoseconds and maps with non-string keys, such as enums and ints.
package tomlx
import (
"errors"
"io"
"io/fs"
"cogentcore.org/core/base/fsx"
"cogentcore.org/core/base/iox"
)
// Open reads the given object from the given filename using TOML encoding
func Open(v any, filename string) error {
return iox.Open(v, filename, NewDecoder)
}
// OpenFiles reads the given object from the given filenames using TOML encoding
func OpenFiles(v any, filenames ...string) error {
return iox.OpenFiles(v, filenames, NewDecoder)
}
// OpenFS reads the given object from the given filename using TOML encoding,
// using the given [fs.FS] filesystem (e.g., for embed files)
func OpenFS(v any, fsys fs.FS, filename string) error {
return iox.OpenFS(v, fsys, filename, NewDecoder)
}
// OpenFilesFS reads the given object from the given filenames using TOML encoding,
// using the given [fs.FS] filesystem (e.g., for embed files)
func OpenFilesFS(v any, fsys fs.FS, filenames ...string) error {
return iox.OpenFilesFS(v, fsys, filenames, NewDecoder)
}
// Read reads the given object from the given reader,
// using TOML encoding
func Read(v any, reader io.Reader) error {
return iox.Read(v, reader, NewDecoder)
}
// ReadBytes reads the given object from the given bytes,
// using TOML encoding
func ReadBytes(v any, data []byte) error {
return iox.ReadBytes(v, data, NewDecoder)
}
// Save writes the given object to the given filename using TOML encoding
func Save(v any, filename string) error {
return iox.Save(v, filename, NewEncoder)
}
// Write writes the given object using TOML encoding
func Write(v any, writer io.Writer) error {
return iox.Write(v, writer, NewEncoder)
}
// WriteBytes writes the given object, returning bytes of the encoding,
// using TOML encoding
func WriteBytes(v any) ([]byte, error) {
return iox.WriteBytes(v, NewEncoder)
}
// OpenFromPaths reads the given object from the given TOML file,
// looking on paths for the file.
func OpenFromPaths(v any, file string, paths ...string) error {
filenames := fsx.FindFilesOnPaths(paths, file)
if len(filenames) == 0 {
return errors.New("OpenFromPaths: no files found")
}
return Open(v, filenames[0])
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !js
package xmlx
import (
"io"
"golang.org/x/net/html/charset"
)
// CharsetReader returns a reader that converts the text of input from the
// character set with the given label to UTF-8. It is meant for
// [xml.Decoder.CharsetReader], which calls it for documents that declare an
// encoding other than UTF-8. On the web, it uses the browser's TextDecoder,
// which keeps the encoding tables of golang.org/x/net/html/charset out of
// web builds.
func CharsetReader(label string, input io.Reader) (io.Reader, error) {
return charset.NewReaderLabel(label, input)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package xmlx provides functions for opening, reading, saving, and writing
// values in XML.
package xmlx
import (
"encoding/xml"
"io"
"io/fs"
"cogentcore.org/core/base/iox"
)
// Open reads the given object from the given filename using XML encoding
func Open(v any, filename string) error {
return iox.Open(v, filename, iox.NewDecoderFunc(xml.NewDecoder))
}
// OpenFiles reads the given object from the given filenames using XML encoding
func OpenFiles(v any, filenames ...string) error {
return iox.OpenFiles(v, filenames, iox.NewDecoderFunc(xml.NewDecoder))
}
// OpenFS reads the given object from the given filename using XML encoding,
// using the given [fs.FS] filesystem (e.g., for embed files)
func OpenFS(v any, fsys fs.FS, filename string) error {
return iox.OpenFS(v, fsys, filename, iox.NewDecoderFunc(xml.NewDecoder))
}
// OpenFilesFS reads the given object from the given filenames using XML encoding,
// using the given [fs.FS] filesystem (e.g., for embed files)
func OpenFilesFS(v any, fsys fs.FS, filenames ...string) error {
return iox.OpenFilesFS(v, fsys, filenames, iox.NewDecoderFunc(xml.NewDecoder))
}
// Read reads the given object from the given reader,
// using XML encoding
func Read(v any, reader io.Reader) error {
return iox.Read(v, reader, iox.NewDecoderFunc(xml.NewDecoder))
}
// ReadBytes reads the given object from the given bytes,
// using XML encoding
func ReadBytes(v any, data []byte) error {
return iox.ReadBytes(v, data, iox.NewDecoderFunc(xml.NewDecoder))
}
// Save writes the given object to the given filename using XML encoding
func Save(v any, filename string) error {
return iox.Save(v, filename, iox.NewEncoderFunc(xml.NewEncoder))
}
// Write writes the given object using XML encoding
func Write(v any, writer io.Writer) error {
return iox.Write(v, writer, iox.NewEncoderFunc(xml.NewEncoder))
}
// WriteBytes writes the given object, returning bytes of the encoding,
// using XML encoding
func WriteBytes(v any) ([]byte, error) {
return iox.WriteBytes(v, iox.NewEncoderFunc(xml.NewEncoder))
}
// IndentEncoderFunc is a [iox.EncoderFunc] that sets indentation
var IndentEncoderFunc = func(w io.Writer) iox.Encoder {
e := xml.NewEncoder(w)
e.Indent("", "\t")
return e
}
// SaveIndent writes the given object to the given filename using XML encoding, with indentation
func SaveIndent(v any, filename string) error {
return iox.Save(v, filename, IndentEncoderFunc)
}
// WriteIndent writes the given object using XML encoding, with indentation
func WriteIndent(v any, writer io.Writer) error {
return iox.Write(v, writer, IndentEncoderFunc)
}
// WriteBytesIndent writes the given object, returning bytes of the encoding,
// using XML encoding, with indentation
func WriteBytesIndent(v any) ([]byte, error) {
return iox.WriteBytes(v, IndentEncoderFunc)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package yamlx provides functions for opening, reading, saving, and writing
// values in YAML.
package yamlx
import (
"io"
"io/fs"
"cogentcore.org/core/base/iox"
"gopkg.in/yaml.v3"
)
// Open reads the given object from the given filename using YAML encoding
func Open(v any, filename string) error {
return iox.Open(v, filename, iox.NewDecoderFunc(yaml.NewDecoder))
}
// OpenFiles reads the given object from the given filenames using YAML encoding
func OpenFiles(v any, filenames ...string) error {
return iox.OpenFiles(v, filenames, iox.NewDecoderFunc(yaml.NewDecoder))
}
// OpenFS reads the given object from the given filename using YAML encoding,
// using the given [fs.FS] filesystem (e.g., for embed files)
func OpenFS(v any, fsys fs.FS, filename string) error {
return iox.OpenFS(v, fsys, filename, iox.NewDecoderFunc(yaml.NewDecoder))
}
// OpenFilesFS reads the given object from the given filenames using YAML encoding,
// using the given [fs.FS] filesystem (e.g., for embed files)
func OpenFilesFS(v any, fsys fs.FS, filenames ...string) error {
return iox.OpenFilesFS(v, fsys, filenames, iox.NewDecoderFunc(yaml.NewDecoder))
}
// Read reads the given object from the given reader,
// using YAML encoding
func Read(v any, reader io.Reader) error {
return iox.Read(v, reader, iox.NewDecoderFunc(yaml.NewDecoder))
}
// ReadBytes reads the given object from the given bytes,
// using YAML encoding
func ReadBytes(v any, data []byte) error {
return iox.ReadBytes(v, data, iox.NewDecoderFunc(yaml.NewDecoder))
}
// Save writes the given object to the given filename using YAML encoding
func Save(v any, filename string) error {
return iox.Save(v, filename, iox.NewEncoderFunc(yaml.NewEncoder))
}
// Write writes the given object using YAML encoding
func Write(v any, writer io.Writer) error {
return iox.Write(v, writer, iox.NewEncoderFunc(yaml.NewEncoder))
}
// WriteBytes writes the given object, returning bytes of the encoding,
// using YAML encoding
func WriteBytes(v any) ([]byte, error) {
return iox.WriteBytes(v, iox.NewEncoderFunc(yaml.NewEncoder))
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
Package keylist implements an ordered list (slice) of items,
with a map from a key (e.g., names) to indexes,
to support fast lookup by name. It has separate slices for
Values and Keys, for direct access to them, and [List.All]
iterates over both.
*/
package keylist
import (
"fmt"
"iter"
"slices"
"strings"
)
// List implements an ordered list (slice) of Values,
// with a map from a key (e.g., names) to indexes,
// to support fast lookup by name.
type List[K comparable, V any] struct { //types:add
// List is the ordered slice of items.
Values []V
// Keys is the ordered list of keys, in same order as [List.Values]
Keys []K
// indexes is the key-to-index mapping.
indexes map[K]int
}
// New returns a new [List]. The zero value
// is usable without initialization, so this is
// just a simple standard convenience method.
func New[K comparable, V any]() *List[K, V] {
return &List[K, V]{}
}
func (kl *List[K, V]) makeIndexes() {
kl.indexes = make(map[K]int)
}
// initIndexes ensures that the index map exists.
func (kl *List[K, V]) initIndexes() {
if kl.indexes == nil {
kl.makeIndexes()
}
}
// Reset resets the list, removing any existing elements.
func (kl *List[K, V]) Reset() {
kl.Values = nil
kl.Keys = nil
kl.makeIndexes()
}
// Set sets given key to given value, adding to the end of the list
// if not already present, and otherwise replacing with this new value.
// This is the same semantics as a Go map.
// See [List.Add] for version that only adds and does not replace.
func (kl *List[K, V]) Set(key K, val V) {
kl.initIndexes()
if idx, ok := kl.indexes[key]; ok {
kl.Values[idx] = val
kl.Keys[idx] = key
return
}
kl.indexes[key] = len(kl.Values)
kl.Values = append(kl.Values, val)
kl.Keys = append(kl.Keys, key)
}
// Add adds an item to the list with given key,
// An error is returned if the key is already on the list.
// See [List.Set] for a method that automatically replaces.
func (kl *List[K, V]) Add(key K, val V) error {
kl.initIndexes()
if _, ok := kl.indexes[key]; ok {
return fmt.Errorf("keylist.Add: key %v is already on the list", key)
}
kl.indexes[key] = len(kl.Values)
kl.Values = append(kl.Values, val)
kl.Keys = append(kl.Keys, key)
return nil
}
// Insert inserts the given value with the given key at the given index.
// This is relatively slow because it needs regenerate the keys list.
// It panics if the key already exists because the behavior is undefined
// in that situation.
func (kl *List[K, V]) Insert(idx int, key K, val V) {
if _, has := kl.indexes[key]; has {
panic("keylist.Add: key is already on the list")
}
kl.Keys = slices.Insert(kl.Keys, idx, key)
kl.Values = slices.Insert(kl.Values, idx, val)
kl.makeIndexes()
for i, k := range kl.Keys {
kl.indexes[k] = i
}
}
// At returns the value corresponding to the given key,
// with a zero value returned for a missing key. See [List.AtTry]
// for one that returns a bool for missing keys.
// For index-based access, use [List.Values] or [List.Keys] slices directly.
func (kl *List[K, V]) At(key K) V {
idx, ok := kl.indexes[key]
if ok {
return kl.Values[idx]
}
var zv V
return zv
}
// AtTry returns the value corresponding to the given key,
// with false returned for a missing key, in case the zero value
// is not diagnostic.
func (kl *List[K, V]) AtTry(key K) (V, bool) {
idx, ok := kl.indexes[key]
if ok {
return kl.Values[idx], true
}
var zv V
return zv, false
}
// IndexIsValid returns an error if the given index is invalid.
func (kl *List[K, V]) IndexIsValid(idx int) error {
if idx >= len(kl.Values) || idx < 0 {
return fmt.Errorf("keylist.List: IndexIsValid: index %d is out of range of a list of length %d", idx, len(kl.Values))
}
return nil
}
// IndexByKey returns the index of the given key, with a -1 for missing key.
func (kl *List[K, V]) IndexByKey(key K) int {
idx, ok := kl.indexes[key]
if !ok {
return -1
}
return idx
}
// IndexByKeyTry returns the index of the given key, and whether it is in
// the list.
func (kl *List[K, V]) IndexByKeyTry(key K) (int, bool) {
idx, ok := kl.indexes[key]
return idx, ok
}
// All returns an iterator over the keys and values of the list, in order:
//
// for key, value := range kl.All() {
func (kl *List[K, V]) All() iter.Seq2[K, V] {
return func(yield func(K, V) bool) {
for i, k := range kl.Keys {
if !yield(k, kl.Values[i]) {
return
}
}
}
}
// Len returns the number of items in the list.
func (kl *List[K, V]) Len() int {
if kl == nil {
return 0
}
return len(kl.Values)
}
// DeleteByIndex deletes item(s) within the index range [i:j].
// This is relatively slow because it needs to regenerate the
// index map.
func (kl *List[K, V]) DeleteByIndex(i, j int) {
ndel := j - i
if ndel <= 0 {
panic("index range is <= 0")
}
kl.Keys = slices.Delete(kl.Keys, i, j)
kl.Values = slices.Delete(kl.Values, i, j)
kl.makeIndexes()
for i, k := range kl.Keys {
kl.indexes[k] = i
}
}
// DeleteByKey deletes the item with the given key,
// returning false if it does not find it.
// This is relatively slow because it needs to regenerate the
// index map.
func (kl *List[K, V]) DeleteByKey(key K) bool {
idx, ok := kl.indexes[key]
if !ok {
return false
}
kl.DeleteByIndex(idx, idx+1)
return true
}
// RenameIndex renames the item at given index to new key.
func (kl *List[K, V]) RenameIndex(i int, key K) {
old := kl.Keys[i]
delete(kl.indexes, old)
kl.Keys[i] = key
kl.indexes[key] = i
}
// Copy copies all of the entries from the given key list
// into this list. It keeps existing entries in this
// list unless they also exist in the given list, in which case
// they are overwritten. Use [List.Reset] first to get an exact copy.
func (kl *List[K, V]) Copy(from *List[K, V]) {
for i, v := range from.Values {
kl.Set(from.Keys[i], v)
}
}
// String returns a string representation of the list.
func (kl *List[K, V]) String() string {
var sv strings.Builder
sv.WriteString("{")
for i, v := range kl.Values {
fmt.Fprintf(&sv, "%v", kl.Keys[i])
sv.WriteString(": ")
fmt.Fprintf(&sv, "%v", v)
sv.WriteString(", ")
}
sv.WriteString("}")
return sv.String()
}
// UpdateIndexes updates the Indexes from Keys and Values.
// This must be called after loading Values from a file, for example,
// where Keys can be populated from Values or are also otherwise available.
func (kl *List[K, V]) UpdateIndexes() {
kl.makeIndexes()
for i := range kl.Values {
k := kl.Keys[i]
kl.indexes[k] = i
}
}
/*
// GoString returns the list as Go code.
func (kl *List[K, V]) GoString() string {
var zk K
var zv V
res := fmt.Sprintf("ordlist.Make([]ordlist.KeyVal[%T, %T]{\n", zk, zv)
for _, kv := range kl.Order {
res += fmt.Sprintf("{%#v, %#v},\n", kv.Key, kv.Value)
}
res += "})"
return res
}
*/
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package labels
import (
"fmt"
"reflect"
"strings"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/base/strcase"
)
// FriendlyTypeName returns a user-friendly version of the name of the given type.
// It transforms it into sentence case, excludes the package, and converts various
// builtin types into more friendly forms (eg: "int" to "Number").
func FriendlyTypeName(typ reflect.Type) string {
nptyp := reflectx.NonPointerType(typ)
if nptyp == nil {
return "None"
}
nm := nptyp.Name()
// if it is named, we use that
if nm != "" {
switch nm {
case "string":
return "Text"
case "float32", "float64", "int", "int8", "int16", "int32", "int64", "uint", "uint8", "uint16", "uint32", "uint64", "uintptr":
return "Number"
}
return strcase.ToSentence(nm)
}
// otherwise, we fall back on Kind
switch nptyp.Kind() {
case reflect.Slice, reflect.Array, reflect.Map:
bnm := FriendlyTypeName(nptyp.Elem())
if strings.HasSuffix(bnm, "s") {
return "List of " + bnm
} else if strings.Contains(bnm, "Function of") {
return strings.ReplaceAll(bnm, "Function of", "Functions of") + "s"
}
return bnm + "s"
case reflect.Func:
var str strings.Builder
str.WriteString("Function")
ni := nptyp.NumIn()
if ni > 0 {
str.WriteString(" of")
}
for i := range ni {
str.WriteString(" ")
str.WriteString(FriendlyTypeName(nptyp.In(i)))
if ni == 2 && i == 0 {
str.WriteString(" and")
} else if i == ni-2 {
str.WriteString(", and")
} else if i < ni-1 {
str.WriteString(",")
}
}
return str.String()
}
if nptyp.String() == "interface {}" {
return "Value"
}
return nptyp.String()
}
// FriendlyStructLabel returns a user-friendly label for the given struct value.
func FriendlyStructLabel(v reflect.Value) string {
npv := reflectx.NonPointerValue(v)
if !v.IsValid() || v.IsZero() {
return "None"
}
opv := reflectx.UnderlyingPointer(v)
if lbler, ok := reflect.TypeAssert[Labeler](opv); ok {
return lbler.Label()
}
return FriendlyTypeName(npv.Type())
}
// FriendlySliceLabel returns a user-friendly label for the given slice value.
func FriendlySliceLabel(v reflect.Value) string {
uv := reflectx.Underlying(v)
label := ""
if !uv.IsValid() {
label = "None"
} else {
if uv.Kind() == reflect.Array || !uv.IsNil() {
bnm := FriendlyTypeName(reflectx.SliceElementType(v.Interface()))
if strings.HasSuffix(bnm, "s") {
label = strcase.ToSentence(fmt.Sprintf("%d lists of %s", uv.Len(), bnm))
} else {
label = strcase.ToSentence(fmt.Sprintf("%d %ss", uv.Len(), bnm))
}
} else {
label = "None"
}
}
return label
}
// FriendlyMapLabel returns a user-friendly label for the given map value.
func FriendlyMapLabel(v reflect.Value) string {
uv := reflectx.Underlying(v)
mpi := v.Interface()
label := ""
if !uv.IsValid() || uv.IsNil() {
label = "None"
} else {
bnm := FriendlyTypeName(reflectx.MapValueType(mpi))
if strings.HasSuffix(bnm, "s") {
label = strcase.ToSentence(fmt.Sprintf("%d lists of %s", uv.Len(), bnm))
} else {
label = strcase.ToSentence(fmt.Sprintf("%d %ss", uv.Len(), bnm))
}
}
return label
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package labels provides the labels of values shown in a GUI, from the
// [Labeler] interface or a friendly form of their names.
package labels
import (
"cogentcore.org/core/base/reflectx"
)
// Labeler interface provides a GUI-appropriate label for an item,
// via a Label string method. See [ToLabel] and [ToLabeler].
type Labeler interface {
// Label returns a GUI-appropriate label for item
Label() string
}
// ToLabel returns the GUI-appropriate label for an item, using the Labeler
// interface if it is defined, and falling back on [reflectx.ToString] converter
// otherwise.
func ToLabel(v any) string {
if lb, ok := v.(Labeler); ok {
return lb.Label()
}
return reflectx.ToString(v)
}
// ToLabeler returns the Labeler label, true if it was defined, else "", false
func ToLabeler(v any) (string, bool) {
if lb, ok := v.(Labeler); ok {
return lb.Label(), true
}
return "", false
}
// SliceLabeler interface provides a GUI-appropriate label
// for a slice item, given an index into the slice.
type SliceLabeler interface {
// ElemLabel returns a GUI-appropriate label for slice element at given index.
ElemLabel(idx int) string
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package logx
import (
"image/color"
"log/slog"
"cogentcore.org/core/colors"
"cogentcore.org/core/colors/matcolor"
"github.com/muesli/termenv"
)
var (
// UseColor is whether to use color in log messages. It is on by default.
UseColor = true
// ColorSchemeIsDark is whether the color scheme of the current terminal is dark-themed.
// Its primary use is in [ColorScheme], and it should typically only be accessed via that.
ColorSchemeIsDark = true
)
// ColorScheme returns the appropriate appropriate color scheme
// for terminal colors. It should be used instead of [colors.Scheme]
// for terminal colors because the theme (dark vs light) of the terminal
// could be different than that of the main app.
func ColorScheme() *matcolor.Scheme {
if ColorSchemeIsDark {
return &colors.Schemes.Dark
}
return &colors.Schemes.Light
}
// colorProfile is the termenv color profile, stored globally for convenience.
// It is set by [SetDefaultLogger] to [termenv.ColorProfile] if [UseColor] is true.
var colorProfile termenv.Profile
// InitColor sets up the terminal environment for color output. It is called automatically
// in an init function if UseColor is set to true. However, if you call a system command
// (ls, cp, etc), you need to call this function again.
func InitColor() {
restoreFunc, err := termenv.EnableVirtualTerminalProcessing(termenv.DefaultOutput())
if err != nil {
slog.Warn("error enabling virtual terminal processing for colored output on Windows", "err", err)
}
_ = restoreFunc // TODO: figure out how to call this at the end of the program
colorProfile = termenv.ColorProfile()
ColorSchemeIsDark = termenv.HasDarkBackground()
}
// ApplyColor applies the given color to the given string
// and returns the resulting string. If [UseColor] is set
// to false, it just returns the string it was passed.
func ApplyColor(clr color.Color, str string) string {
if !UseColor {
return str
}
return termenv.String(str).Foreground(colorProfile.FromColor(clr)).String()
}
// LevelColor applies the color associated with the given level to the
// given string and returns the resulting string. If [UseColor] is set
// to false, it just returns the string it was passed.
func LevelColor(level slog.Level, str string) string {
var clr color.RGBA
switch level {
case slog.LevelDebug:
return DebugColor(str)
case slog.LevelInfo:
return InfoColor(str)
case slog.LevelWarn:
return WarnColor(str)
case slog.LevelError:
return ErrorColor(str)
}
return ApplyColor(clr, str)
}
// DebugColor applies the color associated with the debug level to
// the given string and returns the resulting string. If [UseColor] is set
// to false, it just returns the string it was passed.
func DebugColor(str string) string {
return ApplyColor(colors.ToUniform(ColorScheme().Tertiary.Base), str)
}
// InfoColor applies the color associated with the info level to
// the given string and returns the resulting string. Because the
// color associated with the info level is just white/black, it just
// returns the given string, but it exists for API consistency.
func InfoColor(str string) string {
return str
}
// WarnColor applies the color associated with the warn level to
// the given string and returns the resulting string. If [UseColor] is set
// to false, it just returns the string it was passed.
func WarnColor(str string) string {
return ApplyColor(colors.ToUniform(ColorScheme().Warn.Base), str)
}
// ErrorColor applies the color associated with the error level to
// the given string and returns the resulting string. If [UseColor] is set
// to false, it just returns the string it was passed.
func ErrorColor(str string) string {
return ApplyColor(colors.ToUniform(ColorScheme().Error.Base), str)
}
// SuccessColor applies the color associated with success to the
// given string and returns the resulting string. If [UseColor] is set
// to false, it just returns the string it was passed.
func SuccessColor(str string) string {
return ApplyColor(colors.ToUniform(ColorScheme().Success.Base), str)
}
// CmdColor applies the color associated with terminal commands and arguments
// to the given string and returns the resulting string. If [UseColor] is set
// to false, it just returns the string it was passed.
func CmdColor(str string) string {
return ApplyColor(colors.ToUniform(ColorScheme().Primary.Base), str)
}
// TitleColor applies the color associated with titles and section headers
// to the given string and returns the resulting string. If [UseColor] is set
// to false, it just returns the string it was passed.
func TitleColor(str string) string {
return ApplyColor(colors.ToUniform(ColorScheme().Warn.Base), str)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package logx
import "log/slog"
// UserLevel is the verbosity [slog.Level] that the user has selected for
// what logging and printing messages should be shown. Messages at
// levels at or above this level will be shown. It should typically
// be set through exec to the end user's preference. The default user
// verbosity level is [slog.LevelInfo]. If the build tag "debug" is
// specified, it is [slog.LevelDebug]. If the build tag "release" is
// specified, it is [slog.levelWarn]. Any updates to this value will
// be automatically reflected in the behavior of the logx default logger.
var UserLevel = defaultUserLevel
// LevelFromFlags returns the [slog.Level] object corresponding to the given
// user flag options. The flags correspond to the following values:
// - vv: [slog.LevelDebug]
// - v: [slog.LevelInfo]
// - q: [slog.LevelError]
// - (default: [slog.LevelWarn])
//
// The flags are evaluated in that order, so, for example, if both
// vv and q are specified, it will still return [Debug].
func LevelFromFlags(vv, v, q bool) slog.Level {
switch {
case vv:
return slog.LevelDebug
case v:
return slog.LevelInfo
case q:
return slog.LevelError
default:
return slog.LevelWarn
}
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This code is based on https://github.com/jba/slog/blob/main/handlers/loghandler/log_handler.go
// Copyright (c) 2022, Jonathan Amsterdam. All rights reserved. (BSD 3-Clause License)
// Package logx implements structured log handling and provides
// global log and print verbosity and color options.
package logx
import (
"context"
"fmt"
"io"
"log/slog"
"os"
"runtime"
"strconv"
"sync"
)
// Handler is a [slog.Handler] whose output resembles that of [log.Logger].
// Use [NewHandler] to make a new [Handler] from a writer and options.
type Handler struct {
Opts slog.HandlerOptions
Prefix string // preformatted group names followed by a dot
Preformat string // preformatted Attrs, with an initial space
Mu sync.Mutex
W io.Writer
}
var _ slog.Handler = &Handler{}
// SetDefaultLogger sets the default logger to be a [Handler] with the
// level set to track [UserLevel]. It is called on program start
// automatically, so it should not need to be called by end user code
// in almost all circumstances.
func SetDefaultLogger() {
slog.SetDefault(slog.New(NewHandler(os.Stderr, &slog.HandlerOptions{
Level: &UserLevel,
})))
if UseColor {
InitColor()
}
}
func init() {
SetDefaultLogger()
}
// NewHandler makes a new [Handler] for the given writer with the given options.
func NewHandler(w io.Writer, opts *slog.HandlerOptions) *Handler {
h := &Handler{W: w}
if opts != nil {
h.Opts = *opts
}
if h.Opts.ReplaceAttr == nil {
h.Opts.ReplaceAttr = func(_ []string, a slog.Attr) slog.Attr { return a }
}
return h
}
// Enabled returns whether the handler should log a mesage with the given
// level in the given context.
func (h *Handler) Enabled(ctx context.Context, level slog.Level) bool {
minLevel := slog.LevelInfo
if h.Opts.Level != nil {
minLevel = h.Opts.Level.Level()
}
return level >= minLevel
}
func (h *Handler) WithGroup(name string) slog.Handler {
return &Handler{
W: h.W,
Opts: h.Opts,
Preformat: h.Preformat,
Prefix: h.Prefix + name + ".",
}
}
func (h *Handler) WithAttrs(attrs []slog.Attr) slog.Handler {
var buf []byte
for _, a := range attrs {
buf = h.AppendAttr(buf, h.Prefix, a)
}
return &Handler{
W: h.W,
Opts: h.Opts,
Prefix: h.Prefix,
Preformat: h.Preformat + string(buf),
}
}
func (h *Handler) Handle(ctx context.Context, r slog.Record) error {
var buf []byte
if !r.Time.IsZero() {
buf = r.Time.AppendFormat(buf, "2006/01/02 15:04:05")
buf = append(buf, ' ')
}
buf = append(buf, r.Level.String()...)
buf = append(buf, ' ')
if h.Opts.AddSource && r.PC != 0 {
fs := runtime.CallersFrames([]uintptr{r.PC})
f, _ := fs.Next()
buf = append(buf, f.File...)
buf = append(buf, ':')
buf = strconv.AppendInt(buf, int64(f.Line), 10)
buf = append(buf, ' ')
}
buf = append(buf, r.Message...)
buf = append(buf, h.Preformat...)
r.Attrs(func(a slog.Attr) bool {
buf = h.AppendAttr(buf, h.Prefix, a)
return true
})
buf = append(buf, '\n')
h.Mu.Lock()
defer h.Mu.Unlock()
if UseColor {
_, err := h.W.Write([]byte(LevelColor(r.Level, string(buf))))
return err
}
_, err := h.W.Write(buf)
return err
}
func (h *Handler) AppendAttr(buf []byte, prefix string, a slog.Attr) []byte {
if a.Equal(slog.Attr{}) {
return buf
}
if a.Value.Kind() != slog.KindGroup {
buf = append(buf, ' ')
buf = append(buf, prefix...)
buf = append(buf, a.Key...)
buf = append(buf, '=')
return fmt.Appendf(buf, "%v", a.Value.Any())
}
// Group
if a.Key != "" {
prefix += a.Key + "."
}
for _, a := range a.Value.Group() {
buf = h.AppendAttr(buf, prefix, a)
}
return buf
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package logx
import (
"fmt"
"log/slog"
)
// Print is equivalent to [fmt.Print], but with color based on the given level.
// Also, if [UserLevel] is above the given level, it does not print anything.
func Print(level slog.Level, a ...any) (n int, err error) {
if UserLevel > level {
return 0, nil
}
return fmt.Print(LevelColor(level, fmt.Sprint(a...)))
}
// PrintDebug is equivalent to [Print] with level [slog.LevelDebug].
func PrintDebug(a ...any) (n int, err error) {
return Print(slog.LevelDebug, a...)
}
// PrintInfo is equivalent to [Print] with level [slog.LevelInfo].
func PrintInfo(a ...any) (n int, err error) {
return Print(slog.LevelInfo, a...)
}
// PrintWarn is equivalent to [Print] with level [slog.LevelWarn].
func PrintWarn(a ...any) (n int, err error) {
return Print(slog.LevelWarn, a...)
}
// PrintError is equivalent to [Print] with level [slog.LevelError].
func PrintError(a ...any) (n int, err error) {
return Print(slog.LevelError, a...)
}
// Println is equivalent to [fmt.Println], but with color based on the given level.
// Also, if [UserLevel] is above the given level, it does not print anything.
func Println(level slog.Level, a ...any) (n int, err error) {
if UserLevel > level {
return 0, nil
}
return fmt.Println(LevelColor(level, fmt.Sprint(a...)))
}
// PrintlnDebug is equivalent to [Println] with level [slog.LevelDebug].
func PrintlnDebug(a ...any) (n int, err error) {
return Println(slog.LevelDebug, a...)
}
// PrintlnInfo is equivalent to [Println] with level [slog.LevelInfo].
func PrintlnInfo(a ...any) (n int, err error) {
return Println(slog.LevelInfo, a...)
}
// PrintlnWarn is equivalent to [Println] with level [slog.LevelWarn].
func PrintlnWarn(a ...any) (n int, err error) {
return Println(slog.LevelWarn, a...)
}
// PrintlnError is equivalent to [Println] with level [slog.LevelError].
func PrintlnError(a ...any) (n int, err error) {
return Println(slog.LevelError, a...)
}
// Printf is equivalent to [fmt.Printf], but with color based on the given level.
// Also, if [UserLevel] is above the given level, it does not print anything.
func Printf(level slog.Level, format string, a ...any) (n int, err error) {
if UserLevel > level {
return 0, nil
}
return fmt.Print(LevelColor(level, fmt.Sprintf(format, a...)))
}
// PrintfDebug is equivalent to [Printf] with level [slog.LevelDebug].
func PrintfDebug(format string, a ...any) (n int, err error) {
return Printf(slog.LevelDebug, format, a...)
}
// PrintfInfo is equivalent to [Printf] with level [slog.LevelInfo].
func PrintfInfo(format string, a ...any) (n int, err error) {
return Printf(slog.LevelInfo, format, a...)
}
// PrintfWarn is equivalent to [Printf] with level [slog.LevelWarn].
func PrintfWarn(format string, a ...any) (n int, err error) {
return Printf(slog.LevelWarn, format, a...)
}
// PrintfError is equivalent to [Printf] with level [slog.LevelError].
func PrintfError(format string, a ...any) (n int, err error) {
return Printf(slog.LevelError, format, a...)
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on https://github.com/laher/mergefs
// Copyright (c) 2021 Amir Laher under the MIT License
// Package mergefs provides support for merging multiple filesystems together.
package mergefs
import (
"errors"
"io/fs"
"os"
)
// Merge merges the given filesystems together,
func Merge(filesystems ...fs.FS) fs.FS {
return MergedFS{filesystems: filesystems}
}
// MergedFS combines filesystems. Each filesystem can serve different paths.
// The first FS takes precedence
type MergedFS struct {
filesystems []fs.FS
}
// Open opens the named file.
func (mfs MergedFS) Open(name string) (fs.File, error) {
for _, fs := range mfs.filesystems {
file, err := fs.Open(name)
if err == nil { // TODO should we return early when it's not an os.ErrNotExist? Should we offer options to decide this behaviour?
return file, nil
}
}
return nil, os.ErrNotExist
}
// ReadDir reads from the directory, and produces a DirEntry array of different
// directories.
//
// It iterates through all different filesystems that exist in the mfs MergeFS
// filesystem slice and it identifies overlapping directories that exist in different
// filesystems
func (mfs MergedFS) ReadDir(name string) ([]fs.DirEntry, error) {
dirsMap := make(map[string]fs.DirEntry)
notExistCount := 0
for _, filesystem := range mfs.filesystems {
dir, err := fs.ReadDir(filesystem, name)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
notExistCount++
continue
}
return nil, err
}
for _, v := range dir {
if _, ok := dirsMap[v.Name()]; !ok {
dirsMap[v.Name()] = v
}
}
continue
}
if len(mfs.filesystems) == notExistCount {
return nil, fs.ErrNotExist
}
dirs := make([]fs.DirEntry, 0, len(dirsMap))
for _, value := range dirsMap {
dirs = append(dirs, value)
}
return dirs, nil
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package metadata provides a map of named any elements
// with generic support for type-safe Get and nil-safe Set.
// Metadata keys often function as optional fields in a struct,
// and therefore a CamelCase naming convention is typical.
// Provides default support for "Name", "Doc", "File" standard keys.
package metadata
import (
"fmt"
"maps"
"cogentcore.org/core/base/errors"
)
// Data is metadata as a map of named any elements
// with generic support for type-safe Get and nil-safe Set.
// Metadata keys often function as optional fields in a struct,
// and therefore a CamelCase naming convention is typical.
// Provides default support for "Name" and "Doc" standard keys.
// In general it is good practice to provide access functions
// that establish standard key names, to avoid issues with typos.
type Data map[string]any
func (md *Data) init() {
if *md == nil {
*md = make(map[string]any)
}
}
// Set sets key to given value, ensuring that
// the map is created if not previously.
func (md *Data) Set(key string, value any) {
md.init()
(*md)[key] = value
}
// GetFromData gets metadata value of given type from given Data.
// Returns error if not present or item is a different type.
func GetFromData[T any](md Data, key string) (T, error) {
var z T
x, ok := md[key]
if !ok {
return z, fmt.Errorf("key %q not found in metadata", key)
}
v, ok := x.(T)
if !ok {
return z, fmt.Errorf("key %q has a different type than expected %T: is %T", key, z, x)
}
return v, nil
}
// Copy does a shallow copy of metadata from source.
// Any pointer-based values will still point to the same
// underlying data as the source, but the two maps remain
// distinct. It uses [maps.Copy].
func (md *Data) Copy(src Data) {
if src == nil {
return
}
md.init()
maps.Copy(*md, src)
}
//////// Metadataer
// Metadataer is an interface for a type that returns associated
// metadata.Data using a Metadata() method. To be able to set metadata,
// the method should be defined with a pointer receiver.
type Metadataer interface {
Metadata() *Data
}
// GetData gets the Data from given object, if it implements the
// Metadata() method. Returns nil if it does not.
// Must pass a pointer to the object.
func GetData(obj any) *Data {
if md, ok := obj.(Metadataer); ok {
return md.Metadata()
}
return nil
}
// Get gets metadata value of given type from given object,
// if it implements the Metadata() method.
// Must pass a pointer to the object.
// Returns error if not present or item is a different type.
func Get[T any](obj any, key string) (T, error) {
md := GetData(obj)
if md == nil {
var zv T
return zv, errors.New("metadata not available for given object type")
}
return GetFromData[T](*md, key)
}
// Set sets metadata value on given object, if it implements
// the Metadata() method. Returns error if no Metadata on object.
// Must pass a pointer to the object.
func Set(obj any, key string, value any) error {
md := GetData(obj)
if md == nil {
return errors.Log(errors.New("metadata not available for given object type"))
}
md.Set(key, value)
return nil
}
// Copy copies metadata from source
// Must pass a pointer to the object.
func Copy(to, src any) *Data {
tod := GetData(to)
if tod == nil {
return nil
}
srcd := GetData(src)
if srcd == nil {
return tod
}
tod.Copy(*srcd)
return tod
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package metadata
import "os"
// SetName sets the "Name" standard key.
func SetName(obj any, name string) {
Set(obj, "Name", name)
}
// Name returns the "Name" standard key value (empty if not set).
func Name(obj any) string {
nm, _ := Get[string](obj, "Name")
return nm
}
// SetDoc sets the "Doc" standard key.
func SetDoc(obj any, doc string) {
Set(obj, "Doc", doc)
}
// Doc returns the "Doc" standard key value (empty if not set).
func Doc(obj any) string {
doc, _ := Get[string](obj, "Doc")
return doc
}
// SetFile sets the "File" standard key for *os.File.
func SetFile(obj any, file *os.File) {
Set(obj, "File", file)
}
// File returns the "File" standard key value (nil if not set).
func File(obj any) *os.File {
doc, _ := Get[*os.File](obj, "File")
return doc
}
// SetFilename sets the "Filename" standard key.
func SetFilename(obj any, file string) {
Set(obj, "Filename", file)
}
// Filename returns the "Filename" standard key value (empty if not set).
func Filename(obj any) string {
doc, _ := Get[string](obj, "Filename")
return doc
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
Package nptime provides a non-pointer version of the time.Time struct
that does not have the location pointer information that time.Time has,
which is more efficient from a memory management perspective, in cases
where you have a lot of time values being kept: https://segment.com/blog/allocation-efficiency-in-high-performance-go-services/
*/
package nptime
import "time"
// Time represents the value of time.Time without using any pointers for the
// location information, so it is more memory efficient when lots of time
// values are being stored.
type Time struct {
// [time.Time.Unix] seconds since 1970
Sec int64
// [time.Time.Nanosecond]; nanosecond offset within second, *not* UnixNano
NSec uint32
}
// IsZero returns true if the time is zero and has not been initialized.
func (t Time) IsZero() bool {
return t == Time{}
}
// Time returns the [time.Time] value for this [Time] value.
func (t Time) Time() time.Time {
return time.Unix(t.Sec, int64(t.NSec))
}
// SetTime sets the [Time] value based on the [time.Time]. value
func (t *Time) SetTime(tt time.Time) {
t.Sec = tt.Unix()
t.NSec = uint32(tt.Nanosecond())
}
// Now sets the time value to [time.Now].
func (t *Time) Now() {
t.SetTime(time.Now())
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package num
// Abs returns the absolute value of the given value.
func Abs[T Signed | Float](x T) T {
if x < 0 {
return -x
}
return x
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package num
// see: https://github.com/golang/go/issues/61915
// ToBool returns a bool true if the given number is not zero,
// and false if it is zero, providing a direct way to convert
// numbers to bools as is done automatically in C and other languages.
func ToBool[T Number](v T) bool {
return v != 0
}
// FromBool returns a 1 if the bool is true and a 0 for false.
// Typically the type parameter cannot be inferred and must be provided.
// See SetFromBool for a version that uses a pointer to the destination
// which avoids the need to specify the type parameter.
func FromBool[T Number](v bool) T {
if v {
return 1
}
return 0
}
// SetFromBool converts a bool into a number, using generics,
// setting the pointer to the dst destination value to a 1 if bool is true,
// and 0 otherwise.
// This version of FromBool does not require type parameters typically.
func SetFromBool[T Number](dst *T, b bool) {
if b {
*dst = 1
return
}
*dst = 0
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package option provides optional (nullable) types.
package option
// Option represents an optional (nullable) type. If Valid is true, Option
// represents Value. Otherwise, it represents a null/unset/invalid value.
type Option[T any] struct {
Valid bool `label:"Set"`
Value T
}
// New returns a new [Option] set to the given value.
func New[T any](v T) *Option[T] {
o := &Option[T]{}
o.Set(v)
return o
}
// Set sets the value to the given value.
func (o *Option[T]) Set(v T) *Option[T] {
o.Value = v
o.Valid = true
return o
}
// Clear marks the value as null/unset/invalid.
func (o *Option[T]) Clear() *Option[T] {
o.Valid = false
return o
}
// Or returns the value of the option if it is not marked
// as null/unset/invalid, and otherwise it returns the given value.
func (o *Option[T]) Or(or T) T {
if o.Valid {
return o.Value
}
return or
}
func (o *Option[T]) ShouldSave() bool {
return o.Valid
}
func (o *Option[T]) ShouldDisplay(field string) bool {
switch field {
case "Value":
return o.Valid
}
return true
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package plan provides an efficient mechanism for updating a slice
// to contain a target list of elements, generating minimal edits to
// modify the current slice contents to match the target.
// The mechanism depends on the use of unique name string identifiers
// to determine whether an element is currently configured correctly.
// These could be algorithmically generated hash strings or any other
// such unique identifier.
package plan
import (
"slices"
"cogentcore.org/core/base/slicesx"
)
// Namer is an interface that types can implement to specify their name in a plan context.
type Namer interface {
// PlanName returns the name of the object in a plan context.
PlanName() string
}
// Update ensures that the elements of the given slice contain
// the elements according to the plan specified by the given arguments.
// The argument n specifies the total number of items in the target plan.
// The elements have unique names specified by the given name function.
// If a new item is needed, the given new function is called to create it
// for the given name at the given index position. After a new element is
// created, it is added to the slice, and if the given optional init function
// is non-nil, it is called with the new element and its index. If the
// given destroy function is not-nil, then it is called on any element
// that is being deleted from the slice. Update returns whether any changes
// were made. The given slice must be a pointer so that it can be modified
// live, which is required for init functions to run when the slice is
// correctly updated to the current state.
func Update[T Namer](s *[]T, n int, name func(i int) string, new func(name string, i int) T, init func(e T, i int), destroy func(e T)) bool {
changed := false
// first make a map for looking up the indexes of the target names
names := make([]string, n)
nmap := make(map[string]int, n)
smap := make(map[string]int, n)
for i := range n {
nm := name(i)
names[i] = nm
if _, has := nmap[nm]; has {
panic("plan.Update: duplicate name: " + nm) // no way to recover
}
nmap[nm] = i
}
// first remove anything we don't want
sn := len(*s)
for i := sn - 1; i >= 0; i-- {
nm := (*s)[i].PlanName()
if _, ok := nmap[nm]; !ok {
changed = true
if destroy != nil {
destroy((*s)[i])
}
*s = slices.Delete(*s, i, i+1)
}
smap[nm] = i
}
// next add and move items as needed; in order so guaranteed
for i, tn := range names {
ci := slicesx.Search(*s, func(e T) bool { return e.PlanName() == tn }, smap[tn])
if ci < 0 { // item not currently on the list
changed = true
ne := new(tn, i)
*s = slices.Insert(*s, i, ne)
if init != nil {
init(ne, i)
}
} else { // on the list; is it in the right place?
if ci != i {
changed = true
e := (*s)[ci]
*s = slices.Delete(*s, ci, ci+1)
*s = slices.Insert(*s, i, e)
}
}
}
return changed
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package profile provides basic but effective profiling of targeted
// functions or code sections, which can often be more informative than
// generic cpu profiling.
//
// Here's how you use it:
//
// // somewhere near start of program (e.g., using flag package)
// profileFlag := flag.Bool("profile", false, "turn on targeted profiling")
// ...
// flag.Parse()
// profile.Profiling = *profileFlag
// ...
// // surrounding the code of interest:
// pr := profile.Start()
// ... code
// pr.End()
// ...
// // at the end or whenever you've got enough data:
// profile.Report(time.Millisecond) // or time.Second or whatever
package profile
import (
"cmp"
"fmt"
"runtime"
"slices"
"strings"
"sync"
"time"
"cogentcore.org/core/base/errors"
)
// Main User API:
// Start starts profiling and returns a Profile struct that must have [Profile.End]
// called on it when done timing. It will be nil if not the first to start
// timing on this function; it assumes nested inner / outer loop structure for
// calls to the same method. It uses the short, package-qualified name of the
// calling function as the name of the profile struct. Extra information can be
// passed to Start, which will be added at the end of the name in a dash-delimited
// format. See [StartName] for a version that supports a custom name.
func Start(info ...string) *Profile {
if !Profiling {
return nil
}
name := ""
pc, _, _, ok := runtime.Caller(1)
if ok {
name = runtime.FuncForPC(pc).Name()
// get rid of everything before the package
if li := strings.LastIndex(name, "/"); li >= 0 {
name = name[li+1:]
}
} else {
err := "profile.Start: unexpected error: unable to get caller"
errors.Log(errors.New(err))
name = "!(" + err + ")"
}
if len(info) > 0 {
name += "-" + strings.Join(info, "-")
}
return TheProfiler.Start(name)
}
// StartName starts profiling and returns a Profile struct that must have
// [Profile.End] called on it when done timing. It will be nil if not the first
// to start timing on this function; it assumes nested inner / outer loop structure
// for calls to the same method. It uses the given name as the name of the profile
// struct. Extra information can be passed to StartName, which will be added at
// the end of the name in a dash-delimited format. See [Start] for a version that
// automatically determines the name from the name of the calling function.
func StartName(name string, info ...string) *Profile {
if len(info) > 0 {
name += "-" + strings.Join(info, "-")
}
return TheProfiler.Start(name)
}
// Report generates a report of all the profile data collected.
func Report(units time.Duration) {
TheProfiler.Report(units)
}
// Reset resets all of the profiling data.
func Reset() {
TheProfiler.Reset()
}
// Profiling is whether profiling is currently enabled.
var Profiling = false
// TheProfiler is the global instance of [Profiler].
var TheProfiler = Profiler{}
// Profile represents one profiled function.
type Profile struct {
Name string
Total time.Duration
N int64
Avg float64
St time.Time
Timing bool
}
func (p *Profile) Start() *Profile {
if !p.Timing {
p.St = time.Now()
p.Timing = true
return p
}
return nil
}
func (p *Profile) End() {
if p == nil || !Profiling {
return
}
dur := time.Since(p.St)
p.Total += dur
p.N++
p.Avg = float64(p.Total) / float64(p.N)
p.Timing = false
}
func (p *Profile) Report(tot float64, units time.Duration) {
us := strings.TrimPrefix(units.String(), "1")
fmt.Printf("%-60sTotal:%8.2f %s\tAvg:%6.2f\tN:%6d\tPct:%6.2f\n",
p.Name, float64(p.Total)/float64(units), us, p.Avg/float64(units), p.N, 100.0*float64(p.Total)/tot)
}
// Profiler manages a map of profiled functions.
type Profiler struct {
Profiles map[string]*Profile
mu sync.Mutex
}
// Start starts profiling and returns a Profile struct that must have .End()
// called on it when done timing
func (p *Profiler) Start(name string) *Profile {
if !Profiling {
return nil
}
p.mu.Lock()
if p.Profiles == nil {
p.Profiles = make(map[string]*Profile, 0)
}
pr, ok := p.Profiles[name]
if !ok {
pr = &Profile{Name: name}
p.Profiles[name] = pr
}
prval := pr.Start()
p.mu.Unlock()
return prval
}
// Report generates a report of all the profile data collected
func (p *Profiler) Report(units time.Duration) {
if !Profiling {
return
}
list := make([]*Profile, len(p.Profiles))
tot := 0.0
idx := 0
for _, pr := range p.Profiles {
tot += float64(pr.Total)
list[idx] = pr
idx++
}
slices.SortFunc(list, func(a, b *Profile) int {
return cmp.Compare(b.Total, a.Total)
})
for _, pr := range list {
pr.Report(tot, units)
}
}
func (p *Profiler) Reset() {
p.Profiles = make(map[string]*Profile, 0)
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package reflectx
import (
"reflect"
"strings"
"sync"
)
// CopyStructDeep copies the struct pointed to by src into the struct
// pointed to by dst, which must have the same type. It is the field
// copying behind [cogentcore.org/core/tree.NodeBase.CopyFieldsFrom].
// It has the semantics of github.com/jinzhu/copier with DeepCopy and
// CaseSensitive for copies between values of the same type, which
// Cogent Core used before, except that it never looks up or calls
// methods. Methods found by name with reflection keep every method of
// every type alive in a whole-program dead code eliminating build.
//
// - Exported fields are copied deeply, except for fields with a
// `copier:"-"` struct tag, which keep their dst values. A field is
// also skipped when a field promoted into its struct through
// embedding has the same name and a `copier:"-"` tag.
// - Unexported fields are copied shallowly.
// - Pointers, slices and maps are copied into the existing dst values:
// a non-nil dst pointer is reused, dst slice elements beyond the
// length of src are kept, and dst map entries whose keys are not in
// src are kept. Nil src slices and maps become empty ones when dst
// is nil, and nil pointer map values become pointers to zero values.
// - An interface holding a struct, map or slice is copied deeply when
// the dst interface is nil, unless the interface is in a field
// promoted through embedding. Other interfaces are assigned.
// - Arrays, funcs, channels and all other values are assigned.
func CopyStructDeep(dst, src any) {
d := reflect.ValueOf(dst).Elem()
s := reflect.ValueOf(src).Elem()
info := structInfoFor(d.Type())
copyStruct(d, s, info, false, info.promoted)
}
// copyValue deeply copies src into dst, which must be settable and
// have the same type as src. If shallow, interfaces are assigned;
// copier assigns them in fields promoted through embedding, as it
// copies those fields a second time from the outer struct, once the
// dst interfaces are no longer nil.
func copyValue(dst, src reflect.Value, shallow bool) {
switch src.Kind() {
case reflect.Struct:
info := structInfoFor(src.Type())
if info.plain {
dst.Set(src)
return
}
copyStruct(dst, src, info, shallow, info.promoted)
case reflect.Pointer:
if src.IsNil() {
dst.Set(reflect.Zero(dst.Type()))
return
}
if dst.IsNil() {
dst.Set(reflect.New(dst.Type().Elem()))
}
copyValue(dst.Elem(), src.Elem(), shallow)
case reflect.Slice:
copySlice(dst, src, shallow)
case reflect.Map:
copyMap(dst, src)
case reflect.Interface:
if shallow || src.IsNil() || !dst.IsNil() {
dst.Set(src)
return
}
e := src.Elem()
switch e.Kind() {
case reflect.Struct, reflect.Map, reflect.Slice:
nv := reflect.New(e.Type()).Elem()
copyValue(nv, e, false)
dst.Set(nv)
default:
dst.Set(src)
}
default:
dst.Set(src)
}
}
func copySlice(dst, src reflect.Value, shallow bool) {
n := src.Len()
et := dst.Type().Elem()
if et.Kind() == reflect.Interface {
// copier always makes a new slice of interfaces.
dst.Set(reflect.MakeSlice(dst.Type(), n, src.Cap()))
shallow = false
} else if dst.IsNil() {
dst.Set(reflect.MakeSlice(dst.Type(), n, src.Cap()))
} else if dst.Len() < n {
if dst.Cap() >= n {
dst.SetLen(n)
} else {
ns := reflect.MakeSlice(dst.Type(), n, n)
reflect.Copy(ns, dst)
dst.Set(ns)
}
}
if isShallow(et) {
reflect.Copy(dst, src)
return
}
for i := range n {
copyValue(dst.Index(i), src.Index(i), shallow)
}
}
func copyMap(dst, src reflect.Value) {
if dst.IsNil() {
dst.Set(reflect.MakeMapWithSize(dst.Type(), src.Len()))
}
et := dst.Type().Elem()
shallow := isShallow(et)
it := src.MapRange()
for it.Next() {
if shallow {
dst.SetMapIndex(it.Key(), it.Value())
continue
}
nv := reflect.New(et).Elem()
v := it.Value()
if et.Kind() == reflect.Pointer && v.IsNil() {
nv.Set(reflect.New(et.Elem()))
} else {
copyValue(nv, v, false)
}
dst.SetMapIndex(it.Key(), nv)
}
}
// copyStruct copies src into dst. The promoted node marks the fields
// that copier copies a second time from an outer struct.
func copyStruct(dst, src reflect.Value, info *structInfo, shallow bool, promoted *pathNode) {
if info.hasUnexported {
// Unexported fields can only be set through the whole struct.
tmp := reflect.New(dst.Type()).Elem()
tmp.Set(src)
for _, i := range info.exported {
tmp.Field(i).Set(dst.Field(i))
}
dst.Set(tmp)
}
for _, f := range info.fields {
if f.shallow {
dst.Field(f.index).Set(src.Field(f.index))
continue
}
fsh := shallow
var sub *pathNode
if promoted != nil {
sub = promoted.kids[f.index]
if sub != nil && sub.hit {
fsh = true
}
}
if !f.embedded || sub == nil {
copyValue(dst.Field(f.index), src.Field(f.index), fsh)
continue
}
d, s := dst.Field(f.index), src.Field(f.index)
if s.Kind() == reflect.Pointer {
if s.IsNil() {
d.Set(reflect.Zero(d.Type()))
continue
}
if d.IsNil() {
d.Set(reflect.New(d.Type().Elem()))
}
d, s = d.Elem(), s.Elem()
}
copyStruct(d, s, structInfoFor(s.Type()), fsh, sub)
}
}
// structInfo is the cached copying information for a struct type.
type structInfo struct {
// fields are the exported fields to copy.
fields []fieldInfo
// exported are the indexes of all exported fields.
exported []int
// promoted has the index paths of the fields promoted through
// embedding that copier copies a second time, from this struct
// or from embedded structs.
promoted *pathNode
// hasUnexported is whether the struct has unexported fields.
hasUnexported bool
// plain is whether the struct can be copied by assignment.
plain bool
}
type fieldInfo struct {
index int
shallow bool
embedded bool
}
// pathNode is a node in a tree of field index paths.
type pathNode struct {
hit bool
kids map[int]*pathNode
}
// addPath returns p with the given path added.
func addPath(p *pathNode, path []int) *pathNode {
if p == nil {
p = &pathNode{}
}
if len(path) == 0 {
p.hit = true
return p
}
if p.kids == nil {
p.kids = map[int]*pathNode{}
}
p.kids[path[0]] = addPath(p.kids[path[0]], path[1:])
return p
}
// addTree returns p with all of the paths in o added under the given
// prefix index.
func addTree(p *pathNode, index int, o *pathNode) *pathNode {
if o == nil {
return p
}
if p == nil {
p = &pathNode{}
}
if p.kids == nil {
p.kids = map[int]*pathNode{}
}
p.kids[index] = mergePaths(p.kids[index], o)
return p
}
// mergePaths returns p with all of the paths in o added.
func mergePaths(p, o *pathNode) *pathNode {
if p == nil {
p = &pathNode{}
}
if o.hit {
p.hit = true
}
for i, k := range o.kids {
if p.kids == nil {
p.kids = map[int]*pathNode{}
}
p.kids[i] = mergePaths(p.kids[i], k)
}
return p
}
var (
structInfosMu sync.RWMutex
structInfos = map[reflect.Type]*structInfo{}
)
func structInfoFor(t reflect.Type) *structInfo {
structInfosMu.RLock()
info := structInfos[t]
structInfosMu.RUnlock()
if info != nil {
return info
}
info = newStructInfo(t)
structInfosMu.Lock()
structInfos[t] = info
structInfosMu.Unlock()
return info
}
func newStructInfo(t reflect.Type) *structInfo {
ignored := map[string]bool{}
var names []string
addDeepFields(t, ignored, &names, map[reflect.Type]bool{})
info := &structInfo{plain: true}
for i := range t.NumField() {
f := t.Field(i)
if !f.IsExported() {
info.hasUnexported = true
continue
}
info.exported = append(info.exported, i)
if ignored[f.Name] {
info.plain = false
continue
}
sh := isShallow(f.Type)
if !sh {
info.plain = false
}
info.fields = append(info.fields, fieldInfo{index: i, shallow: sh, embedded: f.Anonymous})
if f.Anonymous && !sh {
et := f.Type
if et.Kind() == reflect.Pointer {
et = et.Elem()
}
if et.Kind() == reflect.Struct {
info.promoted = addTree(info.promoted, i, structInfoFor(et).promoted)
}
}
}
// copier copies each promoted field again by name from this struct.
for _, name := range names {
if ignored[name] {
continue
}
sf, ok := t.FieldByName(name)
if ok && len(sf.Index) > 1 && exportedPath(t, sf.Index) {
info.promoted = addPath(info.promoted, sf.Index)
}
}
return info
}
// exportedPath returns whether all fields along the index path are exported.
func exportedPath(t reflect.Type, index []int) bool {
for _, i := range index {
if t.Kind() == reflect.Pointer {
t = t.Elem()
}
f := t.Field(i)
if !f.IsExported() {
return false
}
t = f.Type
}
return true
}
// addDeepFields adds the names of the exported fields of t, including
// the fields promoted through exported embedded fields, and records
// whether each is ignored by its copier tag; the last tagged field with
// a given name decides.
func addDeepFields(t reflect.Type, ignored map[string]bool, names *[]string, visited map[reflect.Type]bool) {
for t.Kind() == reflect.Pointer {
t = t.Elem()
}
if t.Kind() != reflect.Struct || visited[t] {
return
}
visited[t] = true
for f := range t.Fields() {
if !f.IsExported() {
continue
}
*names = append(*names, f.Name)
if tag := f.Tag.Get("copier"); tag != "" {
ignored[f.Name] = tagIgnores(tag)
}
if f.Anonymous {
addDeepFields(f.Type, ignored, names, visited)
}
}
visited[t] = false
}
func tagIgnores(tag string) bool {
for part := range strings.SplitSeq(tag, ",") {
if part == "-" {
return true
}
}
return false
}
// isShallow returns whether values of the given type are copied by assignment.
func isShallow(t reflect.Type) bool {
switch t.Kind() {
case reflect.Pointer, reflect.Slice, reflect.Map, reflect.Interface:
return false
case reflect.Struct:
return structInfoFor(t).plain
}
return true
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package reflectx
import (
"fmt"
"log"
"reflect"
"sort"
"strings"
"time"
"cogentcore.org/core/base/errors"
)
// This file contains helpful functions for dealing with maps
// in the reflect system
// MapValueType returns the type of the value for the given map (which can be
// a pointer to a map or a direct map); just Elem() of map type, but using
// this function makes it more explicit what is going on.
func MapValueType(mp any) reflect.Type {
return NonPointerType(reflect.TypeOf(mp)).Elem()
}
// MapKeyType returns the type of the key for the given map (which can be a
// pointer to a map or a direct map); just Key() of map type, but using
// this function makes it more explicit what is going on.
func MapKeyType(mp any) reflect.Type {
return NonPointerType(reflect.TypeOf(mp)).Key()
}
// MapAdd adds a new blank entry to the map.
func MapAdd(mv any) {
mpv := reflect.ValueOf(mv)
mpvnp := Underlying(mpv)
mvtyp := mpvnp.Type()
valtyp := MapValueType(mv)
if valtyp.Kind() == reflect.Interface && valtyp.String() == "interface {}" {
valtyp = reflect.TypeFor[string]()
}
nkey := reflect.New(MapKeyType(mv))
nval := reflect.New(valtyp)
if mpvnp.IsNil() { // make a new map
mpv.Elem().Set(reflect.MakeMap(mvtyp))
mpvnp = Underlying(mpv)
}
mpvnp.SetMapIndex(nkey.Elem(), nval.Elem())
}
// MapDelete deletes the given key from the given map.
func MapDelete(mv any, key reflect.Value) {
mpv := reflect.ValueOf(mv)
mpvnp := Underlying(mpv)
mpvnp.SetMapIndex(key, reflect.Value{}) // delete
}
// MapDeleteAll deletes everything from the given map.
func MapDeleteAll(mv any) {
mpv := reflect.ValueOf(mv)
mpvnp := Underlying(mpv)
if mpvnp.Len() == 0 {
return
}
itr := mpvnp.MapRange()
for itr.Next() {
mpvnp.SetMapIndex(itr.Key(), reflect.Value{}) // delete
}
}
// SortOrder is the direction of a sort: [Ascending] or [Descending].
type SortOrder bool
const (
// Ascending sorts from the smallest to the largest value.
Ascending SortOrder = true
// Descending sorts from the largest to the smallest value.
Descending SortOrder = false
)
// MapSort sorts the keys of the map either by key or by value,
// and returns those keys as a slice of [reflect.Value]s.
func MapSort(mp any, byKey bool, ascending SortOrder) []reflect.Value {
mpv := reflect.ValueOf(mp)
mpvnp := Underlying(mpv)
keys := mpvnp.MapKeys() // note: this is a slice of reflect.Value!
if byKey {
ValueSliceSort(keys, ascending)
} else {
MapValueSort(mpvnp, keys, ascending)
}
return keys
}
// MapValueSort sorts the keys of the given map by their values.
func MapValueSort(mpvnp reflect.Value, keys []reflect.Value, ascending SortOrder) error {
if len(keys) == 0 {
return nil
}
keyval := keys[0]
felval := mpvnp.MapIndex(keyval)
eltyp := felval.Type()
elnptyp := NonPointerType(eltyp)
vk := elnptyp.Kind()
elval := OnePointerValue(felval)
elif := elval.Interface()
// try all the numeric types first!
switch {
case vk >= reflect.Int && vk <= reflect.Int64:
sort.Slice(keys, func(i, j int) bool {
iv := Underlying(mpvnp.MapIndex(keys[i])).Int()
jv := Underlying(mpvnp.MapIndex(keys[j])).Int()
if ascending {
return iv < jv
}
return iv > jv
})
return nil
case vk >= reflect.Uint && vk <= reflect.Uint64:
sort.Slice(keys, func(i, j int) bool {
iv := Underlying(mpvnp.MapIndex(keys[i])).Uint()
jv := Underlying(mpvnp.MapIndex(keys[j])).Uint()
if ascending {
return iv < jv
}
return iv > jv
})
return nil
case vk >= reflect.Float32 && vk <= reflect.Float64:
sort.Slice(keys, func(i, j int) bool {
iv := Underlying(mpvnp.MapIndex(keys[i])).Float()
jv := Underlying(mpvnp.MapIndex(keys[j])).Float()
if ascending {
return iv < jv
}
return iv > jv
})
return nil
case vk == reflect.Struct && ShortTypeName(elnptyp) == "time.Time":
sort.Slice(keys, func(i, j int) bool {
iv := Underlying(mpvnp.MapIndex(keys[i])).Interface().(time.Time)
jv := Underlying(mpvnp.MapIndex(keys[j])).Interface().(time.Time)
if ascending {
return iv.Before(jv)
}
return jv.Before(iv)
})
}
// this stringer case will likely pick up most of the rest
switch elif.(type) {
case fmt.Stringer:
sort.Slice(keys, func(i, j int) bool {
iv := Underlying(mpvnp.MapIndex(keys[i])).Interface().(fmt.Stringer).String()
jv := Underlying(mpvnp.MapIndex(keys[j])).Interface().(fmt.Stringer).String()
if ascending {
return iv < jv
}
return iv > jv
})
return nil
}
// last resort!
switch vk {
case reflect.String:
sort.Slice(keys, func(i, j int) bool {
iv := Underlying(mpvnp.MapIndex(keys[i])).String()
jv := Underlying(mpvnp.MapIndex(keys[j])).String()
if ascending {
return strings.ToLower(iv) < strings.ToLower(jv)
}
return strings.ToLower(iv) > strings.ToLower(jv)
})
return nil
}
err := fmt.Errorf("MapValueSort: unable to sort elements of type: %v", eltyp.String())
log.Println(err)
return err
}
// SetMapRobust robustly sets a map value using [reflect.Value]
// representations of the map, key, and value elements, ensuring that the
// proper types are used for the key and value elements using sensible
// conversions.
func SetMapRobust(mp, ky, val reflect.Value) bool {
mtyp := mp.Type()
if mtyp.Kind() != reflect.Map {
log.Printf("reflectx.SetMapRobust: map arg is not map, is: %v\n", mtyp.String())
return false
}
if !mp.CanSet() {
log.Printf("reflectx.SetMapRobust: map arg is not settable: %v\n", mtyp.String())
return false
}
ktyp := mtyp.Key()
etyp := mtyp.Elem()
// a key or value of a different (named) type of the same kind
// must be converted to the type of the map too.
if !ky.Type().AssignableTo(ktyp) {
ky = ky.Convert(ktyp)
}
if !val.Type().AssignableTo(etyp) {
val = val.Convert(etyp)
}
mp.SetMapIndex(ky, val)
return true
}
// CopyMapRobust robustly copies maps.
func CopyMapRobust(to, from any) error {
tov := reflect.ValueOf(to)
fmv := reflect.ValueOf(from)
tonp := Underlying(tov)
fmnp := Underlying(fmv)
totyp := tonp.Type()
if totyp.Kind() != reflect.Map {
err := fmt.Errorf("reflectx.CopyMapRobust: 'to' is not map, is: %v", totyp)
return errors.Log(err)
}
fmtyp := fmnp.Type()
if fmtyp.Kind() != reflect.Map {
err := fmt.Errorf("reflectx.CopyMapRobust: 'from' is not map, is: %v", fmtyp)
return errors.Log(err)
}
if tonp.IsNil() {
OnePointerValue(tov).Elem().Set(reflect.MakeMap(totyp))
} else {
MapDeleteAll(to)
}
if fmnp.Len() == 0 {
return nil
}
eltyp := SliceElementType(to)
itr := fmnp.MapRange()
for itr.Next() {
tonp.SetMapIndex(itr.Key(), CloneToType(eltyp, itr.Value().Interface()).Elem())
}
return nil
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package reflectx
import (
"reflect"
)
// NonPointerType returns a non-pointer version of the given type.
func NonPointerType(typ reflect.Type) reflect.Type {
if typ == nil {
return typ
}
for typ.Kind() == reflect.Pointer {
typ = typ.Elem()
}
return typ
}
// NonPointerValue returns a non-pointer version of the given value.
// If it encounters a nil pointer, it returns the nil pointer instead
// of an invalid value.
func NonPointerValue(v reflect.Value) reflect.Value {
for v.Kind() == reflect.Pointer {
new := v.Elem()
if !new.IsValid() {
return v
}
v = new
}
return v
}
// PointerValue returns a pointer to the given value if it is not already
// a pointer.
func PointerValue(v reflect.Value) reflect.Value {
if !v.IsValid() {
return v
}
if v.Kind() == reflect.Pointer {
return v
}
if v.CanAddr() {
return v.Addr()
}
pv := reflect.New(v.Type())
pv.Elem().Set(v)
return pv
}
// OnePointerValue returns a value that is exactly one pointer away
// from a non-pointer value.
func OnePointerValue(v reflect.Value) reflect.Value {
if !v.IsValid() {
return v
}
if v.Kind() != reflect.Pointer {
if v.CanAddr() {
return v.Addr()
}
// slog.Error("reflectx.OnePointerValue: cannot take address of value", "value", v)
pv := reflect.New(v.Type())
pv.Elem().Set(v)
return pv
}
for v.Elem().Kind() == reflect.Pointer {
v = v.Elem()
}
return v
}
// Underlying returns the actual underlying version of the given value,
// going through any pointers and interfaces. If it encounters a nil
// pointer or interface, it returns the nil pointer or interface instead of
// an invalid value.
func Underlying(v reflect.Value) reflect.Value {
if !v.IsValid() {
return v
}
for v.Type().Kind() == reflect.Interface || v.Type().Kind() == reflect.Pointer {
new := v.Elem()
if !new.IsValid() {
return v
}
v = new
}
return v
}
// UnderlyingPointer returns a pointer to the actual underlying version of the
// given value, going through any pointers and interfaces. It is equivalent to
// [OnePointerValue] of [Underlying], so if it encounters a nil pointer or
// interface, it stops at the nil pointer or interface instead of returning
// an invalid value.
func UnderlyingPointer(v reflect.Value) reflect.Value {
if !v.IsValid() {
return v
}
uv := Underlying(v)
if !uv.IsValid() {
return v
}
return OnePointerValue(uv)
}
// NonNilNew has the same overall behavior as [reflect.New] except that
// it traverses through any pointers such that a new zero non-pointer value
// will be created in the end, so any pointers in the original type will not
// be nil. For example, in pseudo-code, NonNilNew(**int) will return
// &(&(&(0))).
func NonNilNew(typ reflect.Type) reflect.Value {
n := 0
for typ.Kind() == reflect.Pointer {
n++
typ = typ.Elem()
}
v := reflect.New(typ)
for range n {
pv := reflect.New(v.Type())
pv.Elem().Set(v)
v = pv
}
return v
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package reflectx
import (
"fmt"
"reflect"
"sort"
"strings"
"time"
"cogentcore.org/core/base/errors"
)
// This file contains helpful functions for dealing with slices
// in the reflect system
// SliceElementType returns the type of the elements of the given slice (which can be
// a pointer to a slice or a direct slice); just [reflect.Type.Elem] of slice type, but
// using this function bypasses any pointer issues and makes it more explicit what is going on.
func SliceElementType(sl any) reflect.Type {
return Underlying(reflect.ValueOf(sl)).Type().Elem()
}
// SliceElementValue returns a new [reflect.Value] of the [SliceElementType].
func SliceElementValue(sl any) reflect.Value {
return NonNilNew(SliceElementType(sl)).Elem()
}
// SliceNewAt inserts a new blank element at the given index in the given slice.
// -1 means the end.
func SliceNewAt(sl any, idx int) {
up := UnderlyingPointer(reflect.ValueOf(sl))
np := up.Elem()
val := SliceElementValue(sl)
sz := np.Len()
np = reflect.Append(np, val)
if idx >= 0 && idx < sz {
reflect.Copy(np.Slice(idx+1, sz+1), np.Slice(idx, sz))
np.Index(idx).Set(val)
}
up.Elem().Set(np)
}
// SliceDeleteAt deletes the element at the given index in the given slice.
func SliceDeleteAt(sl any, idx int) {
svl := OnePointerValue(reflect.ValueOf(sl))
svnp := NonPointerValue(svl)
svtyp := svnp.Type()
nval := reflect.New(svtyp.Elem())
sz := svnp.Len()
reflect.Copy(svnp.Slice(idx, sz-1), svnp.Slice(idx+1, sz))
svnp.Index(sz - 1).Set(nval.Elem())
svl.Elem().Set(svnp.Slice(0, sz-1))
}
// SliceSort sorts a slice of basic values (see [StructSliceSort] for sorting a
// slice-of-struct using a specific field), using float, int, string, and [time.Time]
// conversions.
func SliceSort(sl any, ascending SortOrder) error {
sv := reflect.ValueOf(sl)
svnp := NonPointerValue(sv)
if svnp.Len() == 0 {
return nil
}
eltyp := SliceElementType(sl)
elnptyp := NonPointerType(eltyp)
vk := elnptyp.Kind()
elval := OnePointerValue(svnp.Index(0))
elif := elval.Interface()
// try all the numeric types first!
switch {
case vk >= reflect.Int && vk <= reflect.Int64:
sort.Slice(svnp.Interface(), func(i, j int) bool {
iv := NonPointerValue(svnp.Index(i)).Int()
jv := NonPointerValue(svnp.Index(j)).Int()
if ascending {
return iv < jv
}
return iv > jv
})
return nil
case vk >= reflect.Uint && vk <= reflect.Uint64:
sort.Slice(svnp.Interface(), func(i, j int) bool {
iv := NonPointerValue(svnp.Index(i)).Uint()
jv := NonPointerValue(svnp.Index(j)).Uint()
if ascending {
return iv < jv
}
return iv > jv
})
return nil
case vk >= reflect.Float32 && vk <= reflect.Float64:
sort.Slice(svnp.Interface(), func(i, j int) bool {
iv := NonPointerValue(svnp.Index(i)).Float()
jv := NonPointerValue(svnp.Index(j)).Float()
if ascending {
return iv < jv
}
return iv > jv
})
return nil
case vk == reflect.Struct && ShortTypeName(elnptyp) == "time.Time":
sort.Slice(svnp.Interface(), func(i, j int) bool {
iv := NonPointerValue(svnp.Index(i)).Interface().(time.Time)
jv := NonPointerValue(svnp.Index(j)).Interface().(time.Time)
if ascending {
return iv.Before(jv)
}
return jv.Before(iv)
})
}
// this stringer case will likely pick up most of the rest
switch elif.(type) {
case fmt.Stringer:
sort.Slice(svnp.Interface(), func(i, j int) bool {
iv := NonPointerValue(svnp.Index(i)).Interface().(fmt.Stringer).String()
jv := NonPointerValue(svnp.Index(j)).Interface().(fmt.Stringer).String()
if ascending {
return iv < jv
}
return iv > jv
})
return nil
}
// last resort!
switch vk {
case reflect.String:
sort.Slice(svnp.Interface(), func(i, j int) bool {
iv := NonPointerValue(svnp.Index(i)).String()
jv := NonPointerValue(svnp.Index(j)).String()
if ascending {
return strings.ToLower(iv) < strings.ToLower(jv)
}
return strings.ToLower(iv) > strings.ToLower(jv)
})
return nil
}
err := fmt.Errorf("SortSlice: unable to sort elements of type: %v", eltyp.String())
return errors.Log(err)
}
// StructSliceSort sorts the given slice of structs according to the given field
// indexes and sort direction, using bool (false first), float, int, string,
// and [time.Time] conversions. The sort is stable, so that the order of the
// structs with equal values stays the same, as for sorting again.
// It will panic if the field indexes are invalid.
func StructSliceSort(structSlice any, fieldIndex []int, ascending SortOrder) error {
sv := reflect.ValueOf(structSlice)
svnp := NonPointerValue(sv)
if svnp.Len() == 0 {
return nil
}
structTyp := SliceElementType(structSlice)
structNptyp := NonPointerType(structTyp)
fld := structNptyp.FieldByIndex(fieldIndex) // not easy to check.
vk := fld.Type.Kind()
structVal := OnePointerValue(svnp.Index(0))
fieldVal := structVal.Elem().FieldByIndex(fieldIndex)
fieldIf := fieldVal.Interface()
// try all the numeric types first!
switch {
case vk == reflect.Bool:
sort.SliceStable(svnp.Interface(), func(i, j int) bool {
ival := OnePointerValue(svnp.Index(i))
iv := ival.Elem().FieldByIndex(fieldIndex).Bool()
jval := OnePointerValue(svnp.Index(j))
jv := jval.Elem().FieldByIndex(fieldIndex).Bool()
if ascending {
return !iv && jv
}
return iv && !jv
})
return nil
case vk >= reflect.Int && vk <= reflect.Int64:
sort.SliceStable(svnp.Interface(), func(i, j int) bool {
ival := OnePointerValue(svnp.Index(i))
iv := ival.Elem().FieldByIndex(fieldIndex).Int()
jval := OnePointerValue(svnp.Index(j))
jv := jval.Elem().FieldByIndex(fieldIndex).Int()
if ascending {
return iv < jv
}
return iv > jv
})
return nil
case vk >= reflect.Uint && vk <= reflect.Uint64:
sort.SliceStable(svnp.Interface(), func(i, j int) bool {
ival := OnePointerValue(svnp.Index(i))
iv := ival.Elem().FieldByIndex(fieldIndex).Uint()
jval := OnePointerValue(svnp.Index(j))
jv := jval.Elem().FieldByIndex(fieldIndex).Uint()
if ascending {
return iv < jv
}
return iv > jv
})
return nil
case vk >= reflect.Float32 && vk <= reflect.Float64:
sort.SliceStable(svnp.Interface(), func(i, j int) bool {
ival := OnePointerValue(svnp.Index(i))
iv := ival.Elem().FieldByIndex(fieldIndex).Float()
jval := OnePointerValue(svnp.Index(j))
jv := jval.Elem().FieldByIndex(fieldIndex).Float()
if ascending {
return iv < jv
}
return iv > jv
})
return nil
case vk == reflect.Struct && ShortTypeName(fld.Type) == "time.Time":
sort.SliceStable(svnp.Interface(), func(i, j int) bool {
ival := OnePointerValue(svnp.Index(i))
iv := ival.Elem().FieldByIndex(fieldIndex).Interface().(time.Time)
jval := OnePointerValue(svnp.Index(j))
jv := jval.Elem().FieldByIndex(fieldIndex).Interface().(time.Time)
if ascending {
return iv.Before(jv)
}
return jv.Before(iv)
})
}
// this stringer case will likely pick up most of the rest
switch fieldIf.(type) {
case fmt.Stringer:
sort.SliceStable(svnp.Interface(), func(i, j int) bool {
ival := OnePointerValue(svnp.Index(i))
iv := ival.Elem().FieldByIndex(fieldIndex).Interface().(fmt.Stringer).String()
jval := OnePointerValue(svnp.Index(j))
jv := jval.Elem().FieldByIndex(fieldIndex).Interface().(fmt.Stringer).String()
if ascending {
return iv < jv
}
return iv > jv
})
return nil
}
// last resort!
switch vk {
case reflect.String:
sort.SliceStable(svnp.Interface(), func(i, j int) bool {
ival := OnePointerValue(svnp.Index(i))
iv := ival.Elem().FieldByIndex(fieldIndex).String()
jval := OnePointerValue(svnp.Index(j))
jv := jval.Elem().FieldByIndex(fieldIndex).String()
if ascending {
return strings.ToLower(iv) < strings.ToLower(jv)
}
return strings.ToLower(iv) > strings.ToLower(jv)
})
return nil
}
err := fmt.Errorf("SortStructSlice: unable to sort on field of type: %v", fld.Type.String())
return errors.Log(err)
}
// ValueSliceSort sorts a slice of [reflect.Value]s using basic types where possible.
func ValueSliceSort(sl []reflect.Value, ascending SortOrder) error {
if len(sl) == 0 {
return nil
}
felval := sl[0] // reflect.Value
eltyp := felval.Type()
elnptyp := NonPointerType(eltyp)
vk := elnptyp.Kind()
elval := OnePointerValue(felval)
elif := elval.Interface()
// try all the numeric types first!
switch {
case vk >= reflect.Int && vk <= reflect.Int64:
sort.Slice(sl, func(i, j int) bool {
iv := NonPointerValue(sl[i]).Int()
jv := NonPointerValue(sl[j]).Int()
if ascending {
return iv < jv
}
return iv > jv
})
return nil
case vk >= reflect.Uint && vk <= reflect.Uint64:
sort.Slice(sl, func(i, j int) bool {
iv := NonPointerValue(sl[i]).Uint()
jv := NonPointerValue(sl[j]).Uint()
if ascending {
return iv < jv
}
return iv > jv
})
return nil
case vk >= reflect.Float32 && vk <= reflect.Float64:
sort.Slice(sl, func(i, j int) bool {
iv := NonPointerValue(sl[i]).Float()
jv := NonPointerValue(sl[j]).Float()
if ascending {
return iv < jv
}
return iv > jv
})
return nil
case vk == reflect.Struct && ShortTypeName(elnptyp) == "time.Time":
sort.Slice(sl, func(i, j int) bool {
iv := NonPointerValue(sl[i]).Interface().(time.Time)
jv := NonPointerValue(sl[j]).Interface().(time.Time)
if ascending {
return iv.Before(jv)
}
return jv.Before(iv)
})
}
// this stringer case will likely pick up most of the rest
switch elif.(type) {
case fmt.Stringer:
sort.Slice(sl, func(i, j int) bool {
iv := NonPointerValue(sl[i]).Interface().(fmt.Stringer).String()
jv := NonPointerValue(sl[j]).Interface().(fmt.Stringer).String()
if ascending {
return iv < jv
}
return iv > jv
})
return nil
}
// last resort!
switch vk {
case reflect.String:
sort.Slice(sl, func(i, j int) bool {
iv := NonPointerValue(sl[i]).String()
jv := NonPointerValue(sl[j]).String()
if ascending {
return strings.ToLower(iv) < strings.ToLower(jv)
}
return strings.ToLower(iv) > strings.ToLower(jv)
})
return nil
}
err := fmt.Errorf("ValueSliceSort: unable to sort elements of type: %v", eltyp.String())
return errors.Log(err)
}
// CopySliceRobust robustly copies slices.
func CopySliceRobust(to, from any) error {
tov := reflect.ValueOf(to)
fmv := reflect.ValueOf(from)
tonp := Underlying(tov)
fmnp := Underlying(fmv)
totyp := tonp.Type()
if totyp.Kind() != reflect.Slice {
err := fmt.Errorf("reflectx.CopySliceRobust: 'to' is not slice, is: %v", totyp.String())
return errors.Log(err)
}
fmtyp := fmnp.Type()
if fmtyp.Kind() != reflect.Slice {
err := fmt.Errorf("reflectx.CopySliceRobust: 'from' is not slice, is: %v", fmtyp.String())
return errors.Log(err)
}
fmlen := fmnp.Len()
if tonp.IsNil() {
tonp.Set(reflect.MakeSlice(totyp, fmlen, fmlen))
} else {
if tonp.Len() > fmlen {
tonp.SetLen(fmlen)
}
}
for i := range fmlen {
tolen := tonp.Len()
if i >= tolen {
SliceNewAt(to, i)
}
SetRobust(PointerValue(tonp.Index(i)).Interface(), fmnp.Index(i).Interface())
}
return nil
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package reflectx
import (
"fmt"
"log/slog"
"reflect"
"strconv"
"strings"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/iox/jsonx"
)
// WalkFields calls the given walk function on all the exported primary fields of the
// given parent struct value, including those on anonymous embedded
// structs that this struct has. It effectively flattens all of the embedded fields
// of the struct.
//
// It passes the current parent struct, current [reflect.StructField],
// and current field value to the given should and walk functions.
//
// The given should function is called on every struct field (including
// on embedded structs themselves) to determine whether that field and any fields
// it has embedded should be handled (a return value of true indicates to continue
// down and a value of false indicates to not).
func WalkFields(parent reflect.Value, should func(parent reflect.Value, field reflect.StructField, value reflect.Value) bool, walk func(parent reflect.Value, parentField *reflect.StructField, field reflect.StructField, value reflect.Value)) {
walkFields(parent, nil, should, walk)
}
func walkFields(parent reflect.Value, parentField *reflect.StructField, should func(parent reflect.Value, field reflect.StructField, value reflect.Value) bool, walk func(parent reflect.Value, parentField *reflect.StructField, field reflect.StructField, value reflect.Value)) {
typ := parent.Type()
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
if !field.IsExported() {
continue
}
value := parent.Field(i)
if !should(parent, field, value) {
continue
}
if field.Type.Kind() == reflect.Struct && field.Anonymous {
walkFields(value, &field, should, walk)
} else {
walk(parent, parentField, field, value)
}
}
}
// NumAllFields returns the number of elemental fields in the given struct type
// using [WalkFields].
func NumAllFields(parent reflect.Value) int {
n := 0
WalkFields(parent,
func(parent reflect.Value, field reflect.StructField, value reflect.Value) bool {
return true
}, func(parent reflect.Value, parentField *reflect.StructField, field reflect.StructField, value reflect.Value) {
n++
})
return n
}
// ValueIsDefault returns whether the given value is equivalent to the
// given string representation used in a field default tag.
func ValueIsDefault(fv reflect.Value, def string) bool {
kind := fv.Kind()
if kind >= reflect.Int && kind <= reflect.Complex128 && strings.Contains(def, ":") {
dtags := strings.Split(def, ":")
lo, _ := strconv.ParseFloat(dtags[0], 64)
hi, _ := strconv.ParseFloat(dtags[1], 64)
vf, err := ToFloat(fv.Interface())
if err != nil {
slog.Error("reflectx.ValueIsDefault: error parsing struct field numerical range def tag", "def", def, "err", err)
return true
}
return lo <= vf && vf <= hi
}
dtags := strings.Split(def, ",")
if strings.ContainsAny(def, "{[") { // complex type, so don't split on commas
dtags = []string{def}
}
for _, df := range dtags {
df = FormatDefault(df)
if df == "" {
return fv.IsZero()
}
dv := reflect.New(fv.Type())
err := SetRobust(dv.Interface(), df)
if err != nil {
slog.Error("reflectx.ValueIsDefault: error getting value from default struct tag", "defaultStructTag", df, "value", fv, "err", err)
return false
}
if reflect.DeepEqual(fv.Interface(), dv.Elem().Interface()) {
return true
}
}
return false
}
// SetFromDefaultTags sets the values of fields in the given struct based on
// `default:` default value struct field tags.
func SetFromDefaultTags(v any) error {
ov := reflect.ValueOf(v)
if IsNil(ov) {
return nil
}
val := NonPointerValue(ov)
typ := val.Type()
for i := 0; i < typ.NumField(); i++ {
f := typ.Field(i)
if !f.IsExported() {
continue
}
fv := val.Field(i)
def := f.Tag.Get("default")
if NonPointerType(f.Type).Kind() == reflect.Struct && def == "" {
SetFromDefaultTags(PointerValue(fv).Interface())
continue
}
err := SetFromDefaultTag(fv, def)
if err != nil {
return fmt.Errorf("reflectx.SetFromDefaultTags: error setting field %q in object of type %q from val %q: %w", f.Name, typ.Name(), def, err)
}
}
return nil
}
// SetFromDefaultTag sets the given value from the given default tag.
func SetFromDefaultTag(v reflect.Value, def string) error {
def = FormatDefault(def)
if def == "" {
return nil
}
return SetRobust(UnderlyingPointer(v).Interface(), def)
}
// ShouldSaver is an interface that types can implement to specify
// whether a value should be included in the result of [NonDefaultFields].
type ShouldSaver interface {
// ShouldSave returns whether this value should be included in the
// result of [NonDefaultFields].
ShouldSave() bool
}
// TODO: it would be good to return a keylist or struct of the fields for
// ordered output, but that may be difficult.
// NonDefaultFields returns a map representing all of the fields of the given
// struct (or pointer to a struct) that have values different than their default
// values as specified by the `default:` struct tag. The resulting map is then typically
// saved using something like JSON or TOML. If a value has no default value, it
// checks whether its value is non-zero. If a field has a `save:"-"` tag, it wil
// not be included in the resulting map. If a field implements [ShouldSaver] and
// returns false, it will not be included in the resulting map.
func NonDefaultFields(v any) map[string]any {
res := map[string]any{}
rv := Underlying(reflect.ValueOf(v))
if IsNil(rv) {
return nil
}
rt := rv.Type()
nf := rt.NumField()
for i := range nf {
fv := rv.Field(i)
ft := rt.Field(i)
if !ft.IsExported() || ft.Tag.Get("save") == "-" { // (unexported fields cannot be saved)
continue
}
if ss, ok := reflect.TypeAssert[ShouldSaver](UnderlyingPointer(fv)); ok {
if !ss.ShouldSave() {
continue
}
}
def := ft.Tag.Get("default")
if NonPointerType(ft.Type).Kind() == reflect.Struct && def == "" {
sfm := NonDefaultFields(fv.Interface())
if len(sfm) > 0 {
res[ft.Name] = sfm
}
continue
}
if !ValueIsDefault(fv, def) {
res[ft.Name] = fv.Interface()
}
}
return res
}
// FormatDefault converts the given `default:` struct tag string into a format suitable
// for being used as a value in [SetRobust]. If it returns "", the default value
// should not be used.
func FormatDefault(def string) string {
if def == "" {
return ""
}
if strings.ContainsAny(def, "{[") { // complex type, so don't split on commas and colons
return strings.ReplaceAll(def, `'`, `"`) // allow single quote to work as double quote for JSON format
}
// we split on commas and colons so we get the first item of lists and ranges
def = strings.Split(def, ",")[0]
def = strings.Split(def, ":")[0]
return def
}
// StructTags returns a map[string]string of the tag string from a [reflect.StructTag] value.
func StructTags(tags reflect.StructTag) map[string]string {
if len(tags) == 0 {
return nil
}
flds := strings.Fields(string(tags))
smap := make(map[string]string, len(flds))
for _, fld := range flds {
cli := strings.Index(fld, ":")
if cli < 0 || len(fld) < cli+3 {
continue
}
vl := strings.TrimSuffix(fld[cli+2:], `"`)
smap[fld[:cli]] = vl
}
return smap
}
// StringJSON returns an indented JSON string representation
// of the given value for printing/debugging.
func StringJSON(v any) string {
return string(errors.Log1(jsonx.WriteBytesIndent(v)))
}
// FieldByPath returns the [reflect.Value] of given field within given struct value,
// where the field can be a path with . separators, for fields within struct fields.
func FieldByPath(s reflect.Value, fieldPath string) (reflect.Value, error) {
sv := Underlying(s)
if sv.Kind() != reflect.Struct {
return reflect.Value{}, errors.New("reflectx.FieldByPath: kind is not struct")
}
fps := strings.SplitSeq(fieldPath, ".")
for fp := range fps {
fv := sv.FieldByName(fp)
if !fv.IsValid() {
return reflect.Value{}, errors.New("reflectx.FieldByPath: field name not found: " + fp)
}
sv = fv
}
return sv, nil
}
// CopyFields copies the named fields from src struct into dest struct.
// Fields can be paths with . separators for sub-fields of fields.
func CopyFields(dest, src any, fields ...string) error {
dsv := Underlying(reflect.ValueOf(dest))
if dsv.Kind() != reflect.Struct {
return errors.New("reflectx.CopyFields: destination kind is not struct")
}
ssv := Underlying(reflect.ValueOf(src))
if ssv.Kind() != reflect.Struct {
return errors.New("reflectx.CopyFields: source kind is not struct")
}
var errs []error
for _, f := range fields {
dfv, err := FieldByPath(dsv, f)
if err != nil {
errs = append(errs, err)
continue
}
sfv, err := FieldByPath(ssv, f)
if err != nil {
errs = append(errs, err)
continue
}
err = SetRobust(PointerValue(dfv).Interface(), sfv.Interface())
if err != nil {
errs = append(errs, err)
continue
}
}
return errors.Join(errs...)
}
// SetFieldsFromMap sets given map[string]any values to fields of given object,
// where the map keys are field paths (with . delimiters for sub-field paths).
// The value can be any appropriate type that applies to the given field.
// A value that is itself a map[string]any, for a field of struct type
// (or pointer to struct, which is allocated if nil), is applied recursively
// to the fields of that struct, so nested tables as decoded from TOML or JSON
// (e.g., PartialRange = {Min = 0.2, Max = 1}) work the same as
// dotted paths ("PartialRange.Min" = 0.2).
// It logs a message for each value that fails to be set, including
// field names that are not found, and returns an error joining all of them.
func SetFieldsFromMap(obj any, vals map[string]any) error {
objv := reflect.ValueOf(obj)
npv := NonPointerValue(objv)
if npv.Kind() == reflect.Map {
return errors.Log(CopyMapRobust(obj, vals))
}
return setFieldsFromMap(objv, vals, "")
}
// setFieldsFromMap is the recursive implementation of [SetFieldsFromMap],
// where prefix is the path of objv within the top-level object, for messages.
// It logs each error at the point of failure.
func setFieldsFromMap(objv reflect.Value, vals map[string]any, prefix string) error {
var errs []error
for k, v := range vals {
path := prefix + k
fld, err := FieldByPath(objv, k)
if err != nil {
errs = append(errs, errors.Log(fmt.Errorf("SetFieldsFromMap: field: %s: %w", path, err)))
continue
}
if sub, ok := v.(map[string]any); ok && NonPointerType(fld.Type()).Kind() == reflect.Struct {
if fld.Kind() == reflect.Pointer && fld.IsNil() {
fld.Set(reflect.New(fld.Type().Elem()))
}
if err := setFieldsFromMap(fld, sub, path+"."); err != nil {
errs = append(errs, err)
}
continue
}
err = SetRobust(PointerValue(fld).Interface(), v)
if err != nil {
errs = append(errs, errors.Log(fmt.Errorf("SetFieldsFromMap: was not able to apply value: %v to field: %s: %w", v, path, err)))
}
}
return errors.Join(errs...)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package reflectx
import (
"path"
"reflect"
)
// LongTypeName returns the long, full package-path qualified type name.
// This is guaranteed to be unique and used for internal storage of
// several maps to avoid any conflicts. It is also very quick to compute.
func LongTypeName(typ reflect.Type) string {
nptyp := NonPointerType(typ)
nm := nptyp.Name()
if nm != "" {
p := nptyp.PkgPath()
if p != "" {
return p + "." + nm
}
return nm
}
return typ.String()
}
// ShortTypeName returns the short version of a package-qualified type name
// which just has the last element of the path. This is what is used in
// standard Go programming, and is is used for the key to lookup reflect.Type
// names -- i.e., this is what you should save in a JSON file.
// The potential naming conflict is worth the brevity, and typically a given
// file will only contain mutually compatible, non-conflicting types.
// This is cached in ShortNames because the path.Base computation is apparently
// a bit slow.
func ShortTypeName(typ reflect.Type) string {
nptyp := NonPointerType(typ)
nm := nptyp.Name()
if nm != "" {
p := nptyp.PkgPath()
if p != "" {
return path.Base(p) + "." + nm
}
return nm
}
return typ.String()
}
// CloneToType creates a new pointer to the given type
// and uses [SetRobust] to copy an existing value
// (of potentially another type) to it.
func CloneToType(typ reflect.Type, val any) reflect.Value {
vn := reflect.New(typ)
evi := vn.Interface()
SetRobust(evi, val)
return vn
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package reflectx provides a collection of helpers for the reflect
// package in the Go standard library.
package reflectx
import (
"encoding/json"
"fmt"
"image"
"image/color"
"reflect"
"strconv"
"time"
"cogentcore.org/core/base/bools"
"cogentcore.org/core/base/elide"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/colors"
"cogentcore.org/core/enums"
)
// IsNil returns whether the given value is nil or invalid.
// If it is a non-nillable type, it does not check whether
// it is nil to avoid panics.
func IsNil(v reflect.Value) bool {
if !v.IsValid() {
return true
}
switch v.Kind() {
case reflect.Pointer, reflect.Interface, reflect.Map, reflect.Slice, reflect.Func, reflect.Chan:
return v.IsNil()
}
return false
}
// KindIsBasic returns whether the given [reflect.Kind] is a basic,
// elemental type such as Int, Float, etc.
func KindIsBasic(vk reflect.Kind) bool {
return vk >= reflect.Bool && vk <= reflect.Complex128
}
// KindIsNumber returns whether the given [reflect.Kind] is a numeric
// type such as Int, Float, etc.
func KindIsNumber(vk reflect.Kind) bool {
return vk >= reflect.Int && vk <= reflect.Complex128
}
// KindIsInt returns whether the given [reflect.Kind] is an int
// type such as int, int32 etc.
func KindIsInt(vk reflect.Kind) bool {
return vk >= reflect.Int && vk <= reflect.Uintptr
}
// KindIsFloat returns whether the given [reflect.Kind] is a
// float32 or float64.
func KindIsFloat(vk reflect.Kind) bool {
return vk >= reflect.Float32 && vk <= reflect.Float64
}
// ToBool robustly converts to a bool any basic elemental type
// (including pointers to such) using a big type switch organized
// for greatest efficiency. It tries the [bools.Booler]
// interface if not a bool type. It falls back on reflection when all
// else fails.
func ToBool(v any) (bool, error) {
switch vt := v.(type) {
case bool:
return vt, nil
case *bool:
if vt == nil {
return false, errors.New("got nil *bool")
}
return *vt, nil
}
if br, ok := v.(bools.Booler); ok {
return br.Bool(), nil
}
switch vt := v.(type) {
case int:
return vt != 0, nil
case *int:
if vt == nil {
return false, errors.New("got nil *int")
}
return *vt != 0, nil
case int32:
return vt != 0, nil
case *int32:
if vt == nil {
return false, errors.New("got nil *int32")
}
return *vt != 0, nil
case int64:
return vt != 0, nil
case *int64:
if vt == nil {
return false, errors.New("got nil *int64")
}
return *vt != 0, nil
case uint8:
return vt != 0, nil
case *uint8:
if vt == nil {
return false, errors.New("got nil *uint8")
}
return *vt != 0, nil
case float64:
return vt != 0, nil
case *float64:
if vt == nil {
return false, errors.New("got nil *float64")
}
return *vt != 0, nil
case float32:
return vt != 0, nil
case *float32:
if vt == nil {
return false, errors.New("got nil *float32")
}
return *vt != 0, nil
case string:
r, err := strconv.ParseBool(vt)
if err != nil {
return false, err
}
return r, nil
case *string:
if vt == nil {
return false, errors.New("got nil *string")
}
r, err := strconv.ParseBool(*vt)
if err != nil {
return false, err
}
return r, nil
case int8:
return vt != 0, nil
case *int8:
if vt == nil {
return false, errors.New("got nil *int8")
}
return *vt != 0, nil
case int16:
return vt != 0, nil
case *int16:
if vt == nil {
return false, errors.New("got nil *int16")
}
return *vt != 0, nil
case uint:
return vt != 0, nil
case *uint:
if vt == nil {
return false, errors.New("got nil *uint")
}
return *vt != 0, nil
case uint16:
return vt != 0, nil
case *uint16:
if vt == nil {
return false, errors.New("got nil *uint16")
}
return *vt != 0, nil
case uint32:
return vt != 0, nil
case *uint32:
if vt == nil {
return false, errors.New("got nil *uint32")
}
return *vt != 0, nil
case uint64:
return vt != 0, nil
case *uint64:
if vt == nil {
return false, errors.New("got nil *uint64")
}
return *vt != 0, nil
case uintptr:
return vt != 0, nil
case *uintptr:
if vt == nil {
return false, errors.New("got nil *uintptr")
}
return *vt != 0, nil
}
// then fall back on reflection
uv := Underlying(reflect.ValueOf(v))
if IsNil(uv) {
return false, fmt.Errorf("got nil value of type %T", v)
}
vk := uv.Kind()
switch {
case vk >= reflect.Int && vk <= reflect.Int64:
return (uv.Int() != 0), nil
case vk >= reflect.Uint && vk <= reflect.Uint64:
return (uv.Uint() != 0), nil
case vk == reflect.Bool:
return uv.Bool(), nil
case vk >= reflect.Float32 && vk <= reflect.Float64:
return (uv.Float() != 0.0), nil
case vk >= reflect.Complex64 && vk <= reflect.Complex128:
return (real(uv.Complex()) != 0.0), nil
case vk == reflect.String:
r, err := strconv.ParseBool(uv.String())
if err != nil {
return false, err
}
return r, nil
default:
return false, fmt.Errorf("got value %v of unsupported type %T", v, v)
}
}
// ToInt robustly converts to an int64 any basic elemental type
// (including pointers to such) using a big type switch organized
// for greatest efficiency, only falling back on reflection when all
// else fails.
func ToInt(v any) (int64, error) {
switch vt := v.(type) {
case int:
return int64(vt), nil
case *int:
if vt == nil {
return 0, errors.New("got nil *int")
}
return int64(*vt), nil
case int32:
return int64(vt), nil
case *int32:
if vt == nil {
return 0, errors.New("got nil *int32")
}
return int64(*vt), nil
case int64:
return vt, nil
case *int64:
if vt == nil {
return 0, errors.New("got nil *int64")
}
return *vt, nil
case uint8:
return int64(vt), nil
case *uint8:
if vt == nil {
return 0, errors.New("got nil *uint8")
}
return int64(*vt), nil
case float64:
return int64(vt), nil
case *float64:
if vt == nil {
return 0, errors.New("got nil *float64")
}
return int64(*vt), nil
case float32:
return int64(vt), nil
case *float32:
if vt == nil {
return 0, errors.New("got nil *float32")
}
return int64(*vt), nil
case bool:
if vt {
return 1, nil
}
return 0, nil
case *bool:
if vt == nil {
return 0, errors.New("got nil *bool")
}
if *vt {
return 1, nil
}
return 0, nil
case string:
r, err := strconv.ParseInt(vt, 0, 64)
if err != nil {
return 0, err
}
return r, nil
case *string:
if vt == nil {
return 0, errors.New("got nil *string")
}
r, err := strconv.ParseInt(*vt, 0, 64)
if err != nil {
return 0, err
}
return r, nil
case enums.Enum:
return vt.Int64(), nil
case int8:
return int64(vt), nil
case *int8:
if vt == nil {
return 0, errors.New("got nil *int8")
}
return int64(*vt), nil
case int16:
return int64(vt), nil
case *int16:
if vt == nil {
return 0, errors.New("got nil *int16")
}
return int64(*vt), nil
case uint:
return int64(vt), nil
case *uint:
if vt == nil {
return 0, errors.New("got nil *uint")
}
return int64(*vt), nil
case uint16:
return int64(vt), nil
case *uint16:
if vt == nil {
return 0, errors.New("got nil *uint16")
}
return int64(*vt), nil
case uint32:
return int64(vt), nil
case *uint32:
if vt == nil {
return 0, errors.New("got nil *uint32")
}
return int64(*vt), nil
case uint64:
return int64(vt), nil
case *uint64:
if vt == nil {
return 0, errors.New("got nil *uint64")
}
return int64(*vt), nil
case uintptr:
return int64(vt), nil
case *uintptr:
if vt == nil {
return 0, errors.New("got nil *uintptr")
}
return int64(*vt), nil
}
// then fall back on reflection
uv := Underlying(reflect.ValueOf(v))
if IsNil(uv) {
return 0, fmt.Errorf("got nil value of type %T", v)
}
vk := uv.Kind()
switch {
case vk >= reflect.Int && vk <= reflect.Int64:
return uv.Int(), nil
case vk >= reflect.Uint && vk <= reflect.Uint64:
return int64(uv.Uint()), nil
case vk == reflect.Bool:
if uv.Bool() {
return 1, nil
}
return 0, nil
case vk >= reflect.Float32 && vk <= reflect.Float64:
return int64(uv.Float()), nil
case vk >= reflect.Complex64 && vk <= reflect.Complex128:
return int64(real(uv.Complex())), nil
case vk == reflect.String:
r, err := strconv.ParseInt(uv.String(), 0, 64)
if err != nil {
return 0, err
}
return r, nil
default:
return 0, fmt.Errorf("got value %v of unsupported type %T", v, v)
}
}
// ToFloat robustly converts to a float64 any basic elemental type
// (including pointers to such) using a big type switch organized for
// greatest efficiency, only falling back on reflection when all else fails.
func ToFloat(v any) (float64, error) {
switch vt := v.(type) {
case float64:
return vt, nil
case *float64:
if vt == nil {
return 0, errors.New("got nil *float64")
}
return *vt, nil
case float32:
return float64(vt), nil
case *float32:
if vt == nil {
return 0, errors.New("got nil *float32")
}
return float64(*vt), nil
case int:
return float64(vt), nil
case *int:
if vt == nil {
return 0, errors.New("got nil *int")
}
return float64(*vt), nil
case int32:
return float64(vt), nil
case *int32:
if vt == nil {
return 0, errors.New("got nil *int32")
}
return float64(*vt), nil
case int64:
return float64(vt), nil
case *int64:
if vt == nil {
return 0, errors.New("got nil *int64")
}
return float64(*vt), nil
case uint8:
return float64(vt), nil
case *uint8:
if vt == nil {
return 0, errors.New("got nil *uint8")
}
return float64(*vt), nil
case bool:
if vt {
return 1, nil
}
return 0, nil
case *bool:
if vt == nil {
return 0, errors.New("got nil *bool")
}
if *vt {
return 1, nil
}
return 0, nil
case string:
r, err := strconv.ParseFloat(vt, 64)
if err != nil {
return 0.0, err
}
return r, nil
case *string:
if vt == nil {
return 0, errors.New("got nil *string")
}
r, err := strconv.ParseFloat(*vt, 64)
if err != nil {
return 0.0, err
}
return r, nil
case int8:
return float64(vt), nil
case *int8:
if vt == nil {
return 0, errors.New("got nil *int8")
}
return float64(*vt), nil
case int16:
return float64(vt), nil
case *int16:
if vt == nil {
return 0, errors.New("got nil *int16")
}
return float64(*vt), nil
case uint:
return float64(vt), nil
case *uint:
if vt == nil {
return 0, errors.New("got nil *uint")
}
return float64(*vt), nil
case uint16:
return float64(vt), nil
case *uint16:
if vt == nil {
return 0, errors.New("got nil *uint16")
}
return float64(*vt), nil
case uint32:
return float64(vt), nil
case *uint32:
if vt == nil {
return 0, errors.New("got nil *uint32")
}
return float64(*vt), nil
case uint64:
return float64(vt), nil
case *uint64:
if vt == nil {
return 0, errors.New("got nil *uint64")
}
return float64(*vt), nil
case uintptr:
return float64(vt), nil
case *uintptr:
if vt == nil {
return 0, errors.New("got nil *uintptr")
}
return float64(*vt), nil
}
// then fall back on reflection
uv := Underlying(reflect.ValueOf(v))
if IsNil(uv) {
return 0, fmt.Errorf("got nil value of type %T", v)
}
vk := uv.Kind()
switch {
case vk >= reflect.Int && vk <= reflect.Int64:
return float64(uv.Int()), nil
case vk >= reflect.Uint && vk <= reflect.Uint64:
return float64(uv.Uint()), nil
case vk == reflect.Bool:
if uv.Bool() {
return 1, nil
}
return 0, nil
case vk >= reflect.Float32 && vk <= reflect.Float64:
return uv.Float(), nil
case vk >= reflect.Complex64 && vk <= reflect.Complex128:
return real(uv.Complex()), nil
case vk == reflect.String:
r, err := strconv.ParseFloat(uv.String(), 64)
if err != nil {
return 0, err
}
return r, nil
default:
return 0, fmt.Errorf("got value %v of unsupported type %T", v, v)
}
}
// ToFloat32 robustly converts to a float32 any basic elemental type
// (including pointers to such) using a big type switch organized for
// greatest efficiency, only falling back on reflection when all else fails.
func ToFloat32(v any) (float32, error) {
switch vt := v.(type) {
case float32:
return vt, nil
case *float32:
if vt == nil {
return 0, errors.New("got nil *float32")
}
return *vt, nil
case float64:
return float32(vt), nil
case *float64:
if vt == nil {
return 0, errors.New("got nil *float64")
}
return float32(*vt), nil
case int:
return float32(vt), nil
case *int:
if vt == nil {
return 0, errors.New("got nil *int")
}
return float32(*vt), nil
case int32:
return float32(vt), nil
case *int32:
if vt == nil {
return 0, errors.New("got nil *int32")
}
return float32(*vt), nil
case int64:
return float32(vt), nil
case *int64:
if vt == nil {
return 0, errors.New("got nil *int64")
}
return float32(*vt), nil
case uint8:
return float32(vt), nil
case *uint8:
if vt == nil {
return 0, errors.New("got nil *uint8")
}
return float32(*vt), nil
case bool:
if vt {
return 1, nil
}
return 0, nil
case *bool:
if vt == nil {
return 0, errors.New("got nil *bool")
}
if *vt {
return 1, nil
}
return 0, nil
case string:
r, err := strconv.ParseFloat(vt, 32)
if err != nil {
return 0, err
}
return float32(r), nil
case *string:
if vt == nil {
return 0, errors.New("got nil *string")
}
r, err := strconv.ParseFloat(*vt, 32)
if err != nil {
return 0, err
}
return float32(r), nil
case int8:
return float32(vt), nil
case *int8:
if vt == nil {
return 0, errors.New("got nil *int8")
}
return float32(*vt), nil
case int16:
return float32(vt), nil
case *int16:
if vt == nil {
return 0, errors.New("got nil *int8")
}
return float32(*vt), nil
case uint:
return float32(vt), nil
case *uint:
if vt == nil {
return 0, errors.New("got nil *uint")
}
return float32(*vt), nil
case uint16:
return float32(vt), nil
case *uint16:
if vt == nil {
return 0, errors.New("got nil *uint16")
}
return float32(*vt), nil
case uint32:
return float32(vt), nil
case *uint32:
if vt == nil {
return 0, errors.New("got nil *uint32")
}
return float32(*vt), nil
case uint64:
return float32(vt), nil
case *uint64:
if vt == nil {
return 0, errors.New("got nil *uint64")
}
return float32(*vt), nil
case uintptr:
return float32(vt), nil
case *uintptr:
if vt == nil {
return 0, errors.New("got nil *uintptr")
}
return float32(*vt), nil
}
// then fall back on reflection
uv := Underlying(reflect.ValueOf(v))
if IsNil(uv) {
return 0, fmt.Errorf("got nil value of type %T", v)
}
vk := uv.Kind()
switch {
case vk >= reflect.Int && vk <= reflect.Int64:
return float32(uv.Int()), nil
case vk >= reflect.Uint && vk <= reflect.Uint64:
return float32(uv.Uint()), nil
case vk == reflect.Bool:
if uv.Bool() {
return 1, nil
}
return 0, nil
case vk >= reflect.Float32 && vk <= reflect.Float64:
return float32(uv.Float()), nil
case vk >= reflect.Complex64 && vk <= reflect.Complex128:
return float32(real(uv.Complex())), nil
case vk == reflect.String:
r, err := strconv.ParseFloat(uv.String(), 32)
if err != nil {
return 0, err
}
return float32(r), nil
default:
return 0, fmt.Errorf("got value %v of unsupported type %T", v, v)
}
}
// ToString robustly converts anything to a String
// using a big type switch organized for greatest efficiency.
// First checks for string or []byte and returns that immediately,
// then checks for the Stringer interface as the preferred conversion
// (e.g., for enums), and then falls back on strconv calls for numeric types.
// If everything else fails, it uses fmt.Sprintf("%v") which always works,
// so there is no need for an error return value. It returns "nil" for any nil
// pointers, and byte is converted as string(byte), not the decimal representation.
func ToString(v any) string {
nilstr := "nil"
// TODO: this reflection is unideal for performance, but we need it to prevent panics,
// so this whole "greatest efficiency" type switch is kind of pointless.
rv := reflect.ValueOf(v)
if IsNil(rv) {
return nilstr
}
switch vt := v.(type) {
case string:
return vt
case *string:
if vt == nil {
return nilstr
}
return *vt
case []byte:
return string(vt)
case *[]byte:
if vt == nil {
return nilstr
}
return string(*vt)
}
if stringer, ok := v.(fmt.Stringer); ok {
return stringer.String()
}
switch vt := v.(type) {
case bool:
if vt {
return "true"
}
return "false"
case *bool:
if vt == nil {
return nilstr
}
if *vt {
return "true"
}
return "false"
case int:
return strconv.FormatInt(int64(vt), 10)
case *int:
if vt == nil {
return nilstr
}
return strconv.FormatInt(int64(*vt), 10)
case int32:
return strconv.FormatInt(int64(vt), 10)
case *int32:
if vt == nil {
return nilstr
}
return strconv.FormatInt(int64(*vt), 10)
case int64:
return strconv.FormatInt(vt, 10)
case *int64:
if vt == nil {
return nilstr
}
return strconv.FormatInt(*vt, 10)
case uint8: // byte, converts as string char
return string(vt)
case *uint8:
if vt == nil {
return nilstr
}
return string(*vt)
case float64:
return strconv.FormatFloat(vt, 'G', -1, 64)
case *float64:
if vt == nil {
return nilstr
}
return strconv.FormatFloat(*vt, 'G', -1, 64)
case float32:
return strconv.FormatFloat(float64(vt), 'G', -1, 32)
case *float32:
if vt == nil {
return nilstr
}
return strconv.FormatFloat(float64(*vt), 'G', -1, 32)
case uintptr:
return fmt.Sprintf("%#x", uintptr(vt))
case *uintptr:
if vt == nil {
return nilstr
}
return fmt.Sprintf("%#x", uintptr(*vt))
case int8:
return strconv.FormatInt(int64(vt), 10)
case *int8:
if vt == nil {
return nilstr
}
return strconv.FormatInt(int64(*vt), 10)
case int16:
return strconv.FormatInt(int64(vt), 10)
case *int16:
if vt == nil {
return nilstr
}
return strconv.FormatInt(int64(*vt), 10)
case uint:
return strconv.FormatInt(int64(vt), 10)
case *uint:
if vt == nil {
return nilstr
}
return strconv.FormatInt(int64(*vt), 10)
case uint16:
return strconv.FormatInt(int64(vt), 10)
case *uint16:
if vt == nil {
return nilstr
}
return strconv.FormatInt(int64(*vt), 10)
case uint32:
return strconv.FormatInt(int64(vt), 10)
case *uint32:
if vt == nil {
return nilstr
}
return strconv.FormatInt(int64(*vt), 10)
case uint64:
return strconv.FormatInt(int64(vt), 10)
case *uint64:
if vt == nil {
return nilstr
}
return strconv.FormatInt(int64(*vt), 10)
case complex64:
return strconv.FormatFloat(float64(real(vt)), 'G', -1, 32) + "," + strconv.FormatFloat(float64(imag(vt)), 'G', -1, 32)
case *complex64:
if vt == nil {
return nilstr
}
return strconv.FormatFloat(float64(real(*vt)), 'G', -1, 32) + "," + strconv.FormatFloat(float64(imag(*vt)), 'G', -1, 32)
case complex128:
return strconv.FormatFloat(real(vt), 'G', -1, 64) + "," + strconv.FormatFloat(imag(vt), 'G', -1, 64)
case *complex128:
if vt == nil {
return nilstr
}
return strconv.FormatFloat(real(*vt), 'G', -1, 64) + "," + strconv.FormatFloat(imag(*vt), 'G', -1, 64)
}
// then fall back on reflection
uv := Underlying(rv)
if IsNil(uv) {
return nilstr
}
vk := uv.Kind()
switch {
case vk >= reflect.Int && vk <= reflect.Int64:
return strconv.FormatInt(uv.Int(), 10)
case vk >= reflect.Uint && vk <= reflect.Uint64:
return strconv.FormatUint(uv.Uint(), 10)
case vk == reflect.Bool:
return strconv.FormatBool(uv.Bool())
case vk >= reflect.Float32 && vk <= reflect.Float64:
return strconv.FormatFloat(uv.Float(), 'G', -1, 64)
case vk >= reflect.Complex64 && vk <= reflect.Complex128:
cv := uv.Complex()
rv := strconv.FormatFloat(real(cv), 'G', -1, 64) + "," + strconv.FormatFloat(imag(cv), 'G', -1, 64)
return rv
case vk == reflect.String:
return uv.String()
case vk == reflect.Slice:
eltyp := SliceElementType(v)
if eltyp.Kind() == reflect.Uint8 { // []byte
return string(v.([]byte))
}
fallthrough
default:
return fmt.Sprintf("%v", v)
}
}
// ToStringPrec robustly converts anything to a String using given precision
// for converting floating values; using a value like 6 truncates the
// nuisance random imprecision of actual floating point values due to the
// fact that they are represented with binary bits.
// Otherwise is identical to ToString for any other cases.
func ToStringPrec(v any, prec int) string {
nilstr := "nil"
switch vt := v.(type) {
case string:
return vt
case *string:
if vt == nil {
return nilstr
}
return *vt
case []byte:
return string(vt)
case *[]byte:
if vt == nil {
return nilstr
}
return string(*vt)
}
if stringer, ok := v.(fmt.Stringer); ok {
return stringer.String()
}
switch vt := v.(type) {
case float64:
return strconv.FormatFloat(vt, 'G', prec, 64)
case *float64:
if vt == nil {
return nilstr
}
return strconv.FormatFloat(*vt, 'G', prec, 64)
case float32:
return strconv.FormatFloat(float64(vt), 'G', prec, 32)
case *float32:
if vt == nil {
return nilstr
}
return strconv.FormatFloat(float64(*vt), 'G', prec, 32)
case complex64:
return strconv.FormatFloat(float64(real(vt)), 'G', prec, 32) + "," + strconv.FormatFloat(float64(imag(vt)), 'G', prec, 32)
case *complex64:
if vt == nil {
return nilstr
}
return strconv.FormatFloat(float64(real(*vt)), 'G', prec, 32) + "," + strconv.FormatFloat(float64(imag(*vt)), 'G', prec, 32)
case complex128:
return strconv.FormatFloat(real(vt), 'G', prec, 64) + "," + strconv.FormatFloat(imag(vt), 'G', prec, 64)
case *complex128:
if vt == nil {
return nilstr
}
return strconv.FormatFloat(real(*vt), 'G', prec, 64) + "," + strconv.FormatFloat(imag(*vt), 'G', prec, 64)
}
return ToString(v)
}
// SetRobust robustly sets the 'to' value from the 'from' value.
// The 'to' value must be a pointer. It copies slices and maps robustly,
// and it can set a struct, slice, or map from a JSON-formatted string
// value. It also handles many other cases, so it is unlikely to fail.
//
// Note that maps are not reset prior to setting, whereas slices are
// set to be fully equivalent to the source slice.
func SetRobust(to, from any) error {
rto := reflect.ValueOf(to)
pto := UnderlyingPointer(rto)
if IsNil(pto) {
// If the original value is a non-nil pointer, we can just use it
// even though the underlying pointer is nil (this happens when there
// is a pointer to a nil pointer; see #1365).
if !IsNil(rto) && rto.Kind() == reflect.Pointer {
pto = rto
} else {
// Otherwise, we cannot recover any meaningful value.
return errors.New("got nil destination value")
}
}
pito := pto.Interface()
totyp := pto.Elem().Type()
tokind := totyp.Kind()
if !pto.Elem().CanSet() {
return fmt.Errorf("destination value cannot be set; it must be a variable or field, not a const or tmp or other value that cannot be set (value: %v of type %T)", pto, pto)
}
// A value set to itself (as by a value widget bound to the value that it
// edits) is not written, which would race with readers of the value
// (as in another window, for an inspector).
if fv := reflect.ValueOf(from); fv.IsValid() {
// (the pointers are compared as interfaces, as goscript does not
// have the addresses of [reflect.Value.Pointer])
if fp := UnderlyingPointer(fv); fp.IsValid() && fp.Type() == pto.Type() && fp.CanInterface() && fp.Interface() == pito {
return nil
}
}
// images should not be copied per content: just set the pointer!
// otherwise the original images (esp colors!) are altered.
// TODO: #1394 notes the more general ambiguity about deep vs. shallow pointer copy.
if img, ok := to.(*image.Image); ok {
if fimg, ok := from.(image.Image); ok {
*img = fimg
return nil
}
}
// first we do the generic AssignableTo case
if rto.Kind() == reflect.Pointer {
fv := reflect.ValueOf(from)
if fv.IsValid() {
if fv.Type().AssignableTo(totyp) {
pto.Elem().Set(fv)
return nil
}
ufvp := UnderlyingPointer(fv)
if ufvp.IsValid() && ufvp.Type().AssignableTo(totyp) {
pto.Elem().Set(ufvp)
return nil
}
ufv := ufvp.Elem()
if ufv.IsValid() && ufv.Type().AssignableTo(totyp) {
pto.Elem().Set(ufv)
return nil
}
} else {
return nil
}
}
if sa, ok := pito.(SetAnyer); ok {
err := sa.SetAny(from)
if err != nil {
return err
}
return nil
}
if ss, ok := pito.(SetStringer); ok {
if s, ok := from.(string); ok {
err := ss.SetString(s)
if err != nil {
return err
}
return nil
}
}
if es, ok := pito.(enums.EnumSetter); ok {
if en, ok := from.(enums.Enum); ok {
es.SetInt64(en.Int64())
return nil
}
if str, ok := from.(string); ok {
return es.SetString(str)
}
fm, err := ToInt(from)
if err != nil {
return err
}
es.SetInt64(fm)
return nil
}
if bv, ok := pito.(bools.BoolSetter); ok {
fb, err := ToBool(from)
if err != nil {
return err
}
bv.SetBool(fb)
return nil
}
if td, ok := pito.(*time.Duration); ok {
if fs, ok := from.(string); ok {
fd, err := time.ParseDuration(fs)
if err != nil {
return err
}
*td = fd
return nil
}
}
if fc, err := colors.FromAny(from); err == nil {
switch c := pito.(type) {
case *color.RGBA:
*c = fc
return nil
case *image.Uniform:
c.C = fc
return nil
case SetColorer:
c.SetColor(fc)
return nil
case *image.Image:
*c = colors.Uniform(fc)
return nil
}
}
ftyp := NonPointerType(reflect.TypeOf(from))
switch {
case tokind >= reflect.Int && tokind <= reflect.Int64:
fm, err := ToInt(from)
if err != nil {
return err
}
pto.Elem().Set(reflect.ValueOf(fm).Convert(totyp))
return nil
case tokind >= reflect.Uint && tokind <= reflect.Uint64:
fm, err := ToInt(from)
if err != nil {
return err
}
pto.Elem().Set(reflect.ValueOf(fm).Convert(totyp))
return nil
case tokind == reflect.Bool:
fm, err := ToBool(from)
if err != nil {
return err
}
pto.Elem().Set(reflect.ValueOf(fm).Convert(totyp))
return nil
case tokind >= reflect.Float32 && tokind <= reflect.Float64:
fm, err := ToFloat(from)
if err != nil {
return err
}
pto.Elem().Set(reflect.ValueOf(fm).Convert(totyp))
return nil
case tokind == reflect.String:
fm := ToString(from)
pto.Elem().Set(reflect.ValueOf(fm).Convert(totyp))
return nil
case tokind == reflect.Struct:
if ftyp.Kind() == reflect.String {
err := json.Unmarshal([]byte(ToString(from)), to) // todo: this is not working -- see what marshal says, etc
if err != nil {
marsh, _ := json.Marshal(to)
return fmt.Errorf("error setting struct from string: %w (example format for string: %s)", err, string(marsh))
}
return nil
}
case tokind == reflect.Slice:
if ftyp.Kind() == reflect.String {
err := json.Unmarshal([]byte(ToString(from)), to)
if err != nil {
marsh, _ := json.Marshal(to)
return fmt.Errorf("error setting slice from string: %w (example format for string: %s)", err, string(marsh))
}
return nil
}
return CopySliceRobust(to, from)
case tokind == reflect.Map:
if ftyp.Kind() == reflect.String {
err := json.Unmarshal([]byte(ToString(from)), to)
if err != nil {
marsh, _ := json.Marshal(to)
return fmt.Errorf("error setting map from string: %w (example format for string: %s)", err, string(marsh))
}
return nil
}
return CopyMapRobust(to, from)
}
tos := elide.End(fmt.Sprintf("%v", to), 40)
fms := elide.End(fmt.Sprintf("%v", from), 40)
return fmt.Errorf("unable to set value %s of type %T (using underlying type: %s) from value %s of type %T (using underlying type: %s): not a supported type pair and direct assigning is not possible", tos, to, totyp.String(), fms, from, LongTypeName(Underlying(reflect.ValueOf(from)).Type()))
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package sharedfile provides a file of data (JSON by default) that is shared by several
// processes, such as different Cogent Core apps, like the sort orders of
// directories and the geometry of windows. The data is read again when
// another process has changed the file, and the file is written with a
// lock file held, after reading the changes of the other processes, so
// that they are not lost, and it is written whole and then renamed, so
// that the other processes never read a partial file.
package sharedfile
import (
"encoding/json"
"errors"
"io"
"io/fs"
"os"
"path/filepath"
"strconv"
"time"
)
// File is a JSON file of data of type T that is shared by several
// processes: see [File.Reload] and [File.Update]. It is not safe for
// concurrent use by goroutines: the caller protects it with a mutex.
// The zero value is ready to use, with only [File.Path] to set.
type File[T any] struct {
// Path is the path of the file. If it is empty, the data are only
// kept in memory. It can be changed, as when the directory of the
// file changes in tests: the data are then those of the new file.
Path string
// Data is the data of the file, as last read from it or updated.
// It is replaced by a new value when the file is read again, so it
// must only be changed by [File.Update].
Data T
// Encode and Decode, if set, write and read the data in another
// format than JSON, which is used for each that is not set, such as
// a text file of lines. Decode returns what it could read along with
// any error.
Encode func(d T) ([]byte, error)
Decode func(b []byte) (T, error)
// file is the path of the file that was last read or written.
file string
// info is the state of the file when it was last read or written,
// to read it again when another process changes it.
info fs.FileInfo
}
// Changed returns whether the file exists and has changed since it was
// last read or written by this File, as another process has written it,
// or whether [File.Path] has changed. Another process is detected by the
// file being a different file (as it is renamed into place when it is
// written), or by a different modification time or size.
func (f *File[T]) Changed() bool {
if f.Path == "" {
return false
}
info, err := os.Stat(f.Path)
if err != nil {
return f.file != f.Path
}
return f.changed(info)
}
// changed returns whether the given state of the file differs from the
// recorded one.
func (f *File[T]) changed(info fs.FileInfo) bool {
if f.file != f.Path || f.info == nil {
return true
}
return !os.SameFile(info, f.info) || !info.ModTime().Equal(f.info.ModTime()) || info.Size() != f.info.Size()
}
// Reload reads the file into [File.Data] if it has [File.Changed], which
// replaces Data by the new value that is read. If the file does not exist,
// Data is kept, except when [File.Path] has changed, when it is reset to
// the zero value. If the file is not valid JSON, Data is what could be
// read from it, and an error is returned; the file is then replaced when
// it is next updated.
func (f *File[T]) Reload() error {
_, err := f.reload()
return err
}
// reload is [File.Reload], which also returns whether the error is from
// reading the file (as opposed to decoding it), as readErr.
func (f *File[T]) reload() (readErr bool, err error) {
if f.Path == "" {
return false, nil
}
// the file is opened before its state is read, so that the state is
// that of the data read even when another process replaces it
fh, err := os.Open(f.Path)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
if f.file != f.Path {
var zero T
f.Data, f.file, f.info = zero, f.Path, nil
}
return false, nil
}
return true, err
}
defer fh.Close()
info, err := fh.Stat()
if err != nil {
return true, err
}
if !f.changed(info) {
return false, nil
}
b, err := io.ReadAll(fh)
if err != nil {
return true, err
}
// the data are decoded into a new value, so that nothing is kept from
// before, and the state is recorded even when it is not valid, so it
// is not read again until it changes
d, err := f.decode(b)
f.Data, f.file, f.info = d, f.Path, info
return false, err
}
// Update changes [File.Data] with the given change function (which can be
// nil to just write it) and writes it to the file, with the file locked
// (see [Lock]), after reading the changes of other processes with
// [File.Reload], which the change function must then merge with. A file
// that is not valid JSON is replaced. If the file cannot be locked or
// read, the data are only changed in memory, and the error is returned.
// The directory of the file is made if it does not exist.
func (f *File[T]) Update(change func(d *T)) error {
if change == nil {
change = func(d *T) {}
}
if f.Path == "" {
change(&f.Data)
return nil
}
// the changes of other processes are read with the file locked, so
// that no other process writes it until this one has
if err := os.MkdirAll(filepath.Dir(f.Path), 0o755); err != nil {
change(&f.Data)
return err
}
unlock, err := Lock(f.Path + ".lck")
if err != nil {
change(&f.Data)
return err
}
defer unlock()
if readErr, err := f.reload(); readErr {
change(&f.Data)
return err
}
change(&f.Data)
// the file is written whole, then renamed, so that other processes
// never read a partial file
b, err := f.encode()
if err != nil {
return err
}
tmp := f.Path + ".tmp"
if err := os.WriteFile(tmp, b, 0o644); err != nil {
return err
}
if err := os.Rename(tmp, f.Path); err != nil {
os.Remove(tmp)
return err
}
if info, err := os.Stat(f.Path); err == nil {
f.file, f.info = f.Path, info
}
return nil
}
// encode returns the data as written to the file: with [File.Encode],
// or as indented JSON.
func (f *File[T]) encode() ([]byte, error) {
if f.Encode != nil {
return f.Encode(f.Data)
}
return json.MarshalIndent(f.Data, "", "\t")
}
// decode returns the data read from the file: with [File.Decode], or as
// JSON, into a new value, so that nothing is kept from before.
func (f *File[T]) decode(b []byte) (T, error) {
if f.Decode != nil {
return f.Decode(b)
}
var d T
err := json.Unmarshal(b, &d)
return d, err
}
// LockStale is how long a lock file can exist before it is taken as left
// by a process that ended while holding it (see [Lock]).
var LockStale = 2 * time.Second
// lockWait is how long [Lock] waits between tries.
const lockWait = 20 * time.Millisecond
// lockTimeout is how long [Lock] tries for, if not 0 (for tests), instead
// of [LockStale] plus a second.
var lockTimeout time.Duration
// Lock locks the given lock file, by creating it (which only one process
// can do), waiting for another process to remove it, or taking it over
// when it is older than [LockStale]. It gives up with an error after
// waiting for longer than LockStale (plus a second). It returns the
// function to unlock it, by removing it.
func Lock(fn string) (unlock func(), err error) {
timeout := LockStale + time.Second
if lockTimeout > 0 {
timeout = lockTimeout
}
deadline := time.Now().Add(timeout)
for {
// the time of locking is written for anyone looking at it, but the
// modification time of the file is what is used
fh, err := os.OpenFile(fn, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
if err == nil {
fh.WriteString(strconv.FormatInt(time.Now().UnixNano(), 10))
fh.Close()
return func() { os.Remove(fn) }, nil
}
if !errors.Is(err, fs.ErrExist) {
return nil, err
}
// a stale lock file is removed, and another try made right away
if info, err := os.Stat(fn); err == nil && time.Since(info.ModTime()) > LockStale {
os.Remove(fn)
continue
}
if time.Now().After(deadline) {
return nil, errors.New("sharedfile: could not lock " + fn)
}
time.Sleep(lockWait)
}
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package slicesx provides additional slice functions
// beyond those in the standard [slices] package.
package slicesx
import (
"slices"
"unsafe"
)
// GrowTo increases the slice's capacity, if necessary,
// so that it can hold at least n elements.
func GrowTo[S ~[]E, E any](s S, n int) S {
if n < 0 {
panic("cannot be negative")
}
if n -= cap(s); n > 0 {
s = append(s[:cap(s)], make([]E, n)...)[:len(s)]
}
return s
}
// SetLength sets the length of the given slice,
// re-using and preserving existing values to the extent possible.
func SetLength[E any](s []E, n int) []E {
if len(s) == n {
return s
}
if s == nil {
return make([]E, n)
}
if cap(s) < n {
s = GrowTo(s, n)
}
s = s[:n]
return s
}
// CopyFrom efficiently copies from src into dest, using SetLength
// to ensure the destination has sufficient capacity, and returns
// the destination (which may have changed location as a result).
func CopyFrom[E any](dest []E, src []E) []E {
dest = SetLength(dest, len(src))
copy(dest, src)
return dest
}
// Move moves the element in the given slice at the given
// old position to the given new position and returns the
// resulting slice.
func Move[E any](s []E, from, to int) []E {
temp := s[from]
s = slices.Delete(s, from, from+1)
s = slices.Insert(s, to, temp)
return s
}
// Swap swaps the elements at the given two indices in the given slice.
func Swap[E any](s []E, i, j int) {
s[i], s[j] = s[j], s[i]
}
// As converts a slice of the given type to a slice of the other given type.
// The underlying types of the slice elements must be equivalent.
func As[F, T any](s []F) []T {
as := make([]T, len(s))
for i, v := range s {
as[i] = any(v).(T)
}
return as
}
// Search returns the index of the item in the given slice that matches the target
// according to the given match function, using the given optional starting index
// to optimize the search by searching bidirectionally outward from given index.
// This is much faster when you have some idea about where the item might be.
// If no start index is given, it starts in the middle, which is a good default.
// It returns -1 if no item matching the match function is found.
func Search[E any](slice []E, match func(e E) bool, startIndex ...int) int {
n := len(slice)
if n == 0 {
return -1
}
si := -1
if len(startIndex) > 0 {
si = startIndex[0]
}
if si < 0 {
si = n / 2
}
if si == 0 {
for idx, e := range slice {
if match(e) {
return idx
}
}
} else {
if si >= n {
si = n - 1
}
ui := si + 1
di := si
upo := false
for {
if !upo && ui < n {
if match(slice[ui]) {
return ui
}
ui++
} else {
upo = true
}
if di >= 0 {
if match(slice[di]) {
return di
}
di--
} else if upo {
break
}
}
}
return -1
}
// ToBytes returns the underlying bytes of given slice.
// for items not in a slice, make one of length 1.
// This is copied from webgpu.
func ToBytes[E any](src []E) []byte {
l := uintptr(len(src))
if l == 0 {
return nil
}
elmSize := unsafe.Sizeof(src[0])
return unsafe.Slice((*byte)(unsafe.Pointer(&src[0])), l*elmSize)
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package sshclient provides an SSH client that runs commands on remote hosts,
// interactively or not, and copies files to and from them.
package sshclient
import (
"bytes"
"errors"
"fmt"
"io/fs"
"log/slog"
"net"
"os"
"path/filepath"
"strings"
"sync"
"time"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/knownhosts"
"golang.org/x/term"
)
// Client represents a persistent connection to an ssh host.
// Commands are run by creating [ssh.Session]s from this client.
//
// The connection is checked with a keepalive request every [Config.KeepAlive],
// and closed if the host does not reply within [Config.Timeout], as happens
// when the network is lost, so that commands waiting on it fail instead of
// hanging. A lost connection is made again the next time it is used
// (see [Client.CheckConnection]), as when the network comes back.
type Client struct {
Config
// ssh client is present (non-nil) after a successful Connect,
// and nil while the connection is lost.
Client *ssh.Client
// keeps track of sessions that are being waited upon
Sessions map[string]*ssh.Session
// sessionCounter increments number of Sessions added
// over the lifetime of the Client.
sessionCounter int
// exports is the shell code that sets the variables of the login
// environment of the user for each command (see [Config.LoginEnv]).
exports string
// sftpClient copies files, made when first needed (see [Client.SFTP]).
sftpClient sftpConn
// addr and sshConfig are those of the connection, for reconnecting.
addr string
sshConfig *ssh.ClientConfig
// lost is closed when the connection is lost.
lost chan struct{}
// lastDial is the time of the last attempt to reconnect, which is
// only tried again after [Config.Timeout].
lastDial time.Time
// mu protects the connection while it is checked and made again.
mu sync.Mutex
}
// NewClient returns a new Client using given [Config] configuration
// parameters.
func NewClient(cfg *Config) *Client {
cl := &Client{Config: *cfg}
return cl
}
// Close terminates any open Sessions and then closes
// the Client connection, which is not made again.
func (cl *Client) Close() {
cl.mu.Lock()
defer cl.mu.Unlock()
cl.closeConnection()
cl.addr = ""
}
// closeConnection closes the sessions, SFTP and ssh client of the
// connection.
func (cl *Client) closeConnection() {
cl.CloseSessions()
if cl.sftpClient != nil {
cl.sftpClient.Close()
cl.sftpClient = nil
}
if cl.Client != nil {
cl.Client.Close()
}
cl.Client = nil
}
// CloseSessions terminates any open Sessions that are
// still Waiting for the associated process to finish.
func (cl *Client) CloseSessions() {
if cl.Sessions == nil {
return
}
for _, ses := range cl.Sessions {
ses.Close()
}
cl.Sessions = nil
}
// Connect connects to given host, which can either be just the host
// or user@host. If host is empty, the Config default host will be used
// if non-empty, or an error is returned.
// If successful, creates a Client that can be used for
// future sessions. Otherwise, returns error.
// This updates the Host (and User) fields in the config, for future
// reference.
func (cl *Client) Connect(host string) error {
if host == "" {
if cl.Host == "" {
return errors.New("ssh: Connect host is empty and no default host set in Config")
}
host = cl.Host
}
atidx := strings.Index(host, "@")
if atidx > 0 {
cl.User.User = host[:atidx]
cl.Host = host[atidx+1:]
host = cl.Host
} else {
cl.Host = host
}
if cl.User.KeyPath == "" {
return fmt.Errorf("ssh: key path (%q) is empty -- must be set", cl.User.KeyPath)
}
// The key file, or the other standard ones if it does not exist.
fn := filepath.Join(cl.User.KeyPath, cl.User.KeyFile)
key, err := os.ReadFile(fn)
for _, kf := range []string{"id_ed25519", "id_ecdsa", "id_rsa"} {
if !errors.Is(err, fs.ErrNotExist) {
break
}
if k, kerr := os.ReadFile(filepath.Join(cl.User.KeyPath, kf)); kerr == nil {
key, err = k, nil
}
}
if err != nil {
return fmt.Errorf("ssh: unable to read private key from: %q %v", fn, err)
}
// Create the Signer for this private key.
signer, err := ssh.ParsePrivateKey(key)
if err != nil {
return fmt.Errorf("ssh: unable to parse private key from: %q %v", fn, err)
}
// more info: https://gist.github.com/Skarlso/34321a230cf0245018288686c9e70b2d
hostKeyCallback, err := knownhosts.New(filepath.Join(cl.User.KeyPath, "known_hosts"))
if err != nil {
return fmt.Errorf("ssh: could not read the known hosts: %w", err)
}
config := &ssh.ClientConfig{
User: cl.User.User,
Auth: []ssh.AuthMethod{
// Use the PublicKeys method for remote authentication.
ssh.PublicKeys(signer),
},
HostKeyCallback: hostKeyCallback,
}
// Connect to the remote server and perform the SSH handshake.
// The port is 22 unless the host has one, as in host:2222.
addr := host
if _, _, err := net.SplitHostPort(host); err != nil {
addr = net.JoinHostPort(host, "22")
}
cl.mu.Lock()
cl.closeConnection()
cl.addr, cl.sshConfig = addr, config
err = cl.dial()
cl.mu.Unlock()
if err != nil {
return err
}
cl.GetHomeDir()
if cl.LoginEnv {
cl.getLoginEnv()
}
return nil
}
// dial makes the connection to the host, with the [Config.Timeout] for
// the connection and the SSH handshake, and starts the keepalive requests.
func (cl *Client) dial() error {
cl.lastDial = time.Now()
conn, err := net.DialTimeout("tcp", cl.addr, cl.Timeout)
if err != nil {
return fmt.Errorf("ssh: unable to connect to %s as user %s: %v", cl.Host, cl.User.User, err)
}
if cl.Timeout > 0 {
conn.SetDeadline(time.Now().Add(cl.Timeout))
}
c, chans, reqs, err := ssh.NewClientConn(conn, cl.addr, cl.sshConfig)
if err != nil {
conn.Close()
return fmt.Errorf("ssh: unable to connect to %s as user %s: %v", cl.Host, cl.User.User, err)
}
conn.SetDeadline(time.Time{})
client := ssh.NewClient(c, chans, reqs)
cl.Sessions = make(map[string]*ssh.Session)
cl.Client = client
lost := make(chan struct{})
cl.lost = lost
var once sync.Once
setLost := func() { once.Do(func() { close(lost) }) }
go func() {
client.Wait()
setLost()
}()
if cl.KeepAlive > 0 {
go cl.keepAlive(client, lost, setLost)
}
return nil
}
// keepAlive sends keepalive requests on the given connection every
// [Config.KeepAlive] until it is lost, and closes it when the host does
// not reply within [Config.Timeout], calling setLost first, so that the
// connection is known to be lost when what is waiting on it fails.
func (cl *Client) keepAlive(client *ssh.Client, lost chan struct{}, setLost func()) {
tick := time.NewTicker(cl.KeepAlive)
defer tick.Stop()
for {
select {
case <-lost:
return
case <-tick.C:
}
reply := make(chan error, 1)
go func() {
// a host that does not know the request replies false, which is fine
_, _, err := client.SendRequest("keepalive@openssh.com", true, nil)
reply <- err
}()
timeout := time.NewTimer(cl.Timeout)
select {
case err := <-reply:
timeout.Stop()
if err == nil {
continue
}
case <-timeout.C:
slog.Error("ssh: lost connection: no reply from host", "host", cl.Host)
}
setLost()
client.Close() // also ends what is waiting on it
return
}
}
// CheckConnection returns nil if the client is connected, and otherwise
// tries to connect again if the connection was lost, as when the network
// was lost, returning an error if that fails. It only tries again after
// the [Config.Timeout] since the last try, returning an error until then,
// so that commands fail fast while the host cannot be reached.
// It returns an error if the client was never connected, or was closed.
func (cl *Client) CheckConnection() error {
_, err := cl.sshClient()
return err
}
// sshClient returns the ssh client of the connection, connecting again
// if it was lost (see [Client.CheckConnection]).
func (cl *Client) sshClient() (*ssh.Client, error) {
cl.mu.Lock()
defer cl.mu.Unlock()
if cl.Client != nil {
select {
case <-cl.lost:
cl.closeConnection()
default:
return cl.Client, nil
}
}
if cl.addr == "" {
return nil, errors.New("ssh: no client, must Connect first")
}
if time.Since(cl.lastDial) < cl.Timeout {
return nil, fmt.Errorf("ssh: not connected to %s: the connection was lost", cl.Host)
}
if err := cl.dial(); err != nil {
return nil, err
}
slog.Info("ssh: connected again", "host", cl.Host)
return cl.Client, nil
}
// SessionMode specifies whether an ssh session is interactive, with a
// terminal: [Interactive] or [NonInteractive].
type SessionMode bool
const (
// Interactive requests a terminal for the session.
Interactive SessionMode = true
// NonInteractive runs the session without a terminal.
NonInteractive SessionMode = false
)
// NewSession creates a new session, sets its input / outputs based on
// config. Only works if Client already connected, and connects again
// if the connection was lost (see [Client.CheckConnection]).
func (cl *Client) NewSession(interact SessionMode) (*ssh.Session, error) {
if interact {
return cl.newSession(nil)
}
client, err := cl.sshClient()
if err != nil {
return nil, err
}
ses, err := client.NewSession()
if err != nil {
return nil, err
}
ses.Stdout = cl.StdIO.Out
ses.Stderr = cl.StdIO.Err
return ses, nil
}
// newSession returns a new interactive session, with a terminal on the
// host (pty), as [Client.NewSession] does. If the given terminal of the
// input is not nil, the terminal on the host has its size and echoes the
// input, which it gets from it while the command runs (see [forwardInput]).
func (cl *Client) newSession(tty *os.File) (*ssh.Session, error) {
ses, err := cl.NewSession(NonInteractive)
if err != nil {
return nil, err
}
modes := ssh.TerminalModes{
ssh.ECHO: 0, // disable echoing
ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
}
rows, cols := 40, 80
if tty != nil {
modes[ssh.ECHO] = 1
if w, h, err := term.GetSize(int(tty.Fd())); err == nil {
rows, cols = h, w
}
}
err = ses.RequestPty("xterm", rows, cols, modes)
if err != nil {
slog.Error(err.Error())
}
return ses, nil
}
// WaitSession adds the session to list of open sessions,
// and calls Wait on it.
// It should be called in a goroutine, and will only return
// when the command is completed or terminated.
// The given name is used to save the session
// in a map, for later reference. If left blank,
// the name will be a number that increases with each
// such session created.
func (cl *Client) WaitSession(name string, ses *ssh.Session) error {
if name == "" {
name = fmt.Sprintf("%d", cl.sessionCounter)
}
cl.Sessions[name] = ses
cl.sessionCounter++
return ses.Wait()
}
// GetHomeDir runs "pwd" on the host to get the users home dir,
// called right after connecting.
func (cl *Client) GetHomeDir() error {
ses, err := cl.NewSession(NonInteractive)
if err != nil {
return err
}
defer ses.Close()
buf := &bytes.Buffer{}
ses.Stdout = buf
err = ses.Run("pwd")
if err != nil {
return fmt.Errorf("ssh: unable to get home directory through pwd: %v", err)
}
cl.HomeDir = strings.TrimSpace(buf.String())
cl.Dir = cl.HomeDir
slog.Debug("ssh: home directory", "Host", cl.Host, "Dir", cl.HomeDir)
return nil
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package sshclient
import (
"os/user"
"path/filepath"
"time"
"cogentcore.org/core/base/exec"
)
// User holds user-specific ssh connection configuration settings,
// including Key info.
type User struct {
// user name to connect with
User string
// path to ssh keys: ~/.ssh by default
KeyPath string
// name of the private ssh key file in KeyPath. If it does not exist,
// the other standard ones are used: id_ed25519, id_ecdsa or id_rsa.
KeyFile string `default:"id_rsa"`
}
func (us *User) Defaults() {
us.KeyFile = "id_rsa"
usr, err := user.Current()
if err == nil {
us.User = usr.Username
us.KeyPath = filepath.Join(usr.HomeDir, ".ssh")
}
}
// Config contains the configuration information that controls
// the behavior of ssh connections and commands. It is used
// to establish a Client connection to a remote host.
// It builds on the shared settings in [exec.Config]
type Config struct {
exec.Config
// user name and ssh key info
User User
// host name / ip address to connect to. can be blank, in which
// case it must be specified in the Client.Connect call.
Host string
// home directory of user on remote host,
// which is captured at initial connection time.
HomeDir string
// KeepAlive is the interval between keepalive requests to the host,
// which detect a lost connection, as when the network is lost
// (see [Client]). 0 turns them off.
KeepAlive time.Duration
// Timeout is the time to wait for the connection to the host, and for
// the replies to keepalive requests. 0 is no limit.
Timeout time.Duration
// LoginEnv is whether the commands get the environment variables of an
// interactive login shell of the user on the host, such as PATH, which
// it gets once when it connects. The commands are otherwise run by a
// shell that is not interactive, for which a standard ~/.bashrc returns
// before it sets them.
LoginEnv bool
}
// NewConfig returns a new ssh Config based on given
// [exec.Config] parameters.
func NewConfig(cfg *exec.Config) *Config {
c := &Config{Config: *cfg, KeepAlive: 15 * time.Second, Timeout: 15 * time.Second, LoginEnv: true}
c.User.Defaults()
c.Dir = "" // start empty until we get homedir
return c
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package sshclient
import (
"context"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"strings"
)
// Location is a file path on a host, for [Copy]: on the host of the given
// connected Client, or on the local host if the Client is nil. A relative
// path on a host is relative to the current Dir of its Client.
type Location struct {
Client *Client
Path string
}
func (l Location) String() string {
if l.Client == nil {
return l.Path
}
return l.Client.Host + ":" + l.Path
}
// Copy copies the files of the given source locations to the given
// destination location, as cp -r does, using the SFTP protocol on the
// connections of the remote hosts. A source can have the wildcards of
// [path.Match], such as *.tsv, and a directory is copied with all of its
// contents. The sources are copied into the destination if it is a
// directory: if it exists, ends with a /, is . or .., or if there are
// several sources (a directory that does not exist is made); otherwise,
// the destination is the new name of the single source file or directory.
// The modes of the files are kept. The copy stops when the context is
// done; use context.Background() for no limit.
func Copy(ctx context.Context, dst Location, srcs ...Location) error {
return CopyProgress(ctx, nil, dst, srcs...)
}
// Progress is the progress of a [CopyProgress].
type Progress struct {
// File is the path of the source file being copied.
File string
// Done and Size are the bytes of the file copied so far, and its size.
Done, Size int64
// TotalDone and Total are the bytes of all of the files copied so far,
// and their total size.
TotalDone, Total int64
// FileNum is the 1-based number of the file being copied, of NFiles.
FileNum, NFiles int
// Finished is whether all of the files are copied.
Finished bool
}
// CopyProgress copies files, as [Copy], calling the given function, if
// non-nil, with the progress of the copy: when a file starts, as its
// bytes are copied, and at the end, when Finished is true. It is called
// often, so a function that shows the progress should show it at
// intervals. It is not called concurrently, but it can be called on
// another goroutine than that of CopyProgress.
func CopyProgress(ctx context.Context, progress func(p Progress), dst Location, srcs ...Location) error {
dfs, err := locationFS(dst)
if err != nil {
return err
}
type source struct {
fs fileSystem
path string
}
var files []source
for _, src := range srcs {
sfs, err := locationFS(src)
if err != nil {
return err
}
p := sfs.abs(src.Path)
if !hasMeta(p) {
files = append(files, source{sfs, p})
continue
}
matches, err := sfs.Glob(p)
if err != nil {
return fmt.Errorf("%s: %w", src, err)
}
if len(matches) == 0 {
return fmt.Errorf("%s: no files match", src)
}
for _, m := range matches {
files = append(files, source{sfs, m})
}
}
if len(files) == 0 {
return errors.New("copy: no files to copy")
}
cp := &copier{ctx: ctx, progress: progress}
if progress != nil { // the total size, for the progress
for _, f := range files {
if err := cp.measure(f.fs, f.path); err != nil {
return err
}
}
}
dpath := dfs.abs(dst.Path)
intoDir := len(files) > 1 || strings.HasSuffix(dst.Path, "/") || dst.Path == "." || dst.Path == ".." || dst.Path == ""
if info, err := dfs.Stat(dpath); err == nil && info.IsDir() {
intoDir = true
} else if intoDir {
if err := dfs.MkdirAll(dpath, 0777); err != nil {
return fmt.Errorf("%s: %w", dst, err)
}
}
for _, f := range files {
to := dpath
if intoDir {
to = dfs.join(dpath, f.fs.base(f.path))
}
if err := cp.copyPath(dfs, to, f.fs, f.path); err != nil {
return err
}
}
cp.report(true)
return nil
}
// copier copies files for [CopyProgress].
type copier struct {
ctx context.Context
progress func(p Progress)
p Progress
}
// report calls the progress function, if any, with the progress.
func (cp *copier) report(finished bool) {
if cp.progress != nil {
cp.p.Finished = finished
cp.progress(cp.p)
}
}
// add adds the given number of bytes copied to the progress.
func (cp *copier) add(n int64) {
if n > 0 {
cp.p.Done += n
cp.p.TotalDone += n
cp.report(false)
}
}
// measure adds the size and number of the files of the given path of the
// given file system to the total of the progress.
func (cp *copier) measure(sfs fileSystem, src string) error {
info, err := sfs.Stat(src)
if err != nil {
return err
}
if !info.IsDir() {
cp.p.Total += info.Size()
cp.p.NFiles++
return nil
}
entries, err := sfs.ReadDir(src)
if err != nil {
return err
}
for _, e := range entries {
if err := cp.measure(sfs, sfs.join(src, e.Name())); err != nil {
return err
}
}
return nil
}
// copyPath copies the file or directory at the given path of the source
// file system to the given path of the destination file system.
func (cp *copier) copyPath(dfs fileSystem, dst string, sfs fileSystem, src string) error {
if err := cp.ctx.Err(); err != nil {
return err
}
info, err := sfs.Stat(src)
if err != nil {
return err
}
if !info.IsDir() {
return cp.copyFile(dfs, dst, sfs, src, info)
}
if err := dfs.MkdirAll(dst, info.Mode().Perm()|0700); err != nil {
return err
}
entries, err := sfs.ReadDir(src)
if err != nil {
return err
}
for _, e := range entries {
if err := cp.copyPath(dfs, dfs.join(dst, e.Name()), sfs, sfs.join(src, e.Name())); err != nil {
return err
}
}
return nil
}
// copyFile copies the file at the given path of the source file system,
// with the given info, to the given path of the destination file system,
// with the same mode.
func (cp *copier) copyFile(dfs fileSystem, dst string, sfs fileSystem, src string, info fs.FileInfo) error {
ctx := cp.ctx
r, err := sfs.Open(src)
if err != nil {
return err
}
defer r.Close()
w, err := dfs.Create(dst)
if err != nil {
return err
}
// Closing the files stops the copy when the context is done.
stop := context.AfterFunc(ctx, func() {
r.Close()
w.Close()
})
defer stop()
cp.p.File, cp.p.Done, cp.p.Size = src, 0, info.Size()
cp.p.FileNum++
cp.report(false)
if rf, ok := sftpReaderFrom(w); ok {
// The reader has the size, for SFTP to write concurrently.
_, err = rf.ReadFrom(&countReader{r: r, size: info.Size(), add: cp.add})
} else {
// A remote source reads concurrently, to the writer (its WriteTo).
_, err = io.Copy(&countWriter{w: w, add: cp.add}, r)
}
if cerr := w.Close(); err == nil {
err = cerr
}
if ctx.Err() != nil {
return ctx.Err()
}
if err != nil {
return fmt.Errorf("copying %s: %w", src, err)
}
return dfs.Chmod(dst, info.Mode().Perm())
}
// countReader is a reader that counts the bytes that it reads, for the
// progress of a copy. It has the size of its data, for the concurrent
// writes of [sftp.File.ReadFrom].
type countReader struct {
r io.Reader
size int64
add func(n int64)
}
func (c *countReader) Read(b []byte) (int, error) {
n, err := c.r.Read(b)
c.add(int64(n))
return n, err
}
func (c *countReader) Size() int64 { return c.size }
// countWriter is a writer that counts the bytes that it writes, for the
// progress of a copy.
type countWriter struct {
w io.Writer
add func(n int64)
}
func (c *countWriter) Write(b []byte) (int, error) {
n, err := c.w.Write(b)
c.add(int64(n))
return n, err
}
// hasMeta returns whether the given path has any of the wildcards of
// path.Match.
func hasMeta(p string) bool {
return strings.ContainsAny(p, `*?[\`)
}
// fileSystem is a file system of a host for [Copy]: that of the local host,
// or of a remote host through SFTP.
type fileSystem interface {
Stat(name string) (fs.FileInfo, error)
Open(name string) (io.ReadCloser, error)
Create(name string) (io.WriteCloser, error)
MkdirAll(name string, perm fs.FileMode) error
ReadDir(name string) ([]fs.FileInfo, error)
Glob(pattern string) ([]string, error)
Chmod(name string, mode fs.FileMode) error
// abs returns the given path as an absolute path, relative to the
// current directory of the host if relative.
abs(p string) string
join(elem ...string) string
base(p string) string
}
// localFS is the file system of the local host.
type localFS struct{}
func (localFS) Stat(name string) (fs.FileInfo, error) { return os.Stat(name) }
func (localFS) Open(name string) (io.ReadCloser, error) { return os.Open(name) }
func (localFS) Create(name string) (io.WriteCloser, error) { return os.Create(name) }
func (localFS) MkdirAll(name string, perm fs.FileMode) error { return os.MkdirAll(name, perm) }
func (localFS) Glob(pattern string) ([]string, error) { return filepath.Glob(pattern) }
func (localFS) Chmod(name string, mode fs.FileMode) error { return os.Chmod(name, mode) }
func (localFS) join(elem ...string) string { return filepath.Join(elem...) }
func (localFS) base(p string) string { return filepath.Base(p) }
func (localFS) ReadDir(name string) ([]fs.FileInfo, error) {
entries, err := os.ReadDir(name)
if err != nil {
return nil, err
}
infos := make([]fs.FileInfo, 0, len(entries))
for _, e := range entries {
info, err := e.Info()
if err != nil {
return nil, err
}
infos = append(infos, info)
}
return infos, nil
}
func (localFS) abs(p string) string {
if p == "" {
p = "."
}
if a, err := filepath.Abs(p); err == nil {
return a
}
return p
}
// CopyLocalFileToHost copies the given local file or directory to the
// given path on the remote host (see [Copy]). A relative host path is
// relative to the current Dir of the Client.
func (cl *Client) CopyLocalFileToHost(ctx context.Context, localFilename, hostFilename string) error {
return Copy(ctx, Location{Client: cl, Path: hostFilename}, Location{Path: localFilename})
}
// CopyHostToLocalFile copies the given file or directory on the remote
// host to the given local path (see [Copy]). A relative host path is
// relative to the current Dir of the Client.
func (cl *Client) CopyHostToLocalFile(ctx context.Context, hostFilename, localFilename string) error {
return Copy(ctx, Location{Path: localFilename}, Location{Client: cl, Path: hostFilename})
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !js
package sshclient
import (
"context"
"fmt"
"io"
"io/fs"
"os"
"path"
"slices"
"strings"
"github.com/pkg/sftp"
)
// sftpConn is the SFTP client of a connection (see [Client.SFTP]).
type sftpConn = *sftp.Client
// locationFS returns the file system of the host of the given location.
func locationFS(l Location) (fileSystem, error) {
if l.Client == nil {
return localFS{}, nil
}
sc, err := l.Client.SFTP()
if err != nil {
return nil, err
}
return &remoteFS{sc: sc, host: l.Client.Host, dir: l.Client.Dir}, nil
}
// sftpReaderFrom returns the given writer as an [io.ReaderFrom] if it is a
// file on a remote host, which writes concurrently from a reader that has
// a Size method.
func sftpReaderFrom(w io.Writer) (io.ReaderFrom, bool) {
sf, ok := w.(*sftp.File)
return sf, ok
}
// remoteFS is the file system of a remote host, through SFTP.
type remoteFS struct {
sc *sftp.Client
host string
dir string // the current directory
}
// The errors of SFTP do not have the path, which these add, with the host,
// as an [fs.PathError].
func (r *remoteFS) Stat(name string) (fs.FileInfo, error) {
info, err := r.sc.Stat(name)
return info, r.pathError("stat", name, err)
}
func (r *remoteFS) Open(name string) (io.ReadCloser, error) {
f, err := r.sc.Open(name)
if err != nil {
return nil, r.pathError("open", name, err)
}
return f, nil
}
func (r *remoteFS) Create(name string) (io.WriteCloser, error) {
f, err := r.sc.Create(name)
if err != nil {
return nil, r.pathError("create", name, err)
}
return f, nil
}
func (r *remoteFS) MkdirAll(name string, perm fs.FileMode) error {
return r.pathError("mkdir", name, r.sc.MkdirAll(name))
}
func (r *remoteFS) ReadDir(name string) ([]fs.FileInfo, error) {
infos, err := r.sc.ReadDir(name)
return infos, r.pathError("readdir", name, err)
}
func (r *remoteFS) Glob(pattern string) ([]string, error) {
m, err := r.sc.Glob(pattern)
return m, r.pathError("glob", pattern, err)
}
func (r *remoteFS) Chmod(name string, mode fs.FileMode) error {
return r.pathError("chmod", name, r.sc.Chmod(name, mode))
}
// pathError returns the given error of the given operation on the given
// path as an [fs.PathError] with the host in the path, or nil if nil.
func (r *remoteFS) pathError(op, name string, err error) error {
if err == nil {
return nil
}
return &fs.PathError{Op: op, Path: r.host + ":" + name, Err: err}
}
func (r *remoteFS) join(elem ...string) string { return path.Join(elem...) }
func (r *remoteFS) base(p string) string { return path.Base(p) }
// abs returns the absolute path of the given path on the host, relative to
// its current directory. A path with a Windows drive, as pwd gives it on a
// Windows host (C:/Users), is given as SFTP has it, with a / (/C:/Users).
func (r *remoteFS) abs(p string) string {
if !path.IsAbs(p) && !hasDrive(p) {
p = path.Join(r.dir, p)
}
if hasDrive(p) {
p = "/" + p
}
return path.Clean(p)
}
// hasDrive returns whether the given path starts with a Windows drive (C:/).
func hasDrive(p string) bool {
if len(p) < 3 {
return false
}
c := p[0] | 0x20 // lower case
return 'a' <= c && c <= 'z' && p[1] == ':' && p[2] == '/'
}
// SFTP returns the SFTP client of the connection to the host, which is
// made when first needed, for copying files to and from the host.
// It is not in js builds, which leave out SFTP: use the methods of
// [Client] such as [Client.ReadDir] and [Client.OpenFile] for code that
// is also built for the web.
func (cl *Client) SFTP() (*sftp.Client, error) {
client, err := cl.sshClient() // which drops the SFTP client of a lost connection
if err != nil {
return nil, err
}
cl.mu.Lock()
defer cl.mu.Unlock()
if cl.sftpClient != nil {
return cl.sftpClient, nil
}
sc, err := sftp.NewClient(client, sftp.UseConcurrentReads(true), sftp.UseConcurrentWrites(true))
if err != nil {
return nil, fmt.Errorf("ssh: starting SFTP on %s: %w", cl.Host, err)
}
cl.sftpClient = sc
return sc, nil
}
// OpenFile opens the given file on the remote host, with the given flags
// of os.OpenFile, such as os.O_CREATE|os.O_WRONLY|os.O_TRUNC to write it,
// or os.O_APPEND to add to it, through SFTP. A relative path is relative to the current Dir of the
// Client.
func (cl *Client) OpenFile(name string, flag int) (io.ReadWriteCloser, error) {
sc, err := cl.SFTP()
if err != nil {
return nil, err
}
rfs := &remoteFS{sc: sc, host: cl.Host, dir: cl.Dir}
name = rfs.abs(name)
f, err := sc.OpenFile(name, flag)
if err != nil {
return nil, rfs.pathError("open", name, err)
}
// SFTP servers can ignore the append flag, as OpenSSH does, so the
// writes start at the end.
if flag&os.O_APPEND != 0 {
if _, err := f.Seek(0, io.SeekEnd); err != nil {
f.Close()
return nil, rfs.pathError("seek", name, err)
}
}
return f, nil
}
// ReadDir returns the entries in the given directory on the remote host,
// sorted by name, through SFTP. Symbolic links are returned as such: use
// [Client.Stat] for what they point to. A relative path is relative to the
// current Dir of the Client.
func (cl *Client) ReadDir(dir string) ([]fs.FileInfo, error) {
sc, err := cl.SFTP()
if err != nil {
return nil, err
}
rfs := &remoteFS{sc: sc, host: cl.Host, dir: cl.Dir}
infos, err := rfs.ReadDir(rfs.abs(dir))
slices.SortFunc(infos, func(a, b fs.FileInfo) int { return strings.Compare(a.Name(), b.Name()) })
return infos, err
}
// Stat returns the information about the given file on the remote host,
// following symbolic links, through SFTP. A relative path is relative to
// the current Dir of the Client.
func (cl *Client) Stat(name string) (fs.FileInfo, error) {
sc, err := cl.SFTP()
if err != nil {
return nil, err
}
rfs := &remoteFS{sc: sc, host: cl.Host, dir: cl.Dir}
return rfs.Stat(rfs.abs(name))
}
// CopyLocalToHost copies the data of the given reader to the given file on
// the remote host. The size is not needed. A relative host path is
// relative to the current Dir of the Client.
func (cl *Client) CopyLocalToHost(ctx context.Context, r io.Reader, size int64, hostFilename string) error {
sc, err := cl.SFTP()
if err != nil {
return err
}
rfs := &remoteFS{sc: sc, host: cl.Host, dir: cl.Dir}
w, err := sc.Create(rfs.abs(hostFilename))
if err != nil {
return err
}
stop := context.AfterFunc(ctx, func() { w.Close() })
defer stop()
_, err = io.Copy(w, r)
if cerr := w.Close(); err == nil {
err = cerr
}
if ctx.Err() != nil {
return ctx.Err()
}
return err
}
// CopyHostToLocal copies the given file on the remote host to the given
// writer. A relative host path is relative to the current Dir of the Client.
func (cl *Client) CopyHostToLocal(ctx context.Context, hostFilename string, w io.Writer) error {
sc, err := cl.SFTP()
if err != nil {
return err
}
rfs := &remoteFS{sc: sc, host: cl.Host, dir: cl.Dir}
r, err := sc.Open(rfs.abs(hostFilename))
if err != nil {
return err
}
defer r.Close()
stop := context.AfterFunc(ctx, func() { r.Close() })
defer stop()
_, err = io.Copy(w, r)
if ctx.Err() != nil {
return ctx.Err()
}
return err
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package sshclient
import (
"bytes"
"maps"
"regexp"
"slices"
"strings"
"time"
)
// loginEnvCmd prints the environment of a command on the host, and then,
// after a marker, that of an interactive login shell of the user, after
// another marker, such that output of its startup files comes before it.
// The variables are separated by NUL (GNU env -0), or else by newlines.
const loginEnvCmd = `env -0 2>/dev/null || env; printf '\001END\001'; ` +
`"$SHELL" -lic 'printf "\001ENV\001"; env -0 2>/dev/null || env' </dev/null`
// loginEnvSkip are the variables of the login shell that are not set for
// the commands: those of the shell itself, its terminal and the session.
var loginEnvSkip = map[string]bool{
"_": true, "SHLVL": true, "PWD": true, "OLDPWD": true, "PS1": true, "PS2": true,
"PS4": true, "PROMPT_COMMAND": true, "TERM": true, "COLUMNS": true, "LINES": true,
"SSH_CLIENT": true, "SSH_CONNECTION": true, "SSH_TTY": true,
}
// envName matches the name of an environment variable.
var envName = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)
// getLoginEnv gets the environment variables that an interactive login
// shell of the user on the host sets, as in its ~/.bashrc after the check
// that the shell is interactive, such as PATH (see [Config.LoginEnv]),
// which are then set for each command, as [Client.exports].
func (cl *Client) getLoginEnv() {
ses, err := cl.NewSession(NonInteractive)
if err != nil {
return
}
defer ses.Close()
timeout := cl.Timeout
if timeout <= 0 {
timeout = 15 * time.Second
}
stop := time.AfterFunc(timeout, func() { ses.Close() }) // as for a .bashrc that waits
defer stop.Stop()
var buf bytes.Buffer
ses.Stdout, ses.Stderr = &buf, nil
ses.Run(loginEnvCmd) // the exit status is that of the shell
plain, login, ok := bytes.Cut(buf.Bytes(), []byte("\001END\001"))
if !ok {
return
}
_, after, ok := bytes.CutLast(login, []byte("\001ENV\001"))
if !ok {
return
}
cl.exports = loginExports(parseEnv(plain), parseEnv(after))
}
// parseEnv returns the variables of the given output of env, separated by
// NUL, or else by newlines (when values with newlines are lost).
func parseEnv(out []byte) map[string]string {
sep := []byte("\n")
if bytes.IndexByte(out, 0) >= 0 {
sep = []byte{0}
if j := bytes.LastIndexByte(out, 0); j >= 0 {
out = out[:j] // anything after the last one is not of env
}
}
env := map[string]string{}
for kv := range bytes.SplitSeq(out, sep) {
k, v, ok := strings.Cut(string(kv), "=")
if ok && envName.MatchString(k) {
env[k] = v
}
}
return env
}
// loginExports returns the shell code that sets the variables of the
// given login environment that differ from those of the given plain one,
// to start a command with, or "" if there are none.
func loginExports(plain, login map[string]string) string {
var b strings.Builder
for _, k := range slices.Sorted(maps.Keys(login)) {
v := login[k]
if loginEnvSkip[k] || strings.HasPrefix(k, "BASH_FUNC_") || plain[k] == v {
continue
}
if b.Len() == 0 {
b.WriteString("export")
}
b.WriteString(" ")
b.WriteString(k)
b.WriteString("='")
b.WriteString(strings.ReplaceAll(v, "'", `'\''`))
b.WriteString("'")
}
if b.Len() == 0 {
return ""
}
return b.String() + "; "
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package sshclient
import (
"bytes"
"context"
"errors"
"os"
"path/filepath"
"strings"
"time"
"cogentcore.org/core/base/exec"
"cogentcore.org/core/base/logx"
"golang.org/x/crypto/ssh"
)
// Exec executes the command, piping its stdout and stderr to the config
// writers. If the command fails, it will return an error with the command output.
// The given cmd and args may include references
// to environment variables in $FOO format, in which case these will be
// expanded before the command is run.
//
// Ran reports if the command ran (rather than was not found or not executable).
// Code reports the exit code the command returned if it ran. If err == nil, ran
// is always true and code is always 0.
func (cl *Client) Exec(sio *exec.StdIOState, start exec.StartMode, output exec.OutputMode, cmd string, args ...string) (string, error) {
return cl.ExecContext(context.Background(), sio, start, output, cmd, args...)
}
// ExecContext is [Client.Exec] with a context: if it is not nil, a command
// that is run (not started) is interrupted when the context is done, as a
// shell does for Control+C: it gets an interrupt signal, and its session
// is closed if it has not ended after [exec.InterruptWait], which ends it
// with a hangup. A command that is run with its standard input from a
// terminal gets the input of that terminal while it runs, such that
// interactive programs such as more and editors work.
func (cl *Client) ExecContext(ctx context.Context, sio *exec.StdIOState, start exec.StartMode, output exec.OutputMode, cmd string, args ...string) (string, error) {
var tty *os.File
if start == exec.Foreground && output == exec.NoCapture {
tty = terminalInput(sio.In)
}
ses, err := cl.newSession(tty)
if err != nil {
return "", err
}
defer ses.Close()
expand := func(s string) string {
s2, ok := cl.Env[s]
if ok {
return s2
}
switch s {
case "!", "?":
return "$" + s
}
return os.Getenv(s)
}
if !cl.NoExpand {
cmd = os.Expand(cmd, expand)
for i := range args {
args[i] = os.Expand(args[i], expand)
}
}
if ctx != nil && ctx.Done() != nil && !start { // (Background is never done)
done := make(chan struct{})
defer close(done)
go interruptOnDone(ctx, done, ses)
}
return cl.run(ses, sio, tty, start, output, cmd, args...)
}
// interruptOnDone interrupts the command of the given session when the
// given context is done, unless done is closed first (see
// [Client.ExecContext]).
func interruptOnDone(ctx context.Context, done chan struct{}, ses *ssh.Session) {
select {
case <-done:
return
case <-ctx.Done():
}
ses.Signal(ssh.SIGINT) // not all servers support this
select {
case <-done:
case <-time.After(exec.InterruptWait):
ses.Close()
}
}
func (cl *Client) run(ses *ssh.Session, sio *exec.StdIOState, tty *os.File, start exec.StartMode, output exec.OutputMode, cmd string, args ...string) (string, error) {
for k, v := range cl.Env {
ses.Setenv(k, v)
}
var err error
out := ""
ses.Stderr = sio.Err // note: no need to save previous b/c not retained
ses.Stdout = sio.Out
if cl.Echo != nil {
cl.PrintCmd(cmd+" "+strings.Join(args, " "), err)
}
if exec.IsPipe(sio.In) {
ses.Stdin = sio.In
}
if tty != nil && !cl.PrintOnly {
stop, err := forwardInput(ses, tty)
if err != nil {
return "", err
}
defer stop()
}
cdto := ""
cmds := cmd + " " + strings.Join(args, " ")
if cl.Dir != "" {
if cmd == "cd" {
if len(args) > 0 {
cdto = args[0]
} else {
cdto = cl.HomeDir
}
}
cmds = `cd '` + cl.Dir + `'; ` + cmds
}
cmds = cl.exports + cmds
if !cl.PrintOnly {
switch {
case start == exec.Background:
err = ses.Start(cmds)
go func() {
ses.Wait()
sio.PopToStart()
}()
case output == exec.CaptureOutput:
buf := &bytes.Buffer{}
ses.Stdout = buf
err = ses.Run(cmds)
if sio.Out != nil {
sio.Out.Write(buf.Bytes())
}
out = strings.TrimSuffix(buf.String(), "\n")
default:
err = ses.Run(cmds)
}
// we must call InitColor after calling a system command
// TODO(kai): maybe figure out a better solution to this
// or expand this list
if cmd == "cp" || cmd == "ls" || cmd == "mv" {
logx.InitColor()
}
if cdto != "" {
if filepath.IsAbs(cdto) {
cl.Dir = filepath.Clean(cdto)
} else {
cl.Dir = filepath.Clean(filepath.Join(cl.Dir, cdto))
}
}
}
return out, err
}
// Shell runs an interactive login shell on the host, in the current
// directory of the client, with the terminal of the given standard input,
// whose input it gets while it runs (see [Client.ExecContext]), until it
// ends, as with exit or Control+D. Its exit status is not an error, as
// it is that of the last command in it. It needs a terminal.
func (cl *Client) Shell(sio *exec.StdIOState) error {
tty := terminalInput(sio.In)
if tty == nil {
return errors.New("ssh: an interactive shell needs the input of a terminal")
}
ses, err := cl.newSession(tty)
if err != nil {
return err
}
defer ses.Close()
for k, v := range cl.Env {
ses.Setenv(k, v)
}
ses.Stdout, ses.Stderr = sio.Out, sio.Err
stop, err := forwardInput(ses, tty)
if err != nil {
return err
}
defer stop()
if cl.Dir != "" && cl.Dir != cl.HomeDir {
err = ses.Start(`cd '` + cl.Dir + `' && exec "$SHELL" -l`)
} else {
err = ses.Shell()
}
if err != nil {
return err
}
err = ses.Wait()
if _, ok := errors.AsType[*ssh.ExitError](err); ok {
return nil
}
return err
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build unix
package sshclient
import (
"errors"
"io"
"os"
"unsafe"
"golang.org/x/crypto/ssh"
"golang.org/x/sys/unix"
"golang.org/x/term"
)
// terminalInput returns the given standard input as a terminal,
// if it is one, or nil.
func terminalInput(in io.Reader) *os.File {
f, ok := in.(*os.File)
if !ok || !term.IsTerminal(int(f.Fd())) || int(f.Fd()) >= fdSetSize {
return nil
}
return f
}
// fdSetSize is the number of file descriptors that a [unix.FdSet] holds,
// for select.
const fdSetSize = int(unsafe.Sizeof(unix.FdSet{})) * 8
// forwardInput sends the input of the given terminal to the command of the
// given session, which has a terminal on the host (see [Client.newSession]),
// with the terminal in raw mode, such that the terminal on the host
// handles it, as for the keys of interactive programs and Control+C,
// and tells it about changes of the size of the terminal. It must be
// called before the command starts, and the returned function must be
// called when it ends: it stops reading the input, and restores the
// mode of the terminal. The input is only read when it is available, so
// that none of it is read after the command ends, as the input that
// follows is for the next command.
func forwardInput(ses *ssh.Session, tty *os.File) (stop func(), err error) {
w, err := ses.StdinPipe()
if err != nil {
return nil, err
}
fd := int(tty.Fd())
state, err := term.MakeRaw(fd)
if err != nil {
return nil, err
}
done := make(chan struct{})
ended := make(chan struct{})
go func() {
defer close(ended)
cols, rows, _ := term.GetSize(fd)
buf := make([]byte, 1024)
for {
select {
case <-done:
return
default:
}
if c, r, err := term.GetSize(fd); err == nil && (c != cols || r != rows) {
cols, rows = c, r
ses.WindowChange(rows, cols)
}
// poll does not work with terminals on macOS, so select is used
var fds unix.FdSet
fds.Set(fd)
tv := unix.Timeval{Usec: 100_000}
n, err := unix.Select(fd+1, &fds, nil, nil, &tv)
if errors.Is(err, unix.EINTR) || (err == nil && n == 0) {
continue
}
if err != nil {
return
}
n, err = unix.Read(fd, buf)
if errors.Is(err, unix.EAGAIN) || errors.Is(err, unix.EINTR) {
continue
}
if err != nil || n == 0 {
return
}
if _, err := w.Write(buf[:n]); err != nil {
return
}
}
}()
return func() {
close(done)
<-ended
term.Restore(fd, state)
}, nil
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package sshclient
import (
"context"
"cogentcore.org/core/base/exec"
)
// Run runs given command, using config input / outputs.
// Must have already made a successful Connect.
func (cl *Client) Run(sio *exec.StdIOState, cmd string, args ...string) error {
_, err := cl.Exec(sio, exec.Foreground, exec.NoCapture, cmd, args...)
return err
}
// RunContext is [Client.Run] with a context, with which the command
// is interrupted (see [Client.ExecContext]).
func (cl *Client) RunContext(ctx context.Context, sio *exec.StdIOState, cmd string, args ...string) error {
_, err := cl.ExecContext(ctx, sio, exec.Foreground, exec.NoCapture, cmd, args...)
return err
}
// Start starts the given command with arguments.
func (cl *Client) Start(sio *exec.StdIOState, cmd string, args ...string) error {
_, err := cl.Exec(sio, exec.Background, exec.NoCapture, cmd, args...)
return err
}
// Output runs the command and returns the text from stdout.
func (cl *Client) Output(sio *exec.StdIOState, cmd string, args ...string) (string, error) {
return cl.Exec(sio, exec.Foreground, exec.CaptureOutput, cmd, args...)
}
// OutputContext is [Client.Output] with a context, with which the command
// is interrupted (see [Client.ExecContext]).
func (cl *Client) OutputContext(ctx context.Context, sio *exec.StdIOState, cmd string, args ...string) (string, error) {
return cl.ExecContext(ctx, sio, exec.Foreground, exec.CaptureOutput, cmd, args...)
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package sshtest provides an SSH server for testing code that uses
// [cogentcore.org/core/base/sshclient], running in the test process on
// the local host: it runs commands with sh in its root directory, which
// is the home directory of the remote host, and serves SFTP.
package sshtest
import (
"crypto/ed25519"
"crypto/rand"
"encoding/binary"
"encoding/pem"
"errors"
"io"
"net"
"os"
"os/exec"
"path/filepath"
"runtime"
"sync"
"sync/atomic"
"testing"
"time"
"cogentcore.org/core/text/terminal/pty"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/knownhosts"
)
// Server is an SSH server for testing.
type Server struct {
// Addr is the address of the server, as host:port.
Addr string
// Root is the root directory of the server, which is its home
// directory for the commands that it runs. On Windows, its separator
// is /, as in the paths that pwd gives on the server (see [Server.session]).
Root string
// KeyPath is a directory with the private key of the client, as
// id_rsa, and a known_hosts file with the key of the server, for
// [cogentcore.org/core/base/sshclient.User.KeyPath].
KeyPath string
// Pty is whether the commands run in a terminal (pty) on the server
// when the client asks for one, as on a real server, such that the
// terminal handles their input, as for Control+C. It is off by
// default, as a terminal ends the lines of the output with \r\n.
Pty atomic.Bool
listener net.Listener
// down is whether the network is down (see [Server.NetworkDown]).
down atomic.Bool
// conns are the connections to the server.
conns []*conn
connsMu sync.Mutex
}
// conn is a connection to the server, which drops all of the data that
// it reads and writes once it is dead, as a connection does when the
// network is lost, without it being closed.
type conn struct {
net.Conn
dead atomic.Bool
}
func (c *conn) Read(b []byte) (int, error) {
for {
n, err := c.Conn.Read(b)
if err != nil || !c.dead.Load() {
return n, err
}
}
}
func (c *conn) Write(b []byte) (int, error) {
if c.dead.Load() {
return len(b), nil
}
return c.Conn.Write(b)
}
// NetworkDown simulates the loss of the network between the clients and
// the server, as when a laptop sleeps or changes networks: the existing
// connections drop all data from then on, without being closed, so a
// client gets no replies, and new connections are closed right away,
// until [Server.NetworkUp].
func (s *Server) NetworkDown() {
s.down.Store(true)
s.connsMu.Lock()
defer s.connsMu.Unlock()
for _, c := range s.conns {
c.dead.Store(true)
}
}
// NetworkUp ends [Server.NetworkDown], such that new connections work.
// The connections from before stay dead, as in a network.
func (s *Server) NetworkUp() {
s.down.Store(false)
}
// closeConns closes all of the connections.
func (s *Server) closeConns() {
s.connsMu.Lock()
defer s.connsMu.Unlock()
for _, c := range s.conns {
c.Close()
}
s.conns = nil
}
// NewServer starts a new SSH server for the test, which it stops at the
// end of the test, with a new temporary root directory.
func NewServer(t testing.TB) *Server {
t.Helper()
s := &Server{Root: t.TempDir(), KeyPath: t.TempDir()}
if root, err := filepath.EvalSymlinks(s.Root); err == nil {
s.Root = root // as pwd gives it
}
if runtime.GOOS == "windows" {
s.Root = filepath.ToSlash(s.Root)
}
_, hostPriv, err := ed25519.GenerateKey(rand.Reader)
check(t, err)
hostSigner, err := ssh.NewSignerFromKey(hostPriv)
check(t, err)
clientPub, clientPriv, err := ed25519.GenerateKey(rand.Reader)
check(t, err)
clientSSHPub, err := ssh.NewPublicKey(clientPub)
check(t, err)
block, err := ssh.MarshalPrivateKey(clientPriv, "")
check(t, err)
check(t, os.WriteFile(filepath.Join(s.KeyPath, "id_rsa"), pem.EncodeToMemory(block), 0600))
config := &ssh.ServerConfig{
PublicKeyCallback: func(_ ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
if string(key.Marshal()) == string(clientSSHPub.Marshal()) {
return nil, nil
}
return nil, errors.New("sshtest: unknown key")
},
}
config.AddHostKey(hostSigner)
s.listener, err = net.Listen("tcp", "127.0.0.1:0")
check(t, err)
s.Addr = s.listener.Addr().String()
line := knownhosts.Line([]string{knownhosts.Normalize(s.Addr)}, hostSigner.PublicKey())
check(t, os.WriteFile(filepath.Join(s.KeyPath, "known_hosts"), []byte(line+"\n"), 0600))
go s.serve(config)
t.Cleanup(func() {
s.listener.Close()
s.closeConns()
})
return s
}
func check(t testing.TB, err error) {
t.Helper()
if err != nil {
t.Fatal(err)
}
}
// serve accepts the connections to the server.
func (s *Server) serve(config *ssh.ServerConfig) {
for {
nc, err := s.listener.Accept()
if err != nil {
return
}
if s.down.Load() {
nc.Close()
continue
}
c := &conn{Conn: nc}
s.connsMu.Lock()
s.conns = append(s.conns, c)
s.connsMu.Unlock()
go func() {
_, chans, reqs, err := ssh.NewServerConn(c, config)
if err != nil {
c.Close()
return
}
go ssh.DiscardRequests(reqs)
for newCh := range chans {
if newCh.ChannelType() != "session" {
newCh.Reject(ssh.UnknownChannelType, "only sessions are supported")
continue
}
ch, reqs, err := newCh.Accept()
if err != nil {
continue
}
go s.session(ch, reqs)
}
}()
}
}
// session serves the requests of a session: environment variables, a
// command run with sh, which can get signals, the shell, which is sh,
// and the SFTP subsystem.
func (s *Server) session(ch ssh.Channel, reqs <-chan *ssh.Request) {
defer ch.Close()
env := []string{"HOME=" + s.Root, "PATH=" + os.Getenv("PATH"), "SHELL=/bin/sh"}
var cmd *exec.Cmd
var tm *pty.Pty // the terminal of the command, if cols > 0
cols, rows := 0, 0
ended := make(chan struct{})
defer func() {
if cmd == nil {
return
}
select {
case <-ended:
default: // the session was closed while the command runs: a hangup
cmd.Process.Kill()
}
}()
for {
var req *ssh.Request
select {
case req = <-reqs:
case <-ended: // the command ended
return
}
if req == nil {
return
}
switch req.Type {
case "pty-req": // the client asks for a terminal for interactive commands
var pr struct {
Term string
Cols, Rows uint32
W, H uint32
Modes string
}
if s.Pty.Load() && ssh.Unmarshal(req.Payload, &pr) == nil {
cols, rows = int(pr.Cols), int(pr.Rows)
}
req.Reply(true, nil)
case "window-change":
var wc struct{ Cols, Rows, W, H uint32 }
if tm != nil && ssh.Unmarshal(req.Payload, &wc) == nil {
tm.Resize(int(wc.Cols), int(wc.Rows))
}
req.Reply(true, nil)
case "env":
var kv struct{ Name, Value string }
if ssh.Unmarshal(req.Payload, &kv) == nil {
env = append(env, kv.Name+"="+kv.Value)
}
req.Reply(true, nil)
case "signal":
var sig struct{ Signal string }
if ssh.Unmarshal(req.Payload, &sig) == nil && sig.Signal == string(ssh.SIGINT) && cmd != nil {
cmd.Process.Signal(os.Interrupt)
}
req.Reply(true, nil)
case "exec", "shell":
var ex struct{ Command string }
if req.Type == "shell" { // the shell of the user
ex.Command = "exec $SHELL"
} else if ssh.Unmarshal(req.Payload, &ex) != nil {
req.Reply(false, nil)
continue
}
if cmd != nil {
req.Reply(false, nil)
continue
}
if runtime.GOOS == "windows" {
// the paths of sh (MSYS2) are not Windows paths, as SFTP and the tests use
ex.Command = "pwd() { command pwd -W; }; " + ex.Command
}
cmd = exec.Command("sh", "-c", ex.Command)
cmd.Dir, cmd.Env = s.Root, env
wait := cmd.Wait
if cols > 0 {
var err error
tm, err = pty.Start(cmd, cols, rows)
if err != nil {
req.Reply(false, nil)
return
}
go io.Copy(tm, ch)
output := make(chan struct{})
go func() {
io.Copy(ch, tm) // ends when the terminal is closed after the command
close(output)
}()
wait = func() error {
err := tm.Wait()
// reading the output does not end on macOS when the
// command ends, and it has to be read before closing
time.AfterFunc(100*time.Millisecond, func() { tm.Close() })
<-output
return err
}
} else {
cmd.Stdout, cmd.Stderr = ch, ch.Stderr()
stdin, _ := cmd.StdinPipe()
if err := cmd.Start(); err != nil {
req.Reply(false, nil)
return
}
go func() {
io.Copy(stdin, ch)
stdin.Close()
}()
}
req.Reply(true, nil)
go func() {
code := 0
if err := wait(); err != nil {
code = 1
if ee, ok := errors.AsType[*exec.ExitError](err); ok {
code = ee.ExitCode()
}
}
status := make([]byte, 4)
binary.BigEndian.PutUint32(status, uint32(code))
ch.SendRequest("exit-status", false, status)
close(ended)
}()
case "subsystem":
var sub struct{ Name string }
if ssh.Unmarshal(req.Payload, &sub) != nil || sub.Name != "sftp" {
req.Reply(false, nil)
continue
}
req.Reply(true, nil)
server, err := sftp.NewServer(ch, sftp.WithServerWorkingDirectory(s.Root))
if err != nil {
return
}
server.Serve()
return
default:
req.Reply(false, nil)
}
}
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package stack provides a generic stack implementation.
package stack
// Stack provides a generic stack using a slice.
type Stack[T any] []T
// Push pushes item(s) onto the stack.
func (st *Stack[T]) Push(it ...T) {
*st = append(*st, it...)
}
// Pop pops the top item off the stack.
// Returns nil / zero value if stack is empty.
func (st *Stack[T]) Pop() T {
n := len(*st)
if n == 0 {
var zv T
return zv
}
li := (*st)[n-1]
*st = (*st)[:n-1]
return li
}
// Peek returns the last element on the stack.
// Returns nil / zero value if stack is empty.
func (st *Stack[T]) Peek() T {
n := len(*st)
if n == 0 {
var zv T
return zv
}
return (*st)[n-1]
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on https://github.com/ettle/strcase
// Copyright (c) 2020 Liyan David Chang under the MIT License
package strcase
import (
"strings"
)
// Cases is an enum with all of the different string cases.
type Cases int32 //enums:enum
const (
// LowerCase is all lower case
LowerCase Cases = iota
// UpperCase is all UPPER CASE
UpperCase
// SnakeCase is lower_case_words_with_underscores
SnakeCase
// SNAKECase is UPPER_CASE_WORDS_WITH_UNDERSCORES
SNAKECase
// KebabCase is lower-case-words-with-dashes
KebabCase
// KEBABCase is UPPER-CASE-WORDS-WITH-DASHES
KEBABCase
// CamelCase is CapitalizedWordsConcatenatedTogether
CamelCase
// LowerCamelCase is capitalizedWordsConcatenatedTogether, with the first word lower case
LowerCamelCase
// TitleCase is Captitalized Words With Spaces
TitleCase
// SentenceCase is Lower case words with spaces, with the first word capitalized
SentenceCase
)
// To converts the given string to the given case.
func To(s string, c Cases) string {
switch c {
case LowerCase:
return strings.ToLower(s)
case UpperCase:
return strings.ToUpper(s)
case SnakeCase:
return ToSnake(s)
case SNAKECase:
return ToSNAKE(s)
case KebabCase:
return ToKebab(s)
case KEBABCase:
return ToKEBAB(s)
case CamelCase:
return ToCamel(s)
case LowerCamelCase:
return ToLowerCamel(s)
case TitleCase:
return ToTitle(s)
case SentenceCase:
return ToSentence(s)
}
return s
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on https://github.com/ettle/strcase
// Copyright (c) 2020 Liyan David Chang under the MIT License
package strcase
import (
"strings"
"unicode"
)
// WordCases is an enumeration of the ways to format a word.
type WordCases int32 //enums:enum -trim-prefix Word
const (
// WordOriginal indicates to preserve the original input case.
WordOriginal WordCases = iota
// WordLowerCase indicates to make all letters lower case (example).
WordLowerCase
// WordUpperCase indicates to make all letters upper case (EXAMPLE).
WordUpperCase
// WordTitleCase indicates to make only the first letter upper case (Example).
WordTitleCase
// WordCamelCase indicates to make only the first letter upper case, except
// in the first word, in which all letters are lower case (exampleText).
WordCamelCase
// WordSentenceCase indicates to make only the first letter upper case, and
// only for the first word (all other words have fully lower case letters).
WordSentenceCase
)
// ToWordCase converts the given input string to the given word case with the given delimiter.
// Pass 0 for delimeter to use no delimiter.
//
//nolint:gocyclo
func ToWordCase(input string, wordCase WordCases, delimiter rune) string {
input = strings.TrimSpace(input)
runes := []rune(input)
if len(runes) == 0 {
return ""
}
var b strings.Builder
b.Grow(len(input) + 4) // In case we need to write delimiters where they weren't before
firstWord := true
var skipIndexes []int
addWord := func(start, end int) {
// If you have nothing good to say, say nothing at all
if start == end || len(skipIndexes) == end-start {
skipIndexes = nil
return
}
// If you have something to say, start with a delimiter
if !firstWord && delimiter != 0 {
b.WriteRune(delimiter)
}
// Check to see if the entire word is an initialism for preserving initialism.
// Note we don't support preserving initialisms if they are followed
// by a number and we're not spliting before numbers.
if wordCase == WordTitleCase || wordCase == WordSentenceCase || (wordCase == WordCamelCase && !firstWord) {
allCaps := true
for i := start; i < end; i++ {
allCaps = allCaps && (isUpper(runes[i]) || !unicode.IsLetter(runes[i]))
}
if allCaps {
b.WriteString(string(runes[start:end]))
firstWord = false
return
}
}
skipIndex := 0
for i := start; i < end; i++ {
if len(skipIndexes) > 0 && skipIndex < len(skipIndexes) && i == skipIndexes[skipIndex] {
skipIndex++
continue
}
r := runes[i]
switch wordCase {
case WordUpperCase:
b.WriteRune(toUpper(r))
case WordLowerCase:
b.WriteRune(toLower(r))
case WordTitleCase:
if i == start {
b.WriteRune(toUpper(r))
} else {
b.WriteRune(toLower(r))
}
case WordCamelCase:
if !firstWord && i == start {
b.WriteRune(toUpper(r))
} else {
b.WriteRune(toLower(r))
}
case WordSentenceCase:
if firstWord && i == start {
b.WriteRune(toUpper(r))
} else {
b.WriteRune(toLower(r))
}
default:
b.WriteRune(r)
}
}
firstWord = false
skipIndexes = nil
}
var prev, curr rune
next := runes[0] // 0 length will have already returned so safe to index
wordStart := 0
for i := range runes {
prev = curr
curr = next
if i+1 == len(runes) {
next = 0
} else {
next = runes[i+1]
}
switch defaultSplitFn(prev, curr, next) {
case Skip:
skipIndexes = append(skipIndexes, i)
case Split:
addWord(wordStart, i)
wordStart = i
case SkipSplit:
addWord(wordStart, i)
wordStart = i + 1
}
}
if wordStart != len(runes) {
addWord(wordStart, len(runes))
}
return b.String()
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package strcase
import "strings"
// FormatList returns a formatted version of the given list of items following these rules:
// - nil => ""
// - "Go" => "Go"
// - "Go", "Python" => "Go and Python"
// - "Go", "Python", "JavaScript" => "Go, Python, and JavaScript"
// - "Go", "Python", "JavaScript", "C" => "Go, Python, JavaScript, and C"
func FormatList(items ...string) string {
switch len(items) {
case 0:
return ""
case 1:
return items[0]
case 2:
return items[0] + " and " + items[1]
}
var res strings.Builder
for i, match := range items {
res.WriteString(match)
if i == len(items)-1 {
// last one, so do nothing
} else if i == len(items)-2 {
res.WriteString(", and ")
} else {
res.WriteString(", ")
}
}
return res.String()
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on https://github.com/ettle/strcase
// Copyright (c) 2020 Liyan David Chang under the MIT License
package strcase
import "unicode"
// SplitAction defines if and how to split a string
type SplitAction int
const (
// Noop - Continue to next character
Noop SplitAction = iota
// Split - Split between words
// e.g. to split between wordsWithoutDelimiters
Split
// SkipSplit - Split the word and drop the character
// e.g. to split words with delimiters
SkipSplit
// Skip - Remove the character completely
Skip
)
//nolint:gocyclo
func defaultSplitFn(prev, curr, next rune) SplitAction {
// The most common case will be that it's just a letter so let lowercase letters return early since we know what they should do
if isLower(curr) {
return Noop
}
// Delimiters are _, -, ., and unicode spaces
// Handle . lower down as it needs to happen after number exceptions
if curr == '_' || curr == '-' || isSpace(curr) {
return SkipSplit
}
if isUpper(curr) {
if isLower(prev) {
// fooBar
return Split
} else if isUpper(prev) && isLower(next) {
// FOOBar
return Split
}
}
// Do numeric exceptions last to avoid perf penalty
if unicode.IsNumber(prev) {
// v4.3 is not split
if (curr == '.' || curr == ',') && unicode.IsNumber(next) {
return Noop
}
if !unicode.IsNumber(curr) && curr != '.' {
return Split
}
}
// While period is a default delimiter, keep it down here to avoid
// penalty for other delimiters
if curr == '.' {
return SkipSplit
}
return Noop
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on https://github.com/ettle/strcase
// Copyright (c) 2020 Liyan David Chang under the MIT License
// Package strcase provides functions for manipulating the case of strings (CamelCase, kebab-case,
// snake_case, Sentence case, etc). It is based on https://github.com/ettle/strcase, which is Copyright
// (c) 2020 Liyan David Chang under the MIT License. Its principle difference from other strcase packages
// is that it preserves acronyms in input text for CamelCase. Therefore, you must call [strings.ToLower]
// on any SCREAMING_INPUT_STRINGS before passing them to [ToCamel], [ToLowerCamel], [ToTitle], and [ToSentence].
package strcase
//go:generate core generate
// ToSnake returns words in snake_case (lower case words with underscores).
func ToSnake(s string) string {
return ToWordCase(s, WordLowerCase, '_')
}
// ToSNAKE returns words in SNAKE_CASE (upper case words with underscores).
// Also known as SCREAMING_SNAKE_CASE or UPPER_CASE.
func ToSNAKE(s string) string {
return ToWordCase(s, WordUpperCase, '_')
}
// ToKebab returns words in kebab-case (lower case words with dashes).
// Also known as dash-case.
func ToKebab(s string) string {
return ToWordCase(s, WordLowerCase, '-')
}
// ToKEBAB returns words in KEBAB-CASE (upper case words with dashes).
// Also known as SCREAMING-KEBAB-CASE or SCREAMING-DASH-CASE.
func ToKEBAB(s string) string {
return ToWordCase(s, WordUpperCase, '-')
}
// ToCamel returns words in CamelCase (capitalized words concatenated together).
// Also known as UpperCamelCase.
func ToCamel(s string) string {
return ToWordCase(s, WordTitleCase, 0)
}
// ToLowerCamel returns words in lowerCamelCase (capitalized words concatenated together,
// with first word lower case). Also known as camelCase or mixedCase.
func ToLowerCamel(s string) string {
return ToWordCase(s, WordCamelCase, 0)
}
// ToTitle returns words in Title Case (capitalized words with spaces).
func ToTitle(s string) string {
return ToWordCase(s, WordTitleCase, ' ')
}
// ToSentence returns words in Sentence case (lower case words with spaces, with the first word capitalized).
func ToSentence(s string) string {
return ToWordCase(s, WordSentenceCase, ' ')
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on https://github.com/ettle/strcase
// Copyright (c) 2020 Liyan David Chang under the MIT License
package strcase
import "unicode"
// Unicode functions, optimized for the common case of ascii
// No performance lost by wrapping since these functions get inlined by the compiler
func isUpper(r rune) bool {
return unicode.IsUpper(r)
}
func isLower(r rune) bool {
return unicode.IsLower(r)
}
func isNumber(r rune) bool {
if r >= '0' && r <= '9' {
return true
}
return unicode.IsNumber(r)
}
func isSpace(r rune) bool {
if r == ' ' || r == '\t' || r == '\n' || r == '\r' {
return true
} else if r < 128 {
return false
}
return unicode.IsSpace(r)
}
func toUpper(r rune) rune {
if r >= 'a' && r <= 'z' {
return r - 32
} else if r < 128 {
return r
}
return unicode.ToUpper(r)
}
func toLower(r rune) rune {
if r >= 'A' && r <= 'Z' {
return r + 32
} else if r < 128 {
return r
}
return unicode.ToLower(r)
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package stringsx provides additional string functions
// beyond those in the standard [strings] package.
package stringsx
import (
"bytes"
"slices"
"strings"
)
// TrimCR returns the string without any trailing \r carriage return
func TrimCR(s string) string {
n := len(s)
if n == 0 {
return s
}
if s[n-1] == '\r' {
return s[:n-1]
}
return s
}
// ByteTrimCR returns the byte string without any trailing \r carriage return
func ByteTrimCR(s []byte) []byte {
n := len(s)
if n == 0 {
return s
}
if s[n-1] == '\r' {
return s[:n-1]
}
return s
}
// SplitLines is a windows-safe version of [strings.Split](s, "\n")
// that removes any trailing \r carriage returns from the split lines.
func SplitLines(s string) []string {
ls := strings.Split(s, "\n")
for i, l := range ls {
ls[i] = TrimCR(l)
}
return ls
}
// ByteSplitLines is a windows-safe version of [bytes.Split](s, "\n")
// that removes any trailing \r carriage returns from the split lines.
func ByteSplitLines(s []byte) [][]byte {
ls := bytes.Split(s, []byte("\n"))
for i, l := range ls {
ls[i] = ByteTrimCR(l)
}
return ls
}
// InsertFirstUnique inserts the given string at the start of the given string slice
// while keeping the overall length to the given max value. If the item is already on
// the list, then it is moved to the top and not re-added (unique items only). This is
// useful for a list of recent items.
func InsertFirstUnique(strs *[]string, str string, max int) {
if max <= 0 { // nothing can be kept
*strs = (*strs)[:0]
return
}
if *strs == nil {
*strs = make([]string, 0, max)
}
sz := len(*strs)
if sz > max {
*strs = (*strs)[:max]
}
for i, s := range *strs {
if s == str {
if i == 0 {
return
}
copy((*strs)[1:i+1], (*strs)[0:i])
(*strs)[0] = str
return
}
}
if sz >= max {
copy((*strs)[1:max], (*strs)[0:max-1])
(*strs)[0] = str
} else {
*strs = append(*strs, "")
if sz > 0 {
copy((*strs)[1:], (*strs)[0:sz])
}
(*strs)[0] = str
}
}
// UniqueList removes duplicates from given string list,
// preserving the order.
func UniqueList(strs []string) []string {
n := len(strs)
for i := n - 1; i >= 0; i-- {
p := strs[i]
for j, s := range strs {
if p == s && i != j {
// deleted once only: the index i is then a different item
strs = slices.Delete(strs, i, i+1)
break
}
}
}
return strs
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package tiered provides a type for a tiered set of objects.
package tiered
// Tiered represents a tiered set of objects of the same type.
// For example, this is frequently used to represent slices of
// functions that can be run at the first, normal, or final time.
type Tiered[T any] struct {
// First is the object that will be used first,
// before [Tiered.Normal] and [Tiered.Final].
First T
// Normal is the object that will be used at the normal
// time, after [Tiered.First] and before [Tiered.Final].
Normal T
// Final is the object that will be used last,
// after [Tiered.First] and [Tiered.Normal].
Final T
}
// Do calls the given function for each tier,
// going through first, then normal, then final.
func (t *Tiered[T]) Do(f func(*T)) {
f(&t.First)
f(&t.Normal)
f(&t.Final)
}
// DoWith calls the given function with each tier of this tiered
// set and the other given tiered set, going through first, then
// normal, then final.
func (t *Tiered[T]) DoWith(other *Tiered[T], f func(*T, *T)) {
f(&t.First, &other.First)
f(&t.Normal, &other.Normal)
f(&t.Final, &other.Final)
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package timer provides a simple wall-clock duration timer based on standard
// [time]. It accumulates total and average over multiple Start / Stop intervals.
package timer
import "time"
// Time manages the timer accumulated time and count
type Time struct {
// the most recent starting time
St time.Time
// the total accumulated time
Total time.Duration
// the number of start/stops
N int
}
// Reset resets the overall accumulated Total and N counters and start time to zero
func (t *Time) Reset() {
t.St = time.Time{}
t.Total = 0
t.N = 0
}
// Start starts the timer
func (t *Time) Start() {
t.St = time.Now()
}
// ResetStart reset then start the timer
func (t *Time) ResetStart() {
t.Reset()
t.Start()
}
// Stop stops the timer and accumulates the latest start - stop interval, and also returns it
func (t *Time) Stop() time.Duration {
if t.St.IsZero() {
t.Total = 0
t.N = 0
return 0
}
iv := time.Since(t.St)
t.Total += iv
t.N++
return iv
}
// Avg returns the average start / stop interval (assumes each was measuring the same thing).
func (t *Time) Avg() time.Duration {
if t.N == 0 {
return 0
}
return t.Total / time.Duration(t.N)
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package tolassert provides functions for asserting the equality of numbers
// with tolerance (in other words, it checks whether numbers are about equal).
package tolassert
import (
"fmt"
"cogentcore.org/core/base/num"
"github.com/stretchr/testify/assert"
)
// Equal asserts that the given two numbers are about equal to each other,
// using a default tolerance of 0.001.
func Equal[T num.Float](t assert.TestingT, expected T, actual T, msgAndArgs ...any) bool {
if h, ok := t.(interface{ Helper() }); ok {
h.Helper()
}
return EqualTol(t, expected, actual, 0.001, msgAndArgs...)
}
// EqualTol asserts that the given two numbers are about equal to each other,
// using the given tolerance value.
func EqualTol[T num.Float](t assert.TestingT, expected T, actual, tolerance T, msgAndArgs ...any) bool {
if h, ok := t.(interface{ Helper() }); ok {
h.Helper()
}
if num.Abs(actual-expected) > tolerance {
return assert.Equal(t, expected, actual, msgAndArgs...)
}
return true
}
// EqualTolSlice asserts that the given two slices of numbers are about equal to each other,
// using the given tolerance value.
func EqualTolSlice[T num.Float](t assert.TestingT, expected, actual []T, tolerance T, msgAndArgs ...any) bool {
if h, ok := t.(interface{ Helper() }); ok {
h.Helper()
}
if len(expected) != len(actual) {
return assert.Equal(t, expected, actual, msgAndArgs...)
}
ok := true
for i, ex := range expected {
a := actual[i]
if num.Abs(a-ex) > tolerance {
assert.Equal(t, expected, actual, fmt.Sprintf("index: %d", i))
ok = false
}
}
return ok
}
// Copyright (c) 2020, The Cogent Core Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package vcs
import (
"maps"
"os"
"path/filepath"
"strings"
)
// Files is a map used for storing files in a repository along with their status
type Files map[string]FileStatus
// Status returns the VCS file status associated with given filename,
// returning Untracked if not found and safe to empty map.
func (fl *Files) Status(repo Repo, fname string) FileStatus {
if len(*fl) == 0 {
return Untracked
}
st, ok := (*fl)[relPath(repo, fname)]
if !ok {
return Untracked
}
return st
}
// moved updates the files for the file or directory at the relative path
// oldrel being moved (renamed) to newrel in the repository: their status is
// Added, as the rename is staged, unless they are untracked.
// It does nothing for a nil map.
func (fl Files) moved(oldrel, newrel string) {
if fl == nil {
return
}
prefix := oldrel + string(filepath.Separator)
moved := Files{}
for f, st := range fl {
if f != oldrel && !strings.HasPrefix(f, prefix) {
continue
}
delete(fl, f)
if st != Untracked {
st = Added
}
moved[newrel+f[len(oldrel):]] = st
}
maps.Copy(fl, moved)
}
// allFiles returns a slice of all the files, recursively, within a given directory
func allFiles(path string) ([]string, error) {
var fnms []string
er := filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
fnms = append(fnms, path)
return nil
})
return fnms, er
}
// FileStatus indicates the status of files in the repository
type FileStatus int32 //enums:enum
const (
// Untracked means file is not under VCS control
Untracked FileStatus = iota
// Stored means file is stored under VCS control, and has not been modified in working copy
Stored
// Modified means file is under VCS control, and has been modified in working copy
Modified
// Added means file has just been added to VCS but is not yet committed
Added
// Deleted means file has been deleted from VCS
Deleted
// Conflicted means file is in conflict -- has not been merged
Conflicted
// Updated means file has been updated in the remote but not locally
Updated
)
// Copyright (c) 2019, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package vcs
import (
"bufio"
"bytes"
"fmt"
"log"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
)
// GitRepo is a git repository, using the git command.
type GitRepo struct {
repoBase
files Files
gettingFiles bool
sync.Mutex
}
// NewGitRepo returns a [GitRepo] for the git repository at the given local
// path. The remote is the location (URL) of the remote repository, or the
// name of a remote, which is origin if empty; it is "" if there is none.
func NewGitRepo(remote, local string) (*GitRepo, error) {
gr := &GitRepo{}
gr.local = local
if _, err := gr.runErr("git", "rev-parse", "--git-dir"); err != nil {
return nil, fmt.Errorf("not a git repository: %s: %w", local, err)
}
gr.remote = remote
if !strings.ContainsAny(remote, "/:") { // a remote name
if remote == "" {
remote = "origin"
}
gr.remote, _ = gr.runErr("git", "config", "--get", "remote."+remote+".url")
}
return gr, nil
}
func (gr *GitRepo) Type() Types {
return Git
}
// Update updates the repository from the remote, with git pull,
// or just git fetch if HEAD is detached (not on a branch).
func (gr *GitRepo) Update() error {
if _, err := gr.runErr("git", "symbolic-ref", "-q", "HEAD"); err != nil {
_, err := gr.runErr("git", "fetch", "--tags")
return err
}
_, err := gr.runErr("git", "pull")
return err
}
// Current returns the current branch, or the commit hash if HEAD is detached.
func (gr *GitRepo) Current() (string, error) {
if br, err := gr.runErr("git", "symbolic-ref", "-q", "--short", "HEAD"); err == nil {
return br, nil
}
return gr.runErr("git", "rev-parse", "HEAD")
}
// Files returns a map of the current files and their status,
// using a cached version of the file list if available.
// nil will be returned immediately if no cache is available.
// The given onUpdated function will be called from a separate
// goroutine when the updated list of the files is available,
// if an update is not already under way. An update is always triggered
// if no files have yet been cached, even if the function is nil.
func (gr *GitRepo) Files(onUpdated func(f Files)) (Files, error) {
gr.Lock()
if gr.files != nil {
f := gr.files
gr.Unlock()
if onUpdated != nil {
go gr.updateFiles(onUpdated)
}
return f, nil
}
gr.Unlock()
go gr.updateFiles(onUpdated)
return nil, nil
}
func (gr *GitRepo) updateFiles(onUpdated func(f Files)) {
gr.Lock()
if gr.gettingFiles {
gr.Unlock()
return
}
gr.gettingFiles = true
gr.Unlock()
nf := max(len(gr.files), 64)
f := make(Files, nf)
out, err := gr.RunFromDir("git", "ls-files", "-o") // other -- untracked
if err == nil {
scan := bufio.NewScanner(bytes.NewReader(out))
for scan.Scan() {
fn := filepath.FromSlash(string(scan.Bytes()))
f[fn] = Untracked
}
}
out, err = gr.RunFromDir("git", "ls-files", "-c") // cached = all in repo
if err == nil {
scan := bufio.NewScanner(bytes.NewReader(out))
for scan.Scan() {
fn := filepath.FromSlash(string(scan.Bytes()))
f[fn] = Stored
}
}
out, err = gr.RunFromDir("git", "ls-files", "-m") // modified
if err == nil {
scan := bufio.NewScanner(bytes.NewReader(out))
for scan.Scan() {
fn := filepath.FromSlash(string(scan.Bytes()))
f[fn] = Modified
}
}
out, err = gr.RunFromDir("git", "ls-files", "-d") // deleted
if err == nil {
scan := bufio.NewScanner(bytes.NewReader(out))
for scan.Scan() {
fn := filepath.FromSlash(string(scan.Bytes()))
f[fn] = Deleted
}
}
out, err = gr.RunFromDir("git", "ls-files", "-u") // unmerged
if err == nil {
scan := bufio.NewScanner(bytes.NewReader(out))
for scan.Scan() {
fn := filepath.FromSlash(string(scan.Bytes()))
f[fn] = Conflicted
}
}
out, err = gr.RunFromDir("git", "diff", "--name-only", "--diff-filter=A", "HEAD") // deleted
if err == nil {
scan := bufio.NewScanner(bytes.NewReader(out))
for scan.Scan() {
fn := filepath.FromSlash(string(scan.Bytes()))
f[fn] = Added
}
}
gr.Lock()
gr.files = f
gr.Unlock()
if onUpdated != nil {
onUpdated(f)
}
gr.Lock()
gr.gettingFiles = false
gr.Unlock()
}
func (gr *GitRepo) charToStat(stat byte) FileStatus {
switch stat {
case 'M':
return Modified
case 'A':
return Added
case 'D':
return Deleted
case 'U':
return Conflicted
case '?', '!':
return Untracked
}
return Untracked
}
// StatusFast returns file status based on the cached file info,
// which might be slightly stale. Much faster than Status.
// Returns Stored if no files have been cached yet.
func (gr *GitRepo) StatusFast(fname string) FileStatus {
var ff Files
gr.Lock()
ff = gr.files
gr.Unlock()
if ff != nil {
return ff.Status(gr, fname)
}
return Stored // not known yet: shown as normal
}
// Status returns status of given file; returns Untracked on any error.
func (gr *GitRepo) Status(fname string) (FileStatus, string) {
out, err := gr.RunFromDir("git", "status", "--porcelain", relPath(gr, fname))
if err != nil {
return Untracked, err.Error()
}
ostr := string(out)
if ostr == "" {
return Stored, ""
}
sf := strings.Fields(ostr)
if len(sf) < 2 {
return Stored, ostr
}
stat := sf[0][0]
return gr.charToStat(stat), ostr
}
// Add adds the file to the repo
func (gr *GitRepo) Add(fname string) error {
fname = relPath(gr, fname)
if _, err := gr.runErr("git", "add", fname); err != nil {
return err
}
gr.Lock()
if gr.files != nil {
gr.files[fname] = Added
}
gr.Unlock()
return nil
}
// Move renames the file or directory at oldpath to newpath with git mv,
// which stages the rename (but not other changes to the files).
func (gr *GitRepo) Move(oldpath, newpath string) error {
oldrel, newrel := relPath(gr, oldpath), relPath(gr, newpath)
out, err := gr.RunFromDir("git", "mv", oldrel, newrel)
if err != nil {
return fmt.Errorf("git mv: %w: %s", err, strings.TrimSpace(string(out)))
}
gr.Lock()
gr.files.moved(oldrel, newrel)
gr.Unlock()
return nil
}
// Delete removes the file from the repo; uses "force" option to ensure deletion
func (gr *GitRepo) Delete(fname string) error {
_, err := gr.runErr("git", "rm", "-f", relPath(gr, fname))
return err
}
// DeleteRemote removes the file from the repo
func (gr *GitRepo) DeleteRemote(fname string) error {
_, err := gr.runErr("git", "rm", "--cached", relPath(gr, fname))
return err
}
// CommitFile commits single file to repo staging
func (gr *GitRepo) CommitFile(fname string, message string) error {
_, err := gr.runErr("git", "commit", relPath(gr, fname), "-m", message)
return err
}
// RevertFile reverts a single file to last commit of master
func (gr *GitRepo) RevertFile(fname string) error {
_, err := gr.runErr("git", "checkout", relPath(gr, fname))
return err
}
// UpdateVersion sets the version of a package currently checked out via Git.
func (gr *GitRepo) UpdateVersion(version string) error {
_, err := gr.runErr("git", "switch", "--detach", version)
return err
}
// FileContents returns the contents of given file, as a []byte array
// at given revision specifier, or the current file in the working copy
// if empty (use HEAD for the last commit). -1, -2 etc also work as
// universal ways of specifying prior revisions.
func (gr *GitRepo) FileContents(fname string, rev string) ([]byte, error) {
if rev == "" {
out, err := os.ReadFile(fname)
if err != nil {
log.Println(err.Error())
}
return out, err
} else if rev[0] == '-' {
rsp, err := strconv.Atoi(rev)
if err == nil && rsp < 0 {
rev = fmt.Sprintf("HEAD~%d:", -rsp)
}
} else {
rev += ":"
}
fspec := rev + relPath(gr, fname)
out, err := gr.RunFromDir("git", "show", fspec)
if err != nil {
log.Println(string(out))
return nil, err
}
return out, nil
}
// fieldsThroughDelim gets the concatenated byte through to point where
// field ends with given delimiter, starting at given index
func fieldsThroughDelim(flds [][]byte, delim byte, idx int) (int, string) {
ln := len(flds)
for i := idx; i < ln; i++ {
fld := flds[i]
fsz := len(fld)
if fld[fsz-1] == delim {
str := string(bytes.Join(flds[idx:i+1], []byte(" ")))
return i + 1, str[:len(str)-1]
}
}
return ln, string(bytes.Join(flds[idx:ln], []byte(" ")))
}
// Log returns the log history of commits for given filename
// (or all files if empty). If since is non-empty, it should be
// a date-like expression that the VCS will understand, such as
// 1/1/2020, yesterday, last year, etc
func (gr *GitRepo) Log(fname string, since string) (Log, error) {
args := []string{"log", "--all"}
if since != "" {
args = append(args, "--since="+since) // (no shell to remove quotes)
}
args = append(args, `--pretty=format:%h %ad} %an} %ae} %s`)
if fname != "" {
args = append(args, fname)
}
out, err := gr.RunFromDir("git", args...)
if err != nil {
return nil, err
}
var lg Log
scan := bufio.NewScanner(bytes.NewReader(out))
for scan.Scan() {
ln := scan.Bytes()
flds := bytes.Fields(ln)
if len(flds) < 4 {
continue
}
rev := string(flds[0])
ni, date := fieldsThroughDelim(flds, '}', 1)
ni, author := fieldsThroughDelim(flds, '}', ni)
ni, email := fieldsThroughDelim(flds, '}', ni)
msg := string(bytes.Join(flds[ni:], []byte(" ")))
lg.Add(rev, date, author, email, msg)
}
return lg, nil
}
// CommitDesc returns the full textual description of the given commit,
// if rev is empty, defaults to current HEAD, -1, -2 etc also work as universal
// ways of specifying prior revisions.
// Optionally includes diffs for the changes (otherwise just a list of files
// with modification status).
func (gr *GitRepo) CommitDesc(rev string, diffs bool) ([]byte, error) {
if rev == "" {
rev = "HEAD"
} else if rev[0] == '-' {
rsp, err := strconv.Atoi(rev)
if err == nil && rsp < 0 {
rev = fmt.Sprintf("HEAD~%d", -rsp)
}
}
var out []byte
var err error
if diffs {
out, err = gr.RunFromDir("git", "show", rev)
} else {
out, err = gr.RunFromDir("git", "show", "--name-status", rev)
}
if err != nil {
log.Println(string(out))
return nil, err
}
return out, nil
}
// FilesChanged returns the list of files changed and their statuses,
// between two revisions.
// If revA is empty, defaults to current HEAD; revB defaults to HEAD-1.
// -1, -2 etc also work as universal ways of specifying prior revisions.
// Optionally includes diffs for the changes.
func (gr *GitRepo) FilesChanged(revA, revB string, diffs bool) ([]byte, error) {
if revA == "" {
revA = "HEAD"
} else if revA[0] == '-' {
rsp, err := strconv.Atoi(revA)
if err == nil && rsp < 0 {
revA = fmt.Sprintf("HEAD~%d", -rsp)
}
}
if revB != "" && revB[0] == '-' {
rsp, err := strconv.Atoi(revB)
if err == nil && rsp < 0 {
revB = fmt.Sprintf("HEAD~%d", -rsp)
}
}
var out []byte
var err error
if diffs {
out, err = gr.RunFromDir("git", "diff", "-u", revA, revB)
} else {
if revB == "" {
out, err = gr.RunFromDir("git", "diff", "--name-status", revA)
} else {
out, err = gr.RunFromDir("git", "diff", "--name-status", revA, revB)
}
}
if err != nil {
log.Println(string(out))
return nil, err
}
return out, nil
}
// Blame returns an annotated report about the file, showing which revision last
// modified each line.
func (gr *GitRepo) Blame(fname string) ([]byte, error) {
out, err := gr.RunFromDir("git", "blame", fname)
if err != nil {
log.Println(string(out))
return nil, err
}
return out, nil
}
// Branches returns a list of the local branches.
func (gr *GitRepo) Branches() ([]string, error) {
out, err := gr.runErr("git", "branch")
if err != nil {
return []string{}, err
}
ff := strings.Fields(out)
var br []string
for _, f := range ff {
if f != "*" {
br = append(br, f)
}
}
return br, nil
}
// Copyright (c) 2018, The Cogent Core Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package vcs
// Commit is one VCS commit entry, as returned in a [Log].
type Commit struct {
// revision number / hash code / unique id
Rev string
// date (author's time) when committed
Date string
// author's name
Author string
// author's email
Email string
// message / subject line for commit
Message string `width:"100"`
}
// Log is a listing of commits.
type Log []*Commit
// Add adds a new [Commit] to the [Log], returning the [Commit].
func (lg *Log) Add(rev, date, author, email, message string) *Commit {
cm := &Commit{Rev: rev, Date: date, Author: author, Email: email, Message: message}
*lg = append(*lg, cm)
return cm
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package vcs
import (
"fmt"
"os"
"os/exec"
"strings"
)
// repoBase has the location of a repository, and runs commands in it.
type repoBase struct {
// remote is the location of the remote repository (a URL).
remote string
// local is the path of the local repository (working copy).
local string
}
// Remote returns the location of the remote repository (a URL),
// or "" if there is none.
func (rb *repoBase) Remote() string {
return rb.remote
}
// LocalPath returns the path of the local repository (working copy).
func (rb *repoBase) LocalPath() string {
return rb.local
}
// CmdFromDir returns a command to run in the local repository directory.
func (rb *repoBase) CmdFromDir(cmd string, args ...string) *exec.Cmd {
c := exec.Command(cmd, args...)
c.Dir = rb.local
c.Env = append(os.Environ(), "PWD="+rb.local)
return c
}
// RunFromDir runs the given command in the local repository directory,
// returning its combined output.
func (rb *repoBase) RunFromDir(cmd string, args ...string) ([]byte, error) {
return rb.CmdFromDir(cmd, args...).CombinedOutput()
}
// runErr runs the given command in the local repository directory,
// returning its output, and an error including the output if it fails.
func (rb *repoBase) runErr(cmd string, args ...string) (string, error) {
out, err := rb.RunFromDir(cmd, args...)
sout := strings.TrimSpace(string(out))
if err != nil {
return sout, fmt.Errorf("%s %s: %w: %s", cmd, args[0], err, sout)
}
return sout, nil
}
// Copyright (c) 2019, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package vcs
import (
"bufio"
"bytes"
"fmt"
"log"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
)
// SvnRepo is a Subversion working copy, using the svn command.
type SvnRepo struct {
repoBase
files Files
gettingFiles bool
sync.Mutex
}
// NewSvnRepo returns an [SvnRepo] for the Subversion working copy at the
// given local path. The remote is the URL of the repository: if empty,
// it is the one of the working copy.
func NewSvnRepo(remote, local string) (*SvnRepo, error) {
gr := &SvnRepo{}
gr.local = local
url, err := gr.runErr("svn", "info", "--show-item", "url")
if err != nil {
return nil, fmt.Errorf("not a Subversion working copy: %s: %w", local, err)
}
gr.remote = remote
if remote == "" {
gr.remote = url
}
return gr, nil
}
func (gr *SvnRepo) Type() Types {
return Svn
}
// Update updates the working copy from the repository (svn update).
func (gr *SvnRepo) Update() error {
return gr.run("update")
}
// UpdateVersion updates the working copy to the given revision.
func (gr *SvnRepo) UpdateVersion(version string) error {
return gr.run("update", "-r", version)
}
// Current returns the revision of the working copy.
func (gr *SvnRepo) Current() (string, error) {
return gr.runErr("svn", "info", "--show-item", "revision")
}
// Branches returns nil: Subversion branches are just directories.
func (gr *SvnRepo) Branches() ([]string, error) {
return nil, nil
}
func (gr *SvnRepo) CharToStat(stat byte) FileStatus {
switch stat {
case 'M', 'R':
return Modified
case 'A':
return Added
case 'D', '!':
return Deleted
case 'C':
return Conflicted
case '?', 'I':
return Untracked
case '*':
return Updated
default:
return Stored
}
}
// Files returns a map of the current files and their status,
// using a cached version of the file list if available.
// nil will be returned immediately if no cache is available.
// The given onUpdated function will be called from a separate
// goroutine when the updated list of the files is available,
// if an update is not already under way. An update is always triggered
// if no files have yet been cached, even if the function is nil.
func (gr *SvnRepo) Files(onUpdated func(f Files)) (Files, error) {
gr.Lock()
if gr.files != nil {
f := gr.files
gr.Unlock()
if onUpdated != nil {
go gr.updateFiles(onUpdated)
}
return f, nil
}
gr.Unlock()
go gr.updateFiles(onUpdated)
return nil, nil
}
func (gr *SvnRepo) updateFiles(onUpdated func(f Files)) {
gr.Lock()
if gr.gettingFiles {
gr.Unlock()
return
}
gr.gettingFiles = true
gr.Unlock()
f := make(Files)
lpath := gr.LocalPath()
allfs, err := allFiles(lpath) // much faster than svn list --recursive
if err == nil {
for _, fn := range allfs {
rpath, _ := filepath.Rel(lpath, fn)
f[rpath] = Stored
}
}
out, err := gr.RunFromDir("svn", "status", "-u")
if err == nil {
scan := bufio.NewScanner(bytes.NewReader(out))
for scan.Scan() {
ln := string(scan.Bytes())
flds := strings.Fields(ln)
if len(flds) < 2 {
continue // shouldn't happend
}
stat := flds[0][0]
fn := flds[len(flds)-1]
f[fn] = gr.CharToStat(stat)
}
}
gr.Lock()
gr.files = f
gr.gettingFiles = false
gr.Unlock()
if onUpdated != nil {
onUpdated(f)
}
}
// StatusFast returns file status based on the cached file info,
// which might be slightly stale. Much faster than Status.
// Returns Stored if no files have been cached yet.
func (gr *SvnRepo) StatusFast(fname string) FileStatus {
var ff Files
gr.Lock()
ff = gr.files
gr.Unlock()
if ff != nil {
return ff.Status(gr, fname)
}
return Stored // not known yet: shown as normal
}
// Status returns status of given file; returns Untracked on any error
func (gr *SvnRepo) Status(fname string) (FileStatus, string) {
out, err := gr.RunFromDir("svn", "status", relPath(gr, fname))
if err != nil {
return Untracked, err.Error()
}
ostr := string(out)
if ostr == "" {
return Stored, ""
}
sf := strings.Fields(ostr)
if len(sf) < 2 {
return Stored, ostr
}
stat := sf[0][0]
return gr.CharToStat(stat), ostr
}
// run runs svn with the given arguments in the repository directory,
// returning an error with the output if it fails.
func (gr *SvnRepo) run(args ...string) error {
out, err := gr.RunFromDir("svn", args...)
if err != nil {
return fmt.Errorf("svn %s: %w: %s", args[0], err, strings.TrimSpace(string(out)))
}
return nil
}
// Add adds the file to the repo
func (gr *SvnRepo) Add(fname string) error {
rel := relPath(gr, fname)
if err := gr.run("add", rel); err != nil {
return err
}
gr.Lock()
if gr.files != nil {
gr.files[rel] = Added
}
gr.Unlock()
return nil
}
// Move renames the file or directory at oldpath to newpath with svn mv.
func (gr *SvnRepo) Move(oldpath, newpath string) error {
oldrel, newrel := relPath(gr, oldpath), relPath(gr, newpath)
if err := gr.run("mv", oldrel, newrel); err != nil {
return err
}
gr.Lock()
gr.files.moved(oldrel, newrel)
gr.Unlock()
return nil
}
// Delete removes the file from the repo -- uses "force" option to ensure deletion
func (gr *SvnRepo) Delete(fname string) error {
return gr.run("rm", "--force", relPath(gr, fname))
}
// DeleteRemote removes the file from the repo, but keeps local copy
func (gr *SvnRepo) DeleteRemote(fname string) error {
return gr.run("delete", "--keep-local", relPath(gr, fname))
}
// CommitFile commits single file to repo staging
func (gr *SvnRepo) CommitFile(fname string, message string) error {
return gr.run("commit", relPath(gr, fname), "-m", message)
}
// RevertFile reverts a single file to last commit of master
func (gr *SvnRepo) RevertFile(fname string) error {
return gr.run("revert", relPath(gr, fname))
}
// FileContents returns the contents of given file, as a []byte array
// at given revision specifier (if empty, defaults to current HEAD).
// -1, -2 etc also work as universal ways of specifying prior revisions.
func (gr *SvnRepo) FileContents(fname string, rev string) ([]byte, error) {
if rev == "" { // the working copy, as for git
return os.ReadFile(fname)
}
out, err := gr.RunFromDir("svn", "-r", rev, "cat", relPath(gr, fname))
if err != nil {
log.Println(string(out))
return nil, err
}
return out, nil
}
// Log returns the log history of commits for given filename
// (or all files if empty). If since is non-empty, it is the
// maximum number of entries to return (a number).
func (gr *SvnRepo) Log(fname string, since string) (Log, error) {
// todo: parse -- requires parsing over multiple lines..
args := []string{"log"}
if since != "" {
args = append(args, `--limit=`+since)
}
if fname != "" {
args = append(args, fname)
}
out, err := gr.RunFromDir("svn", args...)
if err != nil {
return nil, err
}
var lg Log
rev := ""
date := ""
author := ""
email := ""
msg := ""
newStart := false
scan := bufio.NewScanner(bytes.NewReader(out))
for scan.Scan() {
ln := scan.Bytes()
if string(ln[:10]) == "----------" {
if rev != "" {
lg.Add(rev, date, author, email, msg)
}
newStart = true
msg = ""
continue
}
if newStart {
flds := bytes.Split(ln, []byte("|"))
if len(flds) < 4 {
continue
}
rev = strings.TrimSpace(string(flds[0]))
author = strings.TrimSpace(string(flds[1]))
date = strings.TrimSpace(string(flds[2]))
msg = ""
newStart = false
} else {
nosp := bytes.TrimSpace(ln)
if msg == "" && len(nosp) == 0 {
continue
}
msg += string(ln) + "\n"
}
}
return lg, nil
}
// CommitDesc returns the full textual description of the given commit,
// if rev is empty, defaults to current HEAD, -1, -2 etc also work as universal
// ways of specifying prior revisions.
// Optionally includes diffs for the changes (otherwise just a list of files
// with modification status).
func (gr *SvnRepo) CommitDesc(rev string, diffs bool) ([]byte, error) {
if rev == "" {
rev = "HEAD"
} else if rev[0] == '-' {
rsp, err := strconv.Atoi(rev)
if err == nil && rsp < 0 {
rev = fmt.Sprintf("HEAD~%d", -rsp)
}
}
var out []byte
var err error
if diffs {
out, err = gr.RunFromDir("svn", "log", "-v", "--diff", "-r", rev)
} else {
out, err = gr.RunFromDir("svn", "log", "-v", "-r", rev)
}
if err != nil {
log.Println(string(out))
return nil, err
}
return out, err
}
func (gr *SvnRepo) FilesChanged(revA, revB string, diffs bool) ([]byte, error) {
return nil, nil // todo:
}
// Blame returns an annotated report about the file, showing which revision last
// modified each line.
func (gr *SvnRepo) Blame(fname string) ([]byte, error) {
out, err := gr.RunFromDir("svn", "blame", fname)
if err != nil {
log.Println(string(out))
return nil, err
}
return out, nil
}
// Copyright (c) 2018, The Cogent Core Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package vcs provides a version control system interface for git and
// Subversion repositories, with file status information and operations,
// using the git and svn commands.
package vcs
//go:generate core generate
import (
"errors"
"path/filepath"
"cogentcore.org/core/base/fsx"
)
type Types int32 //enums:enum -accept-lower
const (
NoVCS Types = iota
Git
Svn
Bzr
Hg
)
// Repo is a version control repository, with support for
// file status information and operations.
type Repo interface {
// LocalPath returns the path of the local repository (working copy).
LocalPath() string
// Remote returns the location of the remote repository (a URL),
// or "" if there is none.
Remote() string
// Update updates the local repository from the remote (pull).
Update() error
// UpdateVersion checks out the given version (revision).
UpdateVersion(version string) error
// Current returns the current branch, or version if not on a branch.
Current() (string, error)
// Branches returns the list of branches.
Branches() ([]string, error)
// Type returns the type of repo we are using
Type() Types
// Files returns a map of the current files and their status,
// using a cached version of the file list if available.
// nil will be returned immediately if no cache is available.
// The given onUpdated function will be called from a separate
// goroutine when the updated list of the files is available
// (an update is always triggered even if the function is nil).
Files(onUpdated func(f Files)) (Files, error)
// StatusFast returns file status based on the cached file info,
// which might be slightly stale. Much faster than Status.
// Returns Stored if no files have been cached yet (shown as normal).
StatusFast(fname string) FileStatus
// Status returns status of given file -- returns Untracked and error
// message on any error. FileStatus is a summary status category,
// and string return value is more detailed status information formatted
// according to standard conventions of given VCS.
Status(fname string) (FileStatus, string)
// Add adds the file to the repo
Add(fname string) error
// Move moves the file using VCS command to keep it updated
Move(oldpath, newpath string) error
// Delete removes the file from the repo and working copy.
// Uses "force" option to ensure deletion.
Delete(fname string) error
// DeleteRemote removes the file from the repo but keeps the local file itself
DeleteRemote(fname string) error
// CommitFile commits a single file
CommitFile(fname string, message string) error
// RevertFile reverts a single file to the version that it was last in VCS,
// losing any local changes (destructive!)
RevertFile(fname string) error
// FileContents returns the contents of given file, as a []byte array
// at given revision specifier, or the current file in the working copy
// if empty (use HEAD for the last commit).
// -1, -2 etc also work as universal ways of specifying prior revisions.
FileContents(fname string, rev string) ([]byte, error)
// Log returns the log history of commits for given filename
// (or all files if empty). If since is non-empty, it should be
// a date-like expression that the VCS will understand, such as
// 1/1/2020, yesterday, last year, etc. SVN only understands a
// number as a maximum number of items to return.
Log(fname string, since string) (Log, error)
// CommitDesc returns the full textual description of the given commit,
// if rev is empty, defaults to current HEAD, -1, -2 etc also work as universal
// ways of specifying prior revisions.
// Optionally includes diffs for the changes (otherwise just a list of files
// with modification status).
CommitDesc(rev string, diffs bool) ([]byte, error)
// FilesChanged returns the list of files changed and their statuses,
// between two revisions.
// If revA is empty, defaults to current HEAD; revB defaults to HEAD-1.
// -1, -2 etc also work as universal ways of specifying prior revisions.
// Optionally includes diffs for the changes.
FilesChanged(revA, revB string, diffs bool) ([]byte, error)
// Blame returns an annotated report about the file, showing which revision last
// modified each line.
Blame(fname string) ([]byte, error)
}
// NewRepo returns a [Repo] for the repository at the given local path,
// of the type found by [DetectRepo]. The remote is the location (URL) of
// the remote repository, or for git, the name of a remote (origin if empty).
func NewRepo(remote, local string) (Repo, error) {
switch DetectRepo(local) {
case Git:
return NewGitRepo(remote, local)
case Svn:
return NewSvnRepo(remote, local)
}
return nil, errors.New("no supported version control repository at: " + local)
}
// DetectRepo attempts to detect the presence of a repository at the given
// directory path -- returns type of repository if found, else NoVCS.
// Very quickly just looks for signature file name:
// .git for git
// .svn for svn -- but note that this will find any subdir in svn rep.o
func DetectRepo(path string) Types {
if fsx.HasFile(path, ".git") {
return Git
}
if fsx.HasFile(path, ".svn") {
return Svn
}
// todo: rest later..
return NoVCS
}
// DetectRepoRoot returns the root directory and type of the repository
// containing the given directory path: the first one with a repository
// found by [DetectRepo], starting from the path itself and going up.
// It returns "", NoVCS if there is none.
func DetectRepoRoot(path string) (string, Types) {
dir, err := filepath.Abs(path)
if err != nil {
return "", NoVCS
}
for {
if typ := DetectRepo(dir); typ != NoVCS {
return dir, typ
}
parent := filepath.Dir(dir)
if parent == dir {
return "", NoVCS
}
dir = parent
}
}
// relPath return the path relative to the repository LocalPath()
func relPath(repo Repo, path string) string {
relpath, _ := filepath.Rel(repo.LocalPath(), path)
return relpath
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"cogentcore.org/core/base/websocket"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
)
func main() {
b := core.NewBody("Websocket Example")
ws, err := websocket.Connect("ws://localhost:8081/ws")
core.ErrorDialog(b, err)
msgs := []string{}
var list *core.List
tf := core.NewTextField(b).SetPlaceholder("Enter message")
send := core.NewButton(b).SetText("Send")
send.OnClick(func(e events.Event) {
msg := tf.Text()
ws.Send(websocket.TextMessage, []byte(msg))
msgs = append(msgs, msg)
list.Update()
})
list = core.NewList(b)
list.SetSlice(&msgs).SetReadOnly(true)
ws.OnMessage(func(typ websocket.MessageTypes, msg []byte) {
list.AsyncLock()
defer list.AsyncUnlock()
msgs = append(msgs, string(msg))
list.Update()
})
b.RunMainWindow()
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"net/http"
"cogentcore.org/core/base/errors"
"github.com/gorilla/websocket"
)
func main() {
upgrader := websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
origin := r.Header.Get("Origin")
return origin == "" || origin == "http://localhost:8080"
},
}
conns := map[*websocket.Conn]struct{}{}
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if errors.Log(err) != nil {
return
}
conns[conn] = struct{}{}
defer func() {
conn.Close()
delete(conns, conn)
}()
for {
_, msg, err := conn.ReadMessage()
if errors.Log(err) != nil {
return
}
fmt.Println(string(msg))
for other := range conns {
if other == conn {
continue
}
other.WriteMessage(websocket.TextMessage, msg)
}
}
})
http.ListenAndServe(":8081", nil)
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !js
package websocket
import (
"cogentcore.org/core/base/errors"
"cogentcore.org/core/system"
"github.com/gorilla/websocket"
)
// Client represents a WebSocket client connection.
// You can use [Connect] to create a new Client.
type Client struct {
// conn is the underlying WebSocket connection.
conn *websocket.Conn
// done is a channel that is closed when the connection is closed.
done chan struct{}
}
// Connect connects to a WebSocket server and returns a [Client].
func Connect(url string) (*Client, error) {
if system.GenerateHTMLArg() {
return &Client{}, nil
}
conn, _, err := websocket.DefaultDialer.Dial(url, nil)
if err != nil {
return nil, err
}
return &Client{conn: conn, done: make(chan struct{})}, nil
}
// OnMessage sets a callback function to be called when a message is received.
// This function can only be called once.
func (c *Client) OnMessage(f func(typ MessageTypes, msg []byte)) {
if system.GenerateHTMLArg() {
return
}
go func() {
for {
typ, msg, err := c.conn.ReadMessage()
if errors.Log(err) != nil {
close(c.done)
return
}
f(MessageTypes(typ), msg)
}
}()
}
// Send sends a message to the WebSocket server with the given type and message.
func (c *Client) Send(typ MessageTypes, msg []byte) error {
if system.GenerateHTMLArg() {
return nil
}
return c.conn.WriteMessage(int(typ), msg)
}
// Close cleanly closes the WebSocket connection.
// It does not directly trigger [Client.OnClose], but once the connection
// is closed, [Client.OnMessage] will trigger it.
func (c *Client) Close() error {
if system.GenerateHTMLArg() {
return nil
}
return c.conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
}
// OnClose sets a callback function to be called when the connection is closed.
// This function can only be called once.
func (c *Client) OnClose(f func()) {
if system.GenerateHTMLArg() {
return
}
go func() {
<-c.done
f()
}()
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// note: parsing code adapted from pflag package https://github.com/spf13/pflag
// Copyright (c) 2012 Alex Ogier. All rights reserved.
// Copyright (c) 2012 The Go Authors. All rights reserved.
package cli
import (
"fmt"
"reflect"
"strconv"
"strings"
"maps"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/base/strcase"
)
// FlagNotFound specifies whether [SetFromArgs] and [ParseFlags] return an error
// for a flag that is not in the configuration struct: [ErrNotFound] or
// [NoErrNotFound].
type FlagNotFound bool
const (
// ErrNotFound can be passed to [SetFromArgs] and [ParseFlags]
// to indicate that they should return an error for a flag that
// is set but not found in the configuration struct.
ErrNotFound FlagNotFound = true
// ErrNotFound can be passed to [SetFromArgs] and [ParseFlags]
// to indicate that they should NOT return an error for a flag that
// is set but not found in the configuration struct.
NoErrNotFound FlagNotFound = false
)
// SetFromArgs sets config values on the given config object from
// the given from command-line args, based on the field names in
// the config struct and the given list of available commands.
// It returns the command, if any, that was passed in the arguments,
// and any error than occurs during the parsing and setting process.
// If errNotFound is set to true, it is assumed that all flags
// (arguments starting with a "-") must refer to fields in the
// config struct, so any that fail to match trigger an error.
// It is recommended that the [ErrNotFound] and [NoErrNotFound]
// constants be used for the value of errNotFound for clearer code.
func SetFromArgs[T any](cfg T, args []string, errNotFound FlagNotFound, cmds ...*Cmd[T]) (string, error) {
bf := boolFlags(cfg)
// if we are not already a meta config object, we have to add
// all of the bool flags of the meta config object so that we
// correctly handle the short (no value) versions of things like
// verbose and quiet.
if _, ok := any(cfg).(*metaConfig); !ok {
mcf := boolFlags(&metaConfigFields{})
maps.Copy(bf, mcf)
}
nfargs, flags, err := getArgs(args, bf)
if err != nil {
return "", err
}
cmd, allFlags, err := parseArgs(cfg, nfargs, flags, cmds...)
if err != nil {
return "", err
}
err = parseFlags(flags, allFlags, errNotFound)
if err != nil {
return "", err
}
return cmd, nil
}
// boolFlags returns a map with a true value for every flag name
// that maps to a boolean field. This is needed so that bool
// flags can be properly set with their shorthand syntax.
func boolFlags(obj any) map[string]bool {
fields := &fields{}
addFields(obj, fields, addAllFields)
res := map[string]bool{}
for _, f := range fields.Values {
if f.Field.Type.Kind() != reflect.Bool { // we only care about bools here
continue
}
// we need all cases of both normal and "no" version for all names
for _, name := range f.Names {
for _, cnms := range allCases(name) {
res[cnms] = true
}
for _, cnms := range allCases("No" + name) {
res[cnms] = true
}
}
}
return res
}
// getArgs processes the given args using the given map of bool flags,
// which should be obtained through [boolFlags]. It returns the leftover
// (positional) args, the flags, and any error.
func getArgs(args []string, boolFlags map[string]bool) ([]string, map[string]string, error) {
var nonFlags []string
flags := map[string]string{}
for len(args) > 0 {
s := args[0]
args = args[1:]
if len(s) == 0 || s[0] != '-' || len(s) == 1 { // if we are not a flag, just add to non-flags
nonFlags = append(nonFlags, s)
continue
}
if s[1] == '-' && len(s) == 2 { // "--" terminates the flags
// f.argsLenAtDash = len(f.args)
nonFlags = append(nonFlags, args...)
break
}
name, value, nargs, err := getFlag(s, args, boolFlags)
if err != nil {
return nonFlags, flags, err
}
// we need to updated remaining args with latest
args = nargs
if name != "" { // we ignore no-names so that we can skip things like test args
flags[name] = value
}
}
return nonFlags, flags, nil
}
// getFlag parses the given flag arg string in the context of the given
// remaining arguments and bool flags. It returns the name of the flag,
// the value of the flag, the remaining arguments updated with any changes
// caused by getting this flag, and any error.
func getFlag(s string, args []string, boolFlags map[string]bool) (name, value string, a []string, err error) {
// we start out with the remaining args we were passed
a = args
// we know the first character is a dash, so we can trim it directly
name = s[1:]
// then we trim double dash if there is one
name = strings.TrimPrefix(name, "-")
// we can't start with a dash or equal, as those are reserved characters
if len(name) == 0 || name[0] == '-' || name[0] == '=' {
err = fmt.Errorf("bad flag syntax: %q", s)
return
}
// go test passes args, so we ignore them
if strings.HasPrefix(name, "test.") {
name = ""
return
}
// split on equal (we could be in the form flag=value)
split := strings.SplitN(name, "=", 2)
name = split[0]
if len(split) == 2 {
// if we are in the form flag=value, we are done
value = split[1]
} else if len(a) > 0 && !boolFlags[name] { // otherwise, if we still have more remaining args and are not a bool, our value could be the next arg (if we are a bool, we don't care about the next value)
value = a[0]
// if the next arg starts with a dash, it can't be our value, so we are just a bool arg and we exit with an empty value
if strings.HasPrefix(value, "-") {
value = ""
return
}
// if it doesn't start with a dash, it is our value, so we remove it from the remaining args (we have already set value to it above)
a = a[1:]
return
}
return
}
// parseArgs parses the given non-flag arguments in the context of the given
// configuration struct, flags, and commands. The non-flag arguments and flags
// should be gotten through [getArgs] first. It returns the command specified by
// the arguments, an ordered map of all of the flag names and their associated
// field objects, and any error.
func parseArgs[T any](cfg T, args []string, flags map[string]string, cmds ...*Cmd[T]) (cmd string, allFlags *fields, err error) {
newArgs, newCmd, err := parseArgsImpl(cfg, args, "", cmds...)
if err != nil {
return newCmd, allFlags, err
}
// if the command is blank, then it is the root command
if newCmd == "" {
for _, c := range cmds {
if c.Root && c.Name != "help" {
newCmd = c.Name
break
}
}
}
allFields := &fields{}
addMetaConfigFields(allFields)
addFields(cfg, allFields, newCmd)
allFlags = &fields{}
newArgs, err = addFlags(allFields, allFlags, newArgs, flags)
if err != nil {
return newCmd, allFields, err
}
if len(newArgs) > 0 {
return newCmd, allFields, fmt.Errorf("got unused arguments: %v", newArgs)
}
return newCmd, allFlags, nil
}
// parseArgsImpl is the underlying implementation of [parseArgs] that is called
// recursively and takes most of what [parseArgs] does, plus the current command state,
// and returns most of what [parseArgs] does, plus the args state.
func parseArgsImpl[T any](cfg T, baseArgs []string, baseCmd string, cmds ...*Cmd[T]) (args []string, cmd string, err error) {
// we start with our base args and command
args = baseArgs
cmd = baseCmd
// if we have no additional args, we have nothing to do
if len(args) == 0 {
return
}
// we only care about one arg at a time (everything else is handled recursively)
arg := args[0]
// get all of the (sub)commands in our base command
baseCmdStrs := strings.Fields(baseCmd)
for _, c := range cmds {
// get all of the (sub)commands in this command
cmdStrs := strings.Fields(c.Name)
// find the (sub)commands that our base command shares with the command we are checking
gotTo := 0
hasMismatch := false
for i, cstr := range cmdStrs {
// if we have no more (sub)commands on our base, mark our location and break
if i >= len(baseCmdStrs) {
gotTo = i
break
}
// if we have a different thing than our base, it is a mismatch
if baseCmdStrs[i] != cstr {
hasMismatch = true
break
}
}
// if we have a different sub(command) for something, this isn't the right command
if hasMismatch {
continue
}
// if the thing after we ran out of (sub)commands on our base isn't our next arg, this isn't the right command
if gotTo >= len(cmdStrs) || arg != cmdStrs[gotTo] {
continue
}
// otherwise, it is the right command, and our new command is our base plus our next arg
cmd = arg
if baseCmd != "" {
cmd = baseCmd + " " + arg
}
// we have consumed our next arg, so we get rid of it
args = args[1:]
// then, we recursively parse again with our new command as context
oargs, ocmd, err := parseArgsImpl(cfg, args, cmd, cmds...)
if err != nil {
return nil, "", err
}
// our new args and command are now whatever the recursive call returned, building upon what we passed it
args = oargs
cmd = ocmd
// we got the command we wanted, so we can break
break
}
return
}
// parseFlags parses the given flags using the given ordered map of all of the
// available flags, setting the values from that map accordingly.
// Setting errNotFound to true causes flags that are not in allFlags to
// trigger an error; otherwise, it just skips those. It is recommended
// that the [ErrNotFound] and [NoErrNotFound] constants be used for the
// value of errNotFound for clearer code. Also, the flags should be
// gotten through [getArgs] first, and the map of available flags should
// be gotten through [parseArgs] first.
func parseFlags(flags map[string]string, allFlags *fields, errNotFound FlagNotFound) error {
for name, value := range flags {
err := parseFlag(name, value, allFlags, errNotFound)
if err != nil {
return err
}
}
return nil
}
// parseFlag parses the flag with the given name and the given value
// using the given map of all of the available flags, setting the value
// in that map corresponding to the flag name accordingly. Setting
// errNotFound = true causes passing a flag name that is not in allFlags
// to trigger an error; otherwise, it just does nothing and returns no error.
// It is recommended that the [ErrNotFound] and [NoErrNotFound]
// constants be used for the value of errNotFound for clearer code.
func parseFlag(name string, value string, allFlags *fields, errNotFound FlagNotFound) error {
f, exists := allFlags.AtTry(name)
if !exists {
if errNotFound {
return fmt.Errorf("flag name %q not recognized", name)
}
return nil
}
isBool := reflectx.NonPointerValue(f.Value).Kind() == reflect.Bool
if isBool {
// check if we have a "no" prefix and set negate based on that
lcnm := strings.ToLower(name)
negate := false
if len(lcnm) > 3 {
if lcnm[:3] == "no_" || lcnm[:3] == "no-" {
negate = true
} else if lcnm[:2] == "no" {
if _, has := allFlags.AtTry(lcnm[2:]); has { // e.g., nogui and gui is on list
negate = true
}
}
}
// the value could be explicitly set to a bool value,
// so we check that; if it is not set, it is true
b := true
if value != "" {
var err error
b, err = strconv.ParseBool(value)
if err != nil {
return fmt.Errorf("error parsing bool flag %q: %w", name, err)
}
}
// if we are negating and true (ex: -no-something), or not negating
// and false (ex: -something=false), we are false
if negate && b || !negate && !b {
value = "false"
} else { // otherwise, we are true
value = "true"
}
}
if value == "" {
// got '--flag' but arg was required
return fmt.Errorf("flag %q needs an argument", name)
}
return setFieldValue(f, value)
}
// setFieldValue sets the value of the given configuration field
// to the given string argument value.
func setFieldValue(f *field, value string) error {
nptyp := reflectx.NonPointerType(f.Value.Type())
vk := nptyp.Kind()
switch vk {
// TODO: more robust parsing of maps and slices
case reflect.Map:
strs := strings.Split(value, ",")
mval := map[string]string{}
for _, str := range strs {
k, v, found := strings.Cut(str, "=")
if !found {
return fmt.Errorf("missing key-value pair for setting map flag %q from flag value %q (element %q has no %q)", f.Names[0], value, str, "=")
}
mval[k] = v
}
err := reflectx.CopyMapRobust(f.Value.Interface(), mval)
if err != nil {
return fmt.Errorf("unable to set map flag %q from flag value %q: %w", f.Names[0], value, err)
}
case reflect.Slice:
err := reflectx.CopySliceRobust(f.Value.Interface(), strings.Split(value, ","))
if err != nil {
return fmt.Errorf("unable to set slice flag %q from flag value %q: %w", f.Names[0], value, err)
}
default:
// initialize nil fields to prevent panics
// (don't do for maps and slices, as new doesn't work for them)
if f.Value.IsNil() {
f.Value.Set(reflect.New(nptyp))
}
err := reflectx.SetRobust(f.Value.Interface(), value) // overkill but whatever
if err != nil {
return fmt.Errorf("error setting set flag %q from flag value %q: %w", f.Names[0], value, err)
}
}
return nil
}
// addAllCases adds all string cases (kebab-case, snake_case, etc)
// of the given field with the given name to the given set of flags.
func addAllCases(nm string, field *field, allFlags *fields) {
if nm == "Includes" {
return // skip Includes
}
for _, nm := range allCases(nm) {
allFlags.Set(nm, field)
}
}
// allCases returns all of the string cases (kebab-case,
// snake_case, etc) of the given name.
func allCases(nm string) []string {
return []string{nm, strings.ToLower(nm), strcase.ToKebab(nm), strcase.ToSnake(nm), strcase.ToSNAKE(nm)}
}
// addFlags adds to given the given ordered flags map all of the different ways
// all of the given fields can can be specified as flags. It also uses the given
// positional arguments to set the values of the object based on any posarg struct
// tags that fields have. The posarg struct tag must either be "all", "leftover",
// or a valid uint. Finally, it also uses the given map of flags passed to the
// command as context.
func addFlags(allFields *fields, allFlags *fields, args []string, flags map[string]string) ([]string, error) {
consumed := map[int]bool{} // which args we have consumed via pos args
var leftoverField *field
for _, v := range allFields.Values {
f := v.Field
for _, name := range v.Names {
addAllCases(name, v, allFlags)
if f.Type.Kind() == reflect.Bool {
addAllCases("No"+name, v, allFlags)
}
}
// set based on pos arg
posArgTag, ok := f.Tag.Lookup("posarg")
if ok {
switch posArgTag {
case "all":
err := reflectx.SetRobust(v.Value.Interface(), args)
if err != nil {
return nil, fmt.Errorf("error setting field %q to all positional arguments: %v: %w", f.Name, args, err)
}
// everybody has been consumed
for i := range args {
consumed[i] = true
}
case "leftover":
leftoverField = v // must be handled later once we have all of the leftovers
default:
ui, err := strconv.ParseUint(posArgTag, 10, 64)
if err != nil {
return nil, fmt.Errorf("programmer error: invalid value %q for posarg struct tag on field %q: %w", posArgTag, f.Name, err)
}
// if this is true, the pos arg is missing
if ui >= uint64(len(args)) {
// if it isn't required, it doesn't matter if it's missing
req, has := f.Tag.Lookup("required")
if req != "+" && req != "true" && has { // default is required, so !has => required
continue
}
// check if we have set this pos arg as a flag; if we have,
// it makes up for the missing pos arg and there is no error,
// but otherwise there is an error
got := false
for _, fnm := range v.Names { // TODO: is there a more efficient way to do this?
for _, cnm := range allCases(fnm) {
_, ok := flags[cnm]
if ok {
got = true
break
}
}
if got {
break
}
}
if got {
continue // if we got the pos arg through the flag, we skip the rest of the pos arg stuff and go onto the next field
}
return nil, fmt.Errorf("missing positional argument %d (%s)", ui, strcase.ToKebab(v.Names[0]))
}
err = setFieldValue(v, args[ui]) // must be pointer to be settable
if err != nil {
return nil, fmt.Errorf("error setting field %q to positional argument %d (%q): %w", f.Name, ui, args[ui], err)
}
consumed[int(ui)] = true // we have consumed this argument
}
}
}
// get leftovers based on who was consumed
leftovers := []string{}
for i, a := range args {
if !consumed[i] {
leftovers = append(leftovers, a)
}
}
if leftoverField != nil {
err := reflectx.SetRobust(leftoverField.Value.Interface(), leftovers)
if err != nil {
return nil, fmt.Errorf("error setting field %q to all leftover arguments: %v: %w", leftoverField.Name, leftovers, err)
}
return nil, nil // no more leftovers
}
return leftovers, nil
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package cli generates powerful CLIs from Go struct types and functions.
// See package clicore to create a GUI representation of a CLI.
package cli
//go:generate core generate
import (
"fmt"
"log/slog"
"os"
"path/filepath"
"strings"
"cogentcore.org/core/base/logx"
)
// Run runs an app with the given options, configuration struct,
// and commands. It does not run the GUI; see [cogentcore.org/core/cli/clicore.Run]
// for that. The configuration struct should be passed as a pointer, and
// configuration options should be defined as fields on the configuration
// struct. The commands can be specified as either functions or struct
// objects; the functions are more concise but require using [types].
// In addition to the given commands, Run adds a "help" command that
// prints the result of [usage], which will also be the root command if
// no other root command is specified. Also, it adds the fields in
// [metaConfig] as configuration options. If [Options.Fatal] is set to
// true, the error result of Run does not need to be handled. Run uses
// [os.Args] for its arguments.
func Run[T any, C CmdOrFunc[T]](opts *Options, cfg T, cmds ...C) error {
cs, err := CmdsFromCmdOrFuncs[T](cmds)
if err != nil {
err := fmt.Errorf("internal/programmer error: error getting commands from given commands: %w", err)
if opts.Fatal {
logx.PrintError(err)
os.Exit(1)
}
return err
}
if len(cmds) == 1 { // one command is always the root
cs[0].Root = true
}
cmd, err := config(opts, cfg, cs...)
if err != nil {
if opts.Fatal {
logx.PrintlnError("error: ", err)
os.Exit(1)
}
return err
}
err = runCmd(opts, cfg, cmd, cs...)
if err != nil {
if opts.Fatal {
fmt.Println(logx.CmdColor(cmdString(cmd)) + logx.ErrorColor(" failed: "+err.Error()))
os.Exit(1)
}
return fmt.Errorf("%s failed: %w", cmdName()+" "+cmd, err)
}
// if the user sets level to error (via -q), we don't show the success message
if opts.PrintSuccess && logx.UserLevel <= slog.LevelWarn {
fmt.Println(logx.CmdColor(cmdString(cmd)) + logx.SuccessColor(" succeeded"))
}
return nil
}
// runCmd runs the command with the given name using the given options,
// configuration information, and available commands. If the given
// command name is "", it runs the root command.
func runCmd[T any](opts *Options, cfg T, cmd string, cmds ...*Cmd[T]) error {
for _, c := range cmds {
if c.Name == cmd || c.Root && cmd == "" {
err := c.Func(cfg)
if err != nil {
return err
}
return nil
}
}
if cmd == "" { // if we couldn't find the command and we are looking for the root command, we fall back on help
fmt.Println(usage(opts, cfg, cmd, cmds...))
os.Exit(0)
}
return fmt.Errorf("command %q not found", cmd)
}
// cmdName returns the name of the command currently being run.
func cmdName() string {
base := filepath.Base(os.Args[0])
return strings.TrimSuffix(base, filepath.Ext(base))
}
// cmdString is a simple helper function that returns a string
// with [cmdName] and the given command name string combined
// to form a string representing the complete command being run.
func cmdString(cmd string) string {
if cmd == "" {
return cmdName()
}
return cmdName() + " " + cmd
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package clicore extends package cli by generating Cogent Core GUIs.
package clicore
import (
"fmt"
"os"
"cogentcore.org/core/base/logx"
"cogentcore.org/core/base/strcase"
"cogentcore.org/core/cli"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/tree"
)
// Run runs the given app with the given default
// configuration file paths. It is similar to
// [cli.Run], but it also runs the GUI if no
// arguments were provided. The app should be
// a pointer, and configuration options should
// be defined as fields on the app type. Also,
// commands should be defined as methods on the
// app type with the suffix "Cmd"; for example,
// for a command named "build", there should be
// the method:
//
// func (a *App) BuildCmd() error
//
// Run uses [os.Args] for its arguments.
func Run[T any, C cli.CmdOrFunc[T]](opts *cli.Options, cfg T, cmds ...C) error {
cs, err := cli.CmdsFromCmdOrFuncs[T](cmds)
if err != nil {
err := fmt.Errorf("error getting commands from given commands: %w", err)
if opts.Fatal {
logx.PrintlnError(err)
os.Exit(1)
}
return err
}
cs = cli.AddCmd(cs, &cli.Cmd[T]{
Func: func(t T) error {
gui(opts, t, cs...)
return nil
},
Name: "gui",
Doc: "gui runs the GUI version of the " + opts.AppName + " tool",
Root: true, // if root isn't already taken, we take it
})
return cli.Run(opts, cfg, cs...)
}
// gui starts the gui for the given cli app, which must be passed as
// a pointer.
func gui[T any](opts *cli.Options, cfg T, cmds ...*cli.Cmd[T]) {
b := core.NewBody(opts.AppName)
b.AddTopBar(func(bar *core.Frame) {
core.NewToolbar(bar).Maker(func(p *tree.Plan) {
for _, cmd := range cmds {
if cmd.Name == "gui" { // we are already in GUI so that command is irrelevant
continue
}
tree.AddAt(p, cmd.Name, func(w *core.Button) {
w.SetText(strcase.ToSentence(cmd.Name)).SetTooltip(cmd.Doc).
OnClick(func(e events.Event) {
err := cmd.Func(cfg)
if err != nil {
// TODO: snackbar
logx.PrintlnError(err)
}
})
})
}
})
})
sv := core.NewForm(b)
sv.SetStruct(cfg)
b.RunMainWindow()
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"cogentcore.org/core/cli"
"cogentcore.org/core/cli/clicore"
)
//go:generate core generate -add-types -add-methods
type Config struct {
// the name of the user
Name string
// the age of the user
Age int
// whether the user likes Go
LikesGo bool
// the target platform to build for
BuildTarget string
}
// Build builds the app for the config build target.
func Build(c *Config) error {
fmt.Println("Building for platform", c.BuildTarget)
return nil
}
// Run runs the app for the user with the config name.
func Run(c *Config) error {
fmt.Println("Running for user", c.Name)
return nil
}
func main() { //types:skip
opts := cli.DefaultOptions("Basic", "Basic is a basic example application made with clicore.")
clicore.Run(opts, &Config{}, Build, Run)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cli
import (
"fmt"
"strings"
"cogentcore.org/core/base/strcase"
"cogentcore.org/core/types"
)
// Cmd represents a runnable command with configuration options.
// The type constraint is the type of the configuration
// information passed to the command.
type Cmd[T any] struct {
// Func is the actual function that runs the command.
// It takes configuration information and returns an error.
Func func(T) error
// Name is the name of the command.
Name string
// Doc is the documentation for the command.
Doc string
// Root is whether the command is the root command
// (what is called when no subcommands are passed)
Root bool
// Icon is the icon of the command in the tool bar
// when running in the GUI via clicore
Icon string
// SepBefore is whether to add a separator before the
// command in the tool bar when running in the GUI via clicore
SepBefore bool
// SepAfter is whether to add a separator after the
// command in the tool bar when running in the GUI via clicore
SepAfter bool
}
// CmdOrFunc is a generic type constraint that represents either
// a [*Cmd] with the given config type or a command function that
// takes the given config type and returns an error.
type CmdOrFunc[T any] interface {
*Cmd[T] | func(T) error
}
// cmdFromFunc returns a new [Cmd] object from the given function
// and any information specified on it using comment directives,
// which requires the use of [types].
func cmdFromFunc[T any](fun func(T) error) (*Cmd[T], error) {
cmd := &Cmd[T]{
Func: fun,
}
fn := types.FuncName(fun)
// we need to get rid of package name and then convert to kebab
strs := strings.Split(fn, ".")
cfn := strs[len(strs)-1] // camel function name
cmd.Name = strcase.ToKebab(cfn)
if f := types.FuncByName(fn); f != nil {
cmd.Doc = f.Doc
for _, dir := range f.Directives {
if dir.Tool != "cli" {
continue
}
if dir.Directive != "cmd" {
return cmd, fmt.Errorf("unrecognized comment directive %q (from comment %q)", dir.Directive, dir.String())
}
_, err := SetFromArgs(cmd, dir.Args, ErrNotFound)
if err != nil {
return cmd, fmt.Errorf("error setting command from directive arguments (from comment %q): %w", dir.String(), err)
}
}
// we format the doc after the directives so that we have the up-to-date documentation and name
cmd.Doc = types.FormatDoc(cmd.Doc, cfn, strcase.ToSentence(cmd.Name))
}
return cmd, nil
}
// cmdFromCmdOrFunc returns a new [Cmd] object from the given
// [CmdOrFunc] object, using [cmdFromFunc] if it is a function.
func cmdFromCmdOrFunc[T any, C CmdOrFunc[T]](cmd C) (*Cmd[T], error) {
switch c := any(cmd).(type) {
case *Cmd[T]:
return c, nil
case func(T) error:
return cmdFromFunc(c)
default:
panic(fmt.Errorf("internal/programmer error: cli.CmdFromCmdOrFunc: impossible type %T for command %v", cmd, cmd))
}
}
// CmdsFromCmdOrFuncs is a helper function that returns a slice
// of command objects from the given slice of [CmdOrFunc] objects,
// using [cmdFromCmdOrFunc].
func CmdsFromCmdOrFuncs[T any, C CmdOrFunc[T]](cmds []C) ([]*Cmd[T], error) {
res := make([]*Cmd[T], len(cmds))
for i, cmd := range cmds {
cmd, err := cmdFromCmdOrFunc[T](cmd)
if err != nil {
return nil, err
}
res[i] = cmd
}
return res, nil
}
// AddCmd adds the given command to the given set of commands
// if there is not already a command with the same name in the
// set of commands. Also, if [Cmd.Root] is set to true on the
// passed command, and there are no other root commands in the
// given set of commands, the passed command will be made the
// root command; otherwise, it will be made not the root command.
func AddCmd[T any](cmds []*Cmd[T], cmd *Cmd[T]) []*Cmd[T] {
hasCmd := false
hasRoot := false
for _, c := range cmds {
if c.Name == cmd.Name {
hasCmd = true
}
if c.Root {
hasRoot = true
}
}
if hasCmd {
return cmds
}
cmd.Root = cmd.Root && !hasRoot // we must both want root and be able to take root
cmds = append(cmds, cmd)
return cmds
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package commands
import (
"sync"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/sharedfile"
)
// Args are the arguments last used for the subcommands of the commands,
// by command, in a structure parallel to that of the [Cmd] and [SubCmd],
// which are saved in a JSON file (see [OpenArgs]). They are set from the
// form of a subcommand when its command line is run, and set in the form
// when it is shown again.
type Args struct {
// Cmds are the arguments of the commands, by command: "git".
Cmds map[string]*CmdArgs
// Scripts are the values of the arguments of the scripts, by the key
// of the script (see [scriptKey]), and by the name of the argument:
// "true" for a switch that is on.
Scripts map[string]map[string]string
// Macros are the values of the arguments of the macros that are
// prompted for, by the key of the macro (see [macroKey]).
Macros map[string]*SubCmdArgs
// file is the file the arguments are saved in, which other processes
// (apps) share.
file sharedfile.File[argsData]
// mu protects the arguments and the saving of the file.
mu sync.Mutex
}
// CmdArgs are the arguments last used for the subcommands of a [Cmd].
type CmdArgs struct {
// SubCmds are the arguments of the subcommands, by the name of the
// subcommand: "commit", or [MainName].
SubCmds map[string]*SubCmdArgs
}
// SubCmdArgs are the arguments last used for a [SubCmd]: only those that
// were used.
type SubCmdArgs struct {
// Args are the other arguments, such as files, as typed in a shell.
Args string `json:",omitempty"`
// Flags are the values of the flags that were used, by the name of the
// flag ("--message"): "true" for a flag without a value.
Flags map[string]string `json:",omitempty"`
}
// OpenArgs returns the arguments saved in the given JSON file, which are
// empty if it does not exist yet, and are saved in it when they change.
// The file may be shared by other processes (apps): it is read again when
// another process changes it.
func OpenArgs(filename string) *Args {
as := &Args{file: sharedfile.File[argsData]{Path: filename}, Cmds: map[string]*CmdArgs{}}
as.mu.Lock()
as.syncLocked()
as.mu.Unlock()
return as
}
// argsData are the data of the file of the [Args].
type argsData struct {
Cmds map[string]*CmdArgs
Scripts map[string]map[string]string `json:",omitempty"`
Macros map[string]*SubCmdArgs `json:",omitempty"`
}
// syncLocked reads the file of the arguments if another process has
// changed it, under the mutex.
func (as *Args) syncLocked() {
if !as.file.Changed() {
return
}
errors.Log(as.file.Reload())
if as.file.Data.Cmds != nil {
as.Cmds = as.file.Data.Cmds
}
as.Scripts = as.file.Data.Scripts
as.Macros = as.file.Data.Macros
}
// updateLocked changes the arguments with the given function, and saves
// them, with the file locked, after reading the changes of other
// processes, under the mutex.
func (as *Args) updateLocked(change func()) error {
return as.file.Update(func(d *argsData) {
if d.Cmds != nil {
as.Cmds = d.Cmds
}
as.Scripts, as.Macros = d.Scripts, d.Macros
change()
d.Cmds, d.Scripts, d.Macros = as.Cmds, as.Scripts, as.Macros
})
}
// get returns the arguments last used for the given subcommand, or nil.
func (as *Args) get(sc *SubCmd) *SubCmdArgs {
root, _ := splitCmd(sc.Cmd)
as.mu.Lock()
defer as.mu.Unlock()
as.syncLocked()
if ca := as.Cmds[root]; ca != nil {
return ca.SubCmds[sc.Name]
}
return nil
}
// Set sets the arguments last used for the given subcommand from the given
// values of its form (see [SubCmd.FormStruct]), and saves them.
func (as *Args) Set(sc *SubCmd, values any) error {
sa := sc.ArgsOf(values)
root, _ := splitCmd(sc.Cmd)
as.mu.Lock()
defer as.mu.Unlock()
return as.updateLocked(func() {
ca := as.Cmds[root]
if ca == nil {
ca = &CmdArgs{}
as.Cmds[root] = ca
}
if ca.SubCmds == nil {
ca.SubCmds = map[string]*SubCmdArgs{}
}
ca.SubCmds[sc.Name] = sa
})
}
// SetValues sets the given values of the form of the given subcommand
// (see [SubCmd.FormStruct]) to the arguments last used for it, if any.
func (as *Args) SetValues(sc *SubCmd, values any) {
as.get(sc).SetValues(sc, values)
}
// scriptKey returns the key of the given script of the given command (""
// for one of an entry) in the [Args.Scripts].
func scriptKey(root string, s *Script) string {
return root + "/" + s.Name
}
// ScriptValues returns the values of the arguments last used for the given
// script of the given command ("" for one of an entry), by name, which are
// their defaults for those not used yet.
func (as *Args) ScriptValues(root string, s *Script) map[string]string {
values := map[string]string{}
var last map[string]string
if as != nil {
as.mu.Lock()
as.syncLocked()
last = as.Scripts[scriptKey(root, s)]
as.mu.Unlock()
}
for _, a := range s.Args {
v, ok := last[a.Name]
if !ok {
v = a.Default
}
values[a.Name] = v
}
return values
}
// SetScriptValues sets the values of the arguments last used for the given
// script of the given command ("" for one of an entry) to the given ones,
// by name, and saves them.
func (as *Args) SetScriptValues(root string, s *Script, values map[string]string) error {
if as == nil {
return nil
}
as.mu.Lock()
defer as.mu.Unlock()
return as.updateLocked(func() {
if as.Scripts == nil {
as.Scripts = map[string]map[string]string{}
}
as.Scripts[scriptKey(root, s)] = values
})
}
// macroKey returns the key of the given macro of the given command in the
// [Args.Macros]: "git/commit/wip".
func macroKey(root string, mc *Macro) string {
return root + "/" + mc.SubCmd + "/" + mc.Name
}
// MacroValues returns the values last used for the arguments of the given
// macro of the given command that are prompted for, or nil if there are
// none.
func (as *Args) MacroValues(root string, mc *Macro) *SubCmdArgs {
if as == nil {
return nil
}
as.mu.Lock()
defer as.mu.Unlock()
as.syncLocked()
return as.Macros[macroKey(root, mc)]
}
// SetMacroValues sets the values last used for the arguments of the given
// macro of the given command that are prompted for, of the given keys, to
// those of the given ones, and saves them. Those without a value, such as
// a switch that is off, are saved as empty, so that they are not those of
// the macro when it is prompted for again.
func (as *Args) SetMacroValues(root string, mc *Macro, sa *SubCmdArgs, keys map[string]bool) error {
if as == nil {
return nil
}
vals := &SubCmdArgs{Flags: map[string]string{}}
for k := range keys {
if k == argsField {
vals.Args = sa.Args
} else {
vals.Flags[k] = sa.Flags[k]
}
}
as.mu.Lock()
defer as.mu.Unlock()
return as.updateLocked(func() {
if as.Macros == nil {
as.Macros = map[string]*SubCmdArgs{}
}
as.Macros[macroKey(root, mc)] = vals
})
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package commands
import (
"context"
"html"
"image"
"os"
"os/exec"
"reflect"
"runtime"
"slices"
"strings"
"time"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/tree"
)
// Chooser is a type of the values of arguments, such as a git branch,
// whose values are chosen from the lines of the output of a shell command,
// such as git branch --format='%(refname:short)', run in the directory
// that the commands run in (see [Commands.Dir]) when they are chosen. The
// arguments of the subcommands of a command, and of scripts, can have a
// chooser (see [Cmd.Choosers] and [ScriptArg.Chooser]): their text fields
// have a button with a menu of its values, which can still be typed.
type Chooser struct {
// Name is the name of the chooser, such as "Git branch".
Name string
// Command is the shell command whose lines of output are the values,
// other than empty ones, without spaces around them. It can have
// pipes, as in git status --short | cut -c4-.
Command string `width:"50"`
// Empty is what an empty value means, if anything, which is shown in
// an empty field, such as "the current directory (.)".
Empty string `json:",omitempty" width:"30"`
// Doc is the documentation of the chooser.
Doc string `json:",omitempty" width:"40"`
}
// ChooserTimeout is the longest time that the command of a [Chooser] can
// take to output its values.
var ChooserTimeout = 5 * time.Second
// Values returns the values of the chooser: the lines of the output of its
// command, run in the given directory, other than empty ones, without
// spaces around them, and without duplicates.
func (ch *Chooser) Values(dir string) ([]string, error) {
ctx, cancel := context.WithTimeout(context.Background(), ChooserTimeout)
defer cancel()
var cmd *exec.Cmd
if runtime.GOOS == "windows" {
cmd = exec.CommandContext(ctx, "cmd", "/C", ch.Command)
} else {
cmd = exec.CommandContext(ctx, "/bin/sh", "-c", ch.Command)
}
cmd.Dir = dir
out, err := cmd.Output()
var vals []string
for line := range strings.Lines(string(out)) {
line = strings.TrimSpace(line)
if line != "" && !slices.Contains(vals, line) {
vals = append(vals, line)
}
}
if err != nil && len(vals) == 0 {
if ee, ok := err.(*exec.ExitError); ok && len(ee.Stderr) > 0 {
return nil, errors.New(strings.TrimSpace(string(ee.Stderr)))
}
return nil, err
}
return vals, nil
}
// ChooserName is the name of a [Chooser] of the [Commands], or empty for
// none, which is chosen from their names in a form.
type ChooserName string
// Widget returns a chooser of the names of the choosers of the [Default]
// commands, which can also be typed, as for a new one.
func (cn *ChooserName) Widget() core.Value {
ch := core.NewChooser().SetEditable(true)
ch.Maker(func(p *tree.Plan) {}) // (keeps the chooser itself)
items := []core.ChooserItem{{Value: ChooserName(""), Text: "None", Tooltip: "Text, typed"}}
for _, c := range Default().choosers() {
items = append(items, core.ChooserItem{Value: ChooserName(c.Name), Text: c.Name, Tooltip: html.EscapeString(cmpOr(c.Doc, c.Command))})
}
return ch.SetItems(items...)
}
// StandardChoosers are the choosers of the standard commands, which the
// user starts with (see [StandardChooserArgs]).
func StandardChoosers() []*Chooser {
return []*Chooser{
{Name: "Git branch", Command: "git branch --format='%(refname:short)'", Doc: "The local branches of the git repository"},
{Name: "Git remote branch", Command: "git branch --remotes --format='%(refname:short)'", Doc: "The branches of the remotes of the git repository, such as origin/main"},
{Name: "Git remote", Command: "git remote", Empty: "the remote of the current branch", Doc: "The remotes of the git repository, such as origin"},
{Name: "Git tag", Command: "git tag --sort=-creatordate", Doc: "The tags of the git repository, newest first"},
{Name: "Git changed file", Command: "git ls-files --modified --others --exclude-standard", Doc: "The files of the git repository that are changed or new (not ignored)"},
{Name: "Go package", Command: goPackages, Empty: "the package in the current directory (.)", Doc: "The Go packages in the current directory (.), all of them (./...), and each one below it"},
}
}
// goPackages is the command of the standard Go package chooser: the
// current directory, all of the packages below it, and the directory of
// each one, relative to it.
const goPackages = `echo .; echo ./...; go list -f '{{.Dir}}' ./... | sed -e "s|^$(pwd -P)/|./|" -e "s|^$PWD/|./|" -e "s|^$(pwd -P)\$|.|" -e "s|^$PWD\$|.|"`
// oldStandardChoosers are the commands of earlier versions of the
// [StandardChoosers], by name, which are updated to the current ones.
var oldStandardChoosers = map[string][]string{
"Go package": {"go list ./..."},
}
// StandardChooserArgs are the choosers of the arguments of the subcommands
// of the standard commands, by command, and by the key of the argument
// (see [Cmd.Choosers]).
func StandardChooserArgs() map[string]map[string]string {
return map[string]map[string]string{
"git": {
"checkout " + argsField: "Git branch",
"switch " + argsField: "Git branch",
"merge " + argsField: "Git branch",
"rebase " + argsField: "Git branch",
"branch " + argsField: "Git branch",
"branch --set-upstream-to": "Git remote branch",
"add " + argsField: "Git changed file",
"restore " + argsField: "Git changed file",
"push " + argsField: "Git remote",
"pull " + argsField: "Git remote",
"fetch " + argsField: "Git remote",
"cherry-pick " + argsField: "Git branch",
"log " + argsField: "Git branch",
"diff " + argsField: "Git changed file",
"tag --delete": "Git tag",
"show " + argsField: "Git tag",
"worktree add " + argsField: "Git branch",
},
"go": {
"build " + argsField: "Go package",
"test " + argsField: "Go package",
"install " + argsField: "Go package",
"vet " + argsField: "Go package",
},
}
}
// choosers returns the choosers of the commands.
func (cs *Commands) choosers() []*Chooser {
cs.reload()
cs.mu.Lock()
defer cs.mu.Unlock()
return slices.Clone(cs.Choosers)
}
// Chooser returns the chooser of the given name, or nil if there is none.
func (cs *Commands) Chooser(name string) *Chooser {
if name == "" {
return nil
}
for _, c := range cs.choosers() {
if c.Name == name {
return c
}
}
return nil
}
// chooserKey returns the key of the argument of the given key (see
// [SubCmd.argKey]) of the given subcommand in [Cmd.Choosers]: "checkout
// Arguments", "branch --set-upstream-to".
func chooserKey(sc *SubCmd, argKey string) string {
return sc.Name + " " + argKey
}
// ArgChooser returns the name of the chooser of the argument of the given
// key (see [SubCmd.argKey]) of the given subcommand, or "" if it has none.
func (cs *Commands) ArgChooser(sc *SubCmd, argKey string) string {
root, _ := splitCmd(sc.Cmd)
cs.mu.Lock()
defer cs.mu.Unlock()
if cm := cs.Parsed[root]; cm != nil {
return cm.Choosers[chooserKey(sc, argKey)]
}
return ""
}
// SetArgChooser sets the chooser of the argument of the given key (see
// [SubCmd.argKey]) of the given subcommand to that of the given name, or
// to none if it is "", and saves it.
func (cs *Commands) SetArgChooser(sc *SubCmd, argKey, name string) error {
root, _ := splitCmd(sc.Cmd)
return cs.update(func() {
cm := cs.Parsed[root]
if cm == nil {
cm = &Cmd{Cmd: root}
cs.Parsed[root] = cm
}
if cm.Choosers == nil {
cm.Choosers = map[string]string{}
}
if name == "" {
delete(cm.Choosers, chooserKey(sc, argKey))
} else {
cm.Choosers[chooserKey(sc, argKey)] = name
}
})
}
// addStandardChoosersLocked adds the [StandardChoosers] that the commands
// do not have (by name), and the [StandardChooserArgs] of the arguments
// that do not have a chooser, under the mutex.
func (cs *Commands) addStandardChoosersLocked() {
for _, c := range StandardChoosers() {
if !slices.ContainsFunc(cs.Choosers, func(o *Chooser) bool { return o.Name == c.Name }) {
cs.Choosers = append(cs.Choosers, c)
}
}
cs.updateStandardChoosersLocked()
for root, args := range StandardChooserArgs() {
cm := cs.Parsed[root]
if cm == nil {
cm = &Cmd{Cmd: root}
cs.Parsed[root] = cm
}
if cm.Choosers == nil {
cm.Choosers = map[string]string{}
}
for k, name := range args {
if _, has := cm.Choosers[k]; !has && name != "" {
cm.Choosers[k] = name
}
}
}
}
// updateStandardChoosersLocked updates the [StandardChoosers] of earlier
// versions (see [oldStandardChoosers]), which the user has not changed, to
// the current ones, under the mutex.
func (cs *Commands) updateStandardChoosersLocked() {
for _, c := range StandardChoosers() {
for i, o := range cs.Choosers {
if o.Name == c.Name && slices.Contains(oldStandardChoosers[c.Name], o.Command) {
cs.Choosers[i] = c
}
}
}
}
// dir returns the directory that the commands run in from the given
// context widget (see [Commands.Dir]).
func (cs *Commands) dir(ctx core.Widget) string {
if cs.Dir != nil && ctx != nil {
if d := cs.Dir(ctx); d != "" {
return d
}
}
d, _ := os.Getwd()
return d
}
// chooserFunc returns the chooser of the field of the given name of a
// form, or nil if it has none.
type chooserFunc func(field string) *Chooser
// subCmdChoosers returns the [chooserFunc] of the forms of the given
// subcommand (see [SubCmd.FormStruct]).
func (cs *Commands) subCmdChoosers(sc *SubCmd) chooserFunc {
names := sc.fieldNames()
return func(field string) *Chooser {
if i := slices.Index(names, field); i >= 0 {
return cs.Chooser(cs.ArgChooser(sc, sc.argKey(i)))
}
return nil
}
}
// scriptChoosers returns the [chooserFunc] of the form of the arguments of
// the given script (see [Script.FormStruct]).
func (cs *Commands) scriptChoosers(s *Script) chooserFunc {
names := s.fieldNames()
return func(field string) *Chooser {
if i := slices.Index(names, field); i >= 0 && s.Args[i].Kind == ArgString {
return cs.Chooser(string(s.Args[i].Chooser))
}
return nil
}
}
// formFieldName returns the name of the field of the given value widget of
// a [core.Form], whose name is value-<field>-<type>, or "" if it is not one.
func formFieldName(w core.Widget) string {
name, ok := strings.CutPrefix(w.AsTree().Name, "value-")
if !ok {
return ""
}
if before, _, ok := strings.CutLast(name, "-"); ok {
return before
}
return ""
}
// addChooserButton adds a trailing button to the given text field of the
// field of the given name of a form, with a menu of the values of its
// chooser, given by the given function, if it has one, run in the
// directory of the given context widget, which is updated with the field,
// as the chooser of the field can change.
func (cs *Commands) addChooserButton(ctx core.Widget, tf *core.TextField, field string, chooser chooserFunc) {
tf.Updater(func() {
ch := chooser(field)
if ch == nil {
if tf.TrailingIcon == icons.ArrowDropDown {
tf.TrailingIcon, tf.TrailingIconOnClick, tf.Placeholder = icons.None, nil, ""
}
return
}
tf.SetPlaceholder(ch.Empty)
tf.SetTrailingIcon(icons.ArrowDropDown, func(e events.Event) {
cs.chooserMenu(ctx, tf, ch, tf.ContextMenuPos(e))
})
tf.SetTooltip(html.EscapeString(ch.Name + ": " + cmpOr(ch.Doc, ch.Command)))
})
}
// chooserMenu shows a menu of the values of the given chooser, run in the
// directory of the given context widget, at the given position, which sets
// the given text field to the chosen one.
func (cs *Commands) chooserMenu(ctx core.Widget, tf *core.TextField, ch *Chooser, pos image.Point) {
vals, err := ch.Values(cs.dir(ctx))
if err != nil {
core.ErrorSnackbar(tf, err, "Error getting the values of "+ch.Name)
return
}
core.NewMenu(func(m *core.Scene, _ image.Point) { chooserItems(m, tf, ch, vals) }, tf, pos).Run()
}
// chooserItems adds the buttons of the given values of the given chooser
// to the given menu, which set the given text field to them.
func chooserItems(m *core.Scene, tf *core.TextField, ch *Chooser, vals []string) {
if len(vals) == 0 {
core.NewText(m).SetText("No values of " + html.EscapeString(ch.Name))
}
for _, v := range vals {
b := core.NewButton(m).SetText(v)
if v == tf.Text() {
b.SetIcon(icons.Check)
}
b.OnClick(func(e events.Event) {
tf.SetText(v)
tf.SendChange(e)
})
}
}
// choosersMenu adds the buttons to set the choosers of the arguments of
// the given subcommand, other than switches, to the given menu, which
// update the given form, followed by one to edit the choosers.
func (cs *Commands) choosersMenu(m *core.Scene, ctx core.Widget, sc *SubCmd, fm *core.Form) {
chs := cs.choosers()
for i := range sc.fieldNames() {
if sc.argType(i).Kind() != reflect.String {
continue
}
key := sc.argKey(i)
label := argsField
if i > 0 {
label = sc.Flags[i-1].Label()
}
cur := cs.ArgChooser(sc, key)
b := core.NewButton(m).SetText(html.EscapeString(label))
if cur != "" {
b.SetText(html.EscapeString(label + ": " + cur))
}
b.SetMenu(func(sm *core.Scene, _ image.Point) {
add := func(text, chooser, tip string) {
w := core.NewButton(sm).SetText(text)
w.SetTooltip(html.EscapeString(tip))
if chooser == cur {
w.SetIcon(icons.Check)
}
w.OnClick(func(e events.Event) {
if err := cs.SetArgChooser(sc, key, chooser); err != nil {
core.ErrorSnackbar(ctx, err)
return
}
fm.Update()
})
}
add("None", "", "Text, typed")
for _, c := range chs {
add(c.Name, c.Name, cmpOr(c.Doc, c.Command))
}
})
}
core.NewSeparator(m)
core.NewButton(m).SetText("Edit choosers").SetIcon(icons.Edit).
SetTooltip("Edit the choosers, whose values are the lines of the output of a shell command").
OnClick(func(e events.Event) { cs.EditChoosers(ctx) })
}
// ChooserArg is the chooser of an argument of a subcommand of a command,
// as edited in the editor of the choosers (see [Cmd.Choosers]).
type ChooserArg struct {
// Command is the command: "git".
Command string
// SubCmd is the subcommand, its words after the command: "checkout",
// "stash push", or empty for the command itself.
SubCmd string `label:"Subcommand"`
// Arg is the argument: Arguments for the other arguments, such as
// files and branches, or the name of a flag with its dashes:
// "--set-upstream-to".
Arg string `label:"Argument"`
// Chooser is the chooser of the values of the argument.
Chooser ChooserName
}
// ChooserArgs returns the choosers of the arguments of the subcommands of
// the commands, sorted.
func (cs *Commands) ChooserArgs() []*ChooserArg {
cs.reload()
cs.mu.Lock()
defer cs.mu.Unlock()
var cas []*ChooserArg
for root, cm := range cs.Parsed {
for key, name := range cm.Choosers {
before, after, ok := strings.CutLast(key, " ")
if !ok {
continue
}
sub := before
if sub == MainName {
sub = ""
}
cas = append(cas, &ChooserArg{Command: root, SubCmd: sub, Arg: after, Chooser: ChooserName(name)})
}
}
slices.SortFunc(cas, func(a, b *ChooserArg) int {
return strings.Compare(a.Command+" "+a.SubCmd+" "+a.Arg, b.Command+" "+b.SubCmd+" "+b.Arg)
})
return cas
}
// SetChoosers sets the choosers of the commands, and of the arguments of
// their subcommands (in place of all of those they have), to the given
// ones, and saves them. Those without a name or command, and arguments
// without a command, argument, or chooser, are left out.
func (cs *Commands) SetChoosers(chs []*Chooser, args []*ChooserArg) error {
chs = slices.DeleteFunc(slices.Clone(chs), func(c *Chooser) bool {
c.Name, c.Command = strings.TrimSpace(c.Name), strings.TrimSpace(c.Command)
return c.Name == "" || c.Command == ""
})
return cs.update(func() {
cs.Choosers = chs
for _, cm := range cs.Parsed {
cm.Choosers = nil
}
for _, ca := range args {
root := strings.TrimSpace(ca.Command)
sub := strings.Join(strings.Fields(ca.SubCmd), " ")
arg := strings.TrimSpace(ca.Arg)
if root == "" || arg == "" || ca.Chooser == "" {
continue
}
if sub == "" {
sub = MainName
}
cm := cs.Parsed[root]
if cm == nil {
cm = &Cmd{Cmd: root}
cs.Parsed[root] = cm
}
if cm.Choosers == nil {
cm.Choosers = map[string]string{}
}
cm.Choosers[sub+" "+arg] = string(ca.Chooser)
}
})
}
// EditChoosers opens the editor of the choosers of the commands, in the
// context of the given widget (see [Commands.NewChoosersDialog]).
func (cs *Commands) EditChoosers(ctx core.Widget) {
ctx = cs.context(ctx)
runDialog(cs.NewChoosersDialog(ctx), ctx)
}
// NewChoosersDialog returns the body of the editor of the choosers of the
// commands: a table of their names, commands, and documentation, and a
// table of the choosers of the arguments of the subcommands, which saves
// them.
func (cs *Commands) NewChoosersDialog(ctx core.Widget) *core.Body {
ctx = cs.context(ctx)
d := core.NewBody("Choosers")
core.NewText(d).SetType(core.TextSupporting).SetText("The values of an argument with a chooser, such as a git branch, are chosen from the lines of the output of its shell command, run in the directory of the commands, in a menu of the button of its text field. Add rows with the buttons at the top, or the context menu of a table (right-click).")
var chs []*Chooser
for _, c := range cs.choosers() {
nc := *c
chs = append(chs, &nc)
}
args := cs.ChooserArgs()
core.NewText(d).SetType(core.TextTitleSmall).SetText("Choosers")
tb := core.NewTable(d).SetSlice(&chs)
core.NewText(d).SetType(core.TextTitleSmall).SetText("Arguments")
core.NewText(d).SetType(core.TextSupporting).SetText("The choosers of the arguments of commands: the argument is Arguments for the other arguments, such as files and branches, or the name of a flag, such as --set-upstream-to. They can also be set with Choosers at the top of the form of a command, and those of scripts in their arguments.")
at := core.NewTable(d).SetSlice(&args)
d.AddTopBar(func(bar *core.Frame) {
core.NewToolbar(bar).Maker(func(p *tree.Plan) {
tree.Add(p, func(w *core.Button) {
w.SetText("Add chooser").SetIcon(icons.Add).SetTooltip("Add a chooser at the end")
w.OnClick(func(e events.Event) {
chs = append(chs, &Chooser{Name: "Chooser"})
tb.Update()
})
})
tree.Add(p, func(w *core.Button) {
w.SetText("Add argument").SetIcon(icons.Add).SetTooltip("Add the chooser of an argument of a command at the end")
w.OnClick(func(e events.Event) {
args = append(args, &ChooserArg{Arg: argsField})
at.Update()
})
})
tree.Add(p, func(w *core.Button) {
w.SetText("Try").SetIcon(icons.PlayArrow)
w.SetTooltip("Show the values of the selected chooser, in the directory of the commands")
w.OnClick(func(e events.Event) {
i := tb.SelectedIndex
if i < 0 || i >= len(chs) {
core.MessageSnackbar(w, "Select a chooser to try")
return
}
vals, err := chs[i].Values(cs.dir(ctx))
if err != nil {
core.ErrorSnackbar(w, err)
return
}
core.MessageDialog(w, html.EscapeString(strings.Join(vals, "\n")), chs[i].Name)
})
})
})
})
d.AddBottomBar(func(bar *core.Frame) {
d.AddCancel(bar)
d.AddOK(bar).SetText("Save").SetIcon(icons.Save).OnClick(func(e events.Event) {
if err := cs.SetChoosers(chs, args); err != nil {
core.ErrorSnackbar(ctx, err)
return
}
core.MessageSnackbar(ctx, "Saved the choosers")
})
})
return d
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package commands provides a GUI for calling command line tools, such as
// git, whose many options are hard to remember. The help output of each
// command is parsed into a [Cmd], with its subcommands, such as git commit,
// each a [SubCmd] with its flags, which are cached (see [Commands]). The
// user organizes the commands into categories, edited in a
// [core.TreeTable] (see [Commands.Edit]), which are shown in a command bar
// like a bookmarks bar, or in a menu, with menus of the subcommands of the
// commands (see [Commands.Bar] and [Commands.Menu]). Clicking on a
// subcommand shows a form of its flags and arguments, which builds the
// command line to run, in a terminal for example (see
// [Commands.RunDialog]), starting with the arguments last used for it (see
// [Args]). A [Macro] is a version of a subcommand with values for its
// arguments, some of which are prompted for when it runs, such as the
// [StandardMacros] of git, go, and core.
//
// The [Default] commands are shared by the apps, such as Cogent Files and
// Cogent Code, in the Cogent Core data directory: their files are read
// again when another app changes them.
package commands
import (
"strings"
"cogentcore.org/core/base/strcase"
)
// Cmd is a command, such as git, with its subcommands, such as
// git commit, parsed from its help output (see [ParseCmd]).
type Cmd struct {
// Cmd is the command: "git".
Cmd string
// Doc is the documentation of the command, if found.
Doc string `json:",omitempty"`
// SubCmds are the subcommands of the command, which are parsed when
// they are used (see [SubCmd.IsParsed]). A command without
// subcommands has one, named [MainName], for the command itself.
SubCmds []*SubCmd
// Macros are the macros of the subcommands, made by the user, which
// are at the top of the menu of the command (see [Macro]). They are
// kept when the command is parsed again.
Macros []*Macro `json:",omitempty"`
// Scripts are the scripts of the command, made by the user, which are
// in the menu of the command after its macros (see [Script]). They are
// kept when the command is parsed again.
Scripts []*Script `json:",omitempty"`
// Choosers are the names of the choosers of the arguments of the
// subcommands, set by the user, by the name of the subcommand and the
// key of the argument: "checkout Arguments" (see [Chooser]). They are
// kept when the command is parsed again.
Choosers map[string]string `json:",omitempty"`
}
// IsParsed returns whether the help of the command has been parsed: it
// has subcommands (it may only have macros otherwise, from a file of
// another version).
func (cm *Cmd) IsParsed() bool {
return len(cm.SubCmds) > 0
}
// MainName is the name of the [SubCmd] of a [Cmd] without subcommands,
// which is the command itself.
const MainName = "Main"
// SubCmd returns the subcommand of the given name, such as "commit" or
// "stash list", or nil if there is none.
func (cm *Cmd) SubCmd(name string) *SubCmd {
for _, sc := range cm.SubCmds {
if sc.Name == name {
return sc
}
}
return nil
}
// HasSubCmds returns whether the command has subcommands, other than its
// [MainName] one.
func (cm *Cmd) HasSubCmds() bool {
return len(cm.SubCmds) > 1 || (len(cm.SubCmds) == 1 && cm.SubCmds[0].Name != MainName)
}
// SubCmd is a subcommand of a [Cmd], such as git commit, or the command
// itself (see [MainName]), with the information parsed from its help
// output (see [Parse]).
type SubCmd struct {
// Name is the name of the subcommand, its words after the command:
// "commit", "stash list", or [MainName] for the command itself.
Name string
// Cmd is the command line of the subcommand: "git commit".
Cmd string
// Doc is the documentation of the subcommand, if found.
Doc string `json:",omitempty"`
// Usage is the usage synopsis of the subcommand, if found.
Usage string `json:",omitempty"`
// Flags are the flags of the subcommand.
Flags []*Flag `json:",omitempty"`
// Group is the group of the subcommand in the help of its command,
// such as "Main Porcelain Commands" for git: the heading of its
// section, which is shown as a submenu, other than the first group.
Group string `json:",omitempty"`
// Cmds are the subcommands of the subcommand, such as git stash list,
// with their documentation (or usage), which are parsed as subcommands
// of the command when they are used.
Cmds []*SubCmd `json:",omitempty"`
// Source is the help command whose output was parsed: "git commit -h",
// which is empty if the subcommand has not been parsed yet.
Source string `json:",omitempty"`
}
// IsParsed returns whether the help of the subcommand has been parsed.
func (cm *SubCmd) IsParsed() bool {
return cm.Source != ""
}
// Label returns the text shown for the subcommand: [MainName], or its
// last word in sentence case: "Commit", "List" for "stash list".
func (cm *SubCmd) Label() string {
if cm.Name == MainName {
return MainName
}
return label(cm.Cmd)
}
// label returns the last word of the given command in sentence case.
func label(cmd string) string {
if f := strings.Fields(cmd); len(f) > 0 {
return strcase.ToSentence(f[len(f)-1])
}
return ""
}
// splitCmd splits the given command line into the command and the name
// of its subcommand: "git", "stash list".
func splitCmd(cmd string) (root, name string) {
f := strings.Fields(cmd)
if len(f) == 0 {
return "", ""
}
return f[0], strings.Join(f[1:], " ")
}
// Flag is a flag of a [Cmd].
type Flag struct {
// Name is the canonical (longest) name of the flag, with its dashes:
// "--message".
Name string
// Names are all of the names of the flag, with their dashes, shortest
// first: "-m", "--message".
Names []string
// Value is the hint for the value of the flag, such as "<message>",
// or empty for a flag without a value, which is on or off.
Value string `json:",omitempty"`
// Optional is whether the value is optional, as in "--name[=<value>]":
// it is attached to the flag, with = for long names.
Optional bool `json:",omitempty"`
// Equals is whether the value is attached with =, as in "--name=<value>".
Equals bool `json:",omitempty"`
// Negatable is whether the flag has a negated form, as in "--[no-]name".
Negatable bool `json:",omitempty"`
// Doc is the documentation of the flag.
Doc string `json:",omitempty"`
}
// IsBool returns whether the flag has no value: it is on or off.
func (fl *Flag) IsBool() bool {
return fl.Value == ""
}
// Label returns the label of the flag: its names and value hint.
func (fl *Flag) Label() string {
s := strings.Join(fl.Names, ", ")
if fl.Value != "" {
s += " " + fl.Value
}
return s
}
// Arg returns the command line argument(s) for the flag with the given
// value, which is quoted for a shell as needed.
func (fl *Flag) Arg(value string) string {
if fl.IsBool() {
return fl.Name
}
q := shellQuote(value)
long := strings.HasPrefix(fl.Name, "--")
switch {
case fl.Equals || (fl.Optional && long):
return fl.Name + "=" + q
case fl.Optional:
return fl.Name + q
}
return fl.Name + " " + q
}
// shellQuote returns the given string quoted for a POSIX shell, if it has
// any characters that need it.
func shellQuote(s string) string {
if s == "" {
return "''"
}
if !strings.ContainsFunc(s, func(r rune) bool {
return (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') && (r < '0' || r > '9') && !strings.ContainsRune("-_./:=,@%+", r)
}) {
return s
}
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package commands
import (
"cmp"
"context"
"fmt"
"maps"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"slices"
"strings"
"sync"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/sharedfile"
"cogentcore.org/core/core"
)
// Entry is a command, or a category of commands, in the [Commands], which
// are edited in a [core.TreeTable] (see [Commands.Edit]). The top-level
// entries are the buttons of the command bar (see [Commands.Bar]): those
// of categories have menus of their entries, and those of commands with
// subcommands, such as git, have menus of their subcommands.
type Entry struct {
// Name is the name of the command or category, which is shown for it.
// The default for a command is its last word: "Git" for "git", and
// "Commit" for "git commit".
Name string
// Command is the command, such as "git", or a subcommand, such as
// "git commit", which is empty for a category.
Command string `width:"30"`
// Common are the subcommands of the command that are used the most,
// such as "status add commit" for git, separated by spaces, which are
// at the top of the menu of its subcommands, followed by a submenu of
// the others, sorted by name. All of them are in the menu, by group,
// if it is empty.
Common string `width:"30" label:"Common subcommands" doc:"The subcommands used the most, separated by spaces, such as: status add commit, which are at the top of the menu of the command, followed by a submenu of the others"`
// Children are the entries in the category.
Children []*Entry `display:"-"`
// Script is the script of an entry that is a script (see [Script]),
// rather than a command, which is edited in its own editor.
Script *Script `json:",omitempty" display:"-"`
// Closed is whether the category is closed in the editor.
Closed bool `display:"-" treetable:"closed"`
}
// IsCategory returns whether the entry is a category of commands: it has
// children, or no command or script.
func (en *Entry) IsCategory() bool {
return len(en.Children) > 0 || (en.Command == "" && en.Script == nil)
}
// Label returns the text shown for the entry: its name, or else that of
// its script, or the last word of its command.
func (en *Entry) Label() string {
if en.Name != "" {
return en.Name
}
if en.Script != nil && en.Script.Name != "" {
return en.Script.Name
}
return cmp.Or(label(en.Command), "Commands")
}
// version is the version of the format of the file of the [Commands]:
// the parsed commands of other versions are parsed again.
const version = 10
// Commands are the commands of the command bar, organized into categories
// by the user, with the cache of the parsed help of commands, which are
// saved in a JSON file (see [Open]), and the arguments last used for them,
// which are saved in another (see [Args]).
type Commands struct {
// Version is the version of the format of the file.
Version int
// StandardVersion is the version of the [Standard] commands that the
// entries have (see [addStandard]).
StandardVersion int
// Entries are the top-level entries, which are the buttons of the
// command bar.
Entries []*Entry
// Parsed are the parsed commands, by command, such as "git", which are
// parsed when they are first used (see [Commands.SubCmd]).
Parsed map[string]*Cmd
// Choosers are the choosers of the values of arguments, such as a git
// branch (see [Chooser]).
Choosers []*Chooser
// Dir returns the directory that the commands run in from the given
// context widget, such as a command bar, in which the commands of the
// choosers run, if it is not nil: the current directory of the window
// of the app. It is the working directory otherwise.
Dir func(ctx core.Widget) string `json:"-"`
// Args are the arguments last used for the subcommands, which are saved
// in their own file.
Args *Args `json:"-"`
// file is the file the commands are saved in, which other processes
// (apps) share.
file sharedfile.File[commandsData]
// mu protects the commands and the saving of the file.
mu sync.Mutex
// names are for the names of the command lines (see [Commands.Name]).
names struct {
sync.Mutex
// macros are the labels of the macros that ran the command lines,
// by command line (see [Commands.Name]).
macros map[string]string
}
// views are the command bars and the editor of the commands, which are
// updated when the commands change (see [Commands.Changed]).
views struct {
sync.Mutex
bars []*core.Toolbar
editor *core.TreeTable
}
}
// File is the file of the [Default] commands, which are shared by the
// apps: commands.json in the Cogent Core data directory, if it is empty.
var File string
// defaultCommands opens the [Default] commands once.
var defaultCommands = sync.OnceValue(func() *Commands {
if File == "" {
File = filepath.Join(core.TheApp.CogentCoreDataDir(), "commands.json")
}
return Open(File)
})
// Default returns the commands that are shared by the apps, such as Cogent
// Files and Cogent Code, opening them from the [File] the first time.
func Default() *Commands {
return defaultCommands()
}
// Open returns the commands saved in the given JSON file, or the
// [Standard] ones if it does not exist yet, which are saved in it when
// they change, with the arguments last used for them, saved in the file of
// the same name ending in -args.json (see [OpenArgs]). The files may be
// shared by other processes (apps): they are read again when another
// process changes them. The help of the commands that have not been parsed
// yet is parsed in the background (see [Commands.ParseAll]).
func Open(filename string) *Commands {
cs := &Commands{file: sharedfile.File[commandsData]{Path: filename}, Parsed: map[string]*Cmd{}}
cs.mu.Lock()
cs.syncLocked()
if cs.Version < 2 { // (the first version had categories of git subcommands)
cs.Entries = Standard()
cs.StandardVersion = standardVersion
cs.addStandardMacrosLocked()
cs.addStandardChoosersLocked()
}
if cs.Version < 3 { // (the common subcommands were added)
addCommon(cs.Entries)
}
if cs.StandardVersion < standardVersion {
if cs.StandardVersion < 2 { // (the standard ones were added, and the standard macros)
cs.Entries = addStandard(cs.Entries)
cs.addStandardMacrosLocked()
}
if cs.StandardVersion < 3 { // (only the standard choosers, not the entries again)
cs.addStandardChoosersLocked()
} else if cs.StandardVersion < 4 { // (the new versions of the standard choosers)
cs.updateStandardChoosersLocked()
}
cs.StandardVersion = standardVersion
}
cs.mu.Unlock()
args := ""
if filename != "" {
args = strings.TrimSuffix(filename, ".json") + "-args.json"
}
cs.Args = OpenArgs(args)
go cs.ParseAll()
return cs
}
// commandsData are the data of the file of the [Commands].
type commandsData struct {
Version int
StandardVersion int
Entries []*Entry
Parsed map[string]*Cmd
Choosers []*Chooser `json:",omitempty"`
// merged is whether the data have been merged into the commands, or
// are theirs (as written): only data read from the file are merged.
merged bool
}
// data returns the commands as the data of their file.
func (cs *Commands) data() commandsData {
return commandsData{Version: cs.Version, StandardVersion: cs.StandardVersion, Entries: cs.Entries, Parsed: cs.Parsed, Choosers: cs.Choosers}
}
// syncLocked reads the file of the commands if another process has
// changed it, under the mutex, returning whether it did (see
// [Commands.mergeLocked]).
func (cs *Commands) syncLocked() bool {
if !cs.file.Changed() {
return false
}
errors.Log(cs.file.Reload())
if cs.file.Data.merged {
return false
}
cs.mergeLocked(&cs.file.Data)
cs.file.Data.merged = true
return true
}
// mergeLocked merges the given data of the file into the commands, under
// the mutex: the entries and the choosers are those of the file, and the
// parsed commands are merged with those parsed here. A file of another
// version only has its macros, scripts, and choosers taken (made by the
// user), and one of the first version none.
func (cs *Commands) mergeLocked(fc *commandsData) {
if fc.Version < 2 {
return
}
cs.Version = max(cs.Version, fc.Version)
cs.StandardVersion = max(cs.StandardVersion, fc.StandardVersion)
cs.Entries = fc.Entries
cs.Choosers = fc.Choosers
if fc.Version != version {
for root, fcm := range fc.Parsed {
if len(fcm.Macros) == 0 && len(fcm.Scripts) == 0 && len(fcm.Choosers) == 0 {
continue
}
if cm := cs.Parsed[root]; cm != nil {
cm.Macros, cm.Scripts, cm.Choosers = fcm.Macros, fcm.Scripts, fcm.Choosers
} else {
cs.Parsed[root] = &Cmd{Cmd: root, Macros: fcm.Macros, Scripts: fcm.Scripts, Choosers: fcm.Choosers}
}
}
return
}
for root, fcm := range fc.Parsed {
if cm := cs.Parsed[root]; cm != nil && cm != fcm {
for _, sc := range cm.SubCmds {
if !sc.IsParsed() {
continue
}
if i := slices.IndexFunc(fcm.SubCmds, func(f *SubCmd) bool { return f.Name == sc.Name }); i < 0 {
fcm.SubCmds = append(fcm.SubCmds, sc)
} else if !fcm.SubCmds[i].IsParsed() {
fcm.SubCmds[i] = sc
}
}
}
cs.Parsed[root] = fcm
}
}
// reload reads the file of the commands if another process has changed
// it, updating the command bars and the editor if it did.
func (cs *Commands) reload() {
cs.mu.Lock()
changed := cs.syncLocked()
cs.mu.Unlock()
if changed {
cs.updateViews(nil)
}
}
// update changes the commands with the given function, and saves them,
// with the file locked, after reading the changes of other processes.
func (cs *Commands) update(change func()) error {
cs.mu.Lock()
defer cs.mu.Unlock()
return cs.file.Update(func(d *commandsData) {
if !d.merged { // (read again, as another process changed it)
cs.mergeLocked(d)
}
change()
cs.Version = version
*d = cs.data()
d.merged = true
})
}
// Save saves the commands to their file, with the entries as they are
// here, as edited, and the parsed commands merged with those of other
// processes.
func (cs *Commands) Save() error {
cs.mu.Lock()
ens := cs.Entries
cs.mu.Unlock()
return cs.update(func() { cs.Entries = ens })
}
// cached returns the cached parse of the given command, such as "git",
// if any, as a copy, which is not changed by parsing, nor by changes to
// its macros, scripts, and choosers: those delete from their slices in
// place, which would leave nil elements in the menus made from a copy.
func (cs *Commands) cached(cmd string) *Cmd {
cs.mu.Lock()
defer cs.mu.Unlock()
cs.syncLocked()
cm := cs.Parsed[cmd]
if cm == nil {
return nil
}
c := *cm
c.SubCmds = slices.Clone(cm.SubCmds)
c.Macros = slices.Clone(cm.Macros)
c.Scripts = slices.Clone(cm.Scripts)
c.Choosers = maps.Clone(cm.Choosers)
return &c
}
// cachedSub returns the cached parse of the given subcommand, such as
// "git commit", or "ls" for the [MainName] one, if it has been parsed.
func (cs *Commands) cachedSub(cmd string) *SubCmd {
root, name := splitCmd(cmd)
cm := cs.cached(root)
if cm == nil {
return nil
}
if sc := cm.SubCmd(cmp.Or(name, MainName)); sc != nil && sc.IsParsed() {
return sc
}
return nil
}
// ReparseMode specifies whether to parse the commands again, from their
// files: [Reparse] or [NoReparse].
type ReparseMode bool
const (
// Reparse parses the commands again.
Reparse ReparseMode = true
// NoReparse uses the commands as they were parsed.
NoReparse ReparseMode = false
)
// Cmd returns the parsed command for the given command, such as "git",
// parsing its help and saving it if it has not been parsed yet, or if
// reparse is true, keeping the subcommands that have been parsed.
func (cs *Commands) Cmd(cmd string, reparse ReparseMode) (*Cmd, error) {
if cm := cs.cached(cmd); cm != nil && cm.IsParsed() && reparse == NoReparse {
return cm, nil
}
cm, err := ParseCmd(cmd)
if err != nil {
return nil, err
}
err = cs.update(func() {
if old := cs.Parsed[cmd]; old != nil {
cm.Macros, cm.Scripts, cm.Choosers = old.Macros, old.Scripts, old.Choosers
for i, sc := range cm.SubCmds {
if osc := old.SubCmd(sc.Name); osc != nil && osc.IsParsed() && !sc.IsParsed() {
cm.SubCmds[i] = osc
}
}
}
cs.Parsed[cmd] = cm
})
return cs.cached(cmd), err
}
// SubCmd returns the parsed subcommand for the given command line, such
// as "git commit", or "ls" for the [MainName] subcommand of a command
// without subcommands, parsing its help and saving it if it has not been
// parsed yet, or if reparse is true. Its documentation defaults to that
// given by its command (or parent subcommand). A subcommand that is not
// one of those of the command, such as "git stash list", is added to them.
func (cs *Commands) SubCmd(cmd string, reparse ReparseMode) (*SubCmd, error) {
cmd = strings.Join(strings.Fields(cmd), " ")
if sc := cs.cachedSub(cmd); sc != nil && !reparse {
return sc, nil
}
root, name := splitCmd(cmd)
cm, err := cs.Cmd(root, NoReparse)
if err != nil {
return nil, err
}
if name == "" {
if cm.HasSubCmds() {
return nil, fmt.Errorf("commands: %s has subcommands", root)
}
name = MainName
}
if name == MainName && reparse {
if _, err := cs.Cmd(root, Reparse); err != nil {
return nil, err
}
return cs.cachedSub(cmd), nil
}
pcmd := cmd
if name == MainName { // (as for "ls Main", the form of a command with macros)
pcmd = root
}
sc, err := parseSub(pcmd)
if err != nil {
return nil, err
}
sc.Name = name
// a subcommand whose help is that of the command (as of bun run -h)
// lists the subcommands of the command, not its own, and only one level
// of subcommands is nested (as git stash list), as deeper ones are not
// subcommands, but such as the output of a command run by its help
if copiedSubCmds(sc, cm) || strings.Contains(name, " ") {
sc.Cmds = nil
}
cs.addSharedFlags(root, sc)
err = cs.update(func() {
pc := cs.Parsed[root]
if pc == nil {
pc = cm
cs.Parsed[root] = pc
}
doc := ""
for _, other := range pc.SubCmds { // the doc of the command, or of the parent subcommand
if other.Name == name {
doc = cmp.Or(doc, other.Doc)
}
for _, sub := range other.Cmds {
if sub.Cmd == cmd {
doc = cmp.Or(doc, sub.Doc)
}
}
}
sc.Doc = cmp.Or(sc.Doc, doc)
if i := slices.IndexFunc(pc.SubCmds, func(o *SubCmd) bool { return o.Name == name }); i >= 0 {
sc.Group = pc.SubCmds[i].Group // (from the help of the command)
pc.SubCmds[i] = sc
} else {
pc.SubCmds = append(pc.SubCmds, sc)
}
})
return sc, err
}
// parseSub parses the help of a subcommand: [Parse], other than in tests.
var parseSub = Parse
// sharedFlags are the flags that the subcommands of a command share with
// one of its subcommands, which they name in their usage: those of go build,
// which go run, install, test, vet, get, list, clean, and generate have
// ("[build flags]" or "[build/test flags]"), but only describe in their
// help by referring to go build.
var sharedFlags = map[string]struct {
usage *regexp.Regexp
from string
}{
"go": {regexp.MustCompile(`\[build(/test)? flags`), "build"},
}
// addSharedFlags adds the [sharedFlags] of the given command to the given
// subcommand, if its usage names them, after its own flags, without those
// of the same names, parsing the subcommand that they are from if needed.
func (cs *Commands) addSharedFlags(root string, sc *SubCmd) {
sf, ok := sharedFlags[root]
if !ok || sc.Name == sf.from || !sf.usage.MatchString(sc.Usage) {
return
}
from, err := cs.SubCmd(root+" "+sf.from, NoReparse)
if errors.Log(err) != nil {
return
}
sc.Flags = mergeFlags(sc.Flags, from.Flags)
}
// copiedSubCmds returns whether the subcommands of the given subcommand
// are mostly those of the given command: its help is that of the command.
func copiedSubCmds(sc *SubCmd, cm *Cmd) bool {
if len(sc.Cmds) < 2 {
return false
}
n := 0
for _, sub := range sc.Cmds {
if cm.SubCmd(sub.Cmd[strings.LastIndex(sub.Cmd, " ")+1:]) != nil {
n++
}
}
return 2*n >= len(sc.Cmds)
}
// ParseAll parses the help of all of the commands that have not been parsed
// yet, and of their subcommands, and then of the subcommands of those, such
// as git stash list, saving them, and updating the command bars. It is
// called in the background by [Open], so that the help is cached when the
// commands are used.
func (cs *Commands) ParseAll() {
var cmds []string
var add func(ens []*Entry)
add = func(ens []*Entry) {
for _, en := range ens {
add(en.Children)
if en.Command != "" {
cmds = append(cmds, en.Command)
}
}
}
add(cs.Entries)
parse := func(full string) *SubCmd {
if sc := cs.cachedSub(full); sc != nil {
return sc
}
sc, err := cs.SubCmd(full, NoReparse)
errors.Log(err)
return sc
}
// the subcommands first, and then the nested ones
var nested []string
for _, cmd := range cmds {
root, name := splitCmd(cmd)
cm, err := cs.Cmd(root, NoReparse)
if errors.Log(err) != nil {
continue
}
subs := []string{name}
if name == "" {
subs = nil
for _, sc := range cm.SubCmds {
if !strings.Contains(sc.Name, " ") { // (nested ones are below)
subs = append(subs, sc.Name)
}
}
}
for _, sub := range subs {
full := root
if sub != MainName {
full += " " + sub
}
if sc := parse(full); sc != nil {
for _, n := range sc.Cmds {
nested = append(nested, n.Cmd)
}
}
}
}
cs.updateViews(nil)
for _, full := range nested {
parse(full)
}
cs.updateViews(nil)
}
// standardCommon are the [Entry.Common] subcommands of the [Standard]
// commands. Those that a command does not have are ignored.
var standardCommon = map[string]string{
"git": "status add commit diff log show branch switch checkout merge rebase cherry-pick stash fetch pull push clone tag reset restore rm mv remote worktree blame grep clean",
"brew": "install upgrade update search info list uninstall outdated cleanup services",
"port": "install upgrade selfupdate search info installed uninstall outdated",
"apt": "install update upgrade search show list remove autoremove",
"apt-get": "install update upgrade dist-upgrade remove autoremove purge",
"dnf": "install upgrade search info list remove autoremove",
"yum": "install update search info list remove",
"snap": "install refresh find info list remove",
"flatpak": "install update search info list uninstall",
"winget": "install upgrade search show list uninstall",
"choco": "install upgrade search info list uninstall",
"scoop": "install update search info list uninstall",
"npm": "install run test update outdated list uninstall init",
"pip3": "install list show freeze uninstall download",
"cargo": "build run test check add install update clean doc",
"systemctl": "status start stop restart reload enable disable list-units daemon-reload",
"launchctl": "list print load unload start stop kickstart",
"diskutil": "list info mount unmount eject",
}
// standardVersion is the version of the [Standard] commands: the standard
// entries (see [addStandard]) and the [StandardMacros] are added to those
// of a file before version 2, which does not have them, and the
// [StandardChoosers] to those of a file before version 3, and updated
// in those before version 4 (without adding the standard entries again,
// which the user may have deleted).
const standardVersion = 4
// addCommon sets the [Entry.Common] subcommands of the given entries of the
// [Standard] commands that do not have them, for a file of a version from
// before they were added.
func addCommon(ens []*Entry) {
for _, en := range ens {
addCommon(en.Children)
if en.Common == "" {
en.Common = standardCommon[en.Command]
}
}
}
// addStandard adds the [Standard] entries that the given entries do not
// have to them, returning them: the top-level commands and categories, and
// the commands of the categories of the same names.
func addStandard(ens []*Entry) []*Entry {
has := func(ens []*Entry, en *Entry) *Entry {
for _, e := range ens {
if (en.Command != "" && e.Command == en.Command) || (en.Command == "" && e.Command == "" && e.Name == en.Name) {
return e
}
}
return nil
}
for _, en := range Standard() {
e := has(ens, en)
if e == nil {
ens = append(ens, en)
continue
}
for _, c := range en.Children {
if has(e.Children, c) == nil {
e.Children = append(e.Children, c)
}
}
}
return ens
}
// standardCommands are the commands of the [Standard] categories, by
// category, on all platforms, and on the platforms of the given GOOS.
var standardCommands = []struct {
name, goos string
cmds []string
}{
{"Files", "", []string{"ls", "find", "cp", "mv", "rm", "mkdir", "ln", "chmod", "chown", "du", "df", "tar", "zip", "unzip", "rsync"}},
{"Text", "", []string{"grep", "sed", "awk", "sort", "uniq", "wc", "head", "tail", "cut", "diff", "jq", "pdflatex", "latex", "latexmk", "bibtex", "biber"}},
{"Dev", "", []string{"make", "cmake", "pkg-config", "gcc", "g++", "clang", "clang++", "gdb", "lldb", "cargo", "python3", "node"}},
{"Packages", "darwin", []string{"brew", "port"}},
{"Packages", "linux", []string{"apt", "apt-get", "apt-cache", "dpkg", "dnf", "yum", "pacman", "zypper", "snap", "flatpak"}},
{"Packages", "windows", []string{"winget", "choco", "scoop"}},
{"Packages", "", []string{"pip3", "npm"}},
{"Network", "", []string{"curl", "wget", "ssh", "scp", "ping"}},
{"System", "", []string{"ps", "kill", "pkill", "lsof", "uname"}},
{"System", "darwin", []string{"open", "launchctl", "diskutil"}},
{"System", "linux", []string{"systemctl", "journalctl"}},
}
// Standard returns the standard commands, which the user starts with: git,
// go, and core, with the menus of their subcommands, and categories of
// commands for files, text, development, packages, the network, and the
// system, those of this platform. Commands that are not installed are left
// out (see [installed]).
func Standard() []*Entry {
var all []string
for _, sc := range standardCommands {
all = append(all, sc.cmds...)
}
have := installed(append(all, "git", "go", "core"))
var ens []*Entry
for _, cmd := range []string{"git", "go", "core"} {
if have[cmd] {
ens = append(ens, &Entry{Command: cmd, Common: standardCommon[cmd]})
}
}
for _, sc := range standardCommands {
if sc.goos != "" && sc.goos != runtime.GOOS {
continue
}
i := slices.IndexFunc(ens, func(e *Entry) bool { return e.Command == "" && e.Name == sc.name })
if i < 0 {
ens = append(ens, &Entry{Name: sc.name, Closed: true})
i = len(ens) - 1
}
for _, cmd := range sc.cmds {
if have[cmd] {
ens[i].Children = append(ens[i].Children, &Entry{Command: cmd, Common: standardCommon[cmd]})
}
}
}
return slices.DeleteFunc(ens, func(e *Entry) bool { return e.Command == "" && len(e.Children) == 0 })
}
// installed returns which of the given commands are installed: found in
// the PATH, or else by the login shell (whose PATH an app started from the
// desktop may not have), in one call for all of those.
func installed(cmds []string) map[string]bool {
have := map[string]bool{}
var rest []string
for _, cmd := range cmds {
if _, err := exec.LookPath(cmd); err == nil {
have[cmd] = true
} else {
rest = append(rest, cmd)
}
}
sh := os.Getenv("SHELL")
if len(rest) == 0 || sh == "" || runtime.GOOS == "windows" {
return have
}
quoted := make([]string, len(rest))
for i, c := range rest {
quoted[i] = shellQuote(c)
}
script := "for c in " + strings.Join(quoted, " ") + "; do command -v \"$c\" >/dev/null 2>&1 && echo \"$c\"; done"
ctx, cancel := context.WithTimeout(context.Background(), HelpTimeout)
defer cancel()
out, _ := exec.CommandContext(ctx, sh, "-l", "-c", script).Output()
for c := range strings.FieldsSeq(string(out)) {
have[c] = true
}
return have
}
// StandardMacros are the macros of the standard commands, which the user
// starts with, by command: the high-frequency versions of git, go, and
// core commands (those of Cogent Code), which run in the current directory.
func StandardMacros() map[string][]*Macro {
args := argsField
m := func(sub, name, argv string, flags map[string]string, confirm bool, prompts ...string) *Macro {
mc := &Macro{SubCmd: sub, Name: name, Confirm: confirm, Prompts: prompts}
if argv != "" || flags != nil {
mc.Values = &SubCmdArgs{Args: argv, Flags: flags}
}
return mc
}
on := func(flags ...string) map[string]string {
fs := map[string]string{}
for _, f := range flags {
fs[f] = "true"
}
return fs
}
return map[string][]*Macro{
"git": {
m("status", "", "", nil, false),
m("log", "", "", nil, false),
m("diff", "", "", nil, false, args),
m("add", "", "", nil, false, args),
m("commit", "", "", on("--all"), false, "--message"),
m("pull", "", "", nil, false, args),
m("push", "", "origin HEAD", nil, false, args),
m("push", "force", "origin HEAD", on("--force"), true, args),
m("switch", "", "", nil, false, args),
m("checkout", "", "", nil, false, args),
m("restore", "", "", nil, false, args),
m("stash", "", "", nil, false, args),
m("branch", "", "", nil, false, args),
m("rebase", "", "", nil, false, args),
m("rebase", "continue", "--continue", nil, false),
m("reset", "", "", nil, true, args),
m("remote", "", "", nil, false, args),
},
"go": {
m("build", "", "", on("-v"), false),
m("build", "all", "./...", on("-v"), false),
m("install", "", "", on("-v"), false),
m("generate", "", "", nil, false),
m("test", "", "", on("-v"), false, args),
m("test", "all", "./...", on("-v"), false, args),
m("vet", "", "", nil, false),
m("mod tidy", "", "", nil, false),
m("mod init", "", "", nil, false, args),
m("get", "", "", nil, false, args),
m("get", "update", "", on("-u"), false, args),
},
"core": {
m("run", "", "", nil, false, args),
m("install", "", "", nil, false, args),
m("generate", "all", "./...", nil, false),
m("changed", "", "", nil, false),
m("pull", "", "", nil, false),
m("release", "", "", nil, false, args),
m("next-release", "", "", nil, true),
},
}
}
// addStandardMacrosLocked adds the [StandardMacros] to the commands, other
// than those that they have (of the same subcommand and name), under the
// mutex.
func (cs *Commands) addStandardMacrosLocked() {
for root, mcs := range StandardMacros() {
cm := cs.Parsed[root]
if cm == nil {
cm = &Cmd{Cmd: root}
cs.Parsed[root] = cm
}
for _, mc := range mcs {
if !slices.ContainsFunc(cm.Macros, mc.same) {
cm.Macros = append(cm.Macros, mc)
}
}
}
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package commands
import (
"cmp"
"fmt"
"html"
"image"
"reflect"
"slices"
"strconv"
"strings"
"unicode"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/strcase"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/tree"
)
// RunFunc runs the given command line, such as in a terminal.
type RunFunc func(cmdline string)
// Changed saves the commands, and updates the command bars and the editor
// of the commands, other than the given editor, in which the change was
// made (or none if it is nil).
func (cs *Commands) Changed(editor *core.TreeTable) {
errors.Log(cs.Save())
cs.updateViews(editor)
}
// updateViews updates the command bars and the editor of the commands,
// other than the given editor (or none if it is nil).
func (cs *Commands) updateViews(editor *core.TreeTable) {
cs.views.Lock()
cs.views.bars = slices.DeleteFunc(cs.views.bars, func(tb *core.Toolbar) bool { return tb.This == nil })
var widgets []core.Widget
for _, tb := range cs.views.bars {
widgets = append(widgets, tb)
}
if tt := cs.views.editor; tt != nil && tt.This != nil && tt != editor {
widgets = append(widgets, tt)
}
cs.views.Unlock()
for _, w := range widgets {
// (not with the lock of this window, which another window may be
// waiting on)
go func() {
wb := w.AsWidget()
wb.AsyncLock()
defer wb.AsyncUnlock()
if wb.This != nil {
wb.Update()
}
}()
}
}
// Bar adds the command bar to the given parent: a button for each
// top-level entry, which shows the form of its command (see
// [Commands.RunDialog]) to run with the given function, or the menu of
// the entries of a category, or of the subcommands of a command, and which
// can be dragged to another place in the bar, followed by a button to edit
// the commands. An app can add items of its own to the bar, as with
// [tree.NodeBase.FirstMaker] for items before the commands.
func (cs *Commands) Bar(parent core.Widget, run RunFunc) *core.Toolbar {
tb := core.NewToolbar(parent)
tb.SetName("commands")
tb.Styler(func(s *styles.Style) {
s.Grow.Set(1, 0)
})
tb.MoveFunc = func(from, to int) {
ens := cs.Entries
// the indexes of the items in the bar are those of the entries
// after the items of the app, if any (see [entryName])
from, to = entryIndexOf(ens, tb, from), entryIndexOf(ens, tb, to)
if from < 0 || from >= len(ens) || to < 0 || to >= len(ens) {
return
}
en := ens[from]
ens = slices.Delete(ens, from, from+1)
cs.Entries = slices.Insert(ens, to, en)
cs.Changed(nil)
}
// the changes of other apps are shown when the bar is shown, or the
// mouse enters it (the menus are made from the file as it is)
tb.OnShow(func(e events.Event) { go cs.reload() })
tb.On(events.MouseEnter, func(e events.Event) { go cs.reload() })
tb.Maker(func(p *tree.Plan) {
for _, en := range cs.Entries {
tree.AddAt(p, entryName(en), func(w *core.Button) {
w.SetType(core.ButtonAction)
w.OnClick(func(e events.Event) {
switch {
case en.Script != nil:
cs.RunScript(w, "", en.Script, run)
case w.Menu == nil && !en.IsCategory():
cs.RunDialog(w, en.Command, run)
}
})
cs.scriptContextMenu(w, "", func() *Script { return en.Script })
w.Updater(func() { cs.configEntry(w, en, run) })
})
}
tree.AddAt(p, "edit-commands", func(w *core.Button) {
w.SetType(core.ButtonAction).SetIcon(icons.Edit).SetTooltip("Edit the commands and their categories")
w.OnClick(func(e events.Event) { cs.Edit(w) })
})
})
cs.views.Lock()
cs.views.bars = append(cs.views.bars, tb)
cs.views.Unlock()
return tb
}
// entryName returns the name of the button of the given entry in the
// command bar.
func entryName(en *Entry) string {
return fmt.Sprintf("entry-%p", en)
}
// entryIndexOf returns the index among the given entries of the entry of
// the item of the given command bar at the given index, or -1 if it is not
// that of an entry (as an item of the app).
func entryIndexOf(ens []*Entry, tb *core.Toolbar, idx int) int {
if idx < 0 || idx >= tb.NumChildren() {
return -1
}
name := tb.Child(idx).AsTree().Name
return slices.IndexFunc(ens, func(en *Entry) bool { return entryName(en) == name })
}
// Menu adds the commands to the given menu, as in the command bar (see
// [Commands.Bar]), running their command lines with the given function,
// followed by a button to edit the commands, as for the Command menu of an
// app.
func (cs *Commands) Menu(m *core.Scene, run RunFunc) {
cs.reload()
cs.mu.Lock()
ens := cs.Entries
cs.mu.Unlock()
cs.menu(m, ens, run)
core.NewSeparator(m)
core.NewButton(m).SetText("Edit commands").SetIcon(icons.Edit).SetTooltip("Edit the commands and their categories").
OnClick(func(e events.Event) { cs.Edit(m) })
core.NewButton(m).SetText("Edit choosers").SetIcon(icons.List).SetTooltip(chooserTip).
OnClick(func(e events.Event) { cs.EditChoosers(m) })
}
// chooserTip is the tooltip of the buttons that edit the choosers.
const chooserTip = "Edit the choosers of the values of arguments, such as git branches, which are the lines of the output of a shell command, and the arguments of commands that have them"
// configEntry configures the given button, of the command bar or of a
// menu, for the given entry: a category has the menu of its entries, and
// a command that of its subcommands (see [Commands.configCommand]).
func (cs *Commands) configEntry(w *core.Button, en *Entry, run RunFunc) {
w.SetText(en.Label())
if en.IsCategory() {
w.SetIcon(icons.Folder).SetTooltip(en.Label())
w.SetMenu(func(m *core.Scene, _ image.Point) { cs.menu(m, en.Children, run) })
return
}
if en.Script != nil {
w.Menu = nil
configScript(w, en.Script)
w.SetText(en.Label())
return
}
cs.configCommand(w, en.Command, run)
}
// configCommand configures the given button for the given command or
// subcommand: a command with subcommands, such as git, has the menu of
// them, as does a subcommand with subcommands, such as git stash, and
// otherwise clicking it shows the form of the command (see
// [Commands.RunDialog], which the caller does on a click without a menu).
// A command is parsed when it is first clicked, if it has not been parsed
// yet, and its menu shown if it has subcommands.
func (cs *Commands) configCommand(w *core.Button, cmd string, run RunFunc) {
w.SetIcon(icons.Terminal)
w.Menu = nil
root, name := splitCmd(cmd)
tip := cmd
if cm := cs.cached(root); cm != nil {
if name == "" && (cm.HasSubCmds() || len(cm.Macros) > 0 || len(cm.Scripts) > 0) {
w.SetTooltip(tooltip(root, cm.Doc))
w.SetMenu(func(m *core.Scene, _ image.Point) { cs.subCmdsMenu(m, root, run) })
return
}
if sc := cm.SubCmd(cmp.Or(name, MainName)); sc != nil {
tip = tooltip(cmd, cmp.Or(sc.Doc, cm.Doc))
if len(sc.Cmds) > 0 {
w.SetTooltip(tip)
w.SetMenu(func(m *core.Scene, _ image.Point) { cs.nestedMenu(m, sc, run) })
return
}
}
}
w.SetTooltip(tip)
}
// tooltip returns the tooltip of the given command with the given
// documentation, as markup.
func tooltip(cmd, doc string) string {
if doc == "" {
return html.EscapeString(cmd)
}
return html.EscapeString(cmd + ": " + doc)
}
// commandButton adds a button for the given command or subcommand to the
// given menu, with the given text (see [Commands.configCommand]).
func (cs *Commands) commandButton(m *core.Scene, text, cmd string, run RunFunc) {
b := core.NewButton(m).SetText(text)
cs.configCommand(b, cmd, run)
b.OnClick(func(e events.Event) {
if b.Menu == nil {
cs.RunDialog(b, cmd, run)
}
})
}
// menu adds the buttons of the given entries to the given menu: a category
// has a submenu of its entries, and a command with subcommands a submenu
// of them.
func (cs *Commands) menu(m *core.Scene, ens []*Entry, run RunFunc) {
if len(ens) == 0 {
core.NewText(m).SetText("(no commands)")
return
}
for _, en := range ens {
if en.IsCategory() {
b := core.NewButton(m)
cs.configEntry(b, en, run)
continue
}
if s := en.Script; s != nil {
b := core.NewButton(m)
cs.configEntry(b, en, run)
cs.scriptContextMenu(b, "", func() *Script { return s })
b.OnClick(func(e events.Event) { cs.RunScript(b, "", s, run) })
continue
}
cs.commandButton(m, en.Label(), en.Command, run)
}
}
// subCmdsMenu adds the buttons of the subcommands of the given command,
// such as git, to the given menu: those of the command, not the nested
// ones (see [Commands.nestedMenu]), after its macros (see [Macro]) and
// scripts (see [Script]), or the command itself, if it has none, followed
// by a submenu to make and edit its scripts. If the command has [Entry.Common]
// subcommands, they are in the menu, followed by a submenu of the others,
// sorted by name. Otherwise, the subcommands of the first group (see
// [SubCmd.Group]) are in the menu, and those of the others in submenus
// after them.
func (cs *Commands) subCmdsMenu(m *core.Scene, root string, run RunFunc) {
cm := cs.cached(root)
if cm == nil {
return
}
cs.macrosMenu(m, cm, run)
cs.scriptsMenu(m, cm, run)
defer func() {
core.NewSeparator(m)
cs.editScriptsMenu(m, cm)
}()
if !cm.HasSubCmds() { // the command itself
// (its form, not the menu of its macros, which this is)
b := core.NewButton(m).SetText(label(root)).SetIcon(icons.Terminal).SetTooltip(tooltip(root, cm.Doc))
b.OnClick(func(e events.Event) { cs.RunDialog(b, root+" "+MainName, run) })
return
}
var subs []*SubCmd
for _, sc := range cm.SubCmds {
if !strings.Contains(sc.Name, " ") { // not nested
subs = append(subs, sc)
}
}
add := func(m *core.Scene, scs []*SubCmd) {
for _, sc := range scs {
cs.commandButton(m, sc.Label(), sc.Cmd, run)
}
}
submenu := func(text string, scs []*SubCmd) {
b := core.NewButton(m).SetText(text).SetIcon(icons.Folder)
b.SetMenu(func(sm *core.Scene, _ image.Point) { add(sm, scs) })
}
var top, rest []*SubCmd
if common := strings.Fields(cs.common(root)); len(common) > 0 {
rest = slices.Clone(subs)
for _, name := range common {
if i := slices.IndexFunc(rest, func(sc *SubCmd) bool { return sc.Name == name }); i >= 0 {
top = append(top, rest[i])
rest = slices.Delete(rest, i, i+1)
}
}
}
if len(top) > 0 { // (otherwise, as without common subcommands)
subs = rest
add(m, top)
if len(subs) > 0 {
slices.SortFunc(subs, func(a, b *SubCmd) int { return strings.Compare(a.Name, b.Name) })
core.NewSeparator(m)
submenu("More", subs)
}
return
}
var groups []string
byGroup := map[string][]*SubCmd{}
for _, sc := range subs {
if _, ok := byGroup[sc.Group]; !ok {
groups = append(groups, sc.Group)
}
byGroup[sc.Group] = append(byGroup[sc.Group], sc)
}
for i, g := range groups {
if i == 0 {
add(m, byGroup[g])
continue
}
if i == 1 {
core.NewSeparator(m)
}
submenu(cmp.Or(g, "Other"), byGroup[g])
}
}
// common returns the [Entry.Common] subcommands of the first entry of the
// given command, such as git, if any.
func (cs *Commands) common(root string) string {
var find func(ens []*Entry) string
find = func(ens []*Entry) string {
for _, en := range ens {
if en.Command == root && en.Common != "" {
return en.Common
}
if c := find(en.Children); c != "" {
return c
}
}
return ""
}
cs.mu.Lock()
defer cs.mu.Unlock()
return find(cs.Entries)
}
// nestedMenu adds the buttons of the given subcommand, such as git stash,
// and of its subcommands, such as git stash list, to the given menu.
func (cs *Commands) nestedMenu(m *core.Scene, sc *SubCmd, run RunFunc) {
b := core.NewButton(m).SetText(sc.Label()).SetIcon(icons.Terminal).SetTooltip(tooltip(sc.Cmd, sc.Doc))
b.OnClick(func(e events.Event) { cs.RunDialog(b, sc.Cmd, run) })
core.NewSeparator(m)
for _, sub := range sc.Cmds {
cs.commandButton(m, label(sub.Cmd), sub.Cmd, run)
}
}
// Edit opens the editor of the commands, a [core.TreeTable] of them in a new
// window, in which they are saved as they are edited.
func (cs *Commands) Edit(ctx core.Widget) {
if core.RecycleMainWindow(&cs.Entries) {
return
}
b := core.NewBody("Commands")
b.SetData(&cs.Entries)
tt := core.NewTreeTable(b)
tt.SetDragMoves(true)
tt.SetItems(&cs.Entries)
tt.OnChange(func(e events.Event) { cs.Changed(tt) })
// the script of an entry is edited in its own editor
selectedScript := func() *Script {
if en := selectedEntry(tt); en != nil {
return en.Script
}
return nil
}
editScript := func() bool {
s := selectedScript()
if s != nil {
cs.EditScript(tt, "", s)
}
return s != nil
}
tt.AddContextMenu(func(m *core.Scene, _ image.Point) {
if selectedScript() == nil {
return
}
core.NewSeparator(m)
core.NewButton(m).SetText("Edit script").SetIcon(icons.Code).OnClick(func(e events.Event) { editScript() })
})
tt.OnDoubleClick(func(e events.Event) { editScript() })
cs.views.Lock()
cs.views.editor = tt
cs.views.Unlock()
b.OnClose(func(e events.Event) {
cs.views.Lock()
if cs.views.editor == tt {
cs.views.editor = nil
}
cs.views.Unlock()
go cs.ParseAll() // for new commands
})
b.AddTopBar(func(bar *core.Frame) {
core.NewToolbar(bar).Maker(func(p *tree.Plan) {
tree.Add(p, func(w *core.Button) {
w.SetText("Add category").SetIcon(icons.CreateNewFolder).SetTooltip("Add a category of commands at the end")
w.OnClick(func(e events.Event) {
cs.Entries = append(cs.Entries, &Entry{Name: "New category"})
tt.Update()
cs.Changed(tt)
})
})
tree.Add(p, func(w *core.Button) {
w.SetText("Add command").SetIcon(icons.Add).SetTooltip("Add a command at the end, such as git log, to be entered")
w.OnClick(func(e events.Event) {
cs.Entries = append(cs.Entries, &Entry{Name: "New command"})
tt.Update()
cs.Changed(tt)
})
})
tree.Add(p, func(w *core.Button) {
w.SetText("Edit script").SetIcon(icons.Edit).SetTooltip("Edit the script of the selected entry (or double-click it, or use its context menu)")
w.OnClick(func(e events.Event) {
if !editScript() {
core.MessageSnackbar(w, "Select the entry of a script to edit it")
}
})
})
tree.Add(p, func(w *core.Button) {
w.SetText("Add script").SetIcon(icons.Code).SetTooltip("Add a script at the end, written in its editor, for things that are more than a command line")
w.OnClick(func(e events.Event) { cs.NewScript(w, "", "") })
})
tree.Add(p, func(w *core.Button) {
w.SetText("Choosers").SetIcon(icons.List).SetTooltip(chooserTip)
w.OnClick(func(e events.Event) { cs.EditChoosers(w) })
})
tree.Add(p, func(w *core.Button) {
w.SetText("Reset").SetIcon(icons.Reset).SetTooltip("Replace the commands with the standard ones")
w.OnClick(func(e events.Event) {
d := core.NewBody("Reset commands")
core.NewText(d).SetType(core.TextSupporting).SetText("Replace all of the commands and categories with the standard ones?")
d.AddBottomBar(func(bar *core.Frame) {
d.AddCancel(bar)
d.AddOK(bar).SetText("Reset").OnClick(func(e events.Event) {
cs.Entries = Standard()
tt.Update()
cs.Changed(tt)
})
})
d.RunDialog(w)
})
})
})
})
b.RunWindow()
}
// selectedEntry returns the selected entry of the given editor of the
// commands, or nil if there is none.
func selectedEntry(tt *core.TreeTable) *Entry {
rows := reflect.ValueOf(tt.Slice)
if rows.Kind() == reflect.Pointer {
rows = rows.Elem()
}
if i := tt.SelectedIndex; rows.Kind() == reflect.Slice && i >= 0 && i < rows.Len() {
en, _ := reflect.TypeAssert[*Entry](rows.Index(i))
return en
}
return nil
}
// RunDialog shows the form of the flags and arguments of the given
// subcommand, such as "git commit", or command without subcommands, such
// as "ls", once its help is parsed, which runs the resulting command line
// with the given function. For a command with subcommands, such as git, it
// shows the menu of its subcommands, as the menu of the given widget.
func (cs *Commands) RunDialog(ctx core.Widget, cmd string, run RunFunc) {
ctx = cs.context(ctx)
if sc := cs.cachedSub(cmd); sc != nil {
cs.runDialog(ctx, sc, run)
return
}
core.MessageSnackbar(ctx, "Reading the help of "+cmd+"...")
go func() {
root, name := splitCmd(cmd)
cm, err := cs.Cmd(root, NoReparse)
var sc *SubCmd
if err == nil && (name != "" || !cm.HasSubCmds() && len(cm.Macros) == 0 && len(cm.Scripts) == 0) {
sc, err = cs.SubCmd(cmd, NoReparse)
}
cs.updateViews(nil)
ctx.AsWidget().AsyncLock()
defer ctx.AsWidget().AsyncUnlock()
switch {
case err != nil:
core.ErrorSnackbar(ctx, err)
case sc == nil: // the menu of the subcommands
core.NewMenu(func(m *core.Scene, _ image.Point) { cs.subCmdsMenu(m, root, run) }, ctx, ctx.AsWidget().ContextMenuPos(nil)).Run()
default:
cs.runDialog(ctx, sc, run)
}
}()
}
// runDialog shows the form of the given subcommand (see [Commands.RunDialog]).
func (cs *Commands) runDialog(ctx core.Widget, sc *SubCmd, run RunFunc) {
runDialog(cs.NewDialog(ctx, sc, run), ctx)
}
// NewDialog returns the body of the dialog of the form of the given
// subcommand (see [Commands.RunDialog]), in the context of the given
// widget, which runs the command line with the given function. The form
// starts with the arguments last used for the subcommand, which are saved
// when it is run (see [Args]).
func (cs *Commands) NewDialog(ctx core.Widget, sc *SubCmd, run RunFunc) *core.Body {
ctx = cs.context(ctx)
d := core.NewBody(sc.Cmd)
if sc.Doc != "" {
core.NewText(d).SetType(core.TextSupporting).SetText(html.EscapeString(sc.Doc))
}
if sc.Usage != "" {
core.NewText(d).SetType(core.TextSupporting).SetText(html.EscapeString(sc.Usage)).Styler(func(s *styles.Style) {
s.Font.Family = rich.Monospace
})
}
values := sc.FormStruct()
if cs.Args != nil {
cs.Args.SetValues(sc, values)
}
line := core.NewText(d)
line.Styler(func(s *styles.Style) {
s.Font.Family = rich.Monospace
s.Grow.Set(1, 0)
})
line.Updater(func() { line.SetText(html.EscapeString(sc.CommandLine(values))) })
fm := cs.chooserForm(ctx, d, values, cs.subCmdChoosers(sc))
fm.OnChange(func(e events.Event) { line.Update() })
fm.OnInput(func(e events.Event) { line.Update() })
d.AddTopBar(func(bar *core.Frame) {
core.NewToolbar(bar).Maker(func(p *tree.Plan) {
if len(sc.Cmds) > 0 {
tree.Add(p, func(w *core.Button) {
w.SetText("Subcommands").SetIcon(icons.Menu)
w.SetMenu(func(m *core.Scene, _ image.Point) {
for _, sub := range sc.Cmds {
core.NewButton(m).SetText(sub.Cmd).SetTooltip(html.EscapeString(sub.Doc)).OnClick(func(e events.Event) {
d.Close()
cs.RunDialog(ctx, sub.Cmd, run)
})
}
})
})
}
root, _ := splitCmd(sc.Cmd)
cs.macrosButton(p, d, ctx, root, sc, run)
tree.Add(p, func(w *core.Button) {
w.SetText("Choosers").SetIcon(icons.List)
w.SetTooltip("Set the choosers of the arguments, such as a git branch, whose values are chosen from the output of a shell command")
w.SetMenu(func(m *core.Scene, _ image.Point) { cs.choosersMenu(m, ctx, sc, fm) })
})
tree.Add(p, func(w *core.Button) {
w.SetText("Clear").SetIcon(icons.ClearAll).SetTooltip("Clear the flags and arguments")
w.OnClick(func(e events.Event) {
reflect.ValueOf(values).Elem().SetZero()
fm.Update()
line.Update()
})
})
tree.Add(p, func(w *core.Button) {
w.SetText("Reread help").SetIcon(icons.Refresh).SetTooltip(html.EscapeString("Read the help of the command again, as for a new version (from " + sc.Source + ")"))
w.OnClick(func(e events.Event) {
go func() {
nsc, err := cs.SubCmd(sc.Cmd, Reparse)
ctx.AsWidget().AsyncLock()
defer ctx.AsWidget().AsyncUnlock()
if err != nil {
core.ErrorSnackbar(ctx, err)
return
}
d.Close()
cs.runDialog(ctx, nsc, run)
}()
})
})
})
})
d.AddBottomBar(func(bar *core.Frame) {
d.AddCancel(bar)
core.NewButton(bar).SetType(core.ButtonOutlined).SetText("New macro").SetIcon(icons.Add).
SetTooltip("Make a macro of the command with these values, at the top of the menu of the command, which can prompt for some of them").
OnClick(func(e events.Event) {
root, _ := splitCmd(sc.Cmd)
mc := &Macro{SubCmd: sc.Name, Values: sc.ArgsOf(values)}
d.Close()
runDialog(cs.NewMacroDialog(ctx, root, sc, mc, nil, run), ctx)
})
core.NewButton(bar).SetType(core.ButtonOutlined).SetText("New script").SetIcon(icons.Code).
SetTooltip("Make a script of the command, starting with this command line, in the menu of the command, for things that are more than a command line").
OnClick(func(e events.Event) {
root, _ := splitCmd(sc.Cmd)
d.Close()
cs.NewScript(ctx, root, NewScriptCode[:len(NewScriptCode)-1]+sc.CommandLine(values)+"\n")
})
d.AddOK(bar).SetText("Run").SetIcon(icons.PlayArrow).OnClick(func(e events.Event) {
if cs.Args != nil {
errors.Log(cs.Args.Set(sc, values))
}
run(sc.CommandLine(values))
})
})
return d
}
// argsField is the name of the field of the arguments in the
// [SubCmd.FormStruct].
const argsField = "Arguments"
// fieldNames returns the names of the fields of the forms of the
// subcommand (see [SubCmd.FormStruct]): [argsField] for the other
// arguments, and then one for each flag, which are unique.
func (cm *SubCmd) fieldNames() []string {
names := []string{argsField}
used := map[string]bool{argsField: true, macroNameField: true, macroConfirmField: true}
for _, fl := range cm.Flags {
name := fieldName(fl.Name)
for i := 2; used[name]; i++ {
name = fieldName(fl.Name) + strconv.Itoa(i)
}
used[name] = true
names = append(names, name)
}
return names
}
// argKey returns the key of the argument of the given index in the
// [SubCmd.fieldNames]: [argsField] for the other arguments, and the name
// of the flag for the others, as in [SubCmdArgs.Flags] and
// [Macro.Prompts].
func (cm *SubCmd) argKey(i int) string {
if i == 0 {
return argsField
}
return cm.Flags[i-1].Name
}
// argField returns the struct field of the form of the argument of the
// given index in the [SubCmd.fieldNames], with the given type, and with
// the given extra tags.
func (cm *SubCmd) argField(i int, name string, typ reflect.Type, tags string) reflect.StructField {
if i == 0 {
return reflect.StructField{Name: name, Type: typ,
Tag: reflect.StructTag(`doc:"The other arguments of the command, such as files and paths, as typed in a shell"` + tags)}
}
fl := cm.Flags[i-1]
// (the label and doc are shown as markup)
tag := `label:` + strconv.Quote(html.EscapeString(fl.Label())) + ` doc:` + strconv.Quote(html.EscapeString(fl.Doc)) + tags
return reflect.StructField{Name: name, Type: typ, Tag: reflect.StructTag(tag)}
}
// argType returns the type of the value of the argument of the given index
// in the [SubCmd.fieldNames]: bool for a flag without a value, and
// otherwise string.
func (cm *SubCmd) argType(i int) reflect.Type {
if i > 0 && cm.Flags[i-1].IsBool() {
return reflect.TypeFor[bool]()
}
return reflect.TypeFor[string]()
}
// FormStruct returns a pointer to a new struct for a form of the flags of
// the command: a field for the other arguments, and a bool or string field
// for each flag, labeled with its names, with its documentation.
func (cm *SubCmd) FormStruct() any {
return cm.formStruct(nil)
}
// formStruct returns a pointer to a new struct for a form of the flags of
// the command (see [SubCmd.FormStruct]), with only the arguments whose keys
// (see [SubCmd.argKey]) are in the given set, if it is not nil.
func (cm *SubCmd) formStruct(keys map[string]bool) any {
var fields []reflect.StructField
for i, name := range cm.fieldNames() {
if keys != nil && !keys[cm.argKey(i)] {
continue
}
fields = append(fields, cm.argField(i, name, cm.argType(i), ` immediate:"+"`))
}
return reflect.New(reflect.StructOf(fields)).Interface()
}
// fieldName returns an exported Go field name for the given flag name.
func fieldName(flag string) string {
name := strcase.ToCamel(strings.Map(func(r rune) rune {
if unicode.IsLetter(r) || unicode.IsDigit(r) {
return r
}
return '-'
}, strings.TrimLeft(flag, "-")))
if name == "" || !unicode.IsUpper(rune(name[0])) {
name = "F" + name
}
return name
}
// valueField returns the field of the value of the argument of the given
// field name in the given values of a form of a subcommand, which is
// invalid if there is none: the field itself, or the value field of the
// field of a [SubCmd.MacroStruct].
func valueField(values any, name string) reflect.Value {
f := reflect.ValueOf(values).Elem().FieldByName(name)
if f.Kind() == reflect.Struct {
f = f.FieldByName(macroValueField)
}
return f
}
// ArgsOf returns the arguments of the given values of a form of the
// subcommand (see [SubCmd.FormStruct] and [SubCmd.MacroStruct]): only those
// that are used.
func (cm *SubCmd) ArgsOf(values any) *SubCmdArgs {
sa := &SubCmdArgs{}
for i, name := range cm.fieldNames() {
f := valueField(values, name)
val := ""
switch f.Kind() {
case reflect.Bool:
if f.Bool() {
val = "true"
}
case reflect.String:
val = f.String()
}
switch {
case i == 0:
sa.Args = val
case val != "":
if sa.Flags == nil {
sa.Flags = map[string]string{}
}
sa.Flags[cm.argKey(i)] = val
}
}
return sa
}
// SetValues sets the given values of a form of the given subcommand (see
// [SubCmd.FormStruct] and [SubCmd.MacroStruct]) to the arguments, for
// those it has.
func (sa *SubCmdArgs) SetValues(cm *SubCmd, values any) {
if sa == nil {
return
}
for i, name := range cm.fieldNames() {
f := valueField(values, name)
if !f.IsValid() {
continue
}
val := sa.Args
if i > 0 {
var ok bool
if val, ok = sa.Flags[cm.argKey(i)]; !ok {
continue
}
}
switch f.Kind() {
case reflect.Bool:
b, _ := strconv.ParseBool(val)
f.SetBool(b)
case reflect.String:
f.SetString(val)
}
}
}
// CommandLine returns the command line for the given values of a form of
// the command made by [SubCmd.FormStruct]: the command, the flags that are
// on or have values, and the other arguments.
func (cm *SubCmd) CommandLine(values any) string {
return cm.ArgsCommandLine(cm.ArgsOf(values))
}
// ArgsCommandLine returns the command line for the given arguments: the
// command, the flags that are on or have values, and the other arguments.
func (cm *SubCmd) ArgsCommandLine(sa *SubCmdArgs) string {
words := []string{cm.Cmd}
for _, fl := range cm.Flags {
val, ok := sa.Flags[fl.Name]
switch {
case !ok || val == "":
case fl.IsBool():
if b, _ := strconv.ParseBool(val); b {
words = append(words, fl.Arg(""))
}
default:
words = append(words, fl.Arg(val))
}
}
if args := strings.TrimSpace(sa.Args); args != "" {
words = append(words, args)
}
return strings.Join(words, " ")
}
// DialogMinSize is the minimum initial size of the dialogs of the commands,
// in dp: wide enough for the layout of forms on a desktop, with one line
// per field, rather than that of a phone.
var DialogMinSize = math32.Vec2(720, 0)
// runDialog runs the given dialog in a new window, in the context of the
// given widget, with the [DialogMinSize].
func runDialog(d *core.Body, ctx core.Widget) {
d.NewWindowDialog(ctx).SetMinSize(DialogMinSize).Run()
}
// context returns the context widget to use for the dialogs and snackbars
// of the commands, which lasts beyond the given one: the scene of the
// window of an item of a menu (which closes when it is clicked), or else
// the given widget, or a command bar if it is gone.
func (cs *Commands) context(ctx core.Widget) core.Widget {
if live(ctx) {
if st := ctx.AsWidget().Scene.Stage; st.Type == core.MenuStage && st.Main != nil && st.Main.Scene != nil {
return st.Main.Scene
}
return ctx
}
cs.views.Lock()
defer cs.views.Unlock()
for _, tb := range cs.views.bars {
if live(tb) {
return tb
}
}
return ctx
}
// live returns whether the given widget is shown in a stage that is
// running: not deleted, as an item of a closed menu is.
func live(w core.Widget) bool {
if w == nil {
return false
}
wb := w.AsWidget()
return wb != nil && wb.This != nil && wb.Scene != nil && wb.Scene.Stage != nil && wb.Scene.Stage.Mains != nil
}
// newForm adds a form of the given values to the given dialog, whose
// fields are wide (see [styleFormFields]), with the first one in focus
// (see [focusForm]).
func newForm(d *core.Body, values any) *core.Form {
return newChooserForm(d, values, nil)
}
// newChooserForm returns a form as [newForm], whose text fields have a
// button with a menu of the values of their chooser, given by the given
// function, if it is not nil, for those that have one.
func newChooserForm(d *core.Body, values any, chooser func(tf *core.TextField)) *core.Form {
fm := core.NewForm(d)
styleFormFields(fm, chooser)
fm.SetStruct(values)
focusForm(d, fm)
return fm
}
// chooserForm returns a form as [newForm] of the given values, whose text
// fields have a button with a menu of the values of the chooser given by
// the given function, for those that have one (see [Chooser]), run in the
// directory of the given context widget.
func (cs *Commands) chooserForm(ctx core.Widget, d *core.Body, values any, chooser chooserFunc) *core.Form {
return newChooserForm(d, values, func(tf *core.TextField) {
if field := formFieldName(tf); field != "" {
cs.addChooserButton(ctx, tf, field, chooser)
}
})
}
// FieldMinWidth is the minimum width of the text fields of the forms of
// the commands, in ch; they grow with the window (as text fields in forms
// have no maximum width).
var FieldMinWidth float32 = 60
// styleFormFields makes the text fields of the given form, and of its
// inline forms (as of the arguments of a macro), at least [FieldMinWidth]
// wide, calling the given function with those of the form itself, if it
// is not nil.
func styleFormFields(fm *core.Form, textField func(tf *core.TextField)) {
fm.SetOnChildAdded(func(n tree.Node) {
switch w := n.(type) {
case *core.TextField:
w.Styler(func(s *styles.Style) {
s.Min.X.Ch(FieldMinWidth)
})
if textField != nil {
textField(w)
}
case *core.Form:
styleFormFields(w, nil)
}
})
}
// focusForm makes the first field of the given form of the given dialog
// the one in focus when it is shown, rather than the first button of its
// top bar: such as the first argument prompted for by a macro.
func focusForm(d *core.Body, fm *core.Form) {
fm.Update() // (makes the fields)
var first core.Widget
for cw := range fm.AllWidgets() {
switch cw.(type) {
case *core.TextField, *core.Switch, *core.Spinner, *core.Chooser:
first = cw
}
if first != nil {
break
}
}
if first != nil {
d.Scene.Events.SetStartFocus(first)
}
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package commands
import (
"html"
"image"
"maps"
"reflect"
"slices"
"strings"
"unicode"
"unicode/utf8"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/styles"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/tree"
)
// Macro is a version of a subcommand with values for its arguments, some
// of which are prompted for when it is run, such as git commit with
// flags that are always used, prompting for the message. The macros of a
// command are at the top of the menu of its subcommands (see [Cmd.Macros]).
type Macro struct {
// Name is the name of the macro, which is after the command and the
// subcommand in its label: "Git commit wip" (see [Macro.Label]). It can
// be empty, for the default version of the subcommand.
Name string `json:",omitempty"`
// SubCmd is the name of the subcommand: "commit", or [MainName].
SubCmd string
// Values are the values of the arguments, which are used when the
// macro runs, other than those prompted for, which they are the
// defaults of.
Values *SubCmdArgs `json:",omitempty"`
// Confirm is whether the command line of the macro is shown for
// confirmation before it runs, even if nothing is prompted for, as for
// commands that cannot be undone.
Confirm bool `json:",omitempty"`
// Prompts are the arguments that are prompted for when the macro runs,
// by key: the names of flags ("--message"), and [argsField] for the
// other arguments.
Prompts []string `json:",omitempty"`
}
// Cmd returns the command line of the subcommand of the macro of the given
// command, such as "git commit" for git.
func (mc *Macro) Cmd(root string) string {
if mc.SubCmd == MainName || mc.SubCmd == "" {
return root
}
return root + " " + mc.SubCmd
}
// Label returns the text shown for the macro of the given command: its
// command line and its name, starting with an uppercase letter, such as
// "Git commit wip".
func (mc *Macro) Label(root string) string {
s := strings.TrimSpace(mc.Cmd(root) + " " + mc.Name)
r, n := utf8.DecodeRuneInString(s)
return string(unicode.ToUpper(r)) + s[n:]
}
// IsPrompt returns whether the argument of the given key (see [Macro.Prompts])
// is prompted for when the macro runs.
func (mc *Macro) IsPrompt(key string) bool {
return slices.Contains(mc.Prompts, key)
}
// same returns whether the given macro is the same as this one: of the
// same subcommand, with the same name.
func (mc *Macro) same(o *Macro) bool {
return o != nil && mc.SubCmd == o.SubCmd && mc.Name == o.Name
}
// Macro returns the macro of the given command, such as git, with the
// given subcommand ("commit", or [MainName]) and name, or nil if there is
// none.
func (cs *Commands) Macro(root, sub, name string) *Macro {
cm := cs.cached(root)
if cm == nil {
return nil
}
want := &Macro{SubCmd: sub, Name: name}
if i := slices.IndexFunc(cm.Macros, want.same); i >= 0 {
return cm.Macros[i]
}
return nil
}
// promptFlag is whether an argument of a [SubCmd.MacroStruct] is prompted
// for when the macro runs, which is shown as a checkbox.
type promptFlag bool
// Widget returns a checkbox for the flag.
func (pf *promptFlag) Widget() core.Value {
return core.NewSwitch().SetType(core.SwitchCheckbox)
}
const (
// macroNameField and macroConfirmField are the names of the fields of
// the name of the macro, and of whether it is confirmed, in a
// [SubCmd.MacroStruct].
macroNameField = "Name"
macroConfirmField = "Confirm"
// macroPromptField and macroValueField are the names of the fields of
// the struct of each argument in a [SubCmd.MacroStruct].
macroPromptField = "Prompt"
macroValueField = "Value"
)
// MacroStruct returns a pointer to a new struct for the form of a macro of
// the subcommand: a field for the name of the macro, and then a field for
// each argument of the [SubCmd.FormStruct], with a checkbox of whether it
// is prompted for when the macro runs, followed by its value.
func (cm *SubCmd) MacroStruct() any {
fields := []reflect.StructField{{
Name: macroNameField, Type: reflect.TypeFor[string](),
Tag: `immediate:"+" doc:"The name of the macro, after the command in its label, which can be empty for the default version of the command"`,
}, {
Name: macroConfirmField, Type: reflect.TypeFor[bool](),
Tag: `doc:"Whether the command line is shown for confirmation before it runs, even if nothing is prompted for, as for commands that cannot be undone"`,
}}
for i, name := range cm.fieldNames() {
arg := reflect.StructOf([]reflect.StructField{
{Name: macroPromptField, Type: reflect.TypeFor[promptFlag](),
Tag: `label:"" doc:"if checked, this will be prompted for when the macro runs"`},
{Name: macroValueField, Type: cm.argType(i), Tag: `label:"" immediate:"+"`},
})
fields = append(fields, cm.argField(i, name, arg, ` display:"inline"`))
}
return reflect.New(reflect.StructOf(fields)).Interface()
}
// MacroOf returns the macro of the given values of the form of a macro of
// the subcommand (see [SubCmd.MacroStruct]).
func (cm *SubCmd) MacroOf(values any) *Macro {
v := reflect.ValueOf(values).Elem()
mc := &Macro{SubCmd: cm.Name, Values: cm.ArgsOf(values)}
mc.Name = strings.TrimSpace(v.FieldByName(macroNameField).String())
mc.Confirm = v.FieldByName(macroConfirmField).Bool()
for i, name := range cm.fieldNames() {
if v.FieldByName(name).FieldByName(macroPromptField).Bool() {
mc.Prompts = append(mc.Prompts, cm.argKey(i))
}
}
return mc
}
// SetMacroValues sets the given values of the form of a macro of the
// subcommand (see [SubCmd.MacroStruct]) to those of the given macro.
func (cm *SubCmd) SetMacroValues(mc *Macro, values any) {
v := reflect.ValueOf(values).Elem()
v.FieldByName(macroNameField).SetString(mc.Name)
v.FieldByName(macroConfirmField).SetBool(mc.Confirm)
mc.Values.SetValues(cm, values)
for i, name := range cm.fieldNames() {
v.FieldByName(name).FieldByName(macroPromptField).SetBool(mc.IsPrompt(cm.argKey(i)))
}
}
// promptKeys returns the set of the keys of the arguments that are
// prompted for when the macro runs.
func (mc *Macro) promptKeys() map[string]bool {
keys := map[string]bool{}
for _, k := range mc.Prompts {
keys[k] = true
}
return keys
}
// withPrompted returns the values of the macro, with those of the given
// keys from the given values of the form of its prompts.
func (mc *Macro) withPrompted(prompted *SubCmdArgs, keys map[string]bool) *SubCmdArgs {
sa := &SubCmdArgs{Flags: map[string]string{}}
if mc.Values != nil {
sa.Args = mc.Values.Args
maps.Copy(sa.Flags, mc.Values.Flags)
}
for k := range keys {
if k == argsField {
sa.Args = prompted.Args
continue
}
delete(sa.Flags, k)
if v, ok := prompted.Flags[k]; ok {
sa.Flags[k] = v
}
}
return sa
}
// SaveMacro saves the given macro of the given command, such as git, in
// place of the given old one, if it is not nil, and otherwise as a new one
// (in place of one of the same subcommand and name), updating the command
// bars.
func (cs *Commands) SaveMacro(root string, mc, old *Macro) error {
err := cs.update(func() {
cm := cs.Parsed[root]
if cm == nil {
cm = &Cmd{Cmd: root}
cs.Parsed[root] = cm
}
i := slices.IndexFunc(cm.Macros, func(o *Macro) bool { return o.same(old) })
if i < 0 {
i = slices.IndexFunc(cm.Macros, func(o *Macro) bool { return o.same(mc) })
}
if i >= 0 {
cm.Macros[i] = mc
} else {
cm.Macros = append(cm.Macros, mc)
}
})
cs.updateViews(nil)
return err
}
// DeleteMacro deletes the given macro of the given command, such as git,
// updating the command bars.
func (cs *Commands) DeleteMacro(root string, mc *Macro) error {
err := cs.update(func() {
if cm := cs.Parsed[root]; cm != nil {
cm.Macros = slices.DeleteFunc(cm.Macros, func(o *Macro) bool { return o.same(mc) })
}
})
cs.updateViews(nil)
return err
}
// macroSubCmd returns the parsed subcommand of the given macro of the
// given command, parsing it in the background if needed, and calling the
// given function with it, with the lock of the given context widget.
func (cs *Commands) macroSubCmd(ctx core.Widget, root string, mc *Macro, fun func(sc *SubCmd)) {
ctx = cs.context(ctx)
cmd := mc.Cmd(root)
if sc := cs.cachedSub(cmd); sc != nil {
fun(sc)
return
}
core.MessageSnackbar(ctx, "Reading the help of "+cmd+"...")
go func() {
sc, err := cs.SubCmd(cmd, NoReparse)
ctx.AsWidget().AsyncLock()
defer ctx.AsWidget().AsyncUnlock()
if err != nil {
core.ErrorSnackbar(ctx, err)
return
}
fun(sc)
}()
}
// RunMacro runs the given macro of the given command, such as git, with
// the given function, after prompting for the arguments it prompts for,
// if any, in a dialog in the context of the given widget, or else after
// confirming it, if it is to be confirmed (see [Macro.Confirm]).
func (cs *Commands) RunMacro(ctx core.Widget, root string, mc *Macro, run RunFunc) {
ctx = cs.context(ctx)
cs.macroSubCmd(ctx, root, mc, func(sc *SubCmd) {
if len(mc.Prompts) == 0 {
cmdline := sc.ArgsCommandLine(mc.withPrompted(nil, nil))
if !mc.Confirm {
cs.runMacroLine(root, mc, cmdline, run)
return
}
d := core.NewBody(mc.Label(root))
core.NewText(d).SetType(core.TextSupporting).SetText("Run this command?")
commandLineText(d, func() string { return cmdline })
d.AddBottomBar(func(bar *core.Frame) {
d.AddCancel(bar)
d.AddOK(bar).SetText("Run").SetIcon(icons.PlayArrow).OnClick(func(e events.Event) {
cs.runMacroLine(root, mc, cmdline, run)
})
})
d.RunDialog(ctx)
return
}
runDialog(cs.NewPromptDialog(ctx, root, sc, mc, run), ctx)
})
}
// runMacroLine runs the given command line of the given macro of the
// given command with the given function, recording it as that of the
// macro for its [Commands.Name].
func (cs *Commands) runMacroLine(root string, mc *Macro, cmdline string, run RunFunc) {
cs.names.Lock()
if cs.names.macros == nil {
cs.names.macros = map[string]string{}
}
cs.names.macros[cmdline] = strings.ToLower(mc.Label(root))
cs.names.Unlock()
run(cmdline)
}
// Name returns the name of the given command line, as for a tab of its
// output: the label of the macro that it was run by, if any, in lowercase,
// such as "git commit wip", or else its command and subcommand, such as
// "git commit" or "git stash list", without its arguments, if its command
// has been parsed, and otherwise its command and the words after it that
// could be subcommands (up to two lowercase words, before any flag).
func (cs *Commands) Name(cmdline string) string {
cs.names.Lock()
name, ok := cs.names.macros[cmdline]
cs.names.Unlock()
if ok {
return name
}
f := strings.Fields(cmdline)
if len(f) == 0 {
return ""
}
cm := cs.cached(f[0])
if cm == nil || !cm.IsParsed() {
words := f[:1]
for _, w := range f[1:] {
if len(words) == 3 || w[0] == '-' || strings.ContainsFunc(w, func(r rune) bool {
return !unicode.IsLower(r) && !unicode.IsDigit(r) && r != '-'
}) {
break
}
words = append(words, w)
}
return strings.Join(words, " ")
}
best := ""
for _, sc := range cm.SubCmds {
w := strings.Fields(sc.Name)
if sc.Name != MainName && len(w) > len(strings.Fields(best)) && len(w) < len(f) && slices.Equal(w, f[1:1+len(w)]) {
best = sc.Name
}
for _, sub := range sc.Cmds { // (not parsed yet)
_, sn := splitCmd(sub.Cmd)
w := strings.Fields(sn)
if len(w) > len(strings.Fields(best)) && len(w) < len(f) && slices.Equal(w, f[1:1+len(w)]) {
best = sn
}
}
}
return strings.TrimSpace(f[0] + " " + best)
}
// NewPromptDialog returns the body of the dialog that prompts for the
// arguments of the given macro of the given subcommand of the given
// command, which runs its command line with the given function.
func (cs *Commands) NewPromptDialog(ctx core.Widget, root string, sc *SubCmd, mc *Macro, run RunFunc) *core.Body {
ctx = cs.context(ctx)
d := core.NewBody(mc.Label(root))
keys := mc.promptKeys()
values := sc.formStruct(keys)
mc.Values.SetValues(sc, values)
cs.Args.MacroValues(root, mc).SetValues(sc, values)
cmdline := func() string {
return sc.ArgsCommandLine(mc.withPrompted(sc.ArgsOf(values), keys))
}
line := commandLineText(d, cmdline)
fm := cs.chooserForm(ctx, d, values, cs.subCmdChoosers(sc))
fm.OnChange(func(e events.Event) { line.Update() })
fm.OnInput(func(e events.Event) { line.Update() })
d.AddTopBar(func(bar *core.Frame) {
core.NewToolbar(bar).Maker(func(p *tree.Plan) {
tree.Add(p, func(w *core.Button) {
w.SetText("Edit macro").SetIcon(icons.Edit)
w.OnClick(func(e events.Event) {
d.Close()
runDialog(cs.NewMacroDialog(ctx, root, sc, mc, mc, run), ctx)
})
})
})
})
d.AddBottomBar(func(bar *core.Frame) {
d.AddCancel(bar)
d.AddOK(bar).SetText("Run").SetIcon(icons.PlayArrow).OnClick(func(e events.Event) {
errors.Log(cs.Args.SetMacroValues(root, mc, sc.ArgsOf(values), keys))
cs.runMacroLine(root, mc, cmdline(), run)
})
})
return d
}
// NewMacroDialog returns the body of the dialog of the form of the given
// macro of the given subcommand of the given command, such as a new macro
// with the values of its form, which saves it in place of the given old
// macro, if it is not nil, and otherwise as a new one. Its macros are run
// with the given function.
func (cs *Commands) NewMacroDialog(ctx core.Widget, root string, sc *SubCmd, mc, old *Macro, run RunFunc) *core.Body {
ctx = cs.context(ctx)
title := "New macro"
if old != nil {
title = "Edit macro"
}
d := core.NewBody(title + ": " + sc.Cmd)
core.NewText(d).SetType(core.TextSupporting).SetText("The values are used when the macro runs: those that are checked are prompted for, with these values as their defaults.")
values := sc.MacroStruct()
sc.SetMacroValues(mc, values)
line := commandLineText(d, func() string {
m := sc.MacroOf(values)
return m.Label(root) + ": " + sc.ArgsCommandLine(m.Values)
})
fm := newForm(d, values)
fm.OnChange(func(e events.Event) { line.Update() })
fm.OnInput(func(e events.Event) { line.Update() })
if old != nil {
d.AddTopBar(func(bar *core.Frame) {
core.NewToolbar(bar).Maker(func(p *tree.Plan) {
tree.Add(p, func(w *core.Button) {
w.SetText("Delete macro").SetIcon(icons.Delete)
w.OnClick(func(e events.Event) {
errors.Log(cs.DeleteMacro(root, old))
d.Close()
})
})
})
})
}
d.AddBottomBar(func(bar *core.Frame) {
d.AddCancel(bar)
d.AddOK(bar).SetText("Save").SetIcon(icons.Save).OnClick(func(e events.Event) {
nm := sc.MacroOf(values)
if err := cs.SaveMacro(root, nm, old); err != nil {
core.ErrorSnackbar(ctx, err)
return
}
core.MessageSnackbar(ctx, "Saved the macro "+nm.Label(root))
})
})
return d
}
// commandLineText adds a text of the command line given by the given
// function to the given body, which is updated with it.
func commandLineText(d *core.Body, cmdline func() string) *core.Text {
line := core.NewText(d)
line.Styler(func(s *styles.Style) {
s.Font.Family = rich.Monospace
s.Grow.Set(1, 0)
})
line.Updater(func() { line.SetText(html.EscapeString(cmdline())) })
return line
}
// macrosMenu adds the buttons of the macros of the given command, such as
// git, to the given menu, which run them with the given function, followed
// by a separator, if there are any.
func (cs *Commands) macrosMenu(m *core.Scene, cm *Cmd, run RunFunc) {
for _, mc := range cm.Macros {
b := core.NewButton(m).SetText(mc.Label(cm.Cmd)).SetIcon(icons.PlayArrow)
tip := "Run the macro"
if len(mc.Prompts) > 0 {
tip += ", prompting for " + strings.Join(mc.Prompts, ", ")
}
b.SetTooltip(html.EscapeString(tip))
b.OnClick(func(e events.Event) { cs.RunMacro(b, cm.Cmd, mc, run) })
}
if len(cm.Macros) > 0 {
core.NewSeparator(m)
}
}
// macrosButton adds a button with a menu of the macros of the given
// subcommand of the given command to the given plan, which opens their
// editors, if there are any.
func (cs *Commands) macrosButton(p *tree.Plan, d *core.Body, ctx core.Widget, root string, sc *SubCmd, run RunFunc) {
cm := cs.cached(root)
if cm == nil {
return
}
var mcs []*Macro
for _, mc := range cm.Macros {
if mc.SubCmd == sc.Name {
mcs = append(mcs, mc)
}
}
if len(mcs) == 0 {
return
}
tree.Add(p, func(w *core.Button) {
w.SetText("Macros").SetIcon(icons.Edit).SetTooltip("Edit the macros of " + sc.Cmd)
w.SetMenu(func(m *core.Scene, _ image.Point) {
for _, mc := range mcs {
core.NewButton(m).SetText(mc.Label(root)).OnClick(func(e events.Event) {
d.Close()
runDialog(cs.NewMacroDialog(ctx, root, sc, mc, mc, run), ctx)
})
}
})
})
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package commands
import (
"bytes"
"cmp"
"context"
"errors"
"fmt"
"os"
"os/exec"
"regexp"
"slices"
"strings"
"time"
"unicode"
)
// HelpTimeout is the time a help command can take before it is stopped.
var HelpTimeout = 10 * time.Second
// MaxHelpSize is the maximum size of the output of a help command, in
// bytes: a larger output is not help, but that of a command that does not
// take the help arguments as help, and runs.
var MaxHelpSize = 256 << 10
// ParseCmd returns the [Cmd] for the given command, such as git, parsed
// from the output of its help commands (see [Parse]), with its subcommands
// to be parsed when they are used, or else its one [MainName] subcommand,
// which is the command itself, parsed.
func ParseCmd(cmd string) (*Cmd, error) {
sc, err := Parse(cmd)
if err != nil {
return nil, err
}
cm := &Cmd{Cmd: sc.Cmd, Doc: sc.Doc}
if len(sc.Cmds) == 0 {
sc.Name = MainName
cm.SubCmds = []*SubCmd{sc}
return cm, nil
}
for _, sub := range sc.Cmds {
_, sub.Name = splitCmd(sub.Cmd)
cm.SubCmds = append(cm.SubCmds, sub)
}
return cm, nil
}
// Parse returns the [SubCmd] for the given command, such as "git commit",
// parsed from the output of its help commands: those of -h, --help, help,
// and man, as the commands have them. The flags are those of the output
// with the most flags, and the subcommands those of the output with the most
// subcommands, other than a man page, whose indented lists are not commands.
func Parse(cmd string) (*SubCmd, error) {
words := strings.Fields(cmd)
if len(words) == 0 {
return nil, errors.New("commands: no command to parse")
}
dir, err := os.MkdirTemp("", "commands-help")
if err != nil {
return nil, err
}
defer os.RemoveAll(dir)
var best, cmds *SubCmd
doc, manDoc, usage := "", "", ""
for _, hc := range helpCommands(words) {
out := runHelp(dir, hc)
if strings.TrimSpace(out) == "" || !isHelpOf(out, words, hc) {
continue
}
cm := &SubCmd{Cmd: strings.Join(words, " "), Source: strings.Join(hc, " ")}
cm.SetFromHelp(out)
// the indented lists of man pages (which help commands may show) are
// not subcommands; a man page of the same name may be about something
// else (as for core)
man := hc[0] == "man" || isManPage(out)
if man {
cm.Cmds = nil
}
if best == nil || flagScore(cm) > flagScore(best) {
best = cm
}
if cmds == nil || cmdScore(cm) > cmdScore(cmds) {
cmds = cm
}
if hc[0] == "man" {
manDoc = cm.Doc
} else {
doc = cmp.Or(doc, cm.Doc)
}
usage = cmp.Or(usage, cm.Usage)
}
if best == nil {
return nil, fmt.Errorf("commands: no help found for %q", cmd)
}
best.Cmds = cmds.Cmds
if strings.HasPrefix(best.Source, "man ") { // else it may be about something else
doc = cmp.Or(doc, manDoc)
}
best.Doc = cmp.Or(best.Doc, doc)
// flags in other help, as of go test in go help testflag
for _, args := range extraFlagHelp[best.Cmd] {
more := &SubCmd{Cmd: best.Cmd}
more.SetFromHelp(runHelp(dir, args))
best.Flags = mergeFlags(best.Flags, more.Flags)
}
best.Usage = cmp.Or(best.Usage, usage)
return best, nil
}
// flagScore returns the score of the flags of the given parse, for choosing
// the help output with the most flags, and then the most documented ones.
func flagScore(cm *SubCmd) int {
n := 2 * len(cm.Flags)
for _, fl := range cm.Flags {
if fl.Doc != "" {
n++
}
}
return n
}
// extraFlagHelp are the help commands of the flags of subcommands whose
// help only refers to them: go help testflag for go test.
var extraFlagHelp = map[string][][]string{
"go test": {{"go", "help", "testflag"}},
}
// mergeFlags returns the given flags with the given other flags after them,
// other than those with a name of one of them.
func mergeFlags(flags, others []*Flag) []*Flag {
has := map[string]bool{}
for _, fl := range flags {
for _, n := range fl.Names {
has[n] = true
}
}
for _, fl := range others {
if !slices.ContainsFunc(fl.Names, func(n string) bool { return has[n] }) {
flags = append(flags, fl)
for _, n := range fl.Names {
has[n] = true
}
}
}
return flags
}
// cmdScore returns the score of the subcommands of the given parse, for
// choosing the help output with the most subcommands, and then the most
// documented ones (as of npm -l).
func cmdScore(cm *SubCmd) int {
n := 2 * len(cm.Cmds)
for _, sub := range cm.Cmds {
if sub.Doc != "" {
n++
}
}
return n
}
// isHelpOf returns whether the given output of the given help command of
// the given command is help: that of -h or --help for a subcommand, which
// may not take them as help and run (as launchctl dumpstate does), must
// mention its usage, or its name.
func isHelpOf(out string, words, hc []string) bool {
if len(words) < 2 || hc[0] == "man" || slices.Contains(hc, "help") {
return true
}
return strings.Contains(strings.ToLower(out), "usage") || strings.Contains(out, words[len(words)-1])
}
// noFlagHelp are the commands whose subcommands do not take -h or --help
// as help, but run, so that only their help subcommand is used for the
// help of their subcommands: launchctl dumpstate dumps the state of all of
// the processes, and others act on services.
var noFlagHelp = map[string]bool{
"launchctl": true,
}
// helpCommands returns the commands to get the help of the given command.
func helpCommands(words []string) [][]string {
with := func(args ...string) []string {
return append(append([]string{}, words...), args...)
}
hcs := [][]string{with("-h"), with("--help")}
if len(words) > 1 && noFlagHelp[words[0]] {
hcs = nil
}
if len(words) > 1 {
hcs = append(hcs, append([]string{words[0], "help"}, words[1:]...))
hcs = append(hcs, []string{"man", strings.Join(words, "-")})
} else {
// (git help -a has all of the commands of git, not just the common ones)
hcs = append(hcs, with("help"), with("help", "-a"), []string{"man", words[0]})
for _, args := range extraHelp[words[0]] {
hcs = append(hcs, with(args...))
}
}
return hcs
}
// extraHelp are the arguments of other help commands of commands whose
// usual help does not list all of their subcommands: brew commands lists
// them under "==> " headings (see [SubCmd.SetFromHelp]), and npm -l lists
// them with their documentation. Other commands
// are not run with such arguments, which they may not take as help.
var extraHelp = map[string][][]string{
"brew": {{"commands"}},
"npm": {{"-l"}},
}
// runHelp runs the given help command in the given (empty) directory,
// with no input, returning its output, with that of errors, which is empty
// if the command was not found. The help commands of some programs exit
// with an error.
func runHelp(dir string, args []string) string {
ctx, cancel := context.WithTimeout(context.Background(), HelpTimeout)
defer cancel()
if _, err := exec.LookPath(args[0]); err != nil {
// apps started from the desktop may not have the PATH of the shell
sh := os.Getenv("SHELL")
if sh == "" {
return ""
}
quoted := make([]string, len(args))
for i, a := range args {
quoted[i] = shellQuote(a)
}
args = []string{sh, "-l", "-c", strings.Join(quoted, " ")}
}
c := exec.CommandContext(ctx, args[0], args[1:]...)
c.Dir = dir
c.Env = append(os.Environ(), "PAGER=cat", "MANPAGER=cat", "GIT_PAGER=cat", "MANWIDTH=100", "TERM=dumb")
var out bytes.Buffer
c.Stdout, c.Stderr = &out, &out
err := c.Run()
var exitErr *exec.ExitError
if (err != nil && !errors.As(err, &exitErr)) || out.Len() > MaxHelpSize {
return "" // (not help, such as a dump of a command run by it)
}
return stripOverstrike(out.String())
}
// isManPage returns whether the given help output is a man page, with the
// NAME and SYNOPSIS headings.
func isManPage(out string) bool {
return strings.Contains(out, "\nNAME\n") && strings.Contains(out, "\nSYNOPSIS\n")
}
// overstrike matches the overstrike formatting of man pages: a character
// followed by a backspace.
var overstrike = regexp.MustCompile(".\b")
// stripOverstrike removes the overstrike formatting of man pages.
func stripOverstrike(s string) string {
return overstrike.ReplaceAllString(s, "")
}
// block is a name, such as that of a flag or a subcommand, with its
// documentation, in help output, under a section heading, such as
// "The commands are:".
type block struct {
name, doc, section string
indent int
// docCol is the column of the documentation, if known: after the gap on
// the line of the name, or of the first line after it.
docCol int
}
// SetFromHelp sets the documentation, usage, flags, and subcommands of the
// command from the given help output.
func (cm *SubCmd) SetFromHelp(help string) {
lines := strings.Split(strings.ReplaceAll(help, "\r\n", "\n"), "\n")
usage, doc := usageAndDoc(lines)
cm.Usage = cmp.Or(usage, cm.Usage)
cm.Doc = cmp.Or(doc, cm.Doc)
flags := map[string]bool{}
cmds := map[string]bool{}
for _, b := range helpBlocks(lines) {
if strings.HasPrefix(b.name, "-") {
fl := parseFlag(b.name)
if fl == nil || flags[fl.Name] {
continue
}
if fl.Value == "bool" { // as in the help of Go flag packages
fl.Value = ""
}
flags[fl.Name] = true
fl.Doc = b.doc
cm.Flags = append(cm.Flags, fl)
continue
}
if !isSubcommand(b.name) || cmds[b.name] || b.name == "help" || !commandSection(b.section) {
continue
}
cmds[b.name] = true
cm.Cmds = append(cm.Cmds, &SubCmd{Cmd: cm.Cmd + " " + b.name, Doc: b.doc, Group: groupName(b.section)})
}
// lists of subcommands separated by commas, under a heading of
// commands, as of npm -h
commaSection := ""
for _, line := range lines {
text := strings.TrimSpace(line)
if text == "" {
continue
}
if indentOf(line) == 0 {
commaSection = ""
if strings.Contains(strings.ToLower(text), "command") && strings.HasSuffix(text, ":") {
commaSection = text
}
continue
}
if commaSection == "" || !strings.Contains(text, ",") || !commandSection(commaSection) {
continue
}
// each item is one word, not prose with commas (as in go help build)
var names []string
prose := false
for item := range strings.SplitSeq(strings.TrimSuffix(text, ","), ",") {
item = strings.TrimSpace(item)
if !isSubcommand(item) {
prose = true
break
}
names = append(names, item)
}
if prose {
continue
}
for _, n := range names {
if cmds[n] || n == "help" {
continue
}
cmds[n] = true
cm.Cmds = append(cm.Cmds, &SubCmd{Cmd: cm.Cmd + " " + n, Group: groupName(commaSection)})
}
}
// lists of subcommands under "==> " headings, one per line, as of
// brew commands
listSection := ""
for _, line := range lines {
text := strings.TrimSpace(line)
if h, ok := strings.CutPrefix(text, "==> "); ok {
listSection = h
continue
}
if listSection == "" || !isSubcommand(text) || cmds[text] || text == "help" || !commandSection(listSection) {
continue
}
cmds[text] = true
cm.Cmds = append(cm.Cmds, &SubCmd{Cmd: cm.Cmd + " " + text, Group: groupName(listSection)})
}
if len(cm.Flags) == 0 { // as for go mod tidy
cm.Flags = usageFlags(cm.Usage, lines)
}
// a section with one subcommand is an example in the text, as in the
// help of go test
n := map[string]int{}
for _, sub := range cm.Cmds {
n[sub.Group]++
}
cm.Cmds = slices.DeleteFunc(cm.Cmds, func(sub *SubCmd) bool { return n[sub.Group] < 2 })
if len(cm.Cmds) > 0 {
return
}
// subcommands that are only in the usage lines, as for git stash list,
// with their usage as their documentation
for line := range strings.SplitSeq(cm.Usage, "\n") {
rest, ok := strings.CutPrefix(line, cm.Cmd+" ")
f := strings.Fields(rest)
if !ok || len(f) == 0 || !isSubcommand(f[0]) || cmds[f[0]] || f[0] == "help" {
continue
}
cmds[f[0]] = true
cm.Cmds = append(cm.Cmds, &SubCmd{Cmd: cm.Cmd + " " + f[0], Doc: line})
}
}
// usageFlag matches a bracketed flag in a usage line, such as "[-v]",
// "[-go=version]", "[-C dir]", or "[-a | -b]", not containing brackets.
var usageFlag = regexp.MustCompile(`\[(-[^\[\]]*)\]`)
// usageFlags returns the flags in the given usage lines, for help output
// that only has them there, as for go mod tidy, with their documentation
// from the given lines of the help output: the sentence about each, such
// as "The -v flag causes tidy to print ...".
func usageFlags(usage string, lines []string) []*Flag {
text := strings.Join(strings.Fields(strings.Join(lines, " ")), " ")
var flags []*Flag
seen := map[string]bool{}
for _, m := range usageFlag.FindAllStringSubmatch(usage, -1) {
for alt := range strings.SplitSeq(m[1], "|") {
fl := parseFlag(strings.TrimSpace(alt))
if fl == nil || seen[fl.Name] || len(strings.Fields(alt)) > 2 {
continue
}
seen[fl.Name] = true
fl.Doc = flagSentence(text, fl.Name)
flags = append(flags, fl)
}
}
return flags
}
// flagSentence returns the sentence of the given text that is about the
// given flag, starting with "The -v flag", or "" if there is none.
func flagSentence(text, name string) string {
i := strings.Index(text, "The "+name+" flag")
if i < 0 {
return ""
}
s := text[i:]
if j := strings.Index(s, ". "); j >= 0 {
s = s[:j+1]
}
return s
}
// commandSection returns whether the given section of help output can
// have subcommands: not help topics, as of go, the low-level commands,
// interfaces, and external commands of git help -a, or the developer
// commands of brew.
func commandSection(section string) bool {
s := strings.ToLower(section)
for _, not := range []string{"topic", "low-level", "interface", "external", "guide", "developer"} {
if strings.Contains(s, not) {
return false
}
}
return true
}
// groupName returns the name of the group of the subcommands in the given
// section of help output: its heading, without a colon, or "" for the
// usual headings, such as "The commands are:".
func groupName(section string) string {
s := strings.TrimSpace(strings.TrimSuffix(strings.TrimSpace(section), ":"))
switch strings.ToLower(s) {
case "the commands are", "commands", "subcommands", "available commands", "all commands":
return ""
}
return s
}
// isSubcommand returns whether the given name of a block is that of a
// subcommand: a lowercase word.
func isSubcommand(name string) bool {
if name == "" || !unicode.IsLower(rune(name[0])) {
return false
}
return !strings.ContainsFunc(name, func(r rune) bool {
return !unicode.IsLower(r) && !unicode.IsDigit(r) && r != '-' && r != '_'
})
}
// indentOf returns the indentation of the given line, with tabs to 8.
func indentOf(line string) int {
n := 0
for _, r := range line {
switch r {
case ' ':
n++
case '\t':
n += 8 - n%8
default:
return n
}
}
return n
}
// nameGap matches the gap between a name and its documentation on one
// line: two or more spaces, or a tab.
var nameGap = regexp.MustCompile(`\s{2,}|\t`)
// helpBlocks returns the blocks of names with their documentation in the
// given lines of help output: indented lines starting with a name, followed
// by its documentation, after a gap on the same line, or on more indented
// lines after it.
func helpBlocks(lines []string) []block {
var blocks []block
var cur *block
section := ""
finish := func() {
if cur != nil && cur.name != "" {
blocks = append(blocks, *cur)
}
cur = nil
}
for _, line := range lines {
text := strings.TrimSpace(line)
n := indentOf(line)
if n == 0 && text != "" {
section = text
}
switch {
case text == "" || n == 0:
finish()
case cur != nil && n > cur.indent && (!strings.HasPrefix(text, "-") || cur.docCol <= 0 || n >= cur.docCol):
// (a flag indented more than the one before it, but less than its
// documentation, is another flag, as of brew: " --name")
if cur.docCol == 0 {
cur.docCol = n
}
if cur.doc != "" {
cur.doc += " "
}
cur.doc += text
case strings.HasPrefix(text, "-") || isSubcommand(text) || nameGap.MatchString(text):
finish()
cur = &block{name: text, indent: n, section: section}
if loc := nameGap.FindStringIndex(text); loc != nil {
cur.name, cur.doc = text[:loc[0]], strings.TrimSpace(text[loc[1]:])
cur.docCol = n + loc[1]
} else if strings.HasPrefix(text, "-") {
cur.name, cur.doc = splitFlagDoc(text)
}
default:
finish()
}
}
finish()
return blocks
}
// splitFlagDoc splits the given line of help output that starts with a
// flag, with no gap of two spaces before its documentation, into the
// flag, with its value hint, and its documentation, which are separated by
// one space when the flag fills the column of flags. There is no
// documentation unless three or more words follow the flag and any value
// hint, so that "-C dir" is a flag with a value.
func splitFlagDoc(text string) (name, doc string) {
words := strings.Fields(text)
i := 0
for i < len(words) && strings.HasPrefix(words[i], "-") {
i++
}
if i < len(words) && strings.ContainsAny(words[i][:1], "<[") {
i++ // a value hint
}
if len(words)-i < 3 {
return text, ""
}
return strings.Join(words[:i], " "), strings.Join(words[i:], " ")
}
// flagName matches a valid name of a flag.
var flagName = regexp.MustCompile(`^--?[A-Za-z0-9][A-Za-z0-9_.-]*$`)
// parseFlag returns the flag of the given name of a block of help output,
// such as "-m, --[no-]message <message>", or nil if it has no flag names.
func parseFlag(name string) *Flag {
fl := &Flag{}
var toks []string
for tok := range strings.FieldsSeq(strings.ReplaceAll(name, ",", " ")) {
if strings.HasPrefix(tok, "-") && !strings.ContainsAny(tok, "<[") { // "-S|--save", as of npm
toks = append(toks, strings.Split(tok, "|")...)
continue
}
toks = append(toks, tok)
}
for _, tok := range toks {
if !strings.HasPrefix(tok, "-") {
if fl.Value == "" {
fl.Value = tok
}
continue
}
if strings.Contains(tok, "[no-]") {
fl.Negatable = true
tok = strings.Replace(tok, "[no-]", "", 1)
}
if i := strings.IndexAny(tok, "=["); i > 0 {
val := tok[i:]
tok = tok[:i]
if strings.HasPrefix(val, "[") {
fl.Optional = true
val = strings.TrimSuffix(strings.TrimPrefix(val, "["), "]")
}
if strings.HasPrefix(val, "=") {
fl.Equals = !fl.Optional
val = val[1:]
}
if val != "" {
fl.Value = val
}
}
if !flagName.MatchString(tok) {
continue
}
fl.Names = append(fl.Names, tok)
if len(tok) > len(fl.Name) {
fl.Name = tok
}
}
if len(fl.Names) == 0 {
return nil
}
return fl
}
// usageAndDoc returns the usage synopsis and the documentation of the
// command in the given lines of help output: the usage lines (or the
// SYNOPSIS of a man page) and the NAME of a man page, or else the first
// unindented paragraph after the usage.
func usageAndDoc(lines []string) (usage, doc string) {
var us, ds, para []string
section := ""
inUsage, afterUsage := false, false
for _, line := range lines {
text := strings.TrimSpace(line)
n := indentOf(line)
lower := strings.ToLower(text)
switch {
case n == 0 && text != "" && text == strings.ToUpper(text) && !strings.ContainsAny(text, "-:"):
section = text // a heading of a man page
inUsage = false
continue
case strings.HasPrefix(lower, "usage:"):
inUsage = true
us = append(us, strings.TrimSpace(text[len("usage:"):]))
continue
}
switch {
case inUsage && text != "" && !strings.HasSuffix(lower, ":"):
us = append(us, strings.TrimSpace(strings.TrimPrefix(text, "or:")))
continue
case inUsage:
inUsage, afterUsage = false, true
case section == "SYNOPSIS" && text != "":
us = append(us, text)
case section == "NAME" && text != "" && len(ds) == 0:
if _, after, ok := strings.Cut(text, " - "); ok {
ds = append(ds, after)
}
case afterUsage && n == 0 && text != "":
para = append(para, text)
case afterUsage && len(para) > 0:
afterUsage = false
}
}
// the first paragraph after the usage is the documentation if it is a
// sentence, not a heading
if p := strings.Join(para, " "); len(ds) == 0 && strings.Contains(p, ".") {
if i := strings.Index(p, ". "); i > 0 { // the first sentence
p = p[:i+1]
}
ds = append(ds, p)
}
us = slices.DeleteFunc(us, func(s string) bool { return s == "" })
return strings.Join(us, "\n"), strings.Join(ds, " ")
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package commands
//go:generate core generate
import (
"os"
"path/filepath"
"runtime"
"slices"
"strings"
"unicode"
"cogentcore.org/core/base/fileinfo"
)
// Script is a script written by the user, for things that are more than
// a command line: its code starts with a #! line of the program that runs
// it, such as #!/bin/bash, #!/usr/bin/env python3, or #!/usr/bin/env goal
// (the shell, /bin/sh, if there is none). Its arguments are prompted for
// when it runs, and passed to it as $1, $2, and so on. The scripts of a
// command, such as git, are in its menu after its macros (see
// [Cmd.Scripts]), and others are entries of the commands (see
// [Entry.Script]).
type Script struct {
// Name is the name of the script, which is shown for it.
Name string
// Doc is the documentation of the script, which is its tooltip.
Doc string `json:",omitempty"`
// Confirm is whether the script is confirmed before it runs, if it has
// no arguments to prompt for, as for scripts that cannot be undone.
Confirm bool `json:",omitempty"`
// Code is the code of the script, starting with its #! line.
Code string `display:"-"`
// Args are the arguments of the script, which are prompted for when it
// runs, in their order: $1, $2, and so on.
Args []ScriptArg `json:",omitempty" display:"-"`
}
// ScriptArg is an argument of a [Script], which is prompted for when it runs.
type ScriptArg struct {
// Name is the name of the argument, the label of its prompt.
Name string
// Kind is the kind of value of the argument.
Kind ArgKinds
// Doc is the documentation of the argument, the tooltip of its prompt.
Doc string `json:",omitempty" width:"40"`
// Default is the value of the argument when it is first prompted for
// (after that, the last value used): for a switch, "true" if it is on.
Default string `json:",omitempty"`
// On is the value passed for a switch that is on, such as --force, or
// "true" if it is empty; an empty string is passed if it is off.
On string `json:",omitempty"`
// Chooser is the chooser of the values of a text argument, such as a
// git branch, if any (see [Chooser]).
Chooser ChooserName `json:",omitempty"`
}
// ArgKinds are the kinds of values of the arguments of a [Script].
type ArgKinds int32 //enums:enum -trim-prefix Arg
const (
// ArgString is text, such as a name or a message.
ArgString ArgKinds = iota
// ArgSwitch is a switch that is on or off (see [ScriptArg.On]).
ArgSwitch
// ArgFile is the path of a file or directory, which can be chosen.
ArgFile
)
// clone returns a copy of the script, with its own arguments.
func (s *Script) clone() *Script {
c := *s
c.Args = slices.Clone(s.Args)
return &c
}
// interpreter returns the program of the #! line of the code of the
// script, with its arguments, such as ["/usr/bin/env", "python3"], or nil
// if there is none.
func (s *Script) interpreter() []string {
line, _, _ := strings.Cut(s.Code, "\n")
if !strings.HasPrefix(line, "#!") {
return nil
}
return strings.Fields(line[2:])
}
// Language returns the language of the script, from its #! line.
func (s *Script) Language() fileinfo.Known {
in := s.interpreter()
if len(in) == 0 {
return fileinfo.Bash
}
prog := filepath.Base(in[0])
if prog == "env" && len(in) > 1 {
prog = in[len(in)-1]
}
prog = strings.TrimRightFunc(prog, func(r rune) bool { return unicode.IsDigit(r) || r == '.' })
switch prog {
case "sh", "bash", "zsh", "dash", "ksh":
return fileinfo.Bash
case "goal":
return fileinfo.Goal
case "python":
return fileinfo.Python
case "perl":
return fileinfo.Perl
case "ruby":
return fileinfo.Ruby
}
return fileinfo.Unknown
}
// argValues returns the values passed to the script for the given values
// of its arguments, by name (see [Commands.ScriptValues]): the value of a
// switch that is on is its [ScriptArg.On] value, and empty if it is off.
func (s *Script) argValues(values map[string]string) []string {
var vals []string
for _, a := range s.Args {
v := values[a.Name]
if a.Kind == ArgSwitch {
v = ""
if values[a.Name] == "true" {
v = cmpOr(a.On, "true")
}
}
vals = append(vals, v)
}
return vals
}
// cmpOr returns a if it is not empty, and otherwise b.
func cmpOr(a, b string) string {
if a != "" {
return a
}
return b
}
// CommandLine returns the command line that the script stands for with
// the given values of its arguments, by name, as shown to the user: its
// name and the values of its arguments, quoted.
func (s *Script) CommandLine(values map[string]string) string {
words := []string{shellQuote(s.Name)}
for _, v := range s.argValues(values) {
words = append(words, shellQuote(v))
}
return strings.Join(words, " ")
}
// fileName returns the given name as the name of a file: its letters,
// digits, dots, and dashes, with dashes in place of the others.
func fileName(name string) string {
name = strings.Map(func(r rune) rune {
if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '.' || r == '-' || r == '_' {
return r
}
return '-'
}, strings.TrimSpace(name))
return cmpOr(strings.Trim(name, ".-"), "script")
}
// scriptsDir returns the directory of the files of the scripts, next to
// the file of the commands.
func (cs *Commands) scriptsDir() string {
dir := os.TempDir()
if cs.file.Path != "" {
dir = filepath.Dir(cs.file.Path)
}
return filepath.Join(dir, "scripts")
}
// ScriptCommandLine writes the file of the given script of the given
// command ("" for one of an entry), and returns the command line that runs
// it with the given values of its arguments, by name. The arguments are in
// a launcher, a shell script that runs the script with them, so that the
// command line is the same in any shell, such as Goal, which cannot pass
// empty arguments: /bin/sh and the path of the launcher. On Windows, it is
// the program of the #! line and the path of the script, with the
// arguments.
func (cs *Commands) ScriptCommandLine(root string, s *Script, values map[string]string) (string, error) {
dir := filepath.Join(cs.scriptsDir(), fileName(cmpOr(root, "commands")))
name := fileName(s.Name)
file := filepath.Join(dir, name)
if err := os.MkdirAll(dir, 0o755); err != nil {
return "", err
}
code := s.Code
if !strings.HasSuffix(code, "\n") {
code += "\n"
}
if err := os.WriteFile(file, []byte(code), 0o755); err != nil {
return "", err
}
if err := os.Chmod(file, 0o755); err != nil { // (if it existed)
return "", err
}
in := s.interpreter()
args := s.argValues(values)
if runtime.GOOS == "windows" {
prog := "sh"
if len(in) > 0 {
prog = filepath.Base(in[0])
if prog == "env" && len(in) > 1 {
prog = in[1]
}
}
words := []string{prog, shellQuote(file)}
for _, a := range args {
words = append(words, shellQuote(a))
}
return strings.Join(words, " "), nil
}
words := []string{"exec", shellQuote(file)}
if len(in) == 0 {
words = []string{"exec", "/bin/sh", shellQuote(file)}
}
for _, a := range args {
words = append(words, shellQuote(a))
}
rdir := filepath.Join(cs.scriptsDir(), "run", fileName(cmpOr(root, "commands")))
if err := os.MkdirAll(rdir, 0o755); err != nil {
return "", err
}
launcher := filepath.Join(rdir, name)
if err := os.WriteFile(launcher, []byte("#!/bin/sh\n"+strings.Join(words, " ")+"\n"), 0o755); err != nil {
return "", err
}
return "/bin/sh " + shellQuote(launcher), nil
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package commands
import (
"errors"
"html"
"image"
"reflect"
"slices"
"strconv"
"strings"
errs "cogentcore.org/core/base/errors"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/styles"
"cogentcore.org/core/text/textcore"
"cogentcore.org/core/tree"
)
// NewScriptCode is the code of a new script, before it is written.
const NewScriptCode = "#!/bin/sh\n\n"
// fieldNames returns the names of the fields of the form of the arguments
// of the script (see [Script.FormStruct]), which are unique.
func (s *Script) fieldNames() []string {
var names []string
used := map[string]bool{}
for _, a := range s.Args {
name := fieldName(a.Name)
for i := 2; used[name]; i++ {
name = fieldName(a.Name) + strconv.Itoa(i)
}
used[name] = true
names = append(names, name)
}
return names
}
// FormStruct returns a pointer to a new struct for the form of the
// arguments of the script: a string, bool (switch), or [core.Filename]
// field for each, labeled with its name, with its documentation.
func (s *Script) FormStruct() any {
var fields []reflect.StructField
for i, name := range s.fieldNames() {
a := s.Args[i]
typ := reflect.TypeFor[string]()
tags := ` immediate:"+"`
switch a.Kind {
case ArgSwitch:
typ, tags = reflect.TypeFor[bool](), ""
case ArgFile:
typ = reflect.TypeFor[core.Filename]()
}
// (the label and doc are shown as markup)
tag := `label:` + strconv.Quote(html.EscapeString(cmpOr(a.Name, name))) + ` doc:` + strconv.Quote(html.EscapeString(a.Doc)) + tags
fields = append(fields, reflect.StructField{Name: name, Type: typ, Tag: reflect.StructTag(tag)})
}
return reflect.New(reflect.StructOf(fields)).Interface()
}
// SetFormValues sets the given values of the form of the arguments of the
// script (see [Script.FormStruct]) to the given values, by name.
func (s *Script) SetFormValues(form any, values map[string]string) {
v := reflect.ValueOf(form).Elem()
for i, name := range s.fieldNames() {
f := v.FieldByName(name)
val := values[s.Args[i].Name]
if f.Kind() == reflect.Bool {
b, _ := strconv.ParseBool(val)
f.SetBool(b)
continue
}
f.SetString(val)
}
}
// FormValues returns the values of the arguments of the given values of
// the form of the arguments of the script (see [Script.FormStruct]), by
// name: "true" or "" for a switch.
func (s *Script) FormValues(form any) map[string]string {
v := reflect.ValueOf(form).Elem()
values := map[string]string{}
for i, name := range s.fieldNames() {
f := v.FieldByName(name)
val := ""
if f.Kind() == reflect.Bool {
if f.Bool() {
val = "true"
}
} else {
val = f.String()
}
values[s.Args[i].Name] = val
}
return values
}
// Script returns the script of the given command, such as git, with the
// given name, or that of an entry, if the command is "", or nil if there
// is none.
func (cs *Commands) Script(root, name string) *Script {
cs.reload()
cs.mu.Lock()
defer cs.mu.Unlock()
if root != "" {
if cm := cs.Parsed[root]; cm != nil {
if i := slices.IndexFunc(cm.Scripts, func(s *Script) bool { return s.Name == name }); i >= 0 {
return cm.Scripts[i]
}
}
return nil
}
if en := findScriptEntry(cs.Entries, nil, name); en != nil {
return en.Script
}
return nil
}
// findScriptEntry returns the entry of the given script among the given
// entries and their children, or else that of a script of the given name,
// or nil if there is none.
func findScriptEntry(ens []*Entry, s *Script, name string) *Entry {
var byName *Entry
var find func(ens []*Entry) *Entry
find = func(ens []*Entry) *Entry {
for _, en := range ens {
if en.Script != nil {
if s != nil && en.Script == s {
return en
}
if byName == nil && en.Script.Name == name {
byName = en
}
}
if f := find(en.Children); f != nil {
return f
}
}
return nil
}
if en := find(ens); en != nil {
return en
}
return byName
}
// deleteEntry returns the given entries without the given one, which is
// also deleted from their children.
func deleteEntry(ens []*Entry, del *Entry) []*Entry {
ens = slices.DeleteFunc(ens, func(en *Entry) bool { return en == del })
for _, en := range ens {
en.Children = deleteEntry(en.Children, del)
}
return ens
}
// SaveScript saves the given script of the given command, such as git, or
// as an entry, if the command is "", in place of the given old one, if it
// is not nil, and otherwise as a new one (in place of one of the same name
// of the command), updating the command bars and the editor. A new script
// of an entry is the last entry.
func (cs *Commands) SaveScript(root string, s, old *Script) error {
if strings.TrimSpace(s.Name) == "" {
return errors.New("the script has no name")
}
err := cs.update(func() {
if root == "" {
if old != nil {
if en := findScriptEntry(cs.Entries, old, old.Name); en != nil {
en.Script = s
en.Name = s.Name
return
}
}
cs.Entries = append(cs.Entries, &Entry{Name: s.Name, Script: s})
return
}
cm := cs.Parsed[root]
if cm == nil {
cm = &Cmd{Cmd: root}
cs.Parsed[root] = cm
}
i := -1
if old != nil {
i = slices.IndexFunc(cm.Scripts, func(o *Script) bool { return o == old || o.Name == old.Name })
}
if i < 0 {
i = slices.IndexFunc(cm.Scripts, func(o *Script) bool { return o.Name == s.Name })
}
if i >= 0 {
cm.Scripts[i] = s
} else {
cm.Scripts = append(cm.Scripts, s)
}
})
cs.updateViews(nil)
return err
}
// DeleteScript deletes the given script of the given command, such as git,
// or the entry of it, if the command is "", updating the command bars and
// the editor.
func (cs *Commands) DeleteScript(root string, s *Script) error {
err := cs.update(func() {
if root == "" {
if en := findScriptEntry(cs.Entries, s, s.Name); en != nil {
cs.Entries = deleteEntry(cs.Entries, en)
}
return
}
if cm := cs.Parsed[root]; cm != nil {
cm.Scripts = slices.DeleteFunc(cm.Scripts, func(o *Script) bool { return o == s || o.Name == s.Name })
}
})
cs.updateViews(nil)
return err
}
// RunScript runs the given script of the given command, such as git, or
// of an entry, if the command is "", with the given function, after
// prompting for its arguments, if it has any, in a dialog in the context
// of the given widget, or else after confirming it, if it is to be
// confirmed (see [Script.Confirm]). The values of its arguments are saved
// in the [Args], as their defaults for the next time.
func (cs *Commands) RunScript(ctx core.Widget, root string, s *Script, run RunFunc) {
ctx = cs.context(ctx)
if len(s.Args) > 0 {
runDialog(cs.NewScriptPromptDialog(ctx, root, s, run), ctx)
return
}
if !s.Confirm {
cs.runScript(ctx, root, s, nil, run)
return
}
d := core.NewBody(s.Name)
core.NewText(d).SetType(core.TextSupporting).SetText("Run this script?")
if s.Doc != "" {
core.NewText(d).SetType(core.TextSupporting).SetText(html.EscapeString(s.Doc))
}
cs.scriptTopBar(d, ctx, root, s)
d.AddBottomBar(func(bar *core.Frame) {
d.AddCancel(bar)
d.AddOK(bar).SetText("Run").SetIcon(icons.PlayArrow).OnClick(func(e events.Event) {
cs.runScript(ctx, root, s, nil, run)
})
})
d.RunDialog(ctx)
}
// runScript runs the given script of the given command (see
// [Commands.RunScript]) with the given values of its arguments, by name,
// which are saved as their defaults for the next time.
func (cs *Commands) runScript(ctx core.Widget, root string, s *Script, values map[string]string, run RunFunc) {
if len(s.Args) > 0 {
errs.Log(cs.Args.SetScriptValues(root, s, values))
}
cmdline, err := cs.ScriptCommandLine(root, s, values)
if err != nil {
core.ErrorSnackbar(ctx, err, "Error writing the script "+s.Name)
return
}
run(cmdline)
}
// scriptTopBar adds the top bar of the dialogs of running the given script
// of the given command to the given dialog, with a button to edit it.
func (cs *Commands) scriptTopBar(d *core.Body, ctx core.Widget, root string, s *Script) {
d.AddTopBar(func(bar *core.Frame) {
core.NewToolbar(bar).Maker(func(p *tree.Plan) {
tree.Add(p, func(w *core.Button) {
w.SetText("Edit script").SetIcon(icons.Edit)
w.OnClick(func(e events.Event) {
d.Close()
cs.EditScript(ctx, root, s)
})
})
})
})
}
// NewScriptPromptDialog returns the body of the dialog that prompts for
// the arguments of the given script of the given command, such as git, or
// of an entry, if the command is "", which runs it with the given function
// (see [Commands.RunScript]).
func (cs *Commands) NewScriptPromptDialog(ctx core.Widget, root string, s *Script, run RunFunc) *core.Body {
ctx = cs.context(ctx)
d := core.NewBody(s.Name)
if s.Doc != "" {
core.NewText(d).SetType(core.TextSupporting).SetText(html.EscapeString(s.Doc))
}
form := s.FormStruct()
s.SetFormValues(form, cs.Args.ScriptValues(root, s))
line := commandLineText(d, func() string { return s.CommandLine(s.FormValues(form)) })
fm := cs.chooserForm(ctx, d, form, cs.scriptChoosers(s))
fm.OnChange(func(e events.Event) { line.Update() })
fm.OnInput(func(e events.Event) { line.Update() })
cs.scriptTopBar(d, ctx, root, s)
d.AddBottomBar(func(bar *core.Frame) {
d.AddCancel(bar)
d.AddOK(bar).SetText("Run").SetIcon(icons.PlayArrow).OnClick(func(e events.Event) {
cs.runScript(ctx, root, s, s.FormValues(form), run)
})
})
return d
}
// EditScript opens the editor of the given script of the given command,
// such as git, or of an entry, if the command is "" (see
// [Commands.NewScriptDialog]).
func (cs *Commands) EditScript(ctx core.Widget, root string, s *Script) {
ctx = cs.context(ctx)
runDialog(cs.NewScriptDialog(ctx, root, s, s), ctx)
}
// NewScript opens the editor of a new script of the given command, such as
// git, or of an entry, if the command is "", with the given code, or
// [NewScriptCode] if it is empty.
func (cs *Commands) NewScript(ctx core.Widget, root, code string) {
ctx = cs.context(ctx)
s := &Script{Code: cmpOr(code, NewScriptCode)}
runDialog(cs.NewScriptDialog(ctx, root, s, nil), ctx)
}
// NewScriptDialog returns the body of the editor of the given script of
// the given command, such as git, or of an entry, if the command is "":
// its name, documentation, and whether it is confirmed, its code, and the
// table of its arguments. It saves it in place of the given old script,
// if it is not nil, and otherwise as a new one (see [Commands.SaveScript]).
func (cs *Commands) NewScriptDialog(ctx core.Widget, root string, s, old *Script) *core.Body {
ctx = cs.context(ctx)
title := "New script"
if old != nil {
title = "Edit script"
}
if root != "" {
title += ": " + root
}
d := core.NewBody(title)
es := s.clone()
core.NewText(d).SetType(core.TextSupporting).SetText("The script starts with the #! line of the program that runs it, such as #!/bin/bash, #!/usr/bin/env python3, or #!/usr/bin/env goal. Its arguments are prompted for when it runs, and passed to it as $1, $2, and so on.")
newForm(d, es)
core.NewText(d).SetType(core.TextTitleSmall).SetText("Code")
ed := textcore.NewEditor(d)
ed.Lines.SetText([]byte(es.Code))
ed.Lines.SetLanguage(es.Language())
ed.Styler(func(s *styles.Style) {
s.Min.Y.Em(12)
s.Grow.Set(1, 1)
})
core.NewText(d).SetType(core.TextTitleSmall).SetText("Arguments")
core.NewText(d).SetType(core.TextSupporting).SetText("The arguments, $1, $2, and so on, in order, which are prompted for when the script runs: text, a switch (passed as its On value, or empty if it is off), or a file. Text can have a chooser of its values, such as a git branch. Add one with Add argument at the top, or the context menu of the table (right-click).")
tb := core.NewTable(d).SetSlice(&es.Args)
d.AddTopBar(func(bar *core.Frame) {
core.NewToolbar(bar).Maker(func(p *tree.Plan) {
tree.Add(p, func(w *core.Button) {
w.SetText("Add argument").SetIcon(icons.Add).SetTooltip("Add an argument at the end")
w.OnClick(func(e events.Event) {
es.Args = append(es.Args, ScriptArg{Name: "Arg" + strconv.Itoa(len(es.Args)+1)})
tb.Update()
})
})
if old != nil {
tree.Add(p, func(w *core.Button) {
w.SetText("Delete script").SetIcon(icons.Delete)
w.OnClick(func(e events.Event) {
errs.Log(cs.DeleteScript(root, old))
d.Close()
})
})
}
})
})
d.AddBottomBar(func(bar *core.Frame) {
d.AddCancel(bar)
d.AddOK(bar).SetText("Save").SetIcon(icons.Save).OnClick(func(e events.Event) {
es.Name = strings.TrimSpace(es.Name)
es.Code = ed.Lines.String()
if err := cs.SaveScript(root, es, old); err != nil {
core.ErrorSnackbar(ctx, err, "Error saving the script")
return
}
core.MessageSnackbar(ctx, "Saved the script "+es.Name)
})
})
return d
}
// configScript configures the given button, of a menu or the command
// bar, for the given script.
func configScript(w *core.Button, s *Script) {
w.SetText(s.Name).SetIcon(icons.Code)
w.SetTooltip(html.EscapeString(cmpOr(s.Doc, "Run the script")))
}
// scriptContextMenu adds a context menu to the given button, of a menu or
// the command bar, to edit the script given by the given function, of the
// given command, or of an entry, if the command is "", if it is not nil.
func (cs *Commands) scriptContextMenu(w *core.Button, root string, script func() *Script) {
w.AddContextMenu(func(m *core.Scene, _ image.Point) {
s := script()
if s == nil {
return
}
core.NewButton(m).SetText("Edit script").SetIcon(icons.Edit).OnClick(func(e events.Event) {
cs.EditScript(w, root, s)
})
})
}
// scriptsMenu adds the buttons of the scripts of the given command, such
// as git, to the given menu, which run them with the given function,
// followed by a separator, if there are any.
func (cs *Commands) scriptsMenu(m *core.Scene, cm *Cmd, run RunFunc) {
for _, s := range cm.Scripts {
b := core.NewButton(m)
configScript(b, s)
cs.scriptContextMenu(b, cm.Cmd, func() *Script { return s })
b.OnClick(func(e events.Event) { cs.RunScript(b, cm.Cmd, s, run) })
}
if len(cm.Scripts) > 0 {
core.NewSeparator(m)
}
}
// editScriptsMenu adds a button to the given menu of the given command,
// such as git, with a submenu to make a new script of it, and to edit its
// scripts.
func (cs *Commands) editScriptsMenu(m *core.Scene, cm *Cmd) {
b := core.NewButton(m).SetText("Scripts").SetIcon(icons.Code)
b.SetTooltip(html.EscapeString("Make and edit the scripts of " + cm.Cmd))
b.SetMenu(func(sm *core.Scene, _ image.Point) {
core.NewButton(sm).SetText("New script").SetIcon(icons.Add).
SetTooltip(html.EscapeString("Make a script of " + cm.Cmd + ", which is in its menu")).
OnClick(func(e events.Event) { cs.NewScript(b, cm.Cmd, "") })
for _, s := range cm.Scripts {
core.NewButton(sm).SetText("Edit " + s.Name).SetIcon(icons.Edit).OnClick(func(e events.Event) {
cs.EditScript(b, cm.Cmd, s)
})
}
})
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cli
import (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"slices"
"strings"
"cogentcore.org/core/base/iox/tomlx"
"cogentcore.org/core/base/logx"
)
// IMPORTANT: all changes to [metaConfig] must be updated in [metaConfigFields]
// metaConfig contains meta configuration information specified
// via command line arguments that controls the initial behavior
// of cli for all apps before anything else is loaded. Its
// main purpose is to support the help command and flag and
// the specification of custom config files on the command line.
type metaConfig struct {
// the file name of the config file to load
Config string `flag:"cfg,config"`
// whether to display a help message
Help bool `flag:"h,help"`
// the name of the command to display
// help information for. It is only applicable to the
// help command, but it is enabled for all commands so
// that it can consume all positional arguments to prevent
// errors about unused arguments.
HelpCmd string `posarg:"all"`
// whether to run the command in verbose mode
// and print more information
Verbose bool `flag:"v,verbose"`
// whether to run the command in very verbose mode
// and print as much information as possible
VeryVerbose bool `flag:"vv,very-verbose"`
// whether to run the command in quiet mode
// and print less information
Quiet bool `flag:"q,quiet"`
}
// metaConfigFields is the struct used for the implementation
// of [addMetaConfigFields], and for the usage information for
// meta configuration options in [usage].
// NOTE: we could do this through [metaConfig], but that
// causes problems with the HelpCmd field capturing
// everything, so it easier to just add through a separate struct.
// TODO: maybe improve the structure of this.
// TODO: can we get HelpCmd to display correctly in usage?
type metaConfigFields struct { //types:add
// the file name of the config file to load
Config string `flag:"cfg,config"`
// whether to display a help message
Help bool `flag:"h,help"`
// the name of the command to display
// help information for.
HelpCmd string `cmd:"help" posarg:"all"`
// whether to run the command in verbose mode
// and print more information
Verbose bool `flag:"v,verbose"`
// whether to run the command in very verbose mode
// and print as much information as possible
VeryVerbose bool `flag:"vv,very-verbose"`
// whether to run the command in quiet mode
// and print less information
Quiet bool `flag:"q,quiet"`
}
// addMetaConfigFields adds meta fields that control the config process
// to the given map of fields. These fields have no actual effect and
// map to a placeholder value because they are handled elsewhere, but
// they must be set to prevent errors about missing flags. The flags
// that it adds are those in [metaConfig].
func addMetaConfigFields(allFields *fields) {
addFields(&metaConfigFields{}, allFields, "")
}
// metaCmds is a set of commands based on [metaConfig] that
// contains a shell implementation of the help command.
var metaCmds = []*Cmd[*metaConfig]{
{
Func: func(mc *metaConfig) error { return nil }, // this gets handled seperately in [Config], so we don't actually need to do anything here
Name: "help",
Doc: "show usage information for a command",
Root: true,
},
}
// OnConfigurer represents a configuration object that specifies a method to
// be called at the end of the [config] function, with the command that has
// been parsed as an argument.
type OnConfigurer interface {
OnConfig(cmd string) error
}
// config is the main, high-level configuration setting function,
// processing config files and command-line arguments in the following order:
// - Apply any `default:` field tag default values.
// - Look for `--config`, `--cfg`, or `-c` arg, specifying a config file on the command line.
// - Fall back on default config file name passed to `config` function, if arg not found.
// - Read any `Include[s]` files in config file in deepest-first (natural) order,
// then the specified config file last.
// - If multiple config files are found, then they are applied in reverse order, meaning
// that the first specified file takes the highest precedence.
// - Process command-line args based on config field names.
// - Boolean flags are set on with plain -flag; use No prefix to turn off
// (or explicitly set values to true or false).
//
// config also processes -help and -h by printing the [usage] and quitting immediately.
// It takes [Options] that control its behavior, the configuration struct, which is
// what it sets, and the commands, which it uses for context. Also, it uses [os.Args]
// for its command-line arguments. It returns the command, if any, that was passed in
// [os.Args], and any error that ocurred during the configuration process.
func config[T any](opts *Options, cfg T, cmds ...*Cmd[T]) (string, error) {
var errs []error
err := SetFromDefaults(cfg)
if err != nil {
errs = append(errs, err)
}
args := os.Args[1:]
// first, we do a pass to get the meta command flags
// (help and config), which we need to know before
// we can do other configuration.
mc := &metaConfig{}
// we ignore not found flags in meta config, because we only care about meta config and not anything else being passed to the command
cmd, err := SetFromArgs(mc, args, NoErrNotFound, metaCmds...)
if err != nil {
// if we can't do first set for meta flags, we return immediately (we only do AllErrors for more specific errors)
return cmd, fmt.Errorf("error doing meta configuration: %w", err)
}
logx.UserLevel = logx.LevelFromFlags(mc.VeryVerbose, mc.Verbose, mc.Quiet)
// both flag and command trigger help
if mc.Help || cmd == "help" {
// string version of args slice has [] on the side, so need to get rid of them
mc.HelpCmd = strings.TrimPrefix(strings.TrimSuffix(mc.HelpCmd, "]"), "[")
// if flag and no posargs, will be nil
if mc.HelpCmd == "nil" {
mc.HelpCmd = ""
}
fmt.Println(usage(opts, cfg, mc.HelpCmd, cmds...))
os.Exit(0)
}
var cfgFiles []string
if mc.Config != "" {
cfgFiles = append(cfgFiles, mc.Config)
}
cfgFiles = append(cfgFiles, opts.DefaultFiles...)
if opts.SearchUp {
wd, err := os.Getwd()
if err != nil {
return "", fmt.Errorf("error getting current directory: %w", err)
}
pwd := wd
for {
pwd = wd
wd = filepath.Dir(pwd)
if wd == pwd { // if there is no change, we have reached the root of the filesystem
break
}
opts.IncludePaths = append(opts.IncludePaths, wd)
}
}
if opts.NeedConfigFile && len(cfgFiles) == 0 {
return "", errors.New("cli.Config: no config file or default files specified")
}
slices.Reverse(opts.IncludePaths)
// the files of the user come first, so that the others override them
for _, fn := range opts.UserFiles {
err := tomlx.Open(cfg, fn)
if err == nil {
logx.PrintlnDebug("loaded user config file:", fn)
} else if !errors.Is(err, fs.ErrNotExist) {
errs = append(errs, fmt.Errorf("error loading user config file %q: %w", fn, err))
}
}
gotAny := false
for _, fn := range cfgFiles {
err = openWithIncludes(opts, cfg, fn)
if err == nil {
logx.PrintlnDebug("loaded config file:", fn)
gotAny = true
continue
}
// a missing (default) config file is fine, but a file that exists
// and fails to load (e.g., a TOML syntax error) must be reported,
// instead of silently running with the default config.
if !errors.Is(err, errNoConfigFile) {
errs = append(errs, fmt.Errorf("error loading config file %q: %w", fn, err))
}
}
if !gotAny && opts.NeedConfigFile {
return "", errors.New("cli.Config: no config files found")
}
cmd, err = SetFromArgs(cfg, args, ErrNotFound, cmds...)
if err != nil {
errs = append(errs, err)
}
if cfer, ok := any(cfg).(OnConfigurer); ok {
err := cfer.OnConfig(cmd)
if err != nil {
errs = append(errs, err)
}
}
return cmd, errors.Join(errs...)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cli
import (
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/reflectx"
)
// SetFromDefaults sets the values of the given config object
// from `default:` struct field tag values. Errors are automatically
// logged in addition to being returned.
func SetFromDefaults(cfg any) error {
return errors.Log(reflectx.SetFromDefaultTags(cfg))
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cli
import (
"fmt"
"strings"
"unicode"
"cogentcore.org/core/types"
"github.com/mattn/go-shellwords"
)
// ParseDirective parses and returns a comment directive from
// the given comment string. The returned directive will be nil
// if there is no directive contained in the given comment.
// Directives are of the following form (the slashes are optional):
//
// //tool:directive args...
func ParseDirective(comment string) (*types.Directive, error) {
comment = strings.TrimPrefix(comment, "//")
rs := []rune(comment)
if len(rs) == 0 || unicode.IsSpace(rs[0]) { // directives must not have whitespace as their first character
return nil, nil
}
// directives can not have newlines
if strings.Contains(comment, "\n") {
return nil, nil
}
before, after, found := strings.Cut(comment, ":")
if !found {
return nil, nil
}
directive := &types.Directive{}
directive.Tool = before
args, err := shellwords.Parse(after)
if err != nil {
return nil, fmt.Errorf("error parsing args: %w", err)
}
directive.Args = args
if len(args) > 0 {
directive.Directive = directive.Args[0]
directive.Args = directive.Args[1:]
}
if len(directive.Args) == 0 {
directive.Args = nil
}
return directive, nil
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"cogentcore.org/core/base/logx"
"cogentcore.org/core/cli"
)
//go:generate core generate -add-types -add-funcs
type Config struct {
// the name of the user
Name string `flag:"name,nm,n"`
// the age of the user
Age int
// whether the user likes Go
LikesGo bool
Build BuildConfig `cmd:"build"`
Server Server
Client Client
// the directory to build in
Dir string
}
type BuildConfig struct {
// the target platform to build for
Target string `flag:"target,build-target" posarg:"0"`
// the platform to build the executable for
Platform string `posarg:"1" required:"-"`
}
type Server struct {
// the server platform
Platform string
}
type Client struct {
// the client platform
Platform string `nest:"-"`
}
// Build builds the app for the config platform and target. It builds apps
// across platforms using the GOOS and GOARCH environment variables and a
// suitable C compiler located on the system.
//
// It is the main command used during a local development workflow, and
// it serves as a direct replacement for go build when building Cogent Core
// apps. In addition to the basic capacities of go build, Build supports
// cross-compiling CGO applications with ease. Also, it handles the
// bundling of icons and fonts into the executable.
//
// Build also uses GoMobile to support the building of .apk and .app
// files for Android and iOS mobile platforms, respectively. Its simple,
// unified, and configurable API for building applications makes it
// the best way to build applications, whether for local debug versions
// or production releases.
func Build(c *Config) error {
fmt.Println("Building for target", c.Build.Target, "and platform", c.Build.Platform, "- user likes go:", c.LikesGo)
return nil
}
// Run runs the app for the given user.
func Run(c *Config) error {
fmt.Println("Running for user", c.Name, "- likes go:", c.LikesGo, "- user level:", logx.UserLevel)
return nil
}
// Mod configures module information.
func Mod(c *Config) error {
fmt.Println("running mod")
return nil
}
// ModTidy tidies module information.
//
//cli:cmd -name "mod tidy"
func ModTidy(c *Config) error {
fmt.Println("running mod tidy")
return nil
}
// ModTidyRemote tidies module information for the remote.
//
//cli:cmd -name "mod tidy remote"
func ModTidyRemote(c *Config) error {
fmt.Println("running mod tidy remote")
return nil
}
// ModTidyRemoteSetURL tidies module information for the remote
// and sets its URL.
//
//cli:cmd -name "mod tidy remote set-url"
func ModTidyRemoteSetURL(c *Config) error {
fmt.Println("running mod tidy remote set-url")
return nil
}
func main() { //types:skip
opts := cli.DefaultOptions("Basic", "Basic is a basic example application made with cli.")
cli.Run(opts, &Config{}, Build, Run, Mod, ModTidy, ModTidyRemote, ModTidyRemoteSetURL)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cli
import (
"log/slog"
"os"
"reflect"
"strings"
"slices"
"cogentcore.org/core/base/keylist"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/base/strcase"
)
// field represents a struct field in a configuration struct.
type field struct {
// Field is the reflect struct field object for this field
Field reflect.StructField
// Value is the reflect value of the settable pointer to this field
Value reflect.Value
// Struct is the parent struct that contains this field
Struct reflect.Value
// Name is the fully qualified, nested name of this field (eg: A.B.C).
// It is as it appears in code, and is NOT transformed something like kebab-case.
Name string
// Names contains all of the possible end-user names for this field as a flag.
// It defaults to the name of the field, but custom names can be specified via
// the cli struct tag.
Names []string
}
// fields is a simple type alias for an ordered map of [field] objects.
type fields = keylist.List[string, *field]
// addAllFields, when passed as the command to [addFields], indicates
// to add all fields, regardless of their command association.
const addAllFields = "*"
// addFields adds to the given fields map all of the fields of the given
// object, in the context of the given command name. A value of [addAllFields]
// for cmd indicates to add all fields, regardless of their command association.
func addFields(obj any, allFields *fields, cmd string) {
addFieldsImpl(obj, "", "", allFields, map[string]*field{}, cmd)
}
// addFieldsImpl is the underlying implementation of [addFields].
// The path is the current path state, the cmdPath is the
// current path state without command-associated names,
// and usedNames is a map keyed by used CamelCase names with values
// of their associated fields, used to track naming conflicts. The
// [field.Name]s of the fields are set based on the path, whereas the
// names of the flags are set based on the command path. The difference
// between the two is that the path is always fully qualified, whereas the
// command path omits the names of structs associated with commands via
// the "cmd" struct tag, as the user already knows what command they are
// running, so they do not need that duplicated specificity for every flag.
func addFieldsImpl(obj any, path string, cmdPath string, allFields *fields, usedNames map[string]*field, cmd string) {
ov := reflect.ValueOf(obj)
if reflectx.IsNil(ov) {
return
}
val := reflectx.NonPointerValue(ov)
typ := val.Type()
for i := 0; i < typ.NumField(); i++ {
f := typ.Field(i)
if !f.IsExported() {
continue
}
fv := val.Field(i)
pval := reflectx.PointerValue(fv)
cmdTag, hct := f.Tag.Lookup("cmd")
cmds := strings.Split(cmdTag, ",")
if hct && !slices.Contains(cmds, cmd) && !slices.Contains(cmds, addAllFields) { // if we are associated with a different command, skip
continue
}
if reflectx.NonPointerType(f.Type).Kind() == reflect.Struct {
nwPath := f.Name
if path != "" {
nwPath = path + "." + nwPath
}
nwCmdPath := f.Name
// if we have a command tag, we don't scope our command path with our name,
// as we don't need it because we ran that command and know we are in it
if hct {
nwCmdPath = ""
}
if cmdPath != "" {
nwCmdPath = cmdPath + "." + nwCmdPath
}
addFieldsImpl(reflectx.PointerValue(fv).Interface(), nwPath, nwCmdPath, allFields, usedNames, cmd)
// we still add ourself if we are a struct, so we keep going,
// unless we are associated with a command, in which case there
// is no point in adding ourself
if hct {
continue
}
}
// we first add our unqualified command name, which is the best case scenario
name := f.Name
names := []string{name}
// then, we set our future [Field.Name] to the fully path scoped version (but we don't add it as a command name)
if path != "" {
name = path + "." + name
}
// then, we set add our command path scoped name as a command name
if cmdPath != "" {
names = append(names, cmdPath+"."+f.Name)
}
flagTag, ok := f.Tag.Lookup("flag")
if ok {
names = strings.Split(flagTag, ",")
if len(names) == 0 {
slog.Error("programmer error: expected at least one name in flag struct tag, but got none")
}
// the command path scoped name is still a name, so that a nested
// field can always be set by it, as when a flag name conflicts
// with the name of a struct, e.g., -run.run for Run.Run with
// flag:"run" in a Run struct
if cmdPath != "" {
names = append(names, cmdPath+"."+f.Name)
}
}
nf := &field{
Field: f,
Value: pval,
Struct: ov,
Name: name,
Names: names,
}
for i, name := range nf.Names {
// duplicate deletion can cause us to get out of range
if i >= len(nf.Names) {
break
}
name := strcase.ToCamel(name) // everybody is in camel for naming conflict check
if of, has := usedNames[name]; has { // we have a conflict
// if we have a naming conflict between two fields with the same base
// (in the same parent struct), then there is no nesting and they have
// been directly given conflicting names, so there is a simple programmer error
nbase := ""
nli := strings.LastIndex(nf.Name, ".")
if nli >= 0 {
nbase = nf.Name[:nli]
}
obase := ""
oli := strings.LastIndex(of.Name, ".")
if oli >= 0 {
obase = of.Name[:oli]
}
if nbase == obase {
slog.Error("programmer error: cli: two fields were assigned the same name", "name", name, "field0", of.Name, "field1", nf.Name)
os.Exit(1)
}
// if that isn't the case, they are in different parent structs and
// it is a nesting problem, so we use the nest tags to resolve the conflict.
// the basic rule is that whoever specifies the nest:"-" tag gets to
// be non-nested, and if no one specifies it, everyone is nested.
// if both want to be non-nested, that is a programmer error.
// nest field tag values for new and other
nfns := nf.Field.Tag.Get("nest")
ofns := of.Field.Tag.Get("nest")
// whether new and other get to have non-nested version
nfn := nfns == "-"
ofn := ofns == "-"
if nfn && ofn {
slog.Error(`programmer error: cli: nest:"-" specified on two config fields with the same name; keep nest:"-" on the field you want to be able to access without nesting and remove it from the other one`, "name", name, "field0", of.Name, "field1", nf.Name, "exampleFlagWithoutNesting", "-"+name, "exampleFlagWithNesting", "-"+strcase.ToKebab(nf.Name))
os.Exit(1)
} else if !nfn && !ofn {
// neither one gets it, so we replace both with fully qualified name
applyShortestUniqueName(nf, i, usedNames)
for i, on := range of.Names {
if on == name {
applyShortestUniqueName(of, i, usedNames)
}
}
} else if nfn && !ofn {
// we get it, so we keep ours as is and replace them with fully qualified name
for i, on := range of.Names {
if on == name {
applyShortestUniqueName(of, i, usedNames)
}
}
// we also need to update the field for our name to us
usedNames[name] = nf
} else if !nfn && ofn {
// they get it, so we replace ours with fully qualified name
applyShortestUniqueName(nf, i, usedNames)
}
} else {
// if no conflict, we get the name, unless we are forcing
// nesting, in which case we only get it if it is our full name
nfns := nf.Field.Tag.Get("nest")
if nfns == "+" && name != nf.Name {
nf.Names = slices.Delete(nf.Names, i, i+1) // TODO: is it safe to delete while iterating like this?
} else {
usedNames[name] = nf
}
}
}
allFields.Set(name, nf)
}
}
// applyShortestUniqueName uses [shortestUniqueName] to apply the shortest
// unique name for the given field, in the context of the given
// used names, at the given index.
func applyShortestUniqueName(field *field, idx int, usedNames map[string]*field) {
nm := shortestUniqueName(field.Name, usedNames)
// if we already have this name, we don't need to add it, so we just delete
// this entry (unless this entry is the shortest unique name)
if slices.Contains(field.Names, nm) && field.Names[idx] != nm {
field.Names = slices.Delete(field.Names, idx, idx+1)
} else {
field.Names[idx] = nm
usedNames[nm] = field
}
}
// shortestUniqueName returns the shortest unique camel-case name for
// the given fully qualified nest name of a field, using the given
// map of used names. It works backwards, so, for example, if given "A.B.C.D",
// it would check "D", then "C.D", then "B.C.D", and finally "A.B.C.D".
func shortestUniqueName(name string, usedNames map[string]*field) string {
strs := strings.Split(name, ".")
cur := ""
for ri := len(strs) - 1; ri >= 0; ri-- {
str := strs[ri]
if cur == "" {
cur = str
} else {
cur = str + "." + cur
}
if _, has := usedNames[cur]; !has {
return cur
}
}
// It is actually expected for this to happen, for example, when there is
// a Run struct with a Run field inside it (see TestNestedConfig).
// errors.Log(fmt.Errorf("cli: unexpected error: name %q conflicts with itself", name))
return cur
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// note: FindFileOnPaths adapted from viper package https://github.com/spf13/viper
// Copyright (c) 2014 Steve Francia
package cli
import (
"errors"
"reflect"
"cogentcore.org/core/base/fsx"
"cogentcore.org/core/base/iox/tomlx"
"cogentcore.org/core/base/reflectx"
)
// TODO(kai): this seems bad
// includer is an interface that facilitates processing
// include files in configuration objects.
type includer interface {
// IncludesPtr returns a pointer to the "Includes []string"
// field containing file(s) to include before processing
// the current config file.
IncludesPtr() *[]string
}
// includeStack returns the stack of include files in the natural
// order in which they are encountered (nil if none).
// Files should then be read in reverse order of the slice.
// Returns an error if any of the include files cannot be found on IncludePath.
// Does not alter cfg.
func includeStack(opts *Options, cfg includer) ([]string, error) {
clone := reflect.New(reflectx.NonPointerType(reflect.TypeOf(cfg))).Interface().(includer)
*clone.IncludesPtr() = *cfg.IncludesPtr()
return includeStackImpl(opts, clone, nil)
}
// includeStackImpl implements IncludeStack, operating on cloned cfg
// todo: could use a more efficient method to just extract the include field..
func includeStackImpl(opts *Options, clone includer, includes []string) ([]string, error) {
incs := *clone.IncludesPtr()
ni := len(incs)
if ni == 0 {
return includes, nil
}
for i := ni - 1; i >= 0; i-- {
includes = append(includes, incs[i]) // reverse order so later overwrite earlier
}
var errs []error
for _, inc := range incs {
*clone.IncludesPtr() = nil
err := tomlx.OpenFiles(clone, fsx.FindFilesOnPaths(opts.IncludePaths, inc)...)
if err == nil {
includes, err = includeStackImpl(opts, clone, includes)
if err != nil {
errs = append(errs, err)
}
} else {
errs = append(errs, err)
}
}
return includes, errors.Join(errs...)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cli
import (
"errors"
"fmt"
"cogentcore.org/core/base/fsx"
"cogentcore.org/core/base/iox/tomlx"
)
// errNoConfigFile is returned (wrapped) by [openWithIncludes] when the
// config file is not found, which is not an error for default config files.
var errNoConfigFile = errors.New("no config file found")
// openWithIncludes reads the config struct from the given config file
// using the given options, looking on [Options.IncludePaths] for the file.
// It opens any Includes specified in the given config file in the natural
// include order so that includers overwrite included settings.
// Is equivalent to Open if there are no Includes. It returns an error if
// any of the include files cannot be found on [Options.IncludePaths].
func openWithIncludes(opts *Options, cfg any, file string) error {
files := fsx.FindFilesOnPaths(opts.IncludePaths, file)
if len(files) == 0 {
return fmt.Errorf("OpenWithIncludes: %w for %q", errNoConfigFile, file)
}
err := tomlx.OpenFiles(cfg, files...)
if err != nil {
return err
}
incfg, ok := cfg.(includer)
if !ok {
return err
}
incs, err := includeStack(opts, incfg)
ni := len(incs)
if ni == 0 {
return err
}
for i := ni - 1; i >= 0; i-- {
inc := incs[i]
err = tomlx.OpenFiles(cfg, fsx.FindFilesOnPaths(opts.IncludePaths, inc)...)
if err != nil {
fmt.Println(err)
}
}
// reopen original
err = tomlx.OpenFiles(cfg, fsx.FindFilesOnPaths(opts.IncludePaths, file)...)
if err != nil {
return err
}
*incfg.IncludesPtr() = incs
return err
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cli
import "cogentcore.org/core/base/strcase"
// Options contains the options passed to cli
// that control its behavior.
type Options struct {
// AppName is the name of the cli app.
AppName string
// AppAbout is the description of the cli app.
AppAbout string
// Fatal is whether to, if there is an error in [Run],
// print it and fatally exit the program through [os.Exit]
// with an exit code of 1.
Fatal bool
// PrintSuccess is whether to print a message indicating
// that a command was successful after it is run, unless
// the user passes -q or -quiet to the command, in which
// case the success message will always not be printed.
PrintSuccess bool
// DefaultEncoding is the default encoding format for config files.
// currently toml is the only supported format, but others could be added
// if needed.
DefaultEncoding string
// UserFiles are the absolute paths of the configuration files of the
// user, which are opened before all of the other configuration files,
// so that those override them, if they exist. They have the settings
// of the user for all projects, which are not committed with the
// configuration files of a project.
UserFiles []string
// DefaultFiles are the default configuration file paths
DefaultFiles []string
// IncludePaths is a list of file paths to try for finding config files
// specified in Include field or via the command line --config --cfg or -c args.
// Set this prior to calling Config; default is current directory '.' and 'configs'.
// The include paths are searched in reverse order such that first specified include
// paths get the highest precedence (config files found in earlier include paths
// override those found in later ones).
IncludePaths []string
// SearchUp indicates whether to search up the filesystem
// for the default config file by checking the provided default
// config file location relative to each directory up the tree
SearchUp bool
// NeedConfigFile indicates whether a configuration file
// must be provided for the command to run
NeedConfigFile bool
}
// DefaultOptions returns a new [Options] value
// with standard default values, based on the given
// app name and optional app about info.
func DefaultOptions(name string, about ...string) *Options {
abt := ""
if len(about) > 0 {
abt = about[0]
}
return &Options{
AppName: name,
AppAbout: abt,
Fatal: true,
PrintSuccess: true,
DefaultEncoding: "toml",
DefaultFiles: []string{strcase.ToKebab(name) + ".toml"},
IncludePaths: []string{".", "configs"},
}
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cli
import (
"fmt"
"log/slog"
"os"
"runtime/debug"
"slices"
"strconv"
"strings"
"cogentcore.org/core/base/logx"
"cogentcore.org/core/base/strcase"
"cogentcore.org/core/types"
)
// indent is the value used for indentation in [usage].
var indent = " "
// usage returns a usage string based on the given options,
// configuration struct, current command, and available commands.
// It contains [AppAbout], a list of commands and their descriptions,
// and a list of flags and their descriptions, scoped based on the
// current command and its associated commands and configuration.
// The resulting string contains color escape codes.
func usage[T any](opts *Options, cfg T, cmd string, cmds ...*Cmd[T]) string {
var b strings.Builder
if cmd == "" {
if opts.AppAbout != "" {
b.WriteString("\n")
b.WriteString(opts.AppAbout)
b.WriteString("\n\n")
}
} else {
gotCmd := false
for _, c := range cmds {
if c.Name == cmd {
if c.Doc != "" {
b.WriteString("\n")
b.WriteString(c.Doc)
b.WriteString("\n\n")
}
gotCmd = true
break
}
}
if !gotCmd {
fmt.Println(logx.CmdColor(cmdName()+" help") + logx.ErrorColor(fmt.Sprintf(" failed: command %q not found", cmd)))
os.Exit(1)
}
}
if bi, ok := debug.ReadBuildInfo(); ok {
revision, time := "dev", "unknown"
for _, set := range bi.Settings {
if set.Key == "vcs.revision" {
revision = set.Value
}
if set.Key == "vcs.time" {
time = set.Value
}
}
b.WriteString(logx.TitleColor("Version: "))
fmt.Fprintf(&b, "%s (%s)\n\n", revision, time)
}
fs := &fields{}
addFields(cfg, fs, cmd)
cmdName := cmdName()
if cmd != "" {
cmdName += " " + cmd
}
b.WriteString(logx.TitleColor("Usage:\n"))
b.WriteString(indent)
b.WriteString(logx.CmdColor(cmdName + " "))
posArgStrs := []string{}
for _, v := range fs.Values {
f := v.Field
posArgTag, ok := f.Tag.Lookup("posarg")
if ok {
ui := uint64(0)
if posArgTag == "all" || posArgTag == "leftover" {
ui = uint64(len(posArgStrs))
} else {
var err error
ui, err = strconv.ParseUint(posArgTag, 10, 64)
if err != nil {
slog.Error("programmer error: invalid value for posarg struct tag", "field", f.Name, "posArgTag", posArgTag, "err", err)
}
}
// if the slice isn't big enough, grow it to fit this posarg
if ui >= uint64(len(posArgStrs)) {
posArgStrs = slices.Grow(posArgStrs, len(posArgStrs)-int(ui)+1) // increase capacity
posArgStrs = posArgStrs[:ui+1] // extend to capacity
}
nm := strcase.ToKebab(v.Names[0])
req, has := f.Tag.Lookup("required")
if req == "+" || req == "true" || !has { // default is required, so !has => required
posArgStrs[ui] = logx.CmdColor("<" + nm + ">")
} else {
posArgStrs[ui] = logx.SuccessColor("[" + nm + "]")
}
}
}
b.WriteString(strings.Join(posArgStrs, " "))
if len(posArgStrs) > 0 {
b.WriteString(" ")
}
b.WriteString(logx.SuccessColor("[flags]\n"))
commandUsage(&b, cmdName, cmd, cmds...)
b.WriteString(logx.TitleColor("\nFlags:\n"))
b.WriteString(indent)
b.WriteString(logx.TitleColor("Flags are case-insensitive, can be in kebab-case, snake_case,\n"))
b.WriteString(indent)
b.WriteString(logx.TitleColor("or CamelCase, and can have one or two leading dashes. Use a\n"))
b.WriteString(indent)
b.WriteString(logx.TitleColor("\"no\" prefix to turn off a bool flag.\n\n"))
// add meta ones (help, config, verbose, etc) first
mcfields := &fields{}
addMetaConfigFields(mcfields)
flagUsage(mcfields, &b)
flagUsage(fs, &b)
return b.String()
}
// commandUsage adds the command usage info for the given commands to the
// given [strings.Builder].
// It also takes the full name of our command as it appears in the terminal (cmdName),
// (eg: "core build"), and the name of the command we are running (eg: "build").
//
// To be a command that is included in the usage, we must be one command
// nesting depth (subcommand) deeper than the current command (ie, if we
// are on "x", we can see usage for commands of the form "x y"), and all
// of our commands must be consistent with the current command. For example,
// "" could generate usage for "help", "build", and "run", and "mod" could
// generate usage for "mod init", "mod tidy", and "mod edit". This ensures
// that only relevant commands are shown in the usage.
func commandUsage[T any](b *strings.Builder, cmdName string, cmd string, cmds ...*Cmd[T]) {
acmds := []*Cmd[T]{} // actual commands we care about
var rcmd *Cmd[T] // root command
cmdstrs := strings.Fields(cmd) // subcommand strings in passed command
// need this label so that we can continue outer loop when we have non-matching cmdstr
outer:
for _, c := range cmds {
cstrs := strings.Fields(c.Name) // subcommand strings in command we are checking
if len(cstrs) != len(cmdstrs)+1 { // we must be one deeper
continue
}
for i, cmdstr := range cmdstrs {
if cmdstr != cstrs[i] { // every subcommand so far must match
continue outer
}
}
if c.Root {
rcmd = c
} else if c.Name != cmd { // if it is the same subcommand we are already on, we handle it above in main Usage
acmds = append(acmds, c)
}
}
if len(acmds) != 0 {
b.WriteString(indent)
b.WriteString(logx.CmdColor(cmdName + " <subcommand> "))
b.WriteString(logx.SuccessColor("[flags]\n"))
}
if rcmd != nil {
b.WriteString(logx.TitleColor("\nDefault command:\n"))
b.WriteString(indent)
b.WriteString(logx.CmdColor(rcmd.Name))
b.WriteString("\n")
b.WriteString(indent)
b.WriteString(indent)
b.WriteString(strings.ReplaceAll(rcmd.Doc, "\n", "\n"+indent+indent))
b.WriteString("\n") // need to put two indents on every newline for formatting
}
if len(acmds) == 0 && cmd != "" { // nothing to do
return
}
b.WriteString(logx.TitleColor("\nSubcommands:\n"))
// if we are in root, we also add help
if cmd == "" {
b.WriteString(indent)
b.WriteString(logx.CmdColor("help"))
b.WriteString("\n")
b.WriteString(indent)
b.WriteString(indent)
b.WriteString("Help shows usage information for a command\n")
}
for _, c := range acmds {
b.WriteString(indent)
b.WriteString(logx.CmdColor(c.Name))
if c.Doc != "" {
// we only want the first paragraph of text for subcommand usage; after that is where more specific details can go
doc, _, _ := strings.Cut(c.Doc, "\n\n")
b.WriteString("\n")
b.WriteString(indent)
b.WriteString(indent)
b.WriteString(strings.ReplaceAll(doc, "\n", "\n"+indent+indent)) // need to put two indents on every newline for formatting
}
b.WriteString("\n")
}
}
// flagUsage adds the flag usage info for the given fields
// to the given [strings.Builder].
func flagUsage(fields *fields, b *strings.Builder) {
for _, f := range fields.Values {
b.WriteString(indent)
for i, name := range f.Names {
b.WriteString(logx.CmdColor("-" + strcase.ToKebab(name)))
if i != len(f.Names)-1 {
b.WriteString(", ")
}
}
b.WriteString(" ")
b.WriteString(logx.SuccessColor(f.Field.Type.String()))
b.WriteString("\n")
field := types.GetField(f.Struct, f.Field.Name)
if field != nil {
b.WriteString(indent)
b.WriteString(indent)
b.WriteString(strings.ReplaceAll(field.Doc, "\n", "\n"+indent+indent)) // need to put two indents on every newline for formatting
}
def, ok := f.Field.Tag.Lookup("default")
if ok && def != "" {
fmt.Fprintf(b, " (default: %s)", def)
}
b.WriteString("\n")
}
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Command core provides command line tools for developing apps
// and libraries using the Cogent Core framework.
package main
import (
"cogentcore.org/core/cli"
"cogentcore.org/core/cmd"
"cogentcore.org/core/cmd/config"
"cogentcore.org/core/cmd/generate"
)
func main() {
opts := cli.DefaultOptions("Cogent Core", "Command line tools for developing apps and libraries using the Cogent Core framework.")
if uf := config.UserFile(); uf != "" {
opts.UserFiles = []string{uf} // (overridden by the files of the project)
}
opts.DefaultFiles = []string{"core.toml"}
opts.SearchUp = true
cmd.SetFFmpegEnv() // the FFmpeg of core setup -video, for building apps with video
cli.Run(opts, &config.Config{}, cmd.Setup, cmd.Build, cmd.Run, cmd.Test, cmd.Pack, cmd.Install, generate.Generate, cmd.Changed, cmd.Pull, cmd.Log, cmd.Release, cmd.NextRelease, cmd.Update)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package cmd provides utilities for managing
// apps and packages that use the Cogent Core framework.
package cmd
//go:generate core generate
import (
"errors"
"fmt"
"os"
"path/filepath"
"cogentcore.org/core/base/exec"
"cogentcore.org/core/base/logx"
"cogentcore.org/core/cmd/config"
"cogentcore.org/core/cmd/generate"
"cogentcore.org/core/cmd/mobile"
"cogentcore.org/core/cmd/web"
)
// Build builds an executable for the package
// at the config path for the config platforms.
func Build(c *config.Config) error { //types:add
if len(c.Build.Target) == 0 {
return errors.New("build: expected at least 1 platform")
}
// the go build reports the errors of the app if this fails
if err := generate.ContentCode(".", &c.ContentCode); err != nil {
logx.PrintlnWarn("warning:", err)
}
for _, platform := range c.Build.Target {
err := config.OSSupported(platform.OS)
if err != nil {
return err
}
if platform.Arch != "*" {
err := config.ArchSupported(platform.Arch)
if err != nil {
return err
}
}
if platform.OS == "android" || platform.OS == "ios" || platform.OS == "iossimulator" {
return mobile.Build(c)
}
if platform.OS == "wasm" || platform.OS == "js" {
err := os.MkdirAll(c.Build.Output, 0777)
if err != nil {
return err
}
return web.Build(c)
}
err = buildDesktop(c, platform)
if err != nil {
return fmt.Errorf("build: %w", err)
}
}
return nil
}
// buildDesktop builds an executable for the config package for the given desktop platform.
func buildDesktop(c *config.Config, platform config.Platform) error {
xc := exec.Major()
xc.Env["GOOS"] = platform.OS
xc.Env["GOARCH"] = platform.Arch
args := []string{"build"}
if c.Build.Debug {
args = append(args, "-tags", "debug")
}
if c.Build.Trimpath {
args = append(args, "-trimpath")
}
ldflags := ""
output := filepath.Base(c.Build.Output)
if platform.OS == "windows" {
output += ".exe"
// see https://stackoverflow.com/questions/23250505/how-do-i-create-an-executable-from-golang-that-doesnt-open-a-console-window-whe
if c.Build.Windowsgui {
ldflags += " -H=windowsgui"
}
}
ldflags += " " + config.LinkerFlags(c)
args = append(args, "-ldflags", ldflags, "-o", filepath.Join(c.Build.Output, output))
err := xc.Run("go", args...)
if err != nil {
return fmt.Errorf("error building for platform %s/%s: %w", platform.OS, platform.Arch, err)
}
return nil
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cmd
import (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"sync"
"cogentcore.org/core/base/exec"
"cogentcore.org/core/base/logx"
"cogentcore.org/core/cmd/config"
)
// Changed concurrently prints all of the repositories within this directory
// that have been changed and need to be updated in Git.
func Changed(c *config.Config) error { //types:add
wg := sync.WaitGroup{}
errs := []error{}
errMu := sync.Mutex{}
fs.WalkDir(os.DirFS("."), ".", func(path string, d fs.DirEntry, err error) error {
wg.Go(func() {
if d.Name() != ".git" {
return
}
dir := filepath.Dir(path)
out, err := exec.Major().SetDir(dir).Output("git", "diff")
if err != nil {
errMu.Lock()
errs = append(errs, fmt.Errorf("error getting diff of %q: %w", dir, err))
errMu.Unlock()
return
}
if out != "" { // if we have a diff, we have been changed
fmt.Println(logx.CmdColor(dir))
return
}
// if we don't have a diff, we also check to make sure we aren't ahead of the remote
out, err = exec.Minor().SetDir(dir).Output("git", "status")
if err != nil {
errMu.Lock()
errs = append(errs, fmt.Errorf("error getting status of %q: %w", dir, err))
errMu.Unlock()
return
}
if strings.Contains(out, "Your branch is ahead") { // if we are ahead, we have been changed
fmt.Println(logx.CmdColor(dir))
}
})
return nil
})
wg.Wait()
fmt.Println("")
return errors.Join(errs...)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package config contains the configuration
// structs for the Cogent Core tool.
package config
//go:generate core generate
import (
"fmt"
"io/fs"
"os"
"path/filepath"
"runtime"
"strings"
"unicode"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/exec"
"cogentcore.org/core/base/iox/tomlx"
"cogentcore.org/core/base/strcase"
"cogentcore.org/core/enums/enumgen"
"cogentcore.org/core/types/typegen"
)
// Config is the main config struct that contains all of the configuration
// options for the Cogent Core command line tool.
type Config struct { //types:add
// Name is the user-friendly name of the project.
// The default is based on the current directory name.
Name string
// NamePrefix is the prefix to add to the default name of the project
// and any projects nested below it. A separating space is automatically included.
NamePrefix string
// ID is the bundle / package ID to use for the project
// (required for building for mobile platforms and packaging
// for desktop platforms). It is typically in the format com.org.app
// (eg: com.cogent.mail). It defaults to com.parentDirectory.currentDirectory.
ID string
// About is the about information for the project, which can be viewed via
// the "About" button in the app bar. It is also used when packaging the app.
About string
// the version of the project to release
Version string `cmd:"release" posarg:"0" save:"-"`
// Content, if specified, indicates that the app has core content pages
// located at this directory. If so, a directory tree will be made for all
// of the pages when building for the js and wasm platforms. This defaults
// to "content" when building an app for js or wasm that imports content.
Content string
// Opens are the types of files that the app opens, which the pack and
// install commands declare, so that the systems offer the app in their
// Open with choices of apps for those files, without making it their
// default app: categories of files (as Code or Text) or known types of
// files (as Markdown or TeX), as in cogentcore.org/core/base/fileinfo.
// The app gets the files to open as [events.OSOpenFiles] events,
// [system.App.OpenFiles] when it starts, or its arguments on Linux.
Opens []string
// AppGoSymlink makes the app installed in /Applications on macOS run
// the executable installed by go install (in the Go bin directory),
// which the install command also does, so that go install is enough to
// update the app after that, as for apps that are updated often: the
// app copies it into itself, and signs it, when it starts after it
// changes, as macOS only allows notifications for an executable in
// the app. It is typically set in the core.toml of the user (see
// [UserFile]), for all apps, and a project can set it to false, as when
// its go install executable has the same name as that of another app.
AppGoSymlink bool
// Video installs (setup) or updates (update) FFmpeg, which the video
// package (cogentcore.org/core/video) needs on desktop platforms:
// with Homebrew on macOS, and as the prebuilt builds of BtbN on Linux
// and Windows, which the core command builds and runs apps with.
Video bool `cmd:"setup,update"`
// AndroidSim installs (setup) the Android SDK, with the Android
// emulator, and makes an Android virtual device for it (named Cogent),
// which core run android boots when no Android device is connected.
AndroidSim bool `cmd:"setup"`
// JS installs (setup) the tools of the js platform: GoScript and bun,
// which build apps to JavaScript, and tsrs, the TypeScript type checker
// that core test js uses.
JS bool `cmd:"setup"`
// Print prints (setup) the system packages that setup installs for the
// current platform, separated by spaces, without installing anything:
// on Linux, the packages for the package manager of its distribution
// (nothing on other platforms). Continuous integration workflows use
// it to install and cache the packages (as the setup-core action of
// the cogentcore/core repository does), so that the list is only
// defined here. Use it with -q, so that only the packages are printed.
Print bool `cmd:"setup"`
// the configuration options for the build, install, run, and pack commands
// (and the target platform of the test command)
Build Build `cmd:"build,install,run,pack,test"`
// the configuration options for the test command
Test Test `cmd:"test"`
// the configuration information for the pack command
Pack Pack `cmd:"pack"`
// the configuration information for web
Web Web `cmd:"build,install,run,pack"`
// the configuration options for the log and run commands
Log Log `cmd:"log,run"`
// the configuration options for the generate command
Generate Generate `cmd:"generate"`
// ContentCode has the options for compiling the code blocks of content
// apps into them, which the build, install, run, pack, and generate
// commands do (see cogentcore.org/core/content/contentcode).
ContentCode ContentCode `cmd:"build,install,run,pack,generate"`
// the configuration options for the update command
Update Update `cmd:"update"`
}
// Test has the options of the test command.
type Test struct { //types:add
// Packages are the packages to test, as for go test. They default to
// the package in the current directory. For the js platform, a pattern
// with ... in it only matches the packages that opt in with a
// //core:js-test line in one of their test files (see the goscript
// package in base).
Packages []string `posarg:"leftover" required:"-"`
// Run, if non-empty, only runs the tests matching this regular
// expression, as with go test -run.
Run string
// Bench, if non-empty, runs the benchmarks matching this regular
// expression, as with go test -bench.
Bench string
// BenchTime is the minimum time to run each benchmark, as a duration
// such as 2s, as with go test -benchtime.
BenchTime string
// Timeout, if non-empty, is the maximum time to run the tests of each
// package, as a duration such as 10m, as with go test -timeout (for the
// js platform, it replaces the timeout of a //core:js-test line).
Timeout string
// Browser runs the tests of all of the packages for the js platform
// in Chrome, instead of only those whose //core:js-test line says so
// (the others run in bun).
Browser bool
}
type Build struct { //types:add
// the target platforms to build executables for
Target []Platform `flag:"t,target" posarg:"0" required:"-" save:"-"`
// Dir is the directory to build the app from.
// It defaults to the current directory.
Dir string
// Output is the directory to output the built app to.
// It defaults to the current directory for desktop executables
// and "bin/{platform}" for all other platforms and command "pack".
Output string `flag:"o,output"`
// Debug is whether to build/run the app in debug mode, which sets
// the "debug" tag when building and prevents the default stripping
// of debug symbols. On iOS and Android, this also prints the program output.
Debug bool `flag:"d,debug"`
// Ldflags are optional additional linker flags to pass to go build commands.
Ldflags string
// Trimpath is whether to replace file system paths with module paths
// in the resulting executable. It is on by default for commands other
// than core run.
Trimpath bool `default:"true"`
// Windowsgui is whether to make this a "Windows GUI" application that
// opens without a terminal window on Windows. It is on by default for
// commands other than core run.
Windowsgui bool `default:"true"`
// the minimum version of the iOS SDK to compile against
IOSVersion string `default:"13.0"`
// the minimum supported Android SDK (uses-sdk/android:minSdkVersion in AndroidManifest.xml)
AndroidMinSDK int `default:"23" min:"23"`
// the target Android SDK version (uses-sdk/android:targetSdkVersion in AndroidManifest.xml)
AndroidTargetSDK int `default:"35"`
}
type Pack struct { //types:add
// whether to build a .dmg file on macOS in addition to a .app file.
// This is automatically disabled for the install command.
DMG bool `default:"true"`
}
type Log struct { //types:add
// the target platform to view the logs for (ios or android)
Target string `default:"android"`
// whether to keep the previous log messages or clear them
Keep bool `default:"false"`
// messages not generated from your app equal to or above this log level will be shown
All string `default:"F"`
}
// Update has the options for the update command, which updates the core
// command and the tools that it uses.
type Update struct { //types:add
// Check only reports which tools have updates, without updating them.
Check bool
// Force updates tools that were built from a local source checkout
// (such as with go install in a clone), or that are newer than the
// latest version, which are otherwise left as they are, so that such
// a version is not replaced by accident.
Force bool
}
type Generate struct { //types:add
// the enum generation configuration options passed to enumgen
Enumgen enumgen.Config
// the generation configuration options passed to typegen
Typegen typegen.Config
// the source directory to run generate on (can be multiple through ./...)
Dir string `default:"." posarg:"0" required:"-" nest:"-"`
// Icons, if specified, indicates to generate an icongen.go file with
// icon variables for the icon svg files in the specified folder.
Icons string
}
// ContentCode has the options for compiling the code blocks of content apps
// into them (see cogentcore.org/core/content/contentcode). They add to the
// arguments of a go:generate directive that runs contentcode, if there is one.
type ContentCode struct { //types:add
// Imports are other packages that code blocks can use without
// importing them, as import paths or name=path.
Imports []string
// GoalRecord is whether Goal math mode records its variables in tensorfs
// and lists tensorfs to the output of the code block, as the Goal
// interpreter of Cogent Lab (cogentcore.org/lab/mvmlab) does. Turn it
// off for sites whose Goal interpreter does not.
GoalRecord bool `default:"true"`
// Interpret are pages whose code blocks are not compiled into the app,
// so that they run in the interpreter, as markdown files in the content
// directory, with or without the .md extension, which can have the
// wildcards of path.Match. On the web, an interpreter that is in
// Web.DeferredFunctions is then loaded, with the packages that the code
// uses, only when such a page is shown.
Interpret []string
}
// UserFile returns the path of the configuration file of the user for all
// projects, which is opened before the core.toml files of a project, so
// that those override it: core.toml in the Cogent Core data directory of
// the user (~/Library/Cogent Core on macOS, ~/.config/Cogent Core on Linux,
// and AppData/Roaming/Cogent Core on Windows), as for options of the user
// that are not committed with a project, such as AppGoSymlink.
// It is "" if the home directory of the user is unknown.
func UserFile() string {
home, err := os.UserHomeDir()
if err != nil {
return ""
}
dir := filepath.Join(home, ".config")
switch runtime.GOOS {
case "darwin":
dir = filepath.Join(home, "Library")
case "windows":
dir = filepath.Join(home, "AppData", "Roaming")
}
return filepath.Join(dir, "Cogent Core", "core.toml")
}
func (c *Config) OnConfig(cmd string) error {
// if we have no target, we assume it is our current platform,
// unless we are in init, in which case we do not want to set
// the config file to be specific to our platform
if len(c.Build.Target) == 0 && cmd != "init" {
c.Build.Target = []Platform{{OS: runtime.GOOS, Arch: runtime.GOARCH}}
}
if c.Build.Output == "" && len(c.Build.Target) > 0 {
t := c.Build.Target[0]
if cmd == "pack" || t.OS == "wasm" || t.OS == "js" || t.OS == "android" || t.OS == "ios" || t.OS == "iossimulator" {
c.Build.Output = filepath.Join("bin", t.OS)
}
}
// we must make the output dir absolute before changing the current directory
out, err := filepath.Abs(c.Build.Output)
if err != nil {
return err
}
c.Build.Output = out
if c.Build.Dir != "" {
err := os.Chdir(c.Build.Dir)
if err != nil {
return err
}
// re-read the config file from the new location if it exists
err = tomlx.Open(c, "core.toml")
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return err
}
}
// we must do auto-naming after we apply any directory change above
if c.Name == "" || c.ID == "" {
cdir, err := os.Getwd()
if err != nil {
return fmt.Errorf("error finding current directory: %w", err)
}
base := filepath.Base(cdir)
if c.Name == "" {
c.Name = strcase.ToTitle(base)
if c.NamePrefix != "" {
c.Name = c.NamePrefix + " " + c.Name
}
}
if c.ID == "" {
dir := filepath.Dir(cdir)
// if our directory starts with a v and then has only digits, it is a version directory
// so we go up another directory to get to the actual directory
if len(dir) > 1 && dir[0] == 'v' && !strings.ContainsFunc(dir[1:], func(r rune) bool {
return !unicode.IsDigit(r)
}) {
dir = filepath.Dir(dir)
}
dir = filepath.Base(dir)
// we ignore anything after any dot in the directory name
dir, _, _ = strings.Cut(dir, ".")
// the default ID is "com.dir.base", which is relatively likely
// to be close to "com.org.app", the intended format
c.ID = "com." + dir + "." + base
}
}
if cmd == "run" {
c.Build.Trimpath = false
c.Build.Windowsgui = false
}
return nil
}
// linkerX returns the -X linker flag (with a space after it) that sets the
// given string variable to the given value. The go command splits the
// -ldflags into flags with quotes, but a quoted flag can not have its quote
// character in it, as there are no escapes, so the flag is quoted with single
// quotes, or with double quotes if the value has single quotes in it (as
// "O'Reilly" does). If the value has both, its single quotes are replaced with
// the given replacement, such as the typographic apostrophe for text and the
// ' character reference for SVG.
func linkerX(name, value, replace string) string {
q := "'"
if strings.Contains(value, "'") {
if strings.Contains(value, `"`) {
value = strings.ReplaceAll(value, "'", replace)
} else {
q = `"`
}
}
return "-X " + q + name + "=" + value + q + " "
}
// LinkerFlags returns the ld linker flags that specify the app and core version,
// the app about information, the app icon, and the optional [Build.Ldflags].
func LinkerFlags(c *Config) string {
res := ""
if c.Build.Ldflags != "" {
res += c.Build.Ldflags + " "
}
if !c.Build.Debug {
// See https://stackoverflow.com/questions/30005878/avoid-debugging-information-on-golang and go.dev/issues/25148.
res += "-s -w "
}
if c.ID != "" {
res += linkerX("cogentcore.org/core/system.AppID", c.ID, "")
}
if c.About != "" {
res += linkerX("cogentcore.org/core/core.AppAbout", c.About, "’")
}
b, err := os.ReadFile("icon.svg")
if err != nil {
if !errors.Is(err, fs.ErrNotExist) {
errors.Log(err)
}
} else {
res += linkerX("cogentcore.org/core/core.AppIcon", string(b), "'")
}
// TODO: maybe replace this linker flag version injection logic with
// [debug.ReadBuildInfo] at some point; we currently support it as a
// backup in system/app.go, but it is less reliable and formats worse,
// so we won't use it as a full replacement yet (see
// https://github.com/cogentcore/core/issues/1370).
av, err := exec.Silent().Output("git", "describe", "--tags")
if err == nil {
res += "-X cogentcore.org/core/system.AppVersion=" + av + " "
}
// workspaces can interfere with getting the right version
cv, err := exec.Silent().SetEnv("GOWORK", "off").Output("go", "list", "-m", "-f", "{{.Version}}", "cogentcore.org/core")
if err == nil {
// we must be in core itself if it is blank
if cv == "" {
cv = av
}
res += "-X cogentcore.org/core/system.CoreVersion=" + cv
}
return res
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package config
import (
"errors"
"fmt"
"strings"
)
// Note: the maps in this file are derived from https://github.com/golang/go/blob/master/src/go/build/syslist.go
// Platform is a platform with an operating system and an architecture
type Platform struct {
OS string
Arch string
}
// String returns the platform as a string in the form "os/arch"
func (p Platform) String() string {
return p.OS + "/" + p.Arch
}
// OSSupported determines whether the given operating system is supported by Cogent Core. If it is, it returns nil.
// If it isn't, it returns an error detailing the issue with the operating system (not found or not supported).
func OSSupported(os string) error {
// The web platform of earlier versions is now two platforms.
if os == "web" {
return errors.New("the web platform has been replaced by js and wasm: use js (recommended; compiles to JavaScript with GoScript) or wasm (compiles to WebAssembly)")
}
supported, ok := supportedOS[os]
if !ok {
return fmt.Errorf("could not find operating system %s; please check that you spelled it correctly", os)
}
if !supported {
return fmt.Errorf("operating system %s exists but is not supported by Cogent Core", os)
}
return nil
}
// ArchSupported determines whether the given architecture is supported by Cogent Core. If it is, it returns nil.
// If it isn't, it also returns an error detailing the issue with the architecture (not found or not supported).
func ArchSupported(arch string) error {
supported, ok := supportedArch[arch]
if !ok {
return fmt.Errorf("could not find architecture %s; please check that you spelled it correctly", arch)
}
if !supported {
return fmt.Errorf("architecture %s exists but is not supported by Cogent Core", arch)
}
return nil
}
// SetString sets the platform from the given string of format os[/arch]
func (p *Platform) SetString(platform string) error {
before, after, found := strings.Cut(platform, "/")
p.OS = before
err := OSSupported(before)
if err != nil {
return fmt.Errorf("error parsing platform: %w", err)
}
if !found {
p.Arch = "*"
return nil
}
p.Arch = after
err = ArchSupported(after)
if err != nil {
return fmt.Errorf("error parsing platform: %w", err)
}
return nil
}
// ArchsForOS returns contains all of the architectures supported for
// each operating system.
var ArchsForOS = map[string][]string{
"darwin": {"386", "amd64", "arm", "arm64"},
"windows": {"386", "amd64", "arm", "arm64"},
"linux": {"386", "amd64", "arm", "arm64"},
"android": {"386", "amd64", "arm", "arm64"},
"ios": {"arm64"},
// the iOS simulator, on the Mac with the same architecture
"iossimulator": {"arm64", "amd64"},
}
// supportedOS is a map containing all operating systems and whether they are supported by Cogent Core.
var supportedOS = map[string]bool{
"aix": false,
"android": true,
"darwin": true,
"dragonfly": false,
"freebsd": false,
"hurd": false,
"illumos": false,
"ios": true,
// iossimulator is the iOS simulator (GOOS ios), on macOS
"iossimulator": true,
"js": true,
"wasm": true,
"linux": true,
"nacl": false,
"netbsd": false,
"openbsd": false,
"plan9": false,
"solaris": false,
"wasip1": false,
"windows": true,
"zos": false,
}
// supportedArch is a map containing all computer architectures and whether they are supported by Cogent Core.
var supportedArch = map[string]bool{
"386": true,
"amd64": true,
"amd64p32": true,
"arm": true,
"armbe": true,
"arm64": true,
"arm64be": true,
"loong64": false,
"mips": false,
"mipsle": false,
"mips64": false,
"mips64le": false,
"mips64p32": false,
"mips64p32le": false,
"ppc": false,
"ppc64": false,
"ppc64le": false,
"riscv": false,
"riscv64": false,
"s390": false,
"s390x": false,
"sparc": false,
"sparc64": false,
"wasm": true,
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cmd
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"runtime"
"slices"
"strconv"
"strings"
"time"
"cogentcore.org/core/base/exec"
"cogentcore.org/core/base/logx"
)
// The video package (cogentcore.org/core/video) decodes video on desktop
// platforms with FFmpeg through go-astiav, which requires the development
// libraries of one major version of FFmpeg: [ffmpegVersion]. core setup
// -video installs them, and core update -video updates them:
// - on macOS, with Homebrew (ffmpeg, or ffmpeg@9 once Homebrew has moved
// on to a newer FFmpeg);
// - on Linux and Windows (amd64 and arm64), as the prebuilt shared LGPL
// builds of BtbN (https://github.com/BtbN/FFmpeg-Builds), which are
// extracted into [ffmpegDir], as the FFmpeg packages of most systems
// are older; FFmpeg of the system is used if it is the right version.
// The core command then builds and runs apps with the FFmpeg in
// [ffmpegDir] (see [SetFFmpegEnv]).
const (
// ffmpegVersion is the version of FFmpeg that the go-astiav version of
// the video package requires (see its README), which must be updated
// with go-astiav in go.mod.
ffmpegVersion = "9.0"
// ffmpegAvutilMajor is the major version of libavutil of [ffmpegVersion],
// by which an installed FFmpeg is checked.
ffmpegAvutilMajor = 61
// ffmpegReleases is the GitHub API URL of the release of BtbN that has
// the latest builds of each version of FFmpeg, which are made daily.
ffmpegReleases = "https://api.github.com/repos/BtbN/FFmpeg-Builds/releases/tags/latest"
)
// ffmpegMajor returns the major version of [ffmpegVersion].
func ffmpegMajor() string {
major, _, _ := strings.Cut(ffmpegVersion, ".")
return major
}
// ffmpegDir returns the directory that the FFmpeg of BtbN is installed in,
// in the cache directory of the user, or "" if there is none.
func ffmpegDir() string {
dir, err := os.UserCacheDir()
if err != nil {
return ""
}
return filepath.Join(dir, "cogentcore", "ffmpeg")
}
// ffmpegInstalled returns whether the FFmpeg of BtbN is installed in
// [ffmpegDir], with its pkg-config files.
func ffmpegInstalled() bool {
dir := ffmpegDir()
if dir == "" {
return false
}
_, err := os.Stat(filepath.Join(dir, "lib", "pkgconfig", "libavutil.pc"))
return err == nil
}
// SetFFmpegEnv sets the environment of the core command for building and
// running apps with the FFmpeg installed in [ffmpegDir] by core setup
// -video, if any: its pkg-config files, and its shared libraries for the
// apps (an rpath on Linux, and the PATH on Windows, for core run). With
// FFmpeg of Homebrew that is not linked (ffmpeg@9), its pkg-config files.
func SetFFmpegEnv() {
prepend := func(name, value string) {
if old := os.Getenv(name); old != "" {
value += string(os.PathListSeparator) + old
}
os.Setenv(name, value)
}
if ffmpegInstalled() {
dir := ffmpegDir()
prepend("PKG_CONFIG_PATH", filepath.Join(dir, "lib", "pkgconfig"))
switch runtime.GOOS {
case "linux":
lib := filepath.Join(dir, "lib")
os.Setenv("CGO_LDFLAGS", strings.TrimSpace(os.Getenv("CGO_LDFLAGS")+" -Wl,-rpath,"+lib))
case "windows":
prepend("PATH", filepath.Join(dir, "bin"))
}
return
}
if runtime.GOOS == "darwin" {
// a versioned formula is keg-only (not linked), so it is not found
// by pkg-config without its path
formula := "ffmpeg@" + ffmpegMajor()
pc := filepath.Join(brewPrefix(), "opt", formula, "lib", "pkgconfig")
if _, err := os.Stat(pc); err == nil {
prepend("PKG_CONFIG_PATH", pc)
}
}
}
// brewPrefix returns the prefix of Homebrew, /opt/homebrew on Apple
// silicon and /usr/local on Intel.
func brewPrefix() string {
if runtime.GOARCH == "arm64" {
return "/opt/homebrew"
}
return "/usr/local"
}
// systemFFmpegOK returns whether pkg-config finds FFmpeg of [ffmpegVersion],
// and its version.
func systemFFmpegOK() (bool, string) {
v, err := exec.Silent().Output("pkg-config", "--modversion", "libavutil")
if err != nil {
return false, ""
}
v = strings.TrimSpace(v)
major, _, _ := strings.Cut(v, ".")
m, err := strconv.Atoi(major)
return err == nil && m == ffmpegAvutilMajor, v
}
// setupFFmpeg installs FFmpeg for the video package (see ffmpeg.go), or
// updates it if update.
func setupFFmpeg(update bool) error {
if _, err := exec.LookPath("pkg-config"); err != nil {
// (go-astiav finds FFmpeg with it; Homebrew installs it with ffmpeg)
defer logx.PrintlnError("pkg-config is needed to build with FFmpeg; install it with the package manager of the system (as pkg-config or pkgconf)")
}
if runtime.GOOS == "darwin" {
return setupFFmpegBrew(update)
}
if ok, v := systemFFmpegOK(); ok && !ffmpegInstalled() {
logx.PrintlnWarn("FFmpeg " + ffmpegVersion + " is already installed on the system (libavutil " + v + ")")
return nil
}
return setupFFmpegBtbN(update)
}
// setupFFmpegBrew installs or updates FFmpeg with Homebrew.
func setupFFmpegBrew(update bool) error {
if _, err := exec.LookPath("brew"); err != nil {
return errors.New("installing FFmpeg for video needs Homebrew: see https://brew.sh")
}
// the ffmpeg formula, if it is of the version, or else the formula of
// the version (as Homebrew keeps ffmpeg@7 and ffmpeg@8 for older ones)
formula := "ffmpeg"
out, err := exec.Silent().Output("brew", "info", "--json=v2", "--formula", "ffmpeg")
if err != nil {
return err
}
var info struct {
Formulae []struct {
Versions struct{ Stable string }
}
}
if err := json.Unmarshal([]byte(out), &info); err != nil || len(info.Formulae) == 0 {
return fmt.Errorf("reading the version of the ffmpeg formula of Homebrew: %w", err)
}
if !strings.HasPrefix(info.Formulae[0].Versions.Stable, ffmpegMajor()+".") {
formula = "ffmpeg@" + ffmpegMajor()
}
vc := exec.Verbose().SetBuffer(false)
if update {
logx.PrintlnWarn("updating FFmpeg (" + formula + ") with Homebrew")
if err := vc.Run("brew", "upgrade", formula); err == nil {
return nil
}
}
logx.PrintlnWarn("installing FFmpeg (" + formula + ") with Homebrew")
return vc.Run("brew", "install", formula)
}
// btbnAsset is an asset of the release of BtbN.
type btbnAsset struct {
Name string `json:"name"`
URL string `json:"browser_download_url"`
UpdatedAt time.Time `json:"updated_at"`
Size int64 `json:"size"`
}
// btbnAssetName returns the name of the asset of the prebuilt shared LGPL
// build of BtbN of [ffmpegVersion] for the given platform, or "" if there
// is none.
func btbnAssetName(goos, goarch string) string {
var plat, ext string
switch goos + "/" + goarch {
case "linux/amd64":
plat, ext = "linux64", "tar.xz"
case "linux/arm64":
plat, ext = "linuxarm64", "tar.xz"
case "windows/amd64":
plat, ext = "win64", "zip"
case "windows/arm64":
plat, ext = "winarm64", "zip"
default:
return ""
}
return fmt.Sprintf("ffmpeg-n%s-latest-%s-lgpl-shared-%s.%s", ffmpegVersion, plat, ffmpegVersion, ext)
}
// setupFFmpegBtbN installs or updates the prebuilt FFmpeg of BtbN in
// [ffmpegDir]. It is only downloaded again for an update with a newer
// build than the installed one.
func setupFFmpegBtbN(update bool) error {
name := btbnAssetName(runtime.GOOS, runtime.GOARCH)
dir := ffmpegDir()
if name == "" || dir == "" {
return fmt.Errorf("there is no prebuilt FFmpeg for %s/%s: install the development libraries of FFmpeg %s yourself (found with pkg-config)", runtime.GOOS, runtime.GOARCH, ffmpegVersion)
}
stamp := filepath.Join(dir, "core-build.txt") // the asset and its time (see installFFmpegArchive)
if ffmpegInstalled() && !update {
logx.PrintlnWarn("FFmpeg " + ffmpegVersion + " is already installed in " + dir)
return nil
}
asset, err := btbnLatest(name)
if err != nil {
return err
}
want := asset.Name + " " + asset.UpdatedAt.UTC().Format(time.RFC3339)
if b, err := os.ReadFile(stamp); err == nil && ffmpegInstalled() && strings.TrimSpace(string(b)) == want {
logx.PrintlnWarn("FFmpeg " + ffmpegVersion + " in " + dir + " is up to date")
return nil
}
logx.PrintlnWarn(fmt.Sprintf("downloading FFmpeg %s (%s, %d MB)", ffmpegVersion, asset.Name, asset.Size>>20))
if err := os.MkdirAll(filepath.Dir(dir), 0777); err != nil {
return err
}
tmp, err := os.MkdirTemp(filepath.Dir(dir), "ffmpeg-download-")
if err != nil {
return err
}
defer os.RemoveAll(tmp)
archive := filepath.Join(tmp, asset.Name)
if err := download(asset.URL, archive); err != nil {
return err
}
if err := installFFmpegArchive(archive, dir, want); err != nil {
return err
}
logx.PrintlnWarn("installed FFmpeg " + ffmpegVersion + " in " + dir)
return nil
}
// installFFmpegArchive extracts the given archive of BtbN into the given
// directory of FFmpeg, replacing it, and records the given stamp of its
// build in it. The archive has one top directory (the name of the asset
// without its extension), which becomes the directory. Both GNU tar (with
// xz) and the tar of Windows (bsdtar) extract the archives.
func installFFmpegArchive(archive, dir, stamp string) error {
tmp, err := os.MkdirTemp(filepath.Dir(dir), "ffmpeg-extract-")
if err != nil {
return err
}
defer os.RemoveAll(tmp)
name := filepath.Base(archive)
if err := exec.Verbose().SetBuffer(false).Run("tar", "-xf", archive, "-C", tmp); err != nil {
return fmt.Errorf("extracting %s: %w", name, err)
}
top := strings.TrimSuffix(strings.TrimSuffix(name, ".zip"), ".tar.xz")
if _, err := os.Stat(filepath.Join(tmp, top, "lib", "pkgconfig")); err != nil {
return fmt.Errorf("%s has no %s/lib/pkgconfig", name, top)
}
if err := os.RemoveAll(dir); err != nil {
return err
}
if err := os.Rename(filepath.Join(tmp, top), dir); err != nil {
return err
}
return os.WriteFile(filepath.Join(dir, "core-build.txt"), []byte(stamp+"\n"), 0666)
}
// btbnLatest returns the asset of the given name of the latest release
// of BtbN.
func btbnLatest(name string) (*btbnAsset, error) {
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Get(ffmpegReleases)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("getting the release of the FFmpeg builds: %s", resp.Status)
}
var rel struct {
Assets []btbnAsset `json:"assets"`
}
if err := json.NewDecoder(resp.Body).Decode(&rel); err != nil {
return nil, err
}
for i := range rel.Assets {
if rel.Assets[i].Name == name {
return &rel.Assets[i], nil
}
}
return nil, fmt.Errorf("the FFmpeg builds have no %s", name)
}
// download downloads the given URL to the given file.
func download(url, file string) error {
client := &http.Client{Timeout: 15 * time.Minute}
resp, err := client.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("downloading %s: %s", url, resp.Status)
}
f, err := os.Create(file)
if err != nil {
return err
}
if _, err := io.Copy(f, resp.Body); err != nil {
f.Close()
return err
}
return f.Close()
}
// ffmpegWindowsFiles returns the files of FFmpeg to package with the app
// in the current directory for Windows, if it uses FFmpeg (the video
// package, without the novideo build tag): the DLLs of the FFmpeg of BtbN
// in [ffmpegDir], which the app needs next to its executable, and the
// license of FFmpeg (LGPL), which goes with them.
func ffmpegWindowsFiles() ([]string, error) {
// (CGO_ENABLED, which is off by default for another platform, as the
// package of go-astiav is only cgo)
out, err := exec.Silent().SetEnv("GOOS", "windows").SetEnv("CGO_ENABLED", "1").Output("go", "list", "-deps", ".")
if err != nil {
return nil, fmt.Errorf("finding whether the app uses FFmpeg: %w", err)
}
if !slices.Contains(strings.Fields(out), "github.com/asticode/go-astiav") {
return nil, nil
}
dir := ffmpegDir()
dlls, _ := filepath.Glob(filepath.Join(dir, "bin", "*.dll"))
if len(dlls) == 0 {
return nil, errors.New("the app uses FFmpeg (the video package), whose DLLs are not installed: run core setup -video on Windows, or build the app with the novideo build tag")
}
if lic := filepath.Join(dir, "LICENSE.txt"); fileExists(lic) {
dlls = append(dlls, lic)
}
return dlls, nil
}
// fileExists returns whether the given file exists.
func fileExists(file string) bool {
_, err := os.Stat(file)
return err == nil
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package generate
import (
"fmt"
"slices"
"cogentcore.org/core/cmd/config"
"cogentcore.org/core/content/contentcode"
)
// ContentCode compiles the Go and Goal code blocks of the content of the app
// in dir into the app if it is a content app (see [contentcode.App]), with
// the options of cc (from core.toml). It does nothing if they are up to date.
func ContentCode(dir string, cc *config.ContentCode) error {
c, err := contentcode.App(dir)
if err != nil || c == nil {
return err
}
for _, im := range cc.Imports {
if !slices.Contains(c.Imports, im) {
c.Imports = append(c.Imports, im)
}
}
c.GoalRecord = c.GoalRecord && cc.GoalRecord
c.Interpret = append(c.Interpret, cc.Interpret...)
if _, err := contentcode.Generate(c); err != nil {
return fmt.Errorf("compiling the code blocks of the content: %w", err)
}
return nil
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package generate provides the generation
// of useful methods, variables, and constants
// for Cogent Core code.
package generate
//go:generate core generate
import (
"fmt"
"path/filepath"
"slices"
"text/template"
"cogentcore.org/core/base/generate"
"cogentcore.org/core/base/keylist"
"cogentcore.org/core/cmd/config"
"cogentcore.org/core/enums/enumgen"
"cogentcore.org/core/types"
"cogentcore.org/core/types/typegen"
"golang.org/x/tools/go/packages"
)
// treeMethodsTmpl is a template that contains the methods
// and functions specific to [tree.Node] types.
var treeMethodsTmpl = template.Must(template.New("TreeMethods").
Funcs(template.FuncMap{
"HasEmbedDirective": hasEmbedDirective,
"HasNoNewDirective": hasNoNewDirective,
"DocToComment": typegen.DocToComment,
"TreePkg": treePkg,
}).Parse(
`
{{if not (HasNoNewDirective .)}}
// New{{.LocalName}} returns a new [{{.LocalName}}] with the given optional parent:
{{DocToComment .Doc}}
func New{{.LocalName}}(parent ...{{TreePkg .}}Node) *{{.LocalName}} { return {{TreePkg .}}New[{{.LocalName}}](parent...) }
{{end}}
{{if HasEmbedDirective .}}
// {{.LocalName}}Embedder is an interface that all types that embed {{.LocalName}} satisfy
type {{.LocalName}}Embedder interface {
As{{.LocalName}}() *{{.LocalName}}
}
// As{{.LocalName}} returns the given value as a value of type {{.LocalName}} if the type
// of the given value embeds {{.LocalName}}, or nil otherwise
func As{{.LocalName}}(n {{TreePkg .}}Node) *{{.LocalName}} {
if t, ok := n.({{.LocalName}}Embedder); ok {
return t.As{{.LocalName}}()
}
return nil
}
// As{{.LocalName}} satisfies the [{{.LocalName}}Embedder] interface
func (t *{{.LocalName}}) As{{.LocalName}}() *{{.LocalName}} { return t }
{{end}}
`,
))
// treePkg returns the package identifier for the tree package in
// the context of the given type ("" if it is already in the tree
// package, and "tree." otherwise)
func treePkg(typ *typegen.Type) string {
if typ.Pkg == "tree" { // we are already in tree
return ""
}
return "tree."
}
// hasEmbedDirective returns whether the given [typegen.Type] has a "core:embedder"
// comment directive. This function is used in [treeMethodsTmpl].
func hasEmbedDirective(typ *typegen.Type) bool {
return slices.ContainsFunc(typ.Directives, func(d types.Directive) bool {
return d.Tool == "core" && d.Directive == "embedder"
})
}
// hasNoNewDirective returns whether the given [typegen.Type] has a "core:no-new"
// comment directive. This function is used in [treeMethodsTmpl].
func hasNoNewDirective(typ *typegen.Type) bool {
return slices.ContainsFunc(typ.Directives, func(d types.Directive) bool {
return d.Tool == "core" && d.Directive == "no-new"
})
}
// Generate is the main entry point to code generation
// that does all of the generation according to the
// given config info. It overrides the
// [config.Config.Generate.Typegen.InterfaceConfigs] info.
func Generate(c *config.Config) error { //types:add
c.Generate.Typegen.InterfaceConfigs = &keylist.List[string, *typegen.Config]{}
c.Generate.Typegen.InterfaceConfigs.Add("cogentcore.org/core/tree.Node", &typegen.Config{
AddTypes: true,
Setters: true,
Templates: []*template.Template{treeMethodsTmpl},
})
pkgs, err := parsePackages(c)
if err != nil {
return fmt.Errorf("Generate: error parsing package: %w", err)
}
err = enumgen.GeneratePkgs(&c.Generate.Enumgen, pkgs)
if err != nil {
return fmt.Errorf("error running enumgen: %w", err)
}
err = typegen.GeneratePkgs(&c.Generate.Typegen, pkgs)
if err != nil {
return fmt.Errorf("error running typegen: %w", err)
}
err = Icons(c)
if err != nil {
return fmt.Errorf("error running icongen: %w", err)
}
// the code blocks of content apps, after the types they may use
for _, pkg := range pkgs {
if pkg.Name != "main" || len(pkg.GoFiles) == 0 {
continue
}
err = ContentCode(filepath.Dir(pkg.GoFiles[0]), &c.ContentCode)
if err != nil {
return err
}
}
return nil
}
// parsePackages parses the package(s) based on the given config info.
func parsePackages(cfg *config.Config) ([]*packages.Package, error) {
pcfg := &packages.Config{
Mode: enumgen.PackageModes() | typegen.PackageModes(&cfg.Generate.Typegen), // need superset of both
// TODO: Need to think about constants in test files. Maybe write type_string_test.go
// in a separate pass? For later.
Tests: false,
}
return generate.Load(pcfg, cfg.Generate.Dir)
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package generate
import (
"bytes"
"io/fs"
"os"
"path/filepath"
"strings"
"text/template"
"unicode"
"cogentcore.org/core/base/generate"
"cogentcore.org/core/base/strcase"
"cogentcore.org/core/cmd/config"
)
// iconData contains the data for an icon
type iconData struct {
Dir string // Dir is the directory in which the icon is contained
Snake string // Snake is the snake_case name of the icon
Camel string // Camel is the CamelCase name of the icon
IconsPackage string // IconsPackage is "icons." or ""
}
var iconTmpl = template.Must(template.New("icon").Parse(
`
//go:embed {{.Dir}}{{.Snake}}.svg
{{.Camel}} {{.IconsPackage}}Icon`,
))
// Icons does any necessary generation for icons.
func Icons(c *config.Config) error {
if c.Generate.Icons == "" {
return nil
}
b := &bytes.Buffer{}
wd, err := os.Getwd()
if err != nil {
return err
}
generate.PrintHeader(b, filepath.Base(wd))
b.WriteString(`import _ "embed"
var (`)
fs.WalkDir(os.DirFS(c.Generate.Icons), ".", func(path string, d fs.DirEntry, err error) error {
if d.IsDir() || filepath.Ext(path) != ".svg" {
return nil
}
name := strings.TrimSuffix(path, ".svg")
// ignore blank icon, as we define the constant for that separately
if name == "blank" {
return nil
}
camel := strcase.ToCamel(name)
// identifier names can't start with a digit
if unicode.IsDigit([]rune(camel)[0]) {
camel = "X" + camel
}
data := iconData{
Snake: name,
Camel: camel,
}
data.Dir = c.Generate.Icons + "/"
if data.Dir == "./" {
data.Dir = ""
}
if !strings.HasSuffix(wd, filepath.Join("core", "icons")) {
data.IconsPackage = "icons."
}
return iconTmpl.Execute(b, data)
})
b.WriteString("\n)\n")
return generate.Write("icongen.go", b.Bytes(), nil)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cmd
import (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"runtime"
"strings"
"cogentcore.org/core/base/exec"
"cogentcore.org/core/base/logx"
"cogentcore.org/core/cmd/config"
"cogentcore.org/core/cmd/generate"
"cogentcore.org/core/cmd/mobile"
)
// Install installs the package on the local system.
// It uses the same config info as build.
// lsregister is the path of the macOS tool that registers apps
// with Launch Services.
const lsregister = "/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister"
func Install(c *config.Config) error { //types:add
for i, p := range c.Build.Target {
err := config.OSSupported(p.OS)
if err != nil {
return fmt.Errorf("install: %w", err)
}
if p.Arch == "*" {
if p.OS == "android" || p.OS == "ios" {
p.Arch = "arm64"
} else {
p.Arch = runtime.GOARCH
}
c.Build.Target[i] = p
}
switch p.OS {
case "android", "ios":
err := Build(c)
if err != nil {
return fmt.Errorf("error building: %w", err)
}
// we only want this target for install
ot := c.Build.Target
c.Build.Target = []config.Platform{p}
err = mobile.Install(c)
c.Build.Target = ot
if err != nil {
return fmt.Errorf("install: %w", err)
}
case "wasm", "js":
return fmt.Errorf("can not install on platform %s; use build or run instead", p.OS)
case "darwin":
c.Pack.DMG = false
err := Pack(c)
if err != nil {
return err
}
app := filepath.Join("/Applications", c.Name+".app")
if err := removeExecutable(appExecutable(c, app)); err != nil {
return err
}
err = exec.Run("cp", "-a", filepath.Join(c.Build.Output, c.Name+".app"), "/Applications")
if err != nil {
return err
}
if c.AppGoSymlink {
if err := goSymlinkApp(c, app); err != nil {
return err
}
}
if err := signApp(c, app); err != nil {
return err
}
if len(c.Opens) == 0 {
return nil
}
// so that the system knows the types of files that it opens now
return exec.Run(lsregister, "-f", app)
default:
if err := generate.ContentCode(".", &c.ContentCode); err != nil {
logx.PrintlnWarn("warning:", err)
}
return exec.Major().SetEnv("GOOS", p.OS).SetEnv("GOARCH", runtime.GOARCH).Run("go", "install")
}
}
return nil
}
// appExecutable returns the path of the executable of the given macOS app
// of the given config, as packed by [Pack].
func appExecutable(c *config.Config, app string) string {
return filepath.Join(app, "Contents", "MacOS", c.Name+".app")
}
// removeExecutable removes the given executable of an installed app, if
// it exists, before a new one is copied there: cp writes over a file in
// place, which macOS then kills when it starts, with an invalid code
// signature, as it keeps the signature of the file that was there.
func removeExecutable(file string) error {
if err := os.Remove(file); err != nil && !errors.Is(err, fs.ErrNotExist) {
return err
}
return nil
}
// goSymlinkApp installs the app of the given config with go install, and
// makes the executable of the given macOS app run the one that it installs
// (see [config.Config.AppGoSymlink]): the executable is a script that
// copies it into the app, next to the script, and signs it and the app,
// when it changes, and runs the copy. The executable that runs must be a
// file in the app (not a symbolic link, which macOS runs the target of),
// signed with the ID of the app, for macOS to allow notifications, for
// example. The script is run once here, with CORE_APP_UPDATE set, which
// only updates the copy.
func goSymlinkApp(c *config.Config, app string) error {
if err := exec.Major().Run("go", "install"); err != nil {
return err
}
target, err := exec.Output("go", "list", "-f", "{{.Target}}")
if err != nil {
return err
}
target = strings.TrimSpace(target)
if target == "" {
return fmt.Errorf("AppGoSymlink: go install does not install an executable here")
}
exe := appExecutable(c, app)
cp := filepath.Join(filepath.Dir(exe), filepath.Base(target))
for _, f := range []string{exe, cp} {
if err := os.Remove(f); err != nil && !os.IsNotExist(err) {
return err
}
}
id := shellQuote(c.ID)
sign := shellQuote(signIdentity())
script := `#!/bin/sh
# Runs the app installed by go install (AppGoSymlink), which is copied
# into the app and signed when it changes, as macOS only allows
# notifications for an executable in an app that is signed with its ID.
src=` + shellQuote(target) + `
exe="$(dirname "$0")"/` + shellQuote(filepath.Base(cp)) + `
if [ ! -e "$exe" ] || [ "$src" -nt "$exe" ]; then
if cp "$src" "$exe.new" && codesign -s ` + sign + ` -f -i ` + id + ` "$exe.new" && mv -f "$exe.new" "$exe"; then
codesign -s ` + sign + ` -f -i ` + id + ` "$(dirname "$0")/../.."
else
rm -f "$exe.new"
fi
fi
[ -n "$CORE_APP_UPDATE" ] && exit 0
exec "$exe" "$@"
`
if err := os.WriteFile(exe, []byte(script), 0o755); err != nil {
return err
}
if err := exec.Major().SetEnv("CORE_APP_UPDATE", "1").Run(exe); err != nil {
return err
}
if _, err := os.Stat(cp); err != nil {
return fmt.Errorf("AppGoSymlink: the executable was not copied into the app: %w", err)
}
return nil
}
// signApp signs the given macOS app with [signIdentity], with the ID of
// the given config, as macOS only allows notifications for an app that is
// signed with its ID, which the signature of the Go linker does not have.
func signApp(c *config.Config, app string) error {
return exec.Major().Run("codesign", "-s", signIdentity(), "-f", "-i", c.ID, app)
}
// signIdentity returns the identity for signing macOS apps that are
// installed: the first Apple Development certificate, or else "-" to sign
// ad hoc. The notifications that an app schedules belong to its
// signature, and an ad hoc one changes with every build, so the scheduled
// notifications of the previous builds can no longer be removed, and are
// all shown, whereas those of a certificate stay the same.
func signIdentity() string {
out, err := exec.Silent().Output("security", "find-identity", "-v", "-p", "codesigning")
if err != nil {
return "-"
}
return parseSignIdentity(out)
}
// parseSignIdentity returns the hash of the first Apple Development
// identity in the given output of security find-identity, or "-".
func parseSignIdentity(out string) string {
for line := range strings.Lines(out) {
f := strings.Fields(line)
if len(f) >= 3 && strings.HasSuffix(f[0], ")") && strings.Contains(line, `"Apple Development:`) {
return f[1]
}
}
return "-"
}
// shellQuote returns the given text quoted for a shell.
func shellQuote(s string) string {
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cmd
import (
"errors"
"fmt"
"cogentcore.org/core/base/exec"
"cogentcore.org/core/cmd/config"
"cogentcore.org/core/cmd/mobile"
)
// Log prints the logs from your app running on Android to the terminal.
// Android is the only supported platform for log; use the -debug flag on
// run for other platforms.
func Log(c *config.Config) error { //types:add
if c.Log.Target != "android" {
return errors.New("only android is supported for log; use the -debug flag on run for other platforms")
}
if !c.Log.Keep {
err := exec.Run(mobile.AndroidTool("adb"), "logcat", "-c")
if err != nil {
return fmt.Errorf("error clearing logs: %w", err)
}
}
// we are logging continiously so we can't buffer, and we must be verbose
err := exec.Verbose().SetBuffer(false).Run(mobile.AndroidTool("adb"), "logcat", "*:"+c.Log.All, "Go:D", "GoLog:D", "GoLogWGPU:D")
if err != nil {
return fmt.Errorf("erroring getting logs: %w", err)
}
return nil
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mobile
import (
"encoding/xml"
"errors"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"slices"
"strconv"
"strings"
"time"
cexec "cogentcore.org/core/base/exec"
"cogentcore.org/core/base/logx"
"cogentcore.org/core/cmd/mobile/sdkpath"
)
// The Android emulator: core setup -androidsim installs the Android SDK
// (its command line tools, platform tools, emulator, an NDK, and a system
// image of [androidSimAPI] for the architecture of the system) with the
// sdkmanager of the SDK, and makes an Android virtual device (AVD) named
// [AndroidSimAVD]. core run android then runs apps on a connected Android
// device, or else boots the emulator (see [AndroidDevice]).
const (
// androidRepo is the URL of the repository of the packages of the
// Android SDK, whose index ([androidRepoIndex]) has their archives.
androidRepo = "https://dl.google.com/android/repository/"
// androidRepoIndex is the index of the packages of the Android SDK.
androidRepoIndex = androidRepo + "repository2-3.xml"
// androidSimAPI is the Android API level of the system image of the
// emulator (a stable one, with the Google APIs).
androidSimAPI = 36
// AndroidSimAVD is the name of the Android virtual device of the
// emulator that core setup -androidsim makes.
AndroidSimAVD = "Cogent"
)
// androidSimDevices are the hardware profiles for [AndroidSimAVD], in order
// of preference: the first one that avdmanager has (older versions of it
// do not have the newer ones).
var androidSimDevices = []string{"pixel_9", "pixel_8", "pixel_7", "pixel_6", "pixel_5", "pixel_4", "pixel"}
// AndroidTool returns the path of the given tool of the Android SDK (adb,
// emulator, sdkmanager, or avdmanager), or else just its name, to be found
// on the path.
func AndroidTool(name string) string {
sdk, err := sdkpath.AndroidHomePath()
if err != nil {
return name
}
exe := ""
if runtime.GOOS == "windows" {
exe = ".exe"
}
var path string
switch name {
case "adb":
path = filepath.Join(sdk, "platform-tools", "adb"+exe)
case "emulator":
path = filepath.Join(sdk, "emulator", "emulator"+exe)
default:
if runtime.GOOS == "windows" {
exe = ".bat"
}
path = filepath.Join(sdk, "cmdline-tools", "latest", "bin", name+exe)
}
if _, err := os.Stat(path); err != nil {
return name
}
return path
}
// androidSimImage returns the sdkmanager package of the system image of
// the emulator, for the architecture of the system.
func androidSimImage() string {
abi := "x86_64"
if runtime.GOARCH == "arm64" {
abi = "arm64-v8a"
}
return fmt.Sprintf("system-images;android-%d;google_apis;%s", androidSimAPI, abi)
}
// SetupAndroidSim installs the Android SDK and makes the AVD of the
// emulator (see the comment above [AndroidSimAVD]): the command line tools
// from [androidRepo] if they are not installed, which need Java (a JDK,
// which it installs with Homebrew on macOS if there is none), and then the
// rest with their sdkmanager, accepting their licenses. It only installs
// an NDK if there is none.
func SetupAndroidSim() error {
sdk, err := sdkpath.AndroidHomePath()
if err != nil {
return err
}
logx.PrintlnWarn("setting up the Android SDK and emulator in " + sdk)
if err := os.MkdirAll(sdk, 0755); err != nil {
return err
}
vc := cexec.Verbose().SetBuffer(false).SetEnv("ANDROID_HOME", sdk)
if err := setJavaHome(vc); err != nil {
return err
}
var pkgs []repoPackage // (the index, if needed)
index := func() ([]repoPackage, error) {
if pkgs == nil {
pkgs, err = androidRepoPackages()
}
return pkgs, err
}
// the command line tools, with sdkmanager
if AndroidTool("sdkmanager") == "sdkmanager" {
ps, err := index()
if err != nil {
return err
}
if err := installCmdlineTools(sdk, ps); err != nil {
return fmt.Errorf("installing the Android command line tools: %w", err)
}
}
sm := AndroidTool("sdkmanager")
yes := strings.Repeat("y\n", 100) // (accepts all of the licenses)
logx.PrintlnWarn("accepting the licenses of the Android SDK")
lc := cexec.Silent().SetStdin(strings.NewReader(yes))
lc.Env = vc.Env // (ANDROID_HOME and JAVA_HOME)
if _, err := lc.Output(sm, "--licenses"); err != nil {
return fmt.Errorf("accepting the licenses of the Android SDK: %w", err)
}
// the packages: the platform tools (adb), the emulator, its system
// image, and an NDK, for building apps, if there is none
install := []string{"cmdline-tools;latest", "platform-tools", "emulator", androidSimImage()}
if !hasNDK(sdk) {
ps, err := index()
if err != nil {
return err
}
ndk := latestStable(ps, "ndk;")
if ndk == "" {
return errors.New("no stable NDK in the index of the Android SDK")
}
install = append(install, ndk)
}
if err := vc.SetStdin(strings.NewReader(yes)).Run(sm, append([]string{"--install"}, install...)...); err != nil {
return fmt.Errorf("installing %s: %w", strings.Join(install, ", "), err)
}
return makeAndroidSimAVD(vc)
}
// setJavaHome sets JAVA_HOME in the given config for the tools of the
// Android SDK, which need Java 17 or later, if java does not run as it is:
// on macOS, that of java_home, or else that of the openjdk of Homebrew,
// which it installs if needed.
func setJavaHome(vc *cexec.Config) error {
if os.Getenv("JAVA_HOME") != "" {
return nil
}
if _, err := cexec.Silent().Output("java", "-version"); err == nil {
return nil
}
notFound := errors.New("the tools of the Android SDK need Java (a JDK of version 17 or later), which is not installed: install it (as the openjdk package of the system), and run this again")
if runtime.GOOS != "darwin" {
return notFound
}
if home, err := cexec.Silent().Output("/usr/libexec/java_home"); err == nil && strings.TrimSpace(home) != "" {
vc.SetEnv("JAVA_HOME", strings.TrimSpace(home))
return nil
}
if _, err := exec.LookPath("brew"); err != nil {
return notFound
}
if err := vc.Run("brew", "install", "openjdk"); err != nil {
return fmt.Errorf("installing Java (openjdk) with Homebrew: %w", err)
}
prefix, err := cexec.Silent().Output("brew", "--prefix")
if err != nil {
return err
}
vc.SetEnv("JAVA_HOME", filepath.Join(strings.TrimSpace(prefix), "opt", "openjdk", "libexec", "openjdk.jdk", "Contents", "Home"))
return nil
}
// hasNDK returns whether the given Android SDK has an NDK.
func hasNDK(sdk string) bool {
ndks, _ := filepath.Glob(filepath.Join(sdk, "ndk", "*", "source.properties"))
_, err := os.Stat(filepath.Join(sdk, "ndk-bundle", "source.properties"))
return len(ndks) > 0 || err == nil
}
// makeAndroidSimAVD makes [AndroidSimAVD], if there is none, with the
// avdmanager of the SDK, with the keyboard of the computer enabled for it.
func makeAndroidSimAVD(vc *cexec.Config) error {
if slices.Contains(androidAVDs(), AndroidSimAVD) {
logx.PrintlnWarn("the Android virtual device " + AndroidSimAVD + " already exists")
return nil
}
am := AndroidTool("avdmanager")
out, err := cexec.Silent().Output(am, "list", "device", "-c")
if err != nil {
return fmt.Errorf("listing the hardware profiles of avdmanager: %w", err)
}
device := androidSimDevice(strings.Fields(out))
// (no to a custom hardware profile)
err = vc.SetStdin(strings.NewReader("no\n")).Run(am, "create", "avd",
"-n", AndroidSimAVD, "-k", androidSimImage(), "-d", device)
if err != nil {
return fmt.Errorf("making the Android virtual device %s: %w", AndroidSimAVD, err)
}
home, err := os.UserHomeDir()
if err != nil {
return err
}
ini := filepath.Join(home, ".android", "avd", AndroidSimAVD+".avd", "config.ini")
if avdHome := os.Getenv("ANDROID_AVD_HOME"); avdHome != "" {
ini = filepath.Join(avdHome, AndroidSimAVD+".avd", "config.ini")
}
b, err := os.ReadFile(ini)
if err != nil {
return err
}
return os.WriteFile(ini, []byte(setIniValue(string(b), "hw.keyboard", "yes")), 0644)
}
// setIniValue returns the given ini file (key=value lines, as the
// config.ini of an AVD) with the given key set to the given value.
func setIniValue(ini, key, value string) string {
lines := strings.Split(strings.TrimSuffix(ini, "\n"), "\n")
set := false
for i, l := range lines {
if k, _, ok := strings.Cut(l, "="); ok && strings.TrimSpace(k) == key {
lines[i] = key + "=" + value
set = true
}
}
if !set {
lines = append(lines, key+"="+value)
}
return strings.Join(lines, "\n") + "\n"
}
// androidSimDevice returns the hardware profile of [AndroidSimAVD] from the
// given ones of avdmanager: the first one of [androidSimDevices] that it
// has, or else the last pixel one (the newest), or else the first one.
func androidSimDevice(devices []string) string {
for _, d := range androidSimDevices {
if slices.Contains(devices, d) {
return d
}
}
for _, d := range slices.Backward(devices) {
if strings.HasPrefix(d, "pixel") {
return d
}
}
if len(devices) > 0 {
return devices[0]
}
return "pixel"
}
// androidAVDs returns the names of the Android virtual devices.
func androidAVDs() []string {
out, err := cexec.Silent().Output(AndroidTool("emulator"), "-list-avds")
if err != nil {
return nil
}
var avds []string
for l := range strings.SplitSeq(out, "\n") {
l = strings.TrimSpace(l)
// (it can log about its setup, as INFO lines)
if l != "" && !strings.Contains(l, " ") {
avds = append(avds, l)
}
}
return avds
}
// repoPackage is a package of the index of the Android SDK.
type repoPackage struct {
Path string `xml:"path,attr"`
Channel struct {
Ref string `xml:"ref,attr"`
} `xml:"channelRef"`
Archives []struct {
URL string `xml:"complete>url"`
HostOS string `xml:"host-os"`
HostArch string `xml:"host-arch"`
} `xml:"archives>archive"`
}
// androidRepoPackages returns the packages of the index of the Android SDK.
func androidRepoPackages() ([]repoPackage, error) {
client := &http.Client{Timeout: time.Minute}
resp, err := client.Get(androidRepoIndex)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("getting the index of the Android SDK: %s", resp.Status)
}
return parseRepoPackages(resp.Body)
}
// parseRepoPackages returns the packages of the given index of the
// Android SDK.
func parseRepoPackages(r io.Reader) ([]repoPackage, error) {
var repo struct {
Packages []repoPackage `xml:"remotePackage"`
}
if err := xml.NewDecoder(r).Decode(&repo); err != nil {
return nil, fmt.Errorf("reading the index of the Android SDK: %w", err)
}
return repo.Packages, nil
}
// latestStable returns the path of the latest stable package with the
// given prefix of its path and a version after it (as ndk;29.0.14206865).
func latestStable(pkgs []repoPackage, prefix string) string {
best, bestV := "", []int(nil)
for _, p := range pkgs {
if p.Channel.Ref != "channel-0" || !strings.HasPrefix(p.Path, prefix) {
continue
}
v := versionNumbers(strings.TrimPrefix(p.Path, prefix))
if v == nil {
continue
}
if best == "" || slices.Compare(v, bestV) > 0 {
best, bestV = p.Path, v
}
}
return best
}
// versionNumbers returns the numbers of the given dotted version, or nil
// if it is not one.
func versionNumbers(v string) []int {
var nums []int
for s := range strings.SplitSeq(v, ".") {
n, err := strconv.Atoi(s)
if err != nil {
return nil
}
nums = append(nums, n)
}
return nums
}
// archiveURL returns the URL of the archive of the given package of the
// index for the given system (GOOS and GOARCH), or "" if there is none.
func archiveURL(pkgs []repoPackage, path, goos, goarch string) string {
hostOS := map[string]string{"darwin": "macosx", "linux": "linux", "windows": "windows"}[goos]
hostArch := map[string]string{"arm64": "aarch64", "amd64": "x64"}[goarch]
for _, p := range pkgs {
if p.Path != path {
continue
}
for _, a := range p.Archives {
if a.HostOS == hostOS && (a.HostArch == "" || a.HostArch == hostArch) {
return androidRepo + a.URL
}
}
}
return ""
}
// installCmdlineTools installs the latest command line tools of the
// Android SDK from the given index into the given SDK, as
// cmdline-tools/latest, where sdkmanager updates them.
func installCmdlineTools(sdk string, pkgs []repoPackage) error {
url := archiveURL(pkgs, "cmdline-tools;latest", runtime.GOOS, runtime.GOARCH)
if url == "" {
return fmt.Errorf("no command line tools for %s/%s in the index", runtime.GOOS, runtime.GOARCH)
}
tmp, err := os.MkdirTemp(sdk, "cmdline-tools-")
if err != nil {
return err
}
defer os.RemoveAll(tmp)
zip := filepath.Join(tmp, filepath.Base(url))
logx.PrintlnWarn("downloading " + url)
if err := downloadFile(url, zip); err != nil {
return err
}
// (the zip has a cmdline-tools directory; tar extracts zips on all
// of the platforms, as bsdtar on macOS and Windows)
if err := cexec.Verbose().SetBuffer(false).Run("tar", "-xf", zip, "-C", tmp); err != nil {
return fmt.Errorf("extracting %s: %w", filepath.Base(zip), err)
}
dir := filepath.Join(sdk, "cmdline-tools")
if err := os.MkdirAll(dir, 0755); err != nil {
return err
}
latest := filepath.Join(dir, "latest")
if err := os.RemoveAll(latest); err != nil {
return err
}
return os.Rename(filepath.Join(tmp, "cmdline-tools"), latest)
}
// downloadFile downloads the given URL to the given file.
func downloadFile(url, file string) error {
client := &http.Client{Timeout: 15 * time.Minute}
resp, err := client.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("downloading %s: %s", url, resp.Status)
}
f, err := os.Create(file)
if err != nil {
return err
}
if _, err := io.Copy(f, resp.Body); err != nil {
f.Close()
return err
}
return f.Close()
}
// androidDevice is a device of adb devices.
type androidDevice struct {
serial, state string
}
// emulator returns whether the device is an emulator.
func (d androidDevice) emulator() bool {
return strings.HasPrefix(d.serial, "emulator-")
}
// androidDevices returns the devices of adb devices.
func androidDevices() ([]androidDevice, error) {
out, err := cexec.Silent().Output(AndroidTool("adb"), "devices")
if err != nil {
return nil, err
}
return parseAndroidDevices(out), nil
}
// parseAndroidDevices returns the devices of the given output of adb
// devices.
func parseAndroidDevices(out string) []androidDevice {
var devs []androidDevice
for l := range strings.SplitSeq(out, "\n") {
f := strings.Fields(l)
if len(f) == 2 && f[0] != "List" {
devs = append(devs, androidDevice{f[0], f[1]})
}
}
return devs
}
// AndroidDevice returns the serial of the Android device to run apps on:
// that of ANDROID_SERIAL, or else a connected device, preferring a phone
// (not an emulator) for when a phone is plugged in while the emulator is
// running, or else the emulator, which it boots with [AndroidSimAVD] (or
// the first AVD, if there is no [AndroidSimAVD]; see core setup
// -androidsim), waiting for it to finish booting.
func AndroidDevice() (string, error) {
if s := os.Getenv("ANDROID_SERIAL"); s != "" {
return s, nil
}
devs, err := androidDevices()
if err != nil {
return "", fmt.Errorf("listing the Android devices with adb (see core setup -androidsim): %w", err)
}
if s := chooseAndroidDevice(devs); s != "" {
return s, nil
}
return bootAndroidSim()
}
// chooseAndroidDevice returns the serial of the device of the given ones
// to run apps on, preferring a phone to an emulator, or "" if none is
// ready.
func chooseAndroidDevice(devs []androidDevice) string {
var ready []androidDevice
for _, d := range devs {
switch d.state {
case "device":
ready = append(ready, d)
case "unauthorized":
logx.PrintlnWarn("the Android device " + d.serial + " is unauthorized: allow USB debugging on it")
}
}
slices.SortStableFunc(ready, func(a, b androidDevice) int {
if a.emulator() == b.emulator() {
return 0
} else if a.emulator() {
return 1
}
return -1
})
if len(ready) == 0 {
return ""
}
if len(ready) > 1 {
logx.PrintlnWarn("running on the Android device " + ready[0].serial + "; set ANDROID_SERIAL to choose another one")
}
return ready[0].serial
}
// bootAndroidSim boots the emulator with [AndroidSimAVD] (or the first AVD,
// if there is no [AndroidSimAVD]), and returns its serial, once it has
// finished booting. The emulator keeps running.
func bootAndroidSim() (string, error) {
avds := androidAVDs()
if len(avds) == 0 {
return "", errors.New("no Android device is connected, and there is no Android virtual device for the emulator: run core setup -androidsim to make one")
}
avd := avds[0]
if slices.Contains(avds, AndroidSimAVD) {
avd = AndroidSimAVD
}
logx.PrintlnWarn("booting the Android emulator with " + avd)
cmd := exec.Command(AndroidTool("emulator"), "-avd", avd)
if err := cmd.Start(); err != nil {
return "", fmt.Errorf("starting the Android emulator: %w", err)
}
go cmd.Wait() // (it keeps running after this process exits)
serial := ""
deadline := time.Now().Add(3 * time.Minute)
for time.Now().Before(deadline) {
time.Sleep(time.Second)
if serial == "" {
devs, _ := androidDevices()
for _, d := range devs {
if d.emulator() {
serial = d.serial
}
}
continue
}
out, err := cexec.Silent().Output(AndroidTool("adb"), "-s", serial, "shell", "getprop", "sys.boot_completed")
if err == nil && strings.TrimSpace(out) == "1" {
return serial, nil
}
}
return "", errors.New("the Android emulator did not finish booting in 3 minutes")
}
// AndroidDeviceArch returns the Go architecture of the given Android
// device (from its primary ABI), or "" if it is not known.
func AndroidDeviceArch(serial string) string {
out, err := cexec.Silent().Output(AndroidTool("adb"), "-s", serial, "shell", "getprop", "ro.product.cpu.abi")
if err != nil {
return ""
}
return map[string]string{"arm64-v8a": "arm64", "armeabi-v7a": "arm", "x86_64": "amd64", "x86": "386"}[strings.TrimSpace(out)]
}
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:generate go run genarsc.go
//go:generate stringer -output binres_string.go -type ResType,DataType
// Package binres implements encoding and decoding of android binary resources.
//
// Binary resource structs support unmarshalling the binary output of aapt.
// Implementations of marshalling for each struct must produce the exact input
// sent to unmarshalling. This allows tests to validate each struct representation
// of the binary format as follows:
//
// - unmarshal the output of aapt
// - marshal the struct representation
// - perform byte-to-byte comparison with aapt output per chunk header and body
//
// This process should strive to make structs idiomatic to make parsing xml text
// into structs trivial.
//
// Once the struct representation is validated, tests for parsing xml text
// into structs can become self-referential as the following holds true:
//
// - the unmarshalled input of aapt output is the only valid target
// - the unmarshalled input of xml text may be compared to the unmarshalled
// input of aapt output to identify errors, e.g. text-trims, wrong flags, etc
//
// This provides validation, byte-for-byte, for producing binary xml resources.
//
// It should be made clear that unmarshalling binary resources is currently only
// in scope for proving that the BinaryMarshaler works correctly. Any other use
// is currently out of scope.
//
// A simple view of binary xml document structure:
//
// XML
// Pool
// Map
// Namespace
// [...node]
//
// Additional resources:
// https://android.googlesource.com/platform/frameworks/base/+/master/libs/androidfw/include/androidfw/ResourceTypes.h
// https://justanapplication.wordpress.com/2011/09/13/ (a series of articles, increment date)
package binres
import (
"encoding"
"encoding/binary"
"encoding/xml"
"errors"
"fmt"
"io"
"slices"
"sort"
"strconv"
"strings"
"unicode"
)
func errWrongType(have ResType, want ...ResType) error {
return fmt.Errorf("wrong resource type %s, want one of %v", have, want)
}
type ResType uint16
func (t ResType) IsSupported() bool {
return t != ResNull
}
// explicitly defined for clarity and resolvability with apt source
const (
ResNull ResType = 0x0000
ResStringPool ResType = 0x0001
ResTable ResType = 0x0002
ResXML ResType = 0x0003
ResXMLStartNamespace ResType = 0x0100
ResXMLEndNamespace ResType = 0x0101
ResXMLStartElement ResType = 0x0102
ResXMLEndElement ResType = 0x0103
ResXMLCharData ResType = 0x0104
ResXMLResourceMap ResType = 0x0180
ResTablePackage ResType = 0x0200
ResTableType ResType = 0x0201
ResTableTypeSpec ResType = 0x0202
ResTableLibrary ResType = 0x0203
ResTableOverlayable ResType = 0x0204
ResTableOverlayablePolicy ResType = 0x0205
ResTableStagedAlias ResType = 0x0206
)
var (
btou16 = binary.LittleEndian.Uint16
btou32 = binary.LittleEndian.Uint32
putu16 = binary.LittleEndian.PutUint16
putu32 = binary.LittleEndian.PutUint32
)
// unmarshaler wraps BinaryUnmarshaler to provide byte size of decoded chunks.
type unmarshaler interface {
encoding.BinaryUnmarshaler
// size returns the byte size unmarshalled after a call to
// UnmarshalBinary, or otherwise zero.
size() int
}
// chunkHeader appears at the front of every data chunk in a resource.
type chunkHeader struct {
// Type of data that follows this header.
typ ResType
// Advance slice index by this value to find its associated data, if any.
headerByteSize uint16
// This is the header size plus the size of any data associated with the chunk.
// Advance slice index by this value to completely skip its contents, including
// any child chunks. If this value is the same as headerByteSize, there is
// no data associated with the chunk.
byteSize uint32
}
// size implements unmarshaler.
func (hdr chunkHeader) size() int { return int(hdr.byteSize) }
func (hdr *chunkHeader) UnmarshalBinary(bin []byte) error {
hdr.typ = ResType(btou16(bin))
if !hdr.typ.IsSupported() {
return fmt.Errorf("%s not supported", hdr.typ)
}
hdr.headerByteSize = btou16(bin[2:])
hdr.byteSize = btou32(bin[4:])
if len(bin) < int(hdr.byteSize) {
return fmt.Errorf("too few bytes to unmarshal chunk body, have %v, need at-least %v", len(bin), hdr.byteSize)
}
return nil
}
func (hdr chunkHeader) MarshalBinary() ([]byte, error) {
if !hdr.typ.IsSupported() {
return nil, fmt.Errorf("%s not supported", hdr.typ)
}
bin := make([]byte, 8)
putu16(bin, uint16(hdr.typ))
putu16(bin[2:], hdr.headerByteSize)
putu32(bin[4:], hdr.byteSize)
return bin, nil
}
type XML struct {
chunkHeader
Pool *Pool
Map *Map
Namespace *Namespace
Children []*Element
// tmp field used when unmarshalling binary
stack []*Element
}
// RawValueByName returns the original raw string value of first matching element attribute, or error if not exists.
// Given <manifest package="VAL" ...> then RawValueByName("manifest", xml.Name{Local: "package"}) returns "VAL".
func (bx *XML) RawValueByName(elname string, attrname xml.Name) (string, error) {
elref, err := bx.Pool.RefByName(elname)
if err != nil {
return "", err
}
nref, err := bx.Pool.RefByName(attrname.Local)
if err != nil {
return "", err
}
nsref := PoolRef(NoEntry)
if attrname.Space != "" {
nsref, err = bx.Pool.RefByName(attrname.Space)
if err != nil {
return "", err
}
}
for el := range bx.iterElements() {
if el.Name == elref {
for _, attr := range el.attrs {
// TODO enforce TypedValue DataString constraint?
if nsref == attr.NS && nref == attr.Name {
return bx.Pool.strings[int(attr.RawValue)], nil
}
}
}
}
return "", fmt.Errorf("no matching element %q for attribute %+v found", elname, attrname)
}
const (
androidSchema = "http://schemas.android.com/apk/res/android"
toolsSchema = "http://schemas.android.com/tools"
)
// skipSynthesize is set true for tests to avoid synthesis of additional nodes and attributes.
var skipSynthesize bool
// UnmarshalXML decodes an AndroidManifest.xml document returning type XML
// containing decoded resources with the given minimum and target Android SDK / API version.
func UnmarshalXML(r io.Reader, withIcon bool, minSdkVersion, targetSdkVersion int) (*XML, error) {
tbl, err := OpenTable()
if err != nil {
return nil, err
}
lr := &lineReader{r: r}
dec := xml.NewDecoder(lr)
bx := new(XML)
// temporary pool to resolve real poolref later
pool := new(Pool)
type ltoken struct {
xml.Token
line int
}
var q []ltoken
for {
line := lr.line(dec.InputOffset())
tkn, err := dec.Token()
if err != nil {
if err == io.EOF {
break
}
return nil, err
}
tkn = xml.CopyToken(tkn)
switch tkn := tkn.(type) {
case xml.StartElement:
switch tkn.Name.Local {
default:
q = append(q, ltoken{tkn, line})
case "uses-sdk":
return nil, errors.New("manual declaration of uses-sdk in AndroidManifest.xml not supported")
case "manifest":
// synthesize additional attributes and nodes for use during encode.
tkn.Attr = append(tkn.Attr, xml.Attr{
Name: xml.Name{
Space: "",
Local: "platformBuildVersionCode",
},
Value: strconv.Itoa(targetSdkVersion),
},
xml.Attr{
Name: xml.Name{
Space: "",
Local: "platformBuildVersionName",
},
Value: "4.1.2-1425332",
},
)
q = append(q, ltoken{tkn, line})
if !skipSynthesize {
s := xml.StartElement{
Name: xml.Name{
Space: "",
Local: "uses-sdk",
},
Attr: []xml.Attr{
{
Name: xml.Name{
Space: androidSchema,
Local: "minSdkVersion",
},
Value: strconv.Itoa(minSdkVersion),
},
{
Name: xml.Name{
Space: androidSchema,
Local: "targetSdkVersion",
},
Value: strconv.Itoa(targetSdkVersion),
},
},
}
e := xml.EndElement{Name: xml.Name{Local: "uses-sdk"}}
q = append(q, ltoken{s, line}, ltoken{e, line})
}
case "application":
if !skipSynthesize {
for _, attr := range tkn.Attr {
if attr.Name.Space == androidSchema && attr.Name.Local == "icon" {
return nil, errors.New("manual declaration of android:icon in AndroidManifest.xml not supported")
}
}
if withIcon {
tkn.Attr = append(tkn.Attr,
xml.Attr{
Name: xml.Name{
Space: androidSchema,
Local: "icon",
},
Value: "@mipmap/icon",
})
}
}
q = append(q, ltoken{tkn, line})
case "activity", "service":
// android:exported is required for activities and services
// (with intent filters) for target SDK versions 31 and above
hasExported := slices.ContainsFunc(tkn.Attr, func(a xml.Attr) bool {
return a.Name.Space == androidSchema && a.Name.Local == "exported"
})
if !skipSynthesize && targetSdkVersion >= 31 && !hasExported {
tkn.Attr = append(tkn.Attr,
xml.Attr{
Name: xml.Name{
Space: androidSchema,
Local: "exported",
},
Value: "true",
},
)
}
q = append(q, ltoken{tkn, line})
}
default:
q = append(q, ltoken{tkn, line})
}
}
for _, ltkn := range q {
tkn, line := ltkn.Token, ltkn.line
switch tkn := tkn.(type) {
case xml.StartElement:
el := &Element{
LineNumber: uint32(line),
Comment: 0xFFFFFFFF,
NS: NoEntry,
Name: pool.ref(tkn.Name.Local),
}
if len(bx.stack) == 0 {
bx.Children = append(bx.Children, el)
} else {
n := len(bx.stack)
var p *Element
p, bx.stack = bx.stack[n-1], bx.stack[:n-1]
p.Children = append(p.Children, el)
bx.stack = append(bx.stack, p)
}
bx.stack = append(bx.stack, el)
for _, attr := range tkn.Attr {
if (attr.Name.Space == "xmlns" && attr.Name.Local == "tools") || attr.Name.Space == toolsSchema {
continue // TODO can tbl be queried for schemas to determine validity instead?
}
if attr.Name.Space == "xmlns" && attr.Name.Local == "android" {
if bx.Namespace != nil {
return nil, errors.New("multiple declarations of xmlns:android encountered")
}
bx.Namespace = &Namespace{
LineNumber: uint32(line),
Comment: NoEntry,
prefix: 0,
uri: 0,
}
continue
}
nattr := &Attribute{
NS: pool.ref(attr.Name.Space),
Name: pool.ref(attr.Name.Local),
RawValue: NoEntry,
}
el.attrs = append(el.attrs, nattr)
if attr.Name.Space == "" {
nattr.NS = NoEntry
// TODO it's unclear how to query these
switch attr.Name.Local {
case "platformBuildVersionCode":
nattr.TypedValue.Type = DataIntDec
i, err := strconv.Atoi(attr.Value)
if err != nil {
return nil, err
}
nattr.TypedValue.Value = uint32(i)
default: // "package", "platformBuildVersionName", and any invalid
nattr.RawValue = pool.ref(attr.Value)
nattr.TypedValue.Type = DataString
}
} else {
// get type spec and value data type
ref, err := tbl.RefByName("attr/" + attr.Name.Local)
if err != nil {
return nil, err
}
nt, err := ref.Resolve(tbl)
if err != nil {
return nil, err
}
if len(nt.values) == 0 {
panic("encountered empty values slice")
}
if len(nt.values) == 1 {
val := nt.values[0]
if val.data.Type != DataIntDec {
panic("TODO only know how to handle DataIntDec type here")
}
t := DataType(val.data.Value)
switch t {
case DataString, DataAttribute, DataType(0x3e):
// TODO identify 0x3e, in bootstrap.xml this is the native lib name
nattr.RawValue = pool.ref(attr.Value)
nattr.TypedValue.Type = DataString
nattr.TypedValue.Value = uint32(nattr.RawValue)
case DataIntBool, DataType(0x08):
nattr.TypedValue.Type = DataIntBool
switch attr.Value {
case "true":
nattr.TypedValue.Value = 0xFFFFFFFF
case "false":
nattr.TypedValue.Value = 0
default:
return nil, fmt.Errorf("invalid bool value %q", attr.Value)
}
case DataIntDec, DataFloat, DataFraction:
// TODO DataFraction needs it's own case statement. minSdkVersion identifies as DataFraction
// but has accepted input in the past such as android:minSdkVersion="L"
// Other use-cases for DataFraction are currently unknown as applicable to manifest generation
// but this provides minimum support for writing out minSdkVersion="15" correctly.
nattr.TypedValue.Type = DataIntDec
i, err := strconv.Atoi(attr.Value)
if err != nil {
return nil, err
}
nattr.TypedValue.Value = uint32(i)
case DataReference:
nattr.TypedValue.Type = DataReference
dref, err := tbl.RefByName(attr.Value)
if err != nil {
if strings.HasPrefix(attr.Value, "@mipmap") {
// firstDrawableID is a TableRef matching first entry of mipmap spec initialized by NewMipmapTable.
// 7f is default package, 02 is mipmap spec, 0000 is first entry; e.g. R.drawable.icon
// TODO resource table should generate ids as required.
const firstDrawableID = 0x7f020000
nattr.TypedValue.Value = firstDrawableID
continue
}
return nil, err
}
nattr.TypedValue.Value = uint32(dref)
default:
return nil, fmt.Errorf("unhandled data type %0#2x: %s", uint8(t), t)
}
} else {
// 0x01000000 is an unknown ref that doesn't point to anything, typically
// located at the start of entry value lists, peek at last value to determine type.
t := nt.values[len(nt.values)-1].data.Type
switch t {
case DataIntDec:
for _, val := range nt.values {
if val.name == 0x01000000 {
continue
}
nr, err := val.name.Resolve(tbl)
if err != nil {
return nil, err
}
if attr.Value == nr.key.Resolve(tbl.pkgs[0].keyPool) { // TODO hard-coded pkg ref
nattr.TypedValue = *val.data
break
}
}
case DataIntHex:
nattr.TypedValue.Type = t
for x := range strings.SplitSeq(attr.Value, "|") {
for _, val := range nt.values {
if val.name == 0x01000000 {
continue
}
nr, err := val.name.Resolve(tbl)
if err != nil {
return nil, err
}
if x == nr.key.Resolve(tbl.pkgs[0].keyPool) { // TODO hard-coded pkg ref
nattr.TypedValue.Value |= val.data.Value
break
}
}
}
default:
return nil, fmt.Errorf("unhandled data type for configuration %0#2x: %s", uint8(t), t)
}
}
}
}
case xml.CharData:
if s := poolTrim(string(tkn)); s != "" {
cdt := &CharData{
LineNumber: uint32(line),
Comment: NoEntry,
RawData: pool.ref(s),
}
el := bx.stack[len(bx.stack)-1]
if el.head == nil {
el.head = cdt
} else if el.tail == nil {
el.tail = cdt
} else {
return nil, errors.New("element head and tail already contain chardata")
}
}
case xml.EndElement:
if tkn.Name.Local == "manifest" {
bx.Namespace.end = &Namespace{
LineNumber: uint32(line),
Comment: NoEntry,
prefix: 0,
uri: 0,
}
}
n := len(bx.stack)
var el *Element
el, bx.stack = bx.stack[n-1], bx.stack[:n-1]
if el.end != nil {
return nil, errors.New("element end already exists")
}
el.end = &ElementEnd{
LineNumber: uint32(line),
Comment: NoEntry,
NS: el.NS,
Name: el.Name,
}
case xml.Comment, xml.ProcInst:
// discard
default:
panic(fmt.Errorf("unhandled token type: %T %+v", tkn, tkn))
}
}
// pools appear to be sorted as follows:
// * attribute names prefixed with android:
// * "android", [schema-url], [empty-string]
// * for each node:
// * attribute names with no prefix
// * node name
// * attribute value if data type of name is DataString, DataAttribute, or 0x3e (an unknown)
bx.Pool = new(Pool)
var arecurse func(*Element)
arecurse = func(el *Element) {
for _, attr := range el.attrs {
if attr.NS == NoEntry {
continue
}
if attr.NS.Resolve(pool) == androidSchema {
bx.Pool.strings = append(bx.Pool.strings, attr.Name.Resolve(pool))
}
}
for _, child := range el.Children {
arecurse(child)
}
}
for _, el := range bx.Children {
arecurse(el)
}
// TODO encoding/xml does not enforce namespace prefix and manifest encoding in aapt
// appears to ignore all other prefixes. Inserting this manually is not strictly correct
// for the general case, but the effort to do otherwise currently offers nothing.
bx.Pool.strings = append(bx.Pool.strings, "android", androidSchema)
// there always appears to be an empty string located after schema, even if one is
// not present in manifest.
bx.Pool.strings = append(bx.Pool.strings, "")
var brecurse func(*Element)
brecurse = func(el *Element) {
for _, attr := range el.attrs {
if attr.NS == NoEntry {
bx.Pool.strings = append(bx.Pool.strings, attr.Name.Resolve(pool))
}
}
bx.Pool.strings = append(bx.Pool.strings, el.Name.Resolve(pool))
for _, attr := range el.attrs {
if attr.RawValue != NoEntry {
bx.Pool.strings = append(bx.Pool.strings, attr.RawValue.Resolve(pool))
} else if attr.NS == NoEntry {
bx.Pool.strings = append(bx.Pool.strings, fmt.Sprintf("%+v", attr.TypedValue.Value))
}
}
if el.head != nil {
bx.Pool.strings = append(bx.Pool.strings, el.head.RawData.Resolve(pool))
}
if el.tail != nil {
bx.Pool.strings = append(bx.Pool.strings, el.tail.RawData.Resolve(pool))
}
for _, child := range el.Children {
brecurse(child)
}
}
for _, el := range bx.Children {
brecurse(el)
}
// do not eliminate duplicates until the entire slice has been composed.
// consider <activity android:label="label" .../>
// all attribute names come first followed by values; in such a case, the value "label"
// would be a reference to the same "android:label" in the string pool which will occur
// within the beginning of the pool where other attr names are located.
bx.Pool.strings = asSet(bx.Pool.strings)
// TODO consider cases of multiple declarations of the same attr name that should return error
// before ever reaching this point.
bx.Map = new(Map)
for _, s := range bx.Pool.strings {
ref, err := tbl.RefByName("attr/" + s)
if err != nil {
break // break after first non-ref as all strings after are also non-refs.
}
bx.Map.rs = append(bx.Map.rs, ref)
}
// resolve tmp pool refs to final pool refs
// TODO drop this in favor of sort directly on Table
var resolve func(el *Element)
resolve = func(el *Element) {
if el.NS != NoEntry {
el.NS = bx.Pool.ref(el.NS.Resolve(pool))
el.end.NS = el.NS
}
el.Name = bx.Pool.ref(el.Name.Resolve(pool))
el.end.Name = el.Name
for _, attr := range el.attrs {
if attr.NS != NoEntry {
attr.NS = bx.Pool.ref(attr.NS.Resolve(pool))
}
attr.Name = bx.Pool.ref(attr.Name.Resolve(pool))
if attr.RawValue != NoEntry {
attr.RawValue = bx.Pool.ref(attr.RawValue.Resolve(pool))
if attr.TypedValue.Type == DataString {
attr.TypedValue.Value = uint32(attr.RawValue)
}
}
}
for _, child := range el.Children {
resolve(child)
}
}
for _, el := range bx.Children {
resolve(el)
}
// The attributes of an element are sorted by their resource IDs, as
// aapt does, with those without one (no android: prefix) after them:
// Android looks up the attributes of the manifest in that order, so it
// does not find one that is out of order (as android:exported).
resID := func(attr *Attribute) uint32 {
if attr.NS != NoEntry && int(attr.Name) < len(bx.Map.rs) {
return uint32(bx.Map.rs[attr.Name])
}
return 0xFFFFFFFF
}
var asort func(*Element)
asort = func(el *Element) {
sort.SliceStable(el.attrs, func(i, j int) bool {
return resID(el.attrs[i]) < resID(el.attrs[j])
})
for _, child := range el.Children {
asort(child)
}
}
for _, el := range bx.Children {
asort(el)
}
for i, s := range bx.Pool.strings {
switch s {
case androidSchema:
bx.Namespace.uri = PoolRef(i)
bx.Namespace.end.uri = PoolRef(i)
case "android":
bx.Namespace.prefix = PoolRef(i)
bx.Namespace.end.prefix = PoolRef(i)
}
}
return bx, nil
}
// UnmarshalBinary decodes all resource chunks in buf returning any error encountered.
func (bx *XML) UnmarshalBinary(buf []byte) error {
if err := (&bx.chunkHeader).UnmarshalBinary(buf); err != nil {
return err
}
buf = buf[8:]
for len(buf) > 0 {
k, err := bx.unmarshalBinaryKind(buf)
if err != nil {
return err
}
buf = buf[k.size():]
}
return nil
}
// unmarshalBinaryKind decodes and stores the first resource chunk of bin.
// It returns the unmarshaler interface and any error encountered.
// If k.size() < len(bin), subsequent chunks can be decoded at bin[k.size():].
func (bx *XML) unmarshalBinaryKind(bin []byte) (k unmarshaler, err error) {
k, err = bx.kind(ResType(btou16(bin)))
if err != nil {
return nil, err
}
if err = k.UnmarshalBinary(bin); err != nil {
return nil, err
}
return k, nil
}
func (bx *XML) kind(t ResType) (unmarshaler, error) {
switch t {
case ResStringPool:
if bx.Pool != nil {
return nil, errors.New("pool already exists")
}
bx.Pool = new(Pool)
return bx.Pool, nil
case ResXMLResourceMap:
if bx.Map != nil {
return nil, errors.New("resource map already exists")
}
bx.Map = new(Map)
return bx.Map, nil
case ResXMLStartNamespace:
if bx.Namespace != nil {
return nil, errors.New("namespace start already exists")
}
bx.Namespace = new(Namespace)
return bx.Namespace, nil
case ResXMLEndNamespace:
if bx.Namespace.end != nil {
return nil, errors.New("namespace end already exists")
}
bx.Namespace.end = new(Namespace)
return bx.Namespace.end, nil
case ResXMLStartElement:
el := new(Element)
if len(bx.stack) == 0 {
bx.Children = append(bx.Children, el)
} else {
n := len(bx.stack)
var p *Element
p, bx.stack = bx.stack[n-1], bx.stack[:n-1]
p.Children = append(p.Children, el)
bx.stack = append(bx.stack, p)
}
bx.stack = append(bx.stack, el)
return el, nil
case ResXMLEndElement:
n := len(bx.stack)
var el *Element
el, bx.stack = bx.stack[n-1], bx.stack[:n-1]
if el.end != nil {
return nil, errors.New("element end already exists")
}
el.end = new(ElementEnd)
return el.end, nil
case ResXMLCharData: // TODO assure correctness
cdt := new(CharData)
el := bx.stack[len(bx.stack)-1]
if el.head == nil {
el.head = cdt
} else if el.tail == nil {
el.tail = cdt
} else {
return nil, errors.New("element head and tail already contain chardata")
}
return cdt, nil
default:
return nil, fmt.Errorf("unexpected type %s", t)
}
}
func (bx *XML) MarshalBinary() ([]byte, error) {
bx.typ = ResXML
bx.headerByteSize = 8
var (
bin, b []byte
err error
)
b, err = bx.chunkHeader.MarshalBinary()
if err != nil {
return nil, err
}
bin = append(bin, b...)
b, err = bx.Pool.MarshalBinary()
if err != nil {
return nil, err
}
bin = append(bin, b...)
b, err = bx.Map.MarshalBinary()
if err != nil {
return nil, err
}
bin = append(bin, b...)
b, err = bx.Namespace.MarshalBinary()
if err != nil {
return nil, err
}
bin = append(bin, b...)
for _, child := range bx.Children {
if err := marshalRecurse(child, &bin); err != nil {
return nil, err
}
}
b, err = bx.Namespace.end.MarshalBinary()
if err != nil {
return nil, err
}
bin = append(bin, b...)
putu32(bin[4:], uint32(len(bin)))
return bin, nil
}
func marshalRecurse(el *Element, bin *[]byte) error {
b, err := el.MarshalBinary()
if err != nil {
return err
}
*bin = append(*bin, b...)
if el.head != nil {
b, err := el.head.MarshalBinary()
if err != nil {
return err
}
*bin = append(*bin, b...)
}
for _, child := range el.Children {
if err := marshalRecurse(child, bin); err != nil {
return err
}
}
b, err = el.end.MarshalBinary()
if err != nil {
return err
}
*bin = append(*bin, b...)
return nil
}
func (bx *XML) iterElements() <-chan *Element {
ch := make(chan *Element, 1)
go func() {
for _, el := range bx.Children {
iterElementsRecurse(el, ch)
}
close(ch)
}()
return ch
}
func iterElementsRecurse(el *Element, ch chan *Element) {
ch <- el
for _, e := range el.Children {
iterElementsRecurse(e, ch)
}
}
// asSet returns a set from a slice of strings.
func asSet(xs []string) []string {
m := make(map[string]bool)
fo := xs[:0]
for _, x := range xs {
if !m[x] {
m[x] = true
fo = append(fo, x)
}
}
return fo
}
// poolTrim trims all but immediately surrounding space.
// \n\t\tfoobar\n\t\t becomes \tfoobar\n
func poolTrim(s string) string {
var start, end int
for i, r := range s {
if !unicode.IsSpace(r) {
if i != 0 {
start = i - 1 // preserve preceding space
}
break
}
}
for i := len(s) - 1; i >= 0; i-- {
r := rune(s[i])
if !unicode.IsSpace(r) {
if i != len(s)-1 {
end = i + 2
}
break
}
}
if start == 0 && end == 0 {
return "" // every char was a space
}
return s[start:end]
}
type lineReader struct {
off int64
lines []int64
r io.Reader
}
func (r *lineReader) Read(p []byte) (n int, err error) {
n, err = r.r.Read(p)
for i := 0; i < n; i++ {
if p[i] == '\n' {
r.lines = append(r.lines, r.off+int64(i))
}
}
r.off += int64(n)
return n, err
}
func (r *lineReader) line(pos int64) int {
return sort.Search(len(r.lines), func(i int) bool {
return pos < r.lines[i]
}) + 1
}
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package binres
// NodeHeader is header all xml node types have, providing additional
// information regarding an xml node over binChunkHeader.
type NodeHeader struct {
chunkHeader
LineNumber uint32 // line number in source file this element appears
Comment PoolRef // optional xml comment associated with element, MaxUint32 if none
}
func (hdr *NodeHeader) UnmarshalBinary(bin []byte) error {
if err := (&hdr.chunkHeader).UnmarshalBinary(bin); err != nil {
return err
}
hdr.LineNumber = btou32(bin[8:])
hdr.Comment = PoolRef(btou32(bin[12:]))
return nil
}
func (hdr *NodeHeader) MarshalBinary() ([]byte, error) {
bin := make([]byte, 16)
b, err := hdr.chunkHeader.MarshalBinary()
if err != nil {
return nil, err
}
copy(bin, b)
putu32(bin[8:], hdr.LineNumber)
putu32(bin[12:], uint32(hdr.Comment))
return bin, nil
}
type Namespace struct {
NodeHeader
prefix PoolRef
uri PoolRef
end *Namespace // TODO don't let this type be recursive
}
func (ns *Namespace) UnmarshalBinary(bin []byte) error {
if err := (&ns.NodeHeader).UnmarshalBinary(bin); err != nil {
return err
}
buf := bin[ns.headerByteSize:]
ns.prefix = PoolRef(btou32(buf))
ns.uri = PoolRef(btou32(buf[4:]))
return nil
}
func (ns *Namespace) MarshalBinary() ([]byte, error) {
if ns.end == nil {
ns.typ = ResXMLEndNamespace
} else {
ns.typ = ResXMLStartNamespace
}
ns.headerByteSize = 16
ns.byteSize = 24
bin := make([]byte, ns.byteSize)
b, err := ns.NodeHeader.MarshalBinary()
if err != nil {
return nil, err
}
copy(bin, b)
putu32(bin[16:], uint32(ns.prefix))
putu32(bin[20:], uint32(ns.uri))
return bin, nil
}
type Element struct {
NodeHeader
NS PoolRef
Name PoolRef // name of node if element, otherwise chardata if CDATA
AttributeStart uint16 // byte offset where attrs start
AttributeSize uint16 // byte size of attrs
AttributeCount uint16 // length of attrs
IdIndex uint16 // Index (1-based) of the "id" attribute. 0 if none.
ClassIndex uint16 // Index (1-based) of the "class" attribute. 0 if none.
StyleIndex uint16 // Index (1-based) of the "style" attribute. 0 if none.
attrs []*Attribute
Children []*Element
end *ElementEnd
head, tail *CharData
}
func (el *Element) UnmarshalBinary(buf []byte) error {
if err := (&el.NodeHeader).UnmarshalBinary(buf); err != nil {
return err
}
buf = buf[el.headerByteSize:]
el.NS = PoolRef(btou32(buf))
el.Name = PoolRef(btou32(buf[4:]))
el.AttributeStart = btou16(buf[8:])
el.AttributeSize = btou16(buf[10:])
el.AttributeCount = btou16(buf[12:])
el.IdIndex = btou16(buf[14:])
el.ClassIndex = btou16(buf[16:])
el.StyleIndex = btou16(buf[18:])
buf = buf[el.AttributeStart:]
el.attrs = make([]*Attribute, int(el.AttributeCount))
for i := range el.attrs {
attr := new(Attribute)
if err := attr.UnmarshalBinary(buf); err != nil {
return err
}
el.attrs[i] = attr
buf = buf[el.AttributeSize:]
}
return nil
}
func (el *Element) MarshalBinary() ([]byte, error) {
el.typ = ResXMLStartElement
el.headerByteSize = 16
el.AttributeSize = 20
el.AttributeStart = 20
el.AttributeCount = uint16(len(el.attrs))
el.IdIndex = 0
el.ClassIndex = 0
el.StyleIndex = 0
el.byteSize = uint32(el.headerByteSize) + uint32(el.AttributeStart) + uint32(len(el.attrs)*int(el.AttributeSize))
bin := make([]byte, el.byteSize)
b, err := el.NodeHeader.MarshalBinary()
if err != nil {
return nil, err
}
copy(bin, b)
putu32(bin[16:], uint32(el.NS))
putu32(bin[20:], uint32(el.Name))
putu16(bin[24:], el.AttributeStart)
putu16(bin[26:], el.AttributeSize)
putu16(bin[28:], el.AttributeCount)
putu16(bin[30:], el.IdIndex)
putu16(bin[32:], el.ClassIndex)
putu16(bin[34:], el.StyleIndex)
buf := bin[36:]
for _, attr := range el.attrs {
b, err := attr.MarshalBinary()
if err != nil {
return nil, err
}
copy(buf, b)
buf = buf[int(el.AttributeSize):]
}
return bin, nil
}
// ElementEnd marks the end of an element node, either Element or CharData.
type ElementEnd struct {
NodeHeader
NS PoolRef
Name PoolRef // name of node if binElement, raw chardata if binCharData
}
func (el *ElementEnd) UnmarshalBinary(bin []byte) error {
(&el.NodeHeader).UnmarshalBinary(bin)
buf := bin[el.headerByteSize:]
el.NS = PoolRef(btou32(buf))
el.Name = PoolRef(btou32(buf[4:]))
return nil
}
func (el *ElementEnd) MarshalBinary() ([]byte, error) {
el.typ = ResXMLEndElement
el.headerByteSize = 16
el.byteSize = 24
bin := make([]byte, 24)
b, err := el.NodeHeader.MarshalBinary()
if err != nil {
return nil, err
}
copy(bin, b)
putu32(bin[16:], uint32(el.NS))
putu32(bin[20:], uint32(el.Name))
return bin, nil
}
type Attribute struct {
NS PoolRef
Name PoolRef
RawValue PoolRef // The original raw string value of this attribute.
TypedValue Data // Processesd typed value of this attribute.
}
func (attr *Attribute) UnmarshalBinary(bin []byte) error {
attr.NS = PoolRef(btou32(bin))
attr.Name = PoolRef(btou32(bin[4:]))
attr.RawValue = PoolRef(btou32(bin[8:]))
return (&attr.TypedValue).UnmarshalBinary(bin[12:])
}
func (attr *Attribute) MarshalBinary() ([]byte, error) {
bin := make([]byte, 20)
putu32(bin, uint32(attr.NS))
putu32(bin[4:], uint32(attr.Name))
putu32(bin[8:], uint32(attr.RawValue))
b, err := attr.TypedValue.MarshalBinary()
if err != nil {
return nil, err
}
copy(bin[12:], b)
return bin, nil
}
// CharData represents a CDATA node and includes ref to node's text value.
type CharData struct {
NodeHeader
RawData PoolRef // raw character data
TypedData Data // typed value of character data
}
func (cdt *CharData) UnmarshalBinary(bin []byte) error {
if err := (&cdt.NodeHeader).UnmarshalBinary(bin); err != nil {
return err
}
buf := bin[cdt.headerByteSize:]
cdt.RawData = PoolRef(btou32(buf))
return (&cdt.TypedData).UnmarshalBinary(buf[4:])
}
func (cdt *CharData) MarshalBinary() ([]byte, error) {
cdt.typ = ResXMLCharData
cdt.headerByteSize = 16
cdt.byteSize = 28
bin := make([]byte, cdt.byteSize)
b, err := cdt.NodeHeader.MarshalBinary()
if err != nil {
return nil, err
}
copy(bin, b)
putu32(bin[16:], uint32(cdt.RawData))
b, err = cdt.TypedData.MarshalBinary()
if err != nil {
return nil, err
}
copy(bin[20:], b)
return bin, nil
}
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package binres
import (
"errors"
"fmt"
"unicode/utf16"
)
const (
SortedFlag uint32 = 1 << 0
UTF8Flag = 1 << 8
)
// PoolRef is the i'th string in a pool.
type PoolRef uint32
// Resolve returns the string entry of PoolRef in pl.
func (ref PoolRef) Resolve(pl *Pool) string {
return pl.strings[ref]
}
// Pool is a container for string and style span collections.
//
// Pool has the following structure marshalled:
//
// chunkHeader
// uint32 number of strings in this pool
// uint32 number of style spans in pool
// uint32 SortedFlag, UTF8Flag
// uint32 index of string data from header
// uint32 index of style data from header
// []uint32 string indices starting at zero
// []uint16 or []uint8 concatenation of string entries
//
// UTF-16 entries are as follows:
//
// uint16 string length, exclusive
// uint16 [optional] low word if high bit of length set
// [n]byte data
// uint16 0x0000 terminator
//
// UTF-8 entries are as follows:
//
// uint8 character length, exclusive
// uint8 [optional] low word if high bit of character length set
// uint8 byte length, exclusive
// uint8 [optional] low word if high bit of byte length set
// [n]byte data
// uint8 0x00 terminator
type Pool struct {
chunkHeader
strings []string
styles []*Span
flags uint32 // SortedFlag, UTF8Flag
}
// ref returns the PoolRef of s, inserting s if it doesn't exist.
func (pl *Pool) ref(s string) PoolRef {
for i, x := range pl.strings {
if s == x {
return PoolRef(i)
}
}
pl.strings = append(pl.strings, s)
return PoolRef(len(pl.strings) - 1)
}
// RefByName returns the PoolRef of s, or error if not exists.
func (pl *Pool) RefByName(s string) (PoolRef, error) {
for i, x := range pl.strings {
if s == x {
return PoolRef(i), nil
}
}
return 0, fmt.Errorf("PoolRef by name %q does not exist", s)
}
func (pl *Pool) IsSorted() bool { return pl.flags&SortedFlag == SortedFlag }
func (pl *Pool) IsUTF8() bool { return pl.flags&UTF8Flag == UTF8Flag }
func (pl *Pool) UnmarshalBinary(bin []byte) error {
if err := (&pl.chunkHeader).UnmarshalBinary(bin); err != nil {
return err
}
if pl.typ != ResStringPool {
return fmt.Errorf("have type %s, want %s", pl.typ, ResStringPool)
}
pl.strings = make([]string, btou32(bin[8:]))
pl.styles = make([]*Span, btou32(bin[12:]))
pl.flags = btou32(bin[16:])
offstrings := btou32(bin[20:])
offstyle := btou32(bin[24:])
hdrlen := 28
if pl.IsUTF8() {
for i := range pl.strings {
offset := int(offstrings + btou32(bin[hdrlen+i*4:]))
// if leading bit set for nchars and nbytes,
// treat first byte as 7-bit high word and next as low word.
nchars := int(bin[offset])
offset++
if nchars&(1<<7) != 0 {
n0 := nchars ^ (1 << 7) // high word
n1 := int(bin[offset]) // low word
nchars = n0*(1<<8) + n1
offset++
}
// TODO(d) At least one case in android.jar (api-10) resource table has only
// highbit set, making 7-bit highword zero. The reason for this is currently
// unknown but would make tests that unmarshal-marshal to match bytes impossible.
// The values noted were high-word: 0 (after highbit unset), low-word: 141
// The size may be treated as an int8 triggering the use of two bytes to store size
// even though the implementation uses uint8.
nbytes := int(bin[offset])
offset++
if nbytes&(1<<7) != 0 {
n0 := nbytes ^ (1 << 7) // high word
n1 := int(bin[offset]) // low word
nbytes = n0*(1<<8) + n1
offset++
}
data := bin[offset : offset+nbytes]
if x := uint8(bin[offset+nbytes]); x != 0 {
return fmt.Errorf("expected zero terminator, got 0x%02X for nchars=%v nbytes=%v data=%q", x, nchars, nbytes, data)
}
pl.strings[i] = string(data)
}
} else {
for i := range pl.strings {
offset := int(offstrings + btou32(bin[hdrlen+i*4:])) // read index of string
// if leading bit set for nchars, treat first byte as 7-bit high word and next as low word.
nchars := int(btou16(bin[offset:]))
offset += 2
if nchars&(1<<15) != 0 { // TODO(d) this is untested
n0 := nchars ^ (1 << 15) // high word
n1 := int(btou16(bin[offset:])) // low word
nchars = n0*(1<<16) + n1
offset += 2
}
data := make([]uint16, nchars)
for i := range data {
data[i] = btou16(bin[offset+2*i:])
}
if x := btou16(bin[offset+nchars*2:]); x != 0 {
return fmt.Errorf("expected zero terminator, got 0x%04X for nchars=%v data=%q", x, nchars, string(utf16.Decode(data)))
}
pl.strings[i] = string(utf16.Decode(data))
}
}
// TODO decode styles
_ = offstyle
return nil
}
func (pl *Pool) MarshalBinary() ([]byte, error) {
if pl.IsUTF8() {
return nil, errors.New("encode utf8 not supported")
}
var (
hdrlen = 28
// indices of string indices
iis = make([]uint32, len(pl.strings))
iislen = len(iis) * 4
// utf16 encoded strings concatenated together
strs []uint16
)
for i, x := range pl.strings {
if len(x)>>16 > 0 {
panic(fmt.Errorf("string lengths over 1<<15 not yet supported, got len %d", len(x)))
}
p := utf16.Encode([]rune(x))
if len(p) == 0 {
strs = append(strs, 0x0000, 0x0000)
} else {
strs = append(strs, uint16(len(p))) // string length (implicitly includes zero terminator to follow)
strs = append(strs, p...)
strs = append(strs, 0) // zero terminated
}
// indices start at zero
if i+1 != len(iis) {
iis[i+1] = uint32(len(strs) * 2) // utf16 byte index
}
}
// check strings is 4-byte aligned, pad with zeros if not.
for x := (len(strs) * 2) % 4; x != 0; x -= 2 {
strs = append(strs, 0x0000)
}
strslen := len(strs) * 2
hdr := chunkHeader{
typ: ResStringPool,
headerByteSize: 28,
byteSize: uint32(28 + iislen + strslen),
}
bin := make([]byte, hdr.byteSize)
hdrbin, err := hdr.MarshalBinary()
if err != nil {
return nil, err
}
copy(bin, hdrbin)
putu32(bin[8:], uint32(len(pl.strings)))
putu32(bin[12:], uint32(len(pl.styles)))
putu32(bin[16:], pl.flags)
putu32(bin[20:], uint32(hdrlen+iislen))
putu32(bin[24:], 0) // index of styles start, is 0 when styles length is 0
buf := bin[28:]
for _, x := range iis {
putu32(buf, x)
buf = buf[4:]
}
for _, x := range strs {
putu16(buf, x)
buf = buf[2:]
}
if len(buf) != 0 {
panic(fmt.Errorf("failed to fill allocated buffer, %v bytes left over", len(buf)))
}
return bin, nil
}
type Span struct {
name PoolRef
firstChar, lastChar uint32
}
func (spn *Span) UnmarshalBinary(bin []byte) error {
const end = 0xFFFFFFFF
spn.name = PoolRef(btou32(bin))
if spn.name == end {
return nil
}
spn.firstChar = btou32(bin[4:])
spn.lastChar = btou32(bin[8:])
return nil
}
// Map contains a uint32 slice mapping strings in the string
// pool back to resource identifiers. The i'th element of the slice
// is also the same i'th element of the string pool.
type Map struct {
chunkHeader
rs []TableRef
}
func (m *Map) UnmarshalBinary(bin []byte) error {
(&m.chunkHeader).UnmarshalBinary(bin)
buf := bin[m.headerByteSize:m.byteSize]
m.rs = make([]TableRef, len(buf)/4)
for i := range m.rs {
m.rs[i] = TableRef(btou32(buf[i*4:]))
}
return nil
}
func (m *Map) MarshalBinary() ([]byte, error) {
m.typ = ResXMLResourceMap
m.headerByteSize = 8
m.byteSize = uint32(m.headerByteSize) + uint32(len(m.rs)*4)
bin := make([]byte, m.byteSize)
b, err := m.chunkHeader.MarshalBinary()
if err != nil {
return nil, err
}
copy(bin, b)
for i, r := range m.rs {
putu32(bin[8+i*4:], uint32(r))
}
return bin, nil
}
package binres
import (
"archive/zip"
"bytes"
"compress/gzip"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"cogentcore.org/core/cmd/mobile/sdkpath"
)
// MinSDK is the targeted sdk version for support by package binres.
const MinSDK = 16
func apiResources() ([]byte, error) {
apiResPath, err := apiResourcesPath()
if err != nil {
return nil, err
}
zr, err := zip.OpenReader(apiResPath)
if err != nil {
if os.IsNotExist(err) {
return nil, fmt.Errorf(`%v; consider installing with "android update sdk --all --no-ui --filter android-%d"`, err, MinSDK)
}
return nil, err
}
defer zr.Close()
buf := new(bytes.Buffer)
for _, f := range zr.File {
if f.Name == "resources.arsc" {
rc, err := f.Open()
if err != nil {
return nil, err
}
_, err = io.Copy(buf, rc)
if err != nil {
return nil, err
}
rc.Close()
break
}
}
if buf.Len() == 0 {
return nil, errors.New("failed to read resources.arsc")
}
return buf.Bytes(), nil
}
func apiResourcesPath() (string, error) {
platformDir, err := sdkpath.AndroidAPIPath(MinSDK)
if err != nil {
return "", err
}
return filepath.Join(platformDir, "android.jar"), nil
}
// PackResources produces a stripped down gzip version of the resources.arsc from api jar.
func PackResources() ([]byte, error) {
tbl, err := OpenSDKTable()
if err != nil {
return nil, err
}
tbl.pool.strings = []string{} // should not be needed
pkg := tbl.pkgs[0]
// drop language string entries
for _, typ := range pkg.specs[3].types {
if typ.config.locale.language != 0 {
for j, nt := range typ.entries {
if nt == nil { // NoEntry
continue
}
pkg.keyPool.strings[nt.key] = ""
typ.indices[j] = NoEntry
typ.entries[j] = nil
}
}
}
// drop strings from pool for specs to be dropped
for _, spec := range pkg.specs[4:] {
for _, typ := range spec.types {
for _, nt := range typ.entries {
if nt == nil { // NoEntry
continue
}
// don't drop if there's a collision
var collision bool
for _, xspec := range pkg.specs[:4] {
for _, xtyp := range xspec.types {
for _, xnt := range xtyp.entries {
if xnt == nil {
continue
}
if collision = nt.key == xnt.key; collision {
break
}
}
}
}
if !collision {
pkg.keyPool.strings[nt.key] = ""
}
}
}
}
// entries are densely packed but probably safe to drop nil entries off the end
for _, spec := range pkg.specs[:4] {
for _, typ := range spec.types {
var last int
for i, nt := range typ.entries {
if nt != nil {
last = i
}
}
typ.entries = typ.entries[:last+1]
typ.indices = typ.indices[:last+1]
}
}
// keeping 0:attr, 1:id, 2:style, 3:string
pkg.typePool.strings = pkg.typePool.strings[:4]
pkg.specs = pkg.specs[:4]
bin, err := tbl.MarshalBinary()
if err != nil {
return nil, err
}
buf := new(bytes.Buffer)
zw := gzip.NewWriter(buf)
if _, err := zw.Write(bin); err != nil {
return nil, err
}
if err := zw.Flush(); err != nil {
return nil, err
}
if err := zw.Close(); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package binres
import (
"bytes"
"compress/gzip"
"errors"
"fmt"
"io"
"strings"
"unicode/utf16"
)
const NoEntry = 0xFFFFFFFF
// TableRef uniquely identifies entries within a resource table.
type TableRef uint32
// Resolve returns the Entry of TableRef in the given table.
//
// A TableRef is structured as follows:
//
// 0xpptteeee
// pp: package index
// tt: type spec index in package
// eeee: entry index in type spec
//
// The package and type spec values start at 1 for the first item,
// to help catch cases where they have not been supplied.
func (ref TableRef) Resolve(tbl *Table) (*Entry, error) {
pkg := tbl.pkgs[uint8(ref>>24)-1]
spec := pkg.specs[uint8(ref>>16)-1]
idx := uint16(ref)
for _, typ := range spec.types {
if idx < uint16(len(typ.entries)) {
nt := typ.entries[idx]
if nt == nil {
return nil, errors.New("nil entry match")
}
return nt, nil
}
}
return nil, errors.New("failed to resolve table reference")
}
// Table is a container for packaged resources. Resource values within a package
// are obtained through pool while resource names and identifiers are obtained
// through each package's type and key pools respectively.
type Table struct {
chunkHeader
pool *Pool
pkgs []*Package
}
// NewMipmapTable returns a resource table initialized for a single xxxhdpi mipmap resource
// and the path to write resource data to.
func NewMipmapTable(pkgname string) (*Table, string) {
pkg := &Package{id: 127, name: pkgname, typePool: &Pool{}, keyPool: &Pool{}}
attr := pkg.typePool.ref("attr")
mipmap := pkg.typePool.ref("mipmap")
icon := pkg.keyPool.ref("icon")
nt := &Entry{values: []*Value{{data: &Data{Type: DataString}}}}
typ := &Type{id: 2, indices: []uint32{0}, entries: []*Entry{nt}}
typ.config.screenType.density = 640
typ.config.version.sdk = 4
pkg.specs = append(pkg.specs,
&TypeSpec{
id: uint8(attr) + 1, //1,
},
&TypeSpec{
id: uint8(mipmap) + 1, //2,
entryCount: 1,
entries: []uint32{uint32(icon)}, // {0}
types: []*Type{typ},
})
pkg.lastPublicType = uint32(len(pkg.typePool.strings)) // 2
pkg.lastPublicKey = uint32(len(pkg.keyPool.strings)) // 1
name := "res/mipmap-xxxhdpi-v4/icon.png"
tbl := &Table{pool: &Pool{}, pkgs: []*Package{pkg}}
tbl.pool.ref(name)
return tbl, name
}
// OpenSDKTable decodes resources.arsc from sdk platform jar.
func OpenSDKTable() (*Table, error) {
bin, err := apiResources()
if err != nil {
return nil, err
}
tbl := new(Table)
if err := tbl.UnmarshalBinary(bin); err != nil {
return nil, err
}
return tbl, nil
}
// OpenTable decodes the prepacked resources.arsc for the supported sdk platform.
func OpenTable() (*Table, error) {
zr, err := gzip.NewReader(bytes.NewReader(arsc))
if err != nil {
return nil, fmt.Errorf("gzip: %v", err)
}
defer zr.Close()
var buf bytes.Buffer
if _, err := io.Copy(&buf, zr); err != nil {
return nil, fmt.Errorf("io: %v", err)
}
tbl := new(Table)
if err := tbl.UnmarshalBinary(buf.Bytes()); err != nil {
return nil, err
}
return tbl, nil
}
// SpecByName parses the spec name from an entry string if necessary and returns
// the Package and TypeSpec associated with that name along with their respective
// indices.
//
// For example:
//
// tbl.SpecByName("@android:style/Theme.NoTitleBar")
// tbl.SpecByName("style")
//
// Both locate the spec by name "style".
func (tbl *Table) SpecByName(name string) (int, *Package, int, *TypeSpec, error) {
n := strings.TrimPrefix(name, "@android:")
n = strings.Split(n, "/")[0]
for pp, pkg := range tbl.pkgs {
for tt, spec := range pkg.specs {
if n == pkg.typePool.strings[spec.id-1] {
return pp, pkg, tt, spec, nil
}
}
}
return 0, nil, 0, nil, fmt.Errorf("spec by name not found: %q", name)
}
// RefByName returns the TableRef by a given name. The ref may be used to resolve the
// associated Entry and is used for the generation of binary manifest files.
func (tbl *Table) RefByName(name string) (TableRef, error) {
pp, pkg, tt, spec, err := tbl.SpecByName(name)
if err != nil {
return 0, err
}
q := strings.Split(name, "/")
if len(q) != 2 {
return 0, fmt.Errorf("invalid entry format, missing forward-slash: %q", name)
}
n := q[1]
for _, t := range spec.types {
for eeee, nt := range t.entries {
if nt == nil { // NoEntry
continue
}
if n == pkg.keyPool.strings[nt.key] {
return TableRef(uint32(eeee) | uint32(tt+1)<<16 | uint32(pp+1)<<24), nil
}
}
}
return 0, fmt.Errorf("failed to find table ref by %q", name)
}
func (tbl *Table) UnmarshalBinary(bin []byte) error {
if err := (&tbl.chunkHeader).UnmarshalBinary(bin); err != nil {
return err
}
if tbl.typ != ResTable {
return fmt.Errorf("unexpected resource type %s, want %s", tbl.typ, ResTable)
}
npkgs := btou32(bin[8:])
tbl.pkgs = make([]*Package, npkgs)
buf := bin[tbl.headerByteSize:]
tbl.pool = new(Pool)
if err := tbl.pool.UnmarshalBinary(buf); err != nil {
return err
}
buf = buf[tbl.pool.size():]
for i := range tbl.pkgs {
pkg := new(Package)
if err := pkg.UnmarshalBinary(buf); err != nil {
return err
}
tbl.pkgs[i] = pkg
buf = buf[pkg.byteSize:]
}
return nil
}
func (tbl *Table) MarshalBinary() ([]byte, error) {
bin := make([]byte, 12)
putu16(bin, uint16(ResTable))
putu16(bin[2:], 12)
putu32(bin[8:], uint32(len(tbl.pkgs)))
if tbl.pool.IsUTF8() {
tbl.pool.flags ^= UTF8Flag
defer func() {
tbl.pool.flags |= UTF8Flag
}()
}
b, err := tbl.pool.MarshalBinary()
if err != nil {
return nil, err
}
bin = append(bin, b...)
for _, pkg := range tbl.pkgs {
b, err = pkg.MarshalBinary()
if err != nil {
return nil, err
}
bin = append(bin, b...)
}
putu32(bin[4:], uint32(len(bin)))
return bin, nil
}
// Package contains a collection of resource data types.
type Package struct {
chunkHeader
id uint32
name string
lastPublicType uint32 // last index into typePool that is for public use
lastPublicKey uint32 // last index into keyPool that is for public use
typePool *Pool // type names; e.g. theme
keyPool *Pool // resource names; e.g. Theme.NoTitleBar
aliases []*StagedAlias
specs []*TypeSpec
}
func (pkg *Package) UnmarshalBinary(bin []byte) error {
if err := (&pkg.chunkHeader).UnmarshalBinary(bin); err != nil {
return err
}
if pkg.typ != ResTablePackage {
return errWrongType(pkg.typ, ResTablePackage)
}
pkg.id = btou32(bin[8:])
var name []uint16
for i := range 128 {
x := btou16(bin[12+i*2:])
if x == 0 {
break
}
name = append(name, x)
}
pkg.name = string(utf16.Decode(name))
typeOffset := btou32(bin[268:]) // 0 if inheriting from another package
pkg.lastPublicType = btou32(bin[272:])
keyOffset := btou32(bin[276:]) // 0 if inheriting from another package
pkg.lastPublicKey = btou32(bin[280:])
var idOffset uint32 // value determined by either typePool or keyPool below
if typeOffset != 0 {
pkg.typePool = new(Pool)
if err := pkg.typePool.UnmarshalBinary(bin[typeOffset:]); err != nil {
return err
}
idOffset = typeOffset + pkg.typePool.byteSize
}
if keyOffset != 0 {
pkg.keyPool = new(Pool)
if err := pkg.keyPool.UnmarshalBinary(bin[keyOffset:]); err != nil {
return err
}
idOffset = keyOffset + pkg.keyPool.byteSize
}
if idOffset == 0 {
return nil
}
buf := bin[idOffset:pkg.byteSize]
for len(buf) > 0 {
t := ResType(btou16(buf))
switch t {
case ResTableTypeSpec:
spec := new(TypeSpec)
if err := spec.UnmarshalBinary(buf); err != nil {
return err
}
pkg.specs = append(pkg.specs, spec)
buf = buf[spec.byteSize:]
case ResTableType:
typ := new(Type)
if err := typ.UnmarshalBinary(buf); err != nil {
return err
}
last := pkg.specs[len(pkg.specs)-1]
last.types = append(last.types, typ)
buf = buf[typ.byteSize:]
case ResTableStagedAlias:
alias := new(StagedAlias)
if err := alias.UnmarshalBinary(buf); err != nil {
return err
}
pkg.aliases = append(pkg.aliases, alias)
buf = buf[alias.byteSize:]
default:
return errWrongType(t, ResTableTypeSpec, ResTableType, ResTableStagedAlias)
}
}
return nil
}
func (pkg *Package) MarshalBinary() ([]byte, error) {
// Package header size is determined by C++ struct ResTable_package
// see frameworks/base/include/ResourceTypes.h
bin := make([]byte, 288)
putu16(bin, uint16(ResTablePackage))
putu16(bin[2:], 288)
putu32(bin[8:], pkg.id)
p := utf16.Encode([]rune(pkg.name))
for i, x := range p {
putu16(bin[12+i*2:], x)
}
if pkg.typePool != nil {
if pkg.typePool.IsUTF8() {
pkg.typePool.flags ^= UTF8Flag
defer func() {
pkg.typePool.flags |= UTF8Flag
}()
}
b, err := pkg.typePool.MarshalBinary()
if err != nil {
return nil, err
}
putu32(bin[268:], uint32(len(bin)))
putu32(bin[272:], pkg.lastPublicType)
bin = append(bin, b...)
}
if pkg.keyPool != nil {
if pkg.keyPool.IsUTF8() {
pkg.keyPool.flags ^= UTF8Flag
defer func() {
pkg.keyPool.flags |= UTF8Flag
}()
}
b, err := pkg.keyPool.MarshalBinary()
if err != nil {
return nil, err
}
putu32(bin[276:], uint32(len(bin)))
putu32(bin[280:], pkg.lastPublicKey)
bin = append(bin, b...)
}
for _, alias := range pkg.aliases {
b, err := alias.MarshalBinary()
if err != nil {
return nil, err
}
bin = append(bin, b...)
}
for _, spec := range pkg.specs {
b, err := spec.MarshalBinary()
if err != nil {
return nil, err
}
bin = append(bin, b...)
}
putu32(bin[4:], uint32(len(bin)))
return bin, nil
}
// TypeSpec provides a specification for the resources defined by a particular type.
type TypeSpec struct {
chunkHeader
id uint8 // id-1 is name index in Package.typePool
res0 uint8 // must be 0
res1 uint16 // must be 0
entryCount uint32 // number of uint32 entry configuration masks that follow
entries []uint32 // entry configuration masks
types []*Type
}
func (spec *TypeSpec) UnmarshalBinary(bin []byte) error {
if err := (&spec.chunkHeader).UnmarshalBinary(bin); err != nil {
return err
}
if spec.typ != ResTableTypeSpec {
return errWrongType(spec.typ, ResTableTypeSpec)
}
spec.id = uint8(bin[8])
spec.res0 = uint8(bin[9])
spec.res1 = btou16(bin[10:])
spec.entryCount = btou32(bin[12:])
spec.entries = make([]uint32, spec.entryCount)
for i := range spec.entries {
spec.entries[i] = btou32(bin[16+i*4:])
}
return nil
}
func (spec *TypeSpec) MarshalBinary() ([]byte, error) {
bin := make([]byte, 16+len(spec.entries)*4)
putu16(bin, uint16(ResTableTypeSpec))
putu16(bin[2:], 16)
putu32(bin[4:], uint32(len(bin)))
bin[8] = byte(spec.id)
// [9] = 0
// [10:12] = 0
putu32(bin[12:], uint32(len(spec.entries)))
for i, x := range spec.entries {
putu32(bin[16+i*4:], x)
}
for _, typ := range spec.types {
b, err := typ.MarshalBinary()
if err != nil {
return nil, err
}
bin = append(bin, b...)
}
return bin, nil
}
// Type provides a collection of entries for a specific device configuration.
type Type struct {
chunkHeader
id uint8
res0 uint8 // must be 0
res1 uint16 // must be 0
entryCount uint32 // number of uint32 entry configuration masks that follow
entriesStart uint32 // offset from header where Entry data starts
// configuration this collection of entries is designed for
config struct {
size uint32
imsi struct {
mcc uint16 // mobile country code
mnc uint16 // mobile network code
}
locale struct {
language uint16
country uint16
}
screenType struct {
orientation uint8
touchscreen uint8
density uint16
}
input struct {
keyboard uint8
navigation uint8
inputFlags uint8
inputPad0 uint8
}
screenSize struct {
width uint16
height uint16
}
version struct {
sdk uint16
minor uint16 // always 0
}
screenConfig struct {
layout uint8
uiMode uint8
smallestWidthDP uint16
}
screenSizeDP struct {
width uint16
height uint16
}
}
indices []uint32 // values that map to typePool
entries []*Entry
}
func (typ *Type) UnmarshalBinary(bin []byte) error {
if err := (&typ.chunkHeader).UnmarshalBinary(bin); err != nil {
return err
}
if typ.typ != ResTableType {
return errWrongType(typ.typ, ResTableType)
}
typ.id = uint8(bin[8])
typ.res0 = uint8(bin[9])
typ.res1 = btou16(bin[10:])
typ.entryCount = btou32(bin[12:])
typ.entriesStart = btou32(bin[16:])
if typ.res0 != 0 || typ.res1 != 0 {
return errors.New("res0 res1 not zero")
}
typ.config.size = btou32(bin[20:])
typ.config.imsi.mcc = btou16(bin[24:])
typ.config.imsi.mnc = btou16(bin[26:])
typ.config.locale.language = btou16(bin[28:])
typ.config.locale.country = btou16(bin[30:])
typ.config.screenType.orientation = uint8(bin[32])
typ.config.screenType.touchscreen = uint8(bin[33])
typ.config.screenType.density = btou16(bin[34:])
typ.config.input.keyboard = uint8(bin[36])
typ.config.input.navigation = uint8(bin[37])
typ.config.input.inputFlags = uint8(bin[38])
typ.config.input.inputPad0 = uint8(bin[39])
typ.config.screenSize.width = btou16(bin[40:])
typ.config.screenSize.height = btou16(bin[42:])
typ.config.version.sdk = btou16(bin[44:])
typ.config.version.minor = btou16(bin[46:])
typ.config.screenConfig.layout = uint8(bin[48])
typ.config.screenConfig.uiMode = uint8(bin[49])
typ.config.screenConfig.smallestWidthDP = btou16(bin[50:])
typ.config.screenSizeDP.width = btou16(bin[52:])
typ.config.screenSizeDP.height = btou16(bin[54:])
// fmt.Println("language/country:", u16tos(typ.config.locale.language), u16tos(typ.config.locale.country))
buf := bin[typ.headerByteSize:typ.entriesStart]
if len(buf) != 4*int(typ.entryCount) {
return fmt.Errorf("index buffer len[%v] doesn't match entryCount[%v]", len(buf), typ.entryCount)
}
typ.indices = make([]uint32, typ.entryCount)
for i := range typ.indices {
typ.indices[i] = btou32(buf[i*4:])
}
typ.entries = make([]*Entry, typ.entryCount)
for i, x := range typ.indices {
if x == NoEntry {
continue
}
nt := &Entry{}
if err := nt.UnmarshalBinary(bin[typ.entriesStart+x:]); err != nil {
return err
}
typ.entries[i] = nt
}
return nil
}
func (typ *Type) MarshalBinary() ([]byte, error) {
bin := make([]byte, 56+len(typ.entries)*4)
putu16(bin, uint16(ResTableType))
putu16(bin[2:], 56)
bin[8] = byte(typ.id)
// [9] = 0
// [10:12] = 0
putu32(bin[12:], uint32(len(typ.entries)))
putu32(bin[16:], uint32(56+len(typ.entries)*4))
// assure typ.config.size is always written as 36; extended configuration beyond supported
// API level is not supported by this marshal implementation but will be forward-compatible.
putu32(bin[20:], 36)
putu16(bin[24:], typ.config.imsi.mcc)
putu16(bin[26:], typ.config.imsi.mnc)
putu16(bin[28:], typ.config.locale.language)
putu16(bin[30:], typ.config.locale.country)
bin[32] = typ.config.screenType.orientation
bin[33] = typ.config.screenType.touchscreen
putu16(bin[34:], typ.config.screenType.density)
bin[36] = typ.config.input.keyboard
bin[37] = typ.config.input.navigation
bin[38] = typ.config.input.inputFlags
bin[39] = typ.config.input.inputPad0
putu16(bin[40:], typ.config.screenSize.width)
putu16(bin[42:], typ.config.screenSize.height)
putu16(bin[44:], typ.config.version.sdk)
putu16(bin[46:], typ.config.version.minor)
bin[48] = typ.config.screenConfig.layout
bin[49] = typ.config.screenConfig.uiMode
putu16(bin[50:], typ.config.screenConfig.smallestWidthDP)
putu16(bin[52:], typ.config.screenSizeDP.width)
putu16(bin[54:], typ.config.screenSizeDP.height)
var ntbin []byte
for i, nt := range typ.entries {
if nt == nil { // NoEntry
putu32(bin[56+i*4:], NoEntry)
continue
}
putu32(bin[56+i*4:], uint32(len(ntbin)))
b, err := nt.MarshalBinary()
if err != nil {
return nil, err
}
ntbin = append(ntbin, b...)
}
bin = append(bin, ntbin...)
putu32(bin[4:], uint32(len(bin)))
return bin, nil
}
type StagedAliasEntry struct {
stagedID uint32
finalizedID uint32
}
func (ae *StagedAliasEntry) MarshalBinary() ([]byte, error) {
bin := make([]byte, 8)
putu32(bin, ae.stagedID)
putu32(bin[4:], ae.finalizedID)
return bin, nil
}
func (ae *StagedAliasEntry) UnmarshalBinary(bin []byte) error {
ae.stagedID = btou32(bin)
ae.finalizedID = btou32(bin[4:])
return nil
}
type StagedAlias struct {
chunkHeader
count uint32
entries []StagedAliasEntry
}
func (a *StagedAlias) UnmarshalBinary(bin []byte) error {
if err := (&a.chunkHeader).UnmarshalBinary(bin); err != nil {
return err
}
if a.typ != ResTableStagedAlias {
return errWrongType(a.typ, ResTableStagedAlias)
}
a.count = btou32(bin[8:])
a.entries = make([]StagedAliasEntry, a.count)
for i := range a.entries {
if err := a.entries[i].UnmarshalBinary(bin[12+i*8:]); err != nil {
return err
}
}
return nil
}
func (a *StagedAlias) MarshalBinary() ([]byte, error) {
chunkHeaderBin, err := a.chunkHeader.MarshalBinary()
if err != nil {
return nil, err
}
countBin := make([]byte, 4)
putu32(countBin, a.count)
bin := append(chunkHeaderBin, countBin...)
for _, entry := range a.entries {
entryBin, err := entry.MarshalBinary()
if err != nil {
return nil, err
}
bin = append(bin, entryBin...)
}
return bin, nil
}
// Entry is a resource key typically followed by a value or resource map.
type Entry struct {
size uint16
flags uint16
key PoolRef // ref into key pool
// only filled if this is a map entry; when size is 16
parent TableRef // id of parent mapping or zero if none
count uint32 // name and value pairs that follow for FlagComplex
values []*Value
}
func (nt *Entry) UnmarshalBinary(bin []byte) error {
nt.size = btou16(bin)
nt.flags = btou16(bin[2:])
nt.key = PoolRef(btou32(bin[4:]))
if nt.size == 16 {
nt.parent = TableRef(btou32(bin[8:]))
nt.count = btou32(bin[12:])
nt.values = make([]*Value, nt.count)
for i := range nt.values {
val := &Value{}
if err := val.UnmarshalBinary(bin[16+i*12:]); err != nil {
return err
}
nt.values[i] = val
}
} else {
data := &Data{}
if err := data.UnmarshalBinary(bin[8:]); err != nil {
return err
}
// TODO boxing data not strictly correct as binary repr isn't of Value.
nt.values = append(nt.values, &Value{0, data})
}
return nil
}
func (nt *Entry) MarshalBinary() ([]byte, error) {
bin := make([]byte, 8)
sz := nt.size
if sz == 0 {
sz = 8
}
putu16(bin, sz)
putu16(bin[2:], nt.flags)
putu32(bin[4:], uint32(nt.key))
if sz == 16 {
bin = append(bin, make([]byte, 8+len(nt.values)*12)...)
putu32(bin[8:], uint32(nt.parent))
putu32(bin[12:], uint32(len(nt.values)))
for i, val := range nt.values {
b, err := val.MarshalBinary()
if err != nil {
return nil, err
}
copy(bin[16+i*12:], b)
}
} else {
b, err := nt.values[0].data.MarshalBinary()
if err != nil {
return nil, err
}
bin = append(bin, b...)
}
return bin, nil
}
type Value struct {
name TableRef
data *Data
}
func (val *Value) UnmarshalBinary(bin []byte) error {
val.name = TableRef(btou32(bin))
val.data = &Data{}
return val.data.UnmarshalBinary(bin[4:])
}
func (val *Value) MarshalBinary() ([]byte, error) {
bin := make([]byte, 12)
putu32(bin, uint32(val.name))
b, err := val.data.MarshalBinary()
if err != nil {
return nil, err
}
copy(bin[4:], b)
return bin, nil
}
type DataType uint8
// explicitly defined for clarity and resolvability with apt source
const (
DataNull DataType = 0x00 // either 0 or 1 for resource undefined or empty
DataReference DataType = 0x01 // ResTable_ref, a reference to another resource table entry
DataAttribute DataType = 0x02 // attribute resource identifier
DataString DataType = 0x03 // index into the containing resource table's global value string pool
DataFloat DataType = 0x04 // single-precision floating point number
DataDimension DataType = 0x05 // complex number encoding a dimension value, such as "100in"
DataFraction DataType = 0x06 // complex number encoding a fraction of a container
DataDynamicReference DataType = 0x07 // dynamic ResTable_ref, which needs to be resolved before it can be used like a TYPE_REFERENCE.
DataIntDec DataType = 0x10 // raw integer value of the form n..n
DataIntHex DataType = 0x11 // raw integer value of the form 0xn..n
DataIntBool DataType = 0x12 // either 0 or 1, for input "false" or "true"
DataIntColorARGB8 DataType = 0x1c // raw integer value of the form #aarrggbb
DataIntColorRGB8 DataType = 0x1d // raw integer value of the form #rrggbb
DataIntColorARGB4 DataType = 0x1e // raw integer value of the form #argb
DataIntColorRGB4 DataType = 0x1f // raw integer value of the form #rgb
)
type Data struct {
ByteSize uint16
Res0 uint8 // always 0, useful for debugging bad read offsets
Type DataType
Value uint32
}
func (d *Data) UnmarshalBinary(bin []byte) error {
d.ByteSize = btou16(bin)
d.Res0 = uint8(bin[2])
d.Type = DataType(bin[3])
d.Value = btou32(bin[4:])
return nil
}
func (d *Data) MarshalBinary() ([]byte, error) {
bin := make([]byte, 8)
putu16(bin, 8)
bin[2] = byte(d.Res0)
bin[3] = byte(d.Type)
putu32(bin[4:], d.Value)
return bin, nil
}
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package mobile provides functions for building Cogent Core apps for mobile devices.
package mobile
//go:generate go run gendex.go -o dex.go
import (
"bufio"
"errors"
"fmt"
"io"
"regexp"
"strconv"
"strings"
"slices"
"log/slog"
"maps"
"cogentcore.org/core/base/exec"
"cogentcore.org/core/base/logx"
"cogentcore.org/core/cmd/config"
"golang.org/x/tools/go/packages"
)
var tmpDir string
// Build compiles and encodes the app named by the import path.
//
// The named package must define a main function.
//
// The -target flag takes either android (the default), or one or more
// comma-delimited Apple platforms (TODO: apple platforms list).
//
// For -target android, if an AndroidManifest.xml is defined in the
// package directory, it is added to the APK output. Otherwise, a default
// manifest is generated. By default, this builds a fat APK for all supported
// instruction sets (arm, 386, amd64, arm64). A subset of instruction sets can
// be selected by specifying target type with the architecture name. E.g.
// -target=android/arm,android/386.
//
// For Apple -target platforms, gomobile must be run on an OS X machine with
// Xcode installed.
//
// By default, -target ios will generate an XCFramework for both ios
// and iossimulator. Multiple Apple targets can be specified, creating a "fat"
// XCFramework with each slice. To generate a fat XCFramework that supports
// iOS, macOS, and macCatalyst for all supportec architectures (amd64 and arm64),
// specify -target ios,macos,maccatalyst. A subset of instruction sets can be
// selectged by specifying the platform with an architecture name. E.g.
// -target=ios/arm64,maccatalyst/arm64.
//
// If the package directory contains an assets subdirectory, its contents
// are copied into the output.
func Build(c *config.Config) error {
_, err := buildImpl(c)
return err
}
// buildImpl builds a package for mobiles based on the given config info.
// buildImpl returns a built package information and an error if exists.
func buildImpl(c *config.Config) (*packages.Package, error) {
cleanup, err := buildEnvInit(c)
if err != nil {
return nil, err
}
defer cleanup()
for _, platform := range c.Build.Target {
if platform.Arch == "*" {
archs := config.ArchsForOS[platform.OS]
c.Build.Target = make([]config.Platform, len(archs))
for i, arch := range archs {
c.Build.Target[i] = config.Platform{OS: platform.OS, Arch: arch}
}
}
}
// Special case to add iossimulator if we don't already have it and we have ios
hasIOSSimulator := slices.ContainsFunc(c.Build.Target,
func(p config.Platform) bool { return p.OS == "iossimulator" })
hasIOS := slices.ContainsFunc(c.Build.Target,
func(p config.Platform) bool { return p.OS == "ios" })
if !hasIOSSimulator && hasIOS {
c.Build.Target = append(c.Build.Target, config.Platform{OS: "iossimulator", Arch: "arm64"}) // TODO: set arch better here
}
// TODO(ydnar): this should work, unless build tags affect loading a single package.
// Should we try to import packages with different build tags per platform?
pkgs, err := packages.Load(packagesConfig(&c.Build.Target[0]), ".")
if err != nil {
return nil, err
}
// len(pkgs) can be more than 1 e.g., when the specified path includes `...`.
if len(pkgs) != 1 {
return nil, fmt.Errorf("expected 1 package but got %d", len(pkgs))
}
pkg := pkgs[0]
if pkg.Name != "main" {
return nil, errors.New("cannot build non-main package")
}
if c.ID == "" {
return nil, errors.New("id must be set when building for mobile")
}
switch {
case isAndroidPlatform(c.Build.Target[0].OS):
if pkg.Name != "main" {
for _, t := range c.Build.Target {
if err := goBuild(c, pkg.PkgPath, androidEnv[t.Arch]); err != nil {
return nil, err
}
}
return pkg, nil
}
_, err = goAndroidBuild(c, pkg, c.Build.Target)
if err != nil {
return nil, err
}
case isApplePlatform(c.Build.Target[0].OS):
if !xCodeAvailable() {
return nil, fmt.Errorf("-target=%s requires XCode", c.Build.Target)
}
if pkg.Name != "main" {
for _, t := range c.Build.Target {
// Catalyst support requires iOS 13+
v, _ := strconv.ParseFloat(c.Build.IOSVersion, 64)
if t.OS == "maccatalyst" && v < 13.0 {
return nil, errors.New("catalyst requires -iosversion=13 or higher")
}
if err := goBuild(c, pkg.PkgPath, appleEnv[t.String()]); err != nil {
return nil, err
}
}
return pkg, nil
}
_, err = goAppleBuild(c, pkg, c.Build.Target)
if err != nil {
return nil, err
}
}
return pkg, nil
}
var nmRE = regexp.MustCompile(`[0-9a-f]{8} t _?(?:.*/vendor/)?(golang.org/x.*/[^.]*)`)
func extractPkgs(nm string, path string) (map[string]bool, error) {
r, w := io.Pipe()
nmpkgs := make(map[string]bool)
errc := make(chan error, 1)
go func() {
s := bufio.NewScanner(r)
for s.Scan() {
if res := nmRE.FindStringSubmatch(s.Text()); res != nil {
nmpkgs[res[1]] = true
}
}
errc <- s.Err()
}()
err := exec.Major().SetStdout(w).Run(nm, path)
w.Close()
if err != nil {
return nil, fmt.Errorf("%s %s: %v", nm, path, err)
}
if err := <-errc; err != nil {
return nil, fmt.Errorf("%s %s: %v", nm, path, err)
}
return nmpkgs, nil
}
func goBuild(c *config.Config, src string, env map[string]string, args ...string) error {
return goCmd(c, "build", []string{src}, env, args...)
}
func goCmd(c *config.Config, subcmd string, srcs []string, env map[string]string, args ...string) error {
return goCmdAt(c, "", subcmd, srcs, env, args...)
}
func goCmdAt(c *config.Config, at string, subcmd string, srcs []string, env map[string]string, args ...string) error {
cargs := []string{subcmd}
// cmd := exec.Command("go", subcmd)
var tags []string
if c.Build.Debug {
tags = append(tags, "debug")
// (with those of the platform, which -tags would replace)
for f := range strings.FieldsSeq(env["GOFLAGS"]) {
if ts, ok := strings.CutPrefix(f, "-tags="); ok {
tags = append(tags, strings.Split(ts, ",")...)
}
}
}
if len(tags) > 0 {
cargs = append(cargs, "-tags", strings.Join(tags, ","))
}
if logx.UserLevel <= slog.LevelInfo {
cargs = append(cargs, "-v")
}
cargs = append(cargs, args...)
cargs = append(cargs, srcs...)
xc := exec.Major().SetDir(at)
maps.Copy(xc.Env, env)
// Specify GOMODCACHE explicitly. The default cache path is GOPATH[0]/pkg/mod,
// but the path varies when GOPATH is specified at env, which results in cold cache.
if gmc, err := goModCachePath(); err == nil {
xc.SetEnv("GOMODCACHE", gmc)
}
return xc.Run("go", cargs...)
}
func goModCachePath() (string, error) {
out, err := exec.Output("go", "env", "GOMODCACHE")
if err != nil {
return "", err
}
return strings.TrimSpace(string(out)), nil
}
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mobile
import (
"bytes"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"encoding/xml"
"errors"
"fmt"
"image/png"
"io"
"log"
"os"
"path/filepath"
"cogentcore.org/core/base/elide"
"cogentcore.org/core/base/exec"
"cogentcore.org/core/base/logx"
"cogentcore.org/core/cmd/config"
"cogentcore.org/core/cmd/mobile/binres"
"cogentcore.org/core/cmd/rendericon"
"golang.org/x/tools/go/packages"
)
const (
minAndroidSDK = 23
defaultAndroidTargetSDK = 29
)
// goAndroidBuild builds the given package for the given Android targets.
func goAndroidBuild(c *config.Config, pkg *packages.Package, targets []config.Platform) (map[string]bool, error) {
ndkRoot, err := ndkRoot(c, targets...)
if err != nil {
return nil, err
}
libName := androidPkgName(c.Name)
// TODO(hajimehoshi): This works only with Go tools that assume all source files are in one directory.
// Fix this to work with other Go tools.
dir := filepath.Dir(pkg.GoFiles[0])
manifestPath := filepath.Join(dir, "AndroidManifest.xml")
manifestData, err := os.ReadFile(manifestPath)
if err != nil {
if !os.IsNotExist(err) {
return nil, err
}
buf := new(bytes.Buffer)
buf.WriteString(`<?xml version="1.0" encoding="utf-8"?>`)
err := manifestTmpl.Execute(buf, manifestTmplData{
JavaPkgPath: c.ID,
Name: elide.AppName(c.Name),
LibName: libName,
})
if err != nil {
return nil, err
}
manifestData = buf.Bytes()
logx.PrintfDebug("generated AndroidManifest.xml:\n%s\n", manifestData)
} else {
libName, err = manifestLibName(manifestData)
if err != nil {
return nil, fmt.Errorf("error parsing %s: %v", manifestPath, err)
}
}
libFiles := []string{}
nmpkgs := make(map[string]map[string]bool) // map: arch -> extractPkgs' output
for _, t := range targets {
toolchain := ndk.toolchain(t.Arch)
libPath := "lib/" + toolchain.ABI + "/lib" + libName + ".so"
libAbsPath := filepath.Join(tmpDir, libPath)
if err := exec.MkdirAll(filepath.Dir(libAbsPath), 0755); err != nil {
return nil, err
}
args := []string{
"-buildmode=c-shared",
"-ldflags", config.LinkerFlags(c),
"-o", libAbsPath,
}
if c.Build.Trimpath {
args = append(args, "-trimpath")
}
err = goBuild(
c,
pkg.PkgPath,
androidEnv[t.Arch],
args...,
)
if err != nil {
return nil, err
}
nmpkgs[t.Arch], err = extractPkgs(toolchain.path(c, ndkRoot, "nm"), libAbsPath)
if err != nil {
return nil, err
}
libFiles = append(libFiles, libPath)
}
block, _ := pem.Decode([]byte(debugCert))
if block == nil {
return nil, errors.New("no debug cert")
}
privKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
err = os.MkdirAll(c.Build.Output, 0777)
if err != nil {
return nil, err
}
var out io.Writer
f, err := os.Create(filepath.Join(c.Build.Output, c.Name+".apk"))
if err != nil {
return nil, err
}
defer func() {
if cerr := f.Close(); err == nil {
err = cerr
}
}()
out = f
apkw := newWriter(out, privKey)
apkwCreate := func(name string) (io.Writer, error) {
logx.PrintfInfo("apk: %s\n", name)
return apkw.Create(name)
}
apkwWriteFile := func(dst, src string) error {
w, err := apkwCreate(dst)
if err != nil {
return err
}
f, err := os.Open(src)
if err != nil {
return err
}
defer f.Close()
if _, err := io.Copy(w, f); err != nil {
return err
}
return nil
}
// TODO: do we need this writer stuff?
w, err := apkwCreate("classes.dex")
if err != nil {
return nil, err
}
dexData, err := base64.StdEncoding.DecodeString(dexStr)
if err != nil {
log.Fatalf("internal error: bad dexStr: %v", err)
}
if _, err := w.Write(dexData); err != nil {
return nil, err
}
for _, libFile := range libFiles {
if err := apkwWriteFile(libFile, filepath.Join(tmpDir, libFile)); err != nil {
return nil, err
}
}
// TODO: what should we do about OpenAL?
for _, t := range targets {
toolchain := ndk.toolchain(t.Arch)
if nmpkgs[t.Arch]["cogentcore.org/core/mobile/exp/audio/al"] {
dst := "lib/" + toolchain.ABI + "/libopenal.so"
src := filepath.Join(goMobilePath, dst)
if _, err := os.Stat(src); err != nil {
return nil, errors.New("the Android requires the golang.org/x/mobile/exp/audio/al, but the OpenAL libraries was not found. Please run gomobile init with the -openal flag pointing to an OpenAL source directory")
}
if err := apkwWriteFile(dst, src); err != nil {
return nil, err
}
}
}
// Add the icon. 512 is the largest icon size on Android
// (for the Google Play Store icon).
ic, err := rendericon.Render(512)
if err != nil {
return nil, err
}
bxml, err := binres.UnmarshalXML(bytes.NewReader(manifestData), true, c.Build.AndroidMinSDK, c.Build.AndroidTargetSDK)
if err != nil {
return nil, err
}
// generate resources.arsc identifying single xxxhdpi icon resource.
pkgname, err := bxml.RawValueByName("manifest", xml.Name{Local: "package"})
if err != nil {
return nil, err
}
tbl, name := binres.NewMipmapTable(pkgname)
iw, err := apkwCreate(name)
if err != nil {
return nil, err
}
err = png.Encode(iw, ic)
if err != nil {
return nil, err
}
resw, err := apkwCreate("resources.arsc")
if err != nil {
return nil, err
}
rbin, err := tbl.MarshalBinary()
if err != nil {
return nil, err
}
if _, err := resw.Write(rbin); err != nil {
return nil, err
}
w, err = apkwCreate("AndroidManifest.xml")
if err != nil {
return nil, err
}
bin, err := bxml.MarshalBinary()
if err != nil {
return nil, err
}
if _, err := w.Write(bin); err != nil {
return nil, err
}
// TODO: add gdbserver to apk?
if err := apkw.Close(); err != nil {
return nil, err
}
// TODO: return nmpkgs
return nmpkgs[targets[0].Arch], nil
}
// androidPkgName sanitizes the go package name to be acceptable as a android
// package name part. The android package name convention is similar to the
// java package name convention described in
// https://docs.oracle.com/javase/specs/jls/se8/html/jls-6.html#jls-6.5.3.1
// but not exactly same.
func androidPkgName(name string) string {
var res []rune
for _, r := range name {
switch {
case 'a' <= r && r <= 'z', 'A' <= r && r <= 'Z', '0' <= r && r <= '9':
res = append(res, r)
default:
res = append(res, '_')
}
}
if len(res) == 0 || res[0] == '_' || ('0' <= res[0] && res[0] <= '9') {
// Android does not seem to allow the package part starting with _.
res = append([]rune{'g', 'o'}, res...)
}
s := string(res)
// Look for Java keywords that are not Go keywords, and avoid using
// them as a package name.
//
// This is not a problem for normal Go identifiers as we only expose
// exported symbols. The upper case first letter saves everything
// from accidentally matching except for the package name.
//
// Note that basic type names (like int) are not keywords in Go.
switch s {
case "abstract", "assert", "boolean", "byte", "catch", "char", "class",
"do", "double", "enum", "extends", "final", "finally", "float",
"implements", "instanceof", "int", "long", "native", "private",
"protected", "public", "short", "static", "strictfp", "super",
"synchronized", "this", "throw", "throws", "transient", "try",
"void", "volatile", "while":
s += "_"
}
return s
}
// A random uninteresting private key.
// Must be consistent across builds so newer app versions can be installed.
const debugCert = `
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAy6ItnWZJ8DpX9R5FdWbS9Kr1U8Z7mKgqNByGU7No99JUnmyu
NQ6Uy6Nj0Gz3o3c0BXESECblOC13WdzjsH1Pi7/L9QV8jXOXX8cvkG5SJAyj6hcO
LOapjDiN89NXjXtyv206JWYvRtpexyVrmHJgRAw3fiFI+m4g4Qop1CxcIF/EgYh7
rYrqh4wbCM1OGaCleQWaOCXxZGm+J5YNKQcWpjZRrDrb35IZmlT0bK46CXUKvCqK
x7YXHgfhC8ZsXCtsScKJVHs7gEsNxz7A0XoibFw6DoxtjKzUCktnT0w3wxdY7OTj
9AR8mobFlM9W3yirX8TtwekWhDNTYEu8dwwykwIDAQABAoIBAA2hjpIhvcNR9H9Z
BmdEecydAQ0ZlT5zy1dvrWI++UDVmIp+Ve8BSd6T0mOqV61elmHi3sWsBN4M1Rdz
3N38lW2SajG9q0fAvBpSOBHgAKmfGv3Ziz5gNmtHgeEXfZ3f7J95zVGhlHqWtY95
JsmuplkHxFMyITN6WcMWrhQg4A3enKLhJLlaGLJf9PeBrvVxHR1/txrfENd2iJBH
FmxVGILL09fIIktJvoScbzVOneeWXj5vJGzWVhB17DHBbANGvVPdD5f+k/s5aooh
hWAy/yLKocr294C4J+gkO5h2zjjjSGcmVHfrhlXQoEPX+iW1TGoF8BMtl4Llc+jw
lKWKfpECgYEA9C428Z6CvAn+KJ2yhbAtuRo41kkOVoiQPtlPeRYs91Pq4+NBlfKO
2nWLkyavVrLx4YQeCeaEU2Xoieo9msfLZGTVxgRlztylOUR+zz2FzDBYGicuUD3s
EqC0Wv7tiX6dumpWyOcVVLmR9aKlOUzA9xemzIsWUwL3PpyONhKSq7kCgYEA1X2F
f2jKjoOVzglhtuX4/SP9GxS4gRf9rOQ1Q8DzZhyH2LZ6Dnb1uEQvGhiqJTU8CXxb
7odI0fgyNXq425Nlxc1Tu0G38TtJhwrx7HWHuFcbI/QpRtDYLWil8Zr7Q3BT9rdh
moo4m937hLMvqOG9pyIbyjOEPK2WBCtKW5yabqsCgYEAu9DkUBr1Qf+Jr+IEU9I8
iRkDSMeusJ6gHMd32pJVCfRRQvIlG1oTyTMKpafmzBAd/rFpjYHynFdRcutqcShm
aJUq3QG68U9EAvWNeIhA5tr0mUEz3WKTt4xGzYsyWES8u4tZr3QXMzD9dOuinJ1N
+4EEumXtSPKKDG3M8Qh+KnkCgYBUEVSTYmF5EynXc2xOCGsuy5AsrNEmzJqxDUBI
SN/P0uZPmTOhJIkIIZlmrlW5xye4GIde+1jajeC/nG7U0EsgRAV31J4pWQ5QJigz
0+g419wxIUFryGuIHhBSfpP472+w1G+T2mAGSLh1fdYDq7jx6oWE7xpghn5vb9id
EKLjdwKBgBtz9mzbzutIfAW0Y8F23T60nKvQ0gibE92rnUbjPnw8HjL3AZLU05N+
cSL5bhq0N5XHK77sscxW9vXjG0LJMXmFZPp9F6aV6ejkMIXyJ/Yz/EqeaJFwilTq
Mc6xR47qkdzu0dQ1aPm4XD7AWDtIvPo/GG2DKOucLBbQc2cOWtKS
-----END RSA PRIVATE KEY-----
`
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mobile
import (
"bytes"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"text/template"
"cogentcore.org/core/base/elide"
"cogentcore.org/core/base/exec"
"cogentcore.org/core/cmd/config"
"cogentcore.org/core/cmd/rendericon"
"github.com/jackmordaunt/icns/v2"
"golang.org/x/tools/go/packages"
)
// goAppleBuild builds the given package with the given bundle ID for the given iOS targets.
func goAppleBuild(c *config.Config, pkg *packages.Package, targets []config.Platform) (map[string]bool, error) {
src := pkg.PkgPath
infoplist := new(bytes.Buffer)
if err := infoPlistTmpl.Execute(infoplist, infoPlistTmplData{
BundleID: c.ID,
Name: elide.AppName(c.Name),
Version: c.Version,
InfoString: c.About,
ShortVersionString: c.Version,
IconFile: "icon.icns",
}); err != nil {
return nil, err
}
// only for the simulator: built for its SDK, without signing for devices
sim := !slices.ContainsFunc(targets, func(t config.Platform) bool { return t.OS != "iossimulator" })
sdk := "iphoneos"
if sim {
sdk = "iphonesimulator"
}
// Detect the team ID
teamID := ""
if !sim {
var err error
teamID, err = detectTeamID()
if err != nil {
return nil, err
}
}
projPbxproj := new(bytes.Buffer)
if err := projPbxprojTmpl.Execute(projPbxproj, projPbxprojTmplData{
TeamID: teamID,
}); err != nil {
return nil, err
}
files := []struct {
name string
contents []byte
}{
{tmpDir + "/main.xcodeproj/project.pbxproj", projPbxproj.Bytes()},
{tmpDir + "/main/Info.plist", infoplist.Bytes()},
{tmpDir + "/main/Images.xcassets/AppIcon.appiconset/Contents.json", []byte(contentsJSON)},
}
for _, file := range files {
if err := exec.MkdirAll(filepath.Dir(file.name), 0755); err != nil {
return nil, err
}
exec.PrintCmd(fmt.Sprintf("echo \"%s\" > %s", file.contents, file.name), nil)
if err := os.WriteFile(file.name, file.contents, 0644); err != nil {
return nil, err
}
}
// We are using lipo tool to build multiarchitecture binaries.
args := []string{"lipo", "-o", filepath.Join(tmpDir, "main/main"), "-create"}
var nmpkgs map[string]bool
builtArch := map[string]bool{}
for _, t := range targets {
// Only one binary per arch allowed
// e.g. ios/arm64 + iossimulator/amd64
if builtArch[t.Arch] {
continue
}
builtArch[t.Arch] = true
path := filepath.Join(tmpDir, t.OS, t.Arch)
buildArgs := []string{
"-ldflags", config.LinkerFlags(c), "-o=" + path,
}
if c.Build.Trimpath {
buildArgs = append(buildArgs, "-trimpath")
}
if t.OS == "iossimulator" {
if err := checkSimulatorWGPU(t.Arch); err != nil {
return nil, err
}
}
if err := goBuild(c, src, appleEnv[t.String()], buildArgs...); err != nil {
return nil, err
}
if nmpkgs == nil {
var err error
nmpkgs, err = extractPkgs(appleNM, path)
if err != nil {
return nil, err
}
}
args = append(args, path)
}
if err := exec.Run("xcrun", args...); err != nil {
return nil, err
}
if err := appleCopyAssets(tmpDir); err != nil {
return nil, err
}
// Build and move the release build to the output directory.
xargs := []string{"xcodebuild", "-configuration", "Release",
"-project", tmpDir + "/main.xcodeproj", "-sdk", sdk}
if sim {
xargs = append(xargs, "ARCHS="+archClang(targets[0].Arch), "CODE_SIGN_IDENTITY=-")
} else {
xargs = append(xargs, "-allowProvisioningUpdates", "DEVELOPMENT_TEAM="+teamID)
}
err := exec.Run("xcrun", xargs...)
if err != nil {
return nil, err
}
built := tmpDir + "/build/Release-" + sdk + "/main.app"
inm := filepath.Join(built, "icon.icns")
fdsi, err := os.Create(inm)
if err != nil {
return nil, err
}
defer fdsi.Close()
// 1024x1024 is the largest icon size on iOS
// (for the App Store)
sic, err := rendericon.Render(1024)
if err != nil {
return nil, err
}
err = icns.Encode(fdsi, sic)
if err != nil {
return nil, err
}
// TODO(jbd): Fallback to copying if renaming fails.
err = os.MkdirAll(c.Build.Output, 0777)
if err != nil {
return nil, err
}
output := filepath.Join(c.Build.Output, c.Name+".app")
exec.PrintCmd(fmt.Sprintf("mv %s %s", built, output), nil)
// if output already exists, remove.
if err := exec.RemoveAll(output); err != nil {
return nil, err
}
if err := os.Rename(built, output); err != nil {
return nil, err
}
return nmpkgs, nil
}
// detectTeamID determines the Apple Development Team ID on the system.
func detectTeamID() (string, error) {
// Grabs the first certificate for "Apple Development"; will not work if there
// are multiple certificates and the first is not desired.
pemString, err := exec.Output(
"security", "find-certificate",
"-c", "Apple Development", "-p",
)
if err != nil {
err = fmt.Errorf("failed to pull the signing certificate to determine your team ID: %v", err)
return "", err
}
block, _ := pem.Decode([]byte(pemString))
if block == nil {
err = fmt.Errorf("failed to decode the PEM to determine your team ID: %s", pemString)
return "", err
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
err = fmt.Errorf("failed to parse your signing certificate to determine your team ID: %v", err)
return "", err
}
if len(cert.Subject.OrganizationalUnit) == 0 {
err = errors.New("the signing certificate has no organizational unit (team ID)")
return "", err
}
return cert.Subject.OrganizationalUnit[0], nil
}
func appleCopyAssets(xcodeProjDir string) error {
dstAssets := xcodeProjDir + "/main/assets"
return exec.MkdirAll(dstAssets, 0755)
}
type infoPlistTmplData struct {
BundleID string
Name string
Version string
InfoString string
ShortVersionString string
IconFile string
}
var infoPlistTmpl = template.Must(template.New("infoPlist").Parse(`<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>main</string>
<key>CFBundleIdentifier</key>
<string>{{.BundleID}}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>{{.Name}}</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>{{ .Version }}</string>
<key>CFBundleGetInfoString</key>
<string>{{ .InfoString }}</string>
<key>CFBundleShortVersionString</key>
<string>{{ .ShortVersionString }}</string>
<key>CFBundleIconFile</key>
<string>{{ .IconFile }}</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>
<false/>
<key>UISceneConfigurations</key>
<dict>
<key>UIWindowSceneSessionRoleApplication</key>
<array>
<dict>
<key>UISceneConfigurationName</key>
<string>Default Configuration</string>
<key>UISceneDelegateClassName</key>
<string>GoAppSceneDelegate</string>
</dict>
</array>
</dict>
</dict>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>
`))
type projPbxprojTmplData struct {
TeamID string
}
var projPbxprojTmpl = template.Must(template.New("projPbxproj").Parse(`// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 46;
objects = {
/* Begin PBXBuildFile section */
254BB84F1B1FD08900C56DE9 /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 254BB84E1B1FD08900C56DE9 /* Images.xcassets */; };
254BB8681B1FD16500C56DE9 /* main in Resources */ = {isa = PBXBuildFile; fileRef = 254BB8671B1FD16500C56DE9 /* main */; };
25FB30331B30FDEE0005924C /* assets in Resources */ = {isa = PBXBuildFile; fileRef = 25FB30321B30FDEE0005924C /* assets */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
254BB83E1B1FD08900C56DE9 /* main.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = main.app; sourceTree = BUILT_PRODUCTS_DIR; };
254BB8421B1FD08900C56DE9 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
254BB84E1B1FD08900C56DE9 /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Images.xcassets; sourceTree = "<group>"; };
254BB8671B1FD16500C56DE9 /* main */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.executable"; path = main; sourceTree = "<group>"; };
25FB30321B30FDEE0005924C /* assets */ = {isa = PBXFileReference; lastKnownFileType = folder; name = assets; path = main/assets; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXGroup section */
254BB8351B1FD08900C56DE9 = {
isa = PBXGroup;
children = (
25FB30321B30FDEE0005924C /* assets */,
254BB8401B1FD08900C56DE9 /* main */,
254BB83F1B1FD08900C56DE9 /* Products */,
);
sourceTree = "<group>";
usesTabs = 0;
};
254BB83F1B1FD08900C56DE9 /* Products */ = {
isa = PBXGroup;
children = (
254BB83E1B1FD08900C56DE9 /* main.app */,
);
name = Products;
sourceTree = "<group>";
};
254BB8401B1FD08900C56DE9 /* main */ = {
isa = PBXGroup;
children = (
254BB8671B1FD16500C56DE9 /* main */,
254BB84E1B1FD08900C56DE9 /* Images.xcassets */,
254BB8411B1FD08900C56DE9 /* Supporting Files */,
);
path = main;
sourceTree = "<group>";
};
254BB8411B1FD08900C56DE9 /* Supporting Files */ = {
isa = PBXGroup;
children = (
254BB8421B1FD08900C56DE9 /* Info.plist */,
);
name = "Supporting Files";
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
254BB83D1B1FD08900C56DE9 /* main */ = {
isa = PBXNativeTarget;
buildConfigurationList = 254BB8611B1FD08900C56DE9 /* Build configuration list for PBXNativeTarget "main" */;
buildPhases = (
254BB83C1B1FD08900C56DE9 /* Resources */,
);
buildRules = (
);
dependencies = (
);
name = main;
productName = main;
productReference = 254BB83E1B1FD08900C56DE9 /* main.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
254BB8361B1FD08900C56DE9 /* Project object */ = {
isa = PBXProject;
attributes = {
LastUpgradeCheck = 0630;
ORGANIZATIONNAME = Developer;
TargetAttributes = {
254BB83D1B1FD08900C56DE9 = {
CreatedOnToolsVersion = 6.3.1;
DevelopmentTeam = "{{.TeamID}}";
};
};
};
buildConfigurationList = 254BB8391B1FD08900C56DE9 /* Build configuration list for PBXProject "main" */;
compatibilityVersion = "Xcode 3.2";
developmentRegion = English;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 254BB8351B1FD08900C56DE9;
productRefGroup = 254BB83F1B1FD08900C56DE9 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
254BB83D1B1FD08900C56DE9 /* main */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
254BB83C1B1FD08900C56DE9 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
25FB30331B30FDEE0005924C /* assets in Resources */,
254BB8681B1FD16500C56DE9 /* main in Resources */,
254BB84F1B1FD08900C56DE9 /* Images.xcassets in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin XCBuildConfiguration section */
254BB8601B1FD08900C56DE9 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "Apple Development";
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
TARGETED_DEVICE_FAMILY = "1,2";
VALIDATE_PRODUCT = YES;
ENABLE_BITCODE = NO;
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
};
name = Release;
};
254BB8631B1FD08900C56DE9 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
INFOPLIST_FILE = main/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
254BB8391B1FD08900C56DE9 /* Build configuration list for PBXProject "main" */ = {
isa = XCConfigurationList;
buildConfigurations = (
254BB8601B1FD08900C56DE9 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
254BB8611B1FD08900C56DE9 /* Build configuration list for PBXNativeTarget "main" */ = {
isa = XCConfigurationList;
buildConfigurations = (
254BB8631B1FD08900C56DE9 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 254BB8361B1FD08900C56DE9 /* Project object */;
}
`))
const contentsJSON = `{
"images" : [
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "3x"
},
{
"idiom" : "ipad",
"size" : "29x29",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "29x29",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "40x40",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "40x40",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "76x76",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "76x76",
"scale" : "2x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
`
// rfc1034Label sanitizes the name to be usable in a uniform type identifier.
// The sanitization is similar to xcode's rfc1034identifier macro that
// replaces illegal characters (not conforming the rfc1034 label rule) with '-'.
func rfc1034Label(name string) string {
// * Uniform type identifier:
//
// According to
// https://developer.apple.com/library/ios/documentation/FileManagement/Conceptual/understanding_utis/understand_utis_conc/understand_utis_conc.html
//
// A uniform type identifier is a Unicode string that usually contains characters
// in the ASCII character set. However, only a subset of the ASCII characters are
// permitted. You may use the Roman alphabet in upper and lower case (A–Z, a–z),
// the digits 0 through 9, the dot (“.”), and the hyphen (“-”). This restriction
// is based on DNS name restrictions, set forth in RFC 1035.
//
// Uniform type identifiers may also contain any of the Unicode characters greater
// than U+007F.
//
// Note: the actual implementation of xcode does not allow some unicode characters
// greater than U+007f. In this implementation, we just replace everything non
// alphanumeric with "-" like the rfc1034identifier macro.
//
// * RFC1034 Label
//
// <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
// <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
// <let-dig-hyp> ::= <let-dig> | "-"
// <let-dig> ::= <letter> | <digit>
const surrSelf = 0x10000
begin := false
var res []rune
for i, r := range name {
if r == '.' && !begin {
continue
}
begin = true
switch {
case 'a' <= r && r <= 'z', 'A' <= r && r <= 'Z':
res = append(res, r)
case '0' <= r && r <= '9':
if i == 0 {
res = append(res, '-')
} else {
res = append(res, r)
}
default:
if r < surrSelf {
res = append(res, '-')
} else {
res = append(res, '-', '-')
}
}
}
return string(res)
}
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mobile
import (
"crypto"
"crypto/rsa"
"crypto/sha1"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"io"
"math/big"
"time"
)
// signPKCS7 does the minimal amount of work necessary to embed an RSA
// signature into a PKCS#7 certificate.
//
// We prepare the certificate using the x509 package, read it back in
// to our custom data type and then write it back out with the signature.
func signPKCS7(rand io.Reader, priv *rsa.PrivateKey, msg []byte) ([]byte, error) {
b, err := apkCertificate(rand, priv)
if err != nil {
return nil, err
}
return signPKCS7Cert(rand, priv, b, msg)
}
// apkCertSerial and apkCertName are the serial number and name of the
// certificate of [apkCertificate].
const apkCertSerial = 0x5462c4dd // arbitrary
var apkCertName = pkix.Name{CommonName: "gomobile"}
// apkCertificate returns the self-signed certificate (DER) of the given
// key that signs APKs, in both their v1 (JAR) and v2 signatures.
func apkCertificate(rand io.Reader, priv *rsa.PrivateKey) ([]byte, error) {
template := &x509.Certificate{
SerialNumber: big.NewInt(apkCertSerial),
SignatureAlgorithm: x509.SHA1WithRSA,
Subject: apkCertName,
}
return x509.CreateCertificate(rand, template, template, priv.Public(), priv)
}
// signPKCS7Cert is [signPKCS7] with the given certificate (DER) of
// [apkCertificate].
func signPKCS7Cert(rand io.Reader, priv *rsa.PrivateKey, b, msg []byte) ([]byte, error) {
const serialNumber = apkCertSerial
name := apkCertName
c := certificate{}
if _, err := asn1.Unmarshal(b, &c); err != nil {
return nil, err
}
h := sha1.New()
h.Write(msg)
hashed := h.Sum(nil)
signed, err := rsa.SignPKCS1v15(rand, priv, crypto.SHA1, hashed)
if err != nil {
return nil, err
}
content := pkcs7SignedData{
ContentType: oidSignedData,
Content: signedData{
Version: 1,
DigestAlgorithms: []pkix.AlgorithmIdentifier{{
Algorithm: oidSHA1,
Parameters: asn1.RawValue{Tag: 5},
}},
ContentInfo: contentInfo{Type: oidData},
Certificates: c,
SignerInfos: []signerInfo{{
Version: 1,
IssuerAndSerialNumber: issuerAndSerialNumber{
Issuer: name.ToRDNSequence(),
SerialNumber: serialNumber,
},
DigestAlgorithm: pkix.AlgorithmIdentifier{
Algorithm: oidSHA1,
Parameters: asn1.RawValue{Tag: 5},
},
DigestEncryptionAlgorithm: pkix.AlgorithmIdentifier{
Algorithm: oidRSAEncryption,
Parameters: asn1.RawValue{Tag: 5},
},
EncryptedDigest: signed,
}},
},
}
return asn1.Marshal(content)
}
type pkcs7SignedData struct {
ContentType asn1.ObjectIdentifier
Content signedData `asn1:"tag:0,explicit"`
}
// signedData is defined in rfc2315, section 9.1.
type signedData struct {
Version int
DigestAlgorithms []pkix.AlgorithmIdentifier `asn1:"set"`
ContentInfo contentInfo
Certificates certificate `asn1:"tag0,explicit"`
SignerInfos []signerInfo `asn1:"set"`
}
type contentInfo struct {
Type asn1.ObjectIdentifier
// Content is optional in PKCS#7 and not provided here.
}
// certificate is defined in rfc2459, section 4.1.
type certificate struct {
TBSCertificate tbsCertificate
SignatureAlgorithm pkix.AlgorithmIdentifier
SignatureValue asn1.BitString
}
// tbsCertificate is defined in rfc2459, section 4.1.
type tbsCertificate struct {
Version int `asn1:"tag:0,default:2,explicit"`
SerialNumber int
Signature pkix.AlgorithmIdentifier
Issuer pkix.RDNSequence // pkix.Name
Validity validity
Subject pkix.RDNSequence // pkix.Name
SubjectPKI subjectPublicKeyInfo
}
// validity is defined in rfc2459, section 4.1.
type validity struct {
NotBefore time.Time
NotAfter time.Time
}
// subjectPublicKeyInfo is defined in rfc2459, section 4.1.
type subjectPublicKeyInfo struct {
Algorithm pkix.AlgorithmIdentifier
SubjectPublicKey asn1.BitString
}
type signerInfo struct {
Version int
IssuerAndSerialNumber issuerAndSerialNumber
DigestAlgorithm pkix.AlgorithmIdentifier
DigestEncryptionAlgorithm pkix.AlgorithmIdentifier
EncryptedDigest []byte
}
type issuerAndSerialNumber struct {
Issuer pkix.RDNSequence // pkix.Name
SerialNumber int
}
// Various ASN.1 Object Identifies, mostly from rfc3852.
var (
// oidPKCS7 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 7}
oidData = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 7, 1}
oidSignedData = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 7, 2}
oidSHA1 = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 26}
oidRSAEncryption = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
)
package mobile
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"runtime"
"strings"
"slices"
"cogentcore.org/core/base/exec"
"cogentcore.org/core/base/logx"
"cogentcore.org/core/cmd/config"
"cogentcore.org/core/cmd/mobile/sdkpath"
)
// General mobile build environment. Initialized by envInit.
var (
goMobilePath string // $GOPATH/pkg/gomobile
androidEnv map[string]map[string]string // android arch -> map[string]string
appleEnv map[string]map[string]string // platform/arch -> map[string]string
appleNM string
)
func isAndroidPlatform(platform string) bool {
return platform == "android"
}
func isApplePlatform(platform string) bool {
return slices.Contains(applePlatforms, platform)
}
var applePlatforms = []string{"ios", "iossimulator", "macos", "maccatalyst"}
func platformArchs(platform string) []string {
switch platform {
case "ios":
return []string{"arm64"}
case "iossimulator":
return []string{"arm64", "amd64"}
case "macos", "maccatalyst":
return []string{"arm64", "amd64"}
case "android":
return []string{"arm", "arm64", "386", "amd64"}
default:
panic(fmt.Sprintf("unexpected platform: %s", platform))
}
}
// platformOS returns the correct GOOS value for platform.
func platformOS(platform string) string {
switch platform {
case "android":
return "android"
case "ios", "iossimulator":
return "ios"
case "macos", "maccatalyst":
// For "maccatalyst", Go packages should be built with GOOS=darwin,
// not GOOS=ios, since the underlying OS (and kernel, runtime) is macOS.
// We also apply a "macos" or "maccatalyst" build tag, respectively.
// See below for additional context.
return "darwin"
default:
panic(fmt.Sprintf("unexpected platform: %s", platform))
}
}
func platformTags(platform string) []string {
switch platform {
case "android":
return []string{"android"}
case "ios":
return []string{"ios"}
case "iossimulator":
// selects the libraries for the simulator, such as those of WebGPU
return []string{"ios", "iossimulator"}
case "macos":
return []string{"macos"}
case "maccatalyst":
// Mac Catalyst is a subset of iOS APIs made available on macOS
// designed to ease porting apps developed for iPad to macOS.
// See https://developer.apple.com/mac-catalyst/.
// Because of this, when building a Go package targeting maccatalyst,
// GOOS=darwin (not ios). To bridge the gap and enable maccatalyst
// packages to be compiled, we also specify the "ios" build tag.
// To help discriminate between darwin, ios, macos, and maccatalyst
// targets, there is also a "maccatalyst" tag.
// Some additional context on this can be found here:
// https://stackoverflow.com/questions/12132933/preprocessor-macro-for-os-x-targets/49560690#49560690
// TODO(ydnar): remove tag "ios" when cgo supports Catalyst
// See golang.org/issues/47228
return []string{"ios", "macos", "maccatalyst"}
default:
panic(fmt.Sprintf("unexpected platform: %s", platform))
}
}
func buildEnvInit(c *config.Config) (cleanup func(), err error) {
// Find gomobilepath.
gopath := goEnv("GOPATH")
for _, p := range filepath.SplitList(gopath) {
goMobilePath = filepath.Join(p, "pkg", "gomobile")
if _, err := os.Stat(goMobilePath); err == nil {
break
}
}
logx.PrintlnInfo("GOMOBILE=" + goMobilePath)
// Check the toolchain is in a good state.
// Pick a temporary directory for assembling an apk/app.
if goMobilePath == "" {
return nil, errors.New("toolchain not installed, run `gomobile init`")
}
cleanupFn := func() {
exec.RemoveAll(tmpDir)
}
tmpDir, err = os.MkdirTemp("", "gomobile-work-")
if err != nil {
return nil, err
}
logx.PrintlnInfo("WORK=" + tmpDir)
if err := envInit(c); err != nil {
return nil, err
}
return cleanupFn, nil
}
// appleLinkerFlags are the flags of CGO_LDFLAGS that only the Apple
// linker has, which the Android linker does not accept, such as the flag
// that the docs suggest for the warnings of duplicate libraries on macOS.
var appleLinkerFlags = []string{"-Wl,-no_warn_duplicate_libraries"}
// androidLDFlags returns the CGO_LDFLAGS of the go environment without
// the [appleLinkerFlags], for building for Android on macOS.
func androidLDFlags() string {
flags, err := exec.Output("go", "env", "CGO_LDFLAGS")
if err != nil {
return "-O2 -g" // the default
}
return withoutAppleFlags(flags)
}
// withoutAppleFlags returns the given linker flags without the
// [appleLinkerFlags].
func withoutAppleFlags(flags string) string {
return strings.Join(slices.DeleteFunc(strings.Fields(flags), func(f string) bool {
return slices.Contains(appleLinkerFlags, f)
}), " ")
}
func envInit(c *config.Config) (err error) {
// Setup the cross-compiler environments.
if ndkRoot, err := ndkRoot(c); err == nil {
androidEnv = make(map[string]map[string]string)
if c.Build.AndroidMinSDK < minAndroidSDK {
return fmt.Errorf("gomobile requires Android API level >= %d", minAndroidSDK)
}
for arch, toolchain := range ndk {
clang := toolchain.path(c, ndkRoot, "clang")
clangpp := toolchain.path(c, ndkRoot, "clang++")
tools := []string{clang, clangpp}
if runtime.GOOS == "windows" {
// Because of https://github.com/android-ndk/ndk/issues/920,
// we require r19c, not just r19b. Fortunately, the clang++.cmd
// script only exists in r19c.
tools = append(tools, clangpp+".cmd")
}
for _, tool := range tools {
_, err = os.Stat(tool)
if err != nil {
return fmt.Errorf("no compiler for %s was found in the NDK (tried %s). Make sure your NDK version is >= r19c. Use `sdkmanager --update` to update it", arch, tool)
}
}
androidEnv[arch] = map[string]string{
"GOOS": "android",
"GOARCH": arch,
"CC": clang,
"CXX": clangpp,
"CGO_ENABLED": "1",
// (ELF segments aligned for devices with 16 KB pages)
"CGO_LDFLAGS": androidLDFlags() + " -Wl,-z,max-page-size=16384",
}
if arch == "arm" {
androidEnv[arch]["GOARM"] = "7"
}
}
}
if !xCodeAvailable() {
return nil
}
appleNM = "nm"
appleEnv = make(map[string]map[string]string)
for _, platform := range applePlatforms {
for _, arch := range platformArchs(platform) {
var goos, sdk, clang, cflags string
var err error
switch platform {
case "ios":
goos = "ios"
sdk = "iphoneos"
clang, cflags, err = envClang(sdk)
cflags += " -mios-version-min=" + c.Build.IOSVersion
case "iossimulator":
goos = "ios"
sdk = "iphonesimulator"
clang, cflags, err = envClang(sdk)
cflags += " -mios-simulator-version-min=" + c.Build.IOSVersion
case "maccatalyst":
// Mac Catalyst is a subset of iOS APIs made available on macOS
// designed to ease porting apps developed for iPad to macOS.
// See https://developer.apple.com/mac-catalyst/.
// Because of this, when building a Go package targeting maccatalyst,
// GOOS=darwin (not ios). To bridge the gap and enable maccatalyst
// packages to be compiled, we also specify the "ios" build tag.
// To help discriminate between darwin, ios, macos, and maccatalyst
// targets, there is also a "maccatalyst" tag.
// Some additional context on this can be found here:
// https://stackoverflow.com/questions/12132933/preprocessor-macro-for-os-x-targets/49560690#49560690
goos = "darwin"
sdk = "macosx"
clang, cflags, err = envClang(sdk)
// TODO(ydnar): the following 3 lines MAY be needed to compile
// packages or apps for maccatalyst. Commenting them out now in case
// it turns out they are necessary. Currently none of the example
// apps will build for macos or maccatalyst because they have a
// GLKit dependency, which is deprecated on all Apple platforms, and
// broken on maccatalyst (GLKView isn’t available).
// sysroot := strings.SplitN(cflags, " ", 2)[1]
// cflags += " -isystem " + sysroot + "/System/iOSSupport/usr/include"
// cflags += " -iframework " + sysroot + "/System/iOSSupport/System/Library/Frameworks"
switch arch {
case "amd64":
cflags += " -target x86_64-apple-ios" + c.Build.IOSVersion + "-macabi"
case "arm64":
cflags += " -target arm64-apple-ios" + c.Build.IOSVersion + "-macabi"
}
case "macos":
goos = "darwin"
sdk = "macosx" // Note: the SDK is called "macosx", not "macos"
clang, cflags, err = envClang(sdk)
default:
panic(fmt.Errorf("unknown Apple target: %s/%s", platform, arch))
}
if err != nil {
return err
}
appleEnv[platform+"/"+arch] = map[string]string{
"GOOS": goos,
"GOARCH": arch,
"GOFLAGS": "-tags=" + strings.Join(platformTags(platform), ","),
"CC": clang,
"CXX": clang + "++",
"CGO_CFLAGS": cflags + " -arch " + archClang(arch),
"CGO_CXXFLAGS": cflags + " -arch " + archClang(arch),
"CGO_LDFLAGS": cflags + " -arch " + archClang(arch),
"CGO_ENABLED": "1",
"DARWIN_SDK": sdk,
}
}
}
return nil
}
// abi maps GOARCH values to Android abi strings.
// See https://developer.android.com/ndk/guides/abis
func abi(goarch string) string {
switch goarch {
case "arm":
return "armeabi-v7a"
case "arm64":
return "arm64-v8a"
case "386":
return "x86"
case "amd64":
return "x86_64"
default:
return ""
}
}
// checkNDKRoot returns nil if the NDK in `ndkRoot` supports the current configured
// API version and all the specified Android targets.
func checkNDKRoot(c *config.Config, ndkRoot string, targets []config.Platform) error {
platformsJSON, err := os.Open(filepath.Join(ndkRoot, "meta", "platforms.json"))
if err != nil {
return err
}
defer platformsJSON.Close()
decoder := json.NewDecoder(platformsJSON)
supportedVersions := struct {
Min int
Max int
}{}
if err := decoder.Decode(&supportedVersions); err != nil {
return err
}
if supportedVersions.Min > c.Build.AndroidMinSDK ||
supportedVersions.Max < c.Build.AndroidMinSDK {
return fmt.Errorf("unsupported API version %d (not in %d..%d)", c.Build.AndroidMinSDK, supportedVersions.Min, supportedVersions.Max)
}
abisJSON, err := os.Open(filepath.Join(ndkRoot, "meta", "abis.json"))
if err != nil {
return err
}
defer abisJSON.Close()
decoder = json.NewDecoder(abisJSON)
abis := make(map[string]struct{})
if err := decoder.Decode(&abis); err != nil {
return err
}
for _, target := range targets {
if !isAndroidPlatform(target.OS) {
continue
}
if _, found := abis[abi(target.Arch)]; !found {
return fmt.Errorf("ndk does not support %s", target.OS)
}
}
return nil
}
// compatibleNDKRoots searches the side-by-side NDK dirs for compatible SDKs.
func compatibleNDKRoots(c *config.Config, ndkForest string, targets []config.Platform) ([]string, error) {
ndkDirs, err := os.ReadDir(ndkForest)
if err != nil {
return nil, err
}
compatibleNDKRoots := []string{}
var lastErr error
for _, dirent := range ndkDirs {
ndkRoot := filepath.Join(ndkForest, dirent.Name())
lastErr = checkNDKRoot(c, ndkRoot, targets)
if lastErr == nil {
compatibleNDKRoots = append(compatibleNDKRoots, ndkRoot)
}
}
if len(compatibleNDKRoots) > 0 {
return compatibleNDKRoots, nil
}
return nil, lastErr
}
// ndkVersion returns the full version number of an installed copy of the NDK,
// or "" if it cannot be determined.
func ndkVersion(ndkRoot string) string {
properties, err := os.Open(filepath.Join(ndkRoot, "source.properties"))
if err != nil {
return ""
}
defer properties.Close()
// Parse the version number out of the .properties file.
// See https://en.wikipedia.org/wiki/.properties
scanner := bufio.NewScanner(properties)
for scanner.Scan() {
line := scanner.Text()
tokens := strings.SplitN(line, "=", 2)
if len(tokens) != 2 {
continue
}
if strings.TrimSpace(tokens[0]) == "Pkg.Revision" {
return strings.TrimSpace(tokens[1])
}
}
if err := scanner.Err(); err != nil {
logx.PrintlnWarn("error reading the NDK source.properties:", err)
}
return ""
}
// ndkRoot returns the root path of an installed NDK that supports all the
// specified Android targets. For details of NDK locations, see
// https://github.com/android/ndk-samples/wiki/Configure-NDK-Path
func ndkRoot(c *config.Config, targets ...config.Platform) (string, error) {
// Try the ANDROID_NDK_HOME variable. This approach is deprecated, but it
// has the highest priority because it represents an explicit user choice.
if ndkRoot := os.Getenv("ANDROID_NDK_HOME"); ndkRoot != "" {
if err := checkNDKRoot(c, ndkRoot, targets); err != nil {
return "", fmt.Errorf("ANDROID_NDK_HOME specifies %s, which is unusable: %w", ndkRoot, err)
}
return ndkRoot, nil
}
androidHome, err := sdkpath.AndroidHome()
if err != nil {
return "", fmt.Errorf("could not locate Android SDK: %w", err)
}
// Use the newest compatible NDK under the side-by-side path arrangement.
ndkForest := filepath.Join(androidHome, "ndk")
ndkRoots, sideBySideErr := compatibleNDKRoots(c, ndkForest, targets)
if len(ndkRoots) != 0 {
// Choose the latest version that supports the build configuration.
// NDKs whose version cannot be determined will be least preferred.
// In the event of a tie, the later ndkRoot will win.
maxVersion := ""
var selected string
for _, ndkRoot := range ndkRoots {
version := ndkVersion(ndkRoot)
if version >= maxVersion {
maxVersion = version
selected = ndkRoot
}
}
return selected, nil
}
// Try the deprecated NDK location.
ndkRoot := filepath.Join(androidHome, "ndk-bundle")
if legacyErr := checkNDKRoot(c, ndkRoot, targets); legacyErr != nil {
return "", fmt.Errorf("no usable NDK in %s: %w, %v", androidHome, sideBySideErr, legacyErr)
}
return ndkRoot, nil
}
func envClang(sdkName string) (clang, cflags string, err error) {
out, err := exec.Minor().Output("xcrun", "--sdk", sdkName, "--find", "clang")
if err != nil {
return "", "", fmt.Errorf("xcrun --find: %v\n%s", err, out)
}
clang = strings.TrimSpace(string(out))
out, err = exec.Minor().Output("xcrun", "--sdk", sdkName, "--show-sdk-path")
if err != nil {
return "", "", fmt.Errorf("xcrun --show-sdk-path: %v\n%s", err, out)
}
sdk := strings.TrimSpace(string(out))
return clang, "-isysroot " + sdk, nil
}
func archClang(goarch string) string {
switch goarch {
case "arm":
return "armv7"
case "arm64":
return "arm64"
case "386":
return "i386"
case "amd64":
return "x86_64"
default:
panic(fmt.Sprintf("unknown GOARCH: %q", goarch))
}
}
func archNDK() string {
if runtime.GOOS == "windows" && runtime.GOARCH == "386" {
return "windows"
}
var arch string
switch runtime.GOARCH {
case "386":
arch = "x86"
case "amd64":
arch = "x86_64"
case "arm64":
// Android NDK does not contain arm64 toolchains (until and
// including NDK 23), use use x86_64 instead. See:
// https://github.com/android/ndk/issues/1299
if runtime.GOOS == "darwin" {
arch = "x86_64"
break
}
if runtime.GOOS == "android" { // termux
return "linux-aarch64"
}
fallthrough
default:
panic("unsupported GOARCH: " + runtime.GOARCH)
}
return runtime.GOOS + "-" + arch
}
type ndkToolchain struct {
Arch string
ABI string
MinAPI int
ToolPrefix string
ClangPrefixVal string // ClangPrefix is taken by a method
}
func (tc *ndkToolchain) clangPrefix(c *config.Config) string {
if c.Build.AndroidMinSDK < tc.MinAPI {
return fmt.Sprintf("%s%d", tc.ClangPrefixVal, tc.MinAPI)
}
return fmt.Sprintf("%s%d", tc.ClangPrefixVal, c.Build.AndroidMinSDK)
}
func (tc *ndkToolchain) path(c *config.Config, ndkRoot, toolName string) string {
cmdFromPref := func(pref string) string {
return filepath.Join(ndkRoot, "toolchains", "llvm", "prebuilt", archNDK(), "bin", pref+"-"+toolName)
}
var cmd string
switch toolName {
case "clang", "clang++":
cmd = cmdFromPref(tc.clangPrefix(c))
default:
cmd = cmdFromPref(tc.ToolPrefix)
// Starting from NDK 23, GNU binutils are fully migrated to LLVM binutils.
// See https://android.googlesource.com/platform/ndk/+/master/docs/Roadmap.md#ndk-r23
if _, err := os.Stat(cmd); errors.Is(err, fs.ErrNotExist) {
cmd = cmdFromPref("llvm")
}
}
return cmd
}
type ndkConfig map[string]ndkToolchain // map: GOOS->androidConfig.
func (nc ndkConfig) toolchain(arch string) ndkToolchain {
tc, ok := nc[arch]
if !ok {
panic(`unsupported architecture: ` + arch)
}
return tc
}
var ndk = ndkConfig{
"arm": {
Arch: "arm",
ABI: "armeabi-v7a",
MinAPI: 16,
ToolPrefix: "arm-linux-androideabi",
ClangPrefixVal: "armv7a-linux-androideabi",
},
"arm64": {
Arch: "arm64",
ABI: "arm64-v8a",
MinAPI: 21,
ToolPrefix: "aarch64-linux-android",
ClangPrefixVal: "aarch64-linux-android",
},
"386": {
Arch: "x86",
ABI: "x86",
MinAPI: 16,
ToolPrefix: "i686-linux-android",
ClangPrefixVal: "i686-linux-android",
},
"amd64": {
Arch: "x86_64",
ABI: "x86_64",
MinAPI: 21,
ToolPrefix: "x86_64-linux-android",
ClangPrefixVal: "x86_64-linux-android",
},
}
func xCodeAvailable() bool {
err := exec.Run("xcrun", "xcodebuild", "-version")
return err == nil
}
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mobile
import (
"fmt"
"path/filepath"
"cogentcore.org/core/base/exec"
"cogentcore.org/core/cmd/config"
)
// Install installs the app named by the import path on the attached mobile device.
// It assumes that it has already been built.
//
// On Android, the 'adb' tool must be on the PATH.
func Install(c *config.Config) error {
if len(c.Build.Target) != 1 {
return fmt.Errorf("expected 1 target platform, but got %d (%v)", len(c.Build.Target), c.Build.Target)
}
t := c.Build.Target[0]
switch t.OS {
case "android":
return exec.Run(AndroidTool("adb"), "install", "-r", filepath.Join(c.Build.Output, c.Name+".apk"))
case "ios":
return exec.Major().SetBuffer(false).Run("ios-deploy", "-b", filepath.Join(c.Build.Output, c.Name+".app"))
case "iossimulator":
return RunSimulator(c)
default:
return fmt.Errorf("mobile.Install only supports target platforms android, ios and iossimulator, but got %q", t.OS)
}
}
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mobile
import (
"encoding/xml"
"errors"
"fmt"
"html/template"
)
type manifestXML struct {
Activity activityXML `xml:"application>activity"`
}
type activityXML struct {
Name string `xml:"name,attr"`
MetaData []metaDataXML `xml:"meta-data"`
}
type metaDataXML struct {
Name string `xml:"name,attr"`
Value string `xml:"value,attr"`
}
// manifestLibName parses the AndroidManifest.xml and finds the library
// name of the NativeActivity.
func manifestLibName(data []byte) (string, error) {
manifest := new(manifestXML)
if err := xml.Unmarshal(data, manifest); err != nil {
return "", err
}
if manifest.Activity.Name != "org.golang.app.GoNativeActivity" {
return "", fmt.Errorf("can only build an .apk for GoNativeActivity, not %q", manifest.Activity.Name)
}
libName := ""
for _, md := range manifest.Activity.MetaData {
if md.Name == "android.app.lib_name" {
libName = md.Value
break
}
}
if libName == "" {
return "", errors.New("AndroidManifest.xml missing meta-data android.app.lib_name")
}
return libName, nil
}
type manifestTmplData struct {
JavaPkgPath string
Name string
LibName string
}
var manifestTmpl = template.Must(template.New("manifest").Parse(`
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="{{.JavaPkgPath}}"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<application android:label="{{.Name}}" android:debuggable="true">
<activity android:name="org.golang.app.GoNativeActivity"
android:label="{{.Name}}"
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|keyboard|keyboardHidden|navigation|uiMode">
<meta-data android:name="android.app.lib_name" android:value="{{.LibName}}" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="org.golang.app.NotifyReceiver" android:exported="false" />
</application>
</manifest>`))
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package sdkpath provides functions for locating the Android SDK.
// These functions respect the ANDROID_HOME environment variable, and
// otherwise use the default SDK location.
package sdkpath
import (
"fmt"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
)
// AndroidHome returns the absolute path of the selected Android SDK,
// if one can be found.
func AndroidHome() (string, error) {
androidHome, err := AndroidHomePath()
if err != nil {
return "", err
}
if info, err := os.Stat(androidHome); err != nil {
return "", fmt.Errorf("%w; Android SDK was not found at %s", err, androidHome)
} else if !info.IsDir() {
return "", fmt.Errorf("%s is not a directory", androidHome)
}
return androidHome, nil
}
// AndroidHomePath returns the absolute path of the selected Android SDK,
// whether or not it exists: ANDROID_HOME, or else the default location of
// the SDK for the platform (that of Android Studio).
func AndroidHomePath() (string, error) {
if androidHome := os.Getenv("ANDROID_HOME"); androidHome != "" {
return androidHome, nil
}
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
switch runtime.GOOS {
case "windows":
// See https://android.googlesource.com/platform/tools/adt/idea/+/85b4bfb7a10ad858a30ffa4003085b54f9424087/native/installer/win/setup_android_studio.nsi#100
return filepath.Join(home, "AppData", "Local", "Android", "sdk"), nil
case "darwin":
// See https://android.googlesource.com/platform/tools/asuite/+/67e0cd9604379e9663df57f16a318d76423c0aa8/aidegen/lib/ide_util.py#88
return filepath.Join(home, "Library", "Android", "sdk"), nil
default: // Linux, BSDs, etc.
// See LINUX_ANDROID_SDK_PATH in ide_util.py above.
return filepath.Join(home, "Android", "Sdk"), nil
}
}
// AndroidAPIPath returns an android SDK platform directory within the configured SDK.
// If there are multiple platforms that satisfy the minimum version requirement,
// AndroidAPIPath returns the latest one among them.
func AndroidAPIPath(api int) (string, error) {
sdk, err := AndroidHome()
if err != nil {
return "", err
}
sdkDir, err := os.Open(filepath.Join(sdk, "platforms"))
if err != nil {
return "", fmt.Errorf("failed to find android SDK platform: %w", err)
}
defer sdkDir.Close()
fis, err := sdkDir.Readdir(-1)
if err != nil {
return "", fmt.Errorf("failed to find android SDK platform (API level: %d): %w", api, err)
}
var apiPath string
var apiVer int
for _, fi := range fis {
name := fi.Name()
if !strings.HasPrefix(name, "android-") {
continue
}
n, err := strconv.Atoi(name[len("android-"):])
if err != nil || n < api {
continue
}
p := filepath.Join(sdkDir.Name(), name)
_, err = os.Stat(filepath.Join(p, "android.jar"))
if err == nil && apiVer < n {
apiPath = p
apiVer = n
}
}
if apiVer == 0 {
return "", fmt.Errorf("failed to find android SDK platform (API level: %d) in %s",
api, sdkDir.Name())
}
return apiPath, nil
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mobile
import (
"bytes"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/binary"
"errors"
)
// APK Signature Scheme v2 (https://source.android.com/docs/security/features/apksigning/v2),
// which Android requires for apps that target SDK version 30 or later (in
// addition to the v1 JAR signature of [writer.Close], for older versions
// of Android): an APK Signing Block, between the files of the APK (a zip
// file) and its central directory, with a signature of the digest of the
// rest of the APK.
const (
// apkSigV2BlockID is the ID of the v2 signature in the signing block.
apkSigV2BlockID = 0x7109871a
// apkSigRSAPKCS1SHA256 is the ID of the signature algorithm:
// RSASSA-PKCS1-v1_5 with SHA2-256.
apkSigRSAPKCS1SHA256 = 0x0103
// apkSigChunkSize is the size of the chunks of the digest.
apkSigChunkSize = 1 << 20
// apkSigBlockMagic ends the signing block.
apkSigBlockMagic = "APK Sig Block 42"
)
// signV2 returns the given APK (a zip file, signed with v1) with a v2
// signature of the given key and certificate (DER), in an APK Signing
// Block inserted before its central directory.
func signV2(apk []byte, priv *rsa.PrivateKey, cert []byte) ([]byte, error) {
eocd := findEOCD(apk)
if eocd < 0 {
return nil, errors.New("apk: no end of central directory")
}
cdOffset := int(binary.LittleEndian.Uint32(apk[eocd+16:]))
if cdOffset > eocd {
return nil, errors.New("apk: invalid central directory offset")
}
entries, cd, end := apk[:cdOffset], apk[cdOffset:eocd], apk[eocd:]
// the digest of the entries, the central directory, and the end of
// central directory, whose offset of the central directory is that of
// the signing block, which it is here, before it is inserted
digest := apkV2Digest(entries, cd, end)
// signed data: digests, certificates, additional attributes (none)
signedData := lenPrefixed(concat(
lenPrefixed(lenPrefixed(concat(u32(apkSigRSAPKCS1SHA256), lenPrefixed(digest)))),
lenPrefixed(lenPrefixed(cert)),
lenPrefixed(nil),
))
sd := signedData[4:] // (without its length, as it is signed)
h := sha256.Sum256(sd)
sig, err := rsa.SignPKCS1v15(rand.Reader, priv, crypto.SHA256, h[:])
if err != nil {
return nil, err
}
pub, err := x509.MarshalPKIXPublicKey(&priv.PublicKey)
if err != nil {
return nil, err
}
signer := lenPrefixed(concat(
signedData,
lenPrefixed(lenPrefixed(concat(u32(apkSigRSAPKCS1SHA256), lenPrefixed(sig)))),
lenPrefixed(pub),
))
value := lenPrefixed(signer) // the sequence of signers
// the signing block: its size, the ID-value pair, its size, and magic
pair := concat(u64(uint64(4+len(value))), u32(apkSigV2BlockID), value)
size := uint64(len(pair) + 8 + len(apkSigBlockMagic))
block := concat(u64(size), pair, u64(size), []byte(apkSigBlockMagic))
// the end of central directory with the new offset of the central
// directory, after the signing block
newEnd := bytes.Clone(end)
binary.LittleEndian.PutUint32(newEnd[16:], uint32(cdOffset+len(block)))
return concat(entries, block, cd, newEnd), nil
}
// apkV2Digest returns the SHA-256 digest of the given sections of the APK
// for its v2 signature: of the digests of their chunks.
func apkV2Digest(sections ...[]byte) []byte {
var chunks [][]byte
for _, s := range sections {
for len(s) > 0 {
n := min(len(s), apkSigChunkSize)
chunks = append(chunks, s[:n])
s = s[n:]
}
}
top := sha256.New()
top.Write([]byte{0x5a})
top.Write(u32(uint32(len(chunks))))
for _, c := range chunks {
h := sha256.New()
h.Write([]byte{0xa5})
h.Write(u32(uint32(len(c))))
h.Write(c)
top.Write(h.Sum(nil))
}
return top.Sum(nil)
}
// findEOCD returns the offset of the end of central directory record of
// the given zip file, or -1 if there is none.
func findEOCD(b []byte) int {
const eocdLen = 22
for i := len(b) - eocdLen; i >= 0 && i >= len(b)-eocdLen-0xffff; i-- {
if binary.LittleEndian.Uint32(b[i:]) == 0x06054b50 &&
int(binary.LittleEndian.Uint16(b[i+20:])) == len(b)-i-eocdLen {
return i
}
}
return -1
}
// lenPrefixed returns the given bytes with their length before them
// (a little-endian uint32).
func lenPrefixed(b []byte) []byte {
return concat(u32(uint32(len(b))), b)
}
func u32(v uint32) []byte { return binary.LittleEndian.AppendUint32(nil, v) }
func u64(v uint64) []byte { return binary.LittleEndian.AppendUint64(nil, v) }
func concat(bs ...[]byte) []byte { return bytes.Join(bs, nil) }
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mobile
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"cogentcore.org/core/base/exec"
"cogentcore.org/core/cmd/config"
)
// webgpuLibsIOS is the Go module of the libraries of WebGPU for iOS,
// which has those for the iOS simulator on arm64, selected with the
// iossimulator build tag, since webgpu v1.38.0.
const webgpuLibsIOS = "github.com/oliverbestmann/webgpu/libs-ios"
// checkSimulatorWGPU returns an error if the libraries of WebGPU for iOS
// used by the app in the current directory do not have the one for the
// iOS simulator on the given architecture (amd64 is always there).
func checkSimulatorWGPU(arch string) error {
if arch != "arm64" {
return nil
}
dir, err := exec.Output("go", "list", "-m", "-f", "{{.Dir}}", webgpuLibsIOS)
dir = strings.TrimSpace(dir)
if err != nil || dir == "" {
return nil // (not used, or not downloaded yet: the build reports it)
}
if _, err := os.Stat(filepath.Join(dir, "arm64-simulator")); err != nil {
return fmt.Errorf("the WebGPU libraries of the app (%s) have no library for the iOS simulator on arm64: update github.com/oliverbestmann/webgpu to v1.38.0 or later", webgpuLibsIOS)
}
return nil
}
// simDevice is an iOS simulator device, as listed by simctl.
type simDevice struct {
UDID string `json:"udid"`
Name string `json:"name"`
State string `json:"state"`
IsAvailable bool `json:"isAvailable"`
}
// simulatorDevice returns the UDID of the iOS simulator device to run the
// app on: a booted one, or else the last available iPhone of the newest
// runtime, which is booted, with the Simulator app opened to show it.
func simulatorDevice() (string, error) {
out, err := exec.Output("xcrun", "simctl", "list", "devices", "available", "-j")
if err != nil {
return "", err
}
var list struct {
Devices map[string][]simDevice `json:"devices"`
}
if err := json.Unmarshal([]byte(out), &list); err != nil {
return "", err
}
var runtimes []string
for rt, devs := range list.Devices {
for _, d := range devs {
if d.State == "Booted" {
return d.UDID, nil
}
}
if strings.Contains(rt, ".iOS-") {
runtimes = append(runtimes, rt)
}
}
best, bestRT := "", ""
for _, rt := range runtimes {
for _, d := range list.Devices[rt] {
if strings.HasPrefix(d.Name, "iPhone") && runtimeNewer(rt, bestRT) {
best, bestRT = d.UDID, rt
}
}
}
if best == "" {
return "", errors.New("no available iPhone simulator; add one in Xcode")
}
if err := exec.Run("xcrun", "simctl", "boot", best); err != nil {
return "", err
}
exec.Run("open", "-a", "Simulator")
return best, nil
}
// runtimeNewer returns whether the simulator runtime identifier a (as
// com.apple.CoreSimulator.SimRuntime.iOS-26-2) is a newer version than b,
// which is newer than none ("").
func runtimeNewer(a, b string) bool {
if b == "" {
return true
}
va, vb := runtimeVersion(a), runtimeVersion(b)
for i := range min(len(va), len(vb)) {
if va[i] != vb[i] {
return va[i] > vb[i]
}
}
return len(va) > len(vb)
}
// runtimeVersion returns the numbers of the version of the given
// simulator runtime identifier.
func runtimeVersion(rt string) []int {
_, v, _ := strings.Cut(rt, ".iOS-")
var nums []int
for s := range strings.SplitSeq(v, "-") {
var n int
fmt.Sscan(s, &n)
nums = append(nums, n)
}
return nums
}
// RunSimulator installs the app, which has been built for the iOS
// simulator, on a simulator device (see [simulatorDevice]) and launches
// it, showing its output if debugging.
func RunSimulator(c *config.Config) error {
dev, err := simulatorDevice()
if err != nil {
return err
}
if err := exec.Run("xcrun", "simctl", "install", dev, filepath.Join(c.Build.Output, c.Name+".app")); err != nil {
return fmt.Errorf("error installing app: %w", err)
}
args := []string{"simctl", "launch", "--terminate-running-process"}
if c.Build.Debug {
args = append(args, "--console-pty")
}
args = append(args, dev, c.ID)
return exec.Verbose().SetBuffer(false).Run("xcrun", args...)
}
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mobile
import (
"os"
"runtime"
"strings"
"cogentcore.org/core/base/exec"
"cogentcore.org/core/cmd/config"
"golang.org/x/tools/go/packages"
)
var (
goos = runtime.GOOS
goarch = runtime.GOARCH
)
func packagesConfig(t *config.Platform) *packages.Config {
config := &packages.Config{}
// Add CGO_ENABLED=1 explicitly since Cgo is disabled when GOOS is different from host OS.
config.Env = append(os.Environ(), "GOARCH="+t.Arch, "GOOS="+platformOS(t.OS), "CGO_ENABLED=1")
tags := platformTags(t.OS)
if len(tags) > 0 {
config.BuildFlags = []string{"-tags=" + strings.Join(tags, ",")}
}
return config
}
func goEnv(name string) string {
if val := os.Getenv(name); val != "" {
return val
}
val, err := exec.Minor().Output("go", "env", name)
if err != nil {
panic(err) // the Go tool was tested to work earlier
}
return strings.TrimSpace(string(val))
}
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mobile
// TODO: do we need this writer stuff?
// APK is the archival format used for Android apps. It is a ZIP archive with
// three extra files:
//
// META-INF/MANIFEST.MF
// META-INF/CERT.SF
// META-INF/CERT.RSA
//
// The MANIFEST.MF comes from the Java JAR archive format. It is a list of
// files included in the archive along with a SHA1 hash, for example:
//
// Name: lib/armeabi/libbasic.so
// SHA1-Digest: ntLSc1eLCS2Tq1oB4Vw6jvkranw=
//
// For debugging, the equivalent SHA1-Digest can be generated with OpenSSL:
//
// cat lib/armeabi/libbasic.so | openssl sha1 -binary | openssl base64
//
// CERT.SF is a similar manifest. It begins with a SHA1 digest of the entire
// manifest file:
//
// Signature-Version: 1.0
// Created-By: 1.0 (Android)
// SHA1-Digest-Manifest: aJw+u+10C3Enbg8XRCN6jepluYA=
//
// Then for each entry in the manifest it has a SHA1 digest of the manfiest's
// hash combined with the file name:
//
// Name: lib/armeabi/libbasic.so
// SHA1-Digest: Q7NAS6uzrJr6WjePXSGT+vvmdiw=
//
// This can also be generated with openssl:
//
// echo -en "Name: lib/armeabi/libbasic.so\r\nSHA1-Digest: ntLSc1eLCS2Tq1oB4Vw6jvkranw=\r\n\r\n" | openssl sha1 -binary | openssl base64
//
// Note the \r\n line breaks.
//
// CERT.RSA is an RSA signature block made of CERT.SF. Verify it with:
//
// openssl smime -verify -in CERT.RSA -inform DER -content CERT.SF cert.pem
//
// The APK format imposes two extra restrictions on the ZIP format. First,
// it is uncompressed. Second, each contained file is 4-byte aligned. This
// allows the Android OS to mmap contents without unpacking the archive.
// Note: to make life a little harder, Android Studio stores the RSA key used
// for signing in an Oracle Java proprietary keystore format, JKS. For example,
// the generated debug key is in ~/.android/debug.keystore, and can be
// extracted using the JDK's keytool utility:
//
// keytool -importkeystore -srckeystore ~/.android/debug.keystore -destkeystore ~/.android/debug.p12 -deststoretype PKCS12
//
// Once in standard PKCS12, the key can be converted to PEM for use in the
// Go crypto packages:
//
// openssl pkcs12 -in ~/.android/debug.p12 -nocerts -nodes -out ~/.android/debug.pem
//
// Fortunately for debug builds, all that matters is that the APK is signed.
// The choice of key is unimportant, so we can generate one for normal builds.
// For production builds, we can ask users to provide a PEM file.
import (
"archive/zip"
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
"encoding/base64"
"fmt"
"hash"
"io"
"strings"
)
// newWriter returns a new Writer writing an APK file to w.
// The APK will be signed with key, with v1 (JAR) and v2 signatures
// (see [signV2]), so it is written to w on [writer.Close].
func newWriter(w io.Writer, priv *rsa.PrivateKey) *writer {
apkw := &writer{priv: priv, out: w}
apkw.w = zip.NewWriter(&countWriter{apkw: apkw, w: &apkw.buf})
return apkw
}
// writer implements an APK file writer.
type writer struct {
offset int
entries int // the number of files created
buf bytes.Buffer // the APK, before its v2 signature
out io.Writer // the signed APK
w *zip.Writer
priv *rsa.PrivateKey
manifest []manifestEntry
cur *fileWriter
}
// Create adds a file to the APK archive using the provided name.
//
// The name must be a relative path. The file's contents must be written to
// the returned io.Writer before the next call to Create or Close.
func (w *writer) Create(name string) (io.Writer, error) {
if err := w.clearCur(); err != nil {
return nil, fmt.Errorf("apk: Create(%s): %v", name, err)
}
res, err := w.create(name)
if err != nil {
return nil, fmt.Errorf("apk: Create(%s): %v", name, err)
}
return res, nil
}
func (w *writer) create(name string) (io.Writer, error) {
// Align start of file contents by using Extra as padding: to 4 bytes,
// and native libraries, which are stored uncompressed, to 16 KB, for
// devices with 16 KB pages, which map them directly from the APK.
if err := w.w.Flush(); err != nil { // for exact offset
return nil, err
}
const fileHeaderLen = 30 // + filename + extra
start := w.offset + fileHeaderLen + len(name)
if w.entries > 0 {
// the data descriptor of the previous file, which the zip writer
// writes when this one is created
const dataDescriptorLen = 16
start += dataDescriptorLen
}
w.entries++
align := 4
if strings.HasSuffix(name, ".so") {
align = 16384
}
extra := (-start) & (align - 1)
zipfw, err := w.w.CreateHeader(&zip.FileHeader{
Name: name,
Extra: make([]byte, extra),
})
if err != nil {
return nil, err
}
w.cur = &fileWriter{
name: name,
w: zipfw,
sha1: sha1.New(),
}
return w.cur, nil
}
// Close finishes writing the APK. This includes writing the manifest and
// signing the archive, and writing the ZIP central directory.
//
// It does not close the underlying writer.
func (w *writer) Close() error {
if err := w.clearCur(); err != nil {
return fmt.Errorf("apk: %v", err)
}
hasDex := false
for _, entry := range w.manifest {
if entry.name == "classes.dex" {
hasDex = true
break
}
}
manifest := new(bytes.Buffer)
if hasDex {
fmt.Fprint(manifest, manifestDexHeader)
} else {
fmt.Fprint(manifest, manifestHeader)
}
certBody := new(bytes.Buffer)
for _, entry := range w.manifest {
n := entry.name
h := base64.StdEncoding.EncodeToString(entry.sha1.Sum(nil))
fmt.Fprintf(manifest, "Name: %s\nSHA1-Digest: %s\n\n", n, h)
cHash := sha1.New()
fmt.Fprintf(cHash, "Name: %s\r\nSHA1-Digest: %s\r\n\r\n", n, h)
ch := base64.StdEncoding.EncodeToString(cHash.Sum(nil))
fmt.Fprintf(certBody, "Name: %s\nSHA1-Digest: %s\n\n", n, ch)
}
mHash := sha1.New()
mHash.Write(manifest.Bytes())
cert := new(bytes.Buffer)
fmt.Fprint(cert, certHeader)
fmt.Fprintf(cert, "SHA1-Digest-Manifest: %s\n\n", base64.StdEncoding.EncodeToString(mHash.Sum(nil)))
cert.Write(certBody.Bytes())
mw, err := w.Create("META-INF/MANIFEST.MF")
if err != nil {
return err
}
if _, err := mw.Write(manifest.Bytes()); err != nil {
return err
}
cw, err := w.Create("META-INF/CERT.SF")
if err != nil {
return err
}
if _, err := cw.Write(cert.Bytes()); err != nil {
return err
}
certDER, err := apkCertificate(rand.Reader, w.priv)
if err != nil {
return fmt.Errorf("apk: %v", err)
}
rsa, err := signPKCS7Cert(rand.Reader, w.priv, certDER, cert.Bytes())
if err != nil {
return fmt.Errorf("apk: %v", err)
}
rw, err := w.Create("META-INF/CERT.RSA")
if err != nil {
return err
}
if _, err := rw.Write(rsa); err != nil {
return err
}
if err := w.w.Close(); err != nil {
return err
}
signed, err := signV2(w.buf.Bytes(), w.priv, certDER)
if err != nil {
return err
}
_, err = w.out.Write(signed)
return err
}
const manifestHeader = `Manifest-Version: 1.0
Created-By: 1.0 (Go)
`
const manifestDexHeader = `Manifest-Version: 1.0
Dex-Location: classes.dex
Created-By: 1.0 (Go)
`
// certHeader is the header of the v1 signature, which says that the APK
// also has a v2 signature (see [signV2]), so that it is not accepted
// without it on the versions of Android that verify it.
const certHeader = `Signature-Version: 1.0
Created-By: 1.0 (Go)
X-Android-APK-Signed: 2
`
func (w *writer) clearCur() error {
if w.cur == nil {
return nil
}
w.manifest = append(w.manifest, manifestEntry{
name: w.cur.name,
sha1: w.cur.sha1,
})
w.cur.closed = true
w.cur = nil
return nil
}
type manifestEntry struct {
name string
sha1 hash.Hash
}
type countWriter struct {
apkw *writer
w io.Writer
}
func (c *countWriter) Write(p []byte) (n int, err error) {
n, err = c.w.Write(p)
c.apkw.offset += n
return n, err
}
type fileWriter struct {
name string
w io.Writer
sha1 hash.Hash
closed bool
}
func (w *fileWriter) Write(p []byte) (n int, err error) {
if w.closed {
return 0, fmt.Errorf("apk: write to closed file %q", w.name)
}
w.sha1.Write(p)
n, err = w.w.Write(p)
if err != nil {
err = fmt.Errorf("apk: %v", err)
}
return n, err
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cmd
import (
"fmt"
"slices"
"strings"
"cogentcore.org/core/base/fileinfo"
)
// openTypes returns the types of files of the given [config.Config.Opens]:
// categories of files or known types of files, as in [fileinfo], whose
// names are matched regardless of case, as enums do.
func openTypes(opens []string) ([]fileinfo.MimeType, error) {
var cats []fileinfo.Categories
var knowns []fileinfo.Known
for _, op := range opens {
var cat fileinfo.Categories
if cat.SetString(op) == nil && cat != fileinfo.UnknownCategory {
cats = append(cats, cat)
continue
}
kn, err := fileinfo.KnownByName(op)
if err != nil || kn == fileinfo.Unknown {
return nil, fmt.Errorf("opens: %q is not a category or a known type of file", op)
}
knowns = append(knowns, kn)
}
var mts []fileinfo.MimeType
for _, mt := range fileinfo.StandardMimes {
if len(mt.Exts) == 0 || (!slices.Contains(cats, mt.Cat) && (mt.Known == fileinfo.Unknown || !slices.Contains(knowns, mt.Known))) {
continue
}
if slices.ContainsFunc(mts, func(m fileinfo.MimeType) bool { return m.Mime == mt.Mime }) {
continue
}
mts = append(mts, mt)
}
return mts, nil
}
// typeName returns the name of the given type of files.
func typeName(mt fileinfo.MimeType) string {
if mt.Known != fileinfo.Unknown {
return mt.Known.String()
}
return mt.Mime
}
// macTypes are the identifiers of the types of files (UTIs) that macOS has
// for the MIME types, for which the app declares that it opens those types,
// as the other types are matched by the extensions of their files.
var macTypes = map[string]string{
"text/plain": "public.plain-text",
"text/markdown": "net.daringfireball.markdown",
"text/html": "public.html",
"text/css": "public.css",
"text/csv": "public.comma-separated-values-text",
"text/tab-separated-values": "public.tab-separated-values-text",
"application/json": "public.json",
"application/xml": "public.xml",
"application/yaml": "public.yaml",
"application/javascript": "com.netscape.javascript-source",
"text/x-csrc": "public.c-source",
"text/x-sh": "public.shell-script",
"text/x-csh": "public.csh-script",
"text/x-python": "public.python-script",
"text/x-perl": "public.perl-script",
"text/x-php": "public.php-script",
"text/x-ruby": "public.ruby-script",
"text/x-java": "com.sun.java-source",
"text/x-diff": "public.patch-file",
}
// macDocType is a type of files that a macOS app opens, in its
// CFBundleDocumentTypes: with the identifier of its type, if macOS has
// one, or else the extensions of its files.
type macDocType struct {
Name string
UTI string
Extensions []string
}
// macDocTypes returns the types of files for the CFBundleDocumentTypes
// of a macOS app that opens the given types.
func macDocTypes(mts []fileinfo.MimeType) []macDocType {
var dts []macDocType
for _, mt := range mts {
dt := macDocType{Name: typeName(mt), UTI: macTypes[mt.Mime]}
if dt.UTI == "" {
for _, ext := range mt.Exts {
ext = strings.TrimPrefix(ext, ".")
if !slices.Contains(dt.Extensions, strings.ToLower(ext)) {
dt.Extensions = append(dt.Extensions, strings.ToLower(ext))
}
}
}
dts = append(dts, dt)
}
return dts
}
// mimeTypeList returns the MimeType value of a Linux desktop entry
// that opens the given types.
func mimeTypeList(mts []fileinfo.MimeType) string {
var b strings.Builder
for _, mt := range mts {
b.WriteString(mt.Mime)
b.WriteString(";")
}
return b.String()
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cmd
import (
_ "embed"
"os"
"path/filepath"
"strings"
"text/template"
"cogentcore.org/core/base/exec"
"cogentcore.org/core/base/iox/imagex"
"cogentcore.org/core/base/strcase"
"cogentcore.org/core/cmd/config"
"cogentcore.org/core/cmd/rendericon"
"github.com/jackmordaunt/icns/v2"
)
// Pack builds and packages the app for the target platform.
// For android, ios, and web, it is equivalent to build.
func Pack(c *config.Config) error { //types:add
err := Build(c)
if err != nil {
return err
}
for _, platform := range c.Build.Target {
switch platform.OS {
case "android", "ios", "wasm", "js": // build already packages
continue
case "linux":
err := packLinux(c)
if err != nil {
return err
}
case "darwin":
err := packDarwin(c)
if err != nil {
return err
}
case "windows":
err := packWindows(c)
if err != nil {
return err
}
}
}
return nil
}
// packLinux packages the app for Linux by generating a .deb file.
func packLinux(c *config.Config) error {
// based on https://ubuntuforums.org/showthread.php?t=910717
anm := strcase.ToKebab(c.Name)
vnm := strings.TrimPrefix(c.Version, "v")
avnm := anm + "_" + vnm
bpath := c.Build.Output
apath := filepath.Join(bpath, avnm)
ulbpath := filepath.Join(apath, "usr", "local", "bin")
usipath := filepath.Join(apath, "usr", "share", "icons", "hicolor")
usapath := filepath.Join(apath, "usr", "share", "applications")
dpath := filepath.Join(apath, "DEBIAN")
err := os.MkdirAll(ulbpath, 0777)
if err != nil {
return err
}
err = exec.Run("cp", "-p", filepath.Base(c.Build.Output), filepath.Join(ulbpath, anm))
if err != nil {
return err
}
// see https://martin.hoppenheit.info/blog/2016/where-to-put-application-icons-on-linux/
// TODO(kai): consider rendering more icon sizes and/or an XPM icon
ic, err := rendericon.Render(48)
if err != nil {
return err
}
i48path := filepath.Join(usipath, "48x48", "apps")
err = os.MkdirAll(i48path, 0777)
if err != nil {
return err
}
err = imagex.Save(ic, filepath.Join(i48path, anm+".png"))
if err != nil {
return err
}
iscpath := filepath.Join(usipath, "scalable", "apps")
err = os.MkdirAll(iscpath, 0777)
if err != nil {
return err
}
err = exec.Run("cp", "icon.svg", filepath.Join(iscpath, anm+".svg"))
if err != nil {
return err
}
// we need a description
if c.About == "" {
c.About = c.Name
}
err = os.MkdirAll(usapath, 0777)
if err != nil {
return err
}
fapp, err := os.Create(filepath.Join(usapath, anm+".desktop"))
if err != nil {
return err
}
defer fapp.Close()
dfd := &desktopFileData{
Name: c.Name,
Desc: c.About,
Exec: anm,
}
mts, err := openTypes(c.Opens)
if err != nil {
return err
}
dfd.MimeTypes = mimeTypeList(mts)
err = desktopFileTmpl.Execute(fapp, dfd)
if err != nil {
return err
}
err = os.MkdirAll(dpath, 0777)
if err != nil {
return err
}
fctrl, err := os.Create(filepath.Join(dpath, "control"))
if err != nil {
return err
}
defer fctrl.Close()
dcd := &debianControlData{
Name: anm,
Version: vnm,
Desc: c.About,
}
err = debianControlTmpl.Execute(fctrl, dcd)
if err != nil {
return err
}
return exec.Run("dpkg-deb", "--build", apath)
}
// desktopFileData is the data passed to [desktopFileTmpl]
type desktopFileData struct {
Name string
Desc string
Exec string
// MimeTypes are the MIME types of the files that the app opens
// (see [config.Config.Opens]), as a MimeType value.
MimeTypes string
}
// TODO(kai): project website
// desktopFileTmpl is the template for the Linux .desktop file
var desktopFileTmpl = template.Must(template.New("desktopFileTmpl").Parse(
`[Desktop Entry]
Type=Application
Version=1.0
Name={{.Name}}
Comment={{.Desc}}
Exec={{.Exec}}{{if .MimeTypes}} %F{{end}}
Icon={{.Exec}}
Terminal=false
{{- if .MimeTypes}}
MimeType={{.MimeTypes}}
{{- end}}
`))
// debianControlData is the data passed to [debianControlTmpl]
type debianControlData struct {
Name string
Version string
Desc string
}
// TODO(kai): architecture, maintainer, dependencies
// debianControlTmpl is the template for the Linux DEBIAN/control file
var debianControlTmpl = template.Must(template.New("debianControlTmpl").Parse(
`Package: {{.Name}}
Version: {{.Version}}
Section: base
Priority: optional
Architecture: all
Maintainer: Your Name <you@email.com>
Description: {{.Desc}}
`))
// packDarwin packages the app for macOS by generating a .app and .dmg file.
func packDarwin(c *config.Config) error {
// based on https://github.com/machinebox/appify
anm := c.Name + ".app"
bpath := c.Build.Output
apath := filepath.Join(bpath, anm)
cpath := filepath.Join(apath, "Contents")
mpath := filepath.Join(cpath, "MacOS")
rpath := filepath.Join(cpath, "Resources")
err := os.MkdirAll(mpath, 0777)
if err != nil {
return err
}
err = os.MkdirAll(rpath, 0777)
if err != nil {
return err
}
err = exec.Run("cp", "-p", filepath.Base(c.Build.Output), filepath.Join(mpath, anm))
if err != nil {
return err
}
err = exec.Run("chmod", "+x", mpath)
if err != nil {
return err
}
inm := filepath.Join(rpath, "icon.icns")
fdsi, err := os.Create(inm)
if err != nil {
return err
}
defer fdsi.Close()
// 1024x1024 is the largest icon size on macOS
sic, err := rendericon.Render(1024)
if err != nil {
return err
}
err = icns.Encode(fdsi, sic)
if err != nil {
return err
}
fplist, err := os.Create(filepath.Join(cpath, "Info.plist"))
if err != nil {
return err
}
defer fplist.Close()
ipd := &infoPlistData{
Name: c.Name,
Executable: filepath.Join("MacOS", anm),
Identifier: c.ID,
Version: c.Version,
InfoString: c.About,
ShortVersionString: c.Version,
IconFile: filepath.Join("Contents", "Resources", "icon.icns"),
}
mts, err := openTypes(c.Opens)
if err != nil {
return err
}
ipd.DocTypes = macDocTypes(mts)
err = infoPlistTmpl.Execute(fplist, ipd)
if err != nil {
return err
}
if !c.Pack.DMG {
return nil
}
// install dmgbuild if we don't already have it
if _, err := exec.LookPath("dmgbuild"); err != nil {
err = exec.Verbose().SetBuffer(false).Run("pip", "install", "dmgbuild")
if err != nil {
return err
}
}
dmgsnm := filepath.Join(bpath, ".tempDmgBuildSettings.py")
fdmg, err := os.Create(dmgsnm)
if err != nil {
return err
}
defer fdmg.Close()
dmgbd := &dmgBuildData{
AppPath: apath,
AppName: anm,
IconPath: inm,
}
err = dmgBuildTmpl.Execute(fdmg, dmgbd)
if err != nil {
return err
}
err = exec.Run("dmgbuild",
"-s", dmgsnm,
c.Name, filepath.Join(bpath, c.Name+".dmg"))
if err != nil {
return err
}
return os.Remove(dmgsnm)
}
// infoPlistData is the data passed to [infoPlistTmpl]
type infoPlistData struct {
Name string
Executable string
Identifier string
Version string
InfoString string
ShortVersionString string
IconFile string
// DocTypes are the types of files that the app opens (see [config.Config.Opens]),
// with the rank Alternate, so that it is not their default app.
DocTypes []macDocType
}
// infoPlistTmpl is the template for the macOS .app Info.plist
var infoPlistTmpl = template.Must(template.New("infoPlistTmpl").Parse(
`<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>{{ .Name }}</string>
<key>CFBundleExecutable</key>
<string>{{ .Executable }}</string>
<key>CFBundleIdentifier</key>
<string>{{ .Identifier }}</string>
<key>CFBundleVersion</key>
<string>{{ .Version }}</string>
<key>CFBundleGetInfoString</key>
<string>{{ .InfoString }}</string>
<key>CFBundleShortVersionString</key>
<string>{{ .ShortVersionString }}</string>
<key>CFBundleIconFile</key>
<string>{{ .IconFile }}</string>
{{- if .DocTypes }}
<key>CFBundleDocumentTypes</key>
<array>
{{- range .DocTypes }}
<dict>
<key>CFBundleTypeName</key>
<string>{{ .Name }}</string>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>LSHandlerRank</key>
<string>Alternate</string>
{{- if .UTI }}
<key>LSItemContentTypes</key>
<array>
<string>{{ .UTI }}</string>
</array>
{{- else }}
<key>CFBundleTypeExtensions</key>
<array>
{{- range .Extensions }}
<string>{{ . }}</string>
{{- end }}
</array>
{{- end }}
</dict>
{{- end }}
</array>
{{- end }}
</dict>
</plist>
`))
// dmgBuildData is the data passed to [dmgBuildTmpl]
type dmgBuildData struct {
AppPath string
AppName string
IconPath string
}
// dmgBuildTmpl is the template for the dmgbuild python settings file
var dmgBuildTmpl = template.Must(template.New("dmgBuildTmpl").Parse(
`files = ['{{.AppPath}}']
symlinks = {"Applications": "/Applications"}
icon = '{{.IconPath}}'
icon_locations = {'{{.AppName}}': (140, 120), "Applications": (500, 120)}
background = "builtin-arrow"
`))
// packWindows packages the app for Windows by generating a .msi file.
func packWindows(c *config.Config) error {
opath := c.Build.Output
ipath := filepath.Join(opath, "tempWindowsInstaller")
gpath := filepath.Join(ipath, "installer.go")
epath := filepath.Join(opath, c.Name+" Installer.exe")
err := os.MkdirAll(ipath, 0777)
if err != nil {
return err
}
fman, err := os.Create(gpath)
if err != nil {
return err
}
// The DLLs of FFmpeg (and its license), if the app uses it, which are
// installed next to the executable of the app.
ffiles, err := ffmpegWindowsFiles()
if err != nil {
return err
}
wmd := &windowsInstallerData{
Name: c.Name,
Desc: c.About,
}
if len(ffiles) > 0 {
if err := os.MkdirAll(filepath.Join(ipath, "files"), 0777); err != nil {
return err
}
for _, f := range ffiles {
name := filepath.Base(f)
if name == "LICENSE.txt" {
name = "FFmpeg-LICENSE.txt"
}
b, err := os.ReadFile(f)
if err != nil {
return err
}
if err := os.WriteFile(filepath.Join(ipath, "files", name), b, 0666); err != nil {
return err
}
wmd.Files = append(wmd.Files, name)
}
}
err = windowsInstallerTmpl.Execute(fman, wmd)
fman.Close()
if err != nil {
return err
}
err = exec.Run("cp", filepath.Base(c.Build.Output)+".exe", filepath.Join(ipath, "app.exe"))
if err != nil {
return err
}
err = exec.Run("cp", "icon.svg", filepath.Join(ipath, "icon.svg"))
if err != nil {
return err
}
err = exec.Run("go", "build", "-o", epath, gpath)
if err != nil {
return err
}
return os.RemoveAll(ipath)
}
// windowsInstallerData is the data passed to [windowsInstallerTmpl]
type windowsInstallerData struct {
Name string
Desc string
// Files are the names of the files that are installed next to the
// executable of the app (the DLLs of FFmpeg, and its license), which
// are in the files directory of the installer.
Files []string
}
//go:embed windowsinstaller.go.tmpl
var windowsInstallerTmplString string
// windowsInstallerTmpl is the template for the Windows installer Go file
var windowsInstallerTmpl = template.Must(template.New("windowsInstallerTmpl").Parse(windowsInstallerTmplString))
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cmd
import (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"sync"
"cogentcore.org/core/base/exec"
"cogentcore.org/core/cmd/config"
)
// Pull concurrently pulls all of the Git repositories within the current directory.
func Pull(c *config.Config) error { //types:add
wg := sync.WaitGroup{}
errs := []error{}
fs.WalkDir(os.DirFS("."), ".", func(path string, d fs.DirEntry, err error) error {
wg.Go(func() {
if d.Name() != ".git" {
return
}
dir := filepath.Dir(path)
err := exec.Major().SetDir(dir).Run("git", "pull")
if err != nil {
errs = append(errs, fmt.Errorf("error pulling %q: %w", dir, err))
}
})
return nil
})
wg.Wait()
return errors.Join(errs...)
}
//go:build !windows
package cmd
func windowsRegistryAddPath(_ string) error {
return nil // no-op
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cmd
import (
"fmt"
"strings"
"cogentcore.org/core/base/exec"
"cogentcore.org/core/cmd/config"
"github.com/Masterminds/semver/v3"
)
// Release releases the project with the specified git version tag.
func Release(c *config.Config) error { //types:add
err := exec.Run("git", "tag", "-a", c.Version, "-m", c.Version+" release")
if err != nil {
return fmt.Errorf("error tagging release: %w", err)
}
err = exec.Run("git", "push", "origin", "--tags")
if err != nil {
return fmt.Errorf("error pushing tags: %w", err)
}
return nil
}
// NextRelease releases the project with the current git version
// tag incremented by one patch version.
func NextRelease(c *config.Config) error { //types:add
ver, err := nextVersion(c)
if err != nil {
return err
}
c.Version = ver
return Release(c)
}
// nextVersion returns the version of the project
// incremented by one patch version.
func nextVersion(c *config.Config) (string, error) {
cur, err := exec.Output("git", "describe", "--tags", "--abbrev=0")
if err != nil {
return "", err
}
ver, err := semver.NewVersion(cur)
if err != nil {
return "", fmt.Errorf("error getting semver version from version %q: %w", c.Version, err)
}
if !strings.HasPrefix(ver.Prerelease(), "dev") { // if no dev pre-release, we can just do standard increment
*ver = ver.IncPatch()
} else { // otherwise, we have to increment pre-release version instead
pvn := strings.TrimPrefix(ver.Prerelease(), "dev")
pver, err := semver.NewVersion(pvn)
if err != nil {
return "", fmt.Errorf("error parsing dev version %q from version %q: %w", pvn, c.Version, err)
}
*pver = pver.IncPatch()
// apply incremented pre-release version to main version
nv, err := ver.SetPrerelease("dev" + pver.String())
if err != nil {
return "", fmt.Errorf("error setting pre-release of new version to %q from repository version %q: %w", "dev"+pver.String(), c.Version, err)
}
*ver = nv
}
return "v" + ver.String(), nil
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package rendericon renders the icon of an app (icon.svg) to an image of a
// given size.
package rendericon
import (
"errors"
"fmt"
"image"
"io/fs"
"os"
"strings"
"cogentcore.org/core/base/iox/imagex"
"cogentcore.org/core/icons"
"cogentcore.org/core/math32"
_ "cogentcore.org/core/paint/renderers"
"cogentcore.org/core/svg"
)
// Render renders the icon located at icon.svg at the given size.
// If no such icon exists, it sets it to a placeholder icon, [icons.DefaultAppIcon].
func Render(size int) (*image.RGBA, error) {
sv := svg.NewSVG(math32.Vec2(float32(size), float32(size)))
spath := "icon.svg"
err := sv.OpenXML(spath)
if err != nil {
if !errors.Is(err, fs.ErrNotExist) {
return nil, fmt.Errorf("error opening svg icon file: %w", err)
}
err = os.WriteFile(spath, []byte(icons.CogentCore), 0666)
if err != nil {
return nil, err
}
err = sv.ReadXML(strings.NewReader(string(icons.CogentCore)))
if err != nil {
return nil, err
}
}
return imagex.AsRGBA(sv.RenderImage()), nil
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cmd
import (
"fmt"
"os"
"path/filepath"
"runtime"
"cogentcore.org/core/base/exec"
"cogentcore.org/core/base/logx"
"cogentcore.org/core/cmd/config"
"cogentcore.org/core/cmd/mobile"
"cogentcore.org/core/cmd/web"
)
// Run builds and runs the config package. It also displays the logs generated
// by the app. It uses the same config info as build.
func Run(c *config.Config) error { //types:add
if len(c.Build.Target) != 1 {
return fmt.Errorf("expected 1 target platform, but got %d (%v)", len(c.Build.Target), c.Build.Target)
}
t := c.Build.Target[0]
if t.OS == "android" {
// the device to run on, whose architecture to build for, which the
// commands of adb then use
serial, err := mobile.AndroidDevice()
if err != nil {
return err
}
os.Setenv("ANDROID_SERIAL", serial)
if arch := mobile.AndroidDeviceArch(serial); t.Arch == "*" && arch != "" {
t.Arch = arch
c.Build.Target[0] = t
}
}
if t.Arch == "*" {
if t.OS == "android" || t.OS == "ios" {
t.Arch = "arm64"
} else {
t.Arch = runtime.GOARCH
}
c.Build.Target[0] = t
}
if t.OS == "ios" && !c.Build.Debug {
// TODO: is there a way to launch without running the debugger?
logx.PrintlnWarn("warning: only installing, not running, because there is no effective way to just launch an app on iOS from the terminal without debugging; pass the -d flag to run and debug")
}
if t.OS == "wasm" || t.OS == "js" {
// needed for changes to show during local development
c.Web.RandomVersion = true
}
err := Build(c)
if err != nil {
return fmt.Errorf("error building app: %w", err)
}
// Build may have added iossimulator, so we get rid of it for
// the running stage (we already confirmed we were passed 1 up above)
if len(c.Build.Target) > 1 {
c.Build.Target = []config.Platform{t}
}
switch t.OS {
case "darwin", "windows", "linux":
return exec.Verbose().SetBuffer(false).Run(filepath.Join(c.Build.Output, filepath.Base(c.Build.Output)))
case "android":
adb := mobile.AndroidTool("adb")
err := exec.Run(adb, "install", "-r", filepath.Join(c.Build.Output, c.Name+".apk"))
if err != nil {
return fmt.Errorf("error installing app: %w", err)
}
// see https://stackoverflow.com/a/4567928
args := []string{"shell", "am", "start", "-n", c.ID + "/org.golang.app.GoNativeActivity"}
// TODO: get adb am debug on Android working
// if c.Build.Debug {
// args = append(args, "-D")
// }
err = exec.Run(adb, args...)
if err != nil {
return fmt.Errorf("error starting app: %w", err)
}
if c.Build.Debug {
return Log(c)
}
return nil
case "iossimulator":
return mobile.RunSimulator(c)
case "ios":
if !c.Build.Debug {
return mobile.Install(c)
}
return exec.Verbose().SetBuffer(false).Run("ios-deploy", "-b", filepath.Join(c.Build.Output, c.Name+".app"), "-d")
case "wasm", "js":
return web.Serve(c)
}
return nil
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cmd
import (
"errors"
"fmt"
"runtime"
"strings"
"cogentcore.org/core/base/exec"
"cogentcore.org/core/base/logx"
"cogentcore.org/core/cmd/config"
"cogentcore.org/core/cmd/mobile"
"cogentcore.org/core/cmd/web"
)
// Setup installs platform-specific dependencies for the current platform,
// and the latest versions of the Go tools for developing with Cogent Core:
// goimports, goalimports, and goalls (which core update keeps updated).
// It only needs to be called once per system.
//
// With the video option, it also installs FFmpeg for the video package
// (cogentcore.org/core/video), which it needs on desktop platforms.
// With the js option, it installs the tools of the js platform (see
// [web.SetupJS]).
// With the androidsim option, it also installs the Android SDK and makes
// an Android virtual device for the emulator (see [mobile.SetupAndroidSim]).
// With the print option, it only prints the system packages that it
// installs for the current platform (see [SetupPackages]).
func Setup(c *config.Config) error { //types:add
if c.Print {
fmt.Println(strings.Join(SetupPackages(), " "))
return nil
}
err := setupPlatform()
if c.Video {
if verr := setupFFmpeg(false); verr != nil {
err = errors.Join(err, fmt.Errorf("FFmpeg: %w", verr))
}
}
if c.JS {
if jerr := web.SetupJS(); jerr != nil {
err = errors.Join(err, fmt.Errorf("the js tools: %w", jerr))
}
}
if c.AndroidSim {
if aerr := mobile.SetupAndroidSim(); aerr != nil {
err = errors.Join(err, fmt.Errorf("the Android emulator: %w", aerr))
}
}
for _, t := range goDevTools() {
logx.PrintlnWarn("installing " + t.name)
if terr := installGoTool(t); terr != nil {
err = errors.Join(err, fmt.Errorf("%s: %w", t.name, terr))
}
}
return err
}
// setupPlatform installs platform-specific dependencies for the current platform.
func setupPlatform() error {
vc := exec.Verbose().SetBuffer(false)
switch runtime.GOOS {
case "darwin":
p, err := exec.Output("xcode-select", "-p")
if err != nil || p == "" {
err := vc.Run("xcode-select", "--install")
if err != nil {
return err
}
} else {
logx.PrintlnWarn("xcode tools already installed")
}
return nil
case "linux":
ld := findLinuxDistro()
if ld == nil {
return errors.New("unknown Linux distro; please file a bug report at https://github.com/cogentcore/core/issues")
}
if ld.tool == "apt" { // special case for apt
err := vc.Run("sudo", "apt", "update")
if err != nil {
return err
}
}
cmd, args := ld.cmd()
return vc.Run(cmd, args...)
case "windows":
return setupWindows(vc)
}
return fmt.Errorf("platform %q not supported for core setup", runtime.GOOS)
}
// SetupPackages returns the system packages that setup installs for the
// current platform: on Linux, the packages for the package manager of its
// distribution, and nil on other platforms or an unknown distribution.
func SetupPackages() []string {
if runtime.GOOS != "linux" {
return nil
}
if ld := findLinuxDistro(); ld != nil {
return ld.packages
}
return nil
}
// findLinuxDistro returns the supported Linux distribution whose package
// manager is installed, or nil if there is none.
func findLinuxDistro() *linuxDistro {
for _, ld := range linuxDistros {
if _, err := exec.LookPath(ld.tool); err == nil {
return ld
}
}
return nil
}
// linuxDistro represents the data needed to install dependencies for a specific Linux
// distribution family with the same installation steps.
type linuxDistro struct {
// name contains the user-friendly name(s) of the Linux distribution(s).
name string
// sudo is whether the package manager requires sudo.
sudo bool
// tool is the name of the package manager used for installation.
tool string
// command contains the subcommand(s) in the package manager used to install packages.
command []string
// packages are the packages that need to be installed.
packages []string
}
// cmd returns the command and arguments to install the packages for the Linux distribution.
func (ld *linuxDistro) cmd() (cmd string, args []string) {
if ld.sudo {
cmd = "sudo"
args = append(args, ld.tool)
} else {
cmd = ld.tool
}
args = append(args, ld.command...)
args = append(args, ld.packages...)
return
}
func (ld *linuxDistro) String() string {
cmd, args := ld.cmd()
return fmt.Sprintf("%-15s %s %s", ld.name+":", cmd, strings.Join(args, " "))
}
// linuxDistros contains the supported Linux distributions,
// based on https://docs.fyne.io/started.
var linuxDistros = []*linuxDistro{
{name: "Debian/Ubuntu", sudo: true, tool: "apt", command: []string{"install"}, packages: []string{
"gcc", "libgl1-mesa-dev", "libegl1-mesa-dev", "mesa-vulkan-drivers", "xorg-dev", "libwayland-dev", "libxkbcommon-dev",
}},
{name: "Fedora", sudo: true, tool: "dnf", command: []string{"install"}, packages: []string{
"gcc", "libX11-devel", "libXcursor-devel", "libXrandr-devel", "libXinerama-devel", "mesa-libGL-devel", "libXi-devel", "libXxf86vm-devel", "mesa-vulkan-drivers", "wayland-devel", "libxkbcommon-devel",
}},
{name: "Arch", sudo: true, tool: "pacman", command: []string{"-S"}, packages: []string{
"xorg-server-devel", "libxcursor", "libxrandr", "libxinerama", "libxi", "vulkan-swrast", "wayland", "libxkbcommon",
}},
{name: "Solus", sudo: true, tool: "eopkg", command: []string{"it", "-c"}, packages: []string{
"system.devel", "mesalib-devel", "libxrandr-devel", "libxcursor-devel", "libxi-devel", "libxinerama-devel", "vulkan", "wayland-devel", "libxkbcommon-devel",
}},
{name: "openSUSE", sudo: true, tool: "zypper", command: []string{"install"}, packages: []string{
"gcc", "libXcursor-devel", "libXrandr-devel", "libxkbcommon", "Mesa-libGL-devel", "libXi-devel", "libXinerama-devel", "libXxf86vm-devel", "libvulkan1", "wayland-devel",
}},
{name: "Void", sudo: true, tool: "xbps-install", command: []string{"-S"}, packages: []string{
"base-devel", "xorg-server-devel", "libXrandr-devel", "libXcursor-devel", "libXinerama-devel", "vulkan-loader", "wayland-devel", "libxkbcommon-devel",
}},
{name: "Alpine", sudo: true, tool: "apk", command: []string{"add"}, packages: []string{
"gcc", "libxcursor-dev", "libxrandr-dev", "libxinerama-dev", "libxi-dev", "linux-headers", "mesa-dev", "vulkan-loader", "wayland-dev", "libxkbcommon-dev",
}},
{name: "NixOS", sudo: false, tool: "nix-shell", command: []string{"-p"}, packages: []string{
"libGL", "pkg-config", "xorg.libX11.dev", "xorg.libXcursor", "xorg.libXi", "xorg.libXinerama", "xorg.libXrandr", "xorg.libXxf86vm", "mesa.drivers", "vulkan-loader", "wayland", "libxkbcommon",
}},
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cmd
import (
"os"
"path/filepath"
"runtime"
"slices"
"strings"
"cogentcore.org/core/base/exec"
"cogentcore.org/core/base/logx"
"github.com/mitchellh/go-homedir"
)
const (
// llvmMingwVersion is the version of llvm-mingw installed on Windows ARM64.
llvmMingwVersion = "20261020"
// llvmMingwDir is where llvm-mingw is installed on Windows ARM64.
llvmMingwDir = `C:\llvm-mingw`
// windowsARM64Tag is the build tag that Delve (used by Cogent Code)
// requires to build on Windows ARM64, which it supports experimentally.
windowsARM64Tag = "exp.winarm64"
)
// typeInfoStub is C source for a stub of the MSVC C++ runtime symbol
// const type_info::`vftable', which the MSVC-built wgpu_native library for
// Windows ARM64 references (for Rust panics), but MinGW does not have.
// A Rust panic that unwinds may crash instead of being reported.
const typeInfoStub = `// Stub for MSVC's const type_info::vftable, referenced by the
// MSVC-built wgpu_native library for Rust panics, which MinGW lacks.
// Installed by core setup on Windows ARM64.
const void* type_info_vftable[2] __asm__("??_7type_info@@6B@") = {0, 0};
`
// setupWindows installs the C compiler (w64devkit, or llvm-mingw on ARM64)
// and git, which are needed to build Cogent Core apps on Windows.
func setupWindows(vc *exec.Config) error {
// We must be in the home directory to avoid permission issues with file downloading.
hd, err := homedir.Dir()
if err != nil {
return err
}
err = os.Chdir(hd)
if err != nil {
return err
}
if runtime.GOARCH == "arm64" {
err = setupWindowsARM64(vc)
} else {
err = setupWindowsGCC(vc)
}
if err != nil {
return err
}
if _, err := exec.LookPath("git"); err != nil {
installer := "Git-2.45.2-64-bit.exe"
url := "https://github.com/git-for-windows/git/releases/download/v2.45.2.windows.1/" + installer
if runtime.GOARCH == "arm64" {
installer = "Git-2.56.0.4-arm64.exe"
url = "https://github.com/git-for-windows/git/releases/download/v2.56.0.windows.4/" + installer
}
err := vc.Run("curl", "-OL", url)
if err != nil {
return err
}
path, err := filepath.Abs(installer)
if err != nil {
return err
}
err = vc.Run(path)
if err != nil {
return err
}
} else {
logx.PrintlnWarn("git already installed")
}
return nil
}
// setupWindowsGCC installs the w64devkit gcc compiler (for amd64).
func setupWindowsGCC(vc *exec.Config) error {
if _, err := exec.LookPath("gcc"); err == nil {
logx.PrintlnWarn("gcc already installed")
return nil
}
err := vc.Run("curl", "-OL", "https://github.com/skeeto/w64devkit/releases/download/v2.0.0/w64devkit-x64-2.0.0.exe")
if err != nil {
return err
}
path, err := filepath.Abs("w64devkit-x64-2.0.0.exe")
if err != nil {
return err
}
err = vc.Run(path, "x", "-oC:", "-aoa")
if err != nil {
return err
}
return windowsRegistryAddPath(`C:\w64devkit\bin`)
}
// setupWindowsARM64 sets up cgo on Windows ARM64: w64devkit only has
// an x86 compiler, so it installs the aarch64 clang compiler of llvm-mingw,
// sets it as the Go CC and CXX, links a stub needed for the wgpu_native
// library (see [typeInfoStub]), and sets the build tag that Delve needs.
func setupWindowsARM64(vc *exec.Config) error {
clang, err := installLLVMMingw(vc)
if err != nil {
return err
}
clangxx := strings.TrimSuffix(clang, ".exe") + "++"
if strings.HasSuffix(clang, ".exe") {
clangxx += ".exe"
}
err = vc.Run("go", "env", "-w", "CC="+clang, "CXX="+clangxx)
if err != nil {
return err
}
obj, err := buildTypeInfoStub(vc, clang)
if err != nil {
return err
}
ldflags, err := exec.Output("go", "env", "CGO_LDFLAGS")
if err != nil {
return err
}
if nf := cgoFlagsWith(ldflags, obj); nf != ldflags {
err = vc.Run("go", "env", "-w", "CGO_LDFLAGS="+nf)
if err != nil {
return err
}
}
goflags, err := exec.Output("go", "env", "GOFLAGS")
if err != nil {
return err
}
if nf := goFlagsWithTag(goflags, windowsARM64Tag); nf != goflags {
err = vc.Run("go", "env", "-w", "GOFLAGS="+nf)
if err != nil {
return err
}
}
return nil
}
// installLLVMMingw installs llvm-mingw for ARM64 hosts in [llvmMingwDir],
// unless its aarch64 clang compiler is already on the path or there,
// and returns the path of that compiler.
func installLLVMMingw(vc *exec.Config) (string, error) {
const name = "aarch64-w64-mingw32-clang"
if clang, err := exec.LookPath(name); err == nil {
logx.PrintlnWarn("llvm-mingw already installed:", clang)
return clang, nil
}
bin := filepath.Join(llvmMingwDir, "bin")
clang := filepath.Join(bin, name+".exe")
if _, err := os.Stat(clang); err == nil {
logx.PrintlnWarn("llvm-mingw already installed in", llvmMingwDir)
return clang, windowsRegistryAddPath(bin)
}
dist := "llvm-mingw-" + llvmMingwVersion + "-ucrt-aarch64"
err := vc.Run("curl", "-OL", "https://github.com/mstorsjo/llvm-mingw/releases/download/"+llvmMingwVersion+"/"+dist+".zip")
if err != nil {
return "", err
}
// tar (bsdtar) is included in Windows, and extracts zip files
err = vc.Run("tar", "-xf", dist+".zip", "-C", filepath.Dir(llvmMingwDir))
if err != nil {
return "", err
}
err = os.Rename(filepath.Join(filepath.Dir(llvmMingwDir), dist), llvmMingwDir)
if err != nil {
return "", err
}
return clang, windowsRegistryAddPath(bin)
}
// buildTypeInfoStub compiles [typeInfoStub] with the given clang compiler,
// in the Cogent Core directory of the user config directory, and returns
// the path of the object file.
func buildTypeInfoStub(vc *exec.Config, clang string) (string, error) {
dir, err := os.UserConfigDir()
if err != nil {
return "", err
}
dir = filepath.Join(dir, "cogentcore", "windows-arm64")
err = os.MkdirAll(dir, 0o755)
if err != nil {
return "", err
}
src := filepath.Join(dir, "typeinfo.c")
err = os.WriteFile(src, []byte(typeInfoStub), 0o644)
if err != nil {
return "", err
}
obj := filepath.Join(dir, "typeinfo.o")
return obj, vc.Run(clang, "-c", src, "-o", obj)
}
// cgoFlagsWith returns the given CGO_*FLAGS value with the given flag added
// at the end (quoted if it has a space), unless it already has it.
func cgoFlagsWith(flags, flag string) string {
flags = strings.TrimSpace(flags)
if strings.Contains(flags, flag) {
return flags
}
if strings.ContainsAny(flag, " \t") {
flag = `"` + flag + `"`
}
if flags == "" {
return flag
}
return flags + " " + flag
}
// goFlagsWithTag returns the given GOFLAGS value with the given build tag
// added, to an existing -tags flag if there is one, unless it already has it.
func goFlagsWithTag(goflags, tag string) string {
fields := strings.Fields(goflags)
for i, f := range fields {
tags, ok := strings.CutPrefix(f, "-tags=")
if !ok {
tags, ok = strings.CutPrefix(f, "--tags=")
}
if !ok {
continue
}
if slices.Contains(strings.Split(tags, ","), tag) {
return strings.Join(fields, " ")
}
if tags == "" {
fields[i] = f + tag
} else {
fields[i] = f + "," + tag
}
return strings.Join(fields, " ")
}
return strings.Join(append(fields, "-tags="+tag), " ")
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cmd
import (
"cmp"
"fmt"
"io"
"log/slog"
"os"
"strings"
"time"
"cogentcore.org/core/base/exec"
"cogentcore.org/core/base/goscript"
"cogentcore.org/core/base/logx"
"cogentcore.org/core/cmd/config"
"cogentcore.org/core/cmd/web"
)
// Test runs the tests of the given packages for the target platform, as
// with go test. For the js platform (core test js), the tests are compiled
// to JavaScript by GoScript, with the build tags and overrides of core
// build js, and run in bun, or in Chrome for the packages that say so
// with a //core:js-test line in a test file (see the goscript package in
// base), which also has other options. A package pattern with ... only
// matches the packages that have such a line. The tools are installed
// first if needed (as by core setup -js).
func Test(c *config.Config) error { //types:add
if len(c.Build.Target) != 1 {
return fmt.Errorf("expected 1 target platform, but got %d (%v)", len(c.Build.Target), c.Build.Target)
}
pkgs := c.Test.Packages
if len(pkgs) == 0 {
pkgs = []string{"."}
}
verbose := logx.UserLevel <= slog.LevelInfo
if t := c.Build.Target[0]; t.OS != "js" {
// the other platforms are those of go test
args := []string{"test"}
if c.Test.Run != "" {
args = append(args, "-run", c.Test.Run)
}
if c.Test.Bench != "" {
args = append(args, "-bench", c.Test.Bench)
}
if c.Test.BenchTime != "" {
args = append(args, "-benchtime", c.Test.BenchTime)
}
if c.Test.Timeout != "" {
args = append(args, "-timeout", c.Test.Timeout)
}
if verbose {
args = append(args, "-v")
}
args = append(args, pkgs...)
return exec.Verbose().SetBuffer(false).Run("go", args...)
}
var timeout time.Duration
if c.Test.Timeout != "" {
var err error
if timeout, err = time.ParseDuration(c.Test.Timeout); err != nil {
return fmt.Errorf("invalid timeout: %w", err)
}
}
if err := web.SetupJS(); err != nil {
return err
}
dirs, err := testPackageDirs(pkgs)
if err != nil {
return err
}
// each package is tested in turn, in each run that it has
var failed []string
for _, d := range dirs {
runs, err := goscript.PackageOptions(d.dir)
if err != nil {
return err
}
if len(runs) == 0 {
if d.pattern {
continue // not opted in
}
runs = []goscript.Options{{}}
}
for _, o := range runs {
o.Tags = append(strings.Split(web.JSTags, ","), o.Tags...)
o.Run = cmp.Or(c.Test.Run, o.Run)
o.Bench, o.BenchTime = c.Test.Bench, c.Test.BenchTime
if timeout > 0 {
o.Timeout = timeout
}
o.Browser = o.Browser || c.Test.Browser
if o.Browser {
o.BrowserChannel = "chrome"
}
o.Verbose = verbose
var out io.Writer = io.Discard
if verbose || o.Bench != "" {
out = os.Stdout
}
var buf strings.Builder
if out == io.Discard {
out = &buf // shown if it fails
}
st := time.Now()
if err := goscript.RunTests(d.dir, o, out); err != nil {
fmt.Print(buf.String())
fmt.Printf("FAIL\t%s\t%v: %v\n", d.importPath, time.Since(st).Round(time.Millisecond), err)
failed = append(failed, d.importPath)
continue
}
fmt.Printf("ok \t%s\t%v\n", d.importPath, time.Since(st).Round(time.Millisecond))
}
}
if len(failed) > 0 {
return fmt.Errorf("the tests of %d package(s) failed: %s", len(failed), strings.Join(failed, ", "))
}
return nil
}
// testPackage is a package to test, for [Test].
type testPackage struct {
importPath, dir string
// pattern is whether the package was matched by a pattern with ...
// in it, and not given itself.
pattern bool
}
// testPackageDirs returns the packages with tests of the given package
// patterns.
func testPackageDirs(patterns []string) ([]testPackage, error) {
var pkgs []testPackage
seen := map[string]bool{}
for _, pat := range patterns {
out, err := exec.Minor().Output("go", "list", "-e", "-f", "{{if or .TestGoFiles .XTestGoFiles}}{{.ImportPath}} {{.Dir}}{{end}}", pat)
if err != nil {
return nil, err
}
for line := range strings.SplitSeq(out, "\n") {
ip, dir, ok := strings.Cut(strings.TrimSpace(line), " ")
if !ok || seen[dir] {
continue
}
seen[dir] = true
pkgs = append(pkgs, testPackage{importPath: ip, dir: dir, pattern: strings.Contains(pat, "...")})
}
}
return pkgs, nil
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cmd
import (
"debug/buildinfo"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"strings"
"time"
"cogentcore.org/core/base/exec"
"cogentcore.org/core/base/logx"
"cogentcore.org/core/cmd/config"
"cogentcore.org/core/cmd/web"
"golang.org/x/mod/semver"
)
// goTool is a command that is installed with go install.
type goTool struct {
// name is the name of the command.
name string
// pkg is the package of the command.
pkg string
// module is the module that holds the package.
module string
// query is the version query to update to, such as main or latest.
query string
// path is the path of the installed command, or "" if it is not installed.
path string
// install is whether to install the command if it is not installed.
install bool
}
// goDevTools returns the Go tools for developing with Cogent Core, which
// core setup installs, and core update updates, installing them if they
// are not installed: goimports, which formats Go code and fixes its
// imports, and goalimports and goalls, which do that for Goal code, and
// are the language server for Go and Goal code, a proxy for gopls (see
// cogentcore.org/lab/goal).
func goDevTools() []goTool {
tools := []goTool{
{name: "goimports", pkg: "golang.org/x/tools/cmd/goimports", module: "golang.org/x/tools"},
{name: "goalimports", pkg: "cogentcore.org/lab/goal/cmd/goalimports", module: "cogentcore.org/lab"},
{name: "goalls", pkg: "cogentcore.org/lab/goal/cmd/goalls", module: "cogentcore.org/lab"},
}
for i := range tools {
t := &tools[i]
t.query = "latest"
t.install = true
t.path = web.ToolPath(t.name)
}
return tools
}
// installGoTool installs the latest version of the given tool.
func installGoTool(t goTool) error {
return exec.Verbose().SetBuffer(false).SetDir(os.TempDir()).Run("go", "install", t.pkg+"@"+t.query)
}
// Update updates the core command and the tools that it uses to their
// latest versions: the core command itself (from the main branch, as it is
// installed), the GoScript compiler and bun that the js platform uses, if
// they are installed, and the Go tools for developing with Cogent Core
// (goimports, goalimports, and goalls), which it installs if they are not
// installed. A tool built from a local source checkout is not replaced
// unless the force option is set, and the check option only reports
// which tools have updates. With the video option, it also updates FFmpeg
// for the video package (see core setup -video).
func Update(c *config.Config) error { //types:add
core, err := os.Executable()
if err != nil {
return err
}
tools := []goTool{
{name: "core", pkg: "cogentcore.org/core", module: "cogentcore.org/core", query: "main", path: core},
{name: "goscript", pkg: web.GoscriptPackage, module: "github.com/s4wave/goscript", query: "latest", path: web.ToolPath("goscript")},
}
tools = append(tools, goDevTools()...)
var errs []error
for _, t := range tools {
if err := updateGoTool(c, t); err != nil {
errs = append(errs, fmt.Errorf("%s: %w", t.name, err))
}
}
if err := updateBun(c); err != nil {
errs = append(errs, fmt.Errorf("bun: %w", err))
}
if c.Video && !c.Update.Check {
if err := setupFFmpeg(true); err != nil {
errs = append(errs, fmt.Errorf("FFmpeg: %w", err))
}
}
return errors.Join(errs...)
}
// updateGoTool updates the given tool installed with go install, if it is
// installed and a newer version is available.
func updateGoTool(c *config.Config, t goTool) error {
// The installed version is the version of the main module of the
// command; a command built from a local source checkout has no sum.
switch {
case t.path == "" && t.install && c.Update.Check:
fmt.Println(t.name + " is not installed; it can be installed")
return nil
case t.path == "" && t.install:
logx.PrintlnWarn("installing " + t.name)
return installGoTool(t)
case t.path == "":
fmt.Println(t.name + " is not installed")
return nil
}
info, err := buildinfo.ReadFile(t.path)
if err != nil {
return fmt.Errorf("reading the version of %s: %w", t.path, err)
}
if info.Main.Path != t.module {
fmt.Printf("%s (%s) is not built from %s; not updating it\n", t.name, t.path, t.module)
return nil
}
installed := info.Main.Version
latest, err := latestModuleVersion(t.module, t.query)
if err != nil {
return err
}
// Only an older version installed from the module proxy is updated
// without the force option.
switch {
case installed == latest:
fmt.Printf("%s %s is up to date\n", t.name, installed)
return nil
case info.Main.Sum == "" && !c.Update.Force:
fmt.Printf("%s %s was built from a local source checkout; not replacing it with %s (use -force to do so)\n", t.name, installed, latest)
return nil
case semver.Compare(installed, latest) > 0 && !c.Update.Force:
fmt.Printf("%s %s is newer than %s; not replacing it (use -force to do so)\n", t.name, installed, latest)
return nil
case c.Update.Check:
fmt.Printf("%s %s can be updated to %s\n", t.name, installed, latest)
return nil
}
logx.PrintlnWarn(fmt.Sprintf("updating %s from %s to %s", t.name, installed, latest))
return installGoTool(t)
}
// latestModuleVersion returns the version of the given module for the given
// version query (such as main or latest), from the module proxy.
func latestModuleVersion(module, query string) (string, error) {
// A workspace or the module of the current directory does not apply.
v, err := exec.Silent().SetDir(os.TempDir()).SetEnv("GOWORK", "off").Output("go", "list", "-m", "-f", "{{.Version}}", module+"@"+query)
if err != nil {
return "", fmt.Errorf("finding the %s version of %s: %w", query, module, err)
}
return strings.TrimSpace(v), nil
}
// updateBun updates bun with its own upgrade command, if it is installed.
// With the check option, it reports the latest release instead.
func updateBun(c *config.Config) error {
path := web.ToolPath("bun")
if path == "" {
fmt.Println("bun is not installed")
return nil
}
installed, err := exec.Silent().Output(path, "--version")
if err != nil {
return err
}
installed = strings.TrimSpace(installed)
if !c.Update.Check {
logx.PrintlnWarn("updating bun " + installed + " with bun upgrade")
return exec.Verbose().SetBuffer(false).Run(path, "upgrade")
}
// The latest release is only needed to report it.
latest, err := latestBunVersion()
switch {
case err != nil:
fmt.Printf("bun %s is installed; could not find the latest version: %v\n", installed, err)
case latest == installed:
fmt.Printf("bun %s is up to date\n", installed)
default:
fmt.Printf("bun %s can be updated to %s\n", installed, latest)
}
return nil
}
// latestBunVersion returns the version of the latest release of bun on
// GitHub, whose tags are named bun-v1.2.3.
func latestBunVersion() (string, error) {
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Get("https://api.github.com/repos/oven-sh/bun/releases/latest")
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("GitHub returned %s", resp.Status)
}
var release struct {
TagName string `json:"tag_name"`
}
if err := json.NewDecoder(resp.Body).Decode(&release); err != nil {
return "", err
}
return strings.TrimPrefix(release.TagName, "bun-v"), nil
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package web provides functions for building Cogent Core apps for the web.
package web
import (
"crypto/sha1"
"fmt"
"os"
"path/filepath"
"strconv"
"time"
"cogentcore.org/core/base/exec"
"cogentcore.org/core/base/iox/imagex"
"cogentcore.org/core/cmd/config"
"cogentcore.org/core/cmd/rendericon"
"cogentcore.org/core/content/bcontent"
strip "github.com/grokify/html-strip-tags-go"
)
// Build builds an app for web using the given configuration information.
func Build(c *config.Config) error {
if c.Web.HTMLOnly {
return buildHTMLOnly(c)
}
if IsJS(c) {
return buildJS(c)
}
output := filepath.Join(c.Build.Output, "app.wasm")
// The mvmnosrc tag leaves the standard library sources out of the mvm
// interpreter (see buildJS).
args := []string{"build", "-o", output, "-tags", "mvmnosrc", "-ldflags", config.LinkerFlags(c)}
if c.Build.Trimpath {
args = append(args, "-trimpath")
}
err := exec.Major().SetEnv("GOOS", "js").SetEnv("GOARCH", "wasm").Run("go", args...)
if err != nil {
return err
}
return finishBuild(c)
}
// finishBuild measures and compresses the app bundle (see [processBundle]),
// makes the other files of the website, and then reports the bundle size.
func finishBuild(c *config.Config) error {
total, startup, err := processBundle(c)
if err != nil {
return err
}
err = makeFiles(c)
if err != nil {
return err
}
err = copyFiles(c)
if err != nil {
return err
}
reportBundle(c, total, startup)
return nil
}
// makeFiles makes the necessary static web files based on the given configuration information.
func makeFiles(c *config.Config) error {
odir := c.Build.Output
if c.Web.RandomVersion {
t := time.Now().UTC().String()
c.Version = fmt.Sprintf(`%x`, sha1.Sum([]byte(t)))
}
// The about text may contain HTML, which we need to get rid of.
// It is trusted, so we do not need a more advanced sanitizer.
c.About = strip.StripTags(c.About)
if !IsJS(c) {
err := os.WriteFile(filepath.Join(odir, "wasm_exec.js"), []byte(wasmExecJS), 0666)
if err != nil {
return err
}
}
ajs, err := makeAppJS(c)
if err != nil {
return err
}
err = os.WriteFile(filepath.Join(odir, "app.js"), ajs, 0666)
if err != nil {
return err
}
man, err := makeManifestJSON(c)
if err != nil {
return err
}
err = os.WriteFile(filepath.Join(odir, "manifest.webmanifest"), man, 0666)
if err != nil {
return err
}
acs := []byte(appCSS)
err = os.WriteFile(filepath.Join(odir, "app.css"), acs, 0666)
if err != nil {
return err
}
preRenderHTML := ""
if c.Web.GenerateHTML {
preRenderHTML, err = generateHTML()
if err != nil {
return err
}
}
// A custom index page replaces the pre-rendered preview of the root page
// only; the pre-rendered previews of any content pages are still used.
indexPage, err := readIndexPage()
if err != nil {
return err
}
site, err := readSite(preRenderHTML)
if err != nil {
return err
}
awjs, err := makeAppWorkerJS(c, site != nil)
if err != nil {
return err
}
err = os.WriteFile(filepath.Join(odir, "app-worker.js"), awjs, 0666)
if err != nil {
return err
}
if site != nil {
err = makeContentSite(c, site, true, indexPage)
if err != nil {
return err
}
return makeIcons(c)
}
prindex := &bcontent.PreRenderPage{
Name: c.Name,
HTML: preRenderHTML,
}
if c.About != "" {
prindex.Description = c.About
}
iht, err := makeIndexHTML(c, "", prindex, indexPage)
if err != nil {
return err
}
err = os.WriteFile(filepath.Join(odir, "index.html"), iht, 0666)
if err != nil {
return err
}
// The 404 page is just the same as the index page, with an updated base path.
// The logic in the home page can then handle the error appropriately.
notFound, err := makeIndexHTML(c, notFoundBasePath(c), prindex, "")
if err != nil {
return err
}
err = os.WriteFile(filepath.Join(odir, "404.html"), notFound, 0666)
if err != nil {
return err
}
return makeIcons(c)
}
// makeIcons makes the app icon files in the icons directory of the output.
func makeIcons(c *config.Config) error {
odir := c.Build.Output
err := os.MkdirAll(filepath.Join(odir, "icons"), 0777)
if err != nil {
return err
}
sizes := []int{32, 192, 512}
for _, size := range sizes {
ic, err := rendericon.Render(size)
if err != nil {
return err
}
err = imagex.Save(ic, filepath.Join(odir, "icons", strconv.Itoa(size)+".png"))
if err != nil {
return err
}
}
err = exec.Run("cp", "icon.svg", filepath.Join(odir, "icons", "svg.svg"))
if err != nil {
return err
}
return nil
}
// notFoundBasePath returns the base path for the 404.html page, which is
// for pages one level below the root.
func notFoundBasePath(c *config.Config) string {
// TODO: this is a temporary hack to fix the 404 page for multi-nested old URLs in the Cogent Core Docs.
if c.Name == "Cogent Core Docs" {
if c.Build.Trimpath {
return "https://www.cogentcore.org/core/" // production
}
return "http://localhost:8080/" // dev
}
return "../"
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package web
import (
"bytes"
"compress/gzip"
"fmt"
"os"
osexec "os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"cogentcore.org/core/base/datasize"
"cogentcore.org/core/base/logx"
"cogentcore.org/core/cmd/config"
)
// bundleFiles returns the names of the files of the app bundle in the
// build output directory: app.wasm for wasm, and app.gs.js and its chunks
// (see [jsChunkPrefix]) for js.
func bundleFiles(c *config.Config) []string {
if !IsJS(c) {
return []string{"app.wasm"}
}
return append([]string{"app.gs.js"}, jsChunkFiles(c.Build.Output)...)
}
// bundleSize is the total size of the files of an app bundle,
// uncompressed and compressed.
type bundleSize struct {
// Files is the number of files.
Files int
// Size is the uncompressed size in bytes.
Size int
// Gzip is the size in bytes with gzip at the default level, which
// is what web servers that compress responses typically use.
Gzip int
// Brotli is the size in bytes with brotli at quality 5, a typical level
// for compressing responses on the fly, or 0 if the brotli command
// is not available.
Brotli int
}
// fileSize returns the size of a bundle of one file with the given contents.
func fileSize(b []byte) (*bundleSize, error) {
gz, err := gzipBytes(b, gzip.DefaultCompression)
if err != nil {
return nil, err
}
return &bundleSize{Files: 1, Size: len(b), Gzip: len(gz), Brotli: brotliSize(b)}, nil
}
// add adds the given size of other files to the bundle size.
func (bs *bundleSize) add(o *bundleSize) {
bs.Files += o.Files
bs.Size += o.Size
bs.Gzip += o.Gzip
bs.Brotli += o.Brotli
}
// String returns the sizes in the form used in the build report.
func (bs *bundleSize) String() string {
s := fmt.Sprintf("%s (gzip %s", datasize.Size(bs.Size), datasize.Size(bs.Gzip))
if bs.Brotli > 0 {
s += fmt.Sprintf(", brotli %s", datasize.Size(bs.Brotli))
}
s += ")"
if bs.Files > 1 {
s += fmt.Sprintf(" in %d files", bs.Files)
}
return s
}
// jsStaticImport matches a static import of a file of the bundle in
// the JavaScript output of esbuild, such as from"./app.gs.chunk-x.js",
// but not a dynamic import("./app.gs.chunk-x.js").
var jsStaticImport = regexp.MustCompile(`\b(?:from|import)\s*["']\./(app\.gs(?:\.chunk-[\w-]+)?\.js)["']`)
// startupFiles returns the files of the bundle with the given contents that
// the browser loads at startup: the first one, which is the entry, and the
// files that it imports statically, directly or through each other. The
// other files are chunks of [config.Web.DeferredFunctions], which are only
// loaded when they are first called.
func startupFiles(files []string, contents map[string][]byte) map[string]bool {
startup := map[string]bool{files[0]: true}
todo := []string{files[0]}
for len(todo) > 0 {
f := todo[len(todo)-1]
todo = todo[:len(todo)-1]
for _, m := range jsStaticImport.FindAllSubmatch(contents[f], -1) {
imp := string(m[1])
if _, ok := contents[imp]; ok && !startup[imp] {
startup[imp] = true
todo = append(todo, imp)
}
}
}
return startup
}
// processBundle measures the size of the app bundle in the build output
// directory (see [bundleFiles]), in total and of the files loaded at
// startup (see [startupFiles]), and gzips its files in place if
// [config.Web.Gzip] is on, in which case [Serve] serves them with
// Content-Encoding gzip, as must any other server of the app.
func processBundle(c *config.Config) (total, startup *bundleSize, err error) {
files := bundleFiles(c)
contents := map[string][]byte{}
for _, f := range files {
b, err := os.ReadFile(filepath.Join(c.Build.Output, f))
if err != nil {
return nil, nil, err
}
contents[f] = b
}
atStartup := startupFiles(files, contents)
total, startup = &bundleSize{}, &bundleSize{}
for _, f := range files {
fn := filepath.Join(c.Build.Output, f)
b := contents[f]
fs, err := fileSize(b)
if err != nil {
return nil, nil, err
}
total.add(fs)
if atStartup[f] {
startup.add(fs)
}
if !c.Web.Gzip {
continue
}
gz, err := gzipBytes(b, gzip.BestCompression)
if err != nil {
return nil, nil, err
}
err = os.WriteFile(fn, gz, 0666)
if err != nil {
return nil, nil, err
}
}
return total, startup, nil
}
// reportBundle prints the given total size of the app bundle, and the
// size of its files loaded at startup if that is not all of them.
func reportBundle(c *config.Config, total, startup *bundleSize) {
name := "app.wasm"
if IsJS(c) {
name = "app.gs.js"
}
msg := "bundle " + name + ": " + total.String()
if startup.Files < total.Files {
msg += "; loaded at startup: " + startup.String()
}
if c.Web.Gzip {
msg += "; gzipped in place (serve with Content-Encoding: gzip)"
}
logx.PrintlnWarn(msg)
}
// gzipBytes returns the given data compressed with gzip at the given level.
func gzipBytes(b []byte, level int) ([]byte, error) {
var buf bytes.Buffer
gw, err := gzip.NewWriterLevel(&buf, level)
if err != nil {
return nil, err
}
_, err = gw.Write(b)
if err != nil {
return nil, err
}
err = gw.Close()
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// brotliSize returns the size of the given data compressed with brotli
// at quality 5 by the brotli command, or 0 if it is not available.
// (Quality 11, which hosts use for files that they compress ahead of time,
// is much slower, such as 100 seconds for a 60 MB wasm file.)
func brotliSize(b []byte) int {
path, err := osexec.LookPath("brotli")
if err != nil {
return 0
}
cmd := osexec.Command(path, "-c", "-q", "5")
cmd.Stdin = bytes.NewReader(b)
out, err := cmd.Output()
if err != nil {
return 0
}
return len(out)
}
// acceptsGzip returns whether the given Accept-Encoding header value
// accepts gzip.
func acceptsGzip(accept string) bool {
for e := range strings.SplitSeq(accept, ",") {
name, params, _ := strings.Cut(e, ";")
name = strings.TrimSpace(name)
if name != "gzip" && name != "*" {
continue
}
q, ok := strings.CutPrefix(strings.ReplaceAll(params, " ", ""), "q=")
if !ok {
return true
}
v, err := strconv.ParseFloat(q, 64)
return err == nil && v > 0
}
return false
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package web
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"html"
"io/fs"
"net/url"
"os"
"path"
"path/filepath"
"regexp"
"strings"
"text/template"
"cogentcore.org/core/base/exec"
"cogentcore.org/core/base/iox/jsonx"
"cogentcore.org/core/cmd/config"
"cogentcore.org/core/content/bcontent"
strip "github.com/grokify/html-strip-tags-go"
)
// buildHTMLOnly builds a freestanding website consisting only of static
// HTML pages generated from the content of the app, without the Go wasm app
// (see [config.Web.HTMLOnly]).
func buildHTMLOnly(c *config.Config) error {
c.About = strip.StripTags(c.About)
out, err := generateHTML()
if err != nil {
return err
}
site, err := readSite(out)
if err != nil {
return err
}
if site == nil {
return errors.New("htmlonly: the app did not generate content site data; -htmlonly is only supported for apps that use the content package")
}
err = makeContentSite(c, site, false, "")
if err != nil {
return err
}
if err := copyFiles(c); err != nil {
return err
}
return makeIcons(c)
}
// generateHTML runs the app with the -generatehtml argument, which prints
// the pre-rendered HTML for the app, or the JSON [bcontent.Site] data
// for apps that use the content package. The HTML generator of
// [tohtmlPackage] is linked into the app for this run (see [tohtmlOverlay]).
func generateHTML() (string, error) {
args := []string{"run"}
overlay, err := tohtmlOverlay()
if err != nil {
return "", err
}
if overlay != "" {
defer os.RemoveAll(filepath.Dir(overlay))
args = append(args, "-overlay", overlay)
}
args = append(args, ".", "-generatehtml", "-nogui")
return exec.Output("go", args...)
}
// tohtmlPackage is the package that sets the HTML generator of an app
// for the -generatehtml argument (core.GenerateHTML) when it is imported.
const tohtmlPackage = "cogentcore.org/core/htmlcore/tohtml"
// tohtmlOverlay returns the path of a go build -overlay file that adds a
// file importing [tohtmlPackage] to the main package of the app in the
// current directory, so that apps need not import it themselves, without
// changing the files of the app. The caller removes the directory of the
// returned file. It returns "" if the version of Cogent Core that the app
// uses does not have that package (versions in which core itself has the
// HTML generator).
func tohtmlOverlay() (string, error) {
if _, err := exec.Minor().SetStderr(nil).Output("go", "list", tohtmlPackage); err != nil {
return "", nil
}
wd, err := os.Getwd()
if err != nil {
return "", err
}
tdir, err := os.MkdirTemp("", "cogentcore-generatehtml-")
if err != nil {
return "", err
}
src := filepath.Join(tdir, "generatehtml.go")
err = os.WriteFile(src, []byte("package main\n\nimport _ \""+tohtmlPackage+"\"\n"), 0666)
if err != nil {
return "", err
}
ov, err := json.Marshal(map[string]map[string]string{
"Replace": {filepath.Join(wd, "cogentcore_generatehtml.go"): src},
})
if err != nil {
return "", err
}
overlay := filepath.Join(tdir, "overlay.json")
return overlay, os.WriteFile(overlay, ov, 0666)
}
// readSite returns the [bcontent.Site] data in the given output of
// [generateHTML], or nil if the app does not use the content package.
func readSite(out string) (*bcontent.Site, error) {
if !strings.HasPrefix(out, "{") {
return nil, nil
}
site := &bcontent.Site{}
err := jsonx.Read(site, strings.NewReader(out))
if err != nil {
return nil, err
}
return site, nil
}
// makeContentSite makes the website for the given content site data,
// with an index.html file for each page, which contains the pre-rendered
// page content along with the navigation trees and page search (using Vue.js)
// of the content package. If wasm is true, each page loads the Go wasm app,
// and the website is the preview shown while the app is loading. Otherwise,
// it is a freestanding website (see [config.Web.HTMLOnly]). If indexPage is
// non-empty, it is used for the root page instead (see [readIndexPage]).
func makeContentSite(c *config.Config, site *bcontent.Site, wasm bool, indexPage string) error {
odir := c.Build.Output
if c.Content == "" {
c.Content = "content"
}
err := os.WriteFile(filepath.Join(odir, "content.css"), []byte(contentCSS+"\n/* Code highlighting */\n\n"+site.CSS), 0666)
if err != nil {
return err
}
err = os.WriteFile(filepath.Join(odir, "content.js"), []byte(contentJS), 0666)
if err != nil {
return err
}
nav, err := makeNavJS(c, site)
if err != nil {
return err
}
err = os.WriteFile(filepath.Join(odir, "nav.js"), nav, 0666)
if err != nil {
return err
}
// The content files that a js app loads as external embedded files are
// shown from there by the pages too, so they are only downloaded once.
var files map[string]string
if wasm && IsJS(c) {
files = externalContentFiles(c.Content, odir)
}
var root *bcontent.PreRenderPage
for _, prp := range site.Pages {
if prp.URL == "" {
root = prp
}
pdir := filepath.Join(odir, filepath.FromSlash(prp.URL))
err := os.MkdirAll(pdir, 0777)
if err != nil {
return err
}
var b []byte
if prp.URL == "" && wasm && indexPage != "" {
b, err = makeIndexHTML(c, "", &bcontent.PreRenderPage{Name: c.Name}, indexPage)
} else {
b, err = makeContentPage(c, site, prp, basePath(prp.URL), wasm, files)
}
if err != nil {
return err
}
err = os.WriteFile(filepath.Join(pdir, "index.html"), b, 0666)
if err != nil {
return err
}
}
// The 404 page loads the app for wasm, which can then handle the URL
// appropriately, with the root page as the preview. Otherwise, it is
// a page not found message. The base path is for pages one level below
// the root (see [notFoundBasePath]).
notFound := &bcontent.PreRenderPage{
Name: "Page not found", URL: "404",
HTML: `<div class="cc-page-frame"><h1 style="font-size:36px;font-weight:normal;line-height:1.2222222">Page not found</h1><p style="line-height:1.5">The requested page does not exist. Use the navigation or search to find another page.</p></div>`,
}
if wasm && root != nil {
notFound = root
}
b, err := makeContentPage(c, site, notFound, notFoundBasePath(c), wasm, files)
if err != nil {
return err
}
err = os.WriteFile(filepath.Join(odir, "404.html"), b, 0666)
if err != nil {
return err
}
return copyContentFiles(c.Content, odir, files)
}
// basePath returns the relative path to the root of the website
// for the page with the given URL.
func basePath(url string) string {
if url == "" {
return ""
}
return strings.Repeat("../", strings.Count(strings.Trim(url, "/"), "/")+1)
}
// pageHref returns the link to the page with the given URL
// from a page with the given base path.
func pageHref(base, url string) string {
if url == "" {
if base == "" {
return "./"
}
return base
}
return base + url + "/"
}
// navJSData is the site navigation data written to nav.js as window.ccSite,
// which is used by content.js for the categories tree and page search.
type navJSData struct {
Name string
Pages []*bcontent.NavPage
Categories []*bcontent.Category
}
// makeNavJS returns the contents of nav.js for the given site.
func makeNavJS(c *config.Config, site *bcontent.Site) ([]byte, error) {
d := &navJSData{Name: c.Name, Categories: site.Categories}
for _, prp := range site.Pages {
d.Pages = append(d.Pages, &bcontent.NavPage{Name: prp.Name, URL: prp.URL})
}
b, err := json.Marshal(d)
if err != nil {
return nil, err
}
return append(append([]byte("window.ccSite = "), b...), ";\n"...), nil
}
// contentTmpl is the template used in [makeContentPage].
var contentTmpl = template.Must(template.New("content.html").Parse(contentHTML))
// contentData is the data passed to [contentTmpl].
type contentData struct {
indexHTMLData
Wasm bool
Lang string
HomeURL string
NavHTML string
PageHTML string
PageJSON string
}
// pageJSData is the page data in each page as window.ccPage,
// which is used by content.js for the table of contents.
type pageJSData struct {
Name string
URL string
TOC []*bcontent.TOCHeading
}
// makeContentPage returns the HTML file for the given page of the site,
// with the given base path to the root of the site. If wasm is true,
// the page loads the Go wasm app (see [makeContentSite]). The given files
// map content files to other paths in the website (see [rebaseURLs]).
func makeContentPage(c *config.Config, site *bcontent.Site, prp *bcontent.PreRenderPage, base string, wasm bool, files map[string]string) ([]byte, error) {
desc := c.About
if prp.Description != "" && (prp.URL != "" || c.About == "") {
desc = strings.TrimSpace(html.UnescapeString(strip.StripTags(prp.Description)))
}
title := prp.Name
if prp.URL == "" { // root page just gets app name, as in content
title = c.Name
}
pj, err := json.Marshal(&pageJSData{Name: prp.Name, URL: prp.URL, TOC: prp.TOC})
if err != nil {
return nil, err
}
d := &contentData{
BasePath: base,
Author: c.Web.Author,
Description: html.EscapeString(desc),
Keywords: c.Web.Keywords,
Title: html.EscapeString(title),
SiteName: html.EscapeString(c.Name),
Image: c.Web.Image,
Styles: c.Web.Styles,
FontText: html.EscapeString(c.Web.FontText),
VanityURL: c.Web.VanityURL,
GithubVanityRepository: c.Web.GithubVanityRepository,
JS: IsJS(c),
Wasm: wasm,
Lang: c.Web.Lang,
HomeURL: pageHref(base, ""),
NavHTML: staticNavHTML(site, prp, base),
PageHTML: rebaseURLs(prp.HTML, base, prp.URL, pageURLs(site), files),
PageJSON: string(pj),
}
b := &bytes.Buffer{}
err = contentTmpl.Execute(b, d)
if err != nil {
return nil, err
}
return b.Bytes(), nil
}
// staticNavHTML returns the static navigation HTML for the given page,
// which is used as a fallback if JavaScript is not available, and which
// also makes all of the pages discoverable by search engines. It is
// replaced by the interactive Vue trees in content.js.
func staticNavHTML(site *bcontent.Site, prp *bcontent.PreRenderPage, base string) string {
var b strings.Builder
b.WriteString(`<div class="cc-static-nav">`)
if len(prp.TOC) > 0 {
b.WriteString(`<ul><li><b>Contents</b><ul>`)
for _, h := range prp.TOC {
fmt.Fprintf(&b, `<li style="margin-left:%dem"><a href="#%s">%s</a></li>`, h.Level-2, html.EscapeString(h.ID), h.Text)
}
b.WriteString(`</ul></li></ul>`)
}
if cats := site.Categories; len(cats) == 1 && cats[0].Name == "Other" && !cats[0].HasPage {
// Without categories, the pages are listed, as the content app does.
fmt.Fprintf(&b, `<ul><li><a href="%s"><b>Pages</b></a><ul>`, pageHref(base, ""))
for _, pg := range cats[0].Pages {
fmt.Fprintf(&b, `<li><a href="%s">%s</a></li>`, pageHref(base, pg.URL), html.EscapeString(pg.Name))
}
b.WriteString(`</ul></li></ul>`)
} else if len(site.Categories) > 0 {
fmt.Fprintf(&b, `<ul><li><a href="%s"><b>Categories</b></a><ul>`, pageHref(base, ""))
for _, cat := range site.Categories {
b.WriteString("<li>")
if cat.HasPage {
fmt.Fprintf(&b, `<a href="%s">%s</a>`, pageHref(base, cat.URL), html.EscapeString(cat.Name))
} else {
b.WriteString(html.EscapeString(cat.Name))
}
b.WriteString("<ul>")
for _, pg := range cat.Pages {
fmt.Fprintf(&b, `<li><a href="%s">%s</a></li>`, pageHref(base, pg.URL), html.EscapeString(pg.Name))
}
b.WriteString("</ul></li>")
}
b.WriteString(`</ul></li></ul>`)
}
b.WriteString(`</div>`)
return b.String()
}
var (
// htmlTagRe matches the start tags of HTML elements with URL attributes.
htmlTagRe = regexp.MustCompile(`<(a|img|source|video|audio|iframe)\b[^>]*>`)
// urlAttrRe matches a URL attribute in an HTML start tag.
urlAttrRe = regexp.MustCompile(`\s(href|src)="([^"]*)"`)
// urlSchemeRe matches URLs that start with a scheme (such as https:).
urlSchemeRe = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9+.-]*:`)
)
// pageURLs returns the set of the URLs of all of the pages in the site.
func pageURLs(site *bcontent.Site) map[string]bool {
urls := map[string]bool{}
for _, prp := range site.Pages {
urls[prp.URL] = true
}
return urls
}
// rebaseURLs updates the relative URLs in the given page HTML, which are
// relative to the root of the content, to be relative to the page with the
// given URL at the given base path. Links to other pages are made to open
// in the same tab, and links to headings in the same page are reduced to
// just the heading fragment. Links to files (such as images or PDFs in the
// content directory) are left as links to the files themselves. A link is to
// a file if it is not one of the given page URLs and it has a file extension.
// The given files map the paths of content files to their paths in the
// website, if they are elsewhere (see [externalContentFiles]).
func rebaseURLs(h, base, pageURL string, pages map[string]bool, files map[string]string) string {
return htmlTagRe.ReplaceAllStringFunc(h, func(tag string) string {
internal := false // a link to a page, which opens in the same tab
tag = urlAttrRe.ReplaceAllStringFunc(tag, func(attr string) string {
sm := urlAttrRe.FindStringSubmatch(attr)
name, u := sm[1], html.UnescapeString(sm[2])
if u == "" && name == "href" { // the root page in content
internal = true
return fmt.Sprintf(` %s="%s"`, name, html.EscapeString(pageHref(base, "")))
}
if u == "" || u[0] == '#' || u[0] == '/' || urlSchemeRe.MatchString(u) {
return attr
}
pg, frag, hasFrag := strings.Cut(u, "#")
pg = strings.TrimSuffix(pg, "/")
if name == "src" || (!pages[pg] && path.Ext(pg) != "") {
if f, ok := files[u]; ok {
u = f
}
return fmt.Sprintf(` %s="%s"`, name, html.EscapeString(base+u))
}
internal = true
if hasFrag {
frag = "#" + frag
if pg == pageURL {
return fmt.Sprintf(` %s="%s"`, name, html.EscapeString(frag))
}
}
return fmt.Sprintf(` %s="%s"`, name, html.EscapeString(pageHref(base, pg)+frag))
})
if internal {
tag = strings.Replace(tag, ` target="_blank"`, "", 1)
}
return tag
})
}
// copyContentFiles copies all of the files in the given content directory
// other than the content pages themselves (such as images) to the
// given output directory, preserving their relative paths, except for
// the given files, which are elsewhere in the output directory.
func copyContentFiles(content, odir string, files map[string]string) error {
if _, err := os.Stat(content); errors.Is(err, fs.ErrNotExist) {
return nil
}
cfs := os.DirFS(content)
return fs.WalkDir(cfs, ".", func(p string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
ext := path.Ext(p)
if _, ok := files[p]; ok || ext == ".md" || ext == ".html" || strings.HasPrefix(path.Base(p), ".") {
return nil
}
b, err := fs.ReadFile(cfs, p)
if err != nil {
return err
}
op := filepath.Join(odir, filepath.FromSlash(p))
err = os.MkdirAll(filepath.Dir(op), 0777)
if err != nil {
return err
}
return os.WriteFile(op, b, 0666)
})
}
// externalContentFiles returns the content files in the given content
// directory that the js app loads as external embedded files from the given
// output directory (see [copyExternalEmbeds]), mapped to their paths there.
// An external file is named by GoScript with the first 16 hexadecimal digits
// of the SHA-256 of its contents and its base name.
func externalContentFiles(content, odir string) map[string]string {
files := map[string]string{}
cfs := os.DirFS(content)
fs.WalkDir(cfs, ".", func(p string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() {
return nil
}
b, err := fs.ReadFile(cfs, p)
if err != nil {
return nil
}
sum := sha256.Sum256(b)
name := hex.EncodeToString(sum[:])[:16] + "-" + path.Base(p)
if _, err := os.Stat(filepath.Join(odir, jsExternalEmbedDir, name)); err == nil {
files[p] = jsExternalEmbedDir + "/" + url.PathEscape(name)
}
return nil
})
return files
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package web
import (
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"cogentcore.org/core/cmd/config"
)
// copyFiles copies the files and directories of [config.Web.Files] (paths
// and glob patterns relative to the directory of the app, the current
// directory) into the website, at the same relative paths.
func copyFiles(c *config.Config) error {
for _, pat := range c.Web.Files {
paths, err := filepath.Glob(pat)
if err != nil {
return fmt.Errorf("web files: %w", err)
}
if len(paths) == 0 {
return fmt.Errorf("web files: no files match %q", pat)
}
for _, p := range paths {
if filepath.IsAbs(p) || !filepath.IsLocal(p) {
return fmt.Errorf("web files: %q is not within the directory of the app", p)
}
if err := copyTree(p, filepath.Join(c.Build.Output, p)); err != nil {
return fmt.Errorf("web files: %w", err)
}
}
}
return nil
}
// copyTree copies the file or directory src to dst, replacing the files
// that are there.
func copyTree(src, dst string) error {
return filepath.WalkDir(src, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
rel, err := filepath.Rel(src, path)
if err != nil {
return err
}
to := filepath.Join(dst, rel)
if d.IsDir() {
return os.MkdirAll(to, 0777)
}
return copyFile(path, to)
})
}
// copyFile copies the file src to dst, making the directory of dst.
func copyFile(src, dst string) error {
if err := os.MkdirAll(filepath.Dir(dst), 0777); err != nil {
return err
}
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
out, err := os.Create(dst)
if err != nil {
return err
}
if _, err := io.Copy(out, in); err != nil {
out.Close()
return err
}
return out.Close()
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package web
import (
"bytes"
"errors"
"io/fs"
"os"
"cogentcore.org/core/content/bcontent"
"github.com/yuin/goldmark/v2/extension"
"github.com/yuin/goldmark/v2/parser"
"github.com/yuin/goldmark/v2/renderer/html"
)
// readIndexPage returns the HTML for the optional custom index page of the app,
// which is an index.html file or an index.md file (converted from markdown) in
// the app directory, with index.html taking precedence. It replaces the
// automatically pre-rendered HTML preview of the root page in the generated
// index.html file (see [makeIndexHTML]). The result is an HTML fragment that is
// placed inside of the app loader element, not a complete HTML document, so that
// the app keeps loading in the background while the user reads it. It returns ""
// if the app does not have a custom index page.
func readIndexPage() (string, error) {
b, err := os.ReadFile("index.html")
if err == nil {
return string(b), nil
}
if !errors.Is(err, fs.ErrNotExist) {
return "", err
}
// [bcontent.Page.ReadContent] removes any TOML front matter, which is
// ignored here but supported so that content pages can be used directly.
pg := &bcontent.Page{Source: os.DirFS("."), Filename: "index.md"}
b, err = pg.ReadContent(nil)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return "", nil
}
return "", err
}
return string(mdToHTML(b)), nil
}
// mdToHTML converts the given markdown to HTML for a custom index page (see
// [readIndexPage]). Unlike [htmlcore.MDToHTML], this is a plain markdown
// conversion without support for Cogent Core extensions such as wikilinks,
// since those require the GUI packages, which the build tool can not import.
func mdToHTML(md []byte) []byte {
var buf bytes.Buffer
p := parser.New(parser.WithExtensions(extension.NewGFMParser()), parser.WithAutoHeadingID(), parser.WithAttribute())
r := html.New(html.WithUnsafe(), html.WithExtensions(extension.NewGFMHTMLRenderer()))
r.Render(&buf, md, p.Parse(md))
return buf.Bytes()
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package web
import (
"errors"
"fmt"
"go/ast"
"go/parser"
"go/token"
"io/fs"
"maps"
"os"
"path/filepath"
"strings"
"cogentcore.org/core/base/exec"
"cogentcore.org/core/cmd/config"
)
// IsJS returns whether the given configuration is building for the js
// platform, which compiles the app to JavaScript using GoScript
// (https://github.com/s4wave/goscript) instead of to WebAssembly.
// Otherwise, the js platform produces the same static website as web.
func IsJS(c *config.Config) bool {
return len(c.Build.Target) > 0 && c.Build.Target[0].OS == "js"
}
// jsTSConfig is the tsconfig.json used for bundling the GoScript output,
// which maps the @goscript imports to the compiled output.
const jsTSConfig = `{
"compilerOptions": {
"target": "ES2022", "module": "ESNext", "moduleResolution": "Bundler",
"lib": ["ESNext", "DOM"], "strict": true, "allowImportingTsExtensions": true, "noEmit": true,
"paths": { "@goscript/*": ["./output/@goscript/*"] }
},
"include": ["entry.ts"]
}
`
// buildJS builds the app in the current directory to JavaScript using
// GoScript, bundling it into app.gs.js in the output directory with bun.
func buildJS(c *config.Config) error {
// GoScript and bun are installed automatically if they are not found.
err := ensureJSTools()
if err != nil {
return err
}
tags := "goscript," + JSTags
if c.Build.Debug {
tags += ",debug"
}
pkg, mainFile, err := jsMainPackage(tags)
if err != nil {
return err
}
work, err := jsWorkDir(pkg)
if err != nil {
return err
}
output := filepath.Join(work, "output")
err = os.RemoveAll(output)
if err != nil {
return err
}
// Dead code elimination leaves the functions and methods that the
// program can never call out of the bundle (unless the environment
// already sets GOSCRIPT_ELIMINATE_DEAD_CODE, such as to 0 to turn it off).
// Versions of goscript without it ignore the variable.
gs := exec.Major()
gs.Env = maps.Clone(gs.Env)
if gs.Env == nil {
gs.Env = map[string]string{}
}
if _, ok := os.LookupEnv("GOSCRIPT_ELIMINATE_DEAD_CODE"); !ok {
gs.Env["GOSCRIPT_ELIMINATE_DEAD_CODE"] = "1"
}
for k, v := range jsExternalEmbedEnv() {
if _, ok := os.LookupEnv(k); !ok {
gs.Env[k] = v
}
}
gsArgs := []string{"compile", "-p", ".", "--output", output, "-b", "-tags=" + tags}
overrides, err := jsOverrideDirs(tags)
if err != nil {
return err
}
for _, dir := range overrides {
gsArgs = append(gsArgs, "--gs-path", dir)
}
for _, f := range c.Web.DeferredFunctions {
gsArgs = append(gsArgs, "--deferred-function", f)
}
err = gs.Run("goscript", gsArgs...)
if err != nil {
return fmt.Errorf("error compiling with goscript: %w", err)
}
// The dependencies are installed again when the package.json changes,
// so that a cached work directory gets newly added dependencies.
// They are those of the package.json of GoScript, so that they always
// match its runtime.
gsm, err := goscriptPackageJSON()
if err != nil {
return err
}
pkgData, err := jsPackageJSON(gsm)
if err != nil {
return err
}
pkgJSON := filepath.Join(work, "package.json")
oldPkgJSON, _ := os.ReadFile(pkgJSON)
install := string(oldPkgJSON) != string(pkgData)
err = os.WriteFile(pkgJSON, pkgData, 0666)
if err != nil {
return err
}
err = os.WriteFile(filepath.Join(work, "tsconfig.json"), []byte(jsTSConfig), 0666)
if err != nil {
return err
}
entry := fmt.Sprintf("import { main } from %q\n\nawait main()\n", "@goscript/"+pkg+"/"+mainFile+".gs.ts")
err = os.WriteFile(filepath.Join(work, "entry.ts"), []byte(entry), 0666)
if err != nil {
return err
}
if _, err := os.Stat(filepath.Join(work, "node_modules")); err != nil || install {
err = exec.Major().SetDir(work).Run("bun", "install")
if err != nil {
return err
}
}
args := []string{"build", "entry.ts", "--target", "browser", "--format", "esm"}
err = removeJSChunks(c.Build.Output)
if err != nil {
return err
}
if len(c.Web.DeferredFunctions) > 0 {
// The deferred functions are dynamic imports, each in its own chunk.
args = append(args, "--splitting", "--outdir", c.Build.Output, "--entry-naming", "app.gs.js", "--chunk-naming", jsChunkPrefix+"[hash].js")
} else {
args = append(args, "--outfile", filepath.Join(c.Build.Output, "app.gs.js"))
}
if !c.Build.Debug {
// Full minification puts many statements on one line, which is fine
// for tree.AutoPlanName, since its //goscript:callsite directive makes
// GoScript pass it the Go file and line of each call.
args = append(args, "--minify")
}
err = exec.Major().SetDir(work).Run("bun", args...)
if err != nil {
return fmt.Errorf("error bundling with bun: %w", err)
}
err = copyExternalEmbeds(output, c.Build.Output)
if err != nil {
return err
}
return finishBuild(c)
}
// jsChunkPrefix is the prefix of the names of the files of the bundle other
// than app.gs.js: the chunks of [config.Web.DeferredFunctions].
const jsChunkPrefix = "app.gs.chunk-"
// removeJSChunks removes the chunk files of an earlier build from the given
// build output directory.
func removeJSChunks(odir string) error {
for _, f := range jsChunkFiles(odir) {
err := os.Remove(filepath.Join(odir, f))
if err != nil {
return err
}
}
return nil
}
// jsChunkFiles returns the names of the chunk files of the bundle in the
// given build output directory (see [jsChunkPrefix]).
func jsChunkFiles(odir string) []string {
entries, _ := os.ReadDir(odir)
var files []string
for _, e := range entries {
if !e.IsDir() && strings.HasPrefix(e.Name(), jsChunkPrefix) && strings.HasSuffix(e.Name(), ".js") {
files = append(files, e.Name())
}
}
return files
}
// jsExternalEmbedPatterns are the base name patterns of the embedded files of
// embed.FS variables that GoScript writes as separate files, which the app
// fetches when it first opens them, instead of into the bundle: media files,
// such as the images of a content site, which are only needed when a page
// shows them, and which do not compress well, so that they would make the
// download of the bundle much larger.
var jsExternalEmbedPatterns = []string{
"*.png", "*.jpg", "*.jpeg", "*.gif", "*.webp", "*.avif", "*.bmp", "*.ico", "*.svg",
"*.mp3", "*.wav", "*.ogg", "*.mp4", "*.webm", "*.pdf",
}
// jsExternalEmbedMinSize is the size from which a file that matches
// [jsExternalEmbedPatterns] is external; smaller files are not worth a request.
const jsExternalEmbedMinSize = 8 << 10
// jsExternalEmbedDir is the directory of the external embedded files, which
// GoScript writes beside the output of each package and the app loads from
// beside app.gs.js, so they are all copied into it in the output directory.
const jsExternalEmbedDir = "@embed"
// jsExternalEmbedEnv returns the GoScript environment variables that select
// the external embedded files (see [jsExternalEmbedPatterns]), unless the
// environment already sets them. Versions of goscript without them ignore
// them, and then inline all files as before.
func jsExternalEmbedEnv() map[string]string {
return map[string]string{
"GOSCRIPT_EXTERNAL_EMBED": strings.Join(jsExternalEmbedPatterns, ","),
"GOSCRIPT_EXTERNAL_EMBED_MIN_SIZE": fmt.Sprint(jsExternalEmbedMinSize),
}
}
// copyExternalEmbeds copies the external embedded files in the GoScript output
// directory (see [jsExternalEmbedDir]) into the given build output directory.
func copyExternalEmbeds(output, odir string) error {
dst := filepath.Join(odir, jsExternalEmbedDir)
err := os.RemoveAll(dst)
if err != nil {
return err
}
return filepath.WalkDir(output, func(p string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() || filepath.Base(filepath.Dir(p)) != jsExternalEmbedDir {
return err
}
b, err := os.ReadFile(p)
if err != nil {
return err
}
err = os.MkdirAll(dst, 0777)
if err != nil {
return err
}
return os.WriteFile(filepath.Join(dst, d.Name()), b, 0666)
})
}
// externalEmbedFiles returns the paths of the external embedded files in the
// given build output directory (see [jsExternalEmbedDir]), relative to it.
func externalEmbedFiles(odir string) []string {
entries, _ := os.ReadDir(filepath.Join(odir, jsExternalEmbedDir))
var files []string
for _, e := range entries {
if !e.IsDir() {
files = append(files, jsExternalEmbedDir+"/"+e.Name())
}
}
return files
}
// jsMainPackage returns the import path of the main package in the current
// directory for GoScript with the given build tags, and the name of the file
// (without the .go extension) that contains its main function.
func jsMainPackage(tags string) (pkg, mainFile string, err error) {
out, err := exec.Minor().SetEnv("GOOS", "js").SetEnv("GOARCH", "wasm").
Output("go", "list", "-tags", tags, "-f", "{{.ImportPath}}{{range .GoFiles}} {{.}}{{end}}", ".")
if err != nil {
return "", "", err
}
fields := strings.Fields(out)
if len(fields) == 0 {
return "", "", errors.New("no Go package found in the current directory")
}
fset := token.NewFileSet()
for _, fn := range fields[1:] {
f, err := parser.ParseFile(fset, fn, nil, parser.SkipObjectResolution)
if err != nil {
return "", "", err
}
if f.Name.Name != "main" {
return "", "", fmt.Errorf("package %s is not a main package", fields[0])
}
for _, d := range f.Decls {
if fd, ok := d.(*ast.FuncDecl); ok && fd.Recv == nil && fd.Name.Name == "main" {
return fields[0], strings.TrimSuffix(fn, ".go"), nil
}
}
}
return "", "", fmt.Errorf("no main function found in package %s", fields[0])
}
// JSTags are the build tags (besides goscript) that apps are built with
// for the js platform, and that core test js uses.
// The mvmnosrc tag leaves the standard library sources out of the mvm
// interpreter (mvmcore), which only runs code using the packages bound
// to it, so that it adds much less to the bundle.
const JSTags = "purego,noasm,mvmnosrc"
// jsOverrideDirs returns the GoScript override directories of the modules
// that the package in the current directory depends on: a module provides
// GoScript overrides of its packages, the TypeScript implementations that
// GoScript compiles in place of their Go code, in a gsoverride directory at
// its root, laid out by import path (such as the mvm interpreter in
// github.com/cogentcore/mvm). GoScript is given each of them with --gs-path.
func jsOverrideDirs(tags string) ([]string, error) {
out, err := exec.Minor().SetEnv("GOOS", "js").SetEnv("GOARCH", "wasm").
Output("go", "list", "-deps", "-tags", tags, "-f", "{{with .Module}}{{.Dir}}{{end}}", ".")
if err != nil {
return nil, err
}
var dirs []string
seen := map[string]bool{}
for dir := range strings.SplitSeq(out, "\n") {
dir = strings.TrimSpace(dir)
if dir == "" || seen[dir] {
continue
}
seen[dir] = true
gs := filepath.Join(dir, "gsoverride")
if info, err := os.Stat(gs); err == nil && info.IsDir() {
dirs = append(dirs, gs)
}
}
return dirs, nil
}
// jsWorkDir returns the directory in the user cache directory that is used
// for compiling and bundling the given package with GoScript, creating it
// if it does not already exist. The CORE_JS_WORK_DIR environment variable
// sets another directory, such as for builds of the same package from
// several worktrees.
func jsWorkDir(pkg string) (string, error) {
if dir := os.Getenv("CORE_JS_WORK_DIR"); dir != "" {
return dir, os.MkdirAll(dir, 0777)
}
cache, err := os.UserCacheDir()
if err != nil {
return "", err
}
dir := filepath.Join(cache, "cogentcore", "goscript", filepath.FromSlash(pkg))
return dir, os.MkdirAll(dir, 0777)
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package web
import (
"debug/buildinfo"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"cogentcore.org/core/base/exec"
)
// GoscriptModule is the Go module of the GoScript compiler.
const GoscriptModule = "github.com/s4wave/goscript"
// goscriptManifest is the part of the package.json of GoScript that the js
// platform uses: the dependencies are the npm packages that the GoScript
// runtime imports, which the bundle needs, and the development
// dependencies have the version of tsrs that goscript test uses.
type goscriptManifest struct {
Dependencies map[string]string `json:"dependencies"`
DevDependencies map[string]string `json:"devDependencies"`
}
// goscriptPackageJSON returns the package.json of the installed goscript
// command, which comes from the source of its module, so that the npm
// dependencies always match the GoScript runtime in the compiled output.
func goscriptPackageJSON() (*goscriptManifest, error) {
// The module source is found from the build info of the command.
bin := ToolPath("goscript")
if bin == "" {
return nil, errors.New("goscript is not installed")
}
dir, err := goscriptModuleDir(bin)
if err != nil {
return nil, err
}
// Its package.json lists the npm packages of the runtime.
data, err := os.ReadFile(filepath.Join(dir, "package.json"))
if err != nil {
return nil, fmt.Errorf("reading the GoScript package.json: %w", err)
}
m := &goscriptManifest{}
if err := json.Unmarshal(data, m); err != nil {
return nil, fmt.Errorf("parsing the GoScript package.json in %s: %w", dir, err)
}
return m, nil
}
// goscriptModuleDir returns the source directory of the GoScript module that
// the given goscript command was built from. A released version is found in
// the module cache, downloading it if needed. A command built from a local
// checkout has no released version, so the module is then looked up in the
// current Go module or workspace, which normally has that checkout.
func goscriptModuleDir(bin string) (string, error) {
info, err := buildinfo.ReadFile(bin)
if err != nil {
return "", fmt.Errorf("reading the build info of %s: %w", bin, err)
}
version := info.Main.Version
var downloadErr error
if version != "" && version != "(devel)" && !strings.Contains(version, "+dirty") {
dir, err := goModuleDir(os.TempDir(), "download", GoscriptModule+"@"+version)
if err == nil {
return dir, nil
}
downloadErr = err
}
dir, err := goModuleDir("", "list", GoscriptModule)
if err == nil {
return dir, nil
}
return "", fmt.Errorf("could not find the source of GoScript %s, which has the npm dependencies of its runtime in its package.json (install a released version with go install %s@latest): %w", version, GoscriptPackage, errors.Join(downloadErr, err))
}
// goModuleDir returns the source directory of the given module from the
// JSON output of go mod download (cmd "download") or go list -m (cmd "list"),
// run in the given directory ("" for the current one).
func goModuleDir(dir, cmd, module string) (string, error) {
args := []string{"mod", "download", "-json", module}
if cmd == "list" {
args = []string{"list", "-m", "-json", module}
}
ec := exec.Silent()
if dir != "" {
ec = ec.SetDir(dir)
}
out, err := ec.Output("go", args...)
var mod struct {
Dir string
Error any
}
if jerr := json.Unmarshal([]byte(out), &mod); jerr == nil && mod.Error != nil {
return "", fmt.Errorf("go %s: %v", strings.Join(args, " "), mod.Error)
}
if err != nil {
return "", fmt.Errorf("go %s: %w", strings.Join(args, " "), err)
}
if mod.Dir == "" {
return "", fmt.Errorf("go %s: no module directory", strings.Join(args, " "))
}
return mod.Dir, nil
}
// jsPackageJSON returns the package.json used for bundling the GoScript
// output, which has the npm dependencies of the given GoScript package.json.
func jsPackageJSON(m *goscriptManifest) ([]byte, error) {
b, err := json.Marshal(struct {
Type string `json:"type"`
Private bool `json:"private"`
Dependencies map[string]string `json:"dependencies,omitempty"`
}{"module", true, m.Dependencies})
if err != nil {
return nil, err
}
return append(b, '\n'), nil
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package web
import (
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
"cogentcore.org/core/base/exec"
"cogentcore.org/core/base/logx"
)
// GoscriptPackage is the Go package of the GoScript compiler command.
const GoscriptPackage = "github.com/s4wave/goscript/cmd/goscript"
// ensureJSTools makes sure that the goscript and bun commands that the js
// platform needs are available, installing them if they are not. GoScript is
// installed with go install, and bun with its official install script for
// the current platform. The directories they are installed into are added
// to the PATH of this process, so that they can be run right away.
func ensureJSTools() error {
err := ensureTool("goscript", goBinDirs(), installGoscript)
if err != nil {
return err
}
return ensureTool("bun", bunBinDirs(), installBun)
}
// SetupJS installs the tools of the js platform that are not installed:
// GoScript and bun, which build apps to JavaScript, and tsrs, which
// goscript test type checks the compiled code with (core build js does
// not need it, as bun only strips the types).
func SetupJS() error {
if err := ensureJSTools(); err != nil {
return err
}
return ensureTool("tsrs", bunBinDirs(), installTsrs)
}
// installTsrs installs tsrs globally with bun, which puts it in the bin
// directory of bun. Its version is that of the development dependencies in
// the package.json of GoScript, which is what goscript test uses.
func installTsrs() error {
gsm, err := goscriptPackageJSON()
if err != nil {
return err
}
version := gsm.DevDependencies["tsrs"]
if version == "" {
return errors.New("the GoScript package.json has no tsrs development dependency")
}
return exec.Verbose().SetBuffer(false).Run("bun", "add", "-g", "tsrs@"+version)
}
// ensureTool makes sure that the given tool can be found on the PATH. If it
// is not on the PATH, but is in one of the given directories where it is
// normally installed, that directory is added to the PATH. Otherwise, the
// tool is installed with install and looked for again.
func ensureTool(tool string, dirs []string, install func() error) error {
if _, err := exec.LookPath(tool); err == nil {
return nil
}
// The tool may be installed in a directory that is not on the PATH.
if addToolDir(tool, dirs) {
return nil
}
// Otherwise, it is installed and must then be found.
logx.PrintlnWarn("installing " + tool + ", which the js platform needs")
err := install()
if err != nil {
return fmt.Errorf("error installing %s: %w", tool, err)
}
if _, err := exec.LookPath(tool); err == nil || addToolDir(tool, dirs) {
return nil
}
return fmt.Errorf("installed %s, but could not find it in %s", tool, strings.Join(dirs, ", "))
}
// ToolPath returns the path of the given tool that the js platform uses
// (goscript or bun), on the PATH or in the directory it is normally installed
// in, or "" if it is not installed.
func ToolPath(tool string) string {
if path, err := exec.LookPath(tool); err == nil {
return path
}
dirs := goBinDirs()
if tool == "bun" {
dirs = bunBinDirs()
}
if runtime.GOOS == "windows" {
tool += ".exe"
}
for _, dir := range dirs {
path := filepath.Join(dir, tool)
if _, err := os.Stat(path); err == nil {
return path
}
}
return ""
}
// addToolDir adds the first of the given directories that contains the
// given tool to the PATH of this process, and returns whether it found one.
func addToolDir(tool string, dirs []string) bool {
name := tool
if runtime.GOOS == "windows" {
name += ".exe"
}
for _, dir := range dirs {
if _, err := os.Stat(filepath.Join(dir, name)); err != nil {
continue
}
path := dir + string(os.PathListSeparator) + os.Getenv("PATH")
os.Setenv("PATH", path)
return true
}
return false
}
// goBinDirs returns the directories that go install puts commands in:
// GOBIN if it is set, and otherwise the bin directory of GOPATH.
func goBinDirs() []string {
if gobin := goEnv("GOBIN"); gobin != "" {
return []string{gobin}
}
if gopath := goEnv("GOPATH"); gopath != "" {
return []string{filepath.Join(strings.Split(gopath, string(os.PathListSeparator))[0], "bin")}
}
return nil
}
// goEnv returns the value of the given go env variable, or "" if it is
// not set or go env fails.
func goEnv(name string) string {
value, err := exec.Silent().Output("go", "env", name)
if err != nil {
return ""
}
return strings.TrimSpace(value)
}
// bunBinDirs returns the directories that bun's install script puts bun in:
// the bin directory of BUN_INSTALL if it is set, and otherwise ~/.bun/bin.
func bunBinDirs() []string {
if bi := os.Getenv("BUN_INSTALL"); bi != "" {
return []string{filepath.Join(bi, "bin")}
}
home, err := os.UserHomeDir()
if err != nil {
return nil
}
return []string{filepath.Join(home, ".bun", "bin")}
}
// installGoscript installs the latest GoScript compiler with go install.
func installGoscript() error {
return exec.Verbose().SetBuffer(false).Run("go", "install", GoscriptPackage+"@latest")
}
// installBun installs bun with its official install script: a shell script
// on macOS and Linux, and a PowerShell script on Windows.
func installBun() error {
vc := exec.Verbose().SetBuffer(false)
if runtime.GOOS == "windows" {
return vc.Run("powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", "irm bun.sh/install.ps1 | iex")
}
return vc.Run("bash", "-c", "curl -fsSL https://bun.sh/install | bash")
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package web
import (
"bytes"
"compress/gzip"
"mime"
"net/http"
"os"
"path"
"path/filepath"
"slices"
"strconv"
"strings"
"sync"
"time"
"cogentcore.org/core/base/logx"
"cogentcore.org/core/cmd/config"
)
// Serve serves the build output directory on the default network address at the config port.
// Text files and the app bundle are served compressed with gzip, as static
// site hosts do, so that the download sizes are the same as when deployed.
func Serve(c *config.Config) error {
hfs := http.FileServer(http.Dir(c.Build.Output))
gz := &gzipCache{}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
trim := strings.Trim(r.URL.Path, "/")
status := http.StatusOK
info, err := os.Stat(filepath.Join(c.Build.Output, trim))
if err != nil {
r.URL.Path = "/404.html"
trim = "404.html"
status = http.StatusNotFound
}
if trim == "app.wasm" {
w.Header().Set("Content-Type", "application/wasm")
}
if c.Web.Gzip && slices.Contains(bundleFiles(c), trim) {
// The bundle files are already compressed (see [processBundle]).
// The file server does not set the Content-Length of an encoded
// response, which the app loader uses to show progress.
w.Header().Set("Content-Encoding", "gzip")
if r.Header.Get("Range") == "" {
w.Header().Set("Content-Length", strconv.FormatInt(info.Size(), 10))
}
} else if serveGzip(w, r, gz, c.Build.Output, trim, status) {
return
}
if status != http.StatusOK {
w.WriteHeader(status)
}
hfs.ServeHTTP(w, r)
})
logx.PrintlnWarn("Serving at http://localhost:" + c.Web.Port)
return http.ListenAndServe(":"+c.Web.Port, nil)
}
// gzipExts are the extensions of the files that [serveGzip] compresses.
var gzipExts = []string{".html", ".js", ".css", ".json", ".wasm", ".webmanifest", ".svg", ".txt", ".md"}
// serveGzip serves the file at the given path relative to the given
// directory compressed with gzip with the given status, if the request
// accepts gzip and the file is one that compresses well (see [gzipExts]).
// The path of a directory serves its index.html. It returns whether it
// served the file.
func serveGzip(w http.ResponseWriter, r *http.Request, gz *gzipCache, dir, name string, status int) bool {
if r.Method != http.MethodGet && r.Method != http.MethodHead {
return false
}
// Ranges are of the uncompressed file, which the file server handles.
if !acceptsGzip(r.Header.Get("Accept-Encoding")) || r.Header.Get("Range") != "" {
return false
}
fn := filepath.Join(dir, filepath.FromSlash(name))
info, err := os.Stat(fn)
if err != nil {
return false
}
if info.IsDir() {
// The file server redirects a directory without a trailing slash.
if name != "" && !strings.HasSuffix(r.URL.Path, "/") {
return false
}
fn = filepath.Join(fn, "index.html")
info, err = os.Stat(fn)
if err != nil {
return false
}
}
ext := path.Ext(fn)
if !slices.Contains(gzipExts, ext) {
return false
}
b, err := gz.get(fn, info)
if err != nil {
return false
}
h := w.Header()
if h.Get("Content-Type") == "" {
ct := mime.TypeByExtension(ext)
if ct == "" {
ct = "application/octet-stream"
}
h.Set("Content-Type", ct)
}
h.Set("Content-Encoding", "gzip")
h.Add("Vary", "Accept-Encoding")
// The app loader shows download progress with the Content-Length, which
// ServeContent does not set for an encoded response.
h.Set("Content-Length", strconv.Itoa(len(b)))
if status != http.StatusOK {
w.WriteHeader(status)
if r.Method != http.MethodHead {
w.Write(b)
}
return true
}
http.ServeContent(w, r, fn, info.ModTime(), bytes.NewReader(b))
return true
}
// gzipCache is a cache of the files compressed by [serveGzip], so that each
// version of a file is only compressed once.
type gzipCache struct {
mu sync.Mutex
files map[string]*gzipFile
}
// gzipFile is a file compressed with gzip in a [gzipCache].
type gzipFile struct {
// ModTime and Size are those of the file that was compressed.
ModTime time.Time
Size int64
// Data is the compressed file.
Data []byte
}
// get returns the compressed contents of the file with the given name
// and info, compressing it if it is not in the cache.
func (gc *gzipCache) get(name string, info os.FileInfo) ([]byte, error) {
gc.mu.Lock()
defer gc.mu.Unlock()
if f, ok := gc.files[name]; ok && f.ModTime.Equal(info.ModTime()) && f.Size == info.Size() {
return f.Data, nil
}
b, err := os.ReadFile(name)
if err != nil {
return nil, err
}
gz, err := gzipBytes(b, gzip.DefaultCompression)
if err != nil {
return nil, err
}
if gc.files == nil {
gc.files = map[string]*gzipFile{}
}
gc.files[name] = &gzipFile{ModTime: info.ModTime(), Size: info.Size(), Data: gz}
return gz, nil
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package web
import (
"bytes"
"encoding/json"
"html"
"log/slog"
"net/url"
"os"
"regexp"
"slices"
"strings"
"text/template"
"cogentcore.org/core/base/elide"
"cogentcore.org/core/cmd/config"
"cogentcore.org/core/content/bcontent"
strip "github.com/grokify/html-strip-tags-go"
)
// appJSTmpl is the template used in [makeAppJS] to build the app.js file
var appJSTmpl = template.Must(template.New("app.js").Parse(appJS))
// appJSData is the data passed to [appJSTmpl]
type appJSData struct {
Env string
WasmContentLengthHeader string
AutoUpdateInterval int64
// JS is whether the app is compiled to JavaScript with GoScript
// (the js platform) instead of to WebAssembly.
JS bool
}
// makeAppJS exectues [appJSTmpl] based on the given configuration information.
func makeAppJS(c *config.Config) ([]byte, error) {
if c.Web.Env == nil {
c.Web.Env = make(map[string]string)
}
c.Web.Env["GOAPP_STATIC_RESOURCES_URL"] = "/"
c.Web.Env["GOAPP_ROOT_PREFIX"] = "."
for k, v := range c.Web.Env {
if err := os.Setenv(k, v); err != nil {
slog.Error("setting app env variable failed", "name", k, "value", v, "err", err)
}
}
wenv, err := json.Marshal(c.Web.Env)
if err != nil {
return nil, err
}
d := appJSData{
Env: string(wenv),
WasmContentLengthHeader: c.Web.WasmContentLengthHeader,
AutoUpdateInterval: c.Web.AutoUpdateInterval.Milliseconds(),
JS: IsJS(c),
}
b := &bytes.Buffer{}
err = appJSTmpl.Execute(b, d)
if err != nil {
return nil, err
}
return b.Bytes(), nil
}
// appWorkerJSData is the data passed to [config.Config.Web.ServiceWorkerTemplate]
type appWorkerJSData struct {
Version string
ResourcesToCache string
ExternalResourcesToCache string
CacheOrigins string
}
// makeAppWorkerJS executes [config.Config.Web.ServiceWorkerTemplate]. If it empty, it
// sets it to [appWorkerJS]. The service worker caches the files of the app
// for offline use, including those of the website of a content app if
// content is true (see [makeContentSite]).
func makeAppWorkerJS(c *config.Config, content bool) ([]byte, error) {
resources := []string{
"./",
"index.html",
"app.css",
"app.js",
"manifest.webmanifest",
"icons/32.png",
"icons/192.png",
"icons/svg.svg",
}
if IsJS(c) {
resources = append(resources, "app.gs.js")
resources = append(resources, jsChunkFiles(c.Build.Output)...)
resources = append(resources, externalEmbedFiles(c.Build.Output)...)
} else {
resources = append(resources, "app.wasm", "wasm_exec.js")
}
external := externalResources(indexHTML)
if content {
resources = append(resources, "content.css", "content.js", "nav.js")
external = append(external, externalResources(contentHTML)...)
}
external = append(external, c.Web.Styles...)
slices.Sort(external)
external = slices.Compact(external)
origins := []string{}
for _, r := range external {
u, err := url.Parse(r)
if err != nil || u.Host == "" {
continue
}
origins = append(origins, u.Scheme+"://"+u.Host)
}
// Google Fonts stylesheets load their fonts from this other origin.
origins = append(origins, "https://fonts.gstatic.com")
slices.Sort(origins)
origins = slices.Compact(origins)
tmpl, err := template.New("app-worker.js").Parse(appWorkerJS)
if err != nil {
return nil, err
}
d := appWorkerJSData{Version: c.Version}
for _, v := range []struct {
dst *string
src []string
}{{&d.ResourcesToCache, resources}, {&d.ExternalResourcesToCache, external}, {&d.CacheOrigins, origins}} {
b, err := json.Marshal(v.src)
if err != nil {
return nil, err
}
*v.dst = string(b)
}
b := &bytes.Buffer{}
err = tmpl.Execute(b, d)
if err != nil {
return nil, err
}
return b.Bytes(), nil
}
var (
// externalTagRe matches the link and script start tags in an HTML template.
externalTagRe = regexp.MustCompile(`<(?:link|script)\b[^>]*>`)
// externalURLRe matches a URL from another origin in a link or script tag,
// with the URL as its first submatch.
externalURLRe = regexp.MustCompile(`\s(?:href|src)="(https://[^"{]+)"`)
)
// externalResources returns the URLs of the stylesheets and scripts from
// other origins (CDNs) that the given HTML template loads.
func externalResources(tmpl string) []string {
var urls []string
for _, tag := range externalTagRe.FindAllString(tmpl, -1) {
if strings.HasPrefix(tag, "<link") && !strings.Contains(tag, `rel="stylesheet"`) {
continue
}
m := externalURLRe.FindStringSubmatch(tag)
if m != nil {
urls = append(urls, m[1])
}
}
return urls
}
// manifestJSONTmpl is the template used in [makeManifestJSON] to build the mainfest.webmanifest file
var manifestJSONTmpl = template.Must(template.New("manifest.webmanifest").Parse(manifestJSON))
// manifestJSONData is the data passed to [manifestJSONTmpl]
type manifestJSONData struct {
ShortName string
Name string
Description string
}
// makeManifestJSON exectues [manifestJSONTmpl] based on the given configuration information.
func makeManifestJSON(c *config.Config) ([]byte, error) {
d := manifestJSONData{
ShortName: elide.AppName(c.Name),
Name: c.Name,
Description: c.About,
}
b := &bytes.Buffer{}
err := manifestJSONTmpl.Execute(b, d)
if err != nil {
return nil, err
}
return b.Bytes(), nil
}
// indexHTMLTmpl is the template used in [makeIndexHTML] to build the index.html file
var indexHTMLTmpl = template.Must(template.New("index.html").Parse(indexHTML))
// indexHTMLData is the data passed to [indexHTMLTmpl]
type indexHTMLData struct {
BasePath string
Author string
Description string
Keywords []string
Title string
SiteName string
Image string
Styles []string
FontText string
VanityURL string
GithubVanityRepository string
PreRenderHTML string
IndexPage string
// JS is whether the app is compiled to JavaScript with GoScript
// (the js platform), in which case wasm_exec.js is not needed.
JS bool
}
// makeIndexHTML exectues [indexHTMLTmpl] based on the given configuration information,
// base path for app resources (used in [makePages]), optional title (used in [makePages],
// defaults to [config.Config.Name] otherwise), optional page-specific description (used
// in [makePages], defaults to [config.Config.About]), and pre-render HTML representation
// of app content. If indexPage is non-empty, it is the HTML for the custom index page
// of the app (see [readIndexPage]), which is used instead of the pre-render HTML.
func makeIndexHTML(c *config.Config, basePath string, prp *bcontent.PreRenderPage, indexPage string) ([]byte, error) {
if prp.Description == "" {
prp.Description = c.About
} else {
// c.About is already stripped earlier, so only necessary
// for page-specific description here.
prp.Description = strip.StripTags(prp.Description)
}
d := indexHTMLData{
BasePath: basePath,
Author: c.Web.Author,
Description: prp.Description,
Keywords: c.Web.Keywords,
Title: prp.Name,
SiteName: c.Name,
Image: c.Web.Image,
Styles: c.Web.Styles,
FontText: html.EscapeString(c.Web.FontText),
VanityURL: c.Web.VanityURL,
GithubVanityRepository: c.Web.GithubVanityRepository,
PreRenderHTML: prp.HTML,
IndexPage: indexPage,
JS: IsJS(c),
}
b := &bytes.Buffer{}
err := indexHTMLTmpl.Execute(b, d)
if err != nil {
return nil, err
}
return b.Bytes(), nil
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package colors
import (
"image/color"
"cogentcore.org/core/colors/cam/hct"
"cogentcore.org/core/colors/matcolor"
)
// Based on matcolor/accent.go
// ToBase returns the base accent color for the given color
// based on the current scheme (light or dark), which is
// typically used for high emphasis objects or text.
func ToBase(c color.Color) color.RGBA {
if matcolor.SchemeIsDark {
return hct.FromColor(c).WithTone(80).AsRGBA()
}
return hct.FromColor(c).WithTone(40).AsRGBA()
}
// ToOn returns the accent color for the given color
// that should be placed on top of [ToBase] based on
// the current scheme (light or dark).
func ToOn(c color.Color) color.RGBA {
if matcolor.SchemeIsDark {
return hct.FromColor(c).WithTone(20).AsRGBA()
}
return hct.FromColor(c).WithTone(100).AsRGBA()
}
// ToContainer returns the container accent color for the given color
// based on the current scheme (light or dark), which is
// typically used for lower emphasis content.
func ToContainer(c color.Color) color.RGBA {
if matcolor.SchemeIsDark {
return hct.FromColor(c).WithTone(30).AsRGBA()
}
return hct.FromColor(c).WithTone(90).AsRGBA()
}
// ToOnContainer returns the accent color for the given color
// that should be placed on top of [ToContainer] based on
// the current scheme (light or dark).
func ToOnContainer(c color.Color) color.RGBA {
if matcolor.SchemeIsDark {
return hct.FromColor(c).WithTone(90).AsRGBA()
}
return hct.FromColor(c).WithTone(10).AsRGBA()
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package colors
import (
"image/color"
"log/slog"
"cogentcore.org/core/colors/cam/cam16"
"cogentcore.org/core/colors/cam/hct"
"cogentcore.org/core/math32"
)
// BlendTypes are different algorithms (colorspaces) to use for blending
// the color stop values in generating the gradients.
type BlendTypes int32 //enums:enum
const (
// HCT uses the hue, chroma, and tone space and generally produces the best results,
// but at a slight performance cost.
HCT BlendTypes = iota
// RGB uses raw RGB space, which is the standard space that most other programs use.
// It produces decent results with maximum performance.
RGB
// CAM16 is an alternative colorspace, similar to HCT, but not quite as good.
CAM16
)
// Blend returns a color that is the given proportion between the first
// and second color. For example, 0.1 indicates to blend 10% of the first
// color and 90% of the second. Blending is done using the given blending
// algorithm.
func Blend(bt BlendTypes, p float32, x, y color.Color) color.RGBA {
switch bt {
case HCT:
return hct.Blend(p, x, y)
case RGB:
return BlendRGB(p, x, y)
case CAM16:
return cam16.Blend(p, x, y)
}
slog.Error("got unexpected blend type", "type", bt)
return color.RGBA{}
}
// BlendRGB returns a color that is the given proportion between the first
// and second color in RGB colorspace. For example, 0.1 indicates to blend
// 10% of the first color and 90% of the second. Blending is done directly
// on non-premultiplied
// RGB values, and a correctly premultiplied color is returned.
func BlendRGB(pct float32, x, y color.Color) color.RGBA {
fx := NRGBAF32Model.Convert(x).(NRGBAF32)
fy := NRGBAF32Model.Convert(y).(NRGBAF32)
pct = math32.Clamp(pct, 0, 100.0)
px := pct / 100
py := 1.0 - px
fx.R = px*fx.R + py*fy.R
fx.G = px*fx.G + py*fy.G
fx.B = px*fx.B + py*fy.B
fx.A = px*fx.A + py*fy.A
return AsRGBA(fx)
}
// m is the maximum color value returned by [image.Color.RGBA]
const m = 1<<16 - 1
// AlphaBlend blends the two colors, handling alpha blending correctly.
// The source color is figuratively placed "on top of" the destination color.
func AlphaBlend(dst, src color.Color) color.RGBA {
res := color.RGBA{}
dr, dg, db, da := dst.RGBA()
sr, sg, sb, sa := src.RGBA()
a := (m - sa)
res.R = uint8((uint32(dr)*a/m + sr) >> 8)
res.G = uint8((uint32(dg)*a/m + sg) >> 8)
res.B = uint8((uint32(db)*a/m + sb) >> 8)
res.A = uint8((uint32(da)*a/m + sa) >> 8)
return res
}
// Copyright (c) 2021, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package cam02 provides the CIECAM02 color appearance model: the LMS cone
// responses of its transform, luminance adaptation, and response compression.
package cam02
import (
"cogentcore.org/core/colors/cam/cie"
"cogentcore.org/core/math32"
)
// XYZToLMS converts XYZ to Long, Medium, Short cone-based responses,
// using the CAT02 transform from CIECAM02 color appearance model
// (MoroneyFairchildHuntEtAl02)
func XYZToLMS(x, y, z float32) (l, m, s float32) {
l = 0.7328*x + 0.4296*y + -0.1624*z
m = -0.7036*x + 1.6975*y + 0.0061*z
s = 0.0030*x + 0.0136*y + 0.9834*z
return
}
// SRGBLinToLMS converts sRGB linear to Long, Medium, Short
// cone-based responses, using the CAT02 transform from CIECAM02
// color appearance model (MoroneyFairchildHuntEtAl02)
// this is good for representing adaptation but NOT apparently
// good for representing appearances
func SRGBLinToLMS(rl, gl, bl float32) (l, m, s float32) {
l = 0.3904054*rl + 0.54994122*gl + 0.00892632*bl
m = 0.0708416*rl + 0.96317176*gl + 0.00135775*bl
s = 0.0491304*rl + 0.21556128*gl + 0.9450824*bl
return
}
// SRGBToLMS converts sRGB to Long, Medium, Short cone-based responses,
// using the CAT02 transform from CIECAM02 color appearance model
// (MoroneyFairchildHuntEtAl02)
func SRGBToLMS(r, g, b float32) (l, m, s float32) {
rl, gl, bl := cie.SRGBToLinear(r, g, b)
l, m, s = SRGBLinToLMS(rl, gl, bl)
return
}
/*
// convert Long, Medium, Short cone-based responses to XYZ, using the CAT02 transform from CIECAM02 color appearance model (MoroneyFairchildHuntEtAl02)
func LMSToXYZ(l, m, s float32) (x, y, z float32) {
x = 1.096124 * l + 0.4296f * Y + -0.1624f * Z;
y = -0.7036f * X + 1.6975f * Y + 0.0061f * Z;
z = 0.0030f * X + 0.0136f * Y + 0.9834 * Z;
}
*/
///////////////////////////////////
// HPE versions
// LuminanceAdapt implements the luminance adaptation function
// equals 1 at background luminance of 200 so we generally ignore it..
// bgLum is background luminance -- 200 default.
func LuminanceAdapt(bgLum float32) float32 {
lum5 := 5.0 * bgLum
k := 1.0 / (lum5 + 1)
k4 := k * k * k * k
k4m1 := 1 - k4
fl := 0.2*k4*lum5 + .1*k4m1*k4m1*math32.Pow(lum5, 1.0/3.0)
return fl
}
// ResponseCompression takes a 0-1 normalized LMS value
// and performs hyperbolic response compression.
// val must ALREADY have the luminance adaptation applied to it
// using the luminance adaptation function, which is 1 at a
// background luminance level of 200 = 2, so you can skip that
// step if you assume that level of background.
func ResponseCompression(val float32) float32 {
pval := math32.Pow(val, 0.42)
rc := 0.1 + 4.0*pval/(27.13+pval)
return rc
}
// LMSToResp converts Long, Medium, Short cone-based values to
// values that more closely reflect neural responses,
// including a combined long-medium (yellow) channel (lmc).
// Uses the CIECAM02 color appearance model (MoroneyFairchildHuntEtAl02)
// https://en.wikipedia.org/wiki/CIECAM02
func LMSToResp(l, m, s float32) (lc, mc, sc, lmc, grey float32) {
lA := ResponseCompression(l)
mA := ResponseCompression(m)
sA := ResponseCompression(s)
// subtract min and mult by 6 gets values roughly into 1-0 range for L,M
lc = 6 * ((lA + (float32(1)/11)*sA) - 0.109091)
mc = 6 * (((float32(12) / 11) * mA) - 0.109091)
sc = 6 * (((float32(2) / 9) * sA) - 0.0222222)
lmc = 6 * (((float32(1) / 9) * (lA + mA)) - 0.0222222)
grey = (1 / 0.431787) * (2*lA + mA + .05*sA - 0.305)
// note: last term should be: 0.725 * (1/5)^-0.2 = grey background assumption (Yb/Yw = 1/5) = 1
return
}
// SRGBToLMSResp converts sRGB to LMS neural response cone values,
// that more closely reflect neural responses,
// including a combined long-medium (yellow) channel (lmc).
// Uses the CIECAM02 color appearance model (MoroneyFairchildHuntEtAl02)
// https://en.wikipedia.org/wiki/CIECAM02
func SRGBToLMSResp(r, g, b float32) (lc, mc, sc, lmc, grey float32) {
l, m, s := SRGBToLMS(r, g, b)
lc, mc, sc, lmc, grey = LMSToResp(l, m, s)
return
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Adapted from https://github.com/material-foundation/material-color-utilities
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package cam16 provides the CAM16 color appearance model, and its CAM16-UCS
// uniform color space, under given viewing conditions.
package cam16
import (
"image/color"
"cogentcore.org/core/base/num"
"cogentcore.org/core/colors/cam/cie"
"cogentcore.org/core/math32"
)
// CAM represents a point in the cam16 color model along 6 dimensions
// representing the perceived hue, colorfulness, and brightness,
// similar to HSL but much more well-calibrated to actual human subjective judgments.
type CAM struct {
// hue (h) is the spectral identity of the color (red, green, blue etc) in degrees (0-360)
Hue float32
// chroma (C) is the colorfulness or saturation of the color -- greyscale colors have no chroma, and fully saturated ones have high chroma
Chroma float32
// colorfulness (M) is the absolute chromatic intensity
Colorfulness float32
// saturation (s) is the colorfulness relative to brightness
Saturation float32
// brightness (Q) is the apparent amount of light from the color, which is not a simple function of actual light energy emitted
Brightness float32
// lightness (J) is the brightness relative to a reference white, which varies as a function of chroma and hue
Lightness float32
}
// RGBA implements the color.Color interface.
func (cam *CAM) RGBA() (r, g, b, a uint32) {
x, y, z := cam.XYZ()
rf, gf, bf := cie.XYZ100ToSRGB(x, y, z)
return cie.SRGBFloatToUint32(rf, gf, bf, 1)
}
// AsRGBA returns the color as a [color.RGBA].
func (cam *CAM) AsRGBA() color.RGBA {
x, y, z := cam.XYZ()
rf, gf, bf := cie.XYZ100ToSRGB(x, y, z)
r, g, b, a := cie.SRGBFloatToUint8(rf, gf, bf, 1)
return color.RGBA{r, g, b, a}
}
// UCS returns the CAM16-UCS components based on the the CAM values
func (cam *CAM) UCS() (j, m, a, b float32) {
j = (1 + 100*0.007) * cam.Lightness / (1 + 0.007*cam.Lightness)
m = math32.Log(1+0.0228*cam.Colorfulness) / 0.0228
hr := math32.DegToRad(cam.Hue)
a = m * math32.Cos(hr)
b = m * math32.Sin(hr)
return
}
// FromUCS returns CAM values from the given CAM16-UCS coordinates
// (jstar, astar, and bstar), under standard viewing conditions
func FromUCS(j, a, b float32) *CAM {
return FromUCSView(j, a, b, NewStdView())
}
// FromUCSView returns CAM values from the given CAM16-UCS coordinates
// (jstar, astar, and bstar), using the given viewing conditions
func FromUCSView(j, a, b float32, vw *View) *CAM {
m := math32.Sqrt(a*a + b*b)
M := (math32.Exp(m*0.0228) - 1) / 0.0228
c := M / vw.FLRoot
h := math32.RadToDeg(math32.Atan2(b, a))
if h < 0 {
h += 360
}
j /= 1 - (j-100)*0.007
return FromJCHView(j, c, h, vw)
}
// FromJCH returns CAM values from the given lightness (j), chroma (c),
// and hue (h) values under standard viewing condition
func FromJCH(j, c, h float32) *CAM {
return FromJCHView(j, c, h, NewStdView())
}
// FromJCHView returns CAM values from the given lightness (j), chroma (c),
// and hue (h) values under the given viewing conditions
func FromJCHView(j, c, h float32, vw *View) *CAM {
cam := &CAM{Lightness: j, Chroma: c, Hue: h}
cam.Brightness = (4 / vw.C) *
math32.Sqrt(cam.Lightness/100) *
(vw.AW + 4) *
(vw.FLRoot)
cam.Colorfulness = cam.Chroma * vw.FLRoot
alpha := cam.Chroma / math32.Sqrt(cam.Lightness/100)
cam.Saturation = 50 * math32.Sqrt((alpha*vw.C)/(vw.AW+4))
return cam
}
// FromSRGB returns CAM values from given SRGB color coordinates,
// under standard viewing conditions. The RGB value range is 0-1,
// and RGB values have gamma correction.
func FromSRGB(r, g, b float32) *CAM {
return FromXYZ(cie.SRGBToXYZ100(r, g, b))
}
// FromXYZ returns CAM values from given XYZ color coordinate,
// under standard viewing conditions
func FromXYZ(x, y, z float32) *CAM {
return FromXYZView(x, y, z, NewStdView())
}
// FromXYZView returns CAM values from given XYZ color coordinate,
// under given viewing conditions. Requires 100-base XYZ coordinates.
func FromXYZView(x, y, z float32, vw *View) *CAM {
l, m, s := XYZToLMS(x, y, z)
redVgreen, yellowVblue, grey, greyNorm := LMSToOps(l, m, s, vw)
hue := SanitizeDegrees(math32.RadToDeg(math32.Atan2(yellowVblue, redVgreen)))
// achromatic response to color
ac := grey * vw.NBB
// CAM16 lightness and brightness
J := 100 * math32.Pow(ac/vw.AW, vw.C*vw.Z)
Q := (4 / vw.C) * math32.Sqrt(J/100) * (vw.AW + 4) * (vw.FLRoot)
huePrime := hue
if hue < 20.14 {
huePrime += 360
}
eHue := 0.25 * (math32.Cos(huePrime*math32.Pi/180+2) + 3.8)
p1 := 50000 / 13 * eHue * vw.NC * vw.NCB
t := p1 * math32.Sqrt(redVgreen*redVgreen+yellowVblue*yellowVblue) / (greyNorm + 0.305)
alpha := math32.Pow(t, 0.9) * math32.Pow(1.64-math32.Pow(0.29, vw.BgYToWhiteY), 0.73)
// CAM16 chroma, colorfulness, chroma
C := alpha * math32.Sqrt(J/100)
M := C * vw.FLRoot
s = 50 * math32.Sqrt((alpha*vw.C)/(vw.AW+4))
return &CAM{Hue: hue, Chroma: C, Colorfulness: M, Saturation: s, Brightness: Q, Lightness: J}
}
// XYZ returns the CAM color as XYZ coordinates
// under standard viewing conditions.
// Returns 100-base XYZ coordinates.
func (cam *CAM) XYZ() (x, y, z float32) {
return cam.XYZView(NewStdView())
}
// XYZView returns the CAM color as XYZ coordinates
// under the given viewing conditions.
// Returns 100-base XYZ coordinates.
func (cam *CAM) XYZView(vw *View) (x, y, z float32) {
alpha := float32(0)
if cam.Chroma != 0 || cam.Lightness != 0 {
alpha = cam.Chroma / math32.Sqrt(cam.Lightness/100)
}
t := math32.Pow(
alpha/
math32.Pow(
1.64-
math32.Pow(0.29, vw.BgYToWhiteY),
0.73),
1.0/0.9)
hRad := math32.DegToRad(cam.Hue)
eHue := 0.25 * (math32.Cos(hRad+2) + 3.8)
ac := vw.AW * math32.Pow(cam.Lightness/100, 1/vw.C/vw.Z)
p1 := eHue * (50000 / 13) * vw.NC * vw.NCB
p2 := ac / vw.NBB
hSin := math32.Sin(hRad)
hCos := math32.Cos(hRad)
gamma := 23 *
(p2 + 0.305) *
t /
(23*p1 + 11*t*hCos + 108*t*hSin)
a := gamma * hCos
b := gamma * hSin
rA := (460*p2 + 451*a + 288*b) / 1403
gA := (460*p2 - 891*a - 261*b) / 1403
bA := (460*p2 - 220*a - 6300*b) / 1403
rCBase := max(0, (27.13*num.Abs(rA))/(400-num.Abs(rA)))
// TODO(kai): their sign function returns 0 for 0, but we return 1, so this might break
rC := math32.Sign(rA) *
(100 / vw.FL) *
math32.Pow(rCBase, 1/0.42)
gCBase := max(0, (27.13*num.Abs(gA))/(400-num.Abs(gA)))
gC := math32.Sign(gA) *
(100 / vw.FL) *
math32.Pow(gCBase, 1/0.42)
bCBase := max(0, (27.13*num.Abs(bA))/(400-num.Abs(bA)))
bC := math32.Sign(bA) *
(100 / vw.FL) *
math32.Pow(bCBase, 1/0.42)
rF := rC / vw.RGBD.X
gF := gC / vw.RGBD.Y
bF := bC / vw.RGBD.Z
x = 1.86206786*rF - 1.01125463*gF + 0.14918677*bF
y = 0.38752654*rF + 0.62144744*gF - 0.00897398*bF
z = -0.01584150*rF - 0.03412294*gF + 1.04996444*bF
return
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cam16
import (
"cogentcore.org/core/math32"
)
// XYZToLMS converts XYZ to Long, Medium, Short cone-based responses,
// using the CAT16 transform from CIECAM16 color appearance model
// (LiLiWangEtAl17)
func XYZToLMS(x, y, z float32) (l, m, s float32) {
l = x*0.401288 + y*0.650173 + z*-0.051461
m = x*-0.250268 + y*1.204414 + z*0.045854
s = x*-0.002079 + y*0.048952 + z*0.953127
return
}
// LMSToXYZ converts Long, Medium, Short cone-based responses to XYZ
// using the CAT16 transform from CIECAM16 color appearance model
// (LiLiWangEtAl17)
func LMSToXYZ(l, m, s float32) (x, y, z float32) {
x = l*1.86206787 + m*-1.0112563 + s*0.14918667
y = l*0.38752654 + m*0.62144744 + s*-0.00897398
z = l*-0.01584150 + m*-0.03412294 + s*1.04996444
return
}
// LuminanceAdaptComp performs luminance adaptation
// and response compression according to the CAM16 model,
// on one component, using equations from HuntLiLuo03
// d = discount factor
// fl = luminance adaptation factor
func LuminanceAdaptComp(v, d, fl float32) float32 {
vd := v * d
f := math32.Pow((fl*math32.Abs(vd))/100, 0.42)
return (math32.Sign(vd) * 400 * f) / (f + 27.13)
}
func InverseChromaticAdapt(adapted float32) float32 {
adaptedAbs := math32.Abs(adapted)
base := math32.Max(0, 27.13*adaptedAbs/(400.0-adaptedAbs))
return math32.Sign(adapted) * math32.Pow(base, 1.0/0.42)
}
// LuminanceAdapt performs luminance adaptation
// and response compression according to the CAM16 model,
// on given r,g,b components, using equations from HuntLiLuo03
// and parameters on given viewing conditions
func LuminanceAdapt(l, m, s float32, vw *View) (lA, mA, sA float32) {
lA = LuminanceAdaptComp(l, vw.RGBD.X, vw.FL)
mA = LuminanceAdaptComp(m, vw.RGBD.Y, vw.FL)
sA = LuminanceAdaptComp(s, vw.RGBD.Z, vw.FL)
return
}
// LMSToOps converts Long, Medium, Short cone-based values to
// opponent redVgreen (a) and yellowVblue (b), and grey (achromatic) values,
// that more closely reflect neural responses.
// greyNorm is a normalizing grey factor used in the CAM16 model.
// l, m, s values must be in 100-base units.
// Uses the CIECAM16 color appearance model.
func LMSToOps(l, m, s float32, vw *View) (redVgreen, yellowVblue, grey, greyNorm float32) {
// Discount illuminant and adapt
lA, mA, sA := LuminanceAdapt(l, m, s, vw)
redVgreen = (11*lA + -12*mA + sA) / 11
yellowVblue = (lA + mA - 2*sA) / 9
// auxiliary components
grey = (40*lA + 20*mA + sA) / 20 // achromatic response, multiplied * view.NBB
greyNorm = (20*lA + 20*mA + 21*sA) / 20 // normalizing factor
return
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Adapted from https://github.com/material-foundation/material-color-utilities
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cam16
import "cogentcore.org/core/math32"
// SanitizeDegrees ensures that degrees is in [0-360) range
func SanitizeDegrees(deg float32) float32 {
if deg < 0 {
return math32.Mod(deg, 360) + 360
} else if deg >= 360 {
return math32.Mod(deg, 360)
}
return deg
}
// SanitizeRadians sanitizes a small enough angle in radians.
// Takes an angle in radians; must not deviate too much from 0,
// and returns a coterminal angle between 0 and 2pi.
func SanitizeRadians(angle float32) float32 {
return math32.Mod(angle+math32.Pi*8, math32.Pi*2)
}
// InCyclicOrder returns true a, b, c are in order around a circle
func InCyclicOrder(a, b, c float32) bool {
deltaAB := SanitizeRadians(b - a)
deltaAC := SanitizeRadians(c - a)
return deltaAB < deltaAC
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cam16
import (
"image/color"
"cogentcore.org/core/colors/cam/cie"
"cogentcore.org/core/math32"
)
// Blend returns a color that is the given percent blend between the first
// and second color; 10 = 10% of the first and 90% of the second, etc;
// blending is done directly on non-premultiplied CAM16-UCS values, and
// a correctly premultiplied color is returned.
func Blend(pct float32, x, y color.Color) color.RGBA {
pct = math32.Clamp(pct, 0, 100)
amt := pct / 100
xsr, xsg, xsb, _ := cie.SRGBUint32ToFloat(x.RGBA())
ysr, ysg, ysb, _ := cie.SRGBUint32ToFloat(y.RGBA())
cx := FromSRGB(xsr, xsg, xsb)
cy := FromSRGB(ysr, ysg, ysb)
xj, _, xa, xb := cx.UCS()
yj, _, ya, yb := cy.UCS()
j := yj + (xj-yj)*amt
a := ya + (xa-ya)*amt
b := yb + (xb-yb)*amt
cam := FromUCS(j, a, b)
return cam.AsRGBA()
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Adapted from https://github.com/material-foundation/material-color-utilities
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cam16
import (
"cogentcore.org/core/colors/cam/cie"
"cogentcore.org/core/math32"
)
// View represents viewing conditions under which a color is being perceived,
// which greatly affects the subjective perception. Defaults represent the
// standard defined such conditions, under which the CAM16 computations operate.
type View struct {
// white point illumination -- typically cie.WhiteD65
WhitePoint math32.Vector3
// the ambient light strength in lux
Luminance float32 `default:"200"`
// the average luminance of 10 degrees around the color in question
BgLuminance float32 `default:"50"`
// the brightness of the entire environment
Surround float32 `default:"2"`
// whether the person's eyes have adapted to the lighting
Adapted bool `default:"false"`
// computed from Luminance
AdaptingLuminance float32 `display:"-"`
//
BgYToWhiteY float32 `display:"-"`
//
AW float32 `display:"-"`
// luminance level induction factor
NBB float32 `display:"-"`
// luminance level induction factor
NCB float32 `display:"-"`
// exponential nonlinearity
C float32 `display:"-"`
// chromatic induction factor
NC float32 `display:"-"`
// luminance-level adaptation factor, based on the HuntLiLuo03 equations
FL float32 `display:"-"`
// FL to the 1/4 power
FLRoot float32 `display:"-"`
// base exponential nonlinearity
Z float32 `display:"-"`
// inverse of the RGBD factors
DRGBInverse math32.Vector3 `display:"-"`
// cone responses to white point, adjusted for discounting
RGBD math32.Vector3 `display:"-"`
}
// NewView returns a new view with all parameters initialized based on given major params
func NewView(whitePoint math32.Vector3, lum, bgLum, surround float32, adapt bool) *View {
vw := &View{WhitePoint: whitePoint, Luminance: lum, BgLuminance: bgLum, Surround: surround, Adapted: adapt}
vw.Update()
return vw
}
// TheStdView is the standard viewing conditions view
// returned by NewStdView if already created.
var TheStdView *View
// NewStdView returns a new standard viewing conditions model
// returns TheStdView if already created
func NewStdView() *View {
if TheStdView != nil {
return TheStdView
}
TheStdView = NewView(cie.WhiteD65, 200, 50, 2, false)
return TheStdView
}
// Update updates all the computed values based on main parameters
func (vw *View) Update() {
vw.AdaptingLuminance = (vw.Luminance / math32.Pi) * (cie.LToY(50) / 100)
// A background of pure black is non-physical and leads to infinities that
// represent the idea that any color viewed in pure black can't be seen.
vw.BgLuminance = math32.Max(0.1, vw.BgLuminance)
// Transform test illuminant white in XYZ to 'cone'/'rgb' responses
rW, gW, bW := XYZToLMS(vw.WhitePoint.X, vw.WhitePoint.Y, vw.WhitePoint.Z)
// Scale input surround, domain (0, 2), to CAM16 surround, domain (0.8, 1.0)
vw.Surround = math32.Clamp(vw.Surround, 0, 2)
f := 0.8 + (vw.Surround / 10)
// "Exponential non-linearity"
if f >= 0.9 {
vw.C = math32.Lerp(0.59, 0.69, ((f - 0.9) * 10))
} else {
vw.C = math32.Lerp(0.525, 0.59, ((f - 0.8) * 10))
}
// Calculate degree of adaptation to illuminant
d := float32(1)
if !vw.Adapted {
d = f * (1 - ((1 / 3.6) * math32.Exp((-vw.AdaptingLuminance-42)/92)))
}
// Per Li et al, if D is greater than 1 or less than 0, set it to 1 or 0.
d = math32.Clamp(d, 0, 1)
// chromatic induction factor
vw.NC = f
// Cone responses to the whitePoint, r/g/b/W, adjusted for discounting.
//
// Why use 100 instead of the white point's relative luminance?
//
// Some papers and implementations, for both CAM02 and CAM16, use the Y
// value of the reference white instead of 100. Fairchild's Color Appearance
// Models (3rd edition) notes that this is in error: it was included in the
// CIE 2004a report on CIECAM02, but, later parts of the conversion process
// account for scaling of appearance relative to the white point relative
// luminance. This part should simply use 100 as luminance.
vw.RGBD.X = d*(100/rW) + 1 - d
vw.RGBD.Y = d*(100/gW) + 1 - d
vw.RGBD.Z = d*(100/bW) + 1 - d
// Factor used in calculating meaningful factors
k := 1 / (5*vw.AdaptingLuminance + 1)
k4 := k * k * k * k
k4F := 1 - k4
// Luminance-level adaptation factor
vw.FL = (k4 * vw.AdaptingLuminance) +
(0.1 * k4F * k4F * math32.Pow(5*vw.AdaptingLuminance, 1.0/3.0))
vw.FLRoot = math32.Pow(vw.FL, 0.25)
// Intermediate factor, ratio of background relative luminance to white relative luminance
n := cie.LToY(vw.BgLuminance) / vw.WhitePoint.Y
vw.BgYToWhiteY = n
// Base exponential nonlinearity
// note Schlomer 2018 has a typo and uses 1.58, the correct factor is 1.48
vw.Z = 1.48 + math32.Sqrt(n)
// Luminance-level induction factors
vw.NBB = 0.725 / math32.Pow(n, 0.2)
vw.NCB = vw.NBB
// Discounted cone responses to the white point, adjusted for post-saturation
// adaptation perceptual nonlinearities.
rA, gA, bA := LuminanceAdapt(rW, gW, bW, vw)
vw.AW = ((40*rA + 20*gA + bA) / 20) * vw.NBB
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package cie provides the CIE color spaces (XYZ and L*a*b*), standard
// illuminants, and the conversions of sRGB to and from them.
package cie
import "cogentcore.org/core/math32"
// LABCompress does cube-root compression of the X, Y, Z components
// prior to performing the LAB conversion
func LABCompress(t float32) float32 {
e := float32(216.0 / 24389.0)
if t > e {
return math32.Pow(t, 1.0/3.0)
}
kappa := float32(24389.0 / 27.0)
return (kappa*t + 16) / 116
}
func LABUncompress(ft float32) float32 {
e := float32(216.0 / 24389.0)
ft3 := ft * ft * ft
if ft3 > e {
return ft3
}
kappa := float32(24389.0 / 27.0)
return (116*ft - 16) / kappa
}
// XYZToLAB converts a color from XYZ to L*a*b* coordinates
// using the standard D65 illuminant
func XYZToLAB(x, y, z float32) (l, a, b float32) {
x, y, z = XYZNormD65(x, y, z)
fx := LABCompress(x)
fy := LABCompress(y)
fz := LABCompress(z)
l = 116*fy - 16
a = 500 * (fx - fy)
b = 200 * (fy - fz)
return
}
// LABToXYZ converts a color from L*a*b* to XYZ coordinates
// using the standard D65 illuminant
func LABToXYZ(l, a, b float32) (x, y, z float32) {
fy := (l + 16) / 116
fx := a/500 + fy
fz := fy - b/200
x = LABUncompress(fx)
y = LABUncompress(fy)
z = LABUncompress(fz)
x, y, z = XYZDenormD65(x, y, z)
return
}
// LToY Converts an L* value to a Y value.
// L* in L*a*b* and Y in XYZ measure the same quantity, luminance.
// L* measures perceptual luminance, a linear scale. Y in XYZ
// measures relative luminance, a logarithmic scale.
func LToY(l float32) float32 {
return 100 * LABUncompress((l+16)/116)
}
// YToL Converts a Y value to an L* value.
// L* in L*a*b* and Y in XYZ measure the same quantity, luminance.
// L* measures perceptual luminance, a linear scale. Y in XYZ
// measures relative luminance, a logarithmic scale.
func YToL(y float32) float32 {
return LABCompress(y/100)*116 - 16
}
// Copyright (c) 2021, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cie
import "cogentcore.org/core/math32"
// SRGBToLinearComp converts an sRGB rgb component to linear space (removes gamma).
// Used in converting from sRGB to XYZ colors.
func SRGBToLinearComp(srgb float32) float32 {
if srgb <= 0.04045 {
return srgb / 12.92
}
return math32.Pow((srgb+0.055)/1.055, 2.4)
}
// SRGBFromLinearComp converts an sRGB rgb linear component
// to non-linear (gamma corrected) sRGB value
// Used in converting from XYZ to sRGB.
func SRGBFromLinearComp(lin float32) float32 {
var gv float32
if lin <= 0.0031308 {
gv = 12.92 * lin
} else {
gv = (1.055*math32.Pow(lin, 1.0/2.4) - 0.055)
}
return math32.Clamp(gv, 0, 1)
}
// SRGBToLinear converts set of sRGB components to linear values,
// removing gamma correction.
func SRGBToLinear(r, g, b float32) (rl, gl, bl float32) {
rl = SRGBToLinearComp(r)
gl = SRGBToLinearComp(g)
bl = SRGBToLinearComp(b)
return
}
// SRGB100ToLinear converts set of sRGB components to linear values,
// removing gamma correction. returns 100-base RGB values
func SRGB100ToLinear(r, g, b float32) (rl, gl, bl float32) {
rl = 100 * SRGBToLinearComp(r)
gl = 100 * SRGBToLinearComp(g)
bl = 100 * SRGBToLinearComp(b)
return
}
// SRGBFromLinear converts set of sRGB components from linear values,
// adding gamma correction.
func SRGBFromLinear(rl, gl, bl float32) (r, g, b float32) {
r = SRGBFromLinearComp(rl)
g = SRGBFromLinearComp(gl)
b = SRGBFromLinearComp(bl)
return
}
// SRGBFromLinear100 converts set of sRGB components from linear values in 0-100 range,
// adding gamma correction.
func SRGBFromLinear100(rl, gl, bl float32) (r, g, b float32) {
r = SRGBFromLinearComp(rl / 100)
g = SRGBFromLinearComp(gl / 100)
b = SRGBFromLinearComp(bl / 100)
return
}
// SRGBFloatToUint8 converts the given non-alpha-premuntiplied sRGB float32
// values to alpha-premultiplied sRGB uint8 values.
func SRGBFloatToUint8(rf, gf, bf, af float32) (r, g, b, a uint8) {
r = uint8(rf*af*255 + 0.5)
g = uint8(gf*af*255 + 0.5)
b = uint8(bf*af*255 + 0.5)
a = uint8(af*255 + 0.5)
return
}
// SRGBFloatToUint32 converts the given non-alpha-premuntiplied sRGB float32
// values to alpha-premultiplied sRGB uint32 values.
func SRGBFloatToUint32(rf, gf, bf, af float32) (r, g, b, a uint32) {
r = uint32(rf*af*65535 + 0.5)
g = uint32(gf*af*65535 + 0.5)
b = uint32(bf*af*65535 + 0.5)
a = uint32(af*65535 + 0.5)
return
}
// SRGBUint8ToFloat converts the given alpha-premultiplied sRGB uint8 values
// to non-alpha-premuntiplied sRGB float32 values.
func SRGBUint8ToFloat(r, g, b, a uint8) (fr, fg, fb, fa float32) {
fa = float32(a) / 255
fr = (float32(r) / 255) / fa
fg = (float32(g) / 255) / fa
fb = (float32(b) / 255) / fa
return
}
// SRGBUint32ToFloat converts the given alpha-premultiplied sRGB uint32 values
// to non-alpha-premuntiplied sRGB float32 values.
func SRGBUint32ToFloat(r, g, b, a uint32) (fr, fg, fb, fa float32) {
fa = float32(a) / 65535
fr = (float32(r) / 65535) / fa
fg = (float32(g) / 65535) / fa
fb = (float32(b) / 65535) / fa
return
}
// Copyright (c) 2021, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cie
// SRGBLinToXYZ converts sRGB linear into XYZ CIE standard color space
func SRGBLinToXYZ(rl, gl, bl float32) (x, y, z float32) {
x = 0.41233895*rl + 0.35762064*gl + 0.18051042*bl
y = 0.2126*rl + 0.7152*gl + 0.0722*bl
z = 0.01932141*rl + 0.11916382*gl + 0.95034478*bl
return
}
// XYZToSRGBLin converts XYZ CIE standard color space to sRGB linear
func XYZToSRGBLin(x, y, z float32) (rl, gl, bl float32) {
rl = 3.2406*x + -1.5372*y + -0.4986*z
gl = -0.9689*x + 1.8758*y + 0.0415*z
bl = 0.0557*x + -0.2040*y + 1.0570*z
return
}
// SRGBToXYZ converts sRGB into XYZ CIE standard color space
func SRGBToXYZ(r, g, b float32) (x, y, z float32) {
rl, gl, bl := SRGBToLinear(r, g, b)
x, y, z = SRGBLinToXYZ(rl, gl, bl)
return
}
// SRGBToXYZ100 converts sRGB into XYZ CIE standard color space
// with 100-base sRGB values -- used for CAM16 but not CAM02
func SRGBToXYZ100(r, g, b float32) (x, y, z float32) {
rl, gl, bl := SRGB100ToLinear(r, g, b)
x, y, z = SRGBLinToXYZ(rl, gl, bl)
return
}
// XYZToSRGB converts XYZ CIE standard color space into sRGB
func XYZToSRGB(x, y, z float32) (r, g, b float32) {
rl, bl, gl := XYZToSRGBLin(x, y, z)
r, g, b = SRGBFromLinear(rl, bl, gl)
return
}
// XYZ100ToSRGB converts XYZ CIE standard color space, 100 base units,
// into sRGB
func XYZ100ToSRGB(x, y, z float32) (r, g, b float32) {
rl, bl, gl := XYZToSRGBLin(x/100, y/100, z/100)
r, g, b = SRGBFromLinear(rl, bl, gl)
return
}
// XYZNormD65 normalizes XZY values relative to the D65 outdoor white light values
func XYZNormD65(x, y, z float32) (xr, yr, zr float32) {
xr = x / 0.95047
zr = z / 1.08883
yr = y
return
}
// XYZDenormD65 de-normalizes XZY values relative to the D65 outdoor white light values
func XYZDenormD65(x, y, z float32) (xr, yr, zr float32) {
xr = x * 0.95047
zr = z * 1.08883
yr = y
return
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Adapted from https://github.com/material-foundation/material-color-utilities
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package hct
import (
"cogentcore.org/core/base/num"
"cogentcore.org/core/colors/cam/cam16"
"cogentcore.org/core/math32"
)
// double ChromaticAdaptation(double component) {
// double af = pow(abs(component), 0.42);
// return Signum(component) * 400.0 * af / (af + 27.13);
// }
func MatMul(v math32.Vector3, mat [3][3]float32) math32.Vector3 {
x := v.X*mat[0][0] + v.Y*mat[0][1] + v.Z*mat[0][2]
y := v.X*mat[1][0] + v.Y*mat[1][1] + v.Z*mat[1][2]
z := v.X*mat[2][0] + v.Y*mat[2][1] + v.Z*mat[2][2]
return math32.Vec3(x, y, z)
}
// HueOf Returns the hue of a linear RGB color in CAM16.
func HueOf(linrgb math32.Vector3) float32 {
sd := MatMul(linrgb, kScaledDiscountFromLinrgb)
rA := cam16.LuminanceAdaptComp(sd.X, 1, 1)
gA := cam16.LuminanceAdaptComp(sd.Y, 1, 1)
bA := cam16.LuminanceAdaptComp(sd.Z, 1, 1)
// redness-greenness
a := (11*rA + -12*gA + bA) / 11
// yellowness-blueness
b := (rA + gA - 2*bA) / 9
return math32.Atan2(b, a)
}
// Intercept solves the lerp equation.
// @param source The starting number.
// @param mid The number in the middle.
// @param target The ending number.
// @return A number t such that lerp(source, target, t) = mid.
func Intercept(source, mid, target float32) float32 {
return (mid - source) / (target - source)
}
// GetAxis returns value along axis 0,1,2 -- result is divided by 100
// so that resulting numbers are in 0-1 range.
func GetAxis(v math32.Vector3, axis int) float32 {
switch axis {
case 0:
return v.X
case 1:
return v.Y
case 2:
return v.Z
default:
return -1
}
}
// SetCoordinate intersects a segment with a plane.
// @param source The coordinates of point A.
// @param coordinate The R-, G-, or B-coordinate of the plane.
// @param target The coordinates of point B.
// @param axis The axis the plane is perpendicular with. (0: R, 1: G, 2: B)
// @return The intersection point of the segment AB with the plane R=coordinate,
// G=coordinate, or B=coordinate
func SetCoordinate(source, target math32.Vector3, coord float32, axis int) math32.Vector3 {
t := Intercept(GetAxis(source, axis), coord, GetAxis(target, axis))
return source.Lerp(target, t)
}
func IsBounded(x float32) bool {
return 0 <= x && x <= 100
}
// NthVertex returns the nth possible vertex of the polygonal intersection.
// @param y The Y value of the plane.
// @param n The zero-based index of the point. 0 <= n <= 11.
// @return The nth possible vertex of the polygonal intersection of the y plane
// and the RGB cube, in linear RGB coordinates, if it exists. If this possible
// vertex lies outside of the cube,
//
// [-1.0, -1.0, -1.0] is returned.
func NthVertex(y float32, n int) math32.Vector3 {
kR := kYFromLinrgb[0]
kG := kYFromLinrgb[1]
kB := kYFromLinrgb[2]
coordA := float32(0)
if n%4 > 1 {
coordA = 100
}
coordB := float32(0)
if n%2 != 0 {
coordB = 100
}
if n < 4 {
g := coordA
b := coordB
r := (y - g*kG - b*kB) / kR
if IsBounded(r) {
return math32.Vec3(r, g, b)
}
return math32.Vec3(-1.0, -1.0, -1.0)
} else if n < 8 {
b := coordA
r := coordB
g := (y - r*kR - b*kB) / kG
if IsBounded(g) {
return math32.Vec3(r, g, b)
}
return math32.Vec3(-1.0, -1.0, -1.0)
}
r := coordA
g := coordB
b := (y - r*kR - g*kG) / kB
if IsBounded(b) {
return math32.Vec3(r, g, b)
}
return math32.Vec3(-1.0, -1.0, -1.0)
}
// BisectToSegment finds the segment containing the desired color.
// @param y The Y value of the color.
// @param target_hue The hue of the color.
// @return A list of two sets of linear RGB coordinates, each corresponding to
// an endpoint of the segment containing the desired color.
func BisectToSegment(y, targetHue float32) [2]math32.Vector3 {
left := math32.Vec3(-1.0, -1.0, -1.0)
right := left
leftHue := float32(0.0)
rightHue := float32(0.0)
initialized := false
uncut := true
for n := range 12 {
mid := NthVertex(y, n)
if mid.X < 0 {
continue
}
midHue := HueOf(mid)
if !initialized {
left = mid
right = mid
leftHue = midHue
rightHue = midHue
initialized = true
continue
}
if uncut || cam16.InCyclicOrder(leftHue, midHue, rightHue) {
uncut = false
if cam16.InCyclicOrder(leftHue, targetHue, midHue) {
right = mid
rightHue = midHue
} else {
left = mid
leftHue = midHue
}
}
}
var out [2]math32.Vector3
out[0] = left
out[1] = right
return out
}
func Midpoint(a, b math32.Vector3) math32.Vector3 {
return math32.Vec3((a.X+b.X)/2, (a.Y+b.Y)/2, (a.Z+b.Z)/2)
}
func CriticalPlaneBelow(x float32) int { return int(math32.Floor(x - 0.5)) }
func CriticalPlaneAbove(x float32) int { return int(math32.Ceil(x - 0.5)) }
// TrueDelinearized delinearizes an RGB component, returning a floating-point number.
// @param rgb_component 0.0 <= rgb_component <= 100.0, represents linear R/G/B
// channel
// @return 0.0 <= output <= 255.0, color channel converted to regular RGB space
func TrueDelinearized(comp float32) float32 {
normalized := comp / 100
delinearized := float32(0.0)
if normalized <= 0.0031308 {
delinearized = normalized * 12.92
} else {
delinearized = 1.055*math32.Pow(normalized, 1.0/2.4) - 0.055
}
return delinearized * 255
}
// BisectToLimit finds a color with the given Y and hue on the boundary of the cube.
// @param y The Y value of the color.
// @param target_hue The hue of the color.
// @return The desired color, in linear RGB coordinates.
func BisectToLimit(y, targetHue float32) math32.Vector3 {
segment := BisectToSegment(y, targetHue)
left := segment[0]
leftHue := HueOf(left)
right := segment[1]
for axis := range 3 {
if GetAxis(left, axis) != GetAxis(right, axis) {
lPlane := -1
rPlane := 255
if GetAxis(left, axis) < GetAxis(right, axis) {
lPlane = CriticalPlaneBelow(TrueDelinearized(GetAxis(left, axis)))
rPlane = CriticalPlaneAbove(TrueDelinearized(GetAxis(right, axis)))
} else {
lPlane = CriticalPlaneAbove(TrueDelinearized(GetAxis(left, axis)))
rPlane = CriticalPlaneBelow(TrueDelinearized(GetAxis(right, axis)))
}
for range 8 {
if num.Abs(rPlane-lPlane) <= 1 {
break
}
mPlane := int(math32.Floor(float32(lPlane+rPlane) / 2.0))
midPlaneCoordinate := kCriticalPlanes[mPlane]
mid := SetCoordinate(left, right, midPlaneCoordinate, axis)
midHue := HueOf(mid)
if cam16.InCyclicOrder(leftHue, targetHue, midHue) {
right = mid
rPlane = mPlane
} else {
left = mid
leftHue = midHue
lPlane = mPlane
}
}
}
}
return Midpoint(left, right)
}
/////////////////////////////////////////////
var kScaledDiscountFromLinrgb = [3][3]float32{
{
0.001200833568784504,
0.002389694492170889,
0.0002795742885861124,
},
{
0.0005891086651375999,
0.0029785502573438758,
0.0003270666104008398,
},
{
0.00010146692491640572,
0.0005364214359186694,
0.0032979401770712076,
},
}
var kLinrgbFromScaledDiscount = [3][3]float32{
{
1373.2198709594231,
-1100.4251190754821,
-7.278681089101213,
},
{
-271.815969077903,
559.6580465940733,
-32.46047482791194,
},
{
1.9622899599665666,
-57.173814538844006,
308.7233197812385,
},
}
var kYFromLinrgb = [3]float32{0.2126, 0.7152, 0.0722}
var kCriticalPlanes = [255]float32{
0.015176349177441876, 0.045529047532325624, 0.07588174588720938,
0.10623444424209313, 0.13658714259697685, 0.16693984095186062,
0.19729253930674434, 0.2276452376616281, 0.2579979360165119,
0.28835063437139563, 0.3188300904430532, 0.350925934958123,
0.3848314933096426, 0.42057480301049466, 0.458183274052838,
0.4976837250274023, 0.5391024159806381, 0.5824650784040898,
0.6277969426914107, 0.6751227633498623, 0.7244668422128921,
0.775853049866786, 0.829304845476233, 0.8848452951698498,
0.942497089126609, 1.0022825574869039, 1.0642236851973577,
1.1283421258858297, 1.1946592148522128, 1.2631959812511864,
1.3339731595349034, 1.407011200216447, 1.4823302800086415,
1.5599503113873272, 1.6398909516233677, 1.7221716113234105,
1.8068114625156377, 1.8938294463134073, 1.9832442801866852,
2.075074464868551, 2.1693382909216234, 2.2660538449872063,
2.36523901573795, 2.4669114995532007, 2.5710888059345764,
2.6777882626779785, 2.7870270208169257, 2.898822059350997,
3.0131901897720907, 3.1301480604002863, 3.2497121605402226,
3.3718988244681087, 3.4967242352587946, 3.624204428461639,
3.754355295633311, 3.887192587735158, 4.022731918402185,
4.160988767090289, 4.301978482107941, 4.445716283538092,
4.592217266055746, 4.741496401646282, 4.893568542229298,
5.048448422192488, 5.20615066083972, 5.3666897647573375,
5.5300801301023865, 5.696336044816294, 5.865471690767354,
6.037501145825082, 6.212438385869475, 6.390297286737924,
6.571091626112461, 6.7548350853498045, 6.941541251256611,
7.131223617812143, 7.323895587840543, 7.5195704746346665,
7.7182615035334345, 7.919981813454504, 8.124744458384042,
8.332562408825165, 8.543448553206703, 8.757415699253682,
8.974476575321063, 9.194643831691977, 9.417930041841839,
9.644347703669503, 9.873909240696694, 10.106627003236781,
10.342513269534024, 10.58158024687427, 10.8238400726681,
11.069304815507364, 11.317986476196008, 11.569896988756009,
11.825048221409341, 12.083451977536606, 12.345119996613247,
12.610063955123938, 12.878295467455942, 13.149826086772048,
13.42466730586372, 13.702830557985108, 13.984327217668513,
14.269168601521828, 14.55736596900856, 14.848930523210871,
15.143873411576273, 15.44220572664832, 15.743938506781891,
16.04908273684337, 16.35764934889634, 16.66964922287304,
16.985093187232053, 17.30399201960269, 17.62635644741625,
17.95219714852476, 18.281524751807332, 18.614349837764564,
18.95068293910138, 19.290534541298456, 19.633915083172692,
19.98083495742689, 20.331304511189067, 20.685334046541502,
21.042933821039977, 21.404114048223256, 21.76888489811322,
22.137256497705877, 22.50923893145328, 22.884842241736916,
23.264076429332462, 23.6469514538663, 24.033477234264016,
24.42366364919083, 24.817520537484558, 25.21505769858089,
25.61628489293138, 26.021211842414342, 26.429848230738664,
26.842203703840827, 27.258287870275353, 27.678110301598522,
28.10168053274597, 28.529008062403893, 28.96010235337422,
29.39497283293396, 29.83362889318845, 30.276079891419332,
30.722335150426627, 31.172403958865512, 31.62629557157785,
32.08401920991837, 32.54558406207592, 33.010999283389665,
33.4802739966603, 33.953417292456834, 34.430438229418264,
34.911345834551085, 35.39614910352207, 35.88485700094671,
36.37747846067349, 36.87402238606382, 37.37449765026789,
37.87891309649659, 38.38727753828926, 38.89959975977785,
39.41588851594697, 39.93615253289054, 40.460400508064545,
40.98864111053629, 41.520882981230194, 42.05713473317016,
42.597404951718396, 43.141702194811224, 43.6900349931913,
44.24241185063697, 44.798841244188324, 45.35933162437017,
45.92389141541209, 46.49252901546552, 47.065252796817916,
47.64207110610409, 48.22299226451468, 48.808024568002054,
49.3971762874833, 49.9904556690408, 50.587870934119984,
51.189430279724725, 51.79514187861014, 52.40501387947288,
53.0190544071392, 53.637271562750364, 54.259673423945976,
54.88626804504493, 55.517063457223934, 56.15206766869424,
56.79128866487574, 57.43473440856916, 58.08241284012621,
58.734331877617365, 59.39049941699807, 60.05092333227251,
60.715611475655585, 61.38457167773311, 62.057811747619894,
62.7353394731159, 63.417162620860914, 64.10328893648692,
64.79372614476921, 65.48848194977529, 66.18756403501224,
66.89098006357258, 67.59873767827808, 68.31084450182222,
69.02730813691093, 69.74813616640164, 70.47333615344107,
71.20291564160104, 71.93688215501312, 72.67524319850172,
73.41800625771542, 74.16517879925733, 74.9167682708136,
75.67278210128072, 76.43322770089146, 77.1981124613393,
77.96744375590167, 78.74122893956174, 79.51947534912904,
80.30219030335869, 81.08938110306934, 81.88105503125999,
82.67721935322541, 83.4778813166706, 84.28304815182372,
85.09272707154808, 85.90692527145302, 86.72564993000343,
87.54890820862819, 88.3767072518277, 89.2090541872801,
90.04595612594655, 90.88742016217518, 91.73345337380438,
92.58406282226491, 93.43925555268066, 94.29903859396902,
95.16341895893969, 96.03240364439274, 96.9059996312159,
97.78421388448044, 98.6670533535366, 99.55452497210776,
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Adapted from https://github.com/material-foundation/material-color-utilities
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package hct
import (
"image/color"
"cogentcore.org/core/colors/cam/cie"
"cogentcore.org/core/math32"
)
const (
// ContrastAA is the contrast ratio required by WCAG AA for body text
ContrastAA float32 = 4.5
// ContrastLargeAA is the contrast ratio required by WCAG AA for large text
// (at least 120-150% larger than the body text)
ContrastLargeAA float32 = 3
// ContrastGraphicsAA is the contrast ratio required by WCAG AA for graphical objects
// and active user interface components like graphs, icons, and form input borders
ContrastGraphicsAA float32 = 3
// ContrastAAA is the contrast ratio required by WCAG AAA for body text
ContrastAAA float32 = 7
// ContrastLargeAAA is the contrast ratio required by WCAG AAA for large text
// (at least 120-150% larger than the body text)
ContrastLargeAAA float32 = 4.5
)
// ContrastRatio returns the contrast ratio between the given two colors.
// The contrast ratio will be between 1 and 21.
func ContrastRatio(a, b color.Color) float32 {
ah := FromColor(a)
bh := FromColor(b)
return ToneContrastRatio(ah.Tone, bh.Tone)
}
// ToneContrastRatio returns the contrast ratio between the given two tones.
// The contrast ratio will be between 1 and 21, and the tones should be
// between 0 and 100 and will be clamped to such.
func ToneContrastRatio(a, b float32) float32 {
a = math32.Clamp(a, 0, 100)
b = math32.Clamp(b, 0, 100)
return ContrastRatioOfYs(cie.LToY(a), cie.LToY(b))
}
// ContrastColor returns the color that will ensure that the given contrast ratio
// between the given color and the resulting color is met. If the given ratio can
// not be achieved with the given color, it returns the color that would result in
// the highest contrast ratio. The ratio must be between 1 and 21. If the tone of
// the given color is greater than 50, it tries darker tones first, and otherwise
// it tries lighter tones first.
func ContrastColor(c color.Color, ratio float32) color.RGBA {
h := FromColor(c)
ct := ContrastTone(h.Tone, ratio)
return h.WithTone(ct).AsRGBA()
}
// ContrastColorTry returns the color that will ensure that the given contrast ratio
// between the given color and the resulting color is met. It returns color.RGBA{}, false if
// the given ratio can not be achieved with the given color. The ratio must be between
// 1 and 21. If the tone of the given color is greater than 50, it tries darker tones first,
// and otherwise it tries lighter tones first.
func ContrastColorTry(c color.Color, ratio float32) (color.RGBA, bool) {
h := FromColor(c)
ct, ok := ContrastToneTry(h.Tone, ratio)
if !ok {
return color.RGBA{}, false
}
return h.WithTone(ct).AsRGBA(), true
}
// ContrastTone returns the tone that will ensure that the given contrast ratio
// between the given tone and the resulting tone is met. If the given ratio can
// not be achieved with the given tone, it returns the tone that would result in
// the highest contrast ratio. The tone must be between 0 and 100 and the ratio must be
// between 1 and 21. If the given tone is greater than 50, it tries darker tones first,
// and otherwise it tries lighter tones first.
func ContrastTone(tone, ratio float32) float32 {
ct, ok := ContrastToneTry(tone, ratio)
if ok {
return ct
}
dcr := ToneContrastRatio(tone, 0)
lcr := ToneContrastRatio(tone, 100)
if dcr > lcr {
return 0
}
return 100
}
// ContrastToneTry returns the tone that will ensure that the given contrast ratio
// between the given tone and the resulting tone is met. It returns -1, false if
// the given ratio can not be achieved with the given tone. The tone must be between 0
// and 100 and the ratio must be between 1 and 21. If the given tone is greater than 50,
// it tries darker tones first, and otherwise it tries lighter tones first.
func ContrastToneTry(tone, ratio float32) (float32, bool) {
if tone > 50 {
d, ok := ContrastToneDarkerTry(tone, ratio)
if ok {
return d, true
}
l, ok := ContrastToneLighterTry(tone, ratio)
if ok {
return l, true
}
return -1, false
}
l, ok := ContrastToneLighterTry(tone, ratio)
if ok {
return l, true
}
d, ok := ContrastToneDarkerTry(tone, ratio)
if ok {
return d, true
}
return -1, false
}
// ContrastToneLighter returns a tone greater than or equal to the given tone
// that ensures that given contrast ratio between the two tones is met.
// It returns 100 if the given ratio can not be achieved with the
// given tone. The tone must be between 0 and 100 and the ratio must be
// between 1 and 21.
func ContrastToneLighter(tone, ratio float32) float32 {
safe, ok := ContrastToneLighterTry(tone, ratio)
if ok {
return safe
}
return 100
}
// ContrastToneDarker returns a tone less than or equal to the given tone
// that ensures that given contrast ratio between the two tones is met.
// It returns 0 if the given ratio can not be achieved with the
// given tone. The tone must be between 0 and 100 and the ratio must be
// between 1 and 21.
func ContrastToneDarker(tone, ratio float32) float32 {
safe, ok := ContrastToneDarkerTry(tone, ratio)
if ok {
return safe
}
return 0
}
// ContrastToneLighterTry returns a tone greater than or equal to the given tone
// that ensures that given contrast ratio between the two tones is met.
// It returns -1, false if the given ratio can not be achieved with the
// given tone. The tone must be between 0 and 100 and the ratio must be
// between 1 and 21.
func ContrastToneLighterTry(tone, ratio float32) (float32, bool) {
tone, ok := validTone(tone)
if !ok {
return -1, false
}
darkY := cie.LToY(tone)
lightY := ratio*(darkY+5) - 5
realContrast := ContrastRatioOfYs(lightY, darkY)
delta := math32.Abs(realContrast - ratio)
if realContrast < ratio && delta > 0.04 {
return -1, false
}
// TODO(kai/cam): this +0.4 explained by the comment below only seems to cause problems
// Ensure gamut mapping, which requires a 'range' on tone, will still result
// the correct ratio by darkening slightly.
ret, ok := validTone(cie.YToL(lightY)) // + 0.4
if !ok {
return -1, false
}
return ret, true
}
// ContrastToneDarkerTry returns a tone less than or equal to the given tone
// that ensures that given contrast ratio between the two tones is met.
// It returns -1, false if the given ratio can not be achieved with the
// given tone. The tone must be between 0 and 100 and the ratio must be
// between 1 and 21.
func ContrastToneDarkerTry(tone, ratio float32) (float32, bool) {
tone, ok := validTone(tone)
if !ok {
return -1, false
}
lightY := cie.LToY(tone)
darkY := ((lightY + 5) / ratio) - 5
realContrast := ContrastRatioOfYs(lightY, darkY)
delta := math32.Abs(realContrast - ratio)
if realContrast < ratio && delta > 0.04 {
return -1, false
}
// TODO(kai/cam): this -0.4 explained by the comment below only seems to cause problems
// Ensure gamut mapping, which requires a 'range' on tone, will still result
// the correct ratio by darkening slightly.
ret, ok := validTone(cie.YToL(darkY)) // - 0.4
if !ok {
return -1, false
}
return ret, true
}
// validTone returns the given tone and whether it is between 0 and 100,
// allowing for floating point error at the ends of the range, such as a
// tone of -6e-08 for black, which is clamped to the range.
func validTone(tone float32) (float32, bool) {
const tol = 0.001
if tone < -tol || tone > 100+tol {
return -1, false
}
return math32.Clamp(tone, 0, 100), true
}
// ContrastRatioOfYs returns the contrast ratio of two XYZ Y values.
func ContrastRatioOfYs(a, b float32) float32 {
lighter := max(a, b)
darker := min(a, b)
return (lighter + 5) / (darker + 5)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Adapted from https://github.com/material-foundation/material-color-utilities
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package hct provides the HCT (hue, chroma, tone) color space of Material
// Design, based on CAM16 hue and chroma and L* tone, and contrast utilities.
package hct
import (
"fmt"
"image/color"
"cogentcore.org/core/colors/cam/cam16"
"cogentcore.org/core/colors/cam/cie"
)
// HCT represents a color as hue, chroma, and tone. HCT is a color system
// that provides a perceptually accurate color measurement system that can
// also accurately render what colors will appear as in different lighting
// environments. Directly setting the values of the HCT and RGB fields will
// have no effect on the underlying color; instead, use the Set methods
// ([HCT.SetHue], etc). The A field (transparency) can be set directly.
type HCT struct {
// Hue (h) is the spectral identity of the color
// (red, green, blue etc) in degrees (0-360)
Hue float32 `min:"0" max:"360"`
// Chroma (C) is the colorfulness/saturation of the color.
// Grayscale colors have no chroma, and fully saturated ones
// have high chroma. The maximum varies as a function of hue
// and tone, but 120 is a general upper bound (see
// [HCT.MaximumChroma] to get a specific value).
Chroma float32 `min:"0" max:"120"`
// Tone is the L* component from the LAB (L*a*b*) color system,
// which is linear in human perception of lightness.
// It ranges from 0 to 100.
Tone float32 `min:"0" max:"100"`
// sRGB standard gamma-corrected 0-1 normalized RGB representation
// of the color. Critically, components are not premultiplied by alpha.
R, G, B, A float32
}
// New returns a new HCT representation for given parameters:
// hue = 0..360
// chroma = 0..? depends on other params
// tone = 0..100
// also computes and sets the sRGB normalized, gamma corrected RGB values
// while keeping the sRGB representation within its gamut,
// which may cause the chroma to decrease until it is inside the gamut.
func New(hue, chroma, tone float32) HCT {
r, g, b := SolveToRGB(hue, chroma, tone)
return SRGBToHCT(r, g, b)
}
// FromColor constructs a new HCT color from a standard [color.Color].
func FromColor(c color.Color) HCT {
return Uint32ToHCT(c.RGBA())
}
// SetColor sets the HCT color from a standard [color.Color].
func (h *HCT) SetColor(c color.Color) {
*h = FromColor(c)
}
// Model is the standard [color.Model] that converts colors to HCT.
var Model = color.ModelFunc(model)
func model(c color.Color) color.Color {
if h, ok := c.(HCT); ok {
return h
}
return FromColor(c)
}
// RGBA implements the color.Color interface.
// Performs the premultiplication of the RGB components by alpha at this point.
func (h HCT) RGBA() (r, g, b, a uint32) {
return cie.SRGBFloatToUint32(h.R, h.G, h.B, h.A)
}
// AsRGBA returns a standard color.RGBA type
func (h HCT) AsRGBA() color.RGBA {
r, g, b, a := cie.SRGBFloatToUint8(h.R, h.G, h.B, h.A)
return color.RGBA{r, g, b, a}
}
// SetUint32 sets components from unsigned 32bit integers (alpha-premultiplied)
func (h *HCT) SetUint32(r, g, b, a uint32) {
fr, fg, fb, fa := cie.SRGBUint32ToFloat(r, g, b, a)
*h = SRGBAToHCT(fr, fg, fb, fa)
}
// SetHue sets the hue of this color. Chroma may decrease because chroma has a
// different maximum for any given hue and tone.
// 0 <= hue < 360; invalid values are corrected.
func (h *HCT) SetHue(hue float32) *HCT {
r, g, b := SolveToRGB(hue, h.Chroma, h.Tone)
*h = SRGBAToHCT(r, g, b, h.A)
return h
}
// WithHue is like [SetHue] except it returns a new color
// instead of setting the existing one.
func (h HCT) WithHue(hue float32) HCT {
r, g, b := SolveToRGB(hue, h.Chroma, h.Tone)
return SRGBAToHCT(r, g, b, h.A)
}
// SetChroma sets the chroma of this color (0 to max that depends on other params),
// while keeping the sRGB representation within its gamut,
// which may cause the chroma to decrease until it is inside the gamut.
func (h *HCT) SetChroma(chroma float32) *HCT {
r, g, b := SolveToRGB(h.Hue, chroma, h.Tone)
*h = SRGBAToHCT(r, g, b, h.A)
return h
}
// WithChroma is like [SetChroma] except it returns a new color
// instead of setting the existing one.
func (h HCT) WithChroma(chroma float32) HCT {
r, g, b := SolveToRGB(h.Hue, chroma, h.Tone)
return SRGBAToHCT(r, g, b, h.A)
}
// SetTone sets the tone of this color (0 < tone < 100),
// while keeping the sRGB representation within its gamut,
// which may cause the chroma to decrease until it is inside the gamut.
func (h *HCT) SetTone(tone float32) *HCT {
r, g, b := SolveToRGB(h.Hue, h.Chroma, tone)
*h = SRGBAToHCT(r, g, b, h.A)
return h
}
// WithTone is like [SetTone] except it returns a new color
// instead of setting the existing one.
func (h HCT) WithTone(tone float32) HCT {
r, g, b := SolveToRGB(h.Hue, h.Chroma, tone)
return SRGBAToHCT(r, g, b, h.A)
}
// MaximumChroma returns the maximum [HCT.Chroma] value for the hue
// and tone of this color. This will always be between 0 and 120.
func (h HCT) MaximumChroma() float32 {
// WithChroma does a round trip, so the resultant chroma will only
// be as high as the maximum chroma.
return h.WithChroma(120).Chroma
}
// SRGBAToHCT returns an HCT from the given SRGBA color coordinates
// under standard viewing conditions. The RGB value range is 0-1,
// and RGB values have gamma correction. The RGB values must not be
// premultiplied by the given alpha value. See [SRGBToHCT] for
// a version that does not take the alpha value.
func SRGBAToHCT(r, g, b, a float32) HCT {
h := SRGBToHCT(r, g, b)
h.A = a
return h
}
// SRGBToHCT returns an HCT from the given SRGB color coordinates
// under standard viewing conditions. The RGB value range is 0-1,
// and RGB values have gamma correction. Alpha is always 1; see
// [SRGBAToHCT] for a version that takes the alpha value.
func SRGBToHCT(r, g, b float32) HCT {
x, y, z := cie.SRGBToXYZ(r, g, b)
cam := cam16.FromXYZ(100*x, 100*y, 100*z)
l, _, _ := cie.XYZToLAB(x, y, z)
return HCT{Hue: cam.Hue, Chroma: cam.Chroma, Tone: l, R: r, G: g, B: b, A: 1}
}
// Uint32ToHCT returns an HCT from given SRGBA uint32 color coordinates,
// which are used for interchange among image.Color types.
// Uses standard viewing conditions, and RGB values already have gamma correction
// (i.e., they are SRGB values).
func Uint32ToHCT(r, g, b, a uint32) HCT {
h := HCT{}
h.SetUint32(r, g, b, a)
return h
}
func (h HCT) String() string {
return fmt.Sprintf("hct(%g, %g, %g)", h.Hue, h.Chroma, h.Tone)
}
/*
// Translate a color into different [ViewingConditions].
//
// Colors change appearance. They look different with lights on versus off,
// the same color, as in hex code, on white looks different when on black.
// This is called color relativity, most famously explicated by Josef Albers
// in Interaction of Color.
//
// In color science, color appearance models can account for this and
// calculate the appearance of a color in different settings. HCT is based on
// CAM16, a color appearance model, and uses it to make these calculations.
//
// See [ViewingConditions.make] for parameters affecting color appearance.
Hct inViewingConditions(ViewingConditions vc) {
// 1. Use CAM16 to find XYZ coordinates of color in specified VC.
final cam16 = Cam16.fromInt(toInt());
final viewedInVc = cam16.xyzInViewingConditions(vc);
// 2. Create CAM16 of those XYZ coordinates in default VC.
final recastInVc = Cam16.fromXyzInViewingConditions(
viewedInVc[0],
viewedInVc[1],
viewedInVc[2],
ViewingConditions.make(),
);
// 3. Create HCT from:
// - CAM16 using default VC with XYZ coordinates in specified VC.
// - L* converted from Y in XYZ coordinates in specified VC.
final recastHct = Hct.from(
recastInVc.hue,
recastInVc.chroma,
ColorUtils.lstarFromY(viewedInVc[1]),
);
return recastHct;
}
}
*/
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Adapted from https://github.com/material-foundation/material-color-utilities
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package hct
import (
"cogentcore.org/core/colors/cam/cam16"
"cogentcore.org/core/colors/cam/cie"
"cogentcore.org/core/math32"
)
// SolveToRGBLin Finds an sRGB linear color (represented by math32.Vector3, 0-100 range)
// with the given hue, chroma, and tone, if possible.
// if not possible to represent the target values, the hue and tone will be
// sufficiently close, and chroma will be maximized.
func SolveToRGBLin(hue, chroma, tone float32) math32.Vector3 {
if chroma < 0.0001 || tone < 0.0001 || tone > 99.9999 {
y := cie.LToY(tone)
return math32.Vec3(y, y, y)
}
tone = math32.Clamp(tone, 0, 100)
hueDeg := cam16.SanitizeDegrees(hue)
hueRad := math32.DegToRad(hueDeg)
y := cie.LToY(tone)
exact := FindResultByJ(hueRad, chroma, y)
if exact != nil {
return *exact
}
return BisectToLimit(y, hueRad)
}
// SolveToRGB Finds an sRGB (gamma corrected, 0-1 range) color
// with the given hue, chroma, and tone, if possible.
// if not possible to represent the target values, the hue and tone will be
// sufficiently close, and chroma will be maximized.
func SolveToRGB(hue, chroma, tone float32) (r, g, b float32) {
lin := SolveToRGBLin(hue, chroma, tone)
r, g, b = cie.SRGBFromLinear100(lin.X, lin.Y, lin.Z)
return
}
// FindResultByJ finds a color with the given hue, chroma, and Y.
// @param hue_radians The desired hue in radians.
// @param chroma The desired chroma.
// @param y The desired Y.
// @return The desired color as linear sRGB values.
func FindResultByJ(hueRad, chroma, y float32) *math32.Vector3 {
// Initial estimate of j.
j := math32.Sqrt(y) * 11
// ===========================================================
// Operations inlined from Cam16 to avoid repeated calculation
// ===========================================================
vw := cam16.NewStdView()
tInnerCoeff := 1 / math32.Pow(1.64-math32.Pow(0.29, vw.BgYToWhiteY), 0.73)
eHue := 0.25 * (math32.Cos(hueRad+2) + 3.8)
p1 := eHue * (50000 / 13) * vw.NC * vw.NCB
hSin := math32.Sin(hueRad)
hCos := math32.Cos(hueRad)
for itr := range 5 {
jNorm := j / 100
alpha := float32(0)
if !(chroma == 0 || j == 0) {
alpha = chroma / math32.Sqrt(jNorm)
}
t := math32.Pow(alpha*tInnerCoeff, 1/0.9)
ac := vw.AW * math32.Pow(jNorm, 1/vw.C/vw.Z)
p2 := ac / vw.NBB
gamma := 23 * (p2 + 0.305) * t / (23*p1 + 11*t*hCos + 108*t*hSin)
a := gamma * hCos
b := gamma * hSin
rA := (460*p2 + 451*a + 288*b) / 1403
gA := (460*p2 - 891*a - 261*b) / 1403
bA := (460*p2 - 220*a - 6300*b) / 1403
rCScaled := cam16.InverseChromaticAdapt(rA)
gCScaled := cam16.InverseChromaticAdapt(gA)
bCScaled := cam16.InverseChromaticAdapt(bA)
scaled := math32.Vec3(rCScaled, gCScaled, bCScaled)
linrgb := MatMul(scaled, kLinrgbFromScaledDiscount)
if linrgb.X < 0 || linrgb.Y < 0 || linrgb.Z < 0 {
return nil
}
kR := kYFromLinrgb[0]
kG := kYFromLinrgb[1]
kB := kYFromLinrgb[2]
fnj := kR*linrgb.X + kG*linrgb.Y + kB*linrgb.Z
if fnj <= 0 {
return nil
}
if itr == 4 || math32.Abs(fnj-y) < 0.002 {
if linrgb.X > 100.01 || linrgb.Y > 100.01 || linrgb.Z > 100.01 {
return nil
}
return &linrgb
}
// Iterates with Newton method,
// Using 2 * fn(j) / j as the approximation of fn'(j)
j = j - (fnj-y)*j/(2*fnj)
}
return nil
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package hct
import (
"image/color"
"cogentcore.org/core/math32"
)
// Lighten returns a color that is lighter by the
// given absolute HCT tone amount (0-100, ranges enforced)
func Lighten(c color.Color, amount float32) color.RGBA {
h := FromColor(c)
h.SetTone(h.Tone + amount)
return h.AsRGBA()
}
// Darken returns a color that is darker by the
// given absolute HCT tone amount (0-100, ranges enforced)
func Darken(c color.Color, amount float32) color.RGBA {
h := FromColor(c)
h.SetTone(h.Tone - amount)
return h.AsRGBA()
}
// Highlight returns a color that is lighter or darker by the
// given absolute HCT tone amount (0-100, ranges enforced),
// making the color darker if it is light (tone >= 50) and
// lighter otherwise. It is the opposite of [Samelight].
func Highlight(c color.Color, amount float32) color.RGBA {
h := FromColor(c)
if h.Tone >= 50 {
h.SetTone(h.Tone - amount)
} else {
h.SetTone(h.Tone + amount)
}
return h.AsRGBA()
}
// Samelight returns a color that is lighter or darker by the
// given absolute HCT tone amount (0-100, ranges enforced),
// making the color lighter if it is light (tone >= 50) and
// darker otherwise. It is the opposite of [Highlight].
func Samelight(c color.Color, amount float32) color.RGBA {
h := FromColor(c)
if h.Tone >= 50 {
h.SetTone(h.Tone + amount)
} else {
h.SetTone(h.Tone - amount)
}
return h.AsRGBA()
}
// Saturate returns a color that is more saturated by the
// given absolute HCT chroma amount (0-max that depends
// on other params but is around 150, ranges enforced)
func Saturate(c color.Color, amount float32) color.RGBA {
h := FromColor(c)
h.SetChroma(h.Chroma + amount)
return h.AsRGBA()
}
// Desaturate returns a color that is less saturated by the
// given absolute HCT chroma amount (0-max that depends
// on other params but is around 150, ranges enforced)
func Desaturate(c color.Color, amount float32) color.RGBA {
h := FromColor(c)
h.SetChroma(h.Chroma - amount)
return h.AsRGBA()
}
// Spin returns a color that has a different hue by the
// given absolute HCT hue amount (±0-360, ranges enforced)
func Spin(c color.Color, amount float32) color.RGBA {
h := FromColor(c)
h.SetHue(h.Hue + amount)
return h.AsRGBA()
}
// MinHueDistance finds the minimum distance between two hues.
// A positive number means add to a to get to b.
// A negative number means subtract from a to get to b.
func MinHueDistance(a, b float32) float32 {
d1 := b - a
d2 := (b + 360) - a
d3 := (b - (a + 360))
d1a := math32.Abs(d1)
d2a := math32.Abs(d2)
d3a := math32.Abs(d3)
if d1a < d2a && d1a < d3a {
return d1
}
if d2a < d1a && d2a < d3a {
return d2
}
return d3
}
// Blend returns a color that is the given percent blend between the first
// and second color; 10 = 10% of the first and 90% of the second, etc;
// blending is done directly on non-premultiplied HCT values, and
// a correctly premultiplied color is returned.
func Blend(pct float32, x, y color.Color) color.RGBA {
return BlendHCT(pct, x, y).AsRGBA()
}
// BlendHCT returns the HCT color that [Blend] returns as a [color.RGBA],
// whose unrounded R, G, B, and A values are useful for interpolating
// between blended colors.
func BlendHCT(pct float32, x, y color.Color) HCT {
hx := FromColor(x)
hy := FromColor(y)
pct = math32.Clamp(pct, 0, 100)
px := pct / 100
py := 1 - px
dhue := MinHueDistance(hx.Hue, hy.Hue)
// weight as a function of chroma strength: if near grey, hue is unreliable
cpy := py * hy.Chroma / (px*hx.Chroma + py*hy.Chroma)
hue := hx.Hue + cpy*dhue
chroma := px*hx.Chroma + py*hy.Chroma
tone := px*hx.Tone + py*hy.Tone
hr := New(hue, chroma, tone)
hr.A = px*hx.A + py*hy.A
return hr
}
// IsLight returns whether the given color is light
// (has an HCT tone greater than or equal to 50)
func IsLight(c color.Color) bool {
h := FromColor(c)
return h.Tone >= 50
}
// IsDark returns whether the given color is dark
// (has an HCT tone less than 50)
func IsDark(c color.Color) bool {
h := FromColor(c)
return h.Tone < 50
}
// Copyright (c) 2021, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package hpe provides the Hunt-Pointer-Estevez transform of XYZ colors to
// LMS cone responses, and its inverse.
package hpe
import "cogentcore.org/core/colors/cam/cie"
// XYZToLMS convert XYZ to Long, Medium, Short cone-based responses,
// using the Hunt-Pointer-Estevez transform.
// This is closer to the actual response functions of the L,M,S cones apparently.
func XYZToLMS(x, y, z float32) (l, m, s float32) {
l = 0.38971*x + 0.68898*y + -0.07868*z
m = -0.22981*x + 1.18340*y + 0.04641*z
s = z
return
}
// SRGBLinToLMS converts sRGB linear to Long, Medium, Short cone-based responses,
// using the Hunt-Pointer-Estevez transform.
// This is closer to the actual response functions of the L,M,S cones apparently.
func SRGBLinToLMS(rl, gl, bl float32) (l, m, s float32) {
l = 0.30567503*rl + 0.62274014*gl + 0.04530167*bl
m = 0.15771291*rl + 0.7697197*gl + 0.08807348*bl
s = 0.0193*rl + 0.1192*gl + 0.9505*bl
return
}
// SRGBToLMS converts sRGB to Long, Medium, Short cone-based responses,
// using the Hunt-Pointer-Estevez transform.
// This is closer to the actual response functions of the L,M,S cones apparently.
func SRGBToLMS(r, g, b float32) (l, m, s float32) {
rl, gl, bl := cie.SRGBToLinear(r, g, b)
l, m, s = SRGBLinToLMS(rl, gl, bl)
return
}
/*
func LMStoXYZ(float& X, float& Y, float& Z,
L, M, S) {
X = 1.096124f * L + 0.4296f * Y + -0.1624f * Z;
Y = -0.7036f * X + 1.6975f * Y + 0.0061f * Z;
Z = 0.0030f * X + 0.0136f * Y + 0.9834 * Z;
}
// convert Long, Medium, Short cone-based responses to XYZ, using the Hunt-Pointer-Estevez transform -- this is closer to the actual response functions of the L,M,S cones apparently
*/
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package hsl provides the HSL (hue, saturation, lightness) color space.
package hsl
import (
"fmt"
"image/color"
"cogentcore.org/core/math32"
)
// HSL represents the Hue [0..360], Saturation [0..1], and Luminance
// (lightness) [0..1] of the color using float32 values
// In general the Alpha channel is not used for HSL but is maintained
// so it can be used to fully represent an RGBA color value.
// When converting to RGBA, alpha multiplies the RGB components.
type HSL struct {
// the hue of the color
H float32 `min:"0" max:"360" step:"5"`
// the saturation of the color
S float32 `min:"0" max:"1" step:"0.05"`
// the luminance (lightness) of the color
L float32 `min:"0" max:"1" step:"0.05"`
// the transparency of the color
A float32 `min:"0" max:"1" step:"0.05"`
}
// New returns a new HSL representation for given parameters:
// hue = 0..360
// saturation = 0..1
// lightness = 0..1
// A is automatically set to 1
func New(hue, saturation, lightness float32) HSL {
return HSL{hue, saturation, lightness, 1}
}
// FromColor constructs a new HSL color from a standard [color.Color]
func FromColor(c color.Color) HSL {
h := HSL{}
h.SetColor(c)
return h
}
// Model is the standard [color.Model] that converts colors to HSL.
var Model = color.ModelFunc(model)
func model(c color.Color) color.Color {
if h, ok := c.(HSL); ok {
return h
}
return FromColor(c)
}
// RGBA implements the [color.Color] interface.
// Performs the premultiplication of the RGB components by alpha at this point.
func (h HSL) RGBA() (r, g, b, a uint32) {
fr, fg, fb := HSLtoRGBF32(h.H, h.S, h.L)
r = uint32(fr*h.A*65535.0 + 0.5)
g = uint32(fg*h.A*65535.0 + 0.5)
b = uint32(fb*h.A*65535.0 + 0.5)
a = uint32(h.A*65535.0 + 0.5)
return
}
// AsRGBA returns a standard color.RGBA type
func (h HSL) AsRGBA() color.RGBA {
fr, fg, fb := HSLtoRGBF32(h.H, h.S, h.L)
return color.RGBA{uint8(fr*h.A*255.0 + 0.5), uint8(fg*h.A*255.0 + 0.5), uint8(fb*h.A*255.0 + 0.5), uint8(h.A*255.0 + 0.5)}
}
// SetUint32 sets components from unsigned 32bit integers (alpha-premultiplied)
func (h *HSL) SetUint32(r, g, b, a uint32) {
fa := float32(a) / 65535.0
fr := (float32(r) / 65535.0) / fa
fg := (float32(g) / 65535.0) / fa
fb := (float32(b) / 65535.0) / fa
h.H, h.S, h.L = RGBtoHSLF32(fr, fg, fb)
h.A = fa
}
// SetColor sets from a standard color.Color
func (h *HSL) SetColor(ci color.Color) {
if ci == nil {
*h = HSL{}
return
}
r, g, b, a := ci.RGBA()
h.SetUint32(r, g, b, a)
}
// HSLtoRGBF32 converts HSL values to RGB float32 0..1 values (non alpha-premultiplied) -- based on https://stackoverflow.com/questions/2353211/hsl-to-rgb-color-conversion, https://www.w3.org/TR/css-color-3/ and github.com/lucasb-eyer/go-colorful
func HSLtoRGBF32(h, s, l float32) (r, g, b float32) {
if s == 0 {
r = l
g = l
b = l
return
}
h = h / 360.0 // convert to normalized 0-1 h
var q float32
if l < 0.5 {
q = l * (1.0 + s)
} else {
q = l + s - l*s
}
p := 2.0*l - q
r = HueToRGBF32(p, q, h+1.0/3.0)
g = HueToRGBF32(p, q, h)
b = HueToRGBF32(p, q, h-1.0/3.0)
return
}
func HueToRGBF32(p, q, t float32) float32 {
if t < 0 {
t++
}
if t > 1 {
t--
}
if t < 1.0/6.0 {
return p + (q-p)*6.0*t
}
if t < .5 {
return q
}
if t < 2.0/3.0 {
return p + (q-p)*(2.0/3.0-t)*6.0
}
return p
}
// RGBtoHSLF32 converts RGB 0..1 values (non alpha-premultiplied) to HSL -- based on https://stackoverflow.com/questions/2353211/hsl-to-rgb-color-conversion, https://www.w3.org/TR/css-color-3/ and github.com/lucasb-eyer/go-colorful
func RGBtoHSLF32(r, g, b float32) (h, s, l float32) {
min := math32.Min(math32.Min(r, g), b)
max := math32.Max(math32.Max(r, g), b)
l = (max + min) / 2.0
if min == max {
s = 0
h = 0
} else {
d := max - min
if l > 0.5 {
s = d / (2.0 - max - min)
} else {
s = d / (max + min)
}
switch max {
case r:
h = (g - b) / d
if g < b {
h += 6.0
}
case g:
h = 2.0 + (b-r)/d
case b:
h = 4.0 + (r-g)/d
}
h *= 60
if h < 0 {
h += 360
}
}
return
}
func (h HSL) String() string {
return fmt.Sprintf("hsl(%g, %g, %g)", h.H, h.S, h.L)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package hsl
import (
"image/color"
"cogentcore.org/core/math32"
)
// Lighten returns a color that is lighter by the
// given absolute HSL lightness amount (0-100, ranges enforced)
func Lighten(c color.Color, amount float32) color.RGBA {
h := FromColor(c)
h.L += amount / 100
h.L = math32.Clamp(h.L, 0, 1)
return h.AsRGBA()
}
// Darken returns a color that is darker by the
// given absolute HSL lightness amount (0-100, ranges enforced)
func Darken(c color.Color, amount float32) color.RGBA {
h := FromColor(c)
h.L -= amount / 100
h.L = math32.Clamp(h.L, 0, 1)
return h.AsRGBA()
}
// Highlight returns a color that is lighter or darker by the
// given absolute HSL lightness amount (0-100, ranges enforced),
// making the color darker if it is light (tone >= 0.5) and
// lighter otherwise. It is the opposite of [Samelight].
func Highlight(c color.Color, amount float32) color.RGBA {
h := FromColor(c)
if h.L >= 0.5 {
h.L -= amount / 100
} else {
h.L += amount / 100
}
h.L = math32.Clamp(h.L, 0, 1)
return h.AsRGBA()
}
// Samelight returns a color that is lighter or darker by the
// given absolute HSL lightness amount (0-100, ranges enforced),
// making the color lighter if it is light (tone >= 0.5) and
// darker otherwise. It is the opposite of [Highlight].
func Samelight(c color.Color, amount float32) color.RGBA {
h := FromColor(c)
if h.L >= 0.5 {
h.L += amount / 100
} else {
h.L -= amount / 100
}
h.L = math32.Clamp(h.L, 0, 1)
return h.AsRGBA()
}
// Saturate returns a color that is more saturated by the
// given absolute HSL saturation amount (0-100, ranges enforced)
func Saturate(c color.Color, amount float32) color.RGBA {
h := FromColor(c)
h.S += amount / 100
h.S = math32.Clamp(h.S, 0, 1)
return h.AsRGBA()
}
// Desaturate returns a color that is less saturated by the
// given absolute HSL saturation amount (0-100, ranges enforced)
func Desaturate(c color.Color, amount float32) color.RGBA {
h := FromColor(c)
h.S -= amount / 100
h.S = math32.Clamp(h.S, 0, 1)
return h.AsRGBA()
}
// Spin returns a color that has a different hue by the
// given absolute HSL hue amount (0-360, ranges enforced)
func Spin(c color.Color, amount float32) color.RGBA {
h := FromColor(c)
h.H += amount
h.H = math32.Clamp(h.H, 0, 360)
return h.AsRGBA()
}
// IsLight returns whether the given color is light
// (has an HSL lightness greater than or equal to 0.6)
func IsLight(c color.Color) bool {
h := FromColor(c)
return h.L >= 0.6
}
// IsDark returns whether the given color is dark
// (has an HSL lightness less than 0.6)
func IsDark(c color.Color) bool {
h := FromColor(c)
return h.L < 0.6
}
// ContrastColor returns the color that should
// be used to contrast this color (white or black),
// based on the result of [IsLight].
func ContrastColor(c color.Color) color.RGBA {
if IsLight(c) {
return color.RGBA{0, 0, 0, 255}
}
return color.RGBA{255, 255, 255, 255}
}
// Copyright (c) 2021, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package lms provides the opponent color components of LMS cone responses
// (as red-green and blue-yellow).
package lms
//go:generate core generate
// OpponentValues holds color opponent values based on cone-like L,M,S inputs
// These values are useful for generating inputs to vision models that
// simulate color opponency representations in the brain.
type OpponentValues struct {
// red vs. green (long vs. medium)
RedGreen float32
// blue vs. yellow (short vs. avg(long, medium))
BlueYellow float32
// greyscale luminance channel -- typically use L* from LAB as best
Grey float32
}
// NewOpponentValues returns a new [OpponentValues] from values representing
// the LMS long, medium, short cone responses, and an overall grey value.
func NewOpponentValues(l, m, s, lm, grey float32) OpponentValues {
return OpponentValues{RedGreen: l - m, BlueYellow: s - lm, Grey: grey}
}
// Opponents enumerates the three primary opponency channels:
// [WhiteBlack], [RedGreen], and [BlueYellow] using colloquial
// "everyday" terms.
type Opponents int32 //enums:enum
const (
// White vs. Black greyscale
WhiteBlack Opponents = iota
// Red vs. Green
RedGreen
// Blue vs. Yellow
BlueYellow
)
// Copyright (c) 2019, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package colormap provides color maps, which map values to colors, as for
// plots, with standard maps and lookup tables.
package colormap
import (
"image/color"
"maps"
"sort"
"sync/atomic"
"cogentcore.org/core/colors"
"cogentcore.org/core/math32"
)
// Map maps a value onto a color by interpolating between a list of colors
// defining a spectrum, or optionally as an indexed list of colors.
type Map struct {
// Name is the name of the color map
Name string
// if true, this map should be used as an indexed list instead of interpolating a normalized floating point value: requires caller to check this flag and pass int indexes instead of normalized values to MapIndex
Indexed bool
// the colorspace algorithm to use for blending colors
Blend colors.BlendTypes
// color to display for invalid numbers (e.g., NaN)
NoColor color.RGBA
// list of colors to interpolate between
Colors []color.RGBA
// table is the lookup table of blended colors used by [Map.Map],
// built after lutMinCalls calls and rebuilt when Blend or Colors change.
table atomic.Pointer[lut]
// exactCalls is the number of calls to [Map.Map] blending exactly
// before the table is built.
exactCalls atomic.Int32
}
func (cm *Map) String() string {
return cm.Name
}
// Map returns color for normalized value in range 0-1. NaN returns NoColor
// which can be used to indicate missing values.
// Unless Blend is [colors.RGB], which is fast to blend directly, colors
// between the map colors come from a lookup table of the blended colors,
// built once the map has been used enough for it to pay off, which is
// within one level per channel of the exact blend returned by
// [Map.MapExact] and usually equal to it.
func (cm *Map) Map(val float32) color.RGBA {
return cm.mapValue(val, false)
}
// MapExact returns color for normalized value in range 0-1 like [Map.Map],
// but blends the colors exactly instead of using a lookup table.
func (cm *Map) MapExact(val float32) color.RGBA {
return cm.mapValue(val, true)
}
// mapValue implements [Map.Map] and [Map.MapExact].
func (cm *Map) mapValue(val float32, exact bool) color.RGBA {
nc := len(cm.Colors)
if nc == 0 {
return color.RGBA{}
}
if nc == 1 {
return cm.Colors[0]
}
if math32.IsNaN(val) {
return cm.NoColor
}
if val <= 0 {
return cm.Colors[0]
} else if val >= 1 {
return cm.Colors[nc-1]
}
ival := val * float32(nc-1)
lidx := math32.Floor(ival)
uidx := math32.Ceil(ival)
if lidx == uidx {
return cm.Colors[int(lidx)]
}
if !exact && cm.Blend != colors.RGB {
if lt := cm.lookupTable(); lt != nil {
return lt.lookup(int(lidx), ival-lidx)
}
}
cmix := 100 * (1 - (ival - lidx))
lclr := cm.Colors[int(lidx)]
uclr := cm.Colors[int(uidx)]
return colors.Blend(cm.Blend, cmix, lclr, uclr)
}
// lutMinCalls is the number of calls to [Map.Map] that blend exactly
// before the lookup table is built, which costs about as much as that,
// so that maps used only a little (e.g., to show them) do not build it.
const lutMinCalls = 1000
// lookupTable returns the lookup table for the current Blend and Colors,
// building it if needed, or nil if it is not built yet.
// Concurrent callers may each build a table, and the last one built is kept.
func (cm *Map) lookupTable() *lut {
lt := cm.table.Load()
if lt != nil && lt.matches(cm) {
return lt
}
if lt == nil && cm.exactCalls.Add(1) <= lutMinCalls {
return nil
}
lt = newLUT(cm)
cm.table.Store(lt)
return lt
}
// MapIndex returns color for given index, for scale in Indexed mode.
// NoColor is returned for values out of range of available colors.
// It is responsibility of the caller to use this method instead of Map
// based on the Indexed flag.
func (cm *Map) MapIndex(val int) color.RGBA {
nc := len(cm.Colors)
if val < 0 || val >= nc {
return cm.NoColor
}
return cm.Colors[val]
}
// see https://matplotlib.org/tutorials/colors/colormap-manipulation.html
// for how to read out matplotlib scales -- still don't understand segmented ones!
// StandardMaps is a list of standard color maps
var StandardMaps = map[string]*Map{
"ColdHot": {
Name: "ColdHot",
NoColor: colors.FromRGB(200, 200, 200),
Colors: []color.RGBA{
{0, 255, 255, 255},
{0, 0, 255, 255},
{127, 127, 127, 255},
{255, 0, 0, 255},
{255, 255, 0, 255},
},
},
"Jet": {
Name: "Jet",
NoColor: color.RGBA{200, 200, 200, 255},
Colors: []color.RGBA{
{0, 0, 127, 255},
{0, 0, 255, 255},
{0, 127, 255, 255},
{0, 255, 255, 255},
{127, 255, 127, 255},
{255, 255, 0, 255},
{255, 127, 0, 255},
{255, 0, 0, 255},
{127, 0, 0, 255},
},
},
"JetMuted": {
Name: "JetMuted",
NoColor: color.RGBA{200, 200, 200, 255},
Colors: []color.RGBA{
{25, 25, 153, 255},
{25, 102, 230, 255},
{0, 230, 230, 255},
{0, 179, 0, 255},
{230, 230, 0, 255},
{230, 102, 25, 255},
{153, 25, 25, 255},
},
},
"Viridis": {
Name: "Viridis",
NoColor: color.RGBA{200, 200, 200, 255},
Colors: []color.RGBA{
{72, 33, 114, 255},
{67, 62, 133, 255},
{56, 87, 140, 255},
{45, 111, 142, 255},
{36, 133, 142, 255},
{30, 155, 138, 255},
{42, 176, 127, 255},
{81, 197, 105, 255},
{134, 212, 73, 255},
{194, 223, 35, 255},
{253, 231, 37, 255},
},
},
"Plasma": {
Name: "Plasma",
NoColor: color.RGBA{200, 200, 200, 255},
Colors: []color.RGBA{
{61, 4, 155, 255},
{99, 0, 167, 255},
{133, 6, 166, 255},
{166, 32, 152, 255},
{192, 58, 131, 255},
{213, 84, 110, 255},
{231, 111, 90, 255},
{246, 141, 69, 255},
{253, 174, 50, 255},
{252, 210, 36, 255},
{240, 248, 33, 255},
},
},
"Inferno": {
Name: "Inferno",
NoColor: color.RGBA{200, 200, 200, 255},
Colors: []color.RGBA{
{37, 12, 3, 255},
{19, 11, 52, 255},
{57, 9, 99, 255},
{95, 19, 110, 255},
{133, 33, 107, 255},
{169, 46, 94, 255},
{203, 65, 73, 255},
{230, 93, 47, 255},
{247, 131, 17, 255},
{252, 174, 19, 255},
{245, 219, 76, 255},
{252, 254, 164, 255},
},
},
"BlueRed": {
Name: "BlueRed",
NoColor: color.RGBA{200, 200, 200, 255},
Colors: []color.RGBA{
{0, 0, 255, 255},
{255, 0, 0, 255},
},
},
"BlueBlackRed": {
Name: "BlueBlackRed",
NoColor: color.RGBA{200, 200, 200, 255},
Colors: []color.RGBA{
{0, 0, 255, 255},
{76, 76, 76, 255},
{255, 0, 0, 255},
},
},
"BlueGreyRed": {
Name: "BlueGreyRed",
NoColor: color.RGBA{200, 200, 200, 255},
Colors: []color.RGBA{
{0, 0, 255, 255},
{127, 127, 127, 255},
{255, 0, 0, 255},
},
},
"BlueWhiteRed": {
Name: "BlueWhiteRed",
NoColor: color.RGBA{200, 200, 200, 255},
Colors: []color.RGBA{
{0, 0, 255, 255},
{230, 230, 230, 255},
{255, 0, 0, 255},
},
},
"BlueGreenRed": {
Name: "BlueGreenRed",
NoColor: color.RGBA{200, 200, 200, 255},
Colors: []color.RGBA{
{0, 0, 255, 255},
{0, 230, 0, 255},
{255, 0, 0, 255},
},
},
"Rainbow": {
Name: "Rainbow",
NoColor: color.RGBA{200, 200, 200, 255},
Colors: []color.RGBA{
{255, 0, 255, 255},
{0, 0, 255, 255},
{0, 255, 0, 255},
{255, 255, 0, 255},
{255, 0, 0, 255},
},
},
"ROYGBIV": {
Name: "ROYGBIV",
NoColor: color.RGBA{200, 200, 200, 255},
Colors: []color.RGBA{
{255, 0, 255, 255},
{0, 0, 127, 255},
{0, 0, 255, 255},
{0, 255, 0, 255},
{255, 255, 0, 255},
{255, 0, 0, 255},
},
},
"DarkLight": {
Name: "DarkLight",
NoColor: color.RGBA{200, 200, 200, 255},
Colors: []color.RGBA{
{0, 0, 0, 255},
{250, 250, 250, 255},
},
},
"DarkLightDark": {
Name: "DarkLightDark",
NoColor: color.RGBA{200, 200, 200, 255},
Colors: []color.RGBA{
{0, 0, 0, 255},
{250, 250, 250, 255},
{0, 0, 0, 255},
},
},
"LightDarkLight": {
Name: "DarkLightDark",
NoColor: color.RGBA{200, 200, 200, 255},
Colors: []color.RGBA{
{250, 250, 250, 255},
{0, 0, 0, 255},
{250, 250, 250, 255},
},
},
}
// AvailableMaps is the list of all available color maps
var AvailableMaps = map[string]*Map{}
func init() {
maps.Copy(AvailableMaps, StandardMaps)
}
// AvailableMapsList returns a sorted list of color map names, e.g., for choosers
func AvailableMapsList() []string {
sl := make([]string, len(AvailableMaps))
ctr := 0
for k := range AvailableMaps {
sl[ctr] = k
ctr++
}
sort.Strings(sl)
return sl
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package colormap
import (
"image/color"
"slices"
"cogentcore.org/core/colors"
"cogentcore.org/core/colors/cam/hct"
)
// lut is a lookup table of the blended colors of a [Map], which makes
// [Map.Map] much faster than blending (in HCT space by default) on every
// call. Each segment between two adjacent map colors is divided into
// equal cells, which are bisected where the blend bends more sharply,
// and the exact blended colors at the cell boundaries are stored unrounded.
// A value within a cell is linearly interpolated between the colors at its
// boundaries, which is within one level per channel of the exact blend,
// and usually equal to it (HCT blends also have rare jumps over tiny
// distances, which the table smooths over). The smallest cells where
// interpolation is still not that accurate (e.g., at the sharp bends that
// HCT blending has at the ends of some segments) are marked as exact,
// and their values are blended exactly.
type lut struct {
// blend is the blend type the table was built with.
blend colors.BlendTypes
// colors is a copy of the map colors the table was built with.
colors []color.RGBA
// keys are the colors packed by [colorKey], to check that the
// map colors have not changed.
keys []uint32
// entries are the exact blended colors at the cell boundaries,
// as four unrounded alpha-premultiplied 0-255 channel values each.
entries []float32
// The cells of all segments are the first lutCells for each segment,
// followed by the halves of bisected cells. They are stored as
// separate slices of their fields, which is faster in JavaScript.
// half is the index of the first half of a bisected cell,
// followed by its second half, or 0 if the cell is not bisected.
half []int32
// lo and hi are the indexes in entries of the colors at the
// boundaries of a cell that is not bisected.
lo, hi []int32
// exact is whether colors in a cell that is not bisected must be
// blended exactly, because interpolation is not accurate enough there.
exact []bool
}
// lutColor is an unrounded alpha-premultiplied color with 0-255 channels.
type lutColor [4]float32
const (
// lutCells is the number of cells each segment is divided into
// before bisecting.
lutCells = 16
// lutDepth is the maximum number of times a cell is bisected,
// so the smallest cells are 1/4096 of a segment.
lutDepth = 8
// lutTolerance is the largest difference between an interpolated and
// an exact unrounded channel value, at the middle and quarters of
// a cell, for the cell to be interpolated. It is above the noise of
// about half a level in HCT blends, which are not quite smooth.
lutTolerance = 0.5
// lutEndCheck is the distance from the ends of a segment, as a
// proportion of it, at which cells at the ends are also checked:
// a quarter of the smallest cell.
lutEndCheck = 1.0 / (4 * lutCells << lutDepth)
)
// matches returns whether the table was built for the current
// blend type and colors of the given map.
func (lt *lut) matches(cm *Map) bool {
if lt.blend != cm.Blend || len(lt.colors) != len(cm.Colors) {
return false
}
for i, k := range lt.keys {
if k != colorKey(cm.Colors, i) {
return false
}
}
return true
}
// colorKey returns color i of the given colors packed into a uint32,
// which is faster to compare than the color in JavaScript.
func colorKey(cs []color.RGBA, i int) uint32 {
return uint32(cs[i].R)<<24 | uint32(cs[i].G)<<16 | uint32(cs[i].B)<<8 | uint32(cs[i].A)
}
// lookup returns the color at proportion t (0 < t < 1) along
// segment si, interpolated from the table or blended exactly.
func (lt *lut) lookup(si int, t float32) color.RGBA {
p := t * lutCells
ci := int(p)
if ci >= lutCells {
ci = lutCells - 1
}
f := p - float32(ci)
ci += si * lutCells
for h := int(lt.half[ci]); h != 0; h = int(lt.half[ci]) {
f *= 2
if f < 1 {
ci = h
} else {
f -= 1
ci = h + 1
}
}
if lt.exact[ci] {
return colors.Blend(lt.blend, 100*(1-t), lt.colors[si], lt.colors[si+1])
}
e := lt.entries
a, b := int(lt.lo[ci]), int(lt.hi[ci])
r, g, bl, al := lerp8(e[a], e[b], f), lerp8(e[a+1], e[b+1], f), lerp8(e[a+2], e[b+2], f), lerp8(e[a+3], e[b+3], f)
return color.RGBA{r, g, bl, al}
}
// lerp8 returns the value at proportion f between a and b,
// rounded to 8 bits.
func lerp8(a, b, f float32) uint8 {
return uint8(a + (b-a)*f + 0.5)
}
// newLUT builds the lookup table for the given map, which has at least
// two colors.
func newLUT(cm *Map) *lut {
lt := &lut{blend: cm.Blend, colors: slices.Clone(cm.Colors)}
ns := len(lt.colors) - 1
lt.keys = make([]uint32, ns+1)
for i := range lt.keys {
lt.keys[i] = colorKey(lt.colors, i)
}
for range ns * lutCells {
lt.addCell()
}
for si := range ns {
lo := lt.addEntry(si, 0)
for ci := range lutCells {
hi := lt.addEntry(si, float32(ci+1)/lutCells)
lt.buildCell(si*lutCells+ci, si, float32(ci)/lutCells, 1.0/lutCells, lo, hi, 0)
lo = hi
}
}
return lt
}
// addCell adds a cell, returning its index.
func (lt *lut) addCell() int32 {
lt.half = append(lt.half, 0)
lt.lo = append(lt.lo, 0)
lt.hi = append(lt.hi, 0)
lt.exact = append(lt.exact, false)
return int32(len(lt.half) - 1)
}
// addEntry adds the exact blend at proportion t along segment si
// to the entries, returning its index.
func (lt *lut) addEntry(si int, t float32) int32 {
c := lt.blendAt(si, t)
lt.entries = append(lt.entries, c[:]...)
return int32(len(lt.entries) - 4)
}
// entry returns the entry at index i.
func (lt *lut) entry(i int32) lutColor {
e := lt.entries
return lutColor{e[i], e[i+1], e[i+2], e[i+3]}
}
// buildCell sets cell ci of segment si, starting at proportion t0 along it
// with width w and boundary entries lo and hi, bisecting it until
// interpolating is accurate or it has been bisected depth times.
// The exact color at its middle, used to check it, becomes the
// boundary between its halves.
func (lt *lut) buildCell(ci, si int, t0, w float32, lo, hi int32, depth int) {
mid := lt.addEntry(si, t0+0.5*w)
lt.lo[ci], lt.hi[ci] = lo, hi
if lt.accurate(si, t0, w, lo, hi, mid) {
lt.entries = lt.entries[:mid] // middle not needed
return
}
if depth == lutDepth {
lt.exact[ci] = true
return
}
half := lt.addCell()
lt.addCell()
lt.half[ci] = half
lt.buildCell(int(half), si, t0, 0.5*w, lo, mid, depth+1)
lt.buildCell(int(half)+1, si, t0+0.5*w, 0.5*w, mid, hi, depth+1)
}
// accurate returns whether interpolating between the entries lo and hi
// of the cell starting at proportion t0 along segment si with width w
// is within [lutTolerance] of the exact colors at its middle (entry mid)
// and quarters, in all channels. Cells at the ends of the segment are
// also checked very close to the end, because blending can change sharply
// there (in HCT, the colors just inside a segment can differ by a few
// levels from its end colors).
func (lt *lut) accurate(si int, t0, w float32, lo, hi, mid int32) bool {
a, b := lt.entry(lo), lt.entry(hi)
if !near(a, b, 0.5, lt.entry(mid)) {
return false
}
if t0 == 0 && !near(a, b, lutEndCheck/w, lt.blendAt(si, lutEndCheck)) {
return false
}
if t0+w == 1 && !near(a, b, 1-lutEndCheck/w, lt.blendAt(si, 1-lutEndCheck)) {
return false
}
return near(a, b, 0.25, lt.blendAt(si, t0+0.25*w)) && near(a, b, 0.75, lt.blendAt(si, t0+0.75*w))
}
// near returns whether interpolating at proportion f between a and b
// is within [lutTolerance] of c in all channels.
func near(a, b lutColor, f float32, c lutColor) bool {
for i := range 4 {
d := a[i] + (b[i]-a[i])*f - c[i]
if d > lutTolerance || d < -lutTolerance {
return false
}
}
return true
}
// blendAt returns the unrounded exact blend at proportion t along
// segment si, which rounds to the color that [Map.MapExact] returns.
func (lt *lut) blendAt(si int, t float32) lutColor {
x, y := lt.colors[si], lt.colors[si+1]
pct := 100 * (1 - t)
if lt.blend == colors.HCT {
h := hct.BlendHCT(pct, x, y)
return lutColor{h.R * h.A * 255, h.G * h.A * 255, h.B * h.A * 255, h.A * 255}
}
c := colors.Blend(lt.blend, pct, x, y)
return lutColor{float32(c.R), float32(c.G), float32(c.B), float32(c.A)}
}
// maxChannelDiff returns the largest difference between
// the channels of the two colors.
func maxChannelDiff(a, b color.RGBA) int {
return max(absDiff(a.R, b.R), absDiff(a.G, b.G), absDiff(a.B, b.B), absDiff(a.A, b.A))
}
// absDiff returns the absolute difference between a and b.
func absDiff(a, b uint8) int {
if a > b {
return int(a - b)
}
return int(b - a)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package colors provides named colors, utilities for manipulating colors,
// and Material Design 3 color schemes, palettes, and keys in Go.
package colors
//go:generate core generate
import (
"errors"
"fmt"
"image"
"image/color"
"strconv"
"strings"
"cogentcore.org/core/colors/cam/hct"
"cogentcore.org/core/colors/cam/hsl"
"cogentcore.org/core/math32"
)
// IsNil returns whether the color is the nil initial default color
func IsNil(c color.Color) bool {
return AsRGBA(c) == color.RGBA{}
}
// FromRGB makes a new RGBA color from the given
// RGB uint8 values, using 255 for A.
func FromRGB(r, g, b uint8) color.RGBA {
return color.RGBA{r, g, b, 255}
}
// FromNRGBA makes a new RGBA color from the given
// non-alpha-premultiplied RGBA uint8 values.
func FromNRGBA(r, g, b, a uint8) color.RGBA {
return AsRGBA(color.NRGBA{r, g, b, a})
}
// AsRGBA returns the given color as an RGBA color
func AsRGBA(c color.Color) color.RGBA {
if c == nil {
return color.RGBA{}
}
return color.RGBAModel.Convert(c).(color.RGBA)
}
// FromFloat64 makes a new RGBA color from the given 0-1
// normalized floating point numbers (alpha-premultiplied)
func FromFloat64(r, g, b, a float64) color.RGBA {
return color.RGBA{uint8(r * 255), uint8(g * 255), uint8(b * 255), uint8(a * 255)}
}
// FromFloat32 makes a new RGBA color from the given 0-1
// normalized floating point numbers (alpha-premultiplied)
func FromFloat32(r, g, b, a float32) color.RGBA {
return color.RGBA{uint8(r * 255), uint8(g * 255), uint8(b * 255), uint8(a * 255)}
}
// ToFloat32 returns 0-1 normalized floating point numbers from given color
// (alpha-premultiplied)
func ToFloat32(c color.Color) (r, g, b, a float32) {
f := NRGBAF32Model.Convert(c).(NRGBAF32)
r = f.R
g = f.G
b = f.B
a = f.A
return
}
// ToFloat64 returns 0-1 normalized floating point numbers from given color
// (alpha-premultiplied)
func ToFloat64(c color.Color) (r, g, b, a float64) {
f := NRGBAF32Model.Convert(c).(NRGBAF32)
r = float64(f.R)
g = float64(f.G)
b = float64(f.B)
a = float64(f.A)
return
}
// AsString returns the given color as a string,
// using its String method if it exists, and formatting
// it as rgba(r, g, b, a) otherwise.
func AsString(c color.Color) string {
if s, ok := c.(fmt.Stringer); ok {
return s.String()
}
r := AsRGBA(c)
return fmt.Sprintf("rgba(%d, %d, %d, %d)", r.R, r.G, r.B, r.A)
}
// FromName returns the color value specified
// by the given CSS standard color name.
func FromName(name string) (color.RGBA, error) {
c, ok := Map[name]
if !ok {
return color.RGBA{}, errors.New("colors.FromName: name not found: " + name)
}
return c, nil
}
// FromString returns a color value from the given string.
// FromString accepts the following types of strings: standard
// color names, hex, rgb, rgba, hsl, hsla, hct, and hcta values,
// "none" or "off", or any of the transformations listed below.
// The transformations use the given single base color as their starting
// point; if you do not provide a base color, they will use [Transparent]
// as their starting point. The transformations are:
//
// - currentcolor = base color
// - inverse = inverse of base color
// - lighten-VAL or darken-VAL: VAL is amount to lighten or darken (using HCT), e.g., lighter-10 is 10 higher tone
// - saturate-VAL or desaturate-VAL: manipulates the chroma level in HCT by VAL
// - spin-VAL: manipulates the hue level in HCT by VAL
// - clearer-VAL or opaquer-VAL: manipulates the alpha level by VAL
// - blend-VAL-color: blends given percent of given color relative to base in RGB space
func FromString(str string, base ...color.Color) (color.RGBA, error) {
str = strings.TrimSpace(str) // as after the colon of a style property
if len(str) == 0 { // consider it null
return color.RGBA{}, nil
}
lstr := strings.ToLower(str)
switch {
case lstr[0] == '#':
return FromHex(str)
case strings.HasPrefix(lstr, "rgb("), strings.HasPrefix(lstr, "rgba("):
fs, a := colorArgs(lstr)
if len(fs) < 3 {
return color.RGBA{}, fmt.Errorf("colors.FromString: not enough components in %q", str)
}
if strings.Contains(lstr, ",") { // the legacy syntax: all numbers or all percentages
pcts := 0
for _, f := range fs[:3] {
if strings.HasSuffix(f, "%") {
pcts++
}
}
if pcts != 0 && pcts != 3 {
return color.RGBA{}, fmt.Errorf("colors.FromString: numbers and percentages mixed in %q", str)
}
}
c := func(f string) uint8 { return uint8(math32.Clamp(colorArg(f, 255), 0, 255) + 0.5) }
return FromNRGBA(c(fs[0]), c(fs[1]), c(fs[2]), a), nil
case strings.HasPrefix(lstr, "hsl("), strings.HasPrefix(lstr, "hsla("):
fs, a := colorArgs(lstr)
if len(fs) < 3 {
return color.RGBA{}, fmt.Errorf("colors.FromString: not enough components in %q", str)
}
pct := func(f string) float32 { return colorArg(strings.TrimSuffix(f, "%"), 100) / 100 }
h := colorArg(strings.TrimSuffix(fs[0], "deg"), 360)
return WithA(hsl.New(h, pct(fs[1]), pct(fs[2])), a), nil
case strings.HasPrefix(lstr, "hct("), strings.HasPrefix(lstr, "hcta("):
val := lstr[strings.Index(lstr, "(")+1:]
val = strings.TrimRight(val, ")")
val = strings.Trim(val, "%")
var h, c, t, a int
a = 255
if strings.Count(val, ",") == 3 {
format := "%d,%d,%d,%d"
fmt.Sscanf(val, format, &h, &c, &t, &a)
} else {
format := "%d,%d,%d"
fmt.Sscanf(val, format, &h, &c, &t)
}
return WithA(hct.New(float32(h), float32(c), float32(t)), uint8(a)), nil
case strings.HasPrefix(lstr, "light-dark(") && strings.HasSuffix(lstr, ")"):
// the light color, as for the light color scheme (of CSS, as in
// the SVGs of MDN), which was taken for a lighten-like function
args := str[len("light-dark(") : len(str)-1]
depth := 0
for i, r := range args {
switch r {
case '(':
depth++
case ')':
depth--
case ',':
if depth == 0 {
return FromString(args[:i], base...)
}
}
}
return color.RGBA{}, fmt.Errorf("colors.FromString: light-dark needs two colors: %q", str)
default:
var bc color.Color = Transparent
if len(base) > 0 {
bc = base[0]
}
if hidx := strings.Index(lstr, "-"); hidx > 0 {
cmd := lstr[:hidx]
valstr := lstr[hidx+1:]
val64, err := strconv.ParseFloat(valstr, 32)
if err != nil && cmd != "blend" { // blend handles separately
return color.RGBA{}, fmt.Errorf("colors.FromString: error getting numeric value from %q: %w", valstr, err)
}
val := float32(val64)
switch cmd {
case "lighten":
return hct.Lighten(bc, val), nil
case "darken":
return hct.Darken(bc, val), nil
case "highlight":
return hct.Highlight(bc, val), nil
case "samelight":
return hct.Samelight(bc, val), nil
case "saturate":
return hct.Saturate(bc, val), nil
case "desaturate":
return hct.Desaturate(bc, val), nil
case "spin":
return hct.Spin(bc, val), nil
case "clearer":
return Clearer(bc, val), nil
case "opaquer":
return Opaquer(bc, val), nil
case "blend":
clridx := strings.Index(valstr, "-")
if clridx < 0 {
return color.RGBA{}, fmt.Errorf("colors.FromString: blend color spec not found; format is: blend-PCT-color, got: %v; PCT-color is: %v", lstr, valstr)
}
bvalstr := valstr[:clridx]
val64, err := strconv.ParseFloat(bvalstr, 32)
if err != nil {
return color.RGBA{}, fmt.Errorf("colors.FromString: error getting numeric value from %q: %w", bvalstr, err)
}
val := float32(val64)
clrstr := valstr[clridx+1:]
othc, err := FromString(clrstr, bc)
return BlendRGB(val, bc, othc), err
}
}
switch lstr {
case "none", "off":
return color.RGBA{}, nil
case "transparent":
return Transparent, nil
case "currentcolor":
return AsRGBA(bc), nil
case "inverse":
return Inverse(bc), nil
default:
return FromName(lstr)
}
}
}
// FromAny returns a color from the given value of any type.
// It handles values of types string, [color.Color], [*color.Color],
// [image.Image], and [*image.Image]. It takes an optional base color
// for relative transformations
// (see [FromString]).
func FromAny(val any, base ...color.Color) (color.RGBA, error) {
switch vv := val.(type) {
case string:
return FromString(vv, base...)
case color.Color:
return AsRGBA(vv), nil
case *color.Color:
return AsRGBA(*vv), nil
case image.Image:
return ToUniform(vv), nil
case *image.Image:
return ToUniform(*vv), nil
default:
return color.RGBA{}, fmt.Errorf("colors.FromAny: could not get color from value %v of type %T", val, val)
}
}
// FromHex parses the given non-alpha-premultiplied hex color string
// and returns the resulting alpha-premultiplied color.
func FromHex(hex string) (color.RGBA, error) {
hex = strings.TrimPrefix(hex, "#")
var r, g, b, a int
a = 255
if len(hex) == 3 {
format := "%1x%1x%1x"
fmt.Sscanf(hex, format, &r, &g, &b)
r |= r << 4
g |= g << 4
b |= b << 4
} else if len(hex) == 4 { // #RGBA, as in CSS
format := "%1x%1x%1x%1x"
fmt.Sscanf(hex, format, &r, &g, &b, &a)
r |= r << 4
g |= g << 4
b |= b << 4
a |= a << 4
} else if len(hex) == 6 {
format := "%02x%02x%02x"
fmt.Sscanf(hex, format, &r, &g, &b)
} else if len(hex) == 8 {
format := "%02x%02x%02x%02x"
fmt.Sscanf(hex, format, &r, &g, &b, &a)
} else {
return color.RGBA{}, fmt.Errorf("colors.FromHex: could not process %q", hex)
}
return AsRGBA(color.NRGBA{uint8(r), uint8(g), uint8(b), uint8(a)}), nil
}
// AsHex returns the color as a standard 2-hexadecimal-digits-per-component
// non-alpha-premultiplied hex color string.
func AsHex(c color.Color) string {
if c == nil {
return "nil"
}
r := color.NRGBAModel.Convert(c).(color.NRGBA)
// The hex digits are looked up, as this is called for every color
// rendered on the web.
hex := "#" + hexBytes[r.R] + hexBytes[r.G] + hexBytes[r.B]
if r.A == 255 {
return hex
}
return hex + hexBytes[r.A]
}
// hexBytes holds the two upper case hex digits of each byte value.
var hexBytes = func() (hb [256]string) {
const digits = "0123456789ABCDEF"
for i := range hb {
hb[i] = string([]byte{digits[i>>4], digits[i&0xF]})
}
return
}()
// WithR returns the given color with the red
// component (R) set to the given alpha-premultiplied value
func WithR(c color.Color, r uint8) color.RGBA {
rc := AsRGBA(c)
rc.R = r
return rc
}
// WithG returns the given color with the green
// component (G) set to the given alpha-premultiplied value
func WithG(c color.Color, g uint8) color.RGBA {
rc := AsRGBA(c)
rc.G = g
return rc
}
// WithB returns the given color with the blue
// component (B) set to the given alpha-premultiplied value
func WithB(c color.Color, b uint8) color.RGBA {
rc := AsRGBA(c)
rc.B = b
return rc
}
// WithA returns the given color with the
// transparency (A) set to the given value,
// with the color premultiplication updated.
func WithA(c color.Color, a uint8) color.RGBA {
n := color.NRGBAModel.Convert(c).(color.NRGBA)
n.A = a
return AsRGBA(n)
}
// WithAF32 returns the given color with the
// transparency (A) set to the given float32 value
// between 0 and 1, with the color premultiplication updated.
func WithAF32(c color.Color, a float32) color.RGBA {
n := color.NRGBAModel.Convert(c).(color.NRGBA)
a = math32.Clamp(a, 0, 1)
n.A = uint8(a * 255)
return AsRGBA(n)
}
// ApplyOpacity applies the given opacity (0-1) to the given color
// and returns the result. It is different from [WithAF32] in that it
// sets the transparency (A) value of the color to the current value
// times the given value instead of just directly overriding it.
func ApplyOpacity(c color.Color, opacity float32) color.RGBA {
r := AsRGBA(c)
if opacity >= 1 {
return r
}
a := r.A
// new A is current A times opacity
return WithA(c, uint8(float32(a)*opacity))
}
// ApplyOpacityNRGBA applies the given opacity (0-1) to the given color
// and returns the result. It is different from [WithAF32] in that it
// sets the transparency (A) value of the color to the current value
// times the given value instead of just directly overriding it.
// It is the [color.NRGBA] version of [ApplyOpacity].
func ApplyOpacityNRGBA(c color.Color, opacity float32) color.NRGBA {
r := color.NRGBAModel.Convert(c).(color.NRGBA)
if opacity >= 1 {
return r
}
a := r.A
// new A is current A times opacity
return color.NRGBA{r.R, r.G, r.B, uint8(float32(a) * opacity)}
}
// Clearer returns a color that is the given amount
// more transparent (lower alpha value) in terms of
// RGBA absolute alpha from 0 to 100, with the color
// premultiplication updated.
func Clearer(c color.Color, amount float32) color.RGBA {
f32 := NRGBAF32Model.Convert(c).(NRGBAF32)
f32.A -= amount / 100
f32.A = math32.Clamp(f32.A, 0, 1)
return AsRGBA(f32)
}
// Opaquer returns a color that is the given amount
// more opaque (higher alpha value) in terms of
// RGBA absolute alpha from 0 to 100,
// with the color premultiplication updated.
func Opaquer(c color.Color, amount float32) color.RGBA {
f32 := NRGBAF32Model.Convert(c).(NRGBAF32)
f32.A += amount / 100
f32.A = math32.Clamp(f32.A, 0, 1)
return AsRGBA(f32)
}
// Inverse returns the inverse of the given color
// (255 - each component). It does not change the
// alpha channel.
func Inverse(c color.Color) color.RGBA {
r := AsRGBA(c)
return color.RGBA{255 - r.R, 255 - r.G, 255 - r.B, r.A}
}
// Add adds given color deltas to this color, safely avoiding overflow > 255
func Add(c, dc color.Color) color.RGBA {
r, g, b, a := c.RGBA() // uint32
dr, dg, db, da := dc.RGBA() // uint32
r = (r + dr) >> 8
g = (g + dg) >> 8
b = (b + db) >> 8
a = (a + da) >> 8
if r > 255 {
r = 255
}
if g > 255 {
g = 255
}
if b > 255 {
b = 255
}
if a > 255 {
a = 255
}
return color.RGBA{uint8(r), uint8(g), uint8(b), uint8(a)}
}
// Sub subtracts given color deltas from this color, safely avoiding underflow < 0
func Sub(c, dc color.Color) color.RGBA {
r, g, b, a := c.RGBA() // uint32
dr, dg, db, da := dc.RGBA() // uint32
r = (r - dr) >> 8
g = (g - dg) >> 8
b = (b - db) >> 8
a = (a - da) >> 8
if r > 255 { // overflow
r = 0
}
if g > 255 {
g = 0
}
if b > 255 {
b = 0
}
if a > 255 {
a = 0
}
return color.RGBA{uint8(r), uint8(g), uint8(b), uint8(a)}
}
// colorArgs returns the components of the given color function (as
// rgb(...)), separated by commas, spaces, or a slash (before the alpha, as
// in CSS), and its alpha, which is 255 (opaque) if it has none: a fraction
// from 0 to 1 or a percentage, as in CSS, or else a number from 0 to 255.
func colorArgs(fn string) ([]string, uint8) {
val := fn[strings.Index(fn, "(")+1:]
val = strings.TrimSpace(strings.TrimSuffix(strings.TrimSpace(val), ")"))
fs := strings.Fields(strings.NewReplacer(",", " ", "/", " ").Replace(val))
a := uint8(255)
if len(fs) > 3 {
f := fs[3]
if pct, ok := strings.CutSuffix(f, "%"); ok {
v, _ := strconv.ParseFloat(pct, 32)
a = uint8(math32.Clamp(float32(v)/100, 0, 1)*255 + 0.5)
} else if v, err := strconv.ParseFloat(f, 32); err == nil {
if v <= 1 {
v *= 255
}
a = uint8(math32.Clamp(float32(v), 0, 255) + 0.5)
}
}
return fs, a
}
// colorArg returns the value of the given component of a color function:
// a number, or a percentage of the given full value.
func colorArg(f string, full float32) float32 {
if pct, ok := strings.CutSuffix(f, "%"); ok {
v, _ := strconv.ParseFloat(pct, 32)
return float32(v) / 100 * full
}
v, _ := strconv.ParseFloat(f, 32)
return float32(v)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package colors
import (
"image"
"image/color"
)
// Context contains information about the context in which color parsing occurs.
type Context interface {
// Base returns the base color that the color parsing is relative top
Base() color.RGBA
// ImageByURL returns the [image.Image] associated with the given URL.
// Typical URL formats are HTTP URLs like "https://example.com" and node
// URLs like "#name". If it returns nil, that indicats that there is no
// [image.Image] color associated with the given URL.
ImageByURL(url string) image.Image
}
// BaseContext returns a basic [Context] based on the given base color.
func BaseContext(base color.RGBA) Context {
return &baseContext{base}
}
type baseContext struct {
base color.RGBA
}
func (bc *baseContext) Base() color.RGBA {
return bc.base
}
func (bc *baseContext) ImageByURL(url string) image.Image {
return nil
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gradient
import (
"image"
"image/color"
"cogentcore.org/core/colors"
)
// ApplyFunc is a function that transforms input color to an output color.
type ApplyFunc func(c color.Color) color.Color
// ApplyFuncs is a slice of ApplyFunc color functions applied in order
type ApplyFuncs []ApplyFunc
// Add adds a new function
func (af *ApplyFuncs) Add(fun ApplyFunc) {
*af = append(*af, fun)
}
// Apply applies all functions in order to given input color
func (af ApplyFuncs) Apply(c color.Color) color.Color {
for _, f := range af {
c = f(c)
}
return c
}
func (af ApplyFuncs) Clone() ApplyFuncs {
n := len(af)
if n == 0 {
return nil
}
c := make(ApplyFuncs, n)
copy(c, af)
return c
}
// Applier is an image.Image wrapper that applies a color transformation
// to the output of a source image, using the given ApplyFunc
type Applier struct {
image.Image
Func ApplyFunc
}
// NewApplier returns a new applier for given image and apply function
func NewApplier(img image.Image, fun func(c color.Color) color.Color) *Applier {
return &Applier{Image: img, Func: fun}
}
func (ap *Applier) At(x, y int) color.Color {
return ap.Func(ap.Image.At(x, y))
}
// Apply returns a copy of the given image with the given color function
// applied to each pixel of the image, handling special cases:
// [image.Uniform] is optimized and must be preserved as such: color is directly updated.
// [gradient.Gradient] must have Update called prior to rendering, with
// the current bounding box.
func Apply(img image.Image, f ApplyFunc) image.Image {
if img == nil {
return nil
}
switch im := img.(type) {
case *image.Uniform:
return image.NewUniform(f(colors.AsRGBA(im)))
case Gradient:
cp := CopyOf(im)
if cp == nil { // a gradient that cannot be copied
return NewApplier(img, f)
}
cp.AsBase().ApplyFuncs.Add(f)
return cp
default:
return NewApplier(img, f)
}
}
// ApplyOpacity applies the given opacity (0-1) to the given image,
// handling the following special cases, and using an Applier for the general case.
// [image.Uniform] is optimized and must be preserved as such: color is directly updated.
// [gradient.Gradient] must have Update called prior to rendering, with
// the current bounding box. Multiplies the opacity of the stops.
func ApplyOpacity(img image.Image, opacity float32) image.Image {
if img == nil {
return nil
}
if opacity == 1 {
return img
}
switch im := img.(type) {
case *image.Uniform:
return image.NewUniform(colors.ApplyOpacity(colors.AsRGBA(im), opacity))
case Gradient:
cp := CopyOf(im)
if cp == nil { // a gradient that cannot be copied
return NewApplier(img, func(c color.Color) color.Color {
return colors.ApplyOpacity(c, opacity)
})
}
if len(cp.AsBase().Stops) == 0 { // as a Copier
cp.AsBase().ApplyFuncs.Add(func(c color.Color) color.Color { return colors.ApplyOpacity(c, opacity) })
return cp
}
cp.AsBase().ApplyOpacityToStops(opacity)
return cp
default:
return NewApplier(img, func(c color.Color) color.Color {
return colors.ApplyOpacity(c, opacity)
})
}
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on https://github.com/srwiley/rasterx:
// Copyright 2018 by the rasterx Authors. All rights reserved.
// Created 2018 by S.R.Wiley
// Package gradient provides linear, radial, and conic color gradients.
package gradient
//go:generate core generate
import (
"image"
"image/color"
"cogentcore.org/core/colors"
"cogentcore.org/core/math32"
)
// Gradient is the interface that all gradient types satisfy.
type Gradient interface {
image.Image
// AsBase returns the [Base] of the gradient
AsBase() *Base
// Update updates the computed fields of the gradient, using
// the given object opacity, current bounding box, and additional
// object-level transform (i.e., the current painting transform),
// which is applied in addition to the gradient's own Transform.
// This must be called before rendering the gradient, and it should only be called then.
Update(opacity float32, box math32.Box2, objTransform math32.Matrix2)
}
// Base contains the data and logic common to all gradient types.
type Base struct { //types:add -setters
// the stops for the gradient; use AddStop to add stops
Stops []Stop `set:"-"`
// the spread method used for the gradient if it stops before the end
Spread Spreads
// the colorspace algorithm to use for blending colors
Blend colors.BlendTypes
// the units to use for the gradient
Units Units
// the bounding box of the object with the gradient; this is used when rendering
// gradients with [Units] of [ObjectBoundingBox].
Box math32.Box2
// Transform is the gradient's own transformation matrix applied to the gradient's points.
// This is a property of the Gradient itself.
Transform math32.Matrix2
// Opacity is the overall object opacity multiplier, applied in conjunction with the
// stop-level opacity blending.
Opacity float32
// ApplyFuncs contains functions that are applied to the color after gradient color is generated.
// This allows for efficient StateLayer and other post-processing effects
// to be applied. The Applier handles other cases, but gradients always
// must have the Update function called at render time, so they must
// remain Gradient types.
ApplyFuncs ApplyFuncs `set:"-"`
// boxTransform is the Transform applied to the bounding Box,
// only for [Units] == [ObjectBoundingBox].
boxTransform math32.Matrix2 `set:"-"`
// stopsRGB are the computed RGB stops for blend types other than RGB
stopsRGB []Stop `set:"-"`
// stopsRGBSrc are the source Stops when StopsRGB were last computed
stopsRGBSrc []Stop `set:"-"`
}
// Stop represents a single stop in a gradient
type Stop struct {
// Color of the stop. These should be fully opaque,
// with opacity specified separately, for best results, as is done in SVG etc.
Color color.RGBA
// Pos is the position of the stop in normalized units between 0 and 1.
Pos float32
// Opacity is the 0-1 level of opacity for this stop.
Opacity float32
}
// OpacityColor returns the stop color with its opacity applied,
// along with a global opacity multiplier
func (st *Stop) OpacityColor(opacity float32, apply ApplyFuncs) color.Color {
return apply.Apply(colors.ApplyOpacity(st.Color, st.Opacity*opacity))
}
// Spreads are the spread methods used when a gradient reaches
// its end but the object isn't yet fully filled.
type Spreads int32 //enums:enum -transform lower
const (
// Pad indicates to have the final color of the gradient fill
// the object beyond the end of the gradient.
Pad Spreads = iota
// Reflect indicates to have a gradient repeat in reverse order
// (offset 1 to 0) to fully fill an object beyond the end of the gradient.
Reflect
// Repeat indicates to have a gradient continue in its original order
// (offset 0 to 1) by jumping back to the start to fully fill an object beyond
// the end of the gradient.
Repeat
)
// Units are the types of units used for gradient coordinate values
type Units int32 //enums:enum -transform lower-camel
const (
// ObjectBoundingBox indicates that coordinate values are scaled
// relative to the size of the object and are specified in the
// normalized range of 0 to 1.
ObjectBoundingBox Units = iota
// UserSpaceOnUse indicates that coordinate values are specified
// in the current user coordinate system when the gradient is used
// (ie: actual SVG/core coordinates).
UserSpaceOnUse
)
// AddStop adds a new stop with the given color, position, and
// optional opacity to the gradient.
func (b *Base) AddStop(color color.RGBA, pos float32, opacity ...float32) *Base {
op := float32(1)
if len(opacity) > 0 {
op = opacity[0]
}
b.Stops = append(b.Stops, Stop{Color: color, Pos: pos, Opacity: op})
return b
}
// AsBase returns the [Base] of the gradient
func (b *Base) AsBase() *Base {
return b
}
// NewBase returns a new [Base] with default values. It should
// only be used in the New functions of gradient types.
func NewBase() Base {
return Base{
Blend: colors.RGB,
Box: math32.B2(0, 0, 100, 100),
Opacity: 1,
Transform: math32.Identity2(),
}
}
// ColorModel returns the color model used by the gradient image, which is [color.RGBAModel]
func (b *Base) ColorModel() color.Model {
return color.RGBAModel
}
// Bounds returns the bounds of the gradient image, which are infinite.
func (b *Base) Bounds() image.Rectangle {
return image.Rect(-1e9, -1e9, 1e9, 1e9)
}
// CopyFrom copies from the given gradient (cp) onto this gradient (g),
// making new copies of the stops instead of re-using pointers.
// It assumes the gradients are of the same type.
func CopyFrom(g Gradient, cp Gradient) {
switch g := g.(type) {
case *Linear:
*g = *cp.(*Linear)
case *Radial:
*g = *cp.(*Radial)
}
cb := cp.AsBase()
gb := g.AsBase()
gb.CopyStopsFrom(cb)
gb.ApplyFuncs = cb.ApplyFuncs.Clone()
}
// CopyOf returns a copy of the given gradient, making copies of the stops
// instead of re-using pointers.
func CopyOf(g Gradient) Gradient {
var res Gradient
switch g := g.(type) {
case *Linear:
res = &Linear{}
CopyFrom(res, g)
case *Radial:
res = &Radial{}
CopyFrom(res, g)
case Copier:
res = g.CopyGradient()
}
return res
}
// Copier is a [Gradient] of another type than [Linear] and [Radial] (as
// the patterns of SVG, and the masked backgrounds of HTML) that can be
// copied, by [CopyOf]. Its color should have the [Base.ApplyFuncs] of its
// copy applied to it.
type Copier interface {
Gradient
// CopyGradient returns a copy of the gradient, with a copy of its Base.
CopyGradient() Gradient
}
// CopyStopsFrom copies the base gradient stops from the given base gradient
func (b *Base) CopyStopsFrom(cp *Base) {
b.Stops = make([]Stop, len(cp.Stops))
copy(b.Stops, cp.Stops)
if cp.stopsRGB == nil {
b.stopsRGB = nil
b.stopsRGBSrc = nil
} else {
b.stopsRGB = make([]Stop, len(cp.stopsRGB))
copy(b.stopsRGB, cp.stopsRGB)
b.stopsRGBSrc = make([]Stop, len(cp.stopsRGBSrc))
copy(b.stopsRGBSrc, cp.stopsRGBSrc)
}
}
// ApplyOpacityToStops multiplies all stop opacities by the given opacity.
func (b *Base) ApplyOpacityToStops(opacity float32) {
// the stops are changed in place (not copies of them in a range)
for i := range b.Stops {
b.Stops[i].Opacity *= opacity
}
for i := range b.stopsRGB {
b.stopsRGB[i].Opacity *= opacity
}
for i := range b.stopsRGBSrc {
b.stopsRGBSrc[i].Opacity *= opacity
}
}
// updateBase updates the computed fields of the base gradient. It should only be called
// by other gradient types in their [Gradient.Update] functions. It is named updateBase
// to avoid people accidentally calling it instead of [Gradient.Update].
func (b *Base) updateBase() {
b.computeObjectMatrix()
b.updateRGBStops()
}
// computeObjectMatrix computes the effective object transformation
// matrix for a gradient with [Units] of [ObjectBoundingBox], setting
// [Base.boxTransform].
func (b *Base) computeObjectMatrix() {
w, h := b.Box.Size().X, b.Box.Size().Y
oriX, oriY := b.Box.Min.X, b.Box.Min.Y
b.boxTransform = math32.Identity2().Translate(oriX, oriY).Scale(w, h).Mul(b.Transform).
Scale(1/w, 1/h).Translate(-oriX, -oriY).Inverse()
}
// getColor returns the color at the given normalized position along the
// gradient's stops using its spread method and blend algorithm.
func (b *Base) getColor(pos float32) color.Color {
if b.Blend == colors.RGB {
return b.getColorImpl(pos, b.Stops)
}
return b.getColorImpl(pos, b.stopsRGB)
}
// getColorImpl implements [Base.getColor] with given stops
func (b *Base) getColorImpl(pos float32, stops []Stop) color.Color {
d := len(stops)
// These cases can be taken care of early on
if b.Spread == Pad {
if pos >= 1 {
return stops[d-1].OpacityColor(b.Opacity, b.ApplyFuncs)
}
if pos <= 0 {
return stops[0].OpacityColor(b.Opacity, b.ApplyFuncs)
}
}
modRange := float32(1)
if b.Spread == Reflect {
modRange = 2
}
mod := math32.Mod(pos, modRange)
if mod < 0 {
mod += modRange
}
place := 0 // Advance to place where mod is greater than the indicated stop
for place != len(stops) && mod > stops[place].Pos {
place++
}
switch b.Spread {
case Repeat:
var s1, s2 Stop
switch place {
case 0, d:
s1, s2 = stops[d-1], stops[0]
default:
s1, s2 = stops[place-1], stops[place]
}
return b.blendStops(mod, s1, s2, false)
case Reflect:
switch place {
case 0:
return stops[0].OpacityColor(b.Opacity, b.ApplyFuncs)
case d:
// Advance to place where mod-1 is greater than the stop indicated by place in reverse of the stop slice.
// Since this is the reflect b.Spread mode, the mod interval is two, allowing the stop list to be
// iterated in reverse before repeating the sequence.
for place != d*2 && mod-1 > (1-stops[d*2-place-1].Pos) {
place++
}
switch place {
case d:
return stops[d-1].OpacityColor(b.Opacity, b.ApplyFuncs)
case d * 2:
return stops[0].OpacityColor(b.Opacity, b.ApplyFuncs)
default:
return b.blendStops(mod-1, stops[d*2-place], stops[d*2-place-1], true)
}
default:
return b.blendStops(mod, stops[place-1], stops[place], false)
}
default: // PadSpread
switch place {
case 0:
return stops[0].OpacityColor(b.Opacity, b.ApplyFuncs)
case d:
return stops[d-1].OpacityColor(b.Opacity, b.ApplyFuncs)
default:
return b.blendStops(mod, stops[place-1], stops[place], false)
}
}
}
// blendStops blends the given two gradient stops together based on the given position,
// using the gradient's blending algorithm. If flip is true, it flips the given position.
func (b *Base) blendStops(pos float32, s1, s2 Stop, flip bool) color.Color {
s1off := s1.Pos
if s1.Pos > s2.Pos && !flip { // happens in repeat spread mode
s1off--
if pos > 1 {
pos--
}
}
if s2.Pos == s1off {
return s2.OpacityColor(b.Opacity, b.ApplyFuncs)
}
if flip {
pos = 1 - pos
}
tp := (pos - s1off) / (s2.Pos - s1off)
opacity := (s1.Opacity*(1-tp) + s2.Opacity*tp) * b.Opacity
return b.ApplyFuncs.Apply(colors.ApplyOpacity(colors.Blend(colors.RGB, 100*(1-tp), s1.Color, s2.Color), opacity))
}
// updateRGBStops updates stopsRGB from original Stops, for other blend types
func (b *Base) updateRGBStops() {
if b.Blend == colors.RGB || len(b.Stops) == 0 {
b.stopsRGB = nil
b.stopsRGBSrc = nil
return
}
n := len(b.Stops)
lenEq := false
if len(b.stopsRGBSrc) == n {
lenEq = true
equal := true
for i := range b.Stops {
if b.Stops[i] != b.stopsRGBSrc[i] {
equal = false
break
}
}
if equal {
return
}
}
if !lenEq {
b.stopsRGBSrc = make([]Stop, n)
}
copy(b.stopsRGBSrc, b.Stops)
b.stopsRGB = make([]Stop, 0, n*4)
tdp := float32(0.05)
b.stopsRGB = append(b.stopsRGB, b.Stops[0])
for i := 0; i < n-1; i++ {
sp := b.Stops[i]
s := b.Stops[i+1]
dp := s.Pos - sp.Pos
np := int(math32.Ceil(dp / tdp))
if np == 1 {
b.stopsRGB = append(b.stopsRGB, s)
continue
}
pct := float32(1) / float32(np)
dopa := s.Opacity - sp.Opacity
for j := range np {
p := pct * float32(j)
c := colors.Blend(colors.RGB, 100*p, s.Color, sp.Color)
pos := sp.Pos + p*dp
opa := sp.Opacity + p*dopa
b.stopsRGB = append(b.stopsRGB, Stop{Color: c, Pos: pos, Opacity: opa})
}
b.stopsRGB = append(b.stopsRGB, s)
}
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on https://github.com/srwiley/rasterx:
// Copyright 2018 by the rasterx Authors. All rights reserved.
// Created 2018 by S.R.Wiley
package gradient
import (
"image/color"
"cogentcore.org/core/math32"
)
// Linear represents a linear gradient along linear axis from Start to End.
// It implements the [image.Image] interface.
type Linear struct { //types:add -setters
Base
// the starting point of the gradient axis (x1 and y1 in SVG).
Start math32.Vector2
// the ending point of the gradient (x2 and y2 in SVG)
End math32.Vector2
// computed current render versions transformed by object matrix
rStart math32.Vector2
rEnd math32.Vector2
distance math32.Vector2
distanceLengthSquared float32
}
var _ Gradient = &Linear{}
// NewLinear returns a new left-to-right [Linear] gradient.
func NewLinear() *Linear {
return &Linear{
Base: NewBase(),
// default in SVG is LTR
End: math32.Vec2(1, 0),
}
}
// AddStop adds a new stop with the given color, position, and
// optional opacity to the gradient.
func (l *Linear) AddStop(color color.RGBA, pos float32, opacity ...float32) *Linear {
l.Base.AddStop(color, pos, opacity...)
return l
}
// Update updates the computed fields of the gradient, using
// the given current bounding box, and additional
// object-level transform (i.e., the current painting transform),
// which is applied in addition to the gradient's own Transform.
// This must be called before rendering the gradient, and it should only be called then.
func (l *Linear) Update(opacity float32, box math32.Box2, objTransform math32.Matrix2) {
l.Box = box
l.Opacity = opacity
l.updateBase()
if l.Units == ObjectBoundingBox {
sz := l.Box.Size()
l.rStart = l.Box.Min.Add(sz.Mul(l.Start))
l.rEnd = l.Box.Min.Add(sz.Mul(l.End))
} else {
l.rStart = l.Transform.MulPoint(l.Start)
l.rEnd = l.Transform.MulPoint(l.End)
l.rStart = objTransform.MulPoint(l.rStart)
l.rEnd = objTransform.MulPoint(l.rEnd)
}
l.distance = l.rEnd.Sub(l.rStart)
l.distanceLengthSquared = l.distance.LengthSquared()
}
// TransformedAxis returns the Start and End axis points as transformed
// by the last Update call.
func (l *Linear) TransformedAxis() (start, end math32.Vector2) {
return l.rStart, l.rEnd
}
// At returns the color of the linear gradient at the given point
func (l *Linear) At(x, y int) color.Color {
switch len(l.Stops) {
case 0:
return color.RGBA{}
case 1:
return l.Stops[0].OpacityColor(l.Opacity, l.ApplyFuncs)
}
pt := math32.Vec2(float32(x)+0.5, float32(y)+0.5)
if l.Units == ObjectBoundingBox {
pt = l.boxTransform.MulPoint(pt)
}
df := pt.Sub(l.rStart)
pos := (l.distance.X*df.X + l.distance.Y*df.Y) / l.distanceLengthSquared
return l.getColor(pos)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// color parsing is adapted from github.com/srwiley/oksvg:
//
// Copyright 2017 The oksvg Authors. All rights reserved.
//
// created: 2/12/2017 by S.R.Wiley
package gradient
import (
"encoding/xml"
"fmt"
"image"
"image/color"
"io"
"log/slog"
"strconv"
"strings"
"sync"
"cogentcore.org/core/base/iox/xmlx"
"cogentcore.org/core/colors"
"cogentcore.org/core/math32"
)
// XMLAttr searches for given attribute in slice of xml attributes;
// returns "" if not found.
func XMLAttr(name string, attrs []xml.Attr) string {
for _, attr := range attrs {
if attr.Name.Local == name {
return attr.Value
}
}
return ""
}
// Cache is a cache of the [image.Image] results of [FromString] calls
// for each string passed to [FromString]. It is used by the goroutines
// of different windows under a mutex, so it must only be cleared with
// [ClearCache].
var Cache map[string]image.Image
// cacheMu protects [Cache].
var cacheMu sync.Mutex
// ClearCache clears [Cache], as is needed when the colors of the color
// scheme that it uses have changed.
func ClearCache() {
cacheMu.Lock()
defer cacheMu.Unlock()
clear(Cache)
}
// cached returns the cached image for the given string, if any.
func cached(str string) (image.Image, bool) {
cacheMu.Lock()
defer cacheMu.Unlock()
img, ok := Cache[str]
return img, ok
}
// setCached caches the given image for the given string.
func setCached(str string, img image.Image) {
cacheMu.Lock()
defer cacheMu.Unlock()
if Cache == nil {
Cache = make(map[string]image.Image)
}
Cache[str] = img
}
// FromString parses the given CSS image/gradient/color string and returns the resulting image.
// FromString is based on https://www.w3schools.com/css/css3_gradients.asp.
// See [UnmarshalXML] for an XML-based version. If no Context is
// provied, FromString uses [BaseContext] with [Transparent].
func FromString(str string, ctx ...colors.Context) (image.Image, error) {
var cc colors.Context
if len(ctx) > 0 && ctx[0] != nil {
cc = ctx[0]
} else {
cc = colors.BaseContext(colors.Transparent)
}
cnm := str
if img, ok := cached(cnm); ok {
// TODO(kai): do we need to clone?
return img, nil
}
str = strings.TrimSpace(str)
if strings.HasPrefix(str, "url(") {
// A url that is not found (or is of an element that is not
// supported, as an SVG pattern) paints nothing, as in browsers.
img := cc.ImageByURL(str)
if img == nil {
slog.Debug("gradient: unable to find url", "url", str)
}
return img, nil
}
str = strings.ToLower(str)
if str == "none" || str == "" {
return nil, nil
}
grad := "-gradient"
gidx := strings.Index(str, grad)
if gidx <= 0 {
s, err := colors.FromString(str, cc.Base())
if err != nil {
return nil, err
}
return colors.Uniform(s), nil
}
gtyp := str[:gidx]
rmdr := str[gidx+len(grad):]
_, after, ok := strings.Cut(rmdr, "(")
if !ok {
return nil, fmt.Errorf("gradient specified but parameters not found in string %q", str)
}
pars := after
pars = strings.TrimSuffix(pars, ");")
pars = strings.TrimSuffix(pars, ")")
switch gtyp {
case "linear", "repeating-linear":
l := NewLinear()
if gtyp == "repeating-linear" {
l.SetSpread(Repeat)
}
err := l.SetString(pars)
if err != nil {
return nil, err
}
fixGradientStops(l.Stops)
setCached(cnm, l)
return l, nil
case "radial", "repeating-radial":
r := NewRadial()
if gtyp == "repeating-radial" {
r.SetSpread(Repeat)
}
err := r.SetString(pars)
if err != nil {
return nil, err
}
fixGradientStops(r.Stops)
setCached(cnm, r)
return r, nil
}
return nil, fmt.Errorf("got unknown gradient type %q", gtyp)
}
// FromAny returns the color image specified by the given value of any type in the
// given Context. It handles values of types [color.Color], [image.Image], and string.
// If no Context is provided, it uses [BaseContext] with [Transparent].
func FromAny(val any, ctx ...colors.Context) (image.Image, error) {
// an image is checked first, as some images (image.Uniform) are colors too
switch v := val.(type) {
case image.Image:
return v, nil
case color.Color:
return colors.Uniform(v), nil
case *color.Color:
return colors.Uniform(*v), nil
case string:
return FromString(v, ctx...)
case *string:
return FromString(*v, ctx...)
}
return nil, fmt.Errorf("gradient.FromAny: got unsupported type %T", val)
}
// gradientDegToSides maps gradient degree notation to side notation
var gradientDegToSides = map[string]string{
"0deg": "top",
"360deg": "top",
"45deg": "top right",
"-315deg": "top right",
"90deg": "right",
"-270deg": "right",
"135deg": "bottom right",
"-225deg": "bottom right",
"180deg": "bottom",
"-180deg": "bottom",
"225deg": "bottom left",
"-135deg": "bottom left",
"270deg": "left",
"-90deg": "left",
"315deg": "top left",
"-45deg": "top left",
}
// SetString sets the linear gradient from the given CSS linear gradient string
// (only the part inside of "linear-gradient(...)") (see
// https://developer.mozilla.org/en-US/docs/Web/CSS/gradient/linear-gradient)
func (l *Linear) SetString(str string) error {
// TODO(kai): not fully following spec yet
plist := strings.Split(str, ", ")
var prevColor color.Color
stopIndex := 0
outer:
for pidx := range plist {
par := strings.TrimRight(strings.TrimSpace(plist[pidx]), ",")
origPar := par
switch {
case strings.Contains(par, "deg"):
// TODO(kai): this is not true and should be fixed to use trig
// can't use trig, b/c need to be full 1, 0 values -- just use map
var ok bool
par, ok = gradientDegToSides[par]
if !ok {
return fmt.Errorf("invalid gradient angle %q: must be at 45 degree increments", origPar)
}
par = "to " + par
fallthrough
case strings.HasPrefix(par, "to "):
sides := strings.Split(par[3:], " ")
l.Start, l.End = math32.Vector2{}, math32.Vector2{}
for _, side := range sides {
switch side {
case "bottom":
l.Start.Y = 0
l.End.Y = 1
case "top":
l.Start.Y = 1
l.End.Y = 0
case "right":
l.Start.X = 0
l.End.X = 1
case "left":
l.Start.X = 1
l.End.X = 0
}
}
case strings.HasPrefix(par, ")"):
break outer
default: // must be a color stop
var stop *Stop
if len(l.Stops) > stopIndex {
stop = &(l.Stops[stopIndex])
} else {
stop = &Stop{Opacity: 1}
}
err := parseColorStop(stop, prevColor, par)
if err != nil {
return err
}
if len(l.Stops) <= stopIndex {
l.Stops = append(l.Stops, *stop)
}
prevColor = stop.Color
stopIndex++
}
}
if len(l.Stops) > stopIndex {
l.Stops = l.Stops[:stopIndex]
}
return nil
}
// SetString sets the radial gradient from the given CSS radial gradient string
// (only the part inside of "radial-gradient(...)") (see
// https://developer.mozilla.org/en-US/docs/Web/CSS/gradient/radial-gradient)
func (r *Radial) SetString(str string) error {
// TODO(kai): not fully following spec yet
plist := strings.Split(str, ", ")
var prevColor color.Color
stopIndex := 0
outer:
for pidx := range plist {
par := strings.TrimRight(strings.TrimSpace(plist[pidx]), ",")
// currently we just ignore circle and ellipse, but we should handle them at some point
par = strings.TrimPrefix(par, "circle")
par = strings.TrimPrefix(par, "ellipse")
par = strings.TrimLeft(par, " ")
switch {
case strings.HasPrefix(par, "at "):
sides := strings.Split(par[3:], " ")
for _, side := range sides {
switch side {
case "bottom":
r.Center.Set(0.5, 1)
case "top":
r.Center.Set(0.5, 0)
case "right":
r.Center.Set(1, 0.5)
case "left":
r.Center.Set(0, 0.5)
case "center":
r.Center.Set(0.5, 0.5)
}
r.Focal = r.Center
}
case strings.HasPrefix(par, ")"):
break outer
default: // must be a color stop
var stop *Stop
if len(r.Stops) > stopIndex {
stop = &r.Stops[stopIndex]
} else {
stop = &Stop{Opacity: 1}
}
err := parseColorStop(stop, prevColor, par)
if err != nil {
return err
}
if len(r.Stops) <= stopIndex {
r.Stops = append(r.Stops, *stop)
}
prevColor = stop.Color
stopIndex++
}
}
if len(r.Stops) > stopIndex {
r.Stops = r.Stops[:stopIndex]
}
return nil
}
// parseColorStop parses the given color stop based on the given previous color
// and parent gradient string.
func parseColorStop(stop *Stop, prev color.Color, par string) error {
cnm := par
if spcidx := strings.Index(par, " "); spcidx > 0 {
cnm = par[:spcidx]
offs := strings.TrimSpace(par[spcidx+1:])
off, err := readFraction(offs)
if err != nil {
return fmt.Errorf("invalid offset %q: %w", offs, err)
}
stop.Pos = off
}
clr, err := colors.FromString(cnm, prev)
if err != nil {
return fmt.Errorf("got invalid color string %q: %w", cnm, err)
}
stop.Color = clr
return nil
}
// NOTE: XML marshalling functionality is at [cogentcore.org/core/svg.MarshalXMLGradient] instead of here
// because it uses a lot of SVG and XML infrastructure defined there.
// ReadXML reads an XML-formatted gradient color from the given io.Reader and
// sets the properties of the given gradient accordingly.
func ReadXML(g *Gradient, reader io.Reader) error {
decoder := xml.NewDecoder(reader)
decoder.CharsetReader = xmlx.CharsetReader
for {
t, err := decoder.Token()
if err != nil {
if err == io.EOF {
break
}
return fmt.Errorf("error parsing color xml: %w", err)
}
switch se := t.(type) {
case xml.StartElement:
return UnmarshalXML(g, decoder, se)
// todo: ignore rest?
}
}
return nil
}
// UnmarshalXML parses the given XML gradient color data and sets the properties
// of the given gradient accordingly.
func UnmarshalXML(g *Gradient, decoder *xml.Decoder, se xml.StartElement) error {
start := &se
for {
var t xml.Token
var err error
if start != nil {
t = *start
start = nil
} else {
t, err = decoder.Token()
}
if err != nil {
if err == io.EOF {
break
}
return fmt.Errorf("error parsing color: %w", err)
}
switch se := t.(type) {
case xml.StartElement:
switch se.Name.Local {
case "linearGradient":
l := NewLinear().SetEnd(math32.Vec2(1, 0)) // SVG is LTR by default
// if we don't already have a gradient, we use this one
if *g == nil {
*g = l
} else if pl, ok := (*g).(*Linear); ok {
// if our previous gradient is also linear, we build on it
l = pl
}
// fmt.Printf("lingrad %v\n", cs.Gradient)
for _, attr := range se.Attr {
// fmt.Printf("attr: %v val: %v\n", attr.Name.Local, attr.Value)
switch attr.Name.Local {
// note: id not processed here - must be done externally
case "x1":
l.Start.X, err = readFraction(attr.Value)
case "y1":
l.Start.Y, err = readFraction(attr.Value)
case "x2":
l.End.X, err = readFraction(attr.Value)
case "y2":
l.End.Y, err = readFraction(attr.Value)
default:
err = readGradAttr(*g, attr)
}
if err != nil {
return fmt.Errorf("error parsing linear gradient: %w", err)
}
}
case "radialGradient":
r := NewRadial()
// if we don't already have a gradient, we use this one
if *g == nil {
*g = r
} else if pr, ok := (*g).(*Radial); ok {
// if our previous gradient is also radial, we build on it
r = pr
}
var setFx, setFy bool
for _, attr := range se.Attr {
switch attr.Name.Local {
// note: id not processed here - must be done externally
case "r":
var radius float32
radius, err = readFraction(attr.Value)
r.Radius.SetScalar(radius)
case "cx":
r.Center.X, err = readFraction(attr.Value)
case "cy":
r.Center.Y, err = readFraction(attr.Value)
case "fx":
setFx = true
r.Focal.X, err = readFraction(attr.Value)
case "fy":
setFy = true
r.Focal.Y, err = readFraction(attr.Value)
default:
err = readGradAttr(*g, attr)
}
if err != nil {
return fmt.Errorf("error parsing radial gradient: %w", err)
}
}
if !setFx { // set fx to cx by default
r.Focal.X = r.Center.X
}
if !setFy { // set fy to cy by default
r.Focal.Y = r.Center.Y
}
case "stop":
stop := Stop{Color: colors.Black, Opacity: 1}
ats := se.Attr
sty := XMLAttr("style", ats)
if sty != "" {
spl := strings.SplitSeq(sty, ";")
for s := range spl {
s := strings.TrimSpace(s)
before, after, ok := strings.Cut(s, ":")
if !ok {
continue
}
a := xml.Attr{}
a.Name.Local = strings.TrimSpace(before)
a.Value = strings.TrimSpace(after)
ats = append(ats, a)
}
}
for _, attr := range ats {
switch attr.Name.Local {
case "offset":
stop.Pos, err = readFraction(attr.Value)
if err != nil {
return err
}
case "stop-color":
clr, err := colors.FromString(attr.Value)
if err != nil {
return fmt.Errorf("invalid color string: %w", err)
}
stop.Color = clr
case "stop-opacity":
opacity, err := readFraction(attr.Value)
if err != nil {
return fmt.Errorf("invalid stop opacity: %w", err)
}
stop.Opacity = opacity
}
}
if g == nil {
return fmt.Errorf("got stop outside of gradient: %v", stop)
}
gb := (*g).AsBase()
gb.Stops = append(gb.Stops, stop)
default:
// other elements in a gradient, as animate and
// animateTransform (of the spinners of GitHub), are not
// rendered, and do not make it invalid
if err := decoder.Skip(); err != nil {
return err
}
}
case xml.EndElement:
if se.Name.Local == "linearGradient" || se.Name.Local == "radialGradient" {
return nil
}
if se.Name.Local != "stop" {
return fmt.Errorf("got unexpected end element: %v", se.Name.Local)
}
case xml.CharData:
}
}
return nil
}
// readFraction reads a decimal value from the given string.
func readFraction(v string) (float32, error) {
v = strings.TrimSpace(v)
d := float32(1)
if strings.HasSuffix(v, "%") {
d = 100
v = strings.TrimSuffix(v, "%")
}
f64, err := strconv.ParseFloat(v, 32)
if err != nil {
return 0, err
}
f := float32(f64)
f /= d
return f, nil
}
// readGradAttr reads the given xml attribute onto the given gradient.
func readGradAttr(g Gradient, attr xml.Attr) error {
gb := g.AsBase()
switch attr.Name.Local {
case "gradientTransform":
err := gb.Transform.SetString(attr.Value)
if err != nil {
return err
}
case "gradientUnits":
return gb.Units.SetString(strings.TrimSpace(attr.Value))
case "spreadMethod":
return gb.Spread.SetString(strings.TrimSpace(attr.Value))
}
return nil
}
// fixGradientStops applies the CSS rules to regularize the given gradient stops:
// https://www.w3.org/TR/css3-images/#color-stop-syntax
func fixGradientStops(stops []Stop) {
sz := len(stops)
if sz == 0 {
return
}
splitSt := -1
last := float32(0)
for i := range sz {
st := &stops[i]
if i == sz-1 && st.Pos == 0 {
if last < 1.0 {
st.Pos = 1.0
} else {
st.Pos = last
}
}
if i > 0 && st.Pos == 0 && splitSt < 0 {
splitSt = i
st.Pos = last
continue
}
if splitSt > 0 {
start := stops[splitSt].Pos
end := st.Pos
per := (end - start) / float32(1+(i-splitSt))
cur := start + per
for j := splitSt; j < i; j++ {
stops[j].Pos = cur
cur += per
}
}
last = st.Pos
}
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on https://github.com/srwiley/rasterx:
// Copyright 2018 by the rasterx Authors. All rights reserved.
// Created 2018 by S.R.Wiley
package gradient
import (
"image/color"
"cogentcore.org/core/math32"
)
// Radial represents a radial gradient. It implements the [image.Image] interface.
type Radial struct { //types:add -setters
Base
// the center point of the gradient (cx and cy in SVG)
Center math32.Vector2
// the focal point of the gradient (fx and fy in SVG)
Focal math32.Vector2
// the radius of the gradient (rx and ry in SVG)
Radius math32.Vector2
// computed current render versions transformed by object matrix
rCenter math32.Vector2
rFocal math32.Vector2
rRadius math32.Vector2
rotTrans math32.Matrix2
}
var _ Gradient = &Radial{}
// NewRadial returns a new centered [Radial] gradient.
func NewRadial() *Radial {
return &Radial{
Base: NewBase(),
// default is fully centered
Center: math32.Vector2Scalar(0.5),
Focal: math32.Vector2Scalar(0.5),
Radius: math32.Vector2Scalar(0.5),
}
}
// AddStop adds a new stop with the given color, position, and
// optional opacity to the gradient.
func (r *Radial) AddStop(color color.RGBA, pos float32, opacity ...float32) *Radial {
r.Base.AddStop(color, pos, opacity...)
return r
}
// Update updates the computed fields of the gradient, using
// the given current bounding box, and additional
// object-level transform (i.e., the current painting transform),
// which is applied in addition to the gradient's own Transform.
// This must be called before rendering the gradient, and it should only be called then.
func (r *Radial) Update(opacity float32, box math32.Box2, objTransform math32.Matrix2) {
r.Box = box
r.Opacity = opacity
r.updateBase()
r.rotTrans = math32.Identity2()
c, f, rs := r.Center, r.Focal, r.Radius
sz := r.Box.Size()
if r.Units == ObjectBoundingBox {
c = r.Box.Min.Add(sz.Mul(c))
f = r.Box.Min.Add(sz.Mul(f))
rs.SetMul(sz)
} else {
ct := objTransform.Mul(r.Transform)
c = ct.MulPoint(c)
f = ct.MulPoint(f)
_, _, phi, sx, sy, _ := ct.Decompose()
r.rotTrans = math32.Rotate2D(phi)
rs.SetMul(math32.Vec2(sx, sy))
}
if c != f {
f.SetDiv(rs)
c.SetDiv(rs)
df := f.Sub(c)
if df.X*df.X+df.Y*df.Y > 1 { // Focus outside of circle; use intersection
// point of line from center to focus and circle as per SVG specs.
nf, intersects := rayCircleIntersectionF(f, c, c, 1-epsilonF)
f = nf
if !intersects {
f.Set(0, 0)
}
}
}
r.rCenter, r.rFocal, r.rRadius = c, f, rs
}
// TransformedCoords returns the coordinate points as transformed
// by the last Update call.
func (r *Radial) TransformedCoords() (center, focal, radius math32.Vector2) {
return r.rCenter, r.rFocal, r.rRadius
}
const epsilonF = 1e-5
// At returns the color of the radial gradient at the given point
func (r *Radial) At(x, y int) color.Color {
switch len(r.Stops) {
case 0:
return color.RGBA{}
case 1:
return r.Stops[0].Color
}
if r.rCenter == r.rFocal {
// When the center and focal are the same things are much simpler;
// pos is just distance from center scaled by radius
pt := math32.Vec2(float32(x)+0.5, float32(y)+0.5)
if r.Units == ObjectBoundingBox {
pt = r.boxTransform.MulPoint(pt)
}
d := r.rotTrans.MulVector(pt.Sub(r.rCenter))
pos := math32.Sqrt(d.X*d.X/(r.rRadius.X*r.rRadius.X) + (d.Y*d.Y)/(r.rRadius.Y*r.rRadius.Y))
return r.getColor(pos)
}
if r.rFocal == math32.Vec2(0, 0) {
return color.RGBA{} // should not happen
}
pt := math32.Vec2(float32(x)+0.5, float32(y)+0.5)
if r.Units == ObjectBoundingBox {
pt = r.boxTransform.MulPoint(pt)
}
pt = r.rotTrans.MulVector(pt)
e := pt.Div(r.rRadius)
t1, intersects := rayCircleIntersectionF(e, r.rFocal, r.rCenter, 1)
if !intersects { // In this case, use the last stop color
s := r.Stops[len(r.Stops)-1]
return s.Color
}
td := t1.Sub(r.rFocal)
d := e.Sub(r.rFocal)
if td.X*td.X+td.Y*td.Y < epsilonF {
s := r.Stops[len(r.Stops)-1]
return s.Color
}
pos := math32.Sqrt(d.X*d.X+d.Y*d.Y) / math32.Sqrt(td.X*td.X+td.Y*td.Y)
return r.getColor(pos)
}
// rayCircleIntersectionF calculates in floating point the points of intersection of
// a ray starting at s2 passing through s1 and a circle in fixed point.
// Returns intersects == false if no solution is possible. If two
// solutions are possible, the point closest to s2 is returned.
func rayCircleIntersectionF(s1, s2, c math32.Vector2, r float32) (pt math32.Vector2, intersects bool) {
n := s2.X - c.X // Calculating using 64* rather than divide
m := s2.Y - c.Y
e := s2.X - s1.X
d := s2.Y - s1.Y
// Quadratic normal form coefficients
A, B, C := e*e+d*d, -2*(e*n+m*d), n*n+m*m-r*r
D := B*B - 4*A*C
if D <= 0 {
return // No intersection or is tangent
}
D = math32.Sqrt(D)
t1, t2 := (-B+D)/(2*A), (-B-D)/(2*A)
p1OnSide := t1 > 0
p2OnSide := t2 > 0
switch {
case p1OnSide && p2OnSide:
if t2 < t1 { // both on ray, use closest to s2
t1 = t2
}
case p2OnSide: // Only p2 on ray
t1 = t2
case p1OnSide: // only p1 on ray
default: // Neither solution is on the ray
return
}
return math32.Vec2((n-e*t1)+c.X, (m-d*t1)+c.Y), true
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package colors
import (
"image"
"image/color"
)
// Uniform returns a new [image.Uniform] filled completely with the given color.
// See [ToUniform] for the converse.
func Uniform(c color.Color) image.Image {
if c == nil {
return nil
}
return image.NewUniform(c)
}
// ToUniform converts the given image to a uniform [color.RGBA] color.
// See [Uniform] for the converse.
func ToUniform(img image.Image) color.RGBA {
if img == nil {
return color.RGBA{}
}
return AsRGBA(img.At(0, 0))
}
// CloneUniform returns a copy of a Uniform image color, if image is one.
// Otherwise just returns the image back. This is useful when modifying
// an image color, to ensure that it doesn't modify all users of this image.
func CloneUniform(img image.Image) image.Image {
if img == nil {
return nil
}
u, ok := img.(*image.Uniform)
if !ok {
return img
}
return image.NewUniform(AsRGBA(u.C))
}
// Pattern returns a new unbounded [image.Image] represented by the given pattern function.
func Pattern(f func(x, y int) color.Color) image.Image {
return &pattern{f}
}
type pattern struct {
f func(x, y int) color.Color
}
func (p *pattern) ColorModel() color.Model {
return color.RGBAModel
}
func (p *pattern) Bounds() image.Rectangle {
return image.Rect(-1e9, -1e9, 1e9, 1e9)
}
func (p *pattern) At(x, y int) color.Color {
return p.f(x, y)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package colors
import (
"image/color"
"cogentcore.org/core/colors/matcolor"
)
// Palette contains the main, global [MatPalette]. It can
// be used by end-user code for accessing tonal palette values,
// although [Scheme] is a more typical way to access the color
// scheme values. It defaults to a palette based around a
// primary color of Google Blue (#4285f4)
var Palette = matcolor.NewPalette(matcolor.KeyFromPrimary(color.RGBA{66, 133, 244, 255}))
// Schemes are the main global Material Design 3 color schemes.
// They should not be used for accessing the current color scheme;
// see [Scheme] for that. Instead, they should be set if you want
// to define your own custom color schemes for your app. The recommended
// way to set the Schemes is through the [SetSchemes] function.
var Schemes = matcolor.NewSchemes(Palette)
// Scheme is the main currently active global Material Design 3
// color scheme. It is the main way that end-user code should
// access the color scheme; ideally, almost all color values should
// be set to something in here. For more specific tones of colors,
// see [Palette]. For setting the color schemes of your app, see
// [Schemes] and [SetSchemes]. For setting this scheme to
// be light or dark, see [SetScheme].
var Scheme = &Schemes.Light
// SetSchemes sets [Schemes], [Scheme], and [Palette] based on the
// given primary color. It is the main way that end-user code should
// set the color schemes to something custom. For more specific control,
// see [SetSchemesFromKey].
func SetSchemes(primary color.RGBA) {
SetSchemesFromKey(matcolor.KeyFromPrimary(primary))
}
// SetSchemesFromKey sets [Schemes], [Scheme], and [Palette] based on the
// given [matcolor.Key]. It should be used instead of [SetSchemes]
// if you want more specific control over the color scheme.
// The schemes are kept if [Palette] is already from the same key
// colors, so that setting them again (as when settings are applied)
// does not change them while they are used in other goroutines.
func SetSchemesFromKey(key *matcolor.Key) {
if !paletteFromKey(Palette, key) {
Palette = matcolor.NewPalette(key)
Schemes = matcolor.NewSchemes(Palette)
}
SetScheme(matcolor.SchemeIsDark)
}
// paletteFromKey returns whether the given palette is from the
// given key colors.
func paletteFromKey(p *matcolor.Palette, key *matcolor.Key) bool {
if p == nil || len(p.Custom) != len(key.Custom) {
return false
}
same := p.Primary.Key == key.Primary && p.Secondary.Key == key.Secondary &&
p.Tertiary.Key == key.Tertiary && p.Select.Key == key.Select &&
p.Error.Key == key.Error && p.Success.Key == key.Success &&
p.Warn.Key == key.Warn && p.Neutral.Key == key.Neutral &&
p.NeutralVariant.Key == key.NeutralVariant
for name, c := range key.Custom {
if t, ok := p.Custom[name]; !ok || t.Key != c {
return false
}
}
return same
}
// SetScheme sets the value of [Scheme] to either [Schemes.Dark]
// or [Schemes.Light], based on the given value of whether the
// color scheme should be dark. It also sets the value of
// [matcolor.SchemeIsDark]. Values that are already set are not
// written again, as they may be read in other goroutines.
func SetScheme(isDark bool) {
if matcolor.SchemeIsDark != isDark {
matcolor.SchemeIsDark = isDark
}
sc := &Schemes.Light
if isDark {
sc = &Schemes.Dark
}
if Scheme != sc {
Scheme = sc
}
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package matcolor
import (
"image"
)
// Accent contains the four standard variations of a base accent color.
type Accent struct {
// Base is the base color for typically high-emphasis content.
Base image.Image
// On is the color applied to content on top of [Accent.Base].
On image.Image
// Container is the color applied to elements with less emphasis than [Accent.Base].
Container image.Image
// OnContainer is the color applied to content on top of [Accent.Container].
OnContainer image.Image
}
// NewAccentLight returns a new light theme [Accent] from the given [Tones].
func NewAccentLight(tones Tones) Accent {
return Accent{
Base: tones.AbsToneUniform(40),
On: tones.AbsToneUniform(100),
Container: tones.AbsToneUniform(90),
OnContainer: tones.AbsToneUniform(10),
}
}
// NewAccentDark returns a new dark theme [Accent] from the given [Tones].
func NewAccentDark(tones Tones) Accent {
return Accent{
Base: tones.AbsToneUniform(80),
On: tones.AbsToneUniform(20),
Container: tones.AbsToneUniform(30),
OnContainer: tones.AbsToneUniform(90),
}
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on https://github.com/material-foundation/material-color-utilities/blob/main/dart/lib/palettes/core_palette.dart
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package matcolor
import (
"image/color"
"cogentcore.org/core/colors/cam/hct"
)
// Key contains the set of key colors used to generate
// a [Scheme] and [Palette]
type Key struct {
// the primary accent key color
Primary color.RGBA
// the secondary accent key color
Secondary color.RGBA
// the tertiary accent key color
Tertiary color.RGBA
// the select accent key color
Select color.RGBA
// the error accent key color
Error color.RGBA
// the success accent key color
Success color.RGBA
// the warn accent key color
Warn color.RGBA
// the neutral key color used to generate surface and surface container colors
Neutral color.RGBA
// the neutral variant key color used to generate surface variant and outline colors
NeutralVariant color.RGBA
// an optional map of custom accent key colors
Custom map[string]color.RGBA
}
// KeyFromPrimary returns a new [Key] from the given primary accent key color.
func KeyFromPrimary(primary color.RGBA) *Key {
k := &Key{}
p := hct.FromColor(primary)
p.SetTone(40)
k.Primary = p.WithChroma(max(p.Chroma, 48)).AsRGBA()
k.Secondary = p.WithChroma(16).AsRGBA()
// Material adds 60, but we subtract 60 to get green instead of pink when specifying
// blue (TODO: is this a good idea, or should we just follow Material?)
k.Tertiary = p.WithHue(p.Hue - 60).WithChroma(24).AsRGBA()
k.Select = p.WithChroma(24).AsRGBA()
k.Error = color.RGBA{179, 38, 30, 255} // #B3261E (Material default error color)
k.Success = color.RGBA{50, 168, 50, 255} // #32a832 (arbitrarily chosen; TODO: maybe come up with a better default success color)
k.Warn = color.RGBA{168, 143, 50, 255} // #a88f32 (arbitrarily chosen; TODO: maybe come up with a better default warn color)
k.Neutral = p.WithChroma(4).AsRGBA()
k.NeutralVariant = p.WithChroma(8).AsRGBA()
return k
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package matcolor
// Palette contains a tonal palette with tonal values
// for each of the standard colors and any custom colors.
// Use [NewPalette] to create a new palette.
type Palette struct {
// the tones for the primary key color
Primary Tones
// the tones for the secondary key color
Secondary Tones
// the tones for the tertiary key color
Tertiary Tones
// the tones for the select key color
Select Tones
// the tones for the error key color
Error Tones
// the tones for the success key color
Success Tones
// the tones for the warn key color
Warn Tones
// the tones for the neutral key color
Neutral Tones
// the tones for the neutral variant key color
NeutralVariant Tones
// an optional map of tones for custom accent key colors
Custom map[string]Tones
}
// NewPalette creates a new [Palette] from the given key colors.
func NewPalette(key *Key) *Palette {
p := &Palette{
Primary: NewTones(key.Primary),
Secondary: NewTones(key.Secondary),
Tertiary: NewTones(key.Tertiary),
Select: NewTones(key.Select),
Error: NewTones(key.Error),
Success: NewTones(key.Success),
Warn: NewTones(key.Warn),
Neutral: NewTones(key.Neutral),
NeutralVariant: NewTones(key.NeutralVariant),
}
for name, c := range key.Custom {
p.Custom[name] = NewTones(c)
}
return p
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package matcolor
import (
"image"
"image/color"
)
//go:generate core generate
// Scheme contains the colors for one color scheme (ex: light or dark).
// To generate a scheme, use [NewScheme].
type Scheme struct {
// Primary is the primary color applied to important elements
Primary Accent
// Secondary is the secondary color applied to less important elements
Secondary Accent
// Tertiary is the tertiary color applied as an accent to highlight elements and create contrast between other colors
Tertiary Accent
// Select is the selection color applied to selected or highlighted elements and text
Select Accent
// Error is the error color applied to elements that indicate an error or danger
Error Accent
// Success is the color applied to elements that indicate success
Success Accent
// Warn is the color applied to elements that indicate a warning
Warn Accent
// an optional map of custom accent colors
Custom map[string]Accent
// SurfaceDim is the color applied to elements that will always have the dimmest surface color (see Surface for more information)
SurfaceDim image.Image
// Surface is the color applied to contained areas, like the background of an app
Surface image.Image
// SurfaceBright is the color applied to elements that will always have the brightest surface color (see Surface for more information)
SurfaceBright image.Image
// SurfaceContainerLowest is the color applied to surface container elements that have the lowest emphasis (see SurfaceContainer for more information)
SurfaceContainerLowest image.Image
// SurfaceContainerLow is the color applied to surface container elements that have lower emphasis (see SurfaceContainer for more information)
SurfaceContainerLow image.Image
// SurfaceContainer is the color applied to container elements that contrast elements with the surface color
SurfaceContainer image.Image
// SurfaceContainerHigh is the color applied to surface container elements that have higher emphasis (see SurfaceContainer for more information)
SurfaceContainerHigh image.Image
// SurfaceContainerHighest is the color applied to surface container elements that have the highest emphasis (see SurfaceContainer for more information)
SurfaceContainerHighest image.Image
// SurfaceVariant is the color applied to contained areas that contrast standard Surface elements
SurfaceVariant image.Image
// OnSurface is the color applied to content on top of Surface elements
OnSurface image.Image
// OnSurfaceVariant is the color applied to content on top of SurfaceVariant elements
OnSurfaceVariant image.Image
// InverseSurface is the color applied to elements to make them the reverse color of the surrounding elements and create a contrasting effect
InverseSurface image.Image
// InverseOnSurface is the color applied to content on top of InverseSurface
InverseOnSurface image.Image
// InversePrimary is the color applied to interactive elements on top of InverseSurface
InversePrimary image.Image
// Outline is the color applied to borders to create emphasized boundaries that need to have sufficient contrast
Outline image.Image
// OutlineVariant is the color applied to create decorative boundaries
OutlineVariant image.Image
// Shadow is the color applied to shadows
Shadow image.Image
// SurfaceTint is the color applied to tint surfaces
SurfaceTint image.Image
// Scrim is the color applied to scrims (semi-transparent overlays)
Scrim image.Image
}
// NewLightScheme returns a new light-themed [Scheme]
// based on the given [Palette].
func NewLightScheme(p *Palette) Scheme {
s := Scheme{
Primary: NewAccentLight(p.Primary),
Secondary: NewAccentLight(p.Secondary),
Tertiary: NewAccentLight(p.Tertiary),
Select: NewAccentLight(p.Select),
Error: NewAccentLight(p.Error),
Success: NewAccentLight(p.Success),
Warn: NewAccentLight(p.Warn),
Custom: map[string]Accent{},
SurfaceDim: p.Neutral.AbsToneUniform(87),
Surface: p.Neutral.AbsToneUniform(100),
SurfaceBright: p.Neutral.AbsToneUniform(100),
SurfaceContainerLowest: p.Neutral.AbsToneUniform(100),
SurfaceContainerLow: p.Neutral.AbsToneUniform(98),
SurfaceContainer: p.Neutral.AbsToneUniform(96),
SurfaceContainerHigh: p.Neutral.AbsToneUniform(94),
SurfaceContainerHighest: p.Neutral.AbsToneUniform(92),
SurfaceVariant: p.NeutralVariant.AbsToneUniform(90),
OnSurface: p.NeutralVariant.AbsToneUniform(10),
OnSurfaceVariant: p.NeutralVariant.AbsToneUniform(30),
InverseSurface: p.Neutral.AbsToneUniform(20),
InverseOnSurface: p.Neutral.AbsToneUniform(95),
InversePrimary: p.Primary.AbsToneUniform(80),
Outline: p.NeutralVariant.AbsToneUniform(50),
OutlineVariant: p.NeutralVariant.AbsToneUniform(80),
Shadow: p.Neutral.AbsToneUniform(0),
SurfaceTint: p.Primary.AbsToneUniform(40),
Scrim: p.Neutral.AbsToneUniform(0),
}
for nm, c := range p.Custom {
s.Custom[nm] = NewAccentLight(c)
}
return s
// TODO: maybe fixed colors
}
// NewDarkScheme returns a new dark-themed [Scheme]
// based on the given [Palette].
func NewDarkScheme(p *Palette) Scheme {
s := Scheme{
Primary: NewAccentDark(p.Primary),
Secondary: NewAccentDark(p.Secondary),
Tertiary: NewAccentDark(p.Tertiary),
Select: NewAccentDark(p.Select),
Error: NewAccentDark(p.Error),
Success: NewAccentDark(p.Success),
Warn: NewAccentDark(p.Warn),
Custom: map[string]Accent{},
SurfaceDim: p.Neutral.AbsToneUniform(6),
Surface: p.Neutral.AbsToneUniform(6),
SurfaceBright: p.Neutral.AbsToneUniform(24),
SurfaceContainerLowest: p.Neutral.AbsToneUniform(4),
SurfaceContainerLow: p.Neutral.AbsToneUniform(10),
SurfaceContainer: p.Neutral.AbsToneUniform(12),
SurfaceContainerHigh: p.Neutral.AbsToneUniform(17),
SurfaceContainerHighest: p.Neutral.AbsToneUniform(22),
SurfaceVariant: p.NeutralVariant.AbsToneUniform(30),
OnSurface: p.NeutralVariant.AbsToneUniform(90),
OnSurfaceVariant: p.NeutralVariant.AbsToneUniform(80),
InverseSurface: p.Neutral.AbsToneUniform(90),
InverseOnSurface: p.Neutral.AbsToneUniform(20),
InversePrimary: p.Primary.AbsToneUniform(40),
Outline: p.NeutralVariant.AbsToneUniform(60),
OutlineVariant: p.NeutralVariant.AbsToneUniform(30),
// We want some visible "glow" shadow, but not too much
Shadow: image.NewUniform(color.RGBA{127, 127, 127, 127}),
SurfaceTint: p.Primary.AbsToneUniform(80),
Scrim: p.Neutral.AbsToneUniform(0),
}
for nm, c := range p.Custom {
s.Custom[nm] = NewAccentDark(c)
}
return s
// TODO: custom and fixed colors?
}
// SchemeIsDark is whether the currently active color scheme
// is a dark-themed or light-themed color scheme. In almost
// all cases, it should be set via [cogentcore.org/core/colors.SetScheme],
// not directly.
var SchemeIsDark = false
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package matcolor
// Schemes contains multiple color schemes
// (light, dark, and any custom ones).
type Schemes struct {
Light Scheme
Dark Scheme
// TODO: maybe custom schemes?
}
// NewSchemes returns new [Schemes] for the given
// [Palette] containing both light and dark schemes.
func NewSchemes(p *Palette) *Schemes {
return &Schemes{
Light: NewLightScheme(p),
Dark: NewDarkScheme(p),
}
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package matcolor
import (
"image"
"image/color"
"cogentcore.org/core/colors/cam/hct"
)
// Tones contains cached color values for each tone
// of a seed color. To get a tonal value, use [Tones.Tone].
type Tones struct {
// the key color used to generate these tones
Key color.RGBA
// the cached map of tonal color values
Tones map[int]color.RGBA
}
// NewTones returns a new set of [Tones]
// for the given color.
func NewTones(c color.RGBA) Tones {
return Tones{
Key: c,
Tones: map[int]color.RGBA{},
}
}
// AbsTone returns the color at the given absolute
// tone on a scale of 0 to 100. It uses the cached
// value if it exists, and it caches the value if
// it is not already.
func (t *Tones) AbsTone(tone int) color.RGBA {
if c, ok := t.Tones[tone]; ok {
return c
}
c := hct.FromColor(t.Key)
c.SetTone(float32(tone))
r := c.AsRGBA()
t.Tones[tone] = r
return r
}
// AbsToneUniform returns [image.Uniform] of [Tones.AbsTone].
func (t *Tones) AbsToneUniform(tone int) *image.Uniform {
return image.NewUniform(t.AbsTone(tone))
}
// Tone returns the color at the given tone, relative to the "0" tone
// for the current color scheme (0 for light-themed schemes and 100 for
// dark-themed schemes).
func (t *Tones) Tone(tone int) color.RGBA {
if SchemeIsDark {
return t.AbsTone(100 - tone)
}
return t.AbsTone(tone)
}
// ToneUniform returns [image.Uniform] of [Tones.Tone].
func (t *Tones) ToneUniform(tone int) *image.Uniform {
return image.NewUniform(t.Tone(tone))
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package colors
import "image/color"
// RGBAF32 stores alpha-premultiplied RGBA values in a float32 0 to 1
// normalized format, which is more useful for converting to other spaces
type RGBAF32 struct {
R, G, B, A float32
}
// RGBA implements the color.Color interface
func (c RGBAF32) RGBA() (r, g, b, a uint32) {
r = uint32(c.R*65535.0 + 0.5)
g = uint32(c.G*65535.0 + 0.5)
b = uint32(c.B*65535.0 + 0.5)
a = uint32(c.A*65535.0 + 0.5)
return
}
// FromRGBAF32 returns the color specified by the given float32
// alpha-premultiplied RGBA values in the range 0 to 1
func FromRGBAF32(r, g, b, a float32) color.RGBA {
return AsRGBA(RGBAF32{r, g, b, a})
}
// NRGBAF32 stores non-alpha-premultiplied RGBA values in a float32 0 to 1
// normalized format, which is more useful for converting to other spaces
type NRGBAF32 struct {
R, G, B, A float32
}
// RGBA implements the color.Color interface
func (c NRGBAF32) RGBA() (r, g, b, a uint32) {
r = uint32(c.R*c.A*65535.0 + 0.5)
g = uint32(c.G*c.A*65535.0 + 0.5)
b = uint32(c.B*c.A*65535.0 + 0.5)
a = uint32(c.A*65535.0 + 0.5)
return
}
// FromNRGBAF32 returns the color specified by the given float32
// non alpha-premultiplied RGBA values in the range 0 to 1
func FromNRGBAF32(r, g, b, a float32) color.RGBA {
return AsRGBA(NRGBAF32{r, g, b, a})
}
var (
// RGBAF32Model is the model for converting colors to [RGBAF32] colors
RGBAF32Model color.Model = color.ModelFunc(rgbaf32Model)
// NRGBAF32Model is the model for converting colors to [NRGBAF32] colors
NRGBAF32Model color.Model = color.ModelFunc(nrgbaf32Model)
)
func rgbaf32Model(c color.Color) color.Color {
if _, ok := c.(RGBAF32); ok {
return c
}
r, g, b, a := c.RGBA()
return RGBAF32{float32(r) / 65535.0, float32(g) / 65535.0, float32(b) / 65535.0, float32(a) / 65535.0}
}
func nrgbaf32Model(c color.Color) color.Color {
if _, ok := c.(NRGBAF32); ok {
return c
}
r, g, b, a := c.RGBA()
if a > 0 {
// Since color.Color is alpha pre-multiplied, we need to divide the
// RGB values by alpha again in order to get back the original RGB.
r *= 0xffff
r /= a
g *= 0xffff
g /= a
b *= 0xffff
b /= a
}
return NRGBAF32{float32(r) / 65535.0, float32(g) / 65535.0, float32(b) / 65535.0, float32(a) / 65535.0}
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package colors
import (
"image/color"
"cogentcore.org/core/colors/cam/hct"
"cogentcore.org/core/colors/matcolor"
)
// Spaced returns a maximally widely spaced sequence of colors
// for progressive values of the index, using the HCT space.
// This is useful, for example, for assigning colors in graphs.
func Spaced(idx int) color.RGBA {
if matcolor.SchemeIsDark {
return spacedDark(idx)
}
return spacedLight(idx)
}
// spacedLight is the light mode version of [Spaced].
func spacedLight(idx int) color.RGBA {
// blue, red, green, yellow, violet, aqua, orange, blueviolet
// hues := []float32{30, 280, 140, 110, 330, 200, 70, 305}
hues := []float32{255, 25, 150, 105, 340, 210, 60, 300}
// even 45: 30, 75, 120, 165, 210, 255, 300, 345,
toffs := []float32{0, -10, 0, 5, 0, 0, 5, 0}
tones := []float32{65, 80, 45, 65, 80}
chromas := []float32{90, 90, 90, 20, 20}
ncats := len(hues)
ntc := len(tones)
hi := idx % ncats
hr := idx / ncats
tci := hr % ntc
hue := hues[hi]
tone := toffs[hi] + tones[tci]
chroma := chromas[tci]
return hct.New(hue, float32(chroma), tone).AsRGBA()
}
// spacedDark is the dark mode version of [Spaced].
func spacedDark(idx int) color.RGBA {
// blue, red, green, yellow, violet, aqua, orange, blueviolet
// hues := []float32{30, 280, 140, 110, 330, 200, 70, 305}
hues := []float32{255, 25, 150, 105, 340, 210, 60, 300}
// even 45: 30, 75, 120, 165, 210, 255, 300, 345,
toffs := []float32{0, -10, 0, 10, 0, 0, 5, 0}
tones := []float32{65, 80, 45, 65, 80}
chromas := []float32{90, 90, 90, 20, 20}
ncats := len(hues)
ntc := len(tones)
hi := idx % ncats
hr := idx / ncats
tci := hr % ntc
hue := hues[hi]
tone := toffs[hi] + tones[tci]
chroma := chromas[tci]
return hct.New(hue, float32(chroma), tone).AsRGBA()
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package bcontent ("base content") provides base types and functions
// shared by both content and the core build tool for content. This is
// necessary to ensure that the core build tool does not import GUI packages.
package bcontent
import (
"bufio"
"bytes"
"fmt"
"io/fs"
"path/filepath"
"slices"
"strconv"
"strings"
"time"
"cogentcore.org/core/base/iox/tomlx"
"cogentcore.org/core/base/strcase"
)
// Page represents the metadata for a single page of content.
type Page struct {
// Source is the filesystem that the page is stored in.
Source fs.FS `toml:"-" json:"-"`
// Filename is the name of the file in [Page.FS] that the content is stored in.
Filename string `toml:"-" json:"-"`
// Name is the user-friendly name of the page, defaulting to the
// [strcase.ToSentence] of the [Page.Filename] without its extension.
Name string
// URL is the URL of the page relative to the root of the app, without
// any leading slash. It defaults to [Page.Name] in kebab-case
// (ex: "home" or "text-fields"). A blank URL ("") manually
// specified in the front matter indicates that this the root page.
URL string
// Title is the title displayed at the top of the page. It defaults to [Page.Name].
// Note that [Page.Name] is still used for the stage title and other such things; this
// is only for the actual title widget.
Title string
// Date is the optional date that the page was published.
Date time.Time `toml:"-"`
// DateString is only used for parsing the date from the TOML front matter.
DateString string `toml:"Date" json:"-"`
// Version is a version string, e.g., for pages that have some kind of publication
// status. Typically reserve for major changes, with the Date being used to track
// minor changes (typo fixes etc). Will be rendered with "Version: " prepended,
// in the same line as the date if date is set.
Version string
// Authors are the optional author(s) of the page.
Authors string
// Affiliations are optional institutional affiliations of the authors.
Affiliations string
// Abstract is an optional abstract.
Abstract string
// Reference can be used for a publication or other external source
// for the content on this page.
Reference string
// Draft indicates that the page is a draft and should not be visible on the web.
Draft bool
// NoURLinPDF turns off the generation of the page URL when generating the PDF
// version of a page.
NoURLinPDF bool
// Heading is an optional string to use on page headings in the PDF version.
Heading string
// Categories are the categories that the page belongs to.
Categories []string
// Specials are special content elements for each page
// that have names with an underscore-delimited key name,
// such as figure_, table_, sim_ etc, and can be referred
// to using the #id component of a wikilink. They are rendered
// using the index of each such element (e.g., Figure 1) in the link.
Specials map[string][]string
}
// PreRenderPage contains the data for each page in the [Site] printed in JSON
// by a content app run with the -generatehtml argument, which is then handled
// by the core build tool.
type PreRenderPage struct {
Page
// Description is the automatic page description.
Description string
// HTML is the pre-rendered HTML for the page.
HTML string
// TOC is the table of contents for the page.
TOC []*TOCHeading `json:",omitempty"`
}
// NewPage makes a new page in the given filesystem with the given filename,
// sets default values, and reads metadata from the front matter of the page file.
func NewPage(source fs.FS, filename string) (*Page, error) {
pg := &Page{Source: source, Filename: filename}
pg.Defaults()
err := pg.ReadMetadata()
return pg, err
}
const unsetTitle = "$UNSET_TITLE"
// Defaults sets default values for the page based on its filename.
func (pg *Page) Defaults() {
pg.Name = strcase.ToSentence(strings.TrimSuffix(pg.Filename, filepath.Ext(pg.Filename)))
pg.URL = strcase.ToKebab(pg.Name)
pg.Title = unsetTitle
pg.Categories = []string{"Other"}
}
// ReadMetadata reads the page metadata from the front matter of the page file,
// if there is any.
func (pg *Page) ReadMetadata() error {
// Ensure the default title is set if it was not manually set (need defer).
defer func() {
if pg.Title == unsetTitle {
pg.Title = pg.Name
}
}()
f, err := pg.Source.Open(pg.Filename)
if err != nil {
return err
}
defer f.Close()
sc := bufio.NewScanner(f)
var data []byte
for sc.Scan() {
b := sc.Bytes()
if data == nil {
if string(b) != `+++` {
return nil
}
data = []byte{}
continue
}
if string(b) == `+++` {
break
}
data = append(data, append(b, '\n')...)
}
if err := sc.Err(); err != nil {
return err
}
err = tomlx.ReadBytes(pg, data)
if err != nil {
return err
}
if pg.DateString != "" {
pg.Date, err = time.Parse(time.DateOnly, pg.DateString)
if err != nil {
return err
}
}
return nil
}
// ReadContent returns the page content with any front matter removed.
// It also applies [Page.categoryLinks].
func (pg *Page) ReadContent(pagesByCategory map[string][]*Page) ([]byte, error) {
b, err := fs.ReadFile(pg.Source, pg.Filename)
if err != nil {
return nil, err
}
b = append(b, pg.categoryLinks(pagesByCategory)...)
if !bytes.HasPrefix(b, []byte(`+++`)) {
return b, nil
}
b = bytes.TrimPrefix(b, []byte(`+++`))
_, after, has := bytes.Cut(b, []byte(`+++`))
if !has {
return nil, fmt.Errorf("unclosed front matter")
}
return after, nil
}
// categoryLinks, if the page has the same names as one of the given categories,
// returns markdown containing a list of links to all pages in that category.
// Otherwise, it returns nil.
func (pg *Page) categoryLinks(pagesByCategory map[string][]*Page) []byte {
if pagesByCategory == nil {
return nil
}
cpages := pagesByCategory[pg.Name]
if cpages == nil {
return nil
}
res := []byte{'\n'}
for _, cpage := range cpages {
if cpage == pg {
continue
}
res = append(res, fmt.Sprintf("* [[%s]]\n", cpage.Name)...)
}
return res
}
// SpecialName extracts a special element type name from given element name,
// defined as the part before the first underscore _ character.
func SpecialName(name string) string {
before, _, ok := strings.Cut(name, "_")
if !ok {
return ""
}
return before
}
// SpecialToKebab does strcase.ToKebab on parts after specialName if present.
func SpecialToKebab(name string) string {
usi := strings.Index(name, "_")
if usi < 0 {
return strcase.ToKebab(name)
}
spec := name[:usi+1]
name = name[usi+1:]
colon := strings.Index(name, ":")
if colon > 0 {
return spec + strcase.ToKebab(name[:colon]) + name[colon:]
} else {
return spec + strcase.ToKebab(name)
}
}
// SpecialLabel returns the label for given special element, using
// the index of the element in the list of specials, e.g., "Figure 1"
func (pg *Page) SpecialLabel(name string) string {
snm := SpecialName(name)
if snm == "" {
return ""
}
if pg.Specials == nil {
b, err := pg.ReadContent(nil)
if err != nil {
return ""
}
pg.ParseSpecials(b)
}
sl := pg.Specials[snm]
if sl == nil {
return ""
}
i := slices.Index(sl, name)
if i < 0 {
return ""
}
return strcase.ToSentence(snm) + " " + strconv.Itoa(i+1)
}
// ParseSpecials manually parses specials before rendering md
// because they are needed in advance of generating from md file,
// e.g., for wikilinks.
func (pg *Page) ParseSpecials(b []byte) {
if pg.Specials != nil {
return
}
pg.Specials = make(map[string][]string)
scan := bufio.NewScanner(bytes.NewReader(b))
idt := []byte(`{id="`)
idn := len(idt)
for scan.Scan() {
ln := scan.Bytes()
n := len(ln)
if n < idn+1 {
continue
}
if !bytes.HasPrefix(ln, idt) {
continue
}
fs := bytes.Fields(ln) // multiple attributes possible
ln = fs[0] // only deal with first one
id := bytes.TrimSpace(ln[idn:])
n = len(id)
if n < 2 {
continue
}
ed := n - 1 // quotes
if len(fs) == 1 {
ed = n - 2 // brace
}
id = id[:ed]
sid := string(id)
snm := SpecialName(sid)
if snm == "" {
continue
}
// fmt.Println("id:", snm, sid)
sl := pg.Specials[snm]
sl = append(sl, sid)
pg.Specials[snm] = sl
}
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package content
import (
"slices"
"cogentcore.org/core/colors"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/keymap"
"cogentcore.org/core/styles"
"cogentcore.org/core/system"
"cogentcore.org/core/tree"
)
// MakeToolbar adds the standard toolbar buttons for the content.
// See [Content.MakeToolbarPDF] for the optional PDF button.
func (ct *Content) MakeToolbar(p *tree.Plan) {
if false && ct.SizeClass() == core.SizeCompact { // TODO: implement hamburger menu for compact
tree.Add(p, func(w *core.Button) {
w.SetIcon(icons.Menu)
w.SetTooltip("Navigate pages and headings")
w.OnClick(func(e events.Event) {
d := core.NewBody("Navigate")
// tree.MoveToParent(ct.leftFrame, d)
d.AddBottomBar(func(bar *core.Frame) {
d.AddCancel(bar)
})
d.RunDialog(w)
})
})
}
tree.Add(p, func(w *core.Button) {
w.SetIcon(icons.Icon(core.AppIcon))
w.SetTooltip("Home")
w.OnClick(func(e events.Event) {
ct.OpenEvent("", e)
})
})
// Superseded by browser navigation on web.
if core.TheApp.Platform() != system.Web {
tree.Add(p, func(w *core.Button) {
ct.toolbar = w.Parent.(*core.Toolbar)
w.SetIcon(icons.ArrowBack).SetKey(keymap.HistPrev)
w.SetTooltip("Back")
w.Updater(func() {
w.SetEnabled(ct.historyHasBack())
})
w.OnClick(func(e events.Event) {
ct.historyBack()
if ct.toolbar != nil {
ct.toolbar.Update()
}
})
})
tree.Add(p, func(w *core.Button) {
w.SetIcon(icons.ArrowForward).SetKey(keymap.HistNext)
w.SetTooltip("Forward")
w.Updater(func() {
w.SetEnabled(ct.historyHasForward())
})
w.OnClick(func(e events.Event) {
ct.historyForward()
if ct.toolbar != nil {
ct.toolbar.Update()
}
})
})
}
tree.Add(p, func(w *core.Button) {
find := keymap.Find.Chord().Label()
w.SetText("Search").SetIcon(icons.Search).SetKey(keymap.Menu).
SetTooltip("Search for pages by name (use " + find + " or context menu to search within current page)")
w.Styler(func(s *styles.Style) {
s.Background = colors.Scheme.SurfaceVariant
s.Padding.Right.Em(5)
})
w.OnClick(func(e events.Event) {
ct.Scene.MenuSearchDialog("Page search", "Search "+core.TheApp.Name())
})
})
}
// MakeToolbarPDF adds the PDF button to the toolbar. This is optional.
func (ct *Content) MakeToolbarPDF(p *tree.Plan) {
tree.Add(p, func(w *core.Button) {
w.SetText("PDF").SetIcon(icons.PictureAsPdf).SetTooltip("PDF generates and opens / downloads the current page as a printable PDF file. See the Settings/Printer panel (Command+,) for settings.")
w.OnClick(func(e events.Event) {
ct.PagePDF("pdfs")
})
})
}
// MakeToolbarSearch adds a within-page search button to the toolbar.
// This is optional.
func (ct *Content) MakeToolbarSearch(p *tree.Plan) {
tree.Add(p, func(w *core.Button) {
w.SetText("Search").SetIcon(icons.Search).SetKey(keymap.Find).
SetTooltip("Search within content of current page")
w.Styler(func(s *styles.Style) {
s.Background = colors.Scheme.SurfaceVariant
s.Padding.Right.Em(5)
})
w.OnClick(func(e events.Event) {
e.SetHandled()
core.Search(ct.rightFrame, core.LastSearch, core.LastUseCase)
})
})
}
func (ct *Content) MenuSearch(items *[]core.ChooserItem) {
newItems := make([]core.ChooserItem, len(ct.pages))
for i, pg := range ct.pages {
newItems[i] = core.ChooserItem{
Value: pg,
Text: pg.Name,
Icon: icons.Article,
Func: func() {
ct.Open(pg.URL)
},
}
}
*items = append(newItems, *items...)
}
// makeBottomButtons makes the previous and next buttons if relevant.
func (ct *Content) makeBottomButtons(p *tree.Plan) {
if len(ct.current.Page.Categories) == 0 || ct.current.Page.URL == "" {
return
}
cat := ct.current.Page.Categories[0]
pages := ct.pagesByCategory[cat]
idx := slices.Index(pages, ct.current.Page)
ct.prevPage, ct.nextPage = nil, nil
if idx > 0 {
ct.prevPage = pages[idx-1]
}
if idx < len(pages)-1 {
ct.nextPage = pages[idx+1]
}
if ct.prevPage == nil && ct.nextPage == nil {
return
}
tree.Add(p, func(w *core.Frame) {
w.Styler(func(s *styles.Style) {
s.Align.Items = styles.Center
s.Grow.Set(1, 0)
})
w.Maker(func(p *tree.Plan) {
if ct.prevPage != nil {
tree.Add(p, func(w *core.Button) {
w.SetText("Previous").SetIcon(icons.ArrowBack).SetType(core.ButtonTonal)
ct.Context.LinkButtonUpdating(w, func() string { // needed to prevent stale URL variable
return ct.prevPage.URL
})
})
}
if ct.nextPage != nil {
tree.Add(p, func(w *core.Stretch) {})
tree.Add(p, func(w *core.Button) {
w.SetText("Next").SetIcon(icons.ArrowForward).SetType(core.ButtonTonal)
ct.Context.LinkButtonUpdating(w, func() string { // needed to prevent stale URL variable
return ct.nextPage.URL
})
})
}
})
})
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Command contentcode compiles the runnable Go and Goal code blocks (```Go,
// ```Goal) of the markdown files of a content app into the app (see
// [cogentcore.org/core/content/contentcode]).
//
// The core tool already does this for every content app in core build, run,
// install, pack and generate; this command is for running it from
// go generate instead, with a directive in the app's main package:
//
// //go:generate go run cogentcore.org/core/content/cmd/contentcode
//
// The core tool then uses the arguments of the directive.
//
// Usage:
//
// contentcode [-content content] [-o contentcode_gen.go] [-tags tags] [-import name=path]... [-goal-record=false] [-force]
package main
import (
"fmt"
"os"
"cogentcore.org/core/content/contentcode"
)
func main() {
c, err := contentcode.ParseArgs(os.Args[0], os.Args[1:])
if err != nil {
os.Exit(2)
}
if _, err := contentcode.Generate(c); err != nil {
fmt.Fprintln(os.Stderr, "contentcode:", err)
os.Exit(1)
}
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package content
import (
"bytes"
"fmt"
"io"
"maps"
"strings"
"unicode"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/text/textcore"
)
// CodeFunc is a Go code block compiled into the app at build time
// (see cogentcore.org/core/content/contentcode, which the core tool
// runs in core build and core generate). It runs the code
// with the given parent widget, which the code knows as b, and writes
// what the code prints to out.
type CodeFunc func(b *core.Frame, out io.Writer)
// CompiledCode maps the [CodeKey] of the source of a code block to the
// function compiled from it at build time. A code block whose source has
// an entry here runs without an interpreter.
var CompiledCode = map[string]CodeFunc{}
// CodeSymbols are values of the app, by name, that its code blocks use,
// such as embedded files. Compiled code (see [CompiledCode]) uses them from
// the app's package directly; interpreters (see [BindTextEditor]) add them
// to the names that code can use without a package, when they are first
// needed.
var CodeSymbols = map[string]any{}
// AddCompiledCode adds the given compiled code blocks to [CompiledCode].
// Generated code calls it.
func AddCompiledCode(code map[string]CodeFunc) {
maps.Copy(CompiledCode, code)
}
// CodeKey returns the key of the given code block source in [CompiledCode]:
// a hash of the source without any whitespace, so that indentation (tabs
// or spaces) and blank lines do not matter. The generator in
// cogentcore.org/core/content/contentcode computes the same key.
func CodeKey(src string) string {
s := strings.Map(func(r rune) rune {
if unicode.IsSpace(r) {
return -1
}
return r
}, src)
h := uint32(2166136261) // FNV-1a
for i := 0; i < len(s); i++ {
h ^= uint32(s[i])
h *= 16777619
}
return fmt.Sprintf("%08x-%d", h, len(s))
}
// BindCode runs the code of the given text editor in the given parent,
// and again whenever the code is edited. Code that was compiled into the
// app (see [CompiledCode]) runs directly. Other code, including edited
// code, runs in the interpreter of [BindTextEditor] if there is one
// (mvm, through cogentcore.org/core/mvmcore); otherwise an edit shows
// a message that this app can not run edited code. Goal code runs
// compiled while it matches the Goal code compiled for the page (see
// [CompiledGoal]).
func BindCode(ed *textcore.Editor, parent *core.Frame, language string) {
bindFormat(ed, language)
if language == "Goal" {
bindGoal(ed, parent)
return
}
if language == "Go" {
if f := CompiledCode[CodeKey(ed.Lines.String())]; f != nil {
bindCompiledCode(ed, parent, language, f)
return
}
}
if BindTextEditor != nil {
BindTextEditor(ed, parent, language)
return
}
// The code was not compiled (the generator could not compile it) and
// there is no interpreter: it is shown, but does not run.
errors.Log(fmt.Errorf("content: %s code block was not compiled into the app and there is no interpreter to run it", language))
}
// bindCompiledCode runs f now, and hands the editor to the interpreter
// once the code is edited.
func bindCompiledCode(ed *textcore.Editor, parent *core.Frame, language string, f CodeFunc) {
key := CodeKey(ed.Lines.String())
interpreted := false
ed.OnChange(func(e events.Event) {
if interpreted {
return
}
src := ed.Lines.String()
if g := CompiledCode[CodeKey(src)]; g != nil {
if CodeKey(src) != key {
key = CodeKey(src)
f = g
runCompiledCode(ed, parent, f)
}
return
}
if BindTextEditor == nil {
core.ErrorSnackbar(ed, fmt.Errorf("this app has no interpreter to run edited code (only the code compiled into it)"), "Error running "+language+" code")
return
}
// BindTextEditor runs the code now and on later changes.
interpreted = true
BindTextEditor(ed, parent, language)
})
runCompiledCode(ed, parent, f)
}
// runCompiledCode runs f in parent, like the interpreter would.
func runCompiledCode(ed *textcore.Editor, parent *core.Frame, f CodeFunc) {
runCode(ed, parent, func(out io.Writer) { f(parent, out) })
}
// runCode runs compiled code in parent, like the interpreter would: run
// runs it with the given output, which is shown below the result, and
// a panic is shown as an error.
func runCode(ed *textcore.Editor, parent *core.Frame, run func(out io.Writer)) {
parent.DeleteChildren()
// a program that makes a body and runs a window adds it to parent instead
core.ExternalParent = parent
defer func() { core.ExternalParent = nil }()
var out bytes.Buffer
err := func() (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("panic: %v", r)
}
}()
run(&out)
return nil
}()
if ostr := out.String(); len(strings.TrimSpace(ostr)) > 0 {
oe := textcore.NewEditor(parent)
oe.SetReadOnly(true)
oe.Lines.Settings.LineNumbers = false
oe.Lines.SetString(ostr)
}
ShowCodeErrors(ed, parent, err)
parent.Update()
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package content
import (
"errors"
"fmt"
"unicode"
"cogentcore.org/core/colors"
"cogentcore.org/core/core"
"cogentcore.org/core/styles"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/textcore"
"cogentcore.org/core/text/textpos"
)
// positionedError is an error of running code at a position in the code,
// such as those of cogentcore.org/core/mvmcore and of Goal.
type positionedError interface {
error
// CodePos returns the 1-based line and column (in bytes) of the error
// in the code, 0 if not known.
CodePos() (line, col int)
// CodeMessage returns the message of the error, without its position.
CodeMessage() string
}
// ShowCodeErrors shows the given error of running the code of the given
// text editor, if non-nil, and otherwise clears the errors of the editor.
// The errors at a position in the code are marked in the editor (see
// [textcore.Base.SetCodeErrors]), whose tooltips are their messages, and
// the messages of all of the errors are shown in the given parent, below
// the output of the code.
func ShowCodeErrors(ed *textcore.Editor, parent *core.Frame, err error) {
if err == nil {
ed.SetCodeErrors()
return
}
var marks []textcore.CodeError
var msgs []string
for _, e := range splitErrors(err) {
pe, ok := e.(positionedError)
if !ok {
msgs = append(msgs, e.Error())
continue
}
line, col := pe.CodePos()
if line <= 0 {
msgs = append(msgs, pe.CodeMessage())
continue
}
msgs = append(msgs, fmt.Sprintf("%d:%d: %s", line, col, pe.CodeMessage()))
if reg, ok := errorRegion(ed, line, col); ok {
marks = append(marks, textcore.CodeError{Region: reg, Msg: pe.CodeMessage()})
}
}
ed.SetCodeErrors(marks...)
fr := core.NewFrame(parent)
fr.Styler(func(s *styles.Style) {
s.Direction = styles.Column
s.Grow.Set(1, 0)
})
for _, msg := range msgs {
tx := core.NewText(fr).SetText(msg)
tx.Styler(func(s *styles.Style) {
s.Color = colors.Scheme.Error.Base
s.Font.Family = rich.Monospace
s.Grow.Set(1, 0)
})
}
}
// splitErrors returns the errors of the given error, which are the
// errors that it joins, if it joins errors, with any of those that are
// at a position in the code.
func splitErrors(err error) []error {
if _, ok := err.(positionedError); ok {
return []error{err}
}
if j, ok := err.(interface{ Unwrap() []error }); ok {
var errs []error
for _, e := range j.Unwrap() {
errs = append(errs, splitErrors(e)...)
}
return errs
}
if pe, ok := errors.AsType[positionedError](err); ok {
return []error{pe}
}
return []error{err}
}
// errorRegion returns the region of the text of the given editor of an
// error at the given 1-based line and column (in bytes): that of the word
// or other character at the position.
func errorRegion(ed *textcore.Editor, line, col int) (textpos.Region, bool) {
ln := line - 1
if ed.Lines == nil || ln >= ed.Lines.NumLines() {
return textpos.Region{}, false
}
rs := ed.Lines.Line(ln)
st := len(byteRunes(rs, col-1)) // the column is in bytes; the region is in runes
end := st
isWord := func(r rune) bool { return r == '_' || unicode.IsLetter(r) || unicode.IsDigit(r) }
for end < len(rs) && isWord(rs[end]) {
end++
}
if end == st {
end = min(st+1, len(rs))
}
if end == st { // an error at the end of the line
st = max(st-1, 0)
}
return textpos.Region{Start: textpos.Pos{Line: ln, Char: st}, End: textpos.Pos{Line: ln, Char: end}}, end > st
}
// byteRunes returns the runes of the given line that are in its first n
// bytes, in UTF-8.
func byteRunes(rs []rune, n int) []rune {
b := 0
for i, r := range rs {
if b >= n {
return rs[:i]
}
b += len(string(r))
}
return rs
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package content
import (
"go/format"
"strings"
"cogentcore.org/core/events"
"cogentcore.org/core/text/lines"
"cogentcore.org/core/text/textcore"
"cogentcore.org/core/text/textpos"
)
// FormatCode are the functions that format the code of the code blocks
// of each language (such as "Go") when it is edited, as gofmt does for
// Go code, which is the default. Other packages can add other languages,
// as cogentcore.org/lab/mvmlab does Goal. A function returns an error
// for code that it cannot format, which is left as it is.
var FormatCode = map[string]func(src string) (string, error){
"Go": formatGo,
}
// formatGo formats the given Go code, which can be a list of
// declarations or statements, as gofmt does.
func formatGo(src string) (string, error) {
b, err := format.Source([]byte(src))
return string(b), err
}
// bindFormat formats the code of the given editor of a code block of the
// given language when it is edited (see [FormatCode]), before it runs.
// The function of the language is found then, as it can be added when
// code is first edited, by a package that is loaded then.
func bindFormat(ed *textcore.Editor, language string) {
ed.OnFirst(events.Change, func(e events.Event) {
formatEditor(ed, language)
})
}
// formatEditor formats the code of the given editor of a code block of
// the given language, as an edit that can be undone, keeping the cursor
// on its line. The editor is not marked as changed, so that formatting
// does not run the code again.
func formatEditor(ed *textcore.Editor, language string) {
f := FormatCode[language]
ln := ed.Lines
if f == nil || ln == nil {
return
}
src := ln.String()
res, err := f(src)
if err != nil || res == src { // errors are shown when the code runs
return
}
// the text ends with a newline after the end of its last line
if strings.HasSuffix(src, "\n") {
res = strings.TrimSuffix(res, "\n")
}
cur := ed.CursorPos
ln.ReplaceText(textpos.Pos{}, ln.EndPos(), textpos.Pos{}, res, lines.ReplaceNoMatchCase)
ln.SetChanged(false)
cur.Line = min(cur.Line, ln.NumLines()-1)
cur.Char = min(cur.Char, ln.LineLen(cur.Line))
ed.SetCursorShow(cur)
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package content provides a system for making content-focused
// apps and websites consisting of Markdown, HTML, and Cogent Core.
package content
//go:generate core generate
import (
"bytes"
"cmp"
"fmt"
"io/fs"
"net/http"
"os"
"path/filepath"
"slices"
"strings"
"time"
"golang.org/x/exp/maps"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/fsx"
"cogentcore.org/core/base/strcase"
"cogentcore.org/core/content/bcontent"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/events/key"
"cogentcore.org/core/htmlcore"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/system"
"cogentcore.org/core/text/csl"
"cogentcore.org/core/text/paginate"
"cogentcore.org/core/tree"
)
// maxTextWidth is the maximum width of the blocks of text of a page
// ([textBlocks]), in CSS inches. Code, images, and the widgets of element
// handlers, such as simulations, can be wider.
const maxTextWidth = 9
// textBlocks is the CSS selector of the blocks of text of a page, which
// are at most [maxTextWidth] wide.
const textBlocks = "p, h1, h2, h3, h4, h5, h6, ul, ol, dl, blockquote, table, hr, figcaption, details"
// Content manages and displays the content of a set of pages.
type Content struct {
core.Splits
// Source is the source filesystem for the content.
// It should be set using [Content.SetSource] or [Content.SetContent].
Source fs.FS `set:"-"`
// Context is the [htmlcore.Context] used to render the content,
// which can be modified for things such as adding wikilink handlers.
Context *htmlcore.Context `set:"-"`
// References is a list of references used for generating citation text
// for literature reference wikilinks in the format [[@CiteKey]].
References *csl.KeyList
// NoTabs is whether the page is shown without tabs, as it is on the
// web, where pages can not be opened in new tabs, as for content that
// is one page, such as a document in another app.
NoTabs bool
// pages are the pages that constitute the content.
pages []*bcontent.Page
// pagesByName has the [bcontent.Page] for each [bcontent.Page.Name]
// transformed into lowercase. See [Content.pageByName] for a helper
// function that automatically transforms into lowercase.
pagesByName map[string]*bcontent.Page
// pagesByURL has the [bcontent.Page] for each [bcontent.Page.URL].
pagesByURL map[string]*bcontent.Page
// pageBases are the base URLs of the pages in the mounts of a [MountFS]
// source, the directories of their files, against which the relative
// URLs of their resources are resolved.
pageBases map[*bcontent.Page]string
// pagesByCategory has the [bcontent.Page]s for each of all [bcontent.Page.Categories].
pagesByCategory map[string][]*bcontent.Page
// categories has all unique [bcontent.Page.Categories], sorted such that the categories
// with the most pages are listed first. "Other" is always last, and is used for pages that
// do not have a category, unless they are a category themselves.
categories []string
// history is the history of pages that have been visited, per tab.
history []*History
// current is the current location, in current tab.
current Location
// rendered is the most recently rendered location, in current tab.
rendered Location
// leftFrame is the frame on the left side of the widget,
// used for displaying the table of contents and the categories.
leftFrame *core.Frame
// rightFrame is the frame on the right side of the widget,
// used for displaying the page content.
rightFrame *core.Frame
// tabs are the tabs, only for non-web
tabs *core.Tabs
// top toolbar, if present
toolbar *core.Toolbar
// tocNodes are all of the tree nodes in the table of contents
// by kebab-case heading name.
tocNodes map[string]*core.Tree
// tocTree is the table of contents tree of the current page in [Content.leftFrame].
tocTree *core.Tree
// categoriesTree is the categories tree in [Content.leftFrame]. It is made once
// and kept between pages; [Content.updateCategories] updates it for each page.
categoriesTree *core.Tree
// categoryTrees are the tree nodes of [Content.categories] in [Content.categoriesTree].
categoryTrees []*core.Tree
// categoryPages are the pages of the page nodes in [Content.categoriesTree].
categoryPages map[*core.Tree]*bcontent.Page
// inPDFRender indicates that it is rendering a PDF now, turning off
// elements that are not appropriate for that.
inPDFRender bool
// noWebURL is whether the content does not use the URL of the web page,
// as for the help of an app (see [OpenHelp]), whose own URL it is.
noWebURL bool
// The previous and next page, if applicable. They must be stored on this struct
// to avoid stale local closure variables.
prevPage, nextPage *bcontent.Page
// if non-nil, a message is sent when content page is rendered
renderChan chan struct{}
// loads counts the pages loaded by [Content.loadPage], so that the rest of
// a staged page (see [Content.loadRest]) is only added to its own page.
loads int
// leftScroll is the vertical scroll offset of [Content.leftFrame] when
// a staged page was loaded, which [Content.loadRest] restores.
leftScroll float32
}
// stagePages is whether long pages are shown in two stages on the web: the
// first part of the page is shown first, and the rest is added right after
// (see [Content.loadRest]). Building, styling and laying out the widgets of a
// long page takes much longer on the web than natively, and most of them are
// not visible at first.
var stagePages = true
func init() {
// We want Command+[ and Command+] to work for browser back/forward navigation
// in content, since we rely on that. They should still be intercepted by
// Cogent Core for non-content apps for things such as full window dialogs,
// so we only add these in content.
system.ReservedWebShortcuts = append(system.ReservedWebShortcuts, "Command+[", "Command+]")
}
// keepCategories is whether the categories tree is kept between pages,
// instead of being made again for each page (tests compare the two).
var keepCategories = true
// NewPageInitFunc is called when a new page is just being rendered.
// This can do any necessary new-page initialization, e.g.,
// [mvmcore.ResetGoalInterpreter]
var NewPageInitFunc func()
// ImageCacheBytes is the maximum total size in bytes of the decoded
// images that a [Content] keeps in the [htmlcore.ImageCache] of its
// [Content.Context], so that revisiting a page does not decode its
// images again.
var ImageCacheBytes = 64 << 20
func (ct *Content) Init() {
ct.Splits.Init()
ct.SetSplits(0.2, 0.8)
ct.Context = htmlcore.NewContext()
// in the page, which has its own padding; the blocks of text of the page
// (at any depth, as in the element of a simulation that is not closed)
// are not too wide to read (as on a wide screen), and big enough to not
// constrain PDF render, but code, images, and the widgets of element
// handlers (which do not get the styles), such as simulations, can have
// the whole width of the page.
ct.Context.SetStyle(fmt.Sprintf("body { margin: 0; } %s { max-width: %din; }", textBlocks, maxTextWidth))
ct.Context.SetDelayedImageLoad(false) // not useful for content
// The source does not change until SetSource, which resets the cache.
ct.Context.SetImageCache(htmlcore.NewImageCache(ImageCacheBytes))
ct.Context.SetOpenURL(func(url string, e events.Event) {
ct.OpenEvent(url, e)
})
ct.Context.SetGetURL(func(url string) (*http.Response, error) {
return htmlcore.GetURLFromFS(ct.Source, url)
})
ct.Context.AddWikilinkHandler(ct.citeWikilink)
ct.Context.AddWikilinkHandler(ct.mainWikilink)
ct.Context.AddElementHandler("embed-page", func(ctx *htmlcore.Context) bool {
errors.Log(ct.embedPage(ctx))
return true
})
ct.Context.AddElementHandler("pre", ct.htmlPreHandler)
ct.Context.AddAttributeHandler("id", ct.htmlIDAttributeHandler)
ct.Context.AddWidgetHandler(ct.widgetHandler)
ct.Maker(func(p *tree.Plan) {
if ct.current.Page == nil {
return
}
tree.Add(p, func(w *core.Frame) {
ct.leftFrame = w
})
tree.Add(p, func(w *core.Frame) {
ct.rightFrame = w
w.Maker(func(p *tree.Plan) {
if ct.NoTabs || core.TheApp.Platform() == system.Web || system.GenerateHTMLArg() {
ct.pageMaker(p, 0)
} else {
tree.Add(p, func(w *core.Tabs) {
ct.tabs = w
w.SetType(core.FunctionalTabs).SetNewTabButton(true)
w.NewTabFunc = func(index int) {
ct.newTab(ct.tabs.TabAtIndex(index))
ct.open("", true)
}
w.CloseTabFunc = func(index int) {
ct.history = slices.Delete(ct.history, index, index+1)
_, ci := ct.tabs.CurrentTab()
h := ct.history[ci]
lc := h.Records[h.Index]
ct.open(lc.URL, false)
if ct.toolbar != nil {
ct.toolbar.Update()
}
}
fr, _ := w.NewTab("Content")
h := &History{}
h.Save(ct.current.Clone())
ct.history = []*History{h}
fr.Maker(func(p *tree.Plan) { ct.pageMaker(p, 0) })
})
}
})
})
})
// Must be done after the default title is set elsewhere in normal OnShow
ct.OnFinal(events.Show, func(e events.Event) {
ct.setStageTitle()
})
ct.handleWebPopState()
}
// pageFrame returns the current frame for rendering the page.
func (ct *Content) pageFrame() *core.Frame {
if ct.tabs == nil {
return ct.rightFrame
}
w, _ := ct.tabs.CurrentTab()
return w.(*core.Frame)
}
// pageMaker is the maker function for a page
func (ct *Content) pageMaker(p *tree.Plan, tabIdx int) {
tree.Add(p, func(w *core.Frame) {
if system.GenerateHTMLArg() {
w.SetProperty("class", "cc-page-frame") // responsive padding in the web content.css
}
w.Styler(func(s *styles.Style) {
s.Direction = styles.Column
s.Grow.Set(1, 1)
s.Shrink.X = 1 // as wide as the page panel, in which the text wraps
switch w.SizeClass() {
case core.SizeCompact, core.SizeMedium:
s.Padding.SetHorizontal(units.Em(0.5))
case core.SizeExpanded:
s.Padding.SetHorizontal(units.Em(3))
}
})
w.Maker(func(p *tree.Plan) {
if ct.tabs != nil {
_, ci := ct.tabs.CurrentTab()
if ci != tabIdx {
return
}
h := ct.history[tabIdx]
lc := h.Records[h.Index]
ct.current = *lc
}
if !ct.inPDFRender && ct.current.Page.Title != "" {
tree.Add(p, func(w *core.Text) {
w.Updater(func() {
w.SetText(ct.current.Page.Title)
})
w.SetType(core.TextDisplaySmall)
if system.GenerateHTMLArg() {
w.SetProperty("tag", "h1")
w.SetProperty("page-title", true) // not in table of contents
}
})
}
if !ct.inPDFRender && len(ct.current.Page.Authors) > 0 {
tree.Add(p, func(w *core.Text) {
w.SetType(core.TextTitleLarge)
w.Updater(func() {
w.SetText("By " + ct.current.Page.Authors)
})
})
}
if !ct.inPDFRender && len(ct.current.Page.Affiliations) > 0 {
tree.Add(p, func(w *core.Text) {
w.SetType(core.TextBodyLarge)
w.Updater(func() {
w.SetText(ct.current.Page.Affiliations)
})
})
}
if !ct.inPDFRender && !ct.current.Page.Date.IsZero() {
tree.Add(p, func(w *core.Text) {
w.SetType(core.TextTitleMedium)
w.Updater(func() {
if ct.current.Page.Version != "" {
w.SetText(ct.current.Page.Date.Format("January 2, 2006") + ", Version: " + ct.current.Page.Version)
} else {
w.SetText(ct.current.Page.Date.Format("January 2, 2006"))
}
})
})
}
if !ct.inPDFRender && ct.current.Page.Date.IsZero() && ct.current.Page.Version != "" {
tree.Add(p, func(w *core.Text) {
w.SetType(core.TextTitleMedium)
w.Updater(func() {
w.SetText(" Version: " + ct.current.Page.Version)
})
})
}
if !ct.inPDFRender && len(ct.current.Page.Reference) > 0 {
tree.Add(p, func(w *core.Text) {
w.SetType(core.TextBodyLarge)
w.Updater(func() {
w.SetText(ct.current.Page.Reference)
})
})
}
if !ct.inPDFRender && len(ct.current.Page.Abstract) > 0 {
tree.Add(p, func(w *core.Text) {
w.SetType(core.TextBodyLarge)
w.Updater(func() {
w.SetText("<b>Abstract:</b> " + ct.current.Page.Abstract)
})
})
}
tree.Add(p, func(w *core.Frame) {
w.Styler(func(s *styles.Style) {
s.Direction = styles.Column
s.Grow.Set(1, 1)
s.Shrink.X = 1
})
w.Updater(func() {
errors.Log(ct.loadPage(w))
if ct.toolbar != nil {
ct.toolbar.Update()
}
})
})
if !ct.inPDFRender {
ct.makeBottomButtons(p)
}
})
})
}
// pageByName returns [Content.pagesByName] of the lowercase version of the given name.
func (ct *Content) pageByName(name string) *bcontent.Page {
ln := strings.ToLower(name)
if pg, ok := ct.pagesByName[ln]; ok {
return pg
}
nd := strings.ReplaceAll(ln, "-", " ")
if pg, ok := ct.pagesByName[nd]; ok {
return pg
}
return nil
}
// Files is the source filesystem of the content of the app (the
// [Content.Source] that was set last), for the code of its pages to open
// data files in it by their path in the content, as in
// table.OpenFS(content.Files, "datasets/planets.csv", tensor.Comma).
var Files fs.FS
// SetSource sets the source filesystem for the content,
// which is also the [Files] of the app.
func (ct *Content) SetSource(source fs.FS) *Content {
ct.Source = source
Files = source
if ic := ct.Context.ImageCache(); ic != nil {
ic.Reset()
}
ct.pages = []*bcontent.Page{}
ct.pagesByName = map[string]*bcontent.Page{}
ct.pagesByURL = map[string]*bcontent.Page{}
ct.pagesByCategory = map[string][]*bcontent.Page{}
ct.pageBases = map[*bcontent.Page]string{}
mfs, _ := source.(*MountFS)
var mounted []*bcontent.Page // pages in mounts, named after the others
errors.Log(fs.WalkDir(ct.Source, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
if path == "" || path == "." {
return nil
}
ext := filepath.Ext(path)
if ext != ".md" && ext != ".html" {
return nil
}
if mfs != nil {
if mt, rel := mfs.mountOf(path); mt != nil {
pg, err := ct.newMountedPage(mt, rel)
if err != nil {
return err
}
mounted = append(mounted, pg)
return nil
}
}
pg, err := bcontent.NewPage(ct.Source, path)
if err != nil {
return err
}
ct.addPage(pg)
return nil
}))
if mfs != nil {
ct.addMountedPages(mfs, mounted)
}
ct.categories = maps.Keys(ct.pagesByCategory)
slices.SortFunc(ct.categories, func(a, b string) int {
if a == "Other" {
return 1
}
if b == "Other" {
return -1
}
v := cmp.Compare(len(ct.pagesByCategory[b]), len(ct.pagesByCategory[a]))
if v != 0 {
return v
}
return cmp.Compare(a, b)
})
// Pages that are a category are already represented in the categories tree,
// so they do not belong in the "Other" category.
ct.pagesByCategory["Other"] = slices.DeleteFunc(ct.pagesByCategory["Other"], func(pg *bcontent.Page) bool {
_, isCategory := ct.pagesByCategory[pg.Name]
if isCategory {
pg.Categories = slices.DeleteFunc(pg.Categories, func(c string) bool {
return c == "Other"
})
}
return isCategory
})
// The categories tree of the old source is made again.
if ct.categoriesTree != nil {
ct.categoriesTree.Delete()
ct.categoriesTree = nil
}
if url := ct.getWebURL(); url != "" {
return ct.Open(url)
}
if root, ok := ct.pagesByURL[""]; ok {
return ct.Open(root.URL)
}
return ct.Open(ct.pages[0].URL)
}
// SetContent is a helper function that calls [Content.SetSource]
// with the "content" subdirectory of the given filesystem.
func (ct *Content) SetContent(content fs.FS) *Content {
return ct.SetSource(fsx.Sub(content, "content"))
}
// OpenEvent opens the page with the given URL and updates the display.
// If no pages correspond to the URL, it is opened in the default browser.
// This version is for widget event cases, where the keyboard modifiers
// are used to control the way the page is opened: Ctrl/Meta = new tab.
func (ct *Content) OpenEvent(url string, e events.Event) *Content {
if e == nil || !e.HasAnyModifier(key.Control, key.Meta) {
return ct.Open(url)
}
if ct.tabs == nil {
if strings.HasPrefix(url, "https://") || strings.HasPrefix(url, "http://") {
core.TheApp.OpenURL(url)
return ct
}
if strings.HasPrefix(url, "ref://") {
ct.openRef(url)
return ct
}
_, pg, heading := ct.parseURL(url)
_, nw, err := ct.pageURL(pg, heading)
if err != nil || nw == nil { // (no URL other than on the web)
return ct
}
core.TheApp.OpenURL(nw.String())
return ct
}
nt := ct.tabs.NumTabs()
nm := fmt.Sprintf("Tab %d", nt+1)
ct.newTab(ct.tabs.NewTab(nm))
return ct.Open(url)
}
func (ct *Content) newTab(fr *core.Frame, tb *core.Tab) {
ct.rendered.Reset()
nt := ct.tabs.NumTabs()
nm := fmt.Sprintf("Tab %d", nt)
tb.SetText(nm)
h := &History{}
h.Save(ct.current.Clone())
ct.history = append(ct.history, h)
fr.Maker(func(p *tree.Plan) {
ct.pageMaker(p, nt-1)
})
ct.tabs.SelectTabIndex(nt - 1)
}
// Open opens the page with the given URL and updates the display.
// If no pages correspond to the URL, it is opened in the default browser.
// This version is for programmatic use -- see also OpenEvent.
func (ct *Content) Open(url string) *Content {
ct.open(url, true)
return ct
}
// reloadPage reloads the current page
func (ct *Content) reloadPage() {
ct.rendered.Reset()
ct.Update()
}
// loadPage loads the current page content into the given frame if it is not already loaded.
func (ct *Content) loadPage(w *core.Frame) error {
if NewPageInitFunc != nil {
NewPageInitFunc()
}
resetGoal(ct.current.Page.Filename)
w.DeleteChildren()
b, err := ct.current.Page.ReadContent(ct.pagesByCategory)
if err != nil {
return err
}
ct.current.Page.ParseSpecials(b)
// A long page opened at its start is shown in two stages on the web.
ct.loads++
staged := stagePages && core.TheApp.Platform() == system.Web && ct.current.Heading == "" && !ct.inPDFRender
if staged {
ct.Context.SetStageSize(ct.stageSize())
ct.leftScroll = ct.leftFrame.Geom.Scroll.Y
}
// The relative URLs of the resources of a page in a mount of a MountFS
// are relative to the page.
ct.Context.SetPageURL(ct.pageBase(ct.current.Page))
err = htmlcore.ReadMD(ct.Context, w, b)
ct.Context.SetStageSize(0)
if err != nil {
return err
}
if ct.Context.HasRest() {
loads := ct.loads
w.Defer(func() {
go ct.loadRest(w, loads)
})
}
ct.makeTableOfContents(w)
// A new categories tree is styled with the table of contents; a kept one only
// restyles the nodes whose selection changes, in updateCategories.
if ct.makeCategories() {
ct.leftFrame.Update()
} else {
ct.updateCategories(true)
if ct.tocTree != nil {
ct.tocTree.Update()
}
ct.leftFrame.NeedsLayout()
}
ct.rendered = ct.current
return nil
}
// stageSize returns the size of the first stage of a staged page (see
// [htmlcore.Context.StageSize]): about three times the text that fits in
// the window.
func (ct *Content) stageSize() int {
sz := ct.Scene.SceneGeom.Size
charsPerLine := max(sz.X/9, 40)
lines := max(sz.Y/24, 20)
return 3 * charsPerLine * lines
}
// loadRest adds the rest of a staged page to the page frame w after the
// first stage has been shown, unless another page has been loaded since
// (the given loads is [Content.loads] when the page was loaded).
func (ct *Content) loadRest(w *core.Frame, loads int) {
// The browser shows the first stage before the rest is added.
time.Sleep(time.Millisecond)
ct.AsyncLock()
defer ct.AsyncUnlock()
if ct.loads != loads || w.This == nil || !ct.Context.HasRest() {
return
}
// The widgets of the rest are updated, styled and laid out, and the
// table of contents is made again with their headings.
parent, start, err := ct.Context.ReadRest()
errors.Log(err)
pw := parent.AsWidget()
for _, c := range pw.Children[start:] {
c.(core.Widget).AsWidget().Update()
}
ct.makeTableOfContents(w)
if ct.tocTree != nil {
ct.tocTree.Update()
}
ct.leftFrame.NeedsLayout()
w.NeedsLayout()
// The sidebar is scrolled back to where it was before the page was
// loaded, which the shorter table of contents of the first stage may
// have limited, once the layout has updated its range.
if scroll := ct.leftScroll; scroll != 0 {
ct.leftFrame.Defer(func() {
if sb := ct.leftFrame.Scrolls[math32.Y]; sb != nil && ct.loads == loads {
sb.SetValue(-scroll)
ct.leftFrame.ScrollChanged(math32.Y, sb)
}
})
}
}
func (ct *Content) RenderWidget() {
ct.Splits.RenderWidget()
if ct.renderChan != nil {
select {
case ct.renderChan <- struct{}{}:
default:
}
}
}
// makeTableOfContents makes the table of contents and adds it to [Content.leftFrame]
// based on the headings in the given frame.
func (ct *Content) makeTableOfContents(w *core.Frame) {
ct.deleteTableOfContents()
ct.tocNodes = map[string]*core.Tree{}
// The table of contents goes before the categories tree, which is kept between pages.
contents := core.NewTree()
ct.leftFrame.InsertChild(contents, 0)
contents.SetText("<b>Contents</b>")
ct.tocTree = contents
contents.SetReadOnly(true)
contents.OnSelect(func(e events.Event) {
if contents.IsRootSelected() {
ct.pageFrame().ScrollDimToContentStart(math32.Y)
ct.current.Heading = ""
ct.saveWebURL(&ct.current)
}
})
// last is the most recent tree node for each heading level, used for nesting.
last := map[int]*core.Tree{}
for cw, cwb := range w.AllWidgets() {
num, text, ok := headingOf(cw)
if ok {
parent := contents
// Our parent is the last heading with a lower level (closer to h1).
for i := num - 1; i >= 1; i-- {
if last[i] != nil {
parent = last[i]
break
}
}
tr := core.NewTree(parent).SetText(text)
tr.SetProperty("page-text", cw)
last[num] = tr
kebab := strcase.ToKebab(tr.Text)
ct.tocNodes[kebab] = tr
tr.OnSelect(func(e events.Event) {
curPg, heading := ct.current, ct.current.Heading
_ = heading
ct.saveUpdatedPos(curPg)
cwb.ScrollThisToTop()
ct.OpenEvent(ct.current.Page.URL+"#"+kebab, e)
})
}
}
if contents.NumChildren() == 0 {
ct.deleteTableOfContents()
}
}
// deleteTableOfContents deletes the table of contents tree, if there is one.
func (ct *Content) deleteTableOfContents() {
if ct.tocTree != nil {
ct.tocTree.Delete()
ct.tocTree = nil
}
}
// hasCategoriesTree returns whether [Content.categoriesTree] is the
// current categories tree in [Content.leftFrame].
func (ct *Content) hasCategoriesTree() bool {
cats := ct.categoriesTree
return cats != nil && cats.This != nil && ct.leftFrame != nil && cats.Parent == ct.leftFrame.This
}
// makeCategories makes the categories tree for the current page and adds it to
// [Content.leftFrame] if it does not have it yet, returning whether it made it.
func (ct *Content) makeCategories() bool {
if len(ct.categories) == 0 || ct.hasCategoriesTree() {
return false
}
// Without categories, all of the pages are in "Other", and they are
// listed as the pages of the content, with no category trees.
flat := ct.noCategories()
cats := core.NewTree(ct.leftFrame).SetText("<b>Categories</b>")
if flat {
cats.SetText("<b>Pages</b>")
}
cats.SetReadOnly(true)
cats.OnSelect(func(e events.Event) {
if cats.IsRootSelected() {
ct.OpenEvent("", e)
}
})
ct.categoriesTree = cats
ct.categoryTrees = make([]*core.Tree, len(ct.categories))
ct.categoryPages = map[*core.Tree]*bcontent.Page{}
if flat {
ct.categoryTrees = nil
for _, pg := range ct.pagesByCategory["Other"] {
pgTree := core.NewTree(cats).SetText(pg.Name)
ct.categoryPages[pgTree] = pg
pgTree.OnSelect(func(e events.Event) {
ct.OpenEvent(pg.URL, e)
})
}
ct.updateCategories(false)
return true
}
for i, cat := range ct.categories {
catTree := core.NewTree(cats).SetText(cat).SetClosed(true)
ct.categoryTrees[i] = catTree
catTree.OnSelect(func(e events.Event) {
if catPage := ct.pageByName(cat); catPage != nil {
ct.OpenEvent(catPage.URL, e)
} else {
catTree.Open() // no page to open so open the tree
}
})
for _, pg := range ct.pagesByCategory[cat] {
if strings.EqualFold(cat, pg.Name) {
continue
}
pgTree := core.NewTree(catTree).SetText(pg.Name)
ct.categoryPages[pgTree] = pg
pgTree.OnSelect(func(e events.Event) {
ct.OpenEvent(pg.URL, e)
})
}
}
ct.updateCategories(false)
return true
}
// noCategories returns whether the pages have no categories, so that
// they are all in the "Other" category, in which case the categories tree
// lists the pages, as "Pages", without category trees.
func (ct *Content) noCategories() bool {
return len(ct.categories) == 1 && ct.categories[0] == "Other"
}
// updateCategories selects the nodes of the categories tree for the current page
// and opens the categories that contain it, closing the others, as a new tree has them.
// If restyle is true, the nodes whose selection changes are styled again.
func (ct *Content) updateCategories(restyle bool) {
var selected []core.Treer
// setSelected sets whether the given node is selected.
setSelected := func(tr *core.Tree, sel bool) {
if sel {
selected = append(selected, tr)
}
if tr.StateIs(states.Selected) == sel {
return
}
tr.SetState(sel, states.Selected)
if restyle {
styleTreeNode(tr)
}
}
// The root is selected by a click on it until the home page opens.
setSelected(ct.categoriesTree, false)
if ct.categoryTrees == nil { // the pages, without categories
for _, k := range ct.categoriesTree.Children {
pgTree := k.(*core.Tree)
setSelected(pgTree, ct.categoryPages[pgTree] == ct.current.Page)
}
}
for i, catTree := range ct.categoryTrees {
setSelected(catTree, ct.current.Page.Name == ct.categories[i])
hasPage := false
for _, k := range catTree.Children {
pgTree := k.(*core.Tree)
isPage := ct.categoryPages[pgTree] == ct.current.Page
hasPage = hasPage || isPage
setSelected(pgTree, isPage)
}
if hasPage {
catTree.Open()
} else {
catTree.Close()
}
}
ct.categoriesTree.SelectedNodes = selected
}
// styleTreeNode styles the given tree node and its parts, which inherit
// its selection colors, but not its child nodes.
func styleTreeNode(tr *core.Tree) {
tr.Style()
if tr.Parts != nil {
for cw := range tr.Parts.AllWidgets() {
cw.Style()
}
}
tr.NeedsRender()
}
// updateScene updates the scene for a new page, as [core.WidgetBase.Update]
// does, except for the categories tree, which [Content.loadPage] updates.
func (ct *Content) updateScene() {
cats := ct.categoriesTree
if !ct.hasCategoriesTree() {
cats = nil
}
ct.Scene.WidgetWalkDown(func(cw core.Widget, cwb *core.WidgetBase) bool {
if cats != nil && cwb == cats.AsWidget() {
return tree.Break
}
cwb.UpdateWidget()
cw.Style()
return tree.Continue
})
ct.Scene.NeedsLayout()
}
// embedPage handles an <embed-page> element by embedding the lead section
// (content before the first heading) into the current page, with a heading
// and a *Main page: [[Name]]* link added at the start as well. The name of
// the embedded page is the case-insensitive src attribute of the current
// html element. A title attribute may also be specified to override the
// heading text.
func (ct *Content) embedPage(ctx *htmlcore.Context) error {
src := htmlcore.GetAttr(ctx.Node(), "src")
if src == "" {
return fmt.Errorf("missing src attribute in <embed-page>")
}
pg := ct.pageByName(src)
if pg == nil {
return fmt.Errorf("page %q not found in <embed-page>", src)
}
title := htmlcore.GetAttr(ctx.Node(), "title")
if title == "" {
title = pg.Name
}
b, err := pg.ReadContent(ct.pagesByCategory)
if err != nil {
return err
}
lead, _, _ := bytes.Cut(b, []byte("\n#"))
heading := fmt.Sprintf("## %s\n\n*Main page: [[%s]]*\n\n", title, pg.Name)
res := append([]byte(heading), lead...)
base := ctx.PageURL()
ctx.SetPageURL(ct.pageBase(pg))
defer ctx.SetPageURL(base)
return htmlcore.ReadMD(ctx, ctx.BlockParent(), res)
}
// setStageTitle sets the title of the stage based on the current page URL,
// which the window has again when a dialog on it closes.
func (ct *Content) setStageTitle() {
if rw := ct.Scene.RenderWindow(); rw != nil && ct.current.Page != nil {
name := ct.current.Page.Name
if ct.current.Page.URL == "" { // Root page just gets app name
name = core.TheApp.Name()
}
if ct.Scene.Stage != nil {
ct.Scene.Stage.SetTitle(name)
}
rw.SetStageTitle(name)
}
}
// PagePDF generates a PDF of the current page, to given file path
// (directory). the page name is the file name.
func (ct *Content) PagePDF(path string) error {
if ct.current.Page == nil {
return errors.Log(errors.New("Page empty"))
}
core.MessageSnackbar(ct, "Generating PDF...")
Settings.PDF.FontScale = (100.0 / core.AppearanceSettings.DocsFontSize)
ct.inPDFRender = true
ct.reloadPage()
ct.inPDFRender = false
refs := ct.PageRefs(ct.current.Page)
fname := ct.current.Page.Name + ".pdf"
if path != "" {
errors.Log(os.MkdirAll(path, 0777))
fname = filepath.Join(path, fname)
}
f, err := os.Create(fname)
if errors.Log(err) != nil {
return err
}
opts := Settings.PageSettings(ct, ct.current.Page)
// the texts are laid out in the pages without the frames of their
// elements, so they need the tags (for the styles of headings)
// and ids (for links) of them
htmlcore.TagTexts(ct.pageFrame())
if refs != nil {
paginate.PDF(f, opts.PDF, ct.pageFrame(), refs)
} else {
paginate.PDF(f, opts.PDF, ct.pageFrame())
}
err = f.Close()
ct.reloadPage()
core.MessageSnackbar(ct, "PDF saved to: "+fname)
af := errors.Log1(filepath.Abs(fname))
core.TheApp.OpenURL(fsx.FileURL(af))
return err
}
// PageRefs returns a core.Frame with the contents of the references cited
// on the given page. if References is nil, or error, result will be nil.
func (ct *Content) PageRefs(page *bcontent.Page) *core.Frame {
if ct.References == nil {
return nil
}
sty := csl.APA // todo: settings
var b bytes.Buffer
_, err := csl.GenerateMarkdown(&b, ct.Source, "## References", ct.References, sty, page.Filename)
if errors.Log(err) != nil {
return nil
}
// os.WriteFile("tmp-refs.md", b.Bytes(), 0666)
fr := core.NewFrame()
fr.Styler(func(s *styles.Style) {
s.Direction = styles.Column
})
err = htmlcore.ReadMD(ct.Context, fr, b.Bytes())
if errors.Log(err) != nil {
return nil
}
fr.StyleTree()
fr.SetScene(ct.Scene)
return fr
}
// LoadEachPage is a helper function to iterate through loading each page,
// which is used for updating the math cache.
func (ct *Content) LoadEachPage(after func()) error {
// The render sends on the channel without blocking (it has the
// render lock), and a send for an earlier render is dropped before
// each page is opened.
ct.renderChan = make(chan struct{}, 1)
go func() {
for _, pg := range ct.pages {
fmt.Println("\n#### page:", pg.URL)
ct.AsyncLock()
select {
case <-ct.renderChan:
default:
}
ct.OpenEvent(pg.URL, nil)
ct.AsyncUnlock()
<-ct.renderChan
fmt.Println("rendered:", pg.URL)
}
if after != nil {
after()
}
}()
return nil
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package contentcode compiles the runnable Go and Goal code blocks (```Go,
// ```Goal) of the markdown files of a content app into the app: it writes a
// Go file to the app's package that defines a function for each code block
// and registers it in [cogentcore.org/core/content.CompiledCode] (Goal:
// [cogentcore.org/core/content.CompiledGoal]). Content then runs those code
// blocks directly, without an interpreter such as mvm: natively as Go, and
// in `core build js` apps as the GoScript output of the same code.
//
// Code blocks are written as the interpreter (mvmcore) runs them: a list of
// statements that use the parent widget b and the packages of the mvmcore
// symbols (core, styles, ...) without importing them, or a program with a
// main function.
// Code blocks that do not type check are left out (and listed in the output
// file), and their errors are printed at their lines in the markdown files;
// an unused variable is used with `_ = x` instead, since mvm allows it.
//
// Goal code blocks (```Goal) are compiled per page, in order, so that a
// block sees the variables of the blocks before it on its page, as in the
// Goal interpreter (see goal.go and [cogentcore.org/core/content.GoalPage]).
// That needs Cogent Lab's Goal transpiler, so the app's module must require
// cogentcore.org/lab (otherwise, the Goal code blocks are not compiled, with
// a message that says so); Goal code can use the packages of Lab's mvmlab
// symbols without importing them.
//
// The core tool runs [Generate] for every content app (see [App]) in
// `core build`, `core run`, `core install`, `core pack` and `core generate`.
// The contentcode command (cogentcore.org/core/content/cmd/contentcode) runs
// it from a go:generate directive. The output records a hash of what it is
// generated from (the code blocks, the options and the go.mod file of the
// app), and [Generate] does nothing if that has not changed.
package contentcode
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"errors"
"flag"
"fmt"
"go/ast"
"go/build"
"go/format"
"go/parser"
"go/printer"
"go/scanner"
"go/token"
"io/fs"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"slices"
"sort"
"strconv"
"strings"
"unicode"
)
// defaultImports are the packages that code blocks can use without importing
// them: those of mvmcore/basesymbols and mvmcore/coresymbols.
var defaultImports = []string{
"cogentcore.org/core/base/errors",
"cogentcore.org/core/base/fileinfo",
"cogentcore.org/core/base/fsx",
"cogentcore.org/core/base/iox/imagex",
"cogentcore.org/core/base/labels",
"cogentcore.org/core/base/num",
"cogentcore.org/core/base/reflectx",
"cogentcore.org/core/base/strcase",
"cogentcore.org/core/colors",
"cogentcore.org/core/colors/gradient",
"cogentcore.org/core/content",
"cogentcore.org/core/core",
"cogentcore.org/core/cursors",
"cogentcore.org/core/events",
"cogentcore.org/core/filetree",
"cogentcore.org/core/htmlcore",
"cogentcore.org/core/icons",
"cogentcore.org/core/keymap",
"cogentcore.org/core/math32",
"cogentcore.org/core/paint",
"cogentcore.org/core/styles/abilities",
"cogentcore.org/core/styles/states",
"cogentcore.org/core/styles",
"cogentcore.org/core/styles/units",
"cogentcore.org/core/text/lines",
"cogentcore.org/core/text/rich",
"cogentcore.org/core/text/text",
"cogentcore.org/core/text/textcore",
"cogentcore.org/core/tree",
"fmt",
"image/color",
"image/draw",
"image",
"io/fs",
"log/slog",
"math",
"path/filepath",
"reflect",
"strconv",
"strings",
"time",
}
// generated names; the prefix keeps them apart from the app's names.
const (
prefix = "contentCode"
parentVar = prefix + "Parent"
outVar = prefix + "Out"
)
// version is the version of the generated code. Changing it changes the hash
// of all output, so that it is generated again.
const version = "2"
// header is the first line of the output file.
const header = "// Code generated by \"contentcode\"; DO NOT EDIT.\n"
// hashPrefix starts the line of the output file that records its hash.
const hashPrefix = "// contentcode hash: "
// contentImport is the import path of the content package.
const contentImport = "cogentcore.org/core/content"
// Config is the configuration of [Generate].
type Config struct {
// Dir is the directory of the package (default: the current directory).
// Content and Output are relative to it.
Dir string
// Content is the directory of the markdown content.
Content string
// Output is the output Go file, in the package.
Output string
// Tags are build tags for type checking.
Tags string
// Imports are extra packages that code can use: path or name=path.
Imports []string
// GoalRecord is whether Goal math mode records its variables in
// tensorfs and lists tensorfs to the output, as the Goal interpreter
// of Lab's mvmlab does. It is true by default; set it to false for
// sites whose interpreter does not (such as plain goal).
GoalRecord bool
// Interpret are the pages whose code blocks are not compiled into the
// app, so that they run in the interpreter, as markdown file paths in
// the content directory, with or without the .md extension, which can
// have the wildcards of [path.Match], such as neuron-*. On the web, an
// interpreter that is a deferred function is then loaded with the
// packages that the code uses only when such a page is shown, which
// keeps code that few pages use out of the startup of the app.
Interpret []string
// Force generates the output even if it is up to date.
Force bool
}
// interpreted returns whether the code blocks of the given markdown file,
// relative to the package directory with slashes, run in the interpreter
// (see [Config.Interpret]).
func (c *Config) interpreted(file string) bool {
rel := strings.TrimPrefix(file, path.Clean(filepath.ToSlash(c.Content))+"/")
for _, pat := range c.Interpret {
pat = strings.TrimPrefix(pat, "/")
for _, name := range []string{rel, strings.TrimSuffix(rel, ".md")} {
if ok, _ := path.Match(pat, name); ok {
return true
}
}
}
return false
}
type importFlags []string
func (f *importFlags) String() string { return strings.Join(*f, ",") }
func (f *importFlags) Set(s string) error { *f = append(*f, s); return nil }
// ParseArgs returns the configuration given by the arguments of the
// contentcode command.
func ParseArgs(name string, args []string) (*Config, error) {
c := &Config{}
fs := flag.NewFlagSet(name, flag.ContinueOnError)
fs.StringVar(&c.Content, "content", "content", "directory of the markdown content")
fs.StringVar(&c.Output, "o", "contentcode_gen.go", "output Go file, in the current package")
fs.StringVar(&c.Tags, "tags", "", "build tags for type checking")
fs.Var((*importFlags)(&c.Imports), "import", "extra package that code can use: path or name=path (repeatable)")
fs.BoolVar(&c.GoalRecord, "goal-record", true, "record the variables of Goal math mode in tensorfs and list tensorfs to the output, as Lab's mvmlab interpreter does")
fs.Var((*importFlags)(&c.Interpret), "interpret", "page whose code blocks run in the interpreter instead of being compiled: a markdown file in the content directory, with or without .md, which can have wildcards (repeatable)")
fs.BoolVar(&c.Force, "force", false, "generate even if the output is up to date")
if err := fs.Parse(args); err != nil {
return nil, err
}
if fs.NArg() > 0 {
return nil, fmt.Errorf("unexpected arguments: %v", fs.Args())
}
return c, nil
}
// App returns the configuration for the package in dir if it is a content
// app: a main package that imports the content package and embeds (or has)
// a directory with markdown files. If a go:generate directive of the
// package runs contentcode, App uses its arguments. It returns nil if the
// package is not a content app.
func App(dir string) (*Config, error) {
// a main package that imports content
pkg, err := build.ImportDir(dir, 0)
if err != nil {
if _, ok := errors.AsType[*build.NoGoError](err); ok {
return nil, nil
}
return nil, err
}
if pkg.Name != "main" || !slices.Contains(pkg.Imports, contentImport) {
return nil, nil
}
// a go:generate directive gives the arguments
c, err := generateDirective(dir, pkg.GoFiles)
if err != nil || c != nil {
return c, err
}
c, _ = ParseArgs("contentcode", nil)
c.Dir = dir
// the embedded directory of markdown files, or content
c.Content = ""
for _, p := range pkg.EmbedPatterns {
p = strings.TrimPrefix(p, "all:")
if hasMarkdown(filepath.Join(dir, p)) {
c.Content = p
break
}
}
if c.Content == "" && hasMarkdown(filepath.Join(dir, "content")) {
c.Content = "content"
}
if c.Content == "" {
return nil, nil
}
return c, nil
}
// generateDirective returns the configuration given by a go:generate
// directive that runs contentcode in one of the given files of dir.
func generateDirective(dir string, files []string) (*Config, error) {
for _, f := range files {
b, err := os.ReadFile(filepath.Join(dir, f))
if err != nil {
return nil, err
}
for l := range strings.SplitSeq(string(b), "\n") {
args, ok := strings.CutPrefix(strings.TrimSpace(l), "//go:generate ")
if !ok {
continue
}
fields := strings.Fields(args)
i := slices.IndexFunc(fields, func(s string) bool {
return s == "contentcode" || strings.HasSuffix(s, "/contentcode")
})
if i < 0 {
continue
}
c, err := ParseArgs("contentcode", fields[i+1:])
if err != nil {
return nil, fmt.Errorf("%s: go:generate contentcode: %w", f, err)
}
c.Dir = dir
return c, nil
}
}
return nil, nil
}
// hasMarkdown returns whether dir is a directory that has markdown files.
func hasMarkdown(dir string) bool {
found := false
filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return fs.SkipAll
}
if !d.IsDir() && filepath.Ext(path) == ".md" {
found = true
return fs.SkipAll
}
return nil
})
return found
}
// Generate writes the output file of the code blocks of the content, unless
// it is up to date. It returns whether it wrote the file. If the content has
// no code blocks, it removes a previously generated output file instead.
func Generate(c *Config) (bool, error) {
dir := c.Dir
if dir == "" {
dir = "."
}
output := filepath.Join(dir, c.Output)
importPaths := map[string]string{} // package name -> path
for _, p := range defaultImports {
importPaths[pathName(p)] = p
}
for _, e := range c.Imports {
name, path, ok := strings.Cut(e, "=")
if !ok {
name, path = pathName(e), e
}
importPaths[name] = path
}
goalPaths := map[string]string{} // for Goal code
for _, p := range goalImports {
goalPaths[pathName(p)] = p
}
for _, p := range defaultImports {
goalPaths[pathName(p)] = p
}
for _, e := range c.Imports {
name, path, ok := strings.Cut(e, "=")
if !ok {
name, path = pathName(e), e
}
goalPaths[name] = path
}
// the blocks and the hash of what the output is generated from
blocks, err := readBlocks(dir, c.Content)
if err != nil {
return false, err
}
pages, err := readGoalPages(dir, c.Content)
if err != nil {
return false, err
}
blocks = slices.DeleteFunc(blocks, func(b *block) bool { return c.interpreted(b.file) })
pages = slices.DeleteFunc(pages, func(pg *goalPage) bool { return c.interpreted(pg.file) })
old, _ := os.ReadFile(output)
if len(blocks) == 0 && len(pages) == 0 {
if bytes.HasPrefix(old, []byte(header)) {
return true, os.Remove(output)
}
return false, nil
}
hash, err := c.hash(dir, blocks, pages)
if err != nil {
return false, err
}
if !c.Force && bytes.Contains(old, []byte(hashPrefix+hash+"\n")) {
return false, nil
}
pkgName, err := packageName(dir, c.Tags)
if err != nil {
return false, err
}
for i, b := range blocks {
b.name = fmt.Sprintf("%s%d", prefix, i)
if err := b.generate(importPaths); err != nil {
b.err = err.Error()
}
}
if err := transpileGoal(dir, pages, c.Tags, c.GoalRecord); err != nil {
if !errors.Is(err, errNoLab) {
return false, err
}
// the Go code blocks are still compiled
fmt.Fprintf(os.Stderr, "%s:%d: Goal code blocks are not compiled into the app, since compiling Goal code needs Cogent Lab, which the module of the app does not require; to compile them, run: go get cogentcore.org/lab (until then, they run in the Goal interpreter, if the app has one)\n", displayPath(dir, pages[0].file), pages[0].blocks[0].line)
pages = nil
}
for i, pg := range pages {
pg.name = fmt.Sprintf("%s%d", goalPrefix, i)
pg.prepare(goalPaths, c.GoalRecord)
}
src, err := typeCheckBlocks(dir, output, pkgName, hash, c.Tags, blocks, pages, goalPaths, c.GoalRecord)
if err != nil {
// keep the previous output, not a partial one
if old != nil {
os.WriteFile(output, old, 0666)
} else {
os.Remove(output)
}
return false, err
}
if err := os.WriteFile(output, src, 0666); err != nil {
return false, err
}
n := 0
for _, b := range blocks {
if b.err == "" {
n++
continue
}
// the errors of the block, at their place in the markdown file
file := displayPath(dir, b.file)
if len(b.errs) == 0 {
fmt.Fprintf(os.Stderr, "%s:%d: %s\n", file, b.line, b.err)
}
for _, e := range b.errs {
if e.col > 0 {
fmt.Fprintf(os.Stderr, "%s:%d:%d: %s\n", file, e.line, e.col, e.msg)
} else {
fmt.Fprintf(os.Stderr, "%s:%d: %s\n", file, e.line, e.msg)
}
}
}
if n < len(blocks) {
fmt.Fprintf(os.Stderr, "contentcode: compiled %d of %d code blocks into %s; the others, with the errors above, run in the interpreter instead, if the app has one\n", n, len(blocks), output)
} else if len(blocks) > 0 {
fmt.Fprintf(os.Stderr, "contentcode: compiled %d of %d code blocks into %s\n", n, len(blocks), output)
}
if len(pages) > 0 {
nb, ng := 0, 0
for _, pg := range pages {
ng += len(pg.blocks)
nb += pg.n
if pg.n < len(pg.blocks) {
b := pg.blocks[pg.n]
fmt.Fprintf(os.Stderr, "%s:%d: %s\ncontentcode: this Goal code block and the %d after it on its page are not compiled into the app; they run in the Goal interpreter instead, if the app has one\n", displayPath(dir, pg.file), b.line, b.err, len(pg.blocks)-pg.n-1)
}
}
fmt.Fprintf(os.Stderr, "contentcode: compiled %d of %d Goal code blocks (%d pages) into %s\n", nb, ng, len(pages), output)
}
return true, nil
}
// hash returns the hash of what the output is generated from: the version,
// the options, the go.mod file of the package and the code blocks.
func (c *Config) hash(dir string, blocks []*block, pages []*goalPage) (string, error) {
h := sha256.New()
fmt.Fprintf(h, "version %s\ntags %s\nimports %q\n", version, c.Tags, c.Imports)
if len(pages) > 0 {
fmt.Fprintf(h, "goal-record %v\n", c.GoalRecord)
}
gomod, err := goModFile(dir)
if err != nil {
return "", err
}
if gomod != "" {
b, err := os.ReadFile(gomod)
if err != nil {
return "", err
}
h.Write(b)
}
for _, b := range blocks {
fmt.Fprintf(h, "\n%s #%d %d\n%s", b.file, b.index, len(b.src), b.src)
}
for _, pg := range pages {
for _, b := range pg.blocks {
fmt.Fprintf(h, "\nGoal %s #%d %d\n%s", pg.file, b.index, len(b.src), b.src)
}
}
return hex.EncodeToString(h.Sum(nil))[:32], nil
}
// goModFile returns the go.mod file of the module that contains dir, or "".
func goModFile(dir string) (string, error) {
d, err := filepath.Abs(dir)
if err != nil {
return "", err
}
for {
f := filepath.Join(d, "go.mod")
if _, err := os.Stat(f); err == nil {
return f, nil
}
parent := filepath.Dir(d)
if parent == d {
return "", nil
}
d = parent
}
}
// typeCheckBlocks type checks the output with the code of the blocks and fixes
// or leaves out blocks until it type checks. It returns the output.
func typeCheckBlocks(dir, output, pkgName, hash, tags string, blocks []*block, pages []*goalPage, goalPaths map[string]string, goalRecord bool) ([]byte, error) {
var src []byte
for iter := 0; ; iter++ {
src = assemble(pkgName, hash, blocks, pages)
srcLines := strings.Split(string(src), "\n")
if iter == 20 {
return nil, fmt.Errorf("type checking did not converge")
}
errs, err := typeCheck(dir, output, src, tags)
if err != nil {
return nil, err
}
if len(errs) == 0 {
break
}
changed := false
failed := map[*block]bool{} // the blocks that fail in this iteration
unused := map[*block]map[int][]string{}
goalUnused := map[*goalPage]map[int][]string{}
goalErr := map[*goalPage]int{} // first block with an error
for _, e := range errs {
if pg := goalPageAt(pages, e.line); pg != nil {
if name, ok := strings.CutPrefix(e.msg, "declared and not used: "); ok {
if goalUnused[pg] == nil {
goalUnused[pg] = map[int][]string{}
}
goalUnused[pg][e.line-pg.start] = append(goalUnused[pg][e.line-pg.start], name)
continue
}
i := pg.blockAtLine(e.line)
if j, ok := goalErr[pg]; !ok || i < j {
goalErr[pg] = i
if pg.blocks[i].err == "" {
pg.blocks[i].err = e.msg
}
}
continue
}
b := blockAt(blocks, e.line)
if b == nil {
return nil, fmt.Errorf("error outside of the code blocks: %s", e)
}
if name, ok := strings.CutPrefix(e.msg, "declared and not used: "); ok {
if unused[b] == nil {
unused[b] = map[int][]string{}
}
unused[b][e.line-b.start] = append(unused[b][e.line-b.start], name)
continue
}
if b.err == "" {
b.err = e.msg
failed[b] = true
changed = true
}
if failed[b] {
text := ""
if e.line >= 1 && e.line <= len(srcLines) {
text = srcLines[e.line-1]
}
line, col := b.markdownPos(e.line, e.col, text)
b.errs = append(b.errs, blockError{line: line, col: col, msg: e.msg})
}
}
for b, u := range unused {
if b.err != "" || failed[b] {
continue
}
if err := b.useUnused(u); err != nil {
b.err = err.Error()
}
changed = true
}
for pg, i := range goalErr {
pg.truncate(i, pg.blocks[i].err, goalPaths, goalRecord)
changed = true
}
for pg, u := range goalUnused {
if _, ok := goalErr[pg]; ok {
continue
}
if err := pg.useUnused(u); err != nil {
pg.truncate(0, err.Error(), goalPaths, goalRecord)
}
changed = true
}
if !changed {
return nil, fmt.Errorf("could not fix the type errors: %v", errs)
}
}
if f, err := format.Source(src); err == nil {
src = f
}
return src, nil
}
// block is one code block, and the Go code generated for it.
type block struct {
file string // markdown file, relative to the package directory
index int // number of the code block in the file, from 1
line int // line of the code in the file
src string // source of the code block
key string // CodeKey of src
name string // name of the generated function
code string // generated Go declarations
pkgs map[string]bool
indent int // indentation of the code block in the file
err string // why the block was left out
errs []blockError // the errors that left it out, in the file
start int // first line of code in the output file
end int // last line of code in the output file
}
// blockError is an error of a code block at a line (and column, if known)
// of its markdown file.
type blockError struct {
line, col int
msg string
}
// stmtLine is the line of the generated code of a block that is a list of
// statements (from 0) at which its source code starts (see [block.generate]).
const stmtLine = 4
// markdownPos returns the line and column (0 if not known) in the markdown
// file of the given line and column of the output file, whose text is given.
// It finds the line of the code block whose text is that of the output line,
// apart from whitespace and the changes made in [block.generate], which is
// the closest to the line it would be at if the generated code had all of the
// lines of the code block in order, as it does for a list of statements apart
// from consecutive empty lines. It returns the first line of the code block
// if no line matches.
func (b *block) markdownPos(line, col int, text string) (int, int) {
lines := strings.Split(b.src, "\n")
hint := line - b.start - 1 - stmtLine
norm := func(s string) string {
s = strings.ReplaceAll(s, b.name+"_", "")
s = strings.ReplaceAll(s, "("+outVar+", ", "(")
s = strings.ReplaceAll(s, "("+outVar+")", "()")
s = strings.ReplaceAll(s, "fmt.Fprint", "fmt.Print")
s = strings.ReplaceAll(s, parentVar, "b")
return strings.Join(strings.Fields(s), "")
}
want := norm(text)
best := -1
for i, l := range lines {
if want == "" || norm(l) != want {
continue
}
if best < 0 || abs(i-hint) < abs(best-hint) {
best = i
}
}
if best < 0 {
return b.line, 0
}
// the column is known if the line is the same apart from indentation
src := lines[best]
tt, st := strings.TrimLeft(text, " \t"), strings.TrimLeft(src, " \t")
if tt != st || col <= len(text)-len(tt) {
return b.line + best, 0
}
return b.line + best, col - (len(text) - len(tt)) + (len(src) - len(st)) + b.indent
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
// displayPath returns the path of the given file, relative to dir, to show
// in messages: relative to the current directory if it is in it.
func displayPath(dir, file string) string {
p := filepath.Join(dir, filepath.FromSlash(file))
wd, err := os.Getwd()
if err != nil {
return p
}
ap, err := filepath.Abs(p)
if err != nil {
return p
}
if rel, err := filepath.Rel(wd, ap); err == nil && !strings.HasPrefix(rel, "..") {
return rel
}
return ap
}
// pathName returns the package name of an import path (its last element).
func pathName(path string) string {
return path[strings.LastIndex(path, "/")+1:]
}
// packageName returns the name of the package in dir.
func packageName(dir, tags string) (string, error) {
args := []string{"list", "-f", "{{.Name}}"}
if tags != "" {
args = append(args, "-tags="+tags)
}
cmd := exec.Command("go", append(args, ".")...)
cmd.Dir = dir
out, err := cmd.Output()
if err != nil {
return "", fmt.Errorf("go list: %w", err)
}
return strings.TrimSpace(string(out)), nil
}
var fenceStart = regexp.MustCompile("^(\\s*)```Go\\s*$")
// readBlocks returns the ```Go code blocks of the markdown files in the
// content directory of the package in dir, once each (by key), in file order.
func readBlocks(dir, content string) ([]*block, error) {
var blocks []*block
seen := map[string]bool{}
err := walkMarkdown(dir, content, func(rel string, lines []string) {
forFences(lines, fenceStart, func(index, line, indent int, src string) {
key := codeKey(src)
if !seen[key] {
seen[key] = true
blocks = append(blocks, &block{file: rel, index: index, line: line, indent: indent, src: src, key: key})
}
})
})
return blocks, err
}
// walkMarkdown calls f with the path (relative to dir, with slashes) and
// the lines of each markdown file in the content directory of dir.
func walkMarkdown(dir, content string, f func(rel string, lines []string)) error {
return filepath.WalkDir(filepath.Join(dir, content), func(path string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() || filepath.Ext(path) != ".md" {
return err
}
b, err := os.ReadFile(path)
if err != nil {
return err
}
rel, err := filepath.Rel(dir, path)
if err != nil {
return err
}
f(filepath.ToSlash(rel), strings.Split(string(b), "\n"))
return nil
})
}
// forFences calls f with the number (from 1, counting empty ones), line
// (from 1), indentation (in bytes) and source of each code block of the
// given lines that starts with a line matching start (whose first group is
// the indentation), in order, except empty ones.
func forFences(lines []string, start *regexp.Regexp, f func(index, line, indent int, src string)) {
index := 0
for i := 0; i < len(lines); i++ {
m := start.FindStringSubmatch(lines[i])
if m == nil {
continue
}
index++
indent := m[1]
first := i + 1
j := first
for ; j < len(lines); j++ {
if strings.HasPrefix(strings.TrimSpace(lines[j]), "```") {
break
}
}
code := make([]string, 0, j-first)
for _, l := range lines[first:j] {
code = append(code, strings.TrimPrefix(l, indent))
}
src := strings.Join(code, "\n") + "\n"
if strings.TrimSpace(src) != "" {
f(index, first+1, len(indent), src)
}
i = j
}
}
// codeKey is [cogentcore.org/core/content.CodeKey].
func codeKey(src string) string {
s := strings.Map(func(r rune) rune {
if unicode.IsSpace(r) {
return -1
}
return r
}, src)
h := uint32(2166136261) // FNV-1a
for i := 0; i < len(s); i++ {
h ^= uint32(s[i])
h *= 16777619
}
return fmt.Sprintf("%08x-%d", h, len(s))
}
// generate makes the Go declarations of the block.
func (b *block) generate(importPaths map[string]string) error {
b.pkgs = map[string]bool{}
// a program has a main function (like mvmcore, which runs it); other code
// is a list of statements, with the parent widget as b
text := b.src
if !strings.HasPrefix(strings.TrimSpace(text), "package ") {
text = "package main\n\n" + text
}
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, "block.go", text, parser.ParseComments)
program := err == nil && file.Scope.Lookup("main") != nil
if !program {
// b is in an outer block, so that the code can declare its own b
// (the source starts at line stmtLine of the function)
text = "package main\n\nfunc " + b.name + "(" + parentVar + " *core.Frame, " + outVar + " io.Writer) {\nb := " + parentVar + "\n_ = b\n{\n" + b.src + "\n}\n}\n"
fset = token.NewFileSet()
file, err = parser.ParseFile(fset, "block.go", text, parser.ParseComments)
if err != nil {
var el scanner.ErrorList
if errors.As(err, &el) && len(el) > 0 {
for _, e := range el {
// an error after the end of the code is at its last line
i, col := e.Pos.Line-3-stmtLine, e.Pos.Column+b.indent
if last := strings.Count(b.src, "\n") - 1; i > last {
i, col = max(last, 0), 0
}
b.errs = append(b.errs, blockError{line: b.line + i, col: col, msg: e.Msg})
}
return errors.New(el[0].Msg)
}
return err
}
}
local := map[string]string{}
for _, im := range file.Imports {
p, _ := strconv.Unquote(im.Path.Value)
name := pathName(p)
if im.Name != nil {
name = im.Name.Name
}
local[name] = p
}
file.Imports = nil
file.Decls = slices.DeleteFunc(file.Decls, func(d ast.Decl) bool {
g, ok := d.(*ast.GenDecl)
return ok && g.Tok == token.IMPORT
})
// identifiers that are not references: selectors and struct literal keys
notRef := map[*ast.Ident]bool{}
ast.Inspect(file, func(n ast.Node) bool {
switch n := n.(type) {
case *ast.SelectorExpr:
notRef[n.Sel] = true
case *ast.KeyValueExpr:
if id, ok := n.Key.(*ast.Ident); ok && id.Obj == nil {
notRef[id] = true
}
}
return true
})
top := map[*ast.Object]bool{}
if program {
for _, obj := range file.Scope.Objects {
top[obj] = true
}
}
// rewrite: package uses, fmt printing, top-level names, the parent b
ast.Inspect(file, func(n ast.Node) bool {
switch n := n.(type) {
case *ast.CallExpr:
if sel, ok := n.Fun.(*ast.SelectorExpr); ok {
if x, ok := sel.X.(*ast.Ident); ok && x.Obj == nil && x.Name == "fmt" {
switch sel.Sel.Name {
case "Print", "Println", "Printf":
sel.Sel.Name = "Fp" + sel.Sel.Name[1:]
n.Args = append([]ast.Expr{ast.NewIdent(outVar)}, n.Args...)
b.pkgs["io"] = true
}
}
}
case *ast.SelectorExpr:
if x, ok := n.X.(*ast.Ident); ok && x.Obj == nil {
if p, ok := local[x.Name]; ok {
b.pkgs[p] = true
} else if p, ok := importPaths[x.Name]; ok {
b.pkgs[p] = true
}
}
case *ast.Ident:
if notRef[n] {
break
}
if n.Obj != nil && top[n.Obj] {
n.Name = b.name + "_" + n.Name
} else if program && n.Obj == nil && n.Name == "b" {
n.Name = parentVar
}
}
return true
})
if !program {
b.pkgs["cogentcore.org/core/core"] = true
b.pkgs["io"] = true
}
var buf bytes.Buffer
for _, d := range file.Decls {
if err := printer.Fprint(&buf, fset, &printer.CommentedNode{Node: d, Comments: file.Comments}); err != nil {
return err
}
buf.WriteString("\n\n")
}
if program {
fmt.Fprintf(&buf, "func %s(b *core.Frame, out io.Writer) {\n\t%s, %s = b, out\n\t%s_main()\n}\n\n", b.name, parentVar, outVar, b.name)
b.pkgs["cogentcore.org/core/core"] = true
b.pkgs["io"] = true
}
code, err := format.Source(buf.Bytes())
if err != nil {
return err
}
b.code = string(code)
return nil
}
// useUnused inserts `_ = x` after the statements that declare the unused
// variables x of the block, given by the line of the error (relative to the
// start of the block's code: 1 is its first line).
func (b *block) useUnused(unused map[int][]string) error {
code, err := useUnusedIn(b.code, unused)
if err != nil {
return err
}
b.code = code
return nil
}
// useUnusedIn returns the given Go declarations with `_ = x` inserted
// after the statements that declare the unused variables x, given by the
// line of the error (1 is the first line of code).
func useUnusedIn(code string, unused map[int][]string) (string, error) {
text := "package main\n" + code
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, "block.go", text, parser.ParseComments)
if err != nil {
return "", err
}
ast.Inspect(file, func(n ast.Node) bool {
blk, ok := n.(*ast.BlockStmt)
if !ok {
return true
}
var list []ast.Stmt
for _, st := range blk.List {
list = append(list, st)
rel := fset.Position(st.Pos()).Line - 1
for _, name := range unused[rel] {
list = append(list, &ast.AssignStmt{Lhs: []ast.Expr{ast.NewIdent("_")}, Tok: token.ASSIGN, Rhs: []ast.Expr{ast.NewIdent(name)}})
}
}
blk.List = list
return true
})
var buf bytes.Buffer
for _, d := range file.Decls {
if err := printer.Fprint(&buf, fset, &printer.CommentedNode{Node: d, Comments: file.Comments}); err != nil {
return "", err
}
buf.WriteString("\n\n")
}
out, err := format.Source(buf.Bytes())
if err != nil {
return "", err
}
return string(out), nil
}
// assemble returns the output file of the blocks that are not left out,
// and sets their line ranges. The comments name a block by its file and its
// number in the file, not its line, so that the output does not change (and
// is not generated again) when only the text around the code changes.
func assemble(pkgName, hash string, blocks []*block, pages []*goalPage) []byte {
pkgs := map[string]bool{"cogentcore.org/core/content": true, "cogentcore.org/core/core": true, "io": true}
for _, b := range blocks {
if b.err != "" {
continue
}
for p := range b.pkgs {
pkgs[p] = true
}
}
for _, pg := range pages {
if pg.n == 0 {
continue
}
for p := range pg.pkgs {
pkgs[p] = true
}
}
paths := make([]string, 0, len(pkgs))
for p := range pkgs {
paths = append(paths, p)
}
sort.Strings(paths)
var buf bytes.Buffer
buf.WriteString(header)
buf.WriteString(hashPrefix)
buf.WriteString(hash)
buf.WriteString("\n\n")
fmt.Fprintf(&buf, "package %s\n\nimport (\n", pkgName)
for _, p := range paths {
fmt.Fprintf(&buf, "\t%q\n", p)
}
buf.WriteString(")\n\n")
fmt.Fprintf(&buf, "// %s and %s are the parent widget (b) and output of the\n// code block programs that are running.\nvar (\n\t%s *core.Frame\n\t%s io.Writer\n)\n\n", parentVar, outVar, parentVar, outVar)
buf.WriteString("// The code blocks are named by their markdown file and their number in it\n// (#n is the nth code block of its language in the file).\n")
// an init function, not a blank variable: GoScript runs the var
// initializers of a file of package main only if the main file imports it
fmt.Fprintf(&buf, "func init() {\n\tcontent.AddCompiledCode(map[string]content.CodeFunc{\n")
for _, b := range blocks {
if b.err == "" {
fmt.Fprintf(&buf, "\t\t%q: %s, // %s #%d\n", b.key, b.name, b.file, b.index)
}
}
buf.WriteString("\t})\n")
if slices.ContainsFunc(pages, func(pg *goalPage) bool { return pg.n > 0 }) {
buf.WriteString("\tcontent.AddCompiledGoal(map[string]*content.GoalPage{\n")
for _, pg := range pages {
if pg.n == 0 {
continue
}
fmt.Fprintf(&buf, "\t\t%q: {Start: %s, Keys: []string{", pg.key, pg.name)
for i, b := range pg.blocks[:pg.n] {
if i > 0 {
buf.WriteString(", ")
}
fmt.Fprintf(&buf, "%q", b.key)
}
buf.WriteString("}},\n")
}
buf.WriteString("\t})\n")
}
buf.WriteString("}\n\n")
line := bytes.Count(buf.Bytes(), []byte("\n")) + 1
for _, b := range blocks {
b.start, b.end = 0, 0
if b.err != "" {
continue
}
b.start = line
fmt.Fprintf(&buf, "// %s #%d\n", b.file, b.index)
buf.WriteString(b.code)
buf.WriteString("\n")
line += 1 + strings.Count(b.code, "\n") + 1
b.end = line - 1
}
for _, pg := range pages {
pg.start, pg.end = 0, 0
if pg.n == 0 {
continue
}
pg.start = line
fmt.Fprintf(&buf, "// %s\n", pg.file)
buf.WriteString(pg.code)
buf.WriteString("\n")
line += 1 + strings.Count(pg.code, "\n") + 1
pg.end = line - 1
}
var left []string
for _, pg := range pages {
if pg.n < len(pg.blocks) {
b := pg.blocks[pg.n]
left = append(left, fmt.Sprintf("// %s #%d: Goal code from here on (%d blocks): %s", pg.file, b.index, len(pg.blocks)-pg.n, strings.ReplaceAll(b.err, "\n", " ")))
}
}
for _, b := range blocks {
if b.err != "" {
left = append(left, fmt.Sprintf("// %s #%d: %s", b.file, b.index, strings.ReplaceAll(b.err, "\n", " ")))
}
}
if len(left) > 0 {
buf.WriteString("// Code blocks left out:\n")
buf.WriteString(strings.Join(left, "\n"))
buf.WriteString("\n")
}
return buf.Bytes()
}
// typeError is a type error at a line of the output file.
type typeError struct {
line, col int
msg string
}
func (e typeError) String() string { return fmt.Sprintf("%d: %s", e.line, e.msg) }
// typeCheck type checks the package in dir with src as the output file,
// by building it with all errors reported.
func typeCheck(dir, output string, src []byte, tags string) ([]typeError, error) {
if err := os.WriteFile(output, src, 0666); err != nil {
return nil, err
}
args := []string{"build", "-o", os.DevNull, "-gcflags=-e"}
if tags != "" {
args = append(args, "-tags="+tags)
}
cmd := exec.Command("go", append(args, ".")...)
cmd.Dir = dir
out, err := cmd.CombinedOutput()
if err == nil {
return nil, nil
}
base := filepath.Base(output)
var errs []typeError
var outside []string // the errors of the other files of the package
for l := range strings.SplitSeq(string(out), "\n") {
l = strings.TrimSpace(l)
if l == "" || strings.HasPrefix(l, "#") {
continue
}
file, rest, _ := strings.Cut(l, ":")
if filepath.Base(file) != base {
if strings.HasSuffix(file, ".go") && !filepath.IsAbs(file) {
l = displayPath(dir, file) + ":" + rest
}
outside = append(outside, l)
continue
}
ls, rest, _ := strings.Cut(rest, ":")
cs, msg, _ := strings.Cut(rest, ": ")
line, _ := strconv.Atoi(ls)
col, _ := strconv.Atoi(cs)
errs = append(errs, typeError{line: line, col: col, msg: msg})
}
if len(outside) > 0 {
return nil, fmt.Errorf("the code blocks can not be compiled, since the package of the app does not compile; fix these errors first:\n%s", strings.Join(outside, "\n"))
}
if len(errs) == 0 {
return nil, fmt.Errorf("go build: %v: %s", err, out)
}
return errs, nil
}
// goalPageAt returns the Goal page at the given line of the output file.
func goalPageAt(pages []*goalPage, line int) *goalPage {
for _, pg := range pages {
if pg.start > 0 && line >= pg.start && line <= pg.end {
return pg
}
}
return nil
}
// blockAt returns the block at the given line of the output file.
func blockAt(blocks []*block, line int) *block {
for _, b := range blocks {
if b.start > 0 && line >= b.start && line <= b.end {
return b
}
}
return nil
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package contentcode
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"go/ast"
"go/format"
"go/parser"
"go/printer"
"go/token"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
)
// Goal code blocks (```Goal) are compiled per page: the Goal interpreter
// runs all the Goal code of a page in one interpreter, so a block sees the
// variables and functions of the blocks before it on the page. Each page
// becomes one Go function that returns its first block as a closure, which
// returns the next block as a closure in its own scope, and so on: the
// code of a block is nested in the code of the blocks before it, so that
// it can use their declarations and declare the same names again (as the
// interpreter allows), while each block still runs when content shows it.
//
// The Goal code is transpiled to Go by Cogent Lab's Goal transpiler
// (cogentcore.org/lab/goal/transpile), with one transpiler state per page,
// as the interpreter does. Core does not depend on Lab, so the transpiler
// runs in a small program that contentcode writes and runs with go run in
// the app's package, whose module must require cogentcore.org/lab.
//
// A page is compiled up to its first block that does not compile; that
// block and the ones after it run in the interpreter, after the compiled
// ones run again there (see content.GoalReplay).
// goalImports are the packages that Goal code can use without importing
// them, in addition to [defaultImports]: those of the symbols of Lab's
// Goal interpreter (mvmlab: tensorsymbols, labsymbols) and the standard
// library packages that code commonly uses.
var goalImports = []string{
"cogentcore.org/lab/goal/goalib",
"cogentcore.org/lab/lab",
"cogentcore.org/lab/matrix",
"cogentcore.org/lab/physics",
"cogentcore.org/lab/physics/builder",
"cogentcore.org/lab/physics/phyxyz",
"cogentcore.org/lab/plot",
"cogentcore.org/lab/plot/plots",
"cogentcore.org/lab/plot/statsplot",
"cogentcore.org/lab/plotcore",
"cogentcore.org/lab/stats/cluster",
"cogentcore.org/lab/stats/convolve",
"cogentcore.org/lab/stats/glm",
"cogentcore.org/lab/stats/histogram",
"cogentcore.org/lab/stats/metric",
"cogentcore.org/lab/stats/stats",
"cogentcore.org/lab/table",
"cogentcore.org/lab/tensor",
"cogentcore.org/lab/tensor/tmath",
"cogentcore.org/lab/tensorcore",
"cogentcore.org/lab/tensorfs",
"cogentcore.org/lab/vector",
"bufio",
"bytes",
"cmp",
"io",
"maps",
"math/cmplx",
"math/rand",
"os",
"regexp",
"slices",
"sort",
"unicode",
"unicode/utf8",
}
const (
goalPrefix = "contentGoal"
goalW = prefix + "W"
tensorfsPath = "cogentcore.org/lab/tensorfs"
)
// goalPage is the Goal code of a page, and the Go code generated for it.
type goalPage struct {
file string // markdown file, relative to the package directory
key string // page file name in the content (Page.Filename)
blocks []*goalBlock // all the Goal code blocks of the page
n int // number of blocks compiled: the first n
name string // name of the generated function
code string // generated Go declarations
pkgs map[string]bool
start int // first line of code in the output file
end int // last line of code in the output file
}
// goalBlock is a Goal code block.
type goalBlock struct {
index int // number of the code block in the file, from 1
line int // line of the code in the file
src string // Goal source
key string // CodeKey of src
gocode string // transpiled Go statements
err string // why it is not compiled
start int // first line of the block's statements in the output file
}
var goalFenceStart = regexp.MustCompile("^(\\s*)```Goal\\s*$")
// readGoalPages returns the pages of the markdown files in the content
// directory of the package in dir that have ```Goal code blocks, with their
// blocks in order.
func readGoalPages(dir, content string) ([]*goalPage, error) {
var pages []*goalPage
err := walkMarkdown(dir, content, func(rel string, lines []string) {
var pg *goalPage
forFences(lines, goalFenceStart, func(index, line, indent int, src string) {
if pg == nil {
key, _ := filepath.Rel(filepath.FromSlash(content), filepath.FromSlash(rel))
pg = &goalPage{file: rel, key: filepath.ToSlash(key)}
pages = append(pages, pg)
}
pg.blocks = append(pg.blocks, &goalBlock{index: index, line: line, src: src, key: codeKey(src)})
})
})
return pages, err
}
// goalTranspiler is the program that transpiles the Goal code of the pages
// with Lab's transpiler: it reads the pages (a JSON array of arrays of
// block sources) from the file of its first argument and writes the
// transpiled code and errors of each block to its second; its third
// argument sets MathRecord.
const goalTranspiler = `// Code generated by "contentcode"; DO NOT EDIT.
package main
import (
"encoding/json"
"errors"
"fmt"
"os"
"cogentcore.org/lab/goal/transpile"
)
type block struct{ Code, Err string }
func main() {
b, err := os.ReadFile(os.Args[1])
if err != nil {
panic(err)
}
var pages [][]string
if err := json.Unmarshal(b, &pages); err != nil {
panic(err)
}
out := make([][]block, len(pages))
for i, srcs := range pages {
st := transpile.NewState()
st.MathRecord = os.Args[3] == "true"
for _, src := range srcs {
st.Errors = nil
st.TranspileCode(src)
code := st.Code()
st.ResetCode()
var bl block
bl.Code = code
if len(st.Errors) > 0 {
bl.Err = errors.Join(st.Errors...).Error()
} else if st.TotalDepth() != 0 {
bl.Err = fmt.Sprintf("unclosed parentheses, braces or brackets (depth %d)", st.TotalDepth())
st.ResetDepth()
}
out[i] = append(out[i], bl)
}
}
b, err = json.Marshal(out)
if err != nil {
panic(err)
}
if err := os.WriteFile(os.Args[2], b, 0666); err != nil {
panic(err)
}
}
`
// errNoLab is the error of [transpileGoal] when the module of the app does
// not provide Lab's Goal transpiler.
var errNoLab = errors.New("the module of the app does not require cogentcore.org/lab, whose Goal transpiler compiles Goal code")
// transpileGoal transpiles the Goal code of the pages to Go
// (goalBlock.gocode), with MathRecord set to record, in the package in
// pkgDir.
func transpileGoal(pkgDir string, pages []*goalPage, tags string, record bool) error {
if len(pages) == 0 {
return nil
}
dir, err := os.MkdirTemp(pkgDir, "_contentcode_goal")
if err != nil {
return err
}
defer os.RemoveAll(dir)
if dir, err = filepath.Abs(dir); err != nil {
return err
}
srcs := make([][]string, len(pages))
for i, pg := range pages {
for _, b := range pg.blocks {
srcs[i] = append(srcs[i], b.src)
}
}
in, err := json.Marshal(srcs)
if err != nil {
return err
}
inFile, outFile := filepath.Join(dir, "in.json"), filepath.Join(dir, "out.json")
if err := os.WriteFile(inFile, in, 0666); err != nil {
return err
}
if err := os.WriteFile(filepath.Join(dir, "main.go"), []byte(goalTranspiler), 0666); err != nil {
return err
}
args := []string{"run"}
if tags != "" {
args = append(args, "-tags="+tags)
}
// The transpiler imports the GUI through tensorsymbols, so -nogui makes
// it use the offscreen driver, which works without a display (as in CI).
args = append(args, "./"+filepath.Base(dir), inFile, outFile, strconv.FormatBool(record), "-nogui")
cmd := exec.Command("go", args...)
cmd.Dir = filepath.Dir(dir)
if out, err := cmd.CombinedOutput(); err != nil {
if strings.Contains(string(out), "cogentcore.org/lab/goal/transpile") {
return fmt.Errorf("%w: %s", errNoLab, out)
}
return fmt.Errorf("running the Goal transpiler: %v: %s", err, out)
}
b, err := os.ReadFile(outFile)
if err != nil {
return err
}
var res [][]struct{ Code, Err string }
if err := json.Unmarshal(b, &res); err != nil {
return err
}
for i, pg := range pages {
for j, bl := range pg.blocks {
bl.gocode, bl.err = res[i][j].Code, res[i][j].Err
}
}
return nil
}
// prepare sets the number of blocks of the page that can be compiled as far
// as transpiling and parsing tell, and generates its code.
func (pg *goalPage) prepare(importPaths map[string]string, record bool) {
pg.n = len(pg.blocks)
for i, b := range pg.blocks {
if b.err == "" {
// each block must be a list of statements
_, err := parser.ParseFile(token.NewFileSet(), "block.go", "package main\nfunc _() {\n"+b.gocode+"\n}\n", parser.SkipObjectResolution)
if err != nil {
b.err = err.Error()
}
}
if b.err != "" {
pg.n = i
break
}
}
if err := pg.generate(importPaths, record); err != nil {
pg.blocks[0].err = err.Error()
pg.n = 0
}
}
// truncate leaves out the blocks of the page from the i-th one on, for the
// given reason, and generates its code again.
func (pg *goalPage) truncate(i int, reason string, importPaths map[string]string, record bool) {
if pg.blocks[i].err == "" {
pg.blocks[i].err = reason
}
pg.n = i
if err := pg.generate(importPaths, record); err != nil {
pg.n = 0
}
}
// generate makes the Go declarations of the first n blocks of the page.
func (pg *goalPage) generate(importPaths map[string]string, record bool) error {
pg.code = ""
pg.pkgs = map[string]bool{}
if pg.n == 0 {
return nil
}
var buf bytes.Buffer
fmt.Fprintf(&buf, "package main\n\nfunc %s() content.GoalBlock {\n", pg.name)
fmt.Fprintf(&buf, "var %s io.Writer\n_ = %s\n", outVar, outVar)
for i, b := range pg.blocks[:pg.n] {
buf.WriteString("return func(" + parentVar + " *core.Frame, " + goalW + " io.Writer) content.GoalBlock {\n")
buf.WriteString(outVar + " = " + goalW + "\n")
if record {
buf.WriteString("tensorfs.ListOutput = " + goalW + "\ndefer func() { tensorfs.ListOutput = nil }()\n")
pg.pkgs[tensorfsPath] = true
}
buf.WriteString("b := " + parentVar + "\n_ = b\n{\n")
fmt.Fprintf(&buf, "// contentcode:block %d %s #%d\n", i, pg.file, b.index)
buf.WriteString(b.gocode)
buf.WriteString("\n")
}
buf.WriteString("return nil\n")
for range pg.n {
buf.WriteString("}\n}\n")
}
buf.WriteString("}\n")
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, "page.go", buf.String(), parser.ParseComments)
if err != nil {
return err
}
ast.Inspect(file, func(n ast.Node) bool {
switch n := n.(type) {
case *ast.CallExpr:
if sel, ok := n.Fun.(*ast.SelectorExpr); ok {
if x, ok := sel.X.(*ast.Ident); ok && x.Obj == nil && x.Name == "fmt" {
switch sel.Sel.Name {
case "Print", "Println", "Printf":
sel.Sel.Name = "Fp" + sel.Sel.Name[1:]
n.Args = append([]ast.Expr{ast.NewIdent(outVar)}, n.Args...)
}
}
}
case *ast.SelectorExpr:
if x, ok := n.X.(*ast.Ident); ok && x.Obj == nil {
if p, ok := importPaths[x.Name]; ok {
pg.pkgs[p] = true
}
}
}
return true
})
pg.pkgs["cogentcore.org/core/content"] = true
pg.pkgs["cogentcore.org/core/core"] = true
pg.pkgs["io"] = true
var out bytes.Buffer
for _, d := range file.Decls {
if err := printer.Fprint(&out, fset, &printer.CommentedNode{Node: d, Comments: file.Comments}); err != nil {
return err
}
out.WriteString("\n\n")
}
code, err := format.Source(out.Bytes())
if err != nil {
return err
}
pg.code = string(code)
return nil
}
// useUnused inserts `_ = x` after the statements that declare the unused
// variables x of the page code, given by the line of the error (relative to
// the start of the page's code: 1 is its first line).
func (pg *goalPage) useUnused(unused map[int][]string) error {
code, err := useUnusedIn(pg.code, unused)
if err != nil {
return err
}
pg.code = code
return nil
}
var goalBlockMarker = regexp.MustCompile(`^\s*// contentcode:block (\d+) `)
// blockAtLine returns the index of the block of the page at the given line
// of the output file (between the page's start and end), using the block
// markers in its code.
func (pg *goalPage) blockAtLine(line int) int {
lines := strings.Split(pg.code, "\n")
idx := 0
for i := 0; i < len(lines) && pg.start+1+i <= line; i++ {
if m := goalBlockMarker.FindStringSubmatch(lines[i]); m != nil {
idx, _ = strconv.Atoi(m[1])
}
}
return idx
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"embed"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/content"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/htmlcore"
"cogentcore.org/core/icons"
"cogentcore.org/core/keymap"
_ "cogentcore.org/core/mvmcore"
"cogentcore.org/core/text/tex/texcache"
"cogentcore.org/core/tree"
)
//go:generate go run ./genmath.go
//go:embed content
var econtent embed.FS
//go:embed mathcache.json.gz
var mathcache embed.FS
func main() {
texcache.OpenFS(mathcache, "mathcache.json.gz")
texcache.SetShapeMath() // only use cached!
// rasterx.UseGlyphCache = false
content.Settings.SiteTitle = "Cogent Content Example"
content.OfflineURL = "https://example.com"
b := core.NewBody("Cogent Content Example")
ct := content.NewContent(b).SetContent(econtent)
ct.Context.AddWikilinkHandler(htmlcore.GoDocWikilink("doc", "cogentcore.org/core"))
b.AddTopBar(func(bar *core.Frame) {
core.NewToolbar(bar).Maker(func(p *tree.Plan) {
ct.MakeToolbar(p)
ct.MakeToolbarPDF(p)
tree.Add(p, func(w *core.Button) {
w.SetText("SaveMath").SetIcon(icons.Search).SetKey(keymap.Find).
SetTooltip("Save cached math rendering")
w.OnClick(func(e events.Event) {
e.SetHandled()
errors.Log(texcache.SaveAs("mathcache.json"))
})
})
})
})
b.RunMainWindow()
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package content
import (
"cogentcore.org/core/core"
"cogentcore.org/core/htmlcore/tohtml"
)
func init() {
core.GenerateHTML = generateHTML
}
// generateHTML is called by the core tool to pre-render Cogent Core apps
// as HTML that can be used as a preview and for SEO purposes. For apps
// with [Content], it returns the JSON [bcontent.Site] data (see [generateSite]).
func generateHTML(w core.Widget) string {
var ct *Content
for n := range w.AsTree().All() {
if c, ok := n.(*Content); ok {
ct = c
break
}
}
if ct == nil {
return tohtml.Generate(w) // basic fallback
}
return generateSite(ct)
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package content
import (
"fmt"
"io"
"maps"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/text/textcore"
)
// GoalBlock is a Goal code block compiled into the app at build time
// (see cogentcore.org/core/content/cmd/contentcode). It runs the code
// with the given parent widget, which the code knows as b, writes what
// the code prints to out, and returns the next Goal code block of its
// page (nil after the last one). The next block runs in the scope of
// this one, so that it sees the variables and functions this one
// declares, as in the Goal interpreter, which runs all the Goal code of a
// page in one interpreter.
type GoalBlock func(b *core.Frame, out io.Writer) GoalBlock
// GoalPage is the Goal code of a page compiled into the app.
type GoalPage struct {
// Keys are the [CodeKey]s of the sources of the Goal code blocks of
// the page, in order.
Keys []string
// Start returns the first code block of a new run of the page,
// in a new scope.
Start func() GoalBlock
}
// CompiledGoal maps the name of a page file (as in [bcontent.Page.Filename])
// to its Goal code compiled into the app. When a page is shown, its Goal
// code blocks run without an interpreter as long as they match the
// compiled blocks, in order.
var CompiledGoal = map[string]*GoalPage{}
// GoalReplay are the sources of the Goal code blocks of the current page
// that ran compiled before the first one that runs in the interpreter
// (because it was edited or not compiled). An interpreter that makes a new
// Goal interpreter for the page (see [BindTextEditor]) first runs these
// sources, without showing anything, and clears them, so that the
// interpreted code sees the variables of the blocks before it, as it
// would if the whole page had run in the interpreter.
var GoalReplay []string
// AddCompiledGoal adds the given compiled pages to [CompiledGoal].
// Generated code calls it.
func AddCompiledGoal(pages map[string]*GoalPage) {
maps.Copy(CompiledGoal, pages)
}
// goalRun is the state of the Goal code of the page being shown.
var goalRun struct {
// page is the compiled Goal code of the page, if any.
page *GoalPage
// next is the next compiled block to run, if any.
next GoalBlock
// ran are the sources of the blocks that ran compiled, in order.
ran []string
// interpreted is set once a block of the page runs in the
// interpreter: all later ones run there too.
interpreted bool
}
// resetGoal starts the Goal code of a new page, from the given file.
func resetGoal(filename string) {
goalRun.page = CompiledGoal[filename]
goalRun.next = nil
if goalRun.page != nil {
goalRun.next = goalRun.page.Start()
}
goalRun.ran = nil
goalRun.interpreted = false
GoalReplay = nil
}
// bindGoal runs the Goal code block of the given editor: compiled, if it
// is the next compiled block of the page, and otherwise (and once it is
// edited) in the interpreter.
func bindGoal(ed *textcore.Editor, parent *core.Frame) {
src := ed.Lines.String()
gr := &goalRun
n := len(gr.ran)
if gr.interpreted || gr.next == nil || n >= len(gr.page.Keys) || gr.page.Keys[n] != CodeKey(src) {
interpretGoal(ed, parent)
return
}
f := gr.next
gr.next = nil
gr.ran = append(gr.ran, src)
interpreted := false
ed.OnChange(func(e events.Event) {
if interpreted {
return
}
if BindTextEditor == nil {
core.ErrorSnackbar(ed, fmt.Errorf("this app has no interpreter to run edited code (only the code compiled into it)"), "Error running Goal code")
return
}
// BindTextEditor runs the code now and on later changes.
interpreted = true
interpretGoal(ed, parent)
})
runCode(ed, parent, func(out io.Writer) { gr.next = f(parent, out) })
}
// interpretGoal runs the Goal code block of the given editor in the
// interpreter of the page, after the blocks that ran compiled.
func interpretGoal(ed *textcore.Editor, parent *core.Frame) {
if BindTextEditor == nil {
errors.Log(fmt.Errorf("content: Goal code block was not compiled into the app and there is no interpreter to run it"))
return
}
gr := &goalRun
if !gr.interpreted {
gr.interpreted = true
gr.next = nil
GoalReplay = gr.ran
}
BindTextEditor(ed, parent, "Goal")
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package content
import (
"fmt"
"io"
"io/fs"
"os"
"path"
"path/filepath"
"strings"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/fsx"
"cogentcore.org/core/base/labels"
"cogentcore.org/core/base/strcase"
"cogentcore.org/core/colors"
"cogentcore.org/core/content/bcontent"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/htmlcore"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/system"
"cogentcore.org/core/text/csl"
"cogentcore.org/core/text/htmltext"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/textcore"
"cogentcore.org/core/tree"
"github.com/yuin/goldmark/v2/ast"
east "github.com/yuin/goldmark/v2/extension/ast"
)
// BindTextEditor is a function set to [cogentcore.org/core/mvmcore.BindTextEditor]
// when importing mvmcore, which provides interactive
// editing functionality for Go code blocks in text editors.
var BindTextEditor func(ed *textcore.Editor, parent *core.Frame, language string)
// handles the id attribute in htmlcore: needed for equation case
func (ct *Content) htmlIDAttributeHandler(ctx *htmlcore.Context, w io.Writer, node ast.Node, entering bool, tag, value string) bool {
if ct.current.Page == nil {
return false
}
lbl := ct.current.Page.SpecialLabel(value)
if lbl == "" {
return false
}
if _, ok := node.FirstChild().(*ast.Image); ok || node.Kind() == east.KindTable { // own label
return false
}
if entering {
cp := "\n<span id=\"" + value + "\""
style := htmlcore.MDGetAttr(node, "style")
if style != "" {
cp += fmt.Sprintf(" style=%q", style)
}
cp += "><b>" + lbl + ":</b>"
title := htmlcore.MDGetAttr(node, "title")
if title != "" {
cp += " " + title
}
cp += "</span>\n"
w.Write([]byte(cp))
// fmt.Println("id:", value, lbl)
// fmt.Printf("%#v\n", node)
}
return false
}
func (ct *Content) htmlPreHandler(ctx *htmlcore.Context) bool {
hasCode := ctx.Node().FirstChild != nil && ctx.Node().FirstChild.Data == "code"
if !hasCode {
return false
}
codeEl := ctx.Node().FirstChild
collapsed := htmlcore.GetAttr(codeEl, "collapsed")
lang := htmlcore.GetLanguage(htmlcore.GetAttr(codeEl, "class"))
id := htmlcore.GetAttr(codeEl, "id")
title := htmlcore.GetAttr(codeEl, "title")
var ed *textcore.Editor
parent := ctx.Parent().AsWidget()
fr := core.NewFrame(parent.This)
fr.Styler(func(s *styles.Style) {
s.Grow.Set(1, 0)
s.Direction = styles.Column
})
fr.SetProperty("paginate-block", true) // no split
if id != "" {
fr.SetProperty("id", id)
fr.SetName(id)
ttx := parent.Children[parent.NumChildren()-2].(core.Widget)
ttx.AsWidget().SetProperty("id", id) // link target
tree.MoveToParent(ttx, fr) // get title text
}
if collapsed != "" {
cl := core.NewCollapser(fr)
core.NewText(cl.Summary).SetText("Code").SetText(title)
ed = textcore.NewEditor(cl.Details)
if collapsed == "false" || collapsed == "-" {
cl.Open = true
}
} else {
ed = textcore.NewEditor(fr)
}
ctx.SetNode(codeEl)
if lang != "" {
ed.Lines.SetFileExt(lang)
}
ed.Lines.SetString(htmlcore.ExtractText(ctx))
if system.GenerateHTMLArg() { // just the code, without running it
ed.SetProperty("html", codeHTML(ed.Lines.String(), lang))
return true
}
if (lang == "Go" && len(CompiledCode) > 0) || (lang == "Goal" && len(CompiledGoal) > 0) || (BindTextEditor != nil && (lang == "Go" || lang == "Goal")) {
ed.Lines.SpacesToTabs(0, ed.Lines.NumLines()) // Go uses tabs
parFrame := core.NewFrame(fr)
parFrame.Styler(func(s *styles.Style) {
s.Direction = styles.Column
s.Grow.Set(1, 0)
})
// we inherit our Grow.Y from our first child so that
// elements that want to grow can do so
parFrame.SetOnChildAdded(func(n tree.Node) {
if _, ok := n.(*core.Body); ok { // Body should not grow
return
}
wb := core.AsWidget(n)
if wb.IndexInParent() != 0 {
return
}
wb.FinalStyler(func(s *styles.Style) {
parFrame.Styles.Grow.Y = s.Grow.Y
})
})
BindCode(ed, parFrame, lang)
} else {
ed.SetReadOnly(true)
ed.Lines.Settings.LineNumbers = false
ed.Styler(func(s *styles.Style) {
s.Border.Width.Zero()
s.MaxBorder.Width.Zero()
s.StateLayer = 0
s.Background = colors.Scheme.SurfaceContainer
})
}
return true
}
// widgetHandler is htmlcore widget handler for adding our own actions etc.
func (ct *Content) widgetHandler(w core.Widget) {
tag := ""
id := ""
title := ""
wb := w.AsWidget()
if t, ok := wb.Properties["tag"]; ok {
tag = t.(string)
}
if t, ok := wb.Properties["id"]; ok {
id = t.(string)
}
if t, ok := wb.Properties["title"]; ok {
title = t.(string)
}
hdr := len(tag) == 2 && tag[0] == 'h'
// the layout is from the styles of the page (CSS), with the docs font size
if tx, ok := w.(*core.Text); ok {
pdf := ct.inPDFRender
tx.Styler(func(s *styles.Style) {
s.Font.Size.Value *= core.AppearanceSettings.DocsFontSize / 100
if tag := htmlcore.TextTag(tx); pdf && tag != "td" && tag != "th" {
// the blocks of PDFs are spaced by the margins of their texts
// (which add), and not by the CSS margins of the page
s.Margin.SetVertical(units.Em(core.ConstantSpacing(0.25)))
}
})
}
if hdr {
wb.SetProperty("paginate-no-break-after", true)
}
switch x := w.(type) {
case *core.Image:
ct.widgetHandlerFigure(w, id)
x.OnDoubleClick(func(e events.Event) {
d := core.NewBody("Image")
core.NewImage(d).SetImage(x.Image)
d.RunWindowDialog(x)
})
case *core.SVG:
ct.widgetHandlerFigure(w, id)
x.OnDoubleClick(func(e events.Event) {
d := core.NewBody("SVG")
sv := core.NewSVG(d)
sv.SVG = x.SVG
d.RunWindowDialog(x)
})
case *core.Frame:
switch tag {
case "table":
if id != "" {
lbl := ct.current.Page.SpecialLabel(id)
cp := "<b>" + lbl + ":</b>"
if title != "" {
cp += " " + title
}
ct.moveToBlockFrame(w, id, cp, true)
}
x.Styler(func(s *styles.Style) {
s.Align.Self = styles.Center
})
}
}
}
// moveToBlockFrame moves given widget into a block frame with given text
// widget either at the top or bottom of the new frame.
func (ct *Content) moveToBlockFrame(w core.Widget, id, txt string, top bool) {
wb := w.AsWidget()
fr := core.NewFrame(wb.Parent)
fr.Styler(func(s *styles.Style) {
s.Grow.Set(1, 0)
s.Direction = styles.Column
})
fr.SetProperty("paginate-block", true) // no split
fr.SetProperty("id", id)
fr.SetName(id)
var tx *core.Text
if top {
tx = core.NewText(fr).SetText(txt)
tx.SetProperty("id", id) // good link destination
}
tree.MoveToParent(w, fr)
if !top {
tx = core.NewText(fr).SetText(txt)
wb.SetProperty("id", id) // link here
}
tx.Styler(func(s *styles.Style) {
s.Max.X.In(8)
s.Font.Size.Value *= core.AppearanceSettings.DocsFontSize / 100
})
// Links in the caption are opened in the content, like those of the page text.
tx.HandleTextClick(func(tl *rich.Hyperlink, e events.Event) {
ct.OpenEvent(tl.URL, e)
})
}
func (ct *Content) widgetHandlerFigure(w core.Widget, id string) {
wb := w.AsWidget()
fig := false
alt := ""
if p, ok := wb.Properties["alt"]; ok {
alt = p.(string)
}
if alt != "" && id != "" {
fig = true
}
wb.Styler(func(s *styles.Style) {
s.SetAbilities(true, abilities.Clickable, abilities.DoubleClickable)
s.Overflow.Set(styles.OverflowAuto)
if fig {
s.Align.Self = styles.Center
}
})
if alt == "" {
return
}
// The alt text is markdown, rendered as the caption of a figure. The
// tooltip (which htmlcore sets to the alt text, and which is also the
// alt attribute of the pre-rendered HTML) is its plain text, with the
// wikilinks (citations, page links) replaced by their text as in the
// caption.
altf := htmlcore.MDToHTML(ct.Context, []byte(alt))
wb.SetTooltip(htmlPlainText(altf))
if !fig {
return
}
lbl := ct.current.Page.SpecialLabel(id)
lbf := "<b>" + lbl + ":</b> " + string(altf) + " <br><br> "
ct.moveToBlockFrame(w, id, lbf, false)
}
// htmlPlainText returns the text of the given HTML, without its markup, with
// whitespace collapsed to single spaces.
func htmlPlainText(htm []byte) string {
tx, err := htmltext.HTMLToRich(htm, rich.NewStyle(), nil)
if err != nil {
return strings.TrimSpace(string(htm))
}
return strings.Join(strings.Fields(string(tx.Join())), " ")
}
// citeWikilink processes citation links, which start with @
func (ct *Content) citeWikilink(text string) (url string, label string) {
if len(text) == 0 || text[0] != '@' { // @CiteKey reference citations
return "", ""
}
ref := text[1:]
cs := csl.Parenthetical
if len(ref) > 1 && ref[0] == '^' {
cs = csl.Narrative
ref = ref[1:]
}
if ct.inPDFRender {
url = "#" + ref
} else {
url = "ref://" + ref
}
if ct.References == nil {
return url, ref
}
it, has := ct.References.AtTry(ref)
if has {
return url, csl.CiteDefault(cs, it)
}
return url, ref
}
// mainWikilink processes all other wikilinks.
// page -> Page, page
// page|label -> Page, label
// page#heading -> Page#heading, heading
// #heading -> ThisPage#heading, heading
// Page is the resolved page name.
// heading can be a special id, or id:element to find elements within a special,
// e.g., #sim_neuron:Run Cycles
func (ct *Content) mainWikilink(text string) (url string, label string) {
name, label, _ := strings.Cut(text, "|")
name, heading, _ := strings.Cut(name, "#")
if name == "" { // A link with a blank page links to the current page
name = ct.current.Page.Name
} else if heading == "" {
if pg := ct.pageByName(name); pg == ct.current.Page {
// if just a link to current page, don't render link
// this can happen for embedded pages that refer to embedder
return "", ""
}
}
pg := ct.pageByName(name)
if pg == nil {
return "", ""
}
if label == "" {
if heading != "" {
label = ct.wikilinkLabel(pg, heading)
} else {
label = name
}
}
if ct.inPDFRender {
if heading != "" {
if pg == ct.current.Page {
return "#" + heading, label
}
return ct.getPrintURL() + "/" + pg.URL + "#" + heading, label
}
return ct.getPrintURL() + "/" + pg.URL, label
}
if heading != "" {
return pg.URL + "#" + heading, label
}
return pg.URL, label
}
// wikilinkLabel returns a label for given heading, for given page.
func (ct *Content) wikilinkLabel(pg *bcontent.Page, heading string) string {
label := heading
sl := pg.SpecialLabel(heading)
if sl != "" {
label = sl
} else {
colon := strings.Index(heading, ":")
if colon > 0 {
sl = pg.SpecialLabel(heading[:colon])
if sl != "" {
label = sl + ":" + heading[colon+1:]
}
}
}
return label
}
// parseURL parses the given local url into a page and heading.
func (ct *Content) parseURL(url string) (pgURL string, pg *bcontent.Page, heading string) {
url = strings.ReplaceAll(url, "/#", "#")
pgURL, heading, _ = strings.Cut(url, "#")
pg = ct.pagesByURL[pgURL]
if pg == nil {
// We want only the URL after the last slash for automatic redirects
// (old URLs could have nesting).
last := pgURL
if li := strings.LastIndex(last, "/"); li >= 0 {
last = pgURL[li+1:]
}
pg = ct.similarPage(last)
if pg == nil {
core.ErrorSnackbar(ct, errors.New("no pages available"))
} else {
core.MessageSnackbar(ct, fmt.Sprintf("Redirected from %s", pgURL))
}
}
heading = bcontent.SpecialToKebab(heading)
return
}
// isPageURL returns whether the given URL, with an optional #heading,
// is the URL of a page, which has slashes in it for a page in a mount
// of a [MountFS], as distinct from the URL of a resource file.
func (ct *Content) isPageURL(url string) bool {
url = strings.ReplaceAll(url, "/#", "#")
pgURL, _, _ := strings.Cut(url, "#")
_, ok := ct.pagesByURL[pgURL]
return ok
}
// open opens the page with the given URL and updates the display.
// It optionally adds the page to the history.
func (ct *Content) open(url string, history bool) {
if strings.HasPrefix(url, "https://") || strings.HasPrefix(url, "http://") {
core.TheApp.OpenURL(url)
return
}
if strings.HasPrefix(url, "ref://") {
ct.saveUpdatedPos(ct.current)
ct.openRef(url)
return
}
sli := strings.Index(url, "/")
if sli > 0 && len(url) > sli+1 && url[sli+1] != '#' && !ct.isPageURL(url) {
fb, err := fs.ReadFile(ct.Source, url)
if err != nil {
core.MessageSnackbar(ct, "Resource at: "+url+" not found")
return
}
errors.Log(os.MkdirAll("resources", 0777))
_, fn := path.Split(url)
fn = filepath.Join("resources", fn)
err = os.WriteFile(fn, fb, 0666)
if err != nil {
core.MessageSnackbar(ct, "Could not save resource at: "+fn)
return
}
core.TheApp.OpenURL(fsx.FileURL(errors.Log1(filepath.Abs(fn))))
return
}
curPg := ct.current
_, pg, heading := ct.parseURL(url)
// fmt.Println("open:", url, heading, "pg:", pg.URL)
if history {
ct.saveUpdatedPos(curPg)
ct.historyAdd(pg, heading, url)
}
ct.current.Heading = heading
ct.current.URL = url
if ct.current.Page == pg {
ct.openHeading(heading)
return
}
ct.current.Page = pg
// The table of contents of the old page is remade by loadPage,
// so it is deleted now instead of being updated first.
ct.deleteTableOfContents()
if !keepCategories && ct.categoriesTree != nil {
ct.categoriesTree.Delete()
ct.categoriesTree = nil
}
ct.updateScene() // need to update the whole scene to also update the toolbar
// We can only scroll to the heading after the page layout has been updated, so we defer.
ct.Defer(func() {
ct.setStageTitle()
ct.openHeading(heading)
ct.openHeading(heading) // note: needs this on web!
})
}
// openRef opens a ref:// reference url.
func (ct *Content) openRef(url string) {
pg := ct.pagesByURL["references"]
if pg == nil {
core.MessageSnackbar(ct, "references page not generated, use mdcite in csl package")
return
}
ref := strings.TrimPrefix(url, "ref://")
ct.current.Page = pg
// The reference is opened like a heading, so that a staged page is
// built whole and has the reference to scroll to.
ct.current.Heading = ref
ct.historyAdd(pg, "", url)
ct.deleteTableOfContents()
ct.updateScene()
ct.Defer(func() {
ct.setStageTitle()
ct.openID(ref, "")
})
}
func (ct *Content) openHeading(heading string) {
if heading == "" {
ct.pageFrame().ScrollDimToContentStart(math32.Y)
return
}
// fmt.Println("opening heading:", heading)
idname := "" // in case of #id:element
element := ""
colon := strings.Index(heading, ":")
if colon > 0 {
idname = heading[:colon]
element = heading[colon+1:]
}
tr := ct.tocNodes[strcase.ToKebab(heading)]
if tr == nil {
found := false
if idname != "" && element != "" {
found = ct.openID(idname, element)
if !found {
found = ct.openID(heading, "")
}
} else {
found = ct.openID(heading, "")
}
if !found {
errors.Log(fmt.Errorf("heading %q not found", heading))
}
return
}
tr.UnselectAll()
tr.Select()
tx := tr.Property("page-text").(core.Widget).AsWidget() // the heading
tx.ScrollThisToTop()
ct.Defer(func() {
tx.ScrollThisToTop() // try try again -- without this, is somewhat unreliable..
})
}
func (ct *Content) openID(id, element string) bool {
if id == "" {
ct.pageFrame().ScrollDimToContentStart(math32.Y)
return true
}
var found *core.WidgetBase
for _, cwb := range ct.pageFrame().AllWidgets() {
if cwb.Name != id {
continue
}
found = cwb
break
}
if found == nil {
return false
}
if element != "" {
el := ct.elementInSpecial(found, element)
if el != nil {
found = el
}
}
found.SetFocus()
found.SetState(true, states.Active)
found.Style()
found.NeedsRender()
return true
}
// elementInSpecial looks for given element within a special item.
func (ct *Content) elementInSpecial(sp *core.WidgetBase, element string) *core.WidgetBase {
pathPrefix := ""
hasPath := false
if strings.Contains(element, "/") {
pathPrefix, element, hasPath = strings.Cut(element, "/")
}
if cl, ok := sp.Parent.(*core.Collapser); ok { // for code
nxt := tree.NextSibling(cl)
if nxt != nil {
sp = nxt.(core.Widget).AsWidget()
} else {
sp = cl.Parent.(core.Widget).AsWidget() // todo: not sure when this is good
}
}
var found *core.WidgetBase
for cw, cwb := range sp.AllWidgets() {
if !cwb.IsDisplayable() {
continue
}
if hasPath {
pth := cw.AsTree().Path()
if strings.Contains(pth, pathPrefix) {
continue
}
}
label := labels.ToLabel(cw)
kb := bcontent.SpecialToKebab(label)
if !strings.EqualFold(label, element) && kb != element {
continue
}
if cwb.AbilityIs(abilities.Focusable) {
found = cwb
break
}
next := core.AsWidget(tree.Next(cwb))
if next.AbilityIs(abilities.Focusable) {
found = next
break
}
}
return found
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package content
import (
"strconv"
"strings"
"cogentcore.org/core/core"
)
// headingOf returns the heading level (1 to 6) and text of the given
// widget, if it is a heading: a [core.Text] with a tag of h1 to h6, or a
// widget with such a tag with its text in it (as in the browser style of
// htmlcore), which is the widget of the heading (as for scrolling to it).
func headingOf(w core.Widget) (level int, text string, ok bool) {
// note: checking ok first, as a failed assertion of a nil value to a
// string is null instead of "" under goscript (js)
tag, ok := w.AsWidget().Property("tag").(string)
if !ok || len(tag) != 2 || tag[0] != 'h' {
return 0, "", false
}
level, err := strconv.Atoi(tag[1:])
if err != nil || level < 1 || level > 6 {
return 0, "", false
}
if tx, ok := w.(*core.Text); ok {
return level, tx.Text, true
}
var texts []string
for cw := range w.AsWidget().AllWidgets() {
if tx, ok := cw.(*core.Text); ok && strings.TrimSpace(tx.Text) != "" {
texts = append(texts, strings.TrimSpace(tx.Text))
}
}
if len(texts) == 0 {
return 0, "", false
}
return level, strings.Join(texts, " "), true
}
// paragraphText returns the text of the given widget if it is a paragraph:
// a [core.Text] with a tag of p, or a widget with that tag with a text in it.
func paragraphText(w core.Widget) (string, bool) {
if w.AsWidget().Property("tag") != "p" {
return "", false
}
if tx, ok := w.(*core.Text); ok {
return tx.Text, true
}
text := ""
for cw := range w.AsWidget().AllWidgets() {
if tx, ok := cw.(*core.Text); ok {
text = tx.Text
break
}
}
return text, text != ""
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package content
import (
"io/fs"
"cogentcore.org/core/core"
"cogentcore.org/core/tree"
)
// SetAppHelp sets the help of the app ([core.AppHelp]), from the Help item
// of the app menu, to open the given documentation of the app, whose home
// page is home.md, with [OpenHelp].
func SetAppHelp(docs fs.FS) {
core.AppHelp = func(ctx core.Widget) {
OpenHelp(ctx, docs)
}
}
// OpenHelp opens the given documentation of the app in a window, in the
// context of the given widget, or raises the window if it is open already.
// The content does not use the URL of the web page, which is the app's.
func OpenHelp(ctx core.Widget, docs fs.FS) {
if core.RecycleMainWindow(docs) {
return
}
b := core.NewBody(core.TheApp.Name() + " help").SetData(docs)
ct := NewContent(b)
ct.noWebURL = true // before the source, which opens the first page
ct.SetSource(docs)
b.AddTopBar(func(bar *core.Frame) {
core.NewToolbar(bar).Maker(func(p *tree.Plan) {
ct.MakeToolbar(p)
})
})
b.NewWindow().SetContext(ctx).SetNewWindow(true).Run()
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package content
import (
"fmt"
"cogentcore.org/core/base/strcase"
"cogentcore.org/core/content/bcontent"
"cogentcore.org/core/core"
"cogentcore.org/core/math32"
"cogentcore.org/core/tree"
)
func (ct *Content) nearestHeading() string {
fr := ct.pageFrame()
if fr == nil {
return ""
}
d := math32.Y
if !fr.HasScroll[d] || fr.Scrolls[d] == nil {
return ""
}
// go through the lines and find one at pos
var lastHead string
fr.WidgetWalkDown(func(cw core.Widget, cwb *core.WidgetBase) bool {
wpos := cwb.Geom.Pos.Total.Y - fr.Geom.Pos.Content.Y
if wpos > 100 {
return tree.Break
}
if _, text, ok := headingOf(cw); ok {
lastHead = text
}
return tree.Continue
})
return lastHead
}
// saveUpdatedPos saves an updated history record of the current position
// (the nearest heading) on the given current page, before another page is
// opened.
func (ct *Content) saveUpdatedPos(curPg Location) {
nhead := ct.nearestHeading()
if nhead == "" {
return
}
var url string
_, nw, _ := ct.pageURL(curPg.Page, strcase.ToKebab(nhead))
if nw != nil {
url = nw.String()
} else {
url = curPg.Page.URL + "#" + strcase.ToKebab(nhead)
}
ct.historyAdd(curPg.Page, nhead, url)
}
func (ct *Content) historyAdd(pg *bcontent.Page, heading, url string) {
if ct.tabs == nil {
ct.saveWebURL(&Location{Page: pg, Heading: heading, URL: url})
return
}
_, ci := ct.tabs.CurrentTab()
ct.history[ci].Save(&Location{Page: pg, Heading: heading, URL: url})
}
func (ct *Content) historyHasBack() bool {
if ct.tabs == nil { // shouldn't happen
return false
}
_, ci := ct.tabs.CurrentTab()
h := ct.history[ci]
return h.Index > 0
}
func (ct *Content) historyBack() {
if ct.tabs == nil { // shouldn't happen
return
}
_, ci := ct.tabs.CurrentTab()
lc, _ := ct.history[ci].Back()
ct.open(lc.URL, false) // no add more history
}
func (ct *Content) historyHasForward() bool {
if ct.tabs == nil { // shouldn't happen
return false
}
_, ci := ct.tabs.CurrentTab()
h := ct.history[ci]
return h.Index < len(h.Records)-1
}
func (ct *Content) historyForward() {
if ct.tabs == nil { // shouldn't happen
return
}
_, ci := ct.tabs.CurrentTab()
lc, _ := ct.history[ci].Forward()
ct.open(lc.URL, false) // no add more history
}
///////// History
// Location holds one location of browsing history.
type Location struct {
Page *bcontent.Page
Heading string
URL string
}
func (lc *Location) Reset() {
lc.Page = nil
lc.Heading = ""
lc.URL = ""
}
func (lc *Location) String() string {
if lc.Page != nil {
return fmt.Sprintf("%q (page: %q head: %q)", lc.URL, lc.Page.URL, lc.Heading)
}
return fmt.Sprintf("%q", lc.URL)
}
func (lc *Location) Clone() *Location {
nc := &Location{}
*nc = *lc
return nc
}
// History records the history of browsing locations, for back arrow
// navigation.
type History struct {
// Index is the current index in the Records, which is typically the
// current page as saved. Back decrements then returns that.
Index int
// Records is the list of saved locations.
Records []*Location
}
// Save adds the given location after the current one, removing any
// locations after the current one, unless it is the same as the current
// one, in which case nothing changes and Index stays valid.
func (hs *History) Save(lc *Location) {
if hs.Records == nil {
hs.Records = make([]*Location, 1)
hs.Index = 0
hs.Records[0] = lc
return
}
if *(hs.Records[hs.Index]) == *lc { // no repeats
return
}
hs.Records = append(hs.Records[:hs.Index+1], lc)
hs.Index++
}
// Back decrements Index and returns that location.
// If already at the start, returns false.
func (hs *History) Back() (*Location, bool) {
if hs.Index <= 0 {
return hs.Records[0], false
}
hs.Index--
lc := hs.Records[hs.Index]
return lc, true
}
// Forward returns next location and increments Index.
// returns false if already at end (returns end location).
func (hs *History) Forward() (*Location, bool) {
if hs.Index == len(hs.Records)-1 {
return hs.Records[hs.Index], false
}
hs.Index++
return hs.Records[hs.Index], true
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package content
import (
"errors"
"fmt"
"io"
"io/fs"
"path"
"slices"
"strings"
"time"
errs "cogentcore.org/core/base/errors"
"cogentcore.org/core/base/strcase"
"cogentcore.org/core/content/bcontent"
)
// MountFS is a filesystem of content that combines a root filesystem with
// other filesystems mounted in it at URL prefixes, such as the documentation
// of several apps on one website (each also used for the help of its app with
// [SetAppHelp]). Make it with [NewMountFS] and [MountFS.Mount], and use it as
// the source of a [Content] with [Content.SetSource].
//
// The pages of a mounted filesystem are at its prefix: its root page (with
// URL = "" in its front matter, as for the home.md of the help of an app) has
// the URL of the prefix itself (such as "docs/lists"), and its other pages have
// their URLs under it (such as "docs/lists/settings"). The name of the root
// page is its Title, or else the sentence case of the last element of the
// prefix ("Lists"). The other pages keep their names unless a page of the root
// filesystem or of an earlier mount has the same name, in which case the name
// of the mount's root page is added in parentheses ("Settings (Cogent Lists)").
// Relative URLs of images and other resources in a mounted page are relative to
// the page, so that a mounted filesystem works the same as on its own.
type MountFS struct {
// root is the root filesystem, which may be nil.
root fs.FS
// mounts are the mounted filesystems, in the order mounted.
mounts []fsMount
}
// fsMount is a filesystem mounted in a [MountFS] at a prefix.
type fsMount struct {
// prefix is the path of the mount, such as "docs/lists".
prefix string
// fsys is the mounted filesystem.
fsys fs.FS
}
// NewMountFS returns a new [MountFS] with the given root filesystem, which may
// be nil for a filesystem that only has mounts.
func NewMountFS(root fs.FS) *MountFS {
return &MountFS{root: root}
}
// Mount mounts the given filesystem at the given prefix, a slash-separated
// path such as "docs/lists" (see [MountFS]). It panics if the prefix is not a
// valid path of [fs.FS] other than ".", or if it is mounted already.
func (m *MountFS) Mount(prefix string, fsys fs.FS) *MountFS {
if !fs.ValidPath(prefix) || prefix == "." {
panic("content.MountFS: invalid mount prefix " + prefix)
}
if slices.ContainsFunc(m.mounts, func(mt fsMount) bool { return mt.prefix == prefix }) {
panic("content.MountFS: prefix mounted already " + prefix)
}
m.mounts = append(m.mounts, fsMount{prefix: prefix, fsys: fsys})
return m
}
// mountOf returns the mount that has the given path in it (the one with the
// longest prefix, for nested mounts), and the path relative to it, or nil.
func (m *MountFS) mountOf(name string) (mt *fsMount, rel string) {
for i := range m.mounts {
p := m.mounts[i].prefix
if name != p && !strings.HasPrefix(name, p+"/") {
continue
}
if mt == nil || len(p) > len(mt.prefix) {
mt = &m.mounts[i]
}
}
if mt == nil {
return nil, ""
}
if name == mt.prefix {
return mt, "."
}
return mt, name[len(mt.prefix)+1:]
}
// mountDirs returns the names of the next elements of the prefixes of
// the mounts in the given directory, which is not in a mount.
func (m *MountFS) mountDirs(dir string) []string {
var names []string
for _, mt := range m.mounts {
rest := mt.prefix
if dir != "." {
if !strings.HasPrefix(mt.prefix, dir+"/") {
continue
}
rest = mt.prefix[len(dir)+1:]
}
first, _, _ := strings.Cut(rest, "/")
if !slices.Contains(names, first) {
names = append(names, first)
}
}
return names
}
// Open opens the named file, in a mount if it is in one, and otherwise in the
// root filesystem. The directories that contain mounts have the entries of
// those mounts, in addition to any entries of the root filesystem.
func (m *MountFS) Open(name string) (fs.File, error) {
if !fs.ValidPath(name) {
return nil, &fs.PathError{Op: "open", Path: name, Err: fs.ErrInvalid}
}
if mt, rel := m.mountOf(name); mt != nil {
f, err := mt.fsys.Open(rel)
if err != nil || rel != "." {
return f, err
}
return &mountRoot{File: f, name: path.Base(name)}, nil
}
if len(m.mountDirs(name)) > 0 {
entries, err := m.ReadDir(name)
if err != nil {
return nil, err
}
return &mountDir{name: name, entries: entries}, nil
}
if m.root == nil {
return nil, &fs.PathError{Op: "open", Path: name, Err: fs.ErrNotExist}
}
return m.root.Open(name)
}
// ReadDir reads the named directory, as with [MountFS.Open].
func (m *MountFS) ReadDir(name string) ([]fs.DirEntry, error) {
if !fs.ValidPath(name) {
return nil, &fs.PathError{Op: "readdir", Path: name, Err: fs.ErrInvalid}
}
if mt, rel := m.mountOf(name); mt != nil {
return fs.ReadDir(mt.fsys, rel)
}
dirs := m.mountDirs(name)
var entries []fs.DirEntry
if m.root != nil {
re, err := fs.ReadDir(m.root, name)
if err != nil && (len(dirs) == 0 || !errors.Is(err, fs.ErrNotExist)) {
return nil, err
}
// The mounts take the place of root entries with the same names.
entries = slices.DeleteFunc(re, func(e fs.DirEntry) bool {
return slices.Contains(dirs, e.Name())
})
} else if len(dirs) == 0 {
return nil, &fs.PathError{Op: "readdir", Path: name, Err: fs.ErrNotExist}
}
for _, d := range dirs {
entries = append(entries, fs.FileInfoToDirEntry(m.dirStat(path.Join(name, d))))
}
slices.SortFunc(entries, func(a, b fs.DirEntry) int {
return strings.Compare(a.Name(), b.Name())
})
return entries, nil
}
// dirStat returns the [fs.FileInfo] of the given directory that is a mount
// or contains mounts, which is not in a mount.
func (m *MountFS) dirStat(name string) fs.FileInfo {
for _, mt := range m.mounts {
if mt.prefix != name {
continue
}
if fi, err := fs.Stat(mt.fsys, "."); err == nil {
return renamedInfo{FileInfo: fi, name: path.Base(name)}
}
}
return dirInfo(path.Base(name))
}
// renamedInfo is an [fs.FileInfo] with another name, for the root
// directory of a mount, which has the name of its prefix.
type renamedInfo struct {
fs.FileInfo
name string
}
func (r renamedInfo) Name() string { return r.name }
// mountRoot is the open root directory of a mount, which has the name
// of the last element of its prefix.
type mountRoot struct {
fs.File
name string
}
func (r *mountRoot) Stat() (fs.FileInfo, error) {
fi, err := r.File.Stat()
if err != nil {
return nil, err
}
return renamedInfo{FileInfo: fi, name: r.name}, nil
}
func (r *mountRoot) ReadDir(n int) ([]fs.DirEntry, error) {
d, ok := r.File.(fs.ReadDirFile)
if !ok {
return nil, &fs.PathError{Op: "readdir", Path: r.name, Err: errors.New("not implemented")}
}
return d.ReadDir(n)
}
// dirInfo is the [fs.FileInfo] of a directory of a [MountFS] that
// contains mounts.
type dirInfo string
func (d dirInfo) Name() string { return string(d) }
func (d dirInfo) Size() int64 { return 0 }
func (d dirInfo) Mode() fs.FileMode { return fs.ModeDir | 0555 }
func (d dirInfo) ModTime() time.Time { return time.Time{} }
func (d dirInfo) IsDir() bool { return true }
func (d dirInfo) Sys() any { return nil }
// mountDir is an open directory of a [MountFS] that contains mounts.
type mountDir struct {
name string
entries []fs.DirEntry
offset int
}
func (d *mountDir) Stat() (fs.FileInfo, error) { return dirInfo(path.Base(d.name)), nil }
func (d *mountDir) Close() error { return nil }
func (d *mountDir) Read([]byte) (int, error) {
return 0, &fs.PathError{Op: "read", Path: d.name, Err: errors.New("is a directory")}
}
func (d *mountDir) ReadDir(n int) ([]fs.DirEntry, error) {
rest := d.entries[d.offset:]
if n <= 0 {
d.offset = len(d.entries)
return rest, nil
}
if len(rest) == 0 {
return nil, io.EOF
}
n = min(n, len(rest))
d.offset += n
return rest[:n], nil
}
// addPage adds the given page to the pages of the content.
func (ct *Content) addPage(pg *bcontent.Page) {
ct.pages = append(ct.pages, pg)
ct.pagesByName[strings.ToLower(pg.Name)] = pg
ct.pagesByURL[pg.URL] = pg
for _, cat := range pg.Categories {
ct.pagesByCategory[cat] = append(ct.pagesByCategory[cat], pg)
}
}
// newMountedPage returns a new page for the file at the given path relative
// to the given mount of a [MountFS] source, with its URL under the prefix of
// the mount (see [MountFS]).
func (ct *Content) newMountedPage(mt *fsMount, rel string) (*bcontent.Page, error) {
pg, err := bcontent.NewPage(mt.fsys, rel)
if err != nil {
return nil, err
}
pg.Source = ct.Source
pg.Filename = path.Join(mt.prefix, rel)
if pg.URL == "" {
pg.URL = mt.prefix
if pg.Title != pg.Name { // a title in the front matter
pg.Name = pg.Title
} else {
pg.Name = strcase.ToSentence(path.Base(mt.prefix))
pg.Title = pg.Name
}
} else {
pg.URL = mt.prefix + "/" + pg.URL
}
ct.pageBases[pg] = path.Dir(pg.Filename) + "/"
return pg, nil
}
// addMountedPages adds the given pages of the mounts of the given [MountFS]
// source, after the other pages, so that their names do not take the place
// of the names of the other pages: a name that is taken already gets the
// name of the root page of its mount added in parentheses.
func (ct *Content) addMountedPages(mfs *MountFS, pages []*bcontent.Page) {
mountNames := map[string]string{} // by prefix
for _, pg := range pages {
if mt, _ := mfs.mountOf(pg.Filename); pg.URL == mt.prefix {
mountNames[mt.prefix] = pg.Name
}
}
for _, pg := range pages {
if _, ok := ct.pagesByURL[pg.URL]; ok {
errs.Log(fmt.Errorf("content: page %q of a mount has the URL of another page: %q", pg.Filename, pg.URL))
continue
}
if _, ok := ct.pagesByName[strings.ToLower(pg.Name)]; ok {
mt, _ := mfs.mountOf(pg.Filename)
if mn := mountNames[mt.prefix]; mn != "" {
pg.Name += " (" + mn + ")"
}
}
ct.addPage(pg)
}
}
// pageBase returns the base URL of the given page, against which the relative
// URLs of its resources are resolved: the directory of its file for a page in a
// mount of a [MountFS], and "" otherwise (the root of the source).
func (ct *Content) pageBase(pg *bcontent.Page) string {
if pg == nil {
return ""
}
return ct.pageBases[pg]
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package content
import (
"time"
"cogentcore.org/core/content/bcontent"
"cogentcore.org/core/text/paginate"
)
func init() {
Settings.Defaults()
}
// Settings are the current settings for content rendering.
var Settings SettingsData
// SettingsData has settings parameters for content,
// including PDF rendering options.
type SettingsData struct {
PDF paginate.Options
// SiteTitle is the title of the site, used in page headings and titles.
SiteTitle string
// PageSettings is a function that returns the settings data to use
// for the current page. Can set custom parameters for different pages.
// The default sets the PDF Header function to HeaderLeftPageNumber
// with current page Title.
PageSettings func(ct *Content, curPage *bcontent.Page) *SettingsData
}
func (s *SettingsData) Defaults() {
s.PDF.Defaults()
s.PDF.Footer = nil
s.PageSettings = func(ct *Content, curPage *bcontent.Page) *SettingsData {
ps := &SettingsData{}
*ps = Settings
pt := curPage.Title
if ps.SiteTitle != "" && pt == curPage.Name {
pt = ps.SiteTitle + ": " + pt
}
hdr := pt
if curPage.Heading != "" {
hdr = curPage.Heading
}
ps.PDF.Header = paginate.NoFirst(paginate.HeaderLeftPageNumber(hdr))
ur := ct.getPrintURL() + "/" + curPage.URL
ura := `<a href="` + ur + `">` + ur + `</a>`
if curPage.NoURLinPDF {
ura = ""
}
dt := ""
if !curPage.Date.IsZero() {
dt = curPage.Date.Format("January 2, 2006")
} else {
dt = time.Now().Format("January 2, 2006")
}
ps.PDF.Title = paginate.CenteredTitle(pt, curPage.Authors, curPage.Affiliations, ura, dt, curPage.Version, curPage.Reference, curPage.Abstract)
ps.PDF.TextStyler = paginate.APAHeaders
return ps
}
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package content
import (
"fmt"
"html"
"slices"
"strings"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/iox/jsonx"
"cogentcore.org/core/colors"
"cogentcore.org/core/colors/matcolor"
"cogentcore.org/core/content/bcontent"
"cogentcore.org/core/core"
"cogentcore.org/core/htmlcore/tohtml"
"cogentcore.org/core/text/highlighting"
"cogentcore.org/core/text/token"
)
// generateSite generates the JSON [bcontent.Site] data for the website
// of the content, which is used by the core build tool for both the
// pre-rendered preview shown while the wasm app is loading and for a
// freestanding website without the wasm app (htmlonly mode). Only the
// page content is converted to HTML; the navigation trees are generated
// from the returned data by the core build tool.
func generateSite(ct *Content) string {
site := &bcontent.Site{}
ct.UpdateTree() // need initial update first
for _, pg := range ct.pages {
if pg.Draft {
continue
}
ct.Open(pg.URL)
prp := &bcontent.PreRenderPage{
Page: *pg,
HTML: tohtml.Generate(ct.rightFrame),
Description: pageDescription(ct),
TOC: pageTOC(ct.rightFrame),
}
site.Pages = append(site.Pages, prp)
}
for _, cat := range ct.categories {
sc := &bcontent.Category{Name: cat}
if cpg := ct.pageByName(cat); cpg != nil && !cpg.Draft {
sc.HasPage = true
sc.URL = cpg.URL
}
for _, pg := range ct.pagesByCategory[cat] {
if pg.Draft || strings.EqualFold(cat, pg.Name) {
continue
}
sc.Pages = append(sc.Pages, &bcontent.NavPage{Name: pg.Name, URL: pg.URL})
}
site.Categories = append(site.Categories, sc)
}
site.CSS = codeCSS()
return string(errors.Log1(jsonx.WriteBytes(site)))
}
// pageDescription returns the description of the current page, which is the
// first non-emphasized paragraph (<em> typically indicates a note or caption,
// not an introduction).
func pageDescription(ct *Content) string {
desc := ""
for n := range ct.All() {
if w, ok := n.(core.Widget); ok {
if text, ok := paragraphText(w); ok && !strings.HasPrefix(text, "<em>") {
desc = text
break
}
}
}
return desc
}
// pageTOC returns the table of contents headings in the given page frame,
// consistent with [Content.makeTableOfContents].
func pageTOC(w *core.Frame) []*bcontent.TOCHeading {
var toc []*bcontent.TOCHeading
for cw, cwb := range w.AllWidgets() {
level, text, ok := headingOf(cw)
if !ok || cwb.Property("page-title") != nil {
continue
}
id, ok := cwb.Property("id").(string)
if !ok {
id = cwb.Name // consistent with [tohtml.Widget]
}
toc = append(toc, &bcontent.TOCHeading{Level: level, Text: text, ID: id})
}
return toc
}
// codeHTML returns syntax highlighted HTML for the given code in the given
// language, using the CSS classes from [codeCSS].
func codeHTML(code, lang string) string {
var b strings.Builder
b.WriteString(`<pre class="code"><code`)
if lang != "" {
fmt.Fprintf(&b, ` class="language-%s"`, strings.ToLower(lang))
}
b.WriteString(">")
lx := lang
if strings.EqualFold(lx, "goal") {
lx = "go"
}
clex := highlighting.GetLexer(lx)
lines := strings.Split(strings.TrimRight(code, "\n"), "\n")
for i, ln := range lines {
if i > 0 {
b.WriteString("\n")
}
if clex == nil {
b.WriteString(html.EscapeString(ln))
continue
}
tags, err := highlighting.ChromaTagsLine(clex, ln)
if err != nil {
b.WriteString(html.EscapeString(ln))
continue
}
b.Write(highlighting.MarkupLineHTML([]rune(ln), tags, nil, highlighting.EscapeHTML))
}
b.WriteString("</code></pre>")
return b.String()
}
// codeCSS returns the CSS for the syntax highlighting classes used in
// [codeHTML], for both light and dark color schemes, based on
// [core.AppearanceSettings].
func codeCSS() string {
isDark := matcolor.SchemeIsDark
defer func() {
colors.SetScheme(isDark)
highlighting.UpdateFromTheme()
}()
var b strings.Builder
for _, dark := range []bool{false, true} {
colors.SetScheme(dark)
highlighting.UpdateFromTheme()
st := highlighting.AvailableStyle(core.AppearanceSettings.Highlighting)
css := st.ToCSS()
tags := make([]token.Tokens, 0, len(css))
for tag := range css {
tags = append(tags, tag)
}
slices.Sort(tags)
indent := ""
if dark {
b.WriteString("@media (prefers-color-scheme: dark) {\n")
indent = " "
}
for _, tag := range tags {
if css[tag] == "" {
continue
}
fmt.Fprintf(&b, "%s.code .%s { %s; }\n", indent, tag.StyleName(), css[tag])
}
if dark {
b.WriteString("}\n")
}
}
return b.String()
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package content
import (
"cogentcore.org/core/content/bcontent"
"github.com/adrg/strutil/metrics"
)
// similarPage returns the page most similar to the given URL, used for automatic 404 redirects.
func (ct *Content) similarPage(url string) *bcontent.Page {
m := metrics.NewJaccard()
m.CaseSensitive = false
var best *bcontent.Page
bestSimilarity := -1.0
for _, page := range ct.pages {
similarity := m.Compare(url, page.URL)
if similarity > bestSimilarity {
best = page
bestSimilarity = similarity
}
}
return best
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !js
package content
import (
"net/url"
"cogentcore.org/core/content/bcontent"
)
// OfflineURL is the non-web base url, which can be set to allow
// docs to refer to this in frontmatter.
var OfflineURL = ""
// just for printing
func (ct *Content) getPrintURL() string { return OfflineURL }
func (ct *Content) getWebURL() string { return "" }
func (ct *Content) pageURL(pg *bcontent.Page, heading string) (current, nw *url.URL, err error) {
return
}
func (ct *Content) saveWebURL(lc *Location) {}
func (ct *Content) handleWebPopState() {}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"slices"
"time"
)
// Animation represents the data for a widget animation.
// You can call [WidgetBase.Animate] to create a widget animation.
// Animations are stored on the [Scene].
type Animation struct {
// Func is the animation function, which is run every time the [Scene]
// receives a paint tick, which is usually at the same rate as the refresh
// rate of the monitor. It receives the [Animation] object so that
// it can references things such as [Animation.Dt] and set things such as
// [Animation.Done].
Func func(a *Animation)
// Widget is the widget associated with the animation. The animation will
// pause if the widget is not visible, and it will end if the widget is destroyed.
Widget *WidgetBase
// Dt is the amount of time in milliseconds that has passed since the
// last animation frame/step/tick.
Dt float32
// Done can be set to true to permanently stop the animation; the [Animation] object
// will be removed from the [Scene] at the next frame.
Done bool
// lastTime is the last time this animation was run.
lastTime time.Time
}
// Animate adds a new [Animation] to the [Scene] for the widget. The given function is run
// at every tick, and it receives the [Animation] object so that it can reference and modify
// things on it; see the [Animation] docs for more information on things such as [Animation.Dt]
// and [Animation.Done].
func (wb *WidgetBase) Animate(f func(a *Animation)) {
a := &Animation{
Func: f,
Widget: wb,
}
wb.Scene.Animations = append(wb.Scene.Animations, a)
wb.Scene.wake() // (they run at every paint event)
}
// runAnimations runs the [Scene.Animations].
func (sc *Scene) runAnimations() {
if len(sc.Animations) == 0 {
return
}
for _, a := range sc.Animations {
if a.Widget == nil || a.Widget.This == nil {
a.Done = true
}
if a.Done || !a.Widget.IsVisible() {
continue
}
if a.lastTime.IsZero() {
a.Dt = 16.66666667 // 60 FPS fallback
} else {
a.Dt = float32(time.Since(a.lastTime).Seconds()) * 1000
}
a.Func(a)
a.lastTime = time.Now()
}
sc.Animations = slices.DeleteFunc(sc.Animations, func(a *Animation) bool {
return a.Done
})
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"image"
"strings"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/colors"
"cogentcore.org/core/icons"
"cogentcore.org/core/math32"
"cogentcore.org/core/svg"
"cogentcore.org/core/system"
)
var (
// TheApp is the current [App]; only one is ever in effect.
TheApp = &App{App: system.TheApp}
// AppAbout is the about information for the current app.
// It is set by a linker flag in the core command line tool.
AppAbout string
// AppHelp, if set, opens the help of the current app, in the context
// of the given widget, from the Help item of the app menu, as the
// content package does for the documentation of the app.
AppHelp func(ctx Widget)
// AppIcon is the svg icon for the current app.
// It is set by a linker flag in the core command line tool.
// It defaults to [icons.CogentCore] otherwise.
AppIcon string = string(icons.CogentCore)
)
// App represents a Cogent Core app. It extends [system.App] to provide both system-level
// and high-level data and functions to do with the currently running application. The
// single instance of it is [TheApp], which embeds [system.TheApp].
type App struct { //types:add -setters
system.App `set:"-"`
// SceneInit is a function called on every newly created [Scene].
// This can be used to set global configuration and styling for all
// widgets in conjunction with [Scene.WidgetInit].
SceneInit func(sc *Scene) `edit:"-"`
}
// appIconImagesCache is a cached version of [appIconImages].
var appIconImagesCache []image.Image
// appIconImages returns a slice of images of sizes 16x16, 32x32, and 48x48
// rendered from [AppIcon], and 512x512 if it is the app's own icon, not the
// default one, which is the app icon in the Dock on macOS: otherwise the
// Dock keeps the icon of the app bundle, as for an app whose executable is
// one installed with go install, without the [AppIcon] of core build
// (see [system.NewWindowOptions.Icon]). It returns nil if [AppIcon] is ""
// or if there is an error. It automatically logs any errors. It caches the
// result for future calls.
func appIconImages() []image.Image {
if appIconImagesCache != nil {
return appIconImagesCache
}
if AppIcon == "" {
return nil
}
res := make([]image.Image, 3, 4)
sv := svg.NewSVG(math32.Vec2(16, 16))
sv.DefaultFill = colors.Uniform(colors.FromRGB(66, 133, 244)) // Google Blue (#4285f4)
err := sv.ReadXML(strings.NewReader(AppIcon))
if errors.Log(err) != nil {
return nil
}
res[0] = sv.RenderImage()
sv.SetSize(math32.Vec2(32, 32))
res[1] = sv.RenderImage()
sv.SetSize(math32.Vec2(48, 48))
res[2] = sv.RenderImage()
if AppIcon != string(icons.CogentCore) {
sv.SetSize(math32.Vec2(512, 512))
res = append(res, sv.RenderImage())
}
appIconImagesCache = res
return res
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import "cogentcore.org/core/system"
func init() {
system.HandleBack = handleBack
}
// handleBack handles the back button or gesture of the system (on
// Android; see [system.HandleBack]), returning whether it went back within
// the app: it closes the top popup of the current window (as a menu), or
// else the top stage if it has a back button (see [Stage.hasBackButton])
// or is a dialog, as its back button or Escape does.
func handleBack() bool {
rw := getCurrentRenderWindow()
if rw == nil {
return false
}
rc := rw.renderContext()
if rc == nil {
return false
}
rc.Lock()
defer rc.Unlock()
top := rw.mains.top()
if top == nil || top.Scene == nil {
return false
}
if top.popups != nil {
if pop := top.popups.top(); pop != nil {
return pop.ClosePopup()
}
}
if top.Type != DialogStage && !top.hasBackButton(len(rw.mains.list()) > 1) {
return false
}
return top.Scene.Close()
}
// hasBackButton returns whether the stage has a back button in its top
// bar (see [Stage.BackButton]), given whether there are other stages
// below it in its stack.
func (st *Stage) hasBackButton(below bool) bool {
return st.BackButton.Or(st.FullWindow && !st.NewWindow && below)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"slices"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/keymap"
"cogentcore.org/core/styles"
)
// BarFuncs are functions for creating control bars,
// attached to different sides of a [Scene]. Functions
// are called in forward order so first added are called first.
type BarFuncs []func(bar *Frame)
// Add adds the given function for configuring a control bar
func (bf *BarFuncs) Add(fun func(bar *Frame)) *BarFuncs {
*bf = append(*bf, fun)
return bf
}
// call calls all the functions for configuring given widget
func (bf *BarFuncs) call(bar *Frame) {
for _, fun := range *bf {
fun(bar)
}
}
// isEmpty returns true if there are no functions added
func (bf *BarFuncs) isEmpty() bool {
return len(*bf) == 0
}
// makeSceneBars configures the side control bars, for main scenes.
func (sc *Scene) makeSceneBars() {
sc.addDefaultBars()
if !sc.Bars.Top.isEmpty() {
head := NewFrame(sc)
head.SetName("top-bar")
head.Styler(func(s *styles.Style) {
s.Align.Items = styles.Center
s.Grow.Set(1, 0)
})
sc.Bars.Top.call(head)
}
if !sc.Bars.Left.isEmpty() || !sc.Bars.Right.isEmpty() {
mid := NewFrame(sc)
mid.SetName("body-area")
if !sc.Bars.Left.isEmpty() {
left := NewFrame(mid)
left.SetName("left-bar")
left.Styler(func(s *styles.Style) {
s.Direction = styles.Column
s.Align.Items = styles.Center
s.Grow.Set(0, 1)
})
sc.Bars.Left.call(left)
}
if sc.Body != nil {
mid.AddChild(sc.Body)
}
if !sc.Bars.Right.isEmpty() {
right := NewFrame(mid)
right.SetName("right-bar")
right.Styler(func(s *styles.Style) {
s.Direction = styles.Column
s.Align.Items = styles.Center
s.Grow.Set(0, 1)
})
sc.Bars.Right.call(right)
}
} else {
if sc.Body != nil {
sc.AddChild(sc.Body)
}
}
if !sc.Bars.Bottom.isEmpty() {
foot := NewFrame(sc)
foot.SetName("bottom-bar")
foot.Styler(func(s *styles.Style) {
s.Justify.Content = styles.End
s.Align.Items = styles.Center
s.Grow.Set(1, 0)
})
sc.Bars.Bottom.call(foot)
}
}
func (sc *Scene) addDefaultBars() {
st := sc.Stage
addBack := st.hasBackButton(st.Mains == nil || st.Mains.stack.Len() != 0)
if addBack || st.DisplayTitle {
sc.Bars.Top = slices.Insert(sc.Bars.Top, 0, func(bar *Frame) {
if addBack {
back := NewButton(bar).SetIcon(icons.ArrowBack).SetKey(keymap.HistPrev)
back.SetType(ButtonAction).SetTooltip("Back")
back.OnClick(func(e events.Event) {
sc.Close()
})
}
if st.DisplayTitle {
title := NewText(bar).SetType(TextHeadlineSmall)
title.Updater(func() {
title.SetText(sc.Body.Title)
})
}
})
}
}
//////// Scene wrappers
// AddTopBar adds the given function for configuring a control bar
// at the top of the window
func (bd *Body) AddTopBar(fun func(bar *Frame)) {
bd.Scene.Bars.Top.Add(fun)
}
// AddLeftBar adds the given function for configuring a control bar
// on the left of the window
func (bd *Body) AddLeftBar(fun func(bar *Frame)) {
bd.Scene.Bars.Left.Add(fun)
}
// AddRightBar adds the given function for configuring a control bar
// on the right of the window
func (bd *Body) AddRightBar(fun func(bar *Frame)) {
bd.Scene.Bars.Right.Add(fun)
}
// AddBottomBar adds the given function for configuring a control bar
// at the bottom of the window
func (bd *Body) AddBottomBar(fun func(bar *Frame)) {
bd.Scene.Bars.Bottom.Add(fun)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"cogentcore.org/core/base/errors"
"cogentcore.org/core/styles"
"cogentcore.org/core/tree"
)
// Body holds the primary content of a [Scene].
// It is the main container for app content.
type Body struct { //core:no-new
Frame
// Title is the title of the body, which is also
// used for the window title where relevant.
Title string `set:"-"`
}
// NewBody creates a new [Body] that will serve as the content of a [Scene]
// (e.g., a Window, Dialog, etc). [Body] forms the central region
// of a [Scene], and has [styles.OverflowAuto] scrollbars by default.
// It will create its own parent [Scene] at this point, and has wrapper
// functions to transparently manage everything that the [Scene]
// typically manages during configuration, so you can usually avoid
// having to access the [Scene] directly. If a name is given, it will
// be used for the name of the window, and a title widget will be created
// with that text if [Stage.DisplayTitle] is true. Also, if the name of
// [TheApp] is unset, it sets it to the given name.
func NewBody(name ...string) *Body {
bd := tree.New[Body]()
nm := "body"
if len(name) > 0 {
nm = name[0]
}
if TheApp.Name() == "" {
if len(name) == 0 {
nm = "Cogent Core" // first one is called Cogent Core by default
}
TheApp.SetName(nm)
}
if AppearanceSettings.Zoom == 0 {
// we load the settings in NewBody so that people can
// add their own settings to AllSettings first
errors.Log(LoadAllSettings())
restoreWorkingDir()
}
bd.SetName(nm)
bd.Title = nm
bd.Scene = newBodyScene(bd)
return bd
}
func (bd *Body) Init() {
bd.Frame.Init()
bd.Styler(func(s *styles.Style) {
s.Overflow.Set(styles.OverflowAuto)
s.Direction = styles.Column
s.Grow.Set(1, 1)
})
}
// SetTitle sets the title in the [Body], [Scene], [Stage], [renderWindow],
// and title widget. This is the one place to change the title for everything.
func (bd *Body) SetTitle(title string) *Body {
bd.Name = title
bd.Title = title
bd.Scene.Name = title
if bd.Scene.Stage != nil {
bd.Scene.Stage.Title = title
win := bd.Scene.RenderWindow()
if win != nil {
win.setName(title)
win.setTitle(title)
}
}
// title widget is contained within the top bar
if tb, ok := bd.Scene.ChildByName("top-bar").(Widget); ok {
tb.AsWidget().Update()
}
return bd
}
// SetData sets the [Body]'s [Scene.Data].
func (bd *Body) SetData(data any) *Body {
bd.Scene.SetData(data)
return bd
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"image"
"log/slog"
"cogentcore.org/core/colors"
"cogentcore.org/core/cursors"
"cogentcore.org/core/events"
"cogentcore.org/core/events/key"
"cogentcore.org/core/icons"
"cogentcore.org/core/keymap"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/tree"
)
// Button is an interactive button with text, an icon, an indicator, a shortcut,
// and/or a menu. The standard behavior is to register a click event handler with
// [WidgetBase.OnClick].
type Button struct { //core:embedder
Frame
// Type is the type of button.
Type ButtonTypes
// Text is the text for the button.
// If it is blank, no text is shown.
Text string
// Icon is the icon for the button.
// If it is "" or [icons.None], no icon is shown.
Icon icons.Icon
// Indicator is the menu indicator icon to present.
// If it is "" or [icons.None],, no indicator is shown.
// It is automatically set to [icons.KeyboardArrowDown]
// when there is a Menu elements present unless it is
// set to [icons.None].
Indicator icons.Icon
// Shortcut is an optional shortcut keyboard chord to trigger this button,
// active in window-wide scope. Avoid conflicts with other shortcuts
// (a log message will be emitted if so). Shortcuts are processed after
// all other processing of keyboard input. Command is automatically translated
// into Meta on macOS and Control on all other platforms. Also see [Button.SetKey].
Shortcut key.Chord
// Menu is a menu constructor function used to build and display
// a menu whenever the button is clicked. There will be no menu
// if it is nil. The constructor function should add buttons
// to the Scene that it is passed. Position is mouse click position.
Menu func(m *Scene, pos image.Point) `json:"-" xml:"-"`
// menuPressed is whether the menu was opened by pressing the mouse
// button on the button, so that the click of releasing it on the
// button does not open it again.
menuPressed bool
}
// ButtonTypes is an enum containing the
// different possible types of buttons.
type ButtonTypes int32 //enums:enum -trim-prefix Button
const (
// ButtonFilled is a filled button with a
// contrasting background color. It should be
// used for prominent actions, typically those
// that are the final in a sequence. It is equivalent
// to Material Design's filled button.
ButtonFilled ButtonTypes = iota
// ButtonTonal is a filled button, similar
// to [ButtonFilled]. It is used for the same purposes,
// but it has a lighter background color and less emphasis.
// It is equivalent to Material Design's filled tonal button.
ButtonTonal
// ButtonElevated is an elevated button with
// a light background color and a shadow.
// It is equivalent to Material Design's elevated button.
ButtonElevated
// ButtonOutlined is an outlined button that is
// used for secondary actions that are still important.
// It is equivalent to Material Design's outlined button.
ButtonOutlined
// ButtonText is a low-importance button with no border,
// background color, or shadow when not being interacted with.
// It renders primary-colored text, and it renders a background
// color and shadow when hovered/focused/active.
// It should only be used for low emphasis
// actions, and you must ensure it stands out from the
// surrounding context sufficiently. It is equivalent
// to Material Design's text button, but it can also
// contain icons and other things.
ButtonText
// ButtonAction is a simple button that typically serves
// as a simple action among a series of other buttons
// (eg: in a toolbar), or as a part of another widget,
// like a spinner or snackbar. It has no border, background color,
// or shadow when not being interacted with. It inherits the text
// color of its parent, and it renders a background when
// hovered/focused/active. You must ensure it stands out from the
// surrounding context sufficiently. It is equivalent to Material Design's
// icon button, but it can also contain text and other things (and frequently does).
ButtonAction
// ButtonMenu is similar to [ButtonAction], but it is designed
// for buttons located in popup menus.
ButtonMenu
)
func (bt *Button) Init() {
bt.Frame.Init()
bt.Styler(func(s *styles.Style) {
s.SetAbilities(true, abilities.Activatable, abilities.Focusable, abilities.Hoverable, abilities.DoubleClickable, abilities.TripleClickable)
if !bt.IsDisabled() {
s.Cursor = cursors.Pointer
}
s.Border.Radius = styles.BorderRadiusFull
s.Padding.Set(units.Dp(10), units.Dp(24))
if bt.Icon.IsSet() {
s.Padding.Left.Dp(16)
if bt.Text == "" {
s.Padding.Right.Dp(16)
}
}
s.Font.Size.Dp(14) // Button font size is used for text font size
s.IconSize.Set(units.Em(18.0 / 14))
s.Gap.Zero()
s.CenterAll()
s.MaxBoxShadow = styles.BoxShadow1()
switch bt.Type {
case ButtonFilled:
s.Background = colors.Scheme.Primary.Base
s.Color = colors.Scheme.Primary.On
s.Border.Offset.Set(units.Dp(2))
case ButtonTonal:
s.Background = colors.Scheme.Secondary.Container
s.Color = colors.Scheme.Secondary.OnContainer
case ButtonElevated:
s.Background = colors.Scheme.SurfaceContainerLow
s.Color = colors.Scheme.Primary.Base
s.MaxBoxShadow = styles.BoxShadow2()
s.BoxShadow = styles.BoxShadow1()
case ButtonOutlined:
s.Color = colors.Scheme.Primary.Base
s.Border.Style.Set(styles.BorderSolid)
s.Border.Width.Set(units.Dp(1))
case ButtonText:
s.Color = colors.Scheme.Primary.Base
case ButtonAction:
s.MaxBoxShadow = styles.BoxShadow0()
case ButtonMenu:
s.Grow.Set(1, 0) // need to go to edge of menu
s.Justify.Content = styles.Start
s.Border.Radius.Zero()
s.Padding.Set(units.Dp(6), units.Dp(12))
s.MaxBoxShadow = styles.BoxShadow0()
}
if s.Is(states.Hovered) {
s.BoxShadow = s.MaxBoxShadow
}
if bt.IsDisabled() {
s.MaxBoxShadow = styles.BoxShadow0()
s.BoxShadow = s.MaxBoxShadow
}
})
bt.SendClickOnEnter()
// on desktop platforms, the menu opens when the mouse button is
// pressed, so that it can be dragged to an item and released on it
// (see [Stage.pressOpened]); a click (releasing it on the button)
// leaves the menu open
bt.On(events.MouseDown, func(e events.Event) {
bt.menuPressed = false
if !bt.HasMenu() || e.MouseButton() != events.Left || TheApp.SystemPlatform().IsMobile() {
return
}
if st := bt.openMenuStage(e); st != nil {
st.pressOpened = true
bt.menuPressed = true
}
})
bt.On(events.MouseUp, func(e events.Event) {
if !bt.posInScBBox(e.Pos()) { // (no click to come)
bt.menuPressed = false
}
})
bt.OnClick(func(e events.Event) {
if bt.menuPressed {
bt.menuPressed = false
e.SetHandled()
return
}
if bt.openMenu(e) {
e.SetHandled()
}
})
bt.OnDoubleClick(func(e events.Event) {
bt.Send(events.Click, e)
})
bt.On(events.TripleClick, func(e events.Event) {
bt.Send(events.Click, e)
})
bt.Updater(func() {
// We must get the shortcuts every time since buttons
// may be added or removed dynamically.
bt.Events().getShortcutsIn(bt)
})
bt.Maker(func(p *tree.Plan) {
// we check if the icons are unset, not if they are nil, so
// that people can manually set it to [icons.None]
if bt.HasMenu() {
if bt.Type == ButtonMenu {
if bt.Indicator == "" {
bt.Indicator = icons.KeyboardArrowRight
}
} else if bt.Text != "" {
if bt.Indicator == "" {
bt.Indicator = icons.KeyboardArrowDown
}
} else {
if bt.Icon == "" {
bt.Icon = icons.Menu
}
}
}
if bt.Icon.IsSet() {
tree.AddAt(p, "icon", func(w *Icon) {
w.Updater(func() {
w.SetIcon(bt.Icon)
})
})
if bt.Text != "" {
tree.AddAt(p, "space", func(w *Space) {})
}
}
if bt.Text != "" {
tree.AddAt(p, "text", func(w *Text) {
w.Styler(func(s *styles.Style) {
s.SetNonSelectable()
s.SetTextWrap(false)
s.FillMargin = false
s.Font.Size = bt.Styles.Font.Size // Directly inherit to override the [Text.Type]-based default
})
w.Updater(func() {
if bt.Type == ButtonMenu {
w.SetType(TextBodyMedium)
} else {
w.SetType(TextLabelLarge)
}
w.SetText(bt.Text)
})
})
}
if bt.Indicator.IsSet() {
tree.AddAt(p, "indicator-stretch", func(w *Stretch) {
w.Styler(func(s *styles.Style) {
s.Min.Set(units.Em(0.2))
if bt.Type == ButtonMenu {
s.Grow.Set(1, 0)
} else {
s.Grow.Set(0, 0)
}
})
})
tree.AddAt(p, "indicator", func(w *Icon) {
w.Styler(func(s *styles.Style) {
s.IconSize.Set(units.Dp(18)) // independent from Em
})
w.Updater(func() {
w.SetIcon(bt.Indicator)
})
})
}
if bt.Type == ButtonMenu && !TheApp.SystemPlatform().IsMobile() {
if !bt.Indicator.IsSet() && bt.Shortcut != "" {
tree.AddAt(p, "shortcut-stretch", func(w *Stretch) {})
tree.AddAt(p, "shortcut", func(w *Text) {
w.Styler(func(s *styles.Style) {
s.SetNonSelectable()
s.SetTextWrap(false)
s.Color = colors.Scheme.OnSurfaceVariant
})
w.Updater(func() {
if bt.Type == ButtonMenu {
w.SetType(TextBodyMedium)
} else {
w.SetType(TextLabelLarge)
}
w.SetText(bt.Shortcut.Label())
})
})
} else if bt.Shortcut != "" {
slog.Error("programmer error: Button: shortcut cannot be used on a sub-menu for", "button", bt)
}
}
})
}
// SetKey sets the shortcut of the button from the given [keymap.Functions].
func (bt *Button) SetKey(kf keymap.Functions) *Button {
bt.SetShortcut(kf.Chord())
return bt
}
// Label returns the text of the button if it is set; otherwise it returns the name.
func (bt *Button) Label() string {
if bt.Text != "" {
return bt.Text
}
return bt.Name
}
// HasMenu returns true if the button has a menu that pops up when it is clicked
// (not that it is in a menu itself; see [ButtonMenu])
func (bt *Button) HasMenu() bool {
return bt.Menu != nil
}
// openMenu opens any menu associated with this element.
// It returns whether any menu was opened.
func (bt *Button) openMenu(e events.Event) bool {
return bt.openMenuStage(e) != nil
}
// openMenuStage opens any menu associated with this element,
// returning its stage, or nil if there is none.
func (bt *Button) openMenuStage(e events.Event) *Stage {
if !bt.HasMenu() {
return nil
}
pos := bt.ContextMenuPos(e)
if indic := bt.ChildByName("indicator", 3); indic != nil {
pos = indic.(Widget).ContextMenuPos(nil) // use the pos
}
m := NewMenu(bt.Menu, bt.This.(Widget), pos)
if m == nil {
return nil
}
m.Run()
return m
}
func (bt *Button) handleClickDismissMenu() {
// note: must be called last so widgets aren't deleted when the click arrives
bt.OnFinal(events.Click, func(e events.Event) {
bt.Scene.Stage.closePopupAndBelow()
})
}
func (bt *Button) WidgetTooltip(pos image.Point) (string, image.Point) {
res := bt.Tooltip
if bt.Shortcut != "" && !TheApp.SystemPlatform().IsMobile() {
res = "[" + bt.Shortcut.Label() + "]"
if bt.Tooltip != "" {
res += " " + bt.Tooltip
}
}
return res, bt.DefaultTooltipPos()
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"cogentcore.org/core/math32"
"cogentcore.org/core/paint"
"cogentcore.org/core/paint/ppath"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/units"
)
// Canvas is a widget that can be arbitrarily drawn to by setting
// its Draw function using [Canvas.SetDraw].
type Canvas struct {
WidgetBase
// Draw is the function used to draw the content of the
// canvas every time that it is rendered. The paint context
// is automatically normalized to the size of the canvas,
// so you should specify points on a 0-1 scale.
Draw func(pc *paint.Painter)
// painter is the paint painter used for drawing.
painter *paint.Painter
}
func (c *Canvas) Init() {
c.WidgetBase.Init()
c.Styler(func(s *styles.Style) {
s.Min.Set(units.Dp(256))
})
}
func (c *Canvas) Render() {
c.WidgetBase.Render()
sz := c.Geom.Size.Actual.Content
c.painter = &c.Scene.Painter
sty := styles.NewPaint()
sty.Transform = math32.Translate2D(c.Geom.Pos.Content.X, c.Geom.Pos.Content.Y).Scale(sz.X, sz.Y)
c.painter.PushContext(sty, nil)
c.painter.VectorEffect = ppath.VectorEffectNonScalingStroke
c.Draw(c.painter)
c.painter.PopContext()
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"errors"
"fmt"
"image"
"log/slog"
"reflect"
"slices"
"strings"
"unicode"
"cogentcore.org/core/base/labels"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/base/strcase"
"cogentcore.org/core/colors"
"cogentcore.org/core/cursors"
"cogentcore.org/core/enums"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/keymap"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/parse/complete"
"cogentcore.org/core/text/text"
"cogentcore.org/core/tree"
"cogentcore.org/core/types"
)
// Chooser is a dropdown selection widget that allows users to choose
// one option among a list of items.
type Chooser struct {
Frame
// Type is the styling type of the chooser.
Type ChooserTypes
// Items are the chooser items available for selection.
Items []ChooserItem
// Icon is an optional icon displayed on the left side of the chooser.
Icon icons.Icon
// Indicator is the icon to use for the indicator displayed on the
// right side of the chooser.
Indicator icons.Icon
// Editable is whether provide a text field for editing the value,
// or just a button for selecting items.
Editable bool
// AllowNew is whether to allow the user to add new items to the
// chooser through the editable textfield (if Editable is set to
// true) and a button at the end of the chooser menu. See also [DefaultNew].
AllowNew bool
// DefaultNew configures the chooser to accept new items, as in
// [AllowNew], and also turns off completion popups and always
// adds new items to the list of items, without prompting.
// Use this for cases where the typical use-case is to enter new values,
// but the history of prior values can also be useful.
DefaultNew bool
// placeholder, if Editable is set to true, is the text that is
// displayed in the text field when it is empty. It must be set
// using [Chooser.SetPlaceholder].
placeholder string `set:"-"`
// ItemsFuncs is a slice of functions to call before showing the items
// of the chooser, which is typically used to configure them
// (eg: if they are based on dynamic data). The functions are called
// in ascending order such that the items added in the first function
// will appear before those added in the last function. Use
// [Chooser.AddItemsFunc] to add a new items function. If at least
// one ItemsFunc is specified, the items of the chooser will be
// cleared before calling the functions.
ItemsFuncs []func() `copier:"-" json:"-" xml:"-" set:"-"`
// CurrentItem is the currently selected item.
CurrentItem ChooserItem `json:"-" xml:"-" set:"-"`
// CurrentIndex is the index of the currently selected item
// in [Chooser.Items].
CurrentIndex int `json:"-" xml:"-" set:"-"`
text *Text
textField *TextField
}
// ChooserItem is an item that can be used in a [Chooser].
type ChooserItem struct {
// Value is the underlying value the chooser item represents.
Value any
// Text is the text displayed to the user for this item.
// If it is empty, then [labels.ToLabel] of [ChooserItem.Value]
// is used instead.
Text string
// Icon is the icon displayed to the user for this item.
Icon icons.Icon
// Tooltip is the tooltip displayed to the user for this item.
Tooltip string
// Func, if non-nil, is a function to call whenever this
// item is selected as the current value of the chooser.
Func func() `json:"-" xml:"-"`
// SeparatorBefore is whether to add a separator before
// this item in the chooser menu.
SeparatorBefore bool
}
// GetText returns the effective text for this chooser item.
// If [ChooserItem.Text] is set, it returns that. Otherwise,
// it returns [labels.ToLabel] of [ChooserItem.Value].
func (ci *ChooserItem) GetText() string {
if ci.Text != "" {
return ci.Text
}
if ci.Value == nil {
return ""
}
return labels.ToLabel(ci.Value)
}
// ChooserTypes is an enum containing the
// different possible types of combo boxes
type ChooserTypes int32 //enums:enum -trim-prefix Chooser
const (
// ChooserFilled represents a filled
// Chooser with a background color
// and a bottom border
ChooserFilled ChooserTypes = iota
// ChooserOutlined represents an outlined
// Chooser with a border on all sides
// and no background color
ChooserOutlined
)
func (ch *Chooser) WidgetValue() any { return ch.CurrentItem.Value }
func (ch *Chooser) SetWidgetValue(value any) error {
rv := reflect.ValueOf(value)
// If the first item is a pointer, we assume that our value should
// be a pointer. Otherwise, it should be a non-pointer value.
if len(ch.Items) > 0 && reflect.TypeOf(ch.Items[0].Value).Kind() == reflect.Pointer {
rv = reflectx.UnderlyingPointer(rv)
} else {
rv = reflectx.Underlying(rv)
}
ch.SetCurrentValue(rv.Interface())
return nil
}
func (ch *Chooser) OnBind(value any, tags reflect.StructTag) {
if e, ok := value.(enums.Enum); ok {
ch.SetEnum(e)
}
}
func (ch *Chooser) Init() {
ch.Frame.Init()
ch.SetIcon(icons.None).SetIndicator(icons.KeyboardArrowDown)
ch.CurrentIndex = -1
ch.Styler(func(s *styles.Style) {
if !s.IsReadOnly() {
s.SetAbilities(true, abilities.Activatable, abilities.Hoverable, abilities.LongHoverable)
if !ch.Editable {
s.SetAbilities(true, abilities.Focusable)
}
}
s.Text.Align = text.Center
s.Border.Radius = styles.BorderRadiusSmall
s.Padding.Set(units.Dp(8), units.Dp(16))
s.IconSize.Set(units.Em(18.0 / 16))
s.CenterAll()
// textfield handles everything
if ch.Editable {
s.RenderBox = false
s.Border = styles.Border{}
s.MaxBorder = s.Border
s.Background = nil
s.StateLayer = 0
s.Padding.Zero()
s.Border.Radius.Zero()
}
if !s.IsReadOnly() {
s.Cursor = cursors.Pointer
switch ch.Type {
case ChooserFilled:
s.Background = colors.Scheme.Secondary.Container
s.Color = colors.Scheme.Secondary.OnContainer
case ChooserOutlined:
if !s.Is(states.Focused) {
s.Border.Style.Set(styles.BorderSolid)
s.Border.Width.Set(units.Dp(1))
s.Border.Color.Set(colors.Scheme.OnSurfaceVariant)
}
}
}
})
ch.OnClick(func(e events.Event) {
if ch.IsReadOnly() {
return
}
if ch.openMenu(e) {
e.SetHandled()
}
})
ch.OnChange(func(e events.Event) {
if ch.CurrentItem.Func != nil {
ch.CurrentItem.Func()
}
})
ch.OnFinal(events.KeyChord, func(e events.Event) {
tf := ch.textField
kf := keymap.Of(e.KeyChord())
if DebugSettings.KeyEventTrace {
slog.Info("Chooser KeyChordEvent", "widget", ch, "keyFunction", kf)
}
switch {
case kf == keymap.MoveUp:
e.SetHandled()
if len(ch.Items) > 0 {
index := ch.CurrentIndex - 1
if index < 0 {
index += len(ch.Items)
}
ch.selectItemEvent(index)
}
case kf == keymap.MoveDown:
e.SetHandled()
if len(ch.Items) > 0 {
index := ch.CurrentIndex + 1
if index >= len(ch.Items) {
index -= len(ch.Items)
}
ch.selectItemEvent(index)
}
case kf == keymap.PageUp:
e.SetHandled()
if len(ch.Items) > 10 {
index := ch.CurrentIndex - 10
for index < 0 {
index += len(ch.Items)
}
ch.selectItemEvent(index)
}
case kf == keymap.PageDown:
e.SetHandled()
if len(ch.Items) > 10 {
index := ch.CurrentIndex + 10
for index >= len(ch.Items) {
index -= len(ch.Items)
}
ch.selectItemEvent(index)
}
case kf == keymap.Enter || (!ch.Editable && e.KeyRune() == ' '):
// if !(kt.Rune == ' ' && chb.Sc.Type == ScCompleter) {
e.SetHandled()
ch.Send(events.Click, e)
// }
default:
if tf == nil {
break
}
// if we don't have anything special to do,
// we just give our key event to our textfield
tf.HandleEvent(e)
}
})
ch.Maker(func(p *tree.Plan) {
// automatically select the first item if we have nothing selected and no placeholder
if !ch.Editable && ch.CurrentIndex < 0 && ch.CurrentItem.Text == "" {
ch.SetCurrentIndex(0)
}
// editable handles through TextField
if ch.Icon.IsSet() && !ch.Editable {
tree.AddAt(p, "icon", func(w *Icon) {
w.Updater(func() {
w.SetIcon(ch.Icon)
})
})
}
if ch.Editable {
tree.AddAt(p, "text-field", func(w *TextField) {
ch.textField = w
ch.text = nil
w.SetPlaceholder(ch.placeholder)
w.Styler(func(s *styles.Style) {
s.Grow = ch.Styles.Grow // we grow like our parent
s.Max.X.Zero() // constrained by parent
if ch.Styles.Min.X.Value > 0 {
// as narrow as the chooser, instead of the min width of
// a text field (as for short values)
s.Min.X = ch.Styles.Min.X
}
if ch.Styles.Max.X.Value > 0 { // and at most as wide
s.Max.X = ch.Styles.Max.X
}
s.SetTextWrap(false)
})
w.SetValidator(func() error {
err := ch.setCurrentText(w.Text())
if err == nil {
ch.SendChange()
}
return err
})
w.OnFocus(func(e events.Event) {
if ch.IsReadOnly() {
return
}
ch.CallItemsFuncs()
})
w.OnClick(func(e events.Event) {
ch.CallItemsFuncs()
w.offerComplete()
})
w.OnKeyChord(func(e events.Event) {
kf := keymap.Of(e.KeyChord())
if kf == keymap.Abort {
if w.error != nil {
w.clear()
w.clearError()
e.SetHandled()
}
}
})
w.Updater(func() {
if w.error != nil {
return // don't override anything when we have an invalid value
}
w.SetText(ch.CurrentItem.GetText()).SetLeadingIcon(ch.Icon).
SetTrailingIcon(ch.Indicator, func(e events.Event) {
ch.openMenu(e)
})
if ch.Type == ChooserFilled {
w.SetType(TextFieldFilled)
} else {
w.SetType(TextFieldOutlined)
}
if ch.DefaultNew && w.complete != nil {
w.complete = nil
} else if !ch.DefaultNew && w.complete == nil {
w.SetCompleter(w, ch.completeMatch, ch.completeEdit)
}
})
w.Maker(func(p *tree.Plan) {
tree.AddInit(p, "trail-icon", func(w *Button) {
w.Styler(func(s *styles.Style) {
s.IconSize.Set(units.Dp(18)) // independent from Em
// indicator does not need to be focused
s.SetAbilities(false, abilities.Focusable)
})
})
})
})
} else {
tree.AddAt(p, "text", func(w *Text) {
ch.text = w
ch.textField = nil
w.Styler(func(s *styles.Style) {
s.SetNonSelectable()
s.SetTextWrap(false)
})
w.Updater(func() {
w.SetText(ch.CurrentItem.GetText())
})
})
}
if ch.Indicator == "" {
ch.Indicator = icons.KeyboardArrowRight
}
// editable handles through TextField
if !ch.Editable && !ch.IsReadOnly() {
tree.AddAt(p, "indicator", func(w *Icon) {
w.Styler(func(s *styles.Style) {
s.IconSize.Set(units.Dp(16)) // independent from Em
s.Justify.Self = styles.End
})
w.Updater(func() {
w.SetIcon(ch.Indicator)
})
})
}
})
}
// AddItemsFunc adds the given function to [Chooser.ItemsFuncs].
// These functions are called before showing the items of the chooser,
// and they are typically used to configure them (eg: if they are based
// on dynamic data). The functions are called in ascending order such
// that the items added in the first function will appear before those
// added in the last function. If at least one ItemsFunc is specified,
// the items of the chooser will be cleared before calling the functions.
func (ch *Chooser) AddItemsFunc(f func()) *Chooser {
ch.ItemsFuncs = append(ch.ItemsFuncs, f)
return ch
}
// CallItemsFuncs calls [Chooser.ItemsFuncs].
func (ch *Chooser) CallItemsFuncs() {
if len(ch.ItemsFuncs) == 0 {
return
}
ch.Items = nil
for _, f := range ch.ItemsFuncs {
f()
}
}
// SetTypes sets the [Chooser.Items] from the given types.
func (ch *Chooser) SetTypes(ts ...*types.Type) *Chooser {
ch.Items = make([]ChooserItem, len(ts))
for i, typ := range ts {
ch.Items[i] = ChooserItem{Value: typ}
}
return ch
}
// SetStrings sets the [Chooser.Items] from the given strings.
func (ch *Chooser) SetStrings(ss ...string) *Chooser {
ch.Items = make([]ChooserItem, len(ss))
for i, s := range ss {
ch.Items[i] = ChooserItem{Value: s}
}
return ch
}
// SetEnums sets the [Chooser.Items] from the given enums.
func (ch *Chooser) SetEnums(es ...enums.Enum) *Chooser {
ch.Items = make([]ChooserItem, len(es))
for i, enum := range es {
str := enum.String()
lbl := strcase.ToSentence(str)
if lb, ok := enum.(labels.Labeler); ok { // its own label, as "iCloud"
lbl = lb.Label()
}
desc := enum.Desc()
// If the documentation does not start with the transformed name, but it does
// start with an uppercase letter, then we assume that the first word of the
// documentation is the correct untransformed name. This fixes
// https://github.com/cogentcore/core/issues/774 (also for Switches).
if !strings.HasPrefix(desc, str) && len(desc) > 0 && unicode.IsUpper(rune(desc[0])) {
str, _, _ = strings.Cut(desc, " ")
}
tip := types.FormatDoc(desc, str, lbl)
ch.Items[i] = ChooserItem{Value: enum, Text: lbl, Tooltip: tip}
}
return ch
}
// SetEnum sets the [Chooser.Items] from the [enums.Enum.Values] of the given enum.
func (ch *Chooser) SetEnum(enum enums.Enum) *Chooser {
return ch.SetEnums(enum.Values()...)
}
// findItem finds the given item value on the list of items and returns its index.
func (ch *Chooser) findItem(it any) int {
for i, v := range ch.Items {
if it == v.Value {
return i
}
}
return -1
}
// SetPlaceholder sets the given placeholder text and
// indicates that nothing has been selected.
func (ch *Chooser) SetPlaceholder(text string) *Chooser {
ch.placeholder = text
if !ch.Editable {
ch.CurrentItem.Text = text
ch.showCurrentItem()
}
ch.CurrentIndex = -1
return ch
}
// TextField returns the text field of an [Chooser.Editable] chooser, or nil
// if it is not editable or not made yet, as for selecting its text.
func (ch *Chooser) TextField() *TextField {
return ch.textField
}
// SetCurrentValue sets the current item and index to those associated with the given value.
// If the given item is not found, it adds it to the items list if it is not "". It also
// sets the text of the chooser to the label of the item.
func (ch *Chooser) SetCurrentValue(value any) *Chooser {
ch.CurrentIndex = ch.findItem(value)
if value != "" && ch.CurrentIndex < 0 { // add to list if not found
ch.CurrentIndex = len(ch.Items)
ch.Items = append(ch.Items, ChooserItem{Value: value})
}
if ch.CurrentIndex >= 0 {
ch.CurrentItem = ch.Items[ch.CurrentIndex]
}
ch.showCurrentItem()
return ch
}
// SetCurrentIndex sets the current index and the item associated with it.
func (ch *Chooser) SetCurrentIndex(index int) *Chooser {
if index < 0 || index >= len(ch.Items) {
return ch
}
ch.CurrentIndex = index
ch.CurrentItem = ch.Items[index]
ch.showCurrentItem()
return ch
}
// setCurrentText sets the current index and item based on the given text string.
// It can only be used for editable choosers.
func (ch *Chooser) setCurrentText(text string) error {
for i, item := range ch.Items {
if text == item.GetText() {
ch.SetCurrentIndex(i)
return nil
}
}
if !ch.AllowNew && !ch.DefaultNew {
return errors.New("unknown value")
}
ch.Items = append(ch.Items, ChooserItem{Value: text})
ch.SetCurrentIndex(len(ch.Items) - 1)
return nil
}
// showCurrentItem updates the display to present the current item.
func (ch *Chooser) showCurrentItem() *Chooser {
if ch.Editable {
tf := ch.textField
if tf != nil {
tf.SetText(ch.CurrentItem.GetText())
}
} else {
text := ch.text
if text != nil {
text.SetText(ch.CurrentItem.GetText()).UpdateWidget()
}
}
if ch.CurrentItem.Icon.IsSet() {
picon := ch.Icon
ch.SetIcon(ch.CurrentItem.Icon)
if ch.Icon != picon {
ch.Update()
}
}
ch.NeedsRender()
return ch
}
// selectItem selects the item at the given index and updates the chooser to display it.
func (ch *Chooser) selectItem(index int) *Chooser {
if ch.This == nil {
return ch
}
ch.SetCurrentIndex(index)
ch.NeedsLayout()
return ch
}
// selectItemEvent selects the item at the given index and updates the chooser to display it.
// It also sends an [events.Change] event to indicate that the value has changed.
func (ch *Chooser) selectItemEvent(index int) *Chooser {
if ch.This == nil {
return ch
}
ch.selectItem(index)
if ch.textField != nil {
ch.textField.validate()
}
ch.SendChange()
return ch
}
// ClearError clears any existing validation error for an editable chooser.
func (ch *Chooser) ClearError() {
tf := ch.textField
if tf == nil {
return
}
tf.clearError()
}
// makeItemsMenu constructs a menu of all the items.
// It is used when the chooser is clicked.
func (ch *Chooser) makeItemsMenu(m *Scene, pos image.Point) {
ch.CallItemsFuncs()
for i, it := range ch.Items {
if it.SeparatorBefore {
NewSeparator(m)
}
bt := NewButton(m).SetText(it.GetText()).SetIcon(it.Icon).SetTooltip(it.Tooltip)
bt.Styler(func(s *styles.Style) {
s.IconSize = ch.Styles.IconSize
// Chooser has a bigger font size by default, so we have to normalize
// to account for the smaller default button font size.
if s.IconSize.X.Unit == units.UnitEm {
s.IconSize.X.Value *= 16.0 / 14
}
if s.IconSize.Y.Unit == units.UnitEm {
s.IconSize.Y.Value *= 16.0 / 14
}
})
bt.SetSelected(i == ch.CurrentIndex)
bt.OnClick(func(e events.Event) {
ch.selectItemEvent(i)
})
}
if ch.AllowNew {
NewSeparator(m)
NewButton(m).SetText("New item").SetIcon(icons.Add).
SetTooltip("Add a new item to the chooser").
OnClick(func(e events.Event) {
d := NewBody("New item")
NewText(d).SetType(TextSupporting).SetText("Add a new item to the chooser")
tf := NewTextField(d)
d.AddBottomBar(func(bar *Frame) {
d.AddCancel(bar)
d.AddOK(bar).SetText("Add").SetIcon(icons.Add).OnClick(func(e events.Event) {
ch.Items = append(ch.Items, ChooserItem{Value: tf.Text()})
ch.selectItemEvent(len(ch.Items) - 1)
})
})
d.RunDialog(ch)
})
}
}
// openMenu opens the chooser menu that displays all of the items.
// It returns false if there are no items.
func (ch *Chooser) openMenu(e events.Event) bool {
pos := ch.ContextMenuPos(e)
if indicator, ok := ch.ChildByName("indicator").(Widget); ok {
pos = indicator.ContextMenuPos(nil) // use the pos
}
m := NewMenu(ch.makeItemsMenu, ch.This.(Widget), pos)
if m == nil {
return false
}
m.Run()
return true
}
func (ch *Chooser) WidgetTooltip(pos image.Point) (string, image.Point) {
if ch.CurrentItem.Tooltip != "" {
return ch.CurrentItem.Tooltip, ch.DefaultTooltipPos()
}
return ch.Tooltip, ch.DefaultTooltipPos()
}
// completeMatch is the [complete.MatchFunc] used for the
// editable text field part of the Chooser (if it exists).
func (ch *Chooser) completeMatch(data any, text string, posLine, posChar int) (md complete.Matches) {
md.Seed = text
comps := make(complete.Completions, len(ch.Items))
for i, item := range ch.Items {
comps[i] = complete.Completion{
Text: item.GetText(),
Desc: item.Tooltip,
Icon: item.Icon,
}
}
md.Matches = complete.MatchSeedCompletion(comps, md.Seed)
if ch.AllowNew && text != "" && !slices.ContainsFunc(md.Matches, func(c complete.Completion) bool {
return c.Text == text
}) {
md.Matches = append(md.Matches, complete.Completion{
Text: text,
Label: "Add " + text,
Icon: icons.Add,
Desc: fmt.Sprintf("Add %q to the chooser", text),
})
}
return md
}
// completeEdit is the [complete.EditFunc] used for the
// editable textfield part of the Chooser (if it exists).
func (ch *Chooser) completeEdit(data any, text string, cursorPos int, completion complete.Completion, seed string) (ed complete.Edit) {
return complete.Edit{
NewText: completion.Text,
ForwardDelete: len([]rune(text)),
}
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"cogentcore.org/core/colors"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/states"
)
// Collapser is a widget that can be collapsed or expanded by a user.
// The [Collapser.Summary] is always visible, and the [Collapser.Details]
// are only visible when the [Collapser] is expanded with [Collapser.Open]
// equal to true.
//
// You can directly add any widgets to the [Collapser.Summary] and [Collapser.Details]
// by specifying one of them as the parent in calls to New{WidgetName}.
// Collapser is similar to HTML's <details> and <summary> tags.
type Collapser struct {
Frame
// Open is whether the collapser is currently expanded. It defaults to false.
Open bool
// Summary is the part of the collapser that is always visible.
Summary *Frame `set:"-"`
// Details is the part of the collapser that is only visible when
// the collapser is expanded.
Details *Frame `set:"-"`
}
func (cl *Collapser) Init() {
cl.Frame.Init()
cl.Styler(func(s *styles.Style) {
s.Direction = styles.Column
s.Grow.Set(1, 0)
})
}
func (cl *Collapser) OnAdd() {
cl.Frame.OnAdd()
cl.Summary = NewFrame(cl)
cl.Summary.Styler(func(s *styles.Style) {
s.Grow.Set(1, 0)
s.Align.Content = styles.Center
s.Align.Items = styles.Center
s.Gap.X.Em(0.1)
})
toggle := NewSwitch(cl.Summary).SetType(SwitchCheckbox).SetIconOn(icons.KeyboardArrowDown).SetIconOff(icons.KeyboardArrowRight)
toggle.SetName("toggle")
Bind(&cl.Open, toggle)
toggle.Styler(func(s *styles.Style) {
s.Color = colors.Scheme.Primary.Base
s.Padding.Zero()
})
toggle.OnChange(func(e events.Event) {
cl.Update()
})
cl.Details = NewFrame(cl)
cl.Details.Styler(func(s *styles.Style) {
s.Grow.Set(1, 0)
s.Direction = styles.Column
})
cl.Details.Updater(func() {
cl.Details.SetState(!cl.Open, states.Invisible)
})
}
// Copyright (c) 2019, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"log/slog"
"cogentcore.org/core/colors"
"cogentcore.org/core/colors/colormap"
"cogentcore.org/core/colors/gradient"
"cogentcore.org/core/events"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/units"
)
// ColorMapName represents the name of a [colormap.Map],
// which can be edited using a [ColorMapButton].
type ColorMapName string
func (cm ColorMapName) Widget() Value { return NewColorMapButton() }
// ColorMapButton displays a [colormap.Map] and can be clicked on
// to display a dialog for selecting different color map options.
// It represents a [ColorMapName] value.
type ColorMapButton struct {
Button
MapName string
}
func (cm *ColorMapButton) WidgetValue() any { return &cm.MapName }
func (cm *ColorMapButton) Init() {
cm.Button.Init()
cm.Styler(func(s *styles.Style) {
s.Padding.Zero()
s.Min.Set(units.Em(10), units.Em(2))
if cm.MapName == "" {
s.Background = colors.Scheme.OutlineVariant
return
}
cm, ok := colormap.AvailableMaps[cm.MapName]
if !ok {
slog.Error("got invalid color map name", "name", cm.Name)
s.Background = colors.Scheme.OutlineVariant
return
}
g := gradient.NewLinear()
for i := float32(0); i < 1; i += 0.01 {
gc := cm.Map(i)
g.AddStop(gc, i)
}
s.Background = g
})
InitValueButton(cm, false, func(d *Body) {
d.SetTitle("Select a color map")
sl := colormap.AvailableMapsList()
si := 0
ls := NewList(d).SetSlice(&sl).SetSelectedValue(cm.MapName).BindSelect(&si)
ls.OnChange(func(e events.Event) {
cm.MapName = sl[si]
})
})
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"image/color"
"cogentcore.org/core/base/strcase"
"cogentcore.org/core/colors"
"cogentcore.org/core/colors/cam/hct"
"cogentcore.org/core/colors/gradient"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/tree"
)
// ColorPicker represents a color value with an interactive color picker
// composed of history buttons, a hex input, three HCT sliders, and standard
// named color buttons.
type ColorPicker struct {
Frame
// Color is the current color.
Color hct.HCT `set:"-"`
}
func (cp *ColorPicker) WidgetValue() any { return &cp.Color }
// SetColor sets the color of the color picker.
func (cp *ColorPicker) SetColor(c color.Color) *ColorPicker {
cp.Color = hct.FromColor(c)
return cp
}
var namedColors = []string{"red", "orange", "yellow", "green", "blue", "violet", "sienna"}
func (cp *ColorPicker) Init() {
cp.Frame.Init()
cp.Styler(func(s *styles.Style) {
s.Direction = styles.Column
s.Grow.Set(1, 0)
})
colorButton := func(w *Button, c color.Color) {
w.Styler(func(s *styles.Style) {
s.Background = colors.Uniform(c)
s.Padding.Set(units.Dp(ConstantSpacing(16)))
})
w.OnClick(func(e events.Event) {
cp.SetColor(c).UpdateChange()
})
}
tree.AddChild(cp, func(w *Frame) {
tree.AddChild(w, func(w *Button) {
w.SetTooltip("Current color")
colorButton(w, &cp.Color) // a pointer so it updates
})
tree.AddChild(w, func(w *Button) {
w.SetTooltip("Previous color")
colorButton(w, cp.Color) // not a pointer so it does not update
})
tree.AddChild(w, func(w *TextField) {
w.SetTooltip("Hex color")
w.Styler(func(s *styles.Style) {
s.Min.X.Em(6)
s.Max.X.Em(6)
})
w.Updater(func() {
w.SetText(colors.AsHex(cp.Color))
})
w.SetValidator(func() error {
c, err := colors.FromHex(w.Text())
if err != nil {
return err
}
cp.SetColor(c).UpdateChange()
return nil
})
})
})
sf := func(s *styles.Style) {
s.Min.Y.Em(2)
s.Min.X.Em(6)
s.Max.X.Em(40)
s.Grow.Set(1, 0)
}
tree.AddChild(cp, func(w *Slider) {
Bind(&cp.Color.Hue, w)
w.SetMin(0).SetMax(360)
w.SetTooltip("The hue, which is the spectral identity of the color (red, green, blue, etc) in degrees")
w.OnInput(func(e events.Event) {
cp.Color.SetHue(w.Value)
cp.UpdateInput()
})
w.OnChange(func(e events.Event) {
cp.Color.SetHue(w.Value)
cp.UpdateChange()
})
w.Styler(func(s *styles.Style) {
w.ValueColor = nil
w.ThumbColor = colors.Uniform(cp.Color)
g := gradient.NewLinear()
for h := float32(0); h <= 360; h += 5 {
gc := cp.Color.WithHue(h)
g.AddStop(gc.AsRGBA(), h/360)
}
s.Background = g
})
w.FinalStyler(sf)
})
tree.AddChild(cp, func(w *Slider) {
Bind(&cp.Color.Chroma, w)
w.SetMin(0).SetMax(120)
w.SetTooltip("The chroma, which is the colorfulness/saturation of the color")
w.Updater(func() {
w.SetMax(cp.Color.MaximumChroma())
})
w.OnInput(func(e events.Event) {
cp.Color.SetChroma(w.Value)
cp.UpdateInput()
})
w.OnChange(func(e events.Event) {
cp.Color.SetChroma(w.Value)
cp.UpdateChange()
})
w.Styler(func(s *styles.Style) {
w.ValueColor = nil
w.ThumbColor = colors.Uniform(cp.Color)
g := gradient.NewLinear()
for c := float32(0); c <= w.Max; c += 5 {
gc := cp.Color.WithChroma(c)
g.AddStop(gc.AsRGBA(), c/w.Max)
}
s.Background = g
})
w.FinalStyler(sf)
})
tree.AddChild(cp, func(w *Slider) {
Bind(&cp.Color.Tone, w)
w.SetMin(0).SetMax(100)
w.SetTooltip("The tone, which is the lightness of the color")
w.OnInput(func(e events.Event) {
cp.Color.SetTone(w.Value)
cp.UpdateInput()
})
w.OnChange(func(e events.Event) {
cp.Color.SetTone(w.Value)
cp.UpdateChange()
})
w.Styler(func(s *styles.Style) {
w.ValueColor = nil
w.ThumbColor = colors.Uniform(cp.Color)
g := gradient.NewLinear()
for c := float32(0); c <= 100; c += 5 {
gc := cp.Color.WithTone(c)
g.AddStop(gc.AsRGBA(), c/100)
}
s.Background = g
})
w.FinalStyler(sf)
})
tree.AddChild(cp, func(w *Slider) {
Bind(&cp.Color.A, w)
w.SetMin(0).SetMax(1)
w.SetTooltip("The opacity of the color")
w.OnInput(func(e events.Event) {
cp.Color.SetColor(colors.WithAF32(cp.Color, w.Value))
cp.UpdateInput()
})
w.OnChange(func(e events.Event) {
cp.Color.SetColor(colors.WithAF32(cp.Color, w.Value))
cp.UpdateChange()
})
w.Styler(func(s *styles.Style) {
w.ValueColor = nil
w.ThumbColor = colors.Uniform(cp.Color)
g := gradient.NewLinear()
for c := float32(0); c <= 1; c += 0.05 {
gc := colors.WithAF32(cp.Color, c)
g.AddStop(gc, c)
}
s.Background = g
})
w.FinalStyler(sf)
})
tree.AddChild(cp, func(w *Frame) {
for _, name := range namedColors {
c := colors.Map[name]
tree.AddChildAt(w, name, func(w *Button) {
w.SetTooltip(strcase.ToSentence(name))
colorButton(w, c)
})
}
})
}
// ColorButton represents a color value with a button that opens a [ColorPicker].
type ColorButton struct {
Button
Color color.RGBA
}
func (cb *ColorButton) WidgetValue() any { return &cb.Color }
func (cb *ColorButton) Init() {
cb.Button.Init()
cb.SetType(ButtonTonal).SetText("Edit color").SetIcon(icons.Colors)
cb.Styler(func(s *styles.Style) {
// we need to display button as non-transparent
// so that it can be seen
dclr := colors.WithAF32(cb.Color, 1)
s.Background = colors.Uniform(dclr)
s.Color = colors.Uniform(hct.ContrastColor(dclr, hct.ContrastAAA))
})
InitValueButton(cb, false, func(d *Body) {
d.SetTitle("Edit color")
cp := NewColorPicker(d).SetColor(cb.Color)
cp.OnChange(func(e events.Event) {
cb.Color = cp.Color.AsRGBA()
})
})
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"html"
"image"
"sync"
"time"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/keymap"
"cogentcore.org/core/text/parse/complete"
)
// Complete holds the current completion data and functions to call for building
// the list of possible completions and for editing text after a completion is selected.
// It also holds the popup [Stage] associated with it.
type Complete struct { //types:add -setters
// function to get the list of possible completions
MatchFunc complete.MatchFunc
// function to get the text to show for lookup
LookupFunc complete.LookupFunc
// function to edit text using the selected completion
EditFunc complete.EditFunc
// the context object that implements the completion functions
Context any
// line number in source that completion is operating on, if relevant
SrcLn int
// character position in source that completion is operating on
SrcCh int
// the list of potential completions
completions complete.Completions
// current completion seed
Seed string
// the user's completion selection
Completion string
// the event listeners for the completer (it sends [events.Select] events)
listeners events.Listeners
// stage is the popup [Stage] associated with the [Complete].
stage *Stage
delayTimer *time.Timer
delayMu sync.Mutex
showMu sync.Mutex
}
// NewComplete returns a new [Complete] object. It does not show it; see [Complete.Show].
func NewComplete() *Complete {
return &Complete{}
}
// IsAboutToShow returns true if the DelayTimer is started for
// preparing to show a completion. note: don't really need to lock
func (c *Complete) IsAboutToShow() bool {
c.delayMu.Lock()
defer c.delayMu.Unlock()
return c.delayTimer != nil
}
// Show is the main call for listing completions.
// Has a builtin delay timer so completions are only shown after
// a delay, which resets every time it is called.
// After delay, Calls ShowNow, which calls MatchFunc
// to get a list of completions and builds the completion popup menu
func (c *Complete) Show(ctx Widget, pos image.Point, text string) {
if c.MatchFunc == nil {
return
}
wait := TimingSettings.CompleteWaitDuration
if c.stage != nil {
c.Cancel()
}
if wait == 0 {
c.showNow(ctx, pos, text)
return
}
c.delayMu.Lock()
if c.delayTimer != nil {
c.delayTimer.Stop()
}
// The context and position of the completion are those at the time
// of the call, as they can change in the event loop meanwhile.
data, ln, ch := c.Context, c.SrcLn, c.SrcCh
c.delayTimer = time.AfterFunc(wait,
func() {
c.showNowAsync(ctx, pos, text, data, ln, ch)
c.delayMu.Lock()
c.delayTimer = nil
c.delayMu.Unlock()
})
c.delayMu.Unlock()
}
// showNow actually calls MatchFunc to get a list of completions and builds the
// completion popup menu. This is the sync version called from
func (c *Complete) showNow(ctx Widget, pos image.Point, text string) {
if c.stage != nil {
c.Cancel()
}
c.showMu.Lock()
defer c.showMu.Unlock()
md := c.MatchFunc(c.Context, text, c.SrcLn, c.SrcCh)
if c.showMatches(ctx, pos, md) {
c.stage.runPopup()
}
}
// showNowAsync actually calls MatchFunc to get a list of completions and builds the
// completion popup menu. This is the Async version for delayed AfterFunc call.
// The matches are found without the lock of the context widget (as
// they can take time), and then the completer is updated and shown with it.
func (c *Complete) showNowAsync(ctx Widget, pos image.Point, text string, data any, ln, ch int) {
md := c.MatchFunc(data, text, ln, ch)
wb := ctx.AsWidget()
if !wb.AsyncLockIfShown() {
return
}
defer wb.AsyncUnlock()
if c.stage != nil {
c.Cancel()
}
c.showMu.Lock()
defer c.showMu.Unlock()
if c.showMatches(ctx, pos, md) {
c.stage.runPopup()
}
}
// showMatches presents the given completions, returning false if there
// are none to show.
func (c *Complete) showMatches(ctx Widget, pos image.Point, md complete.Matches) bool {
c.completions = md.Matches
c.Seed = md.Seed
if len(c.completions) == 0 {
return false
}
if len(c.completions) > AppearanceSettings.MenuMax {
c.completions = c.completions[0:AppearanceSettings.MenuMax]
}
sc := NewScene(ctx.AsTree().Name + "-complete")
StyleMenuScene(sc)
c.stage = NewPopupStage(CompleterStage, sc, ctx).SetPos(pos)
// we forward our key events to the context object
// so that you can keep typing while in a completer
// sc.OnKeyChord(ctx.HandleEvent)
for i := 0; i < len(c.completions); i++ {
cmp := &c.completions[i]
text := cmp.Text
if cmp.Label != "" {
text = cmp.Label
}
icon := cmp.Icon
// the text of a completion is plain text, not markup (as the <...>
// of an email address, or of a Go channel type)
mi := NewButton(sc).SetText(html.EscapeString(text)).SetIcon(icons.Icon(icon))
mi.SetTooltip(cmp.Desc)
mi.OnClick(func(e events.Event) {
c.complete(cmp.Text)
})
mi.OnKeyChord(func(e events.Event) {
kf := keymap.Of(e.KeyChord())
if e.KeyRune() == ' ' {
ctx.AsWidget().HandleEvent(e) // bypass button handler!
}
if kf == keymap.Enter {
e.SetHandled()
c.complete(cmp.Text)
}
})
if i == 0 {
sc.Events.SetStartFocus(mi)
}
}
return true
}
// Cancel cancels any existing or pending completion.
// Call when new events nullify prior completions.
// Returns true if canceled.
func (c *Complete) Cancel() bool {
if c.stage == nil {
return false
}
st := c.stage
c.stage = nil
st.ClosePopup()
return true
}
// Lookup is the main call for doing lookups.
func (c *Complete) Lookup(text string, posLine, posChar int, sc *Scene, pt image.Point) {
if c.LookupFunc == nil || sc == nil {
return
}
// c.Sc = nil
c.LookupFunc(c.Context, text, posLine, posChar) // this processes result directly
}
// complete sends Select event to listeners, indicating that the user has made a
// selection from the list of possible completions.
// This is called inside the main event loop.
func (c *Complete) complete(s string) {
c.Cancel()
c.Completion = s
c.listeners.Call(&events.Base{Typ: events.Select})
}
// OnSelect registers given listener function for [events.Select] events on Value.
// This is the primary notification event for all [Complete] elements.
func (c *Complete) OnSelect(fun func(e events.Event)) {
c.On(events.Select, fun)
}
// On adds an event listener function for the given event type.
func (c *Complete) On(etype events.Types, fun func(e events.Event)) {
c.listeners.Add(etype, fun)
}
// GetCompletion returns the completion with the given text.
func (c *Complete) GetCompletion(s string) complete.Completion {
for _, cc := range c.completions {
if s == cc.Text {
return cc
}
}
return complete.Completion{}
}
// CompleteEditText is a chance to modify the completion selection before it is inserted.
func CompleteEditText(text string, cp int, completion string, seed string) (ed complete.Edit) {
ed.NewText = completion
return ed
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"image"
"cogentcore.org/core/colors"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/tree"
)
// IsInvisible returns whether the widget is not currently seen: it is not
// visible (see [WidgetBase.IsVisible]), or it is covered by a widget that
// is rendered over it (see [WidgetBase.isCovered]), as a dialog in the
// page over a video, or by an opaque widget in the layer of the scene (see
// [sceneLayer]), through which a translucent one is seen. It is more
// expensive than [WidgetBase.IsVisible], as it looks at the widgets of the
// scene for those over it, and is for a widget that renders often by
// itself (as a video does).
func (wb *WidgetBase) IsInvisible() bool {
return !wb.IsVisible() || wb.covered(true)
}
// isCovered returns whether at least half of the visible box of the widget
// is covered by a box that paints over it (with a background, or an image),
// in a widget that is stacked (positioned or of a z-index, see
// [WidgetBase.stacked]) and that is rendered after it: of a higher z-index
// than the stacked widget that it is in (or itself), or of the same one but
// after it in the tree, as in the stacking of the layout of a [Frame]. It
// is covered also by a translucent box, which is the same as an opaque one
// here (rendering the widget would paint over it). The widgets in the layer
// of the scene (see [sceneLayer]) do not cover a widget that is not, which
// is rendered into the image of the scene, under the layer.
func (wb *WidgetBase) isCovered() bool {
return wb.covered(false)
}
// covered returns whether the widget is covered (see
// [WidgetBase.isCovered]), also by the opaque widgets in the layer of the
// scene if seen is true.
func (wb *WidgetBase) covered(seen bool) bool {
covered, _ := wb.coverage(seen)
return covered
}
// coverage returns whether the widget is covered (see [WidgetBase.covered]),
// and the stacked widgets that are rendered over it in the image of the
// scene (not in its layer) that paint over a part of it, in the order of
// the tree: those that it paints over when it is rendered alone (as a
// render group, as a playing video under the controls of a player of a
// page), which are rendered again after it (see [WidgetBase.doNeedsRender]).
func (wb *WidgetBase) coverage(seen bool) (bool, []Widget) {
bb := wb.Geom.TotalBBox
if bb.Empty() || wb.Scene == nil {
return false, nil
}
ancestors := map[*WidgetBase]bool{}
var base *WidgetBase // the stacked widget that it is in, if any
for w := wb; w != nil; w = w.parentWidget() {
ancestors[w] = true
if base == nil && w.stacked() {
base = w
}
}
baseZ := 0
if base != nil {
baseZ = base.Styles.ZIndex
}
half := bb.Dx() * bb.Dy() / 2
passed := base == nil // after the base in the tree
// the widgets in the layer of the scene are composed over the widget
// (if it is not in the layer itself)
layered := wb.Scene.layer.active && !wb.hasFlag(widgetInLayer)
covered := false
var over []Widget
wb.Scene.WidgetWalkDown(func(cw Widget, cwb *WidgetBase) bool {
if cwb == base {
passed = true
}
if covered || cwb == wb || cwb.StateIs(states.Invisible) {
return tree.Break // (skips its children)
}
if ancestors[cwb] || !cwb.stacked() {
return tree.Continue
}
z := cwb.Styles.ZIndex
if z < baseZ || (z == baseZ && (!passed || z < 0)) {
return tree.Break // under it
}
inLayer := layered && cwb.hasFlag(widgetInLayer)
if inLayer && !seen {
return tree.Break
}
area := cwb.coversArea(bb, inLayer)
if area >= half {
covered = true
} else if area > 0 && !inLayer {
over = append(over, cw)
}
return tree.Break // (its children were looked at)
})
return covered, over
}
// coversArea returns the largest area of the given box that a box painted
// by the widget or a widget in it covers, only by an opaque box if opaque.
func (wb *WidgetBase) coversArea(bb image.Rectangle, opaque bool) int {
area := 0
wb.WidgetWalkDown(func(cw Widget, cwb *WidgetBase) bool {
if cwb.StateIs(states.Invisible) {
return tree.Break
}
if !cwb.paints() || (opaque && !cwb.paintsOpaque()) {
return tree.Continue
}
r := cwb.Geom.TotalBBox.Intersect(bb)
area = max(area, r.Dx()*r.Dy())
return tree.Continue
})
return area
}
// paints returns whether the widget paints its box: it has a background
// that is not transparent, or it is an image with an image.
func (wb *WidgetBase) paints() bool {
if img, ok := wb.This.(*Image); ok && img.Image != nil {
return true
}
bg := wb.Styles.Background
if bg == nil {
return false
}
if u, ok := bg.(*image.Uniform); ok {
return !colors.IsNil(u.C) && colors.AsRGBA(u.C).A > 0 && wb.Styles.Opacity > 0
}
return true
}
// paintsOpaque returns whether the box that the widget paints (see
// [WidgetBase.paints]) is opaque: an image, or an opaque color.
func (wb *WidgetBase) paintsOpaque() bool {
if img, ok := wb.This.(*Image); ok && img.Image != nil {
return wb.Styles.Opacity >= 1
}
u, ok := wb.Styles.Background.(*image.Uniform)
return ok && colors.AsRGBA(u.C).A == 255 && wb.Styles.Opacity >= 1
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"log/slog"
"reflect"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/colors"
"cogentcore.org/core/events"
"cogentcore.org/core/keymap"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/units"
)
// RunDialog returns and runs a new [DialogStage] that does not take up
// the full window it is created in, in the context of the given widget.
// See [Body.NewDialog] to make a new dialog without running it.
func (bd *Body) RunDialog(ctx Widget) *Stage {
return bd.NewDialog(ctx).Run()
}
// NewDialog returns a new [DialogStage] that does not take up the
// full window it is created in, in the context of the given widget.
// You must call [Stage.Run] to run the dialog; see [Body.RunDialog]
// for a version that automatically runs it.
func (bd *Body) NewDialog(ctx Widget) *Stage {
ctx = nonNilContext(ctx)
bd.dialogStyles()
bd.Scene.Stage = newMainStage(DialogStage, bd.Scene)
bd.Scene.Stage.SetModal(true)
bd.Scene.Stage.SetContext(ctx)
bd.Scene.Stage.Pos = ctx.ContextMenuPos(nil)
return bd.Scene.Stage
}
// RunFullDialog returns and runs a new [DialogStage] that takes up the full
// window it is created in, in the context of the given widget.
// See [Body.NewFullDialog] to make a full dialog without running it.
func (bd *Body) RunFullDialog(ctx Widget) *Stage {
return bd.NewFullDialog(ctx).Run()
}
// NewFullDialog returns a new [DialogStage] that takes up the full
// window it is created in, in the context of the given widget.
// You must call [Stage.Run] to run the dialog; see [Body.RunFullDialog]
// for a version that automatically runs it.
func (bd *Body) NewFullDialog(ctx Widget) *Stage {
bd.dialogStyles()
bd.Scene.Stage = newMainStage(DialogStage, bd.Scene)
bd.Scene.Stage.SetModal(true)
bd.Scene.Stage.SetContext(ctx)
bd.Scene.Stage.SetFullWindow(true)
return bd.Scene.Stage
}
// RunWindowDialog returns and runs a new [DialogStage] that is placed in
// a new system window on multi-window platforms, in the context of the given widget.
// See [Body.NewWindowDialog] to make a dialog window without running it.
func (bd *Body) RunWindowDialog(ctx Widget) *Stage {
return bd.NewWindowDialog(ctx).Run()
}
// NewWindowDialog returns a new [DialogStage] that is placed in
// a new system window on multi-window platforms, in the context of the given widget.
// You must call [Stage.Run] to run the dialog; see [Body.RunWindowDialog]
// for a version that automatically runs it.
func (bd *Body) NewWindowDialog(ctx Widget) *Stage {
bd.NewFullDialog(ctx)
bd.Scene.Stage.SetNewWindow(true)
return bd.Scene.Stage
}
// RecycleDialog looks for a dialog with the given data. If it
// finds it, it shows it and returns true. Otherwise, it returns false.
// See [RecycleMainWindow] for a non-dialog window version.
func RecycleDialog(data any) bool {
rw, got := dialogRenderWindows.findData(data)
if !got {
return false
}
rw.Raise()
return true
}
// MessageDialog opens a new Dialog displaying the given message
// in the context of the given widget. An optional title can be provided.
func MessageDialog(ctx Widget, message string, title ...string) {
ttl := ""
if len(title) > 0 {
ttl = title[0]
}
d := NewBody(ttl)
NewText(d).SetType(TextSupporting).SetText(message)
d.AddOKOnly().RunDialog(ctx)
}
// ErrorDialog opens a new dialog displaying the given error
// in the context of the given widget. An optional title can
// be provided; if it is not, the title will default to
// "There was an error". If the given error is nil, no dialog
// is created.
func ErrorDialog(ctx Widget, err error, title ...string) {
if err == nil {
return
}
ttl := "There was an error"
if len(title) > 0 {
ttl = title[0]
}
// we need to get [errors.CallerInfo] at this level
slog.Error(ttl + ": " + err.Error() + " | " + errors.CallerInfo())
d := NewBody(ttl)
NewText(d).SetType(TextSupporting).SetText(err.Error())
d.AddOKOnly().RunDialog(ctx)
}
// AddOK adds an OK button to the given parent widget (typically in
// [Body.AddBottomBar]), connecting to [keymap.Accept]. Clicking on
// the OK button automatically results in the dialog being closed;
// you can add your own [WidgetBase.OnClick] listener to do things
// beyond that. Also see [Body.AddOKOnly].
func (bd *Body) AddOK(parent Widget) *Button {
bt := NewButton(parent).SetText("OK")
bt.OnFinal(events.Click, func(e events.Event) { // then close
e.SetHandled() // otherwise propagates to dead elements
bd.Close()
})
bd.Scene.OnFirst(events.KeyChord, func(e events.Event) {
kf := keymap.Of(e.KeyChord())
if kf == keymap.Accept {
e.SetHandled()
bt.Send(events.Click, e)
}
})
return bt
}
// AddOKOnly adds an OK button to the bottom bar of the [Body] through
// [Body.AddBottomBar], connecting to [keymap.Accept]. Clicking on the
// OK button automatically results in the dialog being closed. Also see
// [Body.AddOK].
func (bd *Body) AddOKOnly() *Body {
bd.AddBottomBar(func(bar *Frame) { bd.AddOK(bar) })
return bd
}
// AddCancel adds a cancel button to the given parent widget
// (typically in [Body.AddBottomBar]), connecting to [keymap.Abort].
// Clicking on the cancel button automatically results in the dialog
// being closed; you can add your own [WidgetBase.OnClick] listener
// to do things beyond that.
func (bd *Body) AddCancel(parent Widget) *Button {
bt := NewButton(parent).SetType(ButtonOutlined).SetText("Cancel")
bt.OnClick(func(e events.Event) {
e.SetHandled() // otherwise propagates to dead elements
bd.Close()
})
abort := func(e events.Event) {
kf := keymap.Of(e.KeyChord())
if kf == keymap.Abort {
e.SetHandled()
bt.Send(events.Click, e)
bd.Close()
}
}
bd.OnFirst(events.KeyChord, abort)
bt.OnFirst(events.KeyChord, abort)
return bt
}
// Close closes the [Stage] associated with this [Body] (typically for dialogs).
func (bd *Body) Close() {
bd.Scene.Close()
}
// dialogStyles sets default stylers for dialog bodies.
// It is automatically called in [Body.NewDialog].
func (bd *Body) dialogStyles() {
bd.Scene.Styler(func(s *styles.Style) {
s.Direction = styles.Column
s.Color = colors.Scheme.OnSurface
if !bd.Scene.Stage.NewWindow && !bd.Scene.Stage.FullWindow {
s.Padding.Set(units.Dp(24))
s.Border.Radius = styles.BorderRadiusLarge
s.BoxShadow = styles.BoxShadow3()
s.Background = colors.Scheme.SurfaceContainerLow
}
})
}
// nonNilContext returns a non-nil context widget, falling back on the top
// scene of the current window.
func nonNilContext(ctx Widget) Widget {
if !reflectx.IsNil(reflect.ValueOf(ctx)) {
return ctx
}
return getCurrentRenderWindow().mains.top().Scene
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"fmt"
"image"
"path/filepath"
"strings"
"sync"
"cogentcore.org/core/base/fileinfo"
"cogentcore.org/core/base/fileinfo/mimedata"
"cogentcore.org/core/base/fsx"
"cogentcore.org/core/events"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/tree"
"github.com/anthonynsimon/bild/clone"
)
// osDrag is the drag that this app most recently handed off to the
// operating system (see [Events.dragToOS]), so that a drop of it back
// into any window of the app can restore the original source widget
// and data, as for a drag within one window.
var osDrag struct {
sync.Mutex
// source is the widget that started the drag.
source Widget
// data is the drag data given to [Events.DragStart].
data any
// files are the files of the drag, from [Events.SetDragFiles].
files []string
}
// FileDragger is an optional interface for a widget that starts a drag
// with [Events.DragStart] and represents files, which are then provided
// as files to other apps if the drag leaves the window
// (see [Events.SetDragFiles]).
type FileDragger interface {
// DragFiles returns the absolute paths of the files being dragged.
DragFiles() []string
}
// SetDragFiles sets the files for the current drag, as absolute paths.
// If the drag leaves the window, they are provided as files to other
// apps, which can then copy or open them. Otherwise, the drag data from
// [Events.DragStart] is provided, if it is [mimedata.Mimes].
// It must be called after [Events.DragStart].
func (em *Events) SetDragFiles(files ...string) {
em.dragFiles = files
}
// SetDragImage sets the image shown under the mouse for the current drag,
// instead of the image of the widget given to [Events.DragStart], with its
// top-left corner at the mouse. It must be called after [Events.DragStart].
func (em *Events) SetDragImage(img image.Image) {
ms := em.scene.Stage.Main
if ms == nil || img == nil {
return
}
em.dragImage = clone.AsRGBA(img)
sp, ok := ms.Sprites.SpriteByName(dragSpriteName)
if !ok {
return
}
em.addDragSprites(sp.EventBBox.Min)
}
// InWindow returns whether the given position, in window coordinates
// (see [events.Event.WindowPos]), is within the window. A drag that
// leaves the window can be handed off to the operating system, so
// widgets that handle their own mouse dragging can start a drag with
// [Events.DragStart] when the mouse leaves the window, to drag their
// data to other windows and apps.
func (em *Events) InWindow(pos image.Point) bool {
rw := em.RenderWindow()
if rw == nil || rw.SystemWindow == nil {
return true
}
return pos.In(image.Rectangle{Max: rw.SystemWindow.Size()})
}
// handleDragOS handles a mouse event during a drag that may need to be
// handed off to the operating system, when it leaves the window, and
// mouse events while the operating system has the drag.
// It returns true if the event has been handled.
func (em *Events) handleDragOS(e events.Event) bool {
et := e.Type()
if em.dragOS {
switch et {
case events.MouseDrag:
e.SetHandled()
return true
case events.MouseUp: // the OS drag has ended
em.dragOSDroppedNowhere(e)
em.dragOSEnd()
e.SetHandled()
return true
case events.MouseMove: // missed the end of the OS drag
em.dragOSEnd()
}
return false
}
if et != events.MouseDrag || tree.IsNil(em.drag) {
return false
}
return em.dragToOS(e)
}
// dragToOS hands the current drag off to the operating system, if the
// mouse is outside of the window and the platform supports it, so that
// the data can be dropped in other windows and apps.
func (em *Events) dragToOS(e events.Event) bool {
if em.InWindow(e.WindowPos()) {
return false
}
rw := em.RenderWindow()
md, _ := em.dragData.(mimedata.Mimes)
if od, ok := em.drag.(osDragger); ok && md == nil {
md = od.osDragData()
}
if len(md) == 0 && len(em.dragFiles) == 0 {
return false
}
if !rw.SystemWindow.StartDrag(md, em.dragFiles, em.dragImage) {
return false
}
if DebugSettings.EventTrace {
fmt.Println(em.drag, "drag handed off to the operating system")
}
osDrag.Lock()
osDrag.source = em.drag
osDrag.data = em.dragData
osDrag.files = em.dragFiles
osDrag.Unlock()
em.dragOS = true
em.dragClearSprite()
em.dragHoversClear(e)
e.SetHandled()
return true
}
// dragOSEnd is called when a drag handed off to the operating system ends,
// with the release of the mouse button. Any drop has already been sent
// by then, as an external drop event to the window where it happened.
func (em *Events) dragOSEnd() {
em.drag = nil
em.dragData = nil
em.dragImage = nil
em.dragFiles = nil
em.dragOS = false
em.press = nil
em.dragPress = nil
for _, cwb := range em.scene.AllWidgets() {
cwb.dragStateReset()
}
em.scene.Restyle()
}
// dragHoversClear clears the current drag hovers, sending DragLeave to
// each, and resets the drag state of all widgets.
func (em *Events) dragHoversClear(e events.Event) {
em.dragHovers = em.updateHovers(nil, em.dragHovers, e, events.DragEnter, events.DragLeave)
for _, cwb := range em.scene.AllWidgets() {
cwb.dragStateReset()
}
em.scene.Restyle()
}
// handleExternalDrag handles a drag-and-drop event from the operating
// system (see [events.Source.DragExternal]), for a drag from another
// window or app, or from this window after it left the window.
// DragMove updates the drag hovers as for a drag within the window,
// so that the targets show it, and Drop is sent to the deepest
// droppable widget under the mouse. If there is none, it is sent to all
// of the widgets under the mouse, deepest first, until it is handled.
func (em *Events) handleExternalDrag(de *events.DragDrop) {
if de.Typ == events.DragLeave {
em.dragHoversClear(de)
return
}
em.mouseInBBox = nil
em.getMouseInBBox(em.scene, de.Pos(), false)
var hovs []Widget
for _, w := range em.mouseInBBox {
if w.AsWidget().AbilityIs(abilities.Droppable) {
hovs = append(hovs, w)
}
}
if de.Typ == events.DragMove {
em.dragHovers = em.updateHovers(hovs, em.dragHovers, de, events.DragEnter, events.DragLeave)
de.SetHandled()
return
}
if de.Typ != events.Drop {
return
}
em.dragHoversClear(de)
var targ Widget
if len(hovs) > 0 {
targ = hovs[len(hovs)-1]
}
if de.FromApp {
osDrag.Lock()
src, data, files := osDrag.source, osDrag.data, osDrag.files
osDrag.source, osDrag.data, osDrag.files = nil, nil, nil
osDrag.Unlock()
if !tree.IsNil(src) && (targ != nil || len(files) == 0) {
de.Source = src
de.Data = data
}
de.DefaultMod()
} else {
de.DropMod = events.DropCopy
}
if DebugSettings.EventTrace {
fmt.Println(targ, "external Drop with mod:", de.DropMod, "source:", de.Source)
}
if targ != nil {
de.Target = targ
targ.AsWidget().HandleEvent(de)
} else {
for i := len(em.mouseInBBox) - 1; i >= 0 && !de.IsHandled(); i-- {
em.mouseInBBox[i].AsWidget().HandleEvent(de)
}
}
if !de.IsHandled() {
// a tab dropped anywhere in the window goes into its tabs
if td, ok := de.Data.(*tabDrag); ok {
td.dropInScene(em.scene)
}
}
}
// DroppedFiles returns the absolute paths of the existing files
// (and directories) in the given drop: those of the source if it is a [FileDragger],
// and otherwise the text items of the data that are such paths
// (including file:// URLs), as for files dropped from other apps.
func DroppedFiles(de *events.DragDrop) []string {
if fd, ok := de.Source.(FileDragger); ok {
return fd.DragFiles()
}
md, _ := de.Data.(mimedata.Mimes)
var paths []string
for _, d := range md {
if d.Type != fileinfo.TextPlain {
continue
}
p := strings.TrimPrefix(string(d.Data), "file://")
if filepath.IsAbs(p) && fsx.Exists(p) {
paths = append(paths, p)
}
}
return paths
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"image"
"cogentcore.org/core/base/fileinfo/mimedata"
"cogentcore.org/core/events"
"cogentcore.org/core/math32"
"cogentcore.org/core/system"
)
// osDragger is implemented by a widget whose drags have data that is not
// [mimedata.Mimes], to give the data for the operating system to drag
// when a drag of it leaves its window (see [Events.dragToOS]), or nil.
type osDragger interface {
osDragData() mimedata.Mimes
}
// osDropper is implemented by a widget whose drags, handed to the operating
// system (see [Events.dragToOS]), do something when they are dropped where
// nothing accepts them, as onto the desktop: a tab of [Tabs] with
// [Tabs.DragToWindow] then moves into a new window there.
type osDropper interface {
// droppedNowhere is called with the event of the end of the drag, and
// the position of the drop on the screen, in the units of the window
// manager (see [system.Window.Position]).
droppedNowhere(e events.Event, screen image.Point)
}
// dragOSDroppedNowhere calls [osDropper.droppedNowhere] for a drag that
// the operating system has dragged, if it was dropped where nothing
// accepted it, at the position of the given event of its end.
func (em *Events) dragOSDroppedNowhere(e events.Event) {
od, ok := em.drag.(osDropper)
rw := em.RenderWindow()
if !ok || rw == nil || rw.SystemWindow == nil || rw.SystemWindow.DragAccepted() {
return
}
od.droppedNowhere(e, screenPos(rw.SystemWindow, e.WindowPos()))
}
// screenPos returns the position on the screen, in the units of the window
// manager, of the given position in the given window, in its pixels.
func screenPos(w system.Window, pos image.Point) image.Point {
return w.Position(nil).Add(scalePoint(pos, 1/screenPixelRatio(w)))
}
// screenPixelRatio returns the device pixel ratio of the screen of the given
// window: the number of its pixels in a unit of the window manager.
func screenPixelRatio(w system.Window) float32 {
if sc := w.Screen(); sc != nil && sc.DevicePixelRatio > 0 {
return sc.DevicePixelRatio
}
return 1
}
// scalePoint returns the given point scaled by the given factor.
func scalePoint(p image.Point, f float32) image.Point {
return image.Pt(int(math32.Round(float32(p.X)*f)), int(math32.Round(float32(p.Y)*f)))
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"cmp"
"fmt"
"image"
"image/color"
"log"
"log/slog"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"time"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/iox/imagex"
"cogentcore.org/core/base/strcase"
"cogentcore.org/core/colors/gradient"
"cogentcore.org/core/cursors"
"cogentcore.org/core/events"
"cogentcore.org/core/events/key"
"cogentcore.org/core/keymap"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/system"
"cogentcore.org/core/tree"
"github.com/anthonynsimon/bild/clone"
)
// dragSpriteName is the name of the sprite added when dragging an object.
const dragSpriteName = "__DragSprite__"
// dragCopySpriteName is the name of the sprite of the green plus on the
// drag sprite, which shows that the drop would copy.
const dragCopySpriteName = "__DragCopySprite__"
// note: Events should be in exclusive control of its own state
// and IF we end up needing a mutex, it should be global on main
// entry points (HandleEvent, anything else?)
// Events is an event manager that handles incoming events for a [Scene].
// It creates all the derived event types (Hover, Sliding, Dragging)
// and Focus management for keyboard events.
type Events struct {
// scene is the scene that we manage events for.
scene *Scene
// mutex that protects timer variable updates (e.g., hover AfterFunc's).
timerMu sync.Mutex
// stack of sprites with mouse pointer in BBox, with any listeners present.
spriteInBBox []*Sprite
// stack of hovered sprites: have mouse pointer in BBox.
spriteHovers []*Sprite
// currently pressing sprite.
spritePress *Sprite
// currently sliding (dragging) sprite.
spriteSlide *Sprite
// stack of widgets with mouse pointer in BBox, and are not Disabled.
// Last item in the stack is the deepest nested widget (smallest BBox).
mouseInBBox []Widget
// stack of hovered widgets: have mouse pointer in BBox and have Hoverable flag.
hovers []Widget
// lastClickWidget is the last widget that has been clicked on.
lastClickWidget Widget
// lastDoubleClickWidget is the last widget that has been clicked on.
lastDoubleClickWidget Widget
// lastClickTime is the time the last widget was clicked on.
lastClickTime time.Time
// the current candidate for a long hover event.
longHoverWidget Widget
// the position of the mouse at the start of LongHoverTimer.
longHoverPos image.Point
// the timer for the LongHover event, started with time.AfterFunc.
longHoverTimer *time.Timer
// the current candidate for a long press event.
longPressWidget Widget
// the position of the mouse at the start of LongPressTimer.
longPressPos image.Point
// the timer for the LongPress event, started with time.AfterFunc.
longPressTimer *time.Timer
// stack of drag-hovered widgets: have mouse pointer in BBox and have Droppable flag.
dragHovers []Widget
// the deepest widget that was just pressed.
press Widget
// widget receiving mouse dragging events, for drag-n-drop.
drag Widget
// the deepest draggable widget that was just pressed.
dragPress Widget
// widget receiving mouse sliding events.
slide Widget
// the deepest slideable widget that was just pressed.
slidePress Widget
// widget receiving mouse scrolling events, has "scroll focus".
scroll Widget
lastScrollTime time.Time
// widget being held down with RepeatClickable ability.
repeatClick Widget
// the timer for RepeatClickable items.
repeatClickTimer *time.Timer
// widget receiving keyboard events. Use SetFocus.
focus Widget
// currently attended widget. Use SetAttend.
attended Widget
// widget to focus on at start when no other focus has been
// set yet. Use SetStartFocus.
startFocus Widget
// if StartFocus not set, activate starting focus on first element
startFocusFirst bool
// previously focused widget. Was in Focus when FocusClear is called.
prevFocus Widget
// Currently active shortcuts for this window (shortcuts are always window-wide.
// Use widget key event processing for more local key functions)
shortcuts shortcuts
// source data from DragStart event.
dragData any
// dragImage is the image of the drag sprite, from DragStart,
// used for a drag handed off to the operating system.
dragImage *image.RGBA
// dragFiles are the files of the current drag, from SetDragFiles.
dragFiles []string
// dragOS is set when the current drag has been handed off to the
// operating system after leaving the window (see [Events.dragToOS]).
dragOS bool
// dragMoves is whether the last drag moves by default, instead of
// copying, as set by its source (see [DragMover]).
dragMoves bool
// dragCopy is whether the drag sprite shows that the drop would copy.
dragCopy bool
// dragCopyOffset is the offset of the sprite of the green plus from
// the drag sprite.
dragCopyOffset image.Point
}
// DragMover is implemented by widgets with an option for whether dragging
// their items moves them by default, instead of copying them, in which
// case the modifier keys that otherwise move them copy them.
type DragMover interface {
DragMovesDefault() bool
}
// dragMovesFrom returns whether a drag from the given widget moves by
// default, as set by it or the first widget above it that is a [DragMover].
func dragMovesFrom(w Widget) bool {
for n := tree.Node(w); n != nil; n = n.AsTree().Parent {
if dm, ok := n.(DragMover); ok {
return dm.DragMovesDefault()
}
}
return false
}
// mains returns the stack of main stages for our scene.
func (em *Events) mains() *stages {
if em.scene == nil || em.scene.Stage == nil { // no stage when generating HTML
return nil
}
return em.scene.Stage.Mains
}
// RenderWindow returns the overall render window in which we reside,
// which could be nil.
func (em *Events) RenderWindow() *renderWindow {
mgr := em.mains()
if mgr == nil {
return nil
}
return mgr.renderWindow
}
func (em *Events) handleEvent(e events.Event) {
if e.IsHandled() {
return
}
if de, ok := e.(*events.DragDrop); ok {
em.handleExternalDrag(de)
return
}
if !tree.IsNil(em.drag) && e.NeedsFocus() { // the modifier keys of the drop
em.updateDragSprite(dragKeyMods(e))
}
switch {
case e.HasPos():
em.handlePosEvent(e)
case e.NeedsFocus():
em.handleFocusEvent(e)
default: // eg. os events
em.scene.HandleEvent(e)
}
}
func (em *Events) handleFocusEvent(e events.Event) {
// key down and key up can not give active focus, only key chord
if tree.IsNil(em.focus) && e.Type() != events.KeyDown && e.Type() != events.KeyUp {
switch {
case !tree.IsNil(em.startFocus):
if DebugSettings.FocusTrace {
fmt.Println(em.scene, "StartFocus:", em.startFocus)
}
em.setFocus(em.startFocus)
case !tree.IsNil(em.prevFocus):
if DebugSettings.FocusTrace {
fmt.Println(em.scene, "PrevFocus:", em.prevFocus)
}
em.setFocus(em.prevFocus)
em.prevFocus = nil
}
}
if !tree.IsNil(em.focus) {
for k := range em.focus.AsTree().Ancestors() {
wb := AsWidget(k)
if !wb.IsDisplayable() {
break
}
wb.firstHandleEvent(e)
if e.IsHandled() {
break
}
}
if !e.IsHandled() {
em.focus.AsWidget().HandleEvent(e)
}
if !e.IsHandled() {
for k := range em.focus.AsTree().Ancestors() {
wb := AsWidget(k)
if !wb.IsDisplayable() {
break
}
wb.finalHandleEvent(e)
if e.IsHandled() {
break
}
}
}
}
em.managerKeyChordEvents(e)
}
// capturesMouse returns whether the mouse events of the scene go to it
// wherever the mouse is, which they do while a widget of it is sliding, or
// can start to slide, until the mouse button is released.
func (em *Events) capturesMouse(e events.Event) bool {
if et := e.Type(); et != events.MouseDrag && et != events.MouseUp {
return false
}
return !tree.IsNil(em.slide) || !tree.IsNil(em.slidePress)
}
func (em *Events) resetOnMouseDown() {
em.press = nil
em.drag = nil
em.dragOS = false
em.dragPress = nil
em.slide = nil
em.slidePress = nil
em.spriteSlide = nil
em.spritePress = nil
em.cancelRepeatClick()
// if we have sent a long hover start event, we send an end
// event (non-nil widget plus nil timer means we already sent)
if !tree.IsNil(em.longHoverWidget) && em.longHoverTimer == nil {
em.longHoverWidget.AsWidget().Send(events.LongHoverEnd)
}
em.longHoverWidget = nil
em.longHoverPos = image.Point{}
if em.longHoverTimer != nil {
em.longHoverTimer.Stop()
em.longHoverTimer = nil
}
}
func (em *Events) handlePosEvent(e events.Event) {
pos := e.Pos()
et := e.Type()
sc := em.scene
if em.handleDragOS(e) {
return
}
switch et {
case events.MouseDown:
em.resetOnMouseDown()
case events.MouseDrag:
if em.spriteSlide != nil {
em.spriteSlide.handleEvent(e)
em.spriteSlide.send(events.SlideMove, e)
e.SetHandled()
em.setCursorFromStyle()
return
}
// A slide continues wherever the mouse moves, as a selection of
// text across texts (see [Text.selectTo]), unless a drag of the
// widget that was pressed can still start out of it (as for the
// index text of a row of a list), which is handled below.
if !tree.IsNil(em.slide) && (tree.IsNil(em.dragPress) || em.slide.AsWidget().posInScBBox(pos)) {
em.slide.AsWidget().HandleEvent(e)
em.slide.AsWidget().Send(events.SlideMove, e)
e.SetHandled()
em.setCursorFromStyle()
return
}
case events.MouseUp:
// a slide of a sprite stops wherever the mouse is released
if sp := em.spriteSlide; sp != nil && !e.WindowPos().In(sp.EventBBox) {
em.spriteSlide = nil
em.spritePress = nil
sp.handleEvent(e)
sp.send(events.SlideStop, e)
e.SetHandled()
em.setCursorFromStyle()
return
}
case events.Scroll:
if !tree.IsNil(em.scroll) {
scInTime := time.Since(em.lastScrollTime) < TimingSettings.ScrollFocusTime
if scInTime {
em.scroll.AsWidget().HandleEvent(e)
if e.IsHandled() {
em.lastScrollTime = time.Now()
}
em.setCursorFromStyle()
return
}
em.scroll = nil
}
}
em.spriteInBBox = nil
em.getSpriteInBBox(sc, e.WindowPos())
if len(em.spriteInBBox) > 0 {
if em.handleSpriteEvent(e) {
em.setCursorFromStyle()
return
}
} else if len(em.spriteHovers) > 0 { // the mouse left them
em.spriteHovers = em.updateSpriteHovers(nil, em.spriteHovers, e, events.MouseEnter, events.MouseLeave)
}
em.mouseInBBox = nil
em.getMouseInScene(sc, pos)
em.mouseInBBox = sortByRenderLayer(em.mouseInBBox)
n := len(em.mouseInBBox)
// A slide continues (or starts) and stops wherever the mouse is.
if n == 0 && (!em.capturesMouse(e) || (et != events.MouseDrag && et != events.MouseUp)) {
if DebugSettings.EventTrace && et != events.MouseMove {
log.Println("Nothing in bbox:", sc.Geom.TotalBBox, "pos:", pos)
}
em.setCursorFromStyle()
return
}
var press, dragPress, slidePress, move, up, repeatClick Widget
slidePriority := false // see [abilities.SlidePriority]
// the widget that has the focus before the press (which may give it to
// another), in which sliding (as selecting the text of a text field that
// is being edited) has priority over dragging the widgets around it (as
// the rows of a tree table)
editing := em.focus
for i := n - 1; i >= 0; i-- {
w := em.mouseInBBox[i]
wb := w.AsWidget()
// we need to handle this here and not in [Events.GetMouseInBBox] so that
// we correctly process cursors for disabled elements.
// in ScRenderBBoxes, everyone is effectively enabled
if wb.StateIs(states.Disabled) && !sc.renderBBoxes {
continue
}
// everyone gets the primary event who is in scope, deepest first
if et == events.Scroll {
if wb.AbilityIs(abilities.ScrollableUnattended) || (wb.StateIs(states.Focused) || wb.StateIs(states.Attended)) {
w.AsWidget().HandleEvent(e)
}
} else {
w.AsWidget().HandleEvent(e)
}
if tree.IsNil(w) { // died while handling
continue
}
switch et {
case events.MouseMove:
em.scroll = nil
if tree.IsNil(move) && wb.Styles.Abilities.IsHoverable() {
move = w
}
case events.MouseDown:
em.scroll = nil
// in ScRenderBBoxes, everyone is effectively pressable
if tree.IsNil(press) && (wb.Styles.Abilities.IsPressable() || sc.renderBBoxes) {
press = w
}
if tree.IsNil(dragPress) && !slidePriority && wb.AbilityIs(abilities.Draggable) {
dragPress = w
}
if tree.IsNil(slidePress) && wb.AbilityIs(abilities.Slideable) {
// On mobile, sliding results in scrolling, so we must have the appropriate
// scrolling attention to allow sliding.
if TheApp.SystemPlatform().IsMobile() && !wb.AbilityIs(abilities.ScrollableUnattended) && !wb.StateIs(states.Focused) && !wb.StateIs(states.Attended) {
continue
}
slidePress = w
slidePriority = wb.AbilityIs(abilities.SlidePriority) || (!tree.IsNil(editing) && w == editing)
}
if repeatClick == nil && wb.Styles.Abilities.Is(abilities.RepeatClickable) {
repeatClick = w
}
case events.MouseUp:
em.scroll = nil
// in ScRenderBBoxes, everyone is effectively pressable
if tree.IsNil(up) && (wb.Styles.Abilities.IsPressable() || sc.renderBBoxes) {
up = w
}
case events.Scroll:
if !wb.AbilityIs(abilities.ScrollableUnattended) && !wb.StateIs(states.Focused) && !wb.StateIs(states.Attended) {
continue
}
if e.IsHandled() {
if tree.IsNil(em.scroll) {
em.scroll = w
em.lastScrollTime = time.Now()
}
}
}
}
switch et {
case events.MouseDown:
if !tree.IsNil(press) {
em.press = press
em.setAttend(press)
}
if !tree.IsNil(dragPress) {
em.dragPress = dragPress
}
if !tree.IsNil(slidePress) {
em.slidePress = slidePress
}
if !tree.IsNil(repeatClick) {
em.repeatClick = repeatClick
em.startRepeatClickTimer()
}
// a long press of an earlier press whose release went elsewhere
// (as to a menu that it opened) is over: otherwise this press of
// the same widget would continue it, and its click would be lost
if !tree.IsNil(em.longPressWidget) && em.longPressTimer == nil {
em.cancelLongPress()
}
em.handleLongPress(e)
case events.MouseMove:
hovs := make([]Widget, 0, len(em.mouseInBBox))
for _, w := range em.mouseInBBox { // requires forward iter through em.MouseInBBox
wb := w.AsWidget()
// in ScRenderBBoxes, everyone is effectively hoverable
if wb.Styles.Abilities.IsHoverable() || sc.renderBBoxes {
hovs = append(hovs, w)
}
}
if !tree.IsNil(em.drag) { // this means we missed the drop
em.dragHovers = em.updateHovers(hovs, em.dragHovers, e, events.DragEnter, events.DragLeave)
em.dragDrop(em.drag, e)
break
}
if sc.renderBBoxes {
pselw := sc.selectedWidget
if len(em.hovers) > 0 {
sc.selectedWidget = em.hovers[len(em.hovers)-1]
} else {
sc.selectedWidget = nil
}
if sc.selectedWidget != pselw {
if !tree.IsNil(pselw) {
pselw.AsWidget().NeedsRender()
}
if !tree.IsNil(sc.selectedWidget) {
sc.selectedWidget.AsWidget().NeedsRender()
}
}
}
em.hovers = em.updateHovers(hovs, em.hovers, e, events.MouseEnter, events.MouseLeave)
em.handleLongHover(e)
case events.MouseDrag:
if !tree.IsNil(em.drag) {
hovs := make([]Widget, 0, len(em.mouseInBBox))
for _, w := range em.mouseInBBox { // requires forward iter through em.MouseInBBox
wb := w.AsWidget()
if wb.AbilityIs(abilities.Droppable) {
hovs = append(hovs, w)
}
}
em.dragHovers = em.updateHovers(hovs, em.dragHovers, e, events.DragEnter, events.DragLeave)
em.dragMove(e) // updates sprite position
em.drag.AsWidget().HandleEvent(e) // raw drag
em.drag.AsWidget().Send(events.DragMove, e) // usually ignored
e.SetHandled()
} else {
if !tree.IsNil(em.dragPress) && em.dragStartCheck(e, TimingSettings.DragStartTime, TimingSettings.DragStartDistance) {
em.cancelRepeatClick()
em.cancelLongPress()
em.dragPress.AsWidget().Send(events.DragStart, e)
e.SetHandled()
} else if !tree.IsNil(em.slidePress) && em.dragStartCheck(e, TimingSettings.SlideStartTime, TimingSettings.DragStartDistance) {
em.cancelRepeatClick()
em.cancelLongPress()
if em.slide != nil { // it continues (see above)
em.slide.AsWidget().Send(events.SlideMove, e)
} else {
em.slide = em.slidePress
em.slide.AsWidget().Send(events.SlideStart, e)
}
e.SetHandled()
}
}
// if we already have a long press widget, we update it based on our dragging movement
if !tree.IsNil(em.longPressWidget) {
em.handleLongPress(e)
}
case events.MouseUp:
em.cancelRepeatClick()
em.slidePress = nil
if !tree.IsNil(em.slide) {
em.slide.AsWidget().Send(events.SlideStop, e)
e.SetHandled()
// the widget pressed where the slide started, as a text field
// in the rows of a list being scrolled, is no longer pressed
if !tree.IsNil(em.press) && em.press != em.slide {
em.press.AsWidget().Send(events.MouseUp, e)
}
em.slide = nil
em.press = nil
}
if !tree.IsNil(em.drag) {
em.dragDrop(em.drag, e)
em.press = nil
}
// if we have sent a long press start event, we don't send click
// events (non-nil widget plus nil timer means we already sent)
if em.press == up && !tree.IsNil(up) && (tree.IsNil(em.longPressWidget) || em.longPressTimer != nil) {
em.cancelLongPress()
switch e.MouseButton() {
case events.Left:
if sc.selectedWidgetChan != nil {
sc.selectedWidgetChan <- up
em.setCursorFromStyle()
return
}
dcInTime := time.Since(em.lastClickTime) < TimingSettings.DoubleClickInterval
em.lastClickTime = time.Now()
sentMulti := false
switch {
case em.lastDoubleClickWidget == up && dcInTime:
tce := e.NewFromClone(events.TripleClick)
for i := n - 1; i >= 0; i-- {
w := em.mouseInBBox[i]
wb := w.AsWidget()
if !wb.StateIs(states.Disabled) && wb.AbilityIs(abilities.TripleClickable) {
sentMulti = true
w.AsWidget().HandleEvent(tce)
break
}
}
case em.lastClickWidget == up && dcInTime:
dce := e.NewFromClone(events.DoubleClick)
for i := n - 1; i >= 0; i-- {
w := em.mouseInBBox[i]
wb := w.AsWidget()
if !wb.StateIs(states.Disabled) && wb.AbilityIs(abilities.DoubleClickable) {
em.lastDoubleClickWidget = up // not actually who gets the event
sentMulti = true
w.AsWidget().HandleEvent(dce)
break
}
}
}
if !sentMulti {
em.lastDoubleClickWidget = nil
em.lastClickWidget = up
up.AsWidget().Send(events.Click, e)
}
case events.Right: // note: automatically gets Control+Left
up.AsWidget().Send(events.ContextMenu, e)
}
}
// if our original pressed widget is different from the one we are
// going up on, then it has not gotten a mouse up event yet, so
// we need to send it one
if em.press != up && !tree.IsNil(em.press) {
em.press.AsWidget().HandleEvent(e)
}
em.press = nil
em.cancelLongPress()
// a mouse up event acts also acts as a mouse leave
// event on mobile, as that is needed to clear any
// hovered state (on a touch device, including on the web),
// of all of the hovered widgets, which are those where the
// touch started if it moved, as in a scroll
if TheApp.SystemPlatform().IsMobile() {
if !tree.IsNil(up) && !slices.Contains(em.hovers, up) {
up.AsWidget().Send(events.MouseLeave, e)
}
for _, h := range em.hovers {
if !tree.IsNil(h) {
h.AsWidget().Send(events.MouseLeave, e)
}
}
em.hovers = nil
}
case events.Scroll:
switch {
case !tree.IsNil(em.slide):
em.slide.AsWidget().HandleEvent(e)
case !tree.IsNil(em.drag):
em.drag.AsWidget().HandleEvent(e)
case !tree.IsNil(em.press):
em.press.AsWidget().HandleEvent(e)
default:
em.scene.HandleEvent(e)
}
}
em.setCursorFromStyle()
}
// updateHovers updates the hovered widgets based on current
// widgets in bounding box.
func (em *Events) updateHovers(hov, prev []Widget, e events.Event, enter, leave events.Types) []Widget {
for _, prv := range prev {
if !slices.Contains(hov, prv) && !tree.IsNil(prv) {
prv.AsWidget().Send(leave, e)
}
}
for _, cur := range hov {
if !slices.Contains(prev, cur) {
cur.AsWidget().Send(enter, e)
}
}
// todo: detect change in top one, use to update cursor
return hov
}
// updateSpriteHovers updates the hovered sprites based on current
// sprites in bounding box.
func (em *Events) updateSpriteHovers(hov, prev []*Sprite, e events.Event, enter, leave events.Types) []*Sprite {
for _, prv := range prev {
if !slices.Contains(hov, prv) {
prv.send(leave, e)
}
}
for _, cur := range hov {
if !slices.Contains(prev, cur) {
cur.send(enter, e)
}
}
return hov
}
// topLongHover returns the top-most LongHoverable widget among the Hovers
func (em *Events) topLongHover() Widget {
var deep Widget
for ri := len(em.hovers) - 1; ri >= 0; ri-- {
h := em.hovers[ri]
if h.AsWidget().AbilityIs(abilities.LongHoverable) {
deep = h
break
}
}
return deep
}
// handleLongHover handles long hover events
func (em *Events) handleLongHover(e events.Event) {
em.handleLong(e, em.topLongHover(), &em.longHoverWidget, &em.longHoverPos, &em.longHoverTimer, events.LongHoverStart, events.LongHoverEnd, TimingSettings.LongHoverTime, TimingSettings.LongHoverStopDistance)
}
// handleLongPress handles long press events
func (em *Events) handleLongPress(e events.Event) {
em.handleLong(e, em.press, &em.longPressWidget, &em.longPressPos, &em.longPressTimer, events.LongPressStart, events.LongPressEnd, TimingSettings.LongPressTime, TimingSettings.LongPressStopDistance)
}
// handleLong is the implementation of [Events.handleLongHover] and
// [EventManger.HandleLongPress]. It handles the logic to do with tracking
// long events using the given pointers to event manager fields and
// constant type, time, and distance properties. It should not need to
// be called by anything except for the aforementioned functions.
func (em *Events) handleLong(e events.Event, deep Widget, w *Widget, pos *image.Point, t **time.Timer, styp, etyp events.Types, stime time.Duration, sdist int) {
em.timerMu.Lock()
defer em.timerMu.Unlock()
// fmt.Println("em:", em.Scene.Name)
clearLong := func() {
if *t != nil {
(*t).Stop() // TODO: do we need to close this?
*t = nil
}
*w = nil
*pos = image.Point{}
// fmt.Println("cleared hover")
}
cpos := e.WindowPos()
dst := int(math32.Hypot(float32(pos.X-cpos.X), float32(pos.Y-cpos.Y)))
// fmt.Println("dist:", dst)
// we have no long hovers, so we must be done
if tree.IsNil(deep) {
// fmt.Println("no deep")
if tree.IsNil(*w) {
// fmt.Println("no lhw")
return
}
// if we have already finished the timer, then we have already
// sent the start event, so we have to send the end one
if *t == nil {
(*w).AsWidget().Send(etyp, e)
}
clearLong()
// fmt.Println("cleared")
return
}
// we still have the current one, so there is nothing to do
// but make sure our position hasn't changed too much
if deep == *w {
// if we haven't gone too far, we have nothing to do
if dst <= sdist {
// fmt.Println("bail on dist:", dst)
return
}
// If we have gone too far, we are done with the long hover and
// we must clear it. However, critically, we do not return, as
// we must make a new tooltip immediately; otherwise, we may end
// up not getting another mouse move event, so we will be on the
// element with no tooltip, which is a bug. Not returning here is
// the solution to https://github.com/cogentcore/core/issues/553
(*w).AsWidget().Send(etyp, e)
clearLong()
// fmt.Println("fallthrough after clear")
}
// if we have changed and still have the timer, we never
// sent a start event, so we just bail
if *t != nil {
clearLong()
// fmt.Println("timer non-nil, cleared")
return
}
// we now know we don't have the timer and thus sent the start
// event already, so we need to send a end event
if !tree.IsNil(*w) {
(*w).AsWidget().Send(etyp, e)
clearLong()
// fmt.Println("lhw, send end, cleared")
return
}
// now we can set it to our new widget
*w = deep
// fmt.Println("setting new:", deep)
*pos = e.WindowPos()
// The window is found here, in the event loop, as the timer function
// can only read the stage of the scene under the render context lock,
// as the scene can be closed in the meantime.
win := em.RenderWindow()
*t = time.AfterFunc(stime, func() {
if win == nil {
return
}
rc := win.renderContext() // have to get this one first
rc.Lock()
defer rc.Unlock()
em.timerMu.Lock() // then can get this
defer em.timerMu.Unlock()
if tree.IsNil(*w) || em.mains() == nil { // the scene was closed
return
}
(*w).AsWidget().Send(styp, e)
// we are done with the timer, and this indicates that
// we have sent a start event
*t = nil
})
}
// getMouseInBBox adds the widgets from the given one down that are under the
// given position to [Events.mouseInBBox], in the order of the tree. If
// layerOnly is true, it only goes into the widgets that are in the layer of
// the scene or have widgets in it (see [Events.getMouseInScene]).
func (em *Events) getMouseInBBox(w Widget, pos image.Point, layerOnly bool) {
wb := w.AsWidget()
wb.WidgetWalkDown(func(cw Widget, cwb *WidgetBase) bool {
// we do not handle disabled here so that
// we correctly process cursors for disabled elements.
// it needs to be handled downstream by anyone who needs it.
if cwb.StateIs(states.Invisible) { // (its ancestors are displayable)
return tree.Break
}
if cwb.Styles.Opacity <= 0 && cwb.Styles.Abilities == 0 {
// it is not rendered, and neither is anything in it (as for
// visibility: hidden in CSS): only a transparent widget that
// is clickable (as a hidden checkbox over a button) gets events
return tree.Break
}
if layerOnly && !cwb.hasFlag(widgetInLayer) && !cwb.hasFlag(widgetHasLayer) {
return tree.Break // nothing of the layer in it
}
if !cwb.posInScBBox(pos) {
if cwb.noClip() {
// its children can be outside of it (as positioned ones,
// as the toggles of the contents of Wikipedia)
return tree.Continue
}
return tree.Break
}
if !cwb.Styles.Abilities.HasFlag(abilities.NoPointerEvents) {
em.mouseInBBox = append(em.mouseInBBox, cw)
}
if cwb.Parts != nil {
em.getMouseInBBox(cwb.Parts, pos, layerOnly)
}
if ly := AsFrame(cw); ly != nil {
for d := math32.X; d <= math32.Y; d++ {
if ly.HasScroll[d] && ly.Scrolls[d] != nil {
sb := ly.Scrolls[d]
em.getMouseInBBox(sb, pos, layerOnly)
}
}
}
return tree.Continue
})
}
// getMouseInScene adds the widgets of the scene under the given position to
// [Events.mouseInBBox] (see [Events.getMouseInBBox]), only those in its layer
// and the widgets that they are in if one of those in the layer is under it
// (see [sceneLayer]), as on a dialog of a web page: the layer is rendered
// over all of the other widgets, so one of them is on top, and the widgets
// under it would not get the events (see [sortByRenderLayer]), so the
// widgets of the page under it are not gone through.
func (em *Events) getMouseInScene(sc *Scene, pos image.Point) {
if sc.layer.active {
em.getMouseInBBox(sc, pos, true)
for _, w := range em.mouseInBBox {
if w.AsWidget().hasFlag(widgetInLayer) {
return
}
}
em.mouseInBBox = em.mouseInBBox[:0]
}
em.getMouseInBBox(sc, pos, false)
}
// WidgetAt returns the widget that mouse events at the given position (in
// the dots of the scene) go to first: the deepest one rendered on top
// there (see [sortByRenderLayer]), as for elementFromPoint in the scripts
// of web pages. It returns nil if there is none.
func (sc *Scene) WidgetAt(pos image.Point) Widget {
em := &sc.Events
saved := em.mouseInBBox
em.mouseInBBox = nil
em.getMouseInScene(sc, pos)
ws := sortByRenderLayer(em.mouseInBBox)
em.mouseInBBox = saved
if len(ws) == 0 {
return nil
}
return ws[len(ws)-1]
}
// sortByRenderLayer sorts the given widgets under the mouse (in the order
// of the tree, with those that are handled first last) by the order in
// which they are rendered (see [WidgetBase.renderOrder]), so that a widget
// that is rendered over another (as one with a position) gets the events.
// Of two widgets, the one in the child of their nearest common ancestor
// that is rendered later is later, as is a widget in another.
// It returns only the widget that is rendered on top and the widgets that
// it is in, as in CSS: the widgets under one that is rendered over them
// (as those under an open menu) do not get the events (as hover).
func sortByRenderLayer(ws []Widget) []Widget {
layered := false
for _, w := range ws {
if renderLayer(w.AsWidget()) != 0 {
layered = true
break
}
}
if !layered {
return ws
}
// path returns the widgets from the root to the given one
path := func(w *WidgetBase) []*WidgetBase {
var p []*WidgetBase
for ; w != nil; w = w.parentWidget() {
p = append(p, w)
}
slices.Reverse(p)
return p
}
paths := make([][]*WidgetBase, len(ws))
for i, w := range ws {
paths[i] = path(w.AsWidget())
}
idx := make([]int, len(ws))
for i := range idx {
idx[i] = i
}
slices.SortStableFunc(idx, func(a, b int) int {
pa, pb := paths[a], paths[b]
for i := 0; i < len(pa) && i < len(pb); i++ {
if pa[i] != pb[i] { // the children of their common ancestor
if c := cmp.Compare(pathLayer(pa, i), pathLayer(pb, i)); c != 0 {
return c
}
break
}
}
return cmp.Compare(a, b) // the order of the tree
})
top := paths[idx[len(idx)-1]]
in := make(map[*WidgetBase]bool, len(top))
for _, w := range top {
in[w] = true
}
sorted := make([]Widget, 0, len(ws))
for _, j := range idx {
if in[ws[j].AsWidget()] {
sorted = append(sorted, ws[j])
}
}
return sorted
}
// pathLayer returns the layer in which the widget at the given index of the
// given path (from the top) is rendered among its siblings (see
// [renderLayer]), or that of a widget in it that is raised to a stacking
// context above it (see [WidgetBase.raisedTo]), which is rendered over the
// widgets after the ones that it is in, if that is higher.
func pathLayer(path []*WidgetBase, i int) int {
l := renderLayer(path[i])
for j := i + 1; j < len(path); j++ {
r := path[j].raisedTo()
if r == nil {
continue
}
for k := range i {
if path[k] == r {
l = max(l, 2+path[j].Styles.ZIndex)
break
}
}
}
return l
}
// renderLayer returns the layer in which the widget is rendered among its
// siblings (see [WidgetBase.renderOrder]): 2 plus its z-index if it is
// positioned (or -1 for a negative z-index), 1 if it floats, or else 0.
func renderLayer(wb *WidgetBase) int {
switch {
case wb.stacked():
if wb.Styles.ZIndex < 0 {
return -1
}
return 2 + wb.Styles.ZIndex
case wb.isFloat():
return 1
}
return 0
}
func (em *Events) cancelLongPress() {
// if we have sent a long press start event, we send an end
// event (non-nil widget plus nil timer means we already sent)
if !tree.IsNil(em.longPressWidget) && em.longPressTimer == nil {
em.longPressWidget.AsWidget().Send(events.LongPressEnd)
}
em.longPressWidget = nil
em.longPressPos = image.Point{}
if em.longPressTimer != nil {
em.longPressTimer.Stop()
em.longPressTimer = nil
}
}
func (em *Events) cancelRepeatClick() {
em.repeatClick = nil
if em.repeatClickTimer != nil {
em.repeatClickTimer.Stop()
em.repeatClickTimer = nil
}
}
func (em *Events) startRepeatClickTimer() {
if tree.IsNil(em.repeatClick) || !em.repeatClick.AsWidget().IsVisible() {
return
}
delay := TimingSettings.RepeatClickTime
if em.repeatClickTimer == nil {
delay *= 8
}
em.repeatClickTimer = time.AfterFunc(delay, func() {
// We are not in the event loop here, so the state of the events
// is only accessed with the lock (as the event loop can cancel the
// repeat click at the same time).
if !em.scene.AsyncLockIfShown() {
return
}
defer em.scene.AsyncUnlock()
if tree.IsNil(em.repeatClick) || !em.repeatClick.AsWidget().IsVisible() {
return
}
em.repeatClick.AsWidget().Send(events.Click)
em.startRepeatClickTimer()
})
}
func (em *Events) dragStartCheck(e events.Event, dur time.Duration, dist int) bool {
since := e.SinceStart()
if since < dur {
return false
}
dst := int(math32.FromPoint(e.StartDelta()).Length())
return dst >= dist
}
// DragStart starts a drag event, capturing a sprite image of the given widget
// and storing the data for later use during Drop.
// A drag does not officially start until this is called.
func (em *Events) DragStart(w Widget, data any, e events.Event) {
em.dragStartFrom(w, w, data, e)
}
// dragStartFrom starts a drag from the given source widget, which gets the
// events of the drag, as [events.DropDeleteSource], with the image of the
// given widget, which can be a part of it, as for a row of a list.
func (em *Events) dragStartFrom(source, image Widget, data any, e events.Event) {
ms := em.scene.Stage.Main
if ms == nil {
return
}
em.drag = source
em.dragData = data
em.slide = nil // a drag replaces any slide in progress
em.dragFiles = nil
if fd, ok := source.(FileDragger); ok {
em.dragFiles = fd.DragFiles()
}
em.dragOS = false
em.dragMoves = dragMovesFrom(source)
em.dragCopy = events.DropModFor(e.Modifiers(), em.dragMoves) == events.DropCopy
// TODO: maybe show the number of items being dragged
em.dragImage = clone.AsRGBA(gradient.ApplyOpacity(grabRenderFrom(image), 0.5))
em.addDragSprites(e.WindowPos())
}
// addDragSprites adds the drag sprite, with the drag image, at the given
// position, and the sprite on it of the green plus, which shows that the
// drop would copy, at its start, which stays in the window for wide images.
// It is at the bottom left, below the mouse pointer at the top left, if
// the image is tall enough.
func (em *Events) addDragSprites(pos image.Point) {
ms := em.scene.Stage.Main
if ms == nil || em.dragImage == nil {
return
}
sp := NewImageSprite(dragSpriteName, pos, em.dragImage)
sp.Active = true
ms.Sprites.Add(sp)
sz := em.dragImage.Bounds().Size()
rv := units.Dp(8)
r := min(int(math32.Ceil(rv.ToDots(&em.scene.Styles.UnitContext))), sz.X/2, sz.Y/2)
if r < 3 {
ms.Sprites.Delete(dragCopySpriteName)
return
}
c := image.Pt(r+1, sz.Y-r-1)
if pointer := 9 * r / 4; c.Y-r < pointer { // too short to be below the pointer, about 18dp
c.Y = r + 1
}
em.dragCopyOffset = c.Sub(image.Pt(r+1, r+1))
cp := NewImageSprite(dragCopySpriteName, pos.Add(em.dragCopyOffset), dragCopyImage(r))
cp.Active = em.dragCopy
ms.Sprites.Add(cp)
}
// dragCopyImage returns the image of the green plus that shows that a drop
// would copy, with the given radius.
func dragCopyImage(r int) *image.RGBA {
img := image.NewRGBA(image.Rect(0, 0, 2*r+3, 2*r+3))
c := image.Pt(r+1, r+1)
arm := r * 3 / 5
w := max(1, r/4)
abs := func(v int) int { return max(v, -v) }
green := color.RGBA{30, 142, 62, 255}
for y := c.Y - r; y <= c.Y+r; y++ {
for x := c.X - r; x <= c.X+r; x++ {
dx, dy := x-c.X, y-c.Y
if dx*dx+dy*dy > r*r {
continue
}
plus := (abs(dx) <= arm && abs(dy) < w) || (abs(dy) <= arm && abs(dx) < w)
if plus {
img.Set(x, y, color.White)
} else {
img.Set(x, y, green)
}
}
}
return img
}
// updateDragSprite shows or hides the green plus on the drag sprite for
// whether the drop would copy, with the given modifier keys.
func (em *Events) updateDragSprite(mods key.Modifiers) {
cp := events.DropModFor(mods, em.dragMoves) == events.DropCopy
if cp == em.dragCopy {
return
}
em.dragCopy = cp
ms := em.scene.Stage.Main
if ms == nil {
return
}
if sp, ok := ms.Sprites.SpriteByName(dragCopySpriteName); ok {
sp.Active = cp
ms.Sprites.SetModified()
em.scene.NeedsRender()
}
}
// dragKeyMods returns the modifier keys after the given key event during a
// drag, as the press or release of a modifier key may not have it yet.
func dragKeyMods(e events.Event) key.Modifiers {
mods := e.Modifiers()
ke, ok := e.(*events.Key)
if !ok {
return mods
}
var m key.Modifiers
switch ke.Code {
case key.CodeLeftShift, key.CodeRightShift:
m = key.Shift
case key.CodeLeftControl, key.CodeRightControl:
m = key.Control
case key.CodeLeftAlt, key.CodeRightAlt:
m = key.Alt
case key.CodeLeftMeta, key.CodeRightMeta:
m = key.Meta
default:
return mods
}
mods.SetFlag(e.Type() == events.KeyDown, m)
return mods
}
// dragMove is generally handled entirely by the event manager
func (em *Events) dragMove(e events.Event) {
ms := em.scene.Stage.Main
if ms == nil {
return
}
sp, ok := ms.Sprites.SpriteByName(dragSpriteName)
if !ok || sp == nil {
fmt.Println("Drag sprite not found")
return
}
em.updateDragSprite(e.Modifiers())
sp.SetPos(e.WindowPos())
if cp, ok := ms.Sprites.SpriteByName(dragCopySpriteName); ok {
cp.SetPos(e.WindowPos().Add(em.dragCopyOffset))
}
for _, w := range em.dragHovers {
w.AsWidget().ScrollToThis()
}
em.scene.NeedsRender()
}
func (em *Events) dragClearSprite() {
ms := em.scene.Stage.Main
if ms == nil {
return
}
ms.Sprites.Delete(dragSpriteName)
ms.Sprites.Delete(dragCopySpriteName)
}
// DragMenuAddModText adds info about key modifiers for a drag drop menu.
func (em *Events) DragMenuAddModText(m *Scene, mod events.DropMods) {
text := ""
switch {
case mod == events.DropCopy && em.dragMoves:
text = "Copy:"
case mod == events.DropCopy:
text = "Copy (use Shift to move):"
case mod == events.DropMove && em.dragMoves:
text = "Move (use Shift to copy):"
case mod == events.DropMove:
text = "Move:"
}
NewText(m).SetType(TextLabelLarge).SetText(text).Styler(func(s *styles.Style) {
s.Margin.Set(units.Em(0.5))
})
}
// dragDrop sends the [events.Drop] event to the top of the DragHovers stack.
// clearing the current dragging sprite before doing anything.
// It is up to the target to call
func (em *Events) dragDrop(drag Widget, e events.Event) {
em.dragClearSprite()
data := em.dragData
em.drag = nil
for _, cwb := range em.scene.AllWidgets() {
cwb.dragStateReset()
}
em.scene.Restyle()
if len(em.dragHovers) == 0 {
if DebugSettings.EventTrace {
fmt.Println(drag, "Drop has no target")
}
return
}
for _, dwi := range em.dragHovers {
dwi.AsWidget().SetState(false, states.DragHovered)
}
targ := em.dragHovers[len(em.dragHovers)-1]
de := events.NewDragDrop(events.Drop, e.(*events.Mouse)) // gets the actual mod at this point
de.DropMod = events.DropModFor(de.Mods, em.dragMoves)
de.Data = data
de.Source = drag
de.Target = targ
if DebugSettings.EventTrace {
fmt.Println(targ, "Drop with mod:", de.DropMod, "source:", de.Source)
}
targ.AsWidget().HandleEvent(de)
}
// DropFinalize should be called as the last step in the Drop event processing,
// to send the DropDeleteSource event to the source in case of DropMod == DropMove.
// Otherwise, nothing actually happens.
func (em *Events) DropFinalize(de *events.DragDrop) {
if de.DropMod != events.DropMove {
return
}
// a copy, so that the drop stays handled for the other listeners of it
dd := *de
dd.Typ = events.DropDeleteSource
dd.ClearHandled()
// the source can be in another window, for a drop from the operating system
src := de.Source.(Widget).AsWidget()
src.runInWindow(em.scene.AsWidget(), func() {
src.HandleEvent(&dd)
})
}
// Clipboard returns the [system.Clipboard], supplying the window context
// if available.
func (em *Events) Clipboard() system.Clipboard {
var gwin system.Window
if win := em.RenderWindow(); win != nil {
gwin = win.SystemWindow
}
return system.TheApp.Clipboard(gwin)
}
// setCursor sets the window cursor to the given [cursors.Cursor].
func (em *Events) setCursor(cur cursors.Cursor) {
win := em.RenderWindow()
if win == nil {
return
}
if !win.isVisible() {
return
}
errors.Log(system.TheApp.Cursor(win.SystemWindow).Set(cur))
}
// setCursorFromStyle sets the window cursor to the cursor of the bottom-most
// widget in the mouseInBBox stack that has a Styles.Cursor set.
// This should be called after every event pass.
func (em *Events) setCursorFromStyle() {
n := len(em.mouseInBBox)
for i := n - 1; i >= 0; i-- {
w := em.mouseInBBox[i]
wb := w.AsWidget()
if wb.Styles.Cursor != cursors.None {
em.setCursor(wb.Styles.Cursor)
break
}
}
}
// focusClear saves current focus to FocusPrev
func (em *Events) focusClear() bool {
if !tree.IsNil(em.focus) {
if DebugSettings.FocusTrace {
fmt.Println(em.scene, "FocusClear:", em.focus)
}
em.prevFocus = em.focus
}
return em.setFocus(nil)
}
// setFocusQuiet sets focus to given item, and returns true if focus changed.
// If item is nil, then nothing has focus.
// This does NOT send the [events.Focus] event to the widget.
// See [Events.setFocus] for version that does send an event.
func (em *Events) setFocusQuiet(w Widget) bool {
if DebugSettings.FocusTrace {
fmt.Println(em.scene, "SetFocus:", w)
}
got := em.setFocusImpl(w, false) // no event
if !got {
if DebugSettings.FocusTrace {
fmt.Println(em.scene, "SetFocus: Failed", w)
}
return false
}
return got
}
// setFocus sets focus to given item, and returns true if focus changed.
// If item is nil, then nothing has focus.
// This sends the [events.Focus] event to the widget.
// See [Events.setFocusQuiet] for a version that does not.
func (em *Events) setFocus(w Widget) bool {
if DebugSettings.FocusTrace {
fmt.Println(em.scene, "SetFocusEvent:", w)
}
got := em.setFocusImpl(w, true) // sends event
if !got {
if DebugSettings.FocusTrace {
fmt.Println(em.scene, "SetFocusEvent: Failed", w)
}
// Focusing the focused widget again (as by tapping it) shows its
// keyboard again, which can have been hidden while it kept the
// focus (as by Done on Android, when there is no next widget).
if !tree.IsNil(w) && w == em.focus && TheApp.SystemPlatform().IsMobile() {
w.AsWidget().showVirtualKeyboard()
}
return false
}
if !tree.IsNil(w) {
w.AsWidget().ScrollToThis()
}
return got
}
// setFocusImpl sets focus to given item -- returns true if focus changed.
// If item is nil, then nothing has focus.
// sendEvent determines whether the events.Focus event is sent to the focused item.
func (em *Events) setFocusImpl(w Widget, sendEvent bool) bool {
cfoc := em.focus
if tree.IsNil(cfoc) {
em.focus = nil
cfoc = nil
}
if !tree.IsNil(cfoc) && !tree.IsNil(w) && cfoc == w {
if DebugSettings.FocusTrace {
fmt.Println(em.scene, "Already Focus:", cfoc)
}
return false
}
if !tree.IsNil(cfoc) {
if DebugSettings.FocusTrace {
fmt.Println(em.scene, "Losing focus:", cfoc)
}
cfoc.AsWidget().Send(events.FocusLost)
}
em.focus = w
if sendEvent && !tree.IsNil(w) {
w.AsWidget().Send(events.Focus)
}
return true
}
// focusNext sets the focus on the next item
// that can accept focus after the current Focus item.
// returns true if a focus item found.
func (em *Events) focusNext() bool {
if tree.IsNil(em.focus) {
return em.focusFirst()
}
return em.FocusNextFrom(em.focus)
}
// FocusNextFrom sets the focus on the next item
// that can accept focus after the given item.
// It returns true if a focus item is found.
func (em *Events) FocusNextFrom(from Widget) bool {
next := widgetNextFunc(from, tabFocusable)
em.setFocus(next)
return !tree.IsNil(next)
}
// tabFocusable returns whether the given widget gets the focus when it is
// moved to the next or previous widget, as with Tab: it is shown, enabled,
// and focusable, and neither it nor a widget it is in has
// [abilities.SkipTab].
func tabFocusable(w Widget) bool {
wb := w.AsWidget()
if !wb.IsDisplayable() || wb.StateIs(states.Disabled) || !wb.AbilityIs(abilities.Focusable) {
return false
}
for n := tree.Node(w); n != nil; n = n.AsTree().Parent {
if pw, ok := n.(Widget); ok && pw.AsWidget().AbilityIs(abilities.SkipTab) {
return false
}
}
return true
}
// focusOnOrNext sets the focus on the given item, or the next one that can
// accept focus; returns true if a new focus item is found.
func (em *Events) focusOnOrNext(foc Widget) bool {
cfoc := em.focus
if cfoc == foc {
return true
}
wb := AsWidget(foc)
if !wb.IsDisplayable() {
return false
}
if wb.AbilityIs(abilities.Focusable) {
em.setFocus(foc)
return true
}
return em.FocusNextFrom(foc)
}
// focusOnOrPrev sets the focus on the given item, or the previous one that can
// accept focus; returns true if a new focus item is found.
func (em *Events) focusOnOrPrev(foc Widget) bool {
cfoc := em.focus
if cfoc == foc {
return true
}
wb := AsWidget(foc)
if !wb.IsDisplayable() {
return false
}
if wb.AbilityIs(abilities.Focusable) {
em.setFocus(foc)
return true
}
return em.focusPrevFrom(foc)
}
// focusPrev sets the focus on the previous item before the
// current focus item.
func (em *Events) focusPrev() bool {
if tree.IsNil(em.focus) {
return em.focusLast()
}
return em.focusPrevFrom(em.focus)
}
// focusPrevFrom sets the focus on the previous item before the given item
// (can be nil).
func (em *Events) focusPrevFrom(from Widget) bool {
prev := widgetPrevFunc(from, tabFocusable)
em.setFocus(prev)
return !tree.IsNil(prev)
}
// focusFirst sets the focus on the first focusable item in the tree.
// returns true if a focusable item was found.
func (em *Events) focusFirst() bool {
return em.FocusNextFrom(em.scene.This.(Widget))
}
// focusLast sets the focus on the last focusable item in the tree.
// returns true if a focusable item was found.
func (em *Events) focusLast() bool {
return em.focusLastFrom(em.scene)
}
// focusLastFrom sets the focus on the last focusable item in the given tree.
// returns true if a focusable item was found.
func (em *Events) focusLastFrom(from Widget) bool {
last := tree.Last(from).(Widget)
return em.focusOnOrPrev(last)
}
// SetStartFocus sets the given item to be the first focus when the window opens.
func (em *Events) SetStartFocus(k Widget) {
em.startFocus = k
}
// activateStartFocus activates start focus if there is no current focus
// and StartFocus is set -- returns true if activated
func (em *Events) activateStartFocus() bool {
if tree.IsNil(em.startFocus) && !em.startFocusFirst {
// fmt.Println("no start focus")
return false
}
sf := em.startFocus
em.startFocus = nil
if tree.IsNil(sf) {
em.focusFirst()
} else {
// fmt.Println("start focus on:", sf)
em.setFocus(sf)
}
return true
}
// setAttend sets attended to given item, and returns true if attended changed.
// If item is nil, then nothing is attended.
// This sends the [events.Attend] event to the widget.
func (em *Events) setAttend(w Widget) bool {
if DebugSettings.FocusTrace {
fmt.Println(em.scene, "SetAttendEvent:", w)
}
got := em.setAttendImpl(w, true) // sends event
if !got {
if DebugSettings.FocusTrace {
fmt.Println(em.scene, "SetAttendEvent: Failed", w)
}
return false
}
return got
}
// setAttendImpl sets attended to given item, and returns true if attended changed.
// If item is nil, then nothing has attended.
// sendEvent determines whether the events.Attend event is sent to the focused item.
func (em *Events) setAttendImpl(w Widget, sendEvent bool) bool {
catd := em.attended
if tree.IsNil(catd) {
em.attended = nil
catd = nil
}
if catd != nil && !tree.IsNil(w) && catd == w {
if DebugSettings.FocusTrace {
fmt.Println(em.scene, "Already Attend:", catd)
}
return false
}
if catd != nil {
if DebugSettings.FocusTrace {
fmt.Println(em.scene, "Losing attend:", catd)
}
catd.AsWidget().Send(events.AttendLost)
}
em.attended = w
if sendEvent && !tree.IsNil(w) {
w.AsWidget().Send(events.Attend)
}
return true
}
// MangerKeyChordEvents handles lower-priority manager-level key events.
// Mainly tab, shift-tab, and Inspector and Settings.
// event will be marked as processed if handled here.
func (em *Events) managerKeyChordEvents(e events.Event) {
if e.IsHandled() {
return
}
if e.Type() != events.KeyChord {
return
}
win := em.RenderWindow()
if win == nil {
return
}
sc := em.scene
cs := e.KeyChord()
kf := keymap.Of(cs)
switch kf {
case keymap.FocusNext: // tab
if em.focusNext() {
e.SetHandled()
}
case keymap.FocusPrev: // shift-tab
if em.focusPrev() {
e.SetHandled()
}
case keymap.Find:
Search(sc, LastSearch, LastUseCase)
e.SetHandled()
case keymap.ContextMenu:
// at the widget: the key event has no position (see [Widget.ContextMenuPos])
if !tree.IsNil(em.focus) {
em.focus.AsWidget().Send(events.ContextMenu, e)
e.SetHandled()
}
case keymap.WinSnapshot:
img := sc.Renderer.Image()
scnm := strings.ReplaceAll(strings.ReplaceAll(strcase.ToKebab(sc.Name), "/", "-"), "•", "-")
dstr := time.Now().Format(time.DateOnly + "-" + "15-04-05")
bnm := filepath.Join(TheApp.AppDataDir(), "screenshot-"+scnm+"-"+dstr)
var sz string
if img != nil {
sz = fmt.Sprint(img.Bounds().Size())
fnm := bnm + ".png"
if errors.Log(imagex.Save(img, fnm)) == nil {
MessageSnackbar(sc, "Saved screenshot to: "+strings.ReplaceAll(fnm, " ", `\ `)+sz)
}
} else {
MessageSnackbar(sc, "Save screenshot: no render image")
}
sc.RenderWidget()
rend := sc.Painter.RenderDone()
svr := paint.NewSVGRenderer(sc.Painter.Size)
sv := svr.Render(rend).Source()
fnm := bnm + ".svg"
errors.Log(os.WriteFile(fnm, sv, 0666))
pdr := paint.NewPDFRenderer(sc.Painter.Size, &sc.Painter.Context().Style.UnitContext)
pd := pdr.Render(rend).Source()
fnm = bnm + ".pdf"
errors.Log(os.WriteFile(fnm, pd, 0666))
sc.SetScene(sc)
sc.Update()
MessageSnackbar(sc, "Saved SVG, PDF screenshots to: "+strings.ReplaceAll(fnm, " ", `\ `)+sz)
e.SetHandled()
case keymap.ZoomIn:
win.stepZoom(1)
e.SetHandled()
case keymap.ZoomOut:
win.stepZoom(-1)
e.SetHandled()
case keymap.Refresh:
e.SetHandled()
system.TheApp.GetScreens()
UpdateAll()
theWindowGeometrySaver.restoreAll()
case keymap.WinFocusNext:
e.SetHandled()
AllRenderWindows.focusNext()
case keymap.New:
if canNewWindow() {
e.SetHandled()
newWindowFrom(sc)
}
}
if !e.IsHandled() {
em.triggerShortcut(cs, e)
}
}
// getShortcutsIn gathers all [Button]s in the given parent widget with
// a shortcut specified. It recursively navigates [Button.Menu]s.
func (em *Events) getShortcutsIn(parent Widget) {
parent.AsWidget().WidgetWalkDown(func(w Widget, wb *WidgetBase) bool {
bt := AsButton(w)
if bt == nil {
return tree.Continue
}
if bt.Shortcut != "" {
em.addShortcut(bt.Shortcut.PlatformChord(), bt)
}
if bt.HasMenu() {
tmps := NewScene()
bt.Menu(tmps, image.Point{})
em.getShortcutsIn(tmps)
}
return tree.Break // there are no buttons in buttons
})
}
// shortcuts is a map between a key chord and a specific Button that can be
// triggered. This mapping must be unique, in that each chord has unique
// Button, and generally each Button only has a single chord as well, though
// this is not strictly enforced. shortcuts are evaluated *after* the
// standard KeyMap event processing, so any conflicts are resolved in favor of
// the local widget's key event processing, with the shortcut only operating
// when no conflicting widgets are in focus. shortcuts are always window-wide
// and are intended for global window / toolbar buttons. Widget-specific key
// functions should be handled directly within widget key event
// processing.
type shortcuts map[key.Chord]*Button
// addShortcut adds the given shortcut for the given button.
func (em *Events) addShortcut(chord key.Chord, bt *Button) {
if chord == "" {
return
}
if em.shortcuts == nil {
em.shortcuts = shortcuts{}
}
chords := strings.SplitSeq(string(chord), "\n")
for c := range chords {
cc := key.Chord(c)
if DebugSettings.KeyEventTrace {
old, exists := em.shortcuts[cc]
if exists && old != bt {
slog.Error("Events.AddShortcut: overwriting duplicate shortcut", "shortcut", cc, "originalButton", old, "newButton", bt)
}
}
em.shortcuts[cc] = bt
}
}
// triggerShortcut attempts to trigger a shortcut, returning true if one was
// triggered, and false otherwise. Also eliminates any shortcuts with deleted
// buttons, and does not trigger for Disabled buttons.
func (em *Events) triggerShortcut(chord key.Chord, e events.Event) bool {
if DebugSettings.KeyEventTrace {
fmt.Printf("Shortcut chord: %v -- looking for button\n", chord)
}
if em.shortcuts == nil {
return false
}
sa, exists := em.shortcuts[chord]
if !exists {
return false
}
if tree.IsNil(sa) {
delete(em.shortcuts, chord)
return false
}
if sa.IsDisabled() {
if DebugSettings.KeyEventTrace {
fmt.Printf("Shortcut chord: %v, button: %v -- is inactive, not fired\n", chord, sa.Text)
}
return false
}
if DebugSettings.KeyEventTrace {
fmt.Printf("Shortcut chord: %v, button: %v triggered\n", chord, sa.Text)
}
e.SetHandled()
prev := em.focus
sa.Send(events.Click)
if em.focus == sa.This && !tree.IsNil(prev) {
// the click focused the button, but the shortcut is not
// for moving the focus to it, as clicking it is
em.setFocusQuiet(prev)
}
return true
}
func (em *Events) getSpriteInBBox(sc *Scene, pos image.Point) {
st := sc.Stage
st.Sprites.Do(func(sl *SpriteList) {
for _, sp := range sl.Values {
if sp == nil || !sp.Active {
continue
}
if sp.listeners == nil {
continue
}
if pos.In(sp.EventBBox) {
em.spriteInBBox = append(em.spriteInBBox, sp)
}
}
})
}
// handleSpriteEvent handles the given event with sprites
// returns true if event was handled
func (em *Events) handleSpriteEvent(e events.Event) bool {
et := e.Type()
loop:
for _, sp := range em.spriteInBBox {
if e.IsHandled() {
break
}
sp.listeners.Call(e) // everyone gets the primary event who is in scope, deepest first
switch et {
case events.MouseDown:
if sp.listeners.HandlesEventType(events.SlideMove) {
e.SetHandled()
em.spriteSlide = sp
em.spriteSlide.send(events.SlideStart, e)
}
if sp.listeners.HandlesEventType(events.Click) {
em.spritePress = sp
}
break loop
case events.MouseUp:
sp.handleEvent(e)
if em.spriteSlide == sp {
sp.send(events.SlideStop, e)
}
if em.spritePress == sp {
sp.send(events.Click, e)
}
}
}
em.spriteHovers = em.updateSpriteHovers(em.spriteInBBox, em.spriteHovers, e, events.MouseEnter, events.MouseLeave)
return e.IsHandled()
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"context"
"fmt"
"image"
"io/fs"
"log"
"log/slog"
"maps"
"os"
"path/filepath"
"reflect"
"strings"
"github.com/mitchellh/go-homedir"
"cogentcore.org/core/base/dirsort"
"cogentcore.org/core/base/elide"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/fileinfo"
"cogentcore.org/core/base/fsx"
"cogentcore.org/core/colors"
"cogentcore.org/core/cursors"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/keymap"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/system"
"cogentcore.org/core/text/parse/complete"
"cogentcore.org/core/tree"
)
// todo:
// * search: use highlighting, not filtering -- < > arrows etc
// * also simple search-while typing in grid?
// * filepicker selector DND is a file:/// url
// FilePicker is a widget for selecting files.
type FilePicker struct {
Frame
// Filterer is an optional filtering function for which files to display.
Filterer FilePickerFilterer `display:"-" json:"-" xml:"-"`
// directory is the absolute path to the directory of files to display.
directory string
// selectedFilename is the name of the currently selected file,
// not including the directory. See [FilePicker.SelectedFile]
// for the full path.
selectedFilename string
// extensions is a list of the target file extensions.
// If there are multiple, they must be comma separated.
// The extensions must include the dot (".") at the start.
// They must be set using [FilePicker.SetExtensions].
extensions string
// extensionMap is a map of lower-cased extensions from Extensions.
// It used for highlighting files with one of these extensions;
// maps onto original Extensions value.
extensionMap map[string]string
// files for current directory
files []*fileinfo.FileInfo
// index of currently selected file in Files list (-1 if none)
selectedIndex int
// stopWatch stops watching the current directory for changes, if set.
stopWatch context.CancelFunc
// Previous path that was processed via UpdateFiles
prevPath string
favoritesTable, filesTable *Table
selectField, extensionField *TextField
}
func (fp *FilePicker) Init() {
fp.Frame.Init()
fp.Styler(func(s *styles.Style) {
s.Direction = styles.Column
s.Grow.Set(1, 1)
})
fp.OnKeyChord(func(e events.Event) {
kf := keymap.Of(e.KeyChord())
if DebugSettings.KeyEventTrace {
slog.Info("FilePicker KeyInput", "widget", fp, "keyFunction", kf)
}
switch kf {
case keymap.Jump, keymap.WordLeft:
e.SetHandled()
fp.directoryUp()
case keymap.Insert, keymap.InsertAfter, keymap.Open, keymap.SelectMode:
e.SetHandled()
if fp.selectFile() {
fp.Send(events.DoubleClick, e) // will close dialog
}
case keymap.Search:
e.SetHandled()
sf := fp.selectField
sf.SetFocus()
}
})
fp.Maker(func(p *tree.Plan) {
if fp.directory == "" {
fp.SetFilename("") // default to current directory
}
if len(recentPaths) == 0 {
openRecentPaths()
}
recentPaths.AddPath(fp.directory, SystemSettings.SavedPathsMax)
saveRecentPaths()
fp.readFiles()
if fp.prevPath != fp.directory {
fp.watchDirectory()
fp.prevPath = fp.directory
}
tree.AddAt(p, "path", func(w *Chooser) {
Bind(&fp.directory, w)
w.SetEditable(true).SetDefaultNew(true)
w.AddItemsFunc(func() {
fp.addRecentPathItems(&w.Items)
})
w.Styler(func(s *styles.Style) {
s.Grow.Set(1, 0)
})
w.OnChange(func(e events.Event) {
fp.updateFilesEvent()
})
})
tree.AddAt(p, "files", func(w *Frame) {
w.Styler(func(s *styles.Style) {
s.Grow.Set(1, 1)
})
w.Maker(fp.makeFilesRow)
})
tree.AddAt(p, "selected", func(w *Frame) {
w.Styler(func(s *styles.Style) {
s.Grow.Set(1, 0)
s.Gap.X.Dp(4)
})
w.Maker(fp.makeSelectedRow)
})
})
}
func (fp *FilePicker) Destroy() {
fp.Frame.Destroy()
if fp.stopWatch != nil {
fp.stopWatch()
fp.stopWatch = nil
}
}
// FilePickerFilterer is a filtering function for files; returns true if the
// file should be visible in the picker, and false if not
type FilePickerFilterer func(fp *FilePicker, fi *fileinfo.FileInfo) bool
// FilePickerDirOnlyFilter is a [FilePickerFilterer] that only shows directories (folders).
func FilePickerDirOnlyFilter(fp *FilePicker, fi *fileinfo.FileInfo) bool {
return fi.IsDir()
}
// FilePickerExtensionOnlyFilter is a [FilePickerFilterer] that only shows files that
// match the target extensions, and directories.
func FilePickerExtensionOnlyFilter(fp *FilePicker, fi *fileinfo.FileInfo) bool {
if fi.IsDir() {
return true
}
ext := strings.ToLower(filepath.Ext(fi.Name))
_, has := fp.extensionMap[ext]
return has
}
// SetFilename sets the directory and filename of the file picker
// from the given filepath.
func (fp *FilePicker) SetFilename(filename string) *FilePicker {
fp.directory, fp.selectedFilename = filepath.Split(filename)
fp.directory = errors.Log1(filepath.Abs(fp.directory))
return fp
}
// SelectedFile returns the full path to the currently selected file.
func (fp *FilePicker) SelectedFile() string {
sf := fp.selectField
sf.editDone()
return filepath.Join(fp.directory, fp.selectedFilename)
}
// SelectedFileInfo returns the currently selected [fileinfo.FileInfo] or nil.
func (fp *FilePicker) SelectedFileInfo() *fileinfo.FileInfo {
if fp.selectedIndex < 0 || fp.selectedIndex >= len(fp.files) {
return nil
}
return fp.files[fp.selectedIndex]
}
// selectFile selects the current file as the selection.
// if a directory it opens the directory and returns false.
// if a file it selects the file and returns true.
// if no selection, returns false.
func (fp *FilePicker) selectFile() bool {
if fi := fp.SelectedFileInfo(); fi != nil {
if fi.IsDir() {
fp.directory = filepath.Join(fp.directory, fi.Name)
fp.selectedFilename = ""
fp.selectedIndex = -1
fp.updateFilesEvent()
return false
}
return true
}
return false
}
func (fp *FilePicker) MakeToolbar(p *tree.Plan) {
tree.Add(p, func(w *FuncButton) {
w.SetFunc(fp.directoryUp).SetIcon(icons.ArrowUpward).SetKey(keymap.Jump).SetText("Up")
})
tree.Add(p, func(w *FuncButton) {
w.SetFunc(fp.addPathToFavorites).SetIcon(icons.Favorite).SetText("Favorite")
})
tree.Add(p, func(w *FuncButton) {
w.SetFunc(fp.updateFilesEvent).SetIcon(icons.Refresh).SetText("Update")
})
tree.Add(p, func(w *FuncButton) {
w.SetFunc(fp.newFolder).SetIcon(icons.CreateNewFolder)
})
}
func (fp *FilePicker) addRecentPathItems(items *[]ChooserItem) {
for _, sp := range recentPaths {
*items = append(*items, ChooserItem{
Value: sp,
})
}
// TODO: file picker reset and edit recent paths buttons not working
// *items = append(*items, ChooserItem{
// Value: "Reset recent paths",
// Icon: icons.Refresh,
// SeparatorBefore: true,
// Func: func() {
// recentPaths = make(FilePaths, 1, SystemSettings.SavedPathsMax)
// recentPaths[0] = fp.directory
// fp.Update()
// },
// })
// *items = append(*items, ChooserItem{
// Value: "Edit recent paths",
// Icon: icons.Edit,
// Func: func() {
// fp.editRecentPaths()
// },
// })
}
func (fp *FilePicker) makeFilesRow(p *tree.Plan) {
tree.AddAt(p, "favorites", func(w *Table) {
fp.favoritesTable = w
w.SelectedIndex = -1
w.SetReadOnly(true)
w.ReadOnlyKeyNav = false // keys must go to files, not favorites
w.Styler(func(s *styles.Style) {
s.Grow.Set(0, 1)
s.Min.X.Ch(25)
s.Overflow.X = styles.OverflowHidden
})
w.SetSlice(&SystemSettings.FavPaths)
w.OnSelect(func(e events.Event) {
fp.favoritesSelect(w.SelectedIndex)
})
w.Updater(func() {
w.ResetSelectedIndexes()
})
})
tree.AddAt(p, "files", func(w *Table) {
fp.filesTable = w
w.SetReadOnly(true)
w.SetSlice(&fp.files)
// the widths of the columns that the user sets are kept for all
// file pickers, of all apps (see [FilePickerSettings]); the table
// only sends a change for them, as it is read only
w.ColumnWidths = loadFilePickerSettings().ColumnWidths
w.OnChange(func(e events.Event) {
widths := maps.Clone(w.ColumnWidths)
errors.Log(updateFilePickerSettings(func(s *FilePickerSettings) {
s.ColumnWidths = widths
}))
})
w.SelectedField = "Name"
w.SelectedValue = fp.selectedFilename
// sorted in the sort order of the directory, which the user sets for
// it, for all apps, by sorting by a column (see [dirsort.For])
w.SortFunc = fp.sortFiles
w.OnSort = func(field string, down bool) {
if by, ok := dirsort.Parse(field); ok {
errors.Log(dirsort.Set(fp.directory, dirsort.Sort{By: by.By, Down: down}))
}
}
w.Updater(func() {
w.SetSortFieldName(dirsort.For(fp.directory).String())
})
w.TableStyler = func(w Widget, s *styles.Style, row, col int) {
fn := fp.files[row].Name
ext := strings.ToLower(filepath.Ext(fn))
if _, has := fp.extensionMap[ext]; has {
s.Color = colors.Scheme.Primary.Base
} else {
s.Color = colors.Scheme.OnSurface
}
}
w.Styler(func(s *styles.Style) {
s.Cursor = cursors.Pointer
s.SetAbilities(true, abilities.Draggable, abilities.Droppable)
})
fp.handleFilesDND(w)
w.OnSelect(func(e events.Event) {
fp.fileSelect(w.SelectedIndex)
})
w.OnDoubleClick(func(e events.Event) {
if w.clickSelectEvent(e) {
if !fp.selectFile() {
e.SetHandled() // don't pass along; keep dialog open
} else {
fp.Scene.sendKey(keymap.Accept, e) // activates Ok button code
}
}
})
w.ContextMenus = nil
w.AddContextMenu(func(m *Scene, pos image.Point) {
open := NewButton(m).SetText("Open").SetIcon(icons.Open)
open.SetTooltip("Open the selected file using the default app")
open.OnClick(func(e events.Event) {
TheApp.OpenURL(fsx.FileURL(fp.SelectedFile()))
})
if TheApp.Platform() == system.Web {
open.SetText("Download").SetIcon(icons.Download).SetTooltip("Download this file to your device")
}
if w.SelectedIndex >= 0 && w.SelectedIndex < len(fp.files) {
if fi := fp.files[w.SelectedIndex]; !fi.IsDir() {
OpenWithMenuItems(m, fi.Path)
}
}
NewSeparator(m)
NewButton(m).SetText("Duplicate").SetIcon(icons.FileCopy).
SetTooltip("Make a copy of the selected file").
OnClick(func(e events.Event) {
fn := fp.files[w.SelectedIndex]
fn.Duplicate()
fp.updateFilesEvent()
})
tip := "Delete moves the selected file to the trash / recycling bin"
if TheApp.Platform().IsMobile() {
tip = "Delete deletes the selected file"
}
NewButton(m).SetText("Delete").SetIcon(icons.Delete).
SetTooltip(tip).
OnClick(func(e events.Event) {
fn := fp.files[w.SelectedIndex]
fb := NewSoloFuncButton(w).SetFunc(fn.Delete).SetConfirm(true).SetAfterFunc(fp.updateFilesEvent)
fb.SetTooltip(tip)
fb.CallFunc()
})
NewButton(m).SetText("Rename").SetIcon(icons.EditNote).
SetTooltip("Rename the selected file").
OnClick(func(e events.Event) {
fn := fp.files[w.SelectedIndex]
NewSoloFuncButton(w).SetFunc(fn.Rename).SetAfterFunc(fp.updateFilesEvent).CallFunc()
})
NewButton(m).SetText("Info").SetIcon(icons.Info).
SetTooltip("View information about the selected file").
OnClick(func(e events.Event) {
fn := fp.files[w.SelectedIndex]
d := NewBody("Info: " + fn.Name)
NewForm(d).SetStruct(&fn).SetReadOnly(true)
d.AddOKOnly().RunWindowDialog(w)
})
NewSeparator(m)
NewFuncButton(m).SetFunc(fp.newFolder).SetIcon(icons.CreateNewFolder)
})
// w.Updater(func() {})
})
}
func (fp *FilePicker) makeSelectedRow(selected *tree.Plan) {
tree.AddAt(selected, "file-text", func(w *Text) {
w.SetText("File: ")
w.SetTooltip("Enter file name here (or select from list above)")
w.Styler(func(s *styles.Style) {
s.SetTextWrap(false)
})
})
tree.AddAt(selected, "file", func(w *TextField) {
fp.selectField = w
w.SetText(fp.selectedFilename)
w.SetTooltip(fmt.Sprintf("Enter the file name. Special keys: up/down to move selection; %s or %s to go up to parent folder; %s or %s or %s or %s to select current file (if directory, goes into it, if file, selects and closes); %s or %s for prev / next history item; %s return to this field", keymap.WordLeft.Label(), keymap.Jump.Label(), keymap.SelectMode.Label(), keymap.Insert.Label(), keymap.InsertAfter.Label(), keymap.Open.Label(), keymap.HistPrev.Label(), keymap.HistNext.Label(), keymap.Search.Label()))
w.SetCompleter(fp, fp.fileComplete, fp.fileCompleteEdit)
w.Styler(func(s *styles.Style) {
s.Min.X.Ch(60)
s.Max.X.Zero()
s.Grow.Set(1, 0)
})
w.OnChange(func(e events.Event) {
fp.setSelectedFile(w.Text())
})
w.OnKeyChord(func(e events.Event) {
kf := keymap.Of(e.KeyChord())
if kf == keymap.Accept {
fp.setSelectedFile(w.Text())
}
})
w.StartFocus()
w.Updater(func() {
w.SetText(fp.selectedFilename)
})
})
tree.AddAt(selected, "extension-text", func(w *Text) {
w.SetText("Extension(s):").SetTooltip("target extension(s) to highlight; if multiple, separate with commas, and include the . at the start")
w.Styler(func(s *styles.Style) {
s.SetTextWrap(false)
})
})
tree.AddAt(selected, "extension", func(w *TextField) {
fp.extensionField = w
w.SetText(fp.extensions)
w.OnChange(func(e events.Event) {
fp.SetExtensions(w.Text()).Update()
})
})
}
// watchDirectory starts watching the current directory for changes
// to its files, updating the file picker after them, and stops
// watching any previous directory.
func (fp *FilePicker) watchDirectory() {
if fp.stopWatch != nil {
fp.stopWatch()
fp.stopWatch = nil
}
ctx, cancel := context.WithCancel(context.Background())
err := watchFilePickerDir(ctx, fp.directory, func() {
// We are not in the event loop, so we update with the lock,
// only if the file picker is still shown.
if fp.AsyncLockIfShown() {
fp.Update()
fp.AsyncUnlock()
}
})
if err != nil {
cancel()
return // e.g., a directory that does not exist
}
fp.stopWatch = cancel
}
// updateFilesEvent updates the list of files and other views for the current path.
func (fp *FilePicker) updateFilesEvent() { //types:add
fp.readFiles()
fp.Update()
// sf := fv.SelectField()
// sf.SetFocusEvent()
}
func (fp *FilePicker) readFiles() {
effpath, err := filepath.EvalSymlinks(fp.directory)
if err != nil {
log.Printf("FilePicker Path: %v could not be opened -- error: %v\n", effpath, err)
return
}
_, err = os.Lstat(effpath)
if err != nil {
log.Printf("FilePicker Path: %v could not be opened -- error: %v\n", effpath, err)
return
}
fp.files = make([]*fileinfo.FileInfo, 0, 1000)
filepath.Walk(effpath, func(path string, info fs.FileInfo, err error) error {
if err != nil {
emsg := fmt.Sprintf("Path %q: Error: %v", effpath, err)
// if fv.Scene != nil {
// PromptDialog(fv, DlgOpts{Title: "FilePicker UpdateFiles", emsg, Ok: true, Cancel: false}, nil)
// } else {
log.Printf("FilePicker error: %v\n", emsg)
// }
return nil // ignore
}
if path == effpath { // proceed..
return nil
}
fi, ferr := fileinfo.NewFileInfo(path)
keep := ferr == nil
if keep && fp.Filterer != nil { // (fi is nil for an error)
keep = fp.Filterer(fp, fi)
}
if keep {
fp.files = append(fp.files, fi)
}
if info.IsDir() {
return filepath.SkipDir
}
return nil
})
}
// updateFavorites updates list of files and other views for current path
func (fp *FilePicker) updateFavorites() {
sv := fp.favoritesTable
sv.Update()
}
// addPathToFavorites adds the current path to favorites
func (fp *FilePicker) addPathToFavorites() { //types:add
dp := fp.directory
if dp == "" {
return
}
_, fnm := filepath.Split(dp)
hd, _ := homedir.Dir()
hd += string(filepath.Separator)
if after, ok := strings.CutPrefix(dp, hd); ok {
dp = filepath.Join("~", after)
}
if fnm == "" {
fnm = dp
}
if _, found := SystemSettings.FavPaths.findPath(dp); found {
MessageSnackbar(fp, "Error: path is already on the favorites list")
return
}
fi := favoritePathItem{"folder", fnm, dp}
SystemSettings.FavPaths = append(SystemSettings.FavPaths, fi)
ErrorSnackbar(fp, SaveSettings(SystemSettings), "Error saving settings")
// fv.FileSig.Emit(fv.This, int64(FilePickerFavAdded), fi)
fp.updateFavorites()
}
// directoryUp moves up one directory in the path
func (fp *FilePicker) directoryUp() { //types:add
pdr := filepath.Dir(fp.directory)
if pdr == "" {
return
}
fp.directory = pdr
fp.updateFilesEvent()
}
// newFolder creates a new folder with the given name in the current directory.
func (fp *FilePicker) newFolder(name string) error { //types:add
dp := fp.directory
if dp == "" {
return nil
}
np := filepath.Join(dp, name)
err := os.MkdirAll(np, 0775)
if err != nil {
return err
}
fp.updateFilesEvent()
return nil
}
// setSelectedFile sets the currently selected file to the given name, sends
// a selection event, and updates the selection in the table.
func (fp *FilePicker) setSelectedFile(file string) {
fp.selectedFilename = file
sv := fp.filesTable
ef := fp.extensionField
exts := ef.Text()
if !sv.selectFieldValue("Name", fp.selectedFilename) { // not found
extl := strings.Split(exts, ",")
if len(extl) == 1 {
if !strings.HasSuffix(fp.selectedFilename, extl[0]) {
fp.selectedFilename += extl[0]
}
}
}
fp.selectedIndex = sv.SelectedIndex
sf := fp.selectField
sf.SetText(fp.selectedFilename) // make sure
fp.Send(events.Select) // receiver needs to get selectedFile
}
// fileSelect updates the selection with the given selected file index and
// sends a select event.
func (fp *FilePicker) fileSelect(idx int) {
if idx < 0 {
return
}
fi := fp.files[idx]
fp.selectedIndex = idx
fp.selectedFilename = fi.Name
sf := fp.selectField
sf.SetText(fp.selectedFilename)
fp.Send(events.Select)
}
// SetExtensions sets the [FilePicker.Extensions] to the given comma separated
// list of file extensions, which each must start with a dot (".").
func (fp *FilePicker) SetExtensions(ext string) *FilePicker {
if ext == "" {
if fp.selectedFilename != "" {
ext = strings.ToLower(filepath.Ext(fp.selectedFilename))
}
}
fp.extensions = ext
exts := strings.Split(fp.extensions, ",")
fp.extensionMap = make(map[string]string, len(exts))
for _, ex := range exts {
ex = strings.TrimSpace(ex)
if len(ex) == 0 {
continue
}
if ex[0] != '.' {
ex = "." + ex
}
fp.extensionMap[strings.ToLower(ex)] = ex
}
return fp
}
// favoritesSelect selects a favorite path and goes there
func (fp *FilePicker) favoritesSelect(idx int) {
if idx < 0 || idx >= len(SystemSettings.FavPaths) {
return
}
fi := SystemSettings.FavPaths[idx]
fp.directory, _ = homedir.Expand(fi.Path)
fp.updateFilesEvent()
}
// sortFiles sorts the files by the field of the given name, up or down,
// in the order of [dirsort.Sort], and returns whether it is a field of it.
func (fp *FilePicker) sortFiles(field string, down bool) bool {
s, ok := dirsort.Parse(field)
if !ok {
return false
}
s.Down = down
s.SortFiles(fp.files)
return true
}
// fileComplete finds the possible completions for the file field
func (fp *FilePicker) fileComplete(data any, text string, posLine, posChar int) (md complete.Matches) {
md.Seed = complete.SeedPath(text)
var files = []string{}
for _, f := range fp.files {
files = append(files, f.Name)
}
if len(md.Seed) > 0 { // return all directories
files = complete.MatchSeedString(files, md.Seed)
}
for _, d := range files {
m := complete.Completion{Text: d}
md.Matches = append(md.Matches, m)
}
return md
}
// fileCompleteEdit is the editing function called when inserting the completion selection in the file field
func (fp *FilePicker) fileCompleteEdit(data any, text string, cursorPos int, c complete.Completion, seed string) (ed complete.Edit) {
ed = complete.EditWord(text, cursorPos, c.Text, seed)
return ed
}
// editRecentPaths displays a dialog allowing the user to
// edit the recent paths list.
func (fp *FilePicker) editRecentPaths() {
d := NewBody("Recent file paths")
NewText(d).SetType(TextSupporting).SetText("You can delete paths you no longer use")
NewList(d).SetSlice(&recentPaths)
d.AddBottomBar(func(bar *Frame) {
d.AddCancel(bar)
d.AddOK(bar).OnClick(func(e events.Event) {
saveRecentPaths()
fp.Update()
})
})
d.RunDialog(fp)
}
// Filename is used to specify an file path.
// It results in a [FileButton] [Value].
type Filename = fsx.Filename
// FileButton represents a [Filename] value with a button
// that opens a [FilePicker].
type FileButton struct {
Button
Filename string
// Extensions are the target file extensions for the file picker.
Extensions string
}
func (fb *FileButton) WidgetValue() any { return &fb.Filename }
func (fb *FileButton) OnBind(value any, tags reflect.StructTag) {
if ext, ok := tags.Lookup("extension"); ok {
fb.SetExtensions(ext)
}
}
func (fb *FileButton) Init() {
fb.Button.Init()
fb.SetType(ButtonTonal).SetIcon(icons.File)
fb.Updater(func() {
if fb.Filename == "" {
fb.SetText("Select file")
} else {
fb.SetText(elide.Middle(fb.Filename, 38))
}
})
var fp *FilePicker
InitValueButton(fb, false, func(d *Body) {
d.Title = "Select file"
d.DeleteChildByName("body-title") // file picker has its own title
fp = NewFilePicker(d).SetFilename(fb.Filename).SetExtensions(fb.Extensions)
fb.setFlag(true, widgetValueNewWindow)
d.AddTopBar(func(bar *Frame) {
NewToolbar(bar).Maker(fp.MakeToolbar)
})
}, func() {
fb.Filename = fp.SelectedFile()
})
}
func (fb *FileButton) WidgetTooltip(pos image.Point) (string, image.Point) {
if fb.Filename == "" {
return fb.Tooltip, fb.DefaultTooltipPos()
}
fnm := "(" + fb.Filename + ")"
if fb.Tooltip == "" {
return fnm, fb.DefaultTooltipPos()
}
return fnm + " " + fb.Tooltip, fb.DefaultTooltipPos()
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"fmt"
"os"
"path/filepath"
"strings"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/fileinfo/mimedata"
"cogentcore.org/core/base/fsx"
"cogentcore.org/core/events"
"cogentcore.org/core/styles/states"
)
// handleFilesDND sets up drag-and-drop for the files table:
// files can be dragged out of it, to other widgets, windows and apps,
// and dropped files are copied (or moved) into the current directory.
func (fp *FilePicker) handleFilesDND(w *Table) {
w.On(events.DragStart, func(e events.Event) {
fp.filesDragStart(e)
})
w.On(events.DragEnter, func(e events.Event) {
w.SetState(true, states.DragHovered)
w.NeedsRender()
e.SetHandled()
})
w.On(events.DragLeave, func(e events.Event) {
w.SetState(false, states.DragHovered)
w.NeedsRender()
e.SetHandled()
})
w.On(events.Drop, func(e events.Event) {
fp.filesDrop(e)
})
}
// filesDragStart starts dragging the file under the mouse.
func (fp *FilePicker) filesDragStart(e events.Event) {
w := fp.filesTable
row, _, ok := w.ListGrid.indexFromPixel(e.Pos())
if !ok {
return
}
idx := row + w.StartIndex
if idx < 0 || idx >= len(fp.files) {
return
}
if !w.indexIsSelected(idx) {
w.updateSelectRow(row, events.SelectOne)
}
path := filepath.Join(fp.directory, fp.files[idx].Name)
rw, ok := w.rowFirstWidget(row)
if !ok {
return
}
fp.Scene.Events.DragStart(rw.This.(Widget), mimedata.NewText(path), e)
fp.Scene.Events.SetDragFiles(path)
e.SetHandled()
}
// filesDrop copies the files dropped on the files table into the
// current directory, or moves them for [events.DropMove], first
// asking whether to overwrite any existing files of the same names.
func (fp *FilePicker) filesDrop(e events.Event) {
de := e.(*events.DragDrop)
e.SetHandled()
fp.filesTable.SetState(false, states.DragHovered)
paths := DroppedFiles(de)
var existing []string
for _, p := range paths {
tp := filepath.Join(fp.directory, filepath.Base(p))
if tp != p && fsx.Exists(tp) {
existing = append(existing, filepath.Base(p))
}
}
move := de.DropMod == events.DropMove
drop := func() {
var errs []error
for _, p := range paths {
tp := filepath.Join(fp.directory, filepath.Base(p))
if tp == p {
continue
}
var err error
if move {
err = movePath(tp, p)
} else {
err = fsx.CopyPath(tp, p)
}
errs = append(errs, err)
}
fp.updateFilesEvent()
ErrorSnackbar(fp, errors.Join(errs...), "Error copying file")
}
if len(existing) == 0 {
drop()
return
}
d := NewBody("Overwrite?")
NewText(d).SetType(TextSupporting).SetText(fmt.Sprintf("Overwrite existing file(s) in %s: %s?", fp.directory, strings.Join(existing, ", ")))
d.AddBottomBar(func(bar *Frame) {
d.AddCancel(bar)
d.AddOK(bar).SetText("Overwrite").OnClick(func(e events.Event) {
drop()
})
})
d.RunDialog(fp)
}
// movePath moves the file or directory at src to dst, overwriting an
// existing file. If it can't be renamed, for example on another drive,
// it is copied, and then deleted if the copy succeeds.
func movePath(dst, src string) error {
if os.Rename(src, dst) == nil {
return nil
}
if err := fsx.CopyPath(dst, src); err != nil {
return err
}
return os.RemoveAll(src)
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !js && !ios
package core
import (
"context"
"log/slog"
"time"
"github.com/sgtdi/fswatcher"
)
// watchFilePickerDir watches the files directly within the given
// directory until ctx is canceled, calling changed from another
// goroutine after changes, which are collected for 200ms.
func watchFilePickerDir(ctx context.Context, dir string, changed func()) error {
w, err := fswatcher.New(fswatcher.WithPath(dir, fswatcher.WithDepth(fswatcher.WatchTopLevel)))
if err != nil {
return err
}
go func() {
if err := w.Watch(ctx); err != nil {
slog.Error("FilePicker: file watcher failed", "path", dir, "err", err)
}
}()
go func() {
timer := time.NewTimer(time.Hour)
timer.Stop()
pending := false
for {
select {
case <-ctx.Done():
return
case _, ok := <-w.Events():
if !ok {
return
}
if !pending {
pending = true
timer.Reset(200 * time.Millisecond)
}
case <-timer.C:
pending = false
changed()
}
}
}()
return nil
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"maps"
"path/filepath"
"sync"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/sharedfile"
)
// FilePickerSettings are the settings of the [FilePicker] that it keeps
// as the user changes them, such as the widths of its columns, in
// filepicker_settings.json in the Cogent Core data directory, which is
// shared by all apps (see [sharedfile]). It is read again when a file
// picker is opened, if another app has changed it. New settings are
// added as new fields, which are ignored by older versions, and are the
// zero value when read from an older file, so the zero value of each
// field must be its default.
type FilePickerSettings struct {
// ColumnWidths are the widths of the columns of the table of files,
// in Dp, by field name, for the columns whose widths the user has set
// (see [Table.ColumnWidths]); the others have automatic widths.
ColumnWidths map[string]float32 `json:",omitempty"`
}
// filePickerSettings is the file of the [FilePickerSettings], protected by
// a mutex, as file pickers can be in different windows.
var filePickerSettings struct {
mu sync.Mutex
file sharedfile.File[FilePickerSettings]
}
// filePickerSettingsPath returns the path of the [FilePickerSettings] file.
// It is that of the current app, as it changes in tests.
func filePickerSettingsPath() string {
return filepath.Join(TheApp.CogentCoreDataDir(), "filepicker_settings.json")
}
// loadFilePickerSettings returns the [FilePickerSettings], read again
// from their file if it has changed since it was last read.
func loadFilePickerSettings() FilePickerSettings {
fs := &filePickerSettings
fs.mu.Lock()
defer fs.mu.Unlock()
fs.file.Path = filePickerSettingsPath()
errors.Log(fs.file.Reload())
s := fs.file.Data
s.ColumnWidths = maps.Clone(s.ColumnWidths) // not shared with the file
return s
}
// updateFilePickerSettings changes the [FilePickerSettings] with the given
// function and saves them, with the changes of other apps (see
// [sharedfile.File.Update]).
func updateFilePickerSettings(change func(s *FilePickerSettings)) error {
fs := &filePickerSettings
fs.mu.Lock()
defer fs.mu.Unlock()
fs.file.Path = filePickerSettingsPath()
return fs.file.Update(change)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"cogentcore.org/core/enums"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/states"
)
// StateIs returns whether the widget has the given [states.States] flag set.
func (wb *WidgetBase) StateIs(state states.States) bool {
// This is equivalent to [states.States.HasFlag] without converting the
// flag to an [enums.BitFlag], since it is called very frequently.
return wb.Styles.State&(1<<uint32(state)) != 0
}
// AbilityIs returns whether the widget has the given [abilities.Abilities] flag set.
func (wb *WidgetBase) AbilityIs(able abilities.Abilities) bool {
return wb.Styles.Abilities.HasFlag(able)
}
// SetState sets the given [states.State] flags to the given value.
func (wb *WidgetBase) SetState(on bool, state ...states.States) *WidgetBase {
bfs := make([]enums.BitFlag, len(state))
for i, st := range state {
bfs[i] = st
}
wb.Styles.State.SetFlag(on, bfs...)
return wb
}
// SetSelected sets the [states.Selected] flag to given value for the entire Widget
// and calls [WidgetBase.Restyle] to apply any resultant style changes.
func (wb *WidgetBase) SetSelected(sel bool) *WidgetBase {
wb.SetState(sel, states.Selected)
wb.Restyle()
return wb
}
// CanFocus returns whether this node can receive keyboard focus.
func (wb *WidgetBase) CanFocus() bool {
return wb.Styles.Abilities.HasFlag(abilities.Focusable)
}
// SetEnabled sets the [states.Disabled] flag to the opposite of the given value.
func (wb *WidgetBase) SetEnabled(enabled bool) *WidgetBase {
return wb.SetState(!enabled, states.Disabled)
}
// IsDisabled returns whether this node is flagged as [states.Disabled].
// If so, behave and style appropriately.
func (wb *WidgetBase) IsDisabled() bool {
return wb.StateIs(states.Disabled)
}
// IsReadOnly returns whether this widget is flagged as either [states.ReadOnly] or [states.Disabled].
func (wb *WidgetBase) IsReadOnly() bool {
return wb.Styles.IsReadOnly()
}
// SetReadOnly sets the [states.ReadOnly] flag to the given value.
func (wb *WidgetBase) SetReadOnly(ro bool) *WidgetBase {
return wb.SetState(ro, states.ReadOnly)
}
// HasStateWithin returns whether this widget or any
// of its children have the given state flag.
func (wb *WidgetBase) HasStateWithin(state states.States) bool {
got := false
for _, cwb := range wb.AllWidgets() {
if cwb.StateIs(state) {
got = true
break
}
}
return got
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/tree"
)
// Widgets with a [styles.Style.Float] float to the left or right side
// of their parent, which is a column ([styles.Flex] with [styles.Column]
// and no wrap): they are out of the flow of its layout, at the position
// in the column where they are, and each widget after them that starts
// beside them is narrowed and moved to be beside them. (This is a
// simplification of CSS floats, in which each line of text beside a
// float is shortened instead.) [styles.Style.Clear] moves a widget below
// the floats on the given sides. The column is as tall as its floats.
// isFloat returns whether the widget floats (see [styles.Style.Float]).
func (wb *WidgetBase) isFloat() bool {
return wb.Styles.Float != styles.FloatNone && !wb.outOfFlow()
}
// floatPlace is the place of a child in a column with floats.
type floatPlace struct {
// pos is the position of the child relative to the content of the column.
pos math32.Vector2
// width is the width allocated to the child.
width float32
}
// floatLayout is the layout of a column that has floats.
type floatLayout struct {
// places has the place of each child, by its index.
places map[int]floatPlace
// size is the size of the content of the column,
// with the floats and the space that clearing them adds.
size math32.Vector2
// floatsWidth is the width that the floats take, on the left and the
// right side, which is the width of a column that only has floats
// (see [Frame.onlyFloats]).
floatsWidth float32
}
// hasFloats returns whether the frame is a column with floating children.
func (fr *Frame) hasFloats() bool {
if fr.Styles.Display != styles.Flex || fr.Styles.Direction != styles.Column || fr.Styles.Wrap {
return false
}
has := false
fr.forVisibleChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
if cwb.isFloat() {
has = true
return tree.Break
}
return tree.Continue
})
return has
}
// onlyFloats returns whether the frame is a column with floating children
// and no other children in the flow of its layout.
func (fr *Frame) onlyFloats() bool {
if !fr.hasFloats() {
return false
}
flow := false
fr.forFlowChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
flow = true
return tree.Break
})
return !flow
}
// layoutFloats computes the [floatLayout] of the frame from the current
// sizes of its children, sets the allocations of the children from it,
// and returns whether any of them changed.
func (fr *Frame) layoutFloats() bool {
if !fr.hasFloats() {
fr.layout.floats = nil
return false
}
type rect struct {
left bool
x, y, w, h float32
}
var floats []rect
width := fr.Geom.Size.Alloc.Content.X - fr.Geom.Size.InnerSpace.X
gap := fr.layout.Gap.Y
fl := &floatLayout{places: map[int]floatPlace{}}
// edges returns the edges of the space beside the floats at y.
edges := func(y float32) (left, right float32) {
left, right = 0, width
for _, f := range floats {
if y < f.y || y >= f.y+f.h {
continue
}
if f.left {
left = max(left, f.x+f.w)
} else {
right = min(right, f.x)
}
}
return
}
// below returns the bottom of the floats on the given sides.
below := func(left, right bool) float32 {
b := float32(0)
for _, f := range floats {
if (f.left && left) || (!f.left && right) {
b = max(b, f.y+f.h)
}
}
return b
}
changed := false
var maxLeft, maxRight float32
y := float32(0)
floatTop := float32(0) // the top of the last float
// the last child in the flow, if it is inline content: its top, and its
// preferred width (on one line)
lastFlow, lastFlowY, lastFlowPref := false, float32(0), float32(0)
fr.forVisibleChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
if cwb.outOfFlow() {
return tree.Continue
}
ksz := &cwb.Geom.Size
cy := y // below the floats that it clears
switch cwb.Styles.Clear {
case styles.ClearLeft:
cy = max(y, below(true, false))
case styles.ClearRight:
cy = max(y, below(false, true))
case styles.ClearBoth:
cy = max(y, below(true, true))
}
if cwb.isFloat() {
// a float that clears is moved down, but not the flow after it
w := min(ksz.Actual.Total.X, width)
if cwb.Styles.Grow.X > 0 {
// a growing float (as for a percentage width in CSS) takes
// the width of the column, up to its Max
// (a percentage Max is of the column, which it may not
// have been resolved for yet)
w = width
if mx := cwb.Styles.Max.X; mx.Unit == units.UnitPw && mx.Value > 0 {
w = min(w, width*mx.Value/100+ksz.Space.X-cwb.boxSizingSpace().X)
} else if mt := ksz.maxTotal().X; mt > 0 {
w = min(w, mt)
}
} else if AsFrame(cw) != nil {
// A float is as wide as its content (shrink-to-fit, as in
// CSS): its preferred width, within the column, also when
// its content is floats (which have no size in its flow), or
// a block of floats (as the breadcrumbs of the header of
// craigslist.org, a list of floats in a floating nav, which
// had no width, so its crumbs were each on a line).
w = min(max(w, ksz.prefWidth), width)
}
h := ksz.Actual.Total.Y
left := cwb.Styles.Float == styles.FloatLeft
// a float is not higher than the floats before it, as in CSS
fy := max(cy, floatTop)
if !left && lastFlow && cwb.Styles.Clear == styles.ClearNone && lastFlowY >= floatTop {
// a right float after content that is on one line is on that
// line, beside it, if it fits there (as the theme and search
// box of the header of the Python docs, after its links), as
// in CSS, where it is on the line of the content before it
if l, r := edges(lastFlowY); r-w >= l+lastFlowPref {
fy = lastFlowY
}
}
// the widths of the floats are rounded up to whole dots, by less
// than a dot each: a float fits in a space that is narrower by
// less than that for the floats before it (as the nine slides of
// the photos of the postings of craigslist.org, of 442px each in
// a row of 3978px, the last of which wrapped)
slack := float32(len(floats))
for range len(floats) + 1 { // down below floats until it fits
l, r := edges(fy)
if r-l+slack >= w || l == 0 && r == width {
break
}
next := float32(-1) // the next bottom of a float
for _, f := range floats {
if b := f.y + f.h; b > fy && (next < 0 || b < next) {
next = b
}
}
if next < 0 {
break
}
fy = next
}
l, r := edges(fy)
x := l
if !left {
x = r - w
}
floats = append(floats, rect{left, x, fy, w, h})
floatTop = fy
if ksz.Alloc.Total.X != w {
changed = true
}
ksz.Alloc.Total = math32.Vec2(w, h)
ksz.SetContentFromTotal(&ksz.Alloc)
if AsFrame(cw) != nil && ksz.Actual.Total.X < w {
// the box of a float is its width (shrink-to-fit), also when
// it is finally sized before its width is set here (as the
// breadcrumbs of craigslist.org, a nav of a list of floats,
// which stayed as wide as nothing)
ksz.Actual.Total.X = w
ksz.SetContentFromTotal(&ksz.Actual)
}
fl.places[i] = floatPlace{pos: math32.Vec2(x, fy), width: w}
fl.size.Y = max(fl.size.Y, fy+h)
if left { // the widths that the floats take on each side
maxLeft = max(maxLeft, x+w)
} else {
maxRight = max(maxRight, width-x)
}
return tree.Continue
}
y = cy
l, r := edges(y)
w := ksz.Alloc.Total.X
if cwb.Styles.Grow.X > 0 || w > r-l {
w = r - l
}
if w != ksz.Alloc.Total.X {
changed = true
ksz.Alloc.Total.X = w
ksz.SetContentFromTotal(&ksz.Alloc)
}
fl.places[i] = floatPlace{pos: math32.Vec2(l, y), width: w}
// only inline content (a text, or a row of inline content that
// wraps), not a block, which a float after it is below in CSS
_, isText := cw.(*Text)
inline := isText || cwb.Styles.Direction == styles.Row && cwb.Styles.Wrap
lastFlow, lastFlowY, lastFlowPref = inline, y, ksz.prefWidth
y += ksz.Actual.Total.Y + gap
return tree.Continue
})
fl.size.Y = max(fl.size.Y, y-gap)
fl.size.X = width
fl.floatsWidth = maxLeft + maxRight
fr.layout.floats = fl
return changed
}
// positionFloats positions the children of the frame from its [floatLayout],
// returning false if it has none.
func (fr *Frame) positionFloats() bool {
fl := fr.layout.floats
if fl == nil {
return false
}
sz := &fr.Geom.Size
var stPos math32.Vector2
stPos.Y = styles.AlignPos(fr.Styles.Justify.Content, fl.size.Y, sz.Actual.Content.Y)
fr.forVisibleChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
pl, ok := fl.places[i]
if !ok {
return tree.Continue
}
pos := stPos.Add(pl.pos)
ksz := &cwb.Geom.Size
pos.X += styles.AlignPos(styles.ItemAlign(fr.Styles.Align.Items, cwb.Styles.Align.Self), ksz.Actual.Total.X, pl.width)
cwb.Geom.RelPos = pos
return tree.Continue
})
return true
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"fmt"
"reflect"
"slices"
"strings"
"cogentcore.org/core/base/keylist"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/base/strcase"
"cogentcore.org/core/colors"
"cogentcore.org/core/cursors"
"cogentcore.org/core/events"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/tree"
"cogentcore.org/core/types"
)
// Form represents a struct with rows of field names and editable values.
type Form struct {
Frame
// Struct is the pointer to the struct that we are viewing.
Struct any
// Inline is whether to display the form in one line.
Inline bool
// Modified optionally highlights and tracks fields that have been modified
// through an OnChange event. If present, it replaces the default value highlighting
// and resetting logic. Ignored if nil.
Modified map[string]bool
// structFields are the fields of the current struct, keys are field paths.
structFields keylist.List[string, *structField]
// isShouldDisplayer is whether the struct implements [ShouldDisplayer], which results
// in additional updating being done at certain points.
isShouldDisplayer bool
}
// structField represents the values of one struct field being viewed.
type structField struct {
path string
field reflect.StructField
value, parent reflect.Value
}
// NoSentenceCaseFor indicates to not transform field names in
// [Form]s into "Sentence case" for types whose full,
// package-path-qualified name contains any of these strings.
// For example, this can be used to disable sentence casing
// for types with scientific abbreviations in field names,
// which are more readable when not sentence cased. However,
// this should not be needed in most circumstances.
var NoSentenceCaseFor []string
// noSentenceCaseForType returns whether the given fully
// package-path-qualified name contains anything in the
// [NoSentenceCaseFor] list.
func noSentenceCaseForType(tnm string) bool {
return slices.ContainsFunc(NoSentenceCaseFor, func(s string) bool {
return strings.Contains(tnm, s)
})
}
// ShouldDisplayer is an interface that determines whether a named field
// should be displayed in [Form].
type ShouldDisplayer interface {
// ShouldDisplay returns whether the given named field should be displayed.
ShouldDisplay(field string) bool
}
func (fm *Form) WidgetValue() any { return &fm.Struct }
func (fm *Form) getStructFields() {
var fields keylist.List[string, *structField]
shouldShow := func(parent reflect.Value, field reflect.StructField) bool {
if field.Tag.Get("display") == "-" {
return false
}
if ss, ok := reflect.TypeAssert[ShouldDisplayer](reflectx.UnderlyingPointer(parent)); ok {
fm.isShouldDisplayer = true
if !ss.ShouldDisplay(field.Name) {
return false
}
}
return true
}
reflectx.WalkFields(reflectx.Underlying(reflect.ValueOf(fm.Struct)),
func(parent reflect.Value, field reflect.StructField, value reflect.Value) bool {
return shouldShow(parent, field)
},
func(parent reflect.Value, parentField *reflect.StructField, field reflect.StructField, value reflect.Value) {
if field.Tag.Get("display") == "add-fields" && (field.Type.Kind() == reflect.Struct || (field.Type.Kind() == reflect.Pointer && !reflectx.IsNil(value))) {
fldval := value
if field.Type.Kind() == reflect.Pointer && !reflectx.IsNil(value) {
fldval = value.Elem()
}
reflectx.WalkFields(fldval,
func(parent reflect.Value, sfield reflect.StructField, value reflect.Value) bool {
return shouldShow(parent, sfield)
},
func(parent reflect.Value, parentField *reflect.StructField, sfield reflect.StructField, value reflect.Value) {
// if our parent field is read only, we must also be
if field.Tag.Get("edit") == "-" && sfield.Tag.Get("edit") == "" {
sfield.Tag += ` edit:"-"`
}
path := field.Name + " • " + sfield.Name
fields.Add(path, &structField{path: path, field: sfield, value: value, parent: parent})
})
} else {
fields.Add(field.Name, &structField{path: field.Name, field: field, value: value, parent: parent})
}
})
fm.structFields = fields
}
func (fm *Form) Init() {
fm.Frame.Init()
fm.Styler(func(s *styles.Style) {
s.Align.Items = styles.Center
if fm.Inline {
return
}
s.Display = styles.Grid
s.Grow.X = 1 // with the values, such as text fields, which fill it
// a margin at the right, as the values (text fields) fill it
s.Padding.Right = s.Gap.X
if fm.SizeClass() == SizeCompact {
s.Columns = 1
} else {
s.Columns = 2
}
})
fm.Maker(func(p *tree.Plan) {
if reflectx.IsNil(reflect.ValueOf(fm.Struct)) {
return
}
fm.getStructFields()
sc := true
if len(NoSentenceCaseFor) > 0 {
sc = !noSentenceCaseForType(types.TypeNameValue(fm.Struct))
}
for i := range fm.structFields.Len() {
f := fm.structFields.Values[i]
fieldPath := fm.structFields.Keys[i]
label := f.path
if sc {
label = strcase.ToSentence(label)
}
if lt, ok := f.field.Tag.Lookup("label"); ok {
label = lt
}
labnm := fmt.Sprintf("label-%s", fieldPath)
// we must have a different name for different types
// so that the widget can be re-made for a new type
typnm := reflectx.ShortTypeName(f.field.Type)
// we must have a different name for invalid values
// so that the widget can be re-made for valid values
if !reflectx.Underlying(f.value).IsValid() {
typnm = "invalid"
}
// Using the type name ensures that widgets are specific to the type,
// even if they happen to have the same name. Using the path to index
// the structFields ensures safety against any [ShouldDisplayer]
// updates (see #1390).
valnm := fmt.Sprintf("value-%s-%s", fieldPath, typnm)
readOnlyTag := f.field.Tag.Get("edit") == "-"
def, hasDef := f.field.Tag.Lookup("default")
var labelWidget *Text
var valueWidget Value
tree.AddAt(p, labnm, func(w *Text) {
labelWidget = w
w.Styler(func(s *styles.Style) {
s.SetTextWrap(false)
})
// TODO: technically we should recompute doc, readOnlyTag,
// def, hasDef, etc every time, as this is not fully robust
// (see https://github.com/cogentcore/core/issues/1098).
doc, _ := types.GetDoc(f.value, f.parent, f.field, label)
w.SetTooltip(doc)
if hasDef || fm.Modified != nil {
if hasDef {
w.SetTooltip("(Default: " + def + ") " + w.Tooltip)
}
var isDef bool
w.Styler(func(s *styles.Style) {
f := fm.structFields.At(fieldPath)
dcr := "(Double click to reset to default) "
if fm.Modified != nil {
isDef = !fm.Modified[f.path]
dcr = "(Double click to mark as not modified) "
} else {
isDef = reflectx.ValueIsDefault(f.value, def)
}
if !isDef {
s.Color = colors.Scheme.Primary.Base
s.Cursor = cursors.Poof
if !strings.HasPrefix(w.Tooltip, dcr) {
w.SetTooltip(dcr + w.Tooltip)
}
} else {
w.SetTooltip(strings.TrimPrefix(w.Tooltip, dcr))
}
})
w.OnDoubleClick(func(e events.Event) {
f := fm.structFields.At(fieldPath)
if isDef {
return
}
e.SetHandled()
var err error
if fm.Modified != nil {
fm.Modified[f.path] = false
} else {
err = reflectx.SetFromDefaultTag(f.value, def)
}
if err != nil {
ErrorSnackbar(w, err, "Error setting default value")
} else {
w.Update()
valueWidget.AsWidget().Update()
if fm.Modified == nil {
valueWidget.AsWidget().SendChange(e)
}
}
})
}
w.Updater(func() {
w.SetText(label)
})
})
tree.AddNew(p, valnm, func() Value {
return NewFieldValue(f.field.Name, reflectx.UnderlyingPointer(f.parent).Interface(), reflectx.UnderlyingPointer(f.value).Interface(), f.field.Tag)
}, func(w Value) {
valueWidget = w
wb := w.AsWidget()
if f.field.Tag.Get("tab") == "-" { // skipped by Tab
wb.FirstStyler(func(s *styles.Style) {
s.SetAbilities(true, abilities.SkipTab)
})
}
wb.Styler(func(s *styles.Style) {
// the values fill the width of a small screen, but for a
// switch, which would be at the end of it
if _, isSwitch := w.(*Switch); fm.SizeClass() == SizeCompact && !fm.Inline && !isSwitch {
s.Grow.X = 1
s.Max.X.Zero() // such as the 40ch of a TextField
}
// text fields grow to the width of the form, with no max
// (the 40ch of a TextField), as the form is their space
if _, isText := w.(*TextField); isText {
s.Max.X.Zero()
}
})
doc, _ := types.GetDoc(f.value, f.parent, f.field, label)
// InitValueButton may set starting wb.Tooltip in Init
if wb.Tooltip == "" {
wb.SetTooltip(doc)
} else if doc == "" {
wb.SetTooltip(wb.Tooltip)
} else {
wb.SetTooltip(wb.Tooltip + " " + doc)
}
if hasDef {
wb.SetTooltip("(Default: " + def + ") " + wb.Tooltip)
}
wb.OnInput(func(e events.Event) {
f := fm.structFields.At(fieldPath)
fm.Send(events.Input, e)
if f.field.Tag.Get("immediate") == "+" {
wb.SendChange(e)
}
})
if !fm.IsReadOnly() && !readOnlyTag {
wb.OnChange(func(e events.Event) {
if fm.Modified != nil {
fm.Modified[f.path] = true
}
fm.SendChange(e)
if hasDef || fm.Modified != nil {
labelWidget.Update()
}
if fm.isShouldDisplayer {
fm.Update()
}
})
}
wb.Updater(func() {
wb.SetReadOnly(fm.IsReadOnly() || readOnlyTag)
f := fm.structFields.At(fieldPath)
Bind(reflectx.UnderlyingPointer(f.value).Interface(), w)
vc := joinValueTitle(fm.ValueTitle, label)
if vc != wb.ValueTitle {
wb.ValueTitle = vc + " (" + wb.ValueTitle + ")"
}
})
})
}
})
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"log/slog"
"time"
"unicode"
"cogentcore.org/core/base/labels"
"cogentcore.org/core/events"
"cogentcore.org/core/events/key"
"cogentcore.org/core/keymap"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/text/parse/complete"
"cogentcore.org/core/tree"
)
// Frame is the primary node type responsible for organizing the sizes
// and positions of child widgets. It also renders the standard box model.
// All collections of widgets should generally be contained within a [Frame];
// otherwise, the parent widget must take over responsibility for positioning.
// Frames automatically can add scrollbars depending on the [styles.Style.Overflow].
//
// For a [styles.Grid] frame, the [styles.Style.Columns] property should
// generally be set to the desired number of columns, from which the number of rows
// is computed; otherwise, it uses the square root of number of
// elements.
type Frame struct {
WidgetBase
// StackTop, for a [styles.Stacked] frame, is the index of the node to use
// as the top of the stack. Only the node at this index is rendered; if it is
// not a valid index, nothing is rendered.
StackTop int
// LayoutStackTopOnly is whether to only layout the top widget
// (specified by [Frame.StackTop]) for a [styles.Stacked] frame.
// The other children are also not updated or styled by updates
// of the tree (such as [WidgetBase.Update]) until they are on top.
// This is appropriate for widgets such as [Tabs], which do a full
// update on stack changes, but not for widgets such as [Switch]es
// which don't.
LayoutStackTopOnly bool
// FrColumns is whether the columns of a [styles.Grid] frame whose
// columns all grow are sized as the fr tracks of CSS: each is its share
// of the width by its grow, or the min-content width of its cells if
// that is more, and the preferred widths of the cells do not count.
// Otherwise, the columns start at the preferred widths of their cells.
FrColumns bool `set:"-" display:"-"`
// FrLastRow is whether the last row of a [styles.Grid] frame is
// flexible and the others are sized by their content, as for a
// grid-template-rows of auto rows and a last one of 1fr in CSS: the
// extra height of a cell that spans rows (beyond that of the rows) is
// in the last row that it spans, not in all of them (as the image of
// a story of npr.org beside its title, whose rows stay together).
FrLastRow bool `set:"-" display:"-"`
// layout contains implementation state info for doing layout
layout layoutState
// HasScroll is whether scrollbars exist for each dimension.
HasScroll [2]bool `edit:"-" copier:"-" json:"-" xml:"-" set:"-"`
// Scrolls are the scroll bars, which are fully managed as needed.
Scrolls [2]*Slider `copier:"-" json:"-" xml:"-" set:"-"`
// handleKeyNav indicates whether this frame should handle keyboard
// navigation events using the default handlers. Set to false to allow
// custom event handling.
handleKeyNav bool
// accumulated name to search for when keys are typed
focusName string
// time of last focus name event; for timeout
focusNameTime time.Time
// last element focused on; used as a starting point if name is the same
focusNameLast tree.Node
}
func (fr *Frame) Init() {
fr.WidgetBase.Init()
fr.handleKeyNav = true
fr.Styler(func(s *styles.Style) {
s.SetAbilities(true, abilities.ScrollableUnattended)
})
fr.FinalStyler(func(s *styles.Style) {
// we only enable, not disable, since some other widget like Slider may want to enable
if s.Overflow.X == styles.OverflowAuto || s.Overflow.Y == styles.OverflowAuto {
s.SetAbilities(true, abilities.Scrollable)
if TheApp.SystemPlatform().IsMobile() {
s.SetAbilities(true, abilities.Slideable)
}
}
})
fr.OnFinal(events.KeyChord, func(e events.Event) {
if !fr.handleKeyNav {
return
}
kf := keymap.Of(e.KeyChord())
if DebugSettings.KeyEventTrace {
slog.Info("Layout KeyInput", "widget", fr, "keyFunction", kf)
}
if kf == keymap.Abort {
if fr.Scene.Stage.closePopupAndBelow() {
e.SetHandled()
}
return
}
em := fr.Events()
if em == nil {
return
}
// the frame itself, also with a quiet focus; not with Shift, which
// selects, or goes to the next or previous tab (see [keymap.OfFallback])
if em.focus == fr.This && !e.HasAnyModifier(key.Shift) && fr.scrollKey(kf) {
e.SetHandled()
return
}
grid := fr.Styles.Display == styles.Grid
if fr.Styles.Direction == styles.Row || grid {
switch kf {
case keymap.MoveRight:
if fr.focusNextChild(false) {
e.SetHandled()
}
return
case keymap.MoveLeft:
if fr.focusPreviousChild(false) {
e.SetHandled()
}
return
}
}
if fr.Styles.Direction == styles.Column || grid {
switch kf {
case keymap.MoveDown:
if fr.focusNextChild(true) {
e.SetHandled()
}
return
case keymap.MoveUp:
if fr.focusPreviousChild(true) {
e.SetHandled()
}
return
case keymap.PageDown:
proc := false
for st := 0; st < TimingSettings.LayoutPageSteps; st++ {
if !fr.focusNextChild(true) {
break
}
proc = true
}
if proc {
e.SetHandled()
}
return
case keymap.PageUp:
proc := false
for st := 0; st < TimingSettings.LayoutPageSteps; st++ {
if !fr.focusPreviousChild(true) {
break
}
proc = true
}
if proc {
e.SetHandled()
}
return
}
}
fr.focusOnName(e)
})
fr.On(events.Scroll, func(e events.Event) {
if fr.AbilityIs(abilities.ScrollableUnattended) || (fr.StateIs(states.Focused) || fr.StateIs(states.Attended)) {
fr.scrollDelta(e)
}
})
// We treat slide events on frames as scroll events on mobile.
prevVels := []math32.Vector2{}
fr.On(events.SlideStart, func(e events.Event) {
if !TheApp.SystemPlatform().IsMobile() {
return
}
// Stop any existing scroll animations for this frame.
for _, anim := range fr.Scene.Animations {
if anim.Widget.This == fr.This {
anim.Done = true
}
}
})
fr.On(events.SlideMove, func(e events.Event) {
if !TheApp.SystemPlatform().IsMobile() {
return
}
// We must negate the delta for "natural" scrolling behavior.
del := math32.FromPoint(e.PrevDelta()).Negate()
fr.scrollDelta(events.NewScroll(e.WindowPos(), del, e.Modifiers()))
time := float32(e.SincePrev().Seconds()) * 1000
vel := del.DivScalar(time)
if len(prevVels) >= 3 {
prevVels = append(prevVels[1:], vel)
} else {
prevVels = append(prevVels, vel)
}
})
fr.On(events.SlideStop, func(e events.Event) {
if !TheApp.SystemPlatform().IsMobile() {
return
}
// If we have enough velocity over the last few slide events,
// we continue scrolling in an animation while slowly decelerating
// for a smoother experience.
if len(prevVels) == 0 {
return
}
vel := math32.Vector2{}
for _, vi := range prevVels {
vel.SetAdd(vi)
}
vel.SetDivScalar(float32(len(prevVels)))
prevVels = prevVels[:0] // reset for next scroll
if vel.Length() < 1 {
return
}
i := 0
t := float32(0)
fr.Animate(func(a *Animation) {
t += a.Dt
// See https://medium.com/@esskeetit/scrolling-mechanics-of-uiscrollview-142adee1142c
vel.SetMulScalar(math32.Pow(0.998, a.Dt)) // TODO: avoid computing Pow each time?
dx := vel.MulScalar(a.Dt)
fr.scrollDelta(events.NewScroll(e.WindowPos(), dx, e.Modifiers()))
i++
if t > 2000 {
a.Done = true
}
})
})
}
func (fr *Frame) Style() {
fr.WidgetBase.Style()
for d := math32.X; d <= math32.Y; d++ {
if fr.HasScroll[d] && fr.Scrolls[d] != nil {
fr.Scrolls[d].Style()
}
}
}
func (fr *Frame) Destroy() {
for d := math32.X; d <= math32.Y; d++ {
fr.deleteScroll(d)
}
fr.WidgetBase.Destroy()
}
// deleteScroll deletes scrollbar along given dimesion.
func (fr *Frame) deleteScroll(d math32.Dims) {
if fr.Scrolls[d] == nil {
return
}
sb := fr.Scrolls[d]
sb.This.Destroy()
fr.Scrolls[d] = nil
}
func (fr *Frame) RenderChildren() {
if fr.Styles.Display == styles.Stacked {
wb := fr.StackTopWidget()
if wb != nil {
wb.This.(Widget).RenderWidget()
}
return
}
fr.renderChildren() // in the order of their positions and z-index
}
func (fr *Frame) RenderWidget() {
if fr.StartRender() {
fr.This.(Widget).Render()
fr.RenderChildren()
fr.renderParts()
fr.RenderScrolls()
fr.EndRender()
fr.renderOutOfFlowChildren()
}
}
// childWithFocus returns a direct child of this layout that either is the
// current window focus item, or contains that focus item (along with its
// index) -- nil, -1 if none.
func (fr *Frame) childWithFocus() (Widget, int) {
em := fr.Events()
if em == nil {
return nil, -1
}
var foc Widget
focIndex := -1
fr.ForWidgetChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
if cwb.ContainsFocus() {
foc = cw
focIndex = i
return tree.Break
}
return tree.Continue
})
return foc, focIndex
}
// focusNextChild attempts to move the focus into the next layout child
// (with wraparound to start); returns true if successful.
// if updn is true, then for Grid layouts, it moves down to next row
// instead of just the sequentially next item.
func (fr *Frame) focusNextChild(updn bool) bool {
sz := len(fr.Children)
if sz <= 1 {
return false
}
foc, idx := fr.childWithFocus()
if foc == nil {
// fmt.Println("no child foc")
return false
}
em := fr.Events()
if em == nil {
return false
}
cur := em.focus
nxti := idx + 1
if fr.Styles.Display == styles.Grid && updn {
nxti = idx + fr.Styles.Columns
}
did := false
if nxti < sz {
nx := fr.Child(nxti).(Widget)
did = em.focusOnOrNext(nx)
} else {
nx := fr.Child(0).(Widget)
did = em.focusOnOrNext(nx)
}
if !did || em.focus == cur {
return false
}
return true
}
// focusPreviousChild attempts to move the focus into the previous layout child
// (with wraparound to end); returns true if successful.
// If updn is true, then for Grid layouts, it moves up to next row
// instead of just the sequentially next item.
func (fr *Frame) focusPreviousChild(updn bool) bool {
sz := len(fr.Children)
if sz <= 1 {
return false
}
foc, idx := fr.childWithFocus()
if foc == nil {
return false
}
em := fr.Events()
if em == nil {
return false
}
cur := em.focus
nxti := idx - 1
if fr.Styles.Display == styles.Grid && updn {
nxti = idx - fr.Styles.Columns
}
did := false
if nxti >= 0 {
did = em.focusOnOrPrev(fr.Child(nxti).(Widget))
} else {
did = em.focusOnOrPrev(fr.Child(sz - 1).(Widget))
}
if !did || em.focus == cur {
return false
}
return true
}
// focusOnName processes key events to look for an element starting with given name
func (fr *Frame) focusOnName(e events.Event) bool {
kf := keymap.Of(e.KeyChord())
if DebugSettings.KeyEventTrace {
slog.Info("Layout FocusOnName", "widget", fr, "keyFunction", kf)
}
delay := e.Time().Sub(fr.focusNameTime)
fr.focusNameTime = e.Time()
if kf == keymap.FocusNext { // tab means go to next match -- don't worry about time
if fr.focusName == "" || delay > TimingSettings.LayoutFocusNameTabTime {
fr.focusName = ""
fr.focusNameLast = nil
return false
}
} else {
if delay > TimingSettings.LayoutFocusNameTimeout {
fr.focusName = ""
}
if !unicode.IsPrint(e.KeyRune()) || e.Modifiers() != 0 {
return false
}
sr := string(e.KeyRune())
if fr.focusName == sr {
// re-search same letter
} else {
fr.focusName += sr
fr.focusNameLast = nil // only use last if tabbing
}
}
// e.SetHandled()
// fmt.Printf("searching for: %v last: %v\n", ly.FocusName, ly.FocusNameLast)
focel := childByLabelCanFocus(fr, fr.focusName, fr.focusNameLast)
if focel != nil {
em := fr.Events()
if em != nil {
em.setFocus(focel.(Widget)) // this will also scroll by default!
}
fr.focusNameLast = focel
return true
}
if fr.focusNameLast == nil {
fr.focusName = "" // nothing being found
}
fr.focusNameLast = nil // start over
return false
}
// childByLabelCanFocus uses breadth-first search to find
// the first focusable element within the layout whose Label (using
// [ToLabel]) matches the given name using [complete.IsSeedMatching].
// If after is non-nil, it only finds after that element.
func childByLabelCanFocus(fr *Frame, name string, after tree.Node) tree.Node {
gotAfter := false
completions := []complete.Completion{}
fr.WalkDownBreadth(func(n tree.Node) bool {
if n == fr.This { // skip us
return tree.Continue
}
wb := AsWidget(n)
if wb == nil || !wb.CanFocus() { // don't go any further
return tree.Continue
}
if after != nil && !gotAfter {
if n == after {
gotAfter = true
}
return tree.Continue // skip to next
}
completions = append(completions, complete.Completion{
Text: labels.ToLabel(n),
Desc: n.AsTree().PathFrom(fr),
})
return tree.Continue
})
matches := complete.MatchSeedCompletion(completions, name)
if len(matches) > 0 {
return fr.FindPath(matches[0].Desc)
}
return nil
}
// Stretch and Space: spacing elements
// Stretch adds a stretchy element that grows to fill all
// available space. You can set [styles.Style.Grow] to change
// how much it grows relative to other growing elements.
// It does not render anything.
type Stretch struct {
WidgetBase
}
func (st *Stretch) Init() {
st.WidgetBase.Init()
st.Styler(func(s *styles.Style) {
s.RenderBox = false
s.Min.X.Ch(1)
s.Min.Y.Em(1)
s.Grow.Set(1, 1)
})
}
// Space is a fixed size blank space, with
// a default width of 1ch and a height of 1em.
// You can set [styles.Style.Min] to change its size.
// It does not render anything.
type Space struct {
WidgetBase
}
func (sp *Space) Init() {
sp.WidgetBase.Init()
sp.Styler(func(s *styles.Style) {
s.RenderBox = false
s.Min.X.Ch(1)
s.Min.Y.Em(1)
s.ZeroSpace()
})
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"log/slog"
"reflect"
"strings"
"unicode"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/base/strcase"
"cogentcore.org/core/cursors"
"cogentcore.org/core/events"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/tree"
"cogentcore.org/core/types"
)
// CallFunc calls the given function in the context of the given widget,
// popping up a dialog to prompt for any arguments and show the return
// values of the function. It is a helper function that uses [NewSoloFuncButton]
// under the hood.
func CallFunc(ctx Widget, fun any) {
NewSoloFuncButton(ctx).SetFunc(fun).CallFunc()
}
// NewSoloFuncButton returns a standalone [FuncButton] with a fake parent
// with the given context for popping up any dialogs.
func NewSoloFuncButton(ctx Widget) *FuncButton {
return NewFuncButton(NewWidgetBase()).SetContext(ctx)
}
// FuncButton is a button that is set up to call a function when it
// is pressed, using a dialog to prompt the user for any arguments.
// Also, it automatically sets various properties of the button like
// the text and tooltip based on the properties of the function,
// using [reflect] and [types]. The function must be registered
// with [types] to get documentation information, but that is not
// required; add a `//types:add` comment directive and run `core generate`
// if you want tooltips. If the function is a method, both the method and
// its receiver type must be added to [types] to get documentation.
// The main function to call first is [FuncButton.SetFunc].
type FuncButton struct {
Button
// typesFunc is the [types.Func] associated with this button.
// This function can also be a method, but it must be
// converted to a [types.Func] first. It should typically
// be set using [FuncButton.SetFunc].
typesFunc *types.Func
// reflectFunc is the [reflect.Value] of the function or
// method associated with this button. It should typically
// bet set using [FuncButton.SetFunc].
reflectFunc reflect.Value
// funcText is the name of the function as text, such as "Update files",
// which is the default text of the button, for [FuncButton.Label].
funcText string
// Args are the [FuncArg] objects associated with the
// arguments of the function. They are automatically set in
// [FuncButton.SetFunc], but they can be customized to configure
// default values and other options.
Args []FuncArg `set:"-"`
// Returns are the [FuncArg] objects associated with the
// return values of the function. They are automatically
// set in [FuncButton.SetFunc], but they can be customized
// to configure options. The [FuncArg.Value]s are not set until
// the function is called, and are thus not typically applicable
// to access.
Returns []FuncArg `set:"-"`
// Confirm is whether to prompt the user for confirmation
// before calling the function.
Confirm bool
// ShowReturn is whether to display the return values of
// the function (and a success message if there are none).
// The way that the return values are shown is determined
// by ShowReturnAsDialog. Non-nil error return values will
// always be shown, even if ShowReturn is set to false.
ShowReturn bool
// ShowReturnAsDialog, if and only if ShowReturn is true,
// indicates to show the return values of the function in
// a dialog, instead of in a snackbar, as they are by default.
// If there are multiple return values from the function, or if
// one of them is a complex type (pointer, struct, slice,
// array, map), then ShowReturnAsDialog will
// automatically be set to true.
ShowReturnAsDialog bool
// NewWindow makes the return value dialog a NewWindow dialog.
NewWindow bool
// WarnUnadded is whether to log warnings when a function that
// has not been added to [types] is used. It is on by default and
// must be set before [FuncButton.SetFunc] is called for it to
// have any effect. Warnings are never logged for anonymous functions.
WarnUnadded bool `default:"true"`
// Context is used for opening dialogs if non-nil.
Context Widget
// AfterFunc is an optional function called after the func button
// function is executed.
AfterFunc func()
}
// FuncArg represents one argument or return value of a function
// in the context of a [FuncButton].
type FuncArg struct { //types:add -setters
// Name is the name of the argument or return value.
Name string
// Tag contains any tags associated with the argument or return value,
// which can be added programmatically to customize [Value] behavior.
Tag reflect.StructTag
// Value is the actual value of the function argument or return value.
// It can be modified when creating a [FuncButton] to set a default value.
Value any
}
func (fb *FuncButton) WidgetValue() any {
if !fb.reflectFunc.IsValid() {
return nil
}
return fb.reflectFunc.Interface()
}
func (fb *FuncButton) SetWidgetValue(value any) error {
fb.SetFunc(reflectx.Underlying(reflect.ValueOf(value)).Interface())
return nil
}
func (fb *FuncButton) OnBind(value any, tags reflect.StructTag) {
// If someone is viewing a function value, there is a good chance
// that it is not added to types (and that is out of their control)
// (eg: in the inspector), so we do not warn on unadded functions.
fb.SetWarnUnadded(false).SetType(ButtonTonal)
}
func (fb *FuncButton) Init() {
fb.Button.Init()
fb.WarnUnadded = true
fb.Styler(func(s *styles.Style) {
// If Disabled, these steps are unnecessary and we want the default NotAllowed cursor, so only check for ReadOnly.
if s.Is(states.ReadOnly) {
s.SetAbilities(false, abilities.Hoverable, abilities.Clickable, abilities.Activatable)
s.Cursor = cursors.None
}
})
fb.OnClick(func(e events.Event) {
if !fb.IsReadOnly() {
fb.CallFunc()
}
})
}
// SetText sets the [FuncButton.Text] and updates the tooltip to
// correspond to the new name.
func (fb *FuncButton) SetText(v string) *FuncButton {
ptext := fb.Text
fb.Text = v
if fb.typesFunc != nil && fb.Text != ptext && ptext != "" && v != "" {
fb.typesFunc.Doc = types.FormatDoc(fb.typesFunc.Doc, ptext, fb.Text)
fb.SetTooltip(fb.typesFunc.Doc)
}
return fb
}
// SetFunc sets the function associated with the FuncButton to the
// given function or method value. For documentation information for
// the function to be obtained, it must be added to [types].
func (fb *FuncButton) SetFunc(fun any) *FuncButton {
if fun == nil || reflect.ValueOf(fun).IsNil() {
return fb.SetText("None")
}
fnm := types.FuncName(fun)
if fnm == "" { // (as a closure on the web, compiled by goscript)
fnm = "reflect.makeFuncStub" // an anonymous function, as in interpreters
}
fnm = strings.ReplaceAll(fnm, "[...]", "") // remove any labeling for generics
// the "-fm" suffix indicates that it is a method
if before, ok := strings.CutSuffix(fnm, "-fm"); ok {
fnm = before
// the last dot separates the function name
li := strings.LastIndex(fnm, ".")
metnm := fnm[li+1:]
typnm := fnm[:li]
// get rid of any parentheses and pointer receivers
// that may surround the type name
typnm = strings.ReplaceAll(typnm, "(*", "")
typnm = strings.TrimSuffix(typnm, ")")
gtyp := types.TypeByName(typnm)
var met *types.Method
if gtyp == nil {
if fb.WarnUnadded {
slog.Warn("core.FuncButton.SetFunc called with a method whose receiver type has not been added to types", "function", fnm)
}
met = &types.Method{Name: metnm}
} else {
for _, m := range gtyp.Methods {
if m.Name == metnm {
met = &m
break
}
}
if met == nil {
if fb.WarnUnadded {
slog.Warn("core.FuncButton.SetFunc called with a method that has not been added to types (even though the receiver type was, you still need to add the method itself)", "function", fnm)
}
met = &types.Method{Name: metnm}
}
}
return fb.setMethodImpl(met, reflect.ValueOf(fun))
}
if isAnonymousFunction(fnm) {
f := &types.Func{Name: fnm, Doc: "Anonymous function " + fnm}
return fb.setFuncImpl(f, reflect.ValueOf(fun))
}
f := types.FuncByName(fnm)
if f == nil {
if fb.WarnUnadded {
slog.Warn("core.FuncButton.SetFunc called with a function that has not been added to types", "function", fnm)
}
f = &types.Func{Name: fnm}
}
return fb.setFuncImpl(f, reflect.ValueOf(fun))
}
func isAnonymousFunction(fnm string) bool {
// FuncName.funcN indicates that a function was defined anonymously
funcN := len(fnm) > 0 && unicode.IsDigit(rune(fnm[len(fnm)-1])) && strings.Contains(fnm, ".func")
return funcN || fnm == "reflect.makeFuncStub" // used for anonymous functions in interpreters
}
// Label returns the text of the button if it is set; otherwise it returns
// the name of the function as text, such as "Update files", for a button
// with only an icon.
func (fb *FuncButton) Label() string {
if fb.Text != "" {
return fb.Text
}
if fb.funcText != "" {
return fb.funcText
}
return fb.Name
}
// setFuncImpl is the underlying implementation of [FuncButton.SetFunc].
// It should typically not be used by end-user code.
func (fb *FuncButton) setFuncImpl(gfun *types.Func, rfun reflect.Value) *FuncButton {
fb.typesFunc = gfun
fb.reflectFunc = rfun
fb.setArgs()
fb.setReturns()
snm := fb.typesFunc.Name
// get name without package
li := strings.LastIndex(snm, ".")
isAnonymous := isAnonymousFunction(snm)
if snm == "reflect.makeFuncStub" { // used for anonymous functions in interpreters
snm = "Anonymous function"
li = -1
} else if isAnonymous {
snm = strings.TrimRightFunc(snm, func(r rune) bool {
return unicode.IsDigit(r) || r == '.'
})
snm = strings.TrimSuffix(snm, ".func")
// we cut at the second to last period (we want to keep the
// receiver / package for anonymous functions)
li = strings.LastIndex(snm[:strings.LastIndex(snm, ".")], ".")
}
if li >= 0 {
snm = snm[li+1:] // must also get rid of "."
// if we are a global function, we may have gone too far with the second to last period,
// so we go after the last slash if there still is one
if strings.Contains(snm, "/") {
snm = snm[strings.LastIndex(snm, "/")+1:]
}
}
snm = strings.Map(func(r rune) rune {
if r == '(' || r == ')' || r == '*' {
return -1
}
return r
}, snm)
txt := strcase.ToSentence(snm)
fb.funcText = txt
fb.SetText(txt)
// doc formatting interferes with anonymous functions
if !isAnonymous {
fb.typesFunc.Doc = types.FormatDoc(fb.typesFunc.Doc, snm, txt)
}
fb.SetTooltip(fb.typesFunc.Doc)
return fb
}
func (fb *FuncButton) goodContext() Widget {
ctx := fb.Context
if fb.Context == nil {
if fb.This == nil {
return nil
}
ctx = fb.This.(Widget)
}
return ctx
}
// mainScene returns the scene of the main stage of the scene of the button:
// the scene of a menu is deleted when the menu closes, which is when its
// button is clicked, so the value button of a solo argument (see
// [FuncButton.CallFunc]) must use the main scene under the menu instead,
// to be in a window when its dialog is accepted.
func (fb *FuncButton) mainScene() *Scene {
sc := fb.Scene
if sc != nil && sc.Stage != nil && sc.Stage.Main != nil && sc.Stage.Main.Scene != nil {
return sc.Stage.Main.Scene
}
return sc
}
func (fb *FuncButton) callFuncShowReturns() {
if fb.AfterFunc != nil {
defer fb.AfterFunc()
}
if len(fb.Args) == 0 {
rets := fb.reflectFunc.Call(nil)
fb.showReturnsDialog(rets)
return
}
rargs := make([]reflect.Value, len(fb.Args))
ftyp := fb.reflectFunc.Type()
for i, arg := range fb.Args {
rargs[i] = funcArgValue(arg.Value, ftyp.In(i))
}
rets := fb.reflectFunc.Call(rargs)
fb.showReturnsDialog(rets)
}
// funcArgValue returns the given argument value as the given type of the
// parameter of the function. The value widgets of the arguments can set
// a value of the underlying type of a named type (as a bool for a switch
// of a type textpos.MatchSyntax bool), which is converted to the type (only
// between types of the same kind, not int to string), and
// a nil value is the zero value of the type.
func funcArgValue(value any, typ reflect.Type) reflect.Value {
v := reflect.ValueOf(value)
if !v.IsValid() {
return reflect.Zero(typ)
}
if v.Kind() == typ.Kind() && !v.Type().AssignableTo(typ) && v.Type().ConvertibleTo(typ) {
return v.Convert(typ)
}
return v
}
// confirmDialog runs the confirm dialog.
func (fb *FuncButton) confirmDialog() {
ctx := fb.goodContext()
d := NewBody(fb.Text + "?")
NewText(d).SetType(TextSupporting).SetText("Are you sure you want to " + strings.ToLower(fb.Text) + "? " + fb.Tooltip)
d.AddBottomBar(func(bar *Frame) {
d.AddCancel(bar)
d.AddOK(bar).SetText(fb.Text).OnClick(func(e events.Event) {
fb.callFuncShowReturns()
})
})
d.RunDialog(ctx)
}
// CallFunc calls the function associated with this button,
// prompting the user for any arguments.
func (fb *FuncButton) CallFunc() {
if !fb.reflectFunc.IsValid() {
return
}
ctx := fb.goodContext()
if len(fb.Args) == 0 {
if !fb.Confirm {
fb.callFuncShowReturns()
return
}
fb.confirmDialog()
return
}
d := NewBody(fb.Text)
NewText(d).SetType(TextSupporting).SetText(fb.Tooltip)
str := funcArgsToStruct(fb.Args)
sv := NewForm(d).SetStruct(str.Addr().Interface())
// setArgs sets the arguments from the values edited in the dialog.
setArgs := func() {
for i := range fb.Args {
fb.Args[i].Value = str.Field(i).Interface()
}
}
accept := func() {
setArgs()
fb.callFuncShowReturns()
}
// If there is a single value button, automatically
// open its dialog instead of this one
if len(fb.Args) == 1 {
sv.UpdateWidget() // need to update first
bt := AsButton(sv.Child(1))
if bt != nil {
bt.OnFinal(events.Change, func(e events.Event) {
// The dialog for the argument has been accepted, so we call the
// function. This runs in the event loop of the window of this
// button, so the arguments are set from it here, and the function
// is sent to the window of the context if that is another one,
// instead of waiting on its lock.
if tree.IsNil(ctx) {
accept()
return
}
cwb := ctx.AsWidget()
if cwb.Scene == nil || cwb.Scene.RenderWindow() == nil {
accept()
return
}
setArgs()
cwb.runInWindow(bt.AsWidget(), fb.callFuncShowReturns)
})
bt.Scene = fb.mainScene() // we must use this scene for context
bt.Send(events.Click)
return
}
}
d.AddBottomBar(func(bar *Frame) {
d.AddCancel(bar)
d.AddOK(bar).SetText(fb.Text).OnClick(func(e events.Event) {
d.Close() // note: the other Close event happens too late!
accept()
})
})
d.RunDialog(ctx)
}
// funcArgsToStruct converts a slice of [FuncArg] objects
// to a new non-pointer struct [reflect.Value].
func funcArgsToStruct(args []FuncArg) reflect.Value {
fields := make([]reflect.StructField, len(args))
for i, arg := range args {
fields[i] = reflect.StructField{
Name: strcase.ToCamel(arg.Name),
Type: reflect.TypeOf(arg.Value),
Tag: arg.Tag,
}
}
typ := reflect.StructOf(fields)
value := reflect.New(typ).Elem()
for i, arg := range args {
value.Field(i).Set(reflect.ValueOf(arg.Value))
}
return value
}
// setMethodImpl is the underlying implementation of [FuncButton.SetFunc] for methods.
// It should typically not be used by end-user code.
func (fb *FuncButton) setMethodImpl(gmet *types.Method, rmet reflect.Value) *FuncButton {
return fb.setFuncImpl(&types.Func{
Name: gmet.Name,
Doc: gmet.Doc,
Directives: gmet.Directives,
Args: gmet.Args,
Returns: gmet.Returns,
}, rmet)
}
// showReturnsDialog runs a dialog displaying the given function return
// values for the function associated with the function button. It does
// nothing if [FuncButton.ShowReturn] is false.
func (fb *FuncButton) showReturnsDialog(rets []reflect.Value) {
if !fb.ShowReturn {
for _, ret := range rets {
if err, ok := reflect.TypeAssert[error](ret); ok && err != nil {
ErrorSnackbar(fb, err, fb.Text+" failed")
return
}
}
return
}
ctx := fb.goodContext()
if ctx == nil {
return
}
for i, ret := range rets {
fb.Returns[i].Value = ret.Interface()
}
main := "Result of " + fb.Text
if len(rets) == 0 {
main = fb.Text + " succeeded"
}
if !fb.ShowReturnAsDialog {
var txt strings.Builder
txt.WriteString(main)
if len(fb.Returns) > 0 {
txt.WriteString(": ")
for i, ret := range fb.Returns {
txt.WriteString(reflectx.ToString(ret.Value))
if i < len(fb.Returns)-1 {
txt.WriteString(", ")
}
}
}
MessageSnackbar(ctx, txt.String())
return
}
d := NewBody(main)
NewText(d).SetType(TextSupporting).SetText(fb.Tooltip)
d.AddOKOnly()
str := funcArgsToStruct(fb.Returns)
sv := NewForm(d).SetStruct(str.Addr().Interface()).SetReadOnly(true)
// If there is a single value button, automatically
// open its dialog instead of this one
if len(fb.Returns) == 1 {
sv.UpdateWidget() // need to update first
bt := AsButton(sv.Child(1))
if bt != nil {
bt.Scene = fb.mainScene() // we must use this scene for context
bt.Send(events.Click)
return
}
}
if fb.NewWindow {
d.RunWindowDialog(ctx)
} else {
d.RunDialog(ctx)
}
}
// setArgs sets the appropriate [Value] objects for the
// arguments of the function associated with the function button.
func (fb *FuncButton) setArgs() {
narg := fb.reflectFunc.Type().NumIn()
fb.Args = make([]FuncArg, narg)
for i := range fb.Args {
typ := fb.reflectFunc.Type().In(i)
name := ""
if fb.typesFunc.Args != nil && len(fb.typesFunc.Args) > i {
name = fb.typesFunc.Args[i]
} else {
name = reflectx.NonPointerType(typ).Name()
}
fb.Args[i] = FuncArg{
Name: name,
Value: reflect.New(typ).Elem().Interface(),
}
}
}
// setReturns sets the appropriate [Value] objects for the
// return values of the function associated with the function
// button.
func (fb *FuncButton) setReturns() {
nret := fb.reflectFunc.Type().NumOut()
fb.Returns = make([]FuncArg, nret)
hasComplex := false
for i := range fb.Returns {
typ := fb.reflectFunc.Type().Out(i)
if !hasComplex {
k := typ.Kind()
if k == reflect.Pointer || k == reflect.Struct || k == reflect.Slice || k == reflect.Array || k == reflect.Map {
hasComplex = true
}
}
name := ""
if fb.typesFunc.Returns != nil && len(fb.typesFunc.Returns) > i {
name = fb.typesFunc.Returns[i]
} else {
name = reflectx.NonPointerType(typ).Name()
}
fb.Returns[i] = FuncArg{
Name: name,
Value: reflect.New(typ).Elem().Interface(),
}
}
if nret > 1 || hasComplex {
fb.ShowReturnAsDialog = true
}
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"cogentcore.org/core/colors"
"cogentcore.org/core/cursors"
"cogentcore.org/core/events"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/units"
)
// Handle represents a draggable handle that can be used to
// control the size of an element. The [styles.Style.Direction]
// controls the direction in which the handle moves.
type Handle struct {
WidgetBase
// Min is the minimum value that the handle can go to
// (typically the lower bound of the dialog/splits)
Min float32
// Max is the maximum value that the handle can go to
// (typically the upper bound of the dialog/splits)
Max float32
// Pos is the current position of the handle on the
// scale of [Handle.Min] to [Handle.Max].
Pos float32
}
func (hl *Handle) Init() {
hl.WidgetBase.Init()
hl.Styler(func(s *styles.Style) {
s.SetAbilities(true, abilities.Clickable, abilities.Focusable, abilities.Hoverable, abilities.Slideable, abilities.SlidePriority, abilities.ScrollableUnattended)
s.Border.Radius = styles.BorderRadiusFull
s.Background = colors.Scheme.OutlineVariant
})
hl.FinalStyler(func(s *styles.Style) {
if s.Direction == styles.Row {
s.Min.X.Dp(6)
s.Min.Y.Em(2)
s.Margin.SetHorizontal(units.Dp(6))
} else {
s.Min.X.Em(2)
s.Min.Y.Dp(6)
s.Margin.SetVertical(units.Dp(6))
}
if !hl.IsReadOnly() {
if s.Direction == styles.Row {
s.Cursor = cursors.ResizeEW
} else {
s.Cursor = cursors.ResizeNS
}
}
})
hl.On(events.SlideMove, func(e events.Event) {
e.SetHandled()
pos := hl.parentWidget().PointToRelPos(e.Pos())
hl.Pos = math32.FromPoint(pos).Dim(hl.Styles.Direction.Dim())
hl.SendChange(e)
})
}
// Value returns the value on a normalized scale of 0-1,
// based on [Handle.Pos], [Handle.Min], and [Handle.Max].
func (hl *Handle) Value() float32 {
return (hl.Pos - hl.Min) / (hl.Max - hl.Min)
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"image"
"image/color"
"strings"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/colors"
"cogentcore.org/core/colors/gradient"
"cogentcore.org/core/icons"
"cogentcore.org/core/styles"
"cogentcore.org/core/svg"
"golang.org/x/image/draw"
)
// Icon renders an [icons.Icon].
// The rendered version is cached for the current size.
// Icons do not render a background or border independent of their SVG object.
// The size of an Icon is determined by the [styles.Font.Size] property.
type Icon struct {
WidgetBase
// Icon is the [icons.Icon] used to render the [Icon].
Icon icons.Icon
// prevIcon is the previously rendered icon.
prevIcon icons.Icon
// prevColor is the previously rendered color, as uniform.
prevColor color.RGBA
// prevOpacity is the previously rendered opacity.
prevOpacity float32
// image representation of the icon, cached for faster drawing.
pixels image.Image
}
func (ic *Icon) WidgetValue() any { return &ic.Icon }
func (ic *Icon) Init() {
ic.WidgetBase.Init()
ic.FinalStyler(func(s *styles.Style) {
s.Min = s.IconSize
})
}
// RerenderSVG forcibly renders the icon, returning the [svg.SVG]
// used to render.
func (ic *Icon) RerenderSVG() *svg.SVG {
ic.pixels = nil
ic.prevIcon = ""
return ic.renderSVG()
}
// renderSVG renders the icon if necessary, returning the [svg.SVG]
// used to render if it was rendered, otherwise nil.
func (ic *Icon) renderSVG() *svg.SVG {
sz := ic.Geom.Size.Actual.Content.ToPoint()
if sz == (image.Point{}) {
return nil
}
var isz image.Point
if ic.pixels != nil {
isz = ic.pixels.Bounds().Size()
}
cc := colors.ToUniform(ic.Styles.Color)
if ic.Icon == ic.prevIcon && sz == isz && ic.prevColor == cc && ic.prevOpacity == ic.Styles.Opacity && !ic.NeedsRebuild() {
return nil
}
ic.pixels = nil
if !ic.Icon.IsSet() {
ic.prevIcon = ic.Icon
return nil
}
sv := svg.NewSVG(ic.Geom.Size.Actual.Content)
err := sv.ReadXML(strings.NewReader(string(ic.Icon)))
if errors.Log(err) != nil || sv.Root == nil || !sv.Root.HasChildren() {
return nil
}
icons.AddUsed(ic.Icon)
ic.prevIcon = ic.Icon
sv.Root.ViewBox.PreserveAspectRatio.SetFromStyle(&ic.Styles)
sv.TextShaper = ic.Scene.TextShaper()
clr := gradient.ApplyOpacity(ic.Styles.Color, ic.Styles.Opacity)
sv.DefaultFill = clr
sv.Scale = 1
ic.pixels = sv.RenderImage()
ic.prevColor = cc
ic.prevOpacity = ic.Styles.Opacity
return sv
}
func (ic *Icon) Render() {
ic.renderSVG()
if ic.pixels == nil {
return
}
r := ic.Geom.ContentBBox
sp := ic.Geom.ScrollOffset()
ic.Scene.Painter.DrawImage(ic.pixels, nil, r, sp, draw.Over)
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"time"
"cogentcore.org/core/enums"
)
// idle.go has the pausing of the paint events of a window while there is
// nothing to update in it (see [system.Window.PaintIdle]), so that an
// idle app does not use the CPU, as on mobile in the background (#1659).
// The window is woken (see [renderWindow.wake]) by everything that needs
// an update: the flags of its scenes that drive updates, changes to its
// stages and sprites, animations, and all events.
// wake resumes the paint events of the window, if they are paused, as
// something in it needs to be updated. It can be called from any
// goroutine, and is cheap when the window is already awake.
func (w *renderWindow) wake() {
if w == nil || w.paintWanted.Swap(true) {
return
}
if sw := w.SystemWindow; sw != nil {
sw.PaintWake()
}
}
// goIdle pauses the paint events of the window, as there is nothing to
// update in it, until it is woken; it is woken right away if something
// needed an update since this render pass started.
func (w *renderWindow) goIdle() {
sw := w.SystemWindow
if sw == nil {
return
}
sw.PaintIdle()
if w.paintWanted.Load() {
sw.PaintWake()
}
}
// redrawAll makes the next render pass draw all of the scenes of the
// window again, even if nothing in them changed, as the window may be
// drawn to a new surface: on mobile, the system window of an app is made
// again when it comes back from the background, with the same size, and
// stayed blank, as the window went idle without drawing to it.
func (w *renderWindow) redrawAll() {
w.flags.SetFlag(true, winRenderSkipped)
w.wake()
}
// idleUntilBlink pauses the paint events of the window until the next
// blink of its active sprites, such as the text cursor, if it has focus.
func (w *renderWindow) idleUntilBlink(top *Stage, blink time.Duration) {
if w.flags.HasFlag(winGotFocus) && top.Sprites.hasActive() {
d := max(blink-time.Since(w.lastSpriteDraw), time.Millisecond)
if w.blinkTimer == nil {
w.blinkTimer = time.AfterFunc(d, w.wake)
} else {
w.blinkTimer.Reset(d)
}
}
w.goIdle()
}
// hasAnimations returns whether any scene of the main stages, or of
// their popups, has animations, which run at every paint event.
func (sm *stages) hasAnimations() bool {
for _, st := range sm.stack.Values {
if st.Scene != nil && len(st.Scene.Animations) > 0 {
return true
}
if st.Type.isMain() && st.popups != nil && st.popups != sm && st.popups.hasAnimations() {
return true
}
}
return false
}
// wake wakes the window of the stages (see [renderWindow.wake]).
func (sm *stages) wake() {
if sm.renderWindow != nil {
sm.renderWindow.wake()
return
}
if sm.main != nil {
sm.main.wake()
}
}
// setModified records that the stages have been modified, waking their
// window to update them.
func (sm *stages) setModified() {
sm.modified = true
sm.wake()
}
// wake wakes the window of the stage (see [renderWindow.wake]).
func (st *Stage) wake() {
if st == nil {
return
}
if sm := st.mains.Load(); sm != nil && sm.renderWindow != nil {
sm.renderWindow.wake()
}
}
// wake wakes the window of the scene (see [renderWindow.wake]).
func (sc *Scene) wake() {
sc.RenderWindow().wake()
}
// wakeFlags returns whether any of the given flags drives an update of
// a scene, for which its window is woken when one is set.
func wakeFlags(f []enums.BitFlag) bool {
for _, fl := range f {
switch fl {
case sceneNeedsRender, sceneNeedsLayout, sceneHasDeferred:
return true
}
}
return false
}
// setModifiedNoLock records that the sprites have been modified, waking
// the window of their stage to draw them.
func (ss *Sprites) setModifiedNoLock() {
ss.modified = true
ss.stage.wake()
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"image/color"
stddraw "image/draw"
"cogentcore.org/core/paint"
"image"
"io/fs"
"cogentcore.org/core/base/iox/imagex"
"cogentcore.org/core/icons"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint/renderers/rasterx"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/sides"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/system"
"cogentcore.org/core/tree"
"golang.org/x/image/draw"
)
// Image is a widget that renders an [image.Image].
// See [styles.Style.ObjectFit] to control the image rendering within
// the allocated size. The default minimum requested size is the pixel
// size in [units.Dp] units (1/160th of an inch).
type Image struct {
WidgetBase
// Image is the [image.Image].
Image image.Image `xml:"-" json:"-"`
// NaturalDp is whether the natural size of the image (when it has no
// Min size) is its size in pixels in dp, as for the CSS px of images
// in web pages, rather than in dots: on a screen with two dots per dp,
// it is twice as large, as in browsers (as the photos of the postings
// of craigslist.org, which were half their size on retina screens).
NaturalDp bool `set:"-" display:"-"`
// Density is the number of pixels of the image per dp of its natural
// size with NaturalDp (as of a candidate of the srcset of an img in a
// web page, as an image of 2x is shown at half its size in pixels);
// 0 is 1.
Density float32 `set:"-" display:"-"`
// prevImage is the cached last [Image.Image].
prevImage image.Image
// prevRenderImage is the cached last rendered image with any transformations applied.
prevRenderImage image.Image
// prevObjectFit is the cached [styles.Style.ObjectFit] of the last rendered image.
prevObjectFit styles.ObjectFits
// prevSize is the cached allocated size for the last rendered image.
prevSize math32.Vector2
}
func (im *Image) WidgetValue() any { return &im.Image }
func (im *Image) Init() {
im.WidgetBase.Init()
im.Styler(func(s *styles.Style) {
s.ObjectFit = styles.FitContain
})
}
// Open sets the image to the image located at the given filename.
func (im *Image) Open(filename Filename) error { //types:add
img, _, err := imagex.Open(string(filename))
if err != nil {
return err
}
im.SetImage(img)
return nil
}
// OpenFS sets the image to the image located at the given filename in the given fs.
func (im *Image) OpenFS(fsys fs.FS, filename string) error {
img, _, err := imagex.OpenFS(fsys, filename)
if err != nil {
return err
}
im.SetImage(img)
return nil
}
func (im *Image) SizeUp() {
im.WidgetBase.SizeUp()
if im.Image != nil {
sz := &im.Geom.Size
obj := im.aspectSize(math32.FromPoint(im.Image.Bounds().Size()))
if dp := im.Styles.UnitContext.Dots(units.UnitDp); im.NaturalDp && dp > 0 {
obj = obj.MulScalar(dp)
if im.Density > 0 {
obj = obj.DivScalar(im.Density)
}
}
csz := sz.Actual.Content
// if only one min size is specified, then allow the other to expand
if im.Styles.Min.Y.Value != 0 && im.Styles.Min.X.Value == 0 {
csz.X = math32.Floor((im.Styles.Min.Y.Dots / obj.Y) * obj.X)
} else if im.Styles.Min.X.Value != 0 && im.Styles.Min.Y.Value == 0 {
csz.Y = im.roundHeight((im.Styles.Min.X.Dots / obj.X) * obj.Y)
} else if im.Styles.Min.X.Value == 0 && im.Styles.Min.Y.Value == 0 {
pwd := float32(0)
pwb := im.parentWidget()
if pwb != nil {
psz := pwb.Geom.Size.Alloc.Content.Sub(pwb.Geom.Size.InnerSpace)
pwd = 0.95 * psz.X
}
if pwd > 0 {
csz.X = min(obj.X, pwd)
csz.Y = im.roundHeight((csz.X / obj.X) * obj.Y)
} else {
csz = obj
}
}
osz := styles.ObjectSizeFromFit(im.Styles.ObjectFit, obj, csz)
sz.Actual.Content = osz
sz.SetTotalFromContent(&sz.Actual)
}
}
// aspectSize returns the given size of the image with the aspect ratio of
// [styles.Style.AspectRatio], if it is set, which is the aspect of the box
// of the image (as the aspect-ratio property of CSS, as for a video of
// another aspect than its box, which then fits in the box by ObjectFit).
func (im *Image) aspectSize(size math32.Vector2) math32.Vector2 {
if r := im.Styles.AspectRatio; r > 0 && size.X > 0 {
size.Y = size.X / r
}
return size
}
// roundHeight returns the given height of the image rounded down, or up
// for an [styles.Style.AspectRatio], as the height of the aspect ratio of
// other widgets is.
func (im *Image) roundHeight(h float32) float32 {
if im.Styles.AspectRatio > 0 {
return math32.Ceil(h)
}
return math32.Floor(h)
}
// SizeDown sets the height of an image whose width is relative
// to its parent, or is limited by a Max relative to it (as an image of
// max-width: 100% in web pages), and whose height is not set, from that
// width, which is only known now, keeping the aspect ratio of the image.
func (im *Image) SizeDown(iter int) bool {
redo := im.WidgetBase.SizeDown(iter)
minX, minY, maxX := im.Styles.Min.X, im.Styles.Min.Y, im.Styles.Max.X
// (a custom length is of the parent too, as min(2rem, 100%))
relative := func(v units.Value) bool { return v.Unit == units.UnitPw || v.Unit == units.UnitPh || v.Custom != nil }
if im.Image == nil || minY.Value != 0 || (!relative(minX) && !relative(maxX)) {
return redo
}
sz := &im.Geom.Size
obj := im.aspectSize(math32.FromPoint(im.Image.Bounds().Size()))
w := sz.Actual.Content.X
h := im.roundHeight((w / obj.X) * obj.Y)
if w <= 0 || sz.Actual.Content.Y == h {
return redo
}
sz.Actual.Content.Y = h
sz.SetTotalFromContent(&sz.Actual)
return true
}
func (im *Image) Render() {
im.WidgetBase.Render()
if im.Image == nil {
return
}
r := im.Geom.ContentBBox
if r == (image.Rectangle{}) || im.Image.Bounds().Size() == (image.Point{}) {
return
}
sp := im.Geom.ScrollOffset()
useLocalResize := false
if TheApp.Platform() == system.Web && im.Scene != nil {
// we are using an image renderer, e.g. PDF, offline rendering.
// note that there is no way to get transformed image back from javascript :(
// which would be the cleaner solution here.
if _, ok := im.Scene.Renderer.(*rasterx.Renderer); ok {
if _, ok := im.prevRenderImage.(*imagex.JSRGBA); ok {
im.prevImage = nil // clear
}
useLocalResize = true
}
}
var rimg image.Image
if im.prevImage == im.Image && im.Styles.ObjectFit == im.prevObjectFit && im.Geom.Size.Actual.Content == im.prevSize {
rimg = im.prevRenderImage
} else {
im.prevImage = im.Image
im.prevObjectFit = im.Styles.ObjectFit
im.prevSize = im.Geom.Size.Actual.Content
if useLocalResize {
rimg = im.Styles.ResizeImageLocal(im.Image, im.Geom.Size.Actual.Content)
} else {
rimg = im.Styles.ResizeImage(im.Image, im.Geom.Size.Actual.Content)
}
// the image is in its rounded corners, as in CSS (as the round
// avatars of lobste.rs)
if radius := im.Styles.Border.Radius.Dots(); !sides.AreZero(radius.Sides) {
rimg = roundCorners(rimg, radius)
}
im.prevRenderImage = rimg
}
// the image is centered in the content box when it is smaller, as by
// ObjectFit contain, as object-position is 50% 50% by default in CSS
if isz, box := rimg.Bounds().Size(), im.Geom.Size.Actual.Content.ToPoint(); isz.X < box.X || isz.Y < box.Y {
off := image.Pt(max(box.X-isz.X, 0)/2, max(box.Y-isz.Y, 0)/2)
org := im.Geom.Pos.Content.ToPoint().Add(off)
r = image.Rectangle{Min: org, Max: org.Add(isz)}.Intersect(im.Geom.ContentBBox)
if r.Empty() {
return
}
sp = r.Min.Sub(org)
}
pim := im.Scene.Painter.DrawImage(rimg, im.Image, r, sp, draw.Over)
if id, ok := im.Properties["id"]; ok {
pim.Anchor = id.(string)
}
}
func (im *Image) MakeToolbar(p *tree.Plan) {
tree.Add(p, func(w *FuncButton) {
w.SetFunc(im.Open).SetIcon(icons.Open)
})
}
// roundCorners returns the given image with its corners rounded by the
// given radii (top left, top right, bottom right, bottom left), outside of
// which it is transparent, with antialiased edges.
func roundCorners(img image.Image, radius sides.Floats) image.Image {
b := img.Bounds()
w, h := float32(b.Dx()), float32(b.Dy())
radius = paint.ClampBorderRadius(radius, w, h)
out := image.NewRGBA(image.Rect(0, 0, b.Dx(), b.Dy()))
mask := image.NewAlpha(out.Bounds())
for y := 0; y < b.Dy(); y++ {
for x := 0; x < b.Dx(); x++ {
px, py := float32(x)+0.5, float32(y)+0.5
// the center of the corner that the pixel is in, if any
var r, cx, cy float32
switch {
case px < radius.Top && py < radius.Top:
r, cx, cy = radius.Top, radius.Top, radius.Top
case px > w-radius.Right && py < radius.Right:
r, cx, cy = radius.Right, w-radius.Right, radius.Right
case px > w-radius.Bottom && py > h-radius.Bottom:
r, cx, cy = radius.Bottom, w-radius.Bottom, h-radius.Bottom
case px < radius.Left && py > h-radius.Left:
r, cx, cy = radius.Left, radius.Left, h-radius.Left
}
a := float32(1)
if r > 0 {
d := math32.Hypot(px-cx, py-cy)
a = math32.Clamp(r-d+0.5, 0, 1)
}
mask.SetAlpha(x, y, color.Alpha{uint8(a*255 + 0.5)})
}
}
stddraw.DrawMask(out, out.Bounds(), img, b.Min, mask, image.Point{}, stddraw.Over)
return out
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"cogentcore.org/core/base/dirsort"
"cogentcore.org/core/system"
)
func init() {
system.HandleRecover = handleRecover
system.UpdateLogicalDPIScaleFunc = AppearanceSettings.updateLogicalDPI
TheApp.CogentCoreDataDir() // ensure it exists
theWindowGeometrySaver.open()
if TheApp.Platform() != system.Offscreen {
// the sort orders of directories are shared by all apps
dirsort.DataDir = TheApp.CogentCoreDataDir()
} else {
// tests do not depend on the file manager of the machine
dirsort.Native = nil
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"image"
"reflect"
"strconv"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/styles"
"cogentcore.org/core/tree"
)
// InlineList represents a slice within a single line of value widgets.
// This is typically used for smaller slices.
type InlineList struct {
Frame
// Slice is the slice that we are viewing.
Slice any `set:"-"`
// isArray is whether the slice is actually an array.
isArray bool
}
func (il *InlineList) WidgetValue() any { return &il.Slice }
func (il *InlineList) Init() {
il.Frame.Init()
il.Styler(func(s *styles.Style) {
// the items flow onto the next lines when there is not room for
// all of them on one, which they are on otherwise (as it shrinks),
// instead of needing a horizontal scrollbar
s.Wrap = true
s.Shrink.X = 1
})
il.Maker(func(p *tree.Plan) {
sl := reflectx.Underlying(reflect.ValueOf(il.Slice))
sz := min(sl.Len(), AppearanceSettings.InlineLengths.Slice)
for i := range sz {
itxt := strconv.Itoa(i)
tree.AddNew(p, "value-"+itxt, func() Value {
val := reflectx.UnderlyingPointer(sl.Index(i))
return NewValue(val.Interface(), "")
}, func(w Value) {
wb := w.AsWidget()
wb.OnChange(func(e events.Event) { il.SendChange() })
wb.OnInput(func(e events.Event) {
il.Send(events.Input, e)
})
if il.IsReadOnly() {
wb.SetReadOnly(true)
} else {
menu := func(m *Scene, pos image.Point) {
il.contextMenu(m, i)
}
wb.AddContextMenu(menu)
// also on the widgets in it, as the fields of a struct,
// which get the clicks, and have their own menus
wb.FinalUpdater(func() {
wb.WidgetWalkDown(func(cw Widget, cwb *WidgetBase) bool {
if cwb == wb || cwb.Property(inlineListItemMenu) != nil {
return tree.Continue
}
cwb.SetProperty(inlineListItemMenu, true)
cwb.AddContextMenu(menu)
return tree.Continue
})
})
}
wb.Updater(func() {
// We need to get the current value each time:
sl := reflectx.Underlying(reflect.ValueOf(il.Slice))
val := reflectx.UnderlyingPointer(sl.Index(i))
Bind(val.Interface(), w)
wb.SetReadOnly(il.IsReadOnly())
})
})
}
if !il.isArray && !il.IsReadOnly() {
tree.AddAt(p, "add-button", func(w *Button) {
w.SetIcon(icons.Add).SetType(ButtonTonal)
w.Tooltip = "Add an element to the list"
w.OnClick(func(e events.Event) {
il.NewAt(-1)
})
})
}
})
}
// SetSlice sets the source slice that we are viewing.
// It rebuilds the children to represent this slice.
func (il *InlineList) SetSlice(sl any) *InlineList {
if reflectx.IsNil(reflect.ValueOf(sl)) {
il.Slice = nil
return il
}
newslc := false
if reflect.TypeOf(sl).Kind() != reflect.Pointer { // prevent crash on non-comparable
newslc = true
} else {
newslc = il.Slice != sl
}
if newslc {
il.Slice = sl
il.isArray = reflectx.NonPointerType(reflect.TypeOf(sl)).Kind() == reflect.Array
il.Update()
}
return il
}
// NewAt inserts a new blank element at the given index in the slice.
// -1 indicates to insert the element at the end.
func (il *InlineList) NewAt(idx int) {
if il.isArray {
return
}
reflectx.SliceNewAt(il.Slice, idx)
il.UpdateChange()
}
// DeleteAt deletes the element at the given index from the slice.
func (il *InlineList) DeleteAt(idx int) {
if il.isArray {
return
}
reflectx.SliceDeleteAt(il.Slice, idx)
il.UpdateChange()
}
// inlineListItemMenu is the property of the widgets in an item of an
// [InlineList] that have the context menu of the item.
const inlineListItemMenu = "inline-list-item-menu"
func (il *InlineList) contextMenu(m *Scene, idx int) {
if il.IsReadOnly() || il.isArray {
return
}
NewButton(m).SetText("Add").SetIcon(icons.Add).OnClick(func(e events.Event) {
il.NewAt(idx)
})
NewButton(m).SetText("Delete").SetIcon(icons.Delete).OnClick(func(e events.Event) {
il.DeleteAt(idx)
})
NewButton(m).SetText("Open in dialog").SetIcon(icons.OpenInNew).OnClick(func(e events.Event) {
d := NewBody(il.ValueTitle)
NewText(d).SetType(TextSupporting).SetText(il.Tooltip)
NewList(d).SetSlice(il.Slice).SetValueTitle(il.ValueTitle).SetReadOnly(il.IsReadOnly())
d.OnClose(func(e events.Event) {
il.UpdateChange()
})
d.RunFullDialog(il)
})
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"fmt"
"reflect"
"cogentcore.org/core/base/iox/jsonx"
"cogentcore.org/core/base/labels"
"cogentcore.org/core/colors"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/keymap"
"cogentcore.org/core/styles"
"cogentcore.org/core/tree"
)
// Inspector represents a [tree.Node] with a [Tree] and a [Form].
type Inspector struct {
Frame
// Root is the root of the tree being edited.
Root tree.Node
// currentNode is the currently selected node in the tree.
currentNode tree.Node
// filename is the current filename for saving / loading
filename Filename
treeWidget *Tree
}
func (is *Inspector) Init() {
is.Frame.Init()
is.Styler(func(s *styles.Style) {
s.Grow.Set(1, 1)
s.Direction = styles.Column
})
var titleWidget *Text
tree.AddChildAt(is, "title", func(w *Text) {
titleWidget = w
is.currentNode = is.Root
w.SetType(TextHeadlineSmall)
w.Styler(func(s *styles.Style) {
s.Grow.Set(1, 0)
s.Align.Self = styles.Center
})
w.Updater(func() {
w.SetText(fmt.Sprintf("Inspector of %s (%s)", is.currentNode.AsTree().Name, labels.FriendlyTypeName(reflect.TypeOf(is.currentNode))))
})
})
renderRebuild := func() {
sc, ok := is.Root.(*Scene)
if !ok {
return
}
sc.runInWindow(is.AsWidget(), func() {
sc.renderContext().rebuild = true // trigger full rebuild
})
}
tree.AddChildAt(is, "splits", func(w *Splits) {
w.SetSplits(.3, .7)
var form *Form
tree.AddChildAt(w, "tree-frame", func(w *Frame) {
w.Styler(func(s *styles.Style) {
s.Background = colors.Scheme.SurfaceContainerLow
s.Direction = styles.Column
s.Overflow.Set(styles.OverflowAuto)
s.Gap.Zero()
})
tree.AddChildAt(w, "tree", func(w *Tree) {
// (its nodes are as wide as the frame, which scrolls
// them when they are wider, as of long names)
is.treeWidget = w
w.OnSelect(func(e events.Event) {
if len(w.SelectedNodes) == 0 {
return
}
sn := w.SelectedNodes[0].AsCoreTree().SyncNode
is.currentNode = sn
// Note: doing Update on the entire inspector reverts all tree expansion,
// so we only want to update the title and form
titleWidget.Update()
form.SetStruct(sn).Update()
sc, ok := is.Root.(*Scene)
if !ok {
return
}
if wb := AsWidget(sn); wb != nil {
// The inspected scene is typically in another window.
sc.runInWindow(is.AsWidget(), func() {
pselw := sc.selectedWidget
sc.selectedWidget = sn.(Widget)
wb.NeedsRender()
if pselw != nil {
pselw.AsWidget().NeedsRender()
}
})
}
})
w.OnChange(func(e events.Event) {
renderRebuild()
})
w.SyncTree(is.Root)
})
})
tree.AddChildAt(w, "struct", func(w *Form) {
form = w
w.OnChange(func(e events.Event) {
renderRebuild()
})
w.OnClose(func(e events.Event) {
sc, ok := is.Root.(*Scene)
if !ok {
return
}
sc.runInWindow(is.AsWidget(), func() {
if sc.renderBBoxes {
is.toggleSelectionModeOf(sc)
}
pselw := sc.selectedWidget
sc.selectedWidget = nil
if pselw != nil {
pselw.AsWidget().NeedsRender()
}
})
})
w.Updater(func() {
w.SetStruct(is.currentNode)
})
})
})
}
// save saves the tree to current filename, in a standard JSON-formatted file.
func (is *Inspector) save() error { //types:add
if is.Root == nil {
return nil
}
if is.filename == "" {
return nil
}
err := jsonx.Save(is.Root, string(is.filename))
if err != nil {
return err
}
return nil
}
// saveAs saves tree to given filename, in a standard JSON-formatted file
func (is *Inspector) saveAs(filename Filename) error { //types:add
if is.Root == nil {
return nil
}
err := jsonx.Save(is.Root, string(filename))
if err != nil {
return err
}
is.filename = filename
is.NeedsRender() // notify our editor
return nil
}
// open opens tree from given filename, in a standard JSON-formatted file
func (is *Inspector) open(filename Filename) error { //types:add
if is.Root == nil {
return nil
}
err := jsonx.Open(is.Root, string(filename))
if err != nil {
return err
}
is.filename = filename
is.NeedsRender() // notify our editor
return nil
}
// toggleSelectionMode toggles the editor between selection mode or not.
// In selection mode, bounding boxes are rendered around each Widget,
// and clicking on a Widget pulls it up in the inspector.
func (is *Inspector) toggleSelectionMode() { //types:add
sc, ok := is.Root.(*Scene)
if !ok {
return
}
sc.runInWindow(is.AsWidget(), func() {
is.toggleSelectionModeOf(sc)
})
}
// toggleSelectionModeOf does [Inspector.toggleSelectionMode] for the given
// inspected scene, in its window.
func (is *Inspector) toggleSelectionModeOf(sc *Scene) {
sc.renderBBoxes = !sc.renderBBoxes
if sc.renderBBoxes {
ch := make(chan Widget)
sc.selectedWidgetChan = ch
sc.Stage.raise() // (here, in the window of the scene, with its lock)
go is.selectionMonitor(sc, ch)
} else {
if sc.selectedWidgetChan != nil {
close(sc.selectedWidgetChan)
}
sc.selectedWidgetChan = nil
}
sc.NeedsLayout()
}
// selectionMonitor monitors for the widget of the given inspected scene
// that is selected, sent on the given channel, in its own goroutine.
func (is *Inspector) selectionMonitor(sc *Scene, ch chan Widget) {
sw, ok := <-ch
if !ok || sw == nil {
return
}
tv := is.treeNodeOf(sw)
if tv == nil {
MessageSnackbar(is, fmt.Sprintf("Inspector: tree node missing: %v", sw))
return
}
is.AsyncLock() // coming from other tree
tv.OpenParents()
tv.SelectEvent(events.SelectOne)
tv.ScrollToThis()
is.Scene.Stage.raise()
is.AsyncUnlock()
sc.AsyncLock()
sc.renderBBoxes = false
if sc.selectedWidgetChan != nil {
close(sc.selectedWidgetChan)
}
sc.selectedWidgetChan = nil
sc.NeedsRender()
sc.AsyncUnlock()
}
// treeNodeOf returns the node of the tree of the inspector for the given
// widget, or for its nearest ancestor that is in the tree, as for a part
// of a widget, which is not in the tree; or nil.
func (is *Inspector) treeNodeOf(w Widget) *Tree {
if tv := is.treeWidget.FindSyncNode(w); tv != nil {
return tv
}
for k := range w.AsTree().Ancestors() {
if tv := is.treeWidget.FindSyncNode(k); tv != nil {
return tv
}
}
return nil
}
// inspectApp displays [TheApp].
func (is *Inspector) inspectApp() { //types:add
d := NewBody("Inspect app")
NewForm(d).SetStruct(TheApp).SetReadOnly(true)
d.RunFullDialog(is)
}
func (is *Inspector) MakeToolbar(p *tree.Plan) {
tree.Add(p, func(w *FuncButton) {
w.SetFunc(is.toggleSelectionMode).SetText("Select element").SetIcon(icons.ArrowSelectorTool)
w.Updater(func() {
_, ok := is.Root.(*Scene)
w.SetEnabled(ok)
})
})
tree.Add(p, func(w *Separator) {})
tree.Add(p, func(w *FuncButton) {
w.SetFunc(is.open).SetIcon(icons.Open).SetKey(keymap.Open)
w.Args[0].SetValue(is.filename).SetTag(`extension:".json"`)
})
tree.Add(p, func(w *FuncButton) {
w.SetFunc(is.save).SetIcon(icons.Save).SetKey(keymap.Save)
w.Updater(func() {
w.SetEnabled(is.filename != "")
})
})
tree.Add(p, func(w *FuncButton) {
w.SetFunc(is.saveAs).SetIcon(icons.SaveAs).SetKey(keymap.SaveAs)
w.Args[0].SetValue(is.filename).SetTag(`extension:".json"`)
})
tree.Add(p, func(w *Separator) {})
tree.Add(p, func(w *FuncButton) {
w.SetFunc(is.inspectApp).SetIcon(icons.Devices)
})
}
// InspectorWindow opens an interactive editor of the given tree
// in a new window.
func InspectorWindow(n tree.Node) {
if RecycleMainWindow(n) {
return
}
d := NewBody("Inspector")
makeInspector(d, n)
d.RunWindow()
}
// makeInspector configures the given body to have an interactive inspector
// of the given tree.
func makeInspector(b *Body, n tree.Node) {
b.SetTitle("Inspector").SetData(n)
if n != nil {
b.Name += "-" + n.AsTree().Name
b.Title += ": " + n.AsTree().Name
}
is := NewInspector(b)
is.SetRoot(n)
b.AddTopBar(func(bar *Frame) {
NewToolbar(bar).Maker(is.MakeToolbar)
})
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"image"
"cogentcore.org/core/events"
"cogentcore.org/core/events/key"
"cogentcore.org/core/icons"
"cogentcore.org/core/keymap"
"cogentcore.org/core/styles/states"
)
// KeyMapButton represents a [keymap.MapName] value with a button.
type KeyMapButton struct {
Button
MapName keymap.MapName
}
func (km *KeyMapButton) WidgetValue() any { return &km.MapName }
func (km *KeyMapButton) Init() {
km.Button.Init()
km.SetType(ButtonTonal)
km.Updater(func() {
km.SetText(string(km.MapName))
})
InitValueButton(km, false, func(d *Body) {
d.SetTitle("Select a key map")
si := 0
_, curRow, _ := keymap.AvailableMaps.MapByName(km.MapName)
tv := NewTable(d).SetSlice(&keymap.AvailableMaps).SetSelectedIndex(curRow).BindSelect(&si)
tv.OnChange(func(e events.Event) {
name := keymap.AvailableMaps[si]
km.MapName = keymap.MapName(name.Name)
})
})
}
// KeyChordButton represents a [key.Chord] value with a button.
type KeyChordButton struct {
Button
Chord key.Chord
}
func (kc *KeyChordButton) WidgetValue() any { return &kc.Chord }
func (kc *KeyChordButton) Init() {
kc.Button.Init()
kc.SetType(ButtonTonal)
kc.OnKeyChord(func(e events.Event) {
if !kc.StateIs(states.Focused) {
return
}
kc.Chord = e.KeyChord()
e.SetHandled()
kc.UpdateChange()
})
kc.Updater(func() {
kc.SetText(kc.Chord.Label())
})
kc.AddContextMenu(func(m *Scene, pos image.Point) {
NewButton(m).SetText("Clear").SetIcon(icons.ClearAll).OnClick(func(e events.Event) {
kc.Chord = ""
kc.UpdateChange()
})
})
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"fmt"
"image"
"reflect"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/styles"
"cogentcore.org/core/tree"
"cogentcore.org/core/types"
)
// KeyedList represents a map value using two columns of editable key and value widgets.
type KeyedList struct {
Frame
// Map is the pointer to the map that we are viewing.
Map any
// Inline is whether to display the map in one line.
Inline bool
// SortByValues is whether to sort by values instead of keys.
SortByValues bool
// ncols is the number of columns to display if the keyed list is not inline.
ncols int
}
func (kl *KeyedList) WidgetValue() any { return &kl.Map }
func (kl *KeyedList) Init() {
kl.Frame.Init()
kl.Styler(func(s *styles.Style) {
if kl.Inline {
return
}
s.Display = styles.Grid
s.Columns = kl.ncols
s.Overflow.Set(styles.OverflowAuto)
s.Grow.Set(1, 1)
s.Min.X.Em(20)
s.Min.Y.Em(10)
})
kl.Maker(func(p *tree.Plan) {
mapv := reflectx.Underlying(reflect.ValueOf(kl.Map))
if reflectx.IsNil(mapv) {
return
}
kl.ncols = 2
typeAny := false
valueType := mapv.Type().Elem()
if valueType.String() == "interface {}" {
kl.ncols = 3
typeAny = true
}
builtinTypes := types.BuiltinTypes()
keys := reflectx.MapSort(kl.Map, !kl.SortByValues, reflectx.Ascending)
for _, key := range keys {
keytxt := reflectx.ToString(key.Interface())
keynm := "key-" + keytxt
valnm := "value-" + keytxt
tree.AddNew(p, keynm, func() Value {
return toValue(key.Interface(), "")
}, func(w Value) {
bindMapKey(mapv, key, w)
wb := w.AsWidget()
wb.SetReadOnly(kl.IsReadOnly())
wb.Styler(func(s *styles.Style) {
s.SetReadOnly(kl.IsReadOnly())
s.SetTextWrap(false)
})
wb.OnChange(func(e events.Event) {
kl.UpdateChange(e)
})
wb.SetReadOnly(kl.IsReadOnly())
wb.OnInput(kl.HandleEvent)
if !kl.IsReadOnly() {
wb.AddContextMenu(func(m *Scene, pos image.Point) {
kl.contextMenu(m, key)
})
}
wb.Updater(func() {
bindMapKey(mapv, key, w)
wb.SetReadOnly(kl.IsReadOnly())
})
})
tree.AddNew(p, valnm, func() Value {
val := mapv.MapIndex(key).Interface()
w := toValue(val, "")
return bindMapValue(mapv, key, w)
}, func(w Value) {
wb := w.AsWidget()
wb.SetReadOnly(kl.IsReadOnly())
wb.OnChange(func(e events.Event) { kl.SendChange(e) })
wb.OnInput(kl.HandleEvent)
wb.Styler(func(s *styles.Style) {
s.SetReadOnly(kl.IsReadOnly())
s.SetTextWrap(false)
})
if !kl.IsReadOnly() {
wb.AddContextMenu(func(m *Scene, pos image.Point) {
kl.contextMenu(m, key)
})
}
wb.Updater(func() {
bindMapValue(mapv, key, w)
wb.SetReadOnly(kl.IsReadOnly())
})
})
if typeAny {
typnm := "type-" + keytxt
tree.AddAt(p, typnm, func(w *Chooser) {
w.SetTypes(builtinTypes...)
w.OnChange(func(e events.Event) {
typ := reflect.TypeOf(w.CurrentItem.Value.(*types.Type).Instance)
newVal := reflect.New(typ)
// try our best to convert the existing value to the new type
reflectx.SetRobust(newVal.Interface(), mapv.MapIndex(key).Interface())
mapv.SetMapIndex(key, newVal.Elem())
kl.DeleteChildByName(valnm) // force it to be updated
kl.Update()
})
w.Updater(func() {
w.SetReadOnly(kl.IsReadOnly())
vtyp := types.TypeByValue(mapv.MapIndex(key).Interface())
if vtyp == nil {
vtyp = types.TypeByName("string") // default to string
}
w.SetCurrentValue(vtyp)
})
})
}
}
if kl.Inline && !kl.IsReadOnly() {
tree.AddAt(p, "add-button", func(w *Button) {
w.SetIcon(icons.Add).SetType(ButtonTonal)
w.Tooltip = "Add an element"
w.OnClick(func(e events.Event) {
kl.AddItem()
})
})
}
})
}
func (kl *KeyedList) contextMenu(m *Scene, keyv reflect.Value) {
if kl.IsReadOnly() {
return
}
NewButton(m).SetText("Add").SetIcon(icons.Add).OnClick(func(e events.Event) {
kl.AddItem()
})
NewButton(m).SetText("Delete").SetIcon(icons.Delete).OnClick(func(e events.Event) {
kl.DeleteItem(keyv)
})
if kl.Inline {
NewButton(m).SetText("Open in dialog").SetIcon(icons.OpenInNew).OnClick(func(e events.Event) {
d := NewBody(kl.ValueTitle)
NewText(d).SetType(TextSupporting).SetText(kl.Tooltip)
NewKeyedList(d).SetMap(kl.Map).SetValueTitle(kl.ValueTitle).SetReadOnly(kl.IsReadOnly())
d.OnClose(func(e events.Event) {
kl.UpdateChange(e)
})
d.RunFullDialog(kl)
})
}
}
// toggleSort toggles sorting by values vs. keys
func (kl *KeyedList) toggleSort() {
kl.SortByValues = !kl.SortByValues
kl.Update()
}
// AddItem adds a new key-value item to the map.
func (kl *KeyedList) AddItem() {
if reflectx.IsNil(reflect.ValueOf(kl.Map)) {
return
}
reflectx.MapAdd(kl.Map)
kl.UpdateChange()
}
// DeleteItem deletes a key-value item from the map.
func (kl *KeyedList) DeleteItem(key reflect.Value) {
if reflectx.IsNil(reflect.ValueOf(kl.Map)) {
return
}
reflectx.MapDelete(kl.Map, reflectx.NonPointerValue(key))
kl.UpdateChange()
}
func (kl *KeyedList) MakeToolbar(p *tree.Plan) {
if reflectx.IsNil(reflect.ValueOf(kl.Map)) {
return
}
tree.Add(p, func(w *Button) {
w.SetText("Sort").SetIcon(icons.Sort).SetTooltip("Switch between sorting by the keys and the values").
OnClick(func(e events.Event) {
kl.toggleSort()
})
})
if !kl.IsReadOnly() {
tree.Add(p, func(w *Button) {
w.SetText("Add").SetIcon(icons.Add).SetTooltip("Add a new element to the map").
OnClick(func(e events.Event) {
kl.AddItem()
})
})
}
}
// bindMapKey is a version of [Bind] that works for keys in a map.
func bindMapKey[T Value](mapv reflect.Value, key reflect.Value, vw T) T {
wb := vw.AsWidget()
alreadyBound := wb.ValueUpdate != nil
wb.ValueUpdate = func() {
if vws, ok := any(vw).(ValueSetter); ok {
ErrorSnackbar(vw, vws.SetWidgetValue(key.Interface()))
} else {
ErrorSnackbar(vw, reflectx.SetRobust(vw.WidgetValue(), key.Interface()))
}
}
wb.ValueOnChange = func() {
newKey := reflect.New(key.Type())
ErrorSnackbar(vw, reflectx.SetRobust(newKey.Interface(), vw.WidgetValue()))
newKey = newKey.Elem()
if !mapv.MapIndex(newKey).IsValid() { // not already taken
mapv.SetMapIndex(newKey, mapv.MapIndex(key))
mapv.SetMapIndex(key, reflect.Value{})
return
}
d := NewBody("Key already exists")
NewText(d).SetType(TextSupporting).SetText(fmt.Sprintf("The key %q already exists", reflectx.ToString(newKey.Interface())))
d.AddBottomBar(func(bar *Frame) {
d.AddCancel(bar)
d.AddOK(bar).SetText("Overwrite").OnClick(func(e events.Event) {
mapv.SetMapIndex(newKey, mapv.MapIndex(key))
mapv.SetMapIndex(key, reflect.Value{})
wb.SendChange()
})
})
d.RunDialog(vw)
}
if alreadyBound {
ResetWidgetValue(vw)
}
if ob, ok := any(vw).(OnBinder); ok {
ob.OnBind(key.Interface(), "")
}
wb.ValueUpdate() // we update it with the initial value immediately
return vw
}
// bindMapValue is a version of [Bind] that works for values in a map.
func bindMapValue[T Value](mapv reflect.Value, key reflect.Value, vw T) T {
wb := vw.AsWidget()
alreadyBound := wb.ValueUpdate != nil
wb.ValueUpdate = func() {
value := mapv.MapIndex(key).Interface()
if vws, ok := any(vw).(ValueSetter); ok {
ErrorSnackbar(vw, vws.SetWidgetValue(value))
} else {
ErrorSnackbar(vw, reflectx.SetRobust(vw.WidgetValue(), value))
}
}
wb.ValueOnChange = func() {
value := reflectx.NonNilNew(mapv.Type().Elem())
err := reflectx.SetRobust(value.Interface(), vw.WidgetValue())
if err != nil {
ErrorSnackbar(vw, err)
return
}
mapv.SetMapIndex(key, value.Elem())
}
if alreadyBound {
ResetWidgetValue(vw)
}
if ob, ok := any(vw).(OnBinder); ok {
value := mapv.MapIndex(key).Interface()
ob.OnBind(value, "")
}
wb.ValueUpdate() // we update it with the initial value immediately
return vw
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"image"
"cogentcore.org/core/colors"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint"
"cogentcore.org/core/paint/pimage"
"cogentcore.org/core/paint/render"
"cogentcore.org/core/styles"
"cogentcore.org/core/system/composer"
"golang.org/x/image/draw"
)
// layersEnabled is whether scenes render their fixed widgets into a layer
// (see [sceneLayer]).
var layersEnabled = true
// sceneLayer is a compositing layer of a [Scene]: a second image, composed
// over the image of the scene (as its own texture of the GPU drawer, as a
// popup is), into which the fixed widgets of the scene are rendered (the
// dialogs, cookie banners and modals of web pages, see
// [WidgetBase.isLayerRoot]), as browsers do. The widgets stay in the one
// widget tree of the scene (with its styles and events); only their painting
// goes to the other image.
//
// The layer holds everything that is painted from the first fixed widget
// on, in the painting order of a render of the whole scene, so that the
// layer over the scene is the same as the one image (whatever is painted
// after the fixed widget, as another fixed one, is in the layer). Each
// render of the whole scene marks the widgets rendered into the layer
// ([widgetInLayer]) and those that have such widgets in them
// ([widgetHasLayer]).
//
// Then a widget under the layer (as a playing video, under the
// translucent backdrop of a dialog) re-renders alone into the image of the
// scene, and the layer, which is unchanged, is composed over it again. A
// widget in the layer that needs to be rendered renders the layer again, as
// a whole: it is cleared, and the render of the scene is replayed (only
// into the widgets that have layer content), with what is painted before
// the layer thrown away.
type sceneLayer struct {
// state is the painting state of the layer, which the painter of the
// scene uses while it renders into the layer.
state *paint.State
// scratch is the painting state that the painter of the scene uses for
// what is painted before the layer while the layer is rendered again,
// which is thrown away.
scratch *paint.State
// renderer renders the layer into its image.
renderer render.Renderer
// mode is the rendering that is being done.
mode layerMode
// started is whether the rendering has reached the layer: the painter
// of the scene paints into it.
started bool
// base is the painting state of the painter of the scene, from before
// it was switched to the layer.
base *paint.State
// active is whether the last render of the whole scene rendered
// something into the layer, which is then composed over the scene.
active bool
// needsRender is whether a widget in the layer needs to be rendered,
// which renders the layer again.
needsRender bool
// renders counts the renders of the layer (for tests).
renders int
}
// layerMode is the rendering that a [sceneLayer] is in.
type layerMode int32
const (
// layerOff is no rendering of the scene with a layer.
layerOff layerMode = iota
// layerFull is a render of the whole scene, which finds the layer.
layerFull
// layerReplay renders the layer again (see [sceneLayer]).
layerReplay
// layerPartial is a render of widgets that need to be rendered, into
// the image of the scene, where those in the layer are not rendered
// (the layer is rendered again for them).
layerPartial
)
// isLayerRoot returns whether the widget starts the layer of its scene (see
// [sceneLayer]): it is fixed (positioned relative to the viewport, so its
// layout is independent of the content that scrolls under it), and not under
// the widgets that it is in (of a negative z-index).
func (wb *WidgetBase) isLayerRoot() bool {
return wb.Styles.Position == styles.PositionFixed && wb.Styles.ZIndex >= 0
}
// layerStart is called by [WidgetBase.StartRender] while the scene is
// rendered with its layer, and returns whether the widget is rendered: it
// switches the painter of the scene to the layer at its first widget, and
// marks the widgets rendered into the layer, or skips the widgets that are
// not rendered in the mode.
func (l *sceneLayer) layerStart(sc *Scene, wb *WidgetBase) bool {
switch l.mode {
case layerPartial:
if wb.hasFlag(widgetInLayer) {
l.needsRender = true
return false
}
return true
case layerReplay:
if !l.started && !wb.hasFlag(widgetInLayer) && !wb.hasFlag(widgetHasLayer) {
return false // nothing of the layer in it
}
}
if !l.started {
if !wb.isLayerRoot() {
return true
}
l.start(sc)
}
if l.mode == layerFull {
wb.setFlag(true, widgetInLayer)
// (all of the widgets that it is in, also those that were rendered
// before the layer and render the widgets raised to them now)
for p := wb.parentWidget(); p != nil && !p.hasFlag(widgetInLayer) && !p.hasFlag(widgetHasLayer); p = p.parentWidget() {
p.setFlag(true, widgetHasLayer)
}
}
return true
}
// start switches the painter of the scene to the layer, which is cleared,
// within the contexts (clipping and transforms) of the widgets that the
// widget that starts the layer is in, as the page that it is in, which
// clips it to the viewport of the page in an app. Those are popped from the
// painting state that it was in, and they pop them from the layer.
func (l *sceneLayer) start(sc *Scene) {
l.started = true
l.renders++
l.base = sc.Painter.State
l.state.RenderDone() // (anything not yet composed is cleared anyway)
l.state.Render.Add(pimage.NewClear(colors.Uniform(colors.Transparent), image.Point{}, draw.Src))
l.state.PushStack(l.base)
l.base.PopStack()
sc.Painter.State = l.state
}
// finish ends a rendering of the scene with its layer, switching the
// painter back to the painting state of the scene.
func (l *sceneLayer) finish(sc *Scene) {
if l.started {
sc.Painter.State = l.base
l.base = nil
}
l.started = false
l.mode = layerOff
}
// resize makes the painting states and the renderer of the layer for the
// size of the scene.
func (l *sceneLayer) resize(sc *Scene) {
sz := math32.FromPoint(sc.SceneGeom.Size)
if l.state != nil && l.state.Size == sz {
return
}
l.state = &paint.State{}
l.state.Init(sc.Painter.Paint, sz)
l.scratch = &paint.State{}
l.scratch.Init(sc.Painter.Paint, sz)
l.renderer = paint.NewSourceRenderer(sz)
l.active = false
}
// renderWhole renders the whole scene, with its layer: the widgets from the
// first fixed widget on are rendered into the layer.
func (sc *Scene) renderWhole() {
l := &sc.layer
if !layersEnabled || sc.Painter.State == nil || sc.SceneGeom.Size == (image.Point{}) {
l.active = false
sc.RenderWidget()
return
}
l.resize(sc)
if l.active { // (the flags of the last render)
for _, cwb := range sc.AllWidgets() {
cwb.setFlag(false, widgetInLayer, widgetHasLayer)
}
}
l.mode = layerFull
l.needsRender = false
sc.RenderWidget()
l.active = l.started
l.finish(sc)
}
// renderLayer renders the layer of the scene again (see [sceneLayer]).
func (sc *Scene) renderLayer() {
l := &sc.layer
l.needsRender = false
if !l.active {
return
}
l.mode = layerReplay
saved := sc.Painter.State
sc.Painter.State = l.scratch
sc.RenderWidget()
l.finish(sc)
l.scratch.RenderDone() // (thrown away)
sc.Painter.State = saved
}
// doNeedsRender renders the widgets of the scene that need to be rendered,
// into the image of the scene, and the layer again if any of them is in it
// (see [sceneLayer]), or the whole scene if it needs to be rendered.
func (sc *Scene) doNeedsRender() {
if sc.WidgetBase.hasFlag(widgetNeedsRender) {
sc.WidgetBase.setFlag(false, widgetChildNeedsRender)
sc.renderWhole()
return
}
l := &sc.layer
if !l.active {
sc.WidgetBase.doNeedsRender()
return
}
l.mode = layerPartial
sc.WidgetBase.doNeedsRender()
l.mode = layerOff
if l.needsRender {
sc.renderLayer()
}
}
// layerSource returns the [composer.Source] for the layer of the scene, to
// be composed over the scene, or nil if it has none.
func (sc *Scene) layerSource() composer.Source {
l := &sc.layer
if !l.active || l.renderer == nil {
return nil
}
return &paintSource{render: l.state.RenderDone(), renderer: l.renderer, drawOp: draw.Over, drawPos: sc.SceneGeom.Pos}
}
// addRenderSources adds the sources of the scene to the given composer: its
// image, with the given draw operation, the widgets that render directly
// to the window (for the scene of the window), and its layer over them.
func (sc *Scene) addRenderSources(cp composer.Composer, op draw.Op, direct bool) {
cp.Add(sc.RenderSource(op), sc)
if direct {
for _, dr := range sc.directRenders {
cp.Add(dr.RenderSource(draw.Over), dr)
}
}
if ls := sc.layerSource(); ls != nil {
cp.Add(ls, &sc.layer)
}
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"fmt"
"image"
"log/slog"
"slices"
"strings"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/tree"
)
// LayoutPasses is used for the SizeFromChildren method,
// which can potentially compute different sizes for different passes.
type LayoutPasses int32 //enums:enum
const (
SizeUpPass LayoutPasses = iota
SizeDownPass
SizeFinalPass
)
// Layouter is an interface containing layout functions
// implemented by all types embedding [Frame].
type Layouter interface {
Widget
// AsFrame returns the Layouter as a [Frame].
AsFrame() *Frame
// LayoutSpace sets our Space based on Styles, Scroll, and Gap Spacing.
// Other layout types can change this if they want to.
LayoutSpace()
// SizeFromChildren gathers Actual size from kids into our Actual.Content size.
// Different Layout types can alter this to present different Content
// sizes for the layout process, e.g., if Content is sized to fit allocation,
// as in the [Toolbar] and [List] types.
SizeFromChildren(iter int, pass LayoutPasses) math32.Vector2
// SizeDownSetAllocs is the key SizeDown step that sets the allocations
// in the children, based on our allocation. In the default implementation
// this calls SizeDownGrow if there is extra space to grow, or
// SizeDownAllocActual to set the allocations as they currently are.
SizeDownSetAllocs(iter int)
// ManageOverflow uses overflow settings to determine if scrollbars
// are needed, based on difference between ActualOverflow (full actual size)
// and Alloc allocation. Returns true if size changes as a result.
// If updateSize is false, then the Actual and Alloc sizes are NOT
// updated as a result of change from adding scrollbars
// (generally should be true, but some cases not)
ManageOverflow(iter int, updateSize bool) bool
// ScrollChanged is called in the OnInput event handler for updating
// when the scrollbar value has changed, for given dimension
ScrollChanged(d math32.Dims, sb *Slider)
// ScrollValues returns the maximum size that could be scrolled,
// the visible size (which could be less than the max size, in which
// case no scrollbar is needed), and visSize / maxSize as the VisiblePct.
// This is used in updating the scrollbar and determining whether one is
// needed in the first place
ScrollValues(d math32.Dims) (maxSize, visSize, visPct float32)
// ScrollGeom returns the target position and size for scrollbars
ScrollGeom(d math32.Dims) (pos, sz math32.Vector2)
// SetScrollParams sets scrollbar parameters. Must set Step and PageStep,
// but can also set others as needed.
// Max and VisiblePct are automatically set based on ScrollValues maxSize, visPct.
SetScrollParams(d math32.Dims, sb *Slider)
}
// AsFrame returns the given value as a [Frame] if it implements [Layouter]
// or nil otherwise.
func AsFrame(n tree.Node) *Frame {
if t, ok := n.(Layouter); ok {
return t.AsFrame()
}
return nil
}
func (fr *Frame) AsFrame() *Frame {
return fr
}
var _ Layouter = &Frame{}
// geomCT has core layout elements: Content and Total
type geomCT struct {
// Content is for the contents (children, parts) of the widget,
// excluding the Space (margin, padding, scrollbars).
// This content includes the InnerSpace factor (Gaps in Layout)
// which must therefore be subtracted when allocating down to children.
Content math32.Vector2
// Total is for the total exterior of the widget: Content + Space
Total math32.Vector2
}
func (ct geomCT) String() string {
return fmt.Sprintf("Content: %v, \tTotal: %v", ct.Content, ct.Total)
}
// GeomSize has all of the relevant Layout sizes
type GeomSize struct {
// Actual is the actual size for the purposes of rendering, representing
// the "external" demands of the widget for space from its parent.
// This is initially the bottom-up constraint computed by SizeUp,
// and only changes during SizeDown when wrapping elements are reshaped
// based on allocated size, or when scrollbars are added.
// For elements with scrollbars (OverflowAuto), the Actual size remains
// at the initial style minimums, "absorbing" is internal size,
// while Internal records the true size of the contents.
// For SizeFinal, Actual size can Grow up to the final Alloc size,
// while Internal records the actual bottom-up contents size.
Actual geomCT `display:"inline"`
// Alloc is the top-down allocated size, based on available visible space,
// starting from the Scene geometry and working downward, attempting to
// accommodate the Actual contents, and allocating extra space based on
// Grow factors. When Actual < Alloc, alignment factors determine positioning
// within the allocated space.
Alloc geomCT `display:"inline"`
// Internal is the internal size representing the true size of all contents
// of the widget. This can be less than Actual.Content if widget has Grow
// factors but its internal contents did not grow accordingly, or it can
// be more than Actual.Content if it has scrollbars (OverflowAuto).
// Note that this includes InnerSpace (Gap).
Internal math32.Vector2
// Space is the padding, total effective margin (border, shadow, etc),
// and scrollbars that subtracts from Total size to get Content size.
Space math32.Vector2
// InnerSpace is total extra space that is included within the Content Size region
// and must be subtracted from Content when passing sizes down to children.
InnerSpace math32.Vector2
// Min is the Styles.Min.Dots() (Ceil int) that constrains the Actual.Content size
Min math32.Vector2
// Max is the Styles.Max.Dots() (Ceil int) that constrains the Actual.Content size
Max math32.Vector2
// slot is the size that the parent layout would have allocated
// to a growing widget whose allocation is limited by its Max size,
// which it is aligned within, and 0 otherwise.
slot math32.Vector2
// extent is the total size of the widget including any content of it
// that overflows it visibly (as for a frame with a Max narrower than
// its content), which is beyond its Actual size; it is zero or Actual
// when there is none. See [Frame.sizeOverflow].
extent math32.Vector2
// preferred is the actual total size of the widget from the SizeUp
// pass, before its parent allocates it less, which is its max-content
// size for widgets that shrink ([styles.Style.Shrink]), so that they
// are as wide as they can be in the space that they have.
preferred math32.Vector2
// minWidth is the min-content width of the widget from the SizeUp
// pass, as in CSS: its total width (with its Space) below which its
// content overflows, such as the width of the longest word of text.
// The layout does not narrow a widget below it.
minWidth float32
// prefWidth is the max-content (preferred) width of the widget from
// the SizeUp pass: its total width without any wrapping, such as the
// width of text on one line. A widget starts at this width, and is
// narrowed toward its minWidth only when there is too little space.
prefWidth float32
}
// setIntrinsicWidths sets the minWidth and prefWidth from the given
// min-content and max-content widths of the content, within the Min and
// Max sizes, with the Space added.
func (ls *GeomSize) setIntrinsicWidths(minw, prefw float32) {
minw = max(minw, ls.Min.X)
prefw = max(prefw, minw)
if mx := ls.Max.X; mx > 0 {
minw = min(minw, mx)
prefw = min(prefw, mx)
}
ls.minWidth = math32.Ceil(minw + ls.Space.X)
ls.prefWidth = math32.Ceil(prefw + ls.Space.X)
}
func (ls GeomSize) String() string {
return fmt.Sprintf("Actual: %v, \tAlloc: %v", ls.Actual, ls.Alloc)
}
// setInitContentMin sets initial Actual.Content size from given Styles.Min,
// further subject to the current Max constraint.
func (ls *GeomSize) setInitContentMin(styMin math32.Vector2) {
csz := &ls.Actual.Content
*csz = styMin
styles.SetClampMaxVector(csz, ls.Max)
}
// maxTotal returns the Max size as a Total size, adding the Space
// to each dimension that has a Max (which is 0 for no Max).
func (ls *GeomSize) maxTotal() math32.Vector2 {
mt := ls.Max
for d := math32.X; d <= math32.Y; d++ {
if mt.Dim(d) > 0 {
mt.SetDim(d, mt.Dim(d)+ls.Space.Dim(d))
}
}
return mt
}
// fitTotalMax increases the given Total size to fit the given fm value,
// subject to the Max constraint on the content, as [GeomSize.FitSizeMax]
// does for a content size.
func (ls *GeomSize) fitTotalMax(to *math32.Vector2, fm math32.Vector2) {
styles.SetClampMinVector(to, fm)
styles.SetClampMaxVector(to, ls.maxTotal())
}
// FitSizeMax increases given size to fit given fm value, subject to Max constraints
func (ls *GeomSize) FitSizeMax(to *math32.Vector2, fm math32.Vector2) {
styles.SetClampMinVector(to, fm)
styles.SetClampMaxVector(to, ls.Max)
}
// SetTotalFromContent sets the Total size as Content plus Space
func (ls *GeomSize) SetTotalFromContent(ct *geomCT) {
ct.Total = ct.Content.Add(ls.Space)
}
// SetContentFromTotal sets the Content from Total size,
// subtracting Space
func (ls *GeomSize) SetContentFromTotal(ct *geomCT) {
ct.Content = ct.Total.Sub(ls.Space)
}
// GeomState contains the the layout geometry state for each widget.
// Set by the parent Layout during the Layout process.
type GeomState struct {
// Size has sizing data for the widget: use Actual for rendering.
// Alloc shows the potentially larger space top-down allocated.
Size GeomSize `display:"add-fields"`
// Pos is position within the overall Scene that we render into,
// including effects of scroll offset, for both Total outer dimension
// and inner Content dimension.
Pos geomCT `display:"inline" edit:"-" copier:"-" json:"-" xml:"-" set:"-"`
// Cell is the logical X, Y index coordinates (col, row) of element
// within its parent layout
Cell image.Point
// RelPos is top, left position relative to parent Content size space
RelPos math32.Vector2
// Scroll is additional scrolling offset within our parent layout
Scroll math32.Vector2
// 2D bounding box for Actual.Total size occupied within parent Scene
// that we render onto, starting at Pos.Total and ending at Pos.Total + Size.Total.
// These are the pixels we can draw into, intersected with parent bounding boxes
// (empty for invisible). Used for render Bounds clipping.
// This includes all space (margin, padding etc).
TotalBBox image.Rectangle `edit:"-" copier:"-" json:"-" xml:"-" set:"-"`
// 2D bounding box for our Content, which excludes our padding, margin, etc.
// starting at Pos.Content and ending at Pos.Content + Size.Content.
// It is intersected with parent bounding boxes.
ContentBBox image.Rectangle `edit:"-" copier:"-" json:"-" xml:"-" set:"-"`
// contentOffset is the offset of Pos.Content from Pos.Total, the
// position of the style's BoxSpace. It is set with Size.Space, so that
// positioning, as when scrolling, need not compute it again.
contentOffset math32.Vector2
}
func (ls *GeomState) String() string {
return "Size: " + ls.Size.String() + "\nPos: " + ls.Pos.String() + "\tCell: " + ls.Cell.String() +
"\tRelPos: " + ls.RelPos.String() + "\tScroll: " + ls.Scroll.String()
}
// contentRangeDim returns the Content bounding box min, max
// along given dimension
func (ls *GeomState) contentRangeDim(d math32.Dims) (cmin, cmax float32) {
cmin = float32(math32.PointDim(ls.ContentBBox.Min, d))
cmax = float32(math32.PointDim(ls.ContentBBox.Max, d))
return
}
// totalRect returns Pos.Total -- Size.Actual.Total
// as an image.Rectangle, e.g., for bounding box
func (ls *GeomState) totalRect() image.Rectangle {
return math32.RectFromPosSizeMax(ls.Pos.Total, ls.Size.Actual.Total)
}
// contentRect returns Pos.Content, Size.Actual.Content
// as an image.Rectangle, e.g., for bounding box.
func (ls *GeomState) contentRect() image.Rectangle {
return math32.RectFromPosSizeMax(ls.Pos.Content, ls.Size.Actual.Content)
}
// ScrollOffset computes the net scrolling offset as a function of
// the difference between the allocated position and the actual
// content position according to the clipped bounding box.
func (ls *GeomState) ScrollOffset() image.Point {
return ls.ContentBBox.Min.Sub(ls.Pos.Content.ToPoint())
}
// layoutCell holds the layout implementation data for col, row Cells
type layoutCell struct {
// Size has the Actual size of elements (not Alloc)
Size math32.Vector2
// Grow has the Grow factors
Grow math32.Vector2
}
func (ls *layoutCell) String() string {
return fmt.Sprintf("Size: %v, \tGrow: %g", ls.Size, ls.Grow)
}
func (ls *layoutCell) reset() {
ls.Size.SetZero()
ls.Grow.SetZero()
}
// layoutCells holds one set of LayoutCell cell elements for rows, cols.
// There can be multiple of these for Wrap case.
type layoutCells struct {
// Shape is number of cells along each dimension for our ColRow cells,
Shape image.Point `edit:"-"`
// ColRow has the data for the columns in [0] and rows in [1]:
// col Size.X = max(X over rows) (cross axis), .Y = sum(Y over rows) (main axis for col)
// row Size.X = sum(X over cols) (main axis for row), .Y = max(Y over cols) (cross axis)
// see: https://docs.google.com/spreadsheets/d/1eimUOIJLyj60so94qUr4Buzruj2ulpG5o6QwG2nyxRw/edit?usp=sharing
ColRow [2][]layoutCell `edit:"-"`
}
// cell returns the cell for given dimension and index along that
// dimension (X = Cols, idx = col, Y = Rows, idx = row)
func (lc *layoutCells) cell(d math32.Dims, idx int) *layoutCell {
if len(lc.ColRow[d]) <= idx {
return nil
}
return &(lc.ColRow[d][idx])
}
// init initializes Cells for given shape
func (lc *layoutCells) init(shape image.Point) {
lc.Shape = shape
for d := math32.X; d <= math32.Y; d++ {
n := math32.PointDim(lc.Shape, d)
if len(lc.ColRow[d]) != n {
lc.ColRow[d] = make([]layoutCell, n)
}
for i := range n {
lc.ColRow[d][i].reset()
}
}
}
// cellsSize returns the total Size represented by the current Cells,
// which is the Sum of the Max values along each dimension.
func (lc *layoutCells) cellsSize() math32.Vector2 {
var ksz math32.Vector2
for ma := math32.X; ma <= math32.Y; ma++ { // main axis = X then Y
n := math32.PointDim(lc.Shape, ma) // cols, rows
sum := float32(0)
for mi := range n {
md := lc.cell(ma, mi) // X, Y
if md == nil {
continue
}
mx := md.Size.Dim(ma)
sum += mx // sum of maxes
}
ksz.SetDim(ma, sum)
}
return ksz.Ceil()
}
// gapSizeDim returns the gap size for given dimension, based on Shape and given gap size
func (lc *layoutCells) gapSizeDim(d math32.Dims, gap float32) float32 {
n := math32.PointDim(lc.Shape, d)
return float32(n-1) * gap
}
func (lc *layoutCells) String() string {
var s strings.Builder
n := lc.Shape.X
for i := 0; i < n; i++ {
col := lc.cell(math32.X, i)
fmt.Fprintln(&s, "col:", i, "\tmax X:", col.Size.X, "\tsum Y:", col.Size.Y, "\tmax grX:", col.Grow.X, "\tsum grY:", col.Grow.Y)
}
n = lc.Shape.Y
for i := 0; i < n; i++ {
row := lc.cell(math32.Y, i)
fmt.Fprintln(&s, "row:", i, "\tsum X:", row.Size.X, "\tmax Y:", row.Size.Y, "\tsum grX:", row.Grow.X, "\tmax grY:", row.Grow.Y)
}
return s.String()
}
// layoutState has internal state for implementing layout
type layoutState struct {
// Shape is number of cells along each dimension,
// computed for each layout type:
// For Grid: Max Col, Row.
// For Flex no Wrap: Cols,1 (X) or 1,Rows (Y).
// For Flex Wrap: Cols,Max(Rows) or Max(Cols),Rows
// For Stacked: 1,1
Shape image.Point `edit:"-"`
// MainAxis cached here from Styles, to enable Wrap-based access.
MainAxis math32.Dims
// Wraps is the number of actual items in each Wrap for Wrap case:
// MainAxis X: Len = Rows, Val = Cols; MainAxis Y: Len = Cols, Val = Rows.
// This should be nil for non-Wrap case.
Wraps []int
// Cells has the Actual size and Grow factor data for each of the child elements,
// organized according to the Shape and Display type.
// For non-Wrap, has one element in slice, with cells based on Shape.
// For Wrap, slice is number of CrossAxis wraps allocated:
// MainAxis X = Rows; MainAxis Y = Cols, and Cells are MainAxis layout x 1 CrossAxis.
Cells []layoutCells `edit:"-"`
// ScrollSize has the scrollbar sizes (widths) for each dim, which adds to Space.
// If there is a vertical scrollbar, X has width; if horizontal, Y has "width" = height
ScrollSize math32.Vector2
// Gap is the Styles.Gap size
Gap math32.Vector2
// spans is whether a grid has cells that span columns.
spans bool
// rowSpans is whether a grid has cells that span rows.
rowSpans bool
// floats is the layout of a column with floating children, if it has any.
floats *floatLayout
// growExtra is the extra space that children with a Grow factor grow
// into, which is within the actual size of a frame that does not grow
// (see [Frame.childSpace]), while other children (such as GrowWrap
// text) are allocated all of the extra allocation of the frame.
growExtra math32.Vector2
// minContent is the min-content width of the content of the frame,
// from its children (see [Frame.sizeUpIntrinsicFrame]), which it
// scrolls in width only if it is narrower than.
minContent float32
// overflow is the size of the content of the frame including the
// content of its children that overflows them visibly (see
// [Frame.sizeOverflow]), which the frame scrolls over.
overflow math32.Vector2
// GapSize has the total extra gap sizing between elements, which adds to Space.
// This depends on cell layout so it can vary for Wrap case.
// For SizeUp / Down Gap contributes to Space like other cases,
// but for BoundingBox rendering and Alignment, it does NOT, and must be
// subtracted. This happens in the Position phase.
GapSize math32.Vector2
}
// initCells initializes the Cells based on Shape, MainAxis, and Wraps
// which must be set before calling.
func (ls *layoutState) initCells() {
if ls.Wraps == nil {
if len(ls.Cells) != 1 {
ls.Cells = make([]layoutCells, 1)
}
ls.Cells[0].init(ls.Shape)
return
}
ma := ls.MainAxis
ca := ma.Other()
nw := len(ls.Wraps)
if len(ls.Cells) != nw {
ls.Cells = make([]layoutCells, nw)
}
for wi, wn := range ls.Wraps {
var shp image.Point
math32.SetPointDim(&shp, ma, wn)
math32.SetPointDim(&shp, ca, 1)
ls.Cells[wi].init(shp)
}
}
func (ls *layoutState) shapeCheck(w Widget, _ string) bool {
if w.AsTree().HasChildren() && (ls.Shape == (image.Point{}) || len(ls.Cells) == 0) {
// fmt.Println(w, "Shape is nil in:", phase) // TODO: plan for this?
return false
}
return true
}
// cell returns the cell for given dimension and index along that
// dimension, and given other-dimension axis which is ignored for non-Wrap cases.
// Does no range checking and will crash if out of bounds.
func (ls *layoutState) cell(d math32.Dims, dIndex, odIndex int) *layoutCell {
if ls.Wraps == nil {
return ls.Cells[0].cell(d, dIndex)
}
if ls.MainAxis == d {
return ls.Cells[odIndex].cell(d, dIndex)
}
return ls.Cells[dIndex].cell(d, 0)
}
// wrapIndexToCoord returns the X,Y coordinates in Wrap case for given sequential idx
func (ls *layoutState) wrapIndexToCoord(idx int) image.Point {
y := 0
x := 0
sum := 0
if ls.MainAxis == math32.X {
for _, nx := range ls.Wraps {
if idx >= sum && idx < sum+nx {
x = idx - sum
break
}
sum += nx
y++
}
} else {
for _, ny := range ls.Wraps {
if idx >= sum && idx < sum+ny {
y = idx - sum
break
}
sum += ny
x++
}
}
return image.Point{x, y}
}
// cellsSize returns the total Size represented by the current Cells,
// which is the Sum of the Max values along each dimension within each Cell,
// Maxed over cross-axis dimension for Wrap case, plus GapSize.
func (ls *layoutState) cellsSize() math32.Vector2 {
if ls.Wraps == nil {
return ls.Cells[0].cellsSize().Add(ls.GapSize)
}
var ksz math32.Vector2
d := ls.MainAxis
od := d.Other()
gap := ls.Gap.Dim(d)
for wi := range ls.Wraps {
wsz := ls.Cells[wi].cellsSize()
wsz.SetDim(d, wsz.Dim(d)+ls.Cells[wi].gapSizeDim(d, gap))
if wi == 0 {
ksz = wsz
} else {
ksz.SetDim(d, max(ksz.Dim(d), wsz.Dim(d)))
ksz.SetDim(od, ksz.Dim(od)+wsz.Dim(od))
}
}
ksz.SetDim(od, ksz.Dim(od)+ls.GapSize.Dim(od))
return ksz.Ceil()
}
// colWidth returns the width of given column for given row index
// (ignored for non-Wrap), with full bounds checking.
// Returns error if out of range.
func (ls *layoutState) colWidth(row, col int) (float32, error) {
if ls.Wraps == nil {
n := math32.PointDim(ls.Shape, math32.X)
if col >= n {
return 0, fmt.Errorf("Layout.ColWidth: col: %d > number of columns: %d", col, n)
}
return ls.cell(math32.X, col, 0).Size.X, nil
}
nw := len(ls.Wraps)
if ls.MainAxis == math32.X {
if row >= nw {
return 0, fmt.Errorf("Layout.ColWidth: row: %d > number of rows: %d", row, nw)
}
wn := ls.Wraps[row]
if col >= wn {
return 0, fmt.Errorf("Layout.ColWidth: col: %d > number of columns: %d", col, wn)
}
return ls.cell(math32.X, col, row).Size.X, nil
}
if col >= nw {
return 0, fmt.Errorf("Layout.ColWidth: col: %d > number of columns: %d", col, nw)
}
wn := ls.Wraps[col]
if row >= wn {
return 0, fmt.Errorf("Layout.ColWidth: row: %d > number of rows: %d", row, wn)
}
return ls.cell(math32.X, col, row).Size.X, nil
}
// rowHeight returns the height of given row for given
// column (ignored for non-Wrap), with full bounds checking.
// Returns error if out of range.
func (ls *layoutState) rowHeight(row, col int) (float32, error) {
if ls.Wraps == nil {
n := math32.PointDim(ls.Shape, math32.Y)
if row >= n {
return 0, fmt.Errorf("Layout.RowHeight: row: %d > number of rows: %d", row, n)
}
return ls.cell(math32.Y, row, 0).Size.Y, nil
}
nw := len(ls.Wraps)
if ls.MainAxis == math32.Y { // the columns wrap
if col >= nw {
return 0, fmt.Errorf("Layout.RowHeight: col: %d > number of columns: %d", col, nw)
}
wn := ls.Wraps[col]
if row >= wn {
return 0, fmt.Errorf("Layout.RowHeight: row: %d > number of rows: %d", row, wn)
}
return ls.cell(math32.Y, row, col).Size.Y, nil
}
// the rows wrap
if row >= nw {
return 0, fmt.Errorf("Layout.RowHeight: row: %d > number of rows: %d", row, nw)
}
wn := ls.Wraps[row]
if col >= wn {
return 0, fmt.Errorf("Layout.RowHeight: col: %d > number of columns: %d", col, wn)
}
return ls.cell(math32.Y, row, col).Size.Y, nil
}
func (ls *layoutState) String() string {
if ls.Wraps == nil {
return ls.Cells[0].String()
}
var s strings.Builder
ods := ls.MainAxis.Other().String()
for wi := range ls.Wraps {
fmt.Fprintf(&s, "%s: %d Shape: %v\n", ods, wi, ls.Cells[wi].Shape)
s.WriteString(ls.Cells[wi].String())
}
return s.String()
}
// StackTopWidget returns the [Frame.StackTop] element as a [WidgetBase].
func (fr *Frame) StackTopWidget() *WidgetBase {
n := fr.Child(fr.StackTop)
return AsWidget(n)
}
// laySetContentFitOverflow sets Internal and Actual.Content size to fit given
// new content size, depending on the Styles Overflow: Auto and Scroll types do NOT
// expand Actual and remain at their current styled actual values,
// absorbing the extra content size within their own scrolling zone
// (full size recorded in Internal).
func (fr *Frame) laySetContentFitOverflow(nsz math32.Vector2, pass LayoutPasses) {
sz := &fr.Geom.Size
asz := &sz.Actual.Content
isz := &sz.Internal
sz.setInitContentMin(sz.Min) // start from style
*isz = nsz // internal is always accurate!
oflow := &fr.Styles.Overflow
// wrapped content is sized by its allocation, except that wrapped
// rows that shrink are as wide as they are on one line, until then
nosz := pass == SizeUpPass && fr.Styles.IsFlexWrap() &&
!(fr.Styles.Shrink.X > 0 && fr.Styles.Direction == styles.Row)
mx := sz.Max
for d := math32.X; d <= math32.Y; d++ {
if nosz || fr.contained(d) {
continue // (contained: as if it had no content)
}
// a frame that scrolls is as large as its style, unless it shrinks
// in width (as in CSS, where it starts at the width of its content,
// and is narrowed to fit, down to nothing: see sizeUpIntrinsicFrame),
// which is then as wide as its content up to its allocation
shrinks := d == math32.X && fr.Styles.Shrink.X > 0
scrolls := (fr.Scene == nil || !fr.Scene.hasFlag(sceneContentSizing)) && oflow.Dim(d) >= styles.OverflowAuto && fr.Parent != nil
switch {
case scrolls && shrinks && pass != SizeUpPass:
w := nsz.X
if al := sz.Alloc.Content.X; al > 0 {
w = min(w, al)
}
asz.X = styles.ClampMin(asz.X, w)
case scrolls && !shrinks:
if mx.Dim(d) > 0 {
asz.SetDim(d, styles.ClampMax(styles.ClampMin(asz.Dim(d), nsz.Dim(d)), mx.Dim(d)))
}
default:
asz.SetDim(d, styles.ClampMin(asz.Dim(d), nsz.Dim(d)))
}
}
styles.SetClampMaxVector(asz, mx)
sz.SetTotalFromContent(&sz.Actual)
}
// SizeUp (bottom-up) gathers Actual sizes from our Children & Parts,
// based on Styles.Min / Max sizes and actual content sizing
// (e.g., text size), along with the intrinsic min-content and preferred
// widths (see layoutintrinsic.go). Wrapping [Text] starts out at its
// preferred width (on one line), and is re-wrapped to its allocated width
// in SizeDown; flex wrap layouts are wrapped in SizeDown.
func (wb *WidgetBase) SizeUp() {
wb.SizeUpWidget()
}
// SizeUpWidget is the standard Widget SizeUp pass
func (wb *WidgetBase) SizeUpWidget() {
wb.sizeFromStyle()
wb.sizeUpParts()
sz := &wb.Geom.Size
sz.SetTotalFromContent(&sz.Actual)
wb.sizeAspect(false)
wb.sizeUpIntrinsic()
}
// sizeUpIntrinsic sets the intrinsic widths of a widget that has no
// children of its own in the layout: both are its actual width. A widget
// with parts (such as a button, switch, or chooser) is not narrowed, as
// its parts are laid out within its actual size: its label stays on one
// line, and the frame that it is in scrolls if it does not fit.
func (wb *WidgetBase) sizeUpIntrinsic() {
sz := &wb.Geom.Size
sz.minWidth, sz.prefWidth = sz.Actual.Total.X, sz.Actual.Total.X
}
// spaceFromStyle sets the Space based on Style BoxSpace().Size(),
// and the content offset from its position.
func (wb *WidgetBase) spaceFromStyle() {
space := wb.Styles.BoxSpace()
wb.Geom.Size.Space = space.Size().Ceil()
wb.Geom.contentOffset = space.Pos().Floor()
}
// sizeFromStyle sets the initial Actual Sizes from Style.Min, Max.
// Required first call in SizeUp.
func (wb *WidgetBase) sizeFromStyle() {
sz := &wb.Geom.Size
s := &wb.Styles
wb.spaceFromStyle()
wb.Geom.Size.InnerSpace.SetZero()
sz.Min = s.Min.Dots().Ceil()
sz.Max = s.Max.Dots().Ceil()
if s.Min.X.Unit == units.UnitPw || s.Min.X.Unit == units.UnitPh {
sz.Min.X = 0
}
if s.Min.Y.Unit == units.UnitPw || s.Min.Y.Unit == units.UnitPh {
sz.Min.Y = 0
}
if s.Max.X.Unit == units.UnitPw || s.Max.X.Unit == units.UnitPh {
sz.Max.X = 0
}
if s.Max.Y.Unit == units.UnitPw || s.Max.Y.Unit == units.UnitPh {
sz.Max.Y = 0
}
if bs := wb.boxSizingSpace(); bs != (math32.Vector2{}) {
for d := math32.X; d <= math32.Y; d++ {
if m := sz.Min.Dim(d); m > 0 {
sz.Min.SetDim(d, max(m-bs.Dim(d), 0))
}
if m := sz.Max.Dim(d); m > 0 {
sz.Max.SetDim(d, max(m-bs.Dim(d), 1))
}
}
}
sz.Internal.SetZero()
sz.setInitContentMin(sz.Min)
sz.SetTotalFromContent(&sz.Actual)
if DebugSettings.LayoutTrace && (sz.Actual.Content.X > 0 || sz.Actual.Content.Y > 0) {
fmt.Println(wb, "SizeUp from Style:", sz.Actual.Content.String())
}
}
// specifiedHeight returns the height of the content of the widget that is
// specified by its style, if it is: its Min height in units that are not
// relative to its parent, or a percentage of the specified height of its
// parent, if it has a Min height and no Max height (as for a height in CSS).
func (wb *WidgetBase) specifiedHeight() (float32, bool) {
s := &wb.Styles
mn := s.Min.Y
if mn.Value <= 0 || mn.Custom != nil || s.Max.Y.Value > 0 {
return 0, false
}
switch mn.Unit {
case units.UnitPw:
return 0, false
case units.UnitPh:
pwb := wb.parentWidget()
if pwb == nil {
return 0, false
}
ph, ok := pwb.specifiedHeight()
if !ok {
return 0, false
}
return max(ph*0.01*mn.Value-wb.boxSizingSpace().Y, 0), true
}
return math32.Ceil(mn.Dots) - wb.boxSizingSpace().Y, true
}
// styleMinDots returns the Min size of the style in dots, rounded up,
// without the dimensions that are relative to the size of the parent
// (pw and ph units), which are not known until the parent is sized (see
// [WidgetBase.updateParentRelSizes]), as in [WidgetBase.sizeFromStyle]:
// their dots are of the size of the parent when the widget was styled (as
// the scene, for a text field of a height of 100% of the search box of
// duckduckgo.com, which was as high as the window).
func (wb *WidgetBase) styleMinDots() math32.Vector2 {
s := &wb.Styles
m := s.Min.Dots().Ceil()
if s.Min.X.Unit == units.UnitPw || s.Min.X.Unit == units.UnitPh {
m.X = 0
}
if s.Min.Y.Unit == units.UnitPw || s.Min.Y.Unit == units.UnitPh {
m.Y = 0
}
return m
}
// boxSizingSpace returns the size of the padding and border of the widget
// if its Min and Max sizes include them ([styles.BoxBorderBox]), which is
// subtracted from them for the size of the content, or zero otherwise.
func (wb *WidgetBase) boxSizingSpace() math32.Vector2 {
s := &wb.Styles
if s.BoxSizing != styles.BoxBorderBox {
return math32.Vector2{}
}
return s.Padding.Dots().Size().Add(s.Border.Width.Dots().Size())
}
// updateParentRelSizes updates any parent-relative Min, Max size values
// based on current actual parent sizes.
func (wb *WidgetBase) updateParentRelSizes() bool {
pwb := wb.parentWidget()
if pwb == nil {
return false
}
sz := &wb.Geom.Size
effmin := sz.Min
s := &wb.Styles
psz := pwb.Geom.Size.Alloc.Content.Sub(pwb.Geom.Size.InnerSpace)
// A percentage Max width of a child of a grid that spans columns (and
// that is not also its Min, as for the percentage tracks of grids and
// the widths of the columns of tables, which are of the grid, as are
// those of the cells of one column of tables) is of its grid area, the
// columns that it spans with the gaps between them, as in CSS, not of
// the grid without all of its gaps (as a max-width of 100% of a child
// of 12 columns of nytimes.com/wirecutter, which was narrower than the
// grid by its 11 gaps).
maxBase := psz.X
if pwb.Styles.Display == styles.Grid && sz.Alloc.Total.X > 0 && s.Min.X.Unit != units.UnitPw && s.ColSpan > 1 {
maxBase = sz.Alloc.Total.X
}
if h, ok := pwb.specifiedHeight(); ok {
// a percentage of the height of the parent is of its specified
// height, as in CSS, not of the height that it is given, which can
// be that of its content: with that, a text field of a height of
// 100% in frames of 100% (as the search box of duckduckgo.com)
// made them higher by its padding on each pass
psz.Y = h
}
bs := wb.boxSizingSpace()
got := false
for d := math32.X; d <= math32.Y; d++ {
if s.Min.Dim(d).Unit == units.UnitPw {
got = true
effmin.SetDim(d, max(psz.X*0.01*s.Min.Dim(d).Value-bs.Dim(d), 0))
}
if s.Min.Dim(d).Unit == units.UnitPh {
got = true
effmin.SetDim(d, max(psz.Y*0.01*s.Min.Dim(d).Value-bs.Dim(d), 0))
}
if s.Max.Dim(d).Unit == units.UnitPw {
got = true
base := psz.X
if d == math32.X {
base = maxBase
}
sz.Max.SetDim(d, max(base*0.01*s.Max.Dim(d).Value-bs.Dim(d), 1))
}
if s.Max.Dim(d).Unit == units.UnitPh {
got = true
sz.Max.SetDim(d, max(psz.Y*0.01*s.Max.Dim(d).Value-bs.Dim(d), 1))
}
// custom sizes are computed with the size of the parent too (as a
// calc() of CSS with a percentage and a length, as the width of
// calc(100% - 256px) of the grids of github.com)
if mn := s.Min.Dim(d); mn.Custom != nil {
got = true
uc := s.UnitContext
uc.Paw, uc.Pah = psz.X, psz.Y
v := max(math32.Ceil(mn.Custom(&uc))-bs.Dim(d), 0)
effmin.SetDim(d, v)
sz.Min.SetDim(d, v)
}
if mx := s.Max.Dim(d); mx.Custom != nil {
got = true
uc := s.UnitContext
uc.Paw, uc.Pah = psz.X, psz.Y
sz.Max.SetDim(d, max(math32.Ceil(mx.Custom(&uc))-bs.Dim(d), 1))
}
}
if got {
// the min is of the content, and the total has the space around it
// (as the padding of the 21.5% navigation of pkg.go.dev, which was
// narrower by its padding)
effmin = effmin.Add(sz.Space)
sz.fitTotalMax(&sz.Actual.Total, effmin)
sz.fitTotalMax(&sz.Alloc.Total, effmin)
sz.SetContentFromTotal(&sz.Actual)
sz.SetContentFromTotal(&sz.Alloc)
}
return got
}
// contained returns whether the size of the widget in the given dimension
// does not depend on its content ([styles.Style.Contain]).
func (wb *WidgetBase) contained(d math32.Dims) bool {
c := wb.Styles.Contain
return c == styles.ContainSize || (c == styles.ContainInlineSize && d == math32.X)
}
// aspectHeight returns the height of the content of the widget for its
// [styles.Style.AspectRatio] at the given width of its content, or 0 if
// it has none, or if its height is set (by its Min).
func (wb *WidgetBase) aspectHeight(w float32) float32 {
r := wb.Styles.AspectRatio
if r <= 0 || w <= 0 || wb.Styles.Min.Y.Value > 0 {
return 0
}
if wb.Styles.BoxSizing == styles.BoxBorderBox {
bs := wb.boxSizingSpace()
return max(math32.Ceil((w+bs.X)/r-bs.Y), 0)
}
return math32.Ceil(w / r)
}
// sizeAspect makes the actual height of the content of the widget at
// least the height for its aspect ratio at its actual width (see
// [WidgetBase.aspectHeight]), and its allocated height too if alloc,
// for its children (in SizeDown). It returns whether the actual height
// changed.
func (wb *WidgetBase) sizeAspect(alloc bool) bool {
sz := &wb.Geom.Size
w := sz.Actual.Content.X
if alloc && wb.Styles.Grow.X > 0 && sz.Alloc.Content.X > w {
w = sz.Alloc.Content.X // as wide as its allocation (as a block)
if sz.Max.X > 0 {
w = min(w, sz.Max.X)
}
}
h := wb.aspectHeight(w)
if h <= 0 {
return false
}
if alloc && sz.Alloc.Content.Y < h {
sz.Alloc.Content.Y = h
sz.SetTotalFromContent(&sz.Alloc)
}
if sz.Actual.Content.Y >= h {
return false
}
sz.Actual.Content.Y = h
sz.SetTotalFromContent(&sz.Actual)
return true
}
// sizeUpParts adjusts the Content size to hold the Parts layout if present
func (wb *WidgetBase) sizeUpParts() {
if wb.Parts == nil {
return
}
wb.Parts.SizeUp()
sz := &wb.Geom.Size
sz.FitSizeMax(&sz.Actual.Content, wb.Parts.Geom.Size.Actual.Total)
}
func (fr *Frame) SizeUp() {
if fr.Styles.Display == styles.Custom {
fr.SizeUpWidget()
fr.sizeUpChildren()
return
}
if !fr.HasChildren() {
fr.SizeUpWidget() // behave like a widget
return
}
fr.sizeFromStyle()
fr.layout.ScrollSize.SetZero() // we don't know yet
fr.setInitCells()
fr.This.(Layouter).LayoutSpace()
fr.sizeUpChildren() // kids do their own thing
fr.sizeUpFlexBasis()
fr.sizeFromChildrenFit(0, SizeUpPass)
fr.sizeUpIntrinsicFrame()
fr.sizeAspect(false)
if fr.Parts != nil {
fr.Parts.SizeUp() // just to get sizes -- no std role in layout
}
}
// sizeUpFlexBasis sets the width of the children of a row that have a
// [styles.Style.FlexBasis] to it (down to their min-content width), as
// their preferred width, from which they grow and shrink, as a flex item
// in CSS (as the events of the current events portal of Wikipedia, of
// flex: 100 1 200px, which started from their text on one line).
func (fr *Frame) sizeUpFlexBasis() {
if fr.Styles.Display != styles.Flex || fr.Styles.Direction != styles.Row {
return
}
fr.forFlowChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
fb := cwb.Styles.FlexBasis.Dots
if fb <= 0 {
return tree.Continue
}
sz := &cwb.Geom.Size
w := math32.Ceil(max(fb+sz.Space.X, sz.minWidth))
if mx := sz.Max.X; mx > 0 {
w = min(w, mx+sz.Space.X)
}
sz.Actual.Total.X = w
sz.SetContentFromTotal(&sz.Actual)
sz.preferred.X = w
return tree.Continue
})
}
// LayoutSpace sets our Space based on Styles and Scroll.
// Other layout types can change this if they want to.
func (fr *Frame) LayoutSpace() {
fr.spaceFromStyle()
fr.Geom.Size.Space.SetAdd(fr.layout.ScrollSize)
}
// sizeUpChildren calls SizeUp on all the children of this node
func (fr *Frame) sizeUpChildren() {
if fr.Styles.Display == styles.Stacked && !fr.LayoutStackTopOnly {
fr.ForWidgetChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
cw.SizeUp()
return tree.Continue
})
return
}
fr.forVisibleChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
cw.SizeUp()
return tree.Continue
})
}
// setInitCells sets the initial default assignment of cell indexes
// to each widget, based on layout type.
func (fr *Frame) setInitCells() {
switch fr.Styles.Display {
case styles.Flex:
if fr.Styles.Wrap {
fr.setInitCellsWrap()
} else {
fr.setInitCellsFlex()
}
case styles.Stacked:
fr.setInitCellsStacked()
case styles.Grid:
fr.setInitCellsGrid()
default:
fr.setInitCellsStacked() // whatever
}
fr.layout.initCells()
fr.setGapSizeFromCells()
fr.layout.shapeCheck(fr, "SizeUp")
// fmt.Println(ly, "SzUp Init", ly.Layout.Shape)
}
func (fr *Frame) setGapSizeFromCells() {
li := &fr.layout
li.Gap = fr.Styles.Gap.Dots().Floor()
// note: this is not accurate for flex
li.GapSize.X = max(float32(li.Shape.X-1)*li.Gap.X, 0)
li.GapSize.Y = max(float32(li.Shape.Y-1)*li.Gap.Y, 0)
fr.Geom.Size.InnerSpace = li.GapSize
}
func (fr *Frame) setInitCellsFlex() {
li := &fr.layout
li.MainAxis = math32.Dims(fr.Styles.Direction)
ca := li.MainAxis.Other()
li.Wraps = nil
idx := 0
fr.forFlowChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
math32.SetPointDim(&cwb.Geom.Cell, li.MainAxis, idx)
math32.SetPointDim(&cwb.Geom.Cell, ca, 0)
idx++
return tree.Continue
})
if idx == 0 {
if DebugSettings.LayoutTrace {
fmt.Println(fr, "no items:", idx)
}
}
math32.SetPointDim(&li.Shape, li.MainAxis, max(idx, 1)) // must be at least 1
math32.SetPointDim(&li.Shape, ca, 1)
}
func (fr *Frame) setInitCellsWrap() {
li := &fr.layout
li.MainAxis = math32.Dims(fr.Styles.Direction)
ni := 0
fr.forFlowChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
ni++
return tree.Continue
})
if ni == 0 {
li.Shape = image.Point{1, 1}
li.Wraps = nil
li.GapSize.SetZero()
fr.Geom.Size.InnerSpace.SetZero()
if DebugSettings.LayoutTrace {
fmt.Println(fr, "no items:", ni)
}
return
}
if fr.Styles.Shrink.X > 0 && li.MainAxis == math32.X {
// all on one line, its widest, which wraps in its allocation
li.Wraps = []int{ni}
fr.setWrapIndexes()
return
}
nm := max(int(math32.Sqrt(float32(ni))), 1)
nc := max(ni/nm, 1)
for nm*nc < ni {
nm++
}
li.Wraps = make([]int, nc)
sum := 0
for i := range li.Wraps {
n := min(ni-sum, nm)
li.Wraps[i] = n
sum += n
}
fr.setWrapIndexes()
}
// setWrapIndexes sets indexes for Wrap case
func (fr *Frame) setWrapIndexes() {
li := &fr.layout
idx := 0
var maxc image.Point
fr.forFlowChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
ic := li.wrapIndexToCoord(idx)
cwb.Geom.Cell = ic
if ic.X > maxc.X {
maxc.X = ic.X
}
if ic.Y > maxc.Y {
maxc.Y = ic.Y
}
idx++
return tree.Continue
})
maxc.X++
maxc.Y++
li.Shape = maxc
}
// UpdateStackedVisibility updates the visibility for Stacked layouts
// so the StackTop widget is visible, and others are Invisible.
func (fr *Frame) UpdateStackedVisibility() {
fr.ForWidgetChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
cwb.SetState(i != fr.StackTop, states.Invisible)
cwb.Geom.Cell = image.Point{0, 0}
return tree.Continue
})
}
func (fr *Frame) setInitCellsStacked() {
fr.UpdateStackedVisibility()
fr.layout.Shape = image.Point{1, 1}
}
func (fr *Frame) setInitCellsGrid() {
n := len(fr.Children)
cols := fr.Styles.Columns
if cols == 0 {
cols = int(math32.Sqrt(float32(n)))
}
if cols == 0 {
fmt.Println(fr, "no cols:", cols)
}
cols = max(cols, 1)
ci := 0
ri := 0
fr.layout.spans = false
fr.layout.rowSpans = false
// occupied has the cells occupied by cells that span rows from above,
// which the cells after them are placed after.
occupied := map[image.Point]bool{}
free := func(c, r, cs int) bool {
for x := c; x < c+cs; x++ {
if occupied[image.Point{x, r}] {
return false
}
}
return true
}
rows := 0
fr.forFlowChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
cs := min(max(cwb.Styles.ColSpan, 1), cols)
rs := max(cwb.Styles.RowSpan, 1)
if cs > 1 {
fr.layout.spans = true
}
if rs > 1 {
fr.layout.rowSpans = true
}
for {
if ci > 0 && ci+cs > cols { // a spanning cell that does not fit starts a new row
ci = 0
ri++
}
if free(ci, ri, cs) {
break
}
ci++
}
cwb.Geom.Cell = image.Point{ci, ri}
for r := ri + 1; r < ri+rs; r++ {
for x := ci; x < ci+cs; x++ {
occupied[image.Point{x, r}] = true
}
}
rows = max(rows, ri+rs)
ci += cs
if ci >= cols {
ci = 0
ri++
}
return tree.Continue
})
fr.layout.Shape = image.Point{cols, max(rows, 1)}
}
// colSpan returns the number of grid columns that the widget spans.
func (fr *Frame) colSpan(cwb *WidgetBase) int {
if fr.Styles.Display != styles.Grid {
return 1
}
return min(max(cwb.Styles.ColSpan, 1), fr.layout.Shape.X-cwb.Geom.Cell.X)
}
// rowSpan returns the number of grid rows that the widget spans.
func (fr *Frame) rowSpan(cwb *WidgetBase) int {
if fr.Styles.Display != styles.Grid {
return 1
}
return min(max(cwb.Styles.RowSpan, 1), fr.layout.Shape.Y-cwb.Geom.Cell.Y)
}
// rowSpanAlloc returns the allocated height of a grid cell at the given
// cell that spans the given number of rows: the total of the heights of
// the rows and the gaps between them, with the given extra height that
// the rows grow into, in proportion to their grow factors.
func (fr *Frame) rowSpanAlloc(cidx image.Point, span int, extra float32) float32 {
li := &fr.layout
gsum := float32(0)
for r := range li.Shape.Y {
gsum += li.cell(math32.Y, r, cidx.X).Grow.Y
}
sum := li.Gap.Y * float32(span-1)
for r := range span {
cd := li.cell(math32.Y, cidx.Y+r, cidx.X)
sum += cd.Size.Y
if gsum > 0 && extra > 0 {
sum += math32.Round(extra * cd.Grow.Y / gsum)
}
}
return sum
}
// sizeFromChildrenFit gathers Actual size from kids, and calls LaySetContentFitOverflow
// to update Actual and Internal size based on this.
func (fr *Frame) sizeFromChildrenFit(iter int, pass LayoutPasses) {
ksz := fr.This.(Layouter).SizeFromChildren(iter, pass)
fr.laySetContentFitOverflow(ksz, pass)
fr.sizeOverflow()
if DebugSettings.LayoutTrace {
sz := &fr.Geom.Size
fmt.Println(fr, pass, "FromChildren:", ksz, "Content:", sz.Actual.Content, "Internal:", sz.Internal)
}
}
// SizeFromChildren gathers Actual size from kids.
// Different Layout types can alter this to present different Content
// sizes for the layout process, e.g., if Content is sized to fit allocation,
// as in the [Toolbar] and [List] types.
func (fr *Frame) SizeFromChildren(iter int, pass LayoutPasses) math32.Vector2 {
var ksz math32.Vector2
if fr.Styles.Display == styles.Stacked {
ksz = fr.sizeFromChildrenStacked()
} else {
ksz = fr.sizeFromChildrenCells(iter, pass)
}
return ksz
}
// sizeFromChildrenCells for Flex, Grid
func (fr *Frame) sizeFromChildrenCells(iter int, pass LayoutPasses) math32.Vector2 {
// r 0 1 col X = max(X over rows), Y = sum(Y over rows)
// +--+--+
// 0 | | | row X = sum(X over cols), Y = max(Y over cols)
// +--+--+
// 1 | | |
// +--+--+
li := &fr.layout
li.initCells()
type spanning struct {
cell image.Point
span int
width float32
grow float32
}
var spans, rowSpans []spanning
fr.forFlowChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
cidx := cwb.Geom.Cell
sz := cwb.Geom.Size.Actual.Total
grw := cwb.Styles.Grow
span := fr.colSpan(cwb)
rspan := fr.rowSpan(cwb)
if pass == SizeFinalPass {
// the cell is the allocation of the child, unless its content
// overflows it (as a frame narrowed below its minimum), which
// then counts for the frame to scroll
if grw.X == 0 && !cwb.Styles.GrowWrap {
sz.X = max(sz.X, cwb.Geom.Size.Alloc.Total.X)
}
if grw.Y == 0 {
sz.Y = max(sz.Y, cwb.Geom.Size.Alloc.Total.Y)
}
}
if pass <= SizeDownPass && iter == 0 && cwb.Styles.GrowWrap {
grw.Set(1, 0)
}
if DebugSettings.LayoutTraceDetail {
fmt.Println("SzUp i:", i, cwb, "cidx:", cidx, "sz:", sz, "grw:", grw)
}
for ma := math32.X; ma <= math32.Y; ma++ { // main axis = X then Y
ca := ma.Other() // cross axis = Y then X
mi := math32.PointDim(cidx, ma) // X, Y
ci := math32.PointDim(cidx, ca) // Y, X
md := li.cell(ma, mi, ci) // X, Y
cd := li.cell(ca, ci, mi) // Y, X
if md == nil || cd == nil {
continue
}
msz := sz.Dim(ma) // main axis size dim: X, Y
mx := md.Size.Dim(ma)
if ma == math32.X && span > 1 { // sized below, over its columns
spans = append(spans, spanning{cidx, span, msz, grw.X})
} else if ma == math32.Y && rspan > 1 { // sized below, over its rows
rowSpans = append(rowSpans, spanning{cidx, rspan, msz, grw.Y})
} else {
mx = max(mx, msz) // Col, max widths of all elements; Row, max heights of all elements
}
md.Size.SetDim(ma, mx)
sm := cd.Size.Dim(ma)
sm += msz
cd.Size.SetDim(ma, sm) // Row, sum widths of all elements; Col, sum heights of all elements
gsz := grw.Dim(ma)
if ma != math32.X || span == 1 { // (the grow of spans is below)
md.Grow.SetDim(ma, max(md.Grow.Dim(ma), gsz))
}
sm = cd.Grow.Dim(ma)
sm += gsz
cd.Grow.SetDim(ma, sm)
}
return tree.Continue
})
// A growing cell that spans columns of which none grow makes them
// all grow (as the columns of a grid of 1fr that cells span), not
// only the first, but not columns that do not grow when others of
// them do: the grow of a span goes to the flexible columns, as in
// CSS (the empty auto columns of the page headers of github.com
// beside a title in minmax(0, 1fr), which were as wide as it).
growing := func(sp spanning) int {
n := 0
for c := range sp.span {
if li.cell(math32.X, sp.cell.X+c, sp.cell.Y).Grow.X > 0 {
n++
}
}
return n
}
for _, sp := range spans {
if sp.grow > 0 && growing(sp) == 0 {
for c := range sp.span {
li.cell(math32.X, sp.cell.X+c, sp.cell.Y).Grow.X = sp.grow
}
}
}
// The columns that a cell spans are widened to fit it: those of
// them that grow, or all of them evenly when none do.
for _, sp := range spans {
sum := li.Gap.X * float32(sp.span-1)
for c := range sp.span {
sum += li.cell(math32.X, sp.cell.X+c, sp.cell.Y).Size.X
}
if extra := sp.width - sum; extra > 0 {
n := growing(sp)
for c := range sp.span {
cd := li.cell(math32.X, sp.cell.X+c, sp.cell.Y)
if n == 0 {
cd.Size.X += extra / float32(sp.span)
} else if cd.Grow.X > 0 {
cd.Size.X += extra / float32(n)
}
}
}
}
// The rows that a cell spans are heightened evenly to fit it.
for _, sp := range rowSpans {
sum := li.Gap.Y * float32(sp.span-1)
for r := range sp.span {
sum += li.cell(math32.Y, sp.cell.Y+r, sp.cell.X).Size.Y
}
if extra := sp.width - sum; extra > 0 {
if fr.FrLastRow { // all in the last one (see Frame.FrLastRow)
li.cell(math32.Y, sp.cell.Y+sp.span-1, sp.cell.X).Size.Y += extra
continue
}
for r := range sp.span {
cd := li.cell(math32.Y, sp.cell.Y+r, sp.cell.X)
cd.Size.Y += extra / float32(sp.span)
}
}
}
if DebugSettings.LayoutTraceDetail {
fmt.Println(fr, "SizeFromChildren")
fmt.Println(li.String())
}
ksz := li.cellsSize()
if fl := li.floats; fl != nil { // the column is as tall as its floats
ksz.Y = max(ksz.Y, fl.size.Y-li.GapSize.Y)
if fr.onlyFloats() { // and as wide, when it only has floats
ksz.X = max(ksz.X, fl.floatsWidth)
}
}
sizing := fr.Scene != nil && fr.Scene.hasFlag(sceneContentSizing)
if pass > SizeUpPass && li.Wraps != nil && li.MainAxis == math32.X && !sizing {
// The lines of a wrapped row whose items are wider than it only by
// the rounding of their sizes to whole dots, which sizeDownWrap
// allows, fit it (as their exact sizes do), so that it does not
// overflow by those dots (except when the scene is sized to fit
// its content, which it is then as wide as).
fit := fr.Geom.Size.Alloc.Content.X
if over := ksz.X - fit; over > 0 && over <= float32(slices.Max(li.Wraps)) {
ksz.X = fit
}
}
return ksz
}
// sizeFromChildrenStacked for stacked case
func (fr *Frame) sizeFromChildrenStacked() math32.Vector2 {
fr.layout.initCells()
kwb := fr.StackTopWidget()
li := &fr.layout
var ksz math32.Vector2
if kwb != nil {
ksz = kwb.Geom.Size.Actual.Total
kgrw := kwb.Styles.Grow
for ma := math32.X; ma <= math32.Y; ma++ { // main axis = X then Y
md := li.cell(ma, 0, 0)
if md == nil {
continue
}
md.Size = ksz
md.Grow = kgrw
}
}
return ksz
}
// SizeDown (top-down, multiple iterations possible) provides top-down
// size allocations based initially on Scene available size and
// the SizeUp Actual sizes. If there is extra space available, it is
// allocated according to the Grow factors.
// Flexible elements (e.g., Flex Wrap layouts and Text with word wrap)
// update their Actual size based on available Alloc size (re-wrap),
// to fit the allocated shape vs. the initial bottom-up guess.
// However, do NOT grow the Actual size to match Alloc at this stage,
// as Actual sizes must always represent the minimums (see Position).
// Returns true if any change in Actual size occurred.
func (wb *WidgetBase) SizeDown(iter int) bool {
wb.updateParentRelSizes()
aspect := wb.sizeAspect(true)
redo := wb.sizeDownParts(iter)
return redo || aspect
}
func (wb *WidgetBase) sizeDownParts(iter int) bool {
if wb.Parts == nil {
return false
}
sz := &wb.Geom.Size
psz := &wb.Parts.Geom.Size
pgrow, _ := wb.growToAllocSize(sz.Actual.Content, sz.Alloc.Content, sz.Max)
psz.Alloc.Total = pgrow // parts = content
psz.SetContentFromTotal(&psz.Alloc)
redo := wb.Parts.SizeDown(iter)
if redo && DebugSettings.LayoutTrace {
fmt.Println(wb, "Parts triggered redo")
}
return redo
}
// sizeDownChildren calls SizeDown on the Children.
// The kids must have their Size.Alloc set prior to this, which
// is what Layout type does. Other special widget types can
// do custom layout and call this too.
func (wb *WidgetBase) sizeDownChildren(iter int) bool {
redo := false
wb.forVisibleChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
re := cw.SizeDown(iter)
if re && DebugSettings.LayoutTrace {
fmt.Println(wb, "SizeDownChildren child:", cwb.Name, "triggered redo")
}
redo = redo || re
return tree.Continue
})
return redo
}
// sizeDownChildren calls SizeDown on the Children.
// The kids must have their Size.Alloc set prior to this, which
// is what Layout type does. Other special widget types can
// do custom layout and call this too.
func (fr *Frame) sizeDownChildren(iter int) bool {
if fr.Styles.Display == styles.Stacked && !fr.LayoutStackTopOnly {
redo := false
fr.ForWidgetChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
re := cw.SizeDown(iter)
if i == fr.StackTop {
redo = redo || re
}
return tree.Continue
})
return redo
}
return fr.WidgetBase.sizeDownChildren(iter)
}
// growToAllocSize returns the potential size that widget could grow,
// for any dimension with a non-zero Grow factor.
// If Grow is < 1, then the size is increased in proportion, but
// any factor > 1 produces a full fill along that dimension.
// Returns true if this resulted in a change.
// The given max is the Max size for the given sizes, which are both either
// Content or Total sizes, with 0 for no Max.
func (wb *WidgetBase) growToAllocSize(act, alloc, mx math32.Vector2) (math32.Vector2, bool) {
change := false
for d := math32.X; d <= math32.Y; d++ {
grw := wb.Styles.Grow.Dim(d)
allocd := alloc.Dim(d)
actd := act.Dim(d)
if grw > 0 && allocd > actd {
grw := min(1, grw)
nsz := math32.Ceil(actd + grw*(allocd-actd))
styles.SetClampMax(&nsz, mx.Dim(d))
if nsz != actd {
change = true
}
act.SetDim(d, nsz)
}
}
return act.Ceil(), change
}
func (fr *Frame) SizeDown(iter int) bool {
redo := fr.sizeDownFrame(iter)
if redo && DebugSettings.LayoutTrace {
fmt.Println(fr, "SizeDown redo")
}
return redo
}
// sizeDownFrame is the [Frame] standard SizeDown pass, returning true if another
// iteration is required. It allocates sizes to fit given parent-allocated
// total size.
func (fr *Frame) sizeDownFrame(iter int) bool {
if fr.Styles.Display == styles.Custom {
return fr.sizeDownCustom(iter)
}
if !fr.HasChildren() || !fr.layout.shapeCheck(fr, "SizeDown") {
return fr.WidgetBase.SizeDown(iter) // behave like a widget
}
fr.updateParentRelSizes()
if iter == 0 { // the sizes of the children from SizeUp
fr.forVisibleChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
cwb.Geom.Size.preferred = cwb.Geom.Size.Actual.Total
return tree.Continue
})
}
sz := &fr.Geom.Size
if fr.Parent != nil {
// A frame is never allocated less than its Min (as a min-width in
// CSS), even when its parent narrows it (as a block in a column):
// its children are laid out in at least that, and it then
// overflows its parent, which scrolls if it can.
styles.SetClampMinVector(&sz.Alloc.Content, sz.Min)
}
styles.SetClampMaxVector(&sz.Alloc.Content, sz.Max) // can't be more than max..
sz.SetTotalFromContent(&sz.Alloc)
// as high as its aspect ratio makes it, for its children too
aspect := fr.sizeAspect(true)
if DebugSettings.LayoutTrace {
fmt.Println(fr, "Managing Alloc:", sz.Alloc.Content)
}
chg := fr.This.(Layouter).ManageOverflow(iter, true) // this must go first.
wrapped := false
if iter <= 1 && fr.Styles.IsFlexWrap() {
wrapped = fr.sizeDownWrap(iter) // first recompute wrap
if iter == 0 {
wrapped = true // always update
}
}
fr.This.(Layouter).SizeDownSetAllocs(iter)
fr.sizeDownOutOfFlow()
floatsChanged := fr.layoutFloats()
redo := fr.sizeDownChildren(iter) || floatsChanged
if redo || wrapped {
fr.sizeFromChildrenFit(iter, SizeDownPass)
}
fr.sizeDownParts(iter) // no std role, just get sizes
if fr.sizeAspect(false) { // after its content (which can make it higher)
aspect = true
}
return chg || wrapped || redo || aspect
}
// SizeDownSetAllocs is the key SizeDown step that sets the allocations
// in the children, based on our allocation. In the default implementation
// this calls SizeDownGrow if there is extra space to grow, or
// SizeDownAllocActual to set the allocations as they currrently are.
func (fr *Frame) SizeDownSetAllocs(iter int) {
sz := &fr.Geom.Size
extra := sz.Alloc.Content.Sub(sz.Internal) // note: critical to use internal to be accurate
// Children that grow only grow within the space of the frame.
fr.layout.growExtra = fr.childSpace().Sub(sz.Internal)
if extra.X > 0 || extra.Y > 0 {
if DebugSettings.LayoutTrace {
fmt.Println(fr, "SizeDown extra:", extra, "Internal:", sz.Internal, "Alloc:", sz.Alloc.Content)
}
fr.sizeDownGrow(iter, extra)
} else {
fr.sizeDownAllocActual(iter) // set allocations as is
}
fr.shrinkColumnHeights()
}
// childSpace returns the content size that the frame allocates to its
// children: its allocation in the dimensions in which it grows, and
// otherwise its actual size, which is all that it takes up even when it
// is allocated more (for example, as the width of the column that it is
// in), so that its children only grow within it.
func (fr *Frame) childSpace() math32.Vector2 {
sz := &fr.Geom.Size
csz := sz.Alloc.Content
if fr.Parent == nil || (fr.Scene != nil && fr.Scene.hasFlag(sceneContentSizing)) {
return csz
}
for d := math32.X; d <= math32.Y; d++ {
grows := fr.Styles.Grow.Dim(d) > 0 || (d == math32.X && fr.Styles.GrowWrap)
if !grows && fr.Styles.Overflow.Dim(d) < styles.OverflowAuto {
csz.SetDim(d, min(csz.Dim(d), sz.Actual.Content.Dim(d)))
}
}
return csz
}
// ManageOverflow uses overflow settings to determine if scrollbars
// are needed (Internal > Alloc). Returns true if size changes as a result.
// If updateSize is false, then the Actual and Alloc sizes are NOT
// updated as a result of change from adding scrollbars
// (generally should be true, but some cases not)
func (fr *Frame) ManageOverflow(iter int, updateSize bool) bool {
sz := &fr.Geom.Size
sbw := math32.Ceil(fr.Styles.ScrollbarWidth.Dots)
change := false
// The scene is being sized to fit its content, from no size,
// so it does not overflow: scrollbars would only make it bigger.
sizing := fr.Parent == nil && fr.Scene != nil && fr.Scene.hasFlag(sceneContentSizing)
if iter == 0 {
fr.layout.ScrollSize.SetZero()
fr.setScrollsOff()
for d := math32.X; d <= math32.Y; d++ {
if fr.Styles.Overflow.Dim(d) == styles.OverflowScroll {
if !fr.HasScroll[d] {
change = true
}
fr.HasScroll[d] = true
fr.layout.ScrollSize.SetDim(d.Other(), sbw)
}
}
}
for d := math32.X; d <= math32.Y; d++ {
maxSize, visSize, _ := fr.This.(Layouter).ScrollValues(d)
if d == math32.X {
maxSize = fr.overflowWidth(iter, maxSize)
}
ofd := maxSize - visSize
switch fr.Styles.Overflow.Dim(d) {
// case styles.OverflowVisible:
// note: this shouldn't happen -- just have this in here for monitoring
// fmt.Println(ly, "OverflowVisible ERROR -- shouldn't have overflow:", d, ofd)
case styles.OverflowAuto:
if ofd < 0.5 || sizing {
if fr.HasScroll[d] {
if DebugSettings.LayoutTrace {
fmt.Println(fr, "turned off scroll", d)
}
change = true
fr.HasScroll[d] = false
fr.layout.ScrollSize.SetDim(d.Other(), 0)
}
continue
}
if !fr.HasScroll[d] {
change = true
}
fr.HasScroll[d] = true
fr.layout.ScrollSize.SetDim(d.Other(), sbw)
if change && DebugSettings.LayoutTrace {
fmt.Println(fr, "OverflowAuto enabling scrollbars for dim for overflow:", d, ofd, "alloc:", sz.Alloc.Content.Dim(d), "internal:", sz.Internal.Dim(d))
}
}
}
fr.This.(Layouter).LayoutSpace() // adds the scroll space
if updateSize {
sz.SetTotalFromContent(&sz.Actual)
sz.SetContentFromTotal(&sz.Alloc) // alloc is *decreased* from any increase in space
}
if change && DebugSettings.LayoutTrace {
fmt.Println(fr, "ManageOverflow changed")
}
return change
}
// sizeDownGrow grows the element sizes based on total extra and Grow
func (fr *Frame) sizeDownGrow(iter int, extra math32.Vector2) bool {
redo := false
// The Max of a child relative to the size of this frame (a percentage
// or a calc of one), which its SizeUp could not know, is of the size
// allocated to this frame before its children grow, so that the width
// that one of them cannot take goes to the others (as the bars of the
// parties of the election results of nytimes.com, of 55% and 44%, which
// were halves of the width up to the 44%).
fr.forFlowChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
if relativeMax(&cwb.Styles) {
cwb.updateParentRelSizes()
}
return tree.Continue
})
if fr.Styles.Display == styles.Stacked {
redo = fr.sizeDownGrowStacked(iter, extra)
} else {
redo = fr.sizeDownGrowCells(iter, extra)
}
return redo
}
// wrapLines returns, for a row that wraps (of [Frame.layout] Wraps, with
// X as its main axis), the width that the widgets of each of its lines
// use (without the gaps between them) and the sum of their grow in X, by
// line, or nils if it does not wrap.
func (fr *Frame) wrapLines() (used, grow []float32) {
li := &fr.layout
if li.Wraps == nil || li.MainAxis != math32.X {
return nil, nil
}
n := len(li.Wraps)
used, grow = make([]float32, n), make([]float32, n)
fr.forFlowChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
if r := cwb.Geom.Cell.Y; r >= 0 && r < n {
used[r] += cwb.Geom.Size.Actual.Total.X
grow[r] += cwb.Styles.Grow.X
}
return tree.Continue
})
return used, grow
}
func (fr *Frame) sizeDownGrowCells(iter int, extra math32.Vector2) bool {
redo := false
sz := &fr.Geom.Size
alloc := sz.Alloc.Content.Sub(sz.InnerSpace) // inner is fixed
// todo: use max growth values instead of individual ones to ensure consistency!
li := &fr.layout
if len(li.Cells) == 0 {
slog.Error("unexpected error: layout has not been initialized", "layout", fr.String())
return false
}
var maxExtra, exn math32.Vector2
var widths []float32
colWidth, colBlock := fr.columnWidth()
// columns that shrink are narrowed to fit, or widened back to their
// widths from SizeUp after they were narrower
widths, shrunk := fr.shrinkWidths()
if fw := fr.frWidths(alloc.X); fw != nil { // (as fr tracks)
widths, shrunk = fw, true
}
// When the columns fit at the widths of shrinkWidths (widened back to
// their preferred widths), those are their base widths, and the columns
// that grow share the width that is left, not the extra width from
// their earlier (narrower) sizes, which would make them overflow.
if widths != nil && !shrunk {
widths = fr.growWidths(widths, alloc.X)
}
lineUsed, lineGrow := fr.wrapLines()
// the width that the widgets of each line of a wrapped row could not
// take, and their grow, which the others of the same line get, not
// those of other lines, which have their own widths
lineExtra, lineExn := make([]float32, len(lineUsed)), make([]float32, len(lineUsed))
for exitr := range 2 {
fr.forFlowChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
cidx := cwb.Geom.Cell
ksz := &cwb.Geom.Size
grw := cwb.Styles.Grow
if iter == 0 && cwb.Styles.GrowWrap {
grw.Set(1, 0)
}
// if DebugSettings.LayoutTrace {
// fmt.Println("szdn i:", i, kwb, "cidx:", cidx, "sz:", sz, "grw:", grw)
// }
for ma := math32.X; ma <= math32.Y; ma++ { // main axis = X then Y
gr := grw.Dim(ma)
ca := ma.Other() // cross axis = Y then X
exd := extra.Dim(ma) // row.X = extra width for cols; col.Y = extra height for rows in this col
if cwb.Styles.Grow.Dim(ma) > 0 {
exd = min(exd, li.growExtra.Dim(ma))
}
if exd < 0 {
exd = 0
}
mi := math32.PointDim(cidx, ma) // X, Y
ci := math32.PointDim(cidx, ca) // Y, X
md := li.cell(ma, mi, ci) // X, Y
cd := li.cell(ca, ci, mi) // Y, X
if md == nil || cd == nil {
continue
}
mx := md.Size.Dim(ma)
asz := mx
gsum := cd.Grow.Dim(ma)
wrapLine := lineUsed != nil && ma == math32.X && ci < len(lineUsed)
if wrapLine {
// a line of a wrapped row grows into the width that is
// left in it (not by the widest widgets in its column
// across the lines, as the first of two items of width
// 100% on lines of their own, which did not grow)
mx = ksz.Actual.Total.X
asz = mx
exd = max(alloc.X-lineUsed[ci], 0)
gsum = lineGrow[ci]
}
if (li.spans || fr.Styles.Display == styles.Grid) && ma == math32.X {
// the columns of a grid grow consistently in every row,
// by the grow of the column, also with spanning cells
// (and in a last row that is not full, whose cells took
// all of the width of the row)
gr = md.Grow.X
gsum = 0
for c := range li.Shape.X {
gsum += li.cell(math32.X, c, ci).Grow.X
}
}
ksz.slot.SetDim(ma, 0)
if gsum > 0 && exd > 0 {
if gr > gsum {
fmt.Println(fr, "SizeDownGrowCells error: grow > grow sum:", gr, gsum)
gr = gsum
}
redo = true
share := mx + exd*(gr/gsum)
asz = math32.Round(share)
oasz := asz
styles.SetClampMax(&asz, ksz.maxTotal().Dim(ma))
if asz < oasz { // didn't consume its full amount
ksz.slot.SetDim(ma, oasz)
if exitr == 0 { // (of its share as it is, not rounded)
if wrapLine {
lineExtra[ci] += share - asz
lineExn[ci] += gr
} else {
maxExtra.SetDim(ma, maxExtra.Dim(ma)+(share-asz))
exn.SetDim(ma, exn.Dim(ma)+gr)
}
}
} else {
if exitr == 1 { // get more!
more, nsum := maxExtra.Dim(ma), gsum-exn.Dim(ma)
if wrapLine {
more, nsum = lineExtra[ci], gsum-lineExn[ci]
}
if nsum > 0 {
// (rounded with its share, rather than each
// rounded up, which overflowed by a pixel)
asz = math32.Round(share + more*(gr/nsum))
}
}
}
if asz > math32.Ceil(alloc.Dim(ma))+1 { // bug!
if DebugSettings.LayoutTrace {
fmt.Println(fr, "SizeDownGrowCells error: sub alloc > total to alloc:", asz, alloc.Dim(ma))
fmt.Println("ma:", ma, "mi:", mi, "ci:", ci, "mx:", mx, "gsum:", gsum, "gr:", gr, "ex:", exd, "par act:", sz.Actual.Content.Dim(ma))
fmt.Println(fr.layout.String())
fmt.Println(fr.layout.cellsSize())
}
}
}
if span := fr.colSpan(cwb); ma == math32.X && span > 1 {
asz = fr.spanAlloc(cidx, span, exd)
}
if span := fr.rowSpan(cwb); ma == math32.Y && span > 1 {
asz = fr.rowSpanAlloc(cidx, span, exd)
}
if ma == math32.X && widths != nil {
// from the widths of shrinkWidths, which those that grow
// grow from into the width that is left (see above)
asz = fr.shrinkAlloc(widths, cidx, fr.colSpan(cwb))
}
if ma == math32.X && colWidth > 0 {
// as wide as it can be (see sizeDownAllocActualCells)
asz = max(asz, ksz.preferred.X)
asz = narrowTo(cwb, asz, colWidth, colBlock)
}
if DebugSettings.LayoutTraceDetail {
fmt.Println(cwb, ma, "alloc:", asz, "was act:", sz.Actual.Total.Dim(ma), "mx:", mx, "gsum:", gsum, "gr:", gr, "ex:", exd)
}
ksz.Alloc.Total.SetDim(ma, asz)
}
ksz.SetContentFromTotal(&ksz.Alloc)
return tree.Continue
})
if exn.X == 0 && exn.Y == 0 && !slices.ContainsFunc(lineExn, func(n float32) bool { return n > 0 }) {
break
}
}
return redo
}
// spanAlloc returns the allocated width of a grid cell at the given cell
// that spans the given number of columns, given the extra width that the
// columns grow into: the total of the widths of the columns and the gaps
// between them.
func (fr *Frame) spanAlloc(cidx image.Point, span int, extra float32) float32 {
li := &fr.layout
gsum := float32(0)
for c := range li.Shape.X {
gsum += li.cell(math32.X, c, cidx.Y).Grow.X
}
sum := li.Gap.X * float32(span-1)
for c := range span {
cd := li.cell(math32.X, cidx.X+c, cidx.Y)
sum += cd.Size.X
if gsum > 0 && extra > 0 {
sum += math32.Round(extra * cd.Grow.X / gsum)
}
}
return sum
}
// shrinkWidths returns the widths of the columns of the frame (its children
// in a row, or the columns of a grid), narrowed to fit within its allocated
// width, in proportion to their width and the [styles.Style.Shrink] of the
// children in them, or nil if it fits or none shrink. It is not for wrapped
// layouts. shrunk is whether they were narrowed to fit, in which case their
// widths are final (they do not also grow), as in CSS.
func (fr *Frame) shrinkWidths() (widths []float32, shrunk bool) {
li := &fr.layout
sz := &fr.Geom.Size
rowOrGrid := fr.Styles.Display == styles.Grid || (fr.Styles.Display == styles.Flex && fr.Styles.Direction == styles.Row)
if li.Wraps != nil || len(li.Cells) == 0 || !rowOrGrid || fr.Styles.MaxContentWidth {
// (the content of a frame as wide as its content is not narrowed)
return nil, false
}
n := li.Shape.X
shrink := make([]float32, n)
minw := make([]float32, n)
pref := make([]float32, n) // the widths of the columns from SizeUp
any := false
type spanning struct {
col, span int
minw float32
}
var spans []spanning
fr.forFlowChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
c := cwb.Geom.Cell.X
if c >= n {
return tree.Continue
}
ksz := &cwb.Geom.Size
if span := fr.colSpan(cwb); span > 1 {
// a cell that spans columns (as a footer over the columns of a
// grid) shrinks with them: they shrink when it can, down to
// the widths that it needs (see below)
spans = append(spans, spanning{c, span, ksz.minWidth})
if ksz.minWidth < ksz.preferred.X {
sh := cwb.Styles.Shrink.X
if sh == 0 {
sh = 1
}
for k := c; k < min(c+span, n); k++ {
shrink[k] = max(shrink[k], sh)
}
any = true
}
return tree.Continue
}
// every widget that can be narrower than it is shrinks, by 1
// unless its style says otherwise
if ksz.minWidth < ksz.preferred.X {
sh := cwb.Styles.Shrink.X
if sh == 0 {
sh = 1
}
shrink[c] = max(shrink[c], sh)
any = true
}
p := ksz.preferred.X
if cwb.Styles.Grow.X > 0 {
// a widget that grows up to its Max (as for a width in CSS)
// starts from it, so that those that have the same Max shrink
// to the same width, as for the flex basis of CSS
if mw := fr.growMaxWidth(cwb); mw > 0 {
p = mw
if cg, ok := cw.(contentGrower); ok && cg.growsFromContent() {
p = min(mw, ksz.prefWidth)
}
}
}
pref[c] = max(pref[c], p)
return tree.Continue
})
if !any {
return nil, false
}
// The columns that shrink start from their widths from SizeUp, so
// that they are as wide as they can be when they were narrower before.
widths = make([]float32, n)
cur := float32(0)
for c := range n {
widths[c] = li.cell(math32.X, c, 0).Size.X
cur += widths[c]
if shrink[c] > 0 {
widths[c] = max(widths[c], pref[c])
}
}
total := float32(0)
for c := range n {
total += widths[c]
}
deficit := sz.Internal.X - cur + total - sz.Alloc.Content.X
if deficit <= 0.5 {
if total > cur+0.5 {
return widths, false
}
return nil, false
}
fr.forFlowChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
if c := cwb.Geom.Cell.X; c < n && fr.colSpan(cwb) == 1 && shrink[c] > 0 {
minw[c] = max(minw[c], cwb.Geom.Size.minWidth)
}
return tree.Continue
})
// The columns that a cell spans are at least as wide as it needs to be,
// widened evenly (as in SizeUp), so that its row is not wider than the
// others (as a header over two columns of a table).
for _, sp := range spans {
end := min(sp.col+sp.span, n)
sum := fr.layout.Gap.X * float32(end-sp.col-1)
nshrink := 0
for c := sp.col; c < end; c++ {
if shrink[c] > 0 {
sum += minw[c]
nshrink++
} else {
sum += widths[c]
}
}
if extra := sp.minw - sum; extra > 0 && nshrink > 0 {
for c := sp.col; c < end; c++ {
if shrink[c] > 0 {
minw[c] += extra / float32(nshrink)
}
}
}
}
for range 2 { // again for those that are not at their minimum
sum := float32(0)
for c := range n {
if shrink[c] > 0 {
sum += shrink[c] * widths[c]
}
}
if sum <= 0 { // none can shrink any more
break
}
left := deficit
for c := range n {
if shrink[c] == 0 {
continue
}
w := widths[c]
nw := max(math32.Round(w-deficit*shrink[c]*w/sum), minw[c])
left -= w - nw
widths[c] = nw
if nw == minw[c] {
shrink[c] = 0 // cannot shrink any more
}
}
if left <= 0.5 {
break
}
deficit = left // those that can shrink more do
}
return widths, true
}
// frWidths returns the widths of the columns of a grid whose columns all
// grow, from the given width of its content, as the fr tracks of CSS: each
// is its share of the width by its grow, or its minimum (the min-content
// width of the cells in it) when that is more, with the others sharing the
// rest, or nil if it is not such a grid. Their preferred widths do not
// count (as the columns of the top stories of bbc.com, whose wider photos
// made their columns wider).
func (fr *Frame) frWidths(width float32) []float32 {
li := &fr.layout
if !fr.FrColumns || fr.Styles.Display != styles.Grid || li.Wraps != nil || fr.Styles.MaxContentWidth {
return nil
}
n := li.Shape.X
if n < 2 || width <= 0 {
return nil
}
// the columns that have no cells (as the empty tracks of
// repeat(auto-fill, minmax(180px, 1fr)) in CSS) grow as the others
// (all of its tracks are fr), so that the others are as wide as they
// are with them, as in CSS (they were sized to their content)
filled := make([]bool, n)
fr.forFlowChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
for c := cwb.Geom.Cell.X; c < min(cwb.Geom.Cell.X+max(fr.colSpan(cwb), 1), n); c++ {
filled[c] = true
}
return tree.Continue
})
grow := make([]float32, n)
emptyGrow := float32(0)
for c := range n {
grow[c] = li.cell(math32.X, c, 0).Grow.X
if filled[c] {
if grow[c] <= 0 {
return nil
}
emptyGrow = max(emptyGrow, grow[c])
}
}
if emptyGrow <= 0 {
return nil
}
for c := range n {
if !filled[c] {
grow[c] = emptyGrow
}
}
minw := make([]float32, n)
type spanning struct {
col, span int
minw float32
}
var spans []spanning
fr.forFlowChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
c := cwb.Geom.Cell.X
if c >= n {
return tree.Continue
}
if span := fr.colSpan(cwb); span > 1 {
spans = append(spans, spanning{c, span, cwb.Geom.Size.minWidth})
} else {
minw[c] = max(minw[c], cwb.Geom.Size.minWidth)
}
return tree.Continue
})
for _, sp := range spans { // spread over their columns, as in SizeUp
end := min(sp.col+sp.span, n)
sum := li.Gap.X * float32(end-sp.col-1)
for c := sp.col; c < end; c++ {
sum += minw[c]
}
if extra := sp.minw - sum; extra > 0 {
for c := sp.col; c < end; c++ {
minw[c] += extra / float32(end-sp.col)
}
}
}
fixed := make([]bool, n) // (the width is without the gaps)
widths := make([]float32, n)
for range n {
left, flex := width, float32(0)
for c := range n {
if fixed[c] {
left -= minw[c]
} else {
flex += grow[c]
}
}
if flex <= 0 {
break
}
unit := max(left, 0) / flex
changed := false
for c := range n {
if !fixed[c] && minw[c] > unit*grow[c] {
fixed[c], changed = true, true
}
}
if changed {
continue
}
for c := range n {
if fixed[c] {
widths[c] = minw[c]
} else {
widths[c] = unit * grow[c]
}
}
return widths
}
return minw
}
// shrinkAlloc returns the allocated width of the given child in the column
// at the given index, from the given shrunk column widths.
func (fr *Frame) shrinkAlloc(widths []float32, cidx image.Point, span int) float32 {
if span <= 1 {
return widths[cidx.X]
}
w := float32(0)
for c := cidx.X; c < min(cidx.X+span, len(widths)); c++ {
w += widths[c]
}
return w + float32(span-1)*fr.layout.Gap.X
}
// columnWidth returns the width of the content of the frame if it is a
// column (block is true) or a wrapped row, within which each of its
// children is allocated at most that width (see [narrowTo]), so that its
// content (such as text) can wrap in it, or -1 otherwise.
func (fr *Frame) columnWidth() (width float32, block bool) {
s := &fr.Styles
if s.Display != styles.Flex {
return -1, false
}
if s.Direction == styles.Column && !s.Wrap {
return fr.Geom.Size.Alloc.Content.X - fr.Geom.Size.InnerSpace.X, true
}
if s.Direction == styles.Row && s.Wrap {
return fr.Geom.Size.Alloc.Content.X, false
}
return -1, false
}
func (fr *Frame) sizeDownWrap(iter int) bool {
wrapped := false
li := &fr.layout
sz := &fr.Geom.Size
d := li.MainAxis
alloc := sz.Alloc.Content
gap := li.Gap.Dim(d)
fit := alloc.Dim(d)
if DebugSettings.LayoutTrace {
fmt.Println(fr, "SizeDownWrap fitting into:", d, fit)
}
first := true
var sum float32
var n int
var wraps []int
fr.forFlowChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
ksz := cwb.Geom.Size.Actual.Total
if d == math32.X && cwb.HasChildren() {
// A frame in a wrapped row is as wide as it can be in it
// (see sizeDownAllocActualCells): its preferred width, within
// the row, which its line needs room for, as for the
// hypothetical main size of a flex item in CSS.
ksz.X = max(ksz.X, min(cwb.Geom.Size.preferred.X, fit))
}
if fb := cwb.Styles.FlexBasis.Dots; d == math32.X && fb > 0 {
// its basis, down to its min-content width (see [styles.Style.FlexBasis]),
// which is of its border box for box-sizing: border-box
fb = max(fb-cwb.boxSizingSpace().X, 0)
ksz.X = min(max(fb+cwb.Geom.Size.Space.X, cwb.Geom.Size.minWidth), fit)
}
if d == math32.X && cwb.Styles.Grow.X > 0 && cwb.Styles.Max.X.Unit == units.UnitPw && cwb.Styles.Min.X.Unit == units.UnitPw {
// A widget whose width is a percentage of the row (its Max,
// with a Min of 0 in percent: as for a percentage width in
// CSS, not a max-width) needs that much room in its line, as
// for the hypothetical main size of a flex item in CSS (as the
// containers of width: 100% of edition.cnn.com, each on a line
// of its own, which were all on one line).
if mw := fr.growMaxWidth(cwb); mw > 0 {
ksz.X = max(ksz.X, min(mw, fit))
}
}
if first {
n = 1
sum = ksz.Dim(d) + gap
first = false
return tree.Continue
}
// The sizes of the items are each rounded up to whole dots, so
// items whose exact sizes fit together (as widths in CSS that add
// up to that of their container) can be up to a dot each over it.
if sum+ksz.Dim(d) > fit+float32(n+1) { // sum has the gap before it
if DebugSettings.LayoutTraceDetail {
fmt.Println(fr, "wrapped:", i, sum, ksz.Dim(d), fit)
}
wraps = append(wraps, n)
sum = ksz.Dim(d) + gap
n = 1 // this guy is on next line
} else {
sum += ksz.Dim(d) + gap
n++
}
return tree.Continue
})
if n > 0 {
wraps = append(wraps, n)
}
wrapped = false
if len(wraps) != len(li.Wraps) {
wrapped = true
} else {
for i := range wraps {
if wraps[i] != li.Wraps[i] {
wrapped = true
break
}
}
}
if !wrapped {
return false
}
if DebugSettings.LayoutTrace {
fmt.Println(fr, "wrapped:", wraps)
}
li.Wraps = wraps
fr.setWrapIndexes()
li.initCells()
fr.setGapSizeFromCells()
fr.sizeFromChildrenCells(iter, SizeDownPass)
return wrapped
}
func (fr *Frame) sizeDownGrowStacked(_ int, _ math32.Vector2) bool {
// stack just gets everything from us
chg := false
asz := fr.Geom.Size.Alloc.Content
// todo: could actually use the grow factors to decide if growing here?
if fr.LayoutStackTopOnly {
kwb := fr.StackTopWidget()
if kwb != nil {
ksz := &kwb.Geom.Size
if ksz.Alloc.Total != asz {
chg = true
}
ksz.Alloc.Total = asz
ksz.SetContentFromTotal(&ksz.Alloc)
}
return chg
}
// note: allocate everyone in case they are flipped to top
// need a new layout if size is actually different
fr.ForWidgetChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
ksz := &cwb.Geom.Size
if ksz.Alloc.Total != asz {
chg = true
}
ksz.Alloc.Total = asz
ksz.SetContentFromTotal(&ksz.Alloc)
return tree.Continue
})
return chg
}
// sizeDownAllocActual sets Alloc to Actual for no-extra case.
func (fr *Frame) sizeDownAllocActual(iter int) {
if fr.Styles.Display == styles.Stacked {
fr.sizeDownAllocActualStacked(iter)
return
}
// todo: wrap needs special case
fr.sizeDownAllocActualCells(iter)
}
// sizeDownAllocActualCells sets Alloc to Actual for no-extra case.
// Note however that due to max sizing for row / column,
// this size can actually be different than original actual.
func (fr *Frame) sizeDownAllocActualCells(_ int) {
// In a column that is narrower than its content, the children get at
// most its width (but not less than their minimum), so that text can
// wrap in it.
colWidth, colBlock := fr.columnWidth()
widths, _ := fr.shrinkWidths()
fr.forFlowChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
ksz := &cwb.Geom.Size
cidx := cwb.Geom.Cell
for ma := math32.X; ma <= math32.Y; ma++ { // main axis = X then Y
ca := ma.Other() // cross axis = Y then X
mi := math32.PointDim(cidx, ma) // X, Y
ci := math32.PointDim(cidx, ca) // Y, X
md := fr.layout.cell(ma, mi, ci) // X, Y
if md == nil {
continue
}
asz := md.Size.Dim(ma)
if span := fr.colSpan(cwb); ma == math32.X && span > 1 {
asz = fr.spanAlloc(cidx, span, 0)
}
if span := fr.rowSpan(cwb); ma == math32.Y && span > 1 {
asz = fr.rowSpanAlloc(cidx, span, 0)
}
if ma == math32.X && widths != nil {
asz = fr.shrinkAlloc(widths, cidx, fr.colSpan(cwb))
}
if ma == math32.X && colWidth > 0 {
// as wide as it can be: its preferred width, within the
// column, even after it was narrower in an earlier iteration
asz = max(asz, cwb.Geom.Size.preferred.X)
asz = narrowTo(cwb, asz, colWidth, colBlock)
}
ksz.Alloc.Total.SetDim(ma, asz)
}
ksz.SetContentFromTotal(&ksz.Alloc)
return tree.Continue
})
}
// shrinkColumnHeights shrinks the heights allocated to the children of a
// flex column that has a maximum height (as a max-height in CSS) whose
// children are higher than it: those that scroll or clip their content
// (whose minimum height is not that of their content, as in CSS) shrink in
// proportion to their heights, down to their Min, so that the others fit
// (as the content of the cookie dialog of reddit.com, which scrolls above
// its buttons, which were below the dialog).
func (fr *Frame) shrinkColumnHeights() {
s := &fr.Styles
if s.Display != styles.Flex || s.Direction != styles.Column || s.Wrap || s.Max.Y.Dots <= 0 {
return
}
sz := &fr.Geom.Size
avail := sz.Alloc.Content.Y - sz.InnerSpace.Y
used := float32(0)
var shrinks []*WidgetBase
fr.forFlowChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
used += cwb.Geom.Size.Alloc.Total.Y
if cwb.Styles.Overflow.Y != styles.OverflowVisible && cwb.Geom.Size.Alloc.Total.Y > cwb.Styles.Min.Y.Dots {
shrinks = append(shrinks, cwb)
}
return tree.Continue
})
deficit := used - avail
for range 4 { // (those at their Min do not shrink more)
if deficit <= 0.5 || len(shrinks) == 0 {
return
}
total := float32(0)
for _, cwb := range shrinks {
total += cwb.Geom.Size.Alloc.Total.Y
}
if total <= 0 {
return
}
var left []*WidgetBase
for _, cwb := range shrinks {
ksz := &cwb.Geom.Size
h := ksz.Alloc.Total.Y
nh := max(h-deficit*h/total, cwb.Styles.Min.Y.Dots)
ksz.Alloc.Total.Y = nh
ksz.SetContentFromTotal(&ksz.Alloc)
if ksz.Actual.Total.Y > nh { // (it scrolls or clips the rest)
ksz.Actual.Total.Y = nh
ksz.SetContentFromTotal(&ksz.Actual)
}
// (its content size, which its final size fits, up to this; it
// is that of its styles again at the next layout, see SizeUp)
ksz.Max.Y = ksz.Alloc.Content.Y
deficit -= h - nh
if nh > cwb.Styles.Min.Y.Dots {
left = append(left, cwb)
}
}
shrinks = left
}
}
func (fr *Frame) sizeDownAllocActualStacked(_ int) {
// stack just gets everything from us
asz := fr.Geom.Size.Actual.Content
// todo: could actually use the grow factors to decide if growing here?
if fr.LayoutStackTopOnly {
kwb := fr.StackTopWidget()
if kwb != nil {
ksz := &kwb.Geom.Size
ksz.Alloc.Total = asz
ksz.SetContentFromTotal(&ksz.Alloc)
}
return
}
// note: allocate everyone in case they are flipped to top
// need a new layout if size is actually different
fr.ForWidgetChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
ksz := &cwb.Geom.Size
ksz.Alloc.Total = asz
ksz.SetContentFromTotal(&ksz.Alloc)
return tree.Continue
})
}
func (fr *Frame) sizeDownCustom(iter int) bool {
fr.updateParentRelSizes()
fr.growToAlloc()
sz := &fr.Geom.Size
if DebugSettings.LayoutTrace {
fmt.Println(fr, "Custom Managing Alloc:", sz.Alloc.Content)
}
styles.SetClampMaxVector(&sz.Alloc.Content, sz.Max) // can't be more than max..
// this allocates our full size to each child, same as ActualStacked all case
asz := sz.Actual.Content
fr.ForWidgetChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
ksz := &cwb.Geom.Size
ksz.Alloc.Total = asz
ksz.SetContentFromTotal(&ksz.Alloc)
return tree.Continue
})
redo := fr.sizeDownChildren(iter)
fr.sizeDownParts(iter) // no std role, just get sizes
return redo
}
// sizeFinalUpdateChildrenSizes can optionally be called for layouts
// that dynamically create child elements based on final layout size.
// It ensures that the children are properly sized.
func (fr *Frame) sizeFinalUpdateChildrenSizes() {
fr.SizeUp()
iter := 3 // late stage..
fr.This.(Layouter).SizeDownSetAllocs(iter)
fr.sizeDownChildren(iter)
fr.sizeDownParts(iter) // no std role, just get sizes
}
// SizeFinal is (bottom-up) similar to SizeUp but done at the end of the
// Sizing phase: first grows widget Actual sizes based on their Grow
// factors, up to their Alloc sizes. Then gathers this updated final
// actual Size information for layouts to register their actual sizes
// prior to positioning, which requires accurate Actual vs. Alloc
// sizes to perform correct alignment calculations.
func (wb *WidgetBase) SizeFinal() {
wb.Geom.RelPos.SetZero()
sz := &wb.Geom.Size
sz.Internal = sz.Actual.Content // keep it before we grow
wb.growToAlloc()
wb.sizeAspect(false) // for its final width
wb.styleSizeUpdate() // now that sizes are stable, ensure styling based on size is updated
wb.sizeFinalParts()
sz.SetTotalFromContent(&sz.Actual)
}
// growToAlloc grows our Actual size up to current Alloc size
// for any dimension with a non-zero Grow factor.
// If Grow is < 1, then the size is increased in proportion, but
// any factor > 1 produces a full fill along that dimension.
// Returns true if this resulted in a change in our Total size.
func (wb *WidgetBase) growToAlloc() bool {
if (wb.Scene != nil && wb.Scene.hasFlag(sceneContentSizing)) || wb.Styles.GrowWrap {
return false
}
sz := &wb.Geom.Size
act, change := wb.growToAllocSize(sz.Actual.Total, sz.Alloc.Total, sz.maxTotal())
if change {
if DebugSettings.LayoutTrace {
fmt.Println(wb, "GrowToAlloc:", sz.Alloc.Total, "from actual:", sz.Actual.Total)
}
sz.Actual.Total = act // already has max constraint
sz.SetContentFromTotal(&sz.Actual)
}
return change
}
// sizeFinalParts adjusts the Content size to hold the Parts Final sizes
func (wb *WidgetBase) sizeFinalParts() {
if wb.Parts == nil {
return
}
wb.Parts.SizeFinal()
sz := &wb.Geom.Size
sz.FitSizeMax(&sz.Actual.Content, wb.Parts.Geom.Size.Actual.Total)
}
func (fr *Frame) SizeFinal() {
if fr.Styles.Display == styles.Custom {
fr.WidgetBase.SizeFinal() // behave like a widget
fr.WidgetBase.sizeFinalChildren()
return
}
if !fr.HasChildren() || !fr.layout.shapeCheck(fr, "SizeFinal") {
fr.WidgetBase.SizeFinal() // behave like a widget
return
}
fr.Geom.RelPos.SetZero()
fr.sizeFinalChildren() // kids do their own thing
fr.sizeDownOutOfFlow() // their final size is still that of their inset
fr.layoutFloats() // with the final sizes
fr.sizeFromChildrenFit(0, SizeFinalPass)
fr.growToAlloc()
fr.dropFittingScroll()
fr.sizeAspect(false) // for its final width
fr.styleSizeUpdate() // now that sizes are stable, ensure styling based on size is updated
fr.sizeFinalParts()
}
// dropFittingScroll turns off the scrolling in width of a frame with an
// auto overflow whose content fits it once it has its final size (within
// the rounding of sizes, as the width of a scrollbar that is rounded up,
// up to a pixel and a half beyond it): rows that wrap deeper in it are
// only sized to fit after it decides to scroll (see [Frame.ManageOverflow]),
// as the row of links of the footer of pkg.go.dev, which made its page
// scroll by a pixel or less. The space of the scrollbar is given to its
// content.
func (fr *Frame) dropFittingScroll() {
if !fr.HasScroll[math32.X] || fr.Styles.Overflow.X != styles.OverflowAuto {
return
}
maxSize, visSize, _ := fr.This.(Layouter).ScrollValues(math32.X)
if maxSize-visSize > 1.5 {
return
}
sz := &fr.Geom.Size
fr.HasScroll[math32.X] = false
fr.layout.ScrollSize.SetDim(math32.Y, 0)
fr.This.(Layouter).LayoutSpace()
sz.SetContentFromTotal(&sz.Actual)
sz.SetContentFromTotal(&sz.Alloc)
}
// sizeFinalChildren calls SizeFinal on all the children of this node
func (wb *WidgetBase) sizeFinalChildren() {
wb.forVisibleChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
cw.SizeFinal()
return tree.Continue
})
}
// sizeFinalChildren calls SizeFinal on all the children of this node
func (fr *Frame) sizeFinalChildren() {
if fr.Styles.Display == styles.Stacked && !fr.LayoutStackTopOnly {
fr.ForWidgetChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
cw.SizeFinal()
return tree.Continue
})
return
}
fr.WidgetBase.sizeFinalChildren()
}
// styleSizeUpdate updates styling size values for widget and its parent,
// which should be called after these are updated. Returns true if any changed.
func (wb *WidgetBase) styleSizeUpdate() bool {
pwb := wb.parentWidget()
if pwb == nil {
return false
}
wb.updateParentRelSizes()
scsz := wb.Scene.SceneGeom.Size
sz := wb.Geom.Size.Alloc.Content
psz := wb.percentBase(pwb)
chg := wb.Styles.UnitContext.SetSizes(float32(scsz.X), float32(scsz.Y), sz.X, sz.Y, psz.X, psz.Y)
if chg {
wb.Styles.ToDots()
// padding and margins of percentages that changed were not those
// of the layout (as the padding-bottom: 56.25% of the boxes of
// the images of edition.cnn.com that its scripts make, which were
// of the width of the page before it was laid out)
if space := wb.Styles.BoxSpace().Size().Ceil(); math32.Abs(space.X-wb.Geom.Size.Space.X) > 0.5 || math32.Abs(space.Y-wb.Geom.Size.Space.Y) > 0.5 {
wb.Scene.spaceChanged = true
}
}
return chg
}
// Position uses the final sizes to set relative positions within layouts
// according to alignment settings.
func (wb *WidgetBase) Position() {
wb.positionParts()
}
// alignSize returns the size that the widget is aligned within:
// its allocation, or the slot that its Max size limited it within.
func (wb *WidgetBase) alignSize() math32.Vector2 {
sz := &wb.Geom.Size
return sz.Alloc.Total.Max(sz.slot)
}
// positionWithinAllocMainX positions the widget within its allocation,
// in a row (main axis X), and within the given cross size (the height
// of its line), if larger, for its alignment on the cross axis.
func (wb *WidgetBase) positionWithinAllocMainX(pos math32.Vector2, parJustify, parAlign styles.Aligns, cross float32) {
sz := &wb.Geom.Size
asz := wb.alignSize()
asz.Y = max(asz.Y, cross)
pos.X += styles.AlignPos(styles.ItemAlign(parJustify, wb.Styles.Justify.Self), sz.Actual.Total.X, asz.X)
pos.Y += styles.AlignPos(styles.ItemAlign(parAlign, wb.Styles.Align.Self), sz.Actual.Total.Y, asz.Y)
wb.Geom.RelPos = pos
if DebugSettings.LayoutTrace {
fmt.Println(wb, "Position within Main=X:", pos)
}
}
// positionWithinAllocMainY positions the widget within its allocation,
// in a column (main axis Y), and within the given cross size (the width
// of its line), if larger, for its alignment on the cross axis.
func (wb *WidgetBase) positionWithinAllocMainY(pos math32.Vector2, parJustify, parAlign styles.Aligns, cross float32) {
sz := &wb.Geom.Size
asz := wb.alignSize()
asz.X = max(asz.X, cross)
pos.Y += styles.AlignPos(styles.ItemAlign(parJustify, wb.Styles.Justify.Self), sz.Actual.Total.Y, asz.Y)
pos.X += styles.AlignPos(styles.ItemAlign(parAlign, wb.Styles.Align.Self), sz.Actual.Total.X, asz.X)
wb.Geom.RelPos = pos
if DebugSettings.LayoutTrace {
fmt.Println(wb, "Position within Main=Y:", pos)
}
}
func (wb *WidgetBase) positionParts() {
if wb.Parts == nil {
return
}
sz := &wb.Geom.Size
pgm := &wb.Parts.Geom
pgm.RelPos.X = styles.AlignPos(wb.Parts.Styles.Justify.Content, pgm.Size.Actual.Total.X, sz.Actual.Content.X)
pgm.RelPos.Y = styles.AlignPos(wb.Parts.Styles.Align.Content, pgm.Size.Actual.Total.Y, sz.Actual.Content.Y)
if DebugSettings.LayoutTrace {
fmt.Println(wb.Parts, "parts align pos:", pgm.RelPos)
}
wb.Parts.This.(Widget).Position()
}
// positionChildren runs Position on the children
func (wb *WidgetBase) positionChildren() {
wb.forVisibleChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
cw.Position()
return tree.Continue
})
}
// Position uses the final sizes to position everything within layouts
// according to alignment settings.
func (fr *Frame) Position() {
if fr.Styles.Display == styles.Custom {
fr.positionFromPos()
fr.positionChildren()
return
}
if !fr.HasChildren() || !fr.layout.shapeCheck(fr, "Position") {
fr.WidgetBase.Position() // behave like a widget
return
}
if fr.Parent == nil {
fr.positionWithinAllocMainY(math32.Vector2{}, fr.Styles.Justify.Items, fr.Styles.Align.Items, 0)
}
fr.ConfigScrolls() // and configure the scrolls
if fr.Styles.Display == styles.Stacked {
fr.positionStacked()
} else {
fr.positionCells()
fr.positionStatic()
fr.positionChildren()
}
fr.positionParts()
}
// positionStatic sets the positions in the layout of the children of the
// frame that are out of its flow (absolute and fixed ones), which they have
// in the dimensions in which their inset is not set (their static position
// in CSS): right after the child in the flow before them, below it in a
// column (as the dropdown panels of the menus of MDN, below their buttons,
// which covered them), and beside it in a row, or at the start.
func (fr *Frame) positionStatic() {
var prev *WidgetBase
column := fr.Styles.Display != styles.Grid && fr.Styles.Direction == styles.Column
fr.ForWidgetChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
if cwb.StateIs(states.Invisible) {
return tree.Continue
}
if !cwb.outOfFlow() {
prev = cwb
return tree.Continue
}
var pos math32.Vector2
if prev != nil {
pos = prev.Geom.RelPos
if column {
pos.X = 0
pos.Y += prev.Geom.Size.Actual.Total.Y
} else {
pos.X += prev.Geom.Size.Actual.Total.X
}
}
cwb.Geom.RelPos = pos
return tree.Continue
})
}
func (fr *Frame) positionCells() {
if fr.Styles.Display == styles.Grid && fr.layout.rowSpans {
fr.positionCellsGrid()
return
}
if fr.Styles.Display == styles.Flex && fr.Styles.Direction == styles.Column {
fr.positionCellsMainY()
return
}
fr.positionCellsMainX()
}
// Main axis = X
// positionCellsGrid positions the cells of a grid that has cells that
// span rows, at the positions of their columns and rows, which are as wide
// and high as the widest and highest of their cells that do not span.
func (fr *Frame) positionCellsGrid() {
li := &fr.layout
gap := li.Gap
sz := &fr.Geom.Size
colW := make([]float32, li.Shape.X)
rowH := make([]float32, li.Shape.Y)
fr.forFlowChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
c := cwb.Geom.Cell
alloc := cwb.Geom.Size.Alloc.Total
if fr.colSpan(cwb) == 1 && c.X < len(colW) {
colW[c.X] = max(colW[c.X], alloc.X)
}
if fr.rowSpan(cwb) == 1 && c.Y < len(rowH) {
rowH[c.Y] = max(rowH[c.Y], alloc.Y)
}
return tree.Continue
})
// the columns that cells span are widened evenly to fit them (as for
// the sizes of the cells), as when all of the cells span columns (as
// the stories of npr.org, of 8 and 4 of 12 columns)
fr.forFlowChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
c, span := cwb.Geom.Cell.X, fr.colSpan(cwb)
if span <= 1 || c+span > len(colW) {
return tree.Continue
}
sum := gap.X * float32(span-1)
for k := range span {
sum += colW[c+k]
}
if extra := cwb.Geom.Size.Alloc.Total.X - sum; extra > 0 {
for k := range span {
colW[c+k] += extra / float32(span)
}
}
return tree.Continue
})
var stPos math32.Vector2
stPos.X = styles.AlignPos(fr.Styles.Justify.Content, sz.Internal.X, sz.Actual.Content.X)
stPos.Y = styles.AlignPos(fr.Styles.Align.Content, sz.Internal.Y, sz.Actual.Content.Y)
colX := make([]float32, li.Shape.X)
rowY := make([]float32, li.Shape.Y)
for c := range colX {
if c > 0 {
colX[c] = colX[c-1] + colW[c-1] + gap.X
}
}
for r := range rowY {
if r > 0 {
rowY[r] = rowY[r-1] + rowH[r-1] + gap.Y
}
}
fr.forFlowChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
c := cwb.Geom.Cell
pos := stPos.Add(math32.Vec2(colX[min(c.X, len(colX)-1)], rowY[min(c.Y, len(rowY)-1)]))
cwb.positionWithinAllocMainX(pos, fr.Styles.Justify.Items, fr.Styles.Align.Items, 0)
return tree.Continue
})
}
// fixedSingleLine returns whether the frame is a row of one line (of the
// given number of lines) whose height is fixed, so that its items that are
// higher are aligned in it as they overflow it: its overflow is hidden in
// the layout but not clipped (as a box of a fixed height in CSS).
func (fr *Frame) fixedSingleLine(lines int) bool {
return lines <= 1 && fr.Styles.Overflow.Y == styles.OverflowHidden && fr.Styles.NoClip && fr.Styles.Max.Y.Dots > 0
}
func (fr *Frame) positionCellsMainX() {
// todo: can break apart further into Flex rows
gap := fr.layout.Gap
sz := &fr.Geom.Size
if DebugSettings.LayoutTraceDetail {
fmt.Println(fr, "PositionCells Main X, actual:", sz.Actual.Content, "internal:", sz.Internal)
}
var stPos math32.Vector2
stPos.X = styles.AlignPos(fr.Styles.Justify.Content, sz.Internal.X, sz.Actual.Content.X)
spaces := fr.lineSpaces(math32.X, sz.Actual.Content.X)
crosses := fr.lineCrosses(math32.X)
stPos.Y = styles.AlignPos(fr.Styles.Align.Content, max(sz.Internal.Y, linesSize(crosses, gap.Y)), sz.Actual.Content.Y)
baselines := fr.lineBaselines()
// the cells of a grid are at the positions of their columns, which a
// cell narrower than its column (as one with a max width) does not move
var colW []float32
if fr.Styles.Display == styles.Grid && fr.layout.Shape.X > 0 {
colW = make([]float32, fr.layout.Shape.X)
fr.forFlowChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
if c := cwb.Geom.Cell.X; c < len(colW) && fr.colSpan(cwb) == 1 {
colW[c] = max(colW[c], cwb.Geom.Size.Alloc.Total.X)
}
return tree.Continue
})
}
pos := stPos
var lastSz math32.Vector2
idx := 0
line := 0
fr.forFlowChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
cidx := cwb.Geom.Cell
if cidx.X == 0 && idx > 0 {
// the next line is after the height of this one, not of its
// last item (as the actions beside a title of two lines in
// the page headers of github.com, which the line under it
// overlapped)
pos.X = stPos.X
pos.Y += max(lastSz.Y, crosses[min(line, len(crosses)-1)]) + gap.Y
line++
}
if spaces != nil && line < len(spaces) {
if cidx.X == 0 {
pos.X += spaces[line].X
} else {
pos.X += spaces[line].Y
}
}
cwb.positionWithinAllocMainX(pos, fr.Styles.Justify.Items, fr.Styles.Align.Items, crosses[min(line, len(crosses)-1)])
if fr.fixedSingleLine(len(crosses)) {
// an item higher than a row of a fixed height (its overflow is
// hidden in the layout, but not clipped) is aligned in the row,
// out of it, as in CSS (as the edition bar of nytimes.com, of a
// height of 0, with its content at its end, above it)
if extra := sz.Actual.Content.Y - cwb.Geom.Size.Actual.Total.Y; extra < 0 {
f := styles.AlignFactor(styles.ItemAlign(fr.Styles.Align.Items, cwb.Styles.Align.Self))
cwb.Geom.RelPos.Y = pos.Y + math32.Floor(f*extra)
}
}
if baselines != nil && styles.ItemAlign(fr.Styles.Align.Items, cwb.Styles.Align.Self) == styles.Baseline {
// the baselines of the items of the line with text are at the
// same place, within the line; the others are at its end
cross := crosses[min(line, len(crosses)-1)]
h := cwb.Geom.Size.Actual.Total.Y
if b, ok := cwb.firstBaseline(); ok {
off := min(cross-baselines[min(line, len(baselines)-1)]-b, cross-h)
cwb.Geom.RelPos.Y = pos.Y + math32.Floor(max(off, 0))
} else {
cwb.Geom.RelPos.Y = pos.Y + math32.Floor(max(cross-h, 0))
}
}
alloc := cwb.Geom.Size.Alloc.Total
if c := cidx.X; colW != nil && c < len(colW) && fr.colSpan(cwb) == 1 {
pos.X += max(alloc.X, colW[c]) + gap.X
} else {
pos.X += alloc.X + gap.X
}
lastSz = alloc
idx++
return tree.Continue
})
}
// lineCrosses returns, for each line of the children along the given main
// axis, its size on the cross axis: the largest allocation of its children,
// within which they are aligned on the cross axis (as a child that is
// centered in a column next to a child that grows to its width). A column
// of one line (see [Frame.singleLineColumn]) is at least as wide as its
// content (as a table that is centered in a column by itself, as with
// align="center" in HTML). It has one line if there are no children.
func (fr *Frame) lineCrosses(ma math32.Dims) []float32 {
ca := ma.Other()
crosses := []float32{0}
idx := 0
fr.forFlowChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
if math32.PointDim(cwb.Geom.Cell, ma) == 0 && idx > 0 {
crosses = append(crosses, 0)
}
ln := len(crosses) - 1
// the size it is aligned in (see [WidgetBase.alignSize]), as its
// slot, which can be wider than its allocation (as a table of
// 600px centered in a cell), so that it is not offset twice: as
// a line (by Align.Content) and in its line (by Align.Items)
crosses[ln] = max(crosses[ln], cwb.alignSize().Dim(ca))
idx++
return tree.Continue
})
if ma == math32.Y && len(crosses) == 1 && fr.singleLineColumn() {
crosses[0] = max(crosses[0], fr.Geom.Size.Actual.Content.Dim(ca))
}
return crosses
}
// linesSize returns the total size of lines of the given sizes on the
// cross axis (see [Frame.lineCrosses]), with the given gap between them,
// which the lines are aligned as a group by (with Align.Content): their
// items may have grown wider than the internal size of the frame (as a
// line of text before a table, both centered in a column, which the text
// made as wide as the column, and the table was off to its end).
func linesSize(crosses []float32, gap float32) float32 {
var sz float32
for i, c := range crosses {
if i > 0 {
sz += gap
}
sz += c
}
return sz
}
// singleLineColumn returns whether the frame is a column of one line, a
// flex one that does not wrap, whose line is the width of its content, in
// which its children are aligned (see [Frame.lineCrosses]), as in CSS. Its
// Align.Content must be Start: otherwise it places its children as a group,
// of the width of the widest, in which they are aligned.
func (fr *Frame) singleLineColumn() bool {
st := &fr.Styles
return st.Direction == styles.Column && !st.Wrap && st.Display == styles.Flex &&
(st.Align.Content == styles.Start || st.Align.Content == styles.Auto)
}
// lineBaselines returns, for each line of the children of the frame in
// a row, the largest distance from the baselines of its children that are
// aligned on their baselines (see [styles.Baseline]) and have text to
// their bottoms: they are aligned on a baseline that far from the end of
// the line (and the children without text are at the end of the line, as
// with [styles.End]). It returns nil if no children are aligned on their
// baselines.
func (fr *Frame) lineBaselines() []float32 {
var bases []float32
any := false
idx := 0
fr.forFlowChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
if cwb.Geom.Cell.X == 0 || idx == 0 {
bases = append(bases, 0)
}
idx++
if styles.ItemAlign(fr.Styles.Align.Items, cwb.Styles.Align.Self) != styles.Baseline {
return tree.Continue
}
any = true
if b, ok := cwb.firstBaseline(); ok {
ln := len(bases) - 1
bases[ln] = max(bases[ln], cwb.Geom.Size.Actual.Total.Y-b)
}
return tree.Continue
})
if !any {
return nil
}
return bases
}
// firstBaseline returns the distance from the top of the widget to the
// baseline of its first line of text: that of a [Text], or of the first
// child of a [Frame] that has one, and whether there is one.
func (wb *WidgetBase) firstBaseline() (float32, bool) {
top := wb.Styles.BoxSpace().Top
switch w := wb.This.(type) {
case *Text:
if w.paintText == nil || len(w.paintText.Lines) == 0 {
return 0, false
}
ls := w.paintText
return top + ls.Lines[0].Offset.Y - ls.Bounds.Min.Y, true
case *TextField:
// its line of text, at the top of its content (as the search
// field of the Python docs, beside the text of its label)
if w.renderAll == nil || len(w.renderAll.Lines) == 0 {
return 0, false
}
ls := w.renderAll
return top + ls.Lines[0].Offset.Y - ls.Bounds.Min.Y, true
}
// a frame, or a widget that is one (as a chooser, whose text is the
// baseline of the select of the Python docs, beside its label)
fr := AsFrame(wb.This)
if fr == nil {
return 0, false
}
if b, ok := fr.rowBaseline(); ok {
return top + b, true
}
var base float32
found := false
content := fr.Geom.Size.Actual.Content.Y
fr.forFlowChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
if b, ok := cwb.firstBaseline(); ok {
// a child of a row that is centered (as the text of a chooser)
// is lower by half of the space around it
if fr.Styles.Direction == styles.Row && styles.ItemAlign(fr.Styles.Align.Items, cwb.Styles.Align.Self) == styles.Center {
b += max(content-cwb.Geom.Size.Actual.Total.Y, 0) / 2
}
base, found = top+b, true
return tree.Break
}
return tree.Continue
})
return base, found
}
// rowBaseline returns the baseline of the first line of a frame that is
// a row aligned on baselines (see [Frame.lineBaselines]), from the top of
// its content, and whether it has one: where its items with text are
// aligned, in the line of the size of its largest item.
func (fr *Frame) rowBaseline() (float32, bool) {
if fr.Styles.Direction != styles.Row || fr.Styles.Align.Items != styles.Baseline {
return 0, false
}
var cross, desc float32
found := false
idx := 0
fr.forFlowChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
if cwb.Geom.Cell.X == 0 && idx > 0 {
return tree.Break // the first line only
}
idx++
h := cwb.Geom.Size.Actual.Total.Y
cross = max(cross, h)
if styles.ItemAlign(fr.Styles.Align.Items, cwb.Styles.Align.Self) != styles.Baseline {
return tree.Continue
}
if b, ok := cwb.firstBaseline(); ok {
desc, found = max(desc, h-b), true
}
return tree.Continue
})
if !found {
return 0, false
}
return cross - desc, true
}
// lineSpaces returns, for each line of the children along the given main
// axis, the space before the first child (X) and between the children (Y)
// for the distributed [styles.Style.Justify] Content values (SpaceBetween,
// SpaceAround, SpaceEvenly) of the frame, given its content size along
// the axis. It returns nil for the other values, which position all of
// the children as a block.
func (fr *Frame) lineSpaces(ma math32.Dims, size float32) []math32.Vector2 {
jc := fr.Styles.Justify.Content
if jc != styles.SpaceBetween && jc != styles.SpaceAround && jc != styles.SpaceEvenly {
return nil
}
gap := fr.layout.Gap.Dim(ma)
var widths []float32
var counts []int
fr.forFlowChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
if math32.PointDim(cwb.Geom.Cell, ma) == 0 || len(widths) == 0 {
widths = append(widths, 0)
counts = append(counts, 0)
}
ln := len(widths) - 1
if counts[ln] > 0 {
widths[ln] += gap
}
widths[ln] += cwb.Geom.Size.Alloc.Total.Dim(ma)
counts[ln]++
return tree.Continue
})
spaces := make([]math32.Vector2, len(widths))
for ln, w := range widths {
extra := size - w
n := float32(counts[ln])
if extra <= 0 || n == 0 {
continue
}
switch jc {
case styles.SpaceBetween:
if n > 1 {
spaces[ln].Y = extra / (n - 1)
}
case styles.SpaceAround:
spaces[ln].Y = extra / n
spaces[ln].X = spaces[ln].Y / 2
case styles.SpaceEvenly:
spaces[ln].Y = extra / (n + 1)
spaces[ln].X = spaces[ln].Y
}
}
return spaces
}
// Main axis = Y
func (fr *Frame) positionCellsMainY() {
if fr.positionFloats() {
return
}
gap := fr.layout.Gap
sz := &fr.Geom.Size
if DebugSettings.LayoutTraceDetail {
fmt.Println(fr, "PositionCells, actual", sz.Actual.Content, "internal:", sz.Internal)
}
var lastSz math32.Vector2
var stPos math32.Vector2
stPos.Y = styles.AlignPos(fr.Styles.Justify.Content, sz.Internal.Y, sz.Actual.Content.Y)
spaces := fr.lineSpaces(math32.Y, sz.Actual.Content.Y)
crosses := fr.lineCrosses(math32.Y)
stPos.X = styles.AlignPos(fr.Styles.Align.Content, max(sz.Internal.X, linesSize(crosses, gap.X)), sz.Actual.Content.X)
pos := stPos
idx := 0
line := 0
fr.forFlowChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
cidx := cwb.Geom.Cell
if cidx.Y == 0 && idx > 0 {
pos.Y = stPos.Y
pos.X += lastSz.X + gap.X
line++
}
if spaces != nil && line < len(spaces) {
if cidx.Y == 0 {
pos.Y += spaces[line].X
} else {
pos.Y += spaces[line].Y
}
}
cwb.positionWithinAllocMainY(pos, fr.Styles.Justify.Items, fr.Styles.Align.Items, crosses[min(line, len(crosses)-1)])
alloc := cwb.Geom.Size.Alloc.Total
pos.Y += alloc.Y + gap.Y
lastSz = alloc
idx++
return tree.Continue
})
}
func (fr *Frame) positionStacked() {
avail := fr.Geom.Size.Alloc.Content.Sub(fr.Geom.Size.InnerSpace)
fr.ForWidgetChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
cwb.Geom.RelPos.SetZero()
// a child that is smaller than the stack is aligned in it by its
// Justify.Self and Align.Self, if they are set (as the logo of
// Google, in a grid cell that it is centered in)
for d, al := range []styles.Aligns{cwb.Styles.Justify.Self, cwb.Styles.Align.Self} {
dim := math32.Dims(d)
extra := avail.Dim(dim) - cwb.Geom.Size.Actual.Total.Dim(dim)
if extra <= 0 {
continue
}
switch al {
case styles.Center:
cwb.Geom.RelPos.SetDim(dim, math32.Floor(extra/2))
case styles.End:
cwb.Geom.RelPos.SetDim(dim, extra)
}
}
if !fr.LayoutStackTopOnly || i == fr.StackTop {
cw.Position()
}
return tree.Continue
})
}
// ApplyScenePos computes scene-based absolute positions and final BBox
// bounding boxes for rendering, based on relative positions from
// Position step and parents accumulated position and scroll offset.
// This is the only step needed when scrolling (very fast).
func (wb *WidgetBase) ApplyScenePos() {
wb.setPosFromParent()
wb.setBBoxes()
}
// setContentPosFromPos sets the Pos.Content position based on current Pos
// plus the BoxSpace position offset.
func (wb *WidgetBase) setContentPosFromPos() {
wb.Geom.Pos.Content = wb.Geom.Pos.Total.Add(wb.Geom.contentOffset)
}
func (wb *WidgetBase) setPosFromParent() {
pwb := wb.parentWidget()
var parPos math32.Vector2
if pwb != nil {
// critical that parent adds here but not to self; the scroll
// offset is in whole dots, so that the content is always at the
// same position relative to the pixels (otherwise lines thinner
// than a pixel come and go while scrolling)
parPos = pwb.Geom.Pos.Content.Add(pwb.Geom.Scroll.Round())
}
switch {
case pwb != nil && wb.outOfFlow():
wb.setPosOutOfFlow(parPos)
case wb.Styles.Position == styles.PositionRelative:
wb.Geom.Pos.Total = wb.Geom.RelPos.Add(parPos).Add(wb.relativeOffset())
case pwb != nil && wb.Styles.Position == styles.PositionSticky:
wb.Geom.Pos.Total = wb.Geom.RelPos.Add(parPos).Add(wb.stickyOffset(pwb, wb.Geom.RelPos.Add(parPos)))
default:
wb.Geom.Pos.Total = wb.Geom.RelPos.Add(parPos)
}
wb.Geom.Pos.Total.SetAdd(wb.translateOffset())
wb.setContentPosFromPos()
if DebugSettings.LayoutTrace {
fmt.Println(wb, "pos:", wb.Geom.Pos.Total, "parPos:", parPos)
}
}
// setBBoxesFromAllocs sets BBox and ContentBBox from Geom.Pos and .Size
// This does NOT intersect with parent content BBox, which is done in SetBBoxes.
// Use this for elements that are dynamically positioned outside of parent BBox.
func (wb *WidgetBase) setBBoxesFromAllocs() {
wb.Geom.TotalBBox = wb.Geom.totalRect()
wb.Geom.ContentBBox = wb.Geom.contentRect()
}
// childClipBBox returns the bounding box that the children of the widget
// are clipped to: its content box, or, if it does not clip its children
// ([styles.Style.NoClip]), that of the nearest widget that it is in that does.
func (wb *WidgetBase) childClipBBox() image.Rectangle {
clip := wb
for clip.noClip() {
p := clip.parentWidget()
if p == nil {
break
}
clip = p
}
return clip.Geom.ContentBBox
}
// noClip returns whether the widget does not clip its children
// ([styles.Style.NoClip], with overflow that does not scroll).
func (wb *WidgetBase) noClip() bool {
s := &wb.Styles
return s.NoClip && s.Overflow.X < styles.OverflowAuto && s.Overflow.Y < styles.OverflowAuto
}
func (wb *WidgetBase) setBBoxes() {
pwb := wb.parentWidget()
var parBB image.Rectangle
if pwb == nil { // scene
sz := &wb.Geom.Size
wb.Geom.TotalBBox = math32.RectFromPosSizeMax(math32.Vector2{}, sz.Alloc.Total)
wb.Geom.ContentBBox = math32.RectFromPosSizeMax(wb.Geom.contentOffset, sz.Alloc.Content)
if DebugSettings.LayoutTrace {
fmt.Println(wb, "Total BBox:", wb.Geom.TotalBBox)
fmt.Println(wb, "Content BBox:", wb.Geom.ContentBBox)
}
} else {
clip := pwb
if wb.outOfFlow() { // not clipped by its parent (see [WidgetBase.RenderWidget])
if gp := pwb.parentWidget(); gp != nil {
clip = gp
}
}
parBB = clip.childClipBBox()
bb := wb.Geom.totalRect()
if m := wb.Styles.Margin.Dots(); m.Left < 0 || m.Right < 0 || m.Top < 0 || m.Bottom < 0 {
// The box inside negative margins (as for a CSS float pulled
// beside another with a negative margin) is larger than the
// total box: it is visible where it is, not only in that.
pos := wb.Geom.Pos.Total.Add(math32.Vec2(m.Left, m.Top))
sz := wb.Geom.Size.Actual.Total.Sub(math32.Vec2(m.Left+m.Right, m.Top+m.Bottom))
bb = bb.Union(math32.RectFromPosSizeMax(pos, sz))
}
wb.Geom.TotalBBox = parBB.Intersect(bb)
if DebugSettings.LayoutTrace {
fmt.Println(wb, "Total BBox:", bb, "parBB:", parBB, "BBox:", wb.Geom.TotalBBox)
}
cbb := wb.Geom.contentRect()
wb.Geom.ContentBBox = parBB.Intersect(cbb)
if DebugSettings.LayoutTrace {
fmt.Println(wb, "Content BBox:", cbb, "parBB:", parBB, "BBox:", wb.Geom.ContentBBox)
}
}
wb.applyScenePosParts()
}
func (wb *WidgetBase) applyScenePosParts() {
if wb.Parts == nil {
return
}
wb.Parts.ApplyScenePos()
}
// applyScenePosChildren runs ApplyScenePos on the children
func (wb *WidgetBase) applyScenePosChildren() {
wb.forVisibleChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
cw.ApplyScenePos()
return tree.Continue
})
}
// applyScenePosChildren runs ScenePos on the children
func (fr *Frame) applyScenePosChildren() {
if fr.Styles.Display == styles.Stacked && !fr.LayoutStackTopOnly {
fr.ForWidgetChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
cw.ApplyScenePos()
return tree.Continue
})
return
}
fr.WidgetBase.applyScenePosChildren()
}
// ApplyScenePos computes the scene-based position and final BBox based on
// parents accumulated position and scrollbar position.
// This step can be performed when scrolling after updating Scroll.
func (fr *Frame) ApplyScenePos() {
fr.scrollResetIfNone()
if fr.Styles.Display == styles.Custom {
fr.WidgetBase.ApplyScenePos()
fr.applyScenePosChildren()
fr.PositionScrolls()
fr.applyScenePosParts() // in case they fit inside parent
return
}
// note: ly.Geom.Scroll has the X, Y scrolling offsets, set by Layouter.ScrollChanged function
if !fr.HasChildren() || !fr.layout.shapeCheck(fr, "ScenePos") {
fr.WidgetBase.ApplyScenePos() // behave like a widget
return
}
fr.WidgetBase.ApplyScenePos()
fr.applyScenePosChildren()
fr.PositionScrolls()
fr.applyScenePosParts() // in case they fit inside parent
// otherwise handle separately like scrolls on layout
}
// scrollResetIfNone resets the scroll offsets if there are no scrollbars
func (fr *Frame) scrollResetIfNone() {
for d := math32.X; d <= math32.Y; d++ {
if !fr.HasScroll[d] {
fr.Geom.Scroll.SetDim(d, 0)
}
}
}
// positionFromPos does Custom positioning from style positions.
func (fr *Frame) positionFromPos() {
fr.forVisibleChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
cwb.Geom.RelPos.X = cwb.Styles.Pos.X.Dots
cwb.Geom.RelPos.Y = cwb.Styles.Pos.Y.Dots
return tree.Continue
})
}
// DirectRenderDrawBBoxes returns the destination and source bounding boxes
// for RenderDraw call for widgets that do direct rendering.
// The destBBox.Min point can be passed as the dp destination point for Draw
// function, and srcBBox is the source region. Empty flag indicates if either
// of the srcBBox dimensions are <= 0.
func (wb *WidgetBase) DirectRenderDrawBBoxes(srcFullBBox image.Rectangle) (destBBox, srcBBox image.Rectangle, empty bool) {
tbb := wb.Geom.TotalBBox
destBBox = tbb.Add(wb.Scene.SceneGeom.Pos)
srcBBox = srcFullBBox
pos := wb.Geom.Pos.Total.ToPoint()
if pos.X < tbb.Min.X { // scrolled off left
srcBBox.Min.X = tbb.Min.X - pos.X
}
if pos.Y < tbb.Min.Y { // scrolled off top
srcBBox.Min.Y = tbb.Min.Y - pos.Y
}
sz := srcBBox.Size()
if sz.X <= 0 || sz.Y <= 0 {
empty = true
}
return
}
// relativeMax returns whether the Max size of the given style is relative
// to the size of the parent (a percentage of it, or a calc of one).
func relativeMax(s *styles.Style) bool {
for d := math32.X; d <= math32.Y; d++ {
mx := s.Max.Dim(d)
if mx.Custom != nil || mx.Unit == units.UnitPw || mx.Unit == units.UnitPh {
return true
}
}
return false
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"slices"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/tree"
)
// This file has the intrinsic widths of the layout, as in CSS: the
// min-content width ([GeomSize.minWidth]) and the max-content (preferred)
// width ([GeomSize.prefWidth]) of each widget, computed in SizeUp. Widths
// are intrinsic and heights follow: a widget starts at its preferred width,
// within the width allocated to it, is narrowed toward its minimum only
// when there is too little width, and its height is that of its content
// at the width that it is finally given.
// sizeUpIntrinsicFrame sets the intrinsic widths of the frame from those
// of its children, as they combine for its layout: a row sums them, a
// column takes the largest, a wrapped row takes the largest minimum and
// the sum of the preferred widths, and a grid does each per column.
func (fr *Frame) sizeUpIntrinsicFrame() {
minw, prefw := fr.childrenIntrinsicWidths()
fr.layout.minContent = minw
sz := &fr.Geom.Size
if fr.Styles.Overflow.X >= styles.OverflowAuto {
minw = 0 // its content scrolls
}
if fr.contained(math32.X) { // as if it had no content
minw, prefw = 0, 0
}
if fr.Styles.MaxContentWidth {
// as wide as its content on one line, which it is not narrowed from
minw = prefw
sz.Actual.Content.X = max(sz.Actual.Content.X, math32.Ceil(prefw))
sz.SetTotalFromContent(&sz.Actual)
}
if fr.onlyFloats() && !fr.contained(math32.X) {
// the floats are its content, of which its width is (as the buttons
// of the bar of google.com, floats in boxes in a row, which were
// as wide as nothing)
w := math32.Ceil(prefw)
if sz.Max.X > 0 {
w = min(w, sz.Max.X)
}
if w > sz.Actual.Content.X {
sz.Actual.Content.X = w
sz.SetTotalFromContent(&sz.Actual)
}
}
if fr.Styles.ContentMinWidth && sz.Max.X > 0 && minw > sz.Max.X {
// as wide as its content needs to be (as a table in CSS)
sz.Max.X = math32.Ceil(minw)
sz.Actual.Content.X = max(sz.Actual.Content.X, sz.Max.X)
sz.SetTotalFromContent(&sz.Actual)
}
sz.setIntrinsicWidths(minw, prefw)
}
// childrenIntrinsicWidths returns the min-content and max-content widths
// of the content of the frame, from its children in the flow of its layout.
func (fr *Frame) childrenIntrinsicWidths() (minw, prefw float32) {
s := &fr.Styles
gap := fr.layout.Gap.X
switch {
case s.Display == styles.Stacked:
if kwb := fr.StackTopWidget(); kwb != nil {
return kwb.Geom.Size.minWidth, kwb.Geom.Size.prefWidth
}
return 0, 0
case s.Display == styles.Grid:
return fr.gridIntrinsicWidths()
case s.Display != styles.Flex:
w := fr.Geom.Size.Actual.Content.X
return w, w
}
row := s.Direction == styles.Row
n := 0
fr.forFlowChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
ksz := &cwb.Geom.Size
switch {
case row && !s.Wrap:
minw += ksz.minWidth
prefw += ksz.prefWidth
case row: // wrapped: one item per line at its narrowest
minw = max(minw, ksz.minWidth)
prefw += ksz.prefWidth
default:
minw = max(minw, ksz.minWidth)
prefw = max(prefw, ksz.prefWidth)
}
n++
return tree.Continue
})
if row && n > 1 {
prefw += float32(n-1) * gap
if !s.Wrap {
minw += float32(n-1) * gap
}
}
if fl := fr.layout.floats; fl != nil {
minw = max(minw, fl.size.X)
prefw = max(prefw, fl.size.X)
}
if fr.onlyFloats() {
// A column that only has floats is as wide as the widest one at
// least, and has them side by side when there is room for all of
// them (as in CSS, in which the max-content width of a block has
// its floats on one line), as for a float of floats.
var fmin, fpref float32
fr.forVisibleChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
if cwb.isFloat() {
fmin = max(fmin, cwb.Geom.Size.minWidth)
fpref += cwb.Geom.Size.prefWidth
}
return tree.Continue
})
minw = max(minw, fmin)
prefw = max(prefw, fpref)
}
return minw, prefw
}
// gridIntrinsicWidths returns the intrinsic widths of the content of a grid
// frame, as the sums of those of its columns: the largest of the cells in
// each, with the cells that span columns widening them evenly as needed.
func (fr *Frame) gridIntrinsicWidths() (minw, prefw float32) {
li := &fr.layout
n := li.Shape.X
if n <= 0 {
return 0, 0
}
mins := make([]float32, n)
prefs := make([]float32, n)
type spanning struct {
col, span int
minw float32
prefw float32
}
var spans []spanning
fr.forFlowChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
c := cwb.Geom.Cell.X
if c >= n {
return tree.Continue
}
ksz := &cwb.Geom.Size
if span := fr.colSpan(cwb); span > 1 {
spans = append(spans, spanning{c, span, ksz.minWidth, ksz.prefWidth})
return tree.Continue
}
mins[c] = max(mins[c], ksz.minWidth)
prefs[c] = max(prefs[c], ksz.prefWidth)
return tree.Continue
})
widen := func(ws []float32, col, span int, w float32) {
sum := li.Gap.X * float32(span-1)
for c := col; c < col+span; c++ {
sum += ws[c]
}
if extra := w - sum; extra > 0 {
for c := col; c < col+span; c++ {
ws[c] += extra / float32(span)
}
}
}
for _, sp := range spans {
widen(mins, sp.col, sp.span, sp.minw)
widen(prefs, sp.col, sp.span, sp.prefw)
}
gaps := float32(n-1) * li.Gap.X
minw, prefw = gaps, gaps
for c := range n {
minw += mins[c]
prefw += max(prefs[c], mins[c])
}
return minw, prefw
}
// narrowTo returns the given allocated width of the given child, narrowed
// to the given width if that is less. In a column (block is true), a frame
// with children is narrowed to the width, as a block is in CSS, so that its
// content then overflows it, while other widgets are not narrowed below
// their min-content width, which keeps the words of text whole (the shaper
// would otherwise break them). The items of a wrapped row (block is false)
// are not narrowed below their min-content width, as flex items in CSS.
func narrowTo(cwb *WidgetBase, alloc, width float32, block bool) float32 {
if alloc <= width {
return alloc
}
if cwb.Styles.MaxContentWidth { // not narrowed: it overflows
return max(alloc, cwb.Geom.Size.minWidth)
}
if block && cwb.HasChildren() {
if _, ok := cwb.This.(Layouter); ok {
return width
}
}
return max(width, min(alloc, cwb.Geom.Size.minWidth))
}
// overflowWidth returns the width of the content of the frame that it
// would overflow in, for deciding whether it needs to scroll in width:
// in the first SizeDown iteration, the children still have their
// preferred widths from SizeUp, which they are narrowed from to fit, so
// the frame only overflows its min-content width, plus any content that
// overflows its children visibly beyond their Max (see [Frame.sizeOverflow]);
// afterward, it is the actual width of its content, as given.
func (fr *Frame) overflowWidth(iter int, maxSize float32) float32 {
if iter > 0 || !fr.HasChildren() || fr.Styles.Display == styles.Custom {
return maxSize
}
excess := max(fr.layout.overflow.X-fr.Geom.Size.Internal.X, 0)
return min(maxSize, fr.layout.minContent+excess)
}
// contentGrower is a widget whose Max width is only the most that it grows
// to, not a width that it starts from when it shrinks (see
// [Frame.shrinkWidths]): it starts from its preferred width, as wide as its
// content, as a text field does, so that the one with the longer text is
// the wider one in a row of them.
type contentGrower interface {
growsFromContent() bool
}
// growMaxWidth returns the total width of the Max of the given child
// (with its Space), as it is (or will be) for the content width of the
// frame, which a parent-relative Max is relative to, or 0 if it has none.
func (fr *Frame) growMaxWidth(cwb *WidgetBase) float32 {
ksz := &cwb.Geom.Size
mx := cwb.Styles.Max.X
w := ksz.Max.X
switch mx.Unit {
case units.UnitPw:
w = (fr.Geom.Size.Alloc.Content.X - fr.Geom.Size.InnerSpace.X) * 0.01 * mx.Value
w = max(w-cwb.boxSizingSpace().X, 1)
case units.UnitPh:
w = (fr.Geom.Size.Alloc.Content.Y - fr.Geom.Size.InnerSpace.Y) * 0.01 * mx.Value
w = max(w-cwb.boxSizingSpace().X, 1)
}
if w <= 0 {
return 0
}
return w + ksz.Space.X
}
// sizeOverflow sets the overflow size of the content of the frame
// (layoutState.overflow), and its own extent ([GeomSize.extent]), from the
// visible overflow of its children: the content that overflows a child
// (which is beyond its Actual size, as for a frame with a Max narrower
// than its content) is still shown, and the frame that scrolls around it
// scrolls over it, as for the scrollable overflow of CSS. The overflow is
// the content size plus the largest overflow of a child, in each
// dimension. A frame that clips its content (not visible overflow) has no
// overflow of its own beyond its size, and the content of a frame only
// overflows it beyond a Max, as its actual size otherwise fits it (the
// content size of wrapped layouts can be ahead of their actual size).
// The overflow of a child only counts beyond the room that it has in the
// content of the frame (see [Frame.overflowRoom]).
func (fr *Frame) sizeOverflow() {
sz := &fr.Geom.Size
var excess math32.Vector2
room := fr.overflowRoom()
fr.forFlowChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
ksz := &cwb.Geom.Size
over := ksz.extent.Sub(ksz.Actual.Total)
if r := room(cwb); over.X > 0 || over.Y > 0 {
over = over.Sub(r)
}
excess.SetMax(over)
return tree.Continue
})
fr.layout.overflow = sz.Internal.Add(excess)
sz.extent = sz.Actual.Total
for d := math32.X; d <= math32.Y; d++ {
// Its own content only overflows it beyond a Max (otherwise its
// actual size fits its content), while that of its children
// overflows it in any case.
ov := sz.Actual.Content.Dim(d) + excess.Dim(d)
if sz.Max.Dim(d) > 0 {
ov = max(ov, fr.layout.overflow.Dim(d))
}
if fr.Styles.Overflow.Dim(d) != styles.OverflowVisible {
continue
}
sz.extent.SetDim(d, max(sz.extent.Dim(d), ov+sz.Space.Dim(d)))
}
}
// overflowRoom returns a function that returns the room that each child
// of the frame, called in order, has after it in the content of the frame,
// in each dimension, which content that overflows the child visibly can
// take without overflowing the frame. In a flex layout on one line, the
// position of a child along its axis follows from the sizes of the
// children before it, and that across it from its alignment. For a grid,
// wrapped lines, and distributed justification, the positions are not known
// when it is sized, so there is no room.
func (fr *Frame) overflowRoom() func(cwb *WidgetBase) math32.Vector2 {
sz := &fr.Geom.Size
jc := fr.Styles.Justify.Content
if fr.Styles.Display != styles.Flex || fr.Styles.Wrap ||
jc == styles.SpaceBetween || jc == styles.SpaceAround || jc == styles.SpaceEvenly {
return func(cwb *WidgetBase) math32.Vector2 { return math32.Vector2{} }
}
content := sz.Actual.Content
ma := fr.Styles.Direction.Dim()
ca := ma.Other()
gap := fr.layout.Gap.Dim(ma)
pos := styles.AlignPos(jc, sz.Internal.Dim(ma), content.Dim(ma))
return func(cwb *WidgetBase) math32.Vector2 {
size := cwb.Geom.Size.Actual.Total
var room math32.Vector2
room.SetDim(ma, max(content.Dim(ma)-pos-size.Dim(ma), 0))
align := styles.ItemAlign(fr.Styles.Align.Items, cwb.Styles.Align.Self)
cpos := styles.AlignPos(align, size.Dim(ca), content.Dim(ca))
room.SetDim(ca, max(content.Dim(ca)-cpos-size.Dim(ca), 0))
pos += size.Dim(ma) + gap
return room
}
}
// growWidths returns the given widths of the columns of the frame (from
// [Frame.shrinkWidths], when they fit), grown into the rest of the given
// width by the columns that grow, in proportion to their Grow, up to their
// Max: the width that a column cannot take beyond its Max goes to the others.
func (fr *Frame) growWidths(widths []float32, width float32) []float32 {
li := &fr.layout
n := len(widths)
grow := make([]float32, n)
maxw := make([]float32, n) // 0 for none
hasMax := make([]bool, n)
for c := range n {
grow[c] = li.cell(math32.X, c, 0).Grow.X
hasMax[c] = true
}
fr.forFlowChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
c := cwb.Geom.Cell.X
if c >= n || fr.colSpan(cwb) > 1 {
return tree.Continue
}
if mx := cwb.Geom.Size.maxTotal().X; mx > 0 && cwb.Geom.Size.Max.X > 0 {
maxw[c] = max(maxw[c], mx)
} else {
hasMax[c] = false
}
return tree.Continue
})
left := width
for _, w := range widths {
left -= w
}
grown := slices.Clone(widths)
for range n { // again when some reach their Max
if left < 0.5 {
break
}
gsum := float32(0)
for c := range n {
gsum += grow[c]
}
if gsum <= 0 {
break
}
used := float32(0)
for c := range n {
if grow[c] == 0 {
continue
}
nw := grown[c] + left*grow[c]/gsum
if hasMax[c] && maxw[c] > 0 && nw >= maxw[c] {
nw = max(grown[c], maxw[c])
grow[c] = 0 // at its Max
}
used += nw - grown[c]
grown[c] = nw
}
left -= used
}
for c := range n {
grown[c] = math32.Floor(grown[c])
}
return grown
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"encoding/json"
"fmt"
"image"
"image/color"
"log"
"log/slog"
"reflect"
"slices"
"sort"
"strconv"
"cogentcore.org/core/base/fileinfo"
"cogentcore.org/core/base/fileinfo/mimedata"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/colors"
"cogentcore.org/core/colors/gradient"
"cogentcore.org/core/cursors"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/keymap"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/text"
"cogentcore.org/core/text/textpos"
"cogentcore.org/core/tree"
)
// List represents a slice value with a list of value widgets and optional index widgets.
// Use [ListBase.BindSelect] to make the list designed for item selection.
type List struct {
ListBase
// ListStyler is an optional styler for list items.
ListStyler ListStyler `copier:"-" json:"-" xml:"-"`
}
// ListStyler is a styling function for custom styling and
// configuration of elements in the list.
type ListStyler func(w Widget, s *styles.Style, row int)
func (ls *List) HasStyler() bool {
return ls.ListStyler != nil
}
func (ls *List) StyleRow(w Widget, idx, fidx int) {
if ls.ListStyler != nil {
ls.ListStyler(w, &w.AsWidget().Styles, idx)
}
}
// note on implementation:
// * ListGrid handles all the layout logic to start with a minimum number of
// rows and then computes the total number visible based on allocated size.
const (
// ListRowProperty is the tree property name for the row of a list element.
ListRowProperty = "ls-row"
// ListColProperty is the tree property name for the column of a list element.
ListColProperty = "ls-col"
)
// Lister is the interface used by [ListBase] to
// support any abstractions needed for different types of lists.
type Lister interface {
tree.Node
// AsListBase returns the base for direct access to relevant fields etc
AsListBase() *ListBase
// RowWidgetNs returns number of widgets per row and
// offset for index label
RowWidgetNs() (nWidgPerRow, idxOff int)
// UpdateSliceSize updates the current size of the slice
// and sets SliceSize if changed.
UpdateSliceSize() int
// UpdateMaxWidths updates the maximum widths per column based
// on estimates from length of strings (for string values)
UpdateMaxWidths()
// SliceIndex returns the logical slice index: si = i + StartIndex,
// the actual value index vi into the slice value (typically = si),
// which can be different if there is an index indirection as in
// tensorcore.Table), and a bool that is true if the
// index is beyond the available data and is thus invisible,
// given the row index provided.
SliceIndex(i int) (si, vi int, invis bool)
// MakeRow adds config for one row at given widget row index.
// Plan must be the StructGrid Plan.
MakeRow(p *tree.Plan, i int)
// StyleValue performs additional value widget styling
StyleValue(w Widget, s *styles.Style, row, col int)
// HasStyler returns whether there is a custom style function.
HasStyler() bool
// StyleRow calls a custom style function on given row (and field)
StyleRow(w Widget, idx, fidx int)
// RowGrabFocus grabs the focus for the first focusable
// widget in given row.
// returns that element or nil if not successful
// note: grid must have already rendered for focus to be grabbed!
RowGrabFocus(row int) *WidgetBase
// NewAt inserts a new blank element at the given index in the slice.
// -1 indicates to insert the element at the end.
NewAt(idx int)
// DeleteAt deletes the element at the given index from the slice.
DeleteAt(idx int)
// MimeDataType returns the data type for mime clipboard
// (copy / paste) data e.g., fileinfo.DataJson
MimeDataType() string
// CopySelectToMime copies selected rows to mime data
CopySelectToMime() mimedata.Mimes
// PasteAssign assigns mime data (only the first one!) to this idx
PasteAssign(md mimedata.Mimes, idx int)
// PasteAtIndex inserts object(s) from mime data at
// (before) given slice index
PasteAtIndex(md mimedata.Mimes, idx int)
}
var _ Lister = &List{}
// ListBase is the base for [List] and [Table] and any other displays
// of array-like data. It automatically computes the number of rows that fit
// within its allocated space, and manages the offset view window into the full
// list of items, and supports row selection, copy / paste, Drag-n-Drop, etc.
// Use [ListBase.BindSelect] to make the list designed for item selection.
type ListBase struct { //core:no-new
Frame
// Slice is the pointer to the slice that we are viewing.
Slice any `set:"-"`
// ShowIndexes is whether to show the indexes of rows or not (default false).
ShowIndexes bool
// MinRows specifies the minimum number of rows to display, to ensure
// at least this amount is displayed.
MinRows int `default:"4"`
// SelectedValue is the current selection value.
// If it is set, it is used as the initially selected value.
SelectedValue any `copier:"-" display:"-" json:"-" xml:"-"`
// SelectedIndex is the index of the currently selected item.
SelectedIndex int `copier:"-" json:"-" xml:"-"`
// InitSelectedIndex is the index of the row to select at the start.
InitSelectedIndex int `copier:"-" json:"-" xml:"-"`
// SelectedIndexes is a list of currently selected slice indexes.
SelectedIndexes map[int]struct{} `set:"-" copier:"-"`
// lastClick is the last row that has been clicked on.
// This is used to prevent erroneous double click events
// from being sent when the user clicks on multiple different
// rows in quick succession.
lastClick int
// normalCursor is the cached cursor to display when there
// is no row being hovered.
normalCursor cursors.Cursor
// currentCursor is the cached cursor that should currently be
// displayed.
currentCursor cursors.Cursor
// sliceUnderlying is the underlying slice value.
sliceUnderlying reflect.Value
// currently hovered row
hoverRow int
// dropIndex is the index of the item highlighted as the target of a
// drop in progress, or -1 (see [ListBase.SetDropIndex]).
dropIndex int
// draggedIndexes are the indexes of the items being dragged from
// the list, which are deleted after a move (see [ListBase.dragStart]).
draggedIndexes []int
// VisibleRows is the total number of rows visible in allocated display size.
VisibleRows int `set:"-" edit:"-" copier:"-" json:"-" xml:"-"`
// StartIndex is the starting slice index of visible rows.
StartIndex int `set:"-" edit:"-" copier:"-" json:"-" xml:"-"`
// SliceSize is the size of the slice.
SliceSize int `set:"-" edit:"-" copier:"-" json:"-" xml:"-"`
// MakeIter is the iteration through the configuration process,
// which is reset when a new slice type is set.
MakeIter int `set:"-" edit:"-" copier:"-" json:"-" xml:"-"`
// temp idx state for e.g., dnd
tmpIndex int
// elementValue is a [reflect.Value] representation of the underlying element type
// which is used whenever there are no slice elements available
elementValue reflect.Value
// maximum width of value column in chars, if string
maxWidth int
// ReadOnlyKeyNav is whether support key navigation when ReadOnly (default true).
// It uses a capture of up / down events to manipulate selection, not focus.
ReadOnlyKeyNav bool `default:"true"`
// SelectMode is whether to be in select rows mode or editing mode:
// clicks (taps) on the rows toggle their selection, instead of editing
// their cells, and the keys that move the selection extend it, as for
// selecting several rows on mobile. [keymap.CancelSelect] ends it.
SelectMode bool `set:"-" copier:"-" json:"-" xml:"-"`
// DragMoves is whether dragging rows moves them by default, instead of
// copying them, in which case the modifier keys that otherwise move
// them (Shift) copy them.
DragMoves bool
// ReadOnlyMultiSelect: if list is ReadOnly, default selection mode is to
// choose one row only. If this is true, standard multiple selection logic
// with modifier keys is instead supported.
ReadOnlyMultiSelect bool
// InFocusGrab is a guard for recursive focus grabbing.
InFocusGrab bool `set:"-" edit:"-" copier:"-" json:"-" xml:"-"`
// isArray is whether the slice is actually an array.
isArray bool
// ListGrid is the [ListGrid] widget.
ListGrid *ListGrid `set:"-" edit:"-" copier:"-" json:"-" xml:"-"`
}
func (lb *ListBase) WidgetValue() any { return &lb.Slice }
func (lb *ListBase) Init() {
lb.Frame.Init()
lb.AddContextMenu(lb.contextMenu)
lb.InitSelectedIndex = -1
lb.hoverRow = -1
lb.dropIndex = -1
lb.MinRows = 4
lb.ReadOnlyKeyNav = true
lb.Styler(func(s *styles.Style) {
s.SetAbilities(true, abilities.Clickable, abilities.DoubleClickable, abilities.TripleClickable)
s.SetAbilities(!lb.IsReadOnly(), abilities.Draggable, abilities.Droppable)
// read-only rows are not focusable, so the list takes the focus for
// moving among them with the keys, as it does when it has no rows,
// for the keys that insert them
s.SetAbilities((lb.IsReadOnly() && lb.ReadOnlyKeyNav) || (!lb.IsReadOnly() && lb.SliceSize == 0), abilities.Focusable)
s.Cursor = lb.currentCursor
s.Direction = styles.Column
// absorb horizontal here, vertical in view
s.Overflow.X = styles.OverflowAuto
s.Grow.Set(1, 1)
})
if !lb.IsReadOnly() {
lb.On(events.DragStart, func(e events.Event) {
lb.dragStart(e)
})
lb.On(events.DragEnter, func(e events.Event) {
e.SetHandled()
})
lb.On(events.DragLeave, func(e events.Event) {
e.SetHandled()
})
lb.On(events.Drop, func(e events.Event) {
lb.dragDrop(e)
})
lb.On(events.DropDeleteSource, func(e events.Event) {
lb.dropDeleteSource(e)
})
}
lb.FinalStyler(func(s *styles.Style) {
lb.normalCursor = s.Cursor
})
lb.OnFinal(events.KeyChord, func(e events.Event) {
if lb.IsReadOnly() {
if lb.ReadOnlyKeyNav {
lb.keyInputReadOnly(e)
}
} else {
lb.keyInputEditable(e)
}
})
lb.On(events.MouseMove, func(e events.Event) {
row, _, isValid := lb.rowFromEventPos(e)
prevHoverRow := lb.hoverRow
if !isValid || TheApp.SystemPlatform().IsMobile() { // (no hover for touch)
lb.hoverRow = -1
lb.Styles.Cursor = lb.normalCursor
} else {
lb.hoverRow = row
lb.Styles.Cursor = cursors.Pointer
}
lb.currentCursor = lb.Styles.Cursor
if lb.hoverRow != prevHoverRow {
lb.NeedsRender()
}
})
lb.On(events.MouseDrag, func(e events.Event) {
row, _, isValid := lb.rowFromEventPos(e)
if !isValid {
return
}
pt := lb.PointToRelPos(e.Pos())
lb.ListGrid.AutoScroll(math32.FromPoint(pt))
prevHoverRow := lb.hoverRow
if !isValid || TheApp.SystemPlatform().IsMobile() { // (no hover for touch)
lb.hoverRow = -1
lb.Styles.Cursor = lb.normalCursor
} else {
lb.hoverRow = row
lb.Styles.Cursor = cursors.Pointer
}
lb.currentCursor = lb.Styles.Cursor
if lb.hoverRow != prevHoverRow {
lb.NeedsRender()
}
})
lb.OnFirst(events.DoubleClick, func(e events.Event) {
row, _, isValid := lb.rowFromEventPos(e)
if !isValid {
return
}
if lb.lastClick != row+lb.StartIndex {
lb.ListGrid.Send(events.Click, e)
e.SetHandled()
}
})
// we must interpret triple click events as double click
// events for rapid cross-row double clicking to work correctly
lb.OnFirst(events.TripleClick, func(e events.Event) {
lb.Send(events.DoubleClick, e)
})
lb.Maker(func(p *tree.Plan) {
ls := lb.This.(Lister)
ls.UpdateSliceSize()
scrollTo := -1
if lb.SelectedValue != nil {
idx, ok := sliceIndexByValue(lb.Slice, lb.SelectedValue)
if ok {
lb.SelectedIndex = idx
scrollTo = lb.SelectedIndex
}
lb.SelectedValue = nil
lb.InitSelectedIndex = -1
} else if lb.InitSelectedIndex >= 0 {
lb.SelectedIndex = lb.InitSelectedIndex
lb.InitSelectedIndex = -1
scrollTo = lb.SelectedIndex
}
if scrollTo >= 0 {
lb.ScrollToIndex(scrollTo)
}
lb.Updater(func() {
lb.UpdateStartIndex()
})
lb.MakeGrid(p, func(p *tree.Plan) {
for i := 0; i < lb.VisibleRows; i++ {
ls.MakeRow(p, i)
}
})
})
}
func (lb *ListBase) SliceIndex(i int) (si, vi int, invis bool) {
si = lb.StartIndex + i
vi = si
invis = si >= lb.SliceSize
return
}
// StyleValue performs additional value widget styling
func (lb *ListBase) StyleValue(w Widget, s *styles.Style, row, col int) {
if lb.maxWidth > 0 {
hv := units.Ch(float32(lb.maxWidth))
s.Min.X.Value = max(s.Min.X.Value, hv.Convert(s.Min.X.Unit, &s.UnitContext).Value)
}
s.Wrap = false // one line, as for the switches of bit flags
s.SetTextWrap(false)
}
// DragMovesDefault returns [ListBase.DragMoves] (see [DragMover]).
func (lb *ListBase) DragMovesDefault() bool { return lb.DragMoves }
func (lb *ListBase) AsListBase() *ListBase {
return lb
}
func (lb *ListBase) SetSliceBase() {
lb.SelectMode = false
lb.MakeIter = 0
lb.StartIndex = 0
lb.VisibleRows = lb.MinRows
if !lb.IsReadOnly() {
lb.SelectedIndex = -1
}
lb.ResetSelectedIndexes()
lb.This.(Lister).UpdateMaxWidths()
}
// SetSlice sets the source slice that we are viewing.
// This ReMakes the view for this slice if different.
// Note: it is important to at least set an empty slice of
// the desired type at the start to enable initial configuration.
func (lb *ListBase) SetSlice(sl any) *ListBase {
if reflectx.IsNil(reflect.ValueOf(sl)) {
lb.Slice = nil
return lb
}
// TODO: a lot of this garbage needs to be cleaned up.
// New is not working!
newslc := false
if reflect.TypeOf(sl).Kind() != reflect.Pointer { // prevent crash on non-comparable
newslc = true
} else {
newslc = lb.Slice != sl
}
if !newslc {
lb.MakeIter = 0
return lb
}
lb.Slice = sl
lb.sliceUnderlying = reflectx.Underlying(reflect.ValueOf(lb.Slice))
lb.isArray = reflectx.NonPointerType(reflect.TypeOf(sl)).Kind() == reflect.Array
lb.elementValue = reflectx.Underlying(reflectx.SliceElementValue(sl))
lb.SetSliceBase()
return lb
}
// rowFromEventPos returns the widget row, slice index, and
// whether the index is in slice range, for given event position.
func (lb *ListBase) rowFromEventPos(e events.Event) (row, idx int, isValid bool) {
lg := lb.ListGrid
row, _, isValid = lg.indexFromPixel(e.Pos())
if !isValid {
return
}
idx = row + lb.StartIndex
if row < 0 || idx >= lb.SliceSize {
isValid = false
}
return
}
// IndexFromEvent returns the index of the item under the position of the
// given event, as for a drop of something onto an item, and whether there
// is an item there.
func (lb *ListBase) IndexFromEvent(e events.Event) (int, bool) {
_, idx, ok := lb.rowFromEventPos(e)
return idx, ok
}
// clickSelectEvent is a helper for processing selection events
// based on a mouse click, which could be a double or triple
// in addition to a regular click.
// Returns false if no further processing should occur,
// because the user clicked outside the range of active rows.
func (lb *ListBase) clickSelectEvent(e events.Event) bool {
row, _, isValid := lb.rowFromEventPos(e)
if !isValid {
e.SetHandled()
} else {
lb.updateSelectRow(row, e.SelectMode())
}
return isValid
}
// BindSelect makes the list a read-only selection list and then
// binds its events to its scene and its current selection index to the given value.
// It will send an [events.Change] event when the user changes the selection row.
func (lb *ListBase) BindSelect(val *int) *ListBase {
lb.SetReadOnly(true)
lb.OnSelect(func(e events.Event) {
*val = lb.SelectedIndex
lb.SendChange(e)
})
lb.OnDoubleClick(func(e events.Event) {
if lb.clickSelectEvent(e) {
*val = lb.SelectedIndex
lb.Scene.sendKey(keymap.Accept, e) // activate OK button
if lb.Scene.Stage.Type == DialogStage {
lb.Scene.Close() // also directly close dialog for value dialogs without OK button
}
}
})
return lb
}
func (lb *ListBase) UpdateMaxWidths() {
lb.maxWidth = 0
ev := lb.elementValue
isString := ev.Type().Kind() == reflect.String && ev.Type() != reflect.TypeFor[icons.Icon]()
if !isString || lb.SliceSize == 0 {
return
}
mxw := 0
for rw := range lb.SliceSize {
str := reflectx.ToString(lb.sliceElementValue(rw).Interface())
mxw = max(mxw, len(str))
}
lb.maxWidth = mxw
}
// sliceElementValue returns an underlying non-pointer [reflect.Value]
// of slice element at given index or ElementValue if out of range.
func (lb *ListBase) sliceElementValue(si int) reflect.Value {
var val reflect.Value
if si < lb.SliceSize {
val = reflectx.Underlying(lb.sliceUnderlying.Index(si)) // deal with pointer lists
} else {
val = lb.elementValue
}
if !val.IsValid() {
val = lb.elementValue
}
return val
}
func (lb *ListBase) MakeGrid(p *tree.Plan, maker func(p *tree.Plan)) {
tree.AddAt(p, "grid", func(w *ListGrid) {
lb.ListGrid = w
w.Styler(func(s *styles.Style) {
nWidgPerRow, _ := lb.This.(Lister).RowWidgetNs()
w.minRows = lb.MinRows
s.Display = styles.Grid
s.Columns = nWidgPerRow
s.Grow.Set(1, 1)
s.Overflow.Y = styles.OverflowAuto
s.Gap.Set(units.Em(0.5)) // note: match header
s.Align.Items = styles.Center
// baseline mins:
s.Min.X.Ch(20)
s.Min.Y.Em(6)
})
oc := func(e events.Event) {
lb.focusReadOnly()
row, _, isValid := w.indexFromPixel(e.Pos())
if !isValid {
return
}
mode := e.SelectMode()
if lb.SelectMode && mode == events.SelectOne {
mode = events.ExtendOne
}
if !lb.IsReadOnly() && (mode == events.ExtendOne || mode == events.ExtendContinuous) {
lb.clickSelectRow(row, mode) // (see MakeValue)
return
}
lb.updateSelectRow(row, e.SelectMode())
lb.lastClick = row + lb.StartIndex
}
w.OnClick(oc)
w.On(events.MouseDown, func(e events.Event) {
// value widgets such as text fields handle the clicks into them
// (the context menu selects for a right click, see contextSelectRow);
// on mobile, a press can start a scroll, and a tap selects as a click
if lb.IsReadOnly() || lb.SelectMode || e.SelectMode() != events.SelectOne || e.MouseButton() != events.Left || TheApp.SystemPlatform().IsMobile() {
return
}
if row, _, isValid := w.indexFromPixel(e.Pos()); isValid {
lb.selectIndexQuiet(row + lb.StartIndex)
}
})
w.On(events.MouseUp, func(e events.Event) {
// on mobile, a tap selects its row when it is released, unless
// it was the slide of a scroll (see the MouseDown above)
if !TheApp.SystemPlatform().IsMobile() || lb.IsReadOnly() || lb.SelectMode || e.MouseButton() != events.Left {
return
}
if em := lb.Events(); em == nil || !tree.IsNil(em.slide) {
return
}
if row, _, isValid := w.indexFromPixel(e.Pos()); isValid {
lb.selectIndexQuiet(row + lb.StartIndex)
}
})
w.On(events.ContextMenu, func(e events.Event) {
// we must select the row on right click so that the context menu
// corresponds to the right row
lb.focusReadOnly()
if row, _, isValid := w.indexFromPixel(e.Pos()); isValid {
lb.contextSelectRow(row)
}
lb.HandleEvent(e)
})
w.Updater(func() {
nWidgPerRow, _ := lb.This.(Lister).RowWidgetNs()
w.Styles.Columns = nWidgPerRow
})
w.Maker(maker)
})
}
func (lb *ListBase) MakeValue(w Value, i int) {
ls := lb.This.(Lister)
wb := w.AsWidget()
wb.SetProperty(ListRowProperty, i)
wb.Styler(func(s *styles.Style) {
if lb.IsReadOnly() {
s.SetAbilities(true, abilities.DoubleClickable)
s.SetAbilities(false, abilities.Hoverable, abilities.Focusable, abilities.Activatable, abilities.TripleClickable)
s.SetReadOnly(true)
}
row, col := lb.widgetIndex(w)
row += lb.StartIndex
ls.StyleValue(w, s, row, col)
if row < lb.SliceSize {
ls.StyleRow(w, row, col)
}
})
wb.OnSelect(func(e events.Event) {
e.SetHandled()
lb.focusReadOnly()
row, _ := lb.widgetIndex(w)
lb.updateSelectRow(row, e.SelectMode())
lb.lastClick = row + lb.StartIndex
})
wb.OnClick(func(e events.Event) {
// a click with Shift or Command (Control), or any click in the
// select mode, as on mobile, selects rows, instead of editing a cell
mode := e.SelectMode()
if lb.SelectMode && mode == events.SelectOne {
mode = events.ExtendOne
}
if mode != events.ExtendOne && mode != events.ExtendContinuous {
return
}
e.SetHandled()
row, _ := lb.widgetIndex(w)
lb.clickSelectRow(row, mode)
})
wb.OnDoubleClick(lb.HandleEvent)
wb.On(events.ContextMenu, lb.HandleEvent)
wb.OnFirst(events.ContextMenu, func(e events.Event) {
// we must select the row for context menu actions
lb.focusReadOnly()
row, _ := lb.widgetIndex(w)
lb.contextSelectRow(row)
})
if !lb.IsReadOnly() {
wb.OnInput(lb.HandleEvent)
}
}
// focusReadOnly focuses a read-only list when its rows are clicked,
// which are not focusable, so that the keys move among them. As for
// other clicked widgets, the focus is set quietly, without the focus style.
func (lb *ListBase) focusReadOnly() {
if lb.CanFocus() && !lb.ContainsFocus() {
lb.SetFocusQuiet()
}
}
func (lb *ListBase) MakeRow(p *tree.Plan, i int) {
ls := lb.This.(Lister)
si, vi, invis := ls.SliceIndex(i)
itxt := strconv.Itoa(i)
val := lb.sliceElementValue(vi)
if lb.ShowIndexes {
lb.MakeGridIndex(p, i, si, itxt, invis)
}
valnm := fmt.Sprintf("value-%s-%s", itxt, reflectx.ShortTypeName(lb.elementValue.Type()))
tree.AddNew(p, valnm, func() Value {
return NewValue(val.Addr().Interface(), "")
}, func(w Value) {
wb := w.AsWidget()
lb.MakeValue(w, i)
if !lb.IsReadOnly() {
wb.OnChange(func(e events.Event) {
lb.This.(Lister).UpdateMaxWidths()
lb.SendChange(e)
})
}
wb.Updater(func() {
wb := w.AsWidget()
_, vi, invis := ls.SliceIndex(i)
val := lb.sliceElementValue(vi)
Bind(val.Addr().Interface(), w)
wb.SetReadOnly(lb.IsReadOnly())
wb.SetState(invis, states.Invisible)
if lb.This.(Lister).HasStyler() {
w.Style()
}
if invis {
wb.SetSelected(false)
}
})
})
}
func (lb *ListBase) MakeGridIndex(p *tree.Plan, i, si int, itxt string, invis bool) {
ls := lb.This.(Lister)
tree.AddAt(p, "index-"+itxt, func(w *Text) {
w.SetProperty(ListRowProperty, i)
w.Styler(func(s *styles.Style) {
s.SetAbilities(true, abilities.DoubleClickable)
s.SetAbilities(!lb.IsReadOnly(), abilities.Draggable, abilities.Droppable)
s.Cursor = cursors.None
nd := math32.Log10(float32(lb.SliceSize))
nd = max(nd, 3)
s.Min.X.Ch(nd + 2)
s.Padding.Right.Dp(4)
s.Text.Align = text.End
s.Min.Y.Em(1)
s.GrowWrap = false
})
w.OnSelect(func(e events.Event) {
e.SetHandled()
lb.updateSelectRow(i, e.SelectMode())
lb.lastClick = si
})
w.OnDoubleClick(lb.HandleEvent)
w.On(events.ContextMenu, lb.HandleEvent)
if !lb.IsReadOnly() {
w.On(events.DragStart, func(e events.Event) {
lb.dragStart(e)
})
w.On(events.DragEnter, func(e events.Event) {
e.SetHandled()
})
w.On(events.DragLeave, func(e events.Event) {
e.SetHandled()
})
w.On(events.Drop, func(e events.Event) {
lb.dragDrop(e)
})
}
w.Updater(func() {
si, _, invis := ls.SliceIndex(i)
sitxt := strconv.Itoa(si)
w.SetText(sitxt)
w.SetReadOnly(lb.IsReadOnly())
w.SetState(invis, states.Invisible)
if invis {
w.SetSelected(false)
}
})
})
}
// RowWidgetNs returns number of widgets per row and offset for index label
func (lb *ListBase) RowWidgetNs() (nWidgPerRow, idxOff int) {
nWidgPerRow = 2
idxOff = 1
if !lb.ShowIndexes {
nWidgPerRow -= 1
idxOff = 0
}
return
}
// UpdateSliceSize updates and returns the size of the slice
// and sets SliceSize
func (lb *ListBase) UpdateSliceSize() int {
sz := lb.sliceUnderlying.Len()
lb.SliceSize = sz
return sz
}
// widgetIndex returns the row and column indexes for given widget,
// from the properties set during construction.
func (lb *ListBase) widgetIndex(w Widget) (row, col int) {
if rwi := w.AsTree().Property(ListRowProperty); rwi != nil {
row = rwi.(int)
}
if cli := w.AsTree().Property(ListColProperty); cli != nil {
col = cli.(int)
}
return
}
// UpdateStartIndex updates StartIndex to fit current view
func (lb *ListBase) UpdateStartIndex() {
sz := lb.This.(Lister).UpdateSliceSize()
if sz > lb.VisibleRows {
lastSt := sz - lb.VisibleRows
lb.StartIndex = min(lastSt, lb.StartIndex)
lb.StartIndex = max(0, lb.StartIndex)
} else {
lb.StartIndex = 0
}
}
// updateScroll updates the scroll value
func (lb *ListBase) updateScroll() {
lg := lb.ListGrid
if lg == nil {
return
}
lg.updateScroll(lb.StartIndex)
}
// newAtRow inserts a new blank element at the given display row.
func (lb *ListBase) newAtRow(row int) {
lb.This.(Lister).NewAt(lb.StartIndex + row)
}
// NewAt inserts a new blank element at the given index in the slice.
// -1 indicates to insert the element at the end.
func (lb *ListBase) NewAt(idx int) {
if lb.isArray {
return
}
lb.NewAtSelect(idx)
reflectx.SliceNewAt(lb.Slice, idx)
if idx < 0 {
idx = lb.SliceSize
}
lb.This.(Lister).UpdateSliceSize()
lb.SelectIndexEvent(idx, events.SelectOne)
lb.UpdateChange()
lb.IndexGrabFocus(idx)
}
// deleteAtRow deletes the element at the given display row.
func (lb *ListBase) deleteAtRow(row int) {
lb.This.(Lister).DeleteAt(lb.StartIndex + row)
}
// NewAtSelect updates the selected rows based on
// inserting a new element at the given index.
func (lb *ListBase) NewAtSelect(i int) {
sl := lb.SelectedIndexesList(reflectx.Ascending)
lb.ResetSelectedIndexes()
for _, ix := range sl {
if ix >= i {
ix++
}
lb.SelectedIndexes[ix] = struct{}{}
}
}
// DeleteAtSelect updates the selected rows based on
// deleting the element at the given index.
func (lb *ListBase) DeleteAtSelect(i int) {
sl := lb.SelectedIndexesList(reflectx.Descending)
lb.ResetSelectedIndexes()
for _, ix := range sl {
switch {
case ix == i:
continue
case ix > i:
ix--
}
lb.SelectedIndexes[ix] = struct{}{}
}
}
// DeleteAt deletes the element at the given index from the slice.
func (lb *ListBase) DeleteAt(i int) {
if lb.isArray {
return
}
if i < 0 || i >= lb.SliceSize {
return
}
lb.DeleteAtSelect(i)
reflectx.SliceDeleteAt(lb.Slice, i)
lb.This.(Lister).UpdateSliceSize()
lb.UpdateChange()
}
func (lb *ListBase) MakeToolbar(p *tree.Plan) {
if reflectx.IsNil(reflect.ValueOf(lb.Slice)) {
return
}
if lb.isArray || lb.IsReadOnly() {
return
}
tree.Add(p, func(w *Button) {
w.SetText("Add").SetIcon(icons.Add).SetTooltip("add a new element to the slice").
OnClick(func(e events.Event) {
lb.This.(Lister).NewAt(-1)
})
})
}
////////
// Row access methods
// NOTE: row = physical GUI display row, idx = slice index
// not the same!
// sliceValue returns value interface at given slice index.
func (lb *ListBase) sliceValue(idx int) any {
if idx < 0 || idx >= lb.SliceSize {
fmt.Printf("core.ListBase: slice index out of range: %v\n", idx)
return nil
}
val := reflectx.UnderlyingPointer(lb.sliceUnderlying.Index(idx)) // deal with pointer lists
vali := val.Interface()
return vali
}
// IsRowInBounds returns true if disp row is in bounds
func (lb *ListBase) IsRowInBounds(row int) bool {
return row >= 0 && row < lb.VisibleRows
}
// rowFirstWidget returns the first widget for given row (could be index or
// not) -- false if out of range
func (lb *ListBase) rowFirstWidget(row int) (*WidgetBase, bool) {
// (the first widget of a row is its value without indexes:
// see RowWidgetNs)
if !lb.IsRowInBounds(row) {
return nil, false
}
nWidgPerRow, _ := lb.This.(Lister).RowWidgetNs()
lg := lb.ListGrid
w := lg.Children[row*nWidgPerRow].(Widget).AsWidget()
return w, true
}
// RowGrabFocus grabs the focus for the first focusable widget
// in given row. returns that element or nil if not successful
// note: grid must have already rendered for focus to be grabbed!
func (lb *ListBase) RowGrabFocus(row int) *WidgetBase {
if !lb.IsRowInBounds(row) || lb.InFocusGrab { // range check
return nil
}
nWidgPerRow, idxOff := lb.This.(Lister).RowWidgetNs()
ridx := nWidgPerRow * row
lg := lb.ListGrid
w := lg.Child(ridx + idxOff).(Widget).AsWidget()
if w.StateIs(states.Focused) {
return w
}
lb.InFocusGrab = true
w.SetFocus()
lb.InFocusGrab = false
return w
}
// IndexGrabFocus grabs the focus for the first focusable widget
// in given idx. returns that element or nil if not successful.
func (lb *ListBase) IndexGrabFocus(idx int) *WidgetBase {
lb.ScrollToIndex(idx)
return lb.This.(Lister).RowGrabFocus(idx - lb.StartIndex)
}
// indexPos returns center of window position of index label for idx (ContextMenuPos)
func (lb *ListBase) indexPos(idx int) image.Point {
row := min(max(idx-lb.StartIndex, 0), lb.VisibleRows-1)
var pos image.Point
w, ok := lb.rowFirstWidget(row)
if ok {
pos = w.ContextMenuPos(nil)
}
return pos
}
// rowFromPos returns the row that contains given vertical position, false if not found
func (lb *ListBase) rowFromPos(posY int) (int, bool) {
// todo: could optimize search to approx loc, and search up / down from there
for rw := 0; rw < lb.VisibleRows; rw++ {
w, ok := lb.rowFirstWidget(rw)
if ok {
if w.Geom.TotalBBox.Min.Y < posY && posY < w.Geom.TotalBBox.Max.Y {
return rw, true
}
}
}
return -1, false
}
// indexFromPos returns the idx that contains given vertical position, false if not found
func (lb *ListBase) indexFromPos(posY int) (int, bool) {
row, ok := lb.rowFromPos(posY)
if !ok {
return -1, false
}
return row + lb.StartIndex, true
}
// ScrollToIndexNoUpdate ensures that given slice idx is visible
// by scrolling display as needed.
// This version does not update the slicegrid.
// Just computes the StartIndex and updates the scrollbar
func (lb *ListBase) ScrollToIndexNoUpdate(idx int) bool {
if lb.VisibleRows == 0 {
return false
}
if idx < lb.StartIndex {
lb.StartIndex = idx
lb.StartIndex = max(0, lb.StartIndex)
lb.updateScroll()
return true
}
if idx >= lb.StartIndex+(lb.VisibleRows-1) {
lb.StartIndex = idx - (lb.VisibleRows - 4)
lb.StartIndex = max(0, lb.StartIndex)
lb.updateScroll()
return true
}
return false
}
// ScrollToIndex ensures that given slice idx is visible
// by scrolling display as needed.
func (lb *ListBase) ScrollToIndex(idx int) bool {
update := lb.ScrollToIndexNoUpdate(idx)
if update {
lb.Update()
}
return update
}
// sliceIndexByValue searches for first index that contains given value in slice;
// returns false if not found
func sliceIndexByValue(slc any, fldVal any) (int, bool) {
svnp := reflectx.NonPointerValue(reflect.ValueOf(slc))
sz := svnp.Len()
for idx := range sz {
rval := reflectx.NonPointerValue(svnp.Index(idx))
if rval.Interface() == fldVal {
return idx, true
}
}
return -1, false
}
// moveDown moves the selection down to next row, using given select mode
// (from keyboard modifiers) -- returns newly selected row or -1 if failed
func (lb *ListBase) moveDown(selMode events.SelectModes) int {
if lb.SelectedIndex >= lb.SliceSize-1 {
lb.SelectedIndex = lb.SliceSize - 1
return -1
}
lb.SelectedIndex++
lb.SelectIndexEvent(lb.SelectedIndex, selMode)
return lb.SelectedIndex
}
// moveDownEvent moves the selection down to next row, using given select
// mode (from keyboard modifiers) -- and emits select event for newly selected
// row
func (lb *ListBase) moveDownEvent(selMode events.SelectModes) int {
nidx := lb.moveDown(selMode)
if nidx >= 0 {
lb.ScrollToIndex(nidx)
lb.Send(events.Select) // todo: need to do this for the item?
}
return nidx
}
// moveUp moves the selection up to previous idx, using given select mode
// (from keyboard modifiers) -- returns newly selected idx or -1 if failed
func (lb *ListBase) moveUp(selMode events.SelectModes) int {
if lb.SelectedIndex < 0 {
lb.SelectedIndex = lb.lastClick
}
if lb.SelectedIndex <= 0 {
lb.SelectedIndex = 0
return -1
}
lb.SelectedIndex--
lb.SelectIndexEvent(lb.SelectedIndex, selMode)
return lb.SelectedIndex
}
// moveUpEvent moves the selection up to previous idx, using given select
// mode (from keyboard modifiers) -- and emits select event for newly selected idx
func (lb *ListBase) moveUpEvent(selMode events.SelectModes) int {
nidx := lb.moveUp(selMode)
if nidx >= 0 {
lb.ScrollToIndex(nidx)
lb.Send(events.Select)
}
return nidx
}
// movePageDown moves the selection down to next page, using given select mode
// (from keyboard modifiers) -- returns newly selected idx or -1 if failed
func (lb *ListBase) movePageDown(selMode events.SelectModes) int {
if lb.SelectedIndex >= lb.SliceSize-1 {
lb.SelectedIndex = lb.SliceSize - 1
return -1
}
lb.SelectedIndex += lb.VisibleRows
lb.SelectedIndex = min(lb.SelectedIndex, lb.SliceSize-1)
lb.SelectIndexEvent(lb.SelectedIndex, selMode)
return lb.SelectedIndex
}
// movePageDownEvent moves the selection down to next page, using given select
// mode (from keyboard modifiers) -- and emits select event for newly selected idx
func (lb *ListBase) movePageDownEvent(selMode events.SelectModes) int {
nidx := lb.movePageDown(selMode)
if nidx >= 0 {
lb.ScrollToIndex(nidx)
lb.Send(events.Select)
}
return nidx
}
// movePageUp moves the selection up to previous page, using given select mode
// (from keyboard modifiers) -- returns newly selected idx or -1 if failed
func (lb *ListBase) movePageUp(selMode events.SelectModes) int {
if lb.SelectedIndex <= 0 {
lb.SelectedIndex = 0
return -1
}
lb.SelectedIndex -= lb.VisibleRows
lb.SelectedIndex = max(0, lb.SelectedIndex)
lb.SelectIndexEvent(lb.SelectedIndex, selMode)
return lb.SelectedIndex
}
// movePageUpEvent moves the selection up to previous page, using given select
// mode (from keyboard modifiers) -- and emits select event for newly selected idx
func (lb *ListBase) movePageUpEvent(selMode events.SelectModes) int {
nidx := lb.movePageUp(selMode)
if nidx >= 0 {
lb.ScrollToIndex(nidx)
lb.Send(events.Select)
}
return nidx
}
//////// Selection: user operates on the index labels
// updateSelectRow updates the selection for the given row
func (lb *ListBase) updateSelectRow(row int, selMode events.SelectModes) {
idx := row + lb.StartIndex
if row < 0 || idx >= lb.SliceSize {
return
}
sel := !lb.indexIsSelected(idx)
lb.updateSelectIndex(idx, sel, selMode)
}
// updateSelectIndex updates the selection for the given index
func (lb *ListBase) updateSelectIndex(idx int, sel bool, selMode events.SelectModes) {
if lb.IsReadOnly() && !lb.ReadOnlyMultiSelect {
lb.unselectAllIndexes()
if sel || lb.SelectedIndex == idx {
lb.SelectedIndex = idx
lb.SelectIndex(idx)
}
lb.Send(events.Select)
lb.Restyle()
} else {
lb.SelectIndexEvent(idx, selMode)
}
}
// clickSelectRow updates the selection for a click on the given row in the
// given mode: [events.ExtendOne] toggles its selection, and
// [events.ExtendContinuous] selects the rows from the one last clicked to
// it. Unlike [ListBase.SelectIndexEvent], the focus does not move to the
// row, as to a text field in it, which would show the keyboard on mobile.
func (lb *ListBase) clickSelectRow(row int, mode events.SelectModes) {
idx := row + lb.StartIndex
if row < 0 || idx >= lb.SliceSize {
return
}
switch mode {
case events.ExtendOne:
if lb.indexIsSelected(idx) {
lb.unselectIndex(idx)
if lb.SelectedIndex == idx {
lb.SelectedIndex = -1
for i := range lb.SelectedIndexes {
lb.SelectedIndex = max(lb.SelectedIndex, i)
}
}
} else {
lb.SelectIndex(idx)
lb.SelectedIndex = idx
}
lb.lastClick = idx
case events.ExtendContinuous:
from := lb.lastClick
if from < 0 || from >= lb.SliceSize {
from = max(lb.SelectedIndex, idx)
}
for i := min(from, idx); i <= max(from, idx); i++ {
lb.SelectIndex(i)
}
lb.SelectedIndex = idx
}
lb.Send(events.Select)
lb.Restyle()
}
// contextSelectRow selects the given row for a context menu on it: only
// it, unless it is already selected, in which case the selection, as of
// several rows, is kept (as in file managers), with the row as the
// [ListBase.SelectedIndex], so that the context menu applies to all of them.
func (lb *ListBase) contextSelectRow(row int) {
idx := row + lb.StartIndex
if row < 0 || idx >= lb.SliceSize {
return
}
lb.lastClick = idx
if lb.indexIsSelected(idx) {
lb.SelectedIndex = idx
return
}
lb.updateSelectIndex(idx, true, events.SelectOne)
}
// selectIndexQuiet selects only the given slice index, if it is not
// already the selected one, without moving the focus, which is on that
// row or is going there, as for a click into a row.
func (lb *ListBase) selectIndexQuiet(idx int) {
if idx < 0 || idx >= lb.SliceSize || (idx == lb.SelectedIndex && len(lb.SelectedIndexes) == 1 && lb.indexIsSelected(idx)) {
return
}
lb.unselectAllIndexes()
lb.SelectedIndex = idx
lb.SelectIndex(idx)
lb.lastClick = idx
lb.Send(events.Select)
lb.Restyle()
}
// selectFocusedRow selects the row with the focus, as after moving
// the focus there with the tab key, if it is not the selected one.
func (lb *ListBase) selectFocusedRow() {
em := lb.Events()
if em == nil || tree.IsNil(em.focus) || lb.ListGrid == nil {
return
}
for n := em.focus.AsTree(); n != nil && n.This != lb.This; n = n.Parent.AsTree() {
if n.Parent == lb.ListGrid.This {
// a focused row that is selected keeps a multiple selection,
// for the keys that act on it, such as copy.
if row, ok := n.Property(ListRowProperty).(int); ok && !lb.indexIsSelected(row+lb.StartIndex) {
lb.selectIndexQuiet(row + lb.StartIndex)
}
return
}
if n.Parent == nil {
return
}
}
}
// indexIsSelected returns the selected status of given slice index
// SetDropIndex highlights the item at the given index as the target of
// a drop in progress, as for a folder that dragged files would be dropped
// into, or no item for -1.
func (lb *ListBase) SetDropIndex(idx int) {
if lb.dropIndex == idx {
return
}
lb.dropIndex = idx
lb.NeedsRender()
}
// rowBackgroundOf returns the background of the row of the given item, at
// the given row of the grid.
func (lg *ListGrid) rowBackgroundOf(ls *ListBase, si, row int) image.Image {
drop := si == ls.dropIndex
return lg.rowBackground(ls.indexIsSelected(si) || drop, si%2 == 1, row == ls.hoverRow || drop)
}
func (lb *ListBase) indexIsSelected(idx int) bool {
if lb.IsReadOnly() && !lb.ReadOnlyMultiSelect {
return idx == lb.SelectedIndex
}
_, ok := lb.SelectedIndexes[idx]
return ok
}
func (lb *ListBase) ResetSelectedIndexes() {
lb.SelectedIndexes = make(map[int]struct{})
}
// SelectedIndexesList returns list of selected indexes,
// sorted either ascending or descending
func (lb *ListBase) SelectedIndexesList(order reflectx.SortOrder) []int {
rws := make([]int, len(lb.SelectedIndexes))
i := 0
for r := range lb.SelectedIndexes {
if r >= lb.SliceSize { // double safety check at this point
delete(lb.SelectedIndexes, r)
rws = rws[:len(rws)-1]
continue
}
rws[i] = r
i++
}
if order == reflectx.Descending {
sort.Slice(rws, func(i, j int) bool {
return rws[i] > rws[j]
})
} else {
slices.Sort(rws)
}
return rws
}
// SelectIndex selects given idx (if not already selected) -- updates select
// status of index label
func (lb *ListBase) SelectIndex(idx int) {
lb.SelectedIndexes[idx] = struct{}{}
}
// unselectIndex unselects given idx (if selected)
func (lb *ListBase) unselectIndex(idx int) {
if lb.indexIsSelected(idx) {
delete(lb.SelectedIndexes, idx)
}
}
// unselectAllIndexes unselects all selected idxs
func (lb *ListBase) unselectAllIndexes() {
lb.ResetSelectedIndexes()
}
// selectAllIndexes selects all idxs
func (lb *ListBase) selectAllIndexes() {
lb.unselectAllIndexes()
lb.SelectedIndexes = make(map[int]struct{}, lb.SliceSize)
for idx := 0; idx < lb.SliceSize; idx++ {
lb.SelectedIndexes[idx] = struct{}{}
}
lb.NeedsRender()
}
// SelectIndexEvent is called when a select event has been received (e.g., a
// mouse click) -- translates into selection updates -- gets selection mode
// from mouse event (ExtendContinuous, ExtendOne)
func (lb *ListBase) SelectIndexEvent(idx int, mode events.SelectModes) {
if mode == events.NoSelect {
return
}
idx = min(idx, lb.SliceSize-1)
if idx < 0 {
lb.ResetSelectedIndexes()
return
}
// row := idx - sv.StartIndex // note: could be out of bounds
switch mode {
case events.SelectOne:
if lb.indexIsSelected(idx) {
if len(lb.SelectedIndexes) > 1 {
lb.unselectAllIndexes()
}
lb.SelectedIndex = idx
lb.SelectIndex(idx)
lb.IndexGrabFocus(idx)
} else {
lb.unselectAllIndexes()
lb.SelectedIndex = idx
lb.SelectIndex(idx)
lb.IndexGrabFocus(idx)
}
lb.Send(events.Select) // sv.SelectedIndex)
case events.ExtendContinuous:
if len(lb.SelectedIndexes) == 0 {
lb.SelectedIndex = idx
lb.SelectIndex(idx)
lb.IndexGrabFocus(idx)
lb.Send(events.Select) // sv.SelectedIndex)
} else {
minIndex := -1
maxIndex := 0
for r := range lb.SelectedIndexes {
if minIndex < 0 {
minIndex = r
} else {
minIndex = min(minIndex, r)
}
maxIndex = max(maxIndex, r)
}
cidx := idx
lb.SelectedIndex = idx
lb.SelectIndex(idx)
if idx < minIndex {
for cidx < minIndex {
r := lb.moveDown(events.SelectQuiet) // just select
cidx = r
}
} else if idx > maxIndex {
for cidx > maxIndex {
r := lb.moveUp(events.SelectQuiet) // just select
cidx = r
}
}
// the moves above change the selected index, which is where
// the selection is extended from next, so it goes back to idx.
lb.SelectedIndex = idx
lb.IndexGrabFocus(idx)
lb.Send(events.Select) // sv.SelectedIndex)
}
case events.ExtendOne:
if lb.indexIsSelected(idx) {
lb.unselectIndexEvent(idx)
lb.Send(events.Select) // sv.SelectedIndex)
} else {
lb.SelectedIndex = idx
lb.SelectIndex(idx)
lb.IndexGrabFocus(idx)
lb.Send(events.Select) // sv.SelectedIndex)
}
case events.Unselect:
lb.SelectedIndex = idx
lb.unselectIndexEvent(idx)
case events.SelectQuiet:
lb.SelectedIndex = idx
lb.SelectIndex(idx)
case events.UnselectQuiet:
lb.SelectedIndex = idx
lb.unselectIndex(idx)
}
lb.Restyle()
}
// unselectIndexEvent unselects this idx (if selected) -- and emits a signal
func (lb *ListBase) unselectIndexEvent(idx int) {
if lb.indexIsSelected(idx) {
lb.unselectIndex(idx)
}
}
//////// Copy / Cut / Paste
// mimeDataIndex adds mimedata for given idx: an application/json of the struct
func (lb *ListBase) mimeDataIndex(md *mimedata.Mimes, idx int) {
val := lb.sliceValue(idx)
b, err := json.MarshalIndent(val, "", " ")
if err == nil {
*md = append(*md, &mimedata.Data{Type: fileinfo.DataJSON, Data: b})
} else {
log.Printf("ListBase MimeData JSON Marshall error: %v\n", err)
}
}
// fromMimeData creates a slice of structs from mime data
func (lb *ListBase) fromMimeData(md mimedata.Mimes) []any {
svtyp := lb.sliceUnderlying.Type()
sl := make([]any, 0, len(md))
for _, d := range md {
if d.Type == fileinfo.DataJSON {
nval := reflect.New(svtyp.Elem()).Interface()
err := json.Unmarshal(d.Data, nval)
if err == nil {
sl = append(sl, nval)
} else {
log.Printf("ListBase FromMimeData: JSON load error: %v\n", err)
}
}
}
return sl
}
// MimeDataType returns the data type for mime clipboard (copy / paste) data
// e.g., fileinfo.DataJson
func (lb *ListBase) MimeDataType() string {
return fileinfo.DataJSON
}
// CopySelectToMime copies selected rows to mime data
func (lb *ListBase) CopySelectToMime() mimedata.Mimes {
nitms := len(lb.SelectedIndexes)
if nitms == 0 {
return nil
}
ixs := lb.SelectedIndexesList(reflectx.Ascending)
md := make(mimedata.Mimes, 0, nitms)
for _, i := range ixs {
lb.mimeDataIndex(&md, i)
}
return md
}
// copyIndexes copies selected idxs to system.Clipboard, optionally resetting the selection
func (lb *ListBase) copyIndexes(reset bool) { //types:add
nitms := len(lb.SelectedIndexes)
if nitms == 0 {
return
}
md := lb.This.(Lister).CopySelectToMime()
if md != nil {
lb.Clipboard().Write(md)
}
if reset {
lb.unselectAllIndexes()
}
}
// cutIndexes copies selected indexes to system.Clipboard and deletes selected indexes
func (lb *ListBase) cutIndexes() { //types:add
if len(lb.SelectedIndexes) == 0 {
return
}
lb.copyIndexes(false)
ixs := lb.SelectedIndexesList(reflectx.Descending)
idx := ixs[0]
lb.unselectAllIndexes()
for _, i := range ixs {
lb.This.(Lister).DeleteAt(i)
}
lb.SendChange()
lb.SelectIndexEvent(idx, events.SelectOne)
lb.Update()
}
// pasteIndex pastes clipboard at given idx
func (lb *ListBase) pasteIndex(idx int) { //types:add
lb.tmpIndex = idx
dt := lb.This.(Lister).MimeDataType()
md := lb.Clipboard().Read([]string{dt})
if md != nil {
lb.pasteMenu(md, lb.tmpIndex)
}
}
// treeLister is implemented by lists of trees, such as [TreeTable], for
// the copy and paste operations that work differently on trees, where
// pasting is relative to the item at an index, and a move deletes the
// moved items wherever they are, not those at the indexes of the rows.
type treeLister interface {
makeTreePasteMenu(m *Scene, md mimedata.Mimes, idx int, mod events.DropMods, fun func())
dropDeleteItems()
}
// makePasteMenu makes the menu of options for paste events
func (lb *ListBase) makePasteMenu(m *Scene, _ image.Point, md mimedata.Mimes, idx int, mod events.DropMods, fun func()) {
if tp, ok := lb.This.(treeLister); ok {
tp.makeTreePasteMenu(m, md, idx, mod, fun)
return
}
ls := lb.This.(Lister)
if mod == events.DropCopy {
NewButton(m).SetText("Assign to").OnClick(func(e events.Event) {
ls.PasteAssign(md, idx)
if fun != nil {
fun()
}
})
}
NewButton(m).SetText("Insert before").OnClick(func(e events.Event) {
ls.PasteAtIndex(md, idx)
if fun != nil {
fun()
}
})
NewButton(m).SetText("Insert after").OnClick(func(e events.Event) {
ls.PasteAtIndex(md, idx+1)
if fun != nil {
fun()
}
})
NewButton(m).SetText("Cancel")
}
// pasteMenu performs a paste from the clipboard using given data -- pops up
// a menu to determine what specifically to do
func (lb *ListBase) pasteMenu(md mimedata.Mimes, idx int) {
lb.unselectAllIndexes()
mf := func(m *Scene, pos image.Point) {
lb.makePasteMenu(m, pos, md, idx, events.DropCopy, nil)
}
pos := lb.indexPos(idx)
NewMenu(mf, lb.This.(Widget), pos).Run()
}
// PasteAssign assigns mime data (only the first one!) to this idx
func (lb *ListBase) PasteAssign(md mimedata.Mimes, idx int) {
sl := lb.fromMimeData(md)
if len(sl) == 0 {
return
}
ns := sl[0]
lb.sliceUnderlying.Index(idx).Set(reflect.ValueOf(ns).Elem())
lb.UpdateChange()
}
// PasteAtIndex inserts object(s) from mime data at (before) given slice index
func (lb *ListBase) PasteAtIndex(md mimedata.Mimes, idx int) {
sl := lb.fromMimeData(md)
if len(sl) == 0 {
return
}
svl := reflect.ValueOf(lb.Slice)
svnp := lb.sliceUnderlying
for _, ns := range sl {
sz := svnp.Len()
svnp = reflect.Append(svnp, reflect.ValueOf(ns).Elem())
svl.Elem().Set(svnp)
if idx >= 0 && idx < sz {
reflect.Copy(svnp.Slice(idx+1, sz+1), svnp.Slice(idx, sz))
svnp.Index(idx).Set(reflect.ValueOf(ns).Elem())
svl.Elem().Set(svnp)
}
idx++
}
lb.sliceUnderlying = reflectx.NonPointerValue(reflect.ValueOf(lb.Slice)) // need to update after changes
lb.SendChange()
lb.SelectIndexEvent(idx, events.SelectOne)
lb.Update()
}
// duplicate copies selected items and inserts them after current selection --
// return idx of start of duplicates if successful, else -1
func (lb *ListBase) duplicate() int { //types:add
nitms := len(lb.SelectedIndexes)
if nitms == 0 {
return -1
}
ixs := lb.SelectedIndexesList(reflectx.Descending) // last first
pasteAt := ixs[0]
lb.copyIndexes(true)
dt := lb.This.(Lister).MimeDataType()
md := lb.Clipboard().Read([]string{dt})
lb.This.(Lister).PasteAtIndex(md, pasteAt)
return pasteAt
}
//////// Drag-n-Drop
// dragSelectRow selects the row where the given drag started, where the
// mouse was pressed, if it is not selected already, so that the row that is
// dragged is the one that was pressed, and returns false if there is none.
// It replaces the selection, rather than extending it with the modifier
// keys of the drag, which choose whether the drop copies or moves.
func (lb *ListBase) dragSelectRow(e events.Event) bool {
row, _, isValid := lb.ListGrid.indexFromPixel(e.StartPos())
if !isValid {
return false
}
if !lb.indexIsSelected(row + lb.StartIndex) {
lb.updateSelectRow(row, events.SelectOne)
}
return true
}
func (lb *ListBase) dragStart(e events.Event) {
if !lb.dragSelectRow(e) {
return
}
ixs := lb.SelectedIndexesList(reflectx.Ascending)
if len(ixs) == 0 {
return
}
md := lb.This.(Lister).CopySelectToMime()
// the list is the source of the drag, which gets the DropDeleteSource
// of a move, with the image of the first row, and it keeps the indexes
// of the dragged items, to delete them after a move
w, ok := lb.rowFirstWidget(ixs[0] - lb.StartIndex)
if ok {
lb.draggedIndexes = ixs
lb.Scene.Events.dragStartFrom(lb.This.(Widget), w, md, e)
e.SetHandled()
}
}
func (lb *ListBase) dragDrop(e events.Event) {
de := e.(*events.DragDrop)
if de.Data == nil || lb.IsReadOnly() { // (made read-only after Init)
return
}
pos := de.Pos()
idx, ok := lb.indexFromPos(pos.Y)
if ok {
lb.tmpIndex = idx
if de.Source == lb.This {
lb.shiftDraggedIndexes(idx)
}
md := de.Data.(mimedata.Mimes)
mf := func(m *Scene, pos image.Point) {
lb.Scene.Events.DragMenuAddModText(m, de.DropMod)
lb.makePasteMenu(m, pos, md, idx, de.DropMod, func() {
lb.dropFinalize(de)
})
}
pos := lb.indexPos(lb.tmpIndex)
NewMenu(mf, lb.This.(Widget), pos).Run()
}
}
// dropFinalize is called to finalize Drop actions on the Source node.
// Only relevant for DropMod == DropMove.
func (lb *ListBase) dropFinalize(de *events.DragDrop) {
lb.NeedsLayout()
lb.unselectAllIndexes()
lb.Scene.Events.DropFinalize(de) // sends DropDeleteSource to Source
}
// dropDeleteSource handles delete source event for DropMove case
func (lb *ListBase) dropDeleteSource(_ events.Event) {
if tl, ok := lb.This.(treeLister); ok {
tl.dropDeleteItems()
return
}
if len(lb.draggedIndexes) == 0 {
return
}
sort.Slice(lb.draggedIndexes, func(i, j int) bool {
return lb.draggedIndexes[i] > lb.draggedIndexes[j]
})
idx := lb.draggedIndexes[0]
for _, i := range lb.draggedIndexes {
lb.This.(Lister).DeleteAt(i)
}
lb.draggedIndexes = nil
lb.SelectIndexEvent(idx, events.SelectOne)
}
// shiftDraggedIndexes shifts the dragged indexes for the insertion of
// the dragged items at the given index of the same list, as for a move
// within it, so that they are the indexes of the items to delete after it.
func (lb *ListBase) shiftDraggedIndexes(idx int) {
sz := len(lb.draggedIndexes)
for i, ix := range lb.draggedIndexes {
if ix > idx {
lb.draggedIndexes[i] = ix + sz // make room for insertion
}
}
}
func (lb *ListBase) contextMenu(m *Scene, pos image.Point) {
if lb.IsReadOnly() || lb.isArray {
NewButton(m).SetText("Copy").SetIcon(icons.Copy).OnClick(func(e events.Event) {
lb.copyIndexes(true)
})
NewSeparator(m)
NewButton(m).SetText("Toggle indexes").SetIcon(icons.Numbers).OnClick(func(e events.Event) {
lb.ShowIndexes = !lb.ShowIndexes
lb.Update()
})
return
}
NewButton(m).SetText("Add row").SetIcon(icons.Add).OnClick(func(e events.Event) {
lb.newAtRow((lb.SelectedIndex - lb.StartIndex) + 1)
})
NewButton(m).SetText("Delete row").SetIcon(icons.Delete).OnClick(func(e events.Event) {
lb.deleteAtRow(lb.SelectedIndex - lb.StartIndex)
})
NewSeparator(m)
NewButton(m).SetText("Copy").SetIcon(icons.Copy).OnClick(func(e events.Event) {
lb.copyIndexes(true)
})
NewButton(m).SetText("Cut").SetIcon(icons.Cut).OnClick(func(e events.Event) {
lb.cutIndexes()
})
NewButton(m).SetText("Paste").SetIcon(icons.Paste).OnClick(func(e events.Event) {
lb.pasteIndex(lb.SelectedIndex)
})
NewButton(m).SetText("Duplicate").SetIcon(icons.Copy).OnClick(func(e events.Event) {
lb.duplicate()
})
NewSeparator(m)
NewButton(m).SetText("Toggle indexes").SetIcon(icons.Numbers).OnClick(func(e events.Event) {
lb.ShowIndexes = !lb.ShowIndexes
lb.Update()
})
}
// keyInputNav supports multiple selection navigation keys
func (lb *ListBase) keyInputNav(kt events.Event) {
kf := keymap.Of(kt.KeyChord())
selMode := events.SelectModeBits(kt.Modifiers())
if selMode == events.SelectOne {
if lb.SelectMode {
selMode = events.ExtendContinuous
}
}
switch kf {
case keymap.CancelSelect:
lb.unselectAllIndexes()
lb.SelectMode = false
kt.SetHandled()
case keymap.MoveDown:
lb.moveDownEvent(selMode)
kt.SetHandled()
case keymap.MoveUp:
lb.moveUpEvent(selMode)
kt.SetHandled()
case keymap.PageDown:
lb.movePageDownEvent(selMode)
kt.SetHandled()
case keymap.PageUp:
lb.movePageUpEvent(selMode)
kt.SetHandled()
case keymap.SelectMode:
lb.SelectMode = !lb.SelectMode
kt.SetHandled()
case keymap.SelectAll:
lb.selectAllIndexes()
lb.SelectMode = false
kt.SetHandled()
}
}
func (lb *ListBase) keyInputEditable(kt events.Event) {
lb.selectFocusedRow()
lb.keyInputNav(kt)
if kt.IsHandled() {
return
}
idx := lb.SelectedIndex
kf := keymap.Of(kt.KeyChord())
if DebugSettings.KeyEventTrace {
slog.Info("ListBase KeyInput", "widget", lb, "keyFunction", kf)
}
switch kf {
// case keymap.Delete: // too dangerous
// sv.This.(Lister).SliceDeleteAt(sv.SelectedIndex)
// sv.SelectMode = false
// sv.SelectIndexEvent(idx, events.SelectOne)
// kt.SetHandled()
case keymap.Duplicate:
nidx := lb.duplicate()
lb.SelectMode = false
if nidx >= 0 {
lb.SelectIndexEvent(nidx, events.SelectOne)
}
kt.SetHandled()
case keymap.Insert:
lb.This.(Lister).NewAt(idx)
lb.SelectMode = false
lb.SelectIndexEvent(idx+1, events.SelectOne) // todo: somehow nidx not working
kt.SetHandled()
case keymap.InsertAfter:
lb.This.(Lister).NewAt(idx + 1)
lb.SelectMode = false
lb.SelectIndexEvent(idx+1, events.SelectOne)
kt.SetHandled()
case keymap.Copy:
lb.copyIndexes(true)
lb.SelectMode = false
lb.SelectIndexEvent(idx, events.SelectOne)
kt.SetHandled()
case keymap.Cut:
lb.cutIndexes()
lb.SelectMode = false
kt.SetHandled()
case keymap.Paste:
lb.pasteIndex(lb.SelectedIndex)
lb.SelectMode = false
kt.SetHandled()
}
}
func (lb *ListBase) keyInputReadOnly(kt events.Event) {
if lb.ReadOnlyMultiSelect {
lb.keyInputNav(kt)
if kt.IsHandled() {
return
}
}
selMode := kt.SelectMode()
if lb.SelectMode {
selMode = events.ExtendOne
}
kf := keymap.Of(kt.KeyChord())
if DebugSettings.KeyEventTrace {
slog.Info("ListBase ReadOnly KeyInput", "widget", lb, "keyFunction", kf)
}
idx := lb.SelectedIndex
switch {
case kf == keymap.MoveDown:
ni := idx + 1
if ni < lb.SliceSize {
lb.ScrollToIndex(ni)
lb.updateSelectIndex(ni, true, selMode)
kt.SetHandled()
}
case kf == keymap.MoveUp:
ni := idx - 1
if ni >= 0 {
lb.ScrollToIndex(ni)
lb.updateSelectIndex(ni, true, selMode)
kt.SetHandled()
}
case kf == keymap.PageDown:
ni := min(idx+lb.VisibleRows-1, lb.SliceSize-1)
lb.ScrollToIndex(ni)
lb.updateSelectIndex(ni, true, selMode)
kt.SetHandled()
case kf == keymap.PageUp:
ni := max(idx-(lb.VisibleRows-1), 0)
lb.ScrollToIndex(ni)
lb.updateSelectIndex(ni, true, selMode)
kt.SetHandled()
case kf == keymap.Enter || kf == keymap.Accept || kt.KeyRune() == ' ':
lb.Send(events.DoubleClick, kt)
kt.SetHandled()
}
}
func (lb *ListBase) SizeFinal() {
lg := lb.ListGrid
if lg == nil {
lb.Frame.SizeFinal()
return
}
localIter := 0
for (lb.MakeIter < 2 || lb.VisibleRows != lg.visibleRows) && localIter < 2 {
if lb.VisibleRows != lg.visibleRows {
lb.setVisibleRows(lg.visibleRows)
} else {
lg.StyleTree()
}
lg.sizeFinalUpdateChildrenSizes()
lb.MakeIter++
localIter++
}
lb.Frame.SizeFinal()
}
// setVisibleRows sets the number of visible rows and updates the list.
// The item of a cell with the focus stays focused, as when the virtual
// keyboard for typing into it shrinks the window: the rows are widgets
// for the items from the [ListBase.StartIndex], which can change, so the
// focus moves to the cell of the item in its row, after scrolling it into
// view if it is no longer in the rows (see [ListBase.keepFocusedItem]).
func (lb *ListBase) setVisibleRows(n int) {
idx, pos, foc := lb.focusedCell()
ed := saveEdit(foc)
start := lb.StartIndex
lb.VisibleRows = n
lb.Update()
if foc != nil {
lb.keepFocusedItem(idx, pos, ed, foc, true)
}
if lb.StartIndex != start {
// the scroll bar is set once laid out, before any scrolling
// to the cell of the focus
lb.Defer(lb.updateScroll)
}
}
// keepFocusedItem keeps the focus on the cell at the given position in
// the row of the given slice index, which had the given focused widget,
// with the given edit in progress (see [saveEdit]), after the rows were
// updated, as the rows are widgets for the items from the
// [ListBase.StartIndex], which can change: if the item is no longer in
// the rows, it is scrolled into view if scroll, or else (when scrolled
// away from, after its edit is completed) the focus is cleared; if its
// cell is another widget, the focus moves there, without losing it in
// between, which would hide the virtual keyboard, as for a new focus.
// The edit continues in the cell (whose text the update set again).
func (lb *ListBase) keepFocusedItem(idx, pos int, ed *cellEdit, foc Widget, scroll bool) {
em := lb.Events()
if em == nil || em.focus != foc {
return
}
if idx < lb.StartIndex || idx >= lb.StartIndex+lb.VisibleRows {
if !scroll {
em.setFocus(nil)
return
}
lb.ScrollToIndexNoUpdate(idx)
lb.Update()
}
cell := lb.cellOf(idx, pos)
if cell == nil {
return
}
if foc.AsTree().This == cell.This || (foc.AsTree().This != nil && isParentOf(cell.This.(Widget), foc)) {
ed.restore(foc) // the same cell
return
}
em.focus = nil // (without the focus lost event)
if foc.AsTree().This != nil {
foc.AsWidget().SetState(false, states.Focused)
// the edit goes with the focus, so it must not stay in the
// widget left behind, which is for another item now
if tf, ok := foc.(*TextField); ok {
tf.revert()
tf.stopCursor()
}
}
lb.Defer(func() { // (once it is laid out, for scrolling to it)
lb.updateScroll()
if em.focus != nil {
return
}
cell := lb.cellOf(idx, pos)
if cell == nil {
return
}
cell.SetFocus()
if em.focus != nil { // (the text field in the cell, as in a tree table)
ed.restore(em.focus)
}
})
}
// cellOf returns the cell at the given position in the row of the given
// slice index, or nil if it is not in the rows.
func (lb *ListBase) cellOf(idx, pos int) *WidgetBase {
nw, _ := lb.This.(Lister).RowWidgetNs()
if lb.ListGrid == nil || idx < lb.StartIndex || idx >= lb.StartIndex+lb.VisibleRows || pos < 0 || pos >= nw {
return nil
}
k := nw*(idx-lb.StartIndex) + pos
if k >= lb.ListGrid.NumChildren() {
return nil
}
return lb.ListGrid.Child(k).(Widget).AsWidget()
}
// cellEdit is the edit in progress in a [TextField] of a cell: its text
// and cursor, which are kept when the rows are updated, which sets the
// text of the cells from their items again, discarding any edit.
type cellEdit struct {
text []rune
cursor int
edited bool
}
// saveEdit returns the edit in progress in the given focused widget of a
// cell, if it is a [TextField], or nil.
func saveEdit(foc Widget) *cellEdit {
tf, ok := foc.(*TextField)
if !ok || tf.This == nil {
return nil
}
return &cellEdit{text: slices.Clone(tf.editText), cursor: tf.cursorPos, edited: tf.edited}
}
// restore continues the edit in the given widget, which is a [TextField]
// of the cell of the same item.
func (ed *cellEdit) restore(w Widget) {
tf, ok := w.(*TextField)
if ed == nil || !ok {
return
}
if ed.edited {
tf.editText = slices.Clone(ed.text)
tf.edited = true
tf.renderVisible = nil
}
tf.cursorPos = min(ed.cursor, len(tf.editText))
tf.NeedsRender()
}
// commitEdit completes any edit of the given focused widget of a cell,
// a [TextField], as before the rows are scrolled away from its item.
func commitEdit(foc Widget) {
if tf, ok := foc.(*TextField); ok && tf.edited {
tf.editDone()
}
}
// focusedCell returns the slice index of the row of the cell of the grid
// with the focus (or containing it), and the position of the cell in its
// row, and the focused widget, which is nil if there is none in the grid.
func (lb *ListBase) focusedCell() (idx, pos int, foc Widget) {
em := lb.Events()
if em == nil || tree.IsNil(em.focus) || lb.ListGrid == nil {
return
}
for n := em.focus.AsTree(); n != nil && n.This != lb.This; n = n.Parent.AsTree() {
if n.Parent == lb.ListGrid.This {
row, ok := n.Property(ListRowProperty).(int)
if !ok {
return
}
nw, _ := lb.This.(Lister).RowWidgetNs()
return row + lb.StartIndex, n.IndexInParent() - nw*row, em.focus
}
if n.Parent == nil {
return
}
}
return
}
//////// Search interface
// TextRunes returns any text content associated with the widget, to be used
// for Search for example. If this is nil, then it is excluded from search.
func (lb *ListBase) TextRunes() []rune {
return nil
}
// Search returns text search results for this widget, searching for
// the find string with given case sensitivity. It is up to each widget
// to define the meaning of the Region line, char values for the matches.
// The bool return value indicates whether this widget handled the search,
// thereby excluding further searching within the elements under it.
func (lb *ListBase) Search(find string, useCase CaseSensitive) ([]textpos.Match, bool) {
var results []textpos.Match
for rw := range lb.SliceSize {
val := lb.sliceElementValue(rw)
str := reflectx.ToString(val.Interface())
m := SearchRunes([]rune(str), find, useCase)
if len(m) == 0 {
continue
}
for i := range m {
m[i].Region.Start.Line = rw
m[i].Region.End.Line = rw
}
results = append(results, m...)
}
return results, true
}
// HighlightMatches does highlighting of the given matches within this widget,
// where the matches are as returned from the Search method.
// Passing a nil causes matches to be reset.
// Any existing highlighting should always be reset first regardless.
// The bool return value indicates whether this widget handled the search,
// thereby excluding further searching within the elements under it.
func (lb *ListBase) HighlightMatches(matches []textpos.Match) bool {
nWidgPerRow, idxOff := lb.RowWidgetNs()
lg := lb.ListGrid
for i := range lb.VisibleRows {
ridx := nWidgPerRow * i
w := lg.Child(ridx + idxOff).(Widget)
w.SelectMatch(matches, 0, SelectNoScroll, SelectReset)
w.HighlightMatches(nil) // reset
}
if matches == nil {
return true
}
for _, m := range matches {
rw := m.Region.Start.Line
if rw < lb.StartIndex || rw >= lb.StartIndex+lb.VisibleRows {
continue
}
ridx := nWidgPerRow * (rw - lb.StartIndex)
w := lg.Child(ridx + idxOff).(Widget)
w.HighlightMatches([]textpos.Match{m})
}
return true
}
// SelectMatch selects match at given index from among those returned
// from the Search method. scroll = scroll widget into view.
// reset = clear selection instead of selecting.
func (lb *ListBase) SelectMatch(matches []textpos.Match, index int, scroll SelectionScroll, reset SelectionReset) {
nWidgPerRow, idxOff := lb.RowWidgetNs()
match := matches[index]
lg := lb.ListGrid
rw := match.Region.Start.Line
if rw < lb.StartIndex || rw >= lb.StartIndex+lb.VisibleRows {
if reset == SelectReset || scroll == SelectNoScroll {
return
}
lb.ScrollToIndex(rw)
lb.HighlightMatches(matches)
}
if rw < lb.StartIndex || rw >= lb.StartIndex+lb.VisibleRows { // shouldn't happen
return
}
ridx := nWidgPerRow * (rw - lb.StartIndex)
w := lg.Child(ridx + idxOff).(Widget)
w.SelectMatch(matches, index, SelectNoScroll, reset) // no scroll is key!
}
//////// ListGrid
// ListGrid handles the resizing logic for all [Lister]s.
type ListGrid struct { //core:no-new
Frame
// minRows is set from parent [List]
minRows int
// height of a single row, computed during layout
rowHeight float32
// total number of rows visible in allocated display size
visibleRows int
// Various computed backgrounds
bgStripe, bgSelect, bgSelectStripe, bgHover, bgHoverStripe, bgHoverSelect, bgHoverSelectStripe image.Image
// lastBackground is the background for which modified
// backgrounds were computed -- don't update if same
lastBackground image.Image
}
func (lg *ListGrid) Init() {
lg.Frame.Init()
lg.handleKeyNav = false
lg.Styler(func(s *styles.Style) {
s.Display = styles.Grid
})
// (these run before the scrolling of the frame, added before them)
lg.On(events.Scroll, func(e events.Event) {
if lg.AbilityIs(abilities.ScrollableUnattended) || lg.StateIs(states.Focused) || lg.StateIs(states.Attended) {
lg.endEdit()
}
})
lg.On(events.SlideStart, func(e events.Event) {
if TheApp.SystemPlatform().IsMobile() { // (a scroll on mobile)
lg.endEdit()
}
})
}
// endEdit applies the edit of the text field of a cell with the focus,
// and clears the focus, as the user starts scrolling the rows: the rows
// are widgets for other items as they scroll.
func (lg *ListGrid) endEdit() {
if !lg.HasScroll[math32.Y] {
return
}
ls := lg.list()
_, _, foc := ls.focusedCell()
if _, ok := foc.(*TextField); !ok {
return
}
commitEdit(foc)
if em := ls.Events(); em != nil && em.focus == foc {
em.setFocus(nil)
}
}
func (lg *ListGrid) SizeFromChildren(iter int, pass LayoutPasses) math32.Vector2 {
lg.fixColumnWidths()
csz := lg.Frame.SizeFromChildren(iter, pass)
rht, err := lg.layout.rowHeight(0, 0)
rht += lg.layout.Gap.Y
if err != nil {
// fmt.Println("ListGrid Sizing Error:", err)
lg.rowHeight = 42
}
lg.rowHeight = rht
if lg.rowHeight == 0 {
// fmt.Println("ListGrid Sizing Error: RowHeight should not be 0!", sg)
lg.rowHeight = 42
}
allocHt := lg.Geom.Size.Alloc.Content.Y
if allocHt > lg.rowHeight {
lg.visibleRows = int(math32.Ceil(allocHt / lg.rowHeight))
}
lg.visibleRows = max(lg.visibleRows, lg.minRows)
minHt := lg.rowHeight * float32(lg.minRows)
// fmt.Println("VisRows:", sg.VisRows, "rh:", sg.RowHeight, "ht:", minHt)
// visHt := sg.RowHeight * float32(sg.VisRows)
csz.Y = minHt
// room for the vertical scrollbar, which would otherwise be taken from
// the width of the rows, which then overflow (see [Frame.ManageOverflow])
if lg.HasScroll[math32.Y] {
csz.X += math32.Ceil(lg.Styles.ScrollbarWidth.Dots)
}
return csz
}
// ColumnWidther is implemented by lists with columns whose widths
// can be set, such as [Table], for which the [ListGrid] makes the
// cells of the columns have those widths, with the [ListColProperty]
// of each cell as its column.
type ColumnWidther interface {
// ColumnWidthDots returns the width of the given column in dots,
// or 0 if it is automatic.
ColumnWidthDots(col int) float32
}
// fixColumnWidths sets the widths of the cells in the columns whose
// widths are set, which do not grow. This is done in the layout, where
// the sizes of their padding, borders, and margins are known.
func (lg *ListGrid) fixColumnWidths() {
cw, ok := lg.list().This.(ColumnWidther)
if !ok {
return
}
lg.forVisibleChildren(func(i int, w Widget, wb *WidgetBase) bool {
col, ok := wb.Property(ListColProperty).(int)
if !ok {
return tree.Continue
}
width := cw.ColumnWidthDots(col)
if width <= 0 {
return tree.Continue
}
wb.Styles.Grow.X = 0
sz := &wb.Geom.Size
space := sz.Actual.Total.X - sz.Actual.Content.X
sz.Actual.Total.X, sz.Actual.Content.X = width, max(width-space, 0)
sz.Alloc.Total.X, sz.Alloc.Content.X = sz.Actual.Total.X, sz.Actual.Content.X
return tree.Continue
})
}
func (lg *ListGrid) list() *ListBase {
ls := tree.ParentByType[Lister](lg)
return ls.AsListBase()
}
func (lg *ListGrid) ScrollChanged(d math32.Dims, sb *Slider) {
if d == math32.X {
lg.Frame.ScrollChanged(d, sb)
return
}
ls := lg.list()
idx, pos, foc := ls.focusedCell()
rht := lg.rowHeight
quo := sb.Value / rht
floor := math32.Floor(quo)
if foc != nil && (idx < int(floor) || idx >= int(floor)+ls.VisibleRows) {
commitEdit(foc) // (scrolled away from, so it is completed)
}
ed := saveEdit(foc)
ls.StartIndex = int(floor)
lg.Geom.Scroll.Y = (floor - quo) * rht
ls.ApplyScenePos()
// the row under the pointer is not highlighted while scrolling,
// as it would show other items, until the pointer moves again
ls.hoverRow = -1
if tt, ok := ls.This.(*TreeTable); ok && tt.HideGroupValues {
// the rows have other widgets for the items of groups,
// whose values are hidden, which are new, so they need to be
// styled and laid out
ls.Update()
} else {
ls.UpdateTree()
ls.NeedsRender()
// ls.NeedsLayout() // needed to recompute size after resize
}
if foc != nil {
ls.keepFocusedItem(idx, pos, ed, foc, false)
}
}
func (lg *ListGrid) ScrollValues(d math32.Dims) (maxSize, visSize, visPct float32) {
if d == math32.X {
return lg.Frame.ScrollValues(d)
}
ls := lg.list()
maxSize = float32(max(ls.SliceSize, 1)) * lg.rowHeight
visSize = lg.Geom.Size.Alloc.Content.Y
visPct = visSize / maxSize
return
}
func (lg *ListGrid) updateScroll(idx int) {
if !lg.HasScroll[math32.Y] || lg.Scrolls[math32.Y] == nil {
return
}
sb := lg.Scrolls[math32.Y]
sb.SetValue(float32(idx) * lg.rowHeight)
}
func (lg *ListGrid) updateBackgrounds() {
bg := lg.Styles.ActualBackground
if lg.lastBackground == bg {
return
}
lg.lastBackground = bg
// we take our zebra intensity applied foreground color and then overlay it onto our background color
zclr := colors.WithAF32(colors.ToUniform(lg.Styles.Color), AppearanceSettings.ZebraStripesWeight())
lg.bgStripe = gradient.Apply(bg, func(c color.Color) color.Color {
return colors.AlphaBlend(c, zclr)
})
hclr := colors.WithAF32(colors.ToUniform(lg.Styles.Color), 0.08)
lg.bgHover = gradient.Apply(bg, func(c color.Color) color.Color {
return colors.AlphaBlend(c, hclr)
})
zhclr := colors.WithAF32(colors.ToUniform(lg.Styles.Color), AppearanceSettings.ZebraStripesWeight()+0.08)
lg.bgHoverStripe = gradient.Apply(bg, func(c color.Color) color.Color {
return colors.AlphaBlend(c, zhclr)
})
lg.bgSelect = colors.Scheme.Select.Container
lg.bgSelectStripe = colors.Uniform(colors.AlphaBlend(colors.ToUniform(colors.Scheme.Select.Container), zclr))
lg.bgHoverSelect = colors.Uniform(colors.AlphaBlend(colors.ToUniform(colors.Scheme.Select.Container), hclr))
lg.bgHoverSelectStripe = colors.Uniform(colors.AlphaBlend(colors.ToUniform(colors.Scheme.Select.Container), zhclr))
}
func (lg *ListGrid) rowBackground(sel, stripe, hover bool) image.Image {
switch {
case sel && stripe && hover:
return lg.bgHoverSelectStripe
case sel && stripe:
return lg.bgSelectStripe
case sel && hover:
return lg.bgHoverSelect
case sel:
return lg.bgSelect
case stripe && hover:
return lg.bgHoverStripe
case stripe:
return lg.bgStripe
case hover:
return lg.bgHover
default:
return lg.Styles.ActualBackground
}
}
func (lg *ListGrid) ChildBackground(child Widget) image.Image {
ls := lg.list()
lg.updateBackgrounds()
row, _ := ls.widgetIndex(child)
si := row + ls.StartIndex
return lg.rowBackgroundOf(ls, si, row)
}
func (lg *ListGrid) renderStripes() {
pos := lg.Geom.Pos.Content
sz := lg.Geom.Size.Actual.Content
if lg.visibleRows == 0 || sz.Y == 0 {
return
}
lg.updateBackgrounds()
pc := &lg.Scene.Painter
rows := lg.layout.Shape.Y
cols := lg.layout.Shape.X
st := pos
ls := lg.list()
startIndex := 0
if ls != nil {
startIndex = ls.StartIndex
}
for r := range rows {
si := r + startIndex
ht := lg.rowHeight
miny := st.Y
for c := range cols {
ki := r*cols + c
if ki < lg.NumChildren() {
kw := lg.Child(ki).(Widget).AsWidget()
pyi := math32.Floor(kw.Geom.Pos.Total.Y)
if pyi < miny {
miny = pyi
}
}
}
st.Y = miny
ssz := sz
ssz.Y = ht
sbg := lg.rowBackgroundOf(ls, si, r)
pc.BlitBox(st, ssz, sbg)
st.Y += ht
}
}
// mousePosInGrid returns true if the event mouse position is
// located within the slicegrid. It is false for a nil grid, as that of a
// list before it is first made, which can get events then.
func (lg *ListGrid) mousePosInGrid(pt image.Point) bool {
if lg == nil {
return false
}
ptrel := lg.PointToRelPos(pt)
sz := lg.Geom.ContentBBox.Size()
if lg.visibleRows == 0 || sz.Y == 0 {
return false
}
if ptrel.Y < 0 || ptrel.Y >= sz.Y || ptrel.X < 0 || ptrel.X >= sz.X-50 { // leave margin on rhs around scroll
return false
}
return true
}
// indexFromPixel returns the row, column indexes of given pixel point within grid.
// Takes a scene-level position.
func (lg *ListGrid) indexFromPixel(pt image.Point) (row, col int, isValid bool) {
if !lg.mousePosInGrid(pt) {
return
}
ptf := math32.FromPoint(lg.PointToRelPos(pt))
sz := math32.FromPoint(lg.Geom.ContentBBox.Size())
isValid = true
rows := lg.layout.Shape.Y
cols := lg.layout.Shape.X
st := math32.Vector2{}
st.Y = lg.Geom.Scroll.Y
got := false
for r := range rows {
ht := lg.rowHeight
miny := st.Y
if r > 0 {
for c := range cols {
kwt := lg.Child(r*cols + c)
if kwt == nil {
continue
}
kw := kwt.(Widget).AsWidget()
pyi := math32.Floor(kw.Geom.Pos.Total.Y)
if pyi < miny {
miny = pyi
}
}
}
st.Y = miny
ssz := sz
ssz.Y = ht
if ptf.Y >= st.Y && ptf.Y < st.Y+ssz.Y {
row = r
got = true
break
// todo: col
}
st.Y += ht
}
if !got {
row = rows - 1
}
return
}
func (lg *ListGrid) Render() {
lg.WidgetBase.Render()
lg.renderStripes()
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"fmt"
"image"
"log/slog"
"os"
"cogentcore.org/core/cursors"
"cogentcore.org/core/events"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/system"
"cogentcore.org/core/tree"
)
// newMainStage returns a new MainStage with given type and scene contents.
// Make further configuration choices using Set* methods, which
// can be chained directly after the newMainStage call.
// Use an appropriate Run call at the end to start the Stage running.
func newMainStage(typ StageTypes, sc *Scene) *Stage {
st := &Stage{}
st.setType(typ)
st.setScene(sc)
st.popups = &stages{}
st.popups.main = st
st.Main = st
return st
}
func generateHTMLBody(bd *Body) {
if !system.GenerateHTMLArg() || ExternalParent != nil {
return
}
if GenerateHTML == nil {
fmt.Fprintln(os.Stderr, "-generatehtml: no HTML generator is linked into this app; import _ \"cogentcore.org/core/htmlcore/tohtml\" (the core tool does this when it runs -generatehtml)")
os.Exit(1)
}
wb := NewWidgetBase()
ExternalParent = wb
wb.SetOnChildAdded(func(n tree.Node) {
fmt.Println(GenerateHTML(n.(Widget)))
os.Exit(0)
})
bd.handleExternalParent()
}
// RunMainWindow creates a new main window from the body,
// runs it, starts the app's main loop, and waits for all windows
// to close. It should typically be called once by every app at
// the end of their main function. It can not be called more than
// once for one app. For secondary windows, see [Body.RunWindow].
// If you need to configure the [Stage] further, use [Body.NewWindow]
// and then [Stage.RunMain] on the resulting [Stage].
func (bd *Body) RunMainWindow() {
generateHTMLBody(bd)
if ExternalParent != nil {
bd.handleExternalParent()
return
}
bd.RunWindow()
Wait()
}
// RunMain runs the stage, starts the app's main loop,
// and waits for all windows to close. It can be called instead
// of [Body.RunMainWindow] if extra configuration steps are necessary
// on the [Stage]. It can not be called more than once for one app.
// For secondary stages, see [Stage.Run].
func (st *Stage) RunMain() {
generateHTMLBody(st.Scene.Body)
if ExternalParent != nil {
st.Scene.Body.handleExternalParent()
return
}
st.Run()
Wait()
}
// ExternalParent is a parent widget external to this program.
// If it is set, calls to [Body.RunWindow] before [Wait] and
// calls to [Body.RunMainWindow] and [Stage.RunMain] will add the [Body] to this
// parent instead of creating a new window. It should typically not be
// used by end users; it is used in mvmcore and for pre-rendering apps
// as HTML that can be used as a preview and for SEO purposes.
var ExternalParent Widget
// waitCalled is whether [Wait] has been called. It is used for
// [ExternalParent] logic in [Body.RunWindow].
var waitCalled bool
// RunWindow returns and runs a new [WindowStage] that is placed in
// a new system window on multi-window platforms.
// See [Body.NewWindow] to make a window without running it.
// For the first window of your app, you should typically call
// [Body.RunMainWindow] instead.
func (bd *Body) RunWindow() *Stage {
generateHTMLBody(bd)
if ExternalParent != nil && !waitCalled {
bd.handleExternalParent()
return nil
}
return bd.NewWindow().Run()
}
// handleExternalParent handles [ExternalParent] logic for
// [Body.RunWindow] and [Body.RunMainWindow].
func (bd *Body) handleExternalParent() {
ExternalParent.AsWidget().AddChild(bd)
// we must set the correct scene for each node
for n := range bd.All() {
n.(Widget).AsWidget().Scene = bd.Scene
}
// we must not get additional scrollbars here
bd.Styler(func(s *styles.Style) {
s.Overflow.Set(styles.OverflowVisible)
})
}
// NewWindow returns a new [WindowStage] that is placed in
// a new system window on multi-window platforms.
// You must call [Stage.Run] or [Stage.RunMain] to run the window;
// see [Body.RunWindow] and [Body.RunMainWindow] for versions that
// automatically do so.
func (bd *Body) NewWindow() *Stage {
ms := newMainStage(WindowStage, bd.Scene)
ms.SetNewWindow(true)
return ms
}
func (st *Stage) addSceneParts() {
if st.Type != DialogStage || st.FullWindow || st.NewWindow {
return
}
// TODO: convert to use [Scene.Bars] instead of parts
sc := st.Scene
parts := sc.newParts()
parts.Styler(func(s *styles.Style) {
s.Direction = styles.Column
s.Grow.Set(0, 1)
s.Gap.Zero()
})
mv := NewHandle(parts)
mv.Styler(func(s *styles.Style) {
s.Direction = styles.Column
})
mv.FinalStyler(func(s *styles.Style) {
s.Cursor = cursors.Move
})
mv.SetName("move")
mv.OnChange(func(e events.Event) {
e.SetHandled()
pd := e.PrevDelta()
np := sc.SceneGeom.Pos.Add(pd)
np.X = max(np.X, 0)
np.Y = max(np.Y, 0)
rw := sc.RenderWindow()
sz := rw.SystemWindow.Size()
mx := sz.X - int(sc.SceneGeom.Size.X)
my := sz.Y - int(sc.SceneGeom.Size.Y)
np.X = min(np.X, mx)
np.Y = min(np.Y, my)
sc.SceneGeom.Pos = np
sc.NeedsRender()
})
if st.Resizable {
rsz := NewHandle(parts)
rsz.Styler(func(s *styles.Style) {
s.Direction = styles.Column
s.FillMargin = false
})
rsz.FinalStyler(func(s *styles.Style) {
s.Cursor = cursors.ResizeNWSE
s.Min.Set(units.Em(1))
})
rsz.SetName("resize")
rsz.OnChange(func(e events.Event) {
e.SetHandled()
pd := e.PrevDelta()
np := sc.SceneGeom.Size.Add(pd)
minsz := 100
np.X = max(np.X, minsz)
np.Y = max(np.Y, minsz)
ng := sc.SceneGeom
ng.Size = np
sc.Resize(ng)
})
}
}
// firstWindowStages creates a temporary [stages] for the first window
// to be able to get sizing information prior to having a RenderWindow,
// based on the system App Screen Size. Only adds a RenderContext.
func (st *Stage) firstWindowStages() *stages {
ms := &stages{}
ms.renderContext = newRenderContext()
return ms
}
// targetScreen returns the screen to use for opening a new window
// based on Screen field, currentRenderWindow's screen, and a fallback
// default of Screen 0.
func (st *Stage) targetScreen() *system.Screen {
if st.Screen >= 0 && st.Screen < TheApp.NScreens() {
return TheApp.Screen(st.Screen)
}
if cw := getCurrentRenderWindow(); cw != nil {
return cw.SystemWindow.Screen()
}
return TheApp.Screen(0)
}
// configMainStage does main-stage configuration steps
func (st *Stage) configMainStage() {
sc := st.Scene
if st.NewWindow {
st.FullWindow = true
}
if TheApp.Platform().IsMobile() {
// If we are a new window dialog on a large single-window platform,
// we use a modeless dialog as a substitute.
if st.NewWindow && st.Type == DialogStage && st.Context != nil && st.Context.AsWidget().SizeClass() != SizeCompact {
st.FullWindow = false
st.Modal = false
st.Scrim = false
// Default is to add back button in this situation.
if !st.BackButton.Valid {
st.SetBackButton(true)
}
}
// If we are on mobile, we can never have new windows.
st.NewWindow = false
}
if st.FullWindow || st.NewWindow {
st.Scrim = false
}
sc.makeSceneBars()
sc.updateScene()
}
// runWindow runs a Window with current settings.
func (st *Stage) runWindow() *Stage {
sc := st.Scene
newWindow := st.NewWindow && !TheApp.Platform().IsMobile()
// The current window is read once, as the event loop of a window that
// is closed sets it to another window.
cw := getCurrentRenderWindow()
if cw == nil || newWindow {
// If we have no current render window, we need to be in a new window,
// and we need a *temporary* Mains to get initial pref size.
// A new window also gets its own, which it keeps, so that it never
// uses the render context of another window, which that window can
// be rendering or closing in its own goroutine.
st.setMains(st.firstWindowStages())
} else {
st.setMains(&cw.mains)
}
st.configMainStage()
st.addSceneParts()
sz := st.renderContext.geom.Size
// Mobile windows must take up the whole window
// and thus don't consider pref size.
// Desktop new windows and non-full windows can pref size.
if !TheApp.Platform().IsMobile() &&
(st.NewWindow || !st.FullWindow || cw == nil) {
initSz := sz
sz = st.windowSize(initSz)
// A new window is first sized for the size class of a scene with
// no size yet. If that gives a size of another size class, it is
// sized again for that one, as it is laid out for it once shown.
if sc.RenderWindow() == nil {
if sizeClassOf(sc.dotsToDp(sz).X) != sizeClassOf(sc.dotsToDp(sc.SceneGeom.Size).X) {
sc.sizingSize = sz
sz = st.windowSize(initSz)
sc.sizingSize = image.Point{}
}
}
}
st.storeMains(nil) // reset
if DebugSettings.WindowRenderTrace {
fmt.Println("MainStage.RunWindow: Window Size:", sz)
}
if st.NewWindow || cw == nil {
sc.Resize(math32.Geom2DInt{Pos: st.renderContext.geom.Pos, Size: sz})
win := st.newRenderWindow(st.renderContext)
mainRenderWindows.add(win)
setCurrentRenderWindow(win)
win.goStartEventLoop()
return st
}
if st.Context != nil {
ms := st.Context.AsWidget().Scene.Stage.Mains
msc := ms.top().Scene
sc.SceneGeom.Size = sz
sc.fitInWindow(msc.SceneGeom) // does resize
ms.push(st)
st.setMains(ms)
} else {
ms := &cw.mains
if ms.top() == nil {
// a window without stages fills the window, as on mobile and
// the web, where the window stays when its last stage is closed
// (as in the tests, which then run a window again), with its
// title, as a new window
sc.Resize(math32.Geom2DInt{Size: cw.SystemWindow.Size()})
cw.setTitle(st.Title)
} else {
msc := ms.top().Scene
sc.SceneGeom.Size = sz
sc.fitInWindow(msc.SceneGeom) // does resize
}
ms.push(st)
st.setMains(ms)
}
return st
}
// windowSize returns the size of the window of the stage, based on the
// size of the content of its scene within the given initial size.
func (st *Stage) windowSize(initSz image.Point) image.Point {
sz := st.Scene.contentSize(initSz)
// On offscreen, we don't want any extra space, as we want the smallest
// possible representation of the content.
if TheApp.Platform() == system.Offscreen {
return sz
}
sz = sz.Add(image.Pt(20, 20))
screen := st.targetScreen()
if screen != nil {
st.SetScreen(screen.ScreenNumber)
if st.NewWindow && st.UseMinSize {
// we require windows to be at least 60% and no more than 80% of the
// screen size by default
scsz := screen.PixelSize
sz = image.Pt(max(sz.X, scsz.X*6/10), max(sz.Y, scsz.Y*6/10))
sz = image.Pt(min(sz.X, scsz.X*8/10), min(sz.Y, scsz.Y*8/10))
}
}
return sz
}
// getValidContext ensures that the Context is non-nil and has a valid
// Scene pointer, using the top stage of the current render window if the
// current Context is not valid, or else of the last main window that has one
// (when the current window is closing). If there is none (should not happen),
// then it returns false and the calling function must bail.
func (st *Stage) getValidContext() bool {
if st.Context == nil || st.Context.AsTree().This == nil || st.Context.AsWidget().Scene == nil {
var top *Stage
if cw := getCurrentRenderWindow(); cw != nil {
top = cw.mains.top()
}
if top == nil { // the current window is closing, such as a dialog
ws := mainRenderWindows.windows()
for i := len(ws) - 1; i >= 0 && top == nil; i-- {
top = ws[i].mains.top()
}
}
if top == nil || top.Scene == nil {
slog.Error("Stage.Run: Context is nil and there is no window with a stage, so cannot Run", "Name", st.Name, "Title", st.Title)
return false
}
st.Context = top.Scene
}
return true
}
// runDialog runs a Dialog with current settings.
func (st *Stage) runDialog() *Stage {
if !st.getValidContext() {
return st
}
ctx := st.Context.AsWidget()
// if our main stages are nil, we wait until our context is shown and then try again
if ctx.Scene.Stage == nil || ctx.Scene.Stage.Mains == nil {
ctx.Defer(func() {
st.runDialog()
})
return st
}
ms := ctx.Scene.Stage.Mains
sc := st.Scene
st.configMainStage()
st.addSceneParts()
sc.SceneGeom.Pos = st.Pos
st.setMains(ms) // temporary for prefs
sz := ms.renderContext.geom.Size
if !st.FullWindow || st.NewWindow {
sz = sc.contentSize(sz)
sz = sz.Add(image.Pt(50, 50))
if st.UseMinSize {
// dialogs must be at least 400dp wide by default
minx := int(ctx.Scene.Styles.UnitContext.Dp(400))
sz.X = max(sz.X, minx)
}
if st.MinSize != (math32.Vector2{}) {
uc := &ctx.Scene.Styles.UnitContext
sz.X = max(sz.X, int(math32.Ceil(uc.Dp(st.MinSize.X))))
sz.Y = max(sz.Y, int(math32.Ceil(uc.Dp(st.MinSize.Y))))
if screen := st.targetScreen(); screen != nil && st.NewWindow { // (fits in the screen)
sz = image.Pt(min(sz.X, screen.PixelSize.X*9/10), min(sz.Y, screen.PixelSize.Y*9/10))
}
}
sc.SceneGeom.Pos = sc.SceneGeom.Pos.Sub(sz.Div(2)) // center dialogs by default
sc.Events.startFocusFirst = true // popup dialogs always need focus
screen := st.targetScreen()
if screen != nil {
st.SetScreen(screen.ScreenNumber)
}
}
if DebugSettings.WindowRenderTrace {
slog.Info("MainStage.RunDialog", "size", sz)
}
if st.NewWindow {
st.storeMains(nil)
sc.Resize(math32.Geom2DInt{Pos: st.renderContext.geom.Pos, Size: sz})
st.Type = WindowStage // critical: now is its own window!
sc.SceneGeom.Pos = image.Point{} // ignore pos
win := st.newRenderWindow(nil)
dialogRenderWindows.add(win)
setCurrentRenderWindow(win)
win.goStartEventLoop()
return st
}
sc.SceneGeom.Size = sz
sc.fitInWindow(st.renderContext.geom) // does resize
ms.push(st)
// st.SetMains(ms) // already set
return st
}
// newRenderWindow returns a new [renderWindow] for the stage, with the given
// render context if it is non-nil and a new one otherwise.
func (st *Stage) newRenderWindow(rc *renderContext) *renderWindow {
name := st.Name
title := st.Title
opts := &system.NewWindowOptions{
Title: title,
Icon: appIconImages(),
Size: st.Scene.SceneGeom.Size,
Pos: st.Pos,
StdPixels: false,
Screen: st.Screen,
}
opts.Flags.SetFlag(!st.Resizable, system.FixedSize)
opts.Flags.SetFlag(st.Maximized, system.Maximized)
opts.Flags.SetFlag(st.Fullscreen, system.Fullscreen)
screen := st.targetScreen()
screenName := ""
if screen != nil {
screenName = screen.Name
}
var wgp *windowGeometry
wgp, screen = theWindowGeometrySaver.get(title, screenName)
if wgp != nil {
theWindowGeometrySaver.settingStart()
opts.Screen = screen.ScreenNumber
opts.Size = wgp.Size
opts.Pos = wgp.Pos
opts.StdPixels = false
if w := AllRenderWindows.FindName(title); w != nil { // offset from existing
opts.Pos.X += 20
opts.Pos.Y += 20
}
opts.Flags.SetFlag(wgp.Max, system.Maximized)
}
win := newRenderWindow(name, title, opts)
theWindowGeometrySaver.settingEnd()
if win == nil {
return nil
}
AllRenderWindows.add(win)
// initialize Mains
win.mains.renderWindow = win
if rc == nil {
rc = newRenderContext() // sets defaults according to Screen
}
win.mains.renderContext = rc
// note: win is not yet created by the OS and we don't yet know its actual size
// or dpi.
win.mains.push(st)
st.setMains(&win.mains)
return win
}
// mainHandleEvent handles main stage events
func (st *Stage) mainHandleEvent(e events.Event) {
if st.Scene == nil {
return
}
st.popups.popupHandleEvent(e)
if e.IsHandled() || (st.popups != nil && st.popups.topIsModal()) || st.Scene == nil {
if DebugSettings.EventTrace && e.Type() != events.MouseMove {
fmt.Println("Event handled by popup:", e)
}
return
}
e.SetLocalOff(st.Scene.SceneGeom.Pos)
st.Scene.Events.handleEvent(e)
}
// mainHandleEvent calls mainHandleEvent on relevant stages in reverse order.
func (sm *stages) mainHandleEvent(e events.Event) {
n := sm.stack.Len()
for i := n - 1; i >= 0; i-- {
st := sm.stack.Values[i]
st.mainHandleEvent(e)
if e.IsHandled() || st.Modal || st.FullWindow {
break
}
if st.Type == DialogStage { // modeless dialog, by definition
if e.HasPos() && st.Scene != nil {
b := st.Scene.SceneGeom.Bounds()
if e.WindowPos().In(b) { // don't propagate
break
}
}
}
}
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"image"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/colors"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/keymap"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/system"
"cogentcore.org/core/tree"
)
// StyleMenuScene configures the default styles
// for the given pop-up menu frame with the given parent.
// It should be called on menu frames when they are created.
func StyleMenuScene(msc *Scene) {
msc.Styler(func(s *styles.Style) {
s.Grow.Set(0, 0)
s.Padding.Set(units.Dp(2))
s.Border.Radius = styles.BorderRadiusExtraSmall
s.Background = colors.Scheme.SurfaceContainer
s.BoxShadow = styles.BoxShadow2()
s.Gap.Zero()
})
msc.SetOnChildAdded(func(n tree.Node) {
if bt := AsButton(n); bt != nil {
bt.Type = ButtonMenu
bt.OnKeyChord(func(e events.Event) {
kf := keymap.Of(e.KeyChord())
switch kf {
case keymap.MoveRight:
if bt.openMenu(e) {
e.SetHandled()
}
case keymap.MoveLeft:
// need to be able to use arrow keys to navigate in completer
if msc.Stage.Type != CompleterStage {
msc.Stage.ClosePopup()
e.SetHandled()
}
}
})
return
}
if sp, ok := n.(*Separator); ok {
sp.Styler(func(s *styles.Style) {
s.Direction = styles.Row
})
}
})
}
// newMenuScene constructs a [Scene] for displaying a menu, using the
// given menu constructor function. If no name is provided, it defaults
// to "menu". If no menu items added, returns nil.
func newMenuScene(menu func(m *Scene, pos image.Point), pos image.Point, name ...string) *Scene {
nm := "menu"
if len(name) > 0 {
nm = name[0] + "-menu"
}
msc := NewScene(nm)
StyleMenuScene(msc)
menu(msc, pos)
if !msc.HasChildren() {
return nil
}
hasSelected := false
for cw, cwb := range msc.AllWidgets() {
if cw == msc {
continue
}
if bt := AsButton(cw); bt != nil {
if bt.Menu == nil {
bt.handleClickDismissMenu()
}
}
if !hasSelected && cwb.StateIs(states.Selected) {
// fmt.Println("start focus sel:", cwb)
msc.Events.SetStartFocus(cwb)
hasSelected = true
}
}
if !hasSelected && msc.HasChildren() {
// fmt.Println("start focus first:", msc.Child(0).(Widget))
msc.Events.SetStartFocus(msc.Child(0).(Widget))
}
return msc
}
// NewMenuStage returns a new Menu stage with given scene contents,
// in connection with given widget, which provides key context
// for constructing the menu, at given RenderWindow position
// (e.g., use ContextMenuPos or WinPos method on ctx Widget).
// Make further configuration choices using Set* methods, which
// can be chained directly after the New call.
// Use Run call at the end to start the Stage running.
func NewMenuStage(sc *Scene, ctx Widget, pos image.Point) *Stage {
if sc == nil || !sc.HasChildren() {
return nil
}
st := NewPopupStage(MenuStage, sc, ctx)
if pos != (image.Point{}) {
st.Pos = pos
}
return st
}
// NewMenu returns a new menu stage based on the given menu constructor
// function, in connection with given widget, which provides key context
// for constructing the menu at given RenderWindow position
// (e.g., use ContextMenuPos or WinPos method on ctx Widget).
// Make further configuration choices using Set* methods, which
// can be chained directly after the New call.
// Use Run call at the end to start the Stage running.
func NewMenu(menu func(m *Scene, pos image.Point), ctx Widget, pos image.Point) *Stage {
return NewMenuStage(newMenuScene(menu, pos, ctx.AsTree().Name), ctx, pos)
}
// AddContextMenu adds the given context menu to [WidgetBase.ContextMenus].
// It is the main way that code should modify a widget's context menus.
// Context menu functions are run in reverse order, and separators are
// automatically added between each context menu function. [Scene.ContextMenus]
// apply to all widgets in the scene.
func (wb *WidgetBase) AddContextMenu(menu func(m *Scene, pos image.Point)) {
wb.ContextMenus = append(wb.ContextMenus, menu)
}
// applyContextMenus adds the [WidgetBase.ContextMenus] and [Scene.ContextMenus]
// to the given menu scene in reverse order. It also adds separators between each
// context menu function.
func (wb *WidgetBase) applyContextMenus(m *Scene, pos image.Point) {
do := func(cms []func(m *Scene, pos image.Point)) {
for ri := len(cms) - 1; ri >= 0; ri-- {
cm := cms[ri]
if m.NumChildren() > 0 {
NewSeparator(m)
}
cm(m, pos)
}
}
do(wb.ContextMenus)
if wb.This != wb.Scene {
do(wb.Scene.ContextMenus)
}
}
// ContextMenuPos returns the default position for the context menu
// upper left corner. The event will be from a mouse ContextMenu
// event if non-nil: should handle both cases.
func (wb *WidgetBase) ContextMenuPos(e events.Event) image.Point {
if e != nil && e.HasPos() {
return e.WindowPos()
}
return wb.winPos(.5, .5) // center, such as for the keyboard
}
func (wb *WidgetBase) handleWidgetContextMenu() {
wb.On(events.ContextMenu, func(e events.Event) {
wi := wb.This.(Widget)
wi.ShowContextMenu(e)
})
}
func (wb *WidgetBase) ShowContextMenu(e events.Event) {
e.SetHandled() // always
if wb == nil || wb.This == nil {
return
}
wi := wb.This.(Widget)
nm := NewMenu(wi.AsWidget().applyContextMenus, wi, wi.ContextMenuPos(e))
if nm == nil { // no items
return
}
nm.Run()
}
// NewMenuFromStrings constructs a new menu from given list of strings,
// calling the given function with the index of the selected string.
// if string == sel, that menu item is selected initially.
func NewMenuFromStrings(strs []string, sel string, fun func(idx int)) *Scene {
return newMenuScene(func(m *Scene, pos image.Point) {
for i, s := range strs {
b := NewButton(m).SetText(s)
b.OnClick(func(e events.Event) {
fun(i)
})
if s == sel {
b.SetSelected(true)
}
}
}, image.Point{})
}
var (
// webCanInstall is whether the app can be installed on the web platform
webCanInstall bool
// webInstall installs the app on the web platform
webInstall func()
)
// MenuSearcher is an interface that [Widget]s can implement
// to customize the items of the menu search chooser created
// by the default [Scene] context menu in [Scene.MenuSearchDialog].
type MenuSearcher interface {
MenuSearch(items *[]ChooserItem)
}
// NewWindowFunc is, if set, a function that returns the body of a new window of the app, as
// for its main window, made from the window of the given scene, which it
// can take settings from, as a directory. The new window is run with the
// size of the window from which it is made, below and to the right of it,
// as in web browsers. It is called
// by the New window item at the top of the Window menu of the standard
// context menu of scenes, and by the [keymap.New] key when no widget handles
// it, on desktop platforms.
var NewWindowFunc func(from *Scene) *Body
// canNewWindow returns whether a new window of the app can be made
// (see [NewWindowFunc]).
func canNewWindow() bool {
return NewWindowFunc != nil && !TheApp.Platform().IsMobile() && TheApp.Platform() != system.Web
}
// newWindowFrom makes and runs a new window of the app (see [NewWindowFunc])
// from the window of the given scene.
func newWindowFrom(sc *Scene) {
bd := NewWindowFunc(sc)
if bd == nil {
return
}
bd.RunWindow()
src := sc.RenderWindow()
win := bd.Scene.RenderWindow()
if src == nil || src.SystemWindow == nil || win == nil || win.SystemWindow == nil {
return
}
off := image.Pt(30, 30) // (in window manager units)
win.SystemWindow.SetGeometry(false, src.SystemWindow.Position(nil).Add(off), src.SystemWindow.Size(), nil)
win.SystemWindow.Raise()
}
// standardContextMenu adds standard context menu items for the [Scene].
func (sc *Scene) standardContextMenu(m *Scene, pos image.Point) { //types:add
sdesc := "Search for text within all widgets in current scene."
NewButton(m).SetText("Search").SetIcon(icons.Search).SetKey(keymap.Find).SetTooltip(sdesc).OnClick(func(e events.Event) {
Search(sc, LastSearch, LastUseCase)
})
msdesc := "Search for menu buttons and other app actions"
NewButton(m).SetText("Menu search").SetIcon(icons.Search).SetKey(keymap.Menu).SetTooltip(msdesc).OnClick(func(e events.Event) {
sc.MenuSearchDialog("Menu search", msdesc)
})
if AppHelp != nil {
NewButton(m).SetText("Help").SetIcon(icons.Help).SetTooltip("The documentation of " + TheApp.Name()).OnClick(func(e events.Event) {
AppHelp(sc)
})
}
NewButton(m).SetText("About").SetIcon(icons.Info).OnClick(func(e events.Event) {
d := NewBody(TheApp.Name())
d.Styler(func(s *styles.Style) {
s.CenterAll()
})
NewText(d).SetType(TextHeadlineLarge).SetText(TheApp.Name())
if AppIcon != "" {
errors.Log(NewSVG(d).ReadString(AppIcon))
}
if AppAbout != "" {
NewText(d).SetText(AppAbout)
}
NewText(d).SetText("App version: " + system.AppVersion)
NewText(d).SetText("Core version: " + system.CoreVersion)
d.AddOKOnly().NewDialog(sc).SetDisplayTitle(false).Run()
})
NewFuncButton(m).SetFunc(SettingsWindow).SetText("Settings").SetIcon(icons.Settings).SetShortcut("Command+,")
if webCanInstall {
icon := icons.InstallDesktop
if TheApp.SystemPlatform().IsMobile() {
icon = icons.InstallMobile
}
NewFuncButton(m).SetFunc(webInstall).SetText("Install").SetIcon(icon).SetTooltip("Install this app to your device as a Progressive Web App (PWA)")
}
NewButton(m).SetText("Inspect").SetIcon(icons.Edit).SetShortcut("Command+Shift+I").
SetTooltip("Developer tools for inspecting the content of the app").
OnClick(func(e events.Event) {
InspectorWindow(sc)
})
// No window menu on mobile platforms
if TheApp.Platform().IsMobile() && TheApp.Platform() != system.Web {
return
}
NewButton(m).SetText("Window").SetMenu(func(m *Scene, pos image.Point) {
if canNewWindow() {
NewButton(m).SetText("New window").SetIcon(icons.NewWindow).SetKey(keymap.New).
OnClick(func(e events.Event) {
newWindowFrom(sc)
})
NewSeparator(m)
}
if sc.IsFullscreen() {
NewButton(m).SetText("Exit fullscreen").SetIcon(icons.Fullscreen).OnClick(func(e events.Event) {
sc.SetFullscreen(false)
})
} else {
NewButton(m).SetText("Fullscreen").SetIcon(icons.Fullscreen).OnClick(func(e events.Event) {
sc.SetFullscreen(true)
})
}
// Only do fullscreen on web
if TheApp.Platform() == system.Web {
return
}
NewButton(m).SetText("Focus next").SetIcon(icons.CenterFocusStrong).
SetKey(keymap.WinFocusNext).OnClick(func(e events.Event) {
AllRenderWindows.focusNext()
})
NewButton(m).SetText("Minimize").SetIcon(icons.Minimize).
OnClick(func(e events.Event) {
win := sc.RenderWindow()
if win != nil {
win.minimize()
}
})
NewSeparator(m)
NewButton(m).SetText("Close window").SetIcon(icons.Close).SetKey(keymap.WinClose).
OnClick(func(e events.Event) {
win := sc.RenderWindow()
if win != nil {
win.closeReq()
}
})
quit := NewButton(m).SetText("Quit").SetIcon(icons.Close).SetShortcut("Command+Q")
quit.OnClick(func(e events.Event) {
go TheApp.QuitReq()
})
})
}
// MenuSearchDialog runs the menu search dialog for the scene with
// the given title and description text. It includes scenes, toolbar buttons,
// and [MenuSearcher]s.
func (sc *Scene) MenuSearchDialog(title, text string) {
d := NewBody(title)
NewText(d).SetType(TextSupporting).SetText(text)
w := NewChooser(d).SetEditable(true).SetIcon(icons.Search)
w.Styler(func(s *styles.Style) {
s.Grow.Set(1, 0)
})
w.AddItemsFunc(func() {
// The stages of other windows are read under the lock of their
// stack, and raised in the event loop of their window.
for _, rw := range AllRenderWindows.windows() {
for _, st := range rw.mains.list() {
// we do not include ourself
if st == sc.Stage || st == w.Scene.Stage {
continue
}
w.Items = append(w.Items, ChooserItem{
Text: st.Title,
Icon: icons.Toolbar,
Tooltip: "Show " + st.Title,
Func: func() {
if stsc := st.Scene; stsc != nil {
stsc.runInWindow(w.AsWidget(), st.raise)
}
},
})
}
}
})
w.AddItemsFunc(func() {
addButtonItems(&w.Items, sc, sc, "")
tmps := menuSearchScene(sc)
sc.applyContextMenus(tmps, image.Point{})
addButtonItems(&w.Items, sc, tmps, "")
})
w.OnFinal(events.Change, func(e events.Event) {
d.Close()
})
d.AddBottomBar(func(bar *Frame) {
d.AddCancel(bar)
})
d.RunDialog(sc)
}
// menuSearchScene returns a new scene for the items of a menu found by the
// menu search of the given scene, which is not shown, but belongs to the
// window of the scene, as a menu of it does, so that the dialogs and other
// popups of its buttons, which use them as their context, are shown there.
func menuSearchScene(sc *Scene) *Scene {
m := NewScene()
main := sc.Stage
if main != nil && main.Main != nil { // (a popup)
main = main.Main
}
if main != nil && main.Mains != nil {
NewPopupStage(MenuStage, m, sc).setPopups(main)
}
return m
}
// addButtonItems adds to the given items all of the buttons under
// the given parent, for the menu search of the given scene. It navigates
// through button menus to find other buttons using a recursive approach
// that updates path with context about the original button menu.
// Consumers of this function should typically set path to "".
func addButtonItems(items *[]ChooserItem, sc *Scene, parent tree.Node, path string) {
for n := range parent.AsTree().All() {
if ms, ok := n.(MenuSearcher); ok {
ms.MenuSearch(items)
}
bt := AsButton(n)
if bt == nil || bt.IsDisabled() {
continue
}
_, isTb := bt.Parent.(*Toolbar)
_, isSc := bt.Parent.(*Scene)
if !isTb && !isSc {
continue
}
if bt.Text == "Menu search" {
continue
}
label := bt.Text
if label == "" {
// the tooltip of a button with only an icon can be long, so a
// func button uses the name of its function
if fb, ok := n.(*FuncButton); ok {
label = fb.Label()
} else {
label = bt.Tooltip
}
}
if bt.HasMenu() {
tmps := menuSearchScene(sc)
bt.Menu(tmps, image.Point{})
npath := path
if npath != "" {
npath += " > "
}
if bt.Name != "overflow-menu" {
npath += label
}
addButtonItems(items, sc, tmps, npath)
continue
}
if path != "" {
label = path + " > " + label
}
*items = append(*items, ChooserItem{
Text: label,
Icon: bt.Icon,
Tooltip: bt.Tooltip,
Func: func() {
bt.Send(events.Click)
},
})
}
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"fmt"
"image"
"cogentcore.org/core/colors"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/htmltext"
"cogentcore.org/core/text/shaped"
"cogentcore.org/core/text/text"
)
// Meter is a widget that renders a current value on as a filled
// bar/circle/semicircle relative to a minimum and maximum potential
// value.
type Meter struct {
WidgetBase
// Type is the styling type of the meter.
Type MeterTypes
// Value is the current value of the meter.
// It defaults to 0.5.
Value float32
// Min is the minimum possible value of the meter.
// It defaults to 0.
Min float32
// Max is the maximum possible value of the meter.
// It defaults to 1.
Max float32
// Text, for [MeterCircle] and [MeterSemicircle], is the
// text to render inside of the circle/semicircle.
Text string
// ValueColor is the image color that will be used to
// render the filled value bar. It should be set in a Styler.
ValueColor image.Image
// Width, for [MeterCircle] and [MeterSemicircle], is the
// width of the circle/semicircle. It should be set in a Styler.
Width units.Value
}
// MeterTypes are the different styling types of [Meter]s.
type MeterTypes int32 //enums:enum -trim-prefix Meter
const (
// MeterLinear indicates to render a meter that goes in a straight,
// linear direction, either horizontal or vertical, as specified by
// [styles.Style.Direction].
MeterLinear MeterTypes = iota
// MeterCircle indicates to render the meter as a circle.
MeterCircle
// MeterSemicircle indicates to render the meter as a semicircle.
MeterSemicircle
)
func (m *Meter) WidgetValue() any { return &m.Value }
func (m *Meter) Init() {
m.WidgetBase.Init()
m.Value = 0.5
m.Max = 1
m.Styler(func(s *styles.Style) {
m.ValueColor = colors.Scheme.Primary.Base
s.Background = colors.Scheme.SurfaceVariant
s.Border.Radius = styles.BorderRadiusFull
s.SetTextWrap(false)
})
m.FinalStyler(func(s *styles.Style) {
switch m.Type {
case MeterLinear:
if s.Direction == styles.Row {
s.Min.Set(units.Dp(320), units.Dp(8))
} else {
s.Min.Set(units.Dp(8), units.Dp(320))
}
case MeterCircle:
s.Min.Set(units.Dp(128))
m.Width.Dp(8)
s.Font.Size.Dp(32)
s.Text.LineHeight = 40.0 / 32
s.Text.Align = text.Center
s.Text.AlignV = text.Center
case MeterSemicircle:
s.Min.Set(units.Dp(112), units.Dp(64))
m.Width.Dp(16)
s.Font.Size.Dp(22)
s.Text.LineHeight = 28.0 / 22
s.Text.Align = text.Center
s.Text.AlignV = text.Center
}
})
}
func (m *Meter) Style() {
m.WidgetBase.Style()
m.Width.ToDots(&m.Styles.UnitContext)
}
func (m *Meter) WidgetTooltip(pos image.Point) (string, image.Point) {
res := m.Tooltip
if res != "" {
res += " "
}
res += fmt.Sprintf("(value: %.4g, minimum: %g, maximum: %g)", m.Value, m.Min, m.Max)
return res, m.DefaultTooltipPos()
}
func (m *Meter) Render() {
pc := &m.Scene.Painter
st := &m.Styles
prop := (m.Value - m.Min) / (m.Max - m.Min)
if m.Type == MeterLinear {
m.RenderStandardBox()
if m.ValueColor != nil {
dim := m.Styles.Direction.Dim()
size := m.Geom.Size.Actual.Content.MulDim(dim, prop)
pc.Fill.Color = m.ValueColor
m.RenderBoxGeom(m.Geom.Pos.Content, size, st.Border)
}
return
}
pc.Stroke.Width = m.Width
sw := m.Width.Dots
pos := m.Geom.Pos.Content.AddScalar(sw / 2)
size := m.Geom.Size.Actual.Content.SubScalar(sw)
pc.Fill.Color = colors.Scheme.Surface
var txt *shaped.Lines
var toff math32.Vector2
if m.Text != "" {
sty, tsty := m.Styles.NewRichText()
tx, _ := htmltext.HTMLToRich([]byte(m.Text), sty, nil)
txt = m.Scene.TextShaper().WrapLines(tx, sty, tsty, size)
toff = txt.Bounds.Size().DivScalar(2)
}
if m.Type == MeterCircle {
r := size.DivScalar(2)
c := pos.Add(r)
pc.EllipticalArc(c.X, c.Y, r.X, r.Y, 0, 0, 2*math32.Pi)
pc.Stroke.Color = st.Background
pc.Draw()
if m.ValueColor != nil {
pc.EllipticalArc(c.X, c.Y, r.X, r.Y, 0, -math32.Pi/2, prop*2*math32.Pi-math32.Pi/2)
pc.Stroke.Color = m.ValueColor
pc.Draw()
}
if txt != nil {
pc.DrawText(txt, c.Sub(toff))
}
return
}
r := size.Mul(math32.Vec2(0.5, 1))
c := pos.Add(r)
pc.EllipticalArc(c.X, c.Y, r.X, r.Y, 0, math32.Pi, 2*math32.Pi)
pc.Stroke.Color = st.Background
pc.Draw()
if m.ValueColor != nil {
pc.EllipticalArc(c.X, c.Y, r.X, r.Y, 0, math32.Pi, (1+prop)*math32.Pi)
pc.Stroke.Color = m.ValueColor
pc.Draw()
}
if txt != nil {
pc.DrawText(txt, c.Sub(size.Mul(math32.Vec2(0, 0.3))).Sub(toff))
}
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"image"
"path/filepath"
"cogentcore.org/core/base/fileinfo/apps"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
)
// OpenWithMenuItems adds the context menu items for opening the given file,
// which is not a directory, with the apps of the system, as in the
// [FilePicker] and the file tree: Open with, a menu of the apps that can
// open it, with the default one first, and Other..., to choose from all of
// the apps, and Change default app. It adds nothing on platforms that do
// not support that (see [apps.For]).
func OpenWithMenuItems(m *Scene, file string) {
as, err := apps.For(file)
if err != nil {
return // not supported
}
NewButton(m).SetText("Open with").SetIcon(icons.Open).
SetMenu(func(m *Scene, pos image.Point) {
ctx := mainContext(m)
for _, app := range as {
text := app.Name
if app.Default {
text += " (default)"
}
NewButton(m).SetText(text).OnClick(func(e events.Event) {
ErrorSnackbar(ctx, apps.OpenWith(file, app))
})
}
if len(as) > 0 {
NewSeparator(m)
}
NewButton(m).SetText(otherApps).
SetTooltip("Open the file with one of all of the apps").
OnClick(func(e events.Event) {
openWithOther(m, file)
})
}).SetTooltip("Open the file with one of the apps that can open it")
NewButton(m).SetText("Change default app").SetIcon(icons.Edit).
SetTooltip("Change the default app for this type of file").
OnClick(func(e events.Event) {
changeDefaultApp(m, file, as)
})
}
// mainContext returns the scene of the main stage of the given context,
// which outlasts a menu the context is in.
func mainContext(ctx Widget) Widget {
if st := ctx.AsWidget().Scene.Stage; st != nil && st.Main != nil && st.Main.Scene != nil {
return st.Main.Scene
}
return ctx
}
// otherApps is the text of the choices of all of the apps.
const otherApps = "Other..."
// newAppChooser makes a chooser of the given apps, with an Other... item
// at the end, which replaces them with all of the apps, or of all of the
// apps if there are none. It can be typed in to find an app.
func newAppChooser(parent Widget, as []apps.App) *Chooser {
ch := NewChooser(parent).SetEditable(true)
setApps := func(as []apps.App, other bool) {
ch.Items = ch.Items[:0]
for _, app := range as {
ch.Items = append(ch.Items, ChooserItem{Value: app, Text: app.Name})
}
if other {
ch.Items = append(ch.Items, ChooserItem{Value: otherApps, Text: otherApps,
Tooltip: "Choose from all of the apps"})
}
if len(ch.Items) > 0 {
ch.SetCurrentIndex(0) // the default, if any, is first
}
}
all := func() {
all, err := apps.All()
ErrorSnackbar(ch, err)
setApps(all, false)
}
if len(as) == 0 {
all()
} else {
setApps(as, true)
}
ch.OnChange(func(e events.Event) {
if ch.CurrentItem.Value == otherApps {
all()
ch.Update()
}
})
return ch
}
// chosenApp returns the app chosen in the given chooser of [newAppChooser].
func chosenApp(ch *Chooser) (apps.App, bool) {
app, ok := ch.CurrentItem.Value.(apps.App)
return app, ok
}
// openWithOther shows a dialog to choose one of all of the apps
// to open the given file with.
func openWithOther(ctx Widget, file string) {
ctx = mainContext(ctx)
d := NewBody("Open with")
NewText(d).SetType(TextSupporting).
SetText("The app to open " + filepath.Base(file) + " with: it may not open this type of file")
ch := newAppChooser(d, nil)
d.AddBottomBar(func(bar *Frame) {
d.AddCancel(bar)
d.AddOK(bar).SetText("Open").OnClick(func(e events.Event) {
if app, ok := chosenApp(ch); ok {
ErrorSnackbar(ctx, apps.OpenWith(file, app))
}
})
})
d.RunDialog(ctx)
}
// changeDefaultApp shows a dialog to choose the default app for the type of
// the given file from the given apps that can open it, or from all of them.
func changeDefaultApp(ctx Widget, file string, as []apps.App) {
ctx = mainContext(ctx)
d := NewBody("Default app")
typ := filepath.Ext(file)
if typ == "" {
typ = filepath.Base(file)
}
NewText(d).SetType(TextSupporting).
SetText("The default app for files like " + typ + ", which opens them in all apps")
ch := newAppChooser(d, as)
d.AddBottomBar(func(bar *Frame) {
d.AddCancel(bar)
d.AddOK(bar).SetText("Set default").OnClick(func(e events.Event) {
if app, ok := chosenApp(ch); ok {
ErrorSnackbar(ctx, apps.SetDefault(file, app))
}
})
})
d.RunDialog(ctx)
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"fmt"
"cogentcore.org/core/styles"
)
// Pages is a frame that can easily swap its content between that of
// different possible pages.
type Pages struct {
Frame
// Page is the currently open page.
Page string
// Pages is a map of page names to functions that configure a page.
Pages map[string]func(pg *Pages) `set:"-"`
// page is the currently rendered page.
page string
}
func (pg *Pages) Init() {
pg.Frame.Init()
pg.Pages = map[string]func(pg *Pages){}
pg.Styler(func(s *styles.Style) {
s.Direction = styles.Column
s.Grow.Set(1, 1)
})
pg.Updater(func() {
if len(pg.Pages) == 0 {
return
}
if pg.page == pg.Page {
return
}
pg.DeleteChildren()
fun, ok := pg.Pages[pg.Page]
if !ok {
ErrorSnackbar(pg, fmt.Errorf("page %q not found", pg.Page))
return
}
pg.page = pg.Page
fun(pg)
pg.DeferShown()
})
}
// AddPage adds a page with the given name and configuration function.
// If [Pages.Page] is currently unset, it will be set to the given name.
func (pg *Pages) AddPage(name string, f func(pg *Pages)) {
pg.Pages[name] = f
if pg.Page == "" {
pg.Page = name
}
}
// Open sets the current page to the given name and updates the display.
// In comparison, [Pages.SetPage] does not update the display and should typically
// only be called at the start.
func (pg *Pages) Open(name string) *Pages {
pg.SetPage(name)
pg.Update()
return pg
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"image"
"slices"
"time"
"cogentcore.org/core/events"
)
// NewPopupStage returns a new PopupStage with given type and scene contents.
// The given context widget must be non-nil.
// Make further configuration choices using Set* methods, which
// can be chained directly after the NewPopupStage call.
// Use Run call at the end to start the Stage running.
func NewPopupStage(typ StageTypes, sc *Scene, ctx Widget) *Stage {
ctx = nonNilContext(ctx)
st := &Stage{}
st.setType(typ)
st.setScene(sc)
st.Context = ctx
st.Pos = ctx.ContextMenuPos(nil)
sc.Stage = st
// note: not setting all the connections until run
return st
}
// runPopup runs a popup-style Stage in context widget's popups.
func (st *Stage) runPopup() *Stage {
if !st.getValidContext() { // doesn't even have a scene
return st
}
ctx := st.Context.AsWidget()
// if our context stage is nil, we wait until
// our context is shown and then try again
if ctx.Scene.Stage == nil {
ctx.Defer(func() {
st.runPopup()
})
return st
}
// a context in a deleted stage, such as a closed menu, uses the
// current window instead
if ctx.Scene.Stage.Main == nil {
rw := getCurrentRenderWindow()
if rw == nil || rw.mains.top() == nil {
return st
}
st.Context = rw.mains.top().Scene
ctx = st.Context.AsWidget()
}
if st.Type == SnackbarStage {
st.Scene.makeSceneBars()
}
st.Scene.updateScene()
sc := st.Scene
ms := ctx.Scene.Stage.Main
msc := ms.Scene
if st.Type == SnackbarStage {
// only one snackbar can exist
ms.popups.popDeleteType(SnackbarStage)
}
ms.popups.push(st)
st.setPopups(ms) // sets all pointers
maxGeom := msc.SceneGeom
winst := ms.Mains.windowStage()
usingWinGeom := false
if winst != nil && winst.Scene != nil && winst.Scene != msc {
usingWinGeom = true
maxGeom = winst.Scene.SceneGeom // use the full window if possible
}
// original size and position, which is that of the context widget / location for a tooltip
osz := sc.SceneGeom.Size
opos := sc.SceneGeom.Pos
sc.SceneGeom.Size = maxGeom.Size
sc.SceneGeom.Pos = st.Pos
sz := sc.contentSize(maxGeom.Size)
// a menu is at its position (as below the text field of a completer),
// in the window, even if it is bigger than a dialog that it is for
bigPopup := st.Type != MenuStage && usingWinGeom && 4*sz.X*sz.Y > 3*msc.SceneGeom.Size.X*msc.SceneGeom.Size.Y // reasonable fraction
scrollWd := int(sc.Styles.ScrollbarWidth.Dots)
fontHt := sc.Styles.Font.FontHeight()
if fontHt == 0 {
fontHt = 16
}
switch st.Type {
case MenuStage:
sz.X += scrollWd * 2
maxht := int(float32(AppearanceSettings.MenuMax) * fontHt)
sz.Y = min(maxht, sz.Y)
if sz.X > maxGeom.Size.X { // room for the horizontal scroll bar
sz.Y += scrollWd
}
case SnackbarStage:
b := msc.SceneGeom.Bounds()
// Go in the middle [(max - min) / 2], and then subtract
// half of the size because we are specifying starting point,
// not the center. This results in us being centered.
sc.SceneGeom.Pos.X = (b.Max.X - b.Min.X - sz.X) / 2
// get enough space to fit plus 10 extra pixels of margin
sc.SceneGeom.Pos.Y = b.Max.Y - sz.Y - 10
case TooltipStage:
sc.SceneGeom.Pos.X = opos.X
// default to tooltip above element
ypos := max(opos.Y-sz.Y-10, 0)
// however, if we are within 10 pixels of the element,
// we put the tooltip below it instead of above it
maxy := ypos + sz.Y
if maxy > opos.Y-10 {
ypos = opos.Add(osz).Y + 10
}
sc.SceneGeom.Pos.Y = ypos
}
sc.SceneGeom.Size = sz
if bigPopup { // we have a big popup -- make it not cover the original window;
sc.fitInWindow(maxGeom) // does resize
// reposition to be as close to top-right of main scene as possible
tpos := msc.SceneGeom.Pos
tpos.X += msc.SceneGeom.Size.X
if tpos.X+sc.SceneGeom.Size.X > maxGeom.Size.X { // favor left side instead
tpos.X = max(msc.SceneGeom.Pos.X-sc.SceneGeom.Size.X, 0)
}
bpos := tpos.Add(sc.SceneGeom.Size)
if bpos.X > maxGeom.Size.X {
tpos.X -= bpos.X - maxGeom.Size.X
}
if bpos.Y > maxGeom.Size.Y {
tpos.Y -= bpos.Y - maxGeom.Size.Y
}
if tpos.X < 0 {
tpos.X = 0
}
if tpos.Y < 0 {
tpos.Y = 0
}
sc.SceneGeom.Pos = tpos
} else if st.Type == MenuStage {
sc.fitInWindow(maxGeom)
} else {
sc.fitInWindow(msc.SceneGeom)
}
sc.showIter = 0
if st.Timeout > 0 {
// The timer runs outside of the event loop, so the popup is deleted
// with the lock of the render context that it was run in.
rc := st.renderContext
time.AfterFunc(st.Timeout, func() {
rc.Lock()
defer rc.Unlock()
if st.Main == nil {
return
}
st.popups.deleteStage(st)
})
}
return st
}
// ClosePopup closes this stage as a popup, returning whether it was closed.
func (st *Stage) ClosePopup() bool {
// NOTE: this is critical for Completer to not crash due to async closing
if st.Main == nil || st.popups == nil || st.Mains == nil {
return false
}
return st.popups.deleteStage(st)
}
// closePopupAndBelow closes this stage as a popup,
// and all those immediately below it of the same type.
// It returns whether it successfully closed popups.
func (st *Stage) closePopupAndBelow() bool {
// NOTE: this is critical for Completer to not crash due to async closing
if st.Main == nil || st.popups == nil || st.Mains == nil {
return false
}
return st.popups.deleteStageAndBelow(st)
}
func (st *Stage) popupHandleEvent(e events.Event) {
if st.Scene == nil {
return
}
if e.IsHandled() {
return
}
e.SetLocalOff(st.Scene.SceneGeom.Pos)
// fmt.Println("pos:", evi.Pos(), "local:", evi.LocalPos())
st.Scene.Events.handleEvent(e)
}
// topIsModal returns true if there is a Top PopupStage and it is Modal.
func (sm *stages) topIsModal() bool {
top := sm.top()
if top == nil {
return false
}
return top.Modal
}
// popupHandleEvent processes Popup events.
// requires outer RenderContext mutex.
func (sm *stages) popupHandleEvent(e events.Event) {
top := sm.top()
if top == nil {
return
}
ts := top.Scene
// we must get the top stage that does not ignore events
if top.ignoreEvents {
var ntop *Stage
for i := sm.stack.Len() - 1; i >= 0; i-- {
s := sm.stack.Values[i]
if !s.ignoreEvents {
ntop = s
break
}
}
if ntop == nil {
return
}
top = ntop
ts = top.Scene
}
if e.HasPos() {
pos := e.WindowPos()
if top.pressOpened && sm.pressOpenedEvent(top, e) {
e.SetHandled()
return
}
// fmt.Println("pos:", pos, "top geom:", ts.SceneGeom)
if pos.In(ts.SceneGeom.Bounds()) || ts.Events.capturesMouse(e) {
top.popupHandleEvent(e)
e.SetHandled()
return
}
if sm.parentMenuPress(top, e) {
e.SetHandled()
return
}
if top.ClickOff && e.Type() == events.MouseUp {
top.closePopupAndBelow()
}
if top.Modal { // absorb any other events!
e.SetHandled()
return
}
// otherwise not Handled, so pass on to first lower stage
// that accepts events and is in bounds
for i := sm.stack.Len() - 1; i >= 0; i-- {
s := sm.stack.Values[i]
ss := s.Scene
if !s.ignoreEvents && pos.In(ss.SceneGeom.Bounds()) {
s.popupHandleEvent(e)
e.SetHandled()
return
}
}
} else { // typically focus, so handle even if not in bounds
top.popupHandleEvent(e) // could be set as Handled or not
}
}
// pressOpenedEvent handles the given event for the given top menu stage,
// which was opened by pressing the mouse button on its context button,
// which is still down (see [Stage.pressOpened]), returning whether it
// handled it. Dragging over the menus hovers their items: over an item with
// a submenu, the submenu opens, and over a menu below the top one (such as
// the parent of a submenu), the menus above it close. Releasing the mouse
// button over an item clicks it, other than one with a submenu, which stays
// open. Releasing it over the context button is a click on it, which leaves
// the menu open, and releasing it anywhere else closes the menus.
func (sm *stages) pressOpenedEvent(top *Stage, e events.Event) bool {
if e.Type() != events.MouseDrag && e.Type() != events.MouseUp {
return false
}
pos := e.WindowPos()
chain := sm.menuChain()
if len(chain) == 0 {
return false
}
root := chain[len(chain)-1] // (opened by the pressed button)
// the menu under the pointer, if any, and the item there
idx := slices.IndexFunc(chain, func(s *Stage) bool {
return s.Scene != nil && pos.In(s.Scene.SceneGeom.Bounds())
})
var under *Stage
var item *Button
if idx >= 0 {
under = chain[idx]
item = menuButtonAt(under, pos)
}
// whether the submenu above the menu under the pointer is that of the item
subOpen := idx > 0 && item != nil && chain[idx-1].Context != nil && chain[idx-1].Context.AsWidget() == item.AsWidget()
if e.Type() == events.MouseDrag {
if under == nil {
return true
}
n := idx
if subOpen {
n--
}
for _, s := range chain[:n] {
sm.deleteStage(s)
}
chain[n].pressOpened = true
under.popupHandleEvent(mouseClone(e, events.MouseMove))
if item != nil && item.HasMenu() && !subOpen {
if st := item.openMenuStage(e); st != nil {
st.pressOpened = true
}
}
return true
}
for _, s := range chain {
s.pressOpened = false
}
// the context button gets the release, ending its press
// (a click on it if it is over it, which leaves the menu open)
var ctx *WidgetBase
if root.Context != nil {
ctx = root.Context.AsWidget()
}
if ctx != nil && ctx.Scene != nil && ctx.Scene.Stage != nil {
ctx.Scene.Stage.popupHandleEvent(mouseClone(e, events.MouseUp))
}
// a release where it was pressed is a click on the context button,
// even over the menu, which can overlap it
d := pos.Sub(e.WindowStartPos())
dragged := max(abs(d.X), abs(d.Y)) > TimingSettings.DragStartDistance
switch {
case !dragged:
case under != nil:
if item != nil && item.HasMenu() { // its submenu stays open
return true
}
for _, s := range chain[:idx] {
sm.deleteStage(s)
}
// a click on the item
under.popupHandleEvent(mouseClone(e, events.MouseDown))
under.popupHandleEvent(e)
case ctx == nil || !ctx.posInScBBox(pos.Sub(ctx.Scene.SceneGeom.Pos)):
top.closePopupAndBelow()
}
return true
}
// menuChain returns the menu stages at the top of the stack, from the top
// one down: a menu and its submenus, skipping the stages that ignore
// events, such as the tooltip of an item.
func (sm *stages) menuChain() []*Stage {
var chain []*Stage
for i := sm.stack.Len() - 1; i >= 0; i-- {
s := sm.stack.Values[i]
if s.ignoreEvents {
continue
}
if s.Type != MenuStage {
break
}
chain = append(chain, s)
}
return chain
}
// menuButtonAt returns the button of the given menu stage at the given
// position in the window, or nil if there is none.
func menuButtonAt(st *Stage, pos image.Point) *Button {
var bt *Button
for cw, cwb := range st.Scene.AllWidgets() {
if b := AsButton(cw); b != nil && pos.In(cwb.winBBox()) {
bt = b
break
}
}
return bt
}
// parentMenuPress handles a mouse press on a menu below the given top menu
// stage, in the menus of the same chain (such as the menu of a submenu),
// returning whether it did: the menus above that menu are closed, and it
// gets the press, so that its items can be clicked, such as to open
// another submenu.
func (sm *stages) parentMenuPress(top *Stage, e events.Event) bool {
if top.Type != MenuStage || e.Type() != events.MouseDown {
return false
}
pos := e.WindowPos()
chain := sm.menuChain()
for i := 1; i < len(chain); i++ {
s := chain[i]
if s.Scene == nil || !pos.In(s.Scene.SceneGeom.Bounds()) {
continue
}
for _, a := range chain[:i] {
sm.deleteStage(a)
}
s.popupHandleEvent(e)
return true
}
return false
}
// abs returns the absolute value of the given int.
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
// mouseClone returns a copy of the given mouse event with the given type,
// not handled, with the mouse button ([events.Event.NewFromClone] only
// copies the base event).
func mouseClone(e events.Event, typ events.Types) events.Event {
me, ok := e.(*events.Mouse)
if !ok {
return e.NewFromClone(typ)
}
c := *me
c.Typ = typ
c.ClearHandled()
return &c
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"cmp"
"slices"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/tree"
)
// Widgets with a [styles.Style.Position] of [styles.PositionAbsolute] or
// [styles.PositionFixed] are out of the flow of the layout of their parent:
// they are sized and positioned like the other children, but they take no
// space in the layout of the parent, and they are positioned by their
// [styles.Style.Inset] relative to their containing block.
// outOfFlow returns whether the widget is out of the flow of the
// layout of its parent (absolute or fixed position).
func (wb *WidgetBase) outOfFlow() bool {
p := wb.Styles.Position
return p == styles.PositionAbsolute || p == styles.PositionFixed
}
// forFlowChildren calls the given function for the visible children
// that are in the flow of the layout (not [WidgetBase.outOfFlow],
// and not floating, [WidgetBase.isFloat]).
func (wb *WidgetBase) forFlowChildren(fun func(i int, cw Widget, cwb *WidgetBase) bool) {
wb.forVisibleChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
if cwb.outOfFlow() || cwb.isFloat() {
return tree.Continue
}
return fun(i, cw, cwb)
})
}
// FixedContainer is implemented by a widget in which the widgets with a
// fixed position ([styles.PositionFixed]) are fixed in a widget other than
// the scene, as a web page in a browser is in the viewport of its tab,
// which does not scroll with it (as with the elements that are the
// containing blocks of their fixed descendants in CSS, as with transforms).
type FixedContainer interface {
// FixedViewport returns the widget that the fixed widgets in the widget
// are fixed in.
FixedViewport() Widget
}
// containingBlock returns the widget that the given out of flow
// widget is positioned relative to: for absolute, the nearest widget
// that it is in that is positioned (not static), or otherwise that
// scrolls (as the document does in a browser); for fixed, the viewport of
// the nearest [FixedContainer] that it is in, or else the scene.
func (wb *WidgetBase) containingBlock() *WidgetBase {
if wb.Styles.Position == styles.PositionFixed {
if vp := wb.fixedViewport(); vp != nil {
return vp
}
}
if wb.Styles.Position == styles.PositionAbsolute {
var scroller *WidgetBase
for p := wb.parentWidget(); p != nil; p = p.parentWidget() {
if p.Styles.Position != styles.PositionStatic {
return p
}
if scroller == nil && (p.Styles.Overflow.X >= styles.OverflowAuto || p.Styles.Overflow.Y >= styles.OverflowAuto) {
scroller = p
}
}
if scroller != nil {
return scroller
}
}
if wb.Scene != nil {
return wb.Scene.AsWidget()
}
return wb.parentWidget()
}
// fixedViewport returns the viewport of the nearest [FixedContainer] that
// the widget is in, or nil.
func (wb *WidgetBase) fixedViewport() *WidgetBase {
for p := wb.parentWidget(); p != nil; p = p.parentWidget() {
if fc, ok := p.This.(FixedContainer); ok {
if vp := fc.FixedViewport(); vp != nil {
return vp.AsWidget()
}
}
}
return nil
}
// paddingBox returns the position offset (from Pos.Total) and the size
// of the padding box of the widget (inside its border).
func (wb *WidgetBase) paddingBox() (offset, size math32.Vector2) {
m := wb.Styles.TotalMargin() // margin and border
offset = math32.Vec2(m.Left, m.Top)
size = wb.Geom.Size.Alloc.Total.Sub(math32.Vec2(m.Left+m.Right, m.Top+m.Bottom))
return
}
// sizeDownOutOfFlow allocates the out of flow children of the frame their
// actual size, or, in a dimension in which both of the opposite sides of
// their inset are set, the space between them in their containing block.
func (fr *Frame) sizeDownOutOfFlow() {
fr.forVisibleChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
if !cwb.outOfFlow() {
return tree.Continue
}
sz := &cwb.Geom.Size
if cwb.styleSizeUpdate() {
// its percentages are of its containing block (see
// [WidgetBase.percentBase]), as its margins, which are in
// the space of its size from before
cwb.spaceFromStyle()
sz.SetTotalFromContent(&sz.Actual)
}
in := cwb.Styles.Inset.Dots()
set := cwb.Styles.InsetSet
_, cbsz := cwb.containingBlock().paddingBox()
// sizes that are relative to the parent are of the containing block
space := sz.Space
for d := math32.X; d <= math32.Y; d++ {
for _, v := range []units.Value{cwb.Styles.Min.Dim(d), cwb.Styles.Max.Dim(d)} {
if v.Value > 0 && (v.Unit == units.UnitPw || v.Unit == units.UnitPh) {
ref := cbsz.X
if v.Unit == units.UnitPh {
ref = cbsz.Y
}
sz.Actual.Total.SetDim(d, ref*v.Value/100+space.Dim(d))
break
}
}
}
center := cwb.Styles.InsetCenter
if set.Left && set.Right && !center[0] {
sz.Actual.Total.X = max(cbsz.X-in.Left-in.Right, 0)
}
if set.Top && set.Bottom && !center[1] {
sz.Actual.Total.Y = max(cbsz.Y-in.Top-in.Bottom, 0)
}
sz.SetContentFromTotal(&sz.Actual)
sz.Alloc = sz.Actual
return tree.Continue
})
}
// setPosOutOfFlow sets the position of the widget, which is out of the flow
// of its parent, from its inset and its containing block, using the given
// position in the parent for the dimensions in which no inset is set.
func (wb *WidgetBase) setPosOutOfFlow(parPos math32.Vector2) {
cb := wb.containingBlock()
off, cbsz := cb.paddingBox()
cbpos := cb.Geom.Pos.Total.Add(off).Add(cb.Geom.Scroll.Round()) // with its content
if wb.Styles.Position == styles.PositionFixed {
// relative to the scene, or a viewport (as of a web page), which
// does not scroll with its content
cbpos = off
if cb != wb.Scene.AsWidget() {
cbpos = cb.Geom.Pos.Total.Add(off)
}
}
in := wb.Styles.Inset.Dots()
set := wb.Styles.InsetSet
sz := wb.Geom.Size.Actual.Total
pos := wb.Geom.RelPos.Add(parPos) // the static position
center := wb.Styles.InsetCenter
switch {
case set.Left && set.Right && center[0]: // centered between them
pos.X = cbpos.X + in.Left + math32.Floor((cbsz.X-in.Left-in.Right-sz.X)/2)
case set.Left:
pos.X = cbpos.X + in.Left
case set.Right:
pos.X = cbpos.X + cbsz.X - in.Right - sz.X
}
switch {
case set.Top && set.Bottom && center[1]:
pos.Y = cbpos.Y + in.Top + math32.Floor((cbsz.Y-in.Top-in.Bottom-sz.Y)/2)
case set.Top:
pos.Y = cbpos.Y + in.Top
case set.Bottom:
pos.Y = cbpos.Y + cbsz.Y - in.Bottom - sz.Y
}
wb.Geom.Pos.Total = pos
}
// relativeOffset returns the offset of a widget with a relative position
// from its position in the layout.
func (wb *WidgetBase) relativeOffset() math32.Vector2 {
var off math32.Vector2
in := wb.Styles.Inset.Dots()
set := wb.Styles.InsetSet
switch {
case set.Left:
off.X = in.Left
case set.Right:
off.X = -in.Right
}
switch {
case set.Top:
off.Y = in.Top
case set.Bottom:
off.Y = -in.Bottom
}
return off
}
// stickyOffset returns the offset of a [styles.PositionSticky] widget at
// the given position in the layout of the given parent: the widget stays
// at its [styles.Style.Inset] from the edges of the visible part of the
// frame that it scrolls in (as it is scrolled past them), within the
// content of its parent.
func (wb *WidgetBase) stickyOffset(pwb *WidgetBase, pos math32.Vector2) math32.Vector2 {
var off math32.Vector2
sf := wb.parentScrollFrame()
if sf == nil {
return off
}
in := wb.Styles.Inset.Dots()
set := wb.Styles.InsetSet
size := wb.Geom.Size.Actual.Total
// the visible part of the scroll frame, and the content of the parent
// (all of the content of the scroll frame, if it is the parent)
view := math32.Box2{Min: sf.Geom.Pos.Content, Max: sf.Geom.Pos.Content.Add(sf.Geom.Size.Actual.Content)}
cmin := pwb.Geom.Pos.Content
csize := pwb.Geom.Size.Actual.Content
if pwb == sf.AsWidget() {
cmin = cmin.Add(sf.Geom.Scroll.Round())
csize = sf.Geom.Size.Internal
}
cmax := cmin.Add(csize)
for d := math32.X; d <= math32.Y; d++ {
start, end := set.Left, set.Right
ins, ine := in.Left, in.Right
if d == math32.Y {
start, end = set.Top, set.Bottom
ins, ine = in.Top, in.Bottom
}
p, sz := pos.Dim(d), size.Dim(d)
np := p
if start {
np = max(np, view.Min.Dim(d)+ins)
}
if end {
np = min(np, view.Max.Dim(d)-ine-sz)
}
// within the content of its parent (but not before its position
// in the layout for start, or after it for end)
if np > p {
np = max(min(np, cmax.Dim(d)-sz), p)
} else if np < p {
np = min(max(np, cmin.Dim(d)), p)
}
off.SetDim(d, np-p)
}
return off
}
// translateOffset returns the offset of the [styles.Style.Translate] of the
// widget in dots, with percentages of the element width and height of its
// own size.
func (wb *WidgetBase) translateOffset() math32.Vector2 {
tr := &wb.Styles.Translate
if tr.X.Value == 0 && tr.Y.Value == 0 {
return math32.Vector2{}
}
sz := wb.Geom.Size.Actual.Total
dots := func(v units.Value, size float32) float32 {
switch v.Unit {
case units.UnitEw, units.UnitEh:
return v.Value / 100 * size
}
return wb.Styles.UnitContext.ToDots(v.Value, v.Unit)
}
return math32.Vec2(dots(tr.X, sz.X), dots(tr.Y, sz.Y))
}
// stacked returns whether the widget is rendered in the order of its
// z-index among its siblings: if it is positioned (not static), or has a
// z-index (see [styles.Style.ZIndex]).
func (wb *WidgetBase) stacked() bool {
return wb.Styles.Position != styles.PositionStatic || wb.Styles.ZIndex != 0
}
// renderOrder returns the children of the widget in the order that they are
// rendered: those that float after the others (over their backgrounds),
// and those that are positioned (not static) after them,
// in the increasing order of their ZIndex, except that those with a negative
// ZIndex are first. It returns nil if they are rendered in order.
func (wb *WidgetBase) renderOrder() []Widget {
positioned := false
wb.ForWidgetChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
if cwb.stacked() || cwb.isFloat() {
positioned = true
return tree.Break
}
return tree.Continue
})
if !positioned {
return nil
}
type item struct {
w Widget
layer int // -1: negative z-index; 0: static; 1: float; 2: positioned
z int
}
var items []item
wb.ForWidgetChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
it := item{w: cw}
switch {
case cwb.stacked():
it.layer, it.z = 2, cwb.Styles.ZIndex
if it.z < 0 {
it.layer = -1
}
case cwb.isFloat():
it.layer = 1
}
items = append(items, it)
return tree.Continue
})
slices.SortStableFunc(items, func(a, b item) int {
if a.layer != b.layer {
return cmp.Compare(a.layer, b.layer)
}
return cmp.Compare(a.z, b.z)
})
ws := make([]Widget, len(items))
for i, it := range items {
ws[i] = it.w
}
return ws
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/units"
)
// PreLayout returns a function that styles and lays out a widget that is
// in no scene (as the new content of a page, made in another goroutine),
// as it would be as the only child of the given parent widget in this
// scene, in a scene of its own that shares the text shaper of the window
// of this scene, and so its caches. Laying the widget out again once it is
// added to the parent (with the lock of this scene held) is then much
// quicker, as the texts in it are shaped and wrapped from the caches.
//
// PreLayout is called with the lock of the scene held (as it gets the
// state of the scene and the parent), and the function that it returns is
// called without it, in any goroutine, before the widget is added to the
// parent. It returns nil if the scene is not in a window yet.
func (sc *Scene) PreLayout(parent Widget) func(w Widget) {
rc := sc.renderContext()
if rc == nil || rc.textShaper == nil {
return nil
}
off := &renderContext{logicalDPI: rc.logicalDPI, textShaper: rc.textShaper, visible: true}
sceneSize := sc.SceneGeom.Size
pwb := parent.AsWidget()
pst := pwb.Styles // a copy, for the inherited styles
size := pwb.Geom.Size.Alloc.Content
return func(w Widget) {
psc := NewScene("pre-layout")
psc.offscreen = off
psc.SceneGeom.Size = sceneSize
psc.Styler(func(s *styles.Style) {
s.Padding.Zero()
s.Gap.Zero()
})
host := NewFrame(psc) // as the parent
host.Styler(func(s *styles.Style) {
// the styles of the parent, which its children inherit, in the
// size of its content
st := s.State
*s = pst
s.State = st
s.Padding.Zero()
s.Margin.Zero()
s.Border.Width.Zero()
s.Min.Set(units.Dot(size.X), units.Dot(size.Y))
s.Max.Set(units.Dot(size.X), units.Dot(size.Y))
s.Overflow.Set(styles.OverflowAuto)
})
host.AddChild(w)
psc.StyleTree()
psc.LayoutScene()
// the widget is taken out of the scene, to be added to the parent
host.Children = nil
w.AsTree().Parent = nil
}
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"fmt"
"path/filepath"
"runtime/debug"
"strings"
"cogentcore.org/core/base/fileinfo/mimedata"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/styles"
"cogentcore.org/core/system"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/text"
)
// timesCrashed is the number of times that the program has
// crashed. It is used to prevent an infinite crash loop
// when rendering the crash window.
var timesCrashed int
// webCrashDialog is the function used to display the crash dialog on web.
// It cannot be displayed normally due to threading and single-window issues.
var webCrashDialog func(title, txt, body string)
// handleRecover is the core value of [system.HandleRecover]. If r is not nil,
// it makes a window displaying information about the panic. [system.HandleRecover]
// is initialized to this in init.
func handleRecover(r any) {
if r == nil {
return
}
timesCrashed++
system.HandleRecoverBase(r)
// Nobody can close a crash window that is rendered offscreen, as in
// tests, which would then wait for the event loop forever.
if TheApp.Platform() == system.Offscreen {
panic(r)
}
if timesCrashed > 1 {
return
}
stack := string(debug.Stack())
// we have to handle the quit button indirectly so that it has the
// right stack for debugging when panicking
quit := make(chan struct{})
title := TheApp.Name() + " stopped unexpectedly"
txt := "There was an unexpected error and " + TheApp.Name() + " stopped running."
clpath := filepath.Join(TheApp.AppDataDir(), "crash-logs")
clpath = strings.ReplaceAll(clpath, " ", `\ `) // escape spaces
body := fmt.Sprintf("Crash log saved in %s\n\n%s", clpath, system.CrashLogText(r, stack))
if webCrashDialog != nil {
webCrashDialog(title, txt, body)
return
}
b := NewBody(title)
NewText(b).SetText(title).SetType(TextHeadlineSmall)
NewText(b).SetType(TextSupporting).SetText(txt)
b.AddBottomBar(func(bar *Frame) {
NewButton(bar).SetText("Details").SetType(ButtonOutlined).OnClick(func(e events.Event) {
d := NewBody("Crash details")
NewText(d).SetText(body).Styler(func(s *styles.Style) {
s.Font.Family = rich.Monospace
s.Text.WhiteSpace = text.WhiteSpacePreWrap
})
d.AddBottomBar(func(bar *Frame) {
NewButton(bar).SetText("Copy").SetIcon(icons.Copy).SetType(ButtonOutlined).
OnClick(func(e events.Event) {
d.Clipboard().Write(mimedata.NewText(body))
})
d.AddOK(bar)
})
d.RunFullDialog(b)
})
NewButton(bar).SetText("Quit").OnClick(func(e events.Event) {
quit <- struct{}{}
})
})
b.RunWindow()
<-quit
panic(r)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"cmp"
"fmt"
"image"
"os"
"path/filepath"
"runtime"
"runtime/pprof"
"slices"
"time"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/profile"
"cogentcore.org/core/colors"
"cogentcore.org/core/colors/cam/hct"
"cogentcore.org/core/events"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint/render"
_ "cogentcore.org/core/paint/renderers" // installs default renderer
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/sides"
"cogentcore.org/core/system"
"cogentcore.org/core/tree"
)
// AsyncLock must be called before making any updates in a separate goroutine
// outside of the main configuration, rendering, and event handling structure.
// It must have a matching [WidgetBase.AsyncUnlock] after it.
//
// If the widget has been deleted, or if the [Scene] has been shown but the render
// context is not available, then this will block forever. Enable
// [DebugSettingsData.UpdateTrace] in [DebugSettings] to see when that happens.
// If the scene has not been shown yet, it waits until the scene is shown.
func (wb *WidgetBase) AsyncLock() {
sc := wb.Scene
// A scene that has not been shown can be in the process of being run,
// in another goroutine without the lock, so its stage is only read
// once it has been shown (except for an offscreen scene, which is
// never shown).
if !sc.hasShown.Load() && sc.offscreen == nil {
if DebugSettings.UpdateTrace {
fmt.Println("AsyncLock: waiting for scene to be shown:", wb)
}
<-sc.shown
}
rc := sc.renderContext()
if rc == nil {
// If the scene has been shown but there is no render context,
// we are probably being deleted, so we just block forever.
if DebugSettings.UpdateTrace {
fmt.Println("AsyncLock: scene shown but no render context; blocking forever:", wb)
}
select {}
}
rc.Lock()
if wb.This == nil {
rc.Unlock()
if DebugSettings.UpdateTrace {
fmt.Println("AsyncLock: widget deleted; blocking forever:", wb)
}
select {}
}
wb.Scene.asyncLocked = rc
wb.Scene.setFlag(true, sceneUpdating)
}
// AsyncLockIfShown is like [WidgetBase.AsyncLock], but it never waits for
// the scene to be shown or blocks forever: if the widget has been deleted,
// or its [Scene] has no render context because it has not been shown yet
// or is no longer shown (as while it is being closed), it returns false
// without locking. Otherwise it locks and returns true, and it must have
// a matching [WidgetBase.AsyncUnlock] after it. It is for updates from a
// separate goroutine that only matter for a widget that is shown, such
// as updates that just render it again, so that a goroutine that updates
// several widgets is not stuck on one of them.
func (wb *WidgetBase) AsyncLockIfShown() bool {
// This is only read under the lock, as the widget can be destroyed
// (setting This to nil) under the lock at any time.
// A scene that has not been shown can be in the process of being run,
// in another goroutine without the lock of its render context.
if wb.Scene == nil || !wb.Scene.hasShown.Load() {
return false
}
rc := wb.Scene.renderContext()
if rc == nil {
return false
}
rc.Lock()
// The scene can have been closed while we waited for the lock.
if wb.This == nil || wb.Scene.renderContext() != rc {
rc.Unlock()
return false
}
wb.Scene.asyncLocked = rc
wb.Scene.setFlag(true, sceneUpdating)
return true
}
// AsyncUnlock must be called after making any updates in a separate goroutine
// outside of the main configuration, rendering, and event handling structure.
// It must have a matching [WidgetBase.AsyncLock] before it.
func (wb *WidgetBase) AsyncUnlock() {
sc := wb.Scene
if sc == nil {
return
}
rc := sc.asyncLocked // the one that was locked
sc.asyncLocked = nil
if rc == nil {
rc = sc.renderContext()
}
if rc == nil {
return
}
sc.setFlag(false, sceneUpdating)
rc.Unlock()
}
// windowFunc is a function that is run in the event loop of a window,
// sent to it as the data of an [events.Custom] event by
// [WidgetBase.runInWindow].
type windowFunc func()
// runInWindow runs the given function, which updates the widget (or other
// widgets in its window), from the event handling of the given other widget.
// The event loop of each window only holds the lock of its own render
// context, so if the widgets are in different windows (on multi-window
// platforms), the function is sent to the event loop of the window of the
// widget, to run there later; otherwise it is run directly. This does not
// wait on the other window, so that two windows that update each other
// cannot deadlock. The function is not run if the widget is no longer shown,
// or has been deleted by the time that it would run in the other window.
func (wb *WidgetBase) runInWindow(from *WidgetBase, f func()) {
// A widget that has been deleted is not updated.
if wb.This == nil {
return
}
// A widget that is not in a window, such as the argument value of a
// solo [FuncButton] (see [CallFunc]), is updated directly, from the
// event loop of the other widget, as nothing renders it.
if wb.Scene == nil {
f()
return
}
rw := wb.Scene.RenderWindow()
if rw == nil {
return
}
if from.Scene != nil && rw == from.Scene.RenderWindow() {
f()
return
}
rw.SystemWindow.Events().Custom(windowFunc(func() {
if wb.This != nil {
f()
}
}))
}
// runInEachWindow runs the given function, which updates the render context
// of a window, in the event loop of each window, where it has the lock of
// the render context. It is sent to each window as a custom event, so it
// never waits on the lock of any window: the caller typically holds the lock
// of its own window, and waiting on another window while holding it could
// deadlock with that window waiting on this one.
func runInEachWindow(f func(w *renderWindow, rc *renderContext)) {
for _, w := range AllRenderWindows.windows() {
w.SystemWindow.Events().Custom(windowFunc(func() {
f(w, w.renderContext())
}))
}
}
// runInCurrentWindow runs the given function in the event loop of the
// current window, where it has the lock of its render context, as for
// updates from callbacks that do not have a window or a lock, such as
// those of the browser on the web. It is sent as a custom event, so it
// does not wait for the function to run. Nothing is done if there is no
// current window.
func runInCurrentWindow(f func()) {
w := getCurrentRenderWindow()
if w == nil {
return
}
w.SystemWindow.Events().Custom(windowFunc(f))
}
// NeedsRender specifies that the widget needs to be rendered.
func (wb *WidgetBase) NeedsRender() {
if DebugSettings.UpdateTrace {
fmt.Println("\tDebugSettings.UpdateTrace: NeedsRender:", wb)
}
wb.setFlag(true, widgetNeedsRender)
wb.setParentsChildNeedsRender()
if wb.Scene != nil {
wb.Scene.setFlag(true, sceneNeedsRender)
}
}
// setParentsChildNeedsRender marks all of the parents of the widget as
// having a widget inside of them that needs to be rendered.
func (wb *WidgetBase) setParentsChildNeedsRender() {
for pwb := wb.parentWidget(); pwb != nil; pwb = pwb.parentWidget() {
pwb.setFlag(true, widgetChildNeedsRender)
}
}
// NeedsLayout specifies that the widget's scene needs to do a layout.
// This needs to be called after any changes that affect the structure
// and/or size of elements.
func (wb *WidgetBase) NeedsLayout() {
if DebugSettings.UpdateTrace {
fmt.Println("\tDebugSettings.UpdateTrace: NeedsLayout:", wb)
}
if wb.Scene != nil {
wb.Scene.setFlag(true, sceneNeedsLayout)
}
}
// NeedsRebuild returns whether the [renderContext] indicates
// a full rebuild is needed. This is typically used to detect
// when the settings have been changed, such as when the color
// scheme or zoom is changed.
func (wb *WidgetBase) NeedsRebuild() bool {
if wb.This == nil || wb.Scene == nil || wb.Scene.Stage == nil {
return false
}
rc := wb.Scene.renderContext()
if rc == nil {
return false
}
return rc.rebuild
}
// LayoutScene does a layout of the scene: Size, Position
func (sc *Scene) LayoutScene() {
if DebugSettings.LayoutTrace {
fmt.Println("\n############################\nLayoutScene SizeUp start:", sc)
}
sc.spaceChanged = false
sc.layoutFrame(math32.FromPoint(sc.SceneGeom.Size))
for range 3 { // with the padding and margins of the final sizes
if !sc.spaceChanged || sc.hasFlag(sceneContentSizing) {
break
}
sc.spaceChanged = false
sc.layoutFrame(math32.FromPoint(sc.SceneGeom.Size))
}
sc.ApplyScenePos()
}
// layoutFrame does the frame layout core functionality
func (fr *Frame) layoutFrame(size math32.Vector2) {
fr.SizeUp()
sz := &fr.Geom.Size
sz.Alloc.Total = size
sz.SetContentFromTotal(&sz.Alloc)
if DebugSettings.LayoutTrace {
fmt.Println("\n############################\nSizeDown start:", fr)
}
// The layout takes up to maxIter iterations while it needs to redo.
// After those, it continues (up to maxSettle in all) only while the
// sizes of the widgets are still changing, as when the heights of
// nested blocks of text follow widths that changed in the previous
// iteration, which otherwise leaves them (and their parents) higher
// than their final content. The redo of some widgets is always true,
// so it is not enough to know that they have settled. Sizes that
// alternate (as a scrollbar that is added and removed) stop it too.
const maxIter, maxSettle = layoutIters, 6
var sizes, prev, prev2 float64
for iter := range maxSettle {
redo := fr.SizeDown(iter)
if !redo {
break
}
if iter >= maxIter-2 {
prev2, prev = prev, sizes
sizes = fr.sizesSum()
if iter >= maxIter-1 && (sizes == prev || sizes == prev2) {
break
}
}
if DebugSettings.LayoutTrace {
fmt.Println("\n############################\nSizeDown redo:", fr, "iter:", iter+1)
}
}
if DebugSettings.LayoutTrace {
fmt.Println("\n############################\nSizeFinal start:", fr)
}
fr.SizeFinal()
if DebugSettings.LayoutTrace {
fmt.Println("\n############################\nPosition start:", fr)
}
fr.Position()
if DebugSettings.LayoutTrace {
fmt.Println("\n############################\nScenePos start:", fr)
}
}
// layoutIters is the number of SizeDown iterations that a layout takes
// while it needs to redo, after which it only continues while the sizes of
// the widgets are still changing (see [Frame.layoutFrame]).
const layoutIters = 3
// sizesSum returns the sum of the actual sizes of the frame and the
// widgets in it, which changes when any of them changes (practically),
// for knowing whether the layout has settled.
func (fr *Frame) sizesSum() float64 {
sum := float64(0)
for _, cwb := range fr.AllWidgets() {
sz := cwb.Geom.Size.Actual.Total
sum += float64(sz.X)*1.0001 + float64(sz.Y)
}
return sum
}
// LayoutFrame does a layout on the given Frame using given size.
func (fr *Frame) LayoutFrame(size math32.Vector2) {
fr.layoutFrame(size)
fr.ApplyScenePos()
}
// LayoutRenderScene does a layout and render of the tree:
// GetSize, DoLayout, Render. Needed after Config.
func (sc *Scene) LayoutRenderScene() {
sc.LayoutScene()
sc.renderWhole()
}
func (sc *Scene) Render() {
if TheApp.Platform() == system.Web {
sc.Painter.Fill.Color = colors.Uniform(colors.Transparent)
sc.Painter.Clear()
}
sc.RenderStandardBox()
}
// renderGrouper is implemented by widgets that are rendered as a whole when
// any widget in them needs to be rendered, if RenderGroup returns true,
// instead of only that widget: those that leave a region of the scene
// transparent for another source that is drawn under their partly
// transparent content (as a video under its controls, see the video
// package), which would otherwise be drawn over its previous rendering.
type renderGrouper interface {
RenderGroup() bool
}
// doNeedsRender calls Render on tree from me for nodes
// with NeedsRender flags set. It only goes into the widgets
// that have such nodes inside of them.
func (wb *WidgetBase) doNeedsRender() {
if wb.This == nil {
return
}
var again map[*WidgetBase]bool // (see below)
wb.WidgetWalkDown(func(cw Widget, cwb *WidgetBase) bool {
if cwb.hasFlag(widgetNeedsRender) {
cwb.setFlag(false, widgetChildNeedsRender)
if a := cwb.seeThroughRoot(); a != nil {
// it would paint over its last render, so the widget that
// it is in with an opaque background is rendered again, with
// what is under it (once, for all of the widgets in it)
if !again[a] {
if again == nil {
again = map[*WidgetBase]bool{}
}
again[a] = true
a.This.(Widget).RenderWidget()
for p := a.parentWidget(); p != nil; p = p.parentWidget() {
p.renderRaised()
}
}
return tree.Break
}
cw.RenderWidget()
// the widgets in it that are raised to the widgets that it is in,
// which are not rendered now, are rendered over it
for p := cwb.parentWidget(); p != nil; p = p.parentWidget() {
p.renderRaised()
}
return tree.Break // don't go any deeper
}
if !cwb.hasFlag(widgetChildNeedsRender) {
return tree.Break // nothing inside needs to be rendered
}
if rg, ok := cw.(renderGrouper); ok && rg.RenderGroup() {
// it is rendered as a whole (see renderGrouper)
for _, dwb := range cwb.AllWidgets() {
dwb.setFlag(false, widgetChildNeedsRender)
}
// not when it is covered by widgets rendered over it in the
// image of the scene, which it would paint over (as a playing
// video under an absolute dialog of a page), but it is when they
// are in the layer of the scene (as a fixed dialog), which is
// composed over it (see [WidgetBase.isCovered] and [sceneLayer])
covered, over := cwb.coverage(false)
if covered {
return tree.Break
}
cw.RenderWidget()
// (with the widgets raised over it, as below)
for p := cwb.parentWidget(); p != nil; p = p.parentWidget() {
p.renderRaised()
}
// and the widgets that are over a part of it, which it painted
// over (as the controls of a player of a page over its playing
// video, which flickered as they were rendered again)
for _, ow := range over {
ow.RenderWidget()
}
return tree.Break
}
cwb.setFlag(false, widgetChildNeedsRender)
if ly := AsFrame(cw); ly != nil {
for d := math32.X; d <= math32.Y; d++ {
if ly.HasScroll[d] && ly.Scrolls[d] != nil {
ly.Scrolls[d].doNeedsRender()
}
}
}
return tree.Continue
})
}
//////// Scene
var sceneShowIters = 2
// doUpdate checks scene Needs flags to do whatever updating is required.
// returns false if already updating.
// This is the main update call made by the RenderWindow at FPS frequency.
func (sc *Scene) doUpdate() bool {
if sc.hasFlag(sceneUpdating) {
return false
}
sc.setFlag(true, sceneUpdating) // prevent rendering
defer func() { sc.setFlag(false, sceneUpdating) }()
sc.runAnimations()
rc := sc.renderContext()
if sc.showIter < sceneShowIters {
sc.setFlag(true, sceneNeedsLayout)
sc.showIter++
}
switch {
case rc.rebuild:
// pr := profile.Start("rebuild")
sc.doRebuild()
sc.setFlag(false, sceneNeedsLayout, sceneNeedsRender)
sc.setFlag(true, sceneImageUpdated)
// pr.End()
case rc.restyle || sc.lastRender.needsRestyle(rc):
// pr := profile.Start("restyle")
sc.applyStyleScene()
sc.LayoutRenderScene()
sc.setFlag(false, sceneNeedsLayout, sceneNeedsRender)
sc.setFlag(true, sceneImageUpdated)
sc.lastRender.saveRender(rc)
// pr.End()
case sc.hasFlag(sceneNeedsLayout):
// pr := profile.Start("layout")
sc.LayoutRenderScene()
sc.setFlag(false, sceneNeedsLayout, sceneNeedsRender)
sc.setFlag(true, sceneImageUpdated)
// pr.End()
case sc.hasFlag(sceneNeedsRender):
// pr := profile.Start("render")
sc.doNeedsRender()
sc.setFlag(false, sceneNeedsRender)
sc.setFlag(true, sceneImageUpdated)
// pr.End()
default:
return false
}
if sc.showIter == sceneShowIters { // end of first pass
sc.showIter++ // just go 1 past the iters cutoff
}
return true
}
// updateScene calls UpdateTree on the Scene, which calls
// UpdateWidget on all widgets in the Scene. This will set
// NeedsLayout to drive subsequent layout and render.
// This is a top-level call, typically only done when the window
// is first drawn or resized, or during rebuild,
// once the full sizing information is available.
func (sc *Scene) updateScene() {
sc.setFlag(true, sceneUpdating) // prevent rendering
defer func() { sc.setFlag(false, sceneUpdating) }()
sc.UpdateTree()
}
// applyStyleScene calls ApplyStyle on all widgets in the Scene,
// This is needed whenever the window geometry, DPI,
// etc is updated, which affects styling.
func (sc *Scene) applyStyleScene() {
sc.setFlag(true, sceneUpdating) // prevent rendering
defer func() { sc.setFlag(false, sceneUpdating) }()
sc.StyleTree()
if sc.Painter.Paint != nil {
sc.Painter.UnitContext = sc.Styles.UnitContext
}
sc.setFlag(true, sceneNeedsLayout)
}
// doRebuild does the full re-render and RenderContext Rebuild flag
// should be used by Widgets to rebuild things that are otherwise
// cached (e.g., Icon, TextCursor).
func (sc *Scene) doRebuild() {
sc.Stage.Sprites.reset()
sc.updateScene()
sc.applyStyleScene()
sc.LayoutRenderScene()
}
// contentSize computes the size of the scene based on current content.
// initSz is the initial size, e.g., size of screen.
// Used for auto-sizing windows when created, and in [Scene.ResizeToContent].
func (sc *Scene) contentSize(_ image.Point) image.Point {
sc.setFlag(true, sceneUpdating) // prevent rendering
defer func() { sc.setFlag(false, sceneUpdating) }()
sc.setFlag(true, sceneContentSizing)
sc.updateScene()
sc.applyStyleScene()
sc.LayoutScene()
sz := &sc.Geom.Size
psz := sz.Actual.Total
sc.setFlag(false, sceneContentSizing)
sc.showIter = 0
return psz.ToPointFloor()
}
//////// Widget local rendering
// StartRender starts the rendering process in the Painter, if the
// widget is visible, otherwise it returns false.
// It pushes our context and bounds onto the render stack.
// This must be called as the first step in [Widget.RenderWidget] implementations.
func (wb *WidgetBase) StartRender() bool {
if wb == nil || wb.This == nil {
return false
}
wb.setFlag(false, widgetNeedsRender) // done!
if !wb.IsVisible() && !wb.rendersOverflow() {
return false
}
if wb.Styles.Opacity <= 0 { // fully transparent (as for visibility: hidden in CSS): nothing to render
return false
}
wb.Styles.ComputeActualBackground(wb.parentActualBackground())
if wb.Scene == nil {
return false
}
if l := &wb.Scene.layer; l.mode != layerOff && !l.layerStart(wb.Scene, wb) {
return false
}
pc := &wb.Scene.Painter
if pc.State == nil {
return false
}
var sty *styles.Paint
if rot := wb.Styles.Rotate; rot != 0 { // around its center
sty = styles.NewPaint()
sty.UnitContext = pc.Context().Style.UnitContext
pos, size := wb.Geom.Pos.Total, wb.Geom.Size.Actual.Total
sty.Transform = math32.Rotate2DAround(math32.DegToRad(rot), pos.Add(size.MulScalar(0.5)))
}
if wb.noClip() || sty != nil { // its children can be outside of it
pc.PushContext(sty, render.NewBoundsRect(wb.childClipBBox(), sides.Floats{}))
} else {
if wb.Styles.BoxShadowOutside && wb.Styles.HasBoxShadow() { // the shadows are around the box
m := wb.Styles.BoxShadowMargin()
bb := wb.Geom.TotalBBox
bb.Min = bb.Min.Sub(image.Pt(int(math32.Ceil(m.Left)), int(math32.Ceil(m.Top))))
bb.Max = bb.Max.Add(image.Pt(int(math32.Ceil(m.Right)), int(math32.Ceil(m.Bottom))))
pc.PushContext(nil, render.NewBoundsRect(bb, sides.Floats{}))
} else {
pc.PushContext(nil, render.NewBoundsRect(wb.Geom.TotalBBox, wb.Styles.Border.Radius.Dots()))
}
}
pc.Defaults() // start with default style values
if DebugSettings.RenderTrace {
fmt.Printf("Render: %v at %v\n", wb.Path(), wb.Geom.TotalBBox)
}
return true
}
// EndRender is the last step in [Widget.RenderWidget] implementations after
// rendering children. It pops our state off of the render stack.
func (wb *WidgetBase) EndRender() {
if wb == nil || wb.This == nil {
return
}
pc := &wb.Scene.Painter
isSelw := wb.Scene.selectedWidget == wb.This
if wb.Scene.renderBBoxes || isSelw {
pos := math32.FromPoint(wb.Geom.TotalBBox.Min)
sz := math32.FromPoint(wb.Geom.TotalBBox.Size())
// node: we won't necc. get a push prior to next update, so saving these.
pcsw := pc.Stroke.Width
pcsc := pc.Stroke.Color
pcfc := pc.Fill.Color
pcop := pc.Fill.Opacity
pc.Stroke.Width.Dot(1)
pc.Stroke.Color = colors.Uniform(hct.New(wb.Scene.renderBBoxHue, 100, 50))
pc.Fill.Color = nil
if isSelw {
fc := pc.Stroke.Color
pc.Fill.Color = fc
pc.Fill.Opacity = 0.2
}
pc.Rectangle(pos.X, pos.Y, sz.X, sz.Y)
pc.Draw()
// restore
pc.Fill.Opacity = pcop
pc.Fill.Color = pcfc
pc.Stroke.Width = pcsw
pc.Stroke.Color = pcsc
wb.Scene.renderBBoxHue += 10
if wb.Scene.renderBBoxHue > 360 {
rmdr := (int(wb.Scene.renderBBoxHue-360) + 1) % 9
wb.Scene.renderBBoxHue = float32(rmdr)
}
}
pc.PopContext()
}
// Render is the method that widgets should implement to define their
// custom rendering steps. It should not typically be called outside of
// [Widget.RenderWidget], which also does other steps applicable
// for all widgets. The base [WidgetBase.Render] implementation
// renders the standard box model.
func (wb *WidgetBase) Render() {
wb.RenderStandardBox()
}
// RenderWidget renders the widget and any parts and children that it has.
// It does not render if the widget is invisible. It calls Widget.Render]
// for widget-specific rendering.
func (wb *WidgetBase) RenderWidget() {
if wb.StartRender() {
wb.This.(Widget).Render()
wb.renderChildren()
wb.renderParts()
wb.EndRender()
wb.renderOutOfFlowChildren()
}
}
// rendersOverflow returns whether the widget is rendered although it has no
// size, for its children: if it does not clip them (see
// [styles.Style.NoClip]), they can be outside of it, as in CSS, where a
// box with overflow visible shows its overflowing content (as the fixed
// consent banner of nytimes.com, in a fixed div that has no size, which
// was not shown and took the clicks of the page).
func (wb *WidgetBase) rendersOverflow() bool {
sz := wb.Geom.Size.Actual.Total
return (sz.X <= 0 || sz.Y <= 0) && wb.noClip() && wb.HasChildren() && wb.IsDisplayable()
}
// renderOutOfFlowChildren renders the children of the widget that are out
// of the flow of its layout (absolute and fixed positions), after the
// widget, outside of its clipping, as they can be outside of it.
func (wb *WidgetBase) renderOutOfFlowChildren() {
for _, cw := range wb.renderOrder() {
if cw.AsWidget().outOfFlow() && cw.AsWidget().Styles.ZIndex >= 0 {
if root := cw.AsWidget().raisedTo(); root != nil {
root.raised = append(root.raised, cw)
continue
}
cw.RenderWidget()
}
}
wb.renderRaised()
}
// raisedTo returns the widget that the widget is rendered after the
// content of (see [WidgetBase.raised]): its positioned ancestor for an
// absolute or fixed widget of no z-index (see
// [WidgetBase.positionedAncestor]), or the stacking context that the
// widget is rendered in if it has a positive z-index (see
// [styles.Style.ZIndex]) and that is not its parent, or nil: the nearest
// widget that it is in that has a z-index (as in CSS, where a z-index of auto,
// the default, makes no stacking context), or the top widget. As in CSS,
// it is then rendered over the widgets after the ones that it is in (as
// the dropdown menus in the header of Wikipedia, over the page).
func (wb *WidgetBase) raisedTo() *WidgetBase {
if wb.Styles.ZIndex == 0 && wb.outOfFlow() {
return wb.positionedAncestor()
}
if wb.Styles.ZIndex <= 0 {
return nil
}
parent := wb.parentWidget()
if parent == nil {
return nil
}
root := parent
for p := parent; p != nil; p = p.parentWidget() {
root = p
if p.Styles.ZIndex != 0 {
break
}
}
if root == parent {
return nil
}
return root
}
// positionedAncestor returns the nearest widget that the widget is in that
// is positioned (not [styles.PositionStatic]), if that is not its parent,
// or nil. An absolute or fixed widget of no z-index is rendered after the
// content of that one, as in CSS, where it is painted after the widgets in
// the flow (as the absolute images of edition.cnn.com, in a picture before
// the ::after of their box, which painted over them).
func (wb *WidgetBase) positionedAncestor() *WidgetBase {
parent := wb.parentWidget()
if parent == nil || parent.Styles.Position != styles.PositionStatic {
return nil
}
for p := parent.parentWidget(); p != nil; p = p.parentWidget() {
if p.Styles.Position != styles.PositionStatic || p.Styles.ZIndex != 0 {
return p
}
}
return nil
}
// renderRaised renders the widgets that are raised to this one as their
// stacking context (see [WidgetBase.raisedTo]), in the order of their
// z-index, after its other content.
func (wb *WidgetBase) renderRaised() {
if len(wb.raised) == 0 {
return
}
raised := wb.raised
wb.raised = nil
slices.SortStableFunc(raised, func(a, b Widget) int {
return cmp.Compare(a.AsWidget().Styles.ZIndex, b.AsWidget().Styles.ZIndex)
})
for _, cw := range raised {
cw.RenderWidget()
}
}
func (wb *WidgetBase) renderParts() {
if wb.Parts != nil {
wb.Parts.RenderWidget()
}
}
// renderChildren renders all of the widget's children.
func (wb *WidgetBase) renderChildren() {
if order := wb.renderOrder(); order != nil { // positioned children
for _, cw := range order {
// out of flow ones are rendered after (see RenderWidget), except
// those with a negative z-index, which are under the others (as
// the offset shadows of github.com, under their content)
if cwb := cw.AsWidget(); !cwb.outOfFlow() || cwb.Styles.ZIndex < 0 {
if root := cw.AsWidget().raisedTo(); root != nil {
root.raised = append(root.raised, cw)
continue
}
cw.RenderWidget()
}
}
return
}
wb.ForWidgetChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
cw.RenderWidget()
return tree.Continue
})
}
//////// Defer
// Defer adds a function to [WidgetBase.Deferred] that will be called after the next
// [Scene] update/render, including on the initial Scene render. After the function
// is called, it is removed and not called again. In the function, sending events
// etc will work as expected.
func (wb *WidgetBase) Defer(fun func()) {
wb.Deferred = append(wb.Deferred, fun)
if wb.Scene != nil {
wb.Scene.setFlag(true, sceneHasDeferred)
}
}
// runDeferred runs deferred functions on all widgets in the scene.
func (sc *Scene) runDeferred() {
for _, cwb := range sc.AllWidgets() {
for _, f := range cwb.Deferred {
f()
}
cwb.Deferred = nil
}
}
// DeferShown adds a [WidgetBase.Defer] function to call [WidgetBase.Shown]
// and activate [WidgetBase.StartFocus]. For example, this is called in [Tabs]
// and [Pages] when a tab/page is newly shown, so that elements can perform
// [WidgetBase.OnShow] updating as needed.
func (wb *WidgetBase) DeferShown() {
wb.Defer(func() {
// Before its scene has been shown, its widgets are not sent the
// show event, as the scene sends it to all of them once it is, and
// they cannot be updated from other goroutines before then (see
// [WidgetBase.AsyncLockIfShown]), as for the tab that is selected
// in a window that is about to be shown.
if wb.Scene == nil || !wb.Scene.hasShown.Load() {
return
}
wb.Shown()
})
}
// Shown sends [events.Show] to all widgets from this one down. Also see
// [WidgetBase.DeferShown].
func (wb *WidgetBase) Shown() {
for _, cwb := range wb.AllWidgets() {
cwb.Send(events.Show)
}
wb.Events().activateStartFocus()
}
//////// Standard Box Model rendering
// RenderBoxGeom renders a box with the given geometry.
func (wb *WidgetBase) RenderBoxGeom(pos math32.Vector2, sz math32.Vector2, bs styles.Border) {
wb.Scene.Painter.Border(pos.X, pos.Y, sz.X, sz.Y, bs)
}
// RenderStandardBox renders the standard box model, using Actual size.
func (wb *WidgetBase) RenderStandardBox() {
pos := wb.Geom.Pos.Total
sz := wb.Geom.Size.Actual.Total
// (no background, or a transparent one, as the controls of the video
// players of npr.org, which painted the black of the player over their
// video when they were rendered after it)
if (wb.Styles.Background == nil || transparentBackground(wb.Styles.Background)) && wb.inTransparentOverlap() {
// An absolute or fixed widget is painted over the widgets that it overlaps,
// so without a background of its own it does not paint that of its
// parent over them (its actual background is kept for its content),
// and neither do the widgets in it without one (as the text over
// the percentage bars of Wikipedia). The same holds for a widget
// that overlaps the one before it by a negative margin (as the
// comments of news.ycombinator.com over their headers).
abg, fm := wb.Styles.ActualBackground, wb.Styles.FillMargin
clear := colors.Uniform(colors.Transparent)
wb.Styles.ActualBackground, wb.Styles.FillMargin = clear, false
wb.Scene.Painter.StandardBox(&wb.Styles, pos, sz, clear)
wb.Styles.ActualBackground, wb.Styles.FillMargin = abg, fm
return
}
if wb.Styles.FillMargin && wb.inTransparentOutOfFlow() {
// A widget with a background of its own in such an absolute or
// fixed widget does not fill its margin with the background of its
// parent either, which is not painted there (as the center line of
// the bars of the election results of nytimes.com, in an absolute
// marker over the bars, which painted the gray of the bars in its
// wide margin).
wb.Styles.FillMargin = false
defer func() { wb.Styles.FillMargin = true }()
}
if wb.inRoundedCorners() {
// A widget in the rounded corners of a parent that does not clip
// (whose radius is not in the bounds of the painter, as for a
// clipping one) does not fill its box with the background of the
// parent as a square over its corners, nor its own box without a
// background of its own (as the search box of the results of
// google.com, of which only the top and bottom of the border were
// shown, under the field in it with its background and radius).
abg, fm := wb.Styles.ActualBackground, wb.Styles.FillMargin
pabg := wb.parentActualBackground()
wb.Styles.FillMargin = false
if wb.Styles.Background == nil {
clear := colors.Uniform(colors.Transparent)
wb.Styles.ActualBackground, pabg = clear, clear
}
wb.Scene.Painter.StandardBox(&wb.Styles, pos, sz, pabg)
wb.Styles.ActualBackground, wb.Styles.FillMargin = abg, fm
return
}
if bg := wb.translucentOverlapBackground(); bg != nil {
// A translucent background of a widget that is painted over the
// widgets that it overlaps (as the dimming overlay of a modal
// dialog, as the consent dialog of nytimes.com) is blended with
// them, not with the background of its parent, which made it
// opaque (the window was gray).
abg, fm := wb.Styles.ActualBackground, wb.Styles.FillMargin
wb.Styles.ActualBackground, wb.Styles.FillMargin = bg, false
wb.Scene.Painter.StandardBox(&wb.Styles, pos, sz, colors.Uniform(colors.Transparent))
wb.Styles.ActualBackground, wb.Styles.FillMargin = abg, fm
return
}
wb.Scene.Painter.StandardBox(&wb.Styles, pos, sz, wb.parentActualBackground())
}
// seeThroughRoot returns, for a widget that does not paint an opaque
// background and is painted over the widgets that it overlaps (see
// [WidgetBase.inTransparentOverlap]), so that rendering it alone would paint
// over its last render (as the anti-aliased text of the items of the
// sidebar of MDN, of a transparent background, which grew bold as they were
// hovered), the nearest widget that it is in that paints an opaque
// background (or the top one), which is rendered again for it. It returns
// nil for other widgets, and for those in the layer of the scene, which is
// cleared as it is rendered again (see [sceneLayer]).
func (wb *WidgetBase) seeThroughRoot() *WidgetBase {
if wb.hasFlag(widgetInLayer) || paintsOpaqueBackground(wb) || !wb.inTransparentOverlap() {
return nil
}
for p := wb.parentWidget(); p != nil; p = p.parentWidget() {
if paintsOpaqueBackground(p) || p.parentWidget() == nil {
return p
}
}
return nil
}
// paintsOpaqueBackground returns whether the widget paints an opaque
// background over all of its box.
func paintsOpaqueBackground(wb *WidgetBase) bool {
bg := wb.Styles.Background
if bg == nil || wb.Styles.Opacity < 1 || wb.Styles.Border.Radius.Dots() != (sides.Floats{}) {
return false
}
if u, ok := bg.(*image.Uniform); ok {
_, _, _, a := u.RGBA()
return a == 0xffff
}
return true // (as an image, or a gradient)
}
// inRoundedCorners returns whether the widget is in the rounded corners of
// its parent, when the parent does not clip its children.
func (wb *WidgetBase) inRoundedCorners() bool {
p := wb.parentWidget()
if p == nil || !p.noClip() {
return false
}
r := p.Styles.Border.Radius.Dots()
radius := max(r.Top, r.Right, r.Bottom, r.Left)
if radius <= 0 {
return false
}
pb, b := p.Geom.TotalBBox, wb.Geom.TotalBBox
return float32(b.Min.Y-pb.Min.Y) < radius || float32(b.Min.X-pb.Min.X) < radius ||
float32(pb.Max.X-b.Max.X) < radius || float32(pb.Max.Y-b.Max.Y) < radius
}
// translucentOverlapBackground returns the background of the widget with
// its opacity, if it is a translucent color and the widget is painted over
// the widgets that it overlaps (see [WidgetBase.inTransparentOverlap]), or
// nil otherwise.
func (wb *WidgetBase) translucentOverlapBackground() image.Image {
u, ok := wb.Styles.Background.(*image.Uniform)
if !ok || colors.IsNil(u.C) || wb.Styles.StateLayer > 0 {
return nil
}
c := colors.AsRGBA(u.C)
if c.A == 255 && wb.Styles.Opacity >= 1 {
return nil
}
if !wb.inTransparentOverlap() {
return nil
}
if wb.Styles.Opacity < 1 {
return colors.Uniform(colors.ApplyOpacity(c, wb.Styles.Opacity))
}
return u
}
// inTransparentOverlap returns whether the widget is out of flow (see
// [WidgetBase.outOfFlow]) or overlaps the widget before it (see
// [WidgetBase.overlapsPrevious]), or is in one that is, with no
// backgrounds from it to the widget, so that it is painted over the
// widgets that it overlaps.
func (wb *WidgetBase) inTransparentOverlap() bool {
for w := wb; w != nil; w = w.parentWidget() {
if w.outOfFlow() || w.overlapsPrevious() {
return true
}
if w != wb && w.Styles.Background != nil {
return false
}
}
return false
}
// inTransparentOutOfFlow returns whether the widget is in an out of flow
// widget (see [WidgetBase.outOfFlow]) with no background between them
// (that one included), which paints nothing of its parent under it.
func (wb *WidgetBase) inTransparentOutOfFlow() bool {
for w := wb.parentWidget(); w != nil; w = w.parentWidget() {
if w.Styles.Background != nil && !transparentBackground(w.Styles.Background) {
return false
}
if w.outOfFlow() {
return true
}
}
return false
}
// overlapsPrevious returns whether the widget can overlap the widget
// before it in its parent, by a negative top or left margin of its own, or
// a negative bottom or right margin of that one, as in CSS.
func (wb *WidgetBase) overlapsPrevious() bool {
m := &wb.Styles.Margin
if m.Top.Dots < 0 || m.Left.Dots < 0 {
return true
}
p := wb.parentWidget()
if p == nil {
return false
}
i := wb.IndexInParent()
if i <= 0 {
return false
}
prev := AsWidget(p.Child(i - 1))
if prev == nil {
return false
}
pm := &prev.Styles.Margin
return pm.Bottom.Dots < 0 || pm.Right.Dots < 0
}
// RenderAllocBox renders the standard box model using Alloc size, instead of Actual.
func (wb *WidgetBase) RenderAllocBox() {
pos := wb.Geom.Pos.Total
sz := wb.Geom.Size.Alloc.Total
wb.Scene.Painter.StandardBox(&wb.Styles, pos, sz, wb.parentActualBackground())
}
//////// Widget position functions
// PointToRelPos translates a point in Scene pixel coords
// into relative position within node, based on the Content BBox
func (wb *WidgetBase) PointToRelPos(pt image.Point) image.Point {
return pt.Sub(wb.Geom.ContentBBox.Min)
}
// winBBox returns the RenderWindow based bounding box for the widget
// by adding the Scene position to the ScBBox
func (wb *WidgetBase) winBBox() image.Rectangle {
bb := wb.Geom.TotalBBox
if wb.Scene != nil {
return bb.Add(wb.Scene.SceneGeom.Pos)
}
return bb
}
// winPos returns the RenderWindow based position within the
// bounding box of the widget, where the x, y coordinates
// are the proportion across the bounding box to use:
// 0 = left / top, 1 = right / bottom
func (wb *WidgetBase) winPos(x, y float32) image.Point {
bb := wb.winBBox()
sz := bb.Size()
var pt image.Point
pt.X = bb.Min.X + int(math32.Round(float32(sz.X)*x))
pt.Y = bb.Min.Y + int(math32.Round(float32(sz.Y)*y))
return pt
}
//////// Profiling and Benchmarking, controlled by settings app bar
// ProfileToggle turns profiling on or off, which does both
// targeted profiling and global CPU and memory profiling.
func ProfileToggle() { //types:add
if profile.Profiling {
endTargetedProfile()
endCPUMemoryProfile()
} else {
startTargetedProfile()
startCPUMemoryProfile()
}
}
var (
// cpuProfileDir is the directory where the profile started
cpuProfileDir string
// cpuProfileFile is the file created by [startCPUMemoryProfile],
// which needs to be stored so that it can be closed in [endCPUMemoryProfile].
cpuProfileFile *os.File
)
// startCPUMemoryProfile starts the standard Go cpu and memory profiling.
func startCPUMemoryProfile() {
cpuProfileDir, _ = os.Getwd()
cpufnm := filepath.Join(cpuProfileDir, "cpu.prof")
fmt.Println("Starting standard cpu and memory profiling to:", cpufnm)
f, err := os.Create(cpufnm)
if errors.Log(err) == nil {
cpuProfileFile = f
errors.Log(pprof.StartCPUProfile(f))
}
}
// endCPUMemoryProfile ends the standard Go cpu and memory profiling.
func endCPUMemoryProfile() {
memfnm := filepath.Join(cpuProfileDir, "mem.prof")
fmt.Println("Ending standard cpu and memory profiling to:", memfnm)
pprof.StopCPUProfile()
errors.Log(cpuProfileFile.Close())
f, err := os.Create(memfnm)
if errors.Log(err) == nil {
runtime.GC() // get up-to-date statistics
errors.Log(pprof.WriteHeapProfile(f))
errors.Log(f.Close())
}
}
// startTargetedProfile starts targeted profiling using the [profile] package.
func startTargetedProfile() {
fmt.Println("Starting targeted profiling")
profile.Reset()
profile.Profiling = true
}
// endTargetedProfile ends targeted profiling and prints the report.
func endTargetedProfile() {
profile.Report(time.Millisecond)
profile.Profiling = false
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !js
package core
import (
"cogentcore.org/core/base/iox/imagex"
"image"
"cogentcore.org/core/colors"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint/renderers/rasterx"
"cogentcore.org/core/system/composer"
"golang.org/x/image/draw"
)
// grabRenderFrom grabs the rendered image from the given widget.
// If it returns nil, then the image could not be fetched.
func grabRenderFrom(w Widget) *image.RGBA {
wb := w.AsWidget()
scimg := wb.Scene.Renderer.Image()
if scimg == nil {
return nil
}
if wb.Geom.TotalBBox.Empty() { // the widget is offscreen
return nil
}
sz := wb.Geom.TotalBBox.Size()
img := image.NewRGBA(image.Rectangle{Max: sz})
draw.Draw(img, img.Bounds(), scimg, wb.Geom.TotalBBox.Min, draw.Src)
return img
}
func (ps *paintSource) Draw(c composer.Composer) {
cd := c.(*composer.ComposerDrawer)
rd := ps.renderer.(*rasterx.Renderer)
unchanged := len(ps.render) == 0
if !unchanged {
rd.Render(ps.render)
}
img := rd.Image()
cd.Drawer.Copy(ps.drawPos, img, img.Bounds(), ps.drawOp, unchanged)
}
func (ss *scrimSource) Draw(c composer.Composer) {
cd := c.(*composer.ComposerDrawer)
clr := colors.Uniform(colors.ApplyOpacity(colors.ToUniform(colors.Scheme.Scrim), 0.5))
cd.Drawer.Copy(ss.bbox.Min, clr, ss.bbox, draw.Over, composer.Unchanged) // (at its place)
}
//////// fillInsets
// fillInsetsSource is a [composer.Source] implementation for fillInsets.
type fillInsetsSource struct {
rbb, wbb image.Rectangle
// clr is the color to fill them with.
clr image.Image
}
func (ss *fillInsetsSource) Draw(c composer.Composer) {
cd := c.(*composer.ComposerDrawer)
fill := func(x0, y0, x1, y1 int) {
r := image.Rect(x0, y0, x1, y1)
if r.Dx() == 0 || r.Dy() == 0 {
return
}
cd.Drawer.Copy(r.Min, ss.clr, r, draw.Src, composer.Unchanged)
}
rb := ss.rbb
wb := ss.wbb
fill(0, 0, wb.Max.X, rb.Min.Y) // top
fill(0, rb.Max.Y, wb.Max.X, wb.Max.Y) // bottom
fill(rb.Max.X, 0, wb.Max.X, wb.Max.Y) // right
fill(0, 0, rb.Min.X, wb.Max.Y) // left
}
// fillInsets fills the window insets, if any (as behind the system bars
// on mobile), with the background color of the body of the top window
// scene, so that they match it, or else [colors.Scheme.Surface].
func (w *renderWindow) fillInsets(cp composer.Composer) {
// render geom and window geom
rg := w.SystemWindow.RenderGeom()
wg := math32.Geom2DInt{Size: w.SystemWindow.Size()}
// if our window geom is the same as our render geom, we have no
// window insets to fill
if wg == rg {
return
}
var clr image.Image = colors.Scheme.Surface
for _, st := range w.mains.stack.Values {
if st.Type != WindowStage || st.Scene == nil {
continue
}
// that of its body, which is what is seen, or else that of the
// scene, if it is opaque (a transparent one would leave the
// background of the system window)
opaque := func(bg image.Image) bool {
u, ok := bg.(*image.Uniform)
if !ok {
return false
}
_, _, _, a := u.RGBA()
return a == 0xffff
}
if bg := st.Scene.Styles.ActualBackground; opaque(bg) {
clr = bg
}
if bd := st.Scene.Body; bd != nil && opaque(bd.Styles.ActualBackground) {
clr = bd.Styles.ActualBackground
}
}
cp.Add(&fillInsetsSource{rbb: rg.Bounds(), wbb: wg.Bounds(), clr: clr}, w)
}
// getImager is implemented by offscreen.Drawer for [AssertRender].
type getImager interface {
GetImage() *image.RGBA
}
// windowImage returns a copy of the rendered image of the given window,
// for the tests (see [RenderImage]), or nil if it is closed.
func windowImage(rw *renderWindow) *image.RGBA {
// The image is copied under the window lock, which is held while it is
// composed, as paint events can still make the event loop render.
dw := rw.SystemWindow.Composer().(*composer.ComposerDrawer).Drawer
if !rw.SystemWindow.Lock() {
return nil
}
img := imagex.CloneAsRGBA(dw.(getImager).GetImage())
rw.SystemWindow.Unlock()
return img
}
// testImageName returns the name of the test image of the given name in
// testdata (see [AssertRender]): the same, other than on the web.
func testImageName(name string) string {
return name
}
// clearTestWindow is for the tests on the web (see the web version), and
// does nothing elsewhere, where the windows of tests are closed with all
// of their stages.
func clearTestWindow() {}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"image"
"cogentcore.org/core/colors"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint"
"cogentcore.org/core/paint/render"
"cogentcore.org/core/system/composer"
"golang.org/x/image/draw"
)
//////// Scene
// SceneSource returns a [composer.Source] for the given scene
// using the given suggested draw operation.
func SceneSource(sc *Scene, op draw.Op) composer.Source {
if sc.Painter.State == nil || sc.Renderer == nil {
return nil
}
render := sc.Painter.RenderDone()
return &paintSource{render: render, renderer: sc.Renderer, drawOp: op, drawPos: sc.SceneGeom.Pos}
}
// paintSource is the [composer.Source] for [paint.Painter] content, such as for a [Scene].
type paintSource struct {
// render is the render content.
render render.Render
// renderer is the renderer for drawing the painter content.
renderer render.Renderer
// drawOp is the [draw.Op] operation: [draw.Src] to copy source,
// [draw.Over] to alpha blend.
drawOp draw.Op
// drawPos is the position offset for the [Image] renderer to
// use in its Draw to a [composer.Drawer] (i.e., the [Scene] position).
drawPos image.Point
}
//////// Scrim
// ScrimSource returns a [composer.Source] for a scrim with the given bounding box.
func ScrimSource(bbox image.Rectangle) composer.Source {
return &scrimSource{bbox: bbox}
}
// scrimSource is a [composer.Source] implementation for a scrim.
type scrimSource struct {
bbox image.Rectangle
}
//////// Sprites
// SpritesSource returns a [composer.Source] for rendering [Sprites].
func SpritesSource(stage *Stage, mainScene *Scene) composer.Source {
stage.Sprites.Lock()
defer stage.Sprites.Unlock()
// Sprites are drawn in window coordinates, so the painter covers the
// scene from the top left of the window, as the scene is offset in it
// by the safe area on mobile platforms: it was the size of the scene,
// which clipped the sprites (such as a text cursor) below that height.
sz := math32.FromPoint(mainScene.SceneGeom.Pos.Add(mainScene.SceneGeom.Size))
if stage.spritePainter == nil || stage.spritePainter.Size != sz {
stage.spritePainter = paint.NewPainter(sz)
stage.spritePainter.UnitContext = mainScene.Styles.UnitContext
stage.spriteRenderer = paint.NewSourceRenderer(sz)
}
pc := stage.spritePainter
pc.Fill.Color = colors.Uniform(colors.Transparent)
pc.Clear()
stage.Sprites.Do(func(sl *SpriteList) {
for _, sp := range sl.Values {
if sp == nil || !sp.Active || sp.Draw == nil {
continue
}
sp.Draw(stage.spritePainter)
}
})
stage.Sprites.modified = false
render := stage.spritePainter.RenderDone()
return &paintSource{render: render, renderer: stage.spriteRenderer, drawOp: draw.Over, drawPos: image.Point{}}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"fmt"
"image"
"log"
"reflect"
"sync"
"sync/atomic"
"time"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/colors/matcolor"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/math32"
"cogentcore.org/core/system"
"cogentcore.org/core/system/composer"
"cogentcore.org/core/text/shaped"
"golang.org/x/image/draw"
)
// windowWait is a wait group for waiting for all the open window event
// loops to finish. It is incremented by [renderWindow.GoStartEventLoop]
// and decremented when the event loop terminates.
var windowWait sync.WaitGroup
// Wait waits for all windows to close and runs the main app loop.
// This should be put at the end of the main function if
// [Body.RunMainWindow] is not used.
//
// For offscreen testing, Wait is typically never called, as it is
// not necessary (the app will already terminate once all tests are done,
// and nothing needs to run on the main thread).
func Wait() {
waitCalled = true
// crashes that are not recovered, as in other goroutines, are saved
system.SaveCrashOutput()
defer func() { system.HandleRecover(recover()) }()
go func() {
defer func() { system.HandleRecover(recover()) }()
windowWait.Wait()
system.TheApp.Quit()
}()
system.TheApp.MainLoop()
}
var (
// currentRenderWindow is the current [renderWindow].
// On single window platforms (mobile, web, and offscreen),
// this is the only render window.
currentRenderWindow *renderWindow
// renderWindowGlobalMu is a mutex for any global state associated with windows
renderWindowGlobalMu sync.Mutex
)
func setCurrentRenderWindow(w *renderWindow) {
renderWindowGlobalMu.Lock()
currentRenderWindow = w
renderWindowGlobalMu.Unlock()
}
// getCurrentRenderWindow returns [currentRenderWindow] under its mutex, as
// the event loop of a window that is closed sets it to another window.
func getCurrentRenderWindow() *renderWindow {
renderWindowGlobalMu.Lock()
defer renderWindowGlobalMu.Unlock()
return currentRenderWindow
}
// renderWindow provides an outer "actual" window where everything is rendered,
// and is the point of entry for all events coming in from user actions.
//
// renderWindow contents are all managed by the [stages] stack that
// handles main [Stage] elements such as [WindowStage] and [DialogStage], which in
// turn manage their own stack of popup stage elements such as menus and tooltips.
// The contents of each Stage is provided by a Scene, containing Widgets,
// and the Stage Pixels image is drawn to the renderWindow in the renderWindow method.
//
// Rendering is handled by the [system.Drawer]. It is akin to a window manager overlaying Go image bitmaps
// on top of each other in the proper order, based on the [stages] stacking order.
// Sprites are managed by the main stage, as layered textures of the same size,
// to enable unlimited number packed into a few descriptors for standard sizes.
type renderWindow struct {
// name is the name of the window.
name string
// title is the displayed name of window, for window manager etc.
// Window object name is the internal handle and is used for tracking property info etc
title string
// SystemWindow is the OS-specific window interface, which handles
// all the os-specific functions, including delivering events etc
SystemWindow system.Window `json:"-" xml:"-"`
// textInput is the current text input state set with
// [WidgetBase.SetTextInput], and textInputWidget the widget that set it.
textInput *system.TextInput
textInputWidget Widget
// mains is the stack of main stages in this render window.
// The [RenderContext] in this manager is the original source for all Stages.
mains stages
// noEventsChan is a channel that the event loop closes after it
// handles an event when there are no events left in the window
// [events.Deque]. It is used internally for event handling in tests
// (see [Body.waitNoEvents]). It is protected by noEventsMu.
noEventsChan chan struct{}
// noEventsMu protects noEventsChan, which is set by the test
// goroutine and closed by the event loop.
noEventsMu sync.Mutex
// resizeMu serializes the resizes of the window by the goroutines of
// [Scene.ResizeToContent], so that they are applied in order.
resizeMu sync.Mutex
// flags are atomic renderWindow flags.
flags renderWindowFlags
// lastResize is the time stamp of the last render after a resize event,
// in Unix nanoseconds, used for efficient updating. It is atomic, as it
// is read before the render context is locked.
lastResize atomic.Int64
lastSpriteDraw time.Time
// paintWanted is whether the window has been woken (see
// [renderWindow.wake]) since the start of the last render pass.
paintWanted atomic.Bool
// occludedRetrying is whether the window is to render again after
// [occludedRetry], as it was occluded (see [renderWindow.renderAsync]).
occludedRetrying atomic.Bool
// blinkTimer wakes the window for the next blink of its active
// sprites while it is idle (see [renderWindow.idleUntilBlink]).
blinkTimer *time.Timer
// winRenderCounter is maintained under atomic locking to coordinate
// the launching of renderAsync functions and when those functions
// actually complete. Each time one is launched, the counter is incremented
// and each time one completes, it is decremented. This ensures
// everything is synchronized. Basically a [sync.WaitGroup] but we
// need to just bail if not done, not wait.
winRenderCounter atomic.Int32
}
// newRenderWindow creates a new window with given internal name handle,
// display name, and options. This is called by Stage.newRenderWindow
// which handles setting the opts and other infrastructure.
func newRenderWindow(name, title string, opts *system.NewWindowOptions) *renderWindow {
w := &renderWindow{}
w.name = name
w.title = title
var err error
w.SystemWindow, err = system.TheApp.NewWindow(opts)
if err != nil {
fmt.Printf("Cogent Core NewRenderWindow error: %v \n", err)
return nil
}
w.SystemWindow.SetName(title)
w.SystemWindow.SetTitleBarIsDark(matcolor.SchemeIsDark)
w.SystemWindow.SetCloseReqFunc(func(win system.Window) {
rc := w.renderContext()
rc.Lock()
if w.hidesOnClose() && !system.TheApp.IsQuitting() {
rc.Unlock()
if TheApp.SystemPlatform() == system.MacOS {
win.Hide()
} else {
win.Minimize()
}
return
}
w.flags.SetFlag(true, winClosing)
// ensure that everyone is closed first
for _, st := range w.mains.stack.Values {
if st == nil || st.Scene == nil || st.Scene.This == nil {
continue
}
if !st.Scene.Close() {
w.flags.SetFlag(false, winClosing)
rc.Unlock()
return
}
}
rc.Unlock()
win.Close()
})
return w
}
// hidesOnClose returns whether the window is hidden instead of closed
// when it is closed, as its first main stage has [Stage.HideOnClose].
// It must be called with the [renderContext] locked.
func (w *renderWindow) hidesOnClose() bool {
if w.mains.stack.Len() == 0 {
return false
}
st := w.mains.stack.Values[0]
return st != nil && st.HideOnClose
}
// MainScene returns the current [renderWindow.mains] top Scene,
// which is the current window or full window dialog occupying the RenderWindow.
func (w *renderWindow) MainScene() *Scene {
top := w.mains.top()
if top == nil {
return nil
}
return top.Scene
}
// RecycleMainWindow looks for an existing non-dialog window with the given Data.
// If it finds it, it shows it and returns true. Otherwise, it returns false.
// See [RecycleDialog] for a dialog version.
func RecycleMainWindow(data any) bool {
if data == nil {
return false
}
ew, got := mainRenderWindows.findData(data)
if !got {
return false
}
if DebugSettings.WindowEventTrace {
fmt.Printf("Win: %v getting recycled based on data match\n", ew.name)
}
ew.Raise()
return true
}
// setName sets name of this window and also the RenderWindow, and applies any window
// geometry settings associated with the new name if it is different from before
func (w *renderWindow) setName(name string) {
curnm := w.name
isdif := curnm != name
w.name = name
if w.SystemWindow != nil {
w.SystemWindow.SetName(name)
}
if isdif && w.SystemWindow != nil && !w.SystemWindow.Is(system.Fullscreen) {
wgp, sc := theWindowGeometrySaver.get(w.title, "")
if wgp != nil {
theWindowGeometrySaver.settingStart()
if w.SystemWindow.Size() != wgp.Size || w.SystemWindow.Position(sc) != wgp.Pos {
if DebugSettings.WindowGeometryTrace {
log.Printf("WindowGeometry: SetName setting geom for window: %v pos: %v size: %v\n", w.name, wgp.Pos, wgp.Size)
}
w.SystemWindow.SetGeometry(false, wgp.Pos, wgp.Size, sc)
system.TheApp.SendEmptyEvent()
}
theWindowGeometrySaver.settingEnd()
}
}
}
// setTitle sets title of this window and its underlying SystemWin.
func (w *renderWindow) setTitle(title string) {
w.title = title
if w.SystemWindow != nil {
w.SystemWindow.SetTitle(title)
}
}
// SetStageTitle sets the title of the underlying [system.Window] to the given stage title
// combined with the [renderWindow] title.
func (w *renderWindow) SetStageTitle(title string) {
if title == "" {
title = w.title
} else if title != w.title {
title = title + " • " + w.title
}
if w.SystemWindow != nil {
w.SystemWindow.SetTitle(title)
}
}
// logicalDPI returns the current logical dots-per-inch resolution of the
// window, which should be used for most conversion of standard units --
// physical DPI can be found in the Screen
func (w *renderWindow) logicalDPI() float32 {
if w.SystemWindow == nil {
sc := system.TheApp.Screen(0)
if sc == nil {
return 160 // null default
}
return sc.LogicalDPI
}
return w.SystemWindow.LogicalDPI()
}
// stepZoom calls [SetZoom] with the current zoom plus 10 times the given number of steps.
func (w *renderWindow) stepZoom(steps float32) {
sc := w.SystemWindow.Screen()
curZoom := AppearanceSettings.Zoom
screenName := ""
sset, ok := AppearanceSettings.Screens[sc.Name]
if ok {
screenName = sc.Name
curZoom = sset.Zoom
}
w.setZoom(curZoom+10*steps, screenName)
}
// setZoom sets [AppearanceSettingsData.Zoom] to the given value and then triggers
// necessary updating and makes a snackbar. If screenName is non-empty, then the
// zoom is set on the screen-specific settings, instead of the global.
func (w *renderWindow) setZoom(zoom float32, screenName string) {
zoom = math32.Clamp(zoom, 10, 500)
if screenName != "" {
sset := AppearanceSettings.Screens[screenName]
sset.Zoom = zoom
AppearanceSettings.Screens[screenName] = sset
} else {
AppearanceSettings.Zoom = zoom
}
AppearanceSettings.Apply()
UpdateAll()
errors.Log(SaveSettings(AppearanceSettings))
if ms := w.MainScene(); ms != nil {
b := NewBody().AddSnackbarText(fmt.Sprintf("%.f%%", zoom))
NewStretch(b)
b.AddSnackbarIcon(icons.Remove, func(e events.Event) {
w.stepZoom(-1)
})
b.AddSnackbarIcon(icons.Add, func(e events.Event) {
w.stepZoom(1)
})
b.AddSnackbarButton("Reset", func(e events.Event) {
w.setZoom(100, screenName)
})
b.DeleteChildByName("stretch")
b.RunSnackbar(ms)
}
}
// resized updates Scene sizes after a window has been resized.
// It is called on any geometry update, including move and
// DPI changes, so it detects what actually needs to be updated.
func (w *renderWindow) resized() {
rc := w.renderContext()
if !w.isVisible() {
rc.visible = false
return
}
w.SystemWindow.Lock()
rg := w.SystemWindow.RenderGeom()
w.SystemWindow.Unlock()
curRg := rc.geom
curDPI := w.logicalDPI()
if curRg == rg {
newDPI := false
if rc.logicalDPI != curDPI {
rc.logicalDPI = curDPI
newDPI = true
}
if DebugSettings.WindowEventTrace {
fmt.Printf("Win: %v same-size resized: %v newDPI: %v\n", w.name, curRg, newDPI)
}
if w.mains.resize(rg) || newDPI {
// The scenes are restyled by their next update.
for _, st := range w.mains.stack.Values {
st.Scene.lastRender.invalidate()
}
}
return
}
rc.logicalDPI = curDPI
if !w.isVisible() {
rc.visible = false
if DebugSettings.WindowEventTrace {
fmt.Printf("Win: %v Resized already closed\n", w.name)
}
return
}
if DebugSettings.WindowEventTrace {
fmt.Printf("Win: %v Resized from: %v to: %v\n", w.name, curRg, rg)
}
rc.geom = rg
rc.visible = true
w.flags.SetFlag(true, winResize)
w.mains.resize(rg)
// On mobile, the focused widget is kept in view, as when the
// virtual keyboard for typing into it shrinks the window, after it
// was scrolled into view for getting the focus.
if TheApp.SystemPlatform().IsMobile() {
if st := w.mains.top(); st != nil && st.Scene != nil {
if f := st.Scene.Events.focus; f != nil {
fw := f.AsWidget()
fw.Defer(func() { fw.ScrollToThis() })
}
}
}
if DebugSettings.WindowGeometryTrace {
log.Printf("WindowGeometry: recording from Resize\n")
}
theWindowGeometrySaver.record(w)
}
// Raise requests that the window be at the top of the stack of windows,
// and receive focus. If it is minimized, it will be un-minimized. This
// is the only supported mechanism for un-minimizing. This also sets
// [currentRenderWindow] to the window.
func (w *renderWindow) Raise() {
w.SystemWindow.Raise()
setCurrentRenderWindow(w)
}
// minimize requests that the window be minimized, making it no longer
// visible or active; rendering should not occur for minimized windows.
func (w *renderWindow) minimize() {
w.SystemWindow.Minimize()
}
// closeReq requests that the window be closed, which could be rejected.
// It firsts unlocks and then locks the [renderContext] to prevent deadlocks.
// If this is called asynchronously outside of the main event loop,
// [renderWindow.SystemWin.closeReq] should be called directly instead.
func (w *renderWindow) closeReq() {
rc := w.renderContext()
rc.Unlock()
w.SystemWindow.CloseReq()
rc.Lock()
}
// closed frees any resources after the window has been closed.
func (w *renderWindow) closed() {
AllRenderWindows.delete(w)
mainRenderWindows.delete(w)
dialogRenderWindows.delete(w)
if DebugSettings.WindowEventTrace {
fmt.Printf("Win: %v Closed\n", w.name)
}
if pfw := AllRenderWindows.last(); pfw != nil {
if DebugSettings.WindowEventTrace {
fmt.Printf("Win: %v getting restored focus after: %v closed\n", pfw.name, w.name)
}
pfw.Raise()
}
}
// isClosed reports if the window has been closed
func (w *renderWindow) isClosed() bool {
return w.SystemWindow.IsClosed() || w.mains.stack.Len() == 0
}
// isVisible is the main visibility check; don't do any window updates if not visible!
func (w *renderWindow) isVisible() bool {
if w == nil || w.SystemWindow == nil || w.isClosed() || w.flags.HasFlag(winClosing) || !w.SystemWindow.IsVisible() {
return false
}
return true
}
// goStartEventLoop starts the event processing loop for this window in a new
// goroutine, and returns immediately. Adds to WindowWait wait group so a main
// thread can wait on that for all windows to close.
func (w *renderWindow) goStartEventLoop() {
windowWait.Add(1)
go w.eventLoop()
}
// eventLoop runs the event processing loop for the RenderWindow -- grabs system
// events for the window and dispatches them to receiving nodes, and manages
// other state etc (popups, etc).
func (w *renderWindow) eventLoop() {
defer func() { system.HandleRecover(recover()) }()
d := &w.SystemWindow.Events().Deque
for {
if w.flags.HasFlag(winStopEventLoop) {
w.flags.SetFlag(false, winStopEventLoop)
break
}
e := d.NextEvent()
if w.flags.HasFlag(winStopEventLoop) {
w.flags.SetFlag(false, winStopEventLoop)
break
}
w.handleEvent(e)
w.signalNoEvents(d)
}
if DebugSettings.WindowEventTrace {
fmt.Printf("Win: %v out of event loop\n", w.name)
}
windowWait.Done()
// our last act must be self destruction!
w.mains.deleteAll()
}
// signalNoEvents closes [renderWindow.noEventsChan], if a test waits on it,
// when there are no events left in the given deque. It is closed instead of
// sent on, so that the event loop never blocks on it.
func (w *renderWindow) signalNoEvents(d *events.Deque) {
w.noEventsMu.Lock()
defer w.noEventsMu.Unlock()
if w.noEventsChan == nil || d.Len() > 0 {
return
}
close(w.noEventsChan)
w.noEventsChan = nil
}
// handleEvent processes given events.Event.
// All event processing operates under a RenderContext.Lock
// so that no rendering update can occur during event-driven updates.
// Because rendering itself is event driven, this extra level of safety
// is redundant in this case, but other non-event-driven updates require
// the lock protection.
func (w *renderWindow) handleEvent(e events.Event) {
rc := w.renderContext()
rc.Lock()
// we manually handle Unlock's in this function instead of deferring
// it to avoid a cryptic "sync: can't unlock an already unlocked Mutex"
// error when panicking in the rendering goroutine. This is critical for
// debugging on Android. TODO: maybe figure out a more sustainable approach to this.
et := e.Type()
if DebugSettings.EventTrace && et != events.WindowPaint && et != events.MouseMove {
log.Println("Window got event", e)
}
if et != events.WindowPaint {
w.wake() // events can change anything (see idle.go)
}
if et >= events.Window && et <= events.WindowPaint {
w.handleWindowEvents(e)
rc.Unlock()
return
}
if ce, ok := e.(*events.CustomEvent); ok {
if f, ok := ce.Data.(windowFunc); ok { // from [WidgetBase.runInWindow]
f()
rc.Unlock()
return
}
}
if DebugSettings.EventTrace && (!w.isVisible() || w.SystemWindow.Is(system.Minimized)) {
log.Println("got event while invisible:", e)
log.Println("w.isClosed:", w.isClosed(), "winClosing flag:", w.flags.HasFlag(winClosing), "syswin !isvis:", !w.SystemWindow.IsVisible(), "minimized:", w.SystemWindow.Is(system.Minimized))
}
// fmt.Printf("got event type: %v: %v\n", et.BitIndexString(), evi)
w.mains.mainHandleEvent(e)
rc.Unlock()
}
func (w *renderWindow) handleWindowEvents(e events.Event) {
et := e.Type()
switch et {
case events.WindowPaint:
e.SetHandled()
rc := w.renderContext()
rc.Unlock() // one case where we need to break lock
w.renderWindow()
rc.Lock()
w.mains.runDeferred() // note: must be outside of locks in renderWindow
case events.WindowResize:
e.SetHandled()
w.resized()
w.redrawAll()
case events.Window:
ev := e.(*events.WindowEvent)
switch ev.Action {
case events.WinClose:
// The system window is already closed (so it cannot be locked)
// when it was closed by this event loop, as by the OK button of
// a dialog: its close sends this event and destroys the window
// before the loop gets the event. It is still removed from the
// windows, raising the next one, and its event loop stops.
e.SetHandled()
w.flags.SetFlag(true, winStopEventLoop)
if w.SystemWindow.Lock() {
w.closed()
w.SystemWindow.Unlock()
} else {
w.closed()
}
case events.WinMinimize:
e.SetHandled()
// On mobile, the app goes into the background, where it is
// often closed, so the edits in progress, as in a text field,
// are completed, as when the focus leaves them.
if TheApp.SystemPlatform().IsMobile() {
if st := w.mains.top(); st != nil && st.Scene != nil {
st.Scene.Events.focusClear()
}
}
// on mobile platforms, we need to set the size to 0 so that it detects a size difference
// and lets the size event go through when we come back later
// if Platform().IsMobile() {
// w.Scene.Geom.Size = image.Point{}
// }
case events.WinShow:
e.SetHandled()
// note that this is sent delayed by driver
if DebugSettings.WindowEventTrace {
fmt.Printf("Win: %v got show event\n", w.name)
}
w.redrawAll()
case events.WinMove:
e.SetHandled()
// fmt.Printf("win move: %v\n", w.SystemWin.Position())
if DebugSettings.WindowGeometryTrace {
log.Printf("WindowGeometry: recording from Move\n")
}
w.SystemWindow.ConstrainFrame(true) // top only
theWindowGeometrySaver.record(w)
case events.WinFocus:
// if we are not already the last in AllRenderWins, we go there,
// as this allows focus to be restored to us in the future
AllRenderWindows.moveToEnd(w)
if !w.flags.HasFlag(winGotFocus) {
w.flags.SetFlag(true, winGotFocus)
if DebugSettings.WindowEventTrace {
fmt.Printf("Win: %v got focus\n", w.name)
}
} else {
if DebugSettings.WindowEventTrace {
fmt.Printf("Win: %v got extra focus\n", w.name)
}
}
setCurrentRenderWindow(w)
case events.WinFocusLost:
if DebugSettings.WindowEventTrace {
fmt.Printf("Win: %v lost focus\n", w.name)
}
w.flags.SetFlag(false, winGotFocus)
case events.ScreenUpdate:
if DebugSettings.WindowEventTrace {
log.Println("Win: ScreenUpdate", w.name, screenConfig())
}
// the system color theme may have changed
themeChanged := AppearanceSettings.Theme == ThemeAuto && TheApp.IsDark() != matcolor.SchemeIsDark
if themeChanged {
AppearanceSettings.Apply()
}
if !TheApp.Platform().IsMobile() { // native desktop
if TheApp.NScreens() > 0 {
if TheApp.Platform() == system.Offscreen && !themeChanged {
// note: this improves testing reliability
AppearanceSettings.Apply()
}
UpdateAll()
}
} else {
if themeChanged {
UpdateAll()
}
w.resized()
}
}
}
}
//////// Rendering
// renderParams are the key [renderWindow] params that determine if
// a scene needs to be restyled since last render, if these params change.
type renderParams struct {
// logicalDPI is the current logical dots-per-inch resolution of the
// window, which should be used for most conversion of standard units.
logicalDPI float32
// Geometry of the rendering window, in actual "dot" pixels used for rendering.
geom math32.Geom2DInt
}
// needsRestyle returns true if the current render context
// params differ from those used in last render.
func (rp *renderParams) needsRestyle(rc *renderContext) bool {
return rp.logicalDPI != rc.logicalDPI || rp.geom != rc.geom
}
// invalidate makes [renderParams.needsRestyle] return true until the next
// [renderParams.saveRender], so that the scene is restyled by its next update.
func (rp *renderParams) invalidate() {
rp.logicalDPI = -1 // never a valid DPI
}
// saveRender grabs current render context params
func (rp *renderParams) saveRender(rc *renderContext) {
rp.logicalDPI = rc.logicalDPI
rp.geom = rc.geom
}
// renderContext provides rendering context from outer RenderWindow
// window to Stage and Scene elements to inform styling, layout
// and rendering. It also has the main Mutex for any updates
// to the window contents: use Lock for anything updating.
type renderContext struct {
// logicalDPI is the current logical dots-per-inch resolution of the
// window, which should be used for most conversion of standard units.
logicalDPI float32
// Geometry of the rendering window, in actual "dot" pixels used for rendering.
geom math32.Geom2DInt
// visible is whether the window is visible and should be rendered to.
visible bool
// rebuild is whether to force a rebuild of all Scene elements.
rebuild bool
// restyle is whether to restyle and lay out all Scenes, as when the
// fonts that texts are measured with have changed.
restyle bool
// TextShaper is the text shaping system for the render context,
// for doing text layout.
textShaper shaped.Shaper
// render mutex for locking out rendering and any destructive updates.
// It is locked at the [renderWindow] level during rendering and
// event processing to provide exclusive blocking of external updates.
// Use [WidgetBase.AsyncLock] from any outside routine to grab the lock before
// doing modifications.
sync.Mutex
}
// newRenderContext returns a new [renderContext] initialized according to
// the main Screen size and LogicalDPI as initial defaults.
// The actual window size is set during Resized method, which is typically
// called after the window is created by the OS.
func newRenderContext() *renderContext {
rc := &renderContext{}
scr := system.TheApp.Screen(0)
if scr != nil {
rc.geom.SetRect(image.Rectangle{Max: scr.PixelSize})
rc.logicalDPI = scr.LogicalDPI
} else {
rc.geom = math32.Geom2DInt{Size: image.Pt(1080, 720)}
rc.logicalDPI = 160
}
rc.visible = true
rc.textShaper = shaped.NewShaper()
return rc
}
func (rc *renderContext) String() string {
str := fmt.Sprintf("Geom: %s Visible: %v", rc.geom, rc.visible)
return str
}
func (w *renderWindow) renderContext() *renderContext {
return w.mains.renderContext
}
//////// renderWindow
// renderWindow performs all rendering based on current Stages config.
// It locks and unlocks the renderContext itself, which is necessary so that
// there is a moment for other goroutines to acquire the lock and get necessary
// updates through (such as in offscreen testing).
func (w *renderWindow) renderWindow() {
// anything that needs an update from now on wakes the window again,
// if it goes idle in this pass (see idle.go)
w.paintWanted.Store(false)
if w.winRenderCounter.Load() > 0 { // still working
w.flags.SetFlag(true, winRenderSkipped)
if DebugSettings.WindowRenderTrace {
log.Printf("RenderWindow: still rendering, skipped: %v\n", w.name)
}
return
}
offscreen := TheApp.Platform() == system.Offscreen
sinceResize := time.Since(time.Unix(0, w.lastResize.Load()))
if !offscreen && sinceResize < 100*time.Millisecond {
// get many rapid updates during resizing, so just rerender last one if so.
// this works best in practice after a lot of experimentation.
w.flags.SetFlag(true, winRenderSkipped)
w.SystemWindow.Composer().Redraw()
return
}
// A hidden (closed with HideOnClose) or minimized window is not updated:
// an update renders the scenes into their painters, whose render lists
// are only taken (and reset) when the window is drawn, so they would
// grow with every update until it is shown again, and then be drawn all
// at once (taking minutes, for an app updated for hours while hidden).
// The updates stay pending (in the flags of the scenes and widgets)
// until it is shown again.
if !w.isVisible() || w.SystemWindow.Is(system.Minimized) {
if DebugSettings.WindowRenderTrace {
log.Printf("RenderWindow: skipping update on inactive / minimized window: %v\n", w.name)
}
// it is woken by the events of being shown again
w.goIdle()
return
}
rc := w.renderContext()
rc.Lock()
defer func() {
rc.rebuild = false
rc.restyle = false
rc.Unlock()
}()
rebuild := rc.rebuild
stageMods, sceneMods := w.mains.updateAll() // handles all Scene / Widget updates!
top := w.mains.top()
if top == nil || w.mains.stack.Len() == 0 {
w.goIdle()
return
}
spriteMods := top.Sprites.IsModified()
spriteUpdateTime := TimingSettings.CursorBlinkTime
if spriteUpdateTime == 0 {
spriteUpdateTime = 500 * time.Millisecond
}
// active sprites, such as the blinking text cursor, are drawn again
// periodically while the window has focus, but there is nothing to
// draw again when there are none (an idle window does nothing).
if w.flags.HasFlag(winGotFocus) && time.Since(w.lastSpriteDraw) > spriteUpdateTime && top.Sprites.hasActive() {
spriteMods = true
}
if !spriteMods && !rebuild && !stageMods && !sceneMods { // nothing to do!
if w.flags.HasFlag(winRenderSkipped) {
w.flags.SetFlag(false, winRenderSkipped)
} else {
// animations run at every paint event; otherwise, the paint
// events are paused until something needs an update
if !w.mains.hasAnimations() {
w.idleUntilBlink(top, spriteUpdateTime)
}
return
}
}
if DebugSettings.WindowRenderTrace {
log.Println("RenderWindow: doing render:", w.name)
log.Println("rebuild:", rebuild, "stageMods:", stageMods, "sceneMods:", sceneMods)
}
if !w.SystemWindow.Lock() {
if DebugSettings.WindowRenderTrace {
log.Printf("RenderWindow: window was closed: %v\n", w.name)
}
return
}
// now we go in the proper bottom-up order to generate the [render.Scene]
cp := w.SystemWindow.Composer()
// On mobile, the system window, with its drawer, is destroyed while
// the app is in the background, and it can be before the window is
// made (when the app starts with the screen off), so there is nothing
// to render to then (the composer is a nil pointer). The window is
// rendered again when it is shown.
if reflectx.IsNil(reflect.ValueOf(cp)) {
w.SystemWindow.Unlock()
w.goIdle() // (woken by the events of being shown again)
return
}
cp.Start()
sm := &w.mains
n := sm.stack.Len()
w.fillInsets(cp) // only does something on non-js
// first, find the top-level window:
winIndex := 0
var winScene *Scene
for i := n - 1; i >= 0; i-- {
st := sm.stack.Values[i]
if st.Type == WindowStage {
if DebugSettings.WindowRenderTrace {
log.Println("GatherScenes: main Window:", st.String())
}
winScene = st.Scene
winIndex = i
winScene.addRenderSources(cp, draw.Src, true)
break
}
}
if winScene == nil { // the window was closed, leaving other stages such as a dialog
w.SystemWindow.Unlock()
return
}
// then add everyone above that
for i := winIndex + 1; i < n; i++ {
st := sm.stack.Values[i]
if st.Scrim && i == n-1 {
// (in the window, where the scene is drawn at its position)
cp.Add(ScrimSource(winScene.Geom.TotalBBox.Add(winScene.SceneGeom.Pos)), &st.Scrim)
}
st.Scene.addRenderSources(cp, draw.Over, false)
if DebugSettings.WindowRenderTrace {
log.Println("GatherScenes: overlay Stage:", st.String())
}
}
// then add the popups for the top main stage
for _, st := range top.popups.stack.Values {
st.Scene.addRenderSources(cp, draw.Over, false)
if DebugSettings.WindowRenderTrace {
log.Println("GatherScenes: popup:", st.String())
}
}
cp.Add(SpritesSource(top, winScene), &top.Sprites)
w.lastSpriteDraw = time.Now()
w.SystemWindow.Unlock()
if offscreen || w.flags.HasFlag(winResize) || sinceResize < 500*time.Millisecond {
w.winRenderCounter.Add(1)
w.renderAsync(cp)
if w.flags.HasFlag(winResize) {
w.lastResize.Store(time.Now().UnixNano())
}
w.flags.SetFlag(false, winResize)
} else {
// note: it is critical to set *before* going into loop
// because otherwise we can lose an entire pass before the goroutine starts!
// function will turn flag off when it finishes.
w.winRenderCounter.Add(1)
go w.renderAsync(cp)
}
}
// occludedRetry is how often a window checks whether it is still occluded
// (hidden), so that the GPU does not draw it (see [renderWindow.renderAsync]).
const occludedRetry = 100 * time.Millisecond
// renderAsync is the implementation of the main render pass,
// which is usually called in a goroutine.
// It calls the Compose function on the given composer.
func (w *renderWindow) renderAsync(cp composer.Composer) {
if !w.SystemWindow.Lock() {
w.winRenderCounter.Add(-1)
// fmt.Println("renderAsync SystemWindow lock fail")
return
}
// pr := profile.Start("Compose")
// fmt.Println("start compose")
cp.Compose()
// pr.End()
occluded := isOccluded(cp)
w.SystemWindow.Unlock()
// Nothing was drawn while the window is occluded (hidden), which can
// last until it is shown, without an event: so it is idle, and checks
// every occludedRetry whether it still is, which is much cheaper than
// rendering, to render again once it is not.
if occluded {
w.flags.SetFlag(true, winRenderSkipped)
w.goIdle()
if !w.occludedRetrying.Swap(true) { // (one retry at a time)
time.AfterFunc(occludedRetry, func() { w.retryOccluded(cp) })
}
}
w.winRenderCounter.Add(-1)
}
// isOccluded returns whether the given composer did not draw, as its
// window is occluded (hidden), if it can tell (see [gpu.Surface.Occluded]).
func isOccluded(cp composer.Composer) bool {
od, ok := cp.(interface{ Occluded() bool })
return ok && od.Occluded()
}
// retryOccluded wakes the window, to render it again, once the given
// composer of it is no longer occluded, checking again after
// occludedRetry while it is (see [renderWindow.renderAsync]).
func (w *renderWindow) retryOccluded(cp composer.Composer) {
if !w.SystemWindow.Lock() { // closed
w.occludedRetrying.Store(false)
return
}
occluded := isOccluded(cp)
w.SystemWindow.Unlock()
if occluded {
time.AfterFunc(occludedRetry, func() { w.retryOccluded(cp) })
return
}
w.occludedRetrying.Store(false)
w.SystemWindow.PaintWake()
}
// RenderSource returns the [render.Render] state from the [Scene.Painter].
func (sc *Scene) RenderSource(op draw.Op) composer.Source {
sc.setFlag(false, sceneImageUpdated)
return SceneSource(sc, op)
}
// renderWindowFlags are atomic bit flags for [renderWindow] state.
// They must be atomic to prevent race conditions.
type renderWindowFlags int32 //enums:bitflag -atomic -trim-prefix win
const (
// winResize indicates that the window was just resized.
winResize renderWindowFlags = iota
// winStopEventLoop indicates that the event loop should be stopped.
winStopEventLoop
// winClosing is whether the window is closing.
winClosing
// winGotFocus indicates that have we received focus.
winGotFocus
// winRenderSkipped indicates that a render update was skipped, so
// another update will be run to ensure full updating.
winRenderSkipped
)
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"image"
"slices"
"sync/atomic"
"cogentcore.org/core/colors"
"cogentcore.org/core/cursors"
"cogentcore.org/core/enums"
"cogentcore.org/core/events"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint"
"cogentcore.org/core/paint/render"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/sides"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/system"
"cogentcore.org/core/text/shaped"
"cogentcore.org/core/tree"
)
// Scene contains a [Widget] tree, rooted in an embedded [Frame] layout,
// which renders into its own [paint.Painter]. The [Scene] is set in a
// [Stage], which the [Scene] has a pointer to.
//
// Each [Scene] contains state specific to its particular usage
// within a given [Stage] and overall rendering context, representing the unit
// of rendering in the Cogent Core framework.
type Scene struct { //core:no-new
Frame
// Body provides the main contents of scenes that use control Bars
// to allow the main window contents to be specified separately
// from that dynamic control content. When constructing scenes using
// a [Body], you can operate directly on the [Body], which has wrappers
// for most major Scene functions.
Body *Body `json:"-" xml:"-" set:"-"`
// WidgetInit is a function called on every newly created [Widget].
// This can be used to set global configuration and styling for all
// widgets in conjunction with [App.SceneInit].
WidgetInit func(w Widget) `json:"-" xml:"-" edit:"-"`
// Bars are functions for creating control bars,
// attached to different sides of a [Scene]. Functions
// are called in forward order so first added are called first.
Bars sides.Sides[BarFuncs] `json:"-" xml:"-" set:"-"`
// Data is the optional data value being represented by this scene.
// Used e.g., for recycling views of a given item instead of creating new one.
Data any
// Size and position relative to overall rendering context.
SceneGeom math32.Geom2DInt `edit:"-" set:"-"`
// painter for rendering all widgets in the scene.
Painter paint.Painter `copier:"-" json:"-" xml:"-" display:"-" set:"-"`
// event manager for this scene.
Events Events `copier:"-" json:"-" xml:"-" set:"-"`
// current stage in which this Scene is set.
Stage *Stage `copier:"-" json:"-" xml:"-" set:"-"`
// Animations are the currently active [Animation]s in this scene.
Animations []*Animation `json:"-" xml:"-" set:"-"`
// renderBBoxes indicates to render colored bounding boxes for all of the widgets
// in the scene. This is enabled by the [Inspector] in select element mode.
renderBBoxes bool
// renderBBoxHue is current hue for rendering bounding box in [Scene.RenderBBoxes] mode.
renderBBoxHue float32
// spaceChanged is whether the padding or margins of a widget, of
// percentages, changed with the sizes of the last layout (see
// [WidgetBase.styleSizeUpdate]), for [Scene.LayoutScene] to lay it out
// again with them.
spaceChanged bool
// selectedWidget is the currently selected/hovered widget through the [Inspector] selection mode
// that should be highlighted with a background color.
selectedWidget Widget
// selectedWidgetChan is the channel on which the selected widget through the inspect editor
// selection mode is transmitted to the inspect editor after the user is done selecting.
selectedWidgetChan chan Widget `json:"-" xml:"-"`
// selectedText is a list of [Text] elements that have been selected,
// to support multi-text selection.
selectedText []*Text
// source renderer for rendering the scene
Renderer render.Renderer `copier:"-" json:"-" xml:"-" display:"-" set:"-"`
// sizingSize is the size, in dots, that the scene of a new window is
// expected to have, which determines its [SizeClasses] while it is sized
// to its content (see [WidgetBase.SceneSize]).
sizingSize image.Point
// lastRender captures key params from last render.
// If different then a new ApplyStyleScene is needed.
lastRender renderParams
// showIter counts up at start of showing a Scene
// to trigger Show event and other steps at start of first show
showIter int
// directRenders are widgets that render directly to the [RenderWindow]
// instead of rendering into the Scene Painter.
directRenders []Widget
// layer is the compositing layer of the scene, into which its fixed
// widgets are rendered (see [sceneLayer]).
layer sceneLayer
// this is our own text shaper in case we don't have a render context
textShaper shaped.Shaper
// offscreen is the render context of a scene that is not in a window,
// as that of [Scene.PreLayout], which shares the DPI and the text shaper
// of the window of another scene.
offscreen *renderContext
// hasShown is whether this scene has been shown.
// This is used to ensure that [events.Show] is only sent once.
// It is atomic, unlike the flags, as [WidgetBase.AsyncLock]
// reads it before it has the lock, when the scene has no
// render context.
hasShown atomic.Bool
// shown is closed when the scene has been shown (with hasShown), for
// [WidgetBase.AsyncLock] to wait on.
shown chan struct{}
// asyncLocked is the render context locked by [WidgetBase.AsyncLock]
// (or [WidgetBase.AsyncLockIfShown]), which [WidgetBase.AsyncUnlock]
// unlocks. The render context of the scene can be nil in between, as
// it briefly is while a new window is created, and that must not
// leave the render context locked. It is only accessed with the lock.
asyncLocked *renderContext
// flags are bit flags for [Scene] state. They are only accessed
// in the event loop or with the lock of the render context, as
// with [WidgetBase.AsyncLock].
flags sceneFlags
}
// sceneFlags are bit flags for [Scene] state.
type sceneFlags int32 //enums:bitflag -trim-prefix scene
const (
// sceneUpdating means the Scene is in the process of sceneUpdating.
// It is set for any kind of tree-level update.
// Skip any further update passes until it goes off.
sceneUpdating sceneFlags = iota
// sceneNeedsRender is whether anything in the Scene needs to be re-rendered
// (but not necessarily the whole scene itself).
sceneNeedsRender
// sceneNeedsLayout is whether the Scene needs a new layout pass.
sceneNeedsLayout
// sceneHasDeferred is whether the Scene has elements with Deferred functions.
sceneHasDeferred
// sceneImageUpdated indicates that the Scene's image has been updated
// e.g., due to a render or a resize. This is reset by the
// global [RenderWindow] rendering pass, so it knows whether it needs to
// copy the image up to the GPU or not.
sceneImageUpdated
// sceneContentSizing means that this scene is currently doing a
// contentSize computation to compute the size of the scene
// (for sizing window for example). Affects layout size computation.
sceneContentSizing
)
// hasFlag returns whether the given flag is set.
func (sc *Scene) hasFlag(f sceneFlags) bool {
return sc.flags&(1<<uint32(f)) != 0
}
// setFlag sets the given flags to the given value.
// Setting the flags that drive updates wakes the window (see idle.go).
func (sc *Scene) setFlag(on bool, f ...enums.BitFlag) {
sc.flags.SetFlag(on, f...)
if on && wakeFlags(f) {
sc.wake()
}
}
// newBodyScene creates a new Scene for use with an associated Body that
// contains the main content of the Scene (e.g., a Window, Dialog, etc).
// It will be constructed from the Bars-configured control bars on each
// side, with the given Body as the central content.
func newBodyScene(body *Body) *Scene {
sc := NewScene(body.Name + " scene")
sc.Body = body
// need to set parent immediately so that SceneInit works,
// but can not add it yet because it may go elsewhere due
// to app bars
tree.SetParent(body, sc)
return sc
}
// NewScene creates a new [Scene] object without a [Body], e.g., for use
// in a Menu, Tooltip or other such simple popups or non-control-bar Scenes.
func NewScene(name ...string) *Scene {
sc := tree.New[Scene]()
if len(name) > 0 {
sc.SetName(name[0])
}
sc.Events.scene = sc
return sc
}
func (sc *Scene) Init() {
sc.Scene = sc
sc.shown = make(chan struct{})
sc.Frame.Init()
sc.AddContextMenu(sc.standardContextMenu)
sc.Styler(func(s *styles.Style) {
s.SetAbilities(true, abilities.Clickable) // this is critical to enable click-off to turn off focus.
s.Cursor = cursors.Arrow
s.Background = colors.Scheme.Surface
s.Color = colors.Scheme.OnSurface
// we never want borders on scenes
s.MaxBorder = styles.Border{}
s.Direction = styles.Column
s.Overflow.Set(styles.OverflowAuto) // screen is always scroller of last resort
// insets and minimum window padding
if sc.Stage == nil {
return
}
if sc.Stage.Type.isPopup() || (sc.Stage.Type == DialogStage && !sc.Stage.FullWindow) {
return
}
s.Padding.Set(units.Dp(8))
})
// the title of the window is that of its main stage on top: popups,
// such as snackbars, which have no title of their own, do not change it.
// It is the window of the scene, which need not be the current window:
// a dialog run from the menu search opens its own window before the menu
// search closes.
sc.OnShow(func(e events.Event) {
if sc.Stage == nil || sc.Stage.Type.isPopup() {
return
}
if rw := sc.RenderWindow(); rw != nil {
rw.SetStageTitle(sc.Stage.Title)
}
})
sc.OnClose(func(e events.Event) {
if sc.Stage == nil || sc.Stage.Type.isPopup() {
return
}
sm := sc.Stage.Mains
if sm == nil || sm.renderWindow == nil {
return
}
sm.Lock()
defer sm.Unlock()
// the stage that will be visible next: the top one other than this
for i := sm.stack.Len() - 1; i >= 0; i-- {
if st := sm.stack.Values[i]; st != sc.Stage {
sm.renderWindow.SetStageTitle(st.Title)
return
}
}
})
sc.Updater(func() {
if TheApp.Platform() == system.Offscreen {
return
}
// At the scene level, we reset the shortcuts and add our context menu
// shortcuts every time. This clears the way for buttons to add their
// shortcuts in their own Updaters. We must get the shortcuts every time
// since buttons may be added or removed dynamically.
sc.Events.shortcuts = nil
tmps := NewScene()
sc.applyContextMenus(tmps, image.Point{})
sc.Events.getShortcutsIn(tmps)
})
if TheApp.SceneInit != nil {
TheApp.SceneInit(sc)
}
}
// renderContext returns the current render context.
// This will be nil prior to actual rendering.
func (sc *Scene) renderContext() *renderContext {
if sc.Stage == nil {
return sc.offscreen
}
sm := sc.Stage.mains.Load()
if sm == nil {
return nil
}
return sm.renderContext
}
// MakeTextShaper makes our own text shaper for offline use,
// if not already in place.
func (sc *Scene) MakeTextShaper() shaped.Shaper {
if sc.textShaper == nil {
sc.textShaper = shaped.NewShaper()
}
return sc.textShaper
}
// TextShaper returns the current [shaped.TextShaper], for text shaping.
// may be nil if not yet initialized.
func (sc *Scene) TextShaper() shaped.Shaper {
rc := sc.renderContext()
if rc != nil {
return rc.textShaper
}
return sc.textShaper
}
// RenderWindow returns the current render window for this scene.
// In general it is best to go through [renderContext] instead of the window.
// This will be nil prior to actual rendering.
func (sc *Scene) RenderWindow() *renderWindow {
if sc.Stage == nil {
return nil
}
sm := sc.Stage.mains.Load()
if sm == nil {
return nil
}
return sm.renderWindow
}
// fitInWindow fits Scene geometry (pos, size) into given window geom.
// Calls resize for the new size and returns whether it actually needed to
// be resized.
func (sc *Scene) fitInWindow(winGeom math32.Geom2DInt) bool {
geom := sc.SceneGeom
geom = geom.FitInWindow(winGeom)
return sc.Resize(geom)
}
// Resize resizes the scene if needed, creating a new image; updates Geom.
// returns false if the scene is already the correct size.
func (sc *Scene) Resize(geom math32.Geom2DInt) bool {
if geom.Size.X <= 0 || geom.Size.Y <= 0 {
return false
}
sz := math32.FromPoint(geom.Size)
if sc.Painter.State == nil {
sc.Painter = *paint.NewPainter(sz)
sc.Painter.UnitContext = sc.Styles.UnitContext
}
sc.SceneGeom.Pos = geom.Pos
if sc.Renderer != nil {
// A renderer without an image (such as the HTML canvas renderer
// on the web) has the size of the scene it was last resized to.
img := sc.Renderer.Image()
if img != nil {
isz := img.Bounds().Size()
if isz == geom.Size {
return false
}
} else if _, rsz := sc.Renderer.Size(); rsz == sz && sc.SceneGeom.Size == geom.Size {
return false
}
} else {
sc.Renderer = paint.NewSourceRenderer(sz)
}
sc.Painter.UnitContext = sc.Styles.UnitContext
sc.Painter.Init(sc.Painter.Paint, sz)
sc.Renderer.SetSize(units.UnitDot, sz)
sc.SceneGeom.Size = geom.Size // make sure
sc.layer.resize(sc)
// sc.updateScene() // note: doing this every resize can be very expensive, and is unnec in general. really you just need a layout.
// The scene is restyled by its next update, before it is laid out, so
// that several resizes before an update, as when a window is shown,
// style it only once.
sc.lastRender.invalidate()
// restart the multi-render updating after resize, to get windows to update correctly while
// resizing on Windows (OS) and Linux (see https://github.com/cogentcore/core/issues/584),
// to get windows on Windows (OS) to update after a window snap (see
// https://github.com/cogentcore/core/issues/497),
// and to get FillInsets to overwrite mysterious black bars that otherwise are rendered
// on both iOS and Android in different contexts.
// It also lays the scene out a second time, which wraps texts to their
// new sizes (the first layout sizes them to their previous allocation).
// TODO(kai): is there a more efficient way to do this, and do we need to do this on all platforms?
sc.showIter = 0
sc.NeedsLayout()
return true
}
// ResizeToContent resizes the scene so it fits the current content.
// Only applicable to desktop systems where windows can be resized.
// Optional extra size is added to the amount computed to hold the contents,
// which is needed in cases with wrapped text elements, which don't
// always size accurately. See [Scene.SetGeometry] for a more general way
// to set all window geometry properties.
func (sc *Scene) ResizeToContent(extra ...image.Point) {
if TheApp.Platform().IsMobile() { // not resizable
return
}
win := sc.RenderWindow()
if win == nil {
return
}
// The content is sized in a goroutine, as the caller typically holds
// the render context lock (for example in an event handler), which the
// goroutine needs, as the content sizing sets the layout state and
// flags of the scene and its widgets. The window is resized after it
// unlocks, as resizing can wait on the main thread, which can wait on
// the render context lock (as when closing a window).
rc := sc.renderContext()
if rc == nil {
return
}
go func() {
win.resizeMu.Lock()
defer win.resizeMu.Unlock()
rc.Lock()
// The scene can have been closed while we waited for the lock.
if sc.This == nil || sc.renderContext() != rc {
rc.Unlock()
return
}
scsz := system.TheApp.Screen(0).PixelSize
sz := sc.contentSize(scsz)
rc.Unlock()
if len(extra) == 1 {
sz = sz.Add(extra[0])
}
win.SystemWindow.SetSize(sz)
}()
}
// SetGeometry uses [system.Window.SetGeometry] to set all window geometry properties,
// with pos in operating system window manager units and size in raw pixels.
// If pos and/or size is not specified, it defaults to the current value.
// If fullscreen is true, pos and size are ignored, and screen indicates the number
// of the screen on which to fullscreen the window. If fullscreen is false, the
// window is moved to the given pos and size on the given screen. If screen is -1,
// the current screen the window is on is used, and fullscreen/pos/size are all
// relative to that screen. It is only applicable on desktop and web platforms,
// with only fullscreen supported on web. See [Scene.SetFullscreen] for a simpler way
// to set only the fullscreen state. See [Scene.ResizeToContent] to resize the window
// to fit the current content.
func (sc *Scene) SetGeometry(fullscreen bool, pos image.Point, size image.Point, screen int) {
rw := sc.RenderWindow()
if rw == nil {
return
}
scr := TheApp.Screen(screen)
if screen < 0 {
scr = rw.SystemWindow.Screen()
}
rw.SystemWindow.SetGeometry(fullscreen, pos, size, scr)
}
// IsFullscreen returns whether the window associated with this [Scene]
// is in fullscreen mode (true) or window mode (false). This is implemented
// on desktop and web platforms. See [Scene.SetFullscreen] to update the
// current fullscreen state and [Stage.SetFullscreen] to set the initial state.
func (sc *Scene) IsFullscreen() bool {
rw := sc.RenderWindow()
if rw == nil {
return false
}
return rw.SystemWindow.Is(system.Fullscreen)
}
// SetFullscreen requests that the window associated with this [Scene]
// be updated to either fullscreen mode (true) or window mode (false).
// This is implemented on desktop and web platforms. See [Scene.IsFullscreen]
// to get the current fullscreen state and [Stage.SetFullscreen] to set the
// initial state. ([Stage.SetFullscreen] sets the initial state, whereas
// this function sets the current state after the [Stage] is already running).
// See [Scene.SetGeometry] for a more general way to set all window
// geometry properties.
func (sc *Scene) SetFullscreen(fullscreen bool) {
rw := sc.RenderWindow()
if rw == nil {
return
}
wgp, screen := theWindowGeometrySaver.get(rw.title, "")
if wgp != nil {
rw.SystemWindow.SetGeometry(fullscreen, wgp.Pos, wgp.Size, screen)
} else {
rw.SystemWindow.SetGeometry(fullscreen, image.Point{}, image.Point{}, rw.SystemWindow.Screen())
}
}
// Close closes the [Stage] associated with this [Scene].
// This only works for main stages (windows and dialogs).
// It returns whether the [Stage] was successfully closed.
func (sc *Scene) Close() bool {
if sc == nil {
return true
}
e := &events.Base{Typ: events.Close}
e.Init()
for cw := range sc.AllWidgets() {
cw.AsWidget().HandleEvent(e)
}
// if they set the event as handled, we do not close the scene
if e.IsHandled() {
return false
}
mm := sc.Stage.Mains
if mm == nil {
return false // todo: needed, but not sure why
}
mm.deleteStage(sc.Stage)
if sc.Stage.NewWindow && !TheApp.Platform().IsMobile() && !mm.renderWindow.flags.HasFlag(winClosing) && !mm.renderWindow.flags.HasFlag(winStopEventLoop) && !TheApp.IsQuitting() {
mm.renderWindow.closeReq()
}
return true
}
func (sc *Scene) ApplyScenePos() {
sc.Frame.ApplyScenePos()
if sc.Parts == nil {
return
}
mvi := sc.Parts.ChildByName("move", 1)
if mvi == nil {
return
}
mv := mvi.(Widget).AsWidget()
sc.Parts.Geom.Pos.Total.Y = math32.Ceil(0.5 * mv.Geom.Size.Actual.Total.Y)
sc.Parts.Geom.Size.Actual = sc.Geom.Size.Actual
sc.Parts.Geom.Size.Alloc = sc.Geom.Size.Alloc
sc.Parts.setContentPosFromPos()
sc.Parts.setBBoxesFromAllocs()
sc.Parts.applyScenePosChildren()
psz := sc.Parts.Geom.Size.Actual.Content
mv.Geom.RelPos.X = 0.5*psz.X - 0.5*mv.Geom.Size.Actual.Total.X
mv.Geom.RelPos.Y = 0
mv.setPosFromParent()
mv.setBBoxesFromAllocs()
rszi := sc.Parts.ChildByName("resize", 1)
if rszi == nil {
return
}
rsz := rszi.(Widget).AsWidget()
rsz.Geom.RelPos.X = psz.X // - 0.5*rsz.Geom.Size.Actual.Total.X
rsz.Geom.RelPos.Y = psz.Y // - 0.5*rsz.Geom.Size.Actual.Total.Y
rsz.setPosFromParent()
rsz.setBBoxesFromAllocs()
}
func (sc *Scene) AddDirectRender(w Widget) {
sc.directRenders = append(sc.directRenders, w)
}
func (sc *Scene) DeleteDirectRender(w Widget) {
idx := slices.Index(sc.directRenders, w)
if idx >= 0 {
sc.directRenders = slices.Delete(sc.directRenders, idx, idx+1)
}
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"image"
"time"
"cogentcore.org/core/events"
"cogentcore.org/core/keymap"
"cogentcore.org/core/events/key"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/tree"
)
// autoScrollRate determines the rate of auto-scrolling of layouts
var autoScrollRate = float32(10)
// hasAnyScroll returns true if the frame has any scrollbars.
func (fr *Frame) hasAnyScroll() bool {
return fr.HasScroll[math32.X] || fr.HasScroll[math32.Y]
}
// ScrollGeom returns the target position and size for scrollbars
func (fr *Frame) ScrollGeom(d math32.Dims) (pos, sz math32.Vector2) {
sbw := math32.Ceil(fr.Styles.ScrollbarWidth.Dots)
sbwb := sbw + fr.Styles.Border.Width.Right.Dots + fr.Styles.Margin.Right.Dots
od := d.Other()
bbmin := math32.FromPoint(fr.Geom.ContentBBox.Min)
bbmax := math32.FromPoint(fr.Geom.ContentBBox.Max)
bbtmax := math32.FromPoint(fr.Geom.TotalBBox.Max)
if fr.This != fr.Scene.This { // if not the scene, keep inside the scene
bbmin.SetMax(math32.FromPoint(fr.Scene.Geom.ContentBBox.Min))
bbmax.SetMin(math32.FromPoint(fr.Scene.Geom.ContentBBox.Max))
bbtmax.SetMin(math32.FromPoint(fr.Scene.Geom.TotalBBox.Max))
}
pos.SetDim(d, bbmin.Dim(d))
pos.SetDim(od, bbtmax.Dim(od)-sbwb) // base from total
bbsz := bbmax.Sub(bbmin)
sz.SetDim(d, bbsz.Dim(d)-4)
sz.SetDim(od, sbw)
sz = sz.Ceil()
return
}
// ConfigScrolls configures any scrollbars that have been enabled
// during the Layout process. This is called during Position, once
// the sizing and need for scrollbars has been established.
// The final position of the scrollbars is set during ScenePos in
// PositionScrolls. Scrolls are kept around in general.
func (fr *Frame) ConfigScrolls() {
for d := math32.X; d <= math32.Y; d++ {
if fr.HasScroll[d] {
fr.configScroll(d)
}
}
}
// configScroll configures scroll for given dimension
func (fr *Frame) configScroll(d math32.Dims) {
if fr.Scrolls[d] != nil {
return
}
fr.Scrolls[d] = NewSlider()
sb := fr.Scrolls[d]
tree.SetParent(sb, fr)
// sr.SetFlag(true, tree.Field) // note: do not turn on -- breaks pos
sb.SetType(SliderScrollbar)
sb.InputThreshold = 1
sb.Min = 0.0
sb.Styler(func(s *styles.Style) {
s.Direction = styles.Directions(d)
s.Padding.Zero()
s.Margin.Zero()
s.MaxBorder.Width.Zero()
s.Border.Width.Zero()
s.FillMargin = false
})
sb.FinalStyler(func(s *styles.Style) {
od := d.Other()
_, sz := fr.This.(Layouter).ScrollGeom(d)
if sz.X > 0 && sz.Y > 0 {
s.SetState(false, states.Invisible)
s.Min.SetDim(d, units.Dot(sz.Dim(d)))
s.Min.SetDim(od, units.Dot(sz.Dim(od)))
} else {
s.SetState(true, states.Invisible)
}
s.Max = s.Min
})
sb.OnInput(func(e events.Event) {
e.SetHandled()
fr.This.(Layouter).ScrollChanged(d, sb)
})
sb.Update()
}
// ScrollChanged is called in the OnInput event handler for updating,
// when the scrollbar value has changed, for given dimension.
// This is part of the Layouter interface.
func (fr *Frame) ScrollChanged(d math32.Dims, sb *Slider) {
fr.Geom.Scroll.SetDim(d, -sb.Value)
fr.This.(Layouter).ApplyScenePos() // computes updated positions
fr.NeedsRender()
}
// ScrollUpdateFromGeom updates the scrollbar for given dimension
// based on the current Geom.Scroll value for that dimension.
// This can be used to programatically update the scroll value.
func (fr *Frame) ScrollUpdateFromGeom(d math32.Dims) {
if !fr.HasScroll[d] || fr.Scrolls[d] == nil {
return
}
sb := fr.Scrolls[d]
cv := fr.Geom.Scroll.Dim(d)
sb.setValueEvent(-cv)
fr.This.(Layouter).ApplyScenePos() // computes updated positions
fr.NeedsRender()
}
// ScrollValues returns the maximum size that could be scrolled,
// the visible size (which could be less than the max size, in which
// case no scrollbar is needed), and visSize / maxSize as the VisiblePct.
// This is used in updating the scrollbar and determining whether one is
// needed in the first place
func (fr *Frame) ScrollValues(d math32.Dims) (maxSize, visSize, visPct float32) {
sz := &fr.Geom.Size
// all of the content, including any that overflows children visibly
maxSize = max(sz.Internal.Dim(d), fr.layout.overflow.Dim(d))
visSize = sz.Alloc.Content.Dim(d)
visPct = visSize / maxSize
return
}
// SetScrollParams sets scrollbar parameters. Must set Step and PageStep,
// but can also set others as needed.
// Max and VisiblePct are automatically set based on ScrollValues maxSize, visPct.
func (fr *Frame) SetScrollParams(d math32.Dims, sb *Slider) {
sb.Min = 0
sb.Step = 1
sb.PageStep = float32(fr.Geom.ContentBBox.Dy())
}
// PositionScrolls arranges scrollbars
func (fr *Frame) PositionScrolls() {
for d := math32.X; d <= math32.Y; d++ {
if fr.HasScroll[d] && fr.Scrolls[d] != nil {
fr.positionScroll(d)
} else {
fr.Geom.Scroll.SetDim(d, 0)
}
}
}
func (fr *Frame) positionScroll(d math32.Dims) {
sb := fr.Scrolls[d]
pos, ssz := fr.This.(Layouter).ScrollGeom(d)
maxSize, _, visPct := fr.This.(Layouter).ScrollValues(d)
if sb.Geom.Pos.Total == pos && sb.Geom.Size.Actual.Content == ssz && sb.visiblePercent == visPct {
return
}
if ssz.X <= 0 || ssz.Y <= 0 {
// a scrollbar of no width is not shown, but the frame still
// scrolls (by the wheel, as with scrollbar-width: none in CSS)
sb.SetState(true, states.Invisible)
sb.Max = maxSize
sb.SetVisiblePercent(visPct)
sb.SetValue(sb.Value) // keep in range
fr.This.(Layouter).SetScrollParams(d, sb)
return
}
sb.SetState(false, states.Invisible)
sb.Max = maxSize
sb.SetVisiblePercent(visPct)
// fmt.Println(ly, d, "vis pct:", asz/csz)
sb.SetValue(sb.Value) // keep in range
fr.This.(Layouter).SetScrollParams(d, sb)
sb.Restyle() // applies style
sb.SizeUp()
sb.Geom.Size.Alloc = fr.Geom.Size.Actual
sb.SizeDown(0)
sb.Geom.Pos.Total = pos
sb.setContentPosFromPos()
// note: usually these are intersected with parent *content* bbox,
// but scrolls are specifically outside of that.
sb.setBBoxesFromAllocs()
}
// RenderScrolls renders the scrollbars.
func (fr *Frame) RenderScrolls() {
for d := math32.X; d <= math32.Y; d++ {
if fr.HasScroll[d] && fr.Scrolls[d] != nil {
fr.Scrolls[d].RenderWidget()
}
}
}
// setScrollsOff turns off the scrollbars.
func (fr *Frame) setScrollsOff() {
for d := math32.X; d <= math32.Y; d++ {
fr.HasScroll[d] = false
}
}
// scrollActionDelta moves the scrollbar in given dimension by given delta.
// returns whether actually scrolled.
func (fr *Frame) scrollActionDelta(d math32.Dims, delta float32) bool {
if fr.HasScroll[d] && fr.Scrolls[d] != nil {
sb := fr.Scrolls[d]
nval := sb.Value + sb.scrollScale(delta)
chg := sb.setValueEvent(nval)
if chg {
fr.NeedsRender() // only render needed -- scroll updates pos
}
return chg
}
return false
}
// scrollKey scrolls the frame for the given key function, when the frame
// itself has the focus, as a panel of text to read: by lines for the arrow
// keys, by pages for PageUp and PageDown, and to the start or end of
// its content for Home and End. It returns whether it handled the key,
// which it does not if the frame cannot scroll in that direction.
func (fr *Frame) scrollKey(kf keymap.Functions) bool {
line := 3 * fr.Styles.UnitContext.FontEm
if line <= 0 {
line = 48
}
page := func(d math32.Dims) float32 {
return max(line, 0.9*fr.Geom.Size.Alloc.Content.Dim(d))
}
by := func(d math32.Dims, delta float32) bool {
if !fr.HasScroll[d] || fr.Scrolls[d] == nil {
return false
}
sb := fr.Scrolls[d]
if sb.setValueEvent(sb.Value + delta) {
fr.NeedsRender()
}
return true
}
switch kf {
case keymap.MoveDown:
return by(math32.Y, line)
case keymap.MoveUp:
return by(math32.Y, -line)
case keymap.MoveRight:
return by(math32.X, line)
case keymap.MoveLeft:
return by(math32.X, -line)
case keymap.PageDown:
return by(math32.Y, page(math32.Y))
case keymap.PageUp:
return by(math32.Y, -page(math32.Y))
case keymap.Home, keymap.DocHome:
return fr.ScrollDimToContentStart(math32.Y)
case keymap.End, keymap.DocEnd:
return fr.ScrollDimToContentEnd(math32.Y)
}
return false
}
// scrollDelta processes a scroll event. If only one dimension is processed,
// and there is a non-zero in other, then the consumed dimension is reset to 0
// and the event is left unprocessed, so a higher level can consume the
// remainder.
func (fr *Frame) scrollDelta(e events.Event) {
se := e.(*events.MouseScroll)
fdel := se.Delta
hasShift := e.HasAnyModifier(key.Shift, key.Alt) // shift or alt indicates to scroll horizontally
if hasShift {
if !fr.HasScroll[math32.X] { // if we have shift, we can only horizontal scroll
return
}
if fr.scrollActionDelta(math32.X, fdel.Y) {
e.SetHandled()
}
return
}
if fr.HasScroll[math32.Y] && fr.HasScroll[math32.X] {
ch1 := fr.scrollActionDelta(math32.Y, fdel.Y)
ch2 := fr.scrollActionDelta(math32.X, fdel.X)
if ch1 || ch2 {
e.SetHandled()
}
} else if fr.HasScroll[math32.Y] {
if fr.scrollActionDelta(math32.Y, fdel.Y) {
e.SetHandled()
}
} else if fr.HasScroll[math32.X] {
if se.Delta.X != 0 {
if fr.scrollActionDelta(math32.X, fdel.X) {
e.SetHandled()
}
} else if se.Delta.Y != 0 {
if fr.scrollActionDelta(math32.X, fdel.Y) {
e.SetHandled()
}
}
}
}
// parentScrollFrame returns the first parent frame that has active scrollbars.
func (wb *WidgetBase) parentScrollFrame() *Frame {
ly := tree.ParentByType[Layouter](wb)
if ly == nil {
return nil
}
fr := ly.AsFrame()
if fr.hasAnyScroll() {
return fr
}
return fr.parentScrollFrame()
}
// ScrollToThis tells this widget's parent frame to scroll to keep
// this widget in view. It returns whether any scrolling was done.
func (wb *WidgetBase) ScrollToThis() bool {
if wb.This == nil {
return false
}
fr := wb.parentScrollFrame()
if fr == nil {
return false
}
return fr.scrollToWidget(wb.This.(Widget))
}
// ScrollThisToTop tells this widget's parent frame to scroll so the top
// of this widget is at the top of the visible range.
// It returns whether any scrolling was done.
func (wb *WidgetBase) ScrollThisToTop() bool {
if wb.This == nil {
return false
}
fr := wb.parentScrollFrame()
if fr == nil {
return false
}
box := wb.AsWidget().Geom.totalRect()
return fr.ScrollDimToStart(math32.Y, box.Min.Y)
}
// scrollToWidget scrolls the layout to ensure that the given widget is in view.
// It returns whether scrolling was needed.
func (fr *Frame) scrollToWidget(w Widget) bool {
// note: critical to NOT use BBox b/c it is zero for invisible items!
box := w.AsWidget().Geom.totalRect()
if box.Size() == (image.Point{}) {
return false
}
return fr.ScrollToBox(box)
}
// autoScrollDim auto-scrolls along one dimension, based on a position value
// relative to the visible dimensions of the frame
// (i.e., subtracting ed.Geom.Pos.Content).
func (fr *Frame) autoScrollDim(d math32.Dims, pos float32) bool {
if !fr.HasScroll[d] || fr.Scrolls[d] == nil {
return false
}
sb := fr.Scrolls[d]
smax := sb.effectiveMax()
ssz := sb.scrollThumbValue()
dst := sb.Step * autoScrollRate
fromMax := ssz - pos // distance from max in visible window
if pos < 0 || pos < math32.Abs(fromMax) { // pushing toward min
pct := pos / ssz
if pct < .1 && sb.Value > 0 {
dst = min(dst, sb.Value)
sb.setValueEvent(sb.Value - dst)
return true
}
} else {
pct := fromMax / ssz
if pct < .1 && sb.Value < smax {
dst = min(dst, (smax - sb.Value))
sb.setValueEvent(sb.Value + dst)
return true
}
}
return false
}
var lastAutoScroll time.Time
// AutoScroll scrolls the layout based on given position in scroll
// coordinates (i.e., already subtracing the BBox Min for a mouse event).
func (fr *Frame) AutoScroll(pos math32.Vector2) bool {
now := time.Now()
lag := now.Sub(lastAutoScroll)
if lag < TimingSettings.LayoutAutoScrollDelay {
return false
}
did := false
if fr.HasScroll[math32.Y] && fr.HasScroll[math32.X] {
did = fr.autoScrollDim(math32.Y, pos.Y)
did = did || fr.autoScrollDim(math32.X, pos.X)
} else if fr.HasScroll[math32.Y] {
did = fr.autoScrollDim(math32.Y, pos.Y)
} else if fr.HasScroll[math32.X] {
did = fr.autoScrollDim(math32.X, pos.X)
}
if did {
lastAutoScroll = time.Now()
}
return did
}
// scrollToBoxDim scrolls to ensure that given target [min..max] range
// along one dimension is in view. Returns true if scrolling was needed
func (fr *Frame) scrollToBoxDim(d math32.Dims, tmini, tmaxi int) bool {
if !fr.HasScroll[d] || fr.Scrolls[d] == nil {
return false
}
sb := fr.Scrolls[d]
if sb == nil || sb.This == nil {
return false
}
tmin, tmax := float32(tmini), float32(tmaxi)
cmin, cmax := fr.Geom.contentRangeDim(d)
if tmin >= cmin && tmax <= cmax {
return false
}
if tmin <= cmin && tmax >= cmax {
// it fills the view, as a widget larger than the frame, such as
// a grid of photos that gets the focus when clicked, and so it
// is in view as much as it can be: scrolling to its start would
// lose the place
return false
}
h := fr.Styles.Font.Size.Dots
if tmin < cmin { // favors scrolling to start
trg := sb.Value + tmin - cmin - h
if trg < 0 {
trg = 0
}
sb.setValueEvent(trg)
return true
}
if (tmax - tmin) < sb.scrollThumbValue() { // only if whole thing fits
trg := sb.Value + float32(tmax-cmax) + h
sb.setValueEvent(trg)
return true
}
return false
}
// ScrollToBox scrolls the layout to ensure that given rect box is in view.
// Returns true if scrolling was needed
func (fr *Frame) ScrollToBox(box image.Rectangle) bool {
did := false
if fr.HasScroll[math32.Y] && fr.HasScroll[math32.X] {
did = fr.scrollToBoxDim(math32.Y, box.Min.Y, box.Max.Y)
did = did || fr.scrollToBoxDim(math32.X, box.Min.X, box.Max.X)
} else if fr.HasScroll[math32.Y] {
did = fr.scrollToBoxDim(math32.Y, box.Min.Y, box.Max.Y)
} else if fr.HasScroll[math32.X] {
did = fr.scrollToBoxDim(math32.X, box.Min.X, box.Max.X)
}
if did {
fr.NeedsRender()
}
return did
}
// ScrollDimToStart scrolls to put the given child coordinate position (eg.,
// top / left of a view box) at the start (top / left) of our scroll area, to
// the extent possible. Returns true if scrolling was needed.
func (fr *Frame) ScrollDimToStart(d math32.Dims, posi int) bool {
if !fr.HasScroll[d] {
return false
}
pos := float32(posi)
cmin, _ := fr.Geom.contentRangeDim(d)
if pos == cmin {
return false
}
sb := fr.Scrolls[d]
trg := math32.Clamp(sb.Value+(pos-cmin), 0, sb.effectiveMax())
sb.setValueEvent(trg)
return true
}
// ScrollDimToContentStart is a helper function that scrolls the layout to the
// start of its content (ie: moves the scrollbar to the very start).
// See also [Frame.IsDimAtContentStart].
func (fr *Frame) ScrollDimToContentStart(d math32.Dims) bool {
if !fr.HasScroll[d] || fr.Scrolls[d] == nil {
return false
}
sb := fr.Scrolls[d]
sb.setValueEvent(0)
return true
}
// IsDimAtContentStart returns whether the given dimension is scrolled to the
// start of its content. See also [Frame.ScrollDimToContentStart].
func (fr *Frame) IsDimAtContentStart(d math32.Dims) bool {
if !fr.HasScroll[d] || fr.Scrolls[d] == nil {
return false
}
sb := fr.Scrolls[d]
return sb.Value == 0
}
// ScrollDimToEnd scrolls to put the given child coordinate position (eg.,
// bottom / right of a view box) at the end (bottom / right) of our scroll
// area, to the extent possible. Returns true if scrolling was needed.
func (fr *Frame) ScrollDimToEnd(d math32.Dims, posi int) bool {
if !fr.HasScroll[d] || fr.Scrolls[d] == nil {
return false
}
pos := float32(posi)
_, cmax := fr.Geom.contentRangeDim(d)
if pos == cmax {
return false
}
sb := fr.Scrolls[d]
trg := math32.Clamp(sb.Value+(pos-cmax), 0, sb.effectiveMax())
sb.setValueEvent(trg)
return true
}
// ScrollDimToContentEnd is a helper function that scrolls the layout to the
// end of its content (ie: moves the scrollbar to the very end).
// See also [Frame.IsDimAtContentEnd].
func (fr *Frame) ScrollDimToContentEnd(d math32.Dims) bool {
if !fr.HasScroll[d] || fr.Scrolls[d] == nil {
return false
}
sb := fr.Scrolls[d]
sb.setValueEvent(sb.effectiveMax())
return true
}
// IsDimAtContentEnd returns whether the given dimension is scrolled to the
// end of its content. See also [Frame.ScrollDimToContentEnd].
func (fr *Frame) IsDimAtContentEnd(d math32.Dims) bool {
if !fr.HasScroll[d] || fr.Scrolls[d] == nil {
return false
}
sb := fr.Scrolls[d]
return sb.Value == sb.effectiveMax()
}
// ScrollDimToCenter scrolls to put the given child coordinate position (eg.,
// middle of a view box) at the center of our scroll area, to the extent
// possible. Returns true if scrolling was needed.
func (fr *Frame) ScrollDimToCenter(d math32.Dims, posi int) bool {
if !fr.HasScroll[d] || fr.Scrolls[d] == nil {
return false
}
pos := float32(posi)
cmin, cmax := fr.Geom.contentRangeDim(d)
mid := 0.5 * (cmin + cmax)
if pos == mid {
return false
}
sb := fr.Scrolls[d]
trg := math32.Clamp(sb.Value+(pos-mid), 0, sb.effectiveMax())
sb.setValueEvent(trg)
return true
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"fmt"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/styles"
"cogentcore.org/core/text/runes"
"cogentcore.org/core/text/textpos"
"cogentcore.org/core/tree"
)
var (
// LastSearch remembers the last search string.
LastSearch string
// LastUseCase remembers the last search useCase value.
LastUseCase CaseSensitive
)
// CaseSensitive specifies whether a search is case-sensitive: [UseCase] or
// [IgnoreCase]. It is [textpos.CaseSensitive], which the text search
// functions use.
type CaseSensitive = textpos.CaseSensitive
// SelectionReset specifies whether a select function resets the selection
// ([SelectReset]) or sets it ([SelectSet]).
type SelectionReset bool
// SelectionScroll specifies whether a select function scrolls to the selection:
// [SelectScroll] or [SelectNoScroll].
type SelectionScroll bool
const (
// UseCase can be used as arg for [Search] functions,
// to use case-sensitive search.
UseCase = textpos.UseCase
// IgnoreCase can be used as arg for [Search] functions
// to use case-insensitive search.
IgnoreCase = textpos.IgnoreCase
// SelectReset can be used as reset arg for Select functions,
// to reset the selection.
SelectReset SelectionReset = true
// SelectSet can be used as reset arg for Select functions,
// to actually set the selection.
SelectSet SelectionReset = false
// SelectScroll can be used as scroll arg for Select functions,
// to scroll to given location.
SelectScroll SelectionScroll = true
// SelectNoScroll can be used as scroll arg for Select functions,
// to NOT scroll to given location.
SelectNoScroll SelectionScroll = false
)
// SearchResult is one set of search results for text in a widget.
type SearchResult struct {
// Widget with the text. Can be a collection too, to manage scrolling.
Widget Widget
// Matches are the matching ranges within the RichText of widget.
Matches []textpos.Match
}
// SearchResults are the collection of search results.
type SearchResults []SearchResult
// Len returns the total number of search results.
func (sr SearchResults) Len() int {
n := 0
for _, r := range sr {
n += len(r.Matches)
}
return n
}
// AtIndex returns the result at given index into the full set
// of results [0..Len()), returning the local index into Matches
// within the given result.
func (sr SearchResults) AtIndex(idx int) (*SearchResult, int) {
n := 0
for i := range sr {
r := &sr[i]
nr := len(r.Matches)
if idx >= n && idx < n+nr {
return r, idx - n
}
n += nr
}
return nil, -1
}
// SearchRunes is a helper function that returns [textpos.Matches]
// as Region Char indexes into the runes.
func SearchRunes(rn []rune, find string, useCase CaseSensitive) []textpos.Match {
var matches []textpos.Match
fr := []rune(find)
fsz := len(fr)
sz := len(rn)
ci := 0
for ci < sz {
var i int
if useCase {
i = runes.Index(rn[ci:], fr)
} else {
i = runes.IndexFold(rn[ci:], fr)
}
if i < 0 {
break
}
i += ci
ci = i + fsz
matches = append(matches, textpos.NewMatch(rn, i, ci, 0))
}
return matches
}
// SearchWidgets performs text in widgets under given widget,
// for the given find string, with given case sensitivity,
// using the Search interface method.
func SearchWidgets(w Widget, find string, useCase CaseSensitive) SearchResults {
var res SearchResults
wb := w.AsWidget()
wb.WidgetWalkDown(func(cw Widget, cwb *WidgetBase) bool {
if !cwb.IsDisplayable() {
return tree.Break
}
matches, handled := cw.Search(find, useCase)
if len(matches) > 0 {
res = append(res, SearchResult{Widget: cw, Matches: matches})
}
if handled {
return tree.Break
}
return tree.Continue
})
return res
}
// SearchHighlight highlights all the [SearchResults] under given
// widget, resetting any existing first. Pass a nil to just reset.
func SearchHighlight(w Widget, results SearchResults) {
wb := w.AsWidget()
wb.WidgetWalkDown(func(cw Widget, cwb *WidgetBase) bool {
handled := cw.HighlightMatches(nil)
if handled {
return tree.Break
}
return tree.Continue
})
if results == nil {
return
}
for _, r := range results {
r.Widget.HighlightMatches(r.Matches)
}
}
// SearchSelect selects the [SearchResult] at given results index
// from given [SearchResults], or resets the selection if reset = true.
func SearchSelect(results SearchResults, index int, reset SelectionReset) {
res, i := results.AtIndex(index)
if res == nil {
return
}
res.Widget.SelectMatch(res.Matches, i, SelectionScroll(!reset), reset)
}
// Search performs an interactive search for given text,
// on elements within given widget.
func Search(w Widget, find string, useCase CaseSensitive) {
LastSearch = find
var res SearchResults
var n int
idx := 0
search := func() {
res = SearchWidgets(w, find, useCase)
SearchHighlight(w, res)
n = res.Len()
}
sel := func() {
SearchSelect(res, idx, SelectSet) // not reset
}
unSel := func() {
SearchSelect(res, idx, SelectReset) // reset
}
search()
sel()
d := NewBody("Search")
d.Styler(func(s *styles.Style) {
s.Direction = styles.Row
})
st := NewTextField(d).SetText(find)
ix := NewText(d).SetText("00/00")
ix.Updater(func() {
ix.SetText(fmt.Sprintf("%d/%d", idx+1, n))
})
st.OnChange(func(e events.Event) {
find = st.Text()
LastSearch = find
unSel()
search()
sel()
ix.Update()
})
up := NewButton(d).SetIcon(icons.ArrowUpward)
up.OnClick(func(e events.Event) {
if n == 0 {
return
}
unSel()
idx--
if idx < 0 {
idx += n
}
sel()
ix.Update()
// todo: select
})
dn := NewButton(d).SetIcon(icons.ArrowDownward)
dn.OnClick(func(e events.Event) {
if n == 0 {
return
}
unSel()
idx++
if idx >= n {
idx -= n
}
sel()
ix.Update()
// todo: select
})
cs := NewSwitch(d).SetText("Use case")
cs.SetTooltip("Use case sensitive search.")
Bind(&useCase, cs)
cs.OnChange(func(e events.Event) {
unSel()
search()
sel()
})
x := NewButton(d).SetIcon(icons.Close)
x.SetTooltip("Close search dialog")
x.OnClick(func(e events.Event) {
unSel()
SearchHighlight(w, nil)
d.Close()
})
d.NewDialog(w).SetModal(false).Run()
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"cogentcore.org/core/colors"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/units"
)
// Separator draws a separator line. It goes in the direction
// specified by [styles.Style.Direction].
type Separator struct {
WidgetBase
}
func (sp *Separator) Init() {
sp.WidgetBase.Init()
sp.Styler(func(s *styles.Style) {
s.Align.Self = styles.Center
s.Justify.Self = styles.Center
s.Background = colors.Scheme.OutlineVariant
})
sp.FinalStyler(func(s *styles.Style) {
if s.Direction == styles.Row {
s.Grow.Set(1, 0)
s.Min.Y.Dp(1)
s.Margin.SetHorizontal(units.Dp(6))
} else {
s.Grow.Set(0, 1)
s.Min.X.Dp(1)
s.Margin.SetVertical(units.Dp(6))
}
})
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"image/color"
"io/fs"
"os"
"os/user"
"path/filepath"
"reflect"
"slices"
"time"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/iox/jsonx"
"cogentcore.org/core/base/iox/tomlx"
"cogentcore.org/core/base/option"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/base/stringsx"
"cogentcore.org/core/colors"
"cogentcore.org/core/colors/gradient"
"cogentcore.org/core/colors/matcolor"
"cogentcore.org/core/cursors/cursorimg"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/keymap"
"cogentcore.org/core/system"
"cogentcore.org/core/text/printer"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/text"
"cogentcore.org/core/tree"
)
// AllSettings is a global slice containing all of the user [Settings]
// that the user will see in the settings window. It contains the base Cogent Core
// settings by default and should be modified by other apps to add their
// app settings.
var AllSettings = []Settings{AppearanceSettings, SystemSettings, &printer.Settings, TimingSettings, DebugSettings}
// AddAppSettings inserts app-specific settings after the AppearanceSettings,
// which are loaded in that order. Their tabs come first in the settings
// editor (see [SettingsEditor]).
func AddAppSettings(sets ...Settings) {
AllSettings = slices.Insert(AllSettings, 1, sets...)
appSettings = append(appSettings, sets...)
}
// appSettings are the app-specific settings added by [AddAppSettings].
var appSettings []Settings
// editorSettings returns [AllSettings] in the order of the tabs of the
// settings editor: the app-specific settings first, then the others.
func editorSettings() []Settings {
var app, others []Settings
for _, se := range AllSettings {
if slices.Contains(appSettings, se) {
app = append(app, se)
} else {
others = append(others, se)
}
}
return append(app, others...)
}
// Settings is the interface that describes the functionality common
// to all settings data types.
type Settings interface {
// Label returns the label text for the settings.
Label() string
// Filename returns the full filename/filepath at which the settings are stored.
Filename() string
// Defaults sets the default values for all of the settings.
Defaults()
// Apply does anything necessary to apply the settings to the app.
Apply()
// MakeToolbar is an optional method that settings objects can implement in order to
// configure the settings view toolbar with settings-related actions that the user can
// perform.
MakeToolbar(p *tree.Plan)
}
// SettingsOpener is an optional additional interface that
// [Settings] can satisfy to customize the behavior of [openSettings].
type SettingsOpener interface {
Settings
// Open opens the settings
Open() error
}
// SettingsSaver is an optional additional interface that
// [Settings] can satisfy to customize the behavior of [SaveSettings].
type SettingsSaver interface {
Settings
// Save saves the settings
Save() error
}
// SettingsBase contains base settings logic that other settings data types can extend.
type SettingsBase struct {
// Name is the name of the settings.
Name string `display:"-" save:"-"`
// File is the full filename/filepath at which the settings are stored.
File string `display:"-" save:"-"`
}
// Label returns the label text for the settings.
func (sb *SettingsBase) Label() string {
return sb.Name
}
// Filename returns the full filename/filepath at which the settings are stored.
func (sb *SettingsBase) Filename() string {
return sb.File
}
// Defaults does nothing by default and can be extended by other settings data types.
func (sb *SettingsBase) Defaults() {}
// Apply does nothing by default and can be extended by other settings data types.
func (sb *SettingsBase) Apply() {}
// MakeToolbar does nothing by default and can be extended by other settings data types.
func (sb *SettingsBase) MakeToolbar(p *tree.Plan) {}
// openSettings opens the given settings from their [Settings.Filename].
// The settings are assumed to be in TOML unless they have a .json file
// extension. If they satisfy the [SettingsOpener] interface,
// [SettingsOpener.Open] will be used instead.
func openSettings(se Settings) error {
if so, ok := se.(SettingsOpener); ok {
return so.Open()
}
fnm := se.Filename()
if filepath.Ext(fnm) == ".json" {
return jsonx.Open(se, fnm)
}
return tomlx.Open(se, fnm)
}
// SaveSettings saves the given settings to their [Settings.Filename].
// The settings will be encoded in TOML unless they have a .json file
// extension. If they satisfy the [SettingsSaver] interface,
// [SettingsSaver.Save] will be used instead. Any non default
// fields are not saved, following [reflectx.NonDefaultFields].
func SaveSettings(se Settings) error {
if ss, ok := se.(SettingsSaver); ok {
return ss.Save()
}
fnm := se.Filename()
ndf := reflectx.NonDefaultFields(se)
if filepath.Ext(fnm) == ".json" {
return jsonx.Save(ndf, fnm)
}
return tomlx.Save(ndf, fnm)
}
// resetSettings resets the given settings to their default values.
func resetSettings(se Settings) error {
err := os.RemoveAll(se.Filename())
if err != nil {
return err
}
npv := reflectx.NonPointerValue(reflect.ValueOf(se))
// we only reset the non-default fields to avoid removing the base
// information (name, filename, etc)
ndf := reflectx.NonDefaultFields(se)
for f := range ndf {
rf := npv.FieldByName(f)
rf.Set(reflect.Zero(rf.Type()))
}
return LoadSettings(se)
}
// resetAllSettings resets all of the settings to their default values.
func resetAllSettings() error { //types:add
for _, se := range AllSettings {
err := resetSettings(se)
if err != nil {
return err
}
}
UpdateAll()
return nil
}
// LoadSettings sets the defaults of, opens, and applies the given settings,
// as [LoadAllSettings] does for [AllSettings], as for those of a package
// that are not in the settings window of an app. It processes their
// `default:` struct tags in addition to calling their [Settings.Defaults]
// method.
func LoadSettings(se Settings) error {
errors.Log(reflectx.SetFromDefaultTags(se))
se.Defaults()
err := openSettings(se)
// we always apply the settings even if we can't open them
// to apply at least the default values
se.Apply()
if errors.Is(err, fs.ErrNotExist) {
return nil // it is okay for settings to not be saved
}
return err
}
// LoadAllSettings sets the defaults of, opens, and applies [AllSettings].
func LoadAllSettings() error {
errs := []error{}
for _, se := range AllSettings {
err := LoadSettings(se)
if err != nil {
errs = append(errs, err)
}
}
return errors.Join(errs...)
}
// UpdateSettings applies and saves the given settings in the context of the given
// widget and then updates all windows and triggers a full render rebuild.
func UpdateSettings(ctx Widget, se Settings) {
se.Apply()
ErrorSnackbar(ctx, SaveSettings(se), "Error saving "+se.Label()+" settings")
UpdateAll()
}
// UpdateAll updates all windows and triggers a full render rebuild.
// It is typically called when user settings are changed.
// The windows are updated by their event loops (see [runInEachWindow]),
// so the rebuild happens after the current event of each window.
func UpdateAll() { //types:add
// Some caches are invalid now:
gradient.ClearCache()
cursorimg.ClearCache()
runInEachWindow(func(w *renderWindow, rc *renderContext) {
rc.logicalDPI = w.logicalDPI()
rc.rebuild = true // trigger full rebuild
})
}
// restyleAll restyles and lays out all windows, as is needed when the fonts
// that texts are measured with have changed.
func restyleAll() {
runInEachWindow(func(w *renderWindow, rc *renderContext) {
rc.restyle = true
})
}
// AppearanceSettings are the currently active global Cogent Core appearance settings.
var AppearanceSettings = &AppearanceSettingsData{
Name: "Appearance",
File: filepath.Join(TheApp.CogentCoreDataDir(), "appearance-settings.toml"),
}
// AppearanceSettingsData is the data type for the global Cogent Core appearance settings.
type AppearanceSettingsData struct { //types:add
SettingsBase
// the color theme.
Theme Themes `default:"Auto"`
// the primary color used to generate the color scheme.
Color color.RGBA `default:"#4285f4"`
// overall zoom factor as a percentage of the default zoom.
// Use Control +/- keyboard shortcut to change zoom level anytime.
// Screen-specific zoom factor will be used if present, see 'Screens' field.
Zoom float32 `default:"100" min:"10" max:"500" step:"10" format:"%g%%"`
// the overall spacing factor as a percentage of the default amount of spacing
// (higher numbers lead to more space and lower numbers lead to higher density).
// Its default depends on the platform (see [DefaultSpacing]), so that
// it is always saved, as there is no fixed default value to compare with.
Spacing float32 `min:"10" max:"500" step:"10" format:"%g%%"`
// the overall font size factor applied to all text as a percentage
// of the default font size (higher numbers lead to larger text).
FontSize float32 `default:"100" min:"10" max:"500" step:"10" format:"%g%%"`
// Font size factor applied only to documentation and other
// dense text contexts, not normal interactive elements.
// It is a percentage of the base Font size setting (higher numbers
// lead to larger text).
DocsFontSize float32 `default:"100" min:"10" max:"500" step:"10" format:"%g%%"`
// the amount that alternating rows are highlighted when showing
// tabular data (set to 0 to disable zebra striping).
ZebraStripes float32 `default:"0" min:"0" max:"100" step:"10" format:"%g%%"`
// screen-specific settings, which will override overall defaults if set,
// so different screens can use different zoom levels.
// Use 'Save screen zoom' in the toolbar to save the current zoom for the current
// screen, and Control +/- keyboard shortcut to change this zoom level anytime.
Screens map[string]ScreenSettings `edit:"-"`
// text highlighting style / theme.
Highlighting HighlightingName `default:"emacs"`
// Text specifies text settings including the language, and the
// font families for different styles of fonts.
Text rich.SettingsData
// only support closing the currently selected active tab;
// if this is set to true, pressing the close button on other tabs
// will take you to that tab, from which you can close it.
OnlyCloseActiveTab bool `default:"false"`
// the maximum number of items in a menu popup panel;
// scroll bars are enforced beyond that size, or for
// completion, this is the max number of items shown.
MenuMax int `default:"30" min:"5" step:"1"`
// length of inline elements to display for containers in Form widgets.
InlineLengths InlineLengths `display:"inline"`
}
func (as *AppearanceSettingsData) Defaults() {
as.Text.Defaults()
as.Spacing = DefaultSpacing()
}
// DefaultSpacing returns the default [AppearanceSettingsData.Spacing] for
// the current platform: 100% on mobile platforms, which follows the
// touch-first sizes of Material Design 3, and 60% elsewhere, which is
// closer to the denser spacing of desktop platforms. It is 100% on the
// offscreen platform, so that the images of tests have the standard spacing.
func DefaultSpacing() float32 {
if TheApp == nil {
return 100
}
if p := TheApp.SystemPlatform(); p.IsMobile() || p == system.Offscreen {
return 100
}
return 60
}
// InlineLengths has the length of inline elements to display for containers in Form widgets.
type InlineLengths struct {
// the number of map elements at or below which an inline representation
// of the map will be presented, which is more convenient for small #'s of properties
Map int `default:"2" min:"1" step:"1"`
// the number of elemental struct fields at or below which an inline representation
// of the struct will be presented, which is more convenient for small structs
Struct int `default:"4" min:"2" step:"1"`
// the number of slice elements below which inline will be used
Slice int `default:"4" min:"2" step:"1"`
}
// ConstantSpacing returns a spacing value (padding, margin, gap)
// that will remain constant regardless of changes in the
// [AppearanceSettings.Spacing] setting.
func ConstantSpacing(value float32) float32 {
return value * 100 / AppearanceSettings.Spacing
}
// Themes are the different possible themes that a user can select in their settings.
type Themes int32 //enums:enum -trim-prefix Theme
const (
// ThemeAuto indicates to use the theme specified by the operating system
ThemeAuto Themes = iota
// ThemeLight indicates to use a light theme
ThemeLight
// ThemeDark indicates to use a dark theme
ThemeDark
)
func (as *AppearanceSettingsData) ShouldDisplay(field string) bool {
switch field {
case "Color":
return !ForceAppColor
}
return true
}
// AppColor is the default primary color used to generate the color
// scheme. The user can still change the primary color used to generate
// the color scheme through [AppearanceSettingsData.Color] unless
// [ForceAppColor] is set to true, but this value will always take
// effect if the settings color is the default value. It defaults to
// Google Blue (#4285f4).
var AppColor = color.RGBA{66, 133, 244, 255}
// ForceAppColor is whether to prevent the user from changing the color
// scheme and make it always based on [AppColor].
var ForceAppColor bool
func (as *AppearanceSettingsData) Apply() { //types:add
if ForceAppColor || (as.Color == color.RGBA{66, 133, 244, 255}) {
colors.SetSchemes(AppColor)
} else {
colors.SetSchemes(as.Color)
}
switch as.Theme {
case ThemeLight:
colors.SetScheme(false)
case ThemeDark:
colors.SetScheme(true)
case ThemeAuto:
colors.SetScheme(system.TheApp.IsDark())
}
if as.Highlighting == "" {
as.Highlighting = "emacs"
}
if rich.Settings != as.Text { // (only when changed, as it is read in other goroutines)
rich.Settings = as.Text
}
// TODO(kai): move HiStyle to a separate text editor settings
// if TheViewInterface != nil {
// TheViewInterface.SetHiStyleDefault(as.HiStyle)
// }
as.applyDPI()
}
// updateLogicalDPI updates the screen LogicalDPI values according to current
// settings and zoom factor. set this as [system.UpdateLogicalDPIFunc] function.
func (as *AppearanceSettingsData) updateLogicalDPI() {
// zoom is percentage, but LogicalDPIScale is multiplier
if scale := as.Zoom / 100; system.LogicalDPIScale != scale {
system.LogicalDPIScale = scale // (only when changed, as it is read in other goroutines)
}
// fmt.Println("system ldpi:", system.LogicalDPIScale)
n := system.TheApp.NScreens()
for i := range n {
sc := system.TheApp.Screen(i)
if sc == nil {
continue
}
if scp, ok := as.Screens[sc.Name]; ok {
// zoom is percentage, but LogicalDPIScale is multiplier
system.SetLogicalDPIScale(sc.Name, scp.Zoom/100)
}
sc.UpdateLogicalDPI()
}
}
// applyDPI updates the screen LogicalDPI values according to current
// settings and zoom factor, and then updates all open windows as well.
func (as *AppearanceSettingsData) applyDPI() {
as.updateLogicalDPI()
for _, w := range AllRenderWindows.windows() {
w.SystemWindow.SetLogicalDPI(w.SystemWindow.Screen().LogicalDPI)
// this isn't DPI-related, but this is the most efficient place to do it
w.SystemWindow.SetTitleBarIsDark(matcolor.SchemeIsDark)
}
}
// deleteSavedWindowGeometries deletes the file that saves the position and size of
// each window, by screen, and clear current in-memory cache. You shouldn't generally
// need to do this, but sometimes it is useful for testing or windows that are
// showing up in bad places that you can't recover from.
func (as *AppearanceSettingsData) deleteSavedWindowGeometries() { //types:add
theWindowGeometrySaver.deleteAll()
}
// ZebraStripesWeight returns a 0 to 0.2 alpha opacity factor to use in computing
// a zebra stripe color.
func (as *AppearanceSettingsData) ZebraStripesWeight() float32 {
return as.ZebraStripes * 0.002
}
// TimingSettings are the global timing settings.
var TimingSettings = &TimingSettingsData{
Name: "Timing",
File: filepath.Join(TheApp.CogentCoreDataDir(), "timing-settings.toml"),
}
// SaveScreenZoom saves the current zoom factor for the current screen,
// which will then be used for this screen instead of overall default.
// Use the Control +/- keyboard shortcut to modify the screen zoom level.
func (as *AppearanceSettingsData) SaveScreenZoom() { //types:add
sc := system.TheApp.Screen(0)
sp, ok := as.Screens[sc.Name]
if !ok {
sp = ScreenSettings{}
}
sp.Zoom = as.Zoom
if as.Screens == nil {
as.Screens = make(map[string]ScreenSettings)
}
as.Screens[sc.Name] = sp
errors.Log(SaveSettings(as))
}
// TimingSettingsData is the data type for the timing settings.
type TimingSettingsData struct { //types:add
SettingsBase
// SnackbarTimeout is the default amount of time until snackbars
// disappear (snackbars show short updates about app processes
// at the bottom of the screen)
SnackbarTimeout time.Duration `default:"5s"`
// The maximum time interval between button press events to count as a double-click
DoubleClickInterval time.Duration `default:"500ms" min:"100ms" step:"50ms"`
// How fast the scroll wheel moves, which is typically pixels per wheel step
// but units can be arbitrary. It is generally impossible to standardize speed
// and variable across devices, and we don't have access to the system settings,
// so unfortunately you have to set it here.
ScrollWheelSpeed float32 `default:"1" min:"0.01" step:"1"`
// The duration over which the current scroll widget retains scroll focus,
// such that subsequent scroll events are sent to it.
ScrollFocusTime time.Duration `default:"1s" min:"100ms" step:"50ms"`
// The amount of time to wait before initiating a slide event
// (as opposed to a basic press event)
SlideStartTime time.Duration `default:"50ms" min:"5ms" max:"1s" step:"5ms"`
// The amount of time to wait before initiating a drag (drag and drop) event
// (as opposed to a basic press or slide event)
DragStartTime time.Duration `default:"150ms" min:"5ms" max:"1s" step:"5ms"`
// The amount of time to wait between each repeat click event,
// when the mouse is pressed down. The first click is 8x this.
RepeatClickTime time.Duration `default:"100ms" min:"5ms" max:"1s" step:"5ms"`
// The number of pixels that must be moved before initiating a slide/drag
// event (as opposed to a basic press event)
DragStartDistance int `default:"4" min:"0" max:"100" step:"1"`
// The amount of time to wait before initiating a long hover event (e.g., for opening a tooltip)
LongHoverTime time.Duration `default:"250ms" min:"10ms" max:"10s" step:"10ms"`
// The maximum number of pixels that mouse can move and still register a long hover event
LongHoverStopDistance int `default:"5" min:"0" max:"1000" step:"1"`
// The amount of time to wait before initiating a long press event (e.g., for opening a tooltip)
LongPressTime time.Duration `default:"500ms" min:"10ms" max:"10s" step:"10ms"`
// The maximum number of pixels that mouse/finger can move and still register a long press event
LongPressStopDistance int `default:"50" min:"0" max:"1000" step:"1"`
// the amount of time to wait before offering completions
CompleteWaitDuration time.Duration `default:"0ms" min:"0ms" max:"10s" step:"10ms"`
// time interval for cursor blinking on and off -- set to 0 to disable blinking
CursorBlinkTime time.Duration `default:"500ms" min:"0ms" max:"1s" step:"5ms"`
// The amount of time to wait before trying to autoscroll again
LayoutAutoScrollDelay time.Duration `default:"25ms" min:"1ms" step:"5ms"`
// number of steps to take in PageUp / Down events in terms of number of items
LayoutPageSteps int `default:"10" min:"1" step:"1"`
// the amount of time between keypresses to combine characters into name
// to search for within layout -- starts over after this delay.
LayoutFocusNameTimeout time.Duration `default:"500ms" min:"0ms" max:"5s" step:"20ms"`
// the amount of time since last focus name event to allow tab to focus
// on next element with same name.
LayoutFocusNameTabTime time.Duration `default:"2s" min:"10ms" max:"10s" step:"100ms"`
}
func (ts *TimingSettingsData) Defaults() {
}
func (ts *TimingSettingsData) Apply() {
events.ScrollWheelSpeed = ts.ScrollWheelSpeed
}
// ScreenSettings are per-screen settings that override the global settings.
type ScreenSettings struct { //types:add
// overall zoom factor as a percentage of the default zoom
Zoom float32 `default:"100" min:"10" max:"1000" step:"10" format:"%g%%"`
}
// SystemSettings are the currently active Cogent Core system settings.
var SystemSettings = &SystemSettingsData{
Name: "System",
File: filepath.Join(TheApp.CogentCoreDataDir(), "system-settings.toml"),
}
// SystemSettingsData is the data type of the global Cogent Core settings.
type SystemSettingsData struct { //types:add
SettingsBase
// The keyboard shortcut map to use
KeyMap keymap.MapName
// The keyboard shortcut maps available as options for Key map.
// If you do not want to have custom key maps, you should leave
// this unset so that you always have the latest standard key maps.
KeyMaps option.Option[keymap.Maps]
// text editor settings
Editor text.EditorSettings
// whether to use a 24-hour clock (instead of AM and PM)
Clock24 bool `label:"24-hour clock"`
// user info, which is partially filled-out automatically if empty
// when settings are first created.
User User
// the limit of file size, above which user will be prompted before
// opening / copying, etc.
BigFileSize int `default:"10000000"`
// maximum number of saved paths to save in FilePicker
SavedPathsMax int `default:"50"`
// favorite paths, shown in FilePickerer and also editable there
FavPaths favoritePaths
}
func (ss *SystemSettingsData) Defaults() {
ss.KeyMap = keymap.DefaultMap
ss.KeyMaps.Value = keymap.AvailableMaps
ss.FavPaths.setToDefaults()
ss.updateUser()
}
// Apply detailed settings to all the relevant settings.
func (ss *SystemSettingsData) Apply() { //types:add
if ss.KeyMaps.Valid {
keymap.AvailableMaps = ss.KeyMaps.Value
}
if ss.KeyMap != "" {
keymap.SetActiveMapName(ss.KeyMap)
}
np := len(ss.FavPaths)
for i := range np {
if ss.FavPaths[i].Icon == "" || ss.FavPaths[i].Icon == "folder" {
ss.FavPaths[i].Icon = icons.Folder
}
}
}
func (ss *SystemSettingsData) Open() error {
fnm := ss.Filename()
err := tomlx.Open(ss, fnm)
if len(ss.FavPaths) == 0 {
ss.FavPaths.setToDefaults()
}
return err
}
// TimeFormat returns the Go time format layout string that should
// be used for displaying times to the user, based on the value of
// [SystemSettingsData.Clock24].
func (ss *SystemSettingsData) TimeFormat() string {
if ss.Clock24 {
return "15:04"
}
return "3:04 PM"
}
// updateUser gets the user info from the OS
func (ss *SystemSettingsData) updateUser() {
usr, err := user.Current()
if err == nil {
ss.User.User = *usr
}
}
// User basic user information that might be needed for different apps
type User struct { //types:add
user.User
// default email address -- e.g., for recording changes in a version control system
Email string
}
//////// FavoritePaths
// favoritePathItem represents one item in a favorite path list, for display of
// favorites. Is an ordered list instead of a map because user can organize
// in order
type favoritePathItem struct { //types:add
// icon for item
Icon icons.Icon
// name of the favorite item
Name string `width:"20"`
// the path of the favorite item
Path string `table:"-select"`
}
// Label satisfies the Labeler interface
func (fi favoritePathItem) Label() string {
return fi.Name
}
// favoritePaths is a list (slice) of favorite path items
type favoritePaths []favoritePathItem
// setToDefaults sets the paths to default values
func (pf *favoritePaths) setToDefaults() {
*pf = make(favoritePaths, len(defaultPaths))
copy(*pf, defaultPaths)
}
// findPath returns index of path on list, or -1, false if not found
func (pf *favoritePaths) findPath(path string) (int, bool) {
for i, fi := range *pf {
if fi.Path == path {
return i, true
}
}
return -1, false
}
// defaultPaths are default favorite paths
var defaultPaths = favoritePaths{
{icons.Home, "home", "~"},
{icons.DesktopMac, "Desktop", "~/Desktop"},
{icons.Document, "Documents", "~/Documents"},
{icons.Download, "Downloads", "~/Downloads"},
{icons.Computer, "root", "/"},
}
//////// FilePaths
// FilePaths represents a set of file paths.
type FilePaths []string
// recentPaths are the recently opened paths in the file picker.
var recentPaths FilePaths
// Open file paths from a json-formatted file.
func (fp *FilePaths) Open(filename string) error { //types:add
err := jsonx.Open(fp, filename)
if err != nil && !errors.Is(err, fs.ErrNotExist) {
errors.Log(err)
}
return err
}
// Save file paths to a json-formatted file.
func (fp *FilePaths) Save(filename string) error { //types:add
return errors.Log(jsonx.Save(fp, filename))
}
// AddPath inserts a path to the file paths (at the start), subject to max
// length -- if path is already on the list then it is moved to the start.
func (fp *FilePaths) AddPath(path string, max int) {
stringsx.InsertFirstUnique((*[]string)(fp), path, max)
}
// savedPathsFilename is the name of the saved file paths file in
// the Cogent Core data directory.
const savedPathsFilename = "saved-paths.json"
// saveRecentPaths saves the active RecentPaths to data dir
func saveRecentPaths() {
pdir := TheApp.CogentCoreDataDir()
pnm := filepath.Join(pdir, savedPathsFilename)
errors.Log(recentPaths.Save(pnm))
}
// openRecentPaths loads the active RecentPaths from data dir
func openRecentPaths() {
pdir := TheApp.CogentCoreDataDir()
pnm := filepath.Join(pdir, savedPathsFilename)
err := recentPaths.Open(pnm)
if err != nil && !errors.Is(err, fs.ErrNotExist) {
errors.Log(err)
}
}
//////// DebugSettings
// DebugSettings are the currently active debugging settings
var DebugSettings = &DebugSettingsData{
Name: "Debug",
File: filepath.Join(TheApp.CogentCoreDataDir(), "debug-settings.toml"),
}
// DebugSettingsData is the data type for debugging settings.
type DebugSettingsData struct { //types:add
SettingsBase
// Print a trace of updates that trigger re-rendering
UpdateTrace bool
// Print a trace of the nodes rendering
RenderTrace bool
// Print a trace of all layouts
LayoutTrace bool
// Print more detailed info about the underlying layout computations
LayoutTraceDetail bool
// Print a trace of window events
WindowEventTrace bool
// Print the stack trace leading up to win publish events
// which are expensive
WindowRenderTrace bool
// Print a trace of window geometry saving / loading functions
WindowGeometryTrace bool
// Print a trace of keyboard events
KeyEventTrace bool
// Print a trace of event handling
EventTrace bool
// Print a trace of focus changes
FocusTrace bool
// Print a trace of DND event handling
DNDTrace bool
// DisableWindowGeometrySaver disables the saving and loading of window geometry
// data to allow for easier testing of window manipulation code.
DisableWindowGeometrySaver bool
// Print a trace of Go language completion and lookup process
GoCompleteTrace bool
// Print a trace of Go language type parsing and inference process
GoTypeTrace bool
}
func (db *DebugSettingsData) Defaults() {
// TODO(kai/binsize): figure out how to do this without dragging in parse langs dependency
// db.GoCompleteTrace = golang.CompleteTrace
// db.GoTypeTrace = golang.TraceTypes
}
func (db *DebugSettingsData) Apply() {
// golang.CompleteTrace = db.GoCompleteTrace
// golang.TraceTypes = db.GoTypeTrace
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"image"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/tree"
)
// settingsEditorToolbarBase is the base toolbar configuration
// function used in [SettingsEditor].
func settingsEditorToolbarBase(p *tree.Plan) {
tree.Add(p, func(w *FuncButton) {
w.SetFunc(AppearanceSettings.SaveScreenZoom).SetIcon(icons.ZoomIn)
w.SetAfterFunc(func() {
AppearanceSettings.Apply()
UpdateAll()
})
})
}
// SettingsWindow opens a window for editing user settings.
func SettingsWindow() { //types:add
if RecycleMainWindow(&AllSettings) {
return
}
d := NewBody("Settings").SetData(&AllSettings)
SettingsEditor(d)
d.RunWindow()
}
// SettingsEditor adds to the given body an editor of user settings.
func SettingsEditor(b *Body) {
b.AddTopBar(func(bar *Frame) {
tb := NewToolbar(bar)
tb.Maker(settingsEditorToolbarBase)
for _, se := range editorSettings() {
tb.Maker(se.MakeToolbar)
}
tb.AddOverflowMenu(func(m *Scene, pos image.Point) {
NewFuncButton(m).SetFunc(resetAllSettings).SetConfirm(true).SetText("Reset settings").SetIcon(icons.Delete)
NewFuncButton(m).SetFunc(AppearanceSettings.deleteSavedWindowGeometries).SetConfirm(true).SetIcon(icons.Delete)
NewFuncButton(m).SetFunc(ProfileToggle).SetShortcut("Control+Alt+R").SetText("Profile performance").SetIcon(icons.Analytics)
})
})
tabs := NewTabs(b)
for _, se := range editorSettings() { // the app settings first
fr, _ := tabs.NewTab(se.Label())
NewForm(fr).SetStruct(se).OnChange(func(e events.Event) {
UpdateSettings(fr, se)
})
}
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"image"
"cogentcore.org/core/math32"
)
// SizeClasses are the different size classes that a window can have.
type SizeClasses int32 //enums:enum -trim-prefix Size
const (
// SizeCompact is the size class for windows with a width less than
// 600dp, which typically happens on phones.
SizeCompact SizeClasses = iota
// SizeMedium is the size class for windows with a width between 600dp
// and 840dp inclusive, which typically happens on tablets.
SizeMedium
// SizeExpanded is the size class for windows with a width greater than
// 840dp, which typically happens on desktop and laptop computers.
SizeExpanded
)
// SceneSize returns the effective size of the scene in which the widget is contained
// in terms of dp (density-independent pixels).
func (wb *WidgetBase) SceneSize() math32.Vector2 {
sc := wb.Scene
dots := sc.SceneGeom.Size
// While the scene is sized to its content, the size of the window that it
// is shown in is used, if it has one. A scene of a new window does not
// have one yet, so the size it is expected to have is used instead, once
// that is known (see [Stage.runWindow]). It is
// never the current window, which a new window is not shown in, and which
// changes as other windows are opened and closed.
if sc.hasFlag(sceneContentSizing) {
if rw := sc.RenderWindow(); rw != nil {
dots = rw.SystemWindow.RenderGeom().Size
} else if sc.sizingSize != (image.Point{}) {
dots = sc.sizingSize
}
}
return sc.dotsToDp(dots)
}
// dotsToDp converts the given size in dots to dp (density-independent pixels).
func (sc *Scene) dotsToDp(dots image.Point) math32.Vector2 {
dpd := sc.Styles.UnitContext.Dp(1) // dots per dp
return math32.FromPoint(dots).DivScalar(dpd) // dots / (dots / dp) = dots * (dp / dots) = dp
}
// SizeClass returns the size class of the scene in which the widget is contained
// based on [WidgetBase.SceneSize].
func (wb *WidgetBase) SizeClass() SizeClasses {
return sizeClassOf(wb.SceneSize().X)
}
// sizeClassOf returns the size class for the given width in dp.
func sizeClassOf(dp float32) SizeClasses {
switch {
case dp < 600:
return SizeCompact
case dp > 840:
return SizeExpanded
default:
return SizeMedium
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"fmt"
"image"
"log/slog"
"reflect"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/colors"
"cogentcore.org/core/cursors"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/keymap"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/tree"
)
// Slider is a slideable widget that provides slider functionality with a draggable
// thumb and a clickable track. The [styles.Style.Direction] determines the direction
// in which the slider slides: Row = left-to-right, Column = top-to-bottom (use Flip
// to invert these directions).
type Slider struct {
Frame
// Type is the type of the slider, which determines its visual
// and functional properties. The default type, [SliderSlider],
// should work for most end-user use cases.
Type SliderTypes
// Value is the current value, represented by the position of the thumb.
// It defaults to 0.5.
Value float32 `set:"-"`
// Min is the minimum possible value.
// It defaults to 0.
Min float32
// Max is the maximum value supported.
// It defaults to 1.
Max float32
// Step is the amount that the arrow keys increment/decrement the value by.
// It defaults to 0.1.
Step float32
// EnforceStep is whether to ensure that the value is always
// a multiple of [Slider.Step].
EnforceStep bool
// PageStep is the amount that the PageUp and PageDown keys
// increment/decrement the value by.
// It defaults to 0.2, and will be at least as big as [Slider.Step].
PageStep float32
// Flip inverts the direction that the slider slides: if true, then
// Row = right-to-left and Column = bottom-to-top.
Flip bool
// Icon is an optional icon to use for the dragging thumb.
Icon icons.Icon
// For Scrollbar type only: proportion (1 max) of the full range of scrolled data
// that is currently visible. This determines the thumb size and range of motion:
// if 1, full slider is the thumb and no motion is possible.
visiblePercent float32 `set:"-"`
// ThumbSize is the size of the thumb as a proportion of the slider thickness,
// which is the content size (inside the padding).
ThumbSize math32.Vector2
// TrackSize is the proportion of slider thickness for the visible track
// for the [SliderSlider] type. It is often thinner than the thumb, achieved
// by values less than 1 (0.5 default).
TrackSize float32 `default:"0.5"`
// InputThreshold is the threshold for the amount of change in scroll
// value before emitting an input event.
InputThreshold float32
// Precision specifies the precision of decimal places (total, not after the decimal
// point) to use in representing the number. This helps to truncate small weird
// floating point values.
Precision int
// ValueColor is the background color that is used for styling the selected value
// section of the slider. It should be set in a Styler, just like the main style
// object is. If it is set to transparent, no value is rendered, so the value
// section of the slider just looks like the rest of the slider.
ValueColor image.Image
// ThumbColor is the background color that is used for styling the thumb (handle)
// of the slider. It should be set in a Styler, just like the main style object is.
// If it is set to transparent, no thumb is rendered, so the thumb section of the
// slider just looks like the rest of the slider.
ThumbColor image.Image
// StayInView is whether to keep the slider (typically a [SliderScrollbar]) within
// the parent [Scene] bounding box, if the parent is in view. This is the default
// behavior for [Frame] scrollbars, and setting this flag replicates that behavior
// in other scrollbars.
StayInView bool
// Computed values below:
// logical position of the slider in dots (pixels), relative to Size
pos float32
// previous Change event emitted value; don't re-emit Change if it is the same
lastValue float32
// previous sliding value (for computing the Input change)
prevSlide float32
// slideStartPos is the underlying drag position of the slider where the
// mouse was pressed, relative to which a slide moves it; it is not
// subject to snapping.
slideStartPos float32
}
// SliderTypes are the different types of sliders.
type SliderTypes int32 //enums:enum -trim-prefix Slider
const (
// SliderSlider indicates a standard, user-controllable slider
// for setting a numeric value.
SliderSlider SliderTypes = iota
// SliderScrollbar indicates a slider acting as a scrollbar for content.
// It has a [Slider.visiblePercent] factor that specifies the percent of the content
// currently visible, which determines the size of the thumb, and thus the range
// of motion remaining for the thumb Value ([Slider.visiblePercent] = 1 means thumb
// is full size, and no remaining range of motion). The content size (inside the
// margin and padding) determines the outer bounds of the rendered area.
SliderScrollbar
)
func (sr *Slider) WidgetValue() any { return &sr.Value }
func (sr *Slider) OnBind(value any, tags reflect.StructTag) {
kind := reflectx.NonPointerType(reflect.TypeOf(value)).Kind()
if kind >= reflect.Int && kind <= reflect.Uintptr {
sr.SetStep(1).SetEnforceStep(true).SetMax(100)
}
setFromTag(tags, "min", func(v float32) { sr.SetMin(v) })
setFromTag(tags, "max", func(v float32) { sr.SetMax(v) })
setFromTag(tags, "step", func(v float32) { sr.SetStep(v) })
}
func (sr *Slider) Init() {
sr.Frame.Init()
sr.Value = 0.5
sr.Max = 1
sr.visiblePercent = 1
sr.Step = 0.1
sr.PageStep = 0.2
sr.Precision = 9
sr.ThumbSize.Set(1, 1)
sr.TrackSize = 0.5
sr.lastValue = -math32.MaxFloat32
sr.Styler(func(s *styles.Style) {
s.SetAbilities(true, abilities.Activatable, abilities.Focusable, abilities.Hoverable, abilities.Slideable, abilities.SlidePriority)
// we use a different color for the thumb and value color
// (compared to the background color) so that they get the
// correct state layer
s.Color = colors.Scheme.Primary.On
if sr.Type == SliderSlider {
sr.ValueColor = colors.Scheme.Primary.Base
sr.ThumbColor = colors.Scheme.Primary.Base
s.Padding.Set(units.Dp(8))
s.Background = colors.Scheme.SurfaceVariant
} else {
sr.ValueColor = colors.Scheme.OutlineVariant
sr.ThumbColor = colors.Scheme.OutlineVariant
s.Background = colors.Scheme.SurfaceContainerLow
}
// sr.ValueColor = s.StateBackgroundColor(sr.ValueColor)
// sr.ThumbColor = s.StateBackgroundColor(sr.ThumbColor)
s.Color = colors.Scheme.OnSurface
s.Border.Radius = styles.BorderRadiusFull
if !sr.IsReadOnly() {
s.Cursor = cursors.Grab
switch {
case s.Is(states.Sliding):
s.Cursor = cursors.Grabbing
case s.Is(states.Active):
s.Cursor = cursors.Grabbing
}
}
})
sr.FinalStyler(func(s *styles.Style) {
if s.Direction == styles.Row {
s.Min.X.Em(20)
s.Min.Y.Em(1)
} else {
s.Min.Y.Em(20)
s.Min.X.Em(1)
}
if sr.Type == SliderScrollbar {
if s.Direction == styles.Row {
s.Min.Y = s.ScrollbarWidth
} else {
s.Min.X = s.ScrollbarWidth
}
}
})
sr.On(events.SlideStart, func(e events.Event) {
pos := sr.pointToRelPos(e.Pos())
sr.setSliderPosEvent(pos)
sr.lastValue = -math32.MaxFloat32
// The slide moves are relative to where the mouse was pressed,
// not to where the slide started, which depends on how far the
// mouse moved before the slide start time.
sr.slideStartPos = pos - sr.slideDelta(e)
})
sr.On(events.SlideMove, func(e events.Event) {
sr.setSliderPosEvent(sr.slideStartPos + sr.slideDelta(e))
})
sr.On(events.SlideStop, func(e events.Event) {
sr.setSliderPosEvent(sr.slideStartPos + sr.slideDelta(e))
sr.sendChange()
})
sr.On(events.Click, func(e events.Event) {
pos := sr.pointToRelPos(e.Pos())
if !sr.setSliderPosEvent(pos) {
sr.Send(events.Input) // always send on click even if same.
}
sr.sendChange()
})
sr.On(events.Scroll, func(e events.Event) {
se := e.(*events.MouseScroll)
se.SetHandled()
var del float32
// if we are scrolling in the y direction on an x slider,
// we still count it
if sr.Styles.Direction == styles.Row && se.Delta.X != 0 {
del = se.Delta.X
} else {
del = se.Delta.Y
}
if sr.Type == SliderScrollbar {
del = -del // invert for "natural" scroll
}
edel := sr.scrollScale(del)
sr.setValueEvent(sr.Value + edel)
sr.sendChange()
})
sr.OnKeyChord(func(e events.Event) {
kf := keymap.Of(e.KeyChord())
if DebugSettings.KeyEventTrace {
slog.Info("SliderBase KeyInput", "widget", sr, "keyFunction", kf)
}
step := sr.Step
if sr.PageStep < sr.Step {
sr.PageStep = 2 * sr.Step
}
pageStep := sr.PageStep
if sr.Flip {
step = -step
pageStep = -pageStep
}
switch kf {
case keymap.MoveUp:
sr.setValueEvent(sr.Value - step)
e.SetHandled()
case keymap.MoveLeft:
sr.setValueEvent(sr.Value - step)
e.SetHandled()
case keymap.MoveDown:
sr.setValueEvent(sr.Value + step)
e.SetHandled()
case keymap.MoveRight:
sr.setValueEvent(sr.Value + step)
e.SetHandled()
case keymap.PageUp:
sr.setValueEvent(sr.Value - pageStep)
e.SetHandled()
case keymap.PageDown:
sr.setValueEvent(sr.Value + pageStep)
e.SetHandled()
case keymap.Home:
if sr.Flip {
sr.setValueEvent(sr.Max)
} else {
sr.setValueEvent(sr.Min)
}
e.SetHandled()
case keymap.End:
if sr.Flip {
sr.setValueEvent(sr.Min)
} else {
sr.setValueEvent(sr.Max)
}
e.SetHandled()
}
})
sr.Maker(func(p *tree.Plan) {
if !sr.Icon.IsSet() {
return
}
tree.AddAt(p, "icon", func(w *Icon) {
w.Styler(func(s *styles.Style) {
s.Font.Size.Dp(24)
s.Color = sr.ThumbColor
})
w.Updater(func() {
w.SetIcon(sr.Icon)
})
})
})
}
// snapValue snaps the value to [Slider.Step] if [Slider.EnforceStep] is on.
func (sr *Slider) snapValue() {
if !sr.EnforceStep {
return
}
// round to the nearest step
sr.Value = sr.Step * math32.Round(sr.Value/sr.Step)
}
// sendChange calls [WidgetBase.SendChange] if the current value
// is different from the last value.
func (sr *Slider) sendChange(e ...events.Event) bool {
if sr.Value == sr.lastValue {
return false
}
sr.lastValue = sr.Value
sr.SendChange(e...)
return true
}
// sliderSize returns the size available for sliding, based on allocation
func (sr *Slider) sliderSize() float32 {
sz := sr.Geom.Size.Actual.Content.Dim(sr.Styles.Direction.Dim())
if sr.Type != SliderScrollbar {
thsz := sr.thumbSizeDots()
sz -= thsz.Dim(sr.Styles.Direction.Dim()) // half on each size
}
return sz
}
// sliderThickness returns the thickness of the slider: Content size in other dim.
func (sr *Slider) sliderThickness() float32 {
return sr.Geom.Size.Actual.Content.Dim(sr.Styles.Direction.Dim().Other())
}
// thumbSizeDots returns the thumb size in dots, based on ThumbSize
// and the content thickness
func (sr *Slider) thumbSizeDots() math32.Vector2 {
return sr.ThumbSize.MulScalar(sr.sliderThickness())
}
// slideThumbSize returns thumb size, based on type
func (sr *Slider) slideThumbSize() float32 {
if sr.Type == SliderScrollbar {
minsz := sr.sliderThickness()
return max(math32.Clamp(sr.visiblePercent, 0, 1)*sr.sliderSize(), minsz)
}
return sr.thumbSizeDots().Dim(sr.Styles.Direction.Dim())
}
// effectiveMax returns the effective maximum value represented.
// For the Slider type, it it is just Max.
// for the Scrollbar type, it is Max - Value of thumb size
func (sr *Slider) effectiveMax() float32 {
if sr.Type == SliderScrollbar {
return sr.Max - math32.Clamp(sr.visiblePercent, 0, 1)*(sr.Max-sr.Min)
}
return sr.Max
}
// scrollThumbValue returns the current scroll VisiblePct
// in terms of the Min - Max range of values.
func (sr *Slider) scrollThumbValue() float32 {
return math32.Clamp(sr.visiblePercent, 0, 1) * (sr.Max - sr.Min)
}
// setSliderPos sets the position of the slider at the given
// relative position within the usable Content sliding range,
// in pixels, and updates the corresponding Value based on that position.
func (sr *Slider) setSliderPos(pos float32) {
sz := sr.Geom.Size.Actual.Content.Dim(sr.Styles.Direction.Dim())
if sz <= 0 {
return
}
thsz := sr.slideThumbSize()
thszh := .5 * thsz
sr.pos = math32.Clamp(pos, thszh, sz-thszh)
prel := (sr.pos - thszh) / (sz - thsz)
effmax := sr.effectiveMax()
val := math32.Truncate(sr.Min+prel*(effmax-sr.Min), sr.Precision)
val = math32.Clamp(val, sr.Min, effmax)
sr.Value = val
sr.snapValue()
sr.setPosFromValue(sr.Value) // go back the other way to be fully consistent
sr.NeedsRender()
}
// setSliderPosEvent sets the position of the slider at the given position in pixels,
// and updates the corresponding Value based on that position.
// This version sends input events. Returns true if event sent.
func (sr *Slider) setSliderPosEvent(pos float32) bool {
sr.setSliderPos(pos)
if math32.Abs(sr.prevSlide-sr.Value) > sr.InputThreshold {
sr.prevSlide = sr.Value
sr.Send(events.Input)
return true
}
return false
}
// setPosFromValue sets the slider position based on the given value
// (typically rs.Value), and marks the slider as needing to be rendered.
func (sr *Slider) setPosFromValue(val float32) {
if sr.updatePos(val) {
sr.NeedsRender()
}
}
// updatePos sets the slider position based on the given value
// (typically rs.Value), without marking it as needing to be rendered.
// It returns false if the slider has no size yet.
func (sr *Slider) updatePos(val float32) bool {
sz := sr.Geom.Size.Actual.Content.Dim(sr.Styles.Direction.Dim())
if sz <= 0 {
return false
}
effmax := sr.effectiveMax()
val = math32.Clamp(val, sr.Min, effmax)
prel := (val - sr.Min) / (effmax - sr.Min) // relative position 0-1
thsz := sr.slideThumbSize()
thszh := .5 * thsz
sr.pos = 0.5*thsz + prel*(sz-thsz)
sr.pos = math32.Clamp(sr.pos, thszh, sz-thszh)
return true
}
// SetVisiblePercent sets the [Slider.visiblePercent] value for a [SliderScrollbar].
func (sr *Slider) SetVisiblePercent(val float32) *Slider {
sr.visiblePercent = math32.Clamp(val, 0, 1)
return sr
}
// SetValue sets the value and updates the slider position,
// but does not send an [events.Change] event.
func (sr *Slider) SetValue(value float32) *Slider {
effmax := sr.effectiveMax()
value = math32.Clamp(value, sr.Min, effmax)
if sr.Value != value {
sr.Value = value
sr.snapValue()
sr.setPosFromValue(value)
}
sr.NeedsRender()
return sr
}
// setValueEvent sets the value and updates the slider representation, and
// emits an input and change event. Returns true if value actually changed.
func (sr *Slider) setValueEvent(val float32) bool {
if sr.Value == val {
return false
}
curVal := sr.Value
sr.SetValue(val)
sr.Send(events.Input)
sr.SendChange()
return curVal != sr.Value
}
func (sr *Slider) WidgetTooltip(pos image.Point) (string, image.Point) {
res := sr.Tooltip
if sr.Type == SliderScrollbar {
return res, sr.DefaultTooltipPos()
}
if res != "" {
res += " "
}
res += fmt.Sprintf("(value: %.4g, minimum: %.4g, maximum: %.4g)", sr.Value, sr.Min, sr.Max)
return res, sr.DefaultTooltipPos()
}
// slideDelta returns the distance that the mouse has moved along the
// slider since it was pressed, for the given slide event.
func (sr *Slider) slideDelta(e events.Event) float32 {
del := math32.FromPoint(e.StartDelta()).Dim(sr.Styles.Direction.Dim())
if sr.Flip {
del = -del
}
return del
}
// pointToRelPos translates a point in scene local pixel coords into relative
// position within the slider content range
func (sr *Slider) pointToRelPos(pt image.Point) float32 {
dim := sr.Styles.Direction.Dim()
ptf := math32.FromPoint(pt).Dim(dim)
pos := sr.Geom.Pos.Content.Dim(dim)
sz := sr.Geom.Size.Actual.Content.Dim(dim)
if sr.Flip {
return (pos + sz) - ptf
}
return ptf - pos
}
// scrollScale returns scaled value of scroll delta
// as a function of the step size.
func (sr *Slider) scrollScale(del float32) float32 {
return del * sr.Step
}
func (sr *Slider) Render() {
// The position is updated without marking the slider as needing to be
// rendered again, which would render it again by itself in the next update.
sr.updatePos(sr.Value)
pc := &sr.Scene.Painter
st := &sr.Styles
dim := sr.Styles.Direction.Dim()
od := dim.Other()
sz := sr.Geom.Size.Actual.Content
pos := sr.Geom.Pos.Content
pabg := sr.parentActualBackground()
if sr.Type == SliderScrollbar {
pc.StandardBox(st, pos, sz, pabg) // track
if sr.ValueColor != nil {
thsz := sr.slideThumbSize()
osz := sr.thumbSizeDots().Dim(od)
origsz := sz.Dim(od)
tpos := pos
tpos = tpos.AddDim(od, 0.5*(osz-origsz))
tsz := sz
tsz.SetDim(dim, thsz)
tsz.SetDim(od, osz)
if sr.Flip {
tpos.SetDim(dim, (pos.Dim(dim)+sz.Dim(dim)-sr.pos)-thsz*.5)
} else {
tpos = tpos.AddDim(dim, sr.pos-thsz*.5)
}
vabg := sr.Styles.ComputeActualBackgroundFor(sr.ValueColor, pabg)
pc.Fill.Color = vabg
sr.RenderBoxGeom(tpos, tsz, styles.Border{Radius: st.Border.Radius}) // thumb
}
} else {
prevbg := st.Background
prevsl := st.StateLayer
if !transparentBackground(pabg) {
// use surrounding background with no state layer for surrounding box
st.Background = pabg
st.StateLayer = 0
st.ComputeActualBackground(pabg)
// surrounding box (needed to prevent it from rendering over itself)
sr.RenderStandardBox()
st.Background = prevbg
st.StateLayer = prevsl
}
// (no surrounding box over a transparent background, which would
// clear what is under it, as the video under its controls, whose
// widget renders them as a whole: see video.Controls.ChildBackground)
st.ComputeActualBackground(pabg)
trsz := sz.Dim(od) * sr.TrackSize
bsz := sz
bsz.SetDim(od, trsz)
bpos := pos
thsz := sr.thumbSizeDots()
tpos := pos
if sr.Flip {
tpos.SetDim(dim, pos.Dim(dim)+sz.Dim(dim)-sr.pos)
} else {
tpos.SetDim(dim, pos.Dim(dim)+sr.pos)
}
tpos = tpos.AddDim(od, 0.5*sz.Dim(od)) // ctr
bpos = bpos.AddDim(od, 0.5*(sz.Dim(od)-trsz))
pc.Fill.Color = st.ActualBackground
sr.RenderBoxGeom(bpos, bsz, styles.Border{Radius: st.Border.Radius}) // track
if sr.ValueColor != nil {
vabg := sr.Styles.ComputeActualBackgroundFor(sr.ValueColor, pabg)
pc.Fill.Color = vabg
bsz.SetDim(dim, sr.pos)
if sr.Flip {
tp := tpos.SubDim(od, 0.5*trsz)
sr.RenderBoxGeom(tp, bsz, styles.Border{Radius: st.Border.Radius})
} else {
sr.RenderBoxGeom(bpos, bsz, styles.Border{Radius: st.Border.Radius})
}
}
// render thumb as icon or box
if sr.Icon.IsSet() && sr.HasChildren() {
ic := sr.Child(0).(*Icon)
tpos.SetSub(thsz.MulScalar(.5))
ic.Geom.Pos.Total = tpos
ic.setContentPosFromPos()
ic.setBBoxes()
} else {
tabg := sr.Styles.ComputeActualBackgroundFor(sr.ThumbColor, pabg)
pc.Fill.Color = tabg
tpos.SetSub(thsz.MulScalar(0.5))
sr.RenderBoxGeom(tpos, thsz, styles.Border{Radius: st.Border.Radius})
}
}
}
func (sr *Slider) ApplyScenePos() {
sr.WidgetBase.ApplyScenePos()
if !sr.StayInView {
return
}
pwb := sr.parentWidget()
if !pwb.IsVisible() {
return
}
sbw := math32.Ceil(sr.Styles.ScrollbarWidth.Dots)
scmax := math32.FromPoint(sr.Scene.Geom.ContentBBox.Max).SubScalar(sbw)
sr.Geom.Pos.Total.SetMin(scmax)
sr.setContentPosFromPos()
sr.setBBoxesFromAllocs()
}
// transparentBackground returns whether the given background is a fully
// transparent color.
func transparentBackground(bg image.Image) bool {
u, ok := bg.(*image.Uniform)
if !ok {
return false
}
_, _, _, a := u.RGBA()
return a == 0
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"log/slog"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/colors"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/styles/units"
)
// RunSnackbar returns and runs a new [SnackbarStage] in the context
// of the given widget. See [Body.NewSnackbar] to make a snackbar without running it.
func (bd *Body) RunSnackbar(ctx Widget) *Stage {
return bd.NewSnackbar(ctx).Run()
}
// NewSnackbar returns a new [SnackbarStage] in the context
// of the given widget. You must call [Stage.Run] to run the
// snackbar; see [Body.RunSnackbar] for a version that
// automatically runs it.
func (bd *Body) NewSnackbar(ctx Widget) *Stage {
ctx = nonNilContext(ctx)
bd.snackbarStyles()
bd.Scene.Stage = NewPopupStage(SnackbarStage, bd.Scene, ctx).
SetTimeout(TimingSettings.SnackbarTimeout)
return bd.Scene.Stage
}
// MessageSnackbar opens a [SnackbarStage] displaying the given message
// in the context of the given widget.
func MessageSnackbar(ctx Widget, message string) {
NewBody().AddSnackbarText(message).RunSnackbar(ctx)
}
// ErrorSnackbar opens a [SnackbarStage] displaying the given error
// in the context of the given widget. Optional label text can be
// provided; if it is not, the label text will default to "Error".
// If the given error is nil, no snackbar is created.
func ErrorSnackbar(ctx Widget, err error, label ...string) {
if err == nil {
return
}
lbl := "Error"
if len(label) > 0 {
lbl = label[0]
}
text := lbl + ": " + err.Error()
// we need to get [errors.CallerInfo] at this level
slog.Error(text + " | " + errors.CallerInfo())
MessageSnackbar(ctx, text)
}
// snackbarStyles sets default stylers for snackbar bodies.
// It is automatically called in [Body.NewSnackbar].
func (bd *Body) snackbarStyles() {
bd.Styler(func(s *styles.Style) {
s.Direction = styles.Row
s.Overflow.Set(styles.OverflowVisible) // key for avoiding sizing errors when re-rendering with small pref size
s.Border.Radius = styles.BorderRadiusExtraSmall
s.Padding.SetHorizontal(units.Dp(16))
s.Background = colors.Scheme.InverseSurface
s.Color = colors.Scheme.InverseOnSurface
// we go on top of things so we want no margin background
s.FillMargin = false
s.Align.Content = styles.Center
s.Align.Items = styles.Center
s.Gap.X.Dp(12)
s.Grow.Set(1, 0)
s.Min.Y.Dp(48)
s.Min.X.SetCustom(func(uc *units.Context) float32 {
return min(uc.Em(20), uc.Vw(70))
})
})
bd.Scene.Styler(func(s *styles.Style) {
s.Background = nil
s.Border.Radius = styles.BorderRadiusExtraSmall
s.BoxShadow = styles.BoxShadow3()
})
}
// AddSnackbarText adds a snackbar [Text] with the given text.
func (bd *Body) AddSnackbarText(text string) *Body {
tx := NewText(bd).SetText(text).SetType(TextBodyMedium)
tx.Styler(func(s *styles.Style) {
s.SetTextWrap(false)
if s.Is(states.Selected) {
s.Color = colors.Scheme.Select.OnContainer
}
})
return bd
}
// AddSnackbarButton adds a snackbar button with the given text and optional OnClick
// event handler. Only the first of the given event handlers is used, and the
// snackbar is automatically closed when the button is clicked regardless of
// whether there is an event handler passed.
func (bd *Body) AddSnackbarButton(text string, onClick ...func(e events.Event)) *Body {
NewStretch(bd)
bt := NewButton(bd).SetType(ButtonText).SetText(text)
bt.Styler(func(s *styles.Style) {
s.Color = colors.Scheme.InversePrimary
})
bt.OnClick(func(e events.Event) {
if len(onClick) > 0 {
onClick[0](e)
}
bd.Scene.Stage.ClosePopup()
})
return bd
}
// AddSnackbarIcon adds a snackbar icon button with the given icon and optional
// OnClick event handler. Only the first of the given event handlers is used, and the
// snackbar is automatically closed when the button is clicked regardless of whether
// there is an event handler passed.
func (bd *Body) AddSnackbarIcon(icon icons.Icon, onClick ...func(e events.Event)) *Body {
ic := NewButton(bd).SetType(ButtonAction).SetIcon(icon)
ic.Styler(func(s *styles.Style) {
s.Color = colors.Scheme.InverseOnSurface
})
ic.OnClick(func(e events.Event) {
if len(onClick) > 0 {
onClick[0](e)
}
bd.Scene.Stage.ClosePopup()
})
return bd
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"fmt"
"image"
"log/slog"
"reflect"
"strconv"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/events"
"cogentcore.org/core/events/key"
"cogentcore.org/core/icons"
"cogentcore.org/core/keymap"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/tree"
)
// Spinner is a [TextField] for editing numerical values. It comes with
// fields, methods, buttons, and shortcuts to enhance numerical value editing.
type Spinner struct {
TextField
// Value is the current value.
Value float32 `set:"-"`
// HasMin is whether there is a minimum value to enforce.
// It should be set using [Spinner.SetMin].
HasMin bool `set:"-"`
// Min, if [Spinner.HasMin] is true, is the the minimum value in range.
// It should be set using [Spinner.SetMin].
Min float32 `set:"-"`
// HaxMax is whether there is a maximum value to enforce.
// It should be set using [Spinner.SetMax].
HasMax bool `set:"-"`
// Max, if [Spinner.HasMax] is true, is the maximum value in range.
// It should be set using [Spinner.SetMax].
Max float32 `set:"-"`
// Step is the amount that the up and down buttons and arrow keys
// increment/decrement the value by. It defaults to 0.1.
Step float32
// EnforceStep is whether to ensure that the value of the spinner
// is always a multiple of [Spinner.Step].
EnforceStep bool
// PageStep is the multiplier on Step for the PageUp and PageDown keys
// to increment/decrement the value by. It defaults to 10.
PageStep float32
// StepFunc is an optional function to return the new value
// after incrementing the value by given number of steps (+ or -).
// This allows for custom stepping functions (e.g., that use logarithmic
// step increments). The returned value is subject to the Min/Max and
// EnforceStep settings (generally set EnforceStep = false here).
StepFunc func(sp *Spinner, steps float32) float32
// Precision specifies the precision of decimal places
// (total, not after the decimal point) to use in
// representing the number. This helps to truncate
// small weird floating point values.
Precision int
// Format is the format string to use for printing the value.
// If it unset, %g is used. If it is decimal based
// (ends in d, b, c, o, O, q, x, X, or U) then the value is
// converted to decimal prior to printing.
Format string
}
func (sp *Spinner) WidgetValue() any { return &sp.Value }
func (sp *Spinner) SetWidgetValue(value any) error {
f, err := reflectx.ToFloat32(value)
if err != nil {
return err
}
sp.SetValue(f)
return nil
}
func (sp *Spinner) OnBind(value any, tags reflect.StructTag) {
kind := reflectx.NonPointerType(reflect.TypeOf(value)).Kind()
if kind >= reflect.Int && kind <= reflect.Uintptr {
sp.SetStep(1).SetEnforceStep(true)
if kind >= reflect.Uint {
sp.SetMin(0)
}
}
if f, ok := tags.Lookup("format"); ok {
sp.SetFormat(f)
}
setFromTag(tags, "min", func(v float32) { sp.SetMin(v) })
setFromTag(tags, "max", func(v float32) { sp.SetMax(v) })
setFromTag(tags, "step", func(v float32) { sp.SetStep(v) })
}
func (sp *Spinner) Init() {
sp.TextField.Init()
sp.SetStep(0.1).SetPageStep(10).SetPrecision(6).SetFormat("%g")
sp.SetLeadingIcon(icons.Remove, func(e events.Event) {
if e.HasAnyModifier(key.Shift, key.Alt) {
sp.pageIncrementValue(-1)
} else {
sp.incrementValue(-1)
}
}).SetTrailingIcon(icons.Add, func(e events.Event) {
if e.HasAnyModifier(key.Shift, key.Alt) {
sp.pageIncrementValue(1)
} else {
sp.incrementValue(1)
}
})
sp.Updater(sp.setTextToValue)
sp.Styler(func(s *styles.Style) {
s.SetTextWrap(false)
s.VirtualKeyboard = styles.KeyboardNumber
if sp.IsReadOnly() {
s.Min.X.Ch(6)
s.Max.X.Ch(14)
} else {
s.Min.X.Ch(14)
s.Max.X.Ch(22)
}
// s.Text.Align = styles.End // this doesn't work
})
sp.On(events.Scroll, func(e events.Event) {
if sp.IsReadOnly() || !sp.StateIs(states.Focused) {
return
}
se := e.(*events.MouseScroll)
se.SetHandled()
sp.incrementValue(float32(se.Delta.Y))
})
sp.SetValidator(func() error {
text := sp.Text()
val, err := sp.stringToValue(text)
if err != nil {
return err
}
sp.SetValue(val)
return nil
})
sp.OnKeyChord(func(e events.Event) {
if sp.IsReadOnly() {
return
}
kf := keymap.Of(e.KeyChord())
if DebugSettings.KeyEventTrace {
slog.Info("Spinner KeyChordEvent", "widget", sp, "keyFunction", kf)
}
switch kf {
case keymap.MoveUp:
e.SetHandled()
sp.incrementValue(1)
case keymap.MoveDown:
e.SetHandled()
sp.incrementValue(-1)
case keymap.PageUp:
e.SetHandled()
sp.pageIncrementValue(1)
case keymap.PageDown:
e.SetHandled()
sp.pageIncrementValue(-1)
}
})
i := func(w *Button) {
w.Styler(func(s *styles.Style) {
// icons do not get separate focus, as people can
// use the arrow keys to get the same effect
s.SetAbilities(false, abilities.Focusable)
s.SetAbilities(true, abilities.RepeatClickable)
})
}
sp.Maker(func(p *tree.Plan) {
if sp.IsReadOnly() {
return
}
// (a spinner without buttons, as for an input of type number of
// htmlcore, has no icons)
if sp.LeadingIcon.IsSet() {
tree.AddInit(p, "lead-icon", i)
}
if sp.TrailingIcon.IsSet() {
tree.AddInit(p, "trail-icon", i)
}
})
}
func (sp *Spinner) setTextToValue() {
sp.SetText(sp.valueToString(sp.Value))
}
// SetMin sets the minimum bound on the value.
func (sp *Spinner) SetMin(min float32) *Spinner {
sp.HasMin = true
sp.Min = min
return sp
}
// SetMax sets the maximum bound on the value.
func (sp *Spinner) SetMax(max float32) *Spinner {
sp.HasMax = true
sp.Max = max
return sp
}
// SetValue sets the value, enforcing any limits, and updates the display.
func (sp *Spinner) SetValue(val float32) *Spinner {
sp.Value = val
if sp.HasMax && sp.Value > sp.Max {
sp.Value = sp.Max
} else if sp.HasMin && sp.Value < sp.Min {
sp.Value = sp.Min
}
sp.Value = math32.Truncate(sp.Value, sp.Precision)
if sp.EnforceStep {
// round to the nearest step
sp.Value = sp.Step * math32.Round(sp.Value/sp.Step)
}
sp.setTextToValue()
sp.NeedsRender()
return sp
}
// setValueEvent calls SetValue and also sends a change event.
func (sp *Spinner) setValueEvent(val float32) *Spinner {
sp.SetValue(val)
sp.SendChange()
return sp
}
// incrementValue increments the value by given number of steps (+ or -),
// and enforces it to be an even multiple of the step size (snap-to-value),
// and sends a change event.
func (sp *Spinner) incrementValue(steps float32) *Spinner {
if sp.IsReadOnly() {
return sp
}
val := sp.Value + steps*sp.Step
if sp.StepFunc != nil {
val = sp.StepFunc(sp, steps)
} else {
val = sp.wrapAround(val)
}
return sp.setValueEvent(val)
}
// pageIncrementValue increments the value by given number of page steps (+ or -),
// and enforces it to be an even multiple of the step size (snap-to-value),
// and sends a change event.
func (sp *Spinner) pageIncrementValue(steps float32) *Spinner {
return sp.incrementValue(steps * sp.PageStep)
}
// wrapAround, if the spinner has a min and a max, converts values less
// than min to max and values greater than max to min.
func (sp *Spinner) wrapAround(val float32) float32 {
if !sp.HasMin || !sp.HasMax {
return val
}
if val < sp.Min {
return sp.Max
}
if val > sp.Max {
return sp.Min
}
return val
}
// formatIsInt returns true if the format string requires an integer value
func (sp *Spinner) formatIsInt() bool {
if sp.Format == "" {
return false
}
fc := sp.Format[len(sp.Format)-1]
switch fc {
case 'd', 'b', 'c', 'o', 'O', 'q', 'x', 'X', 'U':
return true
}
return false
}
// valueToString converts the value to the string representation thereof
func (sp *Spinner) valueToString(val float32) string {
if sp.formatIsInt() {
return fmt.Sprintf(sp.Format, int64(val))
}
return fmt.Sprintf(sp.Format, val)
}
// stringToValue converts the string field back to float value
func (sp *Spinner) stringToValue(str string) (float32, error) {
if sp.Format == "" {
f64, err := strconv.ParseFloat(str, 32)
return float32(f64), err
}
var err error
if sp.formatIsInt() {
var ival int
_, err = fmt.Sscanf(str, sp.Format, &ival)
if err == nil {
return float32(ival), nil
}
} else {
var fval float32
_, err = fmt.Sscanf(str, sp.Format, &fval)
if err == nil {
return fval, nil
}
}
// if we have an error using the formatted version,
// we try using a pure parse
f64, ferr := strconv.ParseFloat(str, 32)
if ferr == nil {
return float32(f64), nil
}
// if everything fails, we return the error for the
// formatted version
return 0, err
}
func (sp *Spinner) WidgetTooltip(pos image.Point) (string, image.Point) {
res, rpos := sp.TextField.WidgetTooltip(pos)
if sp.error != nil {
return res, rpos
}
if sp.HasMin {
if res != "" {
res += " "
}
res += "(minimum: " + sp.valueToString(sp.Min)
if !sp.HasMax {
res += ")"
}
}
if sp.HasMax {
if sp.HasMin {
res += ", "
} else if res != "" {
res += " ("
} else {
res += "("
}
res += "maximum: " + sp.valueToString(sp.Max) + ")"
}
return res, rpos
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"log/slog"
"strconv"
"strings"
"cogentcore.org/core/base/slicesx"
"cogentcore.org/core/events"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/system"
"cogentcore.org/core/tree"
)
// SplitsTiles specifies 2D tiles for organizing elements within the [Splits] Widget.
// The [styles.Style.Direction] defines the main axis, and the cross axis is orthogonal
// to that, which is organized into chunks of 2 cross-axis "rows". In the case of a
// 1D pattern, only Span is relevant, indicating a single element per split.
type SplitsTiles int32 //enums:enum -trim-prefix Tile
const (
// Span has a single element spanning the cross dimension, i.e.,
// a vertical span for a horizontal main axis, or a horizontal
// span for a vertical main axis. It is the only valid value
// for 1D Splits, where it specifies a single element per split.
// If all tiles are Span, then a 1D line is generated.
TileSpan SplitsTiles = iota
// Split has a split between elements along the cross dimension,
// with the first of 2 elements in the first main axis line and
// the second in the second line.
TileSplit
// FirstLong has a long span of first element along the first
// main axis line and a split between the next two elements
// along the second line, with a split between the two lines.
// Visually, the splits form a T shape for a horizontal main axis.
TileFirstLong
// SecondLong has the first two elements split along the first line,
// and the third with a long span along the second main axis line,
// with a split between the two lines. Visually, the splits form
// an inverted T shape for a horizontal main axis.
TileSecondLong
// Plus is arranged like a plus sign + with the main split along
// the main axis line, and then individual cross-axis splits
// between the first two and next two elements.
TilePlus
)
var (
// tileNumElements is the number of elements per tile.
// the number of splitter handles is n-1.
tileNumElements = map[SplitsTiles]int{TileSpan: 1, TileSplit: 2, TileFirstLong: 3, TileSecondLong: 3, TilePlus: 4}
// tileNumSubSplits is the number of SubSplits proportions per tile.
// The Long cases require 2 pairs, first for the split along the cross axis
// and second for the split along the main axis; Plus requires 3 pairs.
tileNumSubSplits = map[SplitsTiles]int{TileSpan: 1, TileSplit: 2, TileFirstLong: 4, TileSecondLong: 4, TilePlus: 6}
)
// Splits allocates a certain proportion of its space to each of its children,
// organized along [styles.Style.Direction] as the main axis, and supporting
// [SplitsTiles] of 2D splits configurations along the cross axis.
// There is always a split between each Tile segment along the main axis,
// with the proportion of the total main axis space per Tile allocated
// according to normalized Splits factors.
// If all Tiles are Span then a 1D line is generated. Children are allocated
// in order along the main axis, according to each of the Tiles,
// which consume 1 to 4 elements, and have 0 to 3 splits internally.
// The internal split proportion are stored separately in SubSplits.
// A [Handle] widget is added to the Parts for each split, allowing the user
// to drag the relative size of each splits region.
// If more complex geometries are required, use nested Splits.
type Splits struct {
Frame
// Tiles specifies the 2D layout of elements along the [styles.Style.Direction]
// main axis and the orthogonal cross axis. If all Tiles are TileSpan, then
// a 1D line is generated. There is always a split between each Tile segment,
// and different tiles consume different numbers of elements in order, and
// have different numbers of SubSplits. Because each Tile can represent a
// different number of elements, care must be taken to ensure that the full
// set of tiles corresponds to the actual number of children. A default
// 1D configuration will be imposed if there is a mismatch.
Tiles []SplitsTiles
// TileSplits is the proportion (0-1 normalized, enforced) of space
// allocated to each Tile element along the main axis.
// 0 indicates that an element should be completely collapsed.
// By default, each element gets the same amount of space.
TileSplits []float32
// SubSplits contains splits proportions for each Tile element, with
// a variable number depending on the Tile. For the First and Second Long
// elements, there are 2 subsets of sub-splits, with 4 total subsplits.
SubSplits [][]float32
// savedSplits is a saved version of the Splits that can be restored
// for dynamic collapse/expand operations.
savedSplits []float32
// savedSubSplits is a saved version of the SubSplits that can be restored
// for dynamic collapse/expand operations.
savedSubSplits [][]float32
// handleDirs contains the target directions for each of the handles.
// this is set by parent split in its style function, and consumed
// by each handle in its own style function.
handleDirs []styles.Directions
}
func (sl *Splits) Init() {
sl.Frame.Init()
sl.Styler(func(s *styles.Style) {
s.Grow.Set(1, 1)
s.Margin.Zero()
s.Padding.Zero()
s.Min.Y.Em(10)
if sl.SizeClass() == SizeCompact {
s.Direction = styles.Column
} else {
s.Direction = styles.Row
}
})
sl.FinalStyler(func(s *styles.Style) {
sl.styleSplits()
})
sl.SetOnChildAdded(func(n tree.Node) {
if n != sl.Parts {
AsWidget(n).Styler(func(s *styles.Style) {
// splits elements must scroll independently and grow
s.Overflow.Set(styles.OverflowAuto)
s.Grow.Set(1, 1)
s.Direction = styles.Column
})
}
})
sl.OnKeyChord(func(e events.Event) {
kc := string(e.KeyChord())
mod := "Control+"
if TheApp.Platform() == system.MacOS {
mod = "Meta+"
}
if !strings.HasPrefix(kc, mod) {
return
}
kns := kc[len(mod):]
knc, err := strconv.Atoi(kns)
if err != nil {
return
}
kn := int(knc)
if kn == 0 {
e.SetHandled()
sl.evenSplits(sl.TileSplits)
sl.NeedsLayout()
} else if kn <= len(sl.TileSplits) { // the number keys are for tiles
e.SetHandled()
if sl.TileSplits[kn-1] <= 0.01 {
sl.restoreChild(kn - 1)
} else {
sl.collapseSplit(true, kn-1)
}
}
})
sl.Updater(func() {
sl.updateSplits()
})
parts := sl.newParts()
parts.Maker(func(p *tree.Plan) {
// The tiles are updated for the children, which are made after the
// updater of the splits runs, the first time.
sl.updateSplits()
// handles are organized first between tiles, then within tiles.
sl.styleSplits()
addHand := func(hidx int) {
tree.AddAt(p, "handle-"+strconv.Itoa(hidx), func(w *Handle) {
w.OnChange(func(e events.Event) {
sl.setHandlePos(w.IndexInParent(), w.Value())
sl.SendChange()
})
w.Styler(func(s *styles.Style) {
ix := w.IndexInParent()
if len(sl.handleDirs) > ix {
s.Direction = sl.handleDirs[ix]
}
})
})
}
nt := len(sl.Tiles)
for i := range nt - 1 {
addHand(i)
}
hi := nt - 1
for _, t := range sl.Tiles {
switch t {
case TileSpan:
case TileSplit:
addHand(hi)
hi++
case TileFirstLong, TileSecondLong:
addHand(hi) // long
addHand(hi + 1) // sub
hi += 2
case TilePlus:
addHand(hi) // long
addHand(hi + 1) // sub1
addHand(hi + 2) // sub2
hi += 3
}
}
})
}
// SetSplits sets the split proportions for the children.
// In general you should pass the same number of args
// as there are children, though fewer could be passed.
func (sl *Splits) SetSplits(splits ...float32) *Splits {
sl.updateSplits()
_, hasNonSpans := sl.tilesTotal()
if !hasNonSpans {
nc := len(splits)
sl.TileSplits = slicesx.SetLength(sl.TileSplits, nc)
copy(sl.TileSplits, splits)
sl.Tiles = slicesx.SetLength(sl.Tiles, nc)
for i := range nc {
sl.Tiles[i] = TileSpan
}
sl.updateSplits()
return sl
}
for i, sp := range splits {
sl.SetSplit(i, sp)
}
return sl
}
// SetSplit sets the split proportion of relevant display width
// specific to given child index. Also updates other split values
// in proportion.
func (sl *Splits) SetSplit(idx int, val float32) {
ci := 0
for i, t := range sl.Tiles {
tn := tileNumElements[t]
if idx < ci || idx >= ci+tn {
ci += tn
continue
}
ri := idx - ci
switch t {
case TileSpan:
sl.TileSplits[i] = val
sl.normOtherSplits(i, sl.TileSplits)
case TileSplit:
sl.SubSplits[i][ri] = val
sl.normOtherSplits(ri, sl.SubSplits[i])
case TileFirstLong:
if ri == 0 {
sl.SubSplits[i][0] = val
sl.normOtherSplits(0, sl.SubSplits[i][:2])
} else {
sl.SubSplits[i][1+ri] = val
sl.normOtherSplits(ri-1, sl.SubSplits[i][2:])
}
case TileSecondLong:
if ri == 2 {
sl.SubSplits[i][1] = val
sl.normOtherSplits(1, sl.SubSplits[i][:2])
} else {
sl.SubSplits[i][2+ri] = val
sl.normOtherSplits(ri, sl.SubSplits[i][2:])
}
case TilePlus:
si := 2 + ri
gi := (si / 2) * 2
oi := 1 - (si % 2)
sl.SubSplits[i][si] = val
sl.normOtherSplits(oi, sl.SubSplits[i][gi:gi+2])
}
ci += tn
}
}
// Splits returns the split proportion for each child element.
func (sl *Splits) Splits() []float32 {
nc := len(sl.Children)
sv := make([]float32, nc)
for i := range nc {
sv[i] = sl.Split(i)
}
return sv
}
// Split returns the split proportion for given child index
func (sl *Splits) Split(idx int) float32 {
ci := 0
for i, t := range sl.Tiles {
tn := tileNumElements[t]
if idx < ci || idx >= ci+tn {
ci += tn
continue
}
ri := idx - ci
switch t {
case TileSpan:
return sl.TileSplits[i]
case TileSplit:
return sl.SubSplits[i][ri]
case TileFirstLong:
if ri == 0 {
return sl.SubSplits[i][0]
}
return sl.SubSplits[i][1+ri]
case TileSecondLong:
if ri == 2 {
return sl.SubSplits[i][1]
}
return sl.SubSplits[i][2+ri]
case TilePlus:
si := 2 + ri
return sl.SubSplits[i][si]
}
ci += tn
}
return 0
}
// ChildIsCollapsed returns true if the split proportion
// for given child index is 0. Also checks the overall tile
// splits for the child.
func (sl *Splits) ChildIsCollapsed(idx int) bool {
if sl.Split(idx) < 0.01 {
return true
}
ci := 0
for i, t := range sl.Tiles {
tn := tileNumElements[t]
if idx < ci || idx >= ci+tn {
ci += tn
continue
}
ri := idx - ci
if sl.TileSplits[i] < 0.01 {
return true
}
// extra consideration for long split onto subs:
switch t {
case TileFirstLong:
if ri > 0 && sl.SubSplits[i][1] < 0.01 {
return true
}
case TileSecondLong:
if ri < 2 && sl.SubSplits[i][0] < 0.01 {
return true
}
case TilePlus:
if ri < 2 {
return sl.SubSplits[i][0] < 0.01
}
return sl.SubSplits[i][1] < 0.01
}
return false
}
return false
}
// tilesTotal returns the total number of child elements associated
// with the current set of Tiles elements, and whether there are any
// non-TileSpan elements, which has implications for error handling
// if the total does not match the actual number of children in the Splits.
func (sl *Splits) tilesTotal() (total int, hasNonSpans bool) {
for _, t := range sl.Tiles {
total += tileNumElements[t]
if t != TileSpan {
hasNonSpans = true
}
}
return
}
// updateSplits ensures the Tiles, TileSplits and SubSplits
// are all configured properly, given the number of children.
func (sl *Splits) updateSplits() *Splits {
nc := len(sl.Children)
ntc, hasNonSpans := sl.tilesTotal()
if nc == 0 && ntc == 0 {
return sl
}
if nc > 0 && ntc != nc {
if ntc != 0 && hasNonSpans {
slog.Error("core.Splits: number of children for current Tiles != number of actual children, reverting to 1D", "children", nc, "tiles", ntc)
}
sl.Tiles = slicesx.SetLength(sl.Tiles, nc)
for i := range nc {
sl.Tiles[i] = TileSpan
}
}
nt := len(sl.Tiles)
sl.TileSplits = slicesx.SetLength(sl.TileSplits, nt)
sl.normSplits(sl.TileSplits)
sl.SubSplits = slicesx.SetLength(sl.SubSplits, nt)
for i, t := range sl.Tiles {
ssn := tileNumSubSplits[t]
ss := sl.SubSplits[i]
ss = slicesx.SetLength(ss, ssn)
switch t {
case TileSpan:
ss[0] = 1
case TileSplit:
sl.normSplits(ss)
case TileFirstLong, TileSecondLong:
sl.normSplits(ss[:2]) // first is cross-axis
sl.normSplits(ss[2:])
case TilePlus:
for j := range 3 {
sl.normSplits(ss[2*j : 2*j+2])
}
}
sl.SubSplits[i] = ss
}
return sl
}
// normSplits normalizes the given splits proportions,
// using evenSplits if all zero
func (sl *Splits) normSplits(s []float32) {
sum := float32(0)
for _, sp := range s {
sum += sp
}
if sum == 0 { // set default even splits
sl.evenSplits(s)
return
}
norm := 1 / sum
for i := range s {
s[i] *= norm
}
}
// normOtherSplits normalizes the given splits proportions,
// while keeping the one at the given index at its current value.
func (sl *Splits) normOtherSplits(idx int, s []float32) {
n := len(s)
if n == 1 {
return
}
val := s[idx]
sum := float32(0)
even := (1 - val) / float32(n-1)
for i, sp := range s {
if i != idx {
if sp == 0 {
s[i], sp = even, even
}
sum += sp
}
}
norm := (1 - val) / sum
nsum := float32(0)
for i := range s {
if i != idx {
s[i] *= norm
}
nsum += s[i]
}
}
// evenSplits splits space evenly across all elements
func (sl *Splits) evenSplits(s []float32) {
n := len(s)
if n == 0 {
return
}
even := 1.0 / float32(n)
for i := range s {
s[i] = even
}
}
// saveSplits saves the current set of splits in SavedSplits, for a later RestoreSplits
func (sl *Splits) saveSplits() {
n := len(sl.TileSplits)
if n == 0 {
return
}
sl.savedSplits = slicesx.SetLength(sl.savedSplits, n)
copy(sl.savedSplits, sl.TileSplits)
sl.savedSubSplits = slicesx.SetLength(sl.savedSubSplits, n)
for i, ss := range sl.SubSplits {
sv := sl.savedSubSplits[i]
sv = slicesx.SetLength(sv, len(ss))
copy(sv, ss)
sl.savedSubSplits[i] = sv
}
}
// restoreSplits restores a previously saved set of splits (if it exists), does an update
func (sl *Splits) restoreSplits() {
if len(sl.savedSplits) != len(sl.TileSplits) {
return
}
sl.SetSplits(sl.savedSplits...)
for i, ss := range sl.SubSplits {
sv := sl.savedSubSplits[i]
if len(sv) == len(ss) {
copy(ss, sv)
}
}
sl.NeedsLayout()
}
// setSplitIndex sets given proportional "Splits" space to given value.
// Splits are indexed first by Tiles (major splits) and then
// within tiles, where TileSplit has 2 and the Long cases,
// have the long element first followed by the two smaller ones.
// Calls updateSplits after to ensure renormalization and
// NeedsLayout to ensure layout is updated.
func (sl *Splits) setSplitIndex(idx int, val float32) {
nt := len(sl.Tiles)
if nt == 0 {
return
}
if idx < nt {
sl.TileSplits[idx] = val
sl.updateSplits()
sl.NeedsLayout()
return
}
ci := nt
for i, t := range sl.Tiles {
tn := tileNumElements[t]
ri := idx - ci
if ri < 0 {
break
}
if ri >= tn {
ci += tn
continue
}
switch t {
case TileSpan:
case TileSplit:
if ri < 2 {
sl.SubSplits[i][ri] = val
}
case TileFirstLong, TileSecondLong:
if ri == 0 {
sl.SubSplits[i][ri] = val
} else {
sl.SubSplits[i][2+ri-1] = val
}
case TilePlus:
sl.SubSplits[i][2+ri] = val
}
ci += tn
}
sl.updateSplits()
sl.NeedsLayout()
}
// collapseSplit collapses the splitter region(s) at given index(es),
// by setting splits value to 0.
// optionally saving the prior splits for later Restore function.
func (sl *Splits) collapseSplit(save bool, idxs ...int) {
if save {
sl.saveSplits()
}
for _, idx := range idxs {
sl.setSplitIndex(idx, 0)
}
}
// setHandlePos sets given splits handle position to given 0-1 normalized value.
// Handles are indexed 0..Tiles-1 for main tiles handles, then sequentially
// for any additional child sub-splits depending on tile config.
// Calls updateSplits after to ensure renormalization and
// NeedsLayout to ensure layout is updated.
func (sl *Splits) setHandlePos(idx int, val float32) {
val = math32.Clamp(val, 0, 1)
update := func(idx int, nw float32, s []float32) {
n := len(s)
old := s[idx]
sumTo := float32(0)
for i := range idx + 1 {
sumTo += s[i]
}
delta := nw - sumTo
uval := old + delta
if uval < 0 {
uval = 0
delta = -old
nw = sumTo + delta
}
rmdr := 1 - nw
oldrmdr := 1 - sumTo
if oldrmdr <= 0 {
if rmdr > 0 {
dper := rmdr / float32((n-1)-idx)
for i := idx + 1; i < n; i++ {
s[i] = dper
}
}
} else {
for i := idx + 1; i < n; i++ {
cur := s[i]
s[i] = rmdr * (cur / oldrmdr) // proportional
}
}
s[idx] = uval
}
nt := len(sl.Tiles)
if idx < nt-1 {
update(idx, val, sl.TileSplits)
sl.updateSplits()
sl.NeedsLayout()
return
}
ci := nt - 1
for i, t := range sl.Tiles {
tn := tileNumElements[t] - 1
if tn == 0 {
continue
}
if idx < ci || idx >= ci+tn {
ci += tn
continue
}
ri := idx - ci
switch t {
case TileSplit:
update(0, val, sl.SubSplits[i])
case TileFirstLong, TileSecondLong:
if ri == 0 {
update(0, val, sl.SubSplits[i][:2])
} else {
update(0, val, sl.SubSplits[i][2:])
}
case TilePlus:
if ri == 0 {
update(0, val, sl.SubSplits[i][:2])
} else {
gi := ri * 2
update(0, val, sl.SubSplits[i][gi:gi+2])
}
}
ci += tn
}
sl.updateSplits()
sl.NeedsLayout()
}
// restoreChild restores the tiles of the given indexes to an even share.
func (sl *Splits) restoreChild(idxs ...int) {
n := len(sl.TileSplits)
for _, idx := range idxs {
if idx >= 0 && idx < n {
sl.TileSplits[idx] = 1.0 / float32(n)
}
}
sl.updateSplits()
sl.NeedsLayout()
}
func (sl *Splits) styleSplits() {
nt := len(sl.Tiles)
if nt == 0 {
return
}
nh := nt - 1
for _, t := range sl.Tiles {
nh += tileNumElements[t] - 1
}
sl.handleDirs = slicesx.SetLength(sl.handleDirs, nh)
dir := sl.Styles.Direction
odir := dir.Other()
hi := nt - 1 // extra handles
for i, t := range sl.Tiles {
if i > 0 {
sl.handleDirs[i-1] = dir
}
switch t {
case TileSpan:
case TileSplit:
sl.handleDirs[hi] = odir
hi++
case TileFirstLong, TileSecondLong:
sl.handleDirs[hi] = odir
sl.handleDirs[hi+1] = dir
hi += 2
case TilePlus:
sl.handleDirs[hi] = odir
sl.handleDirs[hi+1] = dir
sl.handleDirs[hi+2] = dir
hi += 3
}
}
}
func (sl *Splits) SizeDownSetAllocs(iter int) {
if sl.NumChildren() <= 1 {
return
}
sl.updateSplits()
sz := &sl.Geom.Size
// note: InnerSpace is computed based on n children -- not accurate!
csz := sz.Alloc.Content
dim := sl.Styles.Direction.Dim()
odim := dim.Other()
cszd := csz.Dim(dim)
cszo := csz.Dim(odim)
gap := sl.Styles.Gap.Dots().Floor()
gapd := gap.Dim(dim)
gapo := gap.Dim(odim)
hand := sl.Parts.Child(0).(*Handle)
hwd := hand.Geom.Size.Actual.Total.Dim(dim)
cszd -= float32(len(sl.TileSplits)-1) * (hwd + gapd)
setCsz := func(idx int, szm, szc float32) {
cwb := AsWidget(sl.Child(idx))
ksz := &cwb.Geom.Size
ksz.Alloc.Total.SetDim(dim, szm)
ksz.Alloc.Total.SetDim(odim, szc)
ksz.SetContentFromTotal(&ksz.Alloc)
}
ci := 0
for i, t := range sl.Tiles {
szt := math32.Round(sl.TileSplits[i] * cszd) // tile size, main axis
szcs := cszo - hwd - gapo // cross axis spilt
szs := szt - hwd - gapd
tn := tileNumElements[t]
switch t {
case TileSpan:
setCsz(ci, szt, cszo)
case TileSplit:
setCsz(ci, szt, math32.Round(szcs*sl.SubSplits[i][0]))
setCsz(ci+1, szt, math32.Round(szcs*sl.SubSplits[i][1]))
case TileFirstLong:
fcht := math32.Round(szcs * sl.SubSplits[i][0])
scht := math32.Round(szcs * sl.SubSplits[i][1])
setCsz(ci, szt, fcht)
setCsz(ci+1, math32.Round(szs*sl.SubSplits[i][2]), scht)
setCsz(ci+2, math32.Round(szs*sl.SubSplits[i][3]), scht)
case TileSecondLong:
fcht := math32.Round(szcs * sl.SubSplits[i][1])
scht := math32.Round(szcs * sl.SubSplits[i][0])
setCsz(ci, math32.Round(szs*sl.SubSplits[i][2]), scht)
setCsz(ci+1, math32.Round(szs*sl.SubSplits[i][3]), scht)
setCsz(ci+2, szt, fcht)
case TilePlus:
fcht := math32.Round(szcs * sl.SubSplits[i][0])
scht := math32.Round(szcs * sl.SubSplits[i][1])
setCsz(ci, math32.Round(szs*sl.SubSplits[i][2]), fcht)
setCsz(ci+1, math32.Round(szs*sl.SubSplits[i][3]), fcht)
setCsz(ci+2, math32.Round(szs*sl.SubSplits[i][4]), scht)
setCsz(ci+3, math32.Round(szs*sl.SubSplits[i][5]), scht)
}
ci += tn
}
}
func (sl *Splits) positionSplits() {
if sl.NumChildren() <= 1 {
return
}
if sl.Parts != nil {
sl.Parts.Geom.Size = sl.Geom.Size // inherit: allows bbox to include handle
}
sz := &sl.Geom.Size
dim := sl.Styles.Direction.Dim()
odim := dim.Other()
csz := sz.Alloc.Content
cszd := csz.Dim(dim)
cszo := csz.Dim(odim)
gap := sl.Styles.Gap.Dots().Floor()
gapd := gap.Dim(dim)
gapo := gap.Dim(odim)
hand := sl.Parts.Child(0).(*Handle)
hwd := hand.Geom.Size.Actual.Total.Dim(dim)
hht := hand.Geom.Size.Actual.Total.Dim(odim)
cszd -= float32(len(sl.TileSplits)-1) * (hwd + gapd)
hwdg := hwd + 0.5*gapd
setChildPos := func(idx int, dpos, opos float32) {
cwb := AsWidget(sl.Child(idx))
cwb.Geom.RelPos.SetDim(dim, dpos)
cwb.Geom.RelPos.SetDim(odim, opos)
}
setHandlePos := func(idx int, dpos, opos, lpos, mn, mx float32) {
hl := sl.Parts.Child(idx).(*Handle)
hl.Geom.RelPos.SetDim(dim, dpos)
hl.Geom.RelPos.SetDim(odim, opos)
hl.Pos = lpos
hl.Min = mn
hl.Max = mx
}
tpos := float32(0) // tile position
ci := 0
nt := len(sl.Tiles)
hi := nt - 1 // extra handles
for i, t := range sl.Tiles {
szt := math32.Round(sl.TileSplits[i] * cszd) // tile size, main axis
szcs := cszo - hwd - gapo // cross axis spilt
szs := szt - hwd - gapd
tn := tileNumElements[t]
if i > 0 {
setHandlePos(i-1, tpos-hwdg, .5*(cszo-hht), tpos, 0, cszd)
}
switch t {
case TileSpan:
setChildPos(ci, tpos, 0)
case TileSplit:
fcht := math32.Round(szcs * sl.SubSplits[i][0])
setHandlePos(hi, tpos+.5*(szt-hht), fcht+0.5*gapo, fcht, 0, szcs)
hi++
setChildPos(ci, tpos, 0)
setChildPos(ci+1, tpos, fcht+hwd+gapo)
case TileFirstLong, TileSecondLong:
fcht := math32.Round(szcs * sl.SubSplits[i][0])
scht := math32.Round(szcs * sl.SubSplits[i][1])
swd := math32.Round(szs * sl.SubSplits[i][2])
bot := fcht + hwd + gapo
setHandlePos(hi, tpos+.5*(szt-hht), fcht+0.5*gapo, fcht, 0, szcs) // long
if t == TileFirstLong {
setHandlePos(hi+1, tpos+swd+0.5*gapd, bot+0.5*(scht-hht), tpos+swd, tpos, tpos+szs)
setChildPos(ci, tpos, 0)
setChildPos(ci+1, tpos, bot)
setChildPos(ci+2, tpos+swd+hwd+gapd, bot)
} else {
setHandlePos(hi+1, tpos+swd+0.5*gapd, 0.5*(fcht-hht), tpos+swd, tpos, tpos+szs)
setChildPos(ci, tpos, 0)
setChildPos(ci+1, tpos+swd+hwd+gapd, 0)
setChildPos(ci+2, tpos, bot)
}
hi += 2
case TilePlus:
fcht := math32.Round(szcs * sl.SubSplits[i][0])
scht := math32.Round(szcs * sl.SubSplits[i][1])
bot := fcht + hwd + gapo
setHandlePos(hi, tpos+.5*(szt-hht), fcht+0.5*gapo, fcht, 0, szcs) // long
swd1 := math32.Round(szs * sl.SubSplits[i][2])
swd2 := math32.Round(szs * sl.SubSplits[i][4])
setHandlePos(hi+1, tpos+swd1+0.5*gapd, 0.5*(fcht-hht), tpos+swd1, tpos, tpos+szs)
setHandlePos(hi+2, tpos+swd2+0.5*gapd, bot+0.5*(scht-hht), tpos+swd2, tpos, tpos+szs)
setChildPos(ci, tpos, 0)
setChildPos(ci+1, tpos+swd1+hwd+gapd, 0)
setChildPos(ci+2, tpos, bot)
setChildPos(ci+3, tpos+swd2+hwd+gapd, bot)
hi += 3
}
ci += tn
tpos += szt + hwd + gapd
}
}
func (sl *Splits) Position() {
if !sl.HasChildren() {
sl.Frame.Position()
return
}
sl.updateSplits()
sl.ConfigScrolls()
sl.positionSplits()
sl.positionChildren()
}
func (sl *Splits) RenderWidget() {
if sl.StartRender() {
sl.ForWidgetChildren(func(i int, kwi Widget, cwb *WidgetBase) bool {
cwb.SetState(sl.ChildIsCollapsed(i), states.Invisible)
kwi.RenderWidget()
return tree.Continue
})
sl.renderParts()
sl.EndRender()
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"image"
"sync"
"cogentcore.org/core/base/keylist"
"cogentcore.org/core/base/tiered"
"cogentcore.org/core/events"
"cogentcore.org/core/paint"
"golang.org/x/image/draw"
)
// A Sprite is a top-level rendering element that paints onto a transparent
// layer that is cleared every render pass. Sprites are used for text cursors/carets
// and for dynamic editing / interactive GUI elements (e.g., drag-n-drop elements).
// To support cursor sprites and other animations, the sprites are redrawn at a
// minimum update rate that is at least as fast as CursorBlinkTime.
// Sprites can also receive mouse events, within their event bounding box.
// It is basically like a [Canvas] element over the entire screen, with no constraints
// on where you can draw.
type Sprite struct {
// Active is whether this sprite is Active now or not.
// Active sprites Draw and can receive events.
Active bool
// Name is the unique name of the sprite.
Name string
// properties for sprite, which allow for user-extensible data
Properties map[string]any
// Draw is the function that is called for Active sprites on every render pass
// to draw the sprite onto the top-level transparent layer.
Draw func(pc *paint.Painter)
// EventBBox is the bounding box for this sprite to receive mouse events.
// Typically this is the region in which it renders.
EventBBox image.Rectangle
// listeners are event listener functions for processing events on this widget.
// They are called in sequential descending order (so the last added listener
// is called first). They should be added using the On function. FirstListeners
// and FinalListeners are called before and after these listeners, respectively.
listeners events.Listeners `copier:"-" json:"-" xml:"-" set:"-"`
}
// NewSprite returns a new [Sprite] with the given name, which must remain
// invariant and unique among all sprites in use, and is used for all access;
// prefix with package and type name to ensure uniqueness. Starts out in
// inactive state; must call ActivateSprite.
func NewSprite(name string, draw func(pc *paint.Painter)) *Sprite {
sp := &Sprite{Name: name, Draw: draw}
return sp
}
// InitProperties ensures that the Properties map exists.
func (sp *Sprite) InitProperties() {
if sp.Properties != nil {
return
}
sp.Properties = make(map[string]any)
}
// SetPos sets the position of the sprite EventBBox, keeping the same size.
func (sp *Sprite) SetPos(pos image.Point) {
sp.EventBBox = sp.EventBBox.Add(pos.Sub(sp.EventBBox.Min))
}
// On adds the given event handler to the sprite's Listeners for the given event type.
// Listeners are called in sequential descending order, so this listener will be called
// before all of the ones added before it.
func (sp *Sprite) On(etype events.Types, fun func(e events.Event)) *Sprite {
sp.listeners.Add(etype, fun)
return sp
}
// OnClick adds an event listener function for [events.Click] events
func (sp *Sprite) OnClick(fun func(e events.Event)) *Sprite {
return sp.On(events.Click, fun)
}
// OnSlideStart adds an event listener function for [events.SlideStart] events
func (sp *Sprite) OnSlideStart(fun func(e events.Event)) *Sprite {
return sp.On(events.SlideStart, fun)
}
// OnSlideMove adds an event listener function for [events.SlideMove] events
func (sp *Sprite) OnSlideMove(fun func(e events.Event)) *Sprite {
return sp.On(events.SlideMove, fun)
}
// OnSlideStop adds an event listener function for [events.SlideStop] events
func (sp *Sprite) OnSlideStop(fun func(e events.Event)) *Sprite {
return sp.On(events.SlideStop, fun)
}
// HandleEvent sends the given event to all listeners for that event type.
func (sp *Sprite) handleEvent(e events.Event) {
sp.listeners.Call(e)
}
// send sends an new event of the given type to this sprite,
// optionally starting from values in the given original event
// (recommended to include where possible).
// Do not send an existing event using this method if you
// want the Handled state to persist throughout the call chain;
// call [Sprite.handleEvent] directly for any existing events.
func (sp *Sprite) send(typ events.Types, original ...events.Event) {
var e events.Event
if len(original) > 0 && original[0] != nil {
e = original[0].NewFromClone(typ)
} else {
e = &events.Base{Typ: typ}
e.Init()
}
sp.handleEvent(e)
}
// NewImageSprite returns a new Sprite that draws the given image
// in the given location, which is stored in the Min of the EventBBox.
// Move the EventBBox to move the render location.
// The image is stored as "image" in Properties.
func NewImageSprite(name string, pos image.Point, img image.Image) *Sprite {
sp := &Sprite{Name: name}
sp.InitProperties()
sp.Properties["image"] = img
sp.EventBBox = img.Bounds().Add(pos)
sp.Draw = func(pc *paint.Painter) {
pc.DrawImage(img, nil, sp.EventBBox, image.Point{}, draw.Over)
}
return sp
}
//////// Sprites
type SpriteList = keylist.List[string, *Sprite]
// Sprites manages a collection of Sprites, with unique name ids within each
// of three priority lists: Normal, First and Final. The convenience API adds to
// the Normal list, while First and Final are available for more advanced cases
// where rendering order needs to be controlled. First items are rendered first
// (so they can be overwritten) and processed last for event handling,
// and vice-versa for Final.
type Sprites struct {
tiered.Tiered[SpriteList]
// set to true if sprites have been modified since last config
modified bool
// stage is the main stage that has these sprites, whose window is
// woken when they are modified (see idle.go).
stage *Stage
sync.Mutex
}
// SetModified sets the sprite modified flag, which will
// drive a render to reflect the updated sprite.
// This version locks the sprites: see also [Sprites.SetModifiedNoLock].
func (ss *Sprites) SetModified() {
ss.Lock()
ss.setModifiedNoLock()
ss.Unlock()
}
// SetModifiedNoLock sets the sprite modified flag, which will
// drive a render to reflect the updated sprite.
// This version assumes Sprites are already locked, which is better for
// doing multiple coordinated updates at the same time.
func (ss *Sprites) SetModifiedNoLock() {
ss.setModifiedNoLock()
}
// IsModified returns whether the sprites have been modified, under lock.
func (ss *Sprites) IsModified() bool {
ss.Lock()
defer ss.Unlock()
return ss.modified
}
// hasActive returns whether any sprite is active, under lock.
func (ss *Sprites) hasActive() bool {
ss.Lock()
defer ss.Unlock()
active := false
ss.Do(func(sl *SpriteList) {
for _, sp := range sl.Values {
if sp.Active {
active = true
return
}
}
})
return active
}
// Add adds sprite to the Normal list of sprites, updating if already there.
// This version locks the sprites: see also [Sprites.AddNoLock].
func (ss *Sprites) Add(sp *Sprite) {
ss.Lock()
ss.AddNoLock(sp)
ss.Unlock()
}
// AddNoLock adds sprite to the Normal list of sprites, updating if already there.
// This version assumes Sprites are already locked, which is better for
// doing multiple coordinated updates at the same time.
func (ss *Sprites) AddNoLock(sp *Sprite) {
ss.Normal.Set(sp.Name, sp)
ss.setModifiedNoLock()
}
// Delete deletes given sprite by name, returning true if found and deleted.
// This version locks the sprites: see also [Sprites.DeleteNoLock].
func (ss *Sprites) Delete(name string) bool {
ss.Lock()
defer ss.Unlock()
return ss.DeleteNoLock(name)
}
// DeleteNoLock deletes given sprite by name, returning true if found and deleted.
// This version assumes Sprites are already locked, which is better for
// doing multiple coordinated updates at the same time.
func (ss *Sprites) DeleteNoLock(name string) bool {
got := false
ss.Do(func(sl *SpriteList) {
d := sl.DeleteByKey(name)
if d {
got = true
}
})
if got {
ss.setModifiedNoLock()
}
return got
}
// SpriteByName returns the sprite by name.
// This version locks the sprites: see also [Sprites.SpriteByNameNoLock].
func (ss *Sprites) SpriteByName(name string) (*Sprite, bool) {
ss.Lock()
defer ss.Unlock()
return ss.SpriteByNameNoLock(name)
}
// SpriteByNameNoLock returns the sprite by name.
// This version assumes Sprites are already locked, which is better for
// doing multiple coordinated updates at the same time.
func (ss *Sprites) SpriteByNameNoLock(name string) (sp *Sprite, ok bool) {
ss.Do(func(sl *SpriteList) {
if ok {
return
}
sp, ok = sl.AtTry(name)
if ok {
return
}
})
return
}
// reset removes all sprites.
func (ss *Sprites) reset() {
ss.Lock()
ss.Do(func(sl *SpriteList) {
sl.Reset()
})
ss.setModifiedNoLock()
ss.Unlock()
}
// ActivateSprite flags sprite(s) as active, setting Modified if wasn't before.
// This version locks the sprites: see also [Sprites.ActivateSpriteNoLock].
func (ss *Sprites) ActivateSprite(name ...string) {
ss.Lock()
ss.ActivateSpriteNoLock(name...)
ss.Unlock()
}
// ActivateSpriteNoLock flags the sprite(s) as active,
// setting Modified if wasn't before.
// This version assumes Sprites are already locked, which is better for
// doing multiple coordinated updates at the same time.
func (ss *Sprites) ActivateSpriteNoLock(name ...string) {
for _, nm := range name {
sp, ok := ss.SpriteByNameNoLock(nm)
if ok && !sp.Active {
sp.Active = true
ss.setModifiedNoLock()
}
}
}
// InactivateSprite flags the Normal sprite(s) as inactive,
// setting Modified if wasn't before.
// This version locks the sprites: see also [Sprites.InactivateSpriteNoLock].
func (ss *Sprites) InactivateSprite(name ...string) {
ss.Lock()
ss.InactivateSpriteNoLock(name...)
ss.Unlock()
}
// InactivateSpriteNoLock flags the Normal sprite(s) as inactive,
// setting Modified if wasn't before.
// This version assumes Sprites are already locked, which is better for
// doing multiple coordinated updates at the same time.
func (ss *Sprites) InactivateSpriteNoLock(name ...string) {
for _, nm := range name {
sp, ok := ss.SpriteByNameNoLock(nm)
if ok && sp.Active {
sp.Active = false
ss.setModifiedNoLock()
}
}
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"cogentcore.org/core/math32"
"fmt"
"image"
"strings"
"sync/atomic"
"time"
"cogentcore.org/core/base/option"
"cogentcore.org/core/paint"
"cogentcore.org/core/paint/render"
"cogentcore.org/core/system"
)
// StageTypes are the types of [Stage] containers.
// There are two main categories: MainStage and PopupStage.
// MainStages are [WindowStage] and [DialogStage], which are
// large and potentially complex [Scene]s that persist until
// dismissed. PopupStages are [MenuStage], [TooltipStage],
// [SnackbarStage], and [CompleterStage], which are transitory
// and simple, without additional decorations. MainStages live
// in a [stages] associated with a [renderWindow] and manage
// their own set of PopupStages via another [stages].
type StageTypes int32 //enums:enum
const (
// WindowStage is a MainStage that displays a [Scene] in a full window.
// One of these must be created first, as the primary app content,
// and it typically persists throughout. It fills the [renderWindow].
// Additional windows can be created either within the same [renderWindow]
// on all platforms or in separate [renderWindow]s on desktop platforms.
WindowStage StageTypes = iota
// DialogStage is a MainStage that displays a [Scene] in a smaller dialog
// window on top of a [WindowStage], or in a full or separate window.
// It can be [Stage.Modal] or not.
DialogStage
// MenuStage is a PopupStage that displays a [Scene] typically containing
// [Button]s overlaid on a MainStage. It is typically [Stage.Modal] and
// [Stage.ClickOff], and closes when an button is clicked.
MenuStage
// TooltipStage is a PopupStage that displays a [Scene] with extra text
// info for a widget overlaid on a MainStage. It is typically [Stage.ClickOff]
// and not [Stage.Modal].
TooltipStage
// SnackbarStage is a PopupStage that displays a [Scene] with text info
// and an optional additional button. It is displayed at the bottom of the
// screen. It is typically not [Stage.ClickOff] or [Stage.Modal], but has a
// [Stage.Timeout].
SnackbarStage
// CompleterStage is a PopupStage that displays a [Scene] with text completion
// options, spelling corrections, or other such dynamic info. It is typically
// [Stage.ClickOff], not [Stage.Modal], dynamically updating, and closes when
// something is selected or typing renders it no longer relevant.
CompleterStage
)
// isMain returns true if this type of Stage is a Main stage that manages
// its own set of popups
func (st StageTypes) isMain() bool {
return st <= DialogStage
}
// isPopup returns true if this type of Stage is a Popup, managed by another
// Main stage.
func (st StageTypes) isPopup() bool {
return !st.isMain()
}
// Stage is a container and manager for displaying a [Scene]
// in different functional ways, defined by [StageTypes].
type Stage struct { //types:add -setters
// Type is the type of [Stage], which determines behavior and styling.
Type StageTypes `set:"-"`
// Scene contents of this [Stage] (what it displays).
Scene *Scene `set:"-"`
// Context is a widget in another scene that requested this stage to be created
// and provides context.
Context Widget
// Name is the name of the Stage, which is generally auto-set
// based on the [Scene.Name].
Name string
// Title is the title of the Stage, which is generally auto-set
// based on the [Body.Title]. It used for the title of [WindowStage]
// and [DialogStage] types, and for a [Text] title widget if
// [Stage.DisplayTitle] is true.
Title string
// Screen specifies the screen number on which a new window is opened
// by default on desktop platforms. It defaults to -1, which indicates
// that the first window should open on screen 0 (the default primary
// screen) and any subsequent windows should open on the same screen as
// the currently active window. Regardless, the automatically saved last
// screen of a window with the same [Stage.Title] takes precedence if it exists;
// see the website documentation on window geometry saving for more information.
// Use [TheApp].ScreenByName("name").ScreenNumber to get the screen by name.
Screen int
// Modal, if true, blocks input to all other stages.
Modal bool `set:"-"`
// Scrim, if true, places a darkening scrim over other stages.
Scrim bool
// ClickOff, if true, dismisses the [Stage] if the user clicks anywhere
// off of the [Stage].
ClickOff bool
// ignoreEvents is whether to send no events to the stage and
// just pass them down to lower stages.
ignoreEvents bool
// pressOpened is whether a menu stage was opened by pressing the mouse
// button on its [Stage.Context] button, which is still down: dragging
// over the menu hovers its items, and releasing the button over one
// clicks it (see [stages.pressOpenedEvent]).
pressOpened bool
// NewWindow, if true, opens a [WindowStage] or [DialogStage] in its own
// separate operating system window ([renderWindow]). This is true by
// default for [WindowStage] on non-mobile platforms, otherwise false.
NewWindow bool
// FullWindow, if [Stage.NewWindow] is false, makes [DialogStage]s and
// [WindowStage]s take up the entire window they are created in.
FullWindow bool
// Maximized is whether to make a window take up the entire screen on desktop
// platforms by default. It is different from [Stage.Fullscreen] in that
// fullscreen makes the window truly fullscreen without decorations
// (such as for a video player), whereas maximized keeps decorations and just
// makes it fill the available space. The automatically saved user previous
// maximized state takes precedence.
Maximized bool
// Fullscreen is whether to make a window fullscreen on desktop platforms.
// It is different from [Stage.Maximized] in that fullscreen makes
// the window truly fullscreen without decorations (such as for a video player),
// whereas maximized keeps decorations and just makes it fill the available space.
// Not to be confused with [Stage.FullWindow], which is for stages contained within
// another system window. See [Scene.IsFullscreen] and [Scene.SetFullscreen] to
// check and update fullscreen state dynamically on desktop and web platforms
// ([Stage.SetFullscreen] sets the initial state, whereas [Scene.SetFullscreen]
// sets the current state after the [Stage] is already running).
Fullscreen bool
// UseMinSize uses a minimum size as a function of the total available size
// for sizing new windows and dialogs. Otherwise, only the content size is used.
// The saved window position and size takes precedence on multi-window platforms.
UseMinSize bool
// MinSize is the minimum initial size of a dialog in dp, if it is
// non-zero, such as to make the window of a dialog wide enough for the
// layout of a larger [SizeClasses] than the compact one of a phone. It
// only sets the initial size: the window can then be resized, and the
// saved window size takes precedence on multi-window platforms.
MinSize math32.Vector2
// Resizable specifies whether a window on desktop platforms can
// be resized by the user, and whether a non-full same-window dialog can
// be resized by the user on any platform. It defaults to true.
Resizable bool
// HideOnClose is whether closing the window of a [WindowStage] with
// [Stage.NewWindow], as with its close button or [keymap.WinClose],
// keeps it as it is instead, hidden on macOS until the app's dock icon
// is clicked, and minimized on other desktop platforms, so that the app
// stays open, as for the main window of an app such as a mail client.
// The window is closed when the app quits.
HideOnClose bool
// Timeout, if greater than 0, results in a popup stages disappearing
// after this timeout duration.
Timeout time.Duration
// BackButton is whether to add a back button to the top bar that calls
// [Scene.Close] when clicked. If it is unset, is will be treated as true
// on non-[system.Offscreen] platforms for [Stage.FullWindow] but not
// [Stage.NewWindow] [Stage]s that are not the first in the stack.
BackButton option.Option[bool] `set:"-"`
// DisplayTitle is whether to display the [Stage.Title] using a
// [Text] widget in the top bar. It is on by default for [DialogStage]s
// and off for all other stages.
DisplayTitle bool
// Pos is the default target position for the [Stage] to be placed within
// the surrounding window or screen in raw pixels. For a new window on desktop
// platforms, the automatically saved user previous window position takes precedence.
// For dialogs, this position is the target center position, not the upper-left corner.
Pos image.Point
// If a popup stage, this is the main stage that owns it (via its [Stage.popups]).
// If a main stage, it points to itself.
Main *Stage `set:"-"`
// For main stages, this is the stack of the popups within it
// (created specifically for the main stage).
// For popups, this is the pointer to the popups within the
// main stage managing it.
popups *stages
// For all stages, this is the main [Stages] that lives in a [renderWindow]
// and manages the main stages.
Mains *stages `set:"-"`
// mains is the same as [Stage.Mains], set with it by [Stage.storeMains].
// It is atomic, as [Scene.renderContext] reads it from other goroutines
// to find the lock of the render context, before they have that lock.
mains atomic.Pointer[stages]
// rendering context which has info about the RenderWindow onto which we render.
// This should be used instead of the RenderWindow itself for all relevant
// rendering information. This is only available once a Stage is Run,
// and must always be checked for nil.
renderContext *renderContext
// Sprites are named images that are rendered last overlaying everything else.
Sprites Sprites `json:"-" xml:"-" set:"-"`
// spritePainter is the painter for sprite drawing.
spritePainter *paint.Painter
// spriteRenderer is the renderer for sprite drawing.
spriteRenderer render.Renderer
}
func (st *Stage) String() string {
str := fmt.Sprintf("%s Type: %s", st.Name, st.Type)
if st.Scene != nil {
str += " Scene: " + st.Scene.Name
}
rc := st.renderContext
if rc != nil {
str += " Rc: " + rc.String()
}
return str
}
// SetBackButton sets [Stage.BackButton] using [option.Option.Set].
func (st *Stage) SetBackButton(b bool) *Stage {
st.BackButton.Set(b)
return st
}
// setNameFromScene sets the name of this Stage based on existing
// Scene and Type settings.
func (st *Stage) setNameFromScene() *Stage {
if st.Scene == nil {
return nil
}
sc := st.Scene
st.Name = sc.Name + "-" + strings.ToLower(st.Type.String())
if sc.Body != nil {
st.Title = sc.Body.Title
}
return st
}
func (st *Stage) setScene(sc *Scene) *Stage {
st.Scene = sc
if sc != nil {
sc.Stage = st
st.setNameFromScene()
}
return st
}
// setMains sets the [Stage.Mains] to the given stack of main stages,
// and also sets the RenderContext from that.
func (st *Stage) setMains(sm *stages) *Stage {
st.storeMains(sm)
st.Sprites.stage = st
st.renderContext = sm.renderContext
return st
}
// setPopups sets the [Stage.Popups] and [Stage.Mains] from the given main
// stage to which this popup stage belongs.
func (st *Stage) setPopups(mainSt *Stage) *Stage {
st.Main = mainSt
st.storeMains(mainSt.Mains)
st.popups = mainSt.popups
st.renderContext = st.Mains.renderContext
return st
}
// setType sets the type and also sets default parameters based on that type
func (st *Stage) setType(typ StageTypes) *Stage {
st.Type = typ
st.UseMinSize = true
st.Resizable = true
st.Screen = -1
switch st.Type {
case WindowStage:
if !TheApp.Platform().IsMobile() {
st.NewWindow = true
}
st.FullWindow = true
st.Modal = true // note: there is no global modal option between RenderWindow windows
case DialogStage:
st.Modal = true
st.Scrim = true
st.ClickOff = true
st.DisplayTitle = true
case MenuStage:
st.Modal = true
st.Scrim = false
st.ClickOff = true
case TooltipStage:
st.Modal = false
st.ClickOff = true
st.Scrim = false
st.ignoreEvents = true
case SnackbarStage:
st.Modal = false
case CompleterStage:
st.Modal = false
st.Scrim = false
st.ClickOff = true
}
return st
}
// SetModal sets modal flag for blocking other input (for dialogs).
// Also updates [Stage.Scrim] accordingly if not modal.
func (st *Stage) SetModal(modal bool) *Stage {
st.Modal = modal
if !st.Modal {
st.Scrim = false
}
return st
}
// Run runs the stage using the default run behavior based on the type of stage.
func (st *Stage) Run() *Stage {
if system.OnSystemWindowCreated == nil {
return st.run()
}
// need to prevent premature quitting by ensuring
// that WinWait is not done until we run the Stage
windowWait.Go(func() {
<-system.OnSystemWindowCreated
system.OnSystemWindowCreated = nil // no longer applicable
st.run()
// now that we have run the Stage, WinWait is accurate and
// we no longer need to prevent it from being done
})
return st
}
// run is the implementation of [Stage.Run].
func (st *Stage) run() *Stage {
defer func() { system.HandleRecover(recover()) }()
switch st.Type {
case WindowStage:
return st.runWindow()
case DialogStage:
return st.runDialog()
default:
return st.runPopup()
}
}
// doUpdate calls doUpdate on our Scene and UpdateAll on our Popups for Main types.
// returns stageMods = true if any Popup Stages have been modified
// and sceneMods = true if any Scenes have been modified.
func (st *Stage) doUpdate() (stageMods, sceneMods bool) {
if st.Scene == nil {
return
}
if st.Type.isMain() && st.popups != nil {
stageMods, sceneMods = st.popups.updateAll()
}
scMods := st.Scene.doUpdate()
sceneMods = sceneMods || scMods
// if stageMods || sceneMods {
// fmt.Println("scene mod", st.Scene.Name, stageMods, scMods)
// }
return
}
// raise moves the Stage to the top of its main [stages]
// and raises the [renderWindow] it is in if necessary.
func (st *Stage) raise() {
rw := st.Mains.renderWindow
if rw != getCurrentRenderWindow() {
rw.Raise() // which makes it the current window
}
st.Mains.moveToTop(st)
rw.SetStageTitle(st.Title)
}
func (st *Stage) delete() {
if st.Type.isMain() && st.popups != nil {
st.popups.deleteAll()
st.Sprites.reset()
st.spriteRenderer = nil
st.spritePainter = nil
}
if st.Scene != nil {
st.Scene.DeleteChildren()
}
st.Scene = nil
st.Main = nil
st.popups = nil
st.storeMains(nil)
st.renderContext = nil
}
// storeMains sets [Stage.Mains], and the atomic version of it,
// to the given stack of main stages.
func (st *Stage) storeMains(sm *stages) {
st.Mains = sm
st.mains.Store(sm)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"fmt"
"sync"
"cogentcore.org/core/base/keylist"
"cogentcore.org/core/math32"
"cogentcore.org/core/system"
)
// stages manages a stack of [Stage]s.
type stages struct {
// stack is the stack of stages managed by this stage manager.
stack keylist.List[string, *Stage]
// modified is set to true whenever the stack has been modified.
// This is cleared by the RenderWindow each render cycle.
modified bool
// rendering context provides key rendering information and locking
// for the RenderWindow in which the stages are running.
renderContext *renderContext
// render window to which we are rendering.
// rely on the RenderContext wherever possible.
renderWindow *renderWindow
// main is the main stage that owns this [Stages].
// This is only set for popup stages.
main *Stage
// mutex protecting reading / updating of the Stack.
// Destructive stack updating gets a Write lock, else Read.
sync.Mutex
}
// top returns the top-most Stage in the Stack, under Read Lock
func (sm *stages) top() *Stage {
sm.Lock()
defer sm.Unlock()
sz := sm.stack.Len()
if sz == 0 {
return nil
}
return sm.stack.Values[sz-1]
}
// list returns a copy of the stages in the stack, from bottom to top,
// under the lock, for reading the stages of another window.
func (sm *stages) list() []*Stage {
sm.Lock()
defer sm.Unlock()
sts := make([]*Stage, 0, sm.stack.Len())
for _, st := range sm.stack.Values { // (not append(sts, Values...), which goscript mistypes)
sts = append(sts, st)
}
return sts
}
// uniqueName returns unique name for given item
func (sm *stages) uniqueName(nm string) string {
ctr := 0
for _, key := range sm.stack.Keys {
if key == nm {
ctr++
}
}
if ctr > 0 {
return fmt.Sprintf("%s-%d", nm, sm.stack.Len())
}
return nm
}
// push pushes a new Stage to top, under Write lock
func (sm *stages) push(st *Stage) {
sm.Lock()
defer sm.Unlock()
sm.setModified()
sm.stack.Set(sm.uniqueName(st.Name), st)
}
// deleteStage deletes given stage (removing from stack, calling Delete
// on Stage), returning true if found.
// It runs under Write lock.
func (sm *stages) deleteStage(st *Stage) bool {
sm.Lock()
defer sm.Unlock()
l := sm.stack.Len()
fullWindow := st.FullWindow
got := false
for i := l - 1; i >= 0; i-- {
s := sm.stack.Values[i]
if st == s {
sm.setModified()
sm.stack.DeleteByIndex(i, i+1)
st.delete()
got = true
break
}
}
if !got {
return false
}
// After closing a full window stage on web, the top stage behind
// needs to be rerendered, or else nothing will show up.
if fullWindow && TheApp.Platform() == system.Web {
sz := sm.renderWindow.mains.stack.Len()
if sz > 0 {
ts := sm.renderWindow.mains.stack.Values[sz-1]
if ts.Scene != nil {
ts.Scene.NeedsRender()
}
}
}
return true
}
// deleteStageAndBelow deletes given stage (removing from stack,
// calling Delete on Stage), returning true if found.
// And also deletes all stages of the same type immediately below it.
// It runs under Write lock.
func (sm *stages) deleteStageAndBelow(st *Stage) bool {
sm.Lock()
defer sm.Unlock()
styp := st.Type
l := sm.stack.Len()
got := false
for i := l - 1; i >= 0; i-- {
s := sm.stack.Values[i]
if !got {
if st == s {
sm.setModified()
sm.stack.DeleteByIndex(i, i+1)
st.delete()
got = true
}
} else {
if s.Type == styp {
sm.stack.DeleteByIndex(i, i+1)
s.delete()
}
}
}
return got
}
// moveToTop moves the given stage to the top of the stack,
// returning true if found. It runs under Write lock.
func (sm *stages) moveToTop(st *Stage) bool {
sm.Lock()
defer sm.Unlock()
l := sm.stack.Len()
for i := l - 1; i >= 0; i-- {
s := sm.stack.Values[i]
if st == s {
k := sm.stack.Keys[i]
sm.setModified()
sm.stack.DeleteByIndex(i, i+1)
sm.stack.Insert(sm.stack.Len(), k, s)
return true
}
}
return false
}
// popType pops the top-most Stage of the given type of the stack,
// returning it or nil if none. It runs under Write lock.
func (sm *stages) popType(typ StageTypes) *Stage {
sm.Lock()
defer sm.Unlock()
l := sm.stack.Len()
for i := l - 1; i >= 0; i-- {
st := sm.stack.Values[i]
if st.Type == typ {
sm.setModified()
sm.stack.DeleteByIndex(i, i+1)
return st
}
}
return nil
}
// popDeleteType pops the top-most Stage of the given type off the stack
// and calls Delete on it.
func (sm *stages) popDeleteType(typ StageTypes) {
st := sm.popType(typ)
if st != nil {
st.delete()
}
}
// deleteAll deletes all of the stages.
// For when Stage with Popups is Deleted, or when a RenderWindow is closed.
// requires outer RenderContext mutex!
func (sm *stages) deleteAll() {
sm.Lock()
defer sm.Unlock()
sz := sm.stack.Len()
if sz == 0 {
return
}
sm.setModified()
for i := sz - 1; i >= 0; i-- {
st := sm.stack.Values[i]
st.delete()
sm.stack.DeleteByIndex(i, i+1)
}
}
// resize calls resize on all stages within based on the given window render geom.
// if nothing actually needed to be resized, it returns false.
func (sm *stages) resize(rg math32.Geom2DInt) bool {
resized := false
for _, st := range sm.stack.Values {
if st.FullWindow {
did := st.Scene.Resize(rg)
if did {
st.Sprites.reset()
resized = true
}
} else {
did := st.Scene.fitInWindow(rg)
if did {
resized = true
}
}
}
return resized
}
// updateAll is the primary updating function to update all scenes
// and determine if any updates were actually made.
// This [stages] is the mains of the [renderWindow] or the popups
// of a list of popups within a main stage.
// It iterates through all Stages and calls doUpdate on them.
// returns stageMods = true if any Stages have been modified (Main or Popup),
// and sceneMods = true if any Scenes have been modified.
// Stage calls doUpdate on its [Scene], ensuring everything is updated at the
// Widget level. If nothing is needed, nothing is done.
// This is called only during [renderWindow.renderWindow],
// under the global RenderContext.Mu lock so nothing else can happen.
func (sm *stages) updateAll() (stageMods, sceneMods bool) {
sm.Lock()
defer sm.Unlock()
stageMods = sm.modified
sm.modified = false
sz := sm.stack.Len()
if sz == 0 {
return
}
for _, st := range sm.stack.Values {
stMod, scMod := st.doUpdate()
stageMods = stageMods || stMod
sceneMods = sceneMods || scMod
}
return
}
// windowStage returns the highest level WindowStage (i.e., full window)
func (sm *stages) windowStage() *Stage {
n := sm.stack.Len()
for i := n - 1; i >= 0; i-- {
st := sm.stack.Values[i]
if st.Type == WindowStage {
return st
}
}
return nil
}
func (sm *stages) runDeferred() {
for _, st := range sm.stack.Values {
if st.Scene == nil {
continue
}
sc := st.Scene
if sc.hasFlag(sceneContentSizing) {
continue
}
if sc.hasFlag(sceneHasDeferred) {
sc.setFlag(false, sceneHasDeferred)
sc.runDeferred()
}
if sc.showIter == sceneShowIters+1 {
sc.showIter++
if !sc.hasShown.Load() {
sc.hasShown.Store(true)
close(sc.shown)
sc.Shown()
}
}
// If we own popups, we also need to runDeferred on them.
if st.Main == st && st.popups.stack.Len() > 0 {
st.popups.runDeferred()
}
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"image"
"reflect"
"sync"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/tree"
)
// Styler adds the given function for setting the style properties of the widget
// to [WidgetBase.Stylers.Normal]. It is one of the main ways to specify the styles of
// a widget, in addition to FirstStyler and FinalStyler, which add stylers that
// are called before and after the stylers added by this function, respectively.
func (wb *WidgetBase) Styler(s func(s *styles.Style)) {
wb.Stylers.Normal = append(wb.Stylers.Normal, s)
}
// FirstStyler adds the given function for setting the style properties of the widget
// to [WidgetBase.Stylers.First]. It is one of the main ways to specify the styles of
// a widget, in addition to Styler and FinalStyler, which add stylers that
// are called after the stylers added by this function.
func (wb *WidgetBase) FirstStyler(s func(s *styles.Style)) {
wb.Stylers.First = append(wb.Stylers.First, s)
}
// FinalStyler adds the given function for setting the style properties of the widget
// to [WidgetBase.Stylers.Final]. It is one of the main ways to specify the styles of
// a widget, in addition to FirstStyler and Styler, which add stylers that are called
// before the stylers added by this function.
func (wb *WidgetBase) FinalStyler(s func(s *styles.Style)) {
wb.Stylers.Final = append(wb.Stylers.Final, s)
}
// Style updates the style properties of the widget based on [WidgetBase.Stylers].
// To specify the style properties of a widget, use [WidgetBase.Styler].
func (wb *WidgetBase) Style() {
if wb.This == nil {
return
}
pw := wb.parentWidget()
// we do these things even if we are overriding the style
defer func() {
// Invisible is only un-set here if it was set here, for Display
// none, as other things can set it too (as the stacks of a Frame).
if wb.Styles.Display == styles.DisplayNone {
wb.SetState(true, states.Invisible)
wb.displayNone = true
} else if wb.displayNone {
wb.SetState(false, states.Invisible)
wb.displayNone = false
if pw != nil { // its parent is laid out again, with it
pw.NeedsLayout()
}
}
psz := math32.Vector2{}
if pw != nil {
psz = wb.percentBase(pw)
}
setUnitContext(&wb.Styles, wb.Scene, wb.Geom.Size.Alloc.Content, psz)
}()
if wb.OverrideStyle {
return
}
wb.resetStyleWidget()
if pw != nil {
wb.Styles.InheritFields(&pw.Styles)
}
wb.resetStyleSettings()
wb.runStylers()
wb.styleSettings()
}
// resetStyleWidget resets the widget styles and applies the basic
// default styles specified in [styles.Style.Defaults].
func (wb *WidgetBase) resetStyleWidget() {
s := &wb.Styles
// need to persist state
state := s.State
*s = styles.Style{}
s.Defaults()
s.State = state
// default to state layer associated with the state,
// which the developer can override in their stylers
// wb.Transition(&s.StateLayer, s.State.StateLayer(), 200*time.Millisecond, LinearTransition)
s.StateLayer = s.State.StateLayer()
s.Font.Family = rich.SansSerif
}
// StyleLockProperty is the name of the property of a widget that, if it
// is a [sync.Locker], is held while the stylers of the widget run, as for
// the widgets of web pages, whose stylers read the styles of their
// elements, which are found again (in another goroutine) as the scripts of
// the page change it, without the lock of the widgets (see
// htmlcore.Context.PrepareReread).
const StyleLockProperty = "style-lock"
// runStylers runs the [WidgetBase.Stylers].
func (wb *WidgetBase) runStylers() {
if l, ok := wb.Property(StyleLockProperty).(sync.Locker); ok {
l.Lock()
defer l.Unlock()
}
wb.Stylers.Do(func(s *[]func(s *styles.Style)) {
for _, f := range *s {
f(&wb.Styles)
}
})
}
// resetStyleSettings reverses the effects of [WidgetBase.styleSettings]
// for the widget's font size so that it does not create cascading
// inhereted font size values. It only does this for non-root elements,
// as the root element must receive the larger font size so that
// all other widgets inherit it. It must be called before
// [WidgetBase.runStylers] and [WidgetBase.styleSettings].
func (wb *WidgetBase) resetStyleSettings() {
if tree.IsRoot(wb) {
return
}
fsz := AppearanceSettings.FontSize / 100
wb.Styles.Font.Size.Value /= fsz
}
// styleSettings applies [AppearanceSettingsData.Spacing] (unless
// [styles.Style.FixedSpacing]) and [AppearanceSettingsData.FontSize]
// to the style values for the widget.
func (wb *WidgetBase) styleSettings() {
s := &wb.Styles
if !s.FixedSpacing {
spc := AppearanceSettings.Spacing / 100
s.Margin.Top.Value *= spc
s.Margin.Right.Value *= spc
s.Margin.Bottom.Value *= spc
s.Margin.Left.Value *= spc
s.Padding.Top.Value *= spc
s.Padding.Right.Value *= spc
s.Padding.Bottom.Value *= spc
s.Padding.Left.Value *= spc
s.Gap.X.Value *= spc
s.Gap.Y.Value *= spc
}
fsz := AppearanceSettings.FontSize / 100
s.Font.Size.Value *= fsz
}
// StyleTree calls [WidgetBase.Style] on every widget in tree
// underneath and including this widget.
func (wb *WidgetBase) StyleTree() {
wb.WidgetWalkDown(func(cw Widget, cwb *WidgetBase) bool {
if cwb != wb && isHiddenStackChild(cwb) {
return tree.Break
}
cw.Style()
return tree.Continue
})
}
// Restyle ensures that the styling of the widget and all of its children
// is updated and rendered by calling [WidgetBase.StyleTree] and
// [WidgetBase.NeedsRender]. It does not trigger a new update or layout
// pass, so it should only be used for non-structural styling changes.
func (wb *WidgetBase) Restyle() {
wb.StyleTree()
wb.NeedsRender()
}
// setUnitContext sets the unit context based on size of scene, element, and parent
// element (from bbox) and then caches everything out in terms of raw pixel
// dots for rendering.
// Zero values for element and parent size are ignored.
func setUnitContext(st *styles.Style, sc *Scene, el, parent math32.Vector2) {
var rc *renderContext
sz := image.Point{1920, 1080}
if sc != nil {
rc = sc.renderContext()
sz = sc.SceneGeom.Size
}
if rc != nil {
st.UnitContext.DPI = rc.logicalDPI
} else {
st.UnitContext.DPI = 160
}
if st.Zoom > 0 {
st.UnitContext.DPI *= st.Zoom
}
st.UnitContext.SetSizes(float32(sz.X), float32(sz.Y), el.X, el.Y, parent.X, parent.Y)
st.Font.ToDots(&st.UnitContext) // key to set first
st.Font.SetUnitContext(&st.UnitContext)
st.ToDots()
}
// ChildBackground returns the background color (Image) for the given child Widget.
// By default, this is just our [styles.Style.ActualBackground] but it can be computed
// specifically for the child (e.g., for zebra stripes in [ListGrid])
func (wb *WidgetBase) ChildBackground(child Widget) image.Image {
return wb.Styles.ActualBackground
}
// parentActualBackground returns the actual background of
// the parent of the widget. If it has no parent, it returns nil.
func (wb *WidgetBase) parentActualBackground() image.Image {
pwb := wb.parentWidget()
if pwb == nil {
return nil
}
return pwb.This.(Widget).ChildBackground(wb.This.(Widget))
}
// setFromTag uses the given tags to call the given set function for the given tag.
func setFromTag(tags reflect.StructTag, tag string, set func(v float32)) {
if v, ok := tags.Lookup(tag); ok {
f, err := reflectx.ToFloat32(v)
if errors.Log(err) == nil {
set(f)
}
}
}
// styleFromTags adds a [WidgetBase.Styler] to the given widget
// to set its style properties based on the given [reflect.StructTag].
// Width, height, and grow properties are supported, and also new-window,
// and drag-moves for the lists of slices (see [ListBase.DragMoves]).
func styleFromTags(w Widget, tags reflect.StructTag) {
w.AsWidget().Styler(func(s *styles.Style) {
setFromTag(tags, "width", s.Min.X.Ch)
setFromTag(tags, "max-width", s.Max.X.Ch)
setFromTag(tags, "height", s.Min.Y.Em)
setFromTag(tags, "max-height", s.Max.Y.Em)
setFromTag(tags, "grow", func(v float32) { s.Grow.X = v })
setFromTag(tags, "grow-y", func(v float32) { s.Grow.Y = v })
setFromTag(tags, "icon-width", s.IconSize.X.Em)
setFromTag(tags, "icon-height", s.IconSize.Y.Em)
})
if tags.Get("new-window") == "+" {
w.AsWidget().setFlag(true, widgetValueNewWindow)
}
if tags.Get("drag-moves") == "+" {
switch x := w.(type) {
case *ListButton:
x.DragMoves = true
case Lister:
x.AsListBase().DragMoves = true
}
}
}
// percentBase returns the size that the percentages of the parent's size
// (as [units.UnitPw]) of the widget, with the given parent, are of: that of
// the content of its parent, or, for a widget that is out of flow (absolute
// or fixed), that of the padding box of its containing block, as in CSS
// (as for the margin of 50% of the dot under the bookmark icon of
// Wikipedia, of its item, which was a long bar as a margin of its parent).
func (wb *WidgetBase) percentBase(pw *WidgetBase) math32.Vector2 {
if wb.outOfFlow() {
if cb := wb.containingBlock(); cb != nil && cb != pw {
if _, sz := cb.paddingBox(); sz.X > 0 || sz.Y > 0 {
return sz
}
}
}
return pw.Geom.Size.Alloc.Content
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"bytes"
"image"
"io"
"io/fs"
"strings"
"cogentcore.org/core/base/iox/imagex"
"cogentcore.org/core/cursors"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint"
"cogentcore.org/core/paint/render"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/svg"
"cogentcore.org/core/tree"
"golang.org/x/image/draw"
)
// todo: rewrite svg.SVG to accept an external painter to render to,
// and use that for this, so it renders directly instead of via image.
// SVG is a Widget that renders an [svg.SVG] object.
// If it is not [states.ReadOnly], the user can pan and zoom the display.
// By default, it is [states.ReadOnly].
type SVG struct {
WidgetBase
// SVG is the SVG drawing to display.
SVG *svg.SVG `set:"-"`
// image renderer
renderer render.Renderer
// cached rendered image
image image.Image
// prevSize is the cached allocated size for the last rendered image.
prevSize image.Point `xml:"-" json:"-" set:"-"`
}
func (sv *SVG) Init() {
sv.WidgetBase.Init()
sz := math32.Vec2(10, 10)
sv.SVG = svg.NewSVG(sz)
sv.renderer = paint.NewImageRenderer(sz)
sv.SetReadOnly(true)
sv.Styler(func(s *styles.Style) {
s.Min.Set(units.Dp(256))
ro := sv.IsReadOnly()
s.SetAbilities(!ro, abilities.Slideable, abilities.Activatable, abilities.Scrollable)
if !ro {
if s.Is(states.Active) {
s.Cursor = cursors.Grabbing
s.StateLayer = 0
} else {
s.Cursor = cursors.Grab
}
}
})
sv.FinalStyler(func(s *styles.Style) {
sv.SVG.Root.ViewBox.PreserveAspectRatio.SetFromStyle(s)
})
sv.On(events.SlideMove, func(e events.Event) {
if sv.IsReadOnly() {
return
}
e.SetHandled()
sv.SVG.Translate.SetAdd(math32.FromPoint(e.PrevDelta()))
sv.NeedsRender()
})
sv.On(events.Scroll, func(e events.Event) {
if sv.IsReadOnly() {
return
}
e.SetHandled()
se := e.(*events.MouseScroll)
sv.SVG.ZoomAtScroll(se.Delta.Y, se.Pos())
sv.NeedsRender()
})
}
// Open opens an XML-formatted SVG file
func (sv *SVG) Open(filename Filename) error { //types:add
return sv.SVG.OpenXML(string(filename))
}
// OpenFS opens an XML-formatted SVG file from the given fs.
func (sv *SVG) OpenFS(fsys fs.FS, filename string) error {
return sv.SVG.OpenFS(fsys, filename)
}
// Read reads an XML-formatted SVG file from the given reader.
func (sv *SVG) Read(r io.Reader) error {
return sv.SVG.ReadXML(r)
}
// ReadBytes reads an XML-formatted SVG file from the given bytes.
func (sv *SVG) ReadBytes(b []byte) error {
return sv.SVG.ReadXML(bytes.NewReader(b))
}
// ReadString reads an XML-formatted SVG file from the given string.
func (sv *SVG) ReadString(s string) error {
return sv.SVG.ReadXML(strings.NewReader(s))
}
// SaveSVG saves the current SVG to an XML-encoded standard SVG file.
func (sv *SVG) SaveSVG(filename Filename) error { //types:add
return sv.SVG.SaveXML(string(filename))
}
// SaveImage saves the current rendered SVG image to an image file,
// using the filename extension to determine the file type.
func (sv *SVG) SaveImage(filename Filename) error { //types:add
return sv.SVG.SaveImage(string(filename))
}
func (sv *SVG) SizeFinal() {
sv.WidgetBase.SizeFinal()
sz := sv.Geom.Size.Actual.Content
sv.SVG.SetSize(sz)
sv.renderer.SetSize(units.UnitDot, sz)
}
// renderSVG renders the SVG
func (sv *SVG) renderSVG() {
if sv.SVG == nil {
return
}
sv.SVG.TextShaper = sv.Scene.TextShaper()
sv.renderer.Render(sv.SVG.Render(nil).RenderDone())
sv.image = imagex.WrapJS(sv.renderer.Image())
sv.prevSize = sv.image.Bounds().Size()
}
func (sv *SVG) Render() {
sv.WidgetBase.Render()
if sv.SVG == nil {
return
}
needsRender := !sv.IsReadOnly() || sv.NeedsRebuild()
if sv.SVG.Color != sv.Styles.Color { // the current color of the SVG (currentColor)
sv.SVG.Color = sv.Styles.Color
needsRender = true
}
if !needsRender {
if sv.image == nil {
needsRender = true
} else {
sv.SVG.UpdateSize()
sz := sv.SVG.Geom.Size
if sz != sv.prevSize || sv.image.Bounds().Size() == (image.Point{}) {
needsRender = true
}
}
}
if needsRender {
sv.renderSVG()
}
r := sv.Geom.ContentBBox
sp := sv.Geom.ScrollOffset()
sv.Scene.Painter.DrawImage(sv.image, nil, r, sp, draw.Over)
}
func (sv *SVG) MakeToolbar(p *tree.Plan) {
tree.Add(p, func(w *Button) {
w.SetText("Pan").SetIcon(icons.PanTool)
w.SetTooltip("Toggle the ability to zoom and pan")
w.OnClick(func(e events.Event) {
sv.SetReadOnly(!sv.IsReadOnly())
sv.Restyle()
})
})
tree.Add(p, func(w *Separator) {})
tree.Add(p, func(w *FuncButton) {
w.SetFunc(sv.Open).SetIcon(icons.Open)
})
tree.Add(p, func(w *FuncButton) {
w.SetFunc(sv.SaveSVG).SetIcon(icons.Save)
})
tree.Add(p, func(w *FuncButton) {
w.SetFunc(sv.SaveImage).SetIcon(icons.Save)
})
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"reflect"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/colors"
"cogentcore.org/core/cursors"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/text"
"cogentcore.org/core/tree"
)
// Switch is a widget that can toggle between an on and off state.
// It can be displayed as a switch, chip, checkbox, radio button,
// or segmented button.
type Switch struct {
Frame
// Type is the styling type of switch.
// It must be set using [Switch.SetType].
Type SwitchTypes `set:"-"`
// Text is the optional text of the switch.
Text string
// IconOn is the icon to use for the on, checked state of the switch.
IconOn icons.Icon
// Iconoff is the icon to use for the off, unchecked state of the switch.
IconOff icons.Icon
// IconIndeterminate is the icon to use for the indeterminate (unknown) state.
IconIndeterminate icons.Icon
}
// SwitchTypes contains the different types of [Switch]es.
type SwitchTypes int32 //enums:enum -trim-prefix Switch -transform kebab
const (
// SwitchSwitch indicates to display a switch as a switch (toggle slider).
SwitchSwitch SwitchTypes = iota
// SwitchChip indicates to display a switch as chip (like Material Design's
// filter chip), which is typically only used in the context of [Switches].
SwitchChip
// SwitchCheckbox indicates to display a switch as a checkbox.
SwitchCheckbox
// SwitchRadioButton indicates to display a switch as a radio button.
SwitchRadioButton
// SwitchSegmentedButton indicates to display a segmented button, which is
// typically only used in the context of [Switches].
SwitchSegmentedButton
)
func (sw *Switch) WidgetValue() any { return sw.IsChecked() }
func (sw *Switch) SetWidgetValue(value any) error {
b, err := reflectx.ToBool(value)
if err != nil {
return err
}
sw.SetChecked(b)
return nil
}
func (sw *Switch) OnBind(value any, tags reflect.StructTag) {
if d, ok := tags.Lookup("display"); ok {
errors.Log(sw.Type.SetString(d))
sw.SetType(sw.Type)
}
}
func (sw *Switch) Init() {
sw.Frame.Init()
sw.Styler(func(s *styles.Style) {
if !sw.IsReadOnly() {
s.SetAbilities(true, abilities.Activatable, abilities.Focusable, abilities.Hoverable, abilities.Checkable)
s.Cursor = cursors.Pointer
}
s.Text.Align = text.Start
s.Text.AlignV = text.Center
s.Padding.SetVertical(units.Dp(4))
s.Padding.SetHorizontal(units.Dp(ConstantSpacing(4))) // needed for layout issues
s.Border.Radius = styles.BorderRadiusSmall
s.Gap.Zero()
s.CenterAll()
s.IconSize.Set(units.Em(1.5))
switch sw.Type {
case SwitchChip:
if s.Is(states.Checked) {
s.Background = colors.Scheme.SurfaceVariant
s.Color = colors.Scheme.OnSurfaceVariant
} else if !s.Is(states.Focused) {
s.Border.Width.Set(units.Dp(1))
}
case SwitchSegmentedButton:
if !s.Is(states.Focused) {
s.Border.Width.Set(units.Dp(1))
}
if s.Is(states.Checked) {
s.Background = colors.Scheme.SurfaceVariant
s.Color = colors.Scheme.OnSurfaceVariant
}
case SwitchSwitch:
s.IconSize.Set(units.Em(2), units.Em(1.5)) // switches need to be bigger
}
if s.Is(states.Selected) {
s.Background = colors.Scheme.Select.Container
}
})
sw.SendClickOnEnter()
sw.OnFinal(events.Click, func(e events.Event) {
if sw.IsReadOnly() {
return
}
sw.SetChecked(sw.IsChecked())
if sw.Type == SwitchChip || sw.Type == SwitchSegmentedButton {
sw.updateStackTop() // must update here
sw.NeedsLayout()
} else {
sw.NeedsRender()
}
sw.SendChange(e)
})
sw.Maker(func(p *tree.Plan) {
if sw.IconOn == "" {
sw.IconOn = icons.ToggleOnFill // fallback
}
if sw.IconOff == "" {
sw.IconOff = icons.ToggleOff // fallback
}
tree.AddAt(p, "stack", func(w *Frame) {
w.Styler(func(s *styles.Style) {
s.Display = styles.Stacked
s.Gap.Zero()
})
w.Updater(func() {
sw.updateStackTop() // need to update here
})
w.Maker(func(p *tree.Plan) {
tree.AddAt(p, "icon-on", func(w *Icon) {
w.Styler(func(s *styles.Style) {
if sw.Type == SwitchChip {
s.Color = colors.Scheme.OnSurfaceVariant
} else {
s.Color = colors.Scheme.Primary.Base
}
})
w.Updater(func() {
w.SetIcon(sw.IconOn)
})
})
// same styles for off and indeterminate
iconStyle := func(s *styles.Style) {
if sw.IconOff == icons.None && sw.IconIndeterminate == icons.None {
s.IconSize.Zero() // nothing to render
}
}
tree.AddAt(p, "icon-off", func(w *Icon) {
w.Styler(iconStyle)
w.Updater(func() {
w.SetIcon(sw.IconOff)
})
})
tree.AddAt(p, "icon-indeterminate", func(w *Icon) {
w.Styler(iconStyle)
w.Updater(func() {
w.SetIcon(sw.IconIndeterminate)
})
})
})
})
if sw.Text != "" {
tree.AddAt(p, "space", func(w *Space) {
w.Styler(func(s *styles.Style) {
s.Min.X.Ch(0.1)
})
})
tree.AddAt(p, "text", func(w *Text) {
w.Styler(func(s *styles.Style) {
s.SetNonSelectable()
s.SetTextWrap(false)
s.FillMargin = false
})
w.Updater(func() {
w.SetText(sw.Text)
})
})
}
})
}
// IsChecked returns whether the switch is checked.
func (sw *Switch) IsChecked() bool {
return sw.StateIs(states.Checked)
}
// SetChecked sets whether the switch it checked.
func (sw *Switch) SetChecked(on bool) *Switch {
sw.SetState(on, states.Checked)
sw.SetState(false, states.Indeterminate)
return sw
}
// updateStackTop updates the [Frame.StackTop] of the stack in the switch
// according to the current icon. It is called automatically to keep the
// switch up-to-date.
func (sw *Switch) updateStackTop() {
st, ok := sw.ChildByName("stack", 0).(*Frame)
if !ok {
return
}
switch {
case sw.StateIs(states.Indeterminate):
st.StackTop = 2
case sw.IsChecked():
st.StackTop = 0
default:
if sw.Type == SwitchChip {
// chips render no icon when off
st.StackTop = -1
return
}
st.StackTop = 1
}
}
// SetType sets the styling type of the switch.
func (sw *Switch) SetType(typ SwitchTypes) *Switch {
sw.Type = typ
sw.IconIndeterminate = icons.Blank
switch sw.Type {
case SwitchSwitch:
// TODO: material has more advanced switches with a checkmark
// if they are turned on; we could implement that at some point
sw.IconOn = icons.ToggleOnFill
sw.IconOff = icons.ToggleOff
sw.IconIndeterminate = icons.ToggleMid
case SwitchChip, SwitchSegmentedButton:
sw.IconOn = icons.Check
sw.IconOff = icons.None
sw.IconIndeterminate = icons.None
case SwitchCheckbox:
sw.IconOn = icons.CheckBoxFill
sw.IconOff = icons.CheckBoxOutlineBlank
sw.IconIndeterminate = icons.IndeterminateCheckBox
case SwitchRadioButton:
sw.IconOn = icons.RadioButtonChecked
sw.IconOff = icons.RadioButtonUnchecked
sw.IconIndeterminate = icons.RadioButtonPartial
}
return sw
}
func (sw *Switch) Render() {
sw.updateStackTop() // important: make sure we're always up-to-date on render
st, ok := sw.ChildByName("stack", 0).(*Frame)
if ok {
st.UpdateStackedVisibility()
}
sw.WidgetBase.Render()
}
// Copyright (c) 2019, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"fmt"
"reflect"
"slices"
"strconv"
"strings"
"unicode"
"cogentcore.org/core/base/labels"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/base/strcase"
"cogentcore.org/core/enums"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/tree"
"cogentcore.org/core/types"
)
// Switches is a widget for containing a set of [Switch]es.
// It can optionally enforce mutual exclusivity (ie: radio buttons)
// through the [Switches.Mutex] field. It supports binding to
// [enums.Enum] and [enums.BitFlag] values with appropriate properties
// automatically set.
type Switches struct {
Frame
// Type is the type of switches that will be made.
Type SwitchTypes
// Items are the items displayed to the user.
Items []SwitchItem
// Mutex is whether to make the items mutually exclusive
// (checking one turns off all the others).
Mutex bool
// AllowNone is whether to allow the user to deselect all items.
// It is on by default.
AllowNone bool `default:"true"`
// selectedIndexes are the indexes in [Switches.Items] of the currently
// selected switch items.
selectedIndexes []int
// bitFlagValue is the associated bit flag value if non-nil (for [Value]).
bitFlagValue enums.BitFlagSetter
}
// SwitchItem contains the properties of one item in a [Switches].
type SwitchItem struct {
// Value is the underlying value the switch item represents.
Value any
// Text is the text displayed to the user for this item.
// If it is empty, then [labels.ToLabel] of [SwitchItem.Value]
// is used instead.
Text string
// Tooltip is the tooltip displayed to the user for this item.
Tooltip string
}
// getText returns the effective text for this switch item.
// If [SwitchItem.Text] is set, it returns that. Otherwise,
// it returns [labels.ToLabel] of [SwitchItem.Value].
func (si *SwitchItem) getText() string {
if si.Text != "" {
return si.Text
}
if si.Value == nil {
return ""
}
return labels.ToLabel(si.Value)
}
func (sw *Switches) WidgetValue() any {
if sw.bitFlagValue != nil {
sw.bitFlagFromSelected(sw.bitFlagValue)
// We must return a non-pointer value to prevent [ResetWidgetValue]
// from clearing the bit flag value (since we only ever have one
// total pointer to it, so it is uniquely vulnerable to being destroyed).
return reflectx.Underlying(reflect.ValueOf(sw.bitFlagValue)).Interface()
}
item := sw.SelectedItem()
if item == nil {
return nil
}
return item.Value
}
func (sw *Switches) SetWidgetValue(value any) error {
up := reflectx.UnderlyingPointer(reflect.ValueOf(value))
if bf, ok := reflect.TypeAssert[enums.BitFlagSetter](up); ok {
sw.selectFromBitFlag(bf)
return nil
}
return sw.SelectValue(up.Elem().Interface())
}
func (sw *Switches) OnBind(value any, tags reflect.StructTag) {
if e, ok := value.(enums.Enum); ok {
sw.SetEnum(e).SetType(SwitchSegmentedButton).SetMutex(true)
}
if bf, ok := value.(enums.BitFlagSetter); ok {
sw.bitFlagValue = bf
sw.SetType(SwitchChip).SetMutex(false)
} else {
sw.bitFlagValue = nil
sw.AllowNone = false
}
}
func (sw *Switches) Init() {
sw.Frame.Init()
sw.AllowNone = true
sw.Styler(func(s *styles.Style) {
s.Padding.Set(units.Dp(ConstantSpacing(2)))
s.Margin.Set(units.Dp(ConstantSpacing(2)))
if sw.Type == SwitchSegmentedButton {
s.Gap.Zero()
} else {
s.Wrap = true
}
if sw.Type == SwitchSwitch {
s.IconSize.Set(units.Em(2), units.Em(1.5))
} else {
s.IconSize.Set(units.Em(1.5))
}
})
sw.FinalStyler(func(s *styles.Style) {
if s.Direction != styles.Row {
// if we wrap, it just goes in the x direction
s.Wrap = false
}
})
sw.Maker(func(p *tree.Plan) {
for i, item := range sw.Items {
tree.AddAt(p, strconv.Itoa(i), func(w *Switch) {
w.OnChange(func(e events.Event) {
if w.IsChecked() {
if sw.Mutex {
sw.selectedIndexes = []int{i}
} else {
sw.selectedIndexes = append(sw.selectedIndexes, i)
}
} else if sw.AllowNone || len(sw.selectedIndexes) > 1 {
sw.selectedIndexes = slices.DeleteFunc(sw.selectedIndexes, func(v int) bool { return v == i })
}
sw.SendChange(e)
sw.UpdateRender()
})
w.Styler(func(s *styles.Style) {
ps := &sw.Styles
s.IconSize = ps.IconSize // Directly inherit
// Remaining styles are only for segmented buttons
if sw.Type != SwitchSegmentedButton {
return
}
ip := w.IndexInParent()
brf := styles.BorderRadiusFull.Top
if ip == 0 {
if ps.Direction == styles.Row {
s.Border.Radius.Set(brf, units.Zero(), units.Zero(), brf)
} else {
s.Border.Radius.Set(brf, brf, units.Zero(), units.Zero())
}
} else if ip == sw.NumChildren()-1 {
if ps.Direction == styles.Row {
if !s.Is(states.Focused) {
s.Border.Width.SetLeft(units.Zero())
s.MaxBorder.Width = s.Border.Width
}
s.Border.Radius.Set(units.Zero(), brf, brf, units.Zero())
} else {
if !s.Is(states.Focused) {
s.Border.Width.SetTop(units.Zero())
s.MaxBorder.Width = s.Border.Width
}
s.Border.Radius.Set(units.Zero(), units.Zero(), brf, brf)
}
} else {
if !s.Is(states.Focused) {
if ps.Direction == styles.Row {
s.Border.Width.SetLeft(units.Zero())
} else {
s.Border.Width.SetTop(units.Zero())
}
s.MaxBorder.Width = s.Border.Width
}
s.Border.Radius.Zero()
}
})
w.Updater(func() {
w.SetType(sw.Type).SetText(item.getText()).SetTooltip(item.Tooltip)
if sw.Type == SwitchSegmentedButton && sw.Styles.Direction == styles.Column {
// need a blank icon to create a cohesive segmented button
w.SetIconOff(icons.Blank).SetIconIndeterminate(icons.Blank)
}
if !w.StateIs(states.Indeterminate) {
w.SetChecked(slices.Contains(sw.selectedIndexes, i))
}
})
})
}
})
}
// SelectedItem returns the first selected (checked) switch item. It is only
// useful when [Switches.Mutex] is true; if it is not, use [Switches.SelectedItems].
// If no switches are selected, it returns nil.
func (sw *Switches) SelectedItem() *SwitchItem {
if len(sw.selectedIndexes) == 0 {
return nil
}
return &sw.Items[sw.selectedIndexes[0]]
}
// SelectedItems returns all of the currently selected (checked) switch items.
// If [Switches.Mutex] is true, you should use [Switches.SelectedItem] instead.
func (sw *Switches) SelectedItems() []SwitchItem {
res := []SwitchItem{}
for _, i := range sw.selectedIndexes {
res = append(res, sw.Items[i])
}
return res
}
// SelectValue sets the item with the given [SwitchItem.Value]
// to be the only selected item.
func (sw *Switches) SelectValue(value any) error {
for i, item := range sw.Items {
if item.Value == value {
sw.selectedIndexes = []int{i}
return nil
}
}
return fmt.Errorf("Switches.SelectValue: item not found: (value: %v, items: %v)", value, sw.Items)
}
// SetStrings sets the [Switches.Items] from the given strings.
func (sw *Switches) SetStrings(ss ...string) *Switches {
sw.Items = make([]SwitchItem, len(ss))
for i, s := range ss {
sw.Items[i] = SwitchItem{Value: s}
}
return sw
}
// SetEnums sets the [Switches.Items] from the given enums.
func (sw *Switches) SetEnums(es ...enums.Enum) *Switches {
sw.Items = make([]SwitchItem, len(es))
for i, enum := range es {
str := ""
if bf, ok := enum.(enums.BitFlag); ok {
str = bf.BitIndexString()
} else {
str = enum.String()
}
lbl := strcase.ToSentence(str)
if lb, ok := enum.(labels.Labeler); ok { // its own label, as "iCloud"
lbl = lb.Label()
}
desc := enum.Desc()
// If the documentation does not start with the transformed name, but it does
// start with an uppercase letter, then we assume that the first word of the
// documentation is the correct untransformed name. This fixes
// https://github.com/cogentcore/core/issues/774 (also for Chooser).
if !strings.HasPrefix(desc, str) && len(desc) > 0 && unicode.IsUpper(rune(desc[0])) {
str, _, _ = strings.Cut(desc, " ")
}
tip := types.FormatDoc(desc, str, lbl)
sw.Items[i] = SwitchItem{Value: enum, Text: lbl, Tooltip: tip}
}
return sw
}
// SetEnum sets the [Switches.Items] from the [enums.Enum.Values] of the given enum.
func (sw *Switches) SetEnum(enum enums.Enum) *Switches {
return sw.SetEnums(enum.Values()...)
}
// selectFromBitFlag sets which switches are selected based on the given bit flag value.
func (sw *Switches) selectFromBitFlag(bitflag enums.BitFlagSetter) {
values := bitflag.Values()
sw.selectedIndexes = []int{}
for i, value := range values {
if bitflag.HasFlag(value.(enums.BitFlag)) {
sw.selectedIndexes = append(sw.selectedIndexes, i)
}
}
}
// bitFlagFromSelected sets the given bit flag value based on which switches are selected.
func (sw *Switches) bitFlagFromSelected(bitflag enums.BitFlagSetter) {
bitflag.SetInt64(0)
values := bitflag.Values()
for _, i := range sw.selectedIndexes {
bitflag.SetFlag(true, values[i].(enums.BitFlag))
}
}
// SizeUp reserves the width of the check icons of the chips that are not
// checked, when the chips are on one line (not wrapped, as in a list or
// table), so that the switches are as wide as they are with all of them
// checked: a chip is wider when it is checked, with its check icon, and the
// width of a one-line row of switches does not change, as for the columns of
// a table, which do not anticipate it.
func (sw *Switches) SizeUp() {
sw.Frame.SizeUp()
if sw.Type != SwitchChip || sw.Styles.Wrap || sw.Styles.Direction != styles.Row {
return
}
extra := float32(0)
sw.ForWidgetChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
ch, ok := cw.(*Switch)
if !ok || ch.IsChecked() {
return tree.Continue
}
if ic, ok := ch.FindPath("stack/icon-on").(*Icon); ok {
extra += ic.Geom.Size.Actual.Total.X
}
return tree.Continue
})
if extra == 0 {
return
}
sz := &sw.Geom.Size
sz.Actual.Content.X += extra
sz.SetTotalFromContent(&sz.Actual)
sz.minWidth += extra
sz.prefWidth += extra
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"fmt"
"image"
"log/slog"
"reflect"
"strconv"
"strings"
"cogentcore.org/core/base/labels"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/base/strcase"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/textpos"
"cogentcore.org/core/tree"
"cogentcore.org/core/types"
)
// Table represents a slice of structs as a table, where the fields are
// the columns and the elements are the rows. It is a full-featured editor with
// multiple-selection, cut-and-paste, and drag-and-drop.
// Use [ListBase.BindSelect] to make the table designed for item selection.
type Table struct {
ListBase
// TableStyler is an optional styling function for table items.
TableStyler TableStyler `copier:"-" json:"-" xml:"-"`
// HeaderIcons are icons shown in the headers of the columns of the
// fields with the given names instead of their labels, which are in
// their tooltips, as for narrow columns (such as a paperclip for the
// number of attachments).
HeaderIcons map[string]icons.Icon `copier:"-" display:"-" json:"-" xml:"-"`
// SelectedField is the current selection field; initially select value in this field.
SelectedField string `copier:"-" display:"-" json:"-" xml:"-"`
// ColumnWidths are the widths of the columns, in Dp, by field name,
// for those whose widths are set, as the user does by dragging the
// handles between the column headers, which sends a change event.
// The other columns have automatic widths.
ColumnWidths map[string]float32
// ShowField, if set, returns whether to show the given field of the
// structs, which is otherwise shown unless its tags hide it, as for
// showing only some of the fields on a small screen. It must be set
// before the slice or items.
ShowField func(field reflect.StructField) bool `copier:"-" json:"-" xml:"-" display:"-"`
// SortFunc, if set, sorts the slice by the field of the given name, up
// (ascending) or down, instead of by the values of the field, and
// returns whether it did (else they are sorted by their values).
SortFunc func(field string, down bool) bool `copier:"-" json:"-" xml:"-" display:"-"`
// OnSort, if set, is called when the user sorts the slice by the field
// of the given name, up (ascending) or down, by clicking on the header
// of its column (see [Table.SortFieldName]).
OnSort func(field string, down bool) `copier:"-" json:"-" xml:"-" display:"-"`
// rowButton is the button at the end of each row, if any
// (see [Table.SetRowButton]).
rowButton *tableRowButton
// sortIndex is the current sort index.
sortIndex int
// sortDescending is whether the current sort order is descending.
sortDescending bool
// visibleFields are the visible fields.
visibleFields []reflect.StructField
// numVisibleFields is the number of visible fields.
numVisibleFields int
// headerWidths has the number of characters in each header, per visibleFields.
headerWidths []int
// colMaxWidths records maximum width in chars of string type fields.
colMaxWidths []int
header *Frame
}
// tableRowButton is the button at the end of each row of a [Table].
type tableRowButton struct {
icon icons.Icon
tooltip string
fun func(item any)
}
// SetRowButton adds an icon button with the given icon and tooltip at
// the end of each row, which calls the given function with the item of
// the row, a pointer to its struct, as for editing it in a [Form] on a
// small screen, where the table shows only some of its fields. A nil
// function removes the button.
func (tb *Table) SetRowButton(icon icons.Icon, tooltip string, fun func(item any)) *Table {
if fun == nil {
tb.rowButton = nil
return tb
}
tb.rowButton = &tableRowButton{icon: icon, tooltip: tooltip, fun: fun}
return tb
}
// makeRowButton adds the button at the end of the given widget row
// index to the given plan, if there is one (see [Table.SetRowButton]).
func (tb *Table) makeRowButton(p *tree.Plan, i int) {
rb := tb.rowButton
if rb == nil {
return
}
tree.AddAt(p, "row-button-"+strconv.Itoa(i), func(w *Button) {
// its row, for its background (as selected; see
// [ListGrid.ChildBackground]) and selecting its row when focused
w.SetProperty(ListRowProperty, i)
w.SetProperty(ListColProperty, tb.numVisibleFields)
w.SetType(ButtonAction).SetIcon(rb.icon).SetTooltip(rb.tooltip)
w.OnClick(func(e events.Event) {
// the row has the item at the time of the click,
// as the rows show other items as the list scrolls
si, _, invis := tb.This.(Lister).SliceIndex(i)
if !invis {
rb.fun(reflectx.UnderlyingPointer(tb.sliceElementValue(si)).Interface())
}
})
w.Updater(func() {
_, _, invis := tb.This.(Lister).SliceIndex(i)
w.SetState(invis, states.Invisible)
})
})
}
// TableStyler is a styling function for custom styling and
// configuration of elements in the table.
type TableStyler func(w Widget, s *styles.Style, row, col int)
func (tb *Table) Init() {
tb.ListBase.Init()
tb.AddContextMenu(tb.contextMenu)
tb.sortIndex = -1
tb.Makers.Normal[0] = func(p *tree.Plan) { // TODO: reduce redundancy with ListBase Maker
svi := tb.This.(Lister)
svi.UpdateSliceSize()
tb.SortSlice()
scrollTo := -1
if tb.SelectedField != "" && tb.SelectedValue != nil {
tb.SelectedIndex, _ = structSliceIndexByValue(tb.Slice, tb.SelectedField, tb.SelectedValue)
tb.SelectedField = ""
tb.SelectedValue = nil
tb.InitSelectedIndex = -1
scrollTo = tb.SelectedIndex
} else if tb.InitSelectedIndex >= 0 {
tb.SelectedIndex = tb.InitSelectedIndex
tb.InitSelectedIndex = -1
scrollTo = tb.SelectedIndex
}
if scrollTo >= 0 {
tb.ScrollToIndex(scrollTo)
}
tb.UpdateStartIndex()
tb.Updater(func() {
tb.UpdateStartIndex()
})
tb.makeHeader(p)
tb.MakeGrid(p, func(p *tree.Plan) {
for i := range tb.VisibleRows {
svi.MakeRow(p, i)
}
})
}
}
// StyleValue performs additional value widget styling
func (tb *Table) StyleValue(w Widget, s *styles.Style, row, col int) {
// one line, as for the switches of bit flags
s.Wrap = false
if tb.columnWidth(col) > 0 { // see ListGrid.fixColumnWidths
s.SetTextWrap(false)
return
}
// the header button has padding, the space of the sort indicator,
// and the handle after it
hw := float32(tb.headerWidths[col]) + 7
if len(tb.colMaxWidths) > col {
hw = max(float32(tb.colMaxWidths[col]), hw)
}
hv := units.Ch(hw)
s.Min.X.Value = max(s.Min.X.Value, hv.Convert(s.Min.X.Unit, &s.UnitContext).Value)
s.SetTextWrap(false)
}
// SetSlice sets the source slice that we are viewing.
func (tb *Table) SetSlice(sl any) *Table {
if reflectx.IsNil(reflect.ValueOf(sl)) {
tb.Slice = nil
return tb
}
if tb.Slice == sl {
tb.MakeIter = 0
return tb
}
slpTyp := reflect.TypeOf(sl)
if slpTyp.Kind() != reflect.Pointer {
slog.Error("Table requires that you pass a pointer to a slice of struct elements, but type is not a Ptr", "type", slpTyp)
return tb
}
if slpTyp.Elem().Kind() != reflect.Slice {
slog.Error("Table requires that you pass a pointer to a slice of struct elements, but ptr doesn't point to a slice", "type", slpTyp.Elem())
return tb
}
eltyp := reflectx.NonPointerType(reflectx.SliceElementType(sl))
if eltyp.Kind() != reflect.Struct {
slog.Error("Table requires that you pass a slice of struct elements, but type is not a Struct", "type", eltyp.String())
return tb
}
tb.Slice = sl
tb.sliceUnderlying = reflectx.Underlying(reflect.ValueOf(tb.Slice))
tb.elementValue = reflectx.Underlying(reflectx.SliceElementValue(sl))
tb.SetSliceBase()
tb.cacheVisibleFields()
return tb
}
// cacheVisibleFields caches the visible struct fields.
func (tb *Table) cacheVisibleFields() {
tb.visibleFields = make([]reflect.StructField, 0)
shouldShow := func(field reflect.StructField) bool {
if tb.ShowField != nil && !tb.ShowField(field) {
return false
}
tvtag := field.Tag.Get("table")
switch {
case tvtag == "+":
return true
case tvtag == "-":
return false
case tvtag == "-select" && tb.IsReadOnly():
return false
case tvtag == "-edit" && !tb.IsReadOnly():
return false
default:
return field.Tag.Get("display") != "-"
}
}
reflectx.WalkFields(tb.elementValue,
func(parent reflect.Value, field reflect.StructField, value reflect.Value) bool {
return shouldShow(field)
},
func(parent reflect.Value, parentField *reflect.StructField, field reflect.StructField, value reflect.Value) {
if parentField != nil {
field.Index = append(parentField.Index, field.Index...)
}
tb.visibleFields = append(tb.visibleFields, field)
})
tb.numVisibleFields = len(tb.visibleFields)
tb.headerWidths = make([]int, tb.numVisibleFields)
tb.colMaxWidths = make([]int, tb.numVisibleFields)
}
func (tb *Table) UpdateMaxWidths() {
if tb.SliceSize == 0 {
return
}
updated := false
for fli := range tb.numVisibleFields {
field := tb.visibleFields[fli]
val := tb.sliceElementValue(0)
fval := val.FieldByIndex(field.Index)
isString := fval.Type().Kind() == reflect.String && fval.Type() != reflect.TypeFor[icons.Icon]()
if !isString {
tb.colMaxWidths[fli] = 0
continue
}
mxw := 0
for rw := range tb.SliceSize {
val := tb.sliceElementValue(rw)
str := reflectx.ToString(val.FieldByIndex(field.Index).Interface())
mxw = max(mxw, len(str))
}
if mxw != tb.colMaxWidths[fli] {
tb.colMaxWidths[fli] = mxw
updated = true
}
}
if updated {
tb.Update()
}
}
func (tb *Table) makeHeader(p *tree.Plan) {
tree.AddAt(p, "header", func(w *Frame) {
tb.header = w
ToolbarStyles(w)
w.FinalStyler(func(s *styles.Style) {
s.Padding.Zero()
s.Grow.Set(0, 0)
s.Gap.Zero() // the widths of the columns include the gaps (see SizeFinal)
})
w.Maker(func(p *tree.Plan) {
if tb.ShowIndexes {
tree.AddAt(p, "_head-index", func(w *Text) {
w.SetType(TextBodyMedium)
w.Styler(func(s *styles.Style) {
s.Align.Self = styles.Center
})
w.SetText("Index")
})
}
for fli := range tb.numVisibleFields {
field := tb.visibleFields[fli]
// the index is in the name, as it is in the closures, so that
// the header is remade when its field has another index
tree.AddAt(p, fmt.Sprintf("head-%d-%s", fli, field.Name), func(w *Button) {
w.SetType(ButtonAction)
w.Styler(func(s *styles.Style) {
s.Justify.Content = styles.Start
if tb.compactHeader() {
s.Padding.SetHorizontal(units.Em(0.25))
}
})
w.OnClick(func(e events.Event) {
tb.SortColumn(fli)
})
w.Updater(func() {
htxt := ""
if lbl, ok := field.Tag.Lookup("label"); ok {
htxt = lbl
} else {
htxt = strcase.ToSentence(field.Name)
}
w.Tooltip = htxt + " (click to sort by)"
doc, ok := types.GetDoc(reflect.Value{}, tb.elementValue, field, htxt)
if ok && doc != "" {
w.Tooltip += ": " + doc
}
if ic := tb.HeaderIcons[field.Name]; ic != "" {
w.SetIcon(ic).SetText("") // the label is in the tooltip
tb.headerWidths[fli] = 2
} else {
w.SetText(htxt)
tb.headerWidths[fli] = len(htxt)
}
if fli == tb.sortIndex {
if tb.sortDescending {
w.SetIndicator(icons.KeyboardArrowDown)
} else {
w.SetIndicator(icons.KeyboardArrowUp)
}
} else if tb.compactHeader() {
w.SetIndicator(icons.None) // with only the room of the text
} else {
w.SetIndicator(icons.Blank)
}
})
})
tb.makeColumnHandle(p, fli)
}
})
})
}
// compactHeader returns whether the headers of the columns have only the
// room of their text, as for a [TreeTable] with [TreeTable.FitWidth],
// whose columns have the widths of their values.
func (tb *Table) compactHeader() bool {
tt, ok := tb.This.(*TreeTable)
return ok && tt.FitWidth
}
// makeColumnHandle adds the handle after the header of the column of the
// given visible field to the given plan, which sets its width by dragging,
// and makes it automatic again by double clicking.
func (tb *Table) makeColumnHandle(p *tree.Plan, fli int) {
field := tb.visibleFields[fli]
tree.AddAt(p, fmt.Sprintf("width-%d-%s", fli, field.Name), func(w *Handle) { // see head
w.SetTooltip("Drag to set the width of the column, or double click for the automatic width")
w.Styler(func(s *styles.Style) {
s.Direction = styles.Row
s.SetAbilities(false, abilities.Focusable)
s.SetAbilities(true, abilities.DoubleClickable)
})
w.FinalStyler(func(s *styles.Style) {
s.Min.X.Dp(3)
s.Min.Y.Em(1.5)
s.Margin.SetHorizontal(units.Dp(2))
})
var start float32 // the width of the column when the drag starts, in dots
w.On(events.SlideStart, func(e events.Event) {
start = tb.columnDots(fli)
})
w.On(events.SlideMove, func(e events.Event) {
e.SetHandled()
tb.setColumnWidth(fli, start+float32(e.Pos().X-e.StartPos().X))
})
w.On(events.SlideStop, func(e events.Event) {
tb.SendChange(e)
})
w.OnDoubleClick(func(e events.Event) {
delete(tb.ColumnWidths, field.Name)
tb.Restyle()
tb.NeedsLayout()
tb.SendChange(e)
})
})
}
// columnWidth returns the width of the column of the given visible field,
// in Dp, if it is set, or else 0, for the automatic width.
func (tb *Table) columnWidth(fli int) float32 {
if fli < 0 || fli >= len(tb.visibleFields) {
return 0
}
return tb.ColumnWidths[tb.visibleFields[fli].Name]
}
// ColumnWidthDots returns the width of the given column in dots,
// or 0 if it is automatic (see [ColumnWidther]).
func (tb *Table) ColumnWidthDots(col int) float32 {
return tb.columnWidth(col) * tb.Styles.UnitContext.Dots(units.UnitDp)
}
// columnCell returns the widget of the first row in the column of the
// given visible field, or nil if there is none.
func (tb *Table) columnCell(fli int) *WidgetBase {
_, idxOff := tb.This.(Lister).RowWidgetNs()
if tb.ListGrid == nil || idxOff+fli >= tb.ListGrid.NumChildren() {
return nil
}
return AsWidget(tb.ListGrid.Child(idxOff + fli))
}
// columnDots returns the width of the column of the given visible
// field, in dots, without the gap after it.
func (tb *Table) columnDots(fli int) float32 {
if c := tb.columnCell(fli); c != nil {
return c.Geom.Size.Alloc.Total.X
}
return 0
}
// setColumnWidth sets the width of the column of the given visible field
// to the given width in dots, with a minimum of 16 Dp.
func (tb *Table) setColumnWidth(fli int, dots float32) {
c := tb.columnCell(fli)
if c == nil {
return
}
if tb.ColumnWidths == nil {
tb.ColumnWidths = map[string]float32{}
}
tb.ColumnWidths[tb.visibleFields[fli].Name] = max(dots/tb.Styles.UnitContext.Dots(units.UnitDp), 16)
tb.Restyle()
tb.NeedsLayout()
}
// RowWidgetNs returns number of widgets per row and offset for index label
func (tb *Table) RowWidgetNs() (nWidgPerRow, idxOff int) {
nWidgPerRow = 1 + tb.numVisibleFields
idxOff = 1
if !tb.ShowIndexes {
nWidgPerRow -= 1
idxOff = 0
}
if tb.rowButton != nil {
nWidgPerRow++
}
return
}
// valueChanger is a [Lister] that updates after the value of a cell in
// the given row is changed by the user, before its change event is sent.
type valueChanger interface {
valueChanged(row int)
}
func (tb *Table) MakeRow(p *tree.Plan, i int) {
svi := tb.This.(Lister)
si, _, invis := svi.SliceIndex(i)
itxt := strconv.Itoa(i)
if tb.ShowIndexes {
tb.MakeGridIndex(p, i, si, itxt, invis)
}
for fli := range tb.numVisibleFields {
tb.makeFieldValue(p, i, fli)
}
tb.makeRowButton(p, i)
}
// valueHider is implemented by tables such as [TreeTable] that do not show
// some of their values, which have empty frames in their place.
type valueHider interface {
// hideValue returns whether to hide the value of the given visible
// field at the given slice index.
hideValue(si, fli int) bool
}
// makeFieldValue adds the value widget for the given visible field
// at the given widget row index to the given plan.
func (tb *Table) makeFieldValue(p *tree.Plan, i, fli int) {
svi := tb.This.(Lister)
si, _, _ := svi.SliceIndex(i)
itxt := strconv.Itoa(i)
val := tb.sliceElementValue(si)
valPtr := reflectx.UnderlyingPointer(val).Interface()
field := tb.visibleFields[fli]
uvp := reflectx.UnderlyingPointer(val.FieldByIndex(field.Index))
uv := uvp.Elem()
valnm := fmt.Sprintf("value-%d-%s-%s", fli, itxt, reflectx.ShortTypeName(field.Type))
tags := field.Tag
if uv.Kind() == reflect.Slice || uv.Kind() == reflect.Map {
// after the field's own tags, which are kept and take precedence
ni := reflect.StructTag(`display:"no-inline" new-window:"+"`)
if tags == "" {
tags = ni
} else {
tags += " " + ni
}
}
readOnlyTag := tags.Get("edit") == "-"
if vh, ok := tb.This.(valueHider); ok {
if si, _, invis := svi.SliceIndex(i); !invis && vh.hideValue(si, fli) {
// an empty frame in its cell, with its name, so that the value
// is made again for another item in the row
tree.AddAt(p, "hidden-"+valnm, func(w *Frame) {
w.SetProperty(ListRowProperty, i)
w.SetProperty(ListColProperty, fli)
})
return
}
}
tree.AddNew(p, valnm, func() Value {
return NewFieldValue(field.Name, valPtr, uvp.Interface(), tags)
}, func(w Value) {
wb := w.AsWidget()
tb.MakeValue(w, i)
w.AsTree().SetProperty(ListColProperty, fli)
if !tb.IsReadOnly() && !readOnlyTag {
wb.OnChange(func(e events.Event) {
tb.This.(Lister).UpdateMaxWidths()
if vc, ok := tb.This.(valueChanger); ok {
vc.valueChanged(i)
}
tb.SendChange()
})
}
wb.Updater(func() {
si, vi, invis := svi.SliceIndex(i)
val := tb.sliceElementValue(vi)
upv := reflectx.UnderlyingPointer(val.FieldByIndex(field.Index))
Bind(upv.Interface(), w)
vc := tb.ValueTitle + "[" + strconv.Itoa(si) + "]"
if !invis {
if lblr, ok := tb.Slice.(labels.SliceLabeler); ok {
slbl := lblr.ElemLabel(si)
if slbl != "" {
vc = joinValueTitle(tb.ValueTitle, slbl)
}
}
}
wb.ValueTitle = vc + " (" + wb.ValueTitle + ")"
wb.SetReadOnly(tb.IsReadOnly() || readOnlyTag)
wb.SetState(invis, states.Invisible)
if svi.HasStyler() {
w.Style()
}
if invis {
wb.SetSelected(false)
}
})
})
}
func (tb *Table) HasStyler() bool {
return tb.TableStyler != nil
}
func (tb *Table) StyleRow(w Widget, idx, fidx int) {
if tb.TableStyler != nil {
tb.TableStyler(w, &w.AsWidget().Styles, idx, fidx)
}
}
// NewAt inserts a new blank element at the given index in the slice.
// -1 indicates to insert the element at the end.
func (tb *Table) NewAt(idx int) {
tb.NewAtSelect(idx)
reflectx.SliceNewAt(tb.Slice, idx)
if idx < 0 {
idx = tb.SliceSize
}
tb.This.(Lister).UpdateSliceSize()
tb.SelectIndexEvent(idx, events.SelectOne)
tb.UpdateChange()
tb.IndexGrabFocus(idx)
}
// DeleteAt deletes the element at the given index from the slice.
func (tb *Table) DeleteAt(idx int) {
if idx < 0 || idx >= tb.SliceSize {
return
}
tb.DeleteAtSelect(idx)
reflectx.SliceDeleteAt(tb.Slice, idx)
tb.This.(Lister).UpdateSliceSize()
tb.UpdateChange()
}
// SortSlice sorts the slice according to current settings.
func (tb *Table) SortSlice() {
if tb.sortIndex < 0 || tb.sortIndex >= len(tb.visibleFields) {
return
}
field := tb.visibleFields[tb.sortIndex]
if tb.SortFunc != nil && tb.SortFunc(field.Name, tb.sortDescending) {
return
}
reflectx.StructSliceSort(tb.Slice, field.Index, reflectx.SortOrder(!tb.sortDescending))
}
// SortColumn sorts the slice for the given field index.
// It toggles between ascending and descending if already
// sorting on this field. It sends a change event if the
// table is not read-only, as the slice is reordered.
func (tb *Table) SortColumn(fieldIndex int) {
sgh := tb.header
_, idxOff := tb.RowWidgetNs()
for fli := range tb.numVisibleFields {
hdr := sgh.Child(idxOff + 2*fli).(*Button) // with the handles after them
hdr.SetType(ButtonAction)
if fli == fieldIndex {
if tb.sortIndex == fli {
tb.sortDescending = !tb.sortDescending
} else {
tb.sortDescending = false
}
}
}
tb.sortIndex = fieldIndex
tb.SortSlice()
if tb.OnSort != nil && fieldIndex >= 0 && fieldIndex < len(tb.visibleFields) {
// (before it is updated, which can be for the new sort order)
tb.OnSort(tb.visibleFields[fieldIndex].Name, tb.sortDescending)
}
tb.Update()
if !tb.IsReadOnly() {
tb.SendChange()
}
}
// SortFieldName returns the name of the field being sorted, along with :up or
// :down depending on ascending or descending sorting, or "" if none is.
func (tb *Table) SortFieldName() string {
if tb.sortIndex >= 0 && tb.sortIndex < tb.numVisibleFields {
nm := tb.visibleFields[tb.sortIndex].Name
if tb.sortDescending {
nm += ":down"
} else {
nm += ":up"
}
return nm
}
return ""
}
// SetSortFieldName sets sorting to happen on given field and direction,
// as from [Table.SortFieldName], with no sorting for "" or a field that
// it does not have.
func (tb *Table) SetSortFieldName(nm string) {
tb.sortIndex = -1
if nm == "" {
return
}
spnm := strings.Split(nm, ":")
got := false
for fli := range tb.numVisibleFields {
fld := tb.visibleFields[fli]
if fld.Name == spnm[0] {
got = true
// fmt.Println("sorting on:", fld.Name, fli, "from:", nm)
tb.sortIndex = fli
}
}
if len(spnm) == 2 {
if spnm[1] == "down" {
tb.sortDescending = true
} else {
tb.sortDescending = false
}
}
if got {
tb.SortSlice()
}
}
// RowGrabFocus grabs the focus for the first focusable widget in given row;
// returns that element or nil if not successful. Note: grid must have
// already rendered for focus to be grabbed!
func (tb *Table) RowGrabFocus(row int) *WidgetBase {
if !tb.IsRowInBounds(row) || tb.InFocusGrab { // range check
return nil
}
nWidgPerRow, idxOff := tb.RowWidgetNs()
ridx := nWidgPerRow * row
lg := tb.ListGrid
// first check if we already have focus
for fli := range tb.numVisibleFields {
w := lg.Child(ridx + idxOff + fli).(Widget).AsWidget()
if w.StateIs(states.Focused) || w.ContainsFocus() {
return w
}
}
tb.InFocusGrab = true
defer func() { tb.InFocusGrab = false }()
for fli := range tb.numVisibleFields {
w := lg.Child(ridx + idxOff + fli).(Widget).AsWidget()
if w.CanFocus() {
w.SetFocus()
return w
}
}
return nil
}
// selectFieldValue sets SelectedField and SelectedValue and attempts to find
// corresponding row, setting SelectedIndex and selecting row if found; returns
// true if found, false otherwise.
func (tb *Table) selectFieldValue(fld, val string) bool {
tb.SelectedField = fld
tb.SelectedValue = val
if tb.SelectedField != "" && tb.SelectedValue != nil {
idx, _ := structSliceIndexByValue(tb.Slice, tb.SelectedField, tb.SelectedValue)
if idx >= 0 {
tb.ScrollToIndex(idx)
tb.updateSelectIndex(idx, true, events.SelectOne)
return true
}
}
return false
}
// structSliceIndexByValue searches for first index that contains given value in field of
// given name.
func structSliceIndexByValue(structSlice any, fieldName string, fieldValue any) (int, error) {
svnp := reflectx.NonPointerValue(reflect.ValueOf(structSlice))
sz := svnp.Len()
struTyp := reflectx.NonPointerType(reflect.TypeOf(structSlice).Elem().Elem())
fld, ok := struTyp.FieldByName(fieldName)
if !ok {
err := fmt.Errorf("StructSliceRowByValue: field name: %v not found", fieldName)
slog.Error(err.Error())
return -1, err
}
fldIndex := fld.Index
for idx := range sz {
rval := reflectx.UnderlyingPointer(svnp.Index(idx))
fval := rval.Elem().FieldByIndex(fldIndex)
if !fval.IsValid() {
continue
}
if fval.Interface() == fieldValue {
return idx, nil
}
}
return -1, nil
}
func (tb *Table) editIndex(idx int) {
if idx < 0 || idx >= tb.sliceUnderlying.Len() {
return
}
val := reflectx.UnderlyingPointer(tb.sliceUnderlying.Index(idx))
stru := val.Interface()
tynm := reflectx.NonPointerType(val.Type()).Name()
lbl := labels.ToLabel(stru)
if lbl != "" {
tynm += ": " + lbl
}
d := NewBody(tynm)
NewForm(d).SetStruct(stru).SetReadOnly(tb.IsReadOnly())
d.AddBottomBar(func(bar *Frame) {
d.AddCancel(bar)
d.AddOK(bar)
})
d.RunWindowDialog(tb)
}
func (tb *Table) contextMenu(m *Scene, pos image.Point) {
e := NewButton(m)
if tb.IsReadOnly() {
e.SetText("View").SetIcon(icons.Visibility)
} else {
e.SetText("Edit").SetIcon(icons.Edit)
}
e.OnClick(func(e events.Event) {
tb.editIndex(tb.SelectedIndex)
})
}
// Header layout:
func (tb *Table) SizeFinal() {
tb.ListBase.SizeFinal()
sg := tb.ListGrid
if sg == nil {
return
}
sh := tb.header
// the header of each column, with the handle after it, has the width
// of the column, with the gap after it, as the header has no gaps;
// without rows, the cells are invisible, without widths, so the header
// keeps its own, of the names of the fields
_, idxOff := tb.This.(Lister).RowWidgetNs()
if sh == nil || tb.SliceSize == 0 || sh.NumChildren() != idxOff+2*tb.numVisibleFields || sg.NumChildren() < idxOff+tb.numVisibleFields {
return
}
gap := sg.Styles.Gap.X.Dots
setWidth := func(w *WidgetBase, width float32) {
ksz := &w.Geom.Size
d := width - ksz.Actual.Total.X
ksz.Actual.Total.X += d
ksz.Actual.Content.X += d
ksz.Alloc.Total.X = ksz.Actual.Total.X
ksz.Alloc.Content.X = ksz.Actual.Content.X
}
colWidth := func(i int) float32 {
return AsWidget(sg.Child(i)).Geom.Size.Alloc.Total.X + gap
}
if idxOff > 0 {
setWidth(AsWidget(sh.Child(0)), colWidth(0))
}
for fli := range tb.numVisibleFields {
hi := idxOff + 2*fli
handle := AsWidget(sh.Child(hi + 1)).Geom.Size.Actual.Total.X
setWidth(AsWidget(sh.Child(hi)), colWidth(idxOff+fli)-handle)
}
gsz := &sg.Geom.Size
ksz := &sh.Geom.Size
ksz.Actual.Total.X = gsz.Actual.Total.X
ksz.Actual.Content.X = gsz.Actual.Content.X
ksz.Alloc.Total.X = gsz.Alloc.Total.X
ksz.Alloc.Content.X = gsz.Alloc.Content.X
}
//////// Search interface
// TextRunes returns any text content associated with the widget, to be used
// for Search for example. If this is nil, then it is excluded from search.
func (tb *Table) TextRunes() []rune {
return nil
}
// Search returns text search results for this widget, searching for
// the find string with given case sensitivity. It is up to each widget
// to define the meaning of the Region line, char values for the matches.
// The bool return value indicates whether this widget handled the search,
// thereby excluding further searching within the elements under it.
func (tb *Table) Search(find string, useCase CaseSensitive) ([]textpos.Match, bool) {
var results []textpos.Match
for rw := range tb.SliceSize {
val := tb.sliceElementValue(rw)
for fli := range tb.numVisibleFields {
field := tb.visibleFields[fli]
fval := val.FieldByIndex(field.Index)
if fval.Type() == reflect.TypeFor[icons.Icon]() {
continue
}
str := reflectx.ToString(fval.Interface())
m := SearchRunes([]rune(str), find, useCase)
if len(m) == 0 {
continue
}
ln := rw*tb.numVisibleFields + fli
for i := range m {
m[i].Region.Start.Line = ln
m[i].Region.End.Line = ln
}
results = append(results, m...)
}
}
return results, true
}
// HighlightMatches does highlighting of the given matches within this widget,
// where the matches are as returned from the Search method.
// Passing a nil causes matches to be reset.
// Any existing highlighting should always be reset first regardless.
// The bool return value indicates whether this widget handled the search,
// thereby excluding further searching within the elements under it.
func (tb *Table) HighlightMatches(matches []textpos.Match) bool {
nWidgPerRow, idxOff := tb.RowWidgetNs()
lg := tb.ListGrid
for i := range tb.VisibleRows {
ridx := nWidgPerRow * i
for fli := range tb.numVisibleFields {
w := lg.Child(ridx + idxOff + fli).(Widget)
w.SelectMatch(matches, 0, SelectNoScroll, SelectReset)
w.HighlightMatches(nil) // reset
}
}
if matches == nil {
return true
}
for _, m := range matches {
ln := m.Region.Start.Line
rw := ln / tb.numVisibleFields
if rw < tb.StartIndex || rw >= tb.StartIndex+tb.VisibleRows {
continue
}
ridx := nWidgPerRow * (rw - tb.StartIndex)
fli := ln % tb.numVisibleFields
w := lg.Child(ridx + idxOff + fli).(Widget)
w.HighlightMatches([]textpos.Match{m})
}
return true
}
// SelectMatch selects match at given index from among those returned
// from the Search method. scroll = scroll widget into view.
// reset = clear selection instead of selecting.
func (tb *Table) SelectMatch(matches []textpos.Match, index int, scroll SelectionScroll, reset SelectionReset) {
nWidgPerRow, idxOff := tb.RowWidgetNs()
match := matches[index]
lg := tb.ListGrid
ln := match.Region.Start.Line
rw := ln / tb.numVisibleFields
if rw < tb.StartIndex || rw >= tb.StartIndex+tb.VisibleRows {
if reset == SelectReset || scroll == SelectNoScroll {
return
}
tb.ScrollToIndex(rw)
tb.HighlightMatches(matches)
}
if rw < tb.StartIndex || rw >= tb.StartIndex+tb.VisibleRows { // shouldn't happen
return
}
ridx := nWidgPerRow * (rw - tb.StartIndex)
fli := ln % tb.numVisibleFields
w := lg.Child(ridx + idxOff + fli).(Widget)
w.SelectMatch(matches, index, SelectNoScroll, reset)
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"log/slog"
"sync"
"cogentcore.org/core/base/elide"
"cogentcore.org/core/colors"
"cogentcore.org/core/cursors"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/keymap"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/tree"
)
// Tabber is an interface for getting the parent Tabs of tab buttons.
type Tabber interface {
// AsCoreTabs returns the underlying Tabs implementation.
AsCoreTabs() *Tabs
}
// Tabs divide widgets into logical groups and give users the ability
// to freely navigate between them using tab buttons.
type Tabs struct {
Frame
// Type is the styling type of the tabs. If it is changed after
// the tabs are first configured, Update needs to be called on
// the tabs.
Type TabTypes
// NewTabButton is whether to show a new tab button at the end of the list of tabs.
NewTabButton bool
// NewTabFunc is a function that will be called when the NewTabButton
// is clicked to create a new tab, with the index of this new tab.
// This can be used to update the new tab contents.
NewTabFunc func(index int)
// CloseTabFunc is a function that will be called when a tab is closed.
// with the index of the tab that was closed.
// This can be used to manage any additional resources associated with the tab.
CloseTabFunc func(index int)
// maxChars is the maximum number of characters to include in the tab text.
// It elides text that are longer than that.
maxChars int
// CloseIcon is the icon used for tab close buttons.
// If it is "" or [icons.None], the tab is not closeable.
// The default value is [icons.Close].
// Only [FunctionalTabs] can be closed; all other types of
// tabs will not render a close button and can not be closed.
CloseIcon icons.Icon
// DragToWindow, if set, makes a tab of [FunctionalTabs] that is
// dragged out of its window move into a new window, which then moves
// with the mouse until the drag ends, on desktop platforms, as in web
// browsers. It is called with the body of the new window, which it
// initializes as any new window of the app (as a new browser window),
// and returns the tabs in it that the tab is moved into (at their end),
// or nil to not move it. The last tab is not moved. Tabs of
// [FunctionalTabs] can always be dragged to other places in their
// tabs, and to other tabs of [FunctionalTabs] in the same window.
// See also [Tabs.MoveTabFunc].
DragToWindow func(b *Body) *Tabs
// MoveTabFunc is a function that is called when a tab has been moved
// from the given index, by dragging it or by [Tabs.MoveTabIndex], to
// the given index in the given tabs: these tabs, or other tabs (as
// those of a new window, for [Tabs.DragToWindow]). It can be used to
// keep any additional resources associated with the tabs in their order,
// and to move them to those of the other tabs.
MoveTabFunc func(from int, to *Tabs, at int)
// MoveInFunc is a function that is called when a tab of other tabs
// has been moved into these tabs, at the given index, as by dragging it
// from another window (after [Tabs.MoveTabFunc] of the other tabs). It
// can be used to take on any additional resources associated with the
// tab, which are in its content.
MoveInFunc func(index int)
// mu is a mutex protecting updates to tabs. Tabs can be driven
// programmatically and via user input so need extra protection.
mu sync.Mutex
tabs, frame *Frame
// lastFocus has the widgets that last had the focus in the frames of
// the tabs, when other tabs were selected with the keys for them,
// which get it back when their tabs are selected again with the keys.
lastFocus map[*Frame]Widget
}
// TabTypes are the different styling types of tabs.
type TabTypes int32 //enums:enum
const (
// StandardTabs indicates to render the standard type
// of Material Design style tabs.
StandardTabs TabTypes = iota
// FunctionalTabs indicates to render functional tabs
// like those in Google Chrome. These tabs take up less
// space and are the only kind that can be closed, and they
// can be dragged to new positions (see also [Tabs.DragToWindow]).
FunctionalTabs
// NavigationAuto indicates to render the tabs as either
// [NavigationBar] or [NavigationDrawer] if
// [WidgetBase.SizeClass] is [SizeCompact] or not, respectively.
// NavigationAuto should typically be used instead of one of the
// specific navigation types for better cross-platform compatability.
NavigationAuto
// NavigationBar indicates to render the tabs as a
// bottom navigation bar with text and icons.
NavigationBar
// NavigationDrawer indicates to render the tabs as a
// side navigation drawer with text and icons.
NavigationDrawer
)
// effective returns the effective tab type in the context
// of the given widget, handling [NavigationAuto] based on
// [WidgetBase.SizeClass].
func (tt TabTypes) effective(w Widget) TabTypes {
if tt != NavigationAuto {
return tt
}
switch w.AsWidget().SizeClass() {
case SizeCompact:
return NavigationBar
default:
return NavigationDrawer
}
}
// isColumn returns whether the tabs should be arranged in a column.
func (tt TabTypes) isColumn() bool {
return tt == NavigationDrawer
}
func (ts *Tabs) AsCoreTabs() *Tabs { return ts }
func (ts *Tabs) Init() {
ts.Frame.Init()
ts.maxChars = 16
ts.CloseIcon = icons.Close
ts.Styler(func(s *styles.Style) {
s.Color = colors.Scheme.OnSurface
s.Grow.Set(1, 1)
if ts.Type.effective(ts).isColumn() {
s.Direction = styles.Row
} else {
s.Direction = styles.Column
}
})
// The keys for the next and previous tabs ([keymap.NextTab] and
// [keymap.PrevTab]) select them when no widget in the tabs handles them,
// or the tabs have the focus themselves, which a press in them gives
// them, quietly, when no widget in them has the focus (as in a tab
// whose content is not focusable).
ts.On(events.KeyChord, ts.handleTabKeys)
ts.OnFinal(events.KeyChord, ts.handleTabKeys)
ts.On(events.MouseDown, func(e events.Event) {
if em := ts.Events(); em != nil && !ts.ContainsFocus() {
em.setFocusQuiet(ts.This.(Widget))
}
})
ts.Maker(func(p *tree.Plan) {
tree.AddAt(p, "tabs", func(w *Frame) {
ts.tabs = w
w.Styler(func(s *styles.Style) {
s.Overflow.Set(styles.OverflowHidden) // no scrollbars!
s.Gap.Set(units.Dp(4))
if ts.Type.effective(ts).isColumn() {
s.Direction = styles.Column
s.Grow.Set(0, 1)
} else {
s.Direction = styles.Row
s.Grow.Set(1, 0)
s.Wrap = true
}
})
ts.initStripDrop(w)
w.Updater(func() {
if !ts.NewTabButton {
w.DeleteChildByName("new-tab-button")
return
}
if w.ChildByName("new-tab-button") != nil {
return
}
ntb := NewButton(w).SetType(ButtonAction).SetIcon(icons.Add)
ntb.SetTooltip("Add a new tab").SetName("new-tab-button")
ntb.OnClick(func(e events.Event) {
ts.NewTab("New tab")
idx := ts.NumTabs() - 1
if ts.NewTabFunc != nil {
ts.NewTabFunc(idx)
}
ts.SelectTabIndex(idx)
})
})
})
tree.AddAt(p, "frame", func(w *Frame) {
ts.frame = w
w.LayoutStackTopOnly = true // key for allowing each tab to have its own size
w.Styler(func(s *styles.Style) {
s.Display = styles.Stacked
s.Min.Set(units.Dp(160), units.Dp(96))
s.Grow.Set(1, 1)
})
})
// frame comes before tabs in bottom navigation bar
if ts.Type.effective(ts) == NavigationBar {
p.Children[0], p.Children[1] = p.Children[1], p.Children[0]
}
})
}
// NumTabs returns the number of tabs.
func (ts *Tabs) NumTabs() int {
fr := ts.getFrame()
if fr == nil {
return 0
}
return len(fr.Children)
}
// CurrentTab returns currently selected tab and its index; returns nil if none.
func (ts *Tabs) CurrentTab() (Widget, int) {
if ts.NumTabs() == 0 {
return nil, -1
}
ts.mu.Lock()
defer ts.mu.Unlock()
fr := ts.getFrame()
if fr.StackTop < 0 {
return nil, -1
}
w := fr.Child(fr.StackTop).(Widget)
return w, fr.StackTop
}
// NewTab adds a new tab with the given label and returns the resulting tab frame
// and associated tab button, which can be further customized as needed.
// It is the main end-user API for creating new tabs.
func (ts *Tabs) NewTab(label string) (*Frame, *Tab) {
fr := ts.getFrame()
idx := len(fr.Children)
return ts.insertTab(label, idx, nil)
}
// NewLazyTab adds a new tab with the given label whose content is made
// by the given function when the tab is first shown, and returns the
// tab frame and button as [Tabs.NewTab] does. The content of the selected
// tab is made right away. This saves the time of making and styling the
// content of tabs that are not shown, such as at the startup of an app;
// once a tab has been shown, it is the same as a tab made with [Tabs.NewTab]
// and filled with the same function.
func (ts *Tabs) NewLazyTab(label string, build func(tab *Frame)) (*Frame, *Tab) {
fr := ts.getFrame()
return ts.insertTab(label, len(fr.Children), build)
}
// insertTab inserts a new tab with the given label at the given index position
// within the list of tabs and returns the resulting tab frame and button.
// If build is non-nil, it makes the content of the tab when the tab is first
// updated: updates skip the content of tabs that are not selected, so that is
// when the tab is first shown.
func (ts *Tabs) insertTab(label string, idx int, build func(tab *Frame)) (*Frame, *Tab) {
tfr := ts.getFrame()
alreadyExists := tfr.ChildByName(label) != nil
frame := NewFrame()
tfr.InsertChild(frame, idx)
frame.SetName(label)
frame.Styler(func(s *styles.Style) {
// tab frames must scroll independently and grow
s.Overflow.Set(styles.OverflowAuto)
s.Grow.Set(1, 1)
s.Direction = styles.Column
})
if build != nil {
built := false
frame.FirstUpdater(func() {
if !built {
built = true
build(frame)
}
})
}
button := ts.insertTabButtonAt(label, idx)
if alreadyExists {
tree.SetUniqueName(frame) // prevent duplicate names
button.SetName(frame.Name) // must be the same name
}
ts.Update()
return frame, button
}
// insertTabButtonAt inserts just the tab button at given index, after the panel has
// already been added to the frame; assumed to be wrapped in update. Generally
// for internal use only.
func (ts *Tabs) insertTabButtonAt(label string, idx int) *Tab {
tb := ts.getTabs()
tab := tree.New[Tab]()
tb.InsertChild(tab, idx)
tab.SetName(label)
tab.SetText(label).SetType(ts.Type).SetCloseIcon(ts.CloseIcon).SetTooltip(label)
tab.maxChars = ts.maxChars
tab.OnClick(func(e events.Event) {
// (by its index, as another tab can have the same name)
if idx := tab.IndexInParent(); idx >= 0 {
ts.SelectTabIndex(idx)
}
})
fr := ts.getFrame()
if len(fr.Children) == 1 {
fr.StackTop = 0
tab.SetSelected(true)
// } else {
// frame.SetState(true, states.Invisible) // new tab is invisible until selected
}
return tab
}
// TabAtIndex returns content frame and tab button at given index, nil if
// index out of range (emits log message).
func (ts *Tabs) TabAtIndex(idx int) (*Frame, *Tab) {
ts.mu.Lock()
defer ts.mu.Unlock()
fr := ts.getFrame()
tb := ts.getTabs()
sz := len(fr.Children)
if idx < 0 || idx >= sz {
slog.Error("Tabs: index out of range for number of tabs", "index", idx, "numTabs", sz)
return nil, nil
}
tab := tb.Child(idx).(*Tab)
frame := fr.Child(idx).(*Frame)
return frame, tab
}
// SelectTabIndex selects the tab at the given index, returning it or nil.
// This is the final tab selection path.
func (ts *Tabs) SelectTabIndex(idx int) *Frame {
frame, tab := ts.TabAtIndex(idx)
if frame == nil {
return nil
}
fr := ts.getFrame()
if fr.StackTop == idx {
return frame
}
ts.mu.Lock()
ts.unselectOtherTabs(idx)
tab.SetSelected(true)
fr.StackTop = idx
ts.mu.Unlock()
fr.Update()
frame.DeferShown()
return frame
}
// TabByName returns the tab [Frame] with the given widget name
// (nil if not found). The widget name is the original full tab label,
// prior to any eliding.
func (ts *Tabs) TabByName(name string) *Frame {
ts.mu.Lock()
defer ts.mu.Unlock()
fr := ts.getFrame()
frame, _ := fr.ChildByName(name).(*Frame)
return frame
}
// tabIndexByName returns the tab index for the given tab widget name
// and -1 if it can not be found.
// The widget name is the original full tab label, prior to any eliding.
func (ts *Tabs) tabIndexByName(name string) int {
ts.mu.Lock()
defer ts.mu.Unlock()
tb := ts.getTabs()
tab := tb.ChildByName(name)
if tab == nil {
return -1
}
return tab.AsTree().IndexInParent()
}
// SelectTabByName selects the tab by widget name, returning it.
// The widget name is the original full tab label, prior to any eliding.
func (ts *Tabs) SelectTabByName(name string) *Frame {
idx := ts.tabIndexByName(name)
if idx < 0 {
return nil
}
ts.SelectTabIndex(idx)
fr := ts.getFrame()
return fr.Child(idx).(*Frame)
}
// RecycleTab returns a tab with the given name, first by looking for an existing one,
// and if not found, making a new one. It returns the frame for the tab.
func (ts *Tabs) RecycleTab(name string) *Frame {
frame := ts.TabByName(name)
if frame == nil {
frame, _ = ts.NewTab(name)
}
ts.SelectTabByName(name)
return frame
}
// RecycleTabWidget returns a tab with the given widget type in the tab frame,
// first by looking for an existing one with the given name, and if not found,
// making and configuring a new one. It returns the resulting widget.
func RecycleTabWidget[T tree.NodeValue](ts *Tabs, name string) *T {
fr := ts.RecycleTab(name)
if fr.HasChildren() {
return any(fr.Child(0)).(*T)
}
w := tree.New[T](fr)
any(w).(Widget).AsWidget().UpdateWidget()
return w
}
// DeleteTabIndex deletes the tab at the given index, returning whether it was successful.
func (ts *Tabs) DeleteTabIndex(idx int) bool {
frame, _ := ts.TabAtIndex(idx)
if frame == nil {
return false
}
ts.mu.Lock()
fr := ts.getFrame()
sz := len(fr.Children)
tb := ts.getTabs()
// the tab to select after the deletion, by its index after it
nidx := -1
cur := fr.StackTop
switch {
case cur == idx: // the one before it, or the next one for the first
if idx > 0 {
nidx = idx - 1
} else if idx < sz-1 {
nidx = idx
}
case cur > idx: // the current tab, which moves down by one
nidx = cur - 1
case cur >= 0: // the current tab, which stays where it is
nidx = cur
case sz > 1: // no current tab: one next to the deleted one
nidx = max(idx-1, 0)
}
fr.DeleteChildAt(idx)
tb.DeleteChildAt(idx)
ts.mu.Unlock()
if nidx >= 0 {
ts.SelectTabIndex(nidx)
}
ts.NeedsLayout()
if ts.CloseTabFunc != nil {
ts.CloseTabFunc(idx)
}
return true
}
// getTabs returns the [Frame] containing the tabs (the first element within us).
// It configures the [Tabs] if necessary.
func (ts *Tabs) getTabs() *Frame {
if ts.tabs == nil {
ts.UpdateWidget()
}
return ts.tabs
}
// Frame returns the stacked [Frame] (the second element within us).
// It configures the Tabs if necessary.
func (ts *Tabs) getFrame() *Frame {
if ts.frame == nil {
ts.UpdateWidget()
}
return ts.frame
}
// unselectOtherTabs turns off all the tabs except given one
func (ts *Tabs) unselectOtherTabs(idx int) {
sz := ts.NumTabs()
tbs := ts.getTabs()
for i := range sz {
if i == idx {
continue
}
tb := tbs.Child(i).(*Tab)
if tb.StateIs(states.Selected) {
tb.SetSelected(false)
}
}
}
// Tab is a tab button that contains one or more of a label, an icon,
// and a close icon. Tabs should be made using the [Tabs.NewTab] function.
type Tab struct { //core:no-new
Frame
// Type is the styling type of the tab. This property
// must be set on the parent [Tabs] for it to work correctly.
Type TabTypes
// Text is the text for the tab. If it is blank, no text is shown.
// Text is never shown for [NavigationRail] tabs.
Text string
// Icon is the icon for the tab.
// If it is "" or [icons.None], no icon is shown.
Icon icons.Icon
// CloseIcon is the icon used as a close button for the tab.
// If it is "" or [icons.None], the tab is not closeable.
// The default value is [icons.Close].
// Only [FunctionalTabs] can be closed; all other types of
// tabs will not render a close button and can not be closed.
CloseIcon icons.Icon
// TODO(kai): replace this with general text overflow property (#778)
// maxChars is the maximum number of characters to include in tab text.
// It elides text that is longer than that.
maxChars int
}
func (tb *Tab) Init() {
tb.Frame.Init()
tb.maxChars = 16
tb.CloseIcon = icons.Close
tb.Styler(func(s *styles.Style) {
s.SetAbilities(true, abilities.Activatable, abilities.Focusable, abilities.Hoverable)
if !tb.IsReadOnly() {
s.Cursor = cursors.Pointer
}
if tb.Type.effective(tb).isColumn() {
s.Grow.X = 1
s.Border.Radius = styles.BorderRadiusFull
s.Padding.Set(units.Dp(16))
} else {
s.Border.Radius = styles.BorderRadiusSmall
s.Padding.Set(units.Dp(10))
}
s.Gap.Zero()
s.Align.Content = styles.Center
s.Align.Items = styles.Center
s.Font.Size.Dp(14)
s.IconSize.Set(units.Em(18.0 / 14))
if tb.StateIs(states.Selected) {
s.Color = colors.Scheme.Select.OnContainer
} else {
s.Color = colors.Scheme.OnSurfaceVariant
if tb.Type.effective(tb) == FunctionalTabs {
s.Background = colors.Scheme.SurfaceContainer
}
}
})
tb.SendClickOnEnter()
tb.initDrag()
tb.Maker(func(p *tree.Plan) {
if tb.maxChars > 0 { // TODO: find a better time to do this?
tb.Text = elide.Middle(tb.Text, tb.maxChars)
}
if tb.Icon.IsSet() {
tree.AddAt(p, "icon", func(w *Icon) {
w.Updater(func() {
w.SetIcon(tb.Icon)
})
})
if tb.Text != "" {
tree.AddAt(p, "space", func(w *Space) {})
}
}
if tb.Text != "" {
tree.AddAt(p, "text", func(w *Text) {
w.Styler(func(s *styles.Style) {
s.SetNonSelectable()
s.SetTextWrap(false)
s.FillMargin = false
s.Font.Size = tb.Styles.Font.Size // Directly inherit to override the [Text.Type]-based default
})
w.Updater(func() {
if tb.Type.effective(tb) == FunctionalTabs {
w.SetType(TextBodyMedium)
} else {
w.SetType(TextLabelLarge)
}
w.SetText(tb.Text)
})
})
}
if tb.Type.effective(tb) == FunctionalTabs && tb.CloseIcon.IsSet() {
tree.AddAt(p, "close-space", func(w *Space) {})
tree.AddAt(p, "close", func(w *Button) {
w.SetType(ButtonAction)
w.Styler(func(s *styles.Style) {
s.Padding.Zero()
s.Border.Radius = styles.BorderRadiusFull
})
w.OnClick(func(e events.Event) {
ts := tb.tabs()
idx := ts.tabIndexByName(tb.Name)
// if OnlyCloseActiveTab is on, only process delete when already selected
if AppearanceSettings.OnlyCloseActiveTab && !tb.StateIs(states.Selected) {
ts.SelectTabIndex(idx)
} else {
ts.DeleteTabIndex(idx)
}
})
w.Updater(func() {
w.SetIcon(tb.CloseIcon)
})
})
}
})
}
// tabs returns the parent [Tabs] of this [Tab].
func (tb *Tab) tabs() *Tabs {
if tbr, ok := tb.Parent.AsTree().Parent.(Tabber); ok {
return tbr.AsCoreTabs()
}
return nil
}
func (tb *Tab) Label() string {
if tb.Text != "" {
return tb.Text
}
return tb.Name
}
// TabKeys gives the given key event to the tabs that the given widget is
// in, innermost first, for the keys for the next and previous tabs
// ([keymap.NextTab] and [keymap.PrevTab]), marking it as handled if they
// select a tab. It is for widgets that would otherwise handle these keys
// (as editors, for selecting), but leave them to the tabs, as terminals
// do at their command line.
func TabKeys(w Widget, e events.Event) {
for ts := tree.ParentByType[*Tabs](w); ts != nil && !e.IsHandled(); ts = tree.ParentByType[*Tabs](ts) {
ts.handleTabKeys(e)
}
}
// handleTabKeys selects the next or previous tab, after the last one the
// first, for the keys for them ([keymap.NextTab] and [keymap.PrevTab]), and
// focuses it (see [Tabs.focusTab]). With only one tab, the key is left for
// any tabs that these are in.
func (ts *Tabs) handleTabKeys(e events.Event) {
delta := 0
switch keymap.OfFallback(e.KeyChord()) {
case keymap.NextTab:
delta = 1
case keymap.PrevTab:
delta = -1
default:
return
}
if ts.NumTabs() < 2 {
return
}
e.SetHandled()
ts.SelectTabDelta(delta)
}
// SelectTabDelta selects the tab the given number of tabs after the
// current one (before it if negative), cycling around, and focuses it
// (see [Tabs.focusTab]), as the keys for the next and previous tabs do
// ([keymap.NextTab] and [keymap.PrevTab]).
func (ts *Tabs) SelectTabDelta(delta int) {
n := ts.NumTabs()
if n == 0 {
return
}
cur, idx := ts.CurrentTab()
if fr, ok := cur.(*Frame); ok {
if em := ts.Events(); em != nil && !tree.IsNil(em.focus) && isParentOf(fr, em.focus) {
if ts.lastFocus == nil {
ts.lastFocus = map[*Frame]Widget{}
}
ts.lastFocus[fr] = em.focus
}
}
fr := ts.SelectTabIndex(((idx+delta)%n + n) % n)
if em := ts.Events(); em != nil {
em.setFocusQuiet(ts.This.(Widget)) // (not in the hidden tab)
}
ts.Defer(func() { ts.focusTab(fr) }) // (once it is shown)
}
// focusTab focuses the given selected frame of a tab, once it is shown,
// if the tabs still have the focus, which they get quietly when it is
// selected: the widget that last had the focus in it (see
// [Tabs.lastFocus]), or else its first focusable widget that is shown, or
// else the tabs keep it, so that the keys for the tabs keep working.
func (ts *Tabs) focusTab(fr *Frame) {
em := ts.Events()
if fr == nil || em == nil || em.focus != ts.This.(Widget) {
return // (focused elsewhere since)
}
if w := ts.lastFocus[fr]; w != nil && w.AsTree().This != nil && isParentOf(fr, w) {
w.AsWidget().SetFocus()
return
}
var foc Widget
fr.WidgetWalkDown(func(cw Widget, cwb *WidgetBase) bool {
if foc != nil || !cwb.IsDisplayable() {
return tree.Break
}
if cwb.AbilityIs(abilities.Focusable) && !cwb.StateIs(states.Disabled) {
foc = cw
return tree.Break
}
return tree.Continue
})
if foc != nil {
foc.AsWidget().SetFocus()
}
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"fmt"
"image"
"log/slog"
"slices"
"cogentcore.org/core/base/fileinfo/mimedata"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/tree"
)
// tabMimeType is the MIME type of the data of a tab that is dragged out of
// its window by the operating system (see [Tab.osDragData]), which other
// apps ignore, and which a window of this app drops into its tabs.
const tabMimeType = "application/x-cogentcore-tab"
// MoveTabIndex moves the tab at the given index to the given index (the
// one that it then has), returning whether it was successful. The
// selected tab stays selected.
func (ts *Tabs) MoveTabIndex(from, to int) bool {
ts.mu.Lock()
fr := ts.getFrame()
tb := ts.getTabs()
n := len(fr.Children)
if from < 0 || from >= n || to < 0 || to >= n {
ts.mu.Unlock()
slog.Error("Tabs: index out of range for number of tabs", "from", from, "to", to, "numTabs", n)
return false
}
if from == to {
ts.mu.Unlock()
return true
}
moveChild(fr, from, to)
moveChild(tb, from, to)
switch top := fr.StackTop; {
case top == from:
fr.StackTop = to
case from < top && to >= top:
fr.StackTop--
case from > top && to <= top:
fr.StackTop++
}
ts.mu.Unlock()
ts.NeedsLayout()
if ts.MoveTabFunc != nil {
ts.MoveTabFunc(from, ts, to)
}
return true
}
// moveChild moves the child of the given node at the given index to the
// other given index, without deleting it.
func moveChild(n tree.Node, from, to int) {
nb := n.AsTree()
k := nb.Children[from]
nb.Children = slices.Delete(nb.Children, from, from+1)
nb.Children = slices.Insert(nb.Children, to, k)
}
// MoveTabTo moves the tab at the given index (its content and its button)
// into the given other tabs, at the given index there, where it is
// selected, returning the index that it has there, or -1 if it was not
// moved. The tab next to it is selected in these tabs, as when it is
// deleted, but it is not closed: [Tabs.CloseTabFunc] is not called, and
// [Tabs.MoveTabFunc] of these tabs and [Tabs.MoveInFunc] of the other
// tabs are. The tabs must be in the same window (or one not yet shown).
func (ts *Tabs) MoveTabTo(idx int, other *Tabs, at int) int {
if other == ts || idx < 0 || idx >= ts.NumTabs() {
return -1
}
at = min(max(at, 0), other.NumTabs())
return other.attachTab(ts.detachTab(idx, other, at), at)
}
// detachedTab is a tab that has been removed from its tabs, to be added to
// other tabs (see [Tabs.detachTab]).
type detachedTab struct {
frame *Frame
label, text, tooltip string
icon icons.Icon
}
// detachTab removes the tab at the given index, which moves to the given
// index in the given other tabs, keeping its content for them, selects the
// tab next to it, as when it is deleted, and calls [Tabs.MoveTabFunc].
func (ts *Tabs) detachTab(idx int, other *Tabs, at int) *detachedTab {
frame, tab := ts.TabAtIndex(idx)
if frame == nil {
return nil
}
dt := &detachedTab{frame: frame, label: tab.Name, text: tab.Text, tooltip: tab.Tooltip, icon: tab.Icon}
if f := ts.Scene.Events.focus; f != nil && (tree.Node(f) == frame || isParentOf(frame, f)) {
ts.Scene.Events.focusClear() // (not to send events to it here)
}
ts.mu.Lock()
fr := ts.getFrame()
nidx := -1
if len(fr.Children) > 1 {
switch {
case fr.StackTop == idx:
nidx = max(idx-1, 0)
case fr.StackTop > idx:
nidx = fr.StackTop - 1
default:
nidx = fr.StackTop
}
}
ts.getTabs().DeleteChildAt(idx)
fr.Children = slices.Delete(fr.Children, idx, idx+1)
fr.StackTop = -1 // (selected again below)
ts.mu.Unlock()
if nidx >= 0 {
ts.SelectTabIndex(nidx)
}
ts.NeedsLayout()
if ts.MoveTabFunc != nil {
ts.MoveTabFunc(idx, other, at)
}
return dt
}
// attachTab adds the given detached tab at the given index, where it is
// selected, calls [Tabs.MoveInFunc], and returns the index.
func (ts *Tabs) attachTab(dt *detachedTab, at int) int {
if dt == nil {
return -1
}
ts.mu.Lock()
fr := ts.getFrame()
at = min(max(at, 0), len(fr.Children))
// its name is unique in these tabs, whose tabs are found by name
label := dt.label
for n := 2; fr.ChildByName(label) != nil; n++ {
label = fmt.Sprintf("%s-%d", dt.label, n)
}
dt.label = label
dt.frame.SetName(label)
fr.AddChild(dt.frame) // (in the scene of these tabs)
moveChild(fr, len(fr.Children)-1, at)
nt := ts.insertTabButtonAt(dt.label, at)
if dt.text != "" { // (as shown, which may have changed from its label)
nt.SetText(dt.text)
}
nt.SetIcon(dt.icon)
nt.SetTooltip(dt.tooltip)
if len(fr.Children) > 1 && fr.StackTop >= at {
fr.StackTop++ // (it is after the new tab)
}
ts.mu.Unlock()
ts.SelectTabIndex(at)
ts.Update()
if ts.MoveInFunc != nil {
ts.MoveInFunc(at)
}
return at
}
// transferTab moves the tab of the given button of the given tabs to the
// given index in the other given tabs, which may be in another window,
// from the event loop of the given widget. Each window only has its own
// lock, so the tab is removed in the event loop of the window of its tabs,
// and then added in that of the other tabs (see [WidgetBase.runInWindow]).
// A window whose last tab is dragged into another window is closed.
func transferTab(from *WidgetBase, src *Tabs, tab *Tab, dst *Tabs, at int) {
src.runInWindow(from, func() {
idx := tab.IndexInParent()
if idx < 0 || tab.tabs() != src {
return
}
srw, drw := src.Scene.RenderWindow(), dst.Scene.RenderWindow()
if srw == drw {
src.MoveTabTo(idx, dst, at)
return
}
dt := src.detachTab(idx, dst, at)
dst.runInWindow(src.AsWidget(), func() { dst.attachTab(dt, at) })
if src.NumTabs() == 0 && src.DragToWindow != nil {
src.Scene.Close()
}
})
}
// isParentOf returns whether the given node is in the given parent node.
func isParentOf(parent tree.Node, n tree.Node) bool {
for p := n.AsTree().Parent; p != nil; p = p.AsTree().Parent {
if p == parent {
return true
}
}
return false
}
// tabDrag is the data of the drag of a tab.
type tabDrag struct {
// tabs are the tabs of the dragged tab.
tabs *Tabs
// tab is the button of the dragged tab.
tab *Tab
}
// dropAt moves the dragged tab to the given index in the given tabs, into
// which it was dropped: in its own tabs, it moves there (the index that it
// then has), and from other tabs, it is inserted there, also from those
// of another window, as a drag of the operating system.
func (td *tabDrag) dropAt(ts *Tabs, at int) {
if td.tabs == ts {
if from := td.tab.IndexInParent(); from >= 0 {
ts.MoveTabIndex(from, min(at, ts.NumTabs()-1))
}
return
}
if ts.Type.effective(ts) == FunctionalTabs {
transferTab(ts.AsWidget(), td.tabs, td.tab, ts, at)
}
}
// dropIndex returns the index in the tabs at which a tab dropped at the
// given position in the window goes: before the first tab whose middle it
// is before, in the row of tabs that it is in, or that is in a later row
// (as the tabs wrap), or at the end.
func (ts *Tabs) dropIndex(pos image.Point) int {
n := ts.NumTabs()
tb := ts.getTabs()
for i := range n {
bb := AsWidget(tb.Child(i)).Geom.TotalBBox
if pos.Y < bb.Min.Y || pos.Y < bb.Max.Y && pos.X < (bb.Min.X+bb.Max.X)/2 {
return i
}
}
return n
}
// initStripDrop makes the given list of tabs a target of drops of tabs,
// for [FunctionalTabs]: one dropped between tabs goes there, and one
// dropped after them goes to the end (see [Tabs.dropIndex]).
func (ts *Tabs) initStripDrop(w *Frame) {
w.On(events.DragEnter, func(e events.Event) { e.SetHandled() })
w.On(events.DragLeave, func(e events.Event) { e.SetHandled() })
w.On(events.Drop, func(e events.Event) {
td, ok := e.(*events.DragDrop).Data.(*tabDrag)
if !ok {
return
}
e.SetHandled()
td.dropAt(ts, ts.dropIndex(e.Pos()))
})
w.FinalStyler(func(s *styles.Style) {
s.SetAbilities(ts.Type.effective(ts) == FunctionalTabs, abilities.Droppable)
})
}
// initDrag makes the tab draggable, and a target of drops of tabs, for
// [FunctionalTabs].
func (tb *Tab) initDrag() {
tb.FinalStyler(func(s *styles.Style) {
s.SetAbilities(tb.Type.effective(tb) == FunctionalTabs, abilities.Draggable, abilities.Droppable)
})
tb.On(events.DragStart, func(e events.Event) {
ts := tb.tabs()
if ts == nil || !tb.AbilityIs(abilities.Draggable) {
return
}
e.SetHandled()
tb.Scene.Events.DragStart(tb.This.(Widget), &tabDrag{tabs: ts, tab: tb}, e)
})
tb.On(events.DragEnter, func(e events.Event) {
if draggingTab(tb.Scene) {
tb.SetState(true, states.DragHovered)
tb.NeedsRender()
e.SetHandled()
}
})
tb.On(events.DragLeave, func(e events.Event) {
tb.SetState(false, states.DragHovered)
tb.NeedsRender()
e.SetHandled()
})
tb.On(events.Drop, func(e events.Event) {
td, ok := e.(*events.DragDrop).Data.(*tabDrag)
ts := tb.tabs()
if !ok || ts == nil {
return
}
e.SetHandled()
td.dropAt(ts, tb.IndexInParent())
})
}
// draggingTab returns whether a tab is being dragged over the given scene:
// within its window, or from another window of the app, by the operating
// system.
func draggingTab(sc *Scene) bool {
if _, ok := sc.Events.dragData.(*tabDrag); ok {
return true
}
osDrag.Lock()
defer osDrag.Unlock()
_, ok := osDrag.data.(*tabDrag)
return ok
}
// DragMovesDefault returns that a drag of a tab moves it (see [DragMover]).
func (tb *Tab) DragMovesDefault() bool { return true }
// osDragData returns the data of a drag of a tab of tabs with
// [Tabs.DragToWindow] that leaves its window, which the operating system
// then drags (see [osDragger]), to be dropped into the tabs of another
// window of the app, or into a new window where nothing accepts it (see
// [Tab.droppedNowhere]), and nil for other tabs.
func (tb *Tab) osDragData() mimedata.Mimes {
ts := tb.tabs()
if ts == nil || ts.DragToWindow == nil || ts.Type.effective(ts) != FunctionalTabs {
return nil
}
return mimedata.Mimes{{Type: tabMimeType, Data: []byte(tb.Name)}}
}
// droppedNowhere moves the tab into a new window when it was dragged out of
// its window by the operating system and dropped where nothing accepted it
// (as onto the desktop), at the given position on the screen, with its tab
// under the drop, as in web browsers (see [osDropper]). The window of a last
// tab moves there instead.
func (tb *Tab) droppedNowhere(e events.Event, screen image.Point) {
ts := tb.tabs()
if ts == nil || ts.DragToWindow == nil {
return
}
src := ts.Scene.RenderWindow()
idx := tb.IndexInParent()
if src == nil || src.SystemWindow == nil || idx < 0 {
return
}
dpr := screenPixelRatio(src.SystemWindow)
if ts.NumTabs() == 1 {
// the place of the press in the window goes to the drop
src.SystemWindow.SetPos(screen.Sub(scalePoint(e.StartPos(), 1/dpr)), nil)
return
}
// the place of the press in the tab, which goes to the drop, as in the
// new window (initialized as this one) the tabs start where they do here
in := e.StartPos().Sub(tb.Geom.TotalBBox.Min)
start := ts.getTabs().Geom.TotalBBox.Min
// (moved into the new tabs before their window runs)
// (titled as the tab is shown, not by its name, which is unique, as
// "New tab-4" for a tab of a web browser that was new)
title := tb.Text
if title == "" {
title = tb.Name
}
bd := NewBody(title)
nt := ts.DragToWindow(bd)
if nt == nil {
return
}
if nt.DragToWindow == nil { // (so that it closes when its tab is dragged away)
nt.DragToWindow = ts.DragToWindow
}
if ts.MoveTabTo(idx, nt, nt.NumTabs()) < 0 {
return
}
bd.RunWindow()
if win := bd.Scene.RenderWindow(); win != nil && win.SystemWindow != nil {
// of the size of the window of the tabs, as in web browsers
pos := screen.Sub(scalePoint(start.Add(in), 1/dpr))
win.SystemWindow.SetGeometry(false, pos, src.SystemWindow.Size(), nil)
win.SystemWindow.Raise()
}
}
// dropInScene moves the dragged tab, dropped by the operating system where
// nothing in the given scene took it (as onto the content of a page), into
// the first tabs of the scene with [Tabs.DragToWindow], at their end, if
// it is in another window, as in web browsers.
func (td *tabDrag) dropInScene(sc *Scene) {
if td.tabs.Scene.RenderWindow() == sc.RenderWindow() {
return // (back in its own window)
}
var dst *Tabs
for cw := range sc.AllWidgets() {
if ts, ok := cw.(*Tabs); ok && ts.DragToWindow != nil && ts.Type.effective(ts) == FunctionalTabs {
dst = ts
break
}
}
if dst != nil {
td.dropAt(dst, dst.NumTabs())
}
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"cmp"
"fmt"
"image"
"slices"
"strings"
"time"
"cogentcore.org/core/base/iox/imagex"
"cogentcore.org/core/events"
"cogentcore.org/core/events/key"
"cogentcore.org/core/keymap"
)
// AssertRender makes a new window from the given body, waits until it is shown
// and all events have been handled, does any necessary re-rendering,
// asserts that its rendered image is the same as that stored at the given
// filename, saving the image to that filename if it does not already exist,
// and then closes the window. It does not return until all of those steps
// are completed. Each (optional) function passed is called after the
// window is shown, and all system events are handled before proessing continues.
// A testdata directory and png file extension are automatically added to
// the the filename, and forward slashes are automatically replaced with
// backslashes on Windows. On the web, the images are in testdata/js, as
// the browser renders text and paths differently (see [testImageName]).
func AssertRender(t imagex.TestingT, b *Body, filename string, fun ...func()) {
img := RenderImage(b, fun...)
if img == nil {
t.Errorf("AssertRender: the window of %s was closed", filename)
return
}
imagex.Assert(t, img, testImageName(filename))
}
// RenderImage makes a new window from the given body, waits until it is shown
// and all events have been handled, does any necessary re-rendering,
// and returns a copy of its rendered image, closing the window after.
// It is the rendering part of [AssertRender], with the same handling
// of the optional functions, which are called after the window is shown,
// and it is only for offscreen rendering (testing). It returns nil if the
// window was closed before its image could be copied.
func RenderImage(b *Body, fun ...func()) *image.RGBA {
b.runAndShowNewWindow()
rw := b.Scene.RenderWindow()
for i := range fun {
fun[i]()
b.waitNoEvents(rw)
}
if len(fun) == 0 {
// we didn't get it above
b.waitNoEvents(rw)
}
// Ensure that everything is updated and rendered. If there are no changes,
// the performance impact is minimal.
// A render that is still being composed in another goroutine would
// make renderWindow skip its render, so we wait for it first.
for range 10 { // note: 10 is essential for textcore tests
rw.waitRenderDone()
rw.renderWindow()
b.AsyncLock()
rw.mains.runDeferred()
b.AsyncUnlock()
}
rw.waitRenderDone()
img := windowImage(rw)
if img == nil {
return nil
}
// When closing the scene, our access to the render context stops working,
// so using normal AsyncLock and AsyncUnlock will lead to AsyncLock failing.
// That leaves the lock on, which prevents the WinClose event from being
// received. Therefore, we get the rc ahead of time.
rc := b.Scene.renderContext()
rc.Lock()
b.Close()
rc.Unlock()
return img
}
// runAndShowNewWindow runs a new window and waits for it to be shown,
// in an empty window on the web (see [clearTestWindow]).
func (bd *Body) runAndShowNewWindow() {
clearTestWindow()
showed := make(chan struct{})
bd.OnFinal(events.Show, func(e events.Event) {
showed <- struct{}{}
})
bd.RunWindow()
<-showed
}
// waitRenderDone waits until any render of the window that is being
// composed in another goroutine (see [renderWindow.renderAsync]) is done.
func (w *renderWindow) waitRenderDone() {
for w.winRenderCounter.Load() > 0 {
time.Sleep(time.Millisecond)
}
}
// waitNoEvents waits until the event loop has handled an event and there
// are no events left, which includes any rendering of the body necessary,
// as rendering is done in response to the periodic paint events, which
// the window is woken for, as they are paused while it is idle.
func (bd *Body) waitNoEvents(rw *renderWindow) {
ch := make(chan struct{})
rw.noEventsMu.Lock()
rw.noEventsChan = ch
rw.noEventsMu.Unlock()
rw.wake()
<-ch
}
// Locked returns a function that calls the given function with the
// AsyncLock of the given widget (typically the body) held, for use as one
// of the functions passed to [AssertRender] or [RenderImage], which are
// called from outside of the event loop:
//
// AssertRender(t, b, "name", Locked(b, func() { w.Send(events.Click) }))
//
// A function that uses the widgets of another window (such as one that a
// dialog opened in a new window) needs the lock of that window, so it is
// given a widget in that window.
func Locked(w Widget, fun func()) func() {
return func() {
wb := w.AsWidget()
wb.AsyncLock()
defer wb.AsyncUnlock()
fun()
}
}
// TrackWindows returns a function that closes the windows that have been
// opened since TrackWindows was called (as by dialogs in new windows) and
// waits until they are closed, so that the windows of a test do not render
// while other tests change global state (as the color scheme). It must be
// called without the lock of any window held:
//
// defer TrackWindows()()
func TrackWindows() func() {
before := AllRenderWindows.windows()
return func() {
var opened []*renderWindow
for _, w := range AllRenderWindows.windows() {
if !slices.Contains(before, w) {
opened = append(opened, w)
w.SystemWindow.CloseReq()
}
}
for range 500 {
open := slices.ContainsFunc(AllRenderWindows.windows(), func(w *renderWindow) bool {
return slices.Contains(opened, w)
})
if !open {
return
}
time.Sleep(10 * time.Millisecond)
}
}
}
// Popups returns the scenes of the popups (such as dialogs, menus, and
// snackbars) that are open in the window of the given body, from the bottom
// to the top, so that a test can use them. It must be called with the
// AsyncLock of the body held (see [Locked]).
func Popups(b *Body) []*Scene {
st := b.Scene.Stage
if st == nil || st.Main == nil || st.Main.popups == nil {
return nil
}
var scs []*Scene
for _, ps := range st.Main.popups.stack.Values {
if ps.Scene != nil {
scs = append(scs, ps.Scene)
}
}
return scs
}
// TopScene returns the scene on top in the window of the given body: the
// top popup (such as a menu) if there is one, or else the top main scene,
// which is a dialog in the window (which [Popups] does not include) if one
// is open, or else the scene of the window. It must be called with the
// AsyncLock of the body held (see [Locked]).
func TopScene(b *Body) *Scene {
rw := b.Scene.RenderWindow()
if rw == nil {
return nil
}
top := rw.mains.top()
if top == nil {
return nil
}
if pt := top.popups.top(); pt != nil && pt.Scene != nil {
return pt.Scene
}
return top.Scene
}
// ButtonByText returns the first button (or function button) with the given text in the given
// widget and its descendants (such as a menu or dialog scene from
// [Popups]), or nil if there is none.
func ButtonByText(w Widget, text string) *Button {
for cw := range w.AsWidget().AllWidgets() {
var bt *Button
switch x := cw.(type) {
case *Button:
bt = x
case *FuncButton: // (as in context menus)
bt = &x.Button
}
if bt != nil && bt.Text == text {
return bt
}
}
return nil
}
// DragMouse drags the mouse with the left button pressed from one point
// to another in the window of the given body, in ten steps, through the
// events of its system window, so that the events are handled as those of
// a real mouse, including drag and drop. It must be called without the
// AsyncLock held, typically in a function passed to [AssertRender] or
// [RenderImage]. It waits for the time it takes for a drag or slide to
// start after the press.
func DragMouse(b *Body, from, to image.Point) {
ev := b.Scene.RenderWindow().SystemWindow.Events()
ev.MouseButton(events.MouseDown, events.Left, from, 0)
// a drag or slide starts after its time ([TimingSettings], which the
// settings of a window set again when it is opened)
time.Sleep(max(TimingSettings.DragStartTime, TimingSettings.SlideStartTime) + 20*time.Millisecond)
for i := 1; i <= 10; i++ {
ev.MouseMove(from.Add(to.Sub(from).Mul(i).Div(10)))
time.Sleep(10 * time.Millisecond)
}
ev.MouseButton(events.MouseUp, events.Left, to, 0)
}
// SendKey sends a [events.KeyChord] event with the given rune, code, and
// modifier keys (such as [key.Shift], which are flags, not bit masks) to
// the given widget, as if it had been typed while the widget had the focus.
func SendKey(w Widget, rn rune, code key.Codes, mods ...key.Modifiers) {
var m key.Modifiers
for _, mod := range mods {
m.SetFlag(true, mod)
}
sendKeyMods(w, rn, code, m)
}
// sendKeyMods sends a [events.KeyChord] event with the given rune, code,
// and modifier bits to the given widget.
func sendKeyMods(w Widget, rn rune, code key.Codes, mods key.Modifiers) {
w.AsWidget().HandleEvent(events.NewKey(events.KeyChord, rn, code, mods))
}
// TypeText sends a [events.KeyChord] event for each rune of the given
// text to the given widget, as if it had been typed.
func TypeText(w Widget, text string) {
for _, r := range text {
SendKey(w, r, 0)
}
}
// SendKeyFunction sends to the given widget the [events.KeyChord] event
// for the simplest key chord of the given key function in the active
// [keymap.Map] (with the fewest modifiers, as DownArrow rather than
// Control+Meta+N for MoveDown, whose modifiers can change what it does,
// as Meta extending a selection), so that tests do not depend on the
// platform keymap. It panics if the key function has no chord.
func SendKeyFunction(w Widget, kf keymap.Functions) {
chords := strings.Split(string(kf.Chord()), "\n")
slices.SortStableFunc(chords, func(a, b string) int {
return cmp.Or(cmp.Compare(strings.Count(a, "+"), strings.Count(b, "+")), cmp.Compare(len(a), len(b)))
})
rn, code, mods, err := key.Chord(chords[0]).Decode()
if err != nil {
panic(fmt.Errorf("core.SendKeyFunction: %v has no usable key chord: %w", kf, err))
}
sendKeyMods(w, rn, code, mods)
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"fmt"
"image"
"slices"
"strconv"
"strings"
"unicode"
"unicode/utf8"
"cogentcore.org/core/base/elide"
"cogentcore.org/core/base/fileinfo/mimedata"
"cogentcore.org/core/colors"
"cogentcore.org/core/colors/matcolor"
"cogentcore.org/core/cursors"
"cogentcore.org/core/events"
"cogentcore.org/core/events/key"
"cogentcore.org/core/icons"
"cogentcore.org/core/keymap"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/system"
"cogentcore.org/core/text/htmltext"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/shaped"
"cogentcore.org/core/text/text"
"cogentcore.org/core/text/textpos"
)
// Text is a widget for rendering text. It supports full HTML styling,
// including links. By default, text wraps and collapses whitespace, although
// you can change this by changing [styles.Text.WhiteSpace].
type Text struct {
WidgetBase
// Text is the text to display.
Text string
// Type is the styling type of text to use.
// It defaults to [TextBodyLarge].
Type TextTypes
// Links is the list of links in the text.
Links []rich.Hyperlink `copier:"-" json:"-" xml:"-" set:"-"`
// richText is the conversion of the HTML text source.
// This is what is actually rendered.
richText rich.Text
// minWordKey is the text and font size that minWord is for.
minWordKey string
// minWord is the cached width of the longest word, for minContentWidth.
minWord float32
// wrapWidth is the width that the text was last wrapped in by SizeDown,
// which it wraps in again only if its allocated width changes.
wrapWidth float32
// richSource is the source that richText was made from, so that
// a restyle that changes neither the text nor its style does not
// parse the HTML again.
richSource richTextSource
// SelectRange is the selected range, in terms of rune indexes
// into the richText.Join() runes.
selectRange textpos.Range
// selectAnchor is the rune index where a selection by sliding started,
// which stays an end of the selection as the other end moves.
selectAnchor int
// selectTexts are the texts that a selection by sliding that started in
// this text can extend to, in the order of the document (see
// [Text.selectTo]), found when it started.
selectTexts []*Text
// highlights are regions that will be highlighted in the text
// when rendered. Indexes are into richText.Join() runes.
highlights []textpos.Range
// paintText is the [shaped.Lines] for the text.
paintText *shaped.Lines
// normalCursor is the cached cursor to display when there
// is no link being hovered.
normalCursor cursors.Cursor
}
// TextTypes is an enum containing the different
// possible styling types of [Text] widgets.
type TextTypes int32 //enums:enum -trim-prefix Text
const (
// TextDisplayLarge is large, short, and important
// display text with a default font size of 57dp.
TextDisplayLarge TextTypes = iota
// TextDisplayMedium is medium-sized, short, and important
// display text with a default font size of 45dp.
TextDisplayMedium
// TextDisplaySmall is small, short, and important
// display text with a default font size of 36dp.
TextDisplaySmall
// TextHeadlineLarge is large, high-emphasis
// headline text with a default font size of 32dp.
TextHeadlineLarge
// TextHeadlineMedium is medium-sized, high-emphasis
// headline text with a default font size of 28dp.
TextHeadlineMedium
// TextHeadlineSmall is small, high-emphasis
// headline text with a default font size of 24dp.
TextHeadlineSmall
// TextTitleLarge is large, medium-emphasis
// title text with a default font size of 22dp.
TextTitleLarge
// TextTitleMedium is medium-sized, medium-emphasis
// title text with a default font size of 16dp.
TextTitleMedium
// TextTitleSmall is small, medium-emphasis
// title text with a default font size of 14dp.
TextTitleSmall
// TextBodyLarge is large body text used for longer
// passages of text with a default font size of 16dp.
TextBodyLarge
// TextBodyMedium is medium-sized body text used for longer
// passages of text with a default font size of 14dp.
TextBodyMedium
// TextBodySmall is small body text used for longer
// passages of text with a default font size of 12dp.
TextBodySmall
// TextLabelLarge is large text used for label text (like a caption
// or the text inside a button) with a default font size of 14dp.
TextLabelLarge
// TextLabelMedium is medium-sized text used for label text (like a caption
// or the text inside a button) with a default font size of 12dp.
TextLabelMedium
// TextLabelSmall is small text used for label text (like a caption
// or the text inside a button) with a default font size of 11dp.
TextLabelSmall
// TextSupporting is medium-sized supporting text typically used for
// secondary dialog information below the title. It has a default font
// size of 14dp and color of [colors.Scheme.OnSurfaceVariant].
TextSupporting
)
func (tx *Text) WidgetValue() any { return &tx.Text }
// PaintText returns the shaped representation of the text,
// which is needed for some specific special-case rendering
// situations.
func (tx *Text) PaintText() *shaped.Lines {
return tx.paintText
}
func (tx *Text) Init() {
tx.WidgetBase.Init()
tx.AddContextMenu(tx.contextMenu)
tx.SetType(TextBodyLarge)
tx.Styler(func(s *styles.Style) {
s.SetAbilities(true, abilities.Selectable, abilities.DoubleClickable, abilities.TripleClickable, abilities.LongPressable, abilities.Slideable)
if len(tx.Links) > 0 {
s.SetAbilities(true, abilities.Clickable, abilities.LongHoverable, abilities.LongPressable)
}
if !tx.IsReadOnly() {
s.Cursor = cursors.Text
}
s.GrowWrap = true // for text that is not aligned at the start; see below
// Text styles based on https://m3.material.io/styles/typography/type-scale-tokens
// We use Em for line height so that it scales properly with font size changes.
switch tx.Type {
case TextLabelLarge:
s.Text.LineHeight = 20.0 / 14
s.Font.Size.Dp(14)
s.Font.Weight = rich.Medium
case TextLabelMedium:
s.Text.LineHeight = 16.0 / 12
s.Font.Size.Dp(12)
s.Font.Weight = rich.Medium
case TextLabelSmall:
s.Text.LineHeight = 16.0 / 11
s.Font.Size.Dp(11)
s.Font.Weight = rich.Medium
case TextBodyLarge:
s.Text.LineHeight = 24.0 / 16
// s.Font.Size.Dp(16) // already the default so don't specify (to allow for inheritance) (important)
s.Font.Weight = rich.Normal
case TextSupporting:
s.Color = colors.Scheme.OnSurfaceVariant
fallthrough
case TextBodyMedium:
s.Text.LineHeight = 20.0 / 14
s.Font.Size.Dp(14)
s.Font.Weight = rich.Normal
case TextBodySmall:
s.Text.LineHeight = 16.0 / 12
s.Font.Size.Dp(12)
s.Font.Weight = rich.Normal
case TextTitleLarge:
s.Text.LineHeight = 28.0 / 22
s.Font.Size.Dp(22)
s.Font.Weight = rich.Normal
case TextTitleMedium:
s.Text.LineHeight = 24.0 / 16
s.Font.Size.Dp(16)
s.Font.Weight = rich.Bold
case TextTitleSmall:
s.Text.LineHeight = 20.0 / 14
s.Font.Size.Dp(14)
s.Font.Weight = rich.Medium
case TextHeadlineLarge:
s.Text.LineHeight = 40.0 / 32
s.Font.Size.Dp(32)
s.Font.Weight = rich.Normal
case TextHeadlineMedium:
s.Text.LineHeight = 36.0 / 28
s.Font.Size.Dp(28)
s.Font.Weight = rich.Normal
case TextHeadlineSmall:
s.Text.LineHeight = 32.0 / 24
s.Font.Size.Dp(24)
s.Font.Weight = rich.Normal
case TextDisplayLarge:
s.Text.LineHeight = 70.0 / 57
s.Font.Size.Dp(57)
s.Font.Weight = rich.Normal
case TextDisplayMedium:
s.Text.LineHeight = 52.0 / 45
s.Font.Size.Dp(45)
s.Font.Weight = rich.Normal
case TextDisplaySmall:
s.Text.LineHeight = 44.0 / 36
s.Font.Size.Dp(36)
s.Font.Weight = rich.Normal
}
})
tx.FinalStyler(func(s *styles.Style) {
// Text aligned at the start starts out at its preferred width,
// while other text (centered, for example) is aligned within all
// of the width that it can have, as text is in a block in CSS
// (see [styles.Style.GrowWrap]).
if s.Text.Align == text.Start {
s.GrowWrap = false
}
tx.normalCursor = s.Cursor
tx.updateRichText() // note: critical to update with final styles
if tx.paintText != nil && tx.Text != "" {
_, tsty := s.NewRichText()
tx.paintText.UpdateStyle(tx.richText, tsty)
}
})
tx.HandleTextClick(func(tl *rich.Hyperlink, e events.Event) {
system.TheApp.OpenURL(tl.URL)
})
tx.OnFocusLost(func(e events.Event) {
if tx.Scene.selectedText == nil || e.HasAnyModifier(key.Shift, key.Meta) {
tx.selectReset()
}
})
tx.OnKeyChord(func(e events.Event) {
if tx.selectRange.Len() == 0 {
return
}
kf := keymap.Of(e.KeyChord())
if kf == keymap.Copy {
e.SetHandled()
tx.copy()
}
})
tx.On(events.MouseMove, func(e events.Event) {
tl, _ := tx.findLink(e.Pos())
if tl != nil {
tx.Styles.Cursor = cursors.Pointer
} else {
tx.Styles.Cursor = tx.normalCursor
}
})
tx.OnFinal(events.Click, func(e events.Event) {
if !e.HasAnyModifier(key.Shift, key.Meta) {
tx.selectReset()
}
if !TheApp.SystemPlatform().IsMobile() {
return
}
if tx.StateIs(states.Attended) { // toggle attention with clicking
// this allows drag scrolling to proceed.
e.SetHandled()
em := tx.Events()
if em != nil {
em.setAttend(nil)
}
}
})
tx.On(events.DoubleClick, func(e events.Event) {
e.SetHandled()
if !slices.Contains(tx.Scene.selectedText, tx) {
tx.Scene.selectedText = append(tx.Scene.selectedText, tx)
}
tx.selectWord(tx.pixelToRune(e.Pos()))
tx.SetFocusQuiet()
})
tx.On(events.TripleClick, func(e events.Event) {
e.SetHandled()
if !slices.Contains(tx.Scene.selectedText, tx) {
tx.Scene.selectedText = append(tx.Scene.selectedText, tx)
}
tx.selectAll()
tx.SetFocusQuiet()
if TheApp.SystemPlatform().IsMobile() {
tx.Send(events.ContextMenu, e)
}
})
tx.On(events.SlideStart, func(e events.Event) {
e.SetHandled()
tx.SetState(true, states.Sliding)
tx.SetFocusQuiet()
// the selection starts where the mouse was pressed, before it moved
// far enough to start the slide
tx.startSelect(tx.pixelToRune(e.StartPos()))
})
tx.On(events.SlideMove, func(e events.Event) {
e.SetHandled()
tx.selectTo(e.Pos())
})
tx.On(events.SlideStop, func(e events.Event) {
if TheApp.SystemPlatform().IsMobile() {
tx.Send(events.ContextMenu, e)
}
})
tx.FinalUpdater(func() {
// A text that has not been styled yet gets its rich text and size
// when it is styled and laid out.
if tx.Styles.Font.Size.Dots == 0 {
return
}
tx.updateRichText()
tx.configTextAlloc(tx.Geom.Size.Alloc.Content)
})
}
// updateRichText gets the richtext from Text, using HTML parsing.
func (tx *Text) updateRichText() {
sty, tsty := tx.Styles.NewRichText()
src := richTextSource{text: tx.Text, pre: tsty.WhiteSpace.KeepWhiteSpace(), style: sty.ToRunes(), scheme: colors.Scheme}
if tx.richText != nil && src.equal(&tx.richSource) && !tx.NeedsRebuild() {
return
}
tx.richSource = src
if src.pre {
tx.richText, _ = htmltext.HTMLPreToRich([]byte(tx.Text), sty, nil)
} else {
tx.richText, _ = htmltext.HTMLToRich([]byte(tx.Text), sty, nil)
}
tx.Links = tx.richText.GetLinks()
}
// richTextSource is the source of the rich text of a [Text]: its text,
// whether its white space is kept, its encoded rich text style, and
// the color scheme, which gives the colors of links and of marked and
// code text. [colors.SetSchemes] and [colors.SetScheme] (as in a change
// of the color or theme settings) set a new scheme, and a full rebuild
// ([UpdateAll]) also makes the rich text again.
type richTextSource struct {
text string
pre bool
style []rune
scheme *matcolor.Scheme
}
// equal returns whether the sources are the same.
func (rs *richTextSource) equal(o *richTextSource) bool {
return rs.text == o.text && rs.pre == o.pre && rs.scheme == o.scheme && slices.Equal(rs.style, o.style)
}
// findLink finds the text link at the given scene-local position. If it
// finds it, it returns it and its bounds; otherwise, it returns nil.
func (tx *Text) findLink(pos image.Point) (*rich.Hyperlink, image.Rectangle) {
if tx.paintText == nil || len(tx.Links) == 0 {
return nil, image.Rectangle{}
}
tpos := tx.Geom.Pos.Content
ri := tx.pixelToRune(pos)
for li := range tx.Links {
lr := &tx.Links[li]
if !lr.Range.Contains(ri) {
continue
}
gb := tx.paintText.RuneBounds(ri).Translate(tpos).ToRect()
return lr, gb
}
return nil, image.Rectangle{}
}
// HandleTextClick handles click events such that the given function will be called
// on any links that are clicked on.
func (tx *Text) HandleTextClick(openLink func(tl *rich.Hyperlink, e events.Event)) {
tx.OnClick(func(e events.Event) {
tl, _ := tx.findLink(e.Pos())
if tl == nil {
return
}
openLink(tl, e)
e.SetHandled()
})
}
func (tx *Text) WidgetTooltip(pos image.Point) (string, image.Point) {
if pos == image.Pt(-1, -1) {
return tx.Tooltip, image.Point{}
}
tl, bounds := tx.findLink(pos)
if tl == nil {
return tx.Tooltip, tx.DefaultTooltipPos()
}
return tl.URL, bounds.Min
}
func (tx *Text) contextMenu(m *Scene, pos image.Point) {
tl, _ := tx.findLink(pos)
if tl != nil {
bt := NewButton(m).SetIcon(icons.Copy).SetText("Copy link")
bt.OnClick(func(e events.Event) {
em := tx.Events()
if em != nil {
md := mimedata.NewText(tl.URL)
em.Clipboard().Write(md)
}
})
}
NewFuncButton(m).SetFunc(tx.copy).SetIcon(icons.Copy).SetKey(keymap.Copy).SetEnabled(tx.hasSelection())
}
func (tx *Text) copy() { //types:add
if !tx.hasSelection() {
return
}
md := mimedata.NewText(tx.selectedText())
em := tx.Events()
if em != nil {
em.Clipboard().Write(md)
}
tx.selectReset()
}
// Label returns the text of the text, elided to 16 characters (as in the
// tree of an inspector, where it was cut short by the panel), or its name
// if it has no text.
func (tx *Text) Label() string {
if tx.Text != "" {
return elide.End(strings.Join(strings.Fields(tx.Text), " "), 16)
}
return tx.Name
}
func (tx *Text) pixelToRune(pt image.Point) int {
return tx.paintText.RuneAtPoint(math32.FromPoint(pt), tx.Geom.Pos.Content)
}
// selectUpdate updates the selection to be between the anchor where it
// started and the given rune index, on either side of it.
func (tx *Text) selectUpdate(ri int) {
tx.selectRange.Start = min(tx.selectAnchor, ri)
tx.selectRange.End = max(tx.selectAnchor, ri)
}
// hasSelection returns true if there is an active selection.
func (tx *Text) hasSelection() bool {
return tx.selectRange.Len() > 0
}
// selectReset resets any current selection, including for the multi-text
// Scene selectedText.
func (tx *Text) selectReset() {
reset := func(t *Text) {
t.selectRange.Start = 0
t.selectRange.End = 0
t.NeedsRender()
}
for _, st := range tx.Scene.selectedText {
reset(st)
}
reset(tx)
tx.Scene.selectedText = nil
}
// selectAll selects entire set of text
func (tx *Text) selectAll() {
tx.selectAnchor = 0
txt := tx.richText.Join()
tx.selectUpdate(len(txt))
tx.NeedsRender()
}
// selectWord selects word at given rune location
func (tx *Text) selectWord(ri int) {
txt := tx.richText.Join()
wr := textpos.WordAt(txt, ri)
if wr.Start >= 0 {
tx.selectRange = wr
tx.paintText.SelectRegion(tx.selectRange)
}
tx.NeedsRender()
}
// configTextSize does the text shaping layout for text,
// using given size to constrain layout.
func (tx *Text) configTextSize(sz math32.Vector2) {
if tx.Styles.Font.Size.Dots == 0 { // not init
return
}
sty, tsty := tx.Styles.NewRichText()
tsty.Align, tsty.AlignV = text.Start, text.Start
tx.paintText = tx.Scene.TextShaper().WrapLines(tx.richText, sty, tsty, sz)
tx.setAnchorFromProperties()
}
// setAnchorFromProperties sets the Anchor string on paintText based on
// id and tag properties, which is needed for PDF print formatting.
// This is the only point at which we know we have the final
// shaped.Lines for a text item.
func (tx *Text) setAnchorFromProperties() {
anc := ""
if id, ok := tx.Properties["id"].(string); ok {
anc = id
}
if tag, ok := tx.Properties["tag"].(string); ok && len(tag) > 1 && tag[0] == 'h' { // header
if level, err := strconv.Atoi(tag[1:]); err == nil {
anc += fmt.Sprintf(";Header %d:%s", level, tx.Text)
}
}
tx.paintText.Anchor = anc
}
// configTextAlloc is used for determining how much space the text
// takes, using given size (typically Alloc).
// In this case, alignment factors are turned off,
// because they otherwise can absorb much more space, which should
// instead be controlled by the base Align X,Y factors.
func (tx *Text) configTextAlloc(sz math32.Vector2) math32.Vector2 {
if tx.Scene == nil || tx.Scene.TextShaper() == nil {
return sz
}
if tx.Styles.Font.Size.Dots == 0 {
return sz // not init
}
tsh := tx.Scene.TextShaper()
sty, tsty := tx.Styles.NewRichText()
// The height of the text follows from wrapping it in the width, so it
// is not limited by the allocated height, which is only that of one
// line when it starts out at its preferred width.
sz.Y = 0
rsz := sz
if tsty.Align != text.Start && tsty.AlignV != text.Start {
etxs := *tsty
etxs.Align, etxs.AlignV = text.Start, text.Start
tx.paintText = tsh.WrapLines(tx.richText, sty, &etxs, rsz)
rsz = tx.paintText.Bounds.Size().Ceil()
}
tx.paintText = tsh.WrapLines(tx.richText, sty, tsty, rsz)
tx.setAnchorFromProperties()
return tx.paintText.Bounds.Size().Ceil()
}
// contentSizingMeasure is the width in characters (ch) that text is
// limited to when its scene is sized to fit its content (as for a window
// or dialog), within which it wraps, so that the scene is not as wide as
// the text on one line: a readable measure of text.
const contentSizingMeasure = 70
func (tx *Text) SizeUp() {
tx.WidgetBase.SizeUp() // sets Actual size based on styles
sz := &tx.Geom.Size
wraps := tx.wrapsToWidth()
if wraps {
// as wide as it is on one line (its preferred width), within any Max
w := float32(1e6)
if sz.Max.X > 0 {
w = sz.Max.X
}
if tx.Scene != nil && tx.Scene.hasFlag(sceneContentSizing) {
// a window (or dialog) sized to its content is not wider than
// a readable measure of text, which it wraps at
m := units.Ch(contentSizingMeasure)
m.ToDots(&tx.Styles.UnitContext)
w = min(w, m.Dots)
}
tx.configTextSize(math32.Vec2(w, sz.Actual.Content.Y))
} else {
tx.configTextSize(sz.Actual.Content)
}
if tx.paintText == nil {
return
}
rsz := tx.paintText.Bounds.Size().Ceil()
sz.FitSizeMax(&sz.Actual.Content, rsz)
sz.SetTotalFromContent(&sz.Actual)
if wraps {
sz.setIntrinsicWidths(tx.minContentWidth(), sz.Actual.Content.X)
} else {
sz.minWidth, sz.prefWidth = sz.Actual.Total.X, sz.Actual.Total.X
}
if DebugSettings.LayoutTrace {
fmt.Println(tx, "Text SizeUp:", rsz, "Actual:", sz.Actual.Content)
}
}
// minContentWidth returns the min-content width of the content of the
// text: the width of its longest word if it wraps, or of its line if not.
// It is cached for the text and its font size.
func (tx *Text) minContentWidth() float32 {
if tx.cutsToWidth() {
// it is cut to its width, down to about its ellipsis
return min(tx.Styles.Font.Size.Dots, tx.Geom.Size.Actual.Content.X)
}
if !tx.Styles.Text.WhiteSpace.HasWordWrap() || tx.Scene == nil || tx.Styles.Font.Size.Dots == 0 {
return tx.Geom.Size.Actual.Content.X
}
key := fmt.Sprintf("%s\x00%g", tx.Text, tx.Styles.Font.Size.Dots)
if tx.minWordKey == key {
return tx.minWord
}
width := longestWordWidth(tx.Scene, &tx.Styles, string(tx.richText.Join()))
tx.minWordKey, tx.minWord = key, width
return width
}
// longestWordWidth returns the width of the longest word (by its number of
// characters) of the given text in the given style, which is the
// min-content width of the text when it wraps. Words are separated by the
// spaces that lines break at: no-break spaces join them.
func longestWordWidth(sc *Scene, st *styles.Style, txt string) float32 {
longest := ""
for w := range strings.FieldsFuncSeq(txt, isBreakSpace) {
if utf8.RuneCountInString(w) > utf8.RuneCountInString(longest) {
longest = w
}
}
if longest == "" || sc == nil || sc.TextShaper() == nil {
return 0
}
sty, tsty := st.NewRichText()
lines := sc.TextShaper().WrapLines(rich.NewText(sty, []rune(longest)), sty, tsty, math32.Vec2(1e6, 1e6))
return math32.Ceil(lines.Bounds.Size().X)
}
// isBreakSpace returns whether the rune is a space that lines can break at,
// which is not a no-break space.
func isBreakSpace(r rune) bool {
switch r {
case '\u00a0', '\u2007', '\u202f': // no-break, figure, and narrow no-break
return false
}
return unicode.IsSpace(r)
}
// wrapsToWidth returns whether the text is laid out in the width that it
// is given: it wraps, or it is cut to it (see [Text.cutsToWidth]).
func (tx *Text) wrapsToWidth() bool {
return tx.Styles.Text.WhiteSpace.HasWordWrap() || tx.cutsToWidth()
}
// cutsToWidth returns whether the text does not wrap and is cut to its
// width with an ellipsis ([styles.Text.Ellipsis]).
func (tx *Text) cutsToWidth() bool {
return tx.Styles.Text.Ellipsis && !tx.Styles.Text.WhiteSpace.HasWordWrap() && tx.Styles.Text.WhiteSpace != text.WhiteSpacePre
}
func (tx *Text) SizeDown(iter int) bool {
if !tx.wrapsToWidth() {
return false
}
sz := &tx.Geom.Size
asz := sz.Alloc.Content
// The width settles in the first iterations, but can still change
// after them, as when a parent-relative Max is resolved.
if iter > 1 && asz.X == tx.wrapWidth {
return false
}
tx.wrapWidth = asz.X
if pw := sz.prefWidth - sz.Space.X; asz.X < pw && pw-asz.X <= 1 {
// its preferred width (on one line) is rounded up, so it fits on
// one line in a width that is less than 1 dot narrower than that
// (as the menu items of pkg.go.dev, with an icon after the text)
asz.X = pw
}
rsz := tx.configTextAlloc(asz) // use allocation
prevContent := sz.Actual.Content
// start over so we don't reflect hysteresis of prior guess
sz.setInitContentMin(tx.styleMinDots())
sz.FitSizeMax(&sz.Actual.Content, rsz)
sz.SetTotalFromContent(&sz.Actual)
chg := prevContent != sz.Actual.Content
if chg {
if DebugSettings.LayoutTrace {
fmt.Println(tx, "Label Size Changed:", sz.Actual.Content, "was:", prevContent)
}
}
return chg
}
func (tx *Text) Render() {
tx.WidgetBase.Render()
tx.paintText.SelectReset()
tx.paintText.SelectRegion(tx.selectRange)
tx.paintText.HighlightReset()
tx.paintText.HighlightRegion(tx.highlights...)
tx.Scene.Painter.DrawText(tx.paintText, tx.Geom.Pos.Content)
}
//////// Search interface
// TextRunes returns any text content associated with the widget, to be used
// for Search for example. If this is nil, then it is excluded from search.
func (tx *Text) TextRunes() []rune {
return tx.richText.Join()
}
// Search returns text search results for this widget, searching for
// the find string with given case sensitivity. It is up to each widget
// to define the meaning of the Region line, char values for the matches.
// The bool return value indicates whether this widget handled the search,
// thereby excluding further searching within the elements under it.
func (tx *Text) Search(find string, useCase CaseSensitive) ([]textpos.Match, bool) {
return SearchRunes(tx.richText.Join(), find, useCase), true
}
// HighlightMatches does highlighting of the given matches within this widget,
// where the matches are as returned from the Search method.
// Passing a nil causes matches to be reset.
// Any existing highlighting should always be reset first regardless.
// The bool return value indicates whether this widget handled the search,
// thereby excluding further searching within the elements under it.
func (tx *Text) HighlightMatches(matches []textpos.Match) bool {
tx.highlights = nil
tx.NeedsRender()
if matches == nil {
return true
}
for _, m := range matches {
tx.highlights = append(tx.highlights, textpos.Range{Start: m.Region.Start.Char, End: m.Region.End.Char})
}
return true
}
// SelectMatch selects match at given index from among those returned
// from the Search method. scroll = scroll widget into view.
// reset = clear selection instead of selecting (does not scroll).
func (tx *Text) SelectMatch(matches []textpos.Match, index int, scroll SelectionScroll, reset SelectionReset) {
if reset {
tx.selectReset()
return
}
match := matches[index]
tx.selectRange = textpos.Range{Start: match.Region.Start.Char, End: match.Region.End.Char}
tx.NeedsRender()
if scroll {
tx.ScrollThisToTop()
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"image"
"time"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint"
"cogentcore.org/core/system"
"cogentcore.org/core/tree"
)
// TextCursorOwner returns the widget whose cursor of [TextCursor] with
// the given name is in the window of the given widget, or nil.
func TextCursorOwner(w *WidgetBase, name string) tree.Node {
sc := w.Scene
if sc == nil || sc.Stage == nil || sc.Stage.Main == nil {
return nil
}
ms := sc.Stage.Main
ms.Sprites.Lock()
defer ms.Sprites.Unlock()
if sp, ok := ms.Sprites.SpriteByNameNoLock(name); ok {
owner, _ := sp.Properties["owner"].(tree.Node)
return owner
}
return nil
}
// TextCursorPoint returns the position of a text cursor (see [TextCursor])
// for the given exact (fractional) position between two characters. The
// cursor line is centered on its X position, which is the Ceil of the exact
// one: the space between the ink of two characters is about half a pixel to
// the right of the exact position, as their left side bearings are bigger
// than their right ones, so that the cursor is centered in that space,
// where it was about a pixel to the left of it, touching the character
// before it, with Floor (see TestTextFieldCursorPosition). Y is the top of
// the line, which is floored.
func TextCursorPoint(pos math32.Vector2) image.Point {
return image.Pt(int(math32.Ceil(pos.X)), int(math32.Floor(pos.Y)))
}
// TextCursor implements a blinking text cursor using a [Sprite], which
// is shared by the text widgets of a type in a window, and owned by the
// one that last turned it on.
// - on determines whether the cursor should be turned on or off,
// - w is the text widget the cursor belongs to
// - name is the unique name of the cursor (shared among all of same type)
// - width, height are size of cursor line to render
// - color is the color to render.
// - pos is a function that returns the current top-left position of cursor
func TextCursor(on bool, w *WidgetBase, name string, width, height float32, color image.Image, pos func() image.Point) {
sc := w.Scene
if sc == nil || sc.Stage == nil || sc.Stage.Main == nil {
return
}
ms := sc.Stage.Main
ms.Sprites.Lock()
defer ms.Sprites.Unlock()
activate := func(sp *Sprite) {
sp.EventBBox.Min = pos()
sp.Active = true
sp.Properties["turnOn"] = true
sp.Properties["on"] = true
sp.Properties["lastSwitch"] = time.Now()
ms.Sprites.SetModifiedNoLock()
}
// The sprite of the cursor is turned on or off if it is owned by the
// widget; a widget only turns off its own cursor.
if sp, ok := ms.Sprites.SpriteByNameNoLock(name); ok && sp.Properties["owner"] == w.This {
if on {
activate(sp)
} else {
sp.Active = false
ms.Sprites.SetModifiedNoLock()
}
return
}
if !on {
return
}
var sp *Sprite
sp = NewSprite(name, func(pc *paint.Painter) {
if !sp.Active || w == nil || w.This == nil || !w.IsVisible() {
return
}
turnOn := sp.Properties["turnOn"].(bool) // force on
if !turnOn {
isOn := sp.Properties["on"].(bool)
lastSwitch := sp.Properties["lastSwitch"].(time.Time)
if TheApp.Platform() != system.Offscreen && TimingSettings.CursorBlinkTime > 0 && time.Since(lastSwitch) > TimingSettings.CursorBlinkTime {
isOn = !isOn
sp.Properties["on"] = isOn
sp.Properties["lastSwitch"] = time.Now()
}
if !isOn {
return
}
}
bbsz := math32.Vec2(math32.Ceil(width), math32.Ceil(height))
if bbsz.X < 2 { // at least 2
bbsz.X = 2
}
sp.Properties["turnOn"] = false
pos := math32.FromPoint(sp.EventBBox.Min)
if !pos.AddScalar(3).ToPointCeil().Sub(sc.SceneGeom.Pos).In(w.Geom.ContentBBox) {
return
}
pc.Fill.Color = nil
pc.Stroke.Color = color
pc.Stroke.Width.Dot(bbsz.X)
pc.Line(pos.X, pos.Y, pos.X, pos.Y+bbsz.Y)
pc.Draw()
})
sp.InitProperties()
sp.Properties["owner"] = w.This
activate(sp)
ms.Sprites.AddNoLock(sp)
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"fmt"
"image"
"log/slog"
"reflect"
"slices"
"sync"
"time"
"unicode"
"unicode/utf8"
"cogentcore.org/core/base/fileinfo/mimedata"
"cogentcore.org/core/colors"
"cogentcore.org/core/cursors"
"cogentcore.org/core/events"
"cogentcore.org/core/events/key"
"cogentcore.org/core/icons"
"cogentcore.org/core/keymap"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/parse/complete"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/shaped"
"cogentcore.org/core/text/text"
"cogentcore.org/core/text/textpos"
"cogentcore.org/core/tree"
)
// TextField is a widget for editing a line of text.
//
// With the default [styles.WhiteSpaceNormal] setting,
// text will wrap onto multiple lines as needed. You can
// call [styles.Style.SetTextWrap](false) to force everything
// to be rendered on a single line. With multi-line wrapped text,
// the text is still treated as a single contiguous line of wrapped text.
type TextField struct { //core:embedder
Frame
// Type is the styling type of the text field.
Type TextFieldTypes
// Placeholder is the text that is displayed
// when the text field is empty.
Placeholder string
// Validator is a function used to validate the input
// of the text field. If it returns a non-nil error,
// then an error color, icon, and tooltip will be displayed.
Validator func() error `json:"-" xml:"-"`
// PasteFilter, if set, is a function that changes the text pasted
// into the text field before it is inserted, as to take an email
// address out of a mailto: link.
PasteFilter func(text string) string `json:"-" xml:"-"`
// LeadingIcon, if specified, indicates to add a button
// at the start of the text field with this icon.
// See [TextField.SetLeadingIcon].
LeadingIcon icons.Icon `set:"-"`
// LeadingIconOnClick, if specified, is the function to call when
// the LeadingIcon is clicked. If this is nil, the leading icon
// will not be interactive. See [TextField.SetLeadingIcon].
LeadingIconOnClick func(e events.Event) `json:"-" xml:"-"`
// TrailingIcon, if specified, indicates to add a button
// at the end of the text field with this icon.
// See [TextField.SetTrailingIcon].
TrailingIcon icons.Icon `set:"-"`
// TrailingIconOnClick, if specified, is the function to call when
// the TrailingIcon is clicked. If this is nil, the trailing icon
// will not be interactive. See [TextField.SetTrailingIcon].
TrailingIconOnClick func(e events.Event) `json:"-" xml:"-"`
// NoEcho is whether replace displayed characters with bullets
// to conceal text (for example, for a password input). Also
// see [TextField.SetTypePassword].
NoEcho bool
// CursorWidth is the width of the text field cursor.
// It should be set in a Styler like all other style properties.
// By default, it is 1dp.
CursorWidth units.Value
// CursorColor is the color used for the text field cursor (caret).
// It should be set in a Styler like all other style properties.
// By default, it is [colors.Scheme.Primary.Base].
CursorColor image.Image
// PlaceholderColor is the color used for the [TextField.Placeholder] text.
// It should be set in a Styler like all other style properties.
// By default, it is [colors.Scheme.OnSurfaceVariant].
PlaceholderColor image.Image
// complete contains functions and data for text field completion.
// It must be set using [TextField.SetCompleter].
complete *Complete
// text is the last saved value of the text string being edited.
text string
// edited is whether the text has been edited relative to the original.
edited bool
// accepted is whether the edits were accepted with [keymap.Accept],
// after which the text field has the focus without a cursor, and the
// keys of key functions go on to the widgets around it, such as for
// the items of a list, until editing resumes with the typing of a
// character, a click, or the focus.
accepted bool
// editText is the live text string being edited, with the latest modifications.
editText []rune
// error is the current validation error of the text field.
error error
// effPos is the effective position with any leading icon space added.
effPos math32.Vector2
// effSize is the effective size, subtracting any leading and trailing icon space.
effSize math32.Vector2
// dispRange is the range of visible text, for scrolling text case (non-wordwrap).
dispRange textpos.Range
// cursorPos is the current cursor position as rune index into string.
cursorPos int
// composition is the state of text being composed with an input method.
composition textFieldComposition
// cursorLine is the current cursor line position, for word wrap case.
cursorLine int
// charWidth is the approximate number of chars that can be
// displayed at any time, which is computed from the font size.
charWidth int
// selectRange is the selected range.
selectRange textpos.Range
// selectInit is the initial selection position (where it started).
selectInit int
// selectMode is whether to select text as the cursor moves.
selectMode bool
// selectModeShift is whether selectmode was turned on because of the shift key.
selectModeShift bool
// highlights are regions that will be highlighted in the text
// when rendered. Indexes are into editText runes.
highlights []textpos.Range
// renderAll is the render version of entire text, for sizing.
renderAll *shaped.Lines
// renderVisible is the render version of just the visible text in dispRange.
renderVisible *shaped.Lines
// renderedRange is the dispRange last rendered.
renderedRange textpos.Range
// number of lines from last render update, for word-wrap version
numLines int
// cursorShown is the state for which the cursor was last scrolled
// into view (see [TextField.scrollCursorIntoView]).
cursorShown textFieldCursorShown
// lineHeight is the line height cached during styling.
lineHeight float32
// minWordKey is the text and font size that minWord is for, the
// cached width of its longest word (see [TextField.minContentWidth]).
minWordKey string
minWord float32
// cursorMu is the mutex for updating the cursor between blinker and field.
cursorMu sync.Mutex
// undos is the undo manager for the text field.
undos textFieldUndos
leadingIconButton, trailingIconButton *Button
}
// TextFieldTypes is an enum containing the
// different possible types of text fields.
type TextFieldTypes int32 //enums:enum -trim-prefix TextField
const (
// TextFieldFilled represents a filled
// [TextField] with a background color
// and a bottom border.
TextFieldFilled TextFieldTypes = iota
// TextFieldOutlined represents an outlined
// [TextField] with a border on all sides
// and no background color.
TextFieldOutlined
)
// Validator is an interface for types to provide a Validate method
// that is used to validate string [Value]s using [TextField.Validator].
type Validator interface {
// Validate returns an error if the value is invalid.
Validate() error
}
func (tf *TextField) WidgetValue() any { return &tf.text }
func (tf *TextField) OnBind(value any, tags reflect.StructTag) {
if vd, ok := value.(Validator); ok {
tf.Validator = vd.Validate
}
}
func (tf *TextField) Init() {
tf.Frame.Init()
tf.AddContextMenu(tf.contextMenu)
tf.Styler(func(s *styles.Style) {
s.SetAbilities(true, abilities.Activatable, abilities.Focusable, abilities.Hoverable, abilities.Slideable, abilities.DoubleClickable, abilities.TripleClickable)
s.SetAbilities(false, abilities.ScrollableUnattended)
if TheApp.SystemPlatform().IsMobile() {
// a drag scrolls what it is in, as in the rows of a list,
// instead of selecting text, which is done by a double tap
// or the context menu (of a long press), as on iOS
s.SetAbilities(false, abilities.Slideable)
}
tf.CursorWidth.Dp(1)
tf.PlaceholderColor = colors.Scheme.OnSurfaceVariant
tf.CursorColor = colors.Scheme.Primary.Base
s.Cursor = cursors.Text
s.VirtualKeyboard = styles.KeyboardSingleLine
s.GrowWrap = false // note: doesn't work with Grow
s.Grow.Set(1, 0)
s.Min.Y.Em(1.1)
s.Min.X.Ch(20)
s.Max.X.Ch(40)
s.Gap.Zero()
s.Padding.Set(units.Dp(8), units.Dp(8))
if tf.LeadingIcon.IsSet() {
s.Padding.Left.Dp(12)
}
if tf.TrailingIcon.IsSet() {
s.Padding.Right.Dp(12)
}
s.Text.LineHeight = 1.4
s.Text.Align = text.Start
s.Align.Items = styles.Center
s.Color = colors.Scheme.OnSurface
s.IconSize.Set(units.Em(18.0 / 16))
switch tf.Type {
case TextFieldFilled:
s.Border.Style.Set(styles.BorderNone)
s.Border.Style.Bottom = styles.BorderSolid
s.Border.Width.Zero()
s.Border.Color.Zero()
s.Border.Radius = styles.BorderRadiusExtraSmallTop
s.Background = colors.Scheme.SurfaceContainer
s.MaxBorder = s.Border
s.MaxBorder.Width.Bottom = units.Dp(2)
s.MaxBorder.Color.Bottom = colors.Scheme.Primary.Base
s.Border.Width.Bottom = units.Dp(1)
s.Border.Color.Bottom = colors.Scheme.OnSurfaceVariant
if tf.error != nil {
s.Border.Color.Bottom = colors.Scheme.Error.Base
}
case TextFieldOutlined:
s.Border.Style.Set(styles.BorderSolid)
s.Border.Radius = styles.BorderRadiusExtraSmall
s.MaxBorder = s.Border
s.MaxBorder.Width.Set(units.Dp(2))
s.MaxBorder.Color.Set(colors.Scheme.Primary.Base)
s.Border.Width.Set(units.Dp(1))
if tf.error != nil {
s.Border.Color.Set(colors.Scheme.Error.Base)
}
}
if tf.IsReadOnly() {
s.Border.Color.Zero()
s.Border.Width.Zero()
s.Border.Radius.Zero()
s.MaxBorder = s.Border
s.Background = nil
}
if s.Is(states.Selected) {
s.Background = colors.Scheme.Select.Container
}
})
tf.FinalStyler(func(s *styles.Style) {
s.SetAbilities(!tf.IsReadOnly(), abilities.Focusable)
})
tf.handleKeyEvents()
tf.OnFirst(events.Change, func(e events.Event) {
tf.validate()
if tf.error != nil {
e.SetHandled()
}
})
tf.OnClick(func(e events.Event) {
tf.accepted = false
if !tf.IsReadOnly() {
tf.SetFocus()
}
switch e.MouseButton() {
case events.Left:
tf.setCursorFromPixel(e.Pos(), e.SelectMode())
case events.Middle:
if !tf.IsReadOnly() {
tf.paste()
}
}
tf.startCursor()
})
tf.On(events.DoubleClick, func(e events.Event) {
if tf.IsReadOnly() {
return
}
if !tf.IsReadOnly() && !tf.StateIs(states.Focused) {
tf.SetFocus()
}
e.SetHandled()
tf.selectWord()
tf.startCursor()
})
tf.On(events.TripleClick, func(e events.Event) {
if tf.IsReadOnly() {
return
}
if !tf.IsReadOnly() && !tf.StateIs(states.Focused) {
tf.SetFocus()
}
e.SetHandled()
tf.SelectAll()
tf.startCursor()
})
tf.On(events.SlideStart, func(e events.Event) {
e.SetHandled()
tf.SetState(true, states.Sliding)
if tf.selectMode || e.SelectMode() != events.SelectOne { // extend existing select
tf.setCursorFromPixel(e.Pos(), e.SelectMode())
} else {
tf.cursorPos = tf.pixelToCursor(e.Pos())
if !tf.selectMode {
tf.selectModeToggle()
}
}
tf.startCursor()
})
tf.On(events.SlideMove, func(e events.Event) {
e.SetHandled()
tf.selectMode = true // always
tf.setCursorFromPixel(e.Pos(), events.SelectOne)
tf.startCursor()
})
tf.OnClose(func(e events.Event) {
tf.editDone() // todo: this must be protected against something else, for race detector
})
tf.Maker(func(p *tree.Plan) {
if !tf.edited { // if in edit, don't overwrite
tf.editText = []rune(tf.text)
}
if tf.IsReadOnly() {
return
}
if tf.LeadingIcon.IsSet() {
tree.AddAt(p, "lead-icon", func(w *Button) {
tf.leadingIconButton = w
w.SetType(ButtonAction)
w.Styler(func(s *styles.Style) {
s.Padding.Zero()
s.Color = colors.Scheme.OnSurfaceVariant
s.Margin.SetRight(units.Dp(8))
s.Font.Size = tf.Styles.Font.Size
s.IconSize = tf.Styles.IconSize
if tf.LeadingIconOnClick == nil {
s.SetAbilities(false, abilities.Activatable, abilities.Focusable, abilities.Hoverable)
s.Cursor = cursors.None
}
// If we are responsible for a positive (non-disabled) state layer
// (instead of our parent), then we amplify it so that it is clear
// that we ourself are receiving a state layer amplifying event.
// Otherwise, we set our state color to that of our parent
// so that it does not appear as if we are getting interaction ourself;
// instead, we are a part of our parent and render a background color no
// different than them.
if s.Is(states.Hovered) || s.Is(states.Focused) || s.Is(states.Active) {
s.StateLayer *= 3
} else {
s.StateColor = tf.Styles.Color
}
})
w.OnClick(func(e events.Event) {
if tf.LeadingIconOnClick != nil {
tf.LeadingIconOnClick(e)
}
})
w.Updater(func() {
w.SetIcon(tf.LeadingIcon)
})
})
} else {
tf.leadingIconButton = nil
}
if tf.TrailingIcon.IsSet() || tf.error != nil {
tree.AddAt(p, "trail-icon-stretch", func(w *Stretch) {
w.Styler(func(s *styles.Style) {
s.Grow.Set(1, 0)
})
})
tree.AddAt(p, "trail-icon", func(w *Button) {
tf.trailingIconButton = w
w.SetType(ButtonAction)
w.Styler(func(s *styles.Style) {
s.Padding.Zero()
s.Color = colors.Scheme.OnSurfaceVariant
if tf.error != nil {
s.Color = colors.Scheme.Error.Base
}
s.Margin.SetLeft(units.Dp(8))
s.Font.Size = tf.Styles.Font.Size
s.IconSize = tf.Styles.IconSize
if tf.TrailingIconOnClick == nil || tf.error != nil {
s.SetAbilities(false, abilities.Activatable, abilities.Focusable, abilities.Hoverable)
s.Cursor = cursors.None
// need to clear state in case it was set when there
// was no error
s.State = 0
}
// same reasoning as for leading icon
if s.Is(states.Hovered) || s.Is(states.Focused) || s.Is(states.Active) {
s.StateLayer *= 3
} else {
s.StateColor = tf.Styles.Color
}
})
w.OnClick(func(e events.Event) {
if tf.TrailingIconOnClick != nil {
tf.TrailingIconOnClick(e)
}
})
w.Updater(func() {
w.SetIcon(tf.TrailingIcon)
if tf.error != nil {
w.SetIcon(icons.Error)
}
})
})
} else {
tf.trailingIconButton = nil
}
})
tf.Updater(func() {
tf.renderVisible = nil // ensures re-render
})
}
func (tf *TextField) Destroy() {
tf.stopCursor()
tf.Frame.Destroy()
}
// Text returns the current text of the text field. It applies any unapplied changes
// first, and sends an [events.Change] event if applicable. This is the main end-user
// method to get the current value of the text field.
func (tf *TextField) Text() string {
tf.editDone()
return tf.text
}
// Edited returns whether the text of the text field is edited, with edits
// that are not applied yet, as while typing, which [TextField.SetText]
// would revert.
func (tf *TextField) Edited() bool {
return tf.edited
}
// SetText sets the text of the text field and reverts any current edits
// to reflect this new text.
func (tf *TextField) SetText(text string) *TextField {
if tf.text == text && !tf.edited {
return tf
}
tf.text = text
tf.revert()
return tf
}
// SetLeadingIcon sets the [TextField.LeadingIcon] to the given icon. If an
// on click function is specified, it also sets the [TextField.LeadingIconOnClick]
// to that function. If no function is specified, it does not override any already
// set function.
func (tf *TextField) SetLeadingIcon(icon icons.Icon, onClick ...func(e events.Event)) *TextField {
tf.LeadingIcon = icon
if len(onClick) > 0 {
tf.LeadingIconOnClick = onClick[0]
}
return tf
}
// SetTrailingIcon sets the [TextField.TrailingIcon] to the given icon. If an
// on click function is specified, it also sets the [TextField.TrailingIconOnClick]
// to that function. If no function is specified, it does not override any already
// set function.
func (tf *TextField) SetTrailingIcon(icon icons.Icon, onClick ...func(e events.Event)) *TextField {
tf.TrailingIcon = icon
if len(onClick) > 0 {
tf.TrailingIconOnClick = onClick[0]
}
return tf
}
// AddClearButton adds a trailing icon button at the end
// of the text field that clears the text in the text field
// when it is clicked.
func (tf *TextField) AddClearButton() *TextField {
return tf.SetTrailingIcon(icons.Close, func(e events.Event) {
tf.clear()
})
}
// SetTypePassword enables [TextField.NoEcho] and adds a trailing
// icon button at the end of the textfield that toggles [TextField.NoEcho].
// It also sets [styles.Style.VirtualKeyboard] to [styles.KeyboardPassword].
func (tf *TextField) SetTypePassword() *TextField {
tf.SetNoEcho(true).SetTrailingIcon(icons.Visibility, func(e events.Event) {
tf.NoEcho = !tf.NoEcho
if tf.NoEcho {
tf.TrailingIcon = icons.Visibility
} else {
tf.TrailingIcon = icons.VisibilityOff
}
if icon := tf.trailingIconButton; icon != nil {
icon.SetIcon(tf.TrailingIcon).Update()
}
}).Styler(func(s *styles.Style) {
s.VirtualKeyboard = styles.KeyboardPassword
})
return tf
}
// textEdited must be called whenever the text is edited.
// it sets the edited flag and ensures a new render of current text.
func (tf *TextField) textEdited() {
tf.edited = true
tf.renderVisible = nil
tf.NeedsRender()
}
// editDone completes editing and copies the active edited text to the [TextField.text].
// It is called when the return key is pressed or the text field goes out of focus.
func (tf *TextField) editDone() {
if tf.edited {
tf.edited = false
tf.text = string(tf.editText)
tf.SendChange()
// widget can be killed after SendChange
if tf.This == nil {
return
}
}
tf.clearSelected()
tf.stopCursor()
}
// revert aborts editing and reverts to the last saved text.
func (tf *TextField) revert() {
tf.renderVisible = nil
tf.editText = []rune(tf.text)
tf.edited = false
tf.cursorPos = min(tf.cursorPos, len(tf.editText)) // within a shorter text
tf.dispRange.Start = 0
tf.dispRange.End = tf.charWidth
tf.selectReset()
tf.NeedsRender()
}
// clear clears any existing text.
func (tf *TextField) clear() {
tf.renderVisible = nil
tf.edited = true
tf.editText = tf.editText[:0]
tf.dispRange.Start = 0
tf.dispRange.End = 0
tf.selectReset()
tf.SetFocus() // this is essential for ensuring that the clear applies after focus is lost..
tf.NeedsRender()
}
// clearError clears any existing validation error.
func (tf *TextField) clearError() {
if tf.error == nil {
return
}
tf.error = nil
tf.Update()
tf.Send(events.LongHoverEnd) // get rid of any validation tooltip
}
// validate runs [TextField.Validator] and takes any necessary actions
// as a result of that.
func (tf *TextField) validate() {
if tf.Validator == nil {
return
}
err := tf.Validator()
if err == nil {
tf.clearError()
return
}
tf.error = err
tf.Update()
// show the error tooltip immediately
tf.Send(events.LongHoverStart)
}
func (tf *TextField) WidgetTooltip(pos image.Point) (string, image.Point) {
if tf.error == nil {
return tf.Tooltip, tf.DefaultTooltipPos()
}
return tf.error.Error(), tf.DefaultTooltipPos()
}
//////// Cursor Navigation
func (tf *TextField) updateLinePos() {
if tf.renderAll == nil {
return
}
tf.cursorLine = tf.renderAll.RuneToLinePos(tf.cursorPos).Line
}
// cursorForward moves the cursor forward
func (tf *TextField) cursorForward(steps int) {
tf.cursorPos += steps
if tf.cursorPos > len(tf.editText) {
tf.cursorPos = len(tf.editText)
}
if tf.cursorPos > tf.dispRange.End {
inc := tf.cursorPos - tf.dispRange.End
tf.dispRange.End += inc
}
tf.updateLinePos()
if tf.selectMode {
tf.selectRegionUpdate(tf.cursorPos)
}
tf.NeedsRender()
}
// cursorForwardWord moves the cursor forward by words
func (tf *TextField) cursorForwardWord(steps int) {
tf.cursorPos, _ = textpos.ForwardWord(tf.editText, tf.cursorPos, steps)
if tf.cursorPos > tf.dispRange.End {
inc := tf.cursorPos - tf.dispRange.End
tf.dispRange.End += inc
}
tf.updateLinePos()
if tf.selectMode {
tf.selectRegionUpdate(tf.cursorPos)
}
tf.NeedsRender()
}
// cursorBackward moves the cursor backward
func (tf *TextField) cursorBackward(steps int) {
tf.cursorPos -= steps
if tf.cursorPos < 0 {
tf.cursorPos = 0
}
if tf.cursorPos <= tf.dispRange.Start {
dec := min(tf.dispRange.Start, 8)
tf.dispRange.Start -= dec
}
tf.updateLinePos()
if tf.selectMode {
tf.selectRegionUpdate(tf.cursorPos)
}
tf.NeedsRender()
}
// cursorBackwardWord moves the cursor backward by words
func (tf *TextField) cursorBackwardWord(steps int) {
tf.cursorPos, _ = textpos.BackwardWord(tf.editText, tf.cursorPos, steps)
if tf.cursorPos <= tf.dispRange.Start {
dec := min(tf.dispRange.Start, 8)
tf.dispRange.Start -= dec
}
tf.updateLinePos()
if tf.selectMode {
tf.selectRegionUpdate(tf.cursorPos)
}
tf.NeedsRender()
}
// cursorDown moves the cursor down
func (tf *TextField) cursorDown(steps int) {
if tf.numLines <= 1 {
return
}
if tf.cursorLine >= tf.numLines-1 {
return
}
tf.cursorPos = tf.renderVisible.RuneAtLineDelta(tf.cursorPos, steps)
tf.updateLinePos()
if tf.selectMode {
tf.selectRegionUpdate(tf.cursorPos)
}
tf.NeedsRender()
}
// cursorUp moves the cursor up
func (tf *TextField) cursorUp(steps int) {
if tf.numLines <= 1 {
return
}
if tf.cursorLine <= 0 {
return
}
tf.cursorPos = tf.renderVisible.RuneAtLineDelta(tf.cursorPos, -steps)
tf.updateLinePos()
if tf.selectMode {
tf.selectRegionUpdate(tf.cursorPos)
}
tf.NeedsRender()
}
// cursorStart moves the cursor to the start of the text, updating selection
// if select mode is active.
func (tf *TextField) cursorStart() {
tf.cursorPos = 0
tf.dispRange.Start = 0
tf.dispRange.End = min(len(tf.editText), tf.dispRange.Start+tf.charWidth)
if tf.selectMode {
tf.selectRegionUpdate(tf.cursorPos)
}
tf.NeedsRender()
}
// CursorPos returns the position of the cursor in the text, in runes.
func (tf *TextField) CursorPos() int {
return tf.cursorPos
}
// SetCursorPos moves the cursor to the given position in the text, in runes
// (within the text), as for a text field that replaces another in which the
// user was typing (see [TextField.CursorPos]), keeping it in the part of the
// text that is shown.
func (tf *TextField) SetCursorPos(pos int) *TextField {
tf.cursorPos = min(max(pos, 0), len(tf.editText))
if tf.cursorPos < tf.dispRange.Start || tf.cursorPos > tf.dispRange.End {
tf.dispRange.Start = max(0, tf.cursorPos-tf.charWidth)
tf.dispRange.End = min(len(tf.editText), tf.dispRange.Start+tf.charWidth)
}
if tf.selectMode {
tf.selectRegionUpdate(tf.cursorPos)
}
tf.NeedsRender()
return tf
}
// SetCursorEnd moves the cursor to the end of the text, as for a text
// field that replaces another in which the user was typing.
func (tf *TextField) SetCursorEnd() *TextField {
tf.cursorEnd()
return tf
}
// cursorEnd moves the cursor to the end of the text, updating selection
// if select mode is active.
func (tf *TextField) cursorEnd() {
ed := len(tf.editText)
tf.cursorPos = ed
tf.dispRange.End = len(tf.editText) // try -- display will adjust
tf.dispRange.Start = max(0, tf.dispRange.End-tf.charWidth)
if tf.selectMode {
tf.selectRegionUpdate(tf.cursorPos)
}
tf.NeedsRender()
}
// cursorBackspace deletes character(s) immediately before cursor
func (tf *TextField) cursorBackspace(steps int) {
if tf.hasSelection() {
tf.deleteSelection()
return
}
if tf.cursorPos < steps {
steps = tf.cursorPos
}
if steps <= 0 {
return
}
tf.editText = append(tf.editText[:tf.cursorPos-steps], tf.editText[tf.cursorPos:]...)
tf.textEdited()
tf.cursorBackward(steps)
}
// cursorDelete deletes character(s) immediately after the cursor
func (tf *TextField) cursorDelete(steps int) {
if tf.hasSelection() {
tf.deleteSelection()
return
}
if tf.cursorPos+steps > len(tf.editText) {
steps = len(tf.editText) - tf.cursorPos
}
if steps <= 0 {
return
}
tf.editText = append(tf.editText[:tf.cursorPos], tf.editText[tf.cursorPos+steps:]...)
tf.textEdited()
}
// cursorBackspaceWord deletes words(s) immediately before cursor
func (tf *TextField) cursorBackspaceWord(steps int) {
if tf.hasSelection() {
tf.deleteSelection()
return
}
org := tf.cursorPos
tf.cursorBackwardWord(steps)
tf.editText = append(tf.editText[:tf.cursorPos], tf.editText[org:]...)
tf.textEdited()
}
// cursorDeleteWord deletes word(s) immediately after the cursor
func (tf *TextField) cursorDeleteWord(steps int) {
if tf.hasSelection() {
tf.deleteSelection()
return
}
// the text from the cursor to the end of the word(s) is deleted,
// and the cursor stays where it is.
end, _ := textpos.ForwardWord(tf.editText, tf.cursorPos, steps)
if end <= tf.cursorPos {
return
}
tf.editText = append(tf.editText[:tf.cursorPos], tf.editText[end:]...)
tf.textEdited()
tf.NeedsRender()
}
// cursorKill deletes text from cursor to end of text
func (tf *TextField) cursorKill() {
steps := len(tf.editText) - tf.cursorPos
tf.cursorDelete(steps)
}
//////// Selection
// clearSelected resets both the global selected flag and any current selection
func (tf *TextField) clearSelected() {
tf.SetState(false, states.Selected)
tf.selectReset()
}
// HasSelection returns whether there is a selected region of text, as
// after [TextField.SelectAll], which typing replaces.
func (tf *TextField) HasSelection() bool {
return tf.hasSelection()
}
// hasSelection returns whether there is a selected region of text
func (tf *TextField) hasSelection() bool {
tf.selectUpdate()
return tf.selectRange.Start < tf.selectRange.End
}
// SetSelectRange sets the selection range
func (tf *TextField) SetSelectRange(r textpos.Range) {
tf.selectRange = r
tf.NeedsRender()
}
// selection returns the currently selected text
func (tf *TextField) selection() string {
if tf.hasSelection() {
return string(tf.editText[tf.selectRange.Start:tf.selectRange.End])
}
return ""
}
// selectModeToggle toggles the SelectMode, updating selection with cursor movement
func (tf *TextField) selectModeToggle() {
if tf.selectMode {
tf.selectMode = false
} else {
tf.selectMode = true
tf.selectInit = tf.cursorPos
tf.selectRange.Start = tf.cursorPos
tf.selectRange.End = tf.selectRange.Start
}
}
// shiftSelect sets the selection start if the shift key is down but wasn't previously.
// If the shift key has been released, the selection info is cleared.
func (tf *TextField) shiftSelect(e events.Event) {
hasShift := e.HasAnyModifier(key.Shift)
if hasShift && !tf.selectMode {
tf.selectModeToggle()
tf.selectModeShift = true
}
if !hasShift && tf.selectMode && tf.selectModeShift {
tf.selectReset()
tf.selectModeShift = false
}
}
// selectRegionUpdate updates current select region based on given cursor position
// relative to SelectStart position
func (tf *TextField) selectRegionUpdate(pos int) {
if pos < tf.selectInit {
tf.selectRange.Start = pos
tf.selectRange.End = tf.selectInit
} else {
tf.selectRange.Start = tf.selectInit
tf.selectRange.End = pos
}
tf.selectUpdate()
}
// SelectAll selects all of the text, which typing then replaces (as for a
// value proposed in a field, such as the last one chosen).
func (tf *TextField) SelectAll() {
tf.selectRange.Start = 0
tf.selectInit = 0
tf.selectRange.End = len(tf.editText)
if TheApp.SystemPlatform().IsMobile() {
tf.Send(events.ContextMenu)
}
tf.NeedsRender()
}
// selectWord selects the word (whitespace delimited) that the cursor is on
func (tf *TextField) selectWord() {
sz := len(tf.editText)
if sz <= 3 {
tf.SelectAll()
return
}
tf.selectRange = textpos.WordAt(tf.editText, tf.cursorPos)
tf.selectInit = tf.selectRange.Start
if TheApp.SystemPlatform().IsMobile() {
tf.Send(events.ContextMenu)
}
tf.NeedsRender()
}
// selectReset resets the selection
func (tf *TextField) selectReset() {
tf.selectMode = false
if tf.selectRange.Start == 0 && tf.selectRange.End == 0 {
return
}
tf.selectRange.Start = 0
tf.selectRange.End = 0
tf.NeedsRender()
}
// selectUpdate updates the select region after any change to the text, to keep it in range
func (tf *TextField) selectUpdate() {
if tf.selectRange.Start < tf.selectRange.End {
ed := len(tf.editText)
if tf.selectRange.Start < 0 {
tf.selectRange.Start = 0
}
if tf.selectRange.End > ed {
tf.selectRange.End = ed
}
} else {
tf.selectReset()
}
}
// cut cuts any selected text and adds it to the clipboard.
func (tf *TextField) cut() { //types:add
if tf.NoEcho {
return
}
cut := tf.deleteSelection()
if cut != "" {
em := tf.Events()
if em != nil {
em.Clipboard().Write(mimedata.NewText(cut))
}
}
}
// deleteSelection deletes any selected text, without adding to clipboard --
// returns text deleted
func (tf *TextField) deleteSelection() string {
tf.selectUpdate()
if !tf.hasSelection() {
return ""
}
cut := tf.selection()
tf.editText = append(tf.editText[:tf.selectRange.Start], tf.editText[tf.selectRange.End:]...)
if tf.cursorPos > tf.selectRange.Start {
if tf.cursorPos < tf.selectRange.End {
tf.cursorPos = tf.selectRange.Start
} else {
tf.cursorPos -= tf.selectRange.End - tf.selectRange.Start
}
}
tf.textEdited()
tf.selectReset()
return cut
}
// copy copies any selected text to the clipboard, and then
// clears the selection, which shows that it was copied.
func (tf *TextField) copy() { //types:add
if tf.NoEcho {
return
}
tf.selectUpdate()
if !tf.hasSelection() {
return
}
md := mimedata.NewText(tf.selection())
tf.Clipboard().Write(md)
tf.selectReset()
}
// paste inserts text from the clipboard at current cursor position; if
// cursor is within a current selection, that selection is replaced.
func (tf *TextField) paste() { //types:add
data := tf.Clipboard().Read([]string{mimedata.TextPlain})
if data != nil {
if tf.cursorPos >= tf.selectRange.Start && tf.cursorPos < tf.selectRange.End {
tf.deleteSelection()
}
text := data.Text(mimedata.TextPlain)
if tf.PasteFilter != nil {
text = tf.PasteFilter(text)
}
tf.insertAtCursor(text)
}
}
// insertAtCursor inserts the given text at current cursor position.
func (tf *TextField) insertAtCursor(str string) {
if tf.hasSelection() { // replaced, not cut to the clipboard, as in browsers
tf.deleteSelection()
}
rs := []rune(str)
rsl := len(rs)
nt := append(tf.editText, rs...) // first append to end
copy(nt[tf.cursorPos+rsl:], nt[tf.cursorPos:]) // move stuff to end
copy(nt[tf.cursorPos:], rs) // copy into position
tf.editText = nt
tf.dispRange.End += rsl
tf.textEdited()
tf.cursorForward(rsl)
}
func (tf *TextField) contextMenu(m *Scene, pos image.Point) {
NewFuncButton(m).SetFunc(tf.copy).SetIcon(icons.Copy).SetKey(keymap.Copy).SetState(tf.NoEcho || !tf.hasSelection(), states.Disabled)
if !tf.IsReadOnly() {
NewFuncButton(m).SetFunc(tf.cut).SetIcon(icons.Cut).SetKey(keymap.Cut).SetState(tf.NoEcho || !tf.hasSelection(), states.Disabled)
paste := NewFuncButton(m).SetFunc(tf.paste).SetIcon(icons.Paste).SetKey(keymap.Paste)
cb := tf.Scene.Events.Clipboard()
if cb != nil {
paste.SetState(cb.IsEmpty(), states.Disabled)
}
}
}
//////// Undo
// textFieldUndoRecord holds one undo record
type textFieldUndoRecord struct {
text []rune
cursorPos int
}
func (ur *textFieldUndoRecord) set(txt []rune, curpos int) {
ur.text = slices.Clone(txt)
ur.cursorPos = curpos
}
// textFieldUndos manages everything about the undo process for a [TextField].
type textFieldUndos struct {
// stack of undo records
stack []textFieldUndoRecord
// position within the undo stack
pos int
// last time undo was saved, for grouping
lastSave time.Time
}
func (us *textFieldUndos) saveUndo(txt []rune, curpos int) {
n := len(us.stack)
now := time.Now()
ts := now.Sub(us.lastSave)
if n > 0 && ts < 250*time.Millisecond {
// a quick edit is in the group of the last record, which keeps the
// text from before the group, so that undo goes back to it.
return
}
r := textFieldUndoRecord{}
r.set(txt, curpos)
us.stack = append(us.stack, r)
us.pos = len(us.stack)
us.lastSave = now
}
func (tf *TextField) saveUndo() {
tf.undos.saveUndo(tf.editText, tf.cursorPos)
}
func (us *textFieldUndos) undo(txt []rune, curpos int) *textFieldUndoRecord {
n := len(us.stack)
if us.pos <= 0 || n == 0 {
return nil // nothing to undo
}
if us.pos == n {
us.lastSave = time.Time{}
us.saveUndo(txt, curpos)
us.pos--
}
us.pos--
us.lastSave = time.Time{} // prevent any merging
r := &us.stack[us.pos]
return r
}
func (tf *TextField) undo() {
r := tf.undos.undo(tf.editText, tf.cursorPos)
if r != nil {
tf.editText = r.text
tf.cursorPos = r.cursorPos
tf.renderVisible = nil
tf.NeedsRender()
}
}
func (us *textFieldUndos) redo() *textFieldUndoRecord {
n := len(us.stack)
if us.pos >= n-1 {
return nil
}
us.lastSave = time.Time{} // prevent any merging
us.pos++
return &us.stack[us.pos]
}
func (tf *TextField) redo() {
r := tf.undos.redo()
if r != nil {
tf.editText = r.text
tf.cursorPos = r.cursorPos
tf.renderVisible = nil
tf.NeedsRender()
}
}
//////// Complete
// SetCompleter sets completion functions so that completions will
// automatically be offered as the user types.
func (tf *TextField) SetCompleter(data any, matchFun complete.MatchFunc, editFun complete.EditFunc) {
if matchFun == nil || editFun == nil {
tf.complete = nil
return
}
tf.complete = NewComplete().SetContext(data).SetMatchFunc(matchFun).SetEditFunc(editFun)
tf.complete.OnSelect(func(e events.Event) {
tf.completeText(tf.complete.Completion)
})
}
// offerComplete pops up a menu of possible completions
func (tf *TextField) offerComplete() {
if tf.complete == nil {
return
}
s := string(tf.editText[0:tf.cursorPos])
cpos := tf.charRenderPos(tf.cursorPos).ToPoint()
cpos.X += 5
cpos.Y = tf.Geom.TotalBBox.Max.Y
tf.complete.SrcLn = 0
tf.complete.SrcCh = tf.cursorPos
tf.complete.Show(tf, cpos, s)
}
// cancelComplete cancels any pending completion -- call this when new events
// have moved beyond any prior completion scenario
func (tf *TextField) cancelComplete() {
if tf.complete == nil {
return
}
tf.complete.Cancel()
}
// completeText edits the text field using the string chosen from the completion menu
func (tf *TextField) completeText(s string) {
txt := string(tf.editText) // Reminder: do NOT call tf.Text() in an active editing context!
c := tf.complete.GetCompletion(s)
ed := tf.complete.EditFunc(tf.complete.Context, txt, tf.cursorPos, c, tf.complete.Seed)
st := tf.cursorPos - utf8.RuneCountInString(tf.complete.Seed)
tf.cursorPos = st
tf.cursorDelete(ed.ForwardDelete)
tf.insertAtCursor(ed.NewText)
tf.editDone()
}
//////// Rendering
// hasWordWrap returns true if the layout is multi-line word wrapping
func (tf *TextField) hasWordWrap() bool {
return tf.Styles.Text.WhiteSpace.HasWordWrap()
}
// charPos returns the relative starting position of the given rune,
// in the overall RenderAll of all the text.
// These positions can be out of visible range: see CharRenderPos
func (tf *TextField) charPos(idx int) math32.Vector2 {
if idx <= 0 || len(tf.renderAll.Lines) == 0 {
return math32.Vector2{}
}
bb := tf.renderAll.RuneBounds(idx)
if idx >= len(tf.editText) {
if tf.numLines > 1 && tf.editText[len(tf.editText)-1] == ' ' {
bb.Max.X += tf.lineHeight * 0.2
return bb.Max
}
return bb.Max
}
return bb.Min
}
// relCharPos returns the text width in dots between the two text string
// positions (ed is exclusive -- +1 beyond actual char).
func (tf *TextField) relCharPos(st, ed int) math32.Vector2 {
return tf.charPos(ed).Sub(tf.charPos(st))
}
// charRenderPos returns the starting render coords for the given character
// position in string -- makes no attempt to rationalize that pos (i.e., if
// not in visible range, position will be out of range too).
func (tf *TextField) charRenderPos(charidx int) math32.Vector2 {
pos := tf.effPos
sc := tf.Scene
pos = pos.Add(math32.FromPoint(sc.SceneGeom.Pos))
cpos := tf.relCharPos(tf.dispRange.Start, charidx)
return pos.Add(cpos)
}
var (
// textFieldSpriteName is the name of the window sprite used for the cursor.
textFieldSpriteName = "TextField.Cursor"
)
// startCursor starts the cursor blinking and renders it
func (tf *TextField) startCursor() {
if tf == nil || tf.This == nil || !tf.IsVisible() {
return
}
if tf.IsReadOnly() || !tf.AbilityIs(abilities.Focusable) {
return
}
tf.toggleCursor(true)
}
// stopCursor stops the cursor from blinking
func (tf *TextField) stopCursor() {
tf.toggleCursor(false)
}
// toggleSprite turns on or off the cursor sprite.
func (tf *TextField) toggleCursor(on bool) {
TextCursor(on, tf.AsWidget(), textFieldSpriteName, tf.CursorWidth.Dots, tf.lineHeight, tf.CursorColor, func() image.Point {
return TextCursorPoint(tf.charRenderPos(tf.cursorPos))
})
}
// updateCursorPosition updates the position of the cursor.
func (tf *TextField) updateCursorPosition() {
if tf.IsReadOnly() || !tf.StateIs(states.Focused) {
return
}
sc := tf.Scene
if sc == nil || sc.Stage == nil || sc.Stage.Main == nil {
return
}
ms := sc.Stage.Main
ms.Sprites.Lock()
sp, ok := ms.Sprites.SpriteByNameNoLock(textFieldSpriteName)
if ok {
sp.EventBBox.Min = TextCursorPoint(tf.charRenderPos(tf.cursorPos))
}
ms.Sprites.Unlock()
// The sprites are removed when the scene is rebuilt or resized,
// so the cursor of the focused text field is started again.
if !ok {
tf.startCursor()
}
tf.updateTextInput()
tf.scrollCursorIntoView()
}
// textFieldCursorShown is the state of a [TextField] for which its cursor
// was scrolled into view: its position in the text, the length of the
// text, the position of the cursor in the text field, and the sizes of
// the text field, of the frame that it scrolls in, and of the scene, none
// of which change as it is scrolled.
type textFieldCursorShown struct {
pos, n int
cursor math32.Vector2
fieldSize, frameSize, sceneSize math32.Vector2
}
// scrollCursorIntoView scrolls the frame that the text field is in so that
// its cursor is visible, if the cursor moved, the text changed, or the
// text field, the frame or the scene was resized since it last did, as
// when the text field grows with the text that is typed into it, or the
// scene gets smaller as the virtual keyboard of a mobile platform is
// shown. It does not otherwise, so that the frame can be scrolled away
// from the cursor of a focused text field.
func (tf *TextField) scrollCursorIntoView() {
fr := tf.parentScrollFrame()
if fr == nil {
return
}
cs := textFieldCursorShown{pos: tf.cursorPos, n: len(tf.editText), cursor: tf.relCharPos(tf.dispRange.Start, tf.cursorPos),
fieldSize: tf.Geom.Size.Actual.Total, frameSize: fr.Geom.Size.Actual.Content, sceneSize: math32.FromPoint(tf.Scene.SceneGeom.Size)}
if cs == tf.cursorShown {
return
}
tf.cursorShown = cs
pos := tf.charRenderPos(tf.cursorPos).ToPointFloor().Sub(tf.Scene.SceneGeom.Pos) // (in the scene)
box := image.Rectangle{Min: pos, Max: pos.Add(image.Pt(max(1, int(tf.CursorWidth.Dots)), int(math32.Ceil(tf.lineHeight))))}
// after the render: this is called while the text field renders, and
// scrolling can update it, as the rows of a list are when it scrolls,
// which cleared its text as it was rendered (a panic)
tf.Defer(func() { fr.ScrollToBox(box) })
}
// renderSelect renders the selected region, if any, underneath the text
func (tf *TextField) renderSelect() {
tf.renderVisible.SelectReset()
if !tf.hasSelection() {
return
}
dn := tf.dispRange.Len()
effst := max(0, tf.selectRange.Start-tf.dispRange.Start)
effed := min(dn, tf.selectRange.End-tf.dispRange.Start)
if effst == effed {
return
}
tf.renderVisible.SelectRegion(textpos.Range{Start: effst, End: effed})
}
// renderHighlights renders the highlights regions, if any, underneath the text
func (tf *TextField) renderHighlights() {
tf.renderVisible.HighlightReset()
dn := tf.dispRange.Len()
for _, r := range tf.highlights {
effst := max(0, r.Start-tf.dispRange.Start)
effed := min(dn, r.End-tf.dispRange.Start)
if effst == effed {
return
}
tf.renderVisible.HighlightRegion(textpos.Range{Start: effst, End: effed})
}
}
// autoScroll scrolls the starting position to keep the cursor visible,
// and does various other state-updating steps to ensure everything is updated.
// This is called during Render().
func (tf *TextField) autoScroll() {
sz := &tf.Geom.Size
icsz := tf.iconsSize()
availSz := sz.Actual.Content.Sub(icsz)
if tf.renderAll != nil {
availSz.Y += tf.renderAll.LineHeight * 2 // allow it to add a line
}
tf.configTextSize(availSz)
n := len(tf.editText)
tf.cursorPos = math32.Clamp(tf.cursorPos, 0, n)
if tf.hasWordWrap() { // does not scroll
tf.dispRange.Start = 0
tf.dispRange.End = n
if len(tf.renderAll.Lines) != tf.numLines {
tf.renderVisible = nil
tf.NeedsLayout()
}
return
}
st := &tf.Styles
if n == 0 || tf.Geom.Size.Actual.Content.X <= 0 {
tf.cursorPos = 0
tf.dispRange.End = 0
tf.dispRange.Start = 0
return
}
maxw := tf.effSize.X
if maxw < 0 {
return
}
tf.charWidth = max(
// rough guess in chars
int(maxw/st.UnitContext.Dots(units.UnitCh)), 1)
// first rationalize all the values
if tf.dispRange.End == 0 || tf.dispRange.End > n { // not init
tf.dispRange.End = n
}
if tf.dispRange.Start >= tf.dispRange.End {
tf.dispRange.Start = max(0, tf.dispRange.End-tf.charWidth)
}
inc := int(math32.Ceil(.1 * float32(tf.charWidth)))
inc = max(4, inc)
// keep cursor in view with buffer
startIsAnchor := true
if tf.cursorPos < (tf.dispRange.Start + inc) {
tf.dispRange.Start -= inc
tf.dispRange.Start = max(tf.dispRange.Start, 0)
tf.dispRange.End = tf.dispRange.Start + tf.charWidth
tf.dispRange.End = min(n, tf.dispRange.End)
} else if tf.cursorPos > (tf.dispRange.End - inc) {
tf.dispRange.End += inc
tf.dispRange.End = min(tf.dispRange.End, n)
tf.dispRange.Start = tf.dispRange.End - tf.charWidth
tf.dispRange.Start = max(0, tf.dispRange.Start)
startIsAnchor = false
}
if tf.dispRange.End < tf.dispRange.Start {
return
}
if startIsAnchor {
gotWidth := false
spos := tf.charPos(tf.dispRange.Start).X
for {
w := tf.charPos(tf.dispRange.End).X - spos
if w < maxw {
if tf.dispRange.End == n {
break
}
nw := tf.charPos(tf.dispRange.End+1).X - spos
if nw >= maxw {
gotWidth = true
break
}
tf.dispRange.End++
} else {
tf.dispRange.End--
}
}
if gotWidth || tf.dispRange.Start == 0 {
return
}
// otherwise, try getting some more chars by moving up start..
}
// end is now anchor
epos := tf.charPos(tf.dispRange.End).X
for {
w := epos - tf.charPos(tf.dispRange.Start).X
if w < maxw {
if tf.dispRange.Start == 0 {
break
}
nw := epos - tf.charPos(tf.dispRange.Start-1).X
if nw >= maxw {
break
}
tf.dispRange.Start--
} else {
tf.dispRange.Start++
}
}
}
// pixelToCursor finds the cursor position that corresponds to the given pixel location
func (tf *TextField) pixelToCursor(pt image.Point) int {
ptf := math32.FromPoint(pt)
rpt := ptf.Sub(tf.effPos)
if rpt.X <= 0 || rpt.Y < 0 {
return tf.dispRange.Start
}
n := len(tf.editText)
if tf.hasWordWrap() {
ix := tf.renderAll.RuneAtPoint(ptf, tf.effPos)
if ix >= 0 {
return ix
}
return tf.dispRange.Start
}
pr := tf.PointToRelPos(pt)
px := float32(pr.X)
st := &tf.Styles
c := tf.dispRange.Start + int(float64(px/st.UnitContext.Dots(units.UnitCh)))
c = min(c, n)
w := tf.relCharPos(tf.dispRange.Start, c).X
if w > px {
for w > px {
c--
if c <= tf.dispRange.Start {
c = tf.dispRange.Start
break
}
w = tf.relCharPos(tf.dispRange.Start, c).X
}
} else if w < px {
for c < tf.dispRange.End {
wn := tf.relCharPos(tf.dispRange.Start, c+1).X
if wn > px {
break
} else if wn == px {
c++
break
}
c++
}
}
return c
}
// setCursorFromPixel finds cursor location from given scene-relative
// pixel location, and sets current cursor to it, updating selection too.
func (tf *TextField) setCursorFromPixel(pt image.Point, selMode events.SelectModes) {
oldPos := tf.cursorPos
tf.cursorPos = tf.pixelToCursor(pt)
if tf.selectMode || selMode != events.SelectOne {
if !tf.selectMode && selMode != events.SelectOne {
tf.selectRange.Start = oldPos
tf.selectMode = true
}
if !tf.StateIs(states.Sliding) && selMode == events.SelectOne {
tf.selectReset()
} else {
tf.selectRegionUpdate(tf.cursorPos)
}
tf.selectUpdate()
} else if tf.hasSelection() {
tf.selectReset()
}
tf.NeedsRender()
}
func (tf *TextField) handleKeyEvents() {
tf.On(events.Composition, func(e events.Event) {
tf.accepted = false
tf.compose(e.(*events.TextComposition))
e.SetHandled()
})
tf.OnKeyChord(func(e events.Event) {
kf := keymap.Of(e.KeyChord())
if DebugSettings.KeyEventTrace {
slog.Info("TextField KeyInput", "widget", tf, "keyFunction", kf)
}
if !tf.StateIs(states.Focused) && kf == keymap.Abort {
return
}
if tf.accepted {
if kf != keymap.None {
return
}
tf.accepted = false
}
tf.startCursor()
// first all the keys that work for both inactive and active
switch kf {
case keymap.MoveRight:
e.SetHandled()
tf.shiftSelect(e)
tf.cursorForward(1)
tf.offerComplete()
case keymap.WordRight:
e.SetHandled()
tf.shiftSelect(e)
tf.cursorForwardWord(1)
tf.offerComplete()
case keymap.MoveLeft:
e.SetHandled()
tf.shiftSelect(e)
tf.cursorBackward(1)
tf.offerComplete()
case keymap.WordLeft:
e.SetHandled()
tf.shiftSelect(e)
tf.cursorBackwardWord(1)
tf.offerComplete()
case keymap.MoveDown:
if tf.numLines > 1 {
e.SetHandled()
tf.shiftSelect(e)
tf.cursorDown(1)
}
case keymap.MoveUp:
if tf.numLines > 1 {
e.SetHandled()
tf.shiftSelect(e)
tf.cursorUp(1)
}
case keymap.Home:
e.SetHandled()
tf.shiftSelect(e)
tf.cancelComplete()
tf.cursorStart()
case keymap.End:
e.SetHandled()
tf.shiftSelect(e)
tf.cancelComplete()
tf.cursorEnd()
case keymap.SelectMode:
e.SetHandled()
tf.cancelComplete()
tf.selectModeToggle()
case keymap.CancelSelect:
e.SetHandled()
tf.cancelComplete()
tf.selectReset()
case keymap.SelectAll:
e.SetHandled()
tf.cancelComplete()
tf.SelectAll()
case keymap.Copy:
e.SetHandled()
tf.cancelComplete()
tf.copy()
}
if tf.IsReadOnly() || e.IsHandled() {
return
}
switch kf {
case keymap.Enter:
fallthrough
case keymap.FocusNext: // we process tab to make it EditDone as opposed to other ways of losing focus
e.SetHandled()
tf.cancelComplete()
tf.editDone()
tf.focusNext()
case keymap.Accept: // ctrl+enter
e.SetHandled()
tf.cancelComplete()
tf.editDone()
tf.accepted = true
case keymap.FocusPrev:
e.SetHandled()
tf.cancelComplete()
tf.editDone()
tf.focusPrev()
case keymap.Abort: // esc
e.SetHandled()
tf.cancelComplete()
tf.revert()
// tf.FocusChanged(FocusInactive)
case keymap.Backspace:
e.SetHandled()
tf.saveUndo()
tf.cursorBackspace(1)
tf.offerComplete()
tf.Send(events.Input, e)
case keymap.Kill:
e.SetHandled()
tf.cancelComplete()
tf.cursorKill()
tf.Send(events.Input, e)
case keymap.Delete:
e.SetHandled()
tf.saveUndo()
tf.cursorDelete(1)
tf.offerComplete()
tf.Send(events.Input, e)
case keymap.BackspaceWord:
e.SetHandled()
tf.saveUndo()
tf.cursorBackspaceWord(1)
tf.offerComplete()
tf.Send(events.Input, e)
case keymap.DeleteWord:
e.SetHandled()
tf.saveUndo()
tf.cursorDeleteWord(1)
tf.offerComplete()
tf.Send(events.Input, e)
case keymap.Cut:
e.SetHandled()
tf.saveUndo()
tf.cancelComplete()
tf.cut()
tf.Send(events.Input, e)
case keymap.Paste:
e.SetHandled()
tf.saveUndo()
tf.cancelComplete()
tf.paste()
tf.Send(events.Input, e)
case keymap.Undo:
e.SetHandled()
tf.undo()
case keymap.Redo:
e.SetHandled()
tf.redo()
case keymap.Complete:
e.SetHandled()
tf.offerComplete()
case keymap.None:
if unicode.IsPrint(e.KeyRune()) {
if !e.HasAnyModifier(key.Control, key.Meta) {
e.SetHandled()
tf.saveUndo()
tf.insertAtCursor(string(e.KeyRune()))
if e.KeyRune() == ' ' {
tf.cancelComplete()
} else {
tf.offerComplete()
}
tf.Send(events.Input, e)
}
}
}
})
tf.OnFocus(func(e events.Event) {
tf.accepted = false
tf.cursorShown = textFieldCursorShown{}
if tf.IsReadOnly() {
e.SetHandled()
} else {
tf.startCursor()
}
})
tf.OnFocusLost(func(e events.Event) {
if tf.IsReadOnly() {
e.SetHandled()
return
}
tf.endComposition()
tf.ClearTextInput()
tf.editDone()
})
}
func (tf *TextField) Style() {
tf.WidgetBase.Style()
tf.CursorWidth.ToDots(&tf.Styles.UnitContext)
}
func (tf *TextField) configTextSize(sz math32.Vector2) math32.Vector2 {
txt := tf.editText
if len(txt) == 0 && len(tf.Placeholder) > 0 {
txt = []rune(tf.Placeholder)
}
if tf.NoEcho {
txt = concealDots(len(tf.editText))
}
sty, tsty := tf.Styles.NewRichText()
etxs := *tsty
etxs.Align, etxs.AlignV = text.Start, text.Start // only works with this
tx := rich.NewText(sty, txt)
tf.renderAll = tf.Scene.TextShaper().WrapLines(tx, sty, &etxs, sz)
rsz := tf.renderAll.Bounds.Size().Ceil()
return rsz
}
func (tf *TextField) iconsSize() math32.Vector2 {
var sz math32.Vector2
if lead := tf.leadingIconButton; lead != nil {
sz.X += lead.Geom.Size.Actual.Total.X
}
if trail := tf.trailingIconButton; trail != nil {
sz.X += trail.Geom.Size.Actual.Total.X
}
return sz
}
func (tf *TextField) SizeUp() {
tf.renderVisible = nil
tf.Frame.SizeUp()
txt := tf.editText
if len(txt) == 0 && len(tf.Placeholder) > 0 {
txt = []rune(tf.Placeholder)
}
tf.dispRange.Start = 0
tf.dispRange.End = len(txt)
sz := &tf.Geom.Size
icsz := tf.iconsSize()
availSz := sz.Actual.Content.Sub(icsz)
wraps := tf.Styles.Text.WhiteSpace.HasWordWrap()
if wraps {
// as wide as its text on one line (its preferred width), within
// its Max; it wraps in the width that it is given (in SizeDown),
// as text does (it wrapped at its Min width, as the user agent of
// the settings of the web browser, which was many lines high)
w := float32(1e6)
if sz.Max.X > 0 {
w = sz.Max.X - icsz.X
}
if tf.Scene != nil && tf.Scene.hasFlag(sceneContentSizing) {
// a window (or dialog) sized to its content is not wider than
// a readable measure of text, as for text (see [Text.SizeUp])
m := units.Ch(contentSizingMeasure)
m.ToDots(&tf.Styles.UnitContext)
w = min(w, m.Dots-icsz.X)
}
availSz.X = max(availSz.X, w)
}
rsz := tf.configTextSize(availSz)
rsz.SetAdd(icsz)
sz.FitSizeMax(&sz.Actual.Content, rsz)
sz.SetTotalFromContent(&sz.Actual)
if wraps {
sz.setIntrinsicWidths(tf.minContentWidth()+icsz.X, sz.Actual.Content.X)
// its Min is the width that it prefers to be at least, not one
// that it is never narrower than, which is that of its longest word
sz.minWidth = min(sz.minWidth, math32.Ceil(tf.minContentWidth()+icsz.X+sz.Space.X))
}
tf.lineHeight = tf.Styles.LineHeightDots()
if DebugSettings.LayoutTrace {
fmt.Println(tf, "TextField SizeUp:", rsz, "Actual:", sz.Actual.Content)
}
}
// growsFromContent returns whether the text field starts from the width
// of its text (on one line) when it is narrowed in a row, not from its
// Max, which it does when its text wraps (see [contentGrower]).
func (tf *TextField) growsFromContent() bool {
return tf.Styles.Text.WhiteSpace.HasWordWrap()
}
// textFieldMinWidth is the narrowest that a text field is, in ch, when it
// has no words to be as wide as (see [TextField.minContentWidth]).
const textFieldMinWidth = 4
// minContentWidth returns the min-content width of the text of the text
// field (without its icons): the width of its longest word (or of its
// placeholder), and at least [textFieldMinWidth], within its style Min.
func (tf *TextField) minContentWidth() float32 {
txt := string(tf.editText)
if len(txt) == 0 {
txt = tf.Placeholder
}
if tf.NoEcho {
txt = string(concealDots(len(tf.editText)))
}
key := fmt.Sprintf("%s\x00%g", txt, tf.Styles.Font.Size.Dots)
if tf.minWordKey != key {
tf.minWordKey, tf.minWord = key, longestWordWidth(tf.Scene, &tf.Styles, txt)
}
floor := units.Ch(textFieldMinWidth)
floor.ToDots(&tf.Styles.UnitContext)
return min(max(tf.minWord, floor.Dots), tf.styleMinDots().X)
}
func (tf *TextField) SizeDown(iter int) bool {
sz := &tf.Geom.Size
prevContent := sz.Actual.Content
sz.setInitContentMin(tf.styleMinDots())
if tf.Styles.Text.WhiteSpace.HasWordWrap() && sz.Alloc.Content.X < sz.Actual.Content.X {
// narrower than its Min when it is given less width, down to the
// width of its longest word, in which it wraps (as text does)
sz.Actual.Content.X = max(sz.Alloc.Content.X, sz.minWidth-sz.Space.X)
}
pgrow, _ := tf.growToAllocSize(sz.Actual.Content, sz.Alloc.Content, sz.Max) // get before update
icsz := tf.iconsSize()
availSz := pgrow.Sub(icsz)
rsz := tf.configTextSize(availSz)
rsz.SetAdd(icsz)
// start over so we don't reflect hysteresis of prior guess
chg := prevContent != sz.Actual.Content
if chg {
if DebugSettings.LayoutTrace {
fmt.Println(tf, "TextField Size Changed:", sz.Actual.Content, "was:", prevContent)
}
}
if tf.Styles.Grow.X > 0 {
rsz.X = max(pgrow.X, rsz.X)
}
if tf.Styles.Grow.Y > 0 {
rsz.Y = max(pgrow.Y, rsz.Y)
}
sz.FitSizeMax(&sz.Actual.Content, rsz)
sz.SetTotalFromContent(&sz.Actual)
sz.Alloc = sz.Actual // this is important for constraining our children layout:
redo := tf.Frame.SizeDown(iter)
return chg || redo
}
func (tf *TextField) SizeFinal() {
tf.Geom.RelPos.SetZero()
// tf.sizeFromChildrenFit(0, SizeFinalPass) // key to omit
tf.growToAlloc()
tf.sizeFinalChildren()
tf.styleSizeUpdate() // now that sizes are stable, ensure styling based on size is updated
tf.sizeFinalParts()
}
func (tf *TextField) ApplyScenePos() {
tf.Frame.ApplyScenePos()
tf.setEffPosAndSize()
}
// setEffPosAndSize sets the effective position and size of
// the textfield based on its base position and size
// and its icons or lack thereof
func (tf *TextField) setEffPosAndSize() {
sz := tf.Geom.Size.Actual.Content
pos := tf.Geom.Pos.Content
if lead := tf.leadingIconButton; lead != nil {
pos.X += lead.Geom.Size.Actual.Total.X
sz.X -= lead.Geom.Size.Actual.Total.X
}
if trail := tf.trailingIconButton; trail != nil {
sz.X -= trail.Geom.Size.Actual.Total.X
}
if tf.renderAll == nil {
tf.numLines = 0
} else {
tf.numLines = len(tf.renderAll.Lines)
}
if tf.numLines <= 1 {
pos.Y += 0.5 * (sz.Y - tf.lineHeight) // center
}
tf.effSize = sz.Ceil()
tf.effPos = pos.Ceil()
}
func (tf *TextField) layoutCurrent() {
cur := tf.editText[tf.dispRange.Start:tf.dispRange.End]
clr := tf.Styles.Color
if len(tf.editText) == 0 && len(tf.Placeholder) > 0 {
clr = tf.PlaceholderColor
cur = []rune(tf.Placeholder)
} else if tf.NoEcho {
cur = concealDots(len(cur))
}
sz := &tf.Geom.Size
icsz := tf.iconsSize()
availSz := sz.Actual.Content.Sub(icsz)
sty, tsty := tf.Styles.NewRichText()
tsty.Color = colors.ToUniform(clr)
tx := rich.NewText(sty, cur)
if tf.composition.active && !tf.NoEcho && len(tf.editText) > 0 {
tx = tf.compositionText(sty, cur)
}
tf.renderVisible = tf.Scene.TextShaper().WrapLines(tx, sty, tsty, availSz)
tf.renderedRange = tf.dispRange
}
func (tf *TextField) Render() {
tf.autoScroll() // does all update checking, inits paint with our style
tf.RenderAllocBox()
if tf.dispRange.Start < 0 || tf.dispRange.End > len(tf.editText) {
return
}
if tf.renderVisible == nil || tf.dispRange != tf.renderedRange {
tf.layoutCurrent()
}
tf.updateCursorPosition()
tf.renderHighlights()
tf.renderSelect()
tf.Scene.Painter.DrawText(tf.renderVisible, tf.effPos)
}
// concealDots creates an n-length []rune of bullet characters.
func concealDots(n int) []rune {
dots := make([]rune, n)
for i := range dots {
dots[i] = '•'
}
return dots
}
//////// Search interface
// TextRunes returns any text content associated with the widget, to be used
// for Search for example. If this is nil, then it is excluded from search.
func (tf *TextField) TextRunes() []rune {
return tf.editText
}
// Search returns text search results for this widget, searching for
// the find string with given case sensitivity. It is up to each widget
// to define the meaning of the Region line, char values for the matches.
// The bool return value indicates whether this widget handled the search,
// thereby excluding further searching within the elements under it.
func (tf *TextField) Search(find string, useCase CaseSensitive) ([]textpos.Match, bool) {
return SearchRunes(tf.editText, find, useCase), true
}
// HighlightMatches does highlighting of the given matches within this widget,
// where the matches are as returned from the Search method.
// Passing a nil causes matches to be reset.
// Any existing highlighting should always be reset first regardless.
// The bool return value indicates whether this widget handled the search,
// thereby excluding further searching within the elements under it.
func (tf *TextField) HighlightMatches(matches []textpos.Match) bool {
tf.highlights = nil
tf.NeedsRender()
if matches == nil {
return true
}
for _, m := range matches {
tf.highlights = append(tf.highlights, textpos.Range{Start: m.Region.Start.Char, End: m.Region.End.Char})
}
return true
}
// SelectMatch selects match at given index from among those returned
// from the Search method. scroll = scroll widget into view.
// reset = clear selection instead of selecting (does not scroll).
func (tf *TextField) SelectMatch(matches []textpos.Match, index int, scroll SelectionScroll, reset SelectionReset) {
if reset {
tf.selectReset()
return
}
match := matches[index]
tf.selectRange = textpos.Range{Start: match.Region.Start.Char, End: match.Region.End.Char}
tf.NeedsRender()
if scroll {
tf.ScrollThisToTop()
}
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"image"
"slices"
"cogentcore.org/core/events"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/system"
"cogentcore.org/core/text/rich"
)
// textFieldComposition is the state of text being composed with an input
// method (IME) in a [TextField], which is provisionally in its edit text,
// underlined, until the composition ends, when it is removed: any committed
// text then follows as KeyChord events, which insert it as typed text.
type textFieldComposition struct {
// active is whether text is being composed.
active bool
// start is the position of the composition in the edit text, in runes,
// and n is its length.
start, n int
}
// compose handles a [events.Composition] event from an input method,
// showing the text being composed at the cursor, or ending the
// composition if it is empty.
func (tf *TextField) compose(e *events.TextComposition) {
if tf.IsReadOnly() || tf.NoEcho {
return
}
if e.Text == "" {
tf.endComposition()
return
}
cp := &tf.composition
if !cp.active {
if tf.hasSelection() { // typing replaces the selection
tf.deleteSelection()
}
cp.active, cp.start, cp.n = true, tf.cursorPos, 0
}
txt := []rune(e.Text)
tf.editText = slices.Replace(tf.editText, cp.start, cp.start+cp.n, txt...)
tf.dispRange.End = max(0, min(tf.dispRange.End+len(txt)-cp.n, len(tf.editText)))
cp.n = len(txt)
tf.cursorPos = cp.start + max(0, min(e.End, cp.n)) // the input method cursor
tf.renderVisible = nil
tf.NeedsRender()
}
// endComposition ends any composition, removing its text.
func (tf *TextField) endComposition() {
cp := &tf.composition
if !cp.active {
return
}
cp.active = false
end := min(cp.start+cp.n, len(tf.editText))
tf.editText = slices.Delete(tf.editText, cp.start, end)
tf.dispRange.End = max(0, min(tf.dispRange.End-(end-cp.start), len(tf.editText)))
tf.dispRange.Start = min(tf.dispRange.Start, tf.dispRange.End)
tf.cursorPos = cp.start
tf.renderVisible = nil
tf.NeedsRender()
}
// compositionText returns the visible text as rich text,
// with the part of it that is being composed underlined.
func (tf *TextField) compositionText(sty *rich.Style, cur []rune) rich.Text {
cp := &tf.composition
st := max(cp.start-tf.dispRange.Start, 0)
ed := min(cp.start+cp.n-tf.dispRange.Start, len(cur))
if st >= ed {
return rich.NewText(sty, cur)
}
usty := *sty
usty.SetDecoration(rich.Underline)
var tx rich.Text
tx.AddSpan(sty, cur[:st]).AddSpan(&usty, cur[st:ed]).AddSpan(sty, cur[ed:])
return tx
}
// updateTextInput updates the text input state of the window for the
// input method, with the position of the cursor, which is that of the
// input method within the text being composed, if any.
func (tf *TextField) updateTextInput() {
if tf.IsReadOnly() || !tf.StateIs(states.Focused) || tf.renderVisible == nil {
return
}
cmin := tf.charRenderPos(tf.cursorPos).ToPointFloor()
h := int(tf.renderVisible.LineHeight + 0.5)
ti := system.TextInput{Caret: image.Rectangle{Min: cmin, Max: cmin.Add(image.Pt(max(1, int(tf.CursorWidth.Dots)), h))}}
if !tf.NoEcho {
end := tf.cursorPos
if tf.composition.active {
end = tf.composition.start
}
ti.Before = system.TextInputBefore(tf.editText[:min(end, len(tf.editText))])
}
tf.SetTextInput(ti)
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"cogentcore.org/core/system"
)
// SetTextInput sets the state of text input in the window of the widget
// for the input method (IME) of the operating system: the rectangle of the
// text cursor, or the cursor of the input method within the text being
// composed, in window coordinates, and the text before it (see
// [system.TextInput] and [system.Window.SetTextInput]).
// Focused text widgets call it when their cursor moves, and it does
// nothing if the state has not changed. The input method then sends the
// text being composed as [events.Composition] events.
func (wb *WidgetBase) SetTextInput(ti system.TextInput) {
rw := wb.textInputWindow()
if rw == nil {
return
}
if rw.textInput != nil && *rw.textInput == ti && rw.textInputWidget == wb.This {
return
}
rw.textInput = &ti
rw.textInputWidget = wb.This.(Widget)
rw.SystemWindow.SetTextInput(rw.textInput)
}
// ClearTextInput clears the state of text input in the window of the
// widget if the widget set it with [WidgetBase.SetTextInput], which
// ends any text being composed. Text widgets call it when they lose
// the focus.
func (wb *WidgetBase) ClearTextInput() {
rw := wb.textInputWindow()
if rw == nil || rw.textInputWidget == nil || rw.textInputWidget.AsWidget() != wb {
return
}
rw.textInput = nil
rw.textInputWidget = nil
rw.SystemWindow.SetTextInput(nil)
}
// textInputWindow returns the render window of the widget,
// or nil if it does not have a system window.
func (wb *WidgetBase) textInputWindow() *renderWindow {
if wb.Scene == nil {
return nil
}
rw := wb.Scene.RenderWindow()
if rw == nil || rw.SystemWindow == nil {
return nil
}
return rw
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"image"
"slices"
"strings"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/text/textpos"
)
// The selection of text by sliding (dragging) the mouse works as in a web
// browser: it is from the anchor, where the mouse was pressed in a [Text],
// to the focus, the closest place in a text to the mouse, and it includes
// all of the texts in between them in the order of the document (the
// widget tree), which is the order of the source of an htmlcore page, such
// as that of the columns of a multi-column layout. The selection is made
// again for each move of the mouse, from the anchor, so that it follows the
// mouse back past the anchor, up or down. The slide events all go to the
// anchor text (see [Text.selectTo]).
// selectionRoot returns the widget whose texts the selection of the given
// text can extend to: the closest frame around it that scrolls (such as
// the page of a [content.Content]), or else its scene, so that the
// selection does not extend into toolbars and side panels.
func (tx *Text) selectionRoot() Widget {
for p := tx.Parent; p != nil; p = p.AsTree().Parent {
w, ok := p.(Widget)
if !ok {
break
}
st := &w.AsWidget().Styles
if st.Overflow.X >= styles.OverflowAuto || st.Overflow.Y >= styles.OverflowAuto {
return w
}
}
return tx.Scene
}
// selectableTexts returns the texts in the given widget that can be
// selected, in the order of the document. The texts of buttons and other
// widgets that are activated by clicking (such as the nodes of trees) are
// not part of the document text.
func selectableTexts(root Widget) []*Text {
var texts []*Text
root.AsWidget().WidgetWalkDown(func(cw Widget, cwb *WidgetBase) bool {
if !cwb.IsDisplayable() {
return false // hidden
}
if t, ok := cw.(*Text); ok {
if t.AbilityIs(abilities.Selectable) {
texts = append(texts, t)
}
return false
}
if cw != root && cwb.AbilityIs(abilities.Activatable) {
return false
}
return true
})
return texts
}
// closestText returns the index of the text of the given texts that is
// closest to the given position (in the scene), and the index of the rune
// in it that is closest to it, or -1 if none of the texts is visible.
// The distance is to the visible box of each text, so that the position
// is in the text if it is over it, and otherwise it is the closest one,
// which is the one in the same column of a multi-column layout when it is
// between the paragraphs of a column.
func closestText(texts []*Text, pos image.Point) (int, int) {
best, bestDist := -1, float32(0)
pt := math32.FromPoint(pos)
for i, t := range texts {
bb := t.Geom.ContentBBox
if bb.Empty() {
continue
}
box := math32.B2FromRect(bb)
d := box.ClampPoint(pt).DistanceToSquared(pt)
if best < 0 || d < bestDist {
best, bestDist = i, d
if d == 0 {
break
}
}
}
if best < 0 {
return -1, 0
}
return best, texts[best].pixelToRune(pos)
}
// startSelect starts the selection of text by sliding the mouse at the
// given rune index of this text, the anchor, resetting any other selection.
func (tx *Text) startSelect(ri int) {
tx.selectReset()
tx.selectAnchor = ri
tx.selectRange = textpos.Range{Start: ri, End: ri}
tx.selectTexts = selectableTexts(tx.selectionRoot())
tx.Scene.selectedText = []*Text{tx}
tx.NeedsRender()
}
// selectTo selects the text from the anchor of the selection, in this
// text, to the closest place in a text to the given position (in the
// scene), as the mouse slides there (see [Text.startSelect]).
func (tx *Text) selectTo(pos image.Point) {
texts := tx.selectTexts
ai := slices.Index(texts, tx)
fi, fr := -1, 0
if ai >= 0 {
fi, fr = closestText(texts, pos)
}
if fi < 0 || fi == ai {
tx.setSelection(textpos.Range{Start: min(tx.selectAnchor, tx.pixelToRune(pos)), End: max(tx.selectAnchor, tx.pixelToRune(pos))})
if ai >= 0 {
tx.setSelectedTexts(texts[ai : ai+1])
}
return
}
lo, hi := min(ai, fi), max(ai, fi)
for i := lo; i <= hi; i++ {
t := texts[i]
r := textpos.Range{Start: 0, End: t.textLen()}
switch {
case i == ai && fi > ai: // the selection goes down from the anchor
r.Start = tx.selectAnchor
case i == ai: // up from it
r.End = tx.selectAnchor
case i == fi && fi > ai:
r.End = fr
case i == fi:
r.Start = fr
}
t.setSelection(r)
}
tx.setSelectedTexts(texts[lo : hi+1])
}
// setSelection sets the selection of the text to the given range,
// rendering it again if it changed.
func (tx *Text) setSelection(r textpos.Range) {
if tx.selectRange == r {
return
}
tx.selectRange = r
tx.NeedsRender()
}
// setSelectedTexts sets the texts of the selection of the scene of the
// text, in the order of the document, resetting the selection of the
// texts that are no longer in it.
func (tx *Text) setSelectedTexts(texts []*Text) {
for _, st := range tx.Scene.selectedText {
if !slices.Contains(texts, st) {
st.setSelection(textpos.Range{})
}
}
tx.Scene.selectedText = slices.Clone(texts)
}
// textLen returns the number of runes of the text.
func (tx *Text) textLen() int {
if tx.paintText == nil {
return 0
}
return len(tx.richText.Join())
}
// selectedText returns the text that is selected in the texts of the
// selection of the scene of this text (one line for each text with a
// selection, in the order of the document), or in this text.
func (tx *Text) selectedText() string {
if len(tx.Scene.selectedText) == 0 {
// note: selectRange is in runes, not string indexes.
return string(tx.richText.Join()[tx.selectRange.Start:tx.selectRange.End])
}
var sel []string
for _, st := range tx.Scene.selectedText {
if st.selectRange.Len() > 0 {
sel = append(sel, string(st.richText.Join()[st.selectRange.Start:st.selectRange.End]))
}
}
return strings.Join(sel, "\n")
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"reflect"
"strconv"
"strings"
"time"
"cogentcore.org/core/colors"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/tree"
)
// TimePicker is a widget for picking a time.
type TimePicker struct {
Frame
// Time is the time that we are viewing.
Time time.Time
// the raw input hour
hour int
// whether we are in pm mode (so we have to add 12h to everything)
pm bool
}
func (tp *TimePicker) WidgetValue() any { return &tp.Time }
func (tp *TimePicker) Init() {
tp.Frame.Init()
spinnerInit := func(w *Spinner) {
w.Styler(func(s *styles.Style) {
s.Font.Size.Dp(57)
s.Min.X.Ch(7)
s.IconSize.Set(units.Dp(32))
})
}
tree.AddChild(tp, func(w *Spinner) {
spinnerInit(w)
w.SetStep(1).SetEnforceStep(true)
w.Updater(func() {
if SystemSettings.Clock24 {
tp.hour = tp.Time.Hour()
w.SetMax(24).SetMin(0)
} else {
tp.hour = tp.Time.Hour() % 12
if tp.hour == 0 {
tp.hour = 12
}
w.SetMax(12).SetMin(1)
}
w.SetValue(float32(tp.hour))
})
w.OnChange(func(e events.Event) {
hr := int(w.Value)
if hr == 12 && !SystemSettings.Clock24 {
hr = 0
}
tp.hour = hr
if tp.pm {
// only add to local variable
hr += 12
}
// we set our hour and keep everything else
tt := tp.Time
tp.Time = time.Date(tt.Year(), tt.Month(), tt.Day(), hr, tt.Minute(), tt.Second(), tt.Nanosecond(), tt.Location())
tp.SendChange()
})
})
tree.AddChild(tp, func(w *Text) {
w.SetType(TextDisplayLarge).SetText(":")
w.Styler(func(s *styles.Style) {
s.SetTextWrap(false)
s.Min.X.Ch(1)
})
})
tree.AddChild(tp, func(w *Spinner) {
spinnerInit(w)
w.SetStep(1).SetEnforceStep(true).
SetMin(0).SetMax(59).SetFormat("%02d")
w.Updater(func() {
w.SetValue(float32(tp.Time.Minute()))
})
w.OnChange(func(e events.Event) {
// we set our minute and keep everything else
tt := tp.Time
tp.Time = time.Date(tt.Year(), tt.Month(), tt.Day(), tt.Hour(), int(w.Value), tt.Second(), tt.Nanosecond(), tt.Location())
tp.SendChange()
})
})
tp.Maker(func(p *tree.Plan) {
if !SystemSettings.Clock24 {
tree.Add(p, func(w *Switches) {
w.SetMutex(true).SetAllowNone(false).SetType(SwitchSegmentedButton).SetItems(SwitchItem{Value: "AM"}, SwitchItem{Value: "PM"})
tp.pm = tp.Time.Hour() >= 12
w.Styler(func(s *styles.Style) {
s.Direction = styles.Column
})
w.Updater(func() {
if tp.pm {
w.SelectValue("PM")
} else {
w.SelectValue("AM")
}
})
w.OnChange(func(e events.Event) {
si := w.SelectedItem()
tt := tp.Time
if tp.hour == 12 {
tp.hour = 0
}
switch si.Value {
case "AM":
tp.pm = false
tp.Time = time.Date(tt.Year(), tt.Month(), tt.Day(), tp.hour, tt.Minute(), tt.Second(), tt.Nanosecond(), tt.Location())
case "PM":
tp.pm = true
tp.Time = time.Date(tt.Year(), tt.Month(), tt.Day(), tp.hour+12, tt.Minute(), tt.Second(), tt.Nanosecond(), tt.Location())
}
tp.SendChange()
})
})
}
})
}
var shortMonths = []string{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}
// DatePicker is a widget for picking a date.
type DatePicker struct {
Frame
// Time is the time that we are viewing.
Time time.Time
// getTime converts the given calendar grid index to its corresponding time.
// We must store this logic in a closure so that it can always be recomputed
// correctly in the inner closures of the grid maker; otherwise, the local
// variables needed would be stale.
getTime func(i int) time.Time
// som is the start of the month (must be set here to avoid stale variables).
som time.Time
}
// setTime sets the source time and updates the picker.
func (dp *DatePicker) setTime(tim time.Time) {
dp.SetTime(tim).UpdateChange()
}
func (dp *DatePicker) Init() {
dp.Frame.Init()
dp.Styler(func(s *styles.Style) {
s.Direction = styles.Column
})
tree.AddChild(dp, func(w *Frame) {
w.Styler(func(s *styles.Style) {
s.Gap.Zero()
})
arrowStyle := func(s *styles.Style) {
s.Padding.SetHorizontal(units.Dp(12))
s.Color = colors.Scheme.OnSurfaceVariant
}
tree.AddChild(w, func(w *Button) {
w.SetType(ButtonAction).SetIcon(icons.NavigateBefore)
w.OnClick(func(e events.Event) {
dp.setTime(dp.Time.AddDate(0, -1, 0))
})
w.Styler(arrowStyle)
})
tree.AddChild(w, func(w *Chooser) {
sms := make([]ChooserItem, len(shortMonths))
for i, sm := range shortMonths {
sms[i] = ChooserItem{Value: sm}
}
w.SetItems(sms...)
w.Updater(func() {
w.SetCurrentIndex(int(dp.Time.Month() - 1))
})
w.OnChange(func(e events.Event) {
// set our month
dp.setTime(dp.Time.AddDate(0, w.CurrentIndex+1-int(dp.Time.Month()), 0))
})
})
tree.AddChild(w, func(w *Button) {
w.SetType(ButtonAction).SetIcon(icons.NavigateNext)
w.OnClick(func(e events.Event) {
dp.setTime(dp.Time.AddDate(0, 1, 0))
})
w.Styler(arrowStyle)
})
tree.AddChild(w, func(w *Button) {
w.SetType(ButtonAction).SetIcon(icons.NavigateBefore)
w.OnClick(func(e events.Event) {
dp.setTime(dp.Time.AddDate(-1, 0, 0))
})
w.Styler(arrowStyle)
})
tree.AddChild(w, func(w *Chooser) {
w.Updater(func() {
yr := dp.Time.Year()
var yrs []ChooserItem
// we go 100 in each direction from the current year
for i := yr - 100; i <= yr+100; i++ {
yrs = append(yrs, ChooserItem{Value: i})
}
w.SetItems(yrs...)
w.SetCurrentValue(yr)
})
w.OnChange(func(e events.Event) {
// we are centered at current year with 100 in each direction
nyr := w.CurrentIndex + dp.Time.Year() - 100
// set our year
dp.setTime(dp.Time.AddDate(nyr-dp.Time.Year(), 0, 0))
})
})
tree.AddChild(w, func(w *Button) {
w.SetType(ButtonAction).SetIcon(icons.NavigateNext)
w.OnClick(func(e events.Event) {
dp.setTime(dp.Time.AddDate(1, 0, 0))
})
w.Styler(arrowStyle)
})
})
tree.AddChild(dp, func(w *Frame) {
w.Styler(func(s *styles.Style) {
s.Display = styles.Grid
s.Columns = 7
})
w.Maker(func(p *tree.Plan) {
// start of the month
som := dp.Time.AddDate(0, 0, -dp.Time.Day()+1)
// end of the month
eom := dp.Time.AddDate(0, 1, -dp.Time.Day())
// start of the week containing the start of the month
somw := som.AddDate(0, 0, -int(som.Weekday()))
// end of the week containing the end of the month
eomw := eom.AddDate(0, 0, int(6-eom.Weekday()))
// the number of days from somw to eomw, which can be in
// different years (in January and December)
ndays := 0
for d := somw; !d.After(eomw); d = d.AddDate(0, 0, 1) {
ndays++
}
dp.getTime = func(i int) time.Time {
return somw.AddDate(0, 0, i)
}
dp.som = som
for i := range ndays {
tree.AddAt(p, strconv.Itoa(i), func(w *Button) {
w.SetType(ButtonAction)
w.Updater(func() {
w.SetText(strconv.Itoa(dp.getTime(i).Day()))
})
w.OnClick(func(e events.Event) {
dp.setTime(dp.getTime(i))
})
w.Styler(func(s *styles.Style) {
s.CenterAll()
s.Min.Set(units.Dp(32))
s.Padding.Set(units.Dp(6))
dt := dp.getTime(i)
if dt.Month() != dp.som.Month() {
s.Color = colors.Scheme.OnSurfaceVariant
}
if dt.Year() == time.Now().Year() && dt.YearDay() == time.Now().YearDay() {
s.Border.Width.Set(units.Dp(1))
s.Border.Color.Set(colors.Scheme.Primary.Base)
s.Color = colors.Scheme.Primary.Base
}
if dt.Year() == dp.Time.Year() && dt.YearDay() == dp.Time.YearDay() {
s.Background = colors.Scheme.Primary.Base
s.Color = colors.Scheme.Primary.On
}
})
tree.AddChildInit(w, "text", func(w *Text) {
w.FinalUpdater(func() {
w.SetType(TextBodyLarge)
})
})
})
}
})
})
}
// TimeInput presents two text fields for editing a date and time,
// both of which can pull up corresponding picker dialogs.
// The zero time is shown as blank, and clearing the date makes it zero.
type TimeInput struct {
Frame
Time time.Time
// DisplayDate is whether the date input is displayed (default true).
DisplayDate bool
// DisplayTime is whether the time input is displayed (default true).
DisplayTime bool
}
func (ti *TimeInput) WidgetValue() any { return &ti.Time }
func (ti *TimeInput) OnBind(value any, tags reflect.StructTag) {
switch tags.Get("display") {
case "date":
ti.DisplayTime = false
case "time":
ti.DisplayDate = false
}
}
func (ti *TimeInput) Init() {
ti.Frame.Init()
ti.DisplayDate = true
ti.DisplayTime = true
style := func(s *styles.Style) {
s.Min.X.Em(8)
s.Max.X.Em(10)
if ti.IsReadOnly() { // must inherit abilities when read only for table
s.Abilities = ti.Styles.Abilities
}
}
// pickTime is the time for the pickers to start at, which is
// the current time for the zero time
pickTime := func() time.Time {
if ti.Time.IsZero() {
return time.Now()
}
return ti.Time
}
ti.Maker(func(p *tree.Plan) {
if ti.DisplayDate {
tree.Add(p, func(w *TextField) {
w.SetTooltip("The date")
w.SetLeadingIcon(icons.CalendarToday, func(e events.Event) {
d := NewBody("Select date")
dp := NewDatePicker(d).SetTime(pickTime())
d.AddBottomBar(func(bar *Frame) {
d.AddCancel(bar)
d.AddOK(bar).OnClick(func(e events.Event) {
ti.Time = dp.Time
ti.UpdateChange()
})
})
d.RunDialog(w)
})
w.Styler(style)
w.Updater(func() {
w.SetReadOnly(ti.IsReadOnly())
if ti.Time.IsZero() {
w.SetText("")
} else {
w.SetText(ti.Time.Format("1/2/2006"))
}
})
w.SetValidator(func() error {
if strings.TrimSpace(w.Text()) == "" {
ti.Time = time.Time{}
ti.SendChange()
return nil
}
d, err := time.Parse("1/2/2006", w.Text())
if err != nil {
return err
}
// new date and old time, which is midnight for the zero time
loc := ti.Time.Location()
if ti.Time.IsZero() {
loc = time.Local
}
ti.Time = time.Date(d.Year(), d.Month(), d.Day(), ti.Time.Hour(), ti.Time.Minute(), ti.Time.Second(), ti.Time.Nanosecond(), loc)
ti.SendChange()
return nil
})
})
}
if ti.DisplayTime {
tree.Add(p, func(w *TextField) {
w.SetTooltip("The time")
w.SetLeadingIcon(icons.Schedule, func(e events.Event) {
d := NewBody("Edit time")
tp := NewTimePicker(d).SetTime(pickTime())
d.AddBottomBar(func(bar *Frame) {
d.AddCancel(bar)
d.AddOK(bar).OnClick(func(e events.Event) {
ti.Time = tp.Time
ti.UpdateChange()
})
})
d.RunDialog(w)
})
w.Styler(style)
w.Updater(func() {
w.SetReadOnly(ti.IsReadOnly())
if ti.Time.IsZero() {
w.SetText("")
} else {
w.SetText(timeText(ti.Time))
}
})
w.SetValidator(func() error {
if strings.TrimSpace(w.Text()) == "" {
if ti.DisplayDate {
return nil // the date can be cleared
}
ti.Time = time.Time{}
ti.SendChange()
return nil
}
t, err := time.Parse(SystemSettings.TimeFormat(), strings.ReplaceAll(w.Text(), "\u00a0", " "))
if err != nil {
return err
}
// old date, which is today for the zero time, and new time
old := pickTime()
ti.Time = time.Date(old.Year(), old.Month(), old.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), old.Location())
ti.SendChange()
return nil
})
})
}
})
}
// DurationInput represents a [time.Duration] value with a spinner and unit chooser.
type DurationInput struct {
Frame
Duration time.Duration
// Unit is the unit of time.
Unit string
}
func (di *DurationInput) WidgetValue() any { return &di.Duration }
func (di *DurationInput) Init() {
di.Frame.Init()
tree.AddChild(di, func(w *Spinner) {
w.SetStep(1).SetPageStep(10)
w.SetTooltip("The value of time")
w.Updater(func() {
if di.Unit == "" {
di.setAutoUnit()
}
w.SetValue(float32(di.Duration) / float32(durationUnitsMap[di.Unit]))
w.SetReadOnly(di.IsReadOnly())
})
w.OnChange(func(e events.Event) {
di.Duration = time.Duration(w.Value * float32(durationUnitsMap[di.Unit]))
di.SendChange()
})
})
tree.AddChild(di, func(w *Chooser) {
Bind(&di.Unit, w)
units := make([]ChooserItem, len(durationUnits))
for i, u := range durationUnits {
units[i] = ChooserItem{Value: u}
}
w.SetItems(units...)
w.SetTooltip("The unit of time")
w.Updater(func() {
w.SetReadOnly(di.IsReadOnly())
})
w.OnChange(func(e events.Event) {
di.Update()
})
})
}
// setAutoUnit sets the [DurationInput.Unit] automatically based on the current duration.
func (di *DurationInput) setAutoUnit() {
di.Unit = durationUnits[0]
for _, u := range durationUnits {
if durationUnitsMap[u] > di.Duration {
break
}
di.Unit = u
}
}
var durationUnits = []string{
"nanoseconds",
"microseconds",
"milliseconds",
"seconds",
"minutes",
"hours",
"days",
"weeks",
"months",
"years",
}
var durationUnitsMap = map[string]time.Duration{
"nanoseconds": time.Nanosecond,
"microseconds": time.Microsecond,
"milliseconds": time.Millisecond,
"seconds": time.Second,
"minutes": time.Minute,
"hours": time.Hour,
"days": 24 * time.Hour,
"weeks": 7 * 24 * time.Hour,
"months": 30 * 24 * time.Hour,
"years": 365 * 24 * time.Hour,
}
// timeText returns the text of the time of the given time, in the time
// format of the system settings, with no-break spaces, so that it is not
// split onto two lines (as in a narrow column of a table, which would make
// its row taller than the others), while its field can still be narrower
// than it prefers, down to the width of the time, as when a table is just
// too narrow.
func timeText(t time.Time) string {
return strings.ReplaceAll(t.Format(SystemSettings.TimeFormat()), " ", "\u00a0")
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"image"
"cogentcore.org/core/colors"
"cogentcore.org/core/icons"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/tree"
)
// Toolbar is a [Frame] that is useful for holding [Button]s that do things.
// It automatically moves items that do not fit into an overflow menu, and
// manages additional items that are always placed onto this overflow menu.
// Toolbars are frequently added in [Body.AddTopBar]. All toolbars use the
// [WidgetBase.Maker] system, so you cannot directly add widgets; see
// https://cogentcore.org/core/toolbar.
type Toolbar struct {
Frame
// OverflowMenus are functions for configuring the overflow menu of the
// toolbar. You can use [Toolbar.AddOverflowMenu] to add them.
// These are processed in reverse order (last in, first called)
// so that the default items are added last.
OverflowMenus []func(m *Scene, pos image.Point) `set:"-" json:"-" xml:"-"`
// allItemsPlan has all the items, during layout sizing
allItemsPlan *tree.Plan
// overflowItems are items moved from the main toolbar that will be
// shown in the overflow menu.
overflowItems []*tree.PlanItem
// overflowButton is the widget to pull up the overflow menu.
overflowButton *Button
// MoveFunc, if set, makes the items of the toolbar draggable to other
// places in it: an item dropped onto another one moves to its place.
// It is called with the index of the item and the index that it then
// has, among the items of the toolbar (as made by its [WidgetBase.Maker]
// functions, not counting the overflow menu), to move whatever the
// items are made from accordingly, as the toolbar is then updated.
MoveFunc func(from, to int) `set:"-" json:"-" xml:"-"`
}
// ToolbarMaker is an interface that types can implement to make a toolbar plan.
// It is automatically used when making [Value] dialogs.
type ToolbarMaker interface {
MakeToolbar(p *tree.Plan)
}
func (tb *Toolbar) Init() {
tb.Frame.Init()
ToolbarStyles(tb)
styleItem := tb.OnChildAdded
tb.SetOnChildAdded(func(n tree.Node) {
styleItem(n)
tb.initItemDrag(n)
})
tb.FinalMaker(func(p *tree.Plan) { // must go at end
tree.AddAt(p, "overflow-menu", func(w *Button) {
ic := icons.MoreVert
if tb.Styles.Direction != styles.Row {
ic = icons.MoreHoriz
}
w.SetIcon(ic).SetTooltip("Additional menu items")
w.Updater(func() {
tb, ok := w.Parent.(*Toolbar)
if ok {
w.Menu = tb.overflowMenu
}
})
})
})
}
func (tb *Toolbar) SizeUp() {
if tb.Styles.Wrap {
tb.getOverflowButton()
tb.setOverflowMenuVisibility()
tb.Frame.SizeUp()
return
}
tb.allItemsToChildren()
tb.Frame.SizeUp()
}
func (tb *Toolbar) SizeDown(iter int) bool {
if tb.Styles.Wrap {
return tb.Frame.SizeDown(iter)
}
redo := tb.Frame.SizeDown(iter)
if iter == 0 {
return true // ensure a second pass
}
// The items that do not fit are moved to the overflow menu in the
// iterations of the layout that redo (not in those after them, in
// which it only settles), as they are only moved and not moved back.
if tb.Scene.showIter > 0 && iter < layoutIters {
tb.moveToOverflow()
}
return redo
}
func (tb *Toolbar) SizeFromChildren(iter int, pass LayoutPasses) math32.Vector2 {
csz := tb.Frame.SizeFromChildren(iter, pass)
if pass == SizeUpPass || (pass == SizeDownPass && iter == 0) {
dim := tb.Styles.Direction.Dim()
ovsz := tb.Styles.UnitContext.FontEm * 2
if tb.overflowButton != nil {
ovsz = tb.overflowButton.Geom.Size.Actual.Total.Dim(dim)
}
csz.SetDim(dim, ovsz) // present the minimum size initially
return csz
}
return csz
}
// allItemsToChildren moves the overflow items back to the children,
// so the full set is considered for the next layout round,
// and ensures the overflow button is made and moves it
// to the end of the list.
func (tb *Toolbar) allItemsToChildren() {
tb.overflowItems = nil
tb.allItemsPlan = &tree.Plan{}
tb.Make(tb.allItemsPlan)
np := len(tb.allItemsPlan.Children)
if tb.NumChildren() == np {
return
}
// Remake the items that the last layout moved to the overflow menu,
// and update and style them so that they are ready for SizeUp.
// This is like [WidgetBase.Update], but without requesting another
// layout, as we are already in one; nothing must be rendered here,
// as the geometry of the scene is only partly computed.
for cw, cwb := range tb.AllWidgets() {
cwb.UpdateWidget()
cw.Style()
}
}
func (tb *Toolbar) parentSize() float32 {
ma := tb.Styles.Direction.Dim()
psz := tb.parentWidget().Geom.Size.Alloc.Content.Sub(tb.Geom.Size.Space)
avail := psz.Dim(ma)
return avail
}
func (tb *Toolbar) getOverflowButton() {
tb.overflowButton = nil
li := tb.Children[tb.NumChildren()-1]
if li == nil {
return
}
if ob, ok := li.(*Button); ok {
tb.overflowButton = ob
}
}
// moveToOverflow moves overflow out of children to the OverflowItems list
func (tb *Toolbar) moveToOverflow() {
if !tb.HasChildren() {
return
}
ma := tb.Styles.Direction.Dim()
avail := tb.parentSize()
tb.getOverflowButton()
if tb.overflowButton == nil {
return
}
ovsz := tb.overflowButton.Geom.Size.Actual.Total.Dim(ma)
avsz := avail - ovsz
sz := &tb.Geom.Size
sz.Alloc.Total.SetDim(ma, avail)
sz.SetContentFromTotal(&sz.Alloc)
n := len(tb.Children)
pn := len(tb.allItemsPlan.Children)
ovidx := n - 1
hasOv := false
szsum := float32(0)
tb.ForWidgetChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
if i >= n-1 {
return tree.Break
}
ksz := cwb.Geom.Size.Alloc.Total.Dim(ma)
if cwb.Styles.Grow.Dim(ma) > 0 && cwb.Geom.Size.preferred.Dim(ma) > 0 {
// one that grows takes only its size before growing
ksz = min(ksz, cwb.Geom.Size.preferred.Dim(ma))
}
szsum += ksz
if szsum > avsz {
if !hasOv {
ovidx = i
hasOv = true
}
pi := tb.allItemsPlan.Children[i]
tb.overflowItems = append(tb.overflowItems, pi)
}
return tree.Continue
})
if hasOv {
p := &tree.Plan{}
p.Children = tb.allItemsPlan.Children[:ovidx]
p.Children = append(p.Children, tb.allItemsPlan.Children[pn-1]) // ovm
p.Update(tb)
}
if len(tb.overflowItems) == 0 && len(tb.OverflowMenus) == 0 {
tb.overflowButton.SetState(true, states.Invisible)
} else {
tb.overflowButton.SetState(false, states.Invisible)
tb.overflowButton.Update()
}
tb.setOverflowMenuVisibility()
}
func (tb *Toolbar) setOverflowMenuVisibility() {
if tb.overflowButton == nil {
return
}
if len(tb.overflowItems) == 0 && len(tb.OverflowMenus) == 0 {
tb.overflowButton.SetState(true, states.Invisible)
} else {
tb.overflowButton.SetState(false, states.Invisible)
tb.overflowButton.UpdateRender()
}
}
// overflowMenu adds the overflow menu to the given Scene.
func (tb *Toolbar) overflowMenu(m *Scene, pos image.Point) {
nm := len(tb.OverflowMenus)
ni := len(tb.overflowItems)
if ni > 0 {
p := &tree.Plan{}
p.Children = tb.overflowItems
p.Update(m)
if nm > 1 { // default includes sep
NewSeparator(m)
}
}
// reverse order so defaults are last
for i := nm - 1; i >= 0; i-- {
fn := tb.OverflowMenus[i]
fn(m, pos)
}
}
// AddOverflowMenu adds the given menu function to the overflow menu list.
// These functions are called in reverse order such that the last added function
// is called first when constructing the menu.
func (tb *Toolbar) AddOverflowMenu(fun func(m *Scene, pos image.Point)) {
tb.OverflowMenus = append(tb.OverflowMenus, fun)
}
// ToolbarStyles styles the given widget to have standard toolbar styling.
func ToolbarStyles(w Widget) {
wb := w.AsWidget()
wb.Styler(func(s *styles.Style) {
s.Border.Radius = styles.BorderRadiusFull
s.Background = colors.Scheme.SurfaceContainer
s.Gap.Zero()
s.Align.Items = styles.Center
if len(wb.Children) == 0 {
// we must not render toolbars with no children
s.Display = styles.DisplayNone
} else {
s.Display = styles.Flex
}
})
wb.FinalStyler(func(s *styles.Style) {
if s.Direction == styles.Row {
s.Grow.Set(1, 0)
s.Padding.SetHorizontal(units.Dp(16))
} else {
s.Grow.Set(0, 1)
s.Padding.SetVertical(units.Dp(16))
}
})
wb.SetOnChildAdded(func(n tree.Node) {
if bt := AsButton(n); bt != nil {
bt.Type = ButtonAction
return
}
if sp, ok := n.(*Separator); ok {
sp.Styler(func(s *styles.Style) {
s.Direction = wb.Styles.Direction.Other()
})
}
})
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"cogentcore.org/core/events"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/tree"
)
// toolbarDrag is the data of the drag of an item of a [Toolbar] with a
// [Toolbar.MoveFunc].
type toolbarDrag struct {
toolbar *Toolbar
item Widget
}
// DragMovesDefault returns that a drag of an item of the toolbar moves it
// (see [DragMover]).
func (tb *Toolbar) DragMovesDefault() bool { return tb.MoveFunc != nil }
// itemIndex returns the index of the given item among the items of the
// toolbar, or -1 if it is not one of them (as the overflow menu).
func (tb *Toolbar) itemIndex(w Widget) int {
if w.AsTree().Parent != tb.This || w.AsTree().Name == "overflow-menu" {
return -1
}
return w.AsTree().IndexInParent()
}
// initItemDrag makes the given new item of the toolbar draggable to other
// places in it, and a target of drops of its other items, if the toolbar
// has a [Toolbar.MoveFunc].
func (tb *Toolbar) initItemDrag(n tree.Node) {
w, ok := n.(Widget)
if !ok || n.AsTree().Name == "overflow-menu" {
return
}
wb := w.AsWidget()
wb.FinalStyler(func(s *styles.Style) {
if tb.MoveFunc != nil {
s.SetAbilities(true, abilities.Draggable, abilities.Droppable)
}
})
dragged := func() *toolbarDrag {
td, ok := tb.Scene.Events.dragData.(*toolbarDrag)
if !ok || td.toolbar != tb {
return nil
}
return td
}
wb.On(events.DragStart, func(e events.Event) {
if tb.MoveFunc == nil || tb.itemIndex(w) < 0 {
return
}
e.SetHandled()
tb.Scene.Events.DragStart(w, &toolbarDrag{toolbar: tb, item: w}, e)
})
wb.On(events.DragEnter, func(e events.Event) {
if dragged() != nil {
wb.SetState(true, states.DragHovered)
wb.NeedsRender()
e.SetHandled()
}
})
wb.On(events.DragLeave, func(e events.Event) {
wb.SetState(false, states.DragHovered)
wb.NeedsRender()
})
wb.On(events.Drop, func(e events.Event) {
td, ok := e.(*events.DragDrop).Data.(*toolbarDrag)
if !ok || td.toolbar != tb || tb.MoveFunc == nil {
return
}
e.SetHandled()
from, to := tb.itemIndex(td.item), tb.itemIndex(w)
if from < 0 || to < 0 || from == to {
return
}
tb.MoveFunc(from, to)
tb.Update()
})
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"image"
"cogentcore.org/core/colors"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/units"
)
// DefaultTooltipPos returns the default position for the tooltip
// for this widget in window coordinates using the window bounding box.
func (wb *WidgetBase) DefaultTooltipPos() image.Point {
bb := wb.winBBox()
pos := bb.Min
pos.X += (bb.Max.X - bb.Min.X) / 2 // center on X
// top of Y
return pos
}
// newTooltipFromScene returns a new Tooltip stage with given scene contents,
// in connection with given widget (which provides key context).
// Make further configuration choices using Set* methods, which
// can be chained directly after the New call.
// Use an appropriate Run call at the end to start the Stage running.
func newTooltipFromScene(sc *Scene, ctx Widget) *Stage {
return NewPopupStage(TooltipStage, sc, ctx)
}
// newTooltip returns a new tooltip stage displaying the given tooltip text
// for the given widget based at the given window-level position, with the size
// defaulting to the size of the widget.
func newTooltip(w Widget, tooltip string, pos image.Point) *Stage {
return newTooltipTextSize(w, tooltip, pos, w.AsWidget().winBBox().Size())
}
// newTooltipTextSize returns a new tooltip stage displaying the given tooltip text
// for the given widget at the given window-level position with the given size.
func newTooltipTextSize(w Widget, tooltip string, pos, sz image.Point) *Stage {
return newTooltipFromScene(newTooltipScene(w, tooltip, pos, sz), w)
}
// newTooltipScene returns a new tooltip scene for the given widget with the
// given tooltip based on the given context position and context size.
func newTooltipScene(w Widget, tooltip string, pos, sz image.Point) *Scene {
sc := NewScene(w.AsTree().Name + "-tooltip")
// tooltip positioning uses the original scene geom as the context values
sc.SceneGeom.Pos = pos
sc.SceneGeom.Size = sz // used for positioning if needed
sc.Styler(func(s *styles.Style) {
s.Border.Radius = styles.BorderRadiusExtraSmall
s.Grow.Set(1, 1)
s.Overflow.Set(styles.OverflowVisible) // key for avoiding sizing errors when re-rendering with small pref size
s.Padding.Set(units.Dp(8))
s.Background = colors.Scheme.InverseSurface
s.Color = colors.Scheme.InverseOnSurface
s.BoxShadow = styles.BoxShadow1()
})
NewText(sc).SetType(TextBodyMedium).SetText(tooltip).
Styler(func(s *styles.Style) {
s.SetTextWrap(true)
s.Max.X.Em(20)
})
return sc
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"bytes"
"fmt"
"image"
"log/slog"
"strings"
"cogentcore.org/core/base/fileinfo"
"cogentcore.org/core/base/fileinfo/mimedata"
"cogentcore.org/core/base/iox/jsonx"
"cogentcore.org/core/colors"
"cogentcore.org/core/cursors"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/keymap"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/text"
"cogentcore.org/core/text/textpos"
"cogentcore.org/core/tree"
"cogentcore.org/core/types"
)
// Treer is an interface for [Tree] types
// providing access to the base [Tree] and
// overridable method hooks for actions taken on the [Tree],
// including OnOpen, OnClose, etc.
type Treer interface { //types:add
Widget
// AsTree returns the base [Tree] for this node.
AsCoreTree() *Tree
// CanOpen returns true if the node is able to open.
// By default it checks HasChildren(), but could check other properties
// to perform lazy building of the tree.
CanOpen() bool
// OnOpen is called when a node is toggled open.
// The base version does nothing.
OnOpen()
// OnClose is called when a node is toggled closed.
// The base version does nothing.
OnClose()
// The following are all tree editing functions:
MimeData(md *mimedata.Mimes)
Cut()
Copy()
Paste()
DeleteSelected()
DragDrop(e events.Event)
DropDeleteSource(e events.Event)
}
// AsTree returns the given value as a [Tree] if it has
// an AsCoreTree() method, or nil otherwise.
func AsTree(n tree.Node) *Tree {
if t, ok := n.(Treer); ok {
return t.AsCoreTree()
}
return nil
}
// note: see treesync.go for all the SyncNode mode specific
// functions.
// Tree provides a graphical representation of a tree structure,
// providing full navigation and manipulation abilities.
//
// It does not handle layout by itself, so if you want it to scroll
// separately from the rest of the surrounding context, you must
// place it in a [Frame].
//
// If the [Tree.SyncNode] field is non-nil, typically via the
// [Tree.SyncTree] method, then the Tree mirrors another
// tree structure, and tree editing functions apply to
// the source tree first, and then to the Tree by sync.
//
// Otherwise, data can be directly encoded in a Tree
// derived type, to represent any kind of tree structure
// and associated data.
//
// Standard [events.Event]s are sent to any listeners, including
// [events.Select], [events.Change], and [events.DoubleClick].
// The selected nodes are in the root [Tree.SelectedNodes] list;
// select events are sent to both selected nodes and the root node.
// See [Tree.IsRootSelected] to check whether a select event on the root
// node corresponds to the root node or another node.
type Tree struct {
WidgetBase
// SyncNode, if non-nil, is the [tree.Node] that this widget is
// viewing in the tree (the source). It should be set using
// [Tree.SyncTree].
SyncNode tree.Node `set:"-" copier:"-" json:"-" xml:"-"`
// Text is the text to display for the tree item label, which automatically
// defaults to the [tree.Node.Name] of the tree node. It has no effect
// if [Tree.SyncNode] is non-nil.
Text string
// Icon is an optional icon displayed to the the left of the text label.
Icon icons.Icon
// IconOpen is the icon to use for an open (expanded) branch;
// it defaults to [icons.KeyboardArrowDown].
IconOpen icons.Icon
// IconClosed is the icon to use for a closed (collapsed) branch;
// it defaults to [icons.KeyboardArrowRight].
IconClosed icons.Icon
// IconLeaf is the icon to use for a terminal node branch that has no children;
// it defaults to [icons.Blank].
IconLeaf icons.Icon
// TreeInit is a function that can be set on the root node that is called
// with each child tree node when it is initialized. It is only
// called with the root node itself in [Tree.SetTreeInit], so you
// should typically call that instead of setting this directly.
TreeInit func(tr *Tree) `set:"-" json:"-" xml:"-"`
// Indent is the amount to indent children relative to this node.
// It should be set in a Styler like all other style properties.
Indent units.Value `copier:"-" json:"-" xml:"-"`
// OpenDepth is the depth for nodes be initialized as open (default 4).
// Nodes beyond this depth will be initialized as closed.
OpenDepth int `copier:"-" json:"-" xml:"-"`
// Closed is whether this tree node is currently toggled closed
// (children not visible).
Closed bool
// SelectMode, when set on the root node, determines whether keyboard movements should update selection.
SelectMode bool
// NewNodeType, when set on the root node, is the type of the nodes that
// inserting before or after a node, or adding a child, adds one of,
// instead of prompting for the number and type of nodes to add.
// It applies to the [Tree.SyncNode] for a sync tree.
NewNodeType *types.Type `copier:"-" json:"-" xml:"-" display:"-"`
// DragMoves, when set on the root node, is whether dragging nodes moves
// them by default, instead of copying them, in which case the modifier
// keys that otherwise move them (Shift) copy them.
DragMoves bool
// Computed fields:
// linear index of this node within the entire tree.
// updated on full rebuilds and may sometimes be off,
// but close enough for expected uses
viewIndex int
// size of just this node widget.
// our alloc includes all of our children, but we only draw us.
widgetSize math32.Vector2
// Root is the cached root of the tree. It is automatically set.
Root Treer `copier:"-" json:"-" xml:"-" edit:"-" set:"-"`
// SelectedNodes holds the currently selected nodes.
// It is only set on the root node. See [Tree.GetSelectedNodes]
// for a version that also works on non-root nodes.
SelectedNodes []Treer `copier:"-" json:"-" xml:"-" edit:"-" set:"-"`
// actStateLayer is the actual state layer of the tree, which
// should be used when rendering it and its parts (but not its children).
// the reason that it exists is so that the children of the tree
// (other trees) do not inherit its stateful background color, as
// that does not look good.
actStateLayer float32
// inOpen is set in the Open method to prevent recursive opening for lazy-open nodes.
inOpen bool
// Branch is the branch widget that is used to open and close the tree node.
Branch *Switch `json:"-" xml:"-" copier:"-" set:"-" display:"-"`
}
// DragMovesDefault returns whether a drag of a node moves it (see [DragMover]),
// which is the [Tree.DragMoves] of its root.
func (tr *Tree) DragMovesDefault() bool {
return tr.Root != nil && tr.Root.AsCoreTree().DragMoves
}
// AsCoreTree satisfies the [Treer] interface.
func (tr *Tree) AsCoreTree() *Tree {
return tr
}
// rootSetViewIndex sets the [Tree.root] and [Tree.viewIndex] for all nodes.
// It returns the total number of leaves in the tree.
func (tr *Tree) rootSetViewIndex() int {
idx := 0
for cw := range tr.AllWidgets() {
tvn := AsTree(cw)
if tvn != nil {
tvn.viewIndex = idx
if tvn.Root == nil {
tvn.Root = tr.This.(Treer)
}
idx++
}
}
return idx
}
func (tr *Tree) Init() {
tr.WidgetBase.Init()
tr.AddContextMenu(tr.contextMenu)
tr.IconOpen = icons.KeyboardArrowDown
tr.IconClosed = icons.KeyboardArrowRight
tr.IconLeaf = icons.Blank
tr.OpenDepth = 4
tr.Styler(func(s *styles.Style) {
// our parts are draggable and droppable, not us ourself
s.SetAbilities(true, abilities.Activatable, abilities.Focusable, abilities.Selectable, abilities.Hoverable)
tr.Indent.Em(1)
s.Border.Style.Set(styles.BorderNone)
s.Border.Radius = styles.BorderRadiusFull
s.MaxBorder = s.Border
// s.Border.Width.Left.SetDp(1)
// s.Border.Color.Left = colors.Scheme.OutlineVariant
s.Margin.Zero()
s.Padding.Left.Dp(ConstantSpacing(4))
s.Padding.SetVertical(units.Dp(4))
s.Padding.Right.Zero()
s.Text.Align = text.Start
if tr.Root == nil || tr.Root == tr.This {
s.IconSize.Set(units.Em(1.5))
} else {
s.IconSize = tr.Root.AsWidget().Styles.IconSize
}
// need to copy over to actual and then clear styles one
if s.Is(states.Selected) {
// render handles manually, similar to with actStateLayer
s.Background = nil
} else {
s.Color = colors.Scheme.OnSurface
}
})
tr.FinalStyler(func(s *styles.Style) {
tr.actStateLayer = s.StateLayer
s.StateLayer = 0
})
// We let the parts handle our state
// so that we only get it when we are doing
// something with this tree specifically,
// not with any of our children (see OnChildAdded).
// we only need to handle the starting ones here,
// as the other ones will just set the state to
// false, which it already is.
tr.On(events.MouseEnter, func(e events.Event) { e.SetHandled() })
tr.On(events.MouseLeave, func(e events.Event) { e.SetHandled() })
tr.On(events.MouseDown, func(e events.Event) { e.SetHandled() })
tr.OnClick(func(e events.Event) { e.SetHandled() })
tr.On(events.DragStart, func(e events.Event) { e.SetHandled() })
tr.On(events.DragEnter, func(e events.Event) { e.SetHandled() })
tr.On(events.DragLeave, func(e events.Event) { e.SetHandled() })
tr.On(events.Drop, func(e events.Event) { e.SetHandled() })
tr.On(events.DropDeleteSource, func(e events.Event) { tr.This.(Treer).DropDeleteSource(e) })
tr.On(events.KeyChord, func(e events.Event) {
kf := keymap.Of(e.KeyChord())
selMode := events.SelectModeBits(e.Modifiers())
if DebugSettings.KeyEventTrace {
slog.Info("Tree KeyInput", "widget", tr, "keyFunction", kf, "selMode", selMode)
}
if selMode == events.SelectOne {
if tr.SelectMode {
selMode = events.ExtendContinuous
}
}
tri := tr.This.(Treer)
// first all the keys that work for ReadOnly and active
switch kf {
case keymap.CancelSelect:
tr.UnselectAll()
tr.SetSelectMode(false)
e.SetHandled()
case keymap.MoveRight:
tr.Open()
e.SetHandled()
case keymap.MoveLeft:
tr.Close()
e.SetHandled()
case keymap.MoveDown:
tr.moveDownEvent(selMode)
e.SetHandled()
case keymap.MoveUp:
tr.moveUpEvent(selMode)
e.SetHandled()
case keymap.PageUp:
tr.movePageUpEvent(selMode)
e.SetHandled()
case keymap.PageDown:
tr.movePageDownEvent(selMode)
e.SetHandled()
case keymap.Home:
tr.moveHomeEvent(selMode)
e.SetHandled()
case keymap.End:
tr.moveEndEvent(selMode)
e.SetHandled()
case keymap.SelectMode:
tr.SelectMode = !tr.SelectMode
e.SetHandled()
case keymap.SelectAll:
tr.SelectAll()
e.SetHandled()
case keymap.Enter:
tr.ToggleClose()
e.SetHandled()
case keymap.Copy:
tri.Copy()
e.SetHandled()
}
if !tr.rootIsReadOnly() && !e.IsHandled() {
switch kf {
case keymap.Delete:
tr.DeleteSelected()
e.SetHandled()
case keymap.Duplicate:
tr.Duplicate()
e.SetHandled()
case keymap.Insert:
tr.InsertBefore()
e.SetHandled()
case keymap.InsertAfter:
tr.InsertAfter()
e.SetHandled()
case keymap.InsertChild:
tr.AddChildNode()
e.SetHandled()
case keymap.Cut:
tri.Cut()
e.SetHandled()
case keymap.Paste:
tri.Paste()
e.SetHandled()
}
}
})
parts := tr.newParts()
tri := tr.This.(Treer)
parts.Styler(func(s *styles.Style) {
s.Cursor = cursors.Pointer
s.SetAbilities(true, abilities.Activatable, abilities.Focusable, abilities.Selectable, abilities.Hoverable, abilities.DoubleClickable)
s.SetAbilities(!tr.IsReadOnly() && !tr.rootIsReadOnly(), abilities.Draggable, abilities.Droppable)
s.Gap.X.Em(0.1)
s.Padding.Zero()
s.Align.Items = styles.Center
// we manually inherit our state layer from the tree state
// layer so that the parts get it but not the other trees
s.StateLayer = tr.actStateLayer
})
parts.AsWidget().FinalStyler(func(s *styles.Style) {
s.Grow.Set(1, 0)
})
// we let the parts handle our state
// so that we only get it when we are doing
// something with this tree specifically,
// not with any of our children (see HandleTreeMouse)
parts.On(events.MouseEnter, func(e events.Event) {
tr.SetState(true, states.Hovered)
tr.Style()
tr.NeedsRender()
e.SetHandled()
})
parts.On(events.MouseLeave, func(e events.Event) {
tr.SetState(false, states.Hovered)
tr.Style()
tr.NeedsRender()
e.SetHandled()
})
parts.On(events.MouseDown, func(e events.Event) {
tr.SetState(true, states.Active)
tr.Style()
tr.NeedsRender()
e.SetHandled()
})
parts.On(events.MouseUp, func(e events.Event) {
tr.SetState(false, states.Active)
tr.Style()
tr.NeedsRender()
e.SetHandled()
})
parts.OnClick(func(e events.Event) {
tr.SelectEvent(e.SelectMode(), e)
e.SetHandled()
})
parts.AsWidget().OnDoubleClick(func(e events.Event) {
if tr.HasChildren() {
tr.ToggleClose()
}
})
parts.On(events.DragStart, func(e events.Event) {
tr.dragStart(e)
})
parts.On(events.DragEnter, func(e events.Event) {
tr.SetState(true, states.DragHovered)
tr.Style()
tr.NeedsRender()
e.SetHandled()
})
parts.On(events.DragLeave, func(e events.Event) {
tr.SetState(false, states.DragHovered)
tr.Style()
tr.NeedsRender()
e.SetHandled()
})
parts.On(events.Drop, func(e events.Event) {
tri.DragDrop(e)
})
parts.On(events.DropDeleteSource, func(e events.Event) {
tri.DropDeleteSource(e)
})
// the context menu events will get sent to the parts, so it
// needs to intercept them and send them up
parts.On(events.ContextMenu, func(e events.Event) {
sels := tr.GetSelectedNodes()
if len(sels) == 0 {
tr.SelectEvent(e.SelectMode(), e)
}
tr.ShowContextMenu(e)
})
tree.AddChildAt(parts, "branch", func(w *Switch) {
tr.Branch = w
w.SetType(SwitchCheckbox)
w.SetIconOn(tr.IconOpen).SetIconOff(tr.IconClosed).SetIconIndeterminate(tr.IconLeaf)
w.Styler(func(s *styles.Style) {
s.SetAbilities(false, abilities.Focusable)
// parent will handle our cursor
s.Cursor = cursors.None
s.Color = colors.Scheme.Primary.Base
s.Padding.Zero()
s.IconSize = tr.Styles.IconSize
s.Align.Self = styles.Center
if !w.StateIs(states.Indeterminate) {
// we amplify any state layer we receiver so that it is clear
// we are receiving it, not just our parent
s.StateLayer *= 3
} else {
// no abilities and state layer for indeterminate because
// they are not interactive
s.Abilities = 0
s.StateLayer = 0
}
})
w.OnClick(func(e events.Event) {
if w.IsChecked() && !w.StateIs(states.Indeterminate) {
if !tr.Closed {
tr.Close()
}
} else {
if tr.Closed {
tr.Open()
}
}
})
w.Updater(func() {
if tr.This.(Treer).CanOpen() {
tr.setBranchState()
}
})
})
parts.Maker(func(p *tree.Plan) {
if tr.Icon.IsSet() {
tree.AddAt(p, "icon", func(w *Icon) {
w.Styler(func(s *styles.Style) {
s.Color = colors.Scheme.Primary.Base
s.Align.Self = styles.Center
})
w.Updater(func() {
w.SetIcon(tr.Icon)
})
})
}
})
tree.AddChildAt(parts, "text", func(w *Text) {
w.Styler(func(s *styles.Style) {
s.SetNonSelectable()
s.SetTextWrap(false)
s.Min.X.Ch(16)
s.Min.Y.Em(1.2)
})
w.Updater(func() {
w.SetText(tr.Label())
})
})
// note: this causes excessive updates and is not recommended. use Resync() instead.
// tr.Updater(func() {
// if tr.SyncNode != nil {
// tr.syncToSrc(&tr.viewIndex, false, 0)
// }
// })
}
func (tr *Tree) OnAdd() {
tr.WidgetBase.OnAdd()
if tr.Text == "" { // a pasted, moved, or duplicated node keeps its text
tr.Text = tr.Name
}
if ptv := AsTree(tr.Parent); ptv != nil {
if ptv.Root == nil {
// The parent is the root of a tree that has not been added
// anywhere yet, such as the result of [tree.NodeBase.Clone].
ptv.Root = ptv.This.(Treer)
}
tr.Root = ptv.Root
tr.IconOpen = ptv.IconOpen
tr.IconClosed = ptv.IconClosed
tr.IconLeaf = ptv.IconLeaf
} else {
if tr.Root == nil {
tr.Root = tr.This.(Treer)
}
}
// A subtree added as a whole (for example, a duplicate or a moved node)
// already has children, whose roots must now be the new root.
tr.setDescendantRoots(tr.Root)
troot := tr.Root.AsCoreTree()
if troot.TreeInit != nil {
troot.TreeInit(tr)
}
}
// setDescendantRoots sets the [Tree.Root] of all descendant tree
// nodes of this node to the given root.
func (tr *Tree) setDescendantRoots(root Treer) {
for _, c := range tr.Children {
if ct := AsTree(c); ct != nil {
ct.Root = root
ct.setDescendantRoots(root)
}
}
}
// SetTreeInit sets the [Tree.TreeInit]:
// TreeInit is a function that can be set on the root node that is called
// with each child tree node when it is initialized. It is only
// called with the root node itself in this function, SetTreeInit, so you
// should typically call this instead of setting it directly.
func (tr *Tree) SetTreeInit(v func(tr *Tree)) *Tree {
tr.TreeInit = v
v(tr)
return tr
}
// rootIsReadOnly returns the ReadOnly status of the root node,
// which is what controls the functional inactivity of the tree
// if individual nodes are ReadOnly that only affects display typically.
func (tr *Tree) rootIsReadOnly() bool {
if tr.Root == nil {
return true
}
return tr.Root.AsCoreTree().IsReadOnly()
}
func (tr *Tree) Style() {
if !tr.HasChildren() {
tr.SetClosed(true)
}
tr.WidgetBase.Style()
tr.Indent.ToDots(&tr.Styles.UnitContext)
tr.Indent.Dots = math32.Ceil(tr.Indent.Dots)
}
func (tr *Tree) setBranchState() {
br := tr.Branch
if br == nil {
return
}
switch {
case !tr.This.(Treer).CanOpen():
br.SetState(true, states.Indeterminate)
case tr.Closed:
br.SetState(false, states.Indeterminate)
br.SetState(false, states.Checked)
br.NeedsRender()
default:
br.SetState(false, states.Indeterminate)
br.SetState(true, states.Checked)
br.NeedsRender()
}
}
// Tree is tricky for alloc because it is both a layout
// of its children but has to maintain its own bbox for its own widget.
func (tr *Tree) SizeUp() {
tr.WidgetBase.SizeUp()
tr.widgetSize = tr.Geom.Size.Actual.Total
h := tr.widgetSize.Y
w := tr.widgetSize.X
if tr.IsRoot() { // do it every time on root
tr.rootSetViewIndex()
}
if !tr.Closed {
// we layout children under us
tr.ForWidgetChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
cw.SizeUp()
h += cwb.Geom.Size.Actual.Total.Y
kw := cwb.Geom.Size.Actual.Total.X
if math32.IsNaN(kw) { // somehow getting a nan
slog.Error("Tree, node width is NaN", "node:", cwb)
} else {
w = max(w, tr.Indent.Dots+kw)
}
// fmt.Println(kwb, w, h)
return tree.Continue
})
}
sz := &tr.Geom.Size
sz.Actual.Content = math32.Vec2(w, h)
sz.SetTotalFromContent(&sz.Actual)
sz.Alloc = sz.Actual // need allocation to match!
tr.widgetSize.X = w // stretch
}
func (tr *Tree) SizeDown(iter int) bool {
// note: key to not grab the whole allocation, as widget default does
redo := tr.sizeDownParts(iter) // give our content to parts
re := tr.sizeDownChildren(iter)
return redo || re
}
func (tr *Tree) Position() {
if tr.Root == nil {
slog.Error("core.Tree: RootView is nil", "in node:", tr)
return
}
rn := tr.Root.AsCoreTree()
tr.setBranchState()
sz := &tr.Geom.Size
// A node extends to the right edge of the root, so it is as wide as its
// parent node minus its offset from the parent (its indent within the
// content of the parent). The scene positions of the nodes can not be
// used for this, as they are only set after this, in ApplyScenePos,
// and they are not set yet for new nodes.
if ptr := AsTree(tr.Parent); ptr != nil && tr != rn {
sz.Actual.Total.X = ptr.widgetSize.X - (ptr.Geom.contentOffset.X + tr.Geom.RelPos.X)
}
sz.Actual.Content.X = sz.Actual.Total.X - sz.Space.X
tr.widgetSize.X = sz.Actual.Total.X
sz.Alloc = sz.Actual
psz := &tr.Parts.Geom.Size
psz.Alloc.Total = tr.widgetSize
psz.SetContentFromTotal(&psz.Alloc)
tr.WidgetBase.Position() // just does our parts
if !tr.Closed {
h := tr.widgetSize.Y
tr.ForWidgetChildren(func(i int, cw Widget, cwb *WidgetBase) bool {
cwb.Geom.RelPos.Y = h
cwb.Geom.RelPos.X = tr.Indent.Dots
h += cwb.Geom.Size.Actual.Total.Y
cw.Position()
return tree.Continue
})
}
}
func (tr *Tree) ApplyScenePos() {
sz := &tr.Geom.Size
if sz.Actual.Total == tr.widgetSize {
sz.SetTotalFromContent(&sz.Actual) // restore after scrolling
}
tr.WidgetBase.ApplyScenePos()
tr.applyScenePosChildren()
sz.Actual.Total = tr.widgetSize // key: we revert to just ourselves
}
func (tr *Tree) Render() {
pc := &tr.Scene.Painter
st := &tr.Styles
pabg := tr.parentActualBackground()
// must use workaround act values
st.StateLayer = tr.actStateLayer
if st.Is(states.Selected) {
st.Background = colors.Scheme.Select.Container
}
tr.Styles.ComputeActualBackground(pabg)
pc.StandardBox(st, tr.Geom.Pos.Total, tr.Geom.Size.Actual.Total, pabg)
// after we are done rendering, we clear the values so they aren't inherited
st.StateLayer = 0
st.Background = nil
tr.Styles.ComputeActualBackground(pabg)
}
func (tr *Tree) RenderWidget() {
if tr.StartRender() {
tr.Render()
if tr.Parts != nil {
// we must copy from actual values in parent
tr.Parts.Styles.StateLayer = tr.actStateLayer
if tr.StateIs(states.Selected) {
tr.Parts.Styles.Background = colors.Scheme.Select.Container
}
tr.renderParts()
}
tr.EndRender()
}
// We have to render our children outside of `if StartRender`
// since we could be out of scope but they could still be in!
if !tr.Closed {
tr.renderChildren()
}
}
//////// Selection
// IsRootSelected returns whether the root node is the only node selected.
// This can be used in [events.Select] event handlers to check whether a
// select event on the root node truly corresponds to the root node or whether
// it is for another node, as select events are sent to the root when any node
// is selected.
func (tr *Tree) IsRootSelected() bool {
return len(tr.SelectedNodes) == 1 && tr.SelectedNodes[0] == tr.Root
}
// GetSelectedNodes returns a slice of the currently selected
// Trees within the entire tree, using a list maintained
// by the root node.
func (tr *Tree) GetSelectedNodes() []Treer {
if tr.Root == nil {
return nil
}
rn := tr.Root.AsCoreTree()
if len(rn.SelectedNodes) == 0 {
return rn.SelectedNodes
}
return rn.SelectedNodes
}
// SetSelectedNodes updates the selected nodes on the root node to the given list.
func (tr *Tree) SetSelectedNodes(sl []Treer) {
if tr.Root != nil {
tr.Root.AsCoreTree().SelectedNodes = sl
}
}
// HasSelection returns whether there are currently selected items.
func (tr *Tree) HasSelection() bool {
return len(tr.GetSelectedNodes()) > 0
}
// Select selects this node (if not already selected).
// You must use this method to update global selection list.
func (tr *Tree) Select() {
if !tr.StateIs(states.Selected) {
tr.SetSelected(true)
tr.Style()
sl := tr.GetSelectedNodes()
sl = append(sl, tr.This.(Treer))
tr.SetSelectedNodes(sl)
tr.NeedsRender()
}
}
// Unselect unselects this node (if selected).
// You must use this method to update global selection list.
func (tr *Tree) Unselect() {
if tr.StateIs(states.Selected) {
tr.SetSelected(false)
tr.Style()
sl := tr.GetSelectedNodes()
sz := len(sl)
for i := range sz {
if sl[i] == tr.This {
sl = append(sl[:i], sl[i+1:]...)
break
}
}
tr.SetSelectedNodes(sl)
tr.NeedsRender()
}
}
// UnselectAll unselects all selected items in the tree.
func (tr *Tree) UnselectAll() {
if tr.Scene == nil {
return
}
sl := tr.GetSelectedNodes()
tr.SetSelectedNodes(nil) // clear in advance
for _, v := range sl {
vt := v.AsCoreTree()
if vt == nil || vt.This == nil {
continue
}
vt.SetSelected(false)
v.Style()
vt.NeedsRender()
}
tr.NeedsRender()
}
// SelectAll selects all items in the tree.
func (tr *Tree) SelectAll() {
if tr.Scene == nil {
return
}
tr.UnselectAll()
nn := tr.Root.AsCoreTree()
nn.Select()
for nn != nil {
nn = nn.moveDown(events.SelectQuiet)
}
tr.NeedsRender()
}
// selectUpdate updates selection to include this node,
// using selectmode from mouse event (ExtendContinuous, ExtendOne).
// Returns true if this node selected.
func (tr *Tree) selectUpdate(mode events.SelectModes) bool {
if mode == events.NoSelect {
return false
}
sel := false
switch mode {
case events.SelectOne:
if tr.StateIs(states.Selected) {
sl := tr.GetSelectedNodes()
if len(sl) > 1 {
tr.UnselectAll()
tr.Select()
tr.SetFocusQuiet()
sel = true
}
} else {
tr.UnselectAll()
tr.Select()
tr.SetFocusQuiet()
sel = true
}
case events.ExtendContinuous:
sl := tr.GetSelectedNodes()
if len(sl) == 0 {
tr.Select()
tr.SetFocusQuiet()
sel = true
} else {
minIndex := -1
maxIndex := 0
sel = true
for _, v := range sl {
vn := v.AsCoreTree()
if minIndex < 0 {
minIndex = vn.viewIndex
} else {
minIndex = min(minIndex, vn.viewIndex)
}
maxIndex = max(maxIndex, vn.viewIndex)
}
cidx := tr.viewIndex
nn := tr
tr.Select()
if tr.viewIndex < minIndex {
for cidx < minIndex {
nn = nn.moveDown(events.SelectQuiet) // just select
cidx = nn.viewIndex
}
} else if tr.viewIndex > maxIndex {
for cidx > maxIndex {
nn = nn.moveUp(events.SelectQuiet) // just select
cidx = nn.viewIndex
}
}
}
case events.ExtendOne:
if tr.StateIs(states.Selected) {
tr.UnselectEvent()
} else {
tr.Select()
tr.SetFocusQuiet()
sel = true
}
case events.SelectQuiet:
tr.Select()
// not sel -- no signal..
case events.UnselectQuiet:
tr.Unselect()
// not sel -- no signal..
}
tr.NeedsRender()
return sel
}
// sendSelectEvent sends an [events.Select] event on both this node and the root node.
func (tr *Tree) sendSelectEvent(original ...events.Event) {
if !tr.IsRoot() {
tr.Send(events.Select, original...)
}
tr.Root.AsCoreTree().Send(events.Select, original...)
}
// sendChangeEvent sends an [events.Change] event on both this node and the root node.
func (tr *Tree) sendChangeEvent(original ...events.Event) {
if !tr.IsRoot() {
tr.SendChange(original...)
}
tr.Root.AsCoreTree().SendChange(original...)
}
// sendChangeEventReSync sends an [events.Change] event on the RootView node.
// If SyncNode != nil, it also does a re-sync from root.
func (tr *Tree) sendChangeEventReSync(original ...events.Event) {
tr.sendChangeEvent(original...)
rn := tr.Root.AsCoreTree()
if rn.SyncNode != nil {
rn.Resync()
}
}
// SelectEvent updates selection to include this node,
// using selectmode from mouse event (ExtendContinuous, ExtendOne),
// and root sends selection event. Returns true if event sent.
func (tr *Tree) SelectEvent(mode events.SelectModes, original ...events.Event) bool {
sel := tr.selectUpdate(mode)
if sel {
tr.sendSelectEvent(original...)
}
return sel
}
// UnselectEvent unselects this node (if selected),
// and root sends a selection event.
func (tr *Tree) UnselectEvent() {
if tr.StateIs(states.Selected) {
tr.Unselect()
tr.sendSelectEvent()
}
}
//////// Moving
// moveDown moves the selection down to next element in the tree,
// using given select mode (from keyboard modifiers).
// Returns newly selected node.
func (tr *Tree) moveDown(selMode events.SelectModes) *Tree {
if tree.IsNil(tr) || tree.IsNil(tr.Parent) {
return nil
}
if tr.Closed || !tr.HasChildren() { // next sibling
return tr.moveDownSibling(selMode)
}
if tr.HasChildren() {
nn := AsTree(tr.Child(0))
if nn != nil {
nn.selectUpdate(selMode)
return nn
}
}
return nil
}
// moveDownEvent moves the selection down to next element in the tree,
// using given select mode (from keyboard modifiers).
// Sends select event for newly selected item.
func (tr *Tree) moveDownEvent(selMode events.SelectModes) *Tree {
nn := tr.moveDown(selMode)
if nn != nil && nn != tr {
nn.SetFocusQuiet()
nn.ScrollToThis()
nn.sendSelectEvent()
}
return nn
}
// moveDownSibling moves down only to siblings, not down into children,
// using given select mode (from keyboard modifiers)
func (tr *Tree) moveDownSibling(selMode events.SelectModes) *Tree {
if tree.IsNil(tr) || tree.IsNil(tr.Parent) {
return nil
}
if tr.This == tr.Root {
return nil
}
myidx := tr.IndexInParent()
if myidx < len(tr.Parent.AsTree().Children)-1 {
nn := AsTree(tr.Parent.AsTree().Child(myidx + 1))
if nn != nil {
nn.selectUpdate(selMode)
return nn
}
} else {
return AsTree(tr.Parent).moveDownSibling(selMode) // try up
}
return nil
}
// moveUp moves selection up to previous element in the tree,
// using given select mode (from keyboard modifiers).
// Returns newly selected node
func (tr *Tree) moveUp(selMode events.SelectModes) *Tree {
if tree.IsNil(tr) || tree.IsNil(tr.Parent) || tr.This == tr.Root {
return nil
}
myidx := tr.IndexInParent()
if myidx > 0 {
nn := AsTree(tr.Parent.AsTree().Child(myidx - 1))
if nn != nil {
return nn.moveToLastChild(selMode)
}
} else {
if tr.Parent != nil {
nn := AsTree(tr.Parent)
if nn != nil {
nn.selectUpdate(selMode)
return nn
}
}
}
return nil
}
// moveUpEvent moves the selection up to previous element in the tree,
// using given select mode (from keyboard modifiers).
// Sends select event for newly selected item.
func (tr *Tree) moveUpEvent(selMode events.SelectModes) *Tree {
nn := tr.moveUp(selMode)
if nn != nil && nn != tr {
nn.SetFocusQuiet()
nn.ScrollToThis()
nn.sendSelectEvent()
}
return nn
}
// treePageSteps is the number of steps to take in PageUp / Down events
const treePageSteps = 10
// movePageUpEvent moves the selection up to previous
// TreePageSteps elements in the tree,
// using given select mode (from keyboard modifiers).
// Sends select event for newly selected item.
func (tr *Tree) movePageUpEvent(selMode events.SelectModes) *Tree {
mvMode := selMode
switch selMode {
case events.SelectOne:
mvMode = events.NoSelect
case events.ExtendContinuous, events.ExtendOne:
mvMode = events.SelectQuiet
}
fnn := tr.moveUp(mvMode)
if fnn != nil && fnn != tr {
for i := 1; i < treePageSteps; i++ {
nn := fnn.moveUp(mvMode)
if nn == nil || nn == fnn {
break
}
fnn = nn
}
if selMode == events.SelectOne {
fnn.selectUpdate(selMode)
}
fnn.SetFocusQuiet()
fnn.ScrollToThis()
fnn.sendSelectEvent()
}
tr.NeedsRender()
return fnn
}
// movePageDownEvent moves the selection up to
// previous TreePageSteps elements in the tree,
// using given select mode (from keyboard modifiers).
// Sends select event for newly selected item.
func (tr *Tree) movePageDownEvent(selMode events.SelectModes) *Tree {
mvMode := selMode
switch selMode {
case events.SelectOne:
mvMode = events.NoSelect
case events.ExtendContinuous, events.ExtendOne:
mvMode = events.SelectQuiet
}
fnn := tr.moveDown(mvMode)
if fnn != nil && fnn != tr {
for i := 1; i < treePageSteps; i++ {
nn := fnn.moveDown(mvMode)
if nn == nil || nn == fnn {
break
}
fnn = nn
}
if selMode == events.SelectOne {
fnn.selectUpdate(selMode)
}
fnn.SetFocusQuiet()
fnn.ScrollToThis()
fnn.sendSelectEvent()
}
tr.NeedsRender()
return fnn
}
// moveToLastChild moves to the last child under me, using given select mode
// (from keyboard modifiers)
func (tr *Tree) moveToLastChild(selMode events.SelectModes) *Tree {
if tree.IsNil(tr) || tr.Parent == nil || tr.This == tr.Root {
return nil
}
if !tr.Closed && tr.HasChildren() {
nn := AsTree(tr.Child(tr.NumChildren() - 1))
return nn.moveToLastChild(selMode)
}
tr.selectUpdate(selMode)
return tr
}
// moveHomeEvent moves the selection up to top of the tree,
// using given select mode (from keyboard modifiers)
// and emits select event for newly selected item
func (tr *Tree) moveHomeEvent(selMode events.SelectModes) *Tree {
rn := tr.Root.AsCoreTree()
rn.selectUpdate(selMode)
rn.SetFocusQuiet()
rn.ScrollToThis()
rn.sendSelectEvent()
return rn
}
// moveEndEvent moves the selection to the very last node in the tree,
// using given select mode (from keyboard modifiers)
// Sends select event for newly selected item.
func (tr *Tree) moveEndEvent(selMode events.SelectModes) *Tree {
mvMode := selMode
switch selMode {
case events.SelectOne:
mvMode = events.NoSelect
case events.ExtendContinuous, events.ExtendOne:
mvMode = events.SelectQuiet
}
fnn := tr.moveDown(mvMode)
if fnn != nil && fnn != tr {
for {
nn := fnn.moveDown(mvMode)
if nn == nil || nn == fnn {
break
}
fnn = nn
}
if selMode == events.SelectOne {
fnn.selectUpdate(selMode)
}
fnn.SetFocusQuiet()
fnn.ScrollToThis()
fnn.sendSelectEvent()
}
return fnn
}
func (tr *Tree) setChildrenVisibility(parentClosed bool) {
for _, c := range tr.Children {
tvn := AsTree(c)
if tvn != nil {
tvn.SetState(parentClosed, states.Invisible)
}
}
}
// OnClose is called when a node is closed.
// The base version does nothing.
func (tr *Tree) OnClose() {}
// Close closes the given node and updates the tree accordingly
// (if it is not already closed). It calls OnClose in the [Treer]
// interface for extensible actions.
func (tr *Tree) Close() {
if tr.Closed {
return
}
tr.SetClosed(true)
tr.setBranchState()
tr.This.(Treer).OnClose()
tr.setChildrenVisibility(true) // parent closed
tr.NeedsLayout()
}
// OnOpen is called when a node is opened.
// The base version does nothing.
func (tr *Tree) OnOpen() {}
// CanOpen returns true if the node is able to open.
// By default it checks HasChildren(), but could check other properties
// to perform lazy building of the tree.
func (tr *Tree) CanOpen() bool {
return tr.HasChildren()
}
// Open opens the given node and updates the tree accordingly
// (if it is not already opened). It calls OnOpen in the [Treer]
// interface for extensible actions.
func (tr *Tree) Open() {
if !tr.Closed || tr.inOpen || tr.This == nil {
return
}
tr.inOpen = true
if tr.This.(Treer).CanOpen() {
tr.SetClosed(false)
tr.setBranchState()
tr.setChildrenVisibility(false)
tr.This.(Treer).OnOpen()
}
tr.inOpen = false
tr.NeedsLayout()
}
// ToggleClose toggles the close / open status: if closed, opens, and vice-versa.
func (tr *Tree) ToggleClose() {
if tr.Closed {
tr.Open()
} else {
tr.Close()
}
}
// OpenAll opens the node and all of its sub-nodes.
func (tr *Tree) OpenAll() { //types:add
tr.WidgetWalkDown(func(cw Widget, cwb *WidgetBase) bool {
tvn := AsTree(cw)
if tvn != nil {
tvn.Open()
return tree.Continue
}
return tree.Break
})
tr.NeedsLayout()
}
// CloseAll closes the node and all of its sub-nodes.
func (tr *Tree) CloseAll() { //types:add
tr.WidgetWalkDown(func(cw Widget, cwb *WidgetBase) bool {
tvn := AsTree(cw)
if tvn != nil {
tvn.Close()
return tree.Continue
}
return tree.Break
})
tr.NeedsLayout()
}
// OpenParents opens all the parents of this node
// so that it will be visible.
func (tr *Tree) OpenParents() {
for k := range tr.Ancestors() {
tvn := AsTree(k)
if tvn != nil {
tvn.Open()
continue
}
break
}
tr.NeedsLayout()
}
//////// Modifying Source Tree
func (tr *Tree) ContextMenuPos(e events.Event) (pos image.Point) {
if e != nil && e.HasPos() {
pos = e.WindowPos()
return
}
pos.X = tr.Geom.TotalBBox.Min.X + int(tr.Indent.Dots)
pos.Y = (tr.Geom.TotalBBox.Min.Y + tr.Geom.TotalBBox.Max.Y) / 2
return
}
func (tr *Tree) contextMenuReadOnly(m *Scene) {
tri := tr.This.(Treer)
NewFuncButton(m).SetFunc(tri.Copy).SetKey(keymap.Copy).
SetEnabled(tr.HasSelection())
NewFuncButton(m).SetFunc(tr.EditNode).SetText("View").
SetIcon(icons.Visibility).SetEnabled(tr.HasSelection())
NewSeparator(m)
NewFuncButton(m).SetFunc(tr.OpenAll).SetIcon(icons.KeyboardArrowDown).
SetEnabled(tr.HasSelection())
NewFuncButton(m).SetFunc(tr.CloseAll).SetIcon(icons.KeyboardArrowRight).
SetEnabled(tr.HasSelection())
}
func (tr *Tree) contextMenu(m *Scene, pos image.Point) {
if tr.IsReadOnly() || tr.rootIsReadOnly() {
tr.contextMenuReadOnly(m)
return
}
tri := tr.This.(Treer)
NewFuncButton(m).SetFunc(tr.AddChildNode).SetText("Add child").SetIcon(icons.Add).SetKey(keymap.InsertChild).SetEnabled(tr.HasSelection())
NewFuncButton(m).SetFunc(tr.InsertBefore).SetIcon(icons.Add).SetKey(keymap.Insert).
SetEnabled(tr.HasSelection())
NewFuncButton(m).SetFunc(tr.InsertAfter).SetIcon(icons.Add).SetKey(keymap.InsertAfter).
SetEnabled(tr.HasSelection())
NewFuncButton(m).SetFunc(tr.Duplicate).SetIcon(icons.ContentCopy).
SetEnabled(tr.HasSelection())
NewFuncButton(m).SetFunc(tr.DeleteSelected).SetText("Delete").SetIcon(icons.Delete).
SetEnabled(tr.HasSelection())
NewSeparator(m)
NewFuncButton(m).SetFunc(tri.Copy).SetIcon(icons.Copy).SetKey(keymap.Copy).
SetEnabled(tr.HasSelection())
NewFuncButton(m).SetFunc(tri.Cut).SetIcon(icons.Cut).SetKey(keymap.Cut).
SetEnabled(tr.HasSelection())
paste := NewFuncButton(m).SetFunc(tri.Paste).SetIcon(icons.Paste).SetKey(keymap.Paste)
cb := tr.Scene.Events.Clipboard()
if cb != nil {
paste.SetState(cb.IsEmpty(), states.Disabled)
}
NewSeparator(m)
NewFuncButton(m).SetFunc(tr.EditNode).SetText("Edit").SetIcon(icons.Edit).
SetEnabled(tr.HasSelection())
NewFuncButton(m).SetFunc(tr.inspectNode).SetText("Inspect").SetIcon(icons.EditDocument).
SetEnabled(tr.HasSelection())
NewSeparator(m)
NewFuncButton(m).SetFunc(tr.OpenAll).SetIcon(icons.KeyboardArrowDown).
SetEnabled(tr.HasSelection())
NewFuncButton(m).SetFunc(tr.CloseAll).SetIcon(icons.KeyboardArrowRight).
SetEnabled(tr.HasSelection())
}
// IsRoot returns true if given node is the root of the tree,
// creating an error snackbar if it is and action is non-empty.
func (tr *Tree) IsRoot(action ...string) bool {
if tr.This == tr.Root.AsCoreTree().This {
if len(action) > 0 {
MessageSnackbar(tr, fmt.Sprintf("Cannot %v the root of the tree", action[0]))
}
return true
}
return false
}
//////// Copy / Cut / Paste
// DeleteSelected deletes selected items.
// Must be called from first node in selection.
func (tr *Tree) DeleteSelected() { //types:add
if tr.IsRoot("Delete") {
return
}
if tr.SyncNode != nil {
tr.deleteSync()
return
}
sels := tr.GetSelectedNodes()
rn := tr.Root.AsCoreTree()
tr.UnselectAll()
for _, sn := range sels {
sn.AsTree().Delete()
}
rn.Update()
rn.sendChangeEvent()
}
// MimeData adds mimedata for this node: a text/plain of the Path.
func (tr *Tree) MimeData(md *mimedata.Mimes) {
if tr.SyncNode != nil {
tr.mimeDataSync(md)
return
}
*md = append(*md, mimedata.NewTextData(tr.PathFrom(tr.Root.AsCoreTree())))
var buf bytes.Buffer
err := jsonx.Write(tr.This, &buf)
if err == nil {
*md = append(*md, &mimedata.Data{Type: fileinfo.DataJSON, Data: buf.Bytes()})
} else {
ErrorSnackbar(tr, err, "Error encoding node")
}
}
// nodesFromMimeData returns a slice of tree nodes for
// the Tree nodes and paths from mime data.
func (tr *Tree) nodesFromMimeData(md mimedata.Mimes) ([]tree.Node, []string) {
ni := len(md) / 2
sl := make([]tree.Node, 0, ni)
pl := make([]string, 0, ni)
for _, d := range md {
switch d.Type {
case fileinfo.DataJSON:
nn, err := tree.UnmarshalRootJSON(d.Data)
if err == nil {
sl = append(sl, nn)
} else {
ErrorSnackbar(tr, err, "Error loading node")
}
case fileinfo.TextPlain: // paths
pl = append(pl, string(d.Data))
}
}
return sl, pl
}
// Copy copies the selected items to the clipboard.
// This must be called on the first item in the selected list.
func (tr *Tree) Copy() { //types:add
sels := tr.GetSelectedNodes()
nitms := max(1, len(sels))
md := make(mimedata.Mimes, 0, 2*nitms)
tr.This.(Treer).MimeData(&md) // source is always first..
if nitms > 1 {
for _, sn := range sels {
if sn != tr.This {
sn.MimeData(&md)
}
}
}
tr.Clipboard().Write(md)
}
// Cut copies to [system.Clipboard] and deletes selected items.
// This must be called on the first item in the selected list.
func (tr *Tree) Cut() { //types:add
if tr.IsRoot("Cut") {
return
}
if tr.SyncNode != nil {
tr.cutSync()
return
}
tr.Copy()
sels := tr.GetSelectedNodes()
rn := tr.Root.AsCoreTree()
tr.UnselectAll()
for _, sn := range sels {
sn.AsTree().Delete()
}
rn.Update()
rn.sendChangeEvent()
}
// Paste pastes clipboard at given node.
func (tr *Tree) Paste() { //types:add
md := tr.Clipboard().Read([]string{fileinfo.DataJSON})
if md != nil {
tr.pasteMenu(md)
}
}
// pasteMenu performs a paste from the clipboard using given data,
// by popping up a menu to determine what specifically to do.
func (tr *Tree) pasteMenu(md mimedata.Mimes) {
tr.UnselectAll()
mf := func(m *Scene, pos image.Point) {
tr.makePasteMenu(m, pos, md, events.DropCopy, nil)
}
pos := tr.ContextMenuPos(nil)
NewMenu(mf, tr.This.(Widget), pos).Run()
}
// makePasteMenu makes the menu of options for paste events
// Optional function is typically the DropFinalize but could also be other actions
// to take after each optional action.
func (tr *Tree) makePasteMenu(m *Scene, _ image.Point, md mimedata.Mimes, mod events.DropMods, fun func()) {
NewButton(m).SetText("Assign To").OnClick(func(e events.Event) {
tr.PasteAssign(md)
if fun != nil {
fun()
}
})
NewButton(m).SetText("Add to Children").OnClick(func(e events.Event) {
tr.PasteChildren(md, mod)
if fun != nil {
fun()
}
})
if !tr.IsRoot() {
NewButton(m).SetText("Insert Before").OnClick(func(e events.Event) {
tr.PasteBefore(md, mod)
if fun != nil {
fun()
}
})
NewButton(m).SetText("Insert After").OnClick(func(e events.Event) {
tr.PasteAfter(md, mod)
if fun != nil {
fun()
}
})
}
NewButton(m).SetText("Cancel")
}
// PasteAssign assigns mime data (only the first one!) to this node
func (tr *Tree) PasteAssign(md mimedata.Mimes) {
if tr.SyncNode != nil {
tr.pasteAssignSync(md)
return
}
sl, _ := tr.nodesFromMimeData(md)
if len(sl) == 0 {
return
}
tr.CopyFrom(sl[0]) // nodes with data copy here
tr.SetScene(tr.Scene) // ensure children have scene
tr.Update() // could have children
tr.Open()
tr.sendChangeEvent()
}
// PasteBefore inserts object(s) from mime data before this node.
// An object with the name of another one gets a unique name, except
// for one moved within its parent (see [namePasted]).
func (tr *Tree) PasteBefore(md mimedata.Mimes, mod events.DropMods) {
tr.pasteAt(md, mod, 0, "Paste before")
}
// PasteAfter inserts object(s) from mime data after this node.
// An object with the name of another one gets a unique name, except
// for one moved within its parent (see [namePasted]).
func (tr *Tree) PasteAfter(md mimedata.Mimes, mod events.DropMods) {
tr.pasteAt(md, mod, 1, "Paste after")
}
// treeTempMovedTag is a kind of hack to prevent moved items from being deleted, using DND
const treeTempMovedTag = `_\&MOVED\&`
// namePasted names the given node pasted into the given parent, from the
// given path of its source from the root. A node moved within the same
// parent (mod is DropMove) has the name of its source plus
// [treeTempMovedTag], until [Tree.DropDeleteSource] deletes the source and
// restores its name, so that it keeps its name. Other nodes get a unique
// name if theirs is a duplicate.
func namePasted(parent, ns, root tree.Node, mod events.DropMods, orgpath string) {
nt := ns.AsTree()
opar := nt.Parent
nt.Parent = parent // the path relies on the parent
npath := nt.PathFrom(root)
nt.Parent = opar
if mod == events.DropMove && npath == orgpath {
nt.SetName(nt.Name + treeTempMovedTag)
return
}
tree.SetUniqueNameIfDuplicate(parent, ns)
}
// todo: these methods require an interface to work for descended
// nodes, based on base code
// pasteAt inserts object(s) from mime data at rel position to this node.
// An object with the name of another one gets a unique name, except
// for one moved within its parent (see [namePasted]).
func (tr *Tree) pasteAt(md mimedata.Mimes, mod events.DropMods, rel int, actNm string) {
if tr.Parent == nil {
return
}
parent := AsTree(tr.Parent)
if parent == nil {
MessageSnackbar(tr, "Error: cannot insert after the root of the tree")
return
}
if tr.SyncNode != nil {
tr.pasteAtSync(md, mod, rel, actNm)
return
}
sl, pl := tr.nodesFromMimeData(md)
myidx := tr.IndexInParent()
if myidx < 0 {
return
}
myidx += rel
sz := len(sl)
var selTv *Tree
for i, ns := range sl {
namePasted(parent.This, ns, tr.Root, mod, pl[i])
parent.InsertChild(ns, myidx+i)
nwb := AsWidget(ns)
AsTree(ns).Root = tr.Root
nwb.SetScene(tr.Scene)
nwb.Update() // incl children
if i == sz-1 {
selTv = AsTree(ns)
}
}
tr.pasteChanged(mod)
parent.NeedsLayout()
if selTv != nil {
selTv.SelectEvent(events.SelectOne)
}
}
// PasteChildren inserts object(s) from mime data
// at end of children of this node.
func (tr *Tree) PasteChildren(md mimedata.Mimes, mod events.DropMods) {
if tr.SyncNode != nil {
tr.pasteChildrenSync(md, mod)
return
}
sl, pl := tr.nodesFromMimeData(md)
for i, ns := range sl {
namePasted(tr.This, ns, tr.Root, mod, pl[i])
tr.AddChild(ns)
AsTree(ns).Root = tr.Root
AsWidget(ns).SetScene(tr.Scene)
}
tr.Update()
tr.Open()
tr.pasteChanged(mod)
}
// pasteChanged sends the change event for a paste with the given drop
// mod, resyncing a sync tree, except for a move (DropMove): its source is
// deleted after it ([Tree.DropDeleteSource]), which sends it then, so that
// the moved nodes are never seen with their sources, as with the same IDs.
func (tr *Tree) pasteChanged(mod events.DropMods) {
if mod != events.DropMove {
tr.sendChangeEventReSync()
return
}
if rn := tr.Root.AsCoreTree(); rn.SyncNode != nil {
rn.Resync()
}
}
//////// Drag-n-Drop
// dragStart starts a drag-n-drop on this node -- it includes any other
// selected nodes as well, each as additional records in mimedata.
func (tr *Tree) dragStart(e events.Event) {
sels := tr.GetSelectedNodes()
nitms := max(1, len(sels))
md := make(mimedata.Mimes, 0, 2*nitms)
tr.This.(Treer).MimeData(&md) // source is always first..
if nitms > 1 {
for _, sn := range sels {
if sn != tr.This {
sn.MimeData(&md)
}
}
}
tr.Scene.Events.DragStart(tr.This.(Widget), md, e)
}
// dropExternal is not handled by base case but could be in derived
func (tr *Tree) dropExternal(md mimedata.Mimes, mod events.DropMods) {
// todo: not yet implemented
}
// dragClearStates clears the drag-drop related states for this widget
func (tr *Tree) dragClearStates() {
tr.dragStateReset()
tr.Parts.dragStateReset()
tr.Style()
tr.NeedsRender()
}
// DragDrop handles drag drop event
func (tr *Tree) DragDrop(e events.Event) {
// todo: some kind of validation for source
tr.UnselectAll()
de := e.(*events.DragDrop)
stv := AsTree(de.Source.(Widget))
if stv != nil {
stv.dragClearStates()
}
md := de.Data.(mimedata.Mimes)
mf := func(m *Scene, pos image.Point) {
tr.Scene.Events.DragMenuAddModText(m, de.DropMod)
tr.makePasteMenu(m, pos, md, de.DropMod, func() {
tr.DropFinalize(de)
})
}
pos := tr.ContextMenuPos(nil)
NewMenu(mf, tr.This.(Widget), pos).Run()
}
// DropFinalize is called to finalize Drop actions on the Source node.
// Only relevant for DropMod == DropMove.
func (tr *Tree) DropFinalize(de *events.DragDrop) {
tr.UnselectAll()
tr.dragClearStates()
tr.Scene.Events.DropFinalize(de) // sends DropDeleteSource to Source
}
// DropDeleteSource handles delete source event for DropMove case
func (tr *Tree) DropDeleteSource(e events.Event) {
de := e.(*events.DragDrop)
tr.UnselectAll()
if tr.SyncNode != nil {
tr.dropDeleteSourceSync(de)
return
}
md := de.Data.(mimedata.Mimes)
rn := tr.Root.AsCoreTree()
for _, d := range md {
if d.Type != fileinfo.TextPlain { // link
continue
}
path := string(d.Data)
sn := rn.FindPath(path)
if sn != nil {
sn.AsTree().Delete()
}
sn = rn.FindPath(path + treeTempMovedTag)
if sn != nil {
psplt := strings.Split(path, "/")
orgnm := psplt[len(psplt)-1]
sn.AsTree().SetName(orgnm)
AsWidget(sn).NeedsRender()
}
}
rn.sendChangeEvent()
}
//////// Search interface
// TextRunes returns any text content associated with the widget, to be used
// for Search for example. If this is nil, then it is excluded from search.
func (tr *Tree) TextRunes() []rune {
return nil
}
// Search returns text search results for this widget, searching for
// the find string with given case sensitivity. It is up to each widget
// to define the meaning of the Region line, char values for the matches.
// The bool return value indicates whether this widget handled the search,
// thereby excluding further searching within the elements under it.
func (tr *Tree) Search(find string, useCase CaseSensitive) ([]textpos.Match, bool) {
var results []textpos.Match
nn := tr.Root
idx := 0
next := func(c Treer) Treer {
idx++
nni := tree.Next(c)
if n, ok := nni.(Treer); ok {
return n
}
return nil
}
for nn != nil {
tr := nn.AsCoreTree()
str := tr.Label()
m := SearchRunes([]rune(str), find, useCase)
if len(m) == 0 {
nn = next(nn)
continue
}
for i := range m {
m[i].Region.Start.Line = idx
m[i].Region.End.Line = idx
}
results = append(results, m...)
nn = next(nn)
}
return results, true
}
// HighlightMatches does highlighting of the given matches within this widget,
// where the matches are as returned from the Search method.
// Passing a nil causes matches to be reset.
// Any existing highlighting should always be reset first regardless.
// The bool return value indicates whether this widget handled the search,
// thereby excluding further searching within the elements under it.
func (tr *Tree) HighlightMatches(matches []textpos.Match) bool {
nn := tr.Root
next := func(c Treer) Treer {
nni := tree.Next(c)
if n, ok := nni.(Treer); ok {
return n
}
return nil
}
for nn != nil {
tr := nn.AsCoreTree()
tx := tr.Parts.ChildByName("text", 1).(*Text)
tx.HighlightMatches(nil) // reset
tx.SelectMatch(matches, 0, SelectNoScroll, SelectReset)
nn = next(nn)
}
if matches == nil {
return true
}
idx := 0
nextTrg := func(trg int) *Text {
for nn != nil {
tr := nn.AsCoreTree()
tx := tr.Parts.ChildByName("text", 1).(*Text)
if idx == trg {
return tx
}
idx++
nn = next(nn)
}
return nil
}
nn = tr.Root
for _, m := range matches {
trg := m.Region.Start.Line
tx := nextTrg(trg)
tx.HighlightMatches([]textpos.Match{m})
}
return true
}
// SelectMatch selects match at given index from among those returned
// from the Search method. scroll = scroll widget into view.
// reset = clear selection instead of selecting.
func (tr *Tree) SelectMatch(matches []textpos.Match, index int, scroll SelectionScroll, reset SelectionReset) {
match := matches[index]
mIdx := match.Region.Start.Line
idx := 0
nn := tr.Root
next := func(c Treer) Treer {
idx++
nni := tree.Next(c)
if n, ok := nni.(Treer); ok {
return n
}
return nil
}
for nn != nil {
if idx < mIdx {
nn = next(nn)
continue
}
tr := nn.AsCoreTree()
if tr.Closed {
tr.OpenParents()
}
tr.ScrollToThis()
tx := tr.Parts.ChildByName("text", 1).(*Text)
tx.SelectMatch(matches, 0, SelectNoScroll, reset)
break
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"bytes"
"fmt"
"log"
"strings"
"cogentcore.org/core/base/fileinfo"
"cogentcore.org/core/base/fileinfo/mimedata"
"cogentcore.org/core/base/iox/jsonx"
"cogentcore.org/core/base/labels"
"cogentcore.org/core/events"
"cogentcore.org/core/tree"
"cogentcore.org/core/types"
)
// note: see this file has all the SyncNode specific
// functions for Tree.
// SyncTree sets the root [Tree.SyncNode] to the root of the given [tree.Node]
// and synchronizes the rest of the tree to match. The source tree must have
// unique names for each child within a given parent.
func (tr *Tree) SyncTree(n tree.Node) *Tree {
if tr.SyncNode != n {
tr.SyncNode = n
}
tvIndex := 0
tr.syncToSrc(&tvIndex, true, 0)
tr.Update()
return tr
}
// setSyncNode sets the sync source node that we are viewing,
// and syncs the view of its tree. It is called routinely
// via SyncToSrc during tree updating.
// It uses tree Config mechanism to perform minimal updates to
// remain in sync.
func (tr *Tree) setSyncNode(sn tree.Node, tvIndex *int, init bool, depth int) {
if tr.SyncNode != sn {
tr.SyncNode = sn
}
tr.syncToSrc(tvIndex, init, depth)
}
// Resync resynchronizes the [Tree] relative to the [Tree.SyncNode]
// underlying nodes and triggers an update.
func (tr *Tree) Resync() {
tvIndex := tr.viewIndex
tr.syncToSrc(&tvIndex, false, 0)
tr.Update()
}
// syncToSrc updates the view tree to match the sync tree, using
// ConfigChildren to maximally preserve existing tree elements.
// init means we are doing initial build, and depth tracks depth
// (only during init).
func (tr *Tree) syncToSrc(tvIndex *int, init bool, depth int) {
sn := tr.SyncNode
// root must keep the same name for continuity with surrounding context
if tr.This != tr.Root {
nm := "tv_" + sn.AsTree().Name
tr.SetName(nm)
}
tr.viewIndex = *tvIndex
*tvIndex++
if init && depth >= tr.Root.AsCoreTree().OpenDepth {
tr.SetClosed(true)
}
skids := sn.AsTree().Children
p := make(tree.TypePlan, 0, len(skids))
typ := tr.NodeType()
for _, skid := range skids {
p.Add(typ, "tv_"+skid.AsTree().Name)
}
tree.Update(tr, p)
idx := 0
for _, skid := range sn.AsTree().Children {
if len(tr.Children) <= idx {
break
}
vk := AsTree(tr.Children[idx])
vk.setSyncNode(skid, tvIndex, init, depth+1)
idx++
}
if !sn.AsTree().HasChildren() {
tr.SetClosed(true)
}
}
// Label returns the display label for this node,
// satisfying the [labels.Labeler] interface.
func (tr *Tree) Label() string {
if tr.SyncNode != nil {
// TODO: make this an option?
if lbl, has := labels.ToLabeler(tr.SyncNode); has {
return lbl
}
return tr.SyncNode.AsTree().Name
}
if tr.Text != "" {
return tr.Text
}
return tr.Name
}
// selectedSyncNodes returns a slice of the currently selected
// sync source nodes in the entire tree
func (tr *Tree) selectedSyncNodes() []tree.Node {
var res []tree.Node
sl := tr.GetSelectedNodes()
for _, v := range sl {
res = append(res, v.AsCoreTree().SyncNode)
}
return res
}
// FindSyncNode returns the [Tree] node for the corresponding given
// source [tree.Node] in [Tree.SyncNode] or nil if not found.
func (tr *Tree) FindSyncNode(n tree.Node) *Tree {
var res *Tree
for cw := range tr.AllWidgets() {
tvn := AsTree(cw)
if tvn != nil {
if tvn.SyncNode == n {
res = tvn
break
}
}
}
return res
}
// InsertAfter inserts a new node in the tree
// after this node, at the same (sibling) level,
// prompting for the type of node to insert.
// If SyncNode is set, operates on Sync Tree.
func (tr *Tree) InsertAfter() { //types:add
tr.insertAt(1, "Insert after")
}
// InsertBefore inserts a new node in the tree
// before this node, at the same (sibling) level,
// prompting for the type of node to insert
// If SyncNode is set, operates on Sync Tree.
func (tr *Tree) InsertBefore() { //types:add
tr.insertAt(0, "Insert before")
}
func (tr *Tree) addTreeNodes(rel, myidx int, typ *types.Type, n int) {
var stv *Tree
for i := range n {
nn := tree.NewOfType(typ)
tr.InsertChild(nn, myidx+i)
nn.AsTree().SetName(fmt.Sprintf("new-%v-%v", typ.IDName, myidx+rel+i))
ntv := AsTree(nn)
ntv.Update()
if i == n-1 {
stv = ntv
}
}
tr.Update()
tr.Open()
tr.sendChangeEvent()
if stv != nil {
stv.SelectEvent(events.SelectOne)
}
}
func (tr *Tree) addSyncNodes(rel, myidx int, typ *types.Type, n int) {
parent := tr.SyncNode
var sn tree.Node
for i := range n {
nn := tree.NewOfType(typ)
parent.AsTree().InsertChild(nn, myidx+i)
nn.AsTree().SetName(fmt.Sprintf("new-%v-%v", typ.IDName, myidx+rel+i))
if i == n-1 {
sn = nn
}
}
tr.sendChangeEventReSync(nil)
if sn != nil {
if tvk := tr.ChildByName("tv_"+sn.AsTree().Name, 0); tvk != nil {
stv := AsTree(tvk)
stv.SelectEvent(events.SelectOne)
}
}
}
// newNodeType returns the [Tree.NewNodeType] of the root, or nil.
func (tr *Tree) newNodeType() *types.Type {
if tr.Root == nil {
return nil
}
return tr.Root.AsCoreTree().NewNodeType
}
// newItemsData contains the data necessary to make a certain
// number of items of a certain type, which can be used with a
// [Form] in new item dialogs.
type newItemsData struct {
// Number is the number of elements to create
Number int
// Type is the type of elements to create
Type *types.Type
}
// insertAt inserts a new node in the tree
// at given relative offset from this node,
// at the same (sibling) level,
// prompting for the type of node to insert
// If SyncNode is set, operates on Sync Tree.
func (tr *Tree) insertAt(rel int, actNm string) {
if tr.IsRoot(actNm) {
return
}
myidx := tr.IndexInParent()
if myidx < 0 {
return
}
myidx += rel
parent := AsTree(tr.Parent)
if typ := tr.newNodeType(); typ != nil {
if tr.SyncNode != nil {
parent.addSyncNodes(rel, myidx, typ, 1)
} else {
parent.addTreeNodes(rel, myidx, typ, 1)
}
return
}
var typ *types.Type
if tr.SyncNode == nil {
typ = types.TypeByValue(tr.This)
} else {
typ = types.TypeByValue(tr.SyncNode)
}
d := NewBody(actNm)
NewText(d).SetType(TextSupporting).SetText("Number and type of items to insert:")
nd := &newItemsData{Number: 1, Type: typ}
NewForm(d).SetStruct(nd)
d.AddBottomBar(func(bar *Frame) {
d.AddCancel(bar)
d.AddOK(bar).OnClick(func(e events.Event) {
if tr.SyncNode != nil {
parent.addSyncNodes(rel, myidx, nd.Type, nd.Number)
} else {
parent.addTreeNodes(rel, myidx, nd.Type, nd.Number)
}
})
})
d.RunDialog(tr)
}
// AddChildNode adds a new child node to this one in the tree,
// prompting the user for the type of node to add
// If SyncNode is set, operates on Sync Tree.
func (tr *Tree) AddChildNode() { //types:add
if typ := tr.newNodeType(); typ != nil {
if tr.SyncNode != nil {
tr.addSyncNodes(0, 0, typ, 1)
} else {
tr.addTreeNodes(0, 0, typ, 1)
}
return
}
ttl := "Add child"
var typ *types.Type
if tr.SyncNode == nil {
typ = types.TypeByValue(tr.This)
} else {
typ = types.TypeByValue(tr.SyncNode)
}
d := NewBody(ttl)
NewText(d).SetType(TextSupporting).SetText("Number and type of items to insert:")
nd := &newItemsData{Number: 1, Type: typ}
NewForm(d).SetStruct(nd)
d.AddBottomBar(func(bar *Frame) {
d.AddCancel(bar)
d.AddOK(bar).OnClick(func(e events.Event) {
if tr.SyncNode != nil {
tr.addSyncNodes(0, 0, nd.Type, nd.Number)
} else {
tr.addTreeNodes(0, 0, nd.Type, nd.Number)
}
})
})
d.RunDialog(tr)
}
// DeleteNode deletes the tree node or sync node corresponding
// to this view node in the sync tree.
// If SyncNode is set, operates on Sync Tree.
func (tr *Tree) DeleteNode() { //types:add
if tr.IsRoot("Delete") {
return
}
tr.Close()
if tr.moveDown(events.SelectOne) == nil {
tr.moveUp(events.SelectOne)
}
if tr.SyncNode != nil {
tr.SyncNode.AsTree().Delete()
tr.sendChangeEventReSync(nil)
} else {
parent := AsTree(tr.Parent)
tr.Delete()
parent.Update()
parent.sendChangeEvent()
}
}
// deleteSync deletes selected items.
func (tr *Tree) deleteSync() {
sels := tr.selectedSyncNodes()
tr.UnselectAll()
for _, sn := range sels {
sn.AsTree().Delete()
}
tr.sendChangeEventReSync(nil)
}
// Duplicate duplicates this node, and inserts the duplicate after this node
// (as a new sibling). If SyncNode is set, operates on Sync Tree.
func (tr *Tree) Duplicate() { //types:add
ttl := "Duplicate"
if tr.IsRoot(ttl) {
return
}
if tr.Parent == nil {
return
}
if tr.SyncNode != nil {
tr.duplicateSync()
return
}
parent := AsTree(tr.Parent)
myidx := tr.IndexInParent()
if myidx < 0 {
return
}
nm := fmt.Sprintf("%v_Copy", tr.Name)
tr.Unselect()
nwkid := tr.Clone()
nwkid.AsTree().SetName(nm)
tree.SetUniqueNameIfDuplicate(parent, nwkid)
ntv := AsTree(nwkid)
parent.InsertChild(nwkid, myidx+1)
ntv.Update()
parent.Update()
parent.sendChangeEvent()
// ntv.SelectEvent(events.SelectOne)
}
func (tr *Tree) duplicateSync() {
sn := tr.SyncNode
tvparent := AsTree(tr.Parent)
parent := tvparent.SyncNode
if parent == nil {
log.Printf("Tree %v nil SyncNode in: %v\n", tr, tvparent.Path())
return
}
myidx := sn.AsTree().IndexInParent()
if myidx < 0 {
return
}
nm := fmt.Sprintf("%v_Copy", sn.AsTree().Name)
nwkid := sn.AsTree().Clone()
nwkid.AsTree().SetName(nm)
tree.SetUniqueNameIfDuplicate(parent, nwkid)
parent.AsTree().InsertChild(nwkid, myidx+1)
tvparent.sendChangeEventReSync(nil)
if tvk := tvparent.ChildByName("tv_"+nm, 0); tvk != nil {
stv := AsTree(tvk)
stv.SelectEvent(events.SelectOne)
}
}
// EditNode pulls up a [Form] dialog for the node.
// If SyncNode is set, operates on Sync Tree.
func (tr *Tree) EditNode() { //types:add
if tr.SyncNode != nil {
tynm := tr.SyncNode.AsTree().NodeType().Name
d := NewBody(tynm)
NewForm(d).SetStruct(tr.SyncNode).SetReadOnly(tr.IsReadOnly())
d.RunWindowDialog(tr)
} else {
tynm := tr.NodeType().Name
d := NewBody(tynm)
NewForm(d).SetStruct(tr.This).SetReadOnly(tr.IsReadOnly())
d.RunWindowDialog(tr)
}
}
// inspectNode pulls up a new Inspector window on the node.
// If SyncNode is set, operates on Sync Tree.
func (tr *Tree) inspectNode() { //types:add
if tr.SyncNode != nil {
InspectorWindow(tr.SyncNode)
} else {
InspectorWindow(tr)
}
}
// mimeDataSync adds mimedata for this node: a text/plain of the Path,
// and an application/json of the sync node.
func (tr *Tree) mimeDataSync(md *mimedata.Mimes) {
sroot := tr.Root.AsCoreTree().SyncNode
src := tr.SyncNode
*md = append(*md, mimedata.NewTextData(src.AsTree().PathFrom(sroot)))
var buf bytes.Buffer
err := jsonx.Write(src, &buf)
if err == nil {
*md = append(*md, &mimedata.Data{Type: fileinfo.DataJSON, Data: buf.Bytes()})
} else {
ErrorSnackbar(tr, err, "Error encoding node")
}
}
// syncNodesFromMimeData creates a slice of tree node(s)
// from given mime data and also a corresponding slice
// of original paths.
func (tr *Tree) syncNodesFromMimeData(md mimedata.Mimes) ([]tree.Node, []string) {
ni := len(md) / 2
sl := make([]tree.Node, 0, ni)
pl := make([]string, 0, ni)
for _, d := range md {
switch d.Type {
case fileinfo.DataJSON:
nn, err := tree.UnmarshalRootJSON(d.Data)
if err == nil {
sl = append(sl, nn)
} else {
ErrorSnackbar(tr, err, "Error loading node")
}
case fileinfo.TextPlain: // paths
pl = append(pl, string(d.Data))
}
}
return sl, pl
}
// pasteAssignSync assigns mime data (only the first one!) to this node
func (tr *Tree) pasteAssignSync(md mimedata.Mimes) {
sl, _ := tr.syncNodesFromMimeData(md)
if len(sl) == 0 {
return
}
tr.SyncNode.AsTree().CopyFrom(sl[0])
tr.NeedsLayout()
tr.sendChangeEvent()
}
// pasteAtSync inserts object(s) from mime data at rel position to this node.
// An object with the name of another one gets a unique name, except
// for one moved within its parent (see [namePasted]).
func (tr *Tree) pasteAtSync(md mimedata.Mimes, mod events.DropMods, rel int, _ string) {
sn := tr.SyncNode
sl, pl := tr.nodesFromMimeData(md)
tvparent := AsTree(tr.Parent)
parent := sn.AsTree().Parent
myidx := sn.AsTree().IndexInParent()
if myidx < 0 {
return
}
myidx += rel
sroot := tr.Root.AsCoreTree().SyncNode
pt := parent.AsTree()
sz := len(sl)
var seln tree.Node
for i, ns := range sl {
namePasted(parent, ns, sroot, mod, pl[i])
pt.InsertChild(ns, myidx+i)
if i == sz-1 {
seln = ns
}
}
tvparent.pasteChanged(mod)
if seln != nil {
if tvk := tvparent.ChildByName("tv_"+seln.AsTree().Name, myidx); tvk != nil {
stv := AsTree(tvk)
stv.SelectEvent(events.SelectOne)
}
}
}
// pasteChildrenSync inserts object(s) from mime data at
// end of children of this node
func (tr *Tree) pasteChildrenSync(md mimedata.Mimes, mod events.DropMods) {
sl, pl := tr.nodesFromMimeData(md)
spar := tr.SyncNode
sroot := tr.Root.AsCoreTree().SyncNode
for i, ns := range sl {
namePasted(spar, ns, sroot, mod, pl[i])
spar.AsTree().AddChild(ns)
}
tr.pasteChanged(mod)
}
// cutSync copies to system.Clipboard and deletes selected items.
func (tr *Tree) cutSync() {
tr.Copy()
sels := tr.selectedSyncNodes()
tr.UnselectAll()
for _, sn := range sels {
sn.AsTree().Delete()
}
tr.sendChangeEventReSync(nil)
}
// dropDeleteSourceSync handles delete source event for DropMove case, for Sync
func (tr *Tree) dropDeleteSourceSync(de *events.DragDrop) {
md := de.Data.(mimedata.Mimes)
sroot := tr.Root.AsCoreTree().SyncNode
for _, d := range md {
if d.Type != fileinfo.TextPlain { // link
continue
}
path := string(d.Data)
sn := sroot.AsTree().FindPath(path)
if sn != nil {
sn.AsTree().Delete()
}
sn = sroot.AsTree().FindPath(path + treeTempMovedTag)
if sn != nil {
psplt := strings.Split(path, "/")
orgnm := psplt[len(psplt)-1]
sn.AsTree().SetName(orgnm) // the resync renders it
}
}
tr.sendChangeEventReSync(nil)
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"encoding/json"
"image"
"log/slog"
"maps"
"reflect"
"slices"
"strconv"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/fileinfo"
"cogentcore.org/core/base/fileinfo/mimedata"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/colors"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/keymap"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/tree"
)
// TreeTable represents a tree of structs as a table, where the fields are
// the columns and the items are the rows, as in a [Table]. The first column
// shows the tree: the items are indented under their parents, with branches
// that open and close, as in a [Tree]. It is a full-featured editor of the
// tree, with multiple selection, cut-and-paste, and drag-and-drop, which
// insert items before, after, or as the children of other items.
//
// The items are a pointer to a slice of pointers to structs, set with
// [TreeTable.SetItems]. The children of an item are in its field named
// Children, or with a `treetable:"children"` tag, which is a slice of
// pointers to the same struct type, or a []any of them, as needed for
// struct types made with [reflect.StructOf], which cannot refer to
// themselves. If a bool field has a `treetable:"closed"` tag, it records
// whether the item is closed, so that this is saved with the items.
type TreeTable struct {
Table
// Items is the pointer to the slice of the top-level items.
Items any `set:"-"`
// ShowItem, if set, returns whether to show the given item, a pointer
// to a struct, with its children, as for filtering the items.
ShowItem func(item any) bool `json:"-" xml:"-"`
// MatchItem, if set, returns whether the given item, a pointer to a
// struct, matches a search, in which case only the items that match
// are shown, with their children, and with the items that they are
// in, which are open, whether they are closed or not.
MatchItem func(item any) bool `json:"-" xml:"-"`
// FitWidth is whether the tree column has the width that the other
// columns leave in the width of the table, so that the table fits in
// it, without scrolling, as on a small screen, with the values of the
// tree column fitting in it, instead of a width set in ColumnWidths.
FitWidth bool
// HideGroupValues is whether the items with children, which are groups
// of items, such as categories, show only the tree, and not the values
// of their other fields.
HideGroupValues bool
// ReadOnlyDrag is whether the rows of a read-only tree table can be
// dragged, for the app to handle where they are dropped, as for
// moving them in its own data: the tree table itself does not change.
ReadOnlyDrag bool
// itemsSet is the Items for which the item type and rows were set.
itemsSet any
// itemType is the struct type of the items.
itemType reflect.Type
// childrenIndex is the index of the children field of the items,
// or nil if they have none.
childrenIndex []int
// closedIndex is the index of the closed field of the items,
// or nil if they have none, in which case closed records it.
closedIndex []int
// closed has the closed items, if they have no closed field.
closed map[any]bool
// rows are the visible items, in order.
rows []treeTableRow
// draggedItems are the items last copied for dragging,
// which are deleted when they are moved.
draggedItems []reflect.Value
}
// treeTableRow is a visible item of a [TreeTable].
type treeTableRow struct {
// item is the pointer to the item.
item reflect.Value
// parent is the pointer to the parent item, or invalid for a top-level item.
parent reflect.Value
// depth is the number of ancestors of the item.
depth int
}
func (tt *TreeTable) WidgetValue() any { return &tt.Items }
func (tt *TreeTable) Init() {
tt.Table.Init()
tt.closed = map[any]bool{}
tt.ContextMenus = nil // replaces those of the flat lists
tt.AddContextMenu(tt.contextMenu)
// these run before those of the flat lists, which they replace
tt.OnFinal(events.KeyChord, tt.keyInput)
tt.On(events.Drop, tt.dragDrop)
tt.Makers.Normal[0] = func(p *tree.Plan) {
if tt.Items != tt.itemsSet {
tt.setItems()
}
if tt.itemType == nil {
return
}
tt.sortItems()
tt.updateRows()
if tt.InitSelectedIndex >= 0 {
tt.SelectedIndex = tt.InitSelectedIndex
tt.InitSelectedIndex = -1
tt.ScrollToIndex(tt.SelectedIndex)
}
tt.UpdateStartIndex()
tt.makeHeader(p)
tt.MakeGrid(p, func(p *tree.Plan) {
for i := range tt.VisibleRows {
tt.MakeRow(p, i)
}
})
}
}
// SetItems sets the items to the given pointer to a slice of pointers
// to structs, which are the top-level items. If they have the same type as
// the current items, as for new values of them, such as after an undo, the
// view stays the same: the scroll position, the selected rows, and the
// widgets of the rows, with the focus.
func (tt *TreeTable) SetItems(items any) *TreeTable {
if items == tt.itemsSet && items != nil {
tt.MakeIter = 0
return tt
}
tt.Items = items
tt.setItems()
return tt
}
// setItems sets the item type and rows for the Items.
func (tt *TreeTable) setItems() {
if tt.sameItemType() {
tt.itemsSet = tt.Items
// the selection is by index, as the items are new
selected, current := maps.Clone(tt.SelectedIndexes), tt.SelectedIndex
tt.rows = nil
tt.closed = map[any]bool{}
tt.updateRows()
for idx := range selected {
if tt.validIndex(idx) {
tt.SelectedIndexes[idx] = struct{}{}
}
}
tt.SelectedIndex = min(current, len(tt.rows)-1)
return
}
sort := tt.SortFieldName() // kept by name, for the new fields
tt.itemsSet = tt.Items
tt.itemType = nil
tt.rows = nil
tt.closed = map[any]bool{}
if reflectx.IsNil(reflect.ValueOf(tt.Items)) {
tt.Slice = nil
return
}
typ := reflect.TypeOf(tt.Items)
if typ.Kind() != reflect.Pointer || typ.Elem().Kind() != reflect.Slice || typ.Elem().Elem().Kind() != reflect.Pointer || typ.Elem().Elem().Elem().Kind() != reflect.Struct {
slog.Error("TreeTable requires a pointer to a slice of pointers to structs", "type", typ)
return
}
tt.setItemType(typ.Elem().Elem().Elem())
// the Table shows the rows, a slice of pointers to the visible items
rows := reflect.New(typ.Elem())
tt.Slice = rows.Interface()
tt.sliceUnderlying = rows.Elem()
tt.elementValue = reflect.New(tt.itemType).Elem()
tt.cacheVisibleFields()
tt.SetSortFieldName(sort) // before any update in SetSliceBase, which can set it
tt.updateRows()
tt.SetSliceBase()
}
// sameItemType returns whether the Items have the same type as those
// for which the item type and rows were set.
func (tt *TreeTable) sameItemType() bool {
if tt.itemType == nil || reflectx.IsNil(reflect.ValueOf(tt.Items)) {
return false
}
typ := reflect.TypeOf(tt.Items)
return typ.Kind() == reflect.Pointer && typ.Elem() == tt.sliceUnderlying.Type()
}
// setItemType sets the type of the items and their tree fields.
func (tt *TreeTable) setItemType(typ reflect.Type) {
tt.itemType = typ
tt.childrenIndex, tt.closedIndex = nil, nil
children, ok := treeTableField(typ, "children")
if !ok {
children, ok = typ.FieldByName("Children")
}
if ok {
if ct := children.Type; ct.Kind() == reflect.Slice && (ct.Elem() == reflect.PointerTo(typ) || ct.Elem() == reflect.TypeFor[any]()) {
tt.childrenIndex = children.Index
} else {
slog.Error("TreeTable: the children field must be a slice of pointers to the item type, or a []any", "type", typ, "field", children.Name)
}
}
if closed, ok := treeTableField(typ, "closed"); ok && closed.Type.Kind() == reflect.Bool {
tt.closedIndex = closed.Index
}
}
// treeTableField returns the field of the given struct type
// with the given treetable tag.
func treeTableField(typ reflect.Type, tag string) (reflect.StructField, bool) {
for f := range typ.Fields() {
if f.Tag.Get("treetable") == tag {
return f, true
}
}
return reflect.StructField{}, false
}
// cacheVisibleFields caches the visible struct fields,
// which do not include the tree fields.
func (tt *TreeTable) cacheVisibleFields() {
tt.Table.cacheVisibleFields()
tt.visibleFields = slices.DeleteFunc(tt.visibleFields, func(f reflect.StructField) bool {
return slices.Equal(f.Index, tt.childrenIndex) || slices.Equal(f.Index, tt.closedIndex)
})
tt.numVisibleFields = len(tt.visibleFields)
tt.headerWidths = make([]int, tt.numVisibleFields)
tt.colMaxWidths = make([]int, tt.numVisibleFields)
}
//////// Items
// itemsValue returns the slice of the top-level items.
func (tt *TreeTable) itemsValue() reflect.Value {
return reflect.ValueOf(tt.Items).Elem()
}
// children returns the slice of the children of the given item.
func (tt *TreeTable) children(item reflect.Value) reflect.Value {
return item.Elem().FieldByIndex(tt.childrenIndex)
}
// numChildren returns the number of children of the given item.
func (tt *TreeTable) numChildren(item reflect.Value) int {
if tt.childrenIndex == nil {
return 0
}
return tt.children(item).Len()
}
// newItem returns a new item, with the values of its default tags.
func (tt *TreeTable) newItem() reflect.Value {
item := reflect.New(tt.itemType)
errors.Log(reflectx.SetFromDefaultTags(item.Interface()))
return item
}
// walkItems calls the given function on each item in the given slice,
// with its parent and depth, going into its children if it returns true.
func (tt *TreeTable) walkItems(sl, parent reflect.Value, depth int, fun func(item, parent reflect.Value, depth int) bool) {
for i := range sl.Len() {
item := itemAt(sl, i)
if !isItem(item) {
continue
}
if fun(item, parent, depth) && tt.childrenIndex != nil {
tt.walkItems(tt.children(item), item, depth+1, fun)
}
}
}
// itemAt returns the pointer to the item at the given index
// in the given slice of items, which can be a []any. It is a copy,
// which stays the same when the slice changes.
func itemAt(sl reflect.Value, i int) reflect.Value {
item := sl.Index(i)
if item.Kind() == reflect.Interface {
return item.Elem()
}
return reflect.ValueOf(item.Interface())
}
// isItem returns whether the given value from [itemAt] is an item.
func isItem(item reflect.Value) bool {
return item.IsValid() && item.Kind() == reflect.Pointer && !item.IsNil()
}
// indexOfItem returns the index of the given item in the given slice, or -1.
func indexOfItem(sl, item reflect.Value) int {
for i := range sl.Len() {
if it := itemAt(sl, i); isItem(it) && it.UnsafePointer() == item.UnsafePointer() {
return i
}
}
return -1
}
// insertItem inserts the given item into the given slice at the given index.
func insertItem(sl reflect.Value, i int, item reflect.Value) {
n := sl.Len()
ns := reflect.Append(sl, reflect.Zero(sl.Type().Elem()))
reflect.Copy(ns.Slice(i+1, n+1), ns.Slice(i, n))
ns.Index(i).Set(item)
sl.Set(ns)
}
// deleteItem deletes the item at the given index from the given slice.
func deleteItem(sl reflect.Value, i int) {
n := sl.Len()
reflect.Copy(sl.Slice(i, n-1), sl.Slice(i+1, n))
sl.Index(n - 1).SetZero()
sl.Set(sl.Slice(0, n-1))
}
// removeItem removes the given item from the given slice
// or the children of its items, returning whether it was found.
func (tt *TreeTable) removeItem(sl, item reflect.Value) bool {
if k := indexOfItem(sl, item); k >= 0 {
deleteItem(sl, k)
return true
}
if tt.childrenIndex == nil {
return false
}
for i := range sl.Len() {
if c := itemAt(sl, i); isItem(c) && tt.removeItem(tt.children(c), item) {
return true
}
}
return false
}
// sortItems sorts the items and the children of each item by the
// sort column, if there is one.
func (tt *TreeTable) sortItems() {
if tt.sortIndex < 0 || tt.sortIndex >= len(tt.visibleFields) {
return
}
tt.sortSiblings(tt.itemsValue(), tt.visibleFields[tt.sortIndex].Index)
}
// sortSiblings sorts the items in the given slice and their children
// by the field with the given index.
func (tt *TreeTable) sortSiblings(sl reflect.Value, field []int) {
n := sl.Len()
items := reflect.MakeSlice(reflect.SliceOf(reflect.PointerTo(tt.itemType)), 0, n)
for i := range n {
item := itemAt(sl, i)
if !isItem(item) {
return // nothing to sort by
}
items = reflect.Append(items, item)
}
reflectx.StructSliceSort(items.Interface(), field, reflectx.SortOrder(!tt.sortDescending))
for i := range n {
item := items.Index(i)
sl.Index(i).Set(item)
if tt.childrenIndex != nil {
tt.sortSiblings(tt.children(item), field)
}
}
}
//////// Rows
// updateRows updates the rows of the visible items,
// keeping the selection of the same items.
func (tt *TreeTable) updateRows() {
selected := map[any]bool{}
for i := range tt.SelectedIndexes {
if i < len(tt.rows) {
selected[tt.rows[i].item.Interface()] = true
}
}
var current any
if tt.validIndex(tt.SelectedIndex) {
current = tt.rows[tt.SelectedIndex].item.Interface()
}
tt.rows = tt.rows[:0]
if tt.MatchItem != nil {
tt.matchRows(tt.itemsValue(), reflect.Value{}, 0, false)
} else {
tt.walkItems(tt.itemsValue(), reflect.Value{}, 0, func(item, parent reflect.Value, depth int) bool {
if tt.ShowItem != nil && !tt.ShowItem(item.Interface()) {
return false
}
tt.rows = append(tt.rows, treeTableRow{item: item, parent: parent, depth: depth})
return !tt.itemClosed(item)
})
}
rs := reflect.MakeSlice(tt.sliceUnderlying.Type(), len(tt.rows), len(tt.rows))
for i, r := range tt.rows {
rs.Index(i).Set(r.item)
}
tt.sliceUnderlying.Set(rs)
tt.UpdateSliceSize()
tt.ResetSelectedIndexes()
for i, r := range tt.rows {
item := r.item.Interface()
if selected[item] {
tt.SelectedIndexes[i] = struct{}{}
}
if item == current {
tt.SelectedIndex = i
}
}
tt.SelectedIndex = min(tt.SelectedIndex, len(tt.rows)-1)
}
// matchRows adds the rows of the given items and their children that are
// shown for [TreeTable.MatchItem]: those that match, with all of their
// children, which are all shown if in is true, as they are in an item that
// matches, and the items that they are in. It returns whether it added any.
func (tt *TreeTable) matchRows(sl, parent reflect.Value, depth int, in bool) bool {
added := false
for i := range sl.Len() {
item := itemAt(sl, i)
if !isItem(item) || (tt.ShowItem != nil && !tt.ShowItem(item.Interface())) {
continue
}
n := len(tt.rows)
tt.rows = append(tt.rows, treeTableRow{item: item, parent: parent, depth: depth})
match := in || tt.MatchItem(item.Interface())
children := tt.childrenIndex != nil && tt.matchRows(tt.children(item), item, depth+1, match)
if !match && !children {
tt.rows = tt.rows[:n]
continue
}
added = true
}
return added
}
// validIndex returns whether the given row index is that of a visible item.
func (tt *TreeTable) validIndex(idx int) bool {
return idx >= 0 && idx < len(tt.rows)
}
// rowOf returns the row index of the given item, or -1 if it is not visible.
func (tt *TreeTable) rowOf(item reflect.Value) int {
return slices.IndexFunc(tt.rows, func(r treeTableRow) bool {
return r.item.UnsafePointer() == item.UnsafePointer()
})
}
// rowDepth returns the depth of the item at the given widget row index.
func (tt *TreeTable) rowDepth(i int) int {
si, _, invis := tt.SliceIndex(i)
if invis || !tt.validIndex(si) {
return 0
}
return tt.rows[si].depth
}
// siblingsOf returns the slice with the item at the given row index,
// and its index there.
func (tt *TreeTable) siblingsOf(idx int) (reflect.Value, int) {
r := tt.rows[idx]
sl := tt.itemsValue()
if r.parent.IsValid() {
sl = tt.children(r.parent)
}
return sl, indexOfItem(sl, r.item)
}
// edited updates the rows after the items are edited, selects
// the given item, and sends a change event.
func (tt *TreeTable) edited(item reflect.Value) {
tt.sortItems() // as the update does, so that the item is in its row
tt.updateRows()
idx := tt.rowOf(item)
if idx >= 0 {
tt.SelectIndexEvent(idx, events.SelectOne)
}
tt.UpdateChange()
// once shown, and after the rest of the handling of the event, as of
// the click on a button for a new item, which focuses the button
tt.Defer(func() {
if idx := tt.rowOf(item); idx >= 0 {
tt.IndexGrabFocus(idx)
}
})
}
// moved updates the rows after the given item is moved, or pasted, as
// [TreeTable.edited] does, except on mobile, where it only selects the
// item: focusing the text field of its cell, as for a new item to type
// into, would show the virtual keyboard.
func (tt *TreeTable) moved(item reflect.Value) {
if !TheApp.SystemPlatform().IsMobile() {
tt.edited(item)
return
}
tt.sortItems()
tt.updateRows()
if idx := tt.rowOf(item); idx >= 0 {
tt.selectIndexQuiet(idx)
tt.ScrollToIndexNoUpdate(idx)
}
tt.UpdateChange()
}
// valueChanged sorts the items again after the value of a cell in the
// given row is changed by the user, if they are sorted (as by a check box
// for done items that go to the end), and if its item moves, selects it,
// without moving the focus, which stays on its cell if it had it.
func (tt *TreeTable) valueChanged(row int) {
idx := tt.StartIndex + row
if tt.sortIndex < 0 || !tt.validIndex(idx) {
return
}
item := tt.rows[idx].item
fidx, pos, foc := tt.focusedCell()
ed := saveEdit(foc) // (completed, as it changed)
tt.sortItems()
tt.updateRows()
nidx := tt.rowOf(item)
if nidx < 0 || nidx == idx {
return
}
tt.selectIndexQuiet(nidx) // (not moving the focus, as to a text field)
tt.ScrollToIndexNoUpdate(nidx)
tt.Update()
if foc != nil && fidx == idx {
tt.keepFocusedItem(nidx, pos, ed, foc, true)
}
}
//////// Open and close
// IsClosed returns whether the item at the given row index is closed,
// with its children not shown. The items are all open while they are
// searched, with [TreeTable.MatchItem].
func (tt *TreeTable) IsClosed(idx int) bool {
return tt.MatchItem == nil && tt.validIndex(idx) && tt.itemClosed(tt.rows[idx].item)
}
// itemClosed returns whether the given item is closed.
func (tt *TreeTable) itemClosed(item reflect.Value) bool {
if tt.closedIndex != nil {
return item.Elem().FieldByIndex(tt.closedIndex).Bool()
}
return tt.closed[item.Interface()]
}
// setItemClosed sets whether the given item is closed.
func (tt *TreeTable) setItemClosed(item reflect.Value, closed bool) {
if tt.closedIndex != nil {
item.Elem().FieldByIndex(tt.closedIndex).SetBool(closed)
return
}
if closed {
tt.closed[item.Interface()] = true
} else {
delete(tt.closed, item.Interface())
}
}
// Open opens the item at the given row index, showing its children.
func (tt *TreeTable) Open(idx int) {
tt.setClosed(idx, false)
}
// Close closes the item at the given row index, hiding its children.
func (tt *TreeTable) Close(idx int) {
tt.setClosed(idx, true)
}
// ToggleClose opens the item at the given row index if it is closed,
// and otherwise closes it.
func (tt *TreeTable) ToggleClose(idx int) {
tt.setClosed(idx, !tt.IsClosed(idx))
}
// setClosed sets whether the item at the given row index is closed,
// if it has children, and the items are not searched, while which
// they are all open (see [TreeTable.MatchItem]).
func (tt *TreeTable) setClosed(idx int, closed bool) {
if tt.MatchItem != nil || !tt.validIndex(idx) || tt.numChildren(tt.rows[idx].item) == 0 || tt.IsClosed(idx) == closed {
return
}
tt.setItemClosed(tt.rows[idx].item, closed)
tt.closedChanged()
}
// OpenAll opens all of the items.
func (tt *TreeTable) OpenAll() { //types:add
tt.setAllClosed(false)
}
// CloseAll closes all of the items.
func (tt *TreeTable) CloseAll() { //types:add
tt.setAllClosed(true)
}
// setAllClosed sets whether all of the items with children are closed.
func (tt *TreeTable) setAllClosed(closed bool) {
tt.walkItems(tt.itemsValue(), reflect.Value{}, 0, func(item, parent reflect.Value, depth int) bool {
if tt.numChildren(item) > 0 {
tt.setItemClosed(item, closed)
}
return true
})
tt.closedChanged()
}
// closedChanged updates after items are opened or closed,
// which is a change of the items if they have a closed field.
func (tt *TreeTable) closedChanged() {
tt.updateRows()
if tt.closedIndex != nil {
tt.UpdateChange()
} else {
tt.Update()
}
}
//////// Editing
// NewAt inserts a new item after the item in the row before the given
// row index, as its sibling, or before the first item for 0, or at the
// end of the top-level items for -1.
func (tt *TreeTable) NewAt(idx int) {
switch {
case idx < 0 || len(tt.rows) == 0:
tt.insertItemAt(-1, 0, tt.newItem())
case idx == 0:
tt.InsertBefore(0)
default:
tt.InsertAfter(min(idx, len(tt.rows)) - 1)
}
}
// InsertBefore inserts a new item before the item at the given row index,
// as its sibling.
func (tt *TreeTable) InsertBefore(idx int) {
tt.insertNew(idx, 0)
}
// InsertAfter inserts a new item after the item at the given row index,
// as its sibling.
func (tt *TreeTable) InsertAfter(idx int) {
tt.insertNew(idx, 1)
}
// NewItem returns a new item, a pointer to a struct with the default
// values of its fields, for [TreeTable.InsertItemAfter].
func (tt *TreeTable) NewItem() any {
return tt.newItem().Interface()
}
// InsertItemAfter inserts the given item, as made by [TreeTable.NewItem],
// after the item at the given row index, as its sibling, or at the end of
// the top-level items if there is no item at the index.
func (tt *TreeTable) InsertItemAfter(idx int, item any) {
tt.insertItemAt(idx, 1, reflect.ValueOf(item))
}
// insertNew inserts a new item at the given offset from the item at
// the given row index among its siblings.
func (tt *TreeTable) insertNew(idx, offset int) {
tt.insertItemAt(idx, offset, tt.newItem())
}
// insertItemAt inserts the given item at the given offset from the item
// at the given row index among its siblings, or at the end of the
// top-level items if there is no item at the index.
func (tt *TreeTable) insertItemAt(idx, offset int, item reflect.Value) {
sl, k := tt.itemsValue(), -1
if tt.validIndex(idx) {
sl, k = tt.siblingsOf(idx)
k += offset
}
if k < 0 {
k = sl.Len()
}
insertItem(sl, k, item)
tt.edited(item)
}
// AddChild adds a new item at the end of the children of the item at
// the given row index, and opens it.
func (tt *TreeTable) AddChild(idx int) {
if !tt.validIndex(idx) || tt.childrenIndex == nil {
return
}
parent := tt.rows[idx].item
item := tt.newItem()
ch := tt.children(parent)
insertItem(ch, ch.Len(), item)
tt.setItemClosed(parent, false)
tt.edited(item)
}
// DeleteAt deletes the item at the given row index, with its children.
func (tt *TreeTable) DeleteAt(idx int) {
if !tt.validIndex(idx) {
return
}
sl, k := tt.siblingsOf(idx)
deleteItem(sl, k)
tt.updateRows()
tt.UpdateChange()
}
// DeleteSelected deletes the selected items, with their children.
func (tt *TreeTable) DeleteSelected() {
for _, idx := range tt.SelectedIndexesList(reflectx.Descending) { // last first, so the others stay
tt.DeleteAt(idx)
}
}
// Indent moves the item at the given row index into the item before it
// among its siblings, as its last child.
func (tt *TreeTable) Indent(idx int) {
if !tt.validIndex(idx) || tt.childrenIndex == nil {
return
}
sl, k := tt.siblingsOf(idx)
if k <= 0 {
return
}
item := tt.rows[idx].item
parent := itemAt(sl, k-1)
deleteItem(sl, k)
ch := tt.children(parent)
insertItem(ch, ch.Len(), item)
tt.setItemClosed(parent, false)
tt.moved(item)
}
// Outdent moves the item at the given row index out of its parent,
// to after its parent among the siblings of the parent.
func (tt *TreeTable) Outdent(idx int) {
if !tt.validIndex(idx) || !tt.rows[idx].parent.IsValid() {
return
}
r := tt.rows[idx]
sl, k := tt.siblingsOf(idx)
psl, pk := tt.siblingsOf(tt.rowOf(r.parent))
deleteItem(sl, k)
insertItem(psl, pk+1, r.item)
tt.moved(r.item)
}
// MoveItemUp moves the item at the given row index before
// the previous one among its siblings.
func (tt *TreeTable) MoveItemUp(idx int) {
tt.moveItem(idx, -1)
}
// MoveItemDown moves the item at the given row index after
// the next one among its siblings.
func (tt *TreeTable) MoveItemDown(idx int) {
tt.moveItem(idx, 1)
}
// moveItem moves the item at the given row index by the given number
// of places among its siblings.
func (tt *TreeTable) moveItem(idx, delta int) {
if !tt.validIndex(idx) {
return
}
sl, k := tt.siblingsOf(idx)
if j := k + delta; j >= 0 && j < sl.Len() {
reflect.Swapper(sl.Interface())(k, j)
tt.moved(tt.rows[idx].item)
}
}
// targets returns the items to move for the given row index: the selected
// items (without those within another one), in order, if it is one of them,
// or else its item.
func (tt *TreeTable) targets(idx int) []reflect.Value {
if !tt.validIndex(idx) {
return nil
}
if tt.indexIsSelected(idx) && len(tt.SelectedIndexes) > 1 {
return tt.selectedTopItems()
}
return []reflect.Value{tt.rows[idx].item}
}
// movedItems updates after moving the given items, which are selected
// (the first as the current one), and sends a change event.
func (tt *TreeTable) movedItems(items []reflect.Value) {
tt.sortItems()
tt.updateRows()
tt.ResetSelectedIndexes()
tt.SelectedIndex = -1
for ri := len(items) - 1; ri >= 0; ri-- {
item := items[ri]
if idx := tt.rowOf(item); idx >= 0 {
tt.SelectIndex(idx)
tt.SelectedIndex = idx
}
}
if tt.SelectedIndex >= 0 {
tt.ScrollToIndexNoUpdate(tt.SelectedIndex)
}
tt.UpdateChange()
}
// IndentSelected indents the items to move for the given row index (see
// [TreeTable.targets]): each moves into the item before it among its
// siblings, so that consecutive items go into the same one.
func (tt *TreeTable) IndentSelected(idx int) {
items := tt.targets(idx)
if len(items) <= 1 {
tt.Indent(idx)
return
}
if tt.childrenIndex == nil {
return
}
for _, item := range items {
r := tt.rowOf(item)
sl, k := tt.siblingsOf(r)
if k <= 0 {
continue
}
parent := itemAt(sl, k-1)
deleteItem(sl, k)
ch := tt.children(parent)
insertItem(ch, ch.Len(), item)
tt.setItemClosed(parent, false)
tt.updateRows()
}
tt.movedItems(items)
}
// OutdentSelected outdents the items to move for the given row index (see
// [TreeTable.targets]): each moves out of its parent, after it, keeping
// their order.
func (tt *TreeTable) OutdentSelected(idx int) {
items := tt.targets(idx)
if len(items) <= 1 {
tt.Outdent(idx)
return
}
for ri := len(items) - 1; ri >= 0; ri-- { // (the last first, for their order)
item := items[ri]
r := tt.rowOf(item)
if r < 0 || !tt.rows[r].parent.IsValid() {
continue
}
sl, k := tt.siblingsOf(r)
psl, pk := tt.siblingsOf(tt.rowOf(tt.rows[r].parent))
deleteItem(sl, k)
insertItem(psl, pk+1, item)
tt.updateRows()
}
tt.movedItems(items)
}
// MoveSelectedUp moves the items to move for the given row index (see
// [TreeTable.targets]) before the previous one among their siblings,
// unless it is one of them that cannot move.
func (tt *TreeTable) MoveSelectedUp(idx int) {
tt.moveSelected(idx, -1)
}
// MoveSelectedDown moves the items to move for the given row index (see
// [TreeTable.targets]) after the next one among their siblings,
// unless it is one of them that cannot move.
func (tt *TreeTable) MoveSelectedDown(idx int) {
tt.moveSelected(idx, 1)
}
// moveSelected moves the items to move for the given row index by one
// place among their siblings, in the given direction.
func (tt *TreeTable) moveSelected(idx, delta int) {
items := tt.targets(idx)
if len(items) <= 1 {
tt.moveItem(idx, delta)
return
}
moving := map[any]bool{}
for _, item := range items {
moving[item.Interface()] = true
}
order := items
if delta > 0 { // (the last first, so that they do not pass each other)
order = slices.Clone(items)
slices.Reverse(order)
}
for _, item := range order {
sl, k := tt.siblingsOf(tt.rowOf(item))
j := k + delta
if j < 0 || j >= sl.Len() || moving[itemAt(sl, j).Interface()] {
continue // (blocked, as are the next ones, by it)
}
reflect.Swapper(sl.Interface())(k, j)
tt.updateRows()
}
tt.movedItems(items)
}
// Duplicate inserts copies of the selected items after the last of them.
func (tt *TreeTable) Duplicate() {
ixs := tt.SelectedIndexesList(reflectx.Descending)
if len(ixs) == 0 {
return
}
tt.pasteAfter(tt.CopySelectToMime(), ixs[0])
}
//////// Copy and paste
// selectedTopItems returns the selected items, in order, without those
// within another selected item, with which they are copied.
func (tt *TreeTable) selectedTopItems() []reflect.Value {
var items []reflect.Value
for _, idx := range tt.SelectedIndexesList(reflectx.Ascending) {
if tt.validIndex(idx) && !tt.hasSelectedAncestor(idx) {
items = append(items, tt.rows[idx].item)
}
}
return items
}
// hasSelectedAncestor returns whether an ancestor of the item at
// the given row index is selected.
func (tt *TreeTable) hasSelectedAncestor(idx int) bool {
for p := tt.rows[idx].parent; p.IsValid(); {
pi := tt.rowOf(p)
if pi < 0 {
return false
}
if tt.indexIsSelected(pi) {
return true
}
p = tt.rows[pi].parent
}
return false
}
// CopySelectToMime returns the selected items, with their children,
// as mime data. It records them as the dragged items.
func (tt *TreeTable) CopySelectToMime() mimedata.Mimes {
items := tt.selectedTopItems()
tt.draggedItems = items
md := make(mimedata.Mimes, 0, len(items))
for _, item := range items {
b, err := json.MarshalIndent(item.Interface(), "", " ")
if errors.Log(err) == nil {
md = append(md, &mimedata.Data{Type: fileinfo.DataJSON, Data: b})
}
}
return md
}
// itemsFromMime returns new items from the given mime data.
func (tt *TreeTable) itemsFromMime(md mimedata.Mimes) []reflect.Value {
var items []reflect.Value
for _, d := range md {
if d.Type != fileinfo.DataJSON {
continue
}
item, err := tt.itemFromJSON(d.Data)
if errors.Log(err) == nil {
items = append(items, item)
}
}
return items
}
// itemFromJSON returns a new item decoded from the given JSON, with its
// children, which are decoded as items when they are a []any.
func (tt *TreeTable) itemFromJSON(b []byte) (reflect.Value, error) {
item := reflect.New(tt.itemType)
if err := json.Unmarshal(b, item.Interface()); err != nil {
return reflect.Value{}, err
}
if tt.childrenIndex == nil {
return item, nil
}
ch := tt.children(item)
if ch.Type().Elem().Kind() != reflect.Interface {
return item, nil
}
// the children were decoded as maps
items := reflect.MakeSlice(ch.Type(), 0, ch.Len())
for i := range ch.Len() {
cb, err := json.Marshal(ch.Index(i).Interface())
if err != nil {
return reflect.Value{}, err
}
c, err := tt.itemFromJSON(cb)
if err != nil {
return reflect.Value{}, err
}
items = reflect.Append(items, c)
}
ch.Set(items)
return item, nil
}
// pasteItems inserts the items from the given mime data into the given
// slice at the given index, and selects the first of them.
func (tt *TreeTable) pasteItems(md mimedata.Mimes, sl reflect.Value, k int) {
items := tt.itemsFromMime(md)
for i, item := range items {
insertItem(sl, k+i, item)
}
if len(items) > 0 {
tt.moved(items[0])
}
}
// PasteAtIndex inserts the items from the given mime data before the
// item at the given row index, as its siblings, or at the end of the
// top-level items if it is out of range.
func (tt *TreeTable) PasteAtIndex(md mimedata.Mimes, idx int) {
if !tt.validIndex(idx) {
sl := tt.itemsValue()
tt.pasteItems(md, sl, sl.Len())
return
}
sl, k := tt.siblingsOf(idx)
tt.pasteItems(md, sl, k)
}
// pasteAfter inserts the items from the given mime data after the
// item at the given row index, as its siblings.
func (tt *TreeTable) pasteAfter(md mimedata.Mimes, idx int) {
if !tt.validIndex(idx) {
tt.PasteAtIndex(md, -1)
return
}
sl, k := tt.siblingsOf(idx)
tt.pasteItems(md, sl, k+1)
}
// pasteChildren inserts the items from the given mime data at the end
// of the children of the item at the given row index, and opens it.
func (tt *TreeTable) pasteChildren(md mimedata.Mimes, idx int) {
if !tt.validIndex(idx) || tt.childrenIndex == nil {
return
}
parent := tt.rows[idx].item
tt.setItemClosed(parent, false)
ch := tt.children(parent)
tt.pasteItems(md, ch, ch.Len())
}
// PasteAssign assigns the first item from the given mime data,
// with its children, to the item at the given row index.
func (tt *TreeTable) PasteAssign(md mimedata.Mimes, idx int) {
items := tt.itemsFromMime(md)
if len(items) == 0 || !tt.validIndex(idx) {
return
}
item := tt.rows[idx].item
item.Elem().Set(items[0].Elem())
tt.moved(item)
}
// makeTreePasteMenu makes the menu of the ways to paste the given mime
// data relative to the item at the given row index.
func (tt *TreeTable) makeTreePasteMenu(m *Scene, md mimedata.Mimes, idx int, mod events.DropMods, fun func()) {
paste := func(text string, f func()) {
NewButton(m).SetText(text).OnClick(func(e events.Event) {
f()
if fun != nil {
fun()
}
})
}
if !tt.validIndex(idx) {
paste("Insert at end", func() { tt.PasteAtIndex(md, -1) })
NewButton(m).SetText("Cancel")
return
}
if mod == events.DropCopy {
paste("Assign to", func() { tt.PasteAssign(md, idx) })
}
paste("Insert before", func() { tt.PasteAtIndex(md, idx) })
paste("Insert after", func() { tt.pasteAfter(md, idx) })
if tt.childrenIndex != nil {
paste("Insert as child", func() { tt.pasteChildren(md, idx) })
}
NewButton(m).SetText("Cancel")
}
//////// Drag and drop
// dragStart starts dragging the selected items from the given tree cell,
// selecting the item under the mouse if it is not selected.
func (tt *TreeTable) dragStart(e events.Event, cell Widget) {
row, _, ok := tt.ListGrid.indexFromPixel(e.StartPos()) // where the mouse went down
if !ok || !tt.validIndex(tt.StartIndex+row) {
return
}
if !tt.indexIsSelected(tt.StartIndex + row) {
tt.updateSelectRow(row, events.SelectOne)
}
md := tt.CopySelectToMime()
if len(md) == 0 {
return
}
tt.Scene.Events.DragStart(cell, md, e)
e.SetHandled()
}
// dragDrop handles a drop onto the tree table, with a menu of the ways
// to paste the dropped items relative to the item under the mouse.
func (tt *TreeTable) dragDrop(e events.Event) {
if tt.IsReadOnly() { // for the app to handle (see ReadOnlyDrag)
return
}
e.SetHandled()
de := e.(*events.DragDrop)
md, ok := de.Data.(mimedata.Mimes)
if !ok || tt.itemType == nil {
return
}
idx := -1
if row, _, ok := tt.ListGrid.indexFromPixel(de.Pos()); ok && tt.validIndex(tt.StartIndex+row) {
idx = tt.StartIndex + row
}
if idx >= 0 && de.DropMod == events.DropMove && tt.isOwnDrag(de) && tt.withinDragged(tt.rows[idx].item) {
return // cannot move items into themselves
}
mf := func(m *Scene, pos image.Point) {
tt.Scene.Events.DragMenuAddModText(m, de.DropMod)
tt.makeTreePasteMenu(m, md, idx, de.DropMod, func() {
tt.dropFinalize(de)
})
}
NewMenu(mf, tt.This.(Widget), de.WindowPos()).Run()
}
// isOwnDrag returns whether the given drop is of items dragged from
// this tree table.
func (tt *TreeTable) isOwnDrag(de *events.DragDrop) bool {
src, ok := de.Source.(tree.Node)
for ok && src != nil {
if src == tt.This {
return true
}
src = src.AsTree().Parent
}
return false
}
// withinDragged returns whether the given item is one of the dragged
// items or one of their descendants.
func (tt *TreeTable) withinDragged(item reflect.Value) bool {
for item.IsValid() {
if slices.ContainsFunc(tt.draggedItems, func(d reflect.Value) bool {
return d.UnsafePointer() == item.UnsafePointer()
}) {
return true
}
idx := tt.rowOf(item)
if idx < 0 {
return false
}
item = tt.rows[idx].parent
}
return false
}
// dropDeleteItems deletes the dragged items after they are moved.
func (tt *TreeTable) dropDeleteItems() {
if tt.IsReadOnly() { // the app handles it (see ReadOnlyDrag)
tt.draggedItems = nil
return
}
for _, item := range tt.draggedItems {
tt.removeItem(tt.itemsValue(), item)
}
tt.draggedItems = nil
tt.updateRows()
tt.UpdateChange()
}
//////// Widgets
// MakeRow adds the widgets for the given widget row index to the given
// plan, with the tree cell for the first field.
func (tt *TreeTable) MakeRow(p *tree.Plan, i int) {
si, _, invis := tt.SliceIndex(i)
if tt.ShowIndexes {
tt.MakeGridIndex(p, i, si, strconv.Itoa(i), invis)
}
if tt.numVisibleFields == 0 {
return
}
tt.makeTreeCell(p, i)
for fli := 1; fli < tt.numVisibleFields; fli++ {
tt.makeFieldValue(p, i, fli)
}
tt.makeRowButton(p, i)
}
// makeTreeCell adds the tree cell for the given widget row index to the
// given plan: the indented branch and the value of the first field.
func (tt *TreeTable) makeTreeCell(p *tree.Plan, i int) {
tree.AddAt(p, "tree-"+strconv.Itoa(i), func(w *treeTableCell) {
w.tt = tt
w.SetProperty(ListRowProperty, i)
w.SetProperty(ListColProperty, 0)
w.Styler(func(s *styles.Style) {
s.SetAbilities(!tt.IsReadOnly() || tt.ReadOnlyDrag, abilities.Draggable)
s.Direction = styles.Row
s.Align.Items = styles.Center
s.Gap.X.Em(0.1)
s.Padding.Zero()
// the indentation is padding, which the spacing setting scales,
// but it is not for spacing, so it stays the same, as in a Tree
w.depth = tt.rowDepth(i)
s.Padding.Left.Em(ConstantSpacing(float32(w.depth)))
s.Grow.Set(1, 0)
if tt.treeWidthSet() { // see ListGrid.fixColumnWidths
s.Overflow.X = styles.OverflowHidden
}
})
w.On(events.DragStart, func(e events.Event) {
tt.dragStart(e, w)
})
w.On(events.DropDeleteSource, func(e events.Event) {
tt.dropDeleteItems()
})
w.On(events.ContextMenu, tt.rowContextMenu(i))
w.OnClick(func(e events.Event) {
// a click on the cell outside of its value (as past the end of
// a short text) selects its row, as a click on the value does
// (see ListBase.MakeValue), with Shift or Command too
mode := e.SelectMode()
if tt.SelectMode && mode == events.SelectOne {
mode = events.ExtendOne
}
e.SetHandled()
if mode == events.ExtendOne || mode == events.ExtendContinuous {
tt.clickSelectRow(i, mode)
return
}
tt.focusReadOnly()
tt.updateSelectRow(i, mode)
tt.lastClick = i + tt.StartIndex
})
w.Updater(func() {
_, _, invis := tt.SliceIndex(i)
w.SetState(invis, states.Invisible)
if tt.rowDepth(i) != w.depth { // as when scrolled, which only updates
w.Style()
tt.NeedsLayout()
}
})
w.Maker(func(p *tree.Plan) {
tt.makeBranch(p, i)
tt.makeFieldValue(p, i, 0)
})
})
}
// treeWidthSet returns whether the width of the tree column is set, in
// ColumnWidths, or by [TreeTable.FitWidth].
func (tt *TreeTable) treeWidthSet() bool {
return tt.FitWidth || tt.columnWidth(0) > 0
}
// ColumnWidthDots returns the width of the column at the given index in
// dots, or 0 if it is automatic: for the tree column with
// [TreeTable.FitWidth], it is the width that the other columns leave in
// the width of the table, which is known in the layout after the sizes of
// the other columns are, without the scrollbar. The width of each other
// column is that of its widest cell, as in the grid: those of the rows of
// groups can be narrower, with [TreeTable.HideGroupValues].
func (tt *TreeTable) ColumnWidthDots(col int) float32 {
if col != 0 || !tt.FitWidth {
return tt.Table.ColumnWidthDots(col)
}
lg := tt.ListGrid
nw, idxOff := tt.RowWidgetNs()
if lg == nil || lg.NumChildren() < nw {
return 0
}
widths := make([]float32, nw)
for i, c := range lg.Children {
widths[i%nw] = max(widths[i%nw], AsWidget(c).Geom.Size.Actual.Total.X)
}
width := lg.Geom.Size.Alloc.Content.X - lg.Styles.ScrollbarWidth.Dots
for i, w := range widths {
if i != idxOff {
width -= w
}
}
width -= float32(nw-1) * lg.Styles.Gap.X.Dots
return max(width, 4*tt.Styles.UnitContext.Dots(units.UnitEm))
}
// StyleValue styles the value widgets, where the value of the tree cell
// fills it, if the width of the first column is set.
func (tt *TreeTable) StyleValue(w Widget, s *styles.Style, row, col int) {
if col != 0 && tt.FitWidth {
// the other columns have the widths of their values, or of the text
// of their headers, without room for their sort indicators, and the
// tree column has the width that they leave
s.Grow.X = 0
if col < len(tt.headerWidths) {
hv := units.Ch(float32(tt.headerWidths[col]) + 1.5) // with the compact padding
s.Min.X.Value = max(s.Min.X.Value, hv.Convert(s.Min.X.Unit, &s.UnitContext).Value)
}
s.SetTextWrap(false)
return
}
if col != 0 || !tt.treeWidthSet() {
tt.Table.StyleValue(w, s, row, col)
return
}
s.Min.X.Em(2)
s.Max.X.Zero() // such as the 40ch of a TextField
s.Grow.X = 1
s.SetTextWrap(false)
}
// treeTableCell is the tree cell of a [TreeTable], with the indented branch
// and the value of the first field, which fits in the width of the cell when
// the width of the column is set, so that a text field scrolls its text,
// instead of having the width of all of it.
type treeTableCell struct {
Frame
// tt is the tree table of the cell.
tt *TreeTable
// depth is the depth of the item for which the cell was styled, which
// its indentation is for: when the cell shows an item of another depth,
// as when the table is scrolled, it is styled again.
depth int
}
func (tc *treeTableCell) SizeDown(iter int) bool {
if tc.fitValue() {
tc.sizeFromChildrenFit(iter, SizeDownPass) // the layout of the new size
}
return tc.Frame.SizeDown(iter)
}
func (tc *treeTableCell) SizeFinal() {
tc.fitValue() // for the final width of the cell
tc.Frame.SizeFinal()
}
// fitValue fits the value in the width of the cell after the branch,
// if the width of the column is set, returning whether it is.
func (tc *treeTableCell) fitValue() bool {
if tc.tt == nil || !tc.tt.treeWidthSet() || tc.NumChildren() < 2 {
return false
}
other := float32(0)
for _, c := range tc.Children[:tc.NumChildren()-1] {
other += AsWidget(c).Geom.Size.Actual.Total.X + tc.Styles.Gap.X.Dots
}
vs := &AsWidget(tc.Child(tc.NumChildren() - 1)).Geom.Size
width := max(tc.Geom.Size.Alloc.Content.X-other, 0)
space := vs.Actual.Total.X - vs.Actual.Content.X
vs.Actual.Total.X, vs.Actual.Content.X = width, max(width-space, 0)
vs.Max.X = vs.Actual.Content.X // as a TextField sizes itself to its text, up to its max
return true
}
// makeBranch adds the branch for the given widget row index to the given
// plan, which opens and closes the item.
func (tt *TreeTable) makeBranch(p *tree.Plan, i int) {
tree.AddAt(p, "branch", func(w *Switch) {
w.SetType(SwitchCheckbox)
w.SetIconOn(icons.KeyboardArrowDown).SetIconOff(icons.KeyboardArrowRight).SetIconIndeterminate(icons.Blank)
w.Styler(func(s *styles.Style) {
s.SetAbilities(!tt.IsReadOnly(), abilities.Focusable)
s.Color = colors.Scheme.Primary.Base
s.Padding.Zero()
s.Align.Self = styles.Center
if w.StateIs(states.Indeterminate) {
// a leaf, with nothing to open
s.Abilities = 0
s.StateLayer = 0
}
})
w.OnClick(func(e events.Event) {
e.SetHandled() // the item, not the switch, has the state
si, _, _ := tt.SliceIndex(i)
tt.ToggleClose(si)
})
w.On(events.ContextMenu, tt.rowContextMenu(i))
w.On(events.KeyChord, func(e events.Event) {
si, _, _ := tt.SliceIndex(i)
switch keymap.Of(e.KeyChord()) {
case keymap.MoveRight:
tt.Open(si)
e.SetHandled()
case keymap.MoveLeft:
tt.Close(si)
e.SetHandled()
}
})
w.Updater(func() {
si, _, invis := tt.SliceIndex(i)
leaf := invis || !tt.validIndex(si) || tt.numChildren(tt.rows[si].item) == 0
wasLeaf := w.StateIs(states.Indeterminate)
w.SetState(leaf, states.Indeterminate)
w.SetState(!leaf && !tt.IsClosed(si), states.Checked)
if leaf != wasLeaf { // as when scrolled, which only updates: its abilities
w.Style()
w.NeedsRender()
}
})
})
}
// rowContextMenu returns the handler of context menu events on the tree
// cell for the given widget row index, and its branch, which selects the
// row and shows the context menu of the tree table, as for the values.
func (tt *TreeTable) rowContextMenu(i int) func(e events.Event) {
return func(e events.Event) {
if si, _, invis := tt.SliceIndex(i); !invis && !tt.indexIsSelected(si) {
tt.updateSelectRow(i, events.SelectOne)
}
tt.HandleEvent(e)
}
}
// hideValue returns whether to hide the value of the given visible
// field at the given slice index, for [TreeTable.HideGroupValues].
func (tt *TreeTable) hideValue(si, fli int) bool {
return tt.HideGroupValues && fli > 0 && tt.validIndex(si) && tt.numChildren(tt.rows[si].item) > 0
}
// RowGrabFocus grabs the focus for the first focusable value widget in the
// given row, returning it, or nil if there is none.
func (tt *TreeTable) RowGrabFocus(row int) *WidgetBase {
if !tt.IsRowInBounds(row) || tt.InFocusGrab || tt.ListGrid == nil {
return nil
}
nWidgPerRow, idxOff := tt.RowWidgetNs()
ridx := nWidgPerRow * row
lg := tt.ListGrid
if ridx+nWidgPerRow > lg.NumChildren() {
return nil
}
value := func(fli int) *WidgetBase {
w := lg.Child(ridx + idxOff + fli).(Widget).AsWidget()
if fli == 0 { // the tree cell, with the value last
if !w.HasChildren() {
return nil
}
w = w.Child(w.NumChildren() - 1).(Widget).AsWidget()
}
return w
}
for fli := range tt.numVisibleFields {
if w := value(fli); w != nil && (w.StateIs(states.Focused) || w.ContainsFocus()) {
return w
}
}
tt.InFocusGrab = true
defer func() { tt.InFocusGrab = false }()
for fli := range tt.numVisibleFields {
if w := value(fli); w != nil && w.CanFocus() {
w.SetFocus()
return w
}
}
return nil
}
// keyInput handles the keys for the tree: opening and closing items
// when read-only, and inserting, duplicating, and deleting items. The
// keys of a text field, such as [keymap.Delete], come here after its
// edits are accepted with [keymap.Accept].
func (tt *TreeTable) keyInput(e events.Event) {
if !tt.IsReadOnly() {
tt.selectFocusedRow()
}
idx := tt.SelectedIndex
kf := keymap.Of(e.KeyChord())
if len(tt.rows) == 0 && !tt.IsReadOnly() {
switch kf {
case keymap.Insert, keymap.InsertAfter, keymap.InsertChild:
tt.NewAt(-1) // the first item
e.SetHandled()
}
return
}
if !tt.validIndex(idx) {
return
}
if tt.IsReadOnly() {
switch kf {
case keymap.MoveRight:
tt.Open(idx)
e.SetHandled()
case keymap.MoveLeft:
if !tt.IsClosed(idx) && tt.numChildren(tt.rows[idx].item) > 0 {
tt.Close(idx)
} else if pi := tt.rowOf(tt.rows[idx].parent); tt.rows[idx].parent.IsValid() && pi >= 0 {
tt.ScrollToIndex(pi)
tt.updateSelectIndex(pi, true, events.SelectOne)
}
e.SetHandled()
}
return
}
switch kf {
case keymap.Delete: // after the edits of a text field are accepted
tt.DeleteSelected()
tt.IndexGrabFocus(tt.SelectedIndex) // if the focus was in the last row
case keymap.Insert:
tt.InsertBefore(idx)
case keymap.InsertAfter:
tt.InsertAfter(idx)
case keymap.InsertChild:
tt.AddChild(idx)
case keymap.Duplicate:
tt.Duplicate()
default:
return
}
tt.SelectMode = false
e.SetHandled()
}
func (tt *TreeTable) contextMenu(m *Scene, pos image.Point) {
idx := tt.SelectedIndex
view := NewButton(m)
view.OnClick(func(e events.Event) {
tt.editIndex(idx)
})
if tt.IsReadOnly() {
view.SetText("View").SetIcon(icons.Visibility)
NewButton(m).SetText("Copy").SetIcon(icons.Copy).SetKey(keymap.Copy).OnClick(func(e events.Event) {
tt.copyIndexes(true)
})
} else {
view.SetText("Edit").SetIcon(icons.Edit)
NewSeparator(m)
NewButton(m).SetText("Insert before").SetIcon(icons.Add).SetKey(keymap.Insert).OnClick(func(e events.Event) {
tt.InsertBefore(idx)
})
NewButton(m).SetText("Insert after").SetIcon(icons.Add).SetKey(keymap.InsertAfter).OnClick(func(e events.Event) {
tt.InsertAfter(idx)
})
NewButton(m).SetText("Add child").SetIcon(icons.SubdirectoryArrowRight).SetKey(keymap.InsertChild).OnClick(func(e events.Event) {
tt.AddChild(idx)
})
NewButton(m).SetText("Delete").SetIcon(icons.Delete).SetKey(keymap.Delete).OnClick(func(e events.Event) {
tt.DeleteSelected()
})
NewSeparator(m)
NewButton(m).SetText("Indent").SetIcon(icons.FormatIndentIncrease).OnClick(func(e events.Event) {
tt.IndentSelected(idx)
})
NewButton(m).SetText("Outdent").SetIcon(icons.FormatIndentDecrease).OnClick(func(e events.Event) {
tt.OutdentSelected(idx)
})
NewButton(m).SetText("Move up").SetIcon(icons.ArrowUpward).OnClick(func(e events.Event) {
tt.MoveSelectedUp(idx)
})
NewButton(m).SetText("Move down").SetIcon(icons.ArrowDownward).OnClick(func(e events.Event) {
tt.MoveSelectedDown(idx)
})
NewSeparator(m)
NewButton(m).SetText("Copy").SetIcon(icons.Copy).SetKey(keymap.Copy).OnClick(func(e events.Event) {
tt.copyIndexes(true)
})
NewButton(m).SetText("Cut").SetIcon(icons.Cut).SetKey(keymap.Cut).OnClick(func(e events.Event) {
tt.cutIndexes()
})
NewButton(m).SetText("Paste").SetIcon(icons.Paste).SetKey(keymap.Paste).OnClick(func(e events.Event) {
tt.pasteIndex(idx)
})
NewButton(m).SetText("Duplicate").SetIcon(icons.Copy).SetKey(keymap.Duplicate).OnClick(func(e events.Event) {
tt.Duplicate()
})
NewSeparator(m)
tt.selectModeButton(m)
}
NewSeparator(m)
NewButton(m).SetText("Open all").SetIcon(icons.UnfoldMore).OnClick(func(e events.Event) {
tt.OpenAll()
})
NewButton(m).SetText("Close all").SetIcon(icons.UnfoldLess).OnClick(func(e events.Event) {
tt.CloseAll()
})
NewButton(m).SetText("Toggle indexes").SetIcon(icons.Numbers).OnClick(func(e events.Event) {
tt.ShowIndexes = !tt.ShowIndexes
tt.Update()
})
}
// selectModeButton adds the button that starts or ends the select mode
// ([ListBase.SelectMode]), in which taps on the rows select them, as for
// selecting several items to move on mobile, to the given menu or toolbar.
func (tt *TreeTable) selectModeButton(m Widget) *Button {
bt := NewButton(m)
bt.Updater(func() {
if tt.SelectMode {
bt.SetText("Done selecting").SetIcon(icons.Check).
SetTooltip("End selecting items by tapping (clicking) them")
} else {
bt.SetText("Select items").SetIcon(icons.Checklist).
SetTooltip("Select several items by tapping (clicking) them, as to move them together; on desktop, Shift and Command (Control) clicks do this too")
}
})
bt.OnClick(func(e events.Event) {
tt.SetSelectMode(!tt.SelectMode)
})
return bt
}
// SetSelectMode starts or ends the select mode ([ListBase.SelectMode]),
// in which taps (clicks) on the rows select them, instead of editing them,
// as for selecting several items on mobile. Starting it ends any editing.
func (tt *TreeTable) SetSelectMode(on bool) *TreeTable {
tt.SelectMode = on
if on {
if em := tt.Events(); em != nil && tt.ContainsFocus() {
em.focusClear() // (completing an edit, and hiding the keyboard)
}
}
tt.Restyle()
return tt
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"fmt"
"cogentcore.org/core/tree"
)
// UpdateWidget updates the widget by running [WidgetBase.Updaters] in
// sequential descending (reverse) order after calling [WidgetBase.ValueUpdate].
// This includes applying the result of [WidgetBase.Make].
//
// UpdateWidget differs from [WidgetBase.Update] in that it only updates the widget
// itself and not any of its children. Also, it does not restyle the widget or trigger
// a new layout pass, while [WidgetBase.Update] does. End-user code should typically
// call [WidgetBase.Update], not UpdateWidget.
func (wb *WidgetBase) UpdateWidget() *WidgetBase {
if wb.ValueUpdate != nil {
wb.ValueUpdate()
}
wb.RunUpdaters()
return wb
}
// UpdateTree calls [WidgetBase.UpdateWidget] on every widget in the tree
// starting with this one and going down.
func (wb *WidgetBase) UpdateTree() {
wb.WidgetWalkDown(func(cw Widget, cwb *WidgetBase) bool {
if cwb != wb && isHiddenStackChild(cwb) {
return tree.Break
}
cwb.UpdateWidget()
return tree.Continue
})
}
// Update updates the widget and all of its children by running [WidgetBase.UpdateWidget]
// and [WidgetBase.Style] on each one, and triggering a new layout pass with
// [WidgetBase.NeedsLayout]. It is the main way that end users should trigger widget
// updates, and it is guaranteed to fully update a widget to the current state.
// For example, it should be called after making any changes to the core properties
// of a widget, such as the text of [Text], the icon of a [Button], or the slice
// of a [Table].
//
// Update differs from [WidgetBase.UpdateWidget] in that it updates the widget and all
// of its children down the tree, whereas [WidgetBase.UpdateWidget] only updates the widget
// itself. Also, Update also calls [WidgetBase.Style] and [WidgetBase.NeedsLayout],
// whereas [WidgetBase.UpdateWidget] does not. End-user code should typically call Update,
// not [WidgetBase.UpdateWidget].
//
// If you are calling this in a separate goroutine outside of the main
// configuration, rendering, and event handling structure, you need to
// call [WidgetBase.AsyncLock] and [WidgetBase.AsyncUnlock] before and
// after this, respectively.
func (wb *WidgetBase) Update() { //types:add
if DebugSettings.UpdateTrace {
fmt.Println("\tDebugSettings.UpdateTrace Update:", wb)
}
wb.WidgetWalkDown(func(cw Widget, cwb *WidgetBase) bool {
if cwb != wb && isHiddenStackChild(cwb) {
return tree.Break
}
cwb.UpdateWidget()
cw.Style()
return tree.Continue
})
wb.NeedsLayout()
}
// UpdateRender is the same as [WidgetBase.Update], except that it calls
// [WidgetBase.NeedsRender] instead of [WidgetBase.NeedsLayout].
// This should be called when the changes made to the widget do not
// require a new layout pass (if you change the size, spacing, alignment,
// or other layout properties of the widget, you need a new layout pass
// and should call [WidgetBase.Update] instead).
func (wb *WidgetBase) UpdateRender() {
wb.WidgetWalkDown(func(cw Widget, cwb *WidgetBase) bool {
if cwb != wb && isHiddenStackChild(cwb) {
return tree.Break
}
cwb.UpdateWidget()
cw.Style()
return tree.Continue
})
wb.NeedsRender()
}
// isHiddenStackChild returns whether the given widget is a child of a frame
// that only lays out its stack top ([Frame.LayoutStackTopOnly]) other than its
// stack top, such as the content of a tab that is not selected. Updates and
// styling skip it until it becomes the stack top, whose frame is then updated.
func isHiddenStackChild(cwb *WidgetBase) bool {
fr := AsFrame(cwb.Parent)
if fr == nil || !fr.LayoutStackTopOnly {
return false
}
return fr.Child(fr.StackTop) != cwb.This
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"reflect"
"strings"
"cogentcore.org/core/base/labels"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/events"
"cogentcore.org/core/events/key"
)
// Value is a widget that has an associated value representation.
// It can be bound to a value using [Bind].
type Value interface {
Widget
// WidgetValue returns the pointer to the associated value of the widget.
WidgetValue() any
}
// ValueSetter is an optional interface that [Value]s can implement
// to customize how the associated widget value is set from the given value.
type ValueSetter interface {
// SetWidgetValue sets the associated widget value from the given value.
SetWidgetValue(value any) error
}
// OnBinder is an optional interface that [Value]s can implement to
// do something when the widget is bound to the given value.
type OnBinder interface {
// OnBind is called when the widget is bound to the given value
// with the given optional struct tags.
OnBind(value any, tags reflect.StructTag)
}
// Bind binds the given value to the given [Value] such that the values of
// the two will be linked and updated appropriately after [events.Change] events
// and during [WidgetBase.UpdateWidget]. It returns the widget to enable method chaining.
// It also accepts an optional [reflect.StructTag], which is used to set properties
// of certain value widgets.
func Bind[T Value](value any, vw T, tags ...string) T {
// TODO: make tags be reflect.StructTag (yaegi did not support that)
wb := vw.AsWidget()
alreadyBound := wb.ValueUpdate != nil
wb.ValueUpdate = func() {
if vws, ok := any(vw).(ValueSetter); ok {
ErrorSnackbar(vw, vws.SetWidgetValue(value))
} else {
ErrorSnackbar(vw, reflectx.SetRobust(vw.WidgetValue(), value))
}
}
wb.ValueOnChange = func() {
ErrorSnackbar(vw, reflectx.SetRobust(value, vw.WidgetValue()))
}
if alreadyBound {
ResetWidgetValue(vw)
}
wb.ValueTitle = labels.FriendlyTypeName(reflectx.NonPointerType(reflect.TypeOf(value)))
if ob, ok := any(vw).(OnBinder); ok {
tag := reflect.StructTag("")
if len(tags) > 0 {
tag = reflect.StructTag(tags[0])
}
ob.OnBind(value, tag)
}
wb.ValueUpdate() // we update it with the initial value immediately
return vw
}
// ResetWidgetValue resets the [Value] if it was already bound to another value previously.
// We first need to reset the widget value to zero to avoid any issues with the pointer
// from the old value persisting and being updated. For example, that issue happened
// with slice and map pointers persisting in forms when a new struct was set.
// It should not be called by end-user code; it must be exported since it is referenced
// in a generic function that interpreters run from source ([Bind]).
func ResetWidgetValue(vw Value) {
rv := reflect.ValueOf(vw.WidgetValue())
if rv.IsValid() && rv.Type().Kind() == reflect.Pointer && !rv.IsNil() {
rv.Elem().SetZero()
}
}
// joinValueTitle returns a [WidgetBase.ValueTitle] string composed
// of two elements, with a • separator, handling the cases where
// either or both can be empty.
func joinValueTitle(a, b string) string {
switch {
case a == "":
return b
case b == "":
return a
default:
return a + " • " + b
}
}
const shiftNewWindow = "[Shift: new window]"
// InitValueButton configures the given [Value] to open a dialog representing
// its value in accordance with the given dialog construction function when clicked.
// It also sets the tooltip of the widget appropriately. If allowReadOnly is false,
// the dialog will not be opened if the widget is read only. It also takes an optional
// function to call after the dialog is accepted.
func InitValueButton(v Value, allowReadOnly bool, mkfun func(d *Body), after ...func()) {
wb := v.AsWidget()
// windows are never new on mobile
if !TheApp.Platform().IsMobile() {
wb.SetTooltip(shiftNewWindow)
}
wb.OnClick(func(e events.Event) {
if allowReadOnly || !wb.IsReadOnly() {
if e.HasAnyModifier(key.Shift) {
wb.setFlag(!wb.hasFlag(widgetValueNewWindow), widgetValueNewWindow)
}
openValueDialog(v, mkfun, after...)
}
})
}
// openValueDialog opens a new value dialog for the given [Value] using the
// given function for constructing the dialog and the optional given function
// to call after the dialog is accepted.
func openValueDialog(v Value, mkfun func(d *Body), after ...func()) {
opv := reflectx.UnderlyingPointer(reflect.ValueOf(v.WidgetValue()))
if !opv.IsValid() {
return
}
obj := opv.Interface()
if RecycleDialog(obj) {
return
}
wb := v.AsWidget()
d := NewBody(wb.ValueTitle)
if text := strings.ReplaceAll(wb.Tooltip, shiftNewWindow, ""); text != "" {
NewText(d).SetType(TextSupporting).SetText(text)
}
mkfun(d)
// if we don't have anything specific for ok events,
// we just register an OnClose event and skip the
// OK and Cancel buttons
if len(after) == 0 {
d.OnClose(func(e events.Event) {
wb.runInWindow(d.AsWidget(), func() { wb.UpdateChange() })
})
} else {
// otherwise, we have to make the bottom bar
d.AddBottomBar(func(bar *Frame) {
d.AddCancel(bar)
d.AddOK(bar).OnClick(func(e events.Event) {
wb.runInWindow(d.AsWidget(), func() {
after[0]()
wb.UpdateChange()
})
})
})
}
if wb.hasFlag(widgetValueNewWindow) {
d.RunWindowDialog(v)
} else {
d.RunFullDialog(v)
}
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"fmt"
"image"
"image/color"
"reflect"
"time"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/enums"
"cogentcore.org/core/events/key"
"cogentcore.org/core/icons"
"cogentcore.org/core/keymap"
"cogentcore.org/core/tree"
"cogentcore.org/core/types"
)
// Valuer is an interface that types can implement to specify the
// [Value] Widget that should be used to represent them in the GUI.
type Valuer interface {
// Widget returns the [Value] Widget that should be used to represent
// the value in the GUI. If it returns nil, then [ToValue] will
// fall back onto the next step. This function must NOT call [Bind].
Widget() Value
}
// ValueTypes is a map of functions that return a [Value]
// for a value of a certain fully package path qualified type name.
// It is used by [toValue]. If a function returns nil, it falls
// back onto the next step. You can add to this using the [AddValueType]
// helper function. These functions must NOT call [Bind].
var ValueTypes = map[string]func(value any) Value{}
// AddValueType binds the given value type to the given [Value] [tree.NodeValue]
// type, meaning that [toValue] will return a new [Value] of the given type
// when it receives values of the given value type. It uses [ValueTypes].
// This function is called with various standard types automatically.
func AddValueType[T any, W tree.NodeValue]() {
var v T
name := types.TypeNameValue(v)
ValueTypes[name] = func(value any) Value {
return any(tree.New[W]()).(Value)
}
}
// NewValue converts the given value into an appropriate [Value]
// whose associated value is bound to the given value. The given value must
// be a pointer. It uses the given optional struct tags for additional context
// and to determine styling properties via [styleFromTags]. It also adds the
// resulting [Value] to the given optional parent if it specified. The specifics
// on how it determines what type of [Value] to make are further
// documented on [toValue].
func NewValue(value any, tags reflect.StructTag, parent ...tree.Node) Value {
vw := toValue(value, tags)
if tags != "" {
styleFromTags(vw, tags)
}
Bind(value, vw, string(tags))
if len(parent) > 0 {
parent[0].AsTree().AddChild(vw)
}
return vw
}
// toValue converts the given value into an appropriate [Value],
// using the given optional struct tags for additional context.
// The given value should typically be a pointer. It does NOT call [Bind];
// see [NewValue] for a version that does. It first checks the
// [Valuer] interface, then the [ValueTypes], and finally it falls
// back on a set of default bindings. If any step results in nil,
// it falls back on the next step.
func toValue(value any, tags reflect.StructTag) Value {
if vwr, ok := value.(Valuer); ok {
if vw := vwr.Widget(); vw != nil {
return vw
}
}
rv := reflect.ValueOf(value)
if !rv.IsValid() {
return NewText()
}
uv := reflectx.Underlying(rv)
typ := uv.Type()
if vwt, ok := ValueTypes[types.TypeName(typ)]; ok {
if vw := vwt(value); vw != nil {
return vw
}
}
// Default bindings:
if _, ok := value.(enums.BitFlag); ok {
return NewSwitches()
}
if enum, ok := value.(enums.Enum); ok {
if len(enum.Values()) < 4 {
return NewSwitches()
}
return NewChooser()
}
if _, ok := value.(color.Color); ok {
return NewColorButton()
}
if _, ok := value.(tree.Node); ok {
return NewTreeButton()
}
if _, ok := value.(image.Image); ok {
return NewImageButton()
}
inline := tags.Get("display") == "inline"
noInline := tags.Get("display") == "no-inline"
kind := typ.Kind()
switch {
case kind >= reflect.Int && kind <= reflect.Float64:
if _, ok := value.(fmt.Stringer); ok {
return NewTextField()
}
return NewSpinner()
case kind == reflect.Bool:
return NewSwitch()
case kind == reflect.Struct:
num := reflectx.NumAllFields(uv)
if !noInline && (inline || num <= AppearanceSettings.InlineLengths.Struct) {
return NewForm().SetInline(true)
}
return NewFormButton()
case kind == reflect.Map:
len := uv.Len()
if !noInline && (inline || len <= AppearanceSettings.InlineLengths.Map) {
return NewKeyedList().SetInline(true)
}
return NewKeyedListButton()
case kind == reflect.Array, kind == reflect.Slice:
sz := uv.Len()
elemType := reflectx.SliceElementType(value)
if _, ok := value.([]byte); ok {
return NewTextField()
}
if _, ok := value.([]rune); ok {
return NewTextField()
}
isStruct := (reflectx.NonPointerType(elemType).Kind() == reflect.Struct)
if !noInline && (inline || (!isStruct && sz <= AppearanceSettings.InlineLengths.Slice && !tree.IsNode(elemType))) {
return NewInlineList()
}
return NewListButton()
case kind == reflect.Func:
return NewFuncButton()
}
return NewTextField() // final fallback
}
// FieldWidgeter is an interface that struct types can implement to specify the
// [Value] Widget that should be used to represent specific fields in the GUI,
// via the FieldWidget method. For [Form] and [Table] widgets.
type FieldWidgeter interface {
// FieldWidget returns the [Value] that should be used to represent
// the field with the given name in the GUI. If it returns nil, then
// the default is used based on display tags, type, etc. This function
// must NOT call [Bind].
FieldWidget(field string) Value
}
// NewFieldValue converts the given value into an appropriate [Value] widget
// whose associated value is bound to the given value. The given value must
// be a pointer. It uses the given field name and parent struct pointer for
// context, such as if the parent struct implements [FieldWidgeter]. This
// function is used in [Form] and [Table] and generally should not be called
// by end users directly.
//
// It uses the given optional struct tags for additional context
// and to determine styling properties via [styleFromTags]. It also adds the
// resulting [Value] to the given optional parent if it specified.
func NewFieldValue(field string, str any, value any, tags reflect.StructTag, parent ...tree.Node) Value {
if fw, ok := str.(FieldWidgeter); ok {
v := fw.FieldWidget(field)
if v != nil {
return v
}
}
return NewValue(value, tags, parent...)
}
func init() {
AddValueType[icons.Icon, IconButton]()
AddValueType[time.Time, TimeInput]()
AddValueType[time.Duration, DurationInput]()
AddValueType[types.Type, TypeChooser]()
AddValueType[Filename, FileButton]()
// AddValueType[FontName, FontButton]()
AddValueType[FontName, TextField]()
AddValueType[keymap.MapName, KeyMapButton]()
AddValueType[key.Chord, KeyChordButton]()
AddValueType[HighlightingName, HighlightingButton]()
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"fmt"
"image"
"reflect"
"cogentcore.org/core/base/labels"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/styles"
"cogentcore.org/core/text/fonts"
"cogentcore.org/core/text/highlighting"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/tree"
"cogentcore.org/core/types"
"golang.org/x/exp/maps"
)
// ListButton represents a slice or array value with a button that opens a [List].
type ListButton struct {
Button
Slice any
// DragMoves is whether dragging the rows of the list moves them by
// default (see [ListBase.DragMoves]), as set by the drag-moves:"+"
// struct tag.
DragMoves bool
}
func (lb *ListButton) WidgetValue() any { return &lb.Slice }
func (lb *ListButton) Init() {
lb.Button.Init()
lb.SetType(ButtonTonal).SetIcon(icons.Edit)
lb.Updater(func() {
lb.SetText(labels.FriendlySliceLabel(reflect.ValueOf(lb.Slice)))
})
InitValueButton(lb, true, func(d *Body) {
up := reflectx.Underlying(reflect.ValueOf(lb.Slice))
if up.Type().Kind() != reflect.Array && reflectx.NonPointerType(reflectx.SliceElementType(lb.Slice)).Kind() == reflect.Struct {
tb := NewTable(d).SetSlice(lb.Slice)
tb.SetValueTitle(lb.ValueTitle).SetReadOnly(lb.IsReadOnly())
tb.DragMoves = lb.DragMoves
d.AddTopBar(func(bar *Frame) {
NewToolbar(bar).Maker(tb.MakeToolbar)
})
} else {
sv := NewList(d).SetSlice(lb.Slice)
sv.SetValueTitle(lb.ValueTitle).SetReadOnly(lb.IsReadOnly())
sv.DragMoves = lb.DragMoves
d.AddTopBar(func(bar *Frame) {
NewToolbar(bar).Maker(sv.MakeToolbar)
})
}
})
}
// FormButton represents a struct value with a button that opens a [Form].
type FormButton struct {
Button
Struct any
}
func (fb *FormButton) WidgetValue() any { return &fb.Struct }
func (fb *FormButton) Init() {
fb.Button.Init()
fb.SetType(ButtonTonal).SetIcon(icons.Edit)
fb.Updater(func() {
fb.SetText(labels.FriendlyStructLabel(reflect.ValueOf(fb.Struct)))
})
InitValueButton(fb, true, func(d *Body) {
fm := NewForm(d).SetStruct(fb.Struct)
fm.OnChange(func(e events.Event) {
if up, ok := fb.Struct.(Updater); ok {
up.Update()
fm.Update()
}
})
fm.SetValueTitle(fb.ValueTitle).SetReadOnly(fb.IsReadOnly())
if tb, ok := fb.Struct.(ToolbarMaker); ok {
d.AddTopBar(func(bar *Frame) {
NewToolbar(bar).Maker(tb.MakeToolbar)
})
}
})
}
// Updater is an interface for the Update method,
// called by FormButton on changes.
type Updater interface {
Update()
}
// KeyedListButton represents a map value with a button that opens a [KeyedList].
type KeyedListButton struct {
Button
Map any
}
func (kb *KeyedListButton) WidgetValue() any { return &kb.Map }
func (kb *KeyedListButton) Init() {
kb.Button.Init()
kb.SetType(ButtonTonal).SetIcon(icons.Edit)
kb.Updater(func() {
kb.SetText(labels.FriendlyMapLabel(reflect.ValueOf(kb.Map)))
})
InitValueButton(kb, true, func(d *Body) {
kl := NewKeyedList(d).SetMap(kb.Map)
kl.SetValueTitle(kb.ValueTitle).SetReadOnly(kb.IsReadOnly())
d.AddTopBar(func(bar *Frame) {
NewToolbar(bar).Maker(kl.MakeToolbar)
})
})
}
// TreeButton represents a [tree.Node] value with a button.
type TreeButton struct {
Button
Tree tree.Node
}
func (tb *TreeButton) WidgetValue() any { return &tb.Tree }
func (tb *TreeButton) Init() {
tb.Button.Init()
tb.SetType(ButtonTonal).SetIcon(icons.Edit)
tb.Updater(func() {
path := "None"
if !reflectx.UnderlyingPointer(reflect.ValueOf(tb.Tree)).IsNil() {
path = tb.Tree.AsTree().String()
}
tb.SetText(path)
})
InitValueButton(tb, true, func(d *Body) {
if !reflectx.UnderlyingPointer(reflect.ValueOf(tb.Tree)).IsNil() {
makeInspector(d, tb.Tree)
}
})
}
func (tb *TreeButton) WidgetTooltip(pos image.Point) (string, image.Point) {
if reflectx.UnderlyingPointer(reflect.ValueOf(tb.Tree)).IsNil() {
return tb.Tooltip, tb.DefaultTooltipPos()
}
tpa := "(" + tb.Tree.AsTree().Path() + ")"
if tb.Tooltip == "" {
return tpa, tb.DefaultTooltipPos()
}
return tpa + " " + tb.Tooltip, tb.DefaultTooltipPos()
}
// TypeChooser represents a [types.Type] value with a chooser.
type TypeChooser struct {
Chooser
}
func (tc *TypeChooser) Init() {
tc.Chooser.Init()
tc.SetTypes(maps.Values(types.Types)...)
}
// IconButton represents an [icons.Icon] with a [Button] that opens
// a dialog for selecting the icon.
type IconButton struct {
Button
}
func (ib *IconButton) WidgetValue() any { return &ib.Icon }
func (ib *IconButton) Init() {
ib.Button.Init()
ib.Updater(func() {
if !ib.Icon.IsSet() {
ib.SetText("Select an icon")
} else {
ib.SetText("")
}
if ib.IsReadOnly() {
ib.SetType(ButtonText)
if !ib.Icon.IsSet() {
ib.SetText("").SetIcon(icons.Blank)
}
} else {
ib.SetType(ButtonTonal)
}
})
InitValueButton(ib, false, func(d *Body) {
d.SetTitle("Select an icon")
si := 0
used := icons.Used()
ls := NewList(d)
ls.SetSlice(&used).SetSelectedValue(ib.Icon).BindSelect(&si)
ls.OnChange(func(e events.Event) {
ib.Icon = used[si]
})
})
}
// FontName is used to specify a font family name.
// It results in a [FontButton] [Value].
type FontName = rich.FontName
// FontButton represents a [FontName] with a [Button] that opens
// a dialog for selecting the font family.
type FontButton struct {
Button
}
func (fb *FontButton) WidgetValue() any { return &fb.Text }
func (fb *FontButton) Init() {
fb.Button.Init()
fb.SetType(ButtonTonal)
fb.Updater(func() {
if fb.Text == "" {
fb.SetText("(default)")
}
})
InitValueButton(fb, false, func(d *Body) {
d.SetTitle("Select a font family")
si := 0
fi := fonts.Families(fb.Scene.TextShaper().FontList())
tb := NewTable(d)
tb.SetSlice(&fi).SetSelectedField("Family").SetSelectedValue(fb.Text).BindSelect(&si)
tb.SetTableStyler(func(w Widget, s *styles.Style, row, col int) {
if col != 1 {
return
}
s.Font.CustomFont = rich.FontName(fi[row].Family)
s.Font.Family = rich.Custom
s.Font.Size.Dp(24)
})
tb.OnChange(func(e events.Event) {
fb.Text = fi[si].Family
})
})
}
// HighlightingName is a highlighting style name.
type HighlightingName = highlighting.HighlightingName
// HighlightingButton represents a [HighlightingName] with a button.
type HighlightingButton struct {
Button
HighlightingName string
}
func (hb *HighlightingButton) WidgetValue() any { return &hb.HighlightingName }
func (hb *HighlightingButton) Init() {
hb.Button.Init()
hb.SetType(ButtonTonal).SetIcon(icons.Brush)
hb.Updater(func() {
hb.SetText(hb.HighlightingName)
})
InitValueButton(hb, false, func(d *Body) {
d.SetTitle("Select a syntax highlighting style")
si := 0
ls := NewList(d).SetSlice(&highlighting.StyleNames).SetSelectedValue(hb.HighlightingName).BindSelect(&si)
ls.OnChange(func(e events.Event) {
hb.HighlightingName = highlighting.StyleNames[si]
})
})
}
// HighlightingEditor opens an editor of highlighting styles.
func HighlightingEditor(st *highlighting.Styles) {
if RecycleMainWindow(st) {
return
}
d := NewBody("Highlighting styles").SetData(st)
NewText(d).SetType(TextSupporting).SetText("View standard to see the builtin styles, from which you can add and customize by saving ones from the standard and then loading them into a custom file to modify.")
kl := NewKeyedList(d).SetMap(st)
highlighting.StylesChanged = false
kl.OnChange(func(e events.Event) {
highlighting.StylesChanged = true
})
d.AddTopBar(func(bar *Frame) {
NewToolbar(bar).Maker(func(p *tree.Plan) {
tree.Add(p, func(w *FuncButton) {
w.SetFunc(st.OpenJSON).SetText("Open from file").SetIcon(icons.Open)
w.Args[0].SetTag(`extension:".highlighting"`)
})
tree.Add(p, func(w *FuncButton) {
w.SetFunc(st.SaveJSON).SetText("Save from file").SetIcon(icons.Save)
w.Args[0].SetTag(`extension:".highlighting"`)
})
tree.Add(p, func(w *Button) {
w.SetText("View standard").SetIcon(icons.Visibility).OnClick(func(e events.Event) {
HighlightingEditor(&highlighting.StandardStyles)
})
})
tree.Add(p, func(w *Separator) {})
kl.MakeToolbar(p)
})
})
d.RunWindow() // note: no context here so not dialog
}
// ImageButton represents an image.Image value with a button that opens a [Image].
type ImageButton struct {
Button
Image image.Image
}
func (fb *ImageButton) WidgetValue() any { return &fb.Image }
func (fb *ImageButton) Init() {
fb.Button.Init()
fb.SetType(ButtonTonal).SetIcon(icons.Edit)
fb.Updater(func() {
if fb.Image == nil {
fb.SetText("nil image")
} else {
sz := fb.Image.Bounds().Size()
fb.SetText(fmt.Sprintf("image (%d x %d)", sz.X, sz.Y))
}
})
InitValueButton(fb, true, func(d *Body) {
fm := NewImage(d).SetImage(fb.Image)
fm.SetValueTitle(fb.ValueTitle).SetReadOnly(fb.IsReadOnly())
})
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package core provides the core GUI functionality of Cogent Core.
package core
//go:generate core generate
import (
"image"
"iter"
"log/slog"
"cogentcore.org/core/base/tiered"
"cogentcore.org/core/colors"
"cogentcore.org/core/cursors"
"cogentcore.org/core/enums"
"cogentcore.org/core/events"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/system/composer"
"cogentcore.org/core/text/textpos"
"cogentcore.org/core/tree"
"golang.org/x/image/draw"
)
// Widget is the interface that all Cogent Core widgets satisfy.
// The core widget functionality is defined on [WidgetBase],
// and all higher-level widget types must embed it. This
// interface only contains the methods that higher-level
// widget types may need to override. You can call
// [Widget.AsWidget] to get the [WidgetBase] of a Widget
// and access the core widget functionality.
type Widget interface {
tree.Node
// AsWidget returns the [WidgetBase] of this Widget. Most
// core widget functionality is implemented on [WidgetBase].
AsWidget() *WidgetBase
// Style updates the style properties of the widget based on [WidgetBase.Stylers].
// To specify the style properties of a widget, use [WidgetBase.Styler].
// Widgets can implement this method if necessary to add additional styling behavior,
// such as calling [units.Value.ToDots] on a custom [units.Value] field.
Style()
// SizeUp (bottom-up) gathers Actual sizes from our Children & Parts,
// based on Styles.Min / Max sizes and actual content sizing
// (e.g., text size). Flexible elements (e.g., [Text], Flex Wrap,
// [Toolbar]) should reserve the _minimum_ size possible at this stage,
// and then Grow based on SizeDown allocation.
SizeUp()
// SizeDown (top-down, multiple iterations possible) provides top-down
// size allocations based initially on Scene available size and
// the SizeUp Actual sizes. If there is extra space available, it is
// allocated according to the Grow factors.
// Flexible elements (e.g., Flex Wrap layouts and Text with word wrap)
// update their Actual size based on available Alloc size (re-wrap),
// to fit the allocated shape vs. the initial bottom-up guess.
// However, do NOT grow the Actual size to match Alloc at this stage,
// as Actual sizes must always represent the minimums (see Position).
// Returns true if any change in Actual size occurred.
SizeDown(iter int) bool
// SizeFinal: (bottom-up) similar to SizeUp but done at the end of the
// Sizing phase: first grows widget Actual sizes based on their Grow
// factors, up to their Alloc sizes. Then gathers this updated final
// actual Size information for layouts to register their actual sizes
// prior to positioning, which requires accurate Actual vs. Alloc
// sizes to perform correct alignment calculations.
SizeFinal()
// Position uses the final sizes to set relative positions within layouts
// according to alignment settings, and Grow elements to their actual
// Alloc size per Styles settings and widget-specific behavior.
Position()
// ApplyScenePos computes scene-based absolute positions and final BBox
// bounding boxes for rendering, based on relative positions from
// Position step and parents accumulated position and scroll offset.
// This is the only step needed when scrolling (very fast).
ApplyScenePos()
// Render is the method that widgets should implement to define their
// custom rendering steps. It should not typically be called outside of
// [Widget.RenderWidget], which also does other steps applicable
// for all widgets. The base [WidgetBase.Render] implementation
// renders the standard box model.
Render()
// RenderWidget renders the widget and any parts and children that it has.
// It does not render if the widget is invisible. It calls [Widget.Render]
// for widget-specific rendering.
RenderWidget()
// WidgetTooltip returns the tooltip text that should be used for this
// widget, and the window-relative position to use for the upper-left corner
// of the tooltip. The current mouse position in scene-local coordinates
// is passed to the function; if it is {-1, -1}, that indicates that
// WidgetTooltip is being called in a Style function to determine whether
// the widget should be [abilities.LongHoverable] and [abilities.LongPressable]
// (if the return string is not "", then it will have those abilities
// so that the tooltip can be displayed).
//
// By default, WidgetTooltip just returns [WidgetBase.Tooltip]
// and [WidgetBase.DefaultTooltipPos], but widgets can override
// it to do different things. For example, buttons add their
// shortcut to the tooltip here.
WidgetTooltip(pos image.Point) (string, image.Point)
// ContextMenuPos returns the default position for popup menus;
// by default in the middle its Bounding Box, but can be adapted as
// appropriate for different widgets.
ContextMenuPos(e events.Event) image.Point
// ShowContextMenu displays the context menu of various actions
// to perform on a Widget, activated by default on the ShowContextMenu
// event, triggered by a Right mouse click.
// Returns immediately, and actions are all executed directly
// (later) via the action signals. Calls ContextMenu and
// ContextMenuPos.
ShowContextMenu(e events.Event)
// ChildBackground returns the background color (Image) for the given child Widget.
// By default, this is just our [styles.Style.ActualBackground] but it can be computed
// specifically for the child (e.g., for zebra stripes in [ListGrid]).
ChildBackground(child Widget) image.Image
// RenderSource returns the self-contained [composer.Source] for
// rendering this widget. The base widget returns nil, and the [Scene]
// widget returns the [paint.Painter] rendering results.
// Widgets that do direct rendering instead of drawing onto
// the Scene painter should return a suitable render source.
// Use [Scene.AddDirectRender] to register such widgets with the Scene.
// The given draw operation is the suggested way to Draw onto existing images.
RenderSource(op draw.Op) composer.Source
// TextRunes returns any text content associated with the widget, to be used
// for Search for example. If this is nil, then it is excluded from search.
TextRunes() []rune
// Search returns text search results for this widget, searching for
// the find string with given case sensitivity. It is up to each widget
// to define the meaning of the Region line, char values for the matches.
// The bool return value indicates whether this widget handled the search,
// thereby excluding further searching within the elements under it.
Search(find string, useCase CaseSensitive) ([]textpos.Match, bool)
// HighlightMatches does highlighting of the given matches within this widget,
// where the matches are as returned from the Search method.
// Passing a nil causes matches to be reset.
// Any existing highlighting should always be reset first regardless.
// The bool return value indicates whether this widget handled the search,
// thereby excluding further searching within the elements under it.
HighlightMatches(matches []textpos.Match) bool
// SelectMatch selects match at given index from among those returned
// from the Search method. scroll = scroll widget into view.
// reset = clear selection instead of selecting (does not scroll).
SelectMatch(matches []textpos.Match, index int, scroll SelectionScroll, reset SelectionReset)
}
// WidgetBase implements the [Widget] interface and provides the core functionality
// of a widget. You must use WidgetBase as an embedded struct in all higher-level
// widget types. It renders the standard box model, but does not layout or render
// any children; see [Frame] for that.
type WidgetBase struct {
tree.NodeBase
// Tooltip is the text for the tooltip for this widget,
// which can use HTML formatting.
Tooltip string `json:",omitempty"`
// Parts are a separate tree of sub-widgets that can be used to store
// orthogonal parts of a widget when necessary to separate them from children.
// For example, [Tree]s use parts to separate their internal parts from
// the other child tree nodes. Composite widgets like buttons should
// NOT use parts to store their components; parts should only be used when
// absolutely necessary. Use [WidgetBase.newParts] to make the parts.
Parts *Frame `copier:"-" json:"-" xml:"-" set:"-"`
// Geom has the full layout geometry for size and position of this widget.
Geom GeomState `edit:"-" copier:"-" json:"-" xml:"-" set:"-"`
// OverrideStyle, if true, indicates override the computed styles of the widget
// and allow directly editing [WidgetBase.Styles]. It is typically only set in
// the inspector.
OverrideStyle bool `copier:"-" json:"-" xml:"-" set:"-"`
// displayNone is whether the widget is [states.Invisible] because its
// [styles.Style.Display] is [styles.DisplayNone], so that it is shown
// again when its Display is no longer none (see [WidgetBase.Style]).
displayNone bool
// Styles are styling settings for this widget. They are set by
// [WidgetBase.Stylers] in [WidgetBase.Style].
Styles styles.Style `json:"-" xml:"-" set:"-"`
// Stylers is a tiered set of functions that are called in sequential
// ascending order (so the last added styler is called last and
// thus can override all other stylers) to style the element.
// These should be set using the [WidgetBase.Styler], [WidgetBase.FirstStyler],
// and [WidgetBase.FinalStyler] functions.
Stylers tiered.Tiered[[]func(s *styles.Style)] `copier:"-" json:"-" xml:"-" set:"-" edit:"-" display:"add-fields"`
// Listeners is a tiered set of event listener functions for processing events on this widget.
// They are called in sequential descending order (so the last added listener
// is called first). They should be added using the [WidgetBase.On], [WidgetBase.OnFirst],
// and [WidgetBase.OnFinal] functions, or any of the various On{EventType} helper functions.
Listeners tiered.Tiered[events.Listeners] `copier:"-" json:"-" xml:"-" set:"-" edit:"-" display:"add-fields"`
// ContextMenus is a slice of menu functions to call to construct
// the widget's context menu on an [events.ContextMenu]. The
// functions are called in reverse order such that the elements
// added in the last function are the first in the menu.
// Context menus should be added through [WidgetBase.AddContextMenu].
// Separators will be added between each context menu function.
// [Scene.ContextMenus] apply to all widgets in the scene.
ContextMenus []func(m *Scene, pos image.Point) `copier:"-" json:"-" xml:"-" set:"-" edit:"-"`
// Deferred is a slice of functions to call after the next [Scene] update/render.
// In each function event sending etc will work as expected. Use
// [WidgetBase.Defer] to add a function.
Deferred []func() `copier:"-" json:"-" xml:"-" set:"-" edit:"-"`
// raised are the out of flow widgets with a positive z-index in this
// widget, as their stacking context, that are rendered after it (see
// [WidgetBase.raised]), collected while it renders.
raised []Widget
// Scene is the overall Scene to which we belong. It is automatically
// by widgets whenever they are added to another widget parent.
Scene *Scene `copier:"-" json:"-" xml:"-" set:"-"`
// ValueUpdate is a function set by [Bind] that is called in
// [WidgetBase.UpdateWidget] to update the widget's value from the bound value.
// It should not be accessed by end users.
ValueUpdate func() `copier:"-" json:"-" xml:"-" set:"-"`
// ValueOnChange is a function set by [Bind] that is called when
// the widget receives an [events.Change] event to update the bound value
// from the widget's value. It should not be accessed by end users.
ValueOnChange func() `copier:"-" json:"-" xml:"-" set:"-"`
// ValueTitle is the title to display for a dialog for this [Value].
ValueTitle string
// flags are bit flags for [WidgetBase] state. They are only accessed
// in the event loop or with the lock of the render context, as with
// [WidgetBase.AsyncLock].
flags widgetFlags
}
// widgetFlags are bit flags for [WidgetBase] state.
type widgetFlags int32 //enums:bitflag -trim-prefix widget
const (
// widgetValueNewWindow indicates that the dialog of a [Value] should be opened
// as a new window, instead of a typical full window in the same current window.
// This is set by [InitValueButton] and handled by [openValueDialog].
// This is triggered by holding down the Shift key while clicking on a
// [Value] button. Certain values such as [FileButton] may set this to true
// in their [InitValueButton] function.
widgetValueNewWindow widgetFlags = iota
// widgetNeedsRender is whether the widget needs to be rendered on the next render iteration.
widgetNeedsRender
// widgetChildNeedsRender is whether any widget inside of the widget, such as
// a child or a scrollbar, needs to be rendered on the next render iteration,
// so that the render iteration only goes into the parts of the tree that do.
widgetChildNeedsRender
// widgetInLayer is whether the widget was rendered into the layer of its
// scene (see [sceneLayer]) by the last render of the whole scene.
widgetInLayer
// widgetHasLayer is whether a widget inside of the widget was rendered
// into the layer of its scene (see [sceneLayer]) by the last render of
// the whole scene, while the widget itself was not.
widgetHasLayer
)
// hasFlag returns whether the given flag is set.
func (wb *WidgetBase) hasFlag(f widgetFlags) bool {
// This is equivalent to [widgetFlags.HasFlag] without converting the
// flag to an [enums.BitFlag], since it is called very frequently.
return wb.flags&(1<<uint32(f)) != 0
}
// setFlag sets the given flags to the given value.
func (wb *WidgetBase) setFlag(on bool, f ...enums.BitFlag) {
wb.flags.SetFlag(on, f...)
}
// Init should be called by every [Widget] type in its custom
// Init if it has one to establish all the default styling
// and event handling that applies to all widgets.
func (wb *WidgetBase) Init() {
wb.Styler(func(s *styles.Style) {
s.MaxBorder.Style.Set(styles.BorderSolid)
s.MaxBorder.Color.Set(colors.Scheme.Primary.Base)
s.MaxBorder.Width.Set(units.Dp(1))
// if we are disabled, we do not react to any state changes,
// and instead always have the same gray colors
if s.Is(states.Disabled) {
s.Cursor = cursors.NotAllowed
s.Opacity = 0.38
return
}
// TODO(kai): what about context menus on mobile?
tt, _ := wb.This.(Widget).WidgetTooltip(image.Pt(-1, -1))
s.SetAbilities(tt != "", abilities.LongHoverable, abilities.LongPressable)
if s.Is(states.Selected) {
s.Background = colors.Scheme.Select.Container
s.Color = colors.Scheme.Select.OnContainer
}
})
wb.FinalStyler(func(s *styles.Style) {
if s.Is(states.Focused) {
s.Border.Style = s.MaxBorder.Style
s.Border.Color = s.MaxBorder.Color
s.Border.Width = s.MaxBorder.Width
}
if !s.AbilityIs(abilities.Focusable) {
// never need bigger border if not focusable
s.MaxBorder = s.Border
}
})
// TODO(kai): maybe move all of these event handling functions into one function
wb.handleWidgetClick()
wb.handleWidgetStateFromMouse()
wb.handleLongHoverTooltip()
wb.handleWidgetStateFromFocus()
wb.handleWidgetStateFromAttend()
wb.handleWidgetContextMenu()
wb.handleWidgetMagnify()
wb.handleValueOnChange()
wb.Updater(wb.UpdateFromMake)
}
// OnAdd is called when widgets are added to a parent.
// It sets the scene of the widget to its widget parent.
// It should be called by all other OnAdd functions defined
// by widget types.
func (wb *WidgetBase) OnAdd() {
if pwb := wb.parentWidget(); pwb != nil {
if pwb.Scene != nil && pwb.Scene != wb.Scene {
// A subtree added as a whole (for example, a clone or a moved
// widget) has descendants that must now be in the new scene.
// A parent without a scene, as when a body is added to an
// external parent, leaves the scenes of the descendants alone.
wb.setDescendantScenes(pwb.Scene)
}
if wb.Scene != pwb.Scene {
// (not written when it is the same, as for a body added to its
// scene when its window is run, while another goroutine can
// wait in [WidgetBase.AsyncLock] for the scene to be shown)
wb.Scene = pwb.Scene
}
if wb.hasFlag(widgetNeedsRender) || wb.hasFlag(widgetChildNeedsRender) {
wb.setParentsChildNeedsRender()
}
}
if wb.Parts != nil {
// the Scene of the Parts may not have been set yet if they were made in Init
wb.Parts.Scene = wb.Scene
}
if wb.Scene != nil && wb.Scene.WidgetInit != nil {
wb.Scene.WidgetInit(wb.This.(Widget))
}
}
// setDescendantScenes sets the [WidgetBase.Scene] of all of the descendants
// of this widget, including those in parts, to the given scene. Descendants
// that had no scene before, such as those of a clone, have not been
// initialized for any scene yet, so it calls its [Scene.WidgetInit] on them,
// as [WidgetBase.OnAdd] does for each widget.
func (wb *WidgetBase) setDescendantScenes(sc *Scene) {
set := func(kwb *WidgetBase) {
hadScene := kwb.Scene != nil
kwb.Scene = sc
kwb.setDescendantScenes(sc)
if !hadScene && sc != nil && sc.WidgetInit != nil {
sc.WidgetInit(kwb.This.(Widget))
}
}
for _, k := range wb.Children {
if kwb := AsWidget(k); kwb != nil {
set(kwb)
}
}
if wb.Parts != nil {
set(wb.Parts.AsWidget())
}
// the scrollbars of a frame, which are not its children, are rendered
// with its scene (they were rendered in the scene of the page that a web
// page was read in, and not shown, once it was moved into its own)
if fr := AsFrame(wb.This); fr != nil {
for _, sb := range fr.Scrolls {
if sb != nil {
sb.Scene = sc
}
}
}
}
// SetScene sets the Scene pointer for this widget and all of its children.
// This can be necessary when creating widgets outside the usual New* paradigm,
// e.g., when reading from a JSON file.
func (wb *WidgetBase) SetScene(sc *Scene) {
for _, cwb := range wb.AllWidgets() {
cwb.Scene = sc
}
}
// AsWidget returns the given [tree.Node] as a [WidgetBase] or nil.
func AsWidget(n tree.Node) *WidgetBase {
if w, ok := n.(Widget); ok {
return w.AsWidget()
}
return nil
}
func (wb *WidgetBase) AsWidget() *WidgetBase {
return wb
}
func (wb *WidgetBase) CopyFieldsFrom(from tree.Node) {
wb.NodeBase.CopyFieldsFrom(from)
frm := AsWidget(from)
n := len(wb.ContextMenus)
if len(frm.ContextMenus) > n {
wb.ContextMenus = append(wb.ContextMenus, frm.ContextMenus[n:]...)
}
wb.Stylers.DoWith(&frm.Stylers, func(to, from *[]func(s *styles.Style)) {
n := len(*to)
if len(*from) > n {
*to = append(*to, (*from)[n:]...)
}
})
wb.Listeners.DoWith(&frm.Listeners, func(to, from *events.Listeners) {
to.CopyFromExtra(*from)
})
}
func (wb *WidgetBase) Destroy() {
wb.deleteParts()
wb.NodeBase.Destroy()
}
// deleteParts deletes the widget's parts (and the children of the parts).
func (wb *WidgetBase) deleteParts() {
if wb.Parts != nil {
wb.Parts.Destroy()
}
wb.Parts = nil
}
// newParts makes the [WidgetBase.Parts] if they don't already exist.
// It returns the parts regardless.
func (wb *WidgetBase) newParts() *Frame {
if wb.Parts != nil {
return wb.Parts
}
wb.Parts = NewFrame()
wb.Parts.SetName("parts")
tree.SetParent(wb.Parts, wb) // don't add to children list
wb.Parts.Styler(func(s *styles.Style) {
s.Grow.Set(1, 1)
s.RenderBox = false
})
return wb.Parts
}
// parentWidget returns the parent as a [WidgetBase] or nil
// if this is the root and has no parent.
func (wb *WidgetBase) parentWidget() *WidgetBase {
if wb.Parent == nil {
return nil
}
pw, ok := wb.Parent.(Widget)
if ok {
return pw.AsWidget()
}
return nil // the parent may be a non-widget in [tree.UnmarshalRootJSON]
}
// IsDisplayable returns whether the widget has the potential of being displayed.
// If it or any of its parents are deleted or [states.Invisible], it is not
// displayable. Otherwise, it is displayable.
//
// This does *not* check if the widget is actually currently visible, for which you
// can use [WidgetBase.IsVisible]. In other words, if a widget is currently offscreen
// but can be scrolled onscreen, it is still displayable, but it is not visible until
// its bounding box is actually onscreen.
//
// Widgets that are not displayable are automatically not rendered and do not get
// window events.
//
// [styles.DisplayNone] can be set for [styles.Style.Display] to make a widget
// not displayable.
func (wb *WidgetBase) IsDisplayable() bool {
if wb == nil || wb.This == nil || wb.StateIs(states.Invisible) || wb.Scene == nil {
return false
}
if wb.Parent == nil {
return true
}
return wb.parentWidget().IsDisplayable()
}
// IsVisible returns whether the widget is actually currently visible.
// A widget is visible if and only if it is both [WidgetBase.IsDisplayable]
// and it has a non-empty rendering bounding box (ie: it is currently onscreen).
// This means that widgets currently not visible due to scrolling will return false
// for this function, even though they are still displayable and return true for
// [WidgetBase.IsDisplayable].
func (wb *WidgetBase) IsVisible() bool {
// The bounding box is checked first, as it is much faster than checking
// all of the parents, and most widgets are offscreen in a long scene.
return wb != nil && !wb.Geom.TotalBBox.Empty() && wb.IsDisplayable()
}
// RenderSource returns the self-contained [composer.Source] for
// rendering this widget. The base widget returns nil, and the [Scene]
// widget returns the [paint.Painter] rendering results.
// Widgets that do direct rendering instead of drawing onto
// the Scene painter should return a suitable render source.
// Use [Scene.AddDirectRender] to register such widgets with the Scene.
// The given draw operation is the suggested way to Draw onto existing images.
func (wb *WidgetBase) RenderSource(op draw.Op) composer.Source { return nil }
// NodeWalkDown extends [tree.Node.WalkDown] to [WidgetBase.Parts],
// which is key for getting full tree traversal to work when updating,
// configuring, and styling. This implements [tree.Node.NodeWalkDown].
func (wb *WidgetBase) NodeWalkDown(fun func(tree.Node) bool) {
if wb.Parts == nil {
return
}
wb.Parts.WalkDown(fun)
}
// ForWidgetChildren iterates through the children as widgets, calling the given function.
// Return [tree.Continue] (true) to continue, and [tree.Break] (false) to terminate.
func (wb *WidgetBase) ForWidgetChildren(fun func(i int, cw Widget, cwb *WidgetBase) bool) {
for i, c := range wb.Children {
if tree.IsNil(c) {
continue
}
w := c.(Widget)
if !fun(i, w, w.AsWidget()) {
break
}
}
}
// forVisibleChildren iterates through the children,as widgets, calling the given function,
// excluding any with the *local* states.Invisible flag set (does not check parents).
// This is used e.g., for layout functions to exclude non-visible direct children.
// Return [tree.Continue] (true) to continue, and [tree.Break] (false) to terminate.
func (wb *WidgetBase) forVisibleChildren(fun func(i int, cw Widget, cwb *WidgetBase) bool) {
for i, c := range wb.Children {
if tree.IsNil(c) {
continue
}
w := c.(Widget)
cwb := w.AsWidget()
if cwb.StateIs(states.Invisible) {
continue
}
cont := fun(i, w, cwb)
if !cont {
break
}
}
}
// WidgetWalkDown is a version of [tree.NodeBase.WalkDown] that operates on [Widget] types,
// calling the given function on the Widget and all of its children in a depth-first manner.
// Return [tree.Continue] to continue into the children of a widget, and [tree.Break]
// to skip them (the walk continues with the rest of the tree). To visit all of the
// widgets, or to stop at the first one that matches, range over [WidgetBase.AllWidgets].
func (wb *WidgetBase) WidgetWalkDown(fun func(cw Widget, cwb *WidgetBase) bool) {
wb.WalkDown(func(n tree.Node) bool {
cw, cwb := n.(Widget), AsWidget(n)
return fun(cw, cwb)
})
}
// AllWidgets returns an iterator over this widget and all of its descendant
// widgets (including their parts), in depth-first order, as [tree.NodeBase.All]
// does for nodes. Breaking out of the loop stops the iteration:
//
// for cw, cwb := range wb.AllWidgets() {
func (wb *WidgetBase) AllWidgets() iter.Seq2[Widget, *WidgetBase] {
return func(yield func(Widget, *WidgetBase) bool) {
for n := range wb.All() {
if !yield(n.(Widget), AsWidget(n)) {
return
}
}
}
}
// widgetNext returns the next widget in the tree,
// including Parts, which are considered to come after Children.
// returns nil if no more.
func widgetNext(w Widget) Widget {
wb := w.AsWidget()
if !wb.HasChildren() && wb.Parts == nil {
return widgetNextSibling(w)
}
if wb.HasChildren() {
return wb.Child(0).(Widget)
}
if wb.Parts != nil {
return widgetNext(wb.Parts.This.(Widget))
}
return nil
}
// widgetNextSibling returns next sibling or nil if none,
// including Parts, which are considered to come after Children.
func widgetNextSibling(w Widget) Widget {
wb := w.AsWidget()
if wb.Parent == nil {
return nil
}
parent := wb.Parent.(Widget)
myidx := wb.IndexInParent()
if myidx >= 0 && myidx < wb.Parent.AsTree().NumChildren()-1 {
return parent.AsTree().Child(myidx + 1).(Widget)
}
return widgetNextSibling(parent)
}
// widgetPrev returns the previous widget in the tree,
// including Parts, which are considered to come after Children.
// nil if no more.
func widgetPrev(w Widget) Widget {
wb := w.AsWidget()
if wb.Parent == nil {
return nil
}
parent := wb.Parent.(Widget)
myidx := wb.IndexInParent()
if myidx > 0 {
nn := parent.AsTree().Child(myidx - 1).(Widget)
return widgetLastChildParts(nn) // go to parts
}
// we were children, done
return parent
}
// widgetLastChildParts returns the last child under given node,
// or node itself if no children. Starts with Parts,
func widgetLastChildParts(w Widget) Widget {
wb := w.AsWidget()
if wb.Parts != nil && wb.Parts.HasChildren() {
return widgetLastChildParts(wb.Parts.Child(wb.Parts.NumChildren() - 1).(Widget))
}
if wb.HasChildren() {
return widgetLastChildParts(wb.Child(wb.NumChildren() - 1).(Widget))
}
return w
}
// widgetNextFunc returns the next widget in the tree,
// including Parts, which are considered to come after children,
// continuing until the given function returns true.
// nil if no more.
func widgetNextFunc(w Widget, fun func(w Widget) bool) Widget {
for {
nw := widgetNext(w)
if nw == nil {
return nil
}
if fun(nw) {
return nw
}
if nw == w {
slog.Error("WidgetNextFunc", "start", w, "nw == wi", nw)
return nil
}
w = nw
}
}
// widgetPrevFunc returns the previous widget in the tree,
// including Parts, which are considered to come after children,
// continuing until the given function returns true.
// nil if no more.
func widgetPrevFunc(w Widget, fun func(w Widget) bool) Widget {
for {
pw := widgetPrev(w)
if pw == nil {
return nil
}
if fun(pw) {
return pw
}
if pw == w {
slog.Error("WidgetPrevFunc", "start", w, "pw == wi", pw)
return nil
}
w = pw
}
}
// WidgetTooltip is the base implementation of [Widget.WidgetTooltip],
// which just returns [WidgetBase.Tooltip] and [WidgetBase.DefaultTooltipPos].
func (wb *WidgetBase) WidgetTooltip(pos image.Point) (string, image.Point) {
return wb.Tooltip, wb.DefaultTooltipPos()
}
// TextRunes returns any text content associated with the widget, to be used
// for Search for example. If this is nil, then it is excluded from search.
func (wb *WidgetBase) TextRunes() []rune {
return nil
}
// Search returns text search results for this widget, searching for
// the find string with given case sensitivity. It is up to each widget
// to define the meaning of the Region line, char values for the matches.
// The bool return value indicates whether this widget handled the search,
// thereby excluding further searching within the elements under it.
func (wb *WidgetBase) Search(find string, useCase CaseSensitive) ([]textpos.Match, bool) {
return nil, false
}
// HighlightMatches does highlighting of the given matches within this widget,
// where the matches are as returned from the Search method.
// Passing a nil causes matches to be reset.
// Any existing highlighting should always be reset first regardless.
// The bool return value indicates whether this widget handled the search,
// thereby excluding further searching within the elements under it.
func (wb *WidgetBase) HighlightMatches(matches []textpos.Match) bool {
return false
}
// SelectMatch selects match at given index from among those returned
// from the Search method. scroll = scroll widget into view.
// reset = clear selection instead of selecting (does not scroll).
func (wb *WidgetBase) SelectMatch(matches []textpos.Match, index int, scroll SelectionScroll, reset SelectionReset) {
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"fmt"
"image"
"log/slog"
"cogentcore.org/core/events"
"cogentcore.org/core/events/key"
"cogentcore.org/core/keymap"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/system"
"cogentcore.org/core/tree"
)
// Events returns the higher-level core event manager
// for this [Widget]'s [Scene].
func (wb *WidgetBase) Events() *Events {
if wb.Scene == nil {
return nil
}
return &wb.Scene.Events
}
// SystemEvents returns the lower-level system event
// manager for this [Widget]'s [Scene].
func (wb *WidgetBase) SystemEvents() *events.Source {
return wb.Scene.RenderWindow().SystemWindow.Events()
}
// Clipboard returns the clipboard for the [Widget] to use.
func (wb *WidgetBase) Clipboard() system.Clipboard {
return wb.Events().Clipboard()
}
// On adds the given event handler to the [WidgetBase.Listeners.Normal] for the given
// event type. Listeners are called in sequential descending order, so this listener
// will be called before all of the ones added before it. On is one of the main ways
// to add an event handler to a widget, in addition to OnFirst and OnFinal, which add
// event handlers that are called before and after those added by this function,
// respectively.
func (wb *WidgetBase) On(etype events.Types, fun func(e events.Event)) {
wb.Listeners.Normal.Add(etype, fun)
}
// OnFirst adds the given event handler to the [WidgetBase.Listeners.First] for the given
// event type. FirstListeners are called in sequential descending order, so this first
// listener will be called before all of the ones added before it. OnFirst is one of the
// main ways to add an event handler to a widget, in addition to On and OnFinal,
// which add event handlers that are called after those added by this function.
func (wb *WidgetBase) OnFirst(etype events.Types, fun func(e events.Event)) {
wb.Listeners.First.Add(etype, fun)
}
// OnFinal adds the given event handler to the [WidgetBase.Listeners.Final] for the given
// event type. FinalListeners are called in sequential descending order, so this final
// listener will be called before all of the ones added before it. OnFinal is one of the
// main ways to add an event handler to a widget, in addition to OnFirst and On,
// which add event handlers that are called before those added by this function.
func (wb *WidgetBase) OnFinal(etype events.Types, fun func(e events.Event)) {
wb.Listeners.Final.Add(etype, fun)
}
// Helper functions for common event types:
// OnClick adds an event listener function for [events.Click] events.
func (wb *WidgetBase) OnClick(fun func(e events.Event)) {
wb.On(events.Click, fun)
}
// OnDoubleClick adds an event listener function for [events.DoubleClick] events.
func (wb *WidgetBase) OnDoubleClick(fun func(e events.Event)) {
wb.On(events.DoubleClick, fun)
}
// OnChange adds an event listener function for [events.Change] events.
func (wb *WidgetBase) OnChange(fun func(e events.Event)) {
wb.On(events.Change, fun)
}
// OnInput adds an event listener function for [events.Input] events.
func (wb *WidgetBase) OnInput(fun func(e events.Event)) {
wb.On(events.Input, fun)
}
// OnKeyChord adds an event listener function for [events.KeyChord] events.
func (wb *WidgetBase) OnKeyChord(fun func(e events.Event)) {
wb.On(events.KeyChord, fun)
}
// OnFocus adds an event listener function for [events.Focus] events.
func (wb *WidgetBase) OnFocus(fun func(e events.Event)) {
wb.On(events.Focus, fun)
}
// OnFocusLost adds an event listener function for [events.FocusLost] events.
func (wb *WidgetBase) OnFocusLost(fun func(e events.Event)) {
wb.On(events.FocusLost, fun)
}
// OnSelect adds an event listener function for [events.Select] events.
func (wb *WidgetBase) OnSelect(fun func(e events.Event)) {
wb.On(events.Select, fun)
}
// OnShow adds an event listener function for [events.Show] events.
func (wb *WidgetBase) OnShow(fun func(e events.Event)) {
wb.On(events.Show, fun)
}
// OnClose adds an event listener function for [events.Close] events.
func (wb *WidgetBase) OnClose(fun func(e events.Event)) {
wb.On(events.Close, fun)
}
// AddCloseDialog adds a dialog that confirms that the user wants to close the Scene
// associated with this widget when they try to close it. It calls the given config
// function to configure the dialog. It is the responsibility of this config function
// to add the title and close button to the dialog, which is necessary so that the close
// dialog can be fully customized. If this function returns false, it does not make the
// dialog. This can be used to make the dialog conditional on other things, like whether
// something is saved.
func (wb *WidgetBase) AddCloseDialog(config func(d *Body) bool) {
var inClose, canClose bool
wb.OnClose(func(e events.Event) {
if canClose {
return // let it close
}
if inClose {
e.SetHandled()
return
}
inClose = true
d := NewBody()
d.AddBottomBar(func(bar *Frame) {
d.AddCancel(bar).OnClick(func(e events.Event) {
inClose = false
canClose = false
})
bar.AsWidget().SetOnChildAdded(func(n tree.Node) {
if bt := AsButton(n); bt != nil {
bt.OnFirst(events.Click, func(e events.Event) {
// any button click gives us permission to close
canClose = true
})
}
})
})
if !config(d) {
return
}
e.SetHandled()
d.RunDialog(wb)
})
}
// Send sends an new event of the given type to this widget,
// optionally starting from values in the given original event
// (recommended to include where possible).
// Do not send an existing event using this method if you
// want the Handled state to persist throughout the call chain;
// call HandleEvent directly for any existing events.
func (wb *WidgetBase) Send(typ events.Types, original ...events.Event) {
if wb.This == nil {
return
}
if typ == events.Click {
em := wb.Events()
if em != nil && em.focus != wb.This.(Widget) {
// always clear any other focus before the click is processed.
// this causes textfields etc to apply their changes.
em.focusClear()
}
}
var e events.Event
if len(original) > 0 && original[0] != nil {
e = original[0].NewFromClone(typ)
} else {
e = &events.Base{Typ: typ}
e.Init()
}
wb.HandleEvent(e)
}
// SendChange sends a new [events.Change] event, which is widely used to signal
// value changing for most widgets. It takes the event that the new change event
// is derived from, if any.
func (wb *WidgetBase) SendChange(original ...events.Event) {
wb.Send(events.Change, original...)
}
// UpdateChange is a helper function that calls [WidgetBase.SendChange]
// and then [WidgetBase.Update]. That is the correct order, since
// calling [WidgetBase.Update] first would cause the value of the widget
// to be incorrectly overridden in a [Value] context.
//
// See also [WidgetBase.UpdateInput].
func (wb *WidgetBase) UpdateChange(original ...events.Event) {
wb.SendChange(original...)
wb.Update()
}
// UpdateInput is a helper function that calls [WidgetBase.Send]([events.Input])
// and then [WidgetBase.UpdateRender]. See also [WidgetBase.UpdateChange].
func (wb *WidgetBase) UpdateInput(original ...events.Event) {
wb.Send(events.Input, original...)
wb.UpdateRender()
}
func (wb *WidgetBase) sendKey(kf keymap.Functions, original ...events.Event) {
if wb.This == nil {
return
}
kc := kf.Chord()
wb.sendKeyChord(kc, original...)
}
func (wb *WidgetBase) sendKeyChord(kc key.Chord, original ...events.Event) {
r, code, mods, err := kc.Decode()
if err != nil {
fmt.Println("SendKeyChord: Decode error:", err)
return
}
wb.sendKeyChordRune(r, code, mods, original...)
}
func (wb *WidgetBase) sendKeyChordRune(r rune, code key.Codes, mods key.Modifiers, original ...events.Event) {
ke := events.NewKey(events.KeyChord, r, code, mods)
if len(original) > 0 && original[0] != nil {
kb := *original[0].AsBase()
ke.GenTime = kb.GenTime
ke.ClearHandled()
} else {
ke.Init()
}
ke.Typ = events.KeyChord
wb.HandleEvent(ke)
}
// HandleEvent sends the given event to all [WidgetBase.Listeners] for that event type.
// It also checks if the State has changed and calls [WidgetBase.Restyle] if so.
func (wb *WidgetBase) HandleEvent(e events.Event) {
if DebugSettings.EventTrace {
if e.Type() != events.MouseMove {
fmt.Println(e, "to", wb)
}
}
if wb == nil || wb.This == nil {
return
}
s := &wb.Styles
state := s.State
wb.Listeners.Do(func(l *events.Listeners) {
l.Call(e, func() bool {
return wb.This != nil
})
})
if s.State != state && e.Type() != events.Attend && e.Type() != events.AttendLost {
wb.Restyle()
}
}
// firstHandleEvent sends the given event to the Listeners.First for that event type.
// Does NOT do any state updating.
func (wb *WidgetBase) firstHandleEvent(e events.Event) {
if DebugSettings.EventTrace {
if e.Type() != events.MouseMove {
fmt.Println(e, "first to", wb)
}
}
wb.Listeners.First.Call(e, func() bool {
return wb.This != nil
})
}
// finalHandleEvent sends the given event to the Listeners.Final for that event type.
// Does NOT do any state updating.
func (wb *WidgetBase) finalHandleEvent(e events.Event) {
if DebugSettings.EventTrace {
if e.Type() != events.MouseMove {
fmt.Println(e, "final to", wb)
}
}
wb.Listeners.Final.Call(e, func() bool {
return wb.This != nil
})
}
// posInScBBox returns true if given position is within
// this node's scene bbox
func (wb *WidgetBase) posInScBBox(pos image.Point) bool {
return pos.In(wb.Geom.TotalBBox)
}
// handleWidgetClick handles the Click event for basic Widget behavior.
// For Left button:
// If Checkable, toggles Checked. if Focusable, Focuses or clears,
// If Selectable, updates state and sends Select, Deselect.
func (wb *WidgetBase) handleWidgetClick() {
wb.OnClick(func(e events.Event) {
if wb.AbilityIs(abilities.Checkable) && !wb.IsReadOnly() {
wb.SetState(!wb.StateIs(states.Checked), states.Checked)
}
if wb.AbilityIs(abilities.Focusable) {
wb.SetFocusQuiet()
} else {
wb.focusClear()
}
// note: read only widgets are automatically selectable
if wb.AbilityIs(abilities.Selectable) || wb.IsReadOnly() {
wb.Send(events.Select, e)
}
})
}
// handleWidgetStateFromMouse updates all standard
// State flags based on mouse events,
// such as MouseDown / Up -> Active and MouseEnter / Leave -> Hovered.
// None of these "consume" the event by setting Handled flag, as they are
// designed to work in conjunction with more specific handlers.
// Note that Disabled and Invisible widgets do NOT receive
// these events so it is not necessary to check that.
func (wb *WidgetBase) handleWidgetStateFromMouse() {
wb.On(events.MouseDown, func(e events.Event) {
if wb.AbilityIs(abilities.Activatable) {
wb.SetState(true, states.Active)
}
})
wb.On(events.MouseUp, func(e events.Event) {
// note: not contingent on Activatable: always clear on up
wb.SetState(false, states.Active)
})
wb.On(events.LongPressStart, func(e events.Event) {
if wb.AbilityIs(abilities.LongPressable) {
wb.SetState(true, states.LongPressed)
}
})
wb.On(events.LongPressEnd, func(e events.Event) {
if wb.AbilityIs(abilities.LongPressable) {
wb.SetState(false, states.LongPressed)
}
})
wb.On(events.MouseEnter, func(e events.Event) {
if wb.AbilityIs(abilities.Hoverable) {
wb.SetState(true, states.Hovered)
}
})
wb.On(events.MouseLeave, func(e events.Event) {
if wb.AbilityIs(abilities.Hoverable) {
wb.SetState(false, states.Hovered)
}
})
wb.On(events.LongHoverStart, func(e events.Event) {
if wb.AbilityIs(abilities.LongHoverable) {
wb.SetState(true, states.LongHovered)
}
})
wb.On(events.LongHoverEnd, func(e events.Event) {
if wb.AbilityIs(abilities.LongHoverable) {
wb.SetState(false, states.LongHovered)
}
})
wb.On(events.SlideStart, func(e events.Event) {
if wb.AbilityIs(abilities.Slideable) {
wb.SetState(true, states.Sliding)
}
})
wb.On(events.SlideStop, func(e events.Event) {
if wb.AbilityIs(abilities.Slideable) {
wb.SetState(false, states.Sliding, states.Active)
}
})
}
// handleLongHoverTooltip listens for LongHover and LongPress events and
// pops up and deletes tooltips based on those. Most widgets should call
// this as part of their event handler methods.
func (wb *WidgetBase) handleLongHoverTooltip() {
wb.On(events.LongHoverStart, func(e events.Event) {
wi := wb.This.(Widget)
tt, pos := wi.WidgetTooltip(e.Pos())
if tt == "" {
return
}
e.SetHandled()
newTooltip(wi, tt, pos).Run()
})
wb.On(events.LongHoverEnd, func(e events.Event) {
if wb.Scene.Stage != nil {
wb.Scene.Stage.popups.popDeleteType(TooltipStage)
}
})
wb.On(events.LongPressStart, func(e events.Event) {
if !TheApp.SystemPlatform().IsMobile() {
return
}
var pops *stages
var before *Stage
if st := wb.Scene.Stage; st != nil && st.popups != nil {
pops = st.popups
before = pops.top()
}
wb.Send(events.ContextMenu, e)
// the finger is still down: the menu is opened by the press (see
// [Stage.pressOpened]), so its release does not close it (as a
// click off it) and is that of the press, and a drag to an item
// and a release there clicks it
if pops != nil {
if top := pops.top(); top != nil && top != before && top.Type == MenuStage {
top.pressOpened = true
}
}
wi := wb.This.(Widget)
tt, pos := wi.WidgetTooltip(e.Pos())
if tt == "" {
return
}
e.SetHandled()
newTooltip(wi, tt, pos).Run()
})
wb.On(events.LongPressEnd, func(e events.Event) {
if !TheApp.SystemPlatform().IsMobile() {
return
}
if wb.Scene.Stage != nil {
wb.Scene.Stage.popups.popDeleteType(TooltipStage)
}
})
}
// handleWidgetStateFromFocus updates standard State flags based on Focus events
func (wb *WidgetBase) handleWidgetStateFromFocus() {
wb.OnFocus(func(e events.Event) {
if wb.AbilityIs(abilities.Focusable) {
wb.ScrollToThis()
wb.SetState(true, states.Focused)
wb.showVirtualKeyboard()
}
})
wb.OnFocusLost(func(e events.Event) {
// The focused state is always cleared, as the widget can have
// become not focusable (such as read-only) since it got the focus.
wb.SetState(false, states.Focused)
if wb.AbilityIs(abilities.Focusable) && !wb.IsReadOnly() && wb.Styles.VirtualKeyboard != styles.KeyboardNone {
TheApp.HideVirtualKeyboard()
}
})
}
// showVirtualKeyboard shows the virtual keyboard for the widget, which has
// the focus, if it is editable (not read-only, with a keyboard).
func (wb *WidgetBase) showVirtualKeyboard() {
if !wb.IsReadOnly() && wb.Styles.VirtualKeyboard != styles.KeyboardNone {
TheApp.ShowVirtualKeyboard(wb.Styles.VirtualKeyboard)
}
}
// handleWidgetStateFromAttend updates standard State flags based on Attend events
func (wb *WidgetBase) handleWidgetStateFromAttend() {
wb.On(events.Attend, func(e events.Event) {
if wb.Styles.Abilities.IsPressable() {
wb.SetState(true, states.Attended)
}
})
wb.On(events.AttendLost, func(e events.Event) {
if wb.Styles.Abilities.IsPressable() {
wb.SetState(false, states.Attended)
}
})
}
// HandleWidgetMagnifyEvent calls [renderWindow.stepZoom] on [events.Magnify]
func (wb *WidgetBase) handleWidgetMagnify() {
wb.On(events.Magnify, func(e events.Event) {
ev := e.(*events.TouchMagnify)
wb.Events().RenderWindow().stepZoom(ev.ScaleFactor - 1)
})
}
// handleValueOnChange adds a handler that calls [WidgetBase.ValueOnChange],
// for [events.Change]. This is installed by default by [Bind].
func (wb *WidgetBase) handleValueOnChange() {
// need to go before end-user OnChange handlers
wb.OnFirst(events.Change, func(e events.Event) {
if wb.ValueOnChange != nil {
wb.ValueOnChange()
}
})
}
// HandleValueOnInput adds a handler that calls [WidgetBase.ValueOnChange],
// for [events.Input] events. This is not done by default, but can be useful
// if handling input events from a [Slider] for example.
// This is not generally a good idea for a [TextField] or other text-input widget,
// because the input-level partial value is often not parseable.
func (wb *WidgetBase) HandleValueOnInput() {
wb.OnFirst(events.Input, func(e events.Event) {
if wb.ValueOnChange != nil {
wb.ValueOnChange()
}
})
}
// SendChangeOnInput adds an event handler that does [WidgetBase.SendChange]
// in [WidgetBase.OnInput]. This is not done by default, but you can call it
// if you want [events.Input] to trigger full change events, such as in a [Bind]
// context.
func (wb *WidgetBase) SendChangeOnInput() {
wb.OnInput(func(e events.Event) {
wb.SendChange(e)
})
}
// SendClickOnEnter adds a key event handler for Enter and Space
// keys to generate an [events.Click] event. This is not added by default,
// but is added in [Button] and [Switch] for example.
func (wb *WidgetBase) SendClickOnEnter() {
wb.OnKeyChord(func(e events.Event) {
kf := keymap.Of(e.KeyChord())
if DebugSettings.KeyEventTrace {
slog.Info("WidgetBase.SendClickOnEnter", "widget", wb, "keyFunction", kf)
}
if kf == keymap.Accept {
wb.Send(events.Click, e) // don't SetHandled
} else if kf == keymap.Enter || e.KeyRune() == ' ' {
e.SetHandled()
wb.Send(events.Click, e)
}
})
}
// dragStateReset resets the drag related state flags, including [states.Active].
func (wb *WidgetBase) dragStateReset() {
wb.SetState(false, states.Active, states.DragHovered, states.Dragging)
}
//////// Focus
// SetFocusQuiet sets the keyboard input focus on this item or the first item
// within it that can be focused (if none, then just sets focus to this widget).
// This does NOT send an [events.Focus] event, so the widget will NOT appear focused;
// it will however receive keyboard input, at which point it will get visible focus.
// See [WidgetBase.SetFocus] for a version that sends an event. Also see
// [WidgetBase.StartFocus].
func (wb *WidgetBase) SetFocusQuiet() {
foc := wb.This.(Widget)
if !wb.AbilityIs(abilities.Focusable) {
foc = wb.focusableInThis()
if foc == nil {
foc = wb.This.(Widget)
}
}
em := wb.Events()
if em != nil {
em.setFocusQuiet(foc) // doesn't send event
}
}
// SetFocus sets the keyboard input focus on this item or the first item within it
// that can be focused (if none, then just sets focus to this widget).
// This sends an [events.Focus] event, which typically results in
// the widget being styled as focused. See [WidgetBase.SetFocusQuiet] for
// a version that does not. Also see [WidgetBase.StartFocus].
//
// SetFocus only fully works for widgets that have already been shown, so for newly
// created widgets, you should use [WidgetBase.StartFocus], or [WidgetBase.Defer] your
// SetFocus call.
func (wb *WidgetBase) SetFocus() {
foc := wb.This.(Widget)
if !wb.AbilityIs(abilities.Focusable) {
foc = wb.focusableInThis()
if foc == nil {
foc = wb.This.(Widget)
}
}
em := wb.Events()
if em != nil {
em.setFocus(foc)
}
}
// focusableInThis returns the first Focusable element within this widget
func (wb *WidgetBase) focusableInThis() Widget {
var foc Widget
for cw, cwb := range wb.AllWidgets() {
if !cwb.AbilityIs(abilities.Focusable) {
continue
}
foc = cw
break // done
}
return foc
}
// focusNext moves the focus onto the next item
func (wb *WidgetBase) focusNext() {
em := wb.Events()
if em != nil {
em.focusNext()
}
}
// focusPrev moves the focus onto the previous item
func (wb *WidgetBase) focusPrev() {
em := wb.Events()
if em != nil {
em.focusPrev()
}
}
// focusClear resets focus to nil, but keeps the previous focus to pick up next time..
func (wb *WidgetBase) focusClear() {
em := wb.Events()
if em != nil {
em.focusClear()
}
}
// StartFocus specifies that this widget should get focus when the [Scene] is shown,
// or when a major content managing widget (e.g., [Tabs], [Pages]) shows a
// tab/page/element that contains this widget. This is implemented via an
// [events.Show] event.
func (wb *WidgetBase) StartFocus() {
em := wb.Events()
if em != nil {
em.SetStartFocus(wb.This.(Widget))
}
}
// ContainsFocus returns whether this widget contains the current focus widget.
func (wb *WidgetBase) ContainsFocus() bool {
em := wb.Events()
if em == nil {
return false
}
cur := em.focus
if cur == nil {
return false
}
if cur.AsTree().This == wb.This {
return true
}
plev := cur.AsTree().ParentLevel(wb.This)
return plev >= 0
}
// SetAttend sends [events.Attend] to this widget if it is pressable.
func (wb *WidgetBase) SetAttend() {
if !wb.Styles.Abilities.IsPressable() {
return
}
em := wb.Events()
if em != nil {
em.setAttend(wb.This.(Widget))
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"fmt"
"image"
"log"
"maps"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"time"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/sharedfile"
"cogentcore.org/core/system"
)
var (
// theWindowGeometrySaver is the manager of window geometry settings
theWindowGeometrySaver = windowGeometrySaver{}
)
// screenConfigGeometries has the window geometry data for different
// screen configurations, where a screen configuration is a specific
// set of available screens, naturally corresponding to the
// home vs. office vs. travel usage of a laptop, for example,
// with different sets of screens available in each location.
// Each such configuration has a different set of saved window geometries,
// which is restored when the set of screens changes, so your windows will
// be restored to their last positions and sizes for each such configuration.
type screenConfigGeometries map[string]map[string]windowGeometries
// screenConfig returns the current screen configuration string,
// which is the alpha-sorted list of current screen names.
func screenConfig() string {
ns := TheApp.NScreens()
if ns == 0 {
return "none"
}
scs := make([]string, ns)
for i := range ns {
scs[i] = TheApp.Screen(i).Name
}
slices.Sort(scs)
return strings.Join(scs, "|")
}
// windowGeometrySaver records window geometries in a persistent file,
// which is then used when opening new windows to restore.
type windowGeometrySaver struct {
// the full set of window geometries, in the file shared by all apps,
// which is read again when another app has changed it
geometries sharedfile.File[screenConfigGeometries]
// temporary cached geometries: saved to geometries after SaveDelay
cache screenConfigGeometries
// base name of the settings file in Cogent Core settings directory
filename string
// whether init has been done
inited bool
// if true, we are setting geometry so don't save;
// Caller must call SettingStart() SettingEnd() to block.
settingNoSave bool
// read-write mutex that protects updating of WindowGeometry
mu sync.RWMutex
// wait time before saving the Cache into Geometries
saveDelay time.Duration
// timer for delayed save
saveTimer *time.Timer
}
// init does initialization if not yet initialized
func (ws *windowGeometrySaver) init() {
if ws.inited {
return
}
ws.inited = true
ws.resetCache()
ws.filename = "window-geometry-0.3.6"
ws.geometries.Path = filepath.Join(TheApp.CogentCoreDataDir(), ws.filename+".json")
ws.saveDelay = 1 * time.Second
}
// shouldSave returns whether the window geometry should be saved based on
// the platform: only for desktop native platforms.
func (ws *windowGeometrySaver) shouldSave() bool {
return !TheApp.Platform().IsMobile() && TheApp.Platform() != system.Offscreen && !DebugSettings.DisableWindowGeometrySaver
}
// resetCache resets the cache; call under mutex
func (ws *windowGeometrySaver) resetCache() {
ws.cache = make(screenConfigGeometries)
}
// open opens the window geometries file from the Cogent Core data directory,
// if it changed since it was last read. Called under mutex or at start.
func (ws *windowGeometrySaver) open() error {
ws.init()
return ws.geometries.Reload()
}
// windowName returns window name before first colon, if exists.
// This is the part of the name used to record settings
func (ws *windowGeometrySaver) windowName(winName string) string {
if ci := strings.Index(winName, ":"); ci > 0 {
return winName[:ci]
}
return winName
}
// settingStart turns on SettingNoSave to prevent subsequent redundant calls to
// save a geometry that was being set from already-saved settings.
// Must call SettingEnd to turn off (safe to call even if Start not called).
func (ws *windowGeometrySaver) settingStart() {
ws.mu.Lock()
ws.resetCache() // get rid of anything just saved prior to this -- sus.
ws.settingNoSave = true
ws.mu.Unlock()
}
// settingEnd turns off SettingNoSave -- safe to call even if Start not called.
func (ws *windowGeometrySaver) settingEnd() {
ws.mu.Lock()
ws.settingNoSave = false
ws.mu.Unlock()
}
// record records current state of window as preference
func (ws *windowGeometrySaver) record(win *renderWindow) {
if !ws.shouldSave() || !win.isVisible() || win.SystemWindow.Is(system.Fullscreen) {
return
}
win.SystemWindow.Lock()
wsz := win.SystemWindow.Size()
win.SystemWindow.Unlock()
if wsz == (image.Point{}) {
if DebugSettings.WindowGeometryTrace {
log.Printf("WindowGeometry: Record: NOT storing null size for win: %v\n", win.name)
}
return
}
sc := win.SystemWindow.Screen()
pos := win.SystemWindow.Position(sc)
if TheApp.Platform() == system.Windows && pos.X == -32000 || pos.Y == -32000 { // windows badness
if DebugSettings.WindowGeometryTrace {
log.Printf("WindowGeometry: Record: NOT storing very negative pos: %v for win: %v\n", pos, win.name)
}
return
}
ws.mu.Lock()
if ws.settingNoSave {
if DebugSettings.WindowGeometryTrace {
log.Printf("WindowGeometry: Record: SettingNoSave so NOT storing for win: %v\n", win.name)
}
ws.mu.Unlock()
return
}
ws.init()
cfg := screenConfig()
winName := ws.windowName(win.title)
wgr := windowGeometry{DPI: win.logicalDPI(), DPR: sc.DevicePixelRatio, Max: win.SystemWindow.Is(system.Maximized)}
wgr.Pos = pos
wgr.Size = wsz
// first get copy of stored data
sgs := ws.geometries.Data[cfg]
if sgs == nil {
sgs = make(map[string]windowGeometries)
}
var wgs windowGeometries
if swgs, ok := sgs[winName]; ok {
wgs.Last = swgs.Last
wgs.Screens = maps.Clone(swgs.Screens)
} else {
wgs.Screens = make(map[string]windowGeometry)
}
// then look for current cache data
sgsc := ws.cache[cfg]
if sgsc == nil {
sgsc = make(map[string]windowGeometries)
}
wgsc, hasCache := sgsc[winName]
if hasCache {
wgs.Last = wgsc.Last
maps.Copy(wgs.Screens, wgsc.Screens)
}
wgs.Screens[sc.Name] = wgr
wgs.Last = sc.Name
sgsc[winName] = wgs
ws.cache[cfg] = sgsc
if DebugSettings.WindowGeometryTrace {
log.Printf("WindowGeometry: Record win: %q screen: %q cfg: %q geom: %s", winName, sc.Name, cfg, wgr.String())
}
if ws.saveTimer == nil {
ws.saveTimer = time.AfterFunc(time.Duration(ws.saveDelay), func() {
ws.mu.Lock()
ws.saveCached()
ws.saveTimer = nil
ws.mu.Unlock()
})
}
ws.mu.Unlock()
}
// saveCached saves the cached prefs -- called after timer delay,
// under the Mu.Lock. The file is locked while it is saved, after reading
// the changes of other apps, which the cached geometries are merged into.
func (ws *windowGeometrySaver) saveCached() {
if DebugSettings.WindowGeometryTrace {
log.Println("WindowGeometry: saveCached")
}
errors.Log(ws.geometries.Update(func(geoms *screenConfigGeometries) {
if *geoms == nil {
*geoms = make(screenConfigGeometries)
}
for cfg, sgsc := range ws.cache {
for winName, wgs := range sgsc {
sg := (*geoms)[cfg]
if sg == nil {
sg = make(map[string]windowGeometries)
}
sg[winName] = wgs
(*geoms)[cfg] = sg
}
}
}))
ws.resetCache()
}
// get returns saved geometry for given window name, returning
// nil if there is no saved info. The last saved screen is used
// if it is currently available (connected); otherwise the given screen
// name is used if non-empty; otherwise the default screen 0 is used.
// If no saved info is found for any active screen, nil is returned.
// The screen used for the preferences is returned, and should be used
// to set the screen for a new window.
// If the window name has a colon, only the part prior to the colon is used.
func (ws *windowGeometrySaver) get(winName, screenName string) (*windowGeometry, *system.Screen) {
if !ws.shouldSave() {
return nil, nil
}
ws.mu.RLock()
defer ws.mu.RUnlock()
cfg := screenConfig()
winName = ws.windowName(winName)
var wgs windowGeometries
fromMain := false
sgs := ws.cache[cfg]
ok := false
if sgs != nil {
wgs, ok = sgs[winName]
}
if !ok {
sgs, ok = ws.geometries.Data[cfg]
if !ok {
return nil, nil
}
wgs, ok = sgs[winName]
fromMain = true
}
if !ok {
return nil, nil
}
wgr, sc := wgs.getForScreen(screenName)
if wgr != nil {
wgr.constrainGeom(sc)
if DebugSettings.WindowGeometryTrace {
log.Printf("WindowGeometry: Got geom for window: %q screen: %q lastScreen: %q cfg: %q geom: %s fromMain: %v\n", winName, sc.Name, wgs.Last, cfg, wgr.String(), fromMain)
}
return wgr, sc
}
return nil, nil
}
// deleteAll deletes the file that saves the position and size of each window,
// by screen, and clear current in-memory cache. You shouldn't need to use
// this but sometimes useful for testing.
func (ws *windowGeometrySaver) deleteAll() {
ws.mu.Lock()
defer ws.mu.Unlock()
ws.init()
errors.Log(os.Remove(ws.geometries.Path))
ws.geometries.Data = nil
}
// restoreAll restores size and position of all windows, for current screen.
// Called when screen changes.
func (ws *windowGeometrySaver) restoreAll() {
if !ws.shouldSave() {
return
}
renderWindowGlobalMu.Lock()
defer renderWindowGlobalMu.Unlock()
if DebugSettings.WindowGeometryTrace {
log.Printf("WindowGeometry: RestoreAll: starting\n")
}
ws.settingStart()
for _, w := range AllRenderWindows {
wgp, sc := ws.get(w.title, "")
if wgp != nil && !w.SystemWindow.Is(system.Fullscreen) {
if DebugSettings.WindowGeometryTrace {
log.Printf("WindowGeometry: RestoreAll: restoring geom for window: %v screen: %s geom: %s\n", w.name, sc.Name, wgp.String())
}
w.SystemWindow.SetGeometry(false, wgp.Pos, wgp.Size, sc)
}
}
ws.settingEnd()
if DebugSettings.WindowGeometryTrace {
log.Printf("WindowGeometry: RestoreAll: done\n")
}
}
// windowGeometries holds the window geometries for a given window
// across different screens, and the last screen used.
type windowGeometries struct {
Last string // Last screen
Screens map[string]windowGeometry // Screen map
}
// getForScreen returns saved geometry for an active (connected) Screen,
// searching in order of: last screen saved, given screen name, and then
// going through the list of available screens in order.
// returns nil if no saved geometry info is available for any active screen.
func (wgs *windowGeometries) getForScreen(screenName string) (*windowGeometry, *system.Screen) {
sc := TheApp.ScreenByName(wgs.Last)
if sc != nil {
// (only a saved geometry: a zero one would make the window empty)
if wgr, ok := wgs.Screens[wgs.Last]; ok {
return &wgr, sc
}
}
sc = TheApp.ScreenByName(screenName)
if sc != nil {
if wgr, ok := wgs.Screens[screenName]; ok {
return &wgr, sc
}
}
ns := TheApp.NScreens()
for i := range ns {
sc = TheApp.Screen(i)
if wgr, ok := wgs.Screens[sc.Name]; ok {
return &wgr, sc
}
}
return nil, nil
}
// windowGeometry records the geometry settings used for
// a certain screen and window pair.
type windowGeometry struct {
DPI float32
DPR float32 // Device Pixel Ratio
Size image.Point
Pos image.Point
Max bool // Maximized
}
func (wg *windowGeometry) String() string {
return fmt.Sprintf("DPI: %g DPR: %g Size: %v Pos: %v Max: %v", wg.DPI, wg.DPR, wg.Size, wg.Pos, wg.Max)
}
// constrainGeom constrains geometry based on screen params
func (wg *windowGeometry) constrainGeom(sc *system.Screen) {
wg.Pos, wg.Size = sc.ConstrainWindowGeometry(wg.Pos, wg.Size)
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"fmt"
"reflect"
"slices"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/system"
)
// renderWindowList is a list of [renderWindow]s.
type renderWindowList []*renderWindow
// add adds a window to the list.
func (wl *renderWindowList) add(w *renderWindow) {
renderWindowGlobalMu.Lock()
*wl = append(*wl, w)
renderWindowGlobalMu.Unlock()
}
// delete removes a window from the list.
func (wl *renderWindowList) delete(w *renderWindow) {
renderWindowGlobalMu.Lock()
defer renderWindowGlobalMu.Unlock()
*wl = slices.DeleteFunc(*wl, func(rw *renderWindow) bool {
return rw == w
})
}
// windows returns a copy of the list, which can be used without
// the lock that protects the list.
func (wl *renderWindowList) windows() []*renderWindow {
renderWindowGlobalMu.Lock()
defer renderWindowGlobalMu.Unlock()
return slices.Clone(*wl)
}
// Len returns the number of windows in the list.
func (wl *renderWindowList) Len() int {
renderWindowGlobalMu.Lock()
defer renderWindowGlobalMu.Unlock()
return len(*wl)
}
// last returns the last window of the list, or nil if it is empty.
func (wl *renderWindowList) last() *renderWindow {
renderWindowGlobalMu.Lock()
defer renderWindowGlobalMu.Unlock()
if len(*wl) == 0 {
return nil
}
return (*wl)[len(*wl)-1]
}
// moveToEnd moves the given window to the end of the list,
// if it is not already the last one.
func (wl *renderWindowList) moveToEnd(w *renderWindow) {
renderWindowGlobalMu.Lock()
defer renderWindowGlobalMu.Unlock()
if len(*wl) == 0 || (*wl)[len(*wl)-1] == w {
return
}
*wl = slices.DeleteFunc(*wl, func(rw *renderWindow) bool {
return rw == w
})
*wl = append(*wl, w)
}
// FindName finds the window with the given name or title
// on the list (case sensitive).
// It returns the window if found and nil otherwise.
func (wl *renderWindowList) FindName(name string) *renderWindow {
renderWindowGlobalMu.Lock()
defer renderWindowGlobalMu.Unlock()
for _, w := range *wl {
if w.name == name || w.title == name {
return w
}
}
return nil
}
// findData finds window with given Data on list -- returns
// window and true if found, nil, false otherwise.
// data of type string works fine -- does equality comparison on string contents.
func (wl *renderWindowList) findData(data any) (*renderWindow, bool) {
if reflectx.IsNil(reflect.ValueOf(data)) {
return nil, false
}
typ := reflect.TypeOf(data)
if !typ.Comparable() {
fmt.Printf("programmer error in RenderWinList.FindData: Scene.Data type %s not comparable (value: %v)\n", typ.String(), data)
return nil, false
}
renderWindowGlobalMu.Lock()
defer renderWindowGlobalMu.Unlock()
for _, wi := range *wl {
msc := wi.MainScene()
if msc == nil {
continue
}
if msc.Data == data {
return wi, true
}
}
return nil, false
}
// focused returns the (first) window in this list that has the WinGotFocus flag set
// and the index in the list (nil, -1 if not present)
func (wl *renderWindowList) focused() (*renderWindow, int) {
renderWindowGlobalMu.Lock()
defer renderWindowGlobalMu.Unlock()
for i, fw := range *wl {
if fw.flags.HasFlag(winGotFocus) {
return fw, i
}
}
return nil, -1
}
// focusNext focuses on the next window in the list, after the current Focused() one.
// It skips minimized windows.
func (wl *renderWindowList) focusNext() (*renderWindow, int) {
fw, i := wl.focused()
if fw == nil {
return nil, -1
}
renderWindowGlobalMu.Lock()
defer renderWindowGlobalMu.Unlock()
sz := len(*wl)
if sz == 1 {
return nil, -1
}
for j := 0; j < sz-1; j++ {
if i == sz-1 {
i = 0
} else {
i++
}
fw = (*wl)[i]
if !fw.SystemWindow.Is(system.Minimized) {
fw.SystemWindow.Raise()
break
}
}
return fw, i
}
// AllRenderWindows is the list of all [renderWindow]s that have been created
// (dialogs, main windows, etc).
var AllRenderWindows renderWindowList
// dialogRenderWindows is the list of only dialog [renderWindow]s that
// have been created.
var dialogRenderWindows renderWindowList
// mainRenderWindows is the list of main [renderWindow]s (non-dialogs) that
// have been created.
var mainRenderWindows renderWindowList
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"os"
"path/filepath"
"strings"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/system"
"golang.org/x/term"
)
// SetWorkingDir sets the current working directory of the app to the
// given directory, or the directory of the given file, and saves it, so
// that it is restored when the app is started again (see
// [restoreWorkingDir]), and the [FilePicker] starts in it. Apps call it
// when a project or document level file is opened or saved under a new
// name (Save As), with the name of that file. Errors are logged. It does
// nothing on the web and offscreen platforms, where there is no working
// directory to keep (or tests must keep theirs).
func SetWorkingDir(path string) {
if p := TheApp.Platform(); p == system.Web || p == system.Offscreen || path == "" {
return
}
errors.Log(setWorkingDir(path, workingDirFile()))
}
// setWorkingDir changes to the given directory, or the directory of the
// given file, and saves it in the given file.
func setWorkingDir(path, file string) error {
dir, err := filepath.Abs(path)
if err != nil {
return err
}
if st, err := os.Stat(dir); err != nil || !st.IsDir() {
dir = filepath.Dir(dir)
}
if err := os.Chdir(dir); err != nil {
return err
}
return os.WriteFile(file, []byte(dir+"\n"), 0666)
}
// workingDirFile returns the file in which the working directory of the
// app is saved.
func workingDirFile() string {
return filepath.Join(TheApp.AppDataDir(), "working-directory")
}
// restoreWorkingDir restores the working directory saved by
// [SetWorkingDir] on desktop platforms, if the app was not started from a
// terminal, as from the Finder, the dock, or a desktop launcher, where the
// working directory is the root, or within the app bundle, and of no use.
// If none is saved, or it no longer exists, it is the home directory.
// When started from a terminal, the working directory of the shell is kept.
func restoreWorkingDir() {
switch TheApp.Platform() {
case system.MacOS, system.Linux, system.Windows:
default:
return
}
if startedFromTerminal() {
return
}
errors.Log(chdirSaved(workingDirFile()))
}
// chdirSaved changes to the directory saved in the given file,
// or the home directory if there is none or it does not exist.
func chdirSaved(file string) error {
if b, err := os.ReadFile(file); err == nil {
dir := strings.TrimSpace(string(b))
if st, err := os.Stat(dir); err == nil && st.IsDir() {
return os.Chdir(dir)
}
}
home, err := os.UserHomeDir()
if err != nil {
return err
}
return os.Chdir(home)
}
// startedFromTerminal returns whether the app was started from a terminal,
// as its standard input is one (not /dev/null, as from the Finder).
func startedFromTerminal() bool {
return term.IsTerminal(int(os.Stdin.Fd()))
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package cursorimg provides the cached rendering of SVG cursors to images.
package cursorimg
import (
"bytes"
"fmt"
"image"
"image/draw"
_ "image/png"
"sync"
"cogentcore.org/core/colors"
"cogentcore.org/core/colors/gradient"
"cogentcore.org/core/cursors"
"cogentcore.org/core/enums"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint/pimage"
"cogentcore.org/core/svg"
)
// Cursor represents a cached rendered cursor, with the [image.Image]
// of the cursor and its hotspot.
type Cursor struct {
// The cached image of the cursor.
Image image.Image
// The size of the cursor.
Size int
// The hotspot is expressed in terms of raw cursor pixels.
Hotspot image.Point
}
// Cursors contains all of the cached rendered cursors, specified first
// by cursor enum and then by size.
// It is used by different goroutines under a mutex, so it must only be
// cleared with [ClearCache].
var Cursors = map[enums.Enum]map[int]*Cursor{}
// cursorsMu protects [Cursors].
var cursorsMu sync.Mutex
// ClearCache clears [Cursors], as is needed when the colors of the color
// scheme that they use have changed.
func ClearCache() {
cursorsMu.Lock()
defer cursorsMu.Unlock()
clear(Cursors)
}
// NumCached returns the number of cursor types in [Cursors], which is
// 0 after [ClearCache].
func NumCached() int {
cursorsMu.Lock()
defer cursorsMu.Unlock()
return len(Cursors)
}
// Get returns the cursor object corresponding to the given cursor enum,
// with the given size. If it is not already cached in [Cursors], it renders and caches it.
//
// It automatically replaces literal colors in svg with appropriate scheme colors as follows:
// - #fff: [colors.Palette].Neutral.ToneUniform(100)
// - #000: [colors.Palette].Neutral.ToneUniform(0)
// - #f00: [colors.Scheme].Error.Base
// - #0f0: [colors.Scheme].Success.Base
// - #ff0: [colors.Scheme].Warn.Base
func Get(cursor enums.Enum, size int) (*Cursor, error) {
cursorsMu.Lock()
defer cursorsMu.Unlock()
sm := Cursors[cursor]
if sm == nil {
sm = map[int]*Cursor{}
Cursors[cursor] = sm
}
if c, ok := sm[size]; ok {
return c, nil
}
name := cursor.String()
hot, ok := cursors.Hotspots[cursor]
if !ok {
hot = image.Pt(128, 128)
}
sv := svg.NewSVG(math32.Vec2(float32(size), float32(size)))
b, err := cursors.SVG(name)
if err != nil {
return nil, err
}
err = sv.ReadXML(bytes.NewReader(b))
if err != nil {
return nil, fmt.Errorf("error opening SVG file for cursor %q: %w", name, err)
}
img := sv.RenderImage()
blurRadius := size / 16
bounds := img.Bounds()
// We need to add extra space so that the shadow doesn't get clipped.
bounds.Max = bounds.Max.Add(image.Pt(blurRadius, blurRadius))
shadow := image.NewRGBA(bounds)
draw.DrawMask(shadow, shadow.Bounds(), gradient.ApplyOpacity(colors.Scheme.Shadow, 0.25), image.Point{}, img, image.Point{}, draw.Src)
shadow = pimage.GaussianBlur(shadow, float64(blurRadius))
draw.Draw(shadow, shadow.Bounds(), img, image.Point{}, draw.Over)
c := &Cursor{
Image: shadow,
Size: size,
Hotspot: hot.Mul(size).Div(256),
}
sm[size] = c
return c, nil
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cursors
import (
"bytes"
"fmt"
"image"
"io/fs"
"cogentcore.org/core/colors"
)
// SVG reads the cursor with the given name and returns a byte slice of SVG data.
// This is mainly used by [cogentcore.org/core/cursors/cursorimg], but is also used
// by the docs in an example. This function performs color replacement as described
// in [cogentcore.org/core/cursors/cursorimg.Get].
func SVG(name string) ([]byte, error) {
b, err := fs.ReadFile(Cursors, "svg/"+name+".svg")
if err != nil {
return nil, err
}
b = replaceColors(b)
return b, nil
}
// replaceColors replaces literal cursor colors in the given SVG with scheme colors.
func replaceColors(b []byte) []byte {
m := map[string]image.Image{
"#fff": colors.Palette.Neutral.ToneUniform(100),
"#000": colors.Palette.Neutral.ToneUniform(0),
"#f00": colors.Scheme.Error.Base,
"#0f0": colors.Scheme.Success.Base,
"#ff0": colors.Scheme.Warn.Base,
}
for old, clr := range m {
b = bytes.ReplaceAll(b, fmt.Appendf(nil, "%q", old), fmt.Appendf(nil, "%q", colors.AsHex(colors.ToUniform(clr))))
}
return b
}
// Copyright 2024 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Command docs provides documentation of Cogent Core,
// hosted at https://cogentcore.org/core.
package main
import (
"embed"
"io/fs"
"os"
"path/filepath"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/colors"
"cogentcore.org/core/content"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/htmlcore"
"cogentcore.org/core/icons"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/highlighting"
"cogentcore.org/core/text/highlighting/lexers"
"cogentcore.org/core/text/textcore"
"cogentcore.org/core/tree"
)
//go:embed content
var econtent embed.FS
//go:embed *.svg name.png weld-icon.png
var resources embed.FS
//go:embed image.png
var myImage embed.FS
//go:embed icon.svg
var mySVG embed.FS
//go:embed file.go
var myFile embed.FS
//go:embed icon.svg
var icon string
const defaultPlaygroundCode = `package main
func main() {
b := core.NewBody()
core.NewButton(b).SetText("Hello, World!")
b.RunMainWindow()
}`
func main() {
core.AppIcon = icon
b := core.NewBody("Cogent Core Docs")
highlighting.AddLexers(lexers.Bash, lexers.TOML)
ct := content.NewContent(b).SetContent(econtent)
ctx := ct.Context
content.OfflineURL = "https://cogentcore.org/core"
ctx.AddWikilinkHandler(htmlcore.GoDocWikilink("doc", "cogentcore.org/core"))
b.AddTopBar(func(bar *core.Frame) {
tb := core.NewToolbar(bar)
tb.Maker(ct.MakeToolbar)
tb.Maker(func(p *tree.Plan) {
tree.Add(p, func(w *core.Button) {
ctx.LinkButton(w, "playground")
w.SetText("Playground").SetIcon(icons.PlayCircle)
})
tree.Add(p, func(w *core.Button) {
ctx.LinkButton(w, "https://youtube.com/@CogentCore")
w.SetText("Videos").SetIcon(icons.VideoLibrary)
})
tree.Add(p, func(w *core.Button) {
ctx.LinkButton(w, "https://cogentcore.org/blog")
w.SetText("Blog").SetIcon(icons.RssFeed)
})
tree.Add(p, func(w *core.Button) {
ctx.LinkButton(w, "https://github.com/cogentcore/core")
w.SetText("GitHub").SetIcon(icons.GitHub)
})
tree.Add(p, func(w *core.Button) {
ctx.LinkButton(w, "https://cogentcore.org")
w.SetText("CogentCore.org").SetIcon(icons.CogentCore)
})
tree.Add(p, func(w *core.Button) {
ctx.LinkButton(w, "https://cogentcore.org/community")
w.SetText("Community").SetIcon(icons.Forum)
})
tree.Add(p, func(w *core.Button) {
ctx.LinkButton(w, "https://github.com/sponsors/cogentcore")
w.SetText("Sponsor").SetIcon(icons.Favorite)
})
})
})
// for the interpreter (interp.go), when code is edited
content.CodeSymbols["econtent"] = econtent
content.CodeSymbols["myImage"] = myImage
content.CodeSymbols["mySVG"] = mySVG
content.CodeSymbols["myFile"] = myFile
ctx.AddElementHandler("home-page", homePage)
ctx.AddElementHandler("core-playground", func(ctx *htmlcore.Context) bool {
splits := core.NewSplits(ctx.BlockParent())
ed := textcore.NewEditor(splits)
playgroundFile := filepath.Join(core.TheApp.AppDataDir(), "playground.go")
err := ed.Lines.Open(playgroundFile)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
err := os.WriteFile(playgroundFile, []byte(defaultPlaygroundCode), 0666)
core.ErrorSnackbar(ed, err, "Error creating code file")
if err == nil {
err := ed.Lines.Open(playgroundFile)
core.ErrorSnackbar(ed, err, "Error loading code")
}
} else {
core.ErrorSnackbar(ed, err, "Error loading code")
}
}
ed.OnChange(func(e events.Event) {
core.ErrorSnackbar(ed, ed.SaveQuiet(), "Error saving code")
})
parent := core.NewFrame(splits)
content.BindCode(ed, parent, "Go")
return true
})
ctx.AddElementHandler("style-demo", func(ctx *htmlcore.Context) bool {
// same as demo styles tab
sp := core.NewSplits(ctx.BlockParent())
sp.Styler(func(s *styles.Style) {
s.Min.Y.Em(40)
})
fm := core.NewForm(sp)
fr := core.NewFrame(core.NewFrame(sp)) // can not control layout when directly in splits
fr.Styler(func(s *styles.Style) {
s.Background = colors.Scheme.Select.Container
s.Grow.Set(1, 1)
})
fr.Style() // must style immediately to get correct default values
fm.SetStruct(&fr.Styles)
fm.OnChange(func(e events.Event) {
fr.OverrideStyle = true
fr.Update()
})
frameSizes := []math32.Vector2{
{X: 20, Y: 100},
{X: 80, Y: 20},
{X: 60, Y: 80},
{X: 40, Y: 120},
{X: 150, Y: 100},
}
for _, sz := range frameSizes {
core.NewFrame(fr).Styler(func(s *styles.Style) {
s.Min.Set(units.Dp(sz.X), units.Dp(sz.Y))
s.Background = colors.Scheme.Primary.Base
})
}
return true
})
b.RunMainWindow()
}
func homePage(ctx *htmlcore.Context) bool {
home := core.NewFrame(ctx.BlockParent())
home.Styler(func(s *styles.Style) {
s.Direction = styles.Column
s.Grow.Set(1, 1)
s.CenterAll()
})
home.OnShow(func(e events.Event) {
home.Update() // TODO: temporary workaround for #1037
})
tree.AddChild(home, func(w *core.SVG) {
errors.Log(w.ReadString(core.AppIcon))
})
tree.AddChild(home, func(w *core.Image) {
errors.Log(w.OpenFS(resources, "name.png"))
w.Styler(func(s *styles.Style) {
s.Min.X.SetCustom(func(uc *units.Context) float32 {
return min(uc.Dp(612), uc.Vw(80))
})
})
})
tree.AddChild(home, func(w *core.Text) {
w.SetType(core.TextHeadlineMedium).SetText("Interactive documentation for Cogent Core, built using the framework and deployed with WebAssembly")
})
tree.AddChild(home, func(w *core.Frame) {
tree.AddChild(w, func(w *core.Button) {
ctx.LinkButton(w, "basics")
w.SetText("Get started")
})
tree.AddChild(w, func(w *core.Button) {
ctx.LinkButton(w, "install")
w.SetText("Install").SetType(core.ButtonTonal)
})
})
return true
}
// Copyright 2024 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import "fmt"
// ExampleFile is the function of this example file, which the docs of the
// text editor open.
func ExampleFile() {
fmt.Println("This is an example file.")
}
// Copyright 2026 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !nointerp
package main
import (
"cogentcore.org/core/content"
"cogentcore.org/core/mvmcore"
)
// The code blocks of the docs are compiled into the app (contentcode_gen.go).
// The mvm interpreter runs code that users edit, except with the nointerp
// tag. In js builds, mvmcore.BindTextEditor is a deferred function (see
// core.toml): mvm is loaded when code is first edited.
func init() {
content.BindTextEditor = mvmcore.BindTextEditor
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package main provides the actual command line
// implementation of the enumgen library.
package main
import (
"cogentcore.org/core/cli"
"cogentcore.org/core/enums/enumgen"
)
func main() {
opts := cli.DefaultOptions("Enumgen", "Enumgen generates helpful methods for Go enums.")
opts.DefaultFiles = []string{"enumgen.toml"}
cli.Run(opts, &enumgen.Config{}, enumgen.Generate)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on http://github.com/dmarkham/enumer and
// golang.org/x/tools/cmd/stringer:
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package enumgen
import "text/template"
// BuildBitFlagMethods builds methods specific to bit flag types.
func (g *Generator) BuildBitFlagMethods(runs []Value, typ *Type) {
g.Printf("\n")
g.ExecTmpl(HasFlagMethodTmpl, typ)
g.ExecTmpl(SetFlagMethodTmpl, typ)
}
// The HasFlag and SetFlag methods use the bit index of a flag of the
// same type directly when [enums.FlagTypeAssert] is true (in JavaScript),
// instead of calling its Int64 method through the [enums.BitFlag] interface.
// Atomic bit flags use [sync/atomic] functions on their underlying int32
// or int64 value.
var HasFlagMethodTmpl = template.Must(template.New("HasFlagMethod").Parse(
`// HasFlag returns whether these bit flags have the given bit flag set.
func (i *{{.Name}}) HasFlag(f enums.BitFlag) bool {
if enums.FlagTypeAssert {
if b, ok := f.({{.Name}}); ok {
return {{template "value" .}}&(1<<uint32(b)) != 0
}
}
return {{template "value" .}}&(1<<uint32(f.Int64())) != 0
}
{{- define "value"}}{{if .Config.Atomic}}atomic.Load{{.AtomicType}}((*{{.Underlying}})(i)){{else}}*i{{end}}{{end}}
`))
var SetFlagMethodTmpl = template.Must(template.New("SetFlagMethod").Parse(
`// SetFlag sets the value of the given flags in these flags to the given value.
func (i *{{.Name}}) SetFlag(on bool, f ...enums.BitFlag) {
var mask {{if .Config.Atomic}}{{.Underlying}}{{else}}{{.Name}}{{end}}
for _, v := range f {
if enums.FlagTypeAssert {
if b, ok := v.({{.Name}}); ok {
mask |= 1 << uint32(b)
continue
}
}
mask |= 1 << v.Int64()
}
{{- if .Config.Atomic}}
if on {
atomic.Or{{.AtomicType}}((*{{.Underlying}})(i), mask)
} else {
atomic.And{{.AtomicType}}((*{{.Underlying}})(i), ^mask)
}
{{- else}}
if on {
*i |= mask
} else {
*i &^= mask
}
{{- end}}
}
`))
var StringMethodBitFlagTmpl = template.Must(template.New("StringMethodBitFlag").Parse(
`// String returns the string representation of this {{.Name}} value.
func (i {{.Name}}) String() string {
{{- if eq .Extends ""}} return enums.BitFlagString(i, _{{.Name}}Values)
{{- else}} return enums.BitFlagStringExtended(i, _{{.Name}}Values, {{.Extends}}Values()) {{end}} }
`))
var SetStringMethodBitFlagTmpl = template.Must(template.New("SetStringMethodBitFlag").Parse(
`// SetString sets the {{.Name}} value from its string representation,
// and returns an error if the string is invalid.
func (i *{{.Name}}) SetString(s string) error { *i = 0; return i.SetStringOr(s) }
`))
var SetStringOrMethodBitFlagTmpl = template.Must(template.New("SetStringOrMethodBitFlag").Parse(
`// SetStringOr sets the {{.Name}} value from its string representation
// while preserving any bit flags already set, and returns an
// error if the string is invalid.
func (i *{{.Name}}) SetStringOr(s string) error {
{{- if eq .Extends ""}} return enums.SetStringOr{{if .Config.AcceptLower}}Lower{{end}}(i, s, _{{.Name}}ValueMap, "{{.Name}}")
{{- else}} return enums.SetStringOr{{if .Config.AcceptLower}}Lower{{end}}Extended(i, (*{{.Extends}})(i), s, _{{.Name}}ValueMap) {{end}} }
`))
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package enumgen provides functions for generating
// enum methods for enum types.
package enumgen
//go:generate core generate
import (
"fmt"
"cogentcore.org/core/base/generate"
"cogentcore.org/core/base/logx"
"golang.org/x/tools/go/packages"
)
// ParsePackages parses the package(s) located in the configuration source directory.
func ParsePackages(cfg *Config) ([]*packages.Package, error) {
pcfg := &packages.Config{
Mode: PackageModes(),
// TODO: Need to think about constants in test files. Maybe write enumgen_test.go
// in a separate pass? For later.
Tests: false,
}
pkgs, err := generate.Load(pcfg, cfg.Dir)
if err != nil {
return nil, fmt.Errorf("enumgen: Generate: error parsing package: %w", err)
}
return pkgs, err
}
// Generate generates enum methods, using the
// configuration information, loading the packages from the
// configuration source directory, and writing the result
// to the configuration output file.
//
// It is a simple entry point to enumgen that does all
// of the steps; for more specific functionality, create
// a new [Generator] with [NewGenerator] and call methods on it.
//
//cli:cmd -root
func Generate(cfg *Config) error { //types:add
pkgs, err := ParsePackages(cfg)
if err != nil {
logx.PrintlnInfo(err)
return err
}
err = GeneratePkgs(cfg, pkgs)
logx.PrintlnInfo(err)
return err
}
// GeneratePkgs generates enum methods using
// the given configuration object and packages parsed
// from the configuration source directory,
// and writes the result to the config output file.
// It is a simple entry point to enumgen that does all
// of the steps; for more specific functionality, create
// a new [Generator] with [NewGenerator] and call methods on it.
func GeneratePkgs(cfg *Config, pkgs []*packages.Package) error {
g := NewGenerator(cfg, pkgs)
for _, pkg := range g.Pkgs {
g.Pkg = pkg
g.Buf.Reset()
err := g.FindEnumTypes()
if err != nil {
return fmt.Errorf("enumgen: Generate: error finding enum types for package %q: %w", pkg.Name, err)
}
g.PrintHeader()
has, err := g.Generate()
if !has {
continue
}
if err != nil {
return fmt.Errorf("enumgen: Generate: error generating code for package %q: %w", pkg.Name, err)
}
err = g.Write()
if err != nil {
return fmt.Errorf("enumgen: Generate: error writing code for package %q: %w", pkg.Name, err)
}
}
return nil
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on http://github.com/dmarkham/enumer and
// golang.org/x/tools/cmd/stringer:
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package enumgen
import (
"bytes"
"errors"
"fmt"
"go/ast"
"go/constant"
"go/token"
"go/types"
"html"
"log/slog"
"os"
"strings"
"text/template"
"cogentcore.org/core/base/generate"
"cogentcore.org/core/cli"
"golang.org/x/tools/go/packages"
)
// Generator holds the state of the generator.
// It is primarily used to buffer the output.
type Generator struct {
Config *Config // The configuration information
Buf bytes.Buffer // The accumulated output.
Pkgs []*packages.Package // The packages we are scanning.
Pkg *packages.Package // The packages we are currently on.
Types []*Type // The enum types
}
// NewGenerator returns a new generator with the
// given configuration information and parsed packages.
func NewGenerator(config *Config, pkgs []*packages.Package) *Generator {
return &Generator{Config: config, Pkgs: pkgs}
}
// PackageModes returns the package load modes needed for this generator
func PackageModes() packages.LoadMode {
return packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles | packages.NeedImports | packages.NeedTypes | packages.NeedTypesSizes | packages.NeedSyntax | packages.NeedTypesInfo
}
// Printf prints the formatted string to the
// accumulated output in [Generator.Buf]
func (g *Generator) Printf(format string, args ...any) {
fmt.Fprintf(&g.Buf, format, args...)
}
// PrintHeader prints the header and package clause
// to the accumulated output
func (g *Generator) PrintHeader() {
// we need a manual import of enums because it is
// external, but goimports will handle everything else
generate.PrintHeader(&g.Buf, g.Pkg.Name, "cogentcore.org/core/enums")
}
// FindEnumTypes goes through all of the types in the package
// and finds all integer (signed or unsigned) types labeled with enums:enum
// or enums:bitflag. It stores the resulting types in [Generator.Types].
func (g *Generator) FindEnumTypes() error {
g.Types = []*Type{}
return generate.Inspect(g.Pkg, g.InspectForType, "enumgen.go", "typegen.go")
}
// AllowedEnumTypes are the types that can be used for enums and bit flags,
// mapped to their number of bits (int and uint are counted as 32 bits,
// their minimum size, for the bit flag limits).
var AllowedEnumTypes = map[string]int64{"int": 32, "int64": 64, "int32": 32, "int16": 16, "int8": 8, "uint": 32, "uint64": 64, "uint32": 32, "uint16": 16, "uint8": 8}
// AllowedAtomicTypes are the types that can be used for bit flags
// with atomic operations (the -atomic flag).
var AllowedAtomicTypes = map[string]bool{"int64": true, "int32": true}
// InspectForType looks at the given AST node and adds it
// to [Generator.Types] if it is marked with an appropriate
// comment directive. It returns whether the AST inspector should
// continue, and an error if there is one. It should only
// be called in [ast.Inspect].
func (g *Generator) InspectForType(n ast.Node) (bool, error) {
ts, ok := n.(*ast.TypeSpec)
if !ok {
return true, nil
}
if ts.Comment == nil {
return true, nil
}
for _, c := range ts.Comment.List {
dir, err := cli.ParseDirective(c.Text)
if err != nil {
return false, fmt.Errorf("error parsing comment directive %q: %w", c.Text, err)
}
if dir == nil {
continue
}
if dir.Tool != "enums" {
continue
}
if dir.Directive != "enum" && dir.Directive != "bitflag" {
return false, fmt.Errorf("unrecognized enums directive %q (from %q)", dir.Directive, c.Text)
}
typnm := types.ExprString(ts.Type)
// ident, ok := ts.Type.(*ast.Ident)
// if !ok {
// return false, fmt.Errorf("type of enum type (%v) is %T, not *ast.Ident (try using a standard [un]signed integer type instead)", ts.Type, ts.Type)
// }
cfg := &Config{}
*cfg = *g.Config
leftovers, err := cli.SetFromArgs(cfg, dir.Args, cli.ErrNotFound)
if err != nil {
return false, fmt.Errorf("error setting config info from comment directive args: %w (from directive %q)", err, c.Text)
}
if len(leftovers) > 0 {
return false, fmt.Errorf("expected 0 positional arguments but got %d (list: %v) (from directive %q)", len(leftovers), leftovers, c.Text)
}
typ := g.Pkg.TypesInfo.Defs[ts.Name].Type()
utyp := typ.Underlying()
tt := &Type{Name: ts.Name.Name, Type: ts, Config: cfg, Underlying: utyp.String(), Bits: AllowedEnumTypes[utyp.String()]}
// if our direct type isn't the same as our underlying type, we are extending our direct type
if cfg.Extend && typnm != utyp.String() {
tt.Extends = typnm
}
switch dir.Directive {
case "enum":
if tt.Bits == 0 {
return false, fmt.Errorf("enum type %s is not allowed; try using a standard [un]signed integer type instead", typnm)
}
tt.IsBitFlag = false
case "bitflag":
if tt.Bits == 0 {
return false, fmt.Errorf("bit flag enum type %s is not allowed; try using a standard [un]signed integer type instead", typnm)
}
if cfg.Atomic && !AllowedAtomicTypes[tt.Underlying] {
return false, fmt.Errorf("atomic bit flag enum type %s is not allowed; atomic bit flag enums must be of type int32 or int64", typnm)
}
tt.IsBitFlag = true
}
g.Types = append(g.Types, tt)
}
return true, nil
}
// Generate produces the enum methods for the types
// stored in [Generator.Types] and stores them in
// [Generator.Buf]. It returns whether there were
// any enum types to generate methods for, and
// any error that occurred.
func (g *Generator) Generate() (bool, error) {
if len(g.Types) == 0 {
return false, nil
}
for _, typ := range g.Types {
values := make([]Value, 0, 100)
for _, file := range g.Pkg.Syntax {
if generate.ExcludeFile(g.Pkg, file, "enumgen.go", "typegen.go") {
continue
}
var terr error
ast.Inspect(file, func(n ast.Node) bool {
if terr != nil {
return false
}
vals, cont, err := g.GenDecl(n, file, typ)
if err != nil {
terr = err
} else {
values = append(values, vals...)
}
return cont
})
if terr != nil {
return true, fmt.Errorf("Generate: error parsing declaration clauses: %w", terr)
}
}
if len(values) == 0 {
return true, errors.New("no values defined for type " + typ.Name)
}
g.TrimValueNames(values, typ.Config)
err := g.TransformValueNames(values, typ.Config)
if err != nil {
return true, fmt.Errorf("error transforming value names: %w", err)
}
g.PrefixValueNames(values, typ.Config)
values = SortValues(values, typ)
g.BuildBasicMethods(values, typ)
if typ.IsBitFlag {
if typ.MaxValueP1 > typ.Bits {
return true, fmt.Errorf("bit flag type %s has bit index values up to %d, which do not fit in its %d-bit underlying type %s", typ.Name, typ.MaxValueP1-1, typ.Bits, typ.Underlying)
}
g.BuildBitFlagMethods(values, typ)
}
if typ.Config.Text {
g.BuildTextMethods(values, typ)
}
if typ.Config.SQL {
g.AddValueAndScanMethod(typ)
}
if typ.Config.GQL {
g.BuildGQLMethods(values, typ)
}
}
return true, nil
}
// GenDecl processes one declaration clause.
// It returns whether the AST inspector should continue,
// and an error if there is one. It should only be
// called in [ast.Inspect].
func (g *Generator) GenDecl(node ast.Node, file *ast.File, typ *Type) ([]Value, bool, error) {
decl, ok := node.(*ast.GenDecl)
if !ok || decl.Tok != token.CONST {
// We only care about const declarations.
return nil, true, nil
}
vals := []Value{}
// The name of the type of the constants we are declaring.
// Can change if this is a multi-element declaration.
typName := ""
// Loop over the elements of the declaration. Each element is a ValueSpec:
// a list of names possibly followed by a type, possibly followed by values.
// If the type and value are both missing, we carry down the type (and value,
// but the "go/types" package takes care of that).
for _, spec := range decl.Specs {
vspec := spec.(*ast.ValueSpec) // Guaranteed to succeed as this is CONST.
if vspec.Type == nil && len(vspec.Values) > 0 {
// "X = 1". With no type but a value, the constant is untyped.
// Skip this vspec and reset the remembered type.
typName = ""
continue
}
if vspec.Type != nil {
// "X T". We have a type. Remember it.
ident, ok := vspec.Type.(*ast.Ident)
if !ok {
continue
}
typName = ident.Name
}
if typName != typ.Name {
// This is not the type we're looking for.
continue
}
// We now have a list of names (from one line of source code) all being
// declared with the desired type.
// Grab their names and actual values and store them in f.values.
for _, n := range vspec.Names {
if n.Name == "_" {
continue
}
// This dance lets the type checker find the values for us. It's a
// bit tricky: look up the object declared by the n, find its
// types.Const, and extract its value.
obj, ok := g.Pkg.TypesInfo.Defs[n]
if !ok {
return nil, false, errors.New("no value for constant " + n.String())
}
info := obj.Type().Underlying().(*types.Basic).Info()
if info&types.IsInteger == 0 {
return nil, false, errors.New("can't handle non-integer constant type " + typName)
}
value := obj.(*types.Const).Val() // Guaranteed to succeed as this is CONST.
if value.Kind() != constant.Int {
return nil, false, errors.New("can't happen: constant is not an integer " + n.String())
}
i64, isInt := constant.Int64Val(value)
u64, isUint := constant.Uint64Val(value)
if !isInt && !isUint {
return nil, false, errors.New("internal error: value of " + n.String() + " is not an integer: " + value.String())
}
if !isUint {
i64 = int64(u64)
}
v := Value{
OriginalName: n.Name,
Name: n.Name,
Desc: html.EscapeString(strings.Join(strings.Fields(vspec.Doc.Text()), " ")), // need to collapse whitespace and escape
Value: i64,
Signed: info&types.IsUnsigned == 0,
Str: value.String(),
}
if c := vspec.Comment; typ.Config.LineComment && c != nil && len(c.List) == 1 {
v.Name = strings.TrimSpace(c.Text())
}
vals = append(vals, v)
}
}
return vals, false, nil
}
// ExecTmpl executes the given template with the given type and
// writes the result to [Generator.Buf]. It fatally logs any error.
// All enumgen templates take a [Type] as their data.
func (g *Generator) ExecTmpl(t *template.Template, typ *Type) {
err := t.Execute(&g.Buf, typ)
if err != nil {
slog.Error("programmer error: internal error: error executing template", "err", err)
os.Exit(1)
}
}
// Write formats the data in the the Generator's buffer
// ([Generator.Buf]) and writes it to the file specified by
// [Generator.Config.Output].
func (g *Generator) Write() error {
return generate.Write(generate.Filepath(g.Pkg, g.Config.Output), g.Buf.Bytes(), nil)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on http://github.com/dmarkham/enumer and
// golang.org/x/tools/cmd/stringer:
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package enumgen
import "text/template"
var GQLMethodsTmpl = template.Must(template.New("GQLMethods").Parse(`
// MarshalGQL implements the [graphql.Marshaler] interface.
func (i {{.Name}}) MarshalGQL(w io.Writer) { w.Write([]byte(strconv.Quote(i.String()))) }
// UnmarshalGQL implements the [graphql.Unmarshaler] interface.
func (i *{{.Name}}) UnmarshalGQL(value any) error { return enums.Scan(i, value, "{{.Name}}") }
`))
func (g *Generator) BuildGQLMethods(runs []Value, typ *Type) {
g.ExecTmpl(GQLMethodsTmpl, typ)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on http://github.com/dmarkham/enumer and
// golang.org/x/tools/cmd/stringer:
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package enumgen
import "text/template"
var TextMethodsTmpl = template.Must(template.New("TextMethods").Parse(
`
// MarshalText implements the [encoding.TextMarshaler] interface.
func (i {{.Name}}) MarshalText() ([]byte, error) { return []byte(i.String()), nil }
// UnmarshalText implements the [encoding.TextUnmarshaler] interface.
func (i *{{.Name}}) UnmarshalText(text []byte) error { return enums.UnmarshalText(i, text, "{{.Name}}") }
`))
func (g *Generator) BuildTextMethods(runs []Value, typ *Type) {
g.ExecTmpl(TextMethodsTmpl, typ)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on http://github.com/dmarkham/enumer and
// golang.org/x/tools/cmd/stringer:
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package enumgen
import (
"strings"
"text/template"
)
// BuildString builds the string function using a map access approach.
func (g *Generator) BuildString(values []Value, typ *Type) {
g.Printf("\n")
g.Printf("\nvar _%sMap = map[%s]string{", typ.Name, typ.Name)
n := 0
for _, value := range values {
g.Printf("%s: `%s`,", &value, value.Name)
n += len(value.Name)
}
g.Printf("}\n\n")
if typ.IsBitFlag {
g.ExecTmpl(StringMethodBitFlagTmpl, typ)
}
g.ExecTmpl(StringMethodMapTmpl, typ)
}
var StringMethodMapTmpl = template.Must(template.New("StringMethodMap").Parse(
`{{if .IsBitFlag}}
// BitIndexString returns the string representation of this {{.Name}} value
// if it is a bit index value (typically an enum constant), and
// not an actual bit flag value.
{{- else}}
// String returns the string representation of this {{.Name}} value.
{{- end}}
func (i {{.Name}}) {{if .IsBitFlag}} BitIndexString {{else}} String {{end}} () string { return enums.
{{- if eq .Extends ""}}String {{else -}} {{if .IsBitFlag -}} BitIndexStringExtended {{else -}} StringExtended {{- end}}[{{.Name}}, {{.Extends}}]{{- end}}(i, _{{.Name}}Map) }
`))
var NConstantTmpl = template.Must(template.New("StringNConstant").Parse(
`//{{.Name}}N is the highest valid value for type {{.Name}}, plus one.
const {{.Name}}N {{.Name}} = {{.MaxValueP1}}
`))
var NConstantTmplGosl = template.Must(template.New("StringNConstant").Parse(
`//gosl:start
//{{.Name}}N is the highest valid value for type {{.Name}}, plus one.
const {{.Name}}N {{.Name}} = {{.MaxValueP1}}
//gosl:end
`))
var SetStringMethodTmpl = template.Must(template.New("SetStringMethod").Parse(
`// SetString sets the {{.Name}} value from its string representation,
// and returns an error if the string is invalid.
func (i *{{.Name}}) SetString(s string) error {
{{- if eq .Extends ""}} return enums.SetString{{if .Config.AcceptLower}}Lower{{end}}(i, s, _{{.Name}}ValueMap, "{{.Name}}")
{{- else}} return enums.SetString{{if .Config.AcceptLower}}Lower{{end}}Extended(i, (*{{.Extends}})(i), s, _{{.Name}}ValueMap) {{end}} }
`))
var Int64MethodTmpl = template.Must(template.New("Int64Method").Parse(
`// Int64 returns the {{.Name}} value as an int64.
func (i {{.Name}}) Int64() int64 { return int64(i) }
`))
var SetInt64MethodTmpl = template.Must(template.New("SetInt64Method").Parse(
`// SetInt64 sets the {{.Name}} value from an int64.
func (i *{{.Name}}) SetInt64(in int64) { *i = {{.Name}}(in) }
`))
var DescMethodTmpl = template.Must(template.New("DescMethod").Parse(`// Desc returns the description of the {{.Name}} value.
func (i {{.Name}}) Desc() string {
{{- if eq .Extends ""}} return enums.Desc(i, _{{.Name}}DescMap)
{{- else}} return enums.DescExtended[{{.Name}}, {{.Extends}}](i, _{{.Name}}DescMap) {{end}} }
`))
var ValuesGlobalTmpl = template.Must(template.New("ValuesGlobal").Parse(
`// {{.Name}}Values returns all possible values for the type {{.Name}}.
func {{.Name}}Values() []{{.Name}} {
{{- if eq .Extends ""}} return _{{.Name}}Values
{{- else}} return enums.ValuesGlobalExtended(_{{.Name}}Values, {{.Extends}}Values())
{{- end}} }
`))
var ValuesMethodTmpl = template.Must(template.New("ValuesMethod").Parse(
`// Values returns all possible values for the type {{.Name}}.
func (i {{.Name}}) Values() []enums.Enum {
{{- if eq .Extends ""}} return enums.Values(_{{.Name}}Values)
{{- else}} return enums.ValuesExtended(_{{.Name}}Values, {{.Extends}}Values())
{{- end}} }
`))
var IsValidMethodMapTmpl = template.Must(template.New("IsValidMethodMap").Parse(
`// IsValid returns whether the value is a valid option for type {{.Name}}.
func (i {{.Name}}) IsValid() bool { _, ok := _{{.Name}}Map[i]; return ok
{{- if ne .Extends ""}} || {{.Extends}}(i).IsValid() {{end}} }
`))
// BuildBasicMethods builds methods common to all types, like Desc and SetString.
func (g *Generator) BuildBasicMethods(values []Value, typ *Type) {
// Print the slice of values
max := int64(0)
g.Printf("\nvar _%sValues = []%s{", typ.Name, typ.Name)
for _, value := range values {
g.Printf("%s, ", &value)
if value.Value > max {
max = value.Value
}
}
g.Printf("}\n\n")
typ.MaxValueP1 = max + 1
if g.Config.Gosl {
g.ExecTmpl(NConstantTmplGosl, typ)
} else {
g.ExecTmpl(NConstantTmpl, typ)
}
// Print the map between name and value
g.PrintValueMap(values, typ)
// Print the map of values to descriptions
g.PrintDescMap(values, typ)
g.BuildString(values, typ)
// Print the basic extra methods
if typ.IsBitFlag {
g.ExecTmpl(SetStringMethodBitFlagTmpl, typ)
g.ExecTmpl(SetStringOrMethodBitFlagTmpl, typ)
} else {
g.ExecTmpl(SetStringMethodTmpl, typ)
}
g.ExecTmpl(Int64MethodTmpl, typ)
g.ExecTmpl(SetInt64MethodTmpl, typ)
g.ExecTmpl(DescMethodTmpl, typ)
g.ExecTmpl(ValuesGlobalTmpl, typ)
g.ExecTmpl(ValuesMethodTmpl, typ)
if typ.Config.IsValid {
g.ExecTmpl(IsValidMethodMapTmpl, typ)
}
}
// PrintValueMap prints the map between name and value
func (g *Generator) PrintValueMap(values []Value, typ *Type) {
g.Printf("\nvar _%sValueMap = map[string]%s{", typ.Name, typ.Name)
for _, value := range values {
g.Printf("`%s`: %s,", value.Name, &value)
if typ.Config.AcceptLower {
l := strings.ToLower(value.Name)
if l != value.Name { // avoid duplicate keys
g.Printf("`%s`: %s,", l, &value)
}
}
}
g.Printf("}\n\n")
}
// PrintDescMap prints the map of values to descriptions
func (g *Generator) PrintDescMap(values []Value, typ *Type) {
g.Printf("\n")
g.Printf("\nvar _%sDescMap = map[%s]string{", typ.Name, typ.Name)
i := 0
for _, value := range values {
g.Printf("%s: `%s`,", &value, value.Desc)
i++
}
g.Printf("}\n\n")
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on http://github.com/dmarkham/enumer and
// golang.org/x/tools/cmd/stringer:
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package enumgen
import "text/template"
var ValueMethodTmpl = template.Must(template.New("ValueMethod").Parse(
`// Value implements the [driver.Valuer] interface.
func (i {{.Name}}) Value() (driver.Value, error) { return i.String(), nil }
`))
var ScanMethodTmpl = template.Must(template.New("ScanMethod").Parse(
`// Scan implements the [sql.Scanner] interface.
func (i *{{.Name}}) Scan(value any) error { return enums.Scan(i, value, "{{.Name}}") }
`))
func (g *Generator) AddValueAndScanMethod(typ *Type) {
g.Printf("\n")
g.ExecTmpl(ValueMethodTmpl, typ)
g.Printf("\n\n")
g.ExecTmpl(ScanMethodTmpl, typ)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on http://github.com/dmarkham/enumer and
// golang.org/x/tools/cmd/stringer:
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package enumgen
import (
"fmt"
"go/ast"
"slices"
"sort"
"strings"
"unicode"
"unicode/utf8"
"cogentcore.org/core/base/strcase"
)
// Type represents a parsed enum type.
type Type struct {
Name string // The name of the type
Type *ast.TypeSpec // The standard AST type value
IsBitFlag bool // Whether the type is a bit flag type
Underlying string // The underlying integer type of the type (int64, int32, etc)
Bits int64 // The number of bits in the underlying integer type
Extends string // The type that this type extends, if any ("" if it doesn't extend)
MaxValueP1 int64 // the highest defined value for the type, plus one
Config *Config // Configuration information set in the comment directive for the type; is initialized to generator config info first
}
// AtomicType returns the name of the underlying type of the type
// as used in the names of the [sync/atomic] functions (Int32 or Int64).
func (t *Type) AtomicType() string {
return strcase.ToCamel(t.Underlying)
}
// Value represents a declared constant.
type Value struct {
OriginalName string // The name of the constant before transformation
Name string // The name of the constant after transformation (i.e. camel case => snake case)
Desc string // The comment description of the constant
// The Value is stored as a bit pattern alone. The boolean tells us
// whether to interpret it as an int64 or a uint64; the only place
// this matters is when sorting.
// Much of the time the str field is all we need; it is printed
// by Value.String.
Value int64
Signed bool // Whether the constant is a signed type.
Str string // The string representation given by the "go/constant" package.
}
func (v *Value) String() string {
return v.Str
}
// SortValues sorts the values and ensures there
// are no duplicates. The input slice is known
// to be non-empty.
func SortValues(values []Value, typ *Type) []Value {
// We use stable sort so the lexically first name is chosen for equal elements.
sort.Stable(ByValue(values))
// Remove duplicates. Stable sort has put the one we want to print first,
// so use that one. The String method won't care about which named constant
// was the argument, so the first name for the given value is the only one to keep.
// We need to do this because identical values would cause the switch or map
// to fail to compile.
j := 1
for i := 1; i < len(values); i++ {
if values[i].Value != values[i-1].Value {
values[j] = values[i]
j++
}
}
// for exported types, delete any unexported values
// unexported types are expected to have unexported values.
if len(typ.Name) > 0 && !unicode.IsLower(rune(typ.Name[0])) {
values = slices.DeleteFunc(values[:j], func(v Value) bool { // remove any unexported names
return unicode.IsLower(rune(v.OriginalName[0]))
})
}
return values
}
// TrimValueNames removes the prefixes specified
// in [Config.TrimPrefix] from each name
// of the given values.
func (g *Generator) TrimValueNames(values []Value, c *Config) {
for prefix := range strings.SplitSeq(c.TrimPrefix, ",") {
for i := range values {
values[i].Name = strings.TrimPrefix(values[i].Name, prefix)
}
}
}
// PrefixValueNames adds the prefix specified in
// [Config.AddPrefix] to each name of
// the given values.
func (g *Generator) PrefixValueNames(values []Value, c *Config) {
for i := range values {
values[i].Name = c.AddPrefix + values[i].Name
}
}
// TransformValueNames transforms the names of the given values according
// to the transform method specified in [Config.Transform]
func (g *Generator) TransformValueNames(values []Value, c *Config) error {
var fn func(src string) string
switch c.Transform {
case "upper":
fn = strings.ToUpper
case "lower":
fn = strings.ToLower
case "snake":
fn = strcase.ToSnake
case "SNAKE":
fn = strcase.ToSNAKE
case "kebab":
fn = strcase.ToKebab
case "KEBAB":
fn = strcase.ToKEBAB
case "camel":
fn = strcase.ToCamel
case "lower-camel":
fn = strcase.ToLowerCamel
case "title":
fn = strcase.ToTitle
case "sentence":
fn = strcase.ToSentence
case "first":
fn = func(s string) string {
r, _ := utf8.DecodeRuneInString(s)
return string(r)
}
case "first-upper":
fn = func(s string) string {
r, _ := utf8.DecodeRuneInString(s)
return strings.ToUpper(string(r))
}
case "first-lower":
fn = func(s string) string {
r, _ := utf8.DecodeRuneInString(s)
return strings.ToLower(string(r))
}
case "":
return nil
default:
return fmt.Errorf("unknown transformation method: %q", c.Transform)
}
for i, v := range values {
after := fn(v.Name)
// If the original one was "" or the one before the transformation
// was "" (most commonly if linecomment defines it as empty) we
// do not care if it's empty.
// But if any of them was not empty before then it means that
// the transformed emptied the value
if v.OriginalName != "" && v.Name != "" && after == "" {
return fmt.Errorf("transformation of %q (%s) got an empty result", v.Name, v.OriginalName)
}
values[i].Name = after
}
return nil
}
// ByValue is a sorting method that sorts the constants into increasing order.
// We take care in the Less method to sort in signed or unsigned order,
// as appropriate.
type ByValue []Value
func (b ByValue) Len() int { return len(b) }
func (b ByValue) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
func (b ByValue) Less(i, j int) bool {
if b[i].Signed {
return int64(b[i].Value) < int64(b[j].Value)
}
return b[i].Value < b[j].Value
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package enums
import (
"errors"
"fmt"
"log/slog"
"strconv"
"strings"
"sync/atomic"
"cogentcore.org/core/base/num"
)
// This file contains implementations of enumgen methods.
// EnumConstraint is the generic type constraint that all enums satisfy.
type EnumConstraint interface {
Enum
num.Integer
}
// BitFlagConstraint is the generic type constraint that all bit flags satisfy.
type BitFlagConstraint interface {
BitFlag
num.Integer
}
// String returns the string representation of the given
// enum value with the given map.
func String[T EnumConstraint](i T, m map[T]string) string {
if str, ok := m[i]; ok {
return str
}
return strconv.FormatInt(int64(i), 10)
}
// StringExtended returns the string representation of the given enum value
// with the given map, with the enum type extending the given other enum type.
func StringExtended[T, E EnumConstraint](i T, m map[T]string) string {
if str, ok := m[i]; ok {
return str
}
return E(i).String()
}
// BitIndexStringExtended returns the string representation of the given bit flag enum
// bit index value with the given map, with the bit flag type extending the given other
// bit flag type.
func BitIndexStringExtended[T, E BitFlagConstraint](i T, m map[T]string) string {
if str, ok := m[i]; ok {
return str
}
return E(i).BitIndexString()
}
// BitFlagString returns the string representation of the given bit flag value
// with the given values available.
func BitFlagString[T BitFlagConstraint](i T, values []T) string {
str := ""
ip := any(&i).(BitFlagSetter)
for _, ie := range values {
if ip.HasFlag(ie) {
ies := ie.BitIndexString()
if str == "" {
str = ies
} else {
str += "|" + ies
}
}
}
return str
}
// BitFlagStringExtended returns the string representation of the given bit flag value
// with the given values available, with the bit flag type extending the other given
// bit flag type that has the given values (extendedValues) available.
func BitFlagStringExtended[T, E BitFlagConstraint](i T, values []T, extendedValues []E) string {
str := ""
ip := any(&i).(BitFlagSetter)
for _, ie := range extendedValues {
if ip.HasFlag(ie) {
ies := ie.BitIndexString()
if str == "" {
str = ies
} else {
str += "|" + ies
}
}
}
for _, ie := range values {
if ip.HasFlag(ie) {
ies := ie.BitIndexString()
if str == "" {
str = ies
} else {
str += "|" + ies
}
}
}
return str
}
// lookup returns the value of the given name in the given map from enum
// names to values, or else of the one name that is the same regardless of
// case, so that a name whose case changed, as Html to HTML, still works,
// as in saved files.
func lookup[T EnumConstraint](valueMap map[string]T, s string) (T, bool) {
if val, ok := valueMap[s]; ok {
return val, true
}
var val T
found := false
for name, v := range valueMap {
if !strings.EqualFold(name, s) {
continue
}
if found && v != val {
return val, false // ambiguous
}
val, found = v, true
}
return val, found
}
// SetString sets the given enum value from its string representation, the map from
// enum names to values, and the name of the enum type, which is used for the error message.
// The string is matched regardless of case if it does not match exactly.
func SetString[T EnumConstraint](i *T, s string, valueMap map[string]T, typeName string) error {
if val, ok := lookup(valueMap, s); ok {
*i = val
return nil
}
return errors.New(s + " is not a valid value for type " + typeName)
}
// SetStringLower sets the given enum value from its string representation, the map from
// enum names to values, and the name of the enum type, which is used for the error message.
// It also tries the lowercase version of the given string if the original version fails.
func SetStringLower[T EnumConstraint](i *T, s string, valueMap map[string]T, typeName string) error {
if val, ok := valueMap[s]; ok {
*i = val
return nil
}
if val, ok := lookup(valueMap, strings.ToLower(s)); ok {
*i = val
return nil
}
return errors.New(s + " is not a valid value for type " + typeName)
}
// SetStringExtended sets the given enum value from its string representation and the map from
// enum names to values, with the enum type extending the other given enum type. It also takes
// the enum value in terms of the extended enum type (ie).
func SetStringExtended[T EnumConstraint, E EnumSetter](i *T, ie E, s string, valueMap map[string]T) error {
if val, ok := valueMap[s]; ok {
*i = val
return nil
}
err := ie.SetString(s)
if err == nil {
return nil
}
if val, ok := lookup(valueMap, s); ok {
*i = val
return nil
}
return err
}
// SetStringLowerExtended sets the given enum value from its string representation and the map from
// enum names to values, with the enum type extending the other given enum type. It also takes
// the enum value in terms of the extended enum type (ie). It also tries the lowercase version
// of the given string if the original version fails.
func SetStringLowerExtended[T EnumConstraint, E EnumSetter](i *T, ie E, s string, valueMap map[string]T) error {
if val, ok := valueMap[s]; ok {
*i = val
return nil
}
if val, ok := valueMap[strings.ToLower(s)]; ok {
*i = val
return nil
}
return ie.SetString(s)
}
// SetStringOr sets the given bit flag value from its string representation while
// preserving any bit flags already set.
func SetStringOr[T BitFlagConstraint, S BitFlagSetter](i S, s string, valueMap map[string]T, typeName string) error {
flags := strings.SplitSeq(s, "|")
for flag := range flags {
if val, ok := valueMap[flag]; ok {
i.SetFlag(true, val)
} else if flag == "" {
continue
} else {
return fmt.Errorf("%q is not a valid value for type %s", flag, typeName)
}
}
return nil
}
// SetStringOrLower sets the given bit flag value from its string representation while
// preserving any bit flags already set.
// It also tries the lowercase version of each flag string if the original version fails.
func SetStringOrLower[T BitFlagConstraint, S BitFlagSetter](i S, s string, valueMap map[string]T, typeName string) error {
flags := strings.SplitSeq(s, "|")
for flag := range flags {
if val, ok := valueMap[flag]; ok {
i.SetFlag(true, val)
} else if val, ok := valueMap[strings.ToLower(flag)]; ok {
i.SetFlag(true, val)
} else if flag == "" {
continue
} else {
return fmt.Errorf("%q is not a valid value for type %s", flag, typeName)
}
}
return nil
}
// SetStringOrExtended sets the given bit flag value from its string representation while
// preserving any bit flags already set, with the enum type extending the other
// given enum type. It also takes the enum value in terms of the extended enum
// type (ie).
func SetStringOrExtended[T BitFlagConstraint, S BitFlagSetter, E BitFlagSetter](i S, ie E, s string, valueMap map[string]T) error {
flags := strings.SplitSeq(s, "|")
for flag := range flags {
if val, ok := valueMap[flag]; ok {
i.SetFlag(true, val)
} else if flag == "" {
continue
} else {
err := ie.SetStringOr(flag)
if err != nil {
return err
}
}
}
return nil
}
// SetStringOrLowerExtended sets the given bit flag value from its string representation while
// preserving any bit flags already set, with the enum type extending the other
// given enum type. It also takes the enum value in terms of the extended enum
// type (ie). It also tries the lowercase version of each flag string if the original version fails.
func SetStringOrLowerExtended[T BitFlagConstraint, S BitFlagSetter, E BitFlagSetter](i S, ie E, s string, valueMap map[string]T) error {
flags := strings.SplitSeq(s, "|")
for flag := range flags {
if val, ok := valueMap[flag]; ok {
i.SetFlag(true, val)
} else if val, ok := valueMap[strings.ToLower(flag)]; ok {
i.SetFlag(true, val)
} else if flag == "" {
continue
} else {
err := ie.SetStringOr(flag)
if err != nil {
return err
}
}
}
return nil
}
// Desc returns the description of the given enum value.
func Desc[T EnumConstraint](i T, descMap map[T]string) string {
if str, ok := descMap[i]; ok {
return str
}
return i.String()
}
// DescExtended returns the description of the given enum value, with
// the enum type extending the other given enum type.
func DescExtended[T, E EnumConstraint](i T, descMap map[T]string) string {
if str, ok := descMap[i]; ok {
return str
}
return E(i).Desc()
}
// ValuesGlobalExtended returns also possible values for the given enum
// type that extends the other given enum type.
func ValuesGlobalExtended[T, E EnumConstraint](values []T, extendedValues []E) []T {
res := make([]T, len(extendedValues))
for i, e := range extendedValues {
res[i] = T(e)
}
res = append(res, values...)
return res
}
// Values returns all possible values for the given enum type.
func Values[T EnumConstraint](values []T) []Enum {
res := make([]Enum, len(values))
for i, d := range values {
res[i] = d
}
return res
}
// ValuesExtended returns all possible values for the given enum type
// that extends the other given enum type.
func ValuesExtended[T, E EnumConstraint](values []T, extendedValues []E) []Enum {
les := len(extendedValues)
res := make([]Enum, les+len(values))
for i, d := range extendedValues {
res[i] = d
}
for i, d := range values {
res[i+les] = d
}
return res
}
// HasFlag returns whether this bit flag value has the given bit flag set,
// using an atomic load.
func HasFlag(i *int64, f BitFlag) bool {
return atomic.LoadInt64(i)&(1<<uint32(f.Int64())) != 0
}
// HasAnyFlags returns whether this bit flag value has any of the given bit flags set,
// using an atomic load.
func HasAnyFlags(i *int64, f ...BitFlag) bool {
var mask int64
for _, v := range f {
mask |= 1 << v.Int64()
}
return atomic.LoadInt64(i)&mask != 0
}
// SetFlag atomically sets the value of the given flags in these flags
// to the given value.
func SetFlag(i *int64, on bool, f ...BitFlag) {
var mask int64
for _, v := range f {
mask |= 1 << v.Int64()
}
if on {
atomic.OrInt64(i, mask)
} else {
atomic.AndInt64(i, ^mask)
}
}
// UnmarshalText loads the enum from the given text.
// It logs any error instead of returning it to prevent
// one modified enum from tanking an entire object loading operation.
func UnmarshalText[T EnumSetter](i T, text []byte, typeName string) error {
if err := i.SetString(string(text)); err != nil {
slog.Error(typeName+".UnmarshalText", "err", err)
}
return nil
}
// Scan loads the enum from the given SQL scanner value.
func Scan[T EnumSetter](i T, value any, typeName string) error {
if value == nil {
return nil
}
var str string
switch v := value.(type) {
case []byte:
str = string(v)
case string:
str = v
case fmt.Stringer:
str = v.String()
default:
return fmt.Errorf("invalid value for type %s: %T(%v)", typeName, value, value)
}
return i.SetString(str)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package events
import (
"fmt"
"image"
"time"
"cogentcore.org/core/base/nptime"
"cogentcore.org/core/enums"
"cogentcore.org/core/events/key"
)
// Base is the base type for events.
// It is designed to support most event types so no further subtypes
// are needed.
type Base struct {
// Typ is the type of event, returned as Type()
Typ Types
// Flags records event boolean state, using atomic flag operations
Flags EventFlags
// GenTime records the time when the event was first generated, using more
// efficient nptime struct
GenTime nptime.Time
// Key Modifiers present when event occurred: for Key, Mouse, Touch events
Mods key.Modifiers
// Where is the window-based position in raw display dots
// (pixels) where event took place.
Where image.Point
// Start is the window-based starting position in raw display dots
// (pixels) where event started.
Start image.Point
// Prev is the window-based previous position in raw display dots
// (pixels) -- e.g., for mouse dragging.
Prev image.Point
// StTime is the starting time, using more efficient nptime struct
StTime nptime.Time
// PrvTime is the time of the previous event, using more efficient nptime struct
PrvTime nptime.Time
// LocalOffset is the offset subtracted from original window coordinates
// to compute the local coordinates.
LocalOffset image.Point
// WhereLocal is the local position, which can be adjusted from the window pos
// via SubLocalOffset based on a local top-left coordinate for a region within
// the window.
WhereLocal image.Point
// StartLocal is the local starting position
StartLocal image.Point
// PrevLocal is the local previous position
PrevLocal image.Point
// Button is the mouse button being pressed or released, for relevant events.
Button Buttons
// Rune is the meaning of the key event as determined by the
// operating system. The mapping is determined by system-dependent
// current layout, modifiers, lock-states, etc.
Rune rune
// Code is the identity of the physical key relative to a notional
// "standard" keyboard, independent of current layout, modifiers,
// lock-states, etc
Code key.Codes
// todo: add El info
Data any
}
// SetTime sets the event time to Now
func (ev *Base) SetTime() {
ev.GenTime.Now()
}
func (ev *Base) Init() {
ev.SetTime()
ev.SetLocalOff(image.Point{}) // ensure local is copied
}
func (ev Base) Type() Types {
return ev.Typ
}
func (ev *Base) AsBase() *Base {
return ev
}
func (ev Base) IsSame(oth Event) bool {
return ev.Typ == oth.Type() // basic check. redefine in subtypes
}
func (ev Base) IsUnique() bool {
return ev.Flags.HasFlag(Unique)
}
func (ev *Base) SetUnique() {
ev.Flags.SetFlag(true, Unique)
}
func (ev Base) Time() time.Time {
return ev.GenTime.Time()
}
func (ev Base) StartTime() time.Time {
return ev.StTime.Time()
}
func (ev Base) SinceStart() time.Duration {
return ev.Time().Sub(ev.StartTime())
}
func (ev Base) PrevTime() time.Time {
return ev.PrvTime.Time()
}
func (ev Base) SincePrev() time.Duration {
return ev.Time().Sub(ev.PrevTime())
}
func (ev Base) IsHandled() bool {
return ev.Flags.HasFlag(Handled)
}
func (ev *Base) SetHandled() {
ev.Flags.SetFlag(true, Handled)
}
func (ev *Base) ClearHandled() {
ev.Flags.SetFlag(false, Handled)
}
func (ev Base) String() string {
return fmt.Sprintf("%v{Time: %v, Handled: %v}", ev.Typ, ev.Time().Format("04:05"), ev.IsHandled())
}
func (ev Base) OnWinFocus() bool {
return true
}
// SetModifiers sets the bitflags based on a list of key.Modifiers
func (ev *Base) SetModifiers(mods ...enums.BitFlag) {
ev.Mods.SetFlag(true, mods...)
}
// HasAllModifiers tests whether all of given modifier(s) were set
func (ev Base) HasAllModifiers(mods ...enums.BitFlag) bool {
return key.HasAllModifiers(ev.Mods, mods...)
}
func (ev Base) HasAnyModifier(mods ...enums.BitFlag) bool {
return key.HasAnyModifier(ev.Mods, mods...)
}
func (ev Base) NeedsFocus() bool {
return false
}
func (ev Base) HasPos() bool {
return false
}
func (ev Base) WindowPos() image.Point {
return ev.Where
}
func (ev Base) WindowStartPos() image.Point {
return ev.Start
}
func (ev Base) WindowPrevPos() image.Point {
return ev.Prev
}
func (ev Base) StartDelta() image.Point {
return ev.Pos().Sub(ev.StartPos())
}
func (ev Base) PrevDelta() image.Point {
return ev.Pos().Sub(ev.PrevPos())
}
func (ev *Base) SetLocalOff(off image.Point) {
ev.LocalOffset = off
ev.WhereLocal = ev.Where.Sub(off)
ev.StartLocal = ev.Start.Sub(off)
ev.PrevLocal = ev.Prev.Sub(off)
}
func (ev Base) LocalOff() image.Point {
return ev.LocalOffset
}
func (ev Base) Pos() image.Point {
return ev.WhereLocal
}
func (ev Base) StartPos() image.Point {
return ev.StartLocal
}
func (ev Base) PrevPos() image.Point {
return ev.PrevLocal
}
// SelectMode returns the selection mode based on given modifiers on event
func (ev Base) SelectMode() SelectModes {
return SelectModeBits(ev.Mods)
}
// MouseButton is the mouse button being pressed or released, for relevant events.
func (ev Base) MouseButton() Buttons {
return ev.Button
}
// Modifiers returns the modifier keys present at time of event
func (ev Base) Modifiers() key.Modifiers {
return ev.Mods
}
func (ev Base) KeyRune() rune {
return ev.Rune
}
func (ev Base) KeyCode() key.Codes {
return ev.Code
}
// KeyChord returns a string representation of the keyboard event suitable for
// keyboard function maps, etc. Printable runes are sent directly, and
// non-printable ones are converted to their corresponding code names without
// the "Code" prefix.
func (ev Base) KeyChord() key.Chord {
return key.NewChord(ev.Rune, ev.Code, ev.Mods)
}
func (ev Base) Clone() Event {
nb := &Base{}
*nb = ev
nb.Flags.SetFlag(false, Handled)
return nb
}
func (ev Base) NewFromClone(typ Types) Event {
e := ev.Clone()
eb := e.AsBase()
eb.Typ = typ
eb.ClearHandled()
return e
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package events
import "fmt"
// TextComposition is a [Composition] event, which is sent to the focused
// widget while the user composes text with an input method (IME), such
// as for Chinese, Japanese and Korean text, or for accented characters.
// The widget shows the text at its cursor, typically underlined, without
// adding it to its text, and reports the position of the cursor for the
// candidate window of the input method (see [system.Window.SetTextInput]).
// The composition ends with an event with empty text, after which any
// committed text is sent as KeyChord events.
type TextComposition struct {
Base
// Text is the text being composed, which is not yet committed.
// It is empty when the composition ends.
Text string
// Start and End are the range of the selected part of Text,
// in runes, such as the clause being converted, which is the
// position of the cursor of the input method if they are equal.
Start, End int
}
// NewTextComposition returns a new [Composition] event with
// the given text, and range of its selected part, in runes.
func NewTextComposition(text string, start, end int) *TextComposition {
ev := &TextComposition{Text: text, Start: start, End: end}
ev.Typ = Composition
return ev
}
func (ev *TextComposition) HasPos() bool {
return false
}
func (ev *TextComposition) NeedsFocus() bool {
return true
}
func (ev *TextComposition) String() string {
return fmt.Sprintf("%v{Text: %q, Start: %d, End: %d, Time: %v}", ev.Type(), ev.Text, ev.Start, ev.End, ev.Time().Format("04:05"))
}
// Composition sends a [Composition] event with the given text, and range
// of its selected part, in runes. An empty text ends the composition.
func (es *Source) Composition(text string, start, end int) {
ev := NewTextComposition(text, start, end)
ev.Init()
es.Deque.Send(ev)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package events
import (
"fmt"
)
// CustomEvent is a user-specified event that can be sent and received
// as needed, and contains a Data field for arbitrary data, and
// optional position and focus parameters
type CustomEvent struct {
Base
// set to true if position is available
PosAvail bool
}
func (ce CustomEvent) String() string {
return fmt.Sprintf("%v{Data: %v, Time: %v}", ce.Type(), ce.Data, ce.Time())
}
func (ce CustomEvent) HasPos() bool {
return ce.PosAvail
}
// Copyright 2018 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// based on golang.org/x/exp/shiny:
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package events
import (
"fmt"
"sync"
)
// TraceEventCompression can be set to true to see when events
// are being compressed to eliminate laggy behavior.
var TraceEventCompression = false
// Deque is an infinitely buffered double-ended queue of events.
// If an event is not marked as Unique, and the last
// event in the queue is of the same type, then the new one
// replaces the last one. This automatically implements
// event compression to manage the common situation where
// event processing is slower than event generation,
// such as with Mouse movement and Paint events.
// The zero value is usable, but a Deque value must not be copied.
type Deque struct {
Back []Event // FIFO.
Front []Event // LIFO.
Mu sync.Mutex
Cond sync.Cond // Cond.L is lazily initialized to &Deque.Mu.
}
func (q *Deque) LockAndInit() {
q.Mu.Lock()
if q.Cond.L == nil {
q.Cond.L = &q.Mu
}
}
// NextEvent returns the next event in the deque.
// It blocks until such an event has been sent.
func (q *Deque) NextEvent() Event {
q.LockAndInit()
defer q.Mu.Unlock()
for {
if n := len(q.Front); n > 0 {
e := q.Front[n-1]
q.Front[n-1] = nil
q.Front = q.Front[:n-1]
return e
}
if n := len(q.Back); n > 0 {
e := q.Back[0]
q.Back[0] = nil
q.Back = q.Back[1:]
return e
}
q.Cond.Wait()
}
}
// Len returns the number of events in the deque.
func (q *Deque) Len() int {
q.LockAndInit()
defer q.Mu.Unlock()
return len(q.Front) + len(q.Back)
}
// PollEvent returns the next event in the deque if available,
// and returns true.
// If none are available, it returns false immediately.
func (q *Deque) PollEvent() (Event, bool) {
q.LockAndInit()
defer q.Mu.Unlock()
if n := len(q.Front); n > 0 {
e := q.Front[n-1]
q.Front[n-1] = nil
q.Front = q.Front[:n-1]
return e, true
}
if n := len(q.Back); n > 0 {
e := q.Back[0]
q.Back[0] = nil
q.Back = q.Back[1:]
return e, true
}
return nil, false
}
// Send adds an event to the end of the deque,
// replacing the last of the same type unless marked
// as Unique.
// They are returned by NextEvent in FIFO order.
func (q *Deque) Send(ev Event) {
q.LockAndInit()
defer q.Mu.Unlock()
n := len(q.Back)
if !ev.IsUnique() && n > 0 {
lev := q.Back[n-1]
if ev.IsSame(lev) {
q.Back[n-1] = ev // replace
switch ev.Type() {
case MouseMove, MouseDrag:
me := ev.(*Mouse)
le := lev.(*Mouse)
me.Prev = le.Prev
me.PrvTime = le.PrvTime
case Scroll:
me := ev.(*MouseScroll)
le := lev.(*MouseScroll)
me.Delta = me.Delta.Add(le.Delta)
}
q.Cond.Signal()
if TraceEventCompression {
fmt.Println("compressed back:", ev)
}
return
}
}
q.Back = append(q.Back, ev)
q.Cond.Signal()
}
// SendFirst adds an event to the start of the deque.
// They are returned by NextEvent in LIFO order,
// and have priority over events sent via Send.
// This is typically reserved for window events.
func (q *Deque) SendFirst(ev Event) {
q.LockAndInit()
defer q.Mu.Unlock()
n := len(q.Front)
if !ev.IsUnique() && n > 0 {
lev := q.Front[n-1]
if ev.IsSame(lev) {
if TraceEventCompression {
fmt.Println("compressed front:", ev)
}
q.Front[n-1] = ev // replace
q.Cond.Signal()
return
}
}
q.Front = append(q.Front, ev)
q.Cond.Signal()
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package events
import (
"fmt"
"image"
"cogentcore.org/core/events/key"
)
// DragDrop represents the drag-and-drop Drop event
type DragDrop struct {
Base
// When event is received by target, DropMod indicates the suggested modifier
// action associated with the drop (affected by holding down modifier
// keys), suggesting what to do with the dropped item, where appropriate.
// Receivers can ignore or process in their own relevant way as needed,
// BUT it is essential to update the event with the actual type of Mod
// action taken, because the event will be sent back to the source with
// this Mod as set by the receiver. The main consequence is that a
// DropMove requires the drop source to delete itself once the event has
// been received, otherwise it (typically) doesn't do anything, so just
// be careful about that particular case.
DropMod DropMods
// Data contains the data from the Source of the drag,
// typically a mimedata encoded representation.
Data any
// Source of the drop, only available for internal DND actions.
// If it is an external drop, this will be nil.
Source any
// Target of the drop -- receiver of an accepted drop should set this to
// itself, so Source (if internal) can see who got it
Target any
// FromApp is set for an external drag-and-drop event from the operating
// system, when the drag was started by this app (see [system.Window.StartDrag]),
// so that the original Source and Data can be restored from the app.
FromApp bool
}
func NewDragDrop(typ Types, mdrag *Mouse) *DragDrop {
ev := &DragDrop{}
ev.Base = mdrag.Base
ev.Flags.SetFlag(false, Handled)
ev.Typ = typ
ev.DefaultMod()
return ev
}
func NewExternalDrop(typ Types, but Buttons, where image.Point, mods key.Modifiers, data any) *DragDrop {
ev := &DragDrop{}
ev.Typ = typ
ev.SetUnique()
ev.Button = but
ev.Where = where
ev.Mods = mods
ev.Data = data
return ev
}
func (ev *DragDrop) String() string {
return fmt.Sprintf("%v{Button: %v, Pos: %v, Mods: %v, Time: %v}", ev.Type(), ev.Button, ev.Where, ev.Mods.ModifiersString(), ev.Time().Format("04:05"))
}
func (ev *DragDrop) HasPos() bool {
return true
}
// DropMods indicates the modifier associated with the drop action (affected by
// holding down modifier keys), suggesting what to do with the dropped item,
// where appropriate
type DropMods int32 //enums:enum -trim-prefix Drop
const (
NoDropMod DropMods = iota
// Copy is the default and implies data is just copied -- receiver can do
// with it as they please and source does not need to take any further
// action
DropCopy
// Move is signaled with a Shift or Meta key (by default) and implies that
// the source should delete itself when it receives the DropFromSource event
// action with this Mod value set -- receiver must update the Mod to
// reflect actual action taken, and be particularly careful with this one
DropMove
// Link can be any other kind of alternative action -- link is applicable
// to files (symbolic link)
DropLink
// Ignore means that the receiver chose to not process this drop
DropIgnore
)
// DefaultModBits returns the default DropMod modifier action based on modifier keys
func DefaultModBits(mods key.Modifiers) DropMods {
switch {
case key.HasAnyModifier(mods, key.Control):
return DropCopy
case key.HasAnyModifier(mods, key.Shift, key.Meta):
return DropMove
case key.HasAnyModifier(mods, key.Alt):
return DropLink
default:
return DropCopy
}
}
// DropModFor returns the DropMod modifier action for the given modifier
// keys, as [DefaultModBits] does, except that if moveDefault is true, the
// action without modifier keys is to move, and the keys that otherwise
// move instead copy. The lock keys, CapsLock and NumLock, which the
// macOS key events always have, are not modifier keys for this.
func DropModFor(mods key.Modifiers, moveDefault bool) DropMods {
mod := DefaultModBits(mods)
if !moveDefault {
return mod
}
switch {
case !key.HasAnyModifier(mods, key.Control, key.Meta, key.Alt, key.Shift):
return DropMove
case mod == DropMove:
return DropCopy
}
return mod
}
// DefaultMod sets the default DropMod modifier action based on modifier keys
func (ev *DragDrop) DefaultMod() {
ev.DropMod = DefaultModBits(ev.Mods)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package events
import (
"fmt"
"cogentcore.org/core/events/key"
)
// Key is a low-level immediately generated key event, tracking press
// and release of keys -- suitable for fine-grained tracking of key events --
// see also events.Key for events that are generated only on key press,
// and that include the full chord information about all the modifier keys
// that were present when a non-modifier key was released
type Key struct {
Base
}
func NewKey(typ Types, rn rune, code key.Codes, mods key.Modifiers) *Key {
ev := &Key{}
ev.Typ = typ
ev.SetUnique()
ev.Rune = rn
ev.Code = code
ev.Mods = mods
return ev
}
func (ev *Key) HasPos() bool {
return false
}
func (ev *Key) NeedsFocus() bool {
return true
}
func (ev *Key) String() string {
if ev.Typ == KeyChord {
return fmt.Sprintf("%v{Chord: %v, Rune: %d, Hex: %X, Mods: %v, Time: %v, Handled: %v}", ev.Type(), ev.KeyChord(), ev.Rune, ev.Rune, ev.Mods.ModifiersString(), ev.Time().Format("04:05"), ev.IsHandled())
}
return fmt.Sprintf("%v{Code: %v, Mods: %v, Time: %v, Handled: %v}", ev.Type(), ev.Code, ev.Mods.ModifiersString(), ev.Time().Format("04:05"), ev.IsHandled())
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package key
import (
"fmt"
"runtime"
"strings"
"unicode"
)
// Chord represents the key chord associated with a given key function; it
// is linked to the [cogentcore.org/core/core.KeyChordValue] so you can just
// type keys to set key chords.
type Chord string
// SystemPlatform is the string version of [cogentcore.org/core/system.App.SystemPlatform],
// which is set by system during initialization so that this package can conditionalize
// shortcut formatting based on the underlying system platform without import cycles.
var SystemPlatform string
// KeypadMap maps the keypad versions to standard codes,
// for non-printing characters.
var KeypadMap = map[Codes]Codes{
CodeKeypadEnter: CodeReturnEnter,
CodeKeypadFullStop: CodeFullStop,
CodeKeypadEqualSign: CodeEqualSign,
}
// KeypadAlts are alternate codes for keypad keys to use when
// the NumLock key is on.
var KeypadAlts = map[Codes]Codes{
CodeKeypad1: CodeEnd,
CodeKeypad2: CodeDownArrow,
CodeKeypad3: CodePageDown,
CodeKeypad4: CodeLeftArrow,
CodeKeypad6: CodeRightArrow,
CodeKeypad7: CodeHome,
CodeKeypad8: CodeUpArrow,
CodeKeypad9: CodePageUp,
CodeKeypad0: CodeInsert,
CodeKeypadFullStop: CodeDelete,
}
// NewChord returns a string representation of the keyboard event suitable for
// keyboard function maps, etc. Printable runes are sent directly, and
// non-printable ones are converted to their corresponding code names without
// the "Code" prefix.
func NewChord(rn rune, code Codes, mods Modifiers) Chord {
mods.SetFlag(false, CapsLock)
if !mods.HasFlag(NumLock) && code >= CodeKeypadNumLock && code < CodeKeypadEqualSign {
if ac, ok := KeypadAlts[code]; ok {
rn = 0
code = ac
}
}
if ac, ok := KeypadMap[code]; ok {
code = ac
}
mods.SetFlag(false, NumLock)
modstr := mods.ModifiersString()
if modstr != "" && code == CodeSpacebar { // modified space is not regular space
return Chord(modstr + "Spacebar")
}
if unicode.IsPrint(rn) {
if len(modstr) > 0 {
return Chord(modstr + string(unicode.ToUpper(rn))) // all modded keys are uppercase!
}
return Chord(string(rn))
}
// now convert code
codestr := strings.TrimPrefix(code.String(), "Code")
return Chord(modstr + codestr)
}
// PlatformChord translates Command into either Control or Meta depending on the platform
func (ch Chord) PlatformChord() Chord {
sc := string(ch)
if SystemPlatform == "MacOS" {
sc = strings.ReplaceAll(sc, "Command+", "Meta+")
} else {
sc = strings.ReplaceAll(sc, "Command+", "Control+")
}
return Chord(sc)
}
// CodeIsModifier returns true if given code is a modifier key
func CodeIsModifier(c Codes) bool {
return c >= CodeLeftControl && c <= CodeRightMeta
}
// IsMulti returns true if the Chord represents a multi-key sequence
func (ch Chord) IsMulti() bool {
return strings.Contains(string(ch), " ")
}
// Chords returns the multiple keys represented in a multi-key sequence
func (ch Chord) Chords() []Chord {
ss := strings.Fields(string(ch))
nc := len(ss)
if nc <= 1 {
return []Chord{ch}
}
cc := make([]Chord, nc)
for i, s := range ss {
cc[i] = Chord(s)
}
return cc
}
// Decode decodes a chord string into rune and modifiers (set as bit flags)
func (ch Chord) Decode() (r rune, code Codes, mods Modifiers, err error) {
cs := string(ch.PlatformChord())
cs, _, _ = strings.Cut(cs, "\n") // we only care about the first chord
mods, cs = ModifiersFromString(cs)
rs := ([]rune)(cs)
if len(rs) == 1 {
r = rs[0]
return
}
cstr := string(cs)
code.SetString(cstr)
if code != CodeUnknown {
r = 0
return
}
err = fmt.Errorf("system/events/key.DecodeChord got more/less than one rune: %v from remaining chord: %v", rs, string(cs))
return
}
// Label transforms the chord string into a short form suitable for display to users.
func (ch Chord) Label() string {
cs := string(ch.PlatformChord())
cs = strings.ReplaceAll(cs, "Control", "Ctrl")
switch SystemPlatform {
case "MacOS":
if runtime.GOOS == "js" { // no font to display symbol on web
cs = strings.ReplaceAll(cs, "Meta+", "Cmd+")
} else {
cs = strings.ReplaceAll(cs, "Meta+", "⌘")
// need to have + after ⌘ when before other modifiers
cs = strings.ReplaceAll(cs, "⌘Alt", "⌘+Alt")
cs = strings.ReplaceAll(cs, "⌘Shift", "⌘+Shift")
}
case "Windows":
cs = strings.ReplaceAll(cs, "Meta+", "Win+")
}
cs = strings.ReplaceAll(cs, "\n", " or ")
return cs
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package key
//go:generate core generate
import (
"slices"
"strings"
"cogentcore.org/core/enums"
)
// Modifiers are used as bitflags representing a set of modifier keys.
type Modifiers int32 //enums:bitflag
const (
// Control is the "Control" (Ctrl) key.
Control Modifiers = iota
// Meta is the system meta key (the "Command" key on macOS
// and the Windows key on Windows).
Meta
// Alt is the "Alt" ("Option" on macOS) key.
Alt
// Shift is the "Shift" key.
Shift
// CapsLock indicates that CapsLock is toggled on at time of keypress
CapsLock
// NumLock indicates that NumLock is toggled on at time of keypress
NumLock
)
// ModifiersString returns the string representation of the modifiers using
// plus symbols as seperators. The order is given by Modifiers order:
// Control, Meta, Alt, Shift.
func (mo Modifiers) ModifiersString() string {
var modstr strings.Builder
for _, m := range ModifiersValues() {
if mo.HasFlag(m) {
modstr.WriteString(m.BitIndexString())
modstr.WriteString("+")
}
}
return modstr.String()
}
// ModifiersFromString returns the modifiers corresponding to given string
// and the remainder of the string after modifiers have been stripped. This only
// works for modifiers followed with a plus sign (ex: "Control+C" will work, but
// "Control" will not). See [Modifiers.SetString] for simple setting of modifiers
// without the plus sign.
func ModifiersFromString(cs string) (Modifiers, string) {
var mods Modifiers
for _, m := range ModifiersValues() {
mstr := m.BitIndexString() + "+"
if strings.HasPrefix(cs, mstr) {
mods.SetFlag(true, m)
cs = strings.TrimPrefix(cs, mstr)
}
}
return mods, cs
}
// HasAnyModifier tests whether any of given modifier(s) were set
func HasAnyModifier(flags Modifiers, mods ...enums.BitFlag) bool {
return slices.ContainsFunc(mods, flags.HasFlag)
}
// HasAllModifiers tests whether all of given modifier(s) were set
func HasAllModifiers(flags Modifiers, mods ...enums.BitFlag) bool {
for _, m := range mods {
if !flags.HasFlag(m) {
return false
}
}
return true
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package events
// Listeners registers lists of event listener functions
// to receive different event types.
// Listeners are closure methods with all context captured.
// Functions are called in *reverse* order of when they are added:
// First In, Last Called, so that "base" functions are typically
// added first, and then can be overridden by later-added ones.
// Call SetHandled() on the event to stop further propagation.
type Listeners map[Types][]func(ev Event)
// Init ensures that the map is constructed.
func (ls *Listeners) Init() {
if *ls != nil {
return
}
*ls = make(map[Types][]func(Event))
}
// Add adds a listener for the given type to the end of the current stack
// such that it will be called before everything else already on the stack.
func (ls *Listeners) Add(typ Types, fun func(e Event)) {
ls.Init()
ets := (*ls)[typ]
ets = append(ets, fun)
(*ls)[typ] = ets
}
// HandlesEventType returns true if this listener handles the given event type.
func (ls *Listeners) HandlesEventType(typ Types) bool {
if *ls == nil {
return false
}
_, has := (*ls)[typ]
return has
}
// Call calls all functions for given event.
// It goes in reverse order so the last functions added are the first called
// and it stops when the event is marked as Handled. This allows for a natural
// and optional override behavior, as compared to requiring more complex
// priority-based mechanisms. Also, it takes an optional function that
// it calls before each event handler is run, returning if it returns
// false.
func (ls *Listeners) Call(ev Event, shouldContinue ...func() bool) {
if ev.IsHandled() {
return
}
typ := ev.Type()
ets := (*ls)[typ]
n := len(ets)
for i := n - 1; i >= 0; i-- {
if len(shouldContinue) > 0 && !shouldContinue[0]() {
break
}
fun := ets[i]
fun(ev)
if ev.IsHandled() {
break
}
}
}
// CopyFromExtra copies additional listeners from given source
// beyond those present in the receiver.
func (ls *Listeners) CopyFromExtra(fr Listeners) {
if *ls == nil && len(fr) > 0 {
*ls = Listeners{}
}
for typ, fl := range fr {
l := (*ls)[typ]
if n := len(l); len(fl) > n {
(*ls)[typ] = append(l, fl[n:]...)
}
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package events
import (
"fmt"
"image"
"cogentcore.org/core/events/key"
"cogentcore.org/core/math32"
)
var (
// ScrollWheelSpeed controls how fast the scroll wheel moves (typically
// interpreted as pixels per wheel step).
// This is also in core.DeviceSettings and updated from there
ScrollWheelSpeed = float32(1)
)
// Buttons is a mouse button.
type Buttons int32 //enums:enum
// TODO: have a separate axis concept for wheel up/down? How does that relate
// to joystick events?
const (
NoButton Buttons = iota
Left
Middle
Right
)
// Mouse is a basic mouse event for all mouse events except Scroll
type Mouse struct {
Base
// TODO: have a field to hold what other buttons are down, for detecting
// drags or button-chords.
// TODO: add a Device ID, for multiple input devices?
}
func NewMouse(typ Types, but Buttons, where image.Point, mods key.Modifiers) *Mouse {
ev := &Mouse{}
ev.Typ = typ
ev.SetUnique()
ev.Button = but
ev.Where = where
ev.Mods = mods
return ev
}
func (ev *Mouse) String() string {
return fmt.Sprintf("%v{Button: %v, Pos: %v, Mods: %v, Time: %v}", ev.Type(), ev.Button, ev.Where, ev.Mods.ModifiersString(), ev.Time().Format("04:05"))
}
// Clone returns a copy of the mouse event, not handled, which is a
// mouse event, with its button and position (see [Event.HasPos]).
func (ev Mouse) Clone() Event {
nm := &Mouse{}
*nm = ev
nm.Flags.SetFlag(false, Handled)
return nm
}
// NewFromClone returns a copy of the mouse event with the given type,
// as a mouse event, so that an event made from it (as a [ContextMenu]
// from a right [MouseUp]) has its position.
func (ev Mouse) NewFromClone(typ Types) Event {
e := ev.Clone()
eb := e.AsBase()
eb.Typ = typ
eb.ClearHandled()
return e
}
func (ev Mouse) HasPos() bool {
return true
}
func NewMouseMove(but Buttons, where, prev image.Point, mods key.Modifiers) *Mouse {
ev := &Mouse{}
ev.Typ = MouseMove
// not unique
ev.Button = but
ev.Where = where
ev.Prev = prev
ev.Mods = mods
return ev
}
func NewMouseDrag(but Buttons, where, prev, start image.Point, mods key.Modifiers) *Mouse {
ev := &Mouse{}
ev.Typ = MouseDrag
// not unique
ev.Button = but
ev.Where = where
ev.Prev = prev
ev.Start = start
ev.Mods = mods
return ev
}
// MouseScroll is for mouse scrolling, recording the delta of the scroll
type MouseScroll struct {
Mouse
// Delta is the amount of scrolling in each axis, which is always in pixel/dot
// units (see [Scroll]).
Delta math32.Vector2
}
// Clone returns a copy of the scroll event, not handled.
func (ev MouseScroll) Clone() Event {
nm := &MouseScroll{}
*nm = ev
nm.Flags.SetFlag(false, Handled)
return nm
}
// NewFromClone returns a copy of the scroll event with the given type.
func (ev MouseScroll) NewFromClone(typ Types) Event {
e := ev.Clone()
eb := e.AsBase()
eb.Typ = typ
eb.ClearHandled()
return e
}
func (ev *MouseScroll) String() string {
return fmt.Sprintf("%v{Delta: %v, Pos: %v, Mods: %v, Time: %v}", ev.Type(), ev.Delta, ev.Where, ev.Mods.ModifiersString(), ev.Time().Format("04:05"))
}
func NewScroll(where image.Point, delta math32.Vector2, mods key.Modifiers) *MouseScroll {
ev := &MouseScroll{}
ev.Typ = Scroll
// not unique, but delta integrated!
ev.Where = where
ev.Delta = delta
ev.Mods = mods
return ev
}
// Copyright (c) 2021 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package events
import (
"fmt"
)
// OSEvent reports an OS level event
type OSEvent struct {
Base
}
func NewOSEvent(typ Types) *OSEvent {
ev := &OSEvent{}
ev.Typ = typ
return ev
}
func (ev *OSEvent) String() string {
return fmt.Sprintf("%v{Time: %v}", ev.Type(), ev.Time().Format("04:05"))
}
// OSFiles is for OS open files action to open given files
type OSFiles struct {
OSEvent
// Files are a list of files to open
Files []string
}
func NewOSFiles(typ Types, files []string) *OSFiles {
ev := &OSFiles{}
ev.Typ = typ
ev.Files = files
return ev
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package events
import (
"cogentcore.org/core/events/key"
)
// SelectModes interprets the modifier keys to determine what type of selection mode to use.
// This is also used for selection actions and has modes not directly activated by
// modifier keys.
type SelectModes int32 //enums:enum
const (
// SelectOne selects a single item, and is the default when no modifier key
// is pressed
SelectOne SelectModes = iota
// ExtendContinuous, activated by Shift key, extends the selection to
// select a continuous region of selected items, with no gaps
ExtendContinuous
// ExtendOne, activated by Control or Meta / Command, extends the
// selection by adding the one additional item just clicked on, creating a
// potentially discontinuous set of selected items
ExtendOne
// NoSelect means do not update selection -- this is used programmatically
// and not available via modifier key
NoSelect
// Unselect means unselect items -- this is used programmatically
// and not available via modifier key -- typically ExtendOne will
// unselect if already selected
Unselect
// SelectQuiet means select without doing other updates or signals -- for
// bulk updates with a final update at the end -- used programmatically
SelectQuiet
// UnselectQuiet means unselect without doing other updates or signals -- for
// bulk updates with a final update at the end -- used programmatically
UnselectQuiet
)
// SelectModeBits returns the selection mode based on given modifiers bitflags
func SelectModeBits(mods key.Modifiers) SelectModes {
if key.HasAnyModifier(mods, key.Shift) {
return ExtendContinuous
}
if key.HasAnyModifier(mods, key.Meta) {
return ExtendOne
}
return SelectOne
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package events
import (
"fmt"
"image"
"cogentcore.org/core/base/fileinfo/mimedata"
"cogentcore.org/core/base/nptime"
"cogentcore.org/core/events/key"
"cogentcore.org/core/math32"
)
// TraceWindowPaint prints out a . for each WindowPaint event,
// - for other window events, and * for mouse move events.
// Makes it easier to see what is going on in the overall flow.
var TraceWindowPaint = false
// Source is a source of events that manages the event
// construction and sending process for its parent window.
// It caches state as needed to generate derived events such
// as [MouseDrag].
type Source struct {
// Deque is the event queue
Deque Deque
// flag for ignoring mouse events when disabling mouse movement
ResettingPos bool
// Last has the prior state for key variables
Last SourceState
// PaintCount is used for printing paint events as .
PaintCount int
}
// SourceState tracks basic event state over time
// to enable recognition and full data for generating events.
type SourceState struct {
// last mouse button event type (down or up)
MouseButtonType Types
// last mouse button
MouseButton Buttons
// time of MouseDown
MouseDownTime nptime.Time
// position at MouseDown
MouseDownPos image.Point
// position of mouse from move events
MousePos image.Point
// time of last move
MouseMoveTime nptime.Time
// keyboard modifiers (Shift, Alt, etc)
Mods key.Modifiers
// Key event code
Key key.Codes
}
// Key processes a basic key event and sends it
func (es *Source) Key(typ Types, rn rune, code key.Codes, mods key.Modifiers) {
ev := NewKey(typ, rn, code, mods)
es.Last.Mods = mods
es.Last.Key = code
ev.Init()
es.Deque.Send(ev)
mrn, mapped := key.CodeRuneMap[code]
if typ != KeyDown {
return
}
// the event must not be used after it is sent, as the event loop
// handles it concurrently: the arguments are used instead
if !mods.HasFlag(key.NumLock) && code >= key.CodeKeypadNumLock && code < key.CodeKeypadEqualSign {
if mapped {
rn = mrn
}
che := NewKey(KeyChord, rn, code, mods)
che.Init()
es.Deque.Send(che)
return
}
if code < key.CodeLeftControl && (key.HasAnyModifier(mods, key.Control, key.Meta) || !mapped || code == key.CodeTab) {
che := NewKey(KeyChord, rn, code, mods)
che.Init()
es.Deque.Send(che)
return
}
}
// KeyChord processes a basic KeyChord event and sends it
func (es *Source) KeyChord(rn rune, code key.Codes, mods key.Modifiers) {
ev := NewKey(KeyChord, rn, code, mods)
// no further processing of these
ev.Init()
es.Deque.Send(ev)
}
// MouseButton creates and sends a mouse button event with given values
func (es *Source) MouseButton(typ Types, but Buttons, where image.Point, mods key.Modifiers) {
ev := NewMouse(typ, but, where, mods)
if typ != MouseDown && es.Last.MouseButtonType == MouseDown {
ev.StTime = es.Last.MouseDownTime
ev.PrvTime = es.Last.MouseMoveTime
ev.Start = es.Last.MouseDownPos
ev.Prev = es.Last.MousePos
}
es.Last.Mods = mods
es.Last.MouseButtonType = typ
es.Last.MouseButton = but
es.Last.MousePos = where
ev.Init()
if typ == MouseDown {
es.Last.MouseDownPos = where
es.Last.MouseDownTime = ev.GenTime
es.Last.MouseMoveTime = ev.GenTime
}
es.Deque.Send(ev)
}
// MouseMove creates and sends a mouse move or drag event with given values
func (es *Source) MouseMove(where image.Point) {
lastPos := es.Last.MousePos
var ev *Mouse
if es.Last.MouseButtonType == MouseDown {
ev = NewMouseDrag(es.Last.MouseButton, where, lastPos, es.Last.MouseDownPos, es.Last.Mods)
ev.StTime = es.Last.MouseDownTime
ev.PrvTime = es.Last.MouseMoveTime
} else {
ev = NewMouseMove(es.Last.MouseButton, where, lastPos, es.Last.Mods)
ev.PrvTime = es.Last.MouseMoveTime
}
ev.Init()
es.Last.MouseMoveTime = ev.GenTime
// if em.Win.IsCursorEnabled() {
es.Last.MousePos = where
// }
if TraceWindowPaint {
fmt.Printf("*")
}
es.Deque.Send(ev)
}
// Scroll creates and sends a scroll event with given values
func (es *Source) Scroll(where image.Point, delta math32.Vector2) {
ev := NewScroll(where, delta, es.Last.Mods)
ev.Init()
es.Deque.Send(ev)
}
// DropExternal creates and sends a Drop event with given values
func (es *Source) DropExternal(where image.Point, md mimedata.Mimes) {
ev := NewExternalDrop(Drop, es.Last.MouseButton, where, es.Last.Mods, md)
es.Last.MousePos = where
ev.Init()
es.Deque.Send(ev)
}
// DragExternal creates and sends an external drag-and-drop event from the
// operating system, for a drag over the window from another window or app
// (or from this window, after the drag has left it). The type is
// [DragMove] while the drag moves over the window, [DragLeave] when it
// leaves the window without a drop, and [Drop] for the drop, with the
// data in md. fromApp is true if the drag was started by this app.
func (es *Source) DragExternal(typ Types, where image.Point, mods key.Modifiers, md mimedata.Mimes, fromApp bool) {
ev := NewExternalDrop(typ, Left, where, mods, md)
ev.FromApp = fromApp
if typ == DragMove { // successive moves can be compressed
ev.Flags.SetFlag(false, Unique)
}
es.Last.Mods = mods
if typ != DragLeave {
es.Last.MousePos = where
}
ev.Init()
es.Deque.Send(ev)
}
// Touch creates and sends a touch event with the given values.
// It also creates and sends a corresponding mouse event.
func (es *Source) Touch(typ Types, seq Sequence, where image.Point) {
ev := NewTouch(typ, seq, where)
ev.Init()
es.Deque.Send(ev)
switch typ {
case TouchStart:
es.MouseButton(MouseDown, Left, where, 0) // TODO: modifiers
case TouchEnd:
es.MouseButton(MouseUp, Left, where, 0) // TODO: modifiers
default:
es.MouseMove(where)
}
}
// Magnify creates and sends a [TouchMagnify] event with the given values.
func (es *Source) Magnify(scaleFactor float32, where image.Point) {
ev := NewMagnify(scaleFactor, where)
ev.Init()
es.Deque.Send(ev)
}
// func (es *Source) DND(act dnd.Actions, where image.Point, data mimedata.Mimes) {
// ev := dnd.NewEvent(act, where, em.Last.Mods)
// ev.Data = data
// ev.Init()
// es.Deque.Send(ev)
// }
func (es *Source) Window(act WinActions) {
ev := NewWindow(act)
ev.Init()
if TraceWindowPaint {
fmt.Printf("-")
}
es.Deque.SendFirst(ev)
}
// WindowPaint sends a [NewWindowPaint] event.
func (es *Source) WindowPaint() {
ev := NewWindowPaint()
ev.Init()
if TraceWindowPaint {
fmt.Printf(".")
es.PaintCount++
if es.PaintCount > 60 {
fmt.Println("")
es.PaintCount = 0
}
}
es.Deque.SendFirst(ev) // separate channel for window!
}
func (es *Source) WindowResize() {
ev := NewWindowResize()
ev.Init()
if TraceWindowPaint {
fmt.Printf("r")
}
es.Deque.SendFirst(ev)
}
func (es *Source) OSOpenFiles(files []string) {
ev := NewOSFiles(OSOpenFiles, files)
ev.Init()
es.Deque.Send(ev)
}
func (es *Source) Custom(data any) {
ce := &CustomEvent{}
ce.Typ = Custom
ce.Data = data
ce.Init()
es.Deque.Send(ce)
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package events
import (
"fmt"
"image"
)
// The best source on android input events is the NDK: include/android/input.h
//
// iOS event handling guide:
// https://developer.apple.com/library/ios/documentation/EventHandling/Conceptual/EventHandlingiPhoneOS
// Touch is a touch event.
type Touch struct {
Base
// Sequence is the sequence number. The same number is shared by all events
// in a sequence. A sequence begins with a single Begin, is followed by
// zero or more Moves, and ends with a single End. A Sequence
// distinguishes concurrent sequences but its value is subsequently reused.
Sequence Sequence
}
// Sequence identifies a sequence of touch events.
type Sequence int64
// NewTouch creates a new touch event from the given values.
func NewTouch(typ Types, seq Sequence, where image.Point) *Touch {
ev := &Touch{}
ev.Typ = typ
ev.SetUnique()
ev.Sequence = seq
ev.Where = where
return ev
}
func (ev *Touch) HasPos() bool {
return true
}
func (ev *Touch) String() string {
return fmt.Sprintf("%v{Pos: %v, Sequence: %v, Time: %v}", ev.Type(), ev.Where, ev.Sequence, ev.Time().Format("04:05"))
}
// todo: what about these higher-level abstractions of touch-like events?
// TouchMagnify is a touch magnification (scaling) gesture event.
// It is the event struct corresponding to events of type [Magnify].
type TouchMagnify struct {
Touch
// the multiplicative scale factor relative to the previous
// zoom of the screen
ScaleFactor float32
}
// NewMagnify creates a new [TouchMagnify] event based on
// the given multiplicative scale factor.
func NewMagnify(scaleFactor float32, where image.Point) *TouchMagnify {
ev := &TouchMagnify{}
ev.Typ = Magnify
ev.ScaleFactor = scaleFactor
ev.Where = where
return ev
}
// // check for interface implementation
// var _ Event = &MagnifyEvent{}
// ////////////////////////////////////////////
// // RotateEvent is used to represent a rotation gesture.
// type RotateEvent struct {
// GestureEvent
// Rotation float64 // measured in degrees; positive == clockwise
// }
// func (ev *RotateEvent) EventTypes() EventTypes {
// return RotateEventTypes
// }
// // check for interface implementation
// var _ Event = &RotateEvent{}
// // Scroll Event is used to represent a scrolling gesture.
// type ScrollEvent struct {
// GestureEvent
// Delta image.Point
// }
// func (ev *ScrollEvent) EventTypes() EventTypes {
// return ScrollEventTypes
// }
// // check for interface implementation
// var _ Event = &ScrollEvent{}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package events
//go:generate core generate
// Types determines the type of GUI event, and also the
// level at which one can select which events to listen to.
// The type should include both the source / nature of the event
// and the "action" type of the event (e.g., MouseDown, MouseUp
// are separate event types). The standard
// [JavaScript Event](https://developer.mozilla.org/en-US/docs/Web/Events)
// provide the basis for most of the event type names and categories.
// Most events use the same Base type and only need
// to set relevant fields and the type.
// Unless otherwise noted, all events are marked as Unique,
// meaning they are always sent. Non-Unique events are subject
// to compression, where if the last event added (and not yet
// processed and therefore removed from the queue) is of the same type
// then it is replaced with the new one, instead of adding.
type Types int32 //enums:enum
const (
// zero value is an unknown type
UnknownType Types = iota
// MouseDown happens when a mouse button is pressed down.
// See MouseButton() for which.
// See Click for a synthetic event representing a MouseDown
// followed by MouseUp on the same element with Left (primary)
// mouse button. Often that is the most useful.
MouseDown
// MouseUp happens when a mouse button is released.
// See MouseButton() for which.
MouseUp
// MouseMove is always sent when the mouse is moving but no
// button is down, even if there might be other higher-level events too.
// These can be numerous and thus it is typically more efficient
// to listen to other events derived from this.
// Not unique, and Prev position is updated during compression.
MouseMove
// MouseDrag is always sent when the mouse is moving and there
// is a button down, even if there might be other higher-level
// events too.
// The start pos indicates where (and when) button first was pressed.
// Not unique and Prev position is updated during compression.
MouseDrag
// Click represents a MouseDown followed by MouseUp
// in sequence on the same element, with the Left (primary) button.
// This is the typical event for most basic user interaction.
Click
// DoubleClick represents two Click events in a row in rapid
// succession.
DoubleClick
// TripleClick represents three Click events in a row in rapid
// succession.
TripleClick
// ContextMenu represents a MouseDown/Up event with the
// Right mouse button (which is also activated by
// Control key + Left Click).
ContextMenu
// LongPressStart is when the mouse has been relatively stable
// after MouseDown on an element for a minimum duration (500 msec default).
LongPressStart
// LongPressEnd is sent after LongPressStart when the mouse has
// gone up, moved sufficiently, left the current element,
// or another input event has happened.
LongPressEnd
// MouseEnter is when the mouse enters the bounding box
// of a new element. It is used for setting the Hover state,
// and can trigger cursor changes.
// See DragEnter for alternative case during Drag events.
MouseEnter
// MouseLeave is when the mouse leaves the bounding box
// of an element, that previously had a MouseEnter event.
// Given that elements can have overlapping bounding boxes
// (e.g., child elements within a container), it is not the case
// that a MouseEnter on a child triggers a MouseLeave on
// surrounding containers.
// See DragLeave for alternative case during Drag events.
MouseLeave
// LongHoverStart is when the mouse has been relatively stable
// after MouseEnter on an element for a minimum duration
// (500 msec default).
// This triggers the LongHover state typically used for Tooltips.
LongHoverStart
// LongHoverEnd is after LongHoverStart when the mouse has
// moved sufficiently, left the current element,
// or another input event has happened,
// thereby terminating the LongHover state.
LongHoverEnd
// DragStart is at the start of a drag-n-drop event sequence, when
// a Draggable element is Active and a sufficient distance of
// MouseDrag events has occurred to engage the DragStart event.
DragStart
// DragMove is for a MouseDrag event during the drag-n-drop sequence.
// Usually don't need to listen to this one. MouseDrag is also sent.
DragMove
// DragEnter is like MouseEnter but after a DragStart during a
// drag-n-drop sequence. MouseEnter is not sent in this case.
DragEnter
// DragLeave is like MouseLeave but after a DragStart during a
// drag-n-drop sequence. MouseLeave is not sent in this case.
DragLeave
// Drop is sent when an item being Dragged is dropped on top of a
// target element. The event struct should be DragDrop.
Drop
// DropDeleteSource is sent to the source Drag element if the
// Drag-n-Drop event is a Move type, which requires deleting
// the source element. The event struct should be DragDrop.
DropDeleteSource
// SlideStart is for a Slideable element when Active and a
// sufficient distance of MouseDrag events has occurred to
// engage the SlideStart event. Sets the Sliding state.
SlideStart
// SlideMove is for a Slideable element after SlideStart
// is being dragged via MouseDrag events.
SlideMove
// SlideStop is when the mouse button is released on a Slideable
// element being dragged via MouseDrag events. This typically
// also accompanied by a Changed event for the new slider value.
SlideStop
// Scroll is for scroll wheel or other scrolling events (gestures).
// These are not unique and Delta is updated during compression.
// The [MouseScroll.Delta] on scroll events is always in real pixel/dot units;
// low-level sources may be in lines or pages, but we normalize everything
// to real pixels/dots.
Scroll
// KeyDown is when a key is pressed down.
// This provides fine-grained data about each key as it happens.
// KeyChord is recommended for a more complete Key event.
KeyDown
// KeyUp is when a key is released.
// This provides fine-grained data about each key as it happens.
// KeyChord is recommended for a more complete Key event.
KeyUp
// KeyChord is only generated when a non-modifier key is released,
// and it also contains a string representation of the full chord,
// suitable for translation into keyboard commands, emacs-style etc.
// It can be somewhat delayed relative to the KeyUp.
KeyChord
// Composition is sent to the focused widget while the user composes
// text with an input method (IME), with the text not yet committed
// (see [TextComposition]). The committed text is sent as KeyChord
// events, after a Composition event with empty text.
Composition
// TouchStart is when a touch event starts, for the low-level touch
// event processing. TouchStart also activates MouseDown, Scroll,
// Magnify, or Rotate events depending on gesture recognition.
TouchStart
// TouchEnd is when a touch event ends, for the low-level touch
// event processing. TouchEnd also activates MouseUp events
// depending on gesture recognition.
TouchEnd
// TouchMove is when a touch event moves, for the low-level touch
// event processing. TouchMove also activates MouseMove, Scroll,
// Magnify, or Rotate events depending on gesture recognition.
TouchMove
// Magnify is a touch-based magnify event (e.g., pinch)
Magnify
// Rotate is a touch-based rotate event.
Rotate
// Select is sent for any direction of selection change
// on (or within if relevant) a Selectable element.
// Typically need to query the element(s) to determine current
// selection state.
Select
// Focus is sent when a Focusable element receives keyboard focus (ie: by tabbing).
Focus
// FocusLost is sent when a Focusable element loses keyboard focus.
FocusLost
// Attend is sent when a Pressable element is programmatically set
// as Attended through an event. Typically the Attended state is engaged
// by clicking. Attention is like Focus, in that there is only 1 element
// at a time in the Attended state, but it does not direct keyboard input.
// The primary effect of attention is on scrolling events via
// [abilities.ScrollableUnattended].
Attend
// AttendLost is sent when a different Pressable element is Attended.
AttendLost
// Change is when a value represented by the element has been changed
// by the user and committed (for example, someone has typed text in a
// textfield and then pressed enter). This is *not* triggered when
// the value has not been committed; see [Input] for that.
// This is for Editable, Checkable, and Slidable items.
Change
// Input is when a value represented by the element has changed, but
// has not necessarily been committed (for example, this triggers each
// time someone presses a key in a text field). This *is* triggered when
// the value has not been committed; see [Change] for a version that only
// occurs when the value is committed.
// This is for Editable, Checkable, and Slidable items.
Input
// Show is sent to widgets when their Scene is first shown to the user
// in its final form, and whenever a major content managing widget
// (e.g., [core.Tabs], [core.Pages]) shows a new tab/page/element (via
// [core.WidgetBase.Shown] or DeferShown). This can be used for updates
// that depend on other elements, or relatively expensive updates that
// should be only done when actually needed "at show time".
Show
// Close is sent to widgets when their Scene is being closed. This is an
// opportunity to save unsaved edits, for example. This is guaranteed to
// only happen once per widget per Scene.
Close
// Window reports on changes in the window position,
// visibility (iconify), focus changes, screen update, and closing.
// These are only sent once per event (Unique).
Window
// WindowResize happens when the window has been resized,
// which can happen continuously during a user resizing
// episode. These are not Unique events, and are compressed
// to minimize lag.
WindowResize
// WindowPaint is sent continuously at FPS frequency
// (60 frames per second by default) to drive updating check
// on the window. It is not unique, will be compressed
// to keep pace with updating.
WindowPaint
// OS is an operating system generated event (app level typically)
OS
// OSOpenFiles is an event telling app to open given files
OSOpenFiles
// Custom is a user-defined event with a data any field
Custom
)
// IsKey returns true if event type is a Key type
func (tp Types) IsKey() bool {
return tp >= KeyDown && tp <= KeyChord
}
// IsMouse returns true if event type is a Mouse type
func (tp Types) IsMouse() bool {
return tp >= MouseDown && tp <= LongHoverEnd
}
// IsTouch returns true if event type is a Touch type
func (tp Types) IsTouch() bool {
return tp >= TouchStart && tp <= Rotate
}
// IsDrag returns true if event type is a Drag type
func (tp Types) IsDrag() bool {
return tp >= DragStart && tp <= DragLeave
}
// IsSlide returns true if event type is a Slide type
func (tp Types) IsSlide() bool {
return tp >= SlideStart && tp <= SlideStop
}
// IsWindow returns true if event type is a Window type
func (tp Types) IsWindow() bool {
return tp >= Window && tp <= WindowPaint
}
// EventFlags encode boolean event properties
type EventFlags int32 //enums:bitflag
const (
// Handled indicates that the event has been handled
Handled EventFlags = iota
// EventUnique indicates that the event is Unique and not
// to be compressed with like events.
Unique
)
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package events
import (
"fmt"
)
// WindowEvent reports on actions taken on a window.
// The system.Window Flags and other state information
// will always be updated prior to this event being sent,
// so those should be consulted directly for the new current state.
type WindowEvent struct {
Base
// Action taken on the window -- what has changed.
// Window state fields have current values.
Action WinActions
}
func NewWindow(act WinActions) *WindowEvent {
ev := &WindowEvent{}
ev.Action = act
ev.Typ = Window
ev.SetUnique()
return ev
}
func NewWindowResize() *WindowEvent {
ev := &WindowEvent{}
ev.Typ = WindowResize
// not unique
return ev
}
func NewWindowPaint() *WindowEvent {
ev := &WindowEvent{}
ev.Typ = WindowPaint
// not unique
return ev
}
func (ev *WindowEvent) HasPos() bool {
return false
}
func (ev *WindowEvent) String() string {
return fmt.Sprintf("%v{Action: %v, Time: %v}", ev.Type(), ev.Action, ev.Time().Format("04:05"))
}
// WinActions is the action taken on the window by the user.
type WinActions int32 //enums:enum -trim-prefix Win
const (
// NoWinAction is the zero value for special types (Resize, Paint)
NoWinAction WinActions = iota
// WinClose means that the window is about to close, but has not yet closed.
WinClose
// WinMinimize means that the window has been iconified / miniaturized / is no
// longer visible.
WinMinimize
// WinMove means that the window was moved but NOT resized or changed in any
// other way -- does not require a redraw, but anything tracking positions
// will want to update.
WinMove
// WinFocus indicates that the window has been activated for receiving user
// input.
WinFocus
// WinFocusLost indicates that the window is no longer activated for
// receiving input.
WinFocusLost
// WinShow is for the WindowShow event -- sent by the system shortly
// after the window has opened, to ensure that full rendering
// is completed with the proper size, and to trigger one-time actions such as
// configuring the main menu after the window has opened.
WinShow
// ScreenUpdate occurs when any of the screen information is updated
// This event is sent to the first window on the list of active windows
// and it should then perform any necessary updating
ScreenUpdate
)
// Command async demonstrates async updating in Cogent Core.
package main
import (
"time"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
)
type tableStruct struct {
Icon icons.Icon
IntField int
FloatField float32
StrField string
File core.Filename
}
const rows = 100000
func main() {
table := make([]*tableStruct, 0, rows)
b := core.NewBody("Async Updating")
tv := core.NewTable(b)
tv.SetReadOnly(true)
tv.SetSlice(&table)
b.OnShow(func(e events.Event) {
go func() {
for i := range rows {
b.AsyncLock()
table = append(table, &tableStruct{IntField: i, FloatField: float32(i) / 10.0})
tv.Update()
if len(table) > 0 {
tv.ScrollToIndex(len(table) - 1)
}
b.AsyncUnlock()
time.Sleep(1 * time.Millisecond)
}
}()
})
b.RunMainWindow()
}
package main
import "cogentcore.org/core/core"
func main() {
b := core.NewBody()
core.NewButton(b).SetText("Hello, World!")
b.RunMainWindow()
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
//go:generate core generate
import (
"embed"
"fmt"
"image"
"strconv"
"strings"
"time"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/fileinfo"
"cogentcore.org/core/base/strcase"
"cogentcore.org/core/colors"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/highlighting"
"cogentcore.org/core/text/highlighting/lexers"
"cogentcore.org/core/text/textcore"
"cogentcore.org/core/tree"
)
//go:embed demo.go
var demoFile embed.FS
func main() {
b := core.NewBody("Cogent Core Demo")
makeBody(b)
b.RunMainWindow()
}
// makeBody makes the content of the demo in the given body.
func makeBody(b *core.Body) {
highlighting.AddLexers(lexers.XML)
ts := core.NewTabs(b)
// The content of each tab is made when the tab is first shown.
ts.NewLazyTab("Home", home)
ts.NewLazyTab("Widgets", widgets)
ts.NewLazyTab("Collections", collections)
ts.NewLazyTab("Value binding", valueBinding)
ts.NewLazyTab("Styles", makeStyles)
}
func home(tab *core.Frame) {
tab.Styler(func(s *styles.Style) {
s.CenterAll()
})
errors.Log(core.NewSVG(tab).ReadString(core.AppIcon))
core.NewText(tab).SetType(core.TextDisplayLarge).SetText("The Cogent Core Demo")
core.NewText(tab).SetType(core.TextTitleLarge).SetText(`A <b>demonstration</b> of the <i>various</i> features of the <a href="https://cogentcore.org/core">Cogent Core</a> 2D and 3D Go GUI <u>framework</u>`)
}
func widgets(tab *core.Frame) {
wts := core.NewTabs(tab)
wts.NewLazyTab("Text", text)
wts.NewLazyTab("Buttons", buttons)
wts.NewLazyTab("Inputs", inputs)
wts.NewLazyTab("Sliders", sliders)
wts.NewLazyTab("Dialogs", dialogs)
wts.NewLazyTab("Text editors", textEditors)
}
func text(tab *core.Frame) {
core.NewText(tab).SetType(core.TextHeadlineLarge).SetText("Text")
core.NewText(tab).SetText("Cogent Core provides fully customizable text elements that can be styled in any way you want. Also, there are pre-configured style types for text that allow you to easily create common text types.")
for _, typ := range core.TextTypesValues() {
s := strcase.ToSentence(typ.String())
core.NewText(tab).SetType(typ).SetText(s)
}
core.NewText(tab).SetText("Emojis: 🧁🍰🎁")
core.NewText(tab).SetText("Hebrew/RTL: אָהַבְתָּ אֵת יְיָ | אֱלֹהֶיךָ, בְּכָל-לְבָֽבְךָ, Let there be light וּבְכָל-נַפְשְׁךָ,")
core.NewText(tab).SetText("Chinese/Japanese/Korean: 国際化活動・計算機科学を勉強する・한국어")
}
func makeRow(parent core.Widget) *core.Frame {
row := core.NewFrame(parent)
row.Styler(func(s *styles.Style) {
s.Wrap = true
s.Align.Items = styles.Center
})
return row
}
func buttons(tab *core.Frame) {
core.NewText(tab).SetType(core.TextHeadlineLarge).SetText("Buttons")
core.NewText(tab).SetText("Cogent Core provides customizable buttons that support various events and can be styled in any way you want. Also, there are pre-configured style types for buttons that allow you to achieve common functionality with ease. All buttons support any combination of text, an icon, and an indicator.")
rowm := makeRow(tab)
rowti := makeRow(tab)
rowt := makeRow(tab)
rowi := makeRow(tab)
menu := func(m *core.Scene, pos image.Point) {
m1 := core.NewButton(m).SetText("Menu Item 1").SetIcon(icons.Save).SetShortcut("Control+Shift+1")
m1.SetTooltip("A standard menu item with an icon")
m1.OnClick(func(e events.Event) {
fmt.Println("Clicked on menu item 1")
})
m2 := core.NewButton(m).SetText("Menu Item 2").SetIcon(icons.Open)
m2.SetTooltip("A menu item with an icon and a sub menu")
m2.Menu = func(m *core.Scene, pos image.Point) {
sm2 := core.NewButton(m).SetText("Sub Menu Item 2").SetIcon(icons.InstallDesktop).
SetTooltip("A sub menu item with an icon")
sm2.OnClick(func(e events.Event) {
fmt.Println("Clicked on sub menu item 2")
})
}
core.NewSeparator(m)
m3 := core.NewButton(m).SetText("Menu Item 3").SetIcon(icons.Favorite).SetShortcut("Control+3").
SetTooltip("A standard menu item with an icon, below a separator")
m3.OnClick(func(e events.Event) {
fmt.Println("Clicked on menu item 3")
})
}
ics := []icons.Icon{
icons.Search, icons.Home, icons.Close, icons.Done, icons.Favorite, icons.PlayArrow,
icons.Add, icons.Delete, icons.ArrowBack, icons.Info, icons.Refresh, icons.VideoCall,
icons.Menu, icons.Settings, icons.AccountCircle, icons.Download, icons.Sort, icons.DateRange,
}
for _, typ := range core.ButtonTypesValues() {
// not really a real button, so not worth including in demo
if typ == core.ButtonMenu {
continue
}
s := strings.TrimPrefix(typ.String(), "Button")
sl := strings.ToLower(s)
art := "A "
if typ == core.ButtonElevated || typ == core.ButtonOutlined || typ == core.ButtonAction {
art = "An "
}
core.NewButton(rowm).SetType(typ).SetText(s).SetIcon(ics[typ]).SetMenu(menu).
SetTooltip(art + sl + " menu button with text and an icon")
b := core.NewButton(rowti).SetType(typ).SetText(s).SetIcon(ics[typ+6]).
SetTooltip("A " + sl + " button with text and an icon")
b.OnClick(func(e events.Event) {
fmt.Println("Got click event on", b.Name)
})
bt := core.NewButton(rowt).SetType(typ).SetText(s).
SetTooltip("A " + sl + " button with text")
bt.OnClick(func(e events.Event) {
fmt.Println("Got click event on", bt.Name)
})
bi := core.NewButton(rowi).SetType(typ).SetIcon(ics[typ+12]).
SetTooltip("A " + sl + " button with an icon")
bi.OnClick(func(e events.Event) {
fmt.Println("Got click event on", bi.Name)
})
}
}
func inputs(tab *core.Frame) {
core.NewText(tab).SetType(core.TextHeadlineLarge).SetText("Inputs")
core.NewText(tab).SetText("Cogent Core provides various customizable input widgets that cover all common uses. Various events can be bound to inputs, and their data can easily be fetched and used wherever needed. There are also pre-configured style types for most inputs that allow you to easily switch among common styling patterns.")
core.NewTextField(tab).SetPlaceholder("Text field")
core.NewTextField(tab).AddClearButton().SetLeadingIcon(icons.Search)
core.NewTextField(tab).SetType(core.TextFieldOutlined).SetTypePassword().SetPlaceholder("Password")
core.NewTextField(tab).SetText("Text field with relatively long initial text")
spinners := core.NewFrame(tab)
core.NewSpinner(spinners).SetStep(5).SetMin(-50).SetMax(100).SetValue(15)
core.NewSpinner(spinners).SetFormat("%X").SetStep(1).SetMax(255).SetValue(44)
choosers := core.NewFrame(tab)
fruits := []core.ChooserItem{
{Value: "Apple", Tooltip: "A round, edible fruit that typically has red skin"},
{Value: "Apricot", Tooltip: "A stonefruit with a yellow or orange color"},
{Value: "Blueberry", Tooltip: "A small blue or purple berry"},
{Value: "Blackberry", Tooltip: "A small, edible, dark fruit"},
{Value: "Peach", Tooltip: "A fruit with yellow or white flesh and a large seed"},
{Value: "Strawberry", Tooltip: "A widely consumed small, red fruit"},
}
core.NewChooser(choosers).SetPlaceholder("Select a fruit").SetItems(fruits...).SetAllowNew(true)
core.NewChooser(choosers).SetPlaceholder("Select a fruit").SetItems(fruits...).SetType(core.ChooserOutlined)
core.NewChooser(tab).SetEditable(true).SetPlaceholder("Select or type a fruit").SetItems(fruits...).SetAllowNew(true)
core.NewChooser(tab).SetEditable(true).SetPlaceholder("Select or type a fruit").SetItems(fruits...).SetType(core.ChooserOutlined)
core.NewSwitch(tab).SetText("Toggle")
core.NewSwitches(tab).SetItems(
core.SwitchItem{Value: "Switch 1", Tooltip: "The first switch"},
core.SwitchItem{Value: "Switch 2", Tooltip: "The second switch"},
core.SwitchItem{Value: "Switch 3", Tooltip: "The third switch"})
core.NewSwitches(tab).SetType(core.SwitchChip).SetStrings("Chip 1", "Chip 2", "Chip 3")
core.NewSwitches(tab).SetType(core.SwitchCheckbox).SetStrings("Checkbox 1", "Checkbox 2", "Checkbox 3")
cs := core.NewSwitches(tab).SetType(core.SwitchCheckbox).SetStrings("Indeterminate 1", "Indeterminate 2", "Indeterminate 3")
cs.SetOnChildAdded(func(n tree.Node) {
core.AsWidget(n).SetState(true, states.Indeterminate)
})
core.NewSwitches(tab).SetType(core.SwitchRadioButton).SetMutex(true).SetStrings("Radio Button 1", "Radio Button 2", "Radio Button 3")
rs := core.NewSwitches(tab).SetType(core.SwitchRadioButton).SetMutex(true).SetStrings("Indeterminate 1", "Indeterminate 2", "Indeterminate 3")
rs.SetOnChildAdded(func(n tree.Node) {
core.AsWidget(n).SetState(true, states.Indeterminate)
})
core.NewSwitches(tab).SetType(core.SwitchSegmentedButton).SetMutex(true).SetStrings("Segmented Button 1", "Segmented Button 2", "Segmented Button 3")
}
func sliders(tab *core.Frame) {
core.NewText(tab).SetType(core.TextHeadlineLarge).SetText("Sliders and meters")
core.NewText(tab).SetText("Cogent Core provides interactive sliders and customizable meters, allowing you to edit and display bounded numbers.")
core.NewSlider(tab)
core.NewSlider(tab).SetValue(0.7).SetState(true, states.Disabled)
csliders := core.NewFrame(tab)
core.NewSlider(csliders).SetValue(0.3).Styler(func(s *styles.Style) {
s.Direction = styles.Column
})
core.NewSlider(csliders).SetValue(0.2).SetState(true, states.Disabled).Styler(func(s *styles.Style) {
s.Direction = styles.Column
})
core.NewMeter(tab).SetType(core.MeterCircle).SetValue(0.7).SetText("70%")
core.NewMeter(tab).SetType(core.MeterSemicircle).SetValue(0.7).SetText("70%")
core.NewMeter(tab).SetValue(0.7)
core.NewMeter(tab).SetValue(0.7).Styler(func(s *styles.Style) {
s.Direction = styles.Column
})
}
func textEditors(tab *core.Frame) {
core.NewText(tab).SetType(core.TextHeadlineLarge).SetText("Text editors")
core.NewText(tab).SetText("Cogent Core provides powerful text editors that support advanced code editing features, like syntax highlighting, completion, undo and redo, copy and paste, rectangular selection, and word, line, and page based navigation, selection, and deletion.")
sp := core.NewSplits(tab)
ed := textcore.NewEditor(sp)
ed.Styler(func(s *styles.Style) {
s.Padding.Set(units.Em(core.ConstantSpacing(1)))
})
ed.Lines.OpenFS(demoFile, "demo.go")
textcore.NewEditor(sp).Lines.SetLanguage(fileinfo.SVG).SetString(core.AppIcon)
}
func valueBinding(tab *core.Frame) {
core.NewText(tab).SetType(core.TextHeadlineLarge).SetText("Value binding")
core.NewText(tab).SetText("Cogent Core provides the value binding system, which allows you to instantly bind Go values to interactive widgets with just a single simple line of code.")
name := "Gopher"
core.Bind(&name, core.NewTextField(tab)).OnChange(func(e events.Event) {
fmt.Println("Your name is now", name)
})
age := 35
core.Bind(&age, core.NewSpinner(tab)).OnChange(func(e events.Event) {
fmt.Println("Your age is now", age)
})
on := true
core.Bind(&on, core.NewSwitch(tab)).OnChange(func(e events.Event) {
fmt.Println("The switch is now", on)
})
theme := core.ThemeLight
core.Bind(&theme, core.NewSwitches(tab)).OnChange(func(e events.Event) {
fmt.Println("The theme is now", theme)
})
var state states.States
state.SetFlag(true, states.Hovered)
state.SetFlag(true, states.Dragging)
core.Bind(&state, core.NewSwitches(tab)).OnChange(func(e events.Event) {
fmt.Println("The state is now", state)
})
color := colors.Orange
core.Bind(&color, core.NewColorButton(tab)).OnChange(func(e events.Event) {
fmt.Println("The color is now", color)
})
colorMap := core.ColorMapName("ColdHot")
core.Bind(&colorMap, core.NewColorMapButton(tab)).OnChange(func(e events.Event) {
fmt.Println("The color map is now", colorMap)
})
t := time.Now()
core.Bind(&t, core.NewTimeInput(tab)).OnChange(func(e events.Event) {
fmt.Println("The time is now", t)
})
duration := 5 * time.Minute
core.Bind(&duration, core.NewDurationInput(tab)).OnChange(func(e events.Event) {
fmt.Println("The duration is now", duration)
})
file := core.Filename("demo.go")
core.Bind(&file, core.NewFileButton(tab)).OnChange(func(e events.Event) {
fmt.Println("The file is now", file)
})
font := core.AppearanceSettings.Text.SansSerif
core.Bind(&font, core.NewFontButton(tab)).OnChange(func(e events.Event) {
fmt.Println("The font is now", font)
})
core.Bind(hello, core.NewFuncButton(tab)).SetShowReturn(true)
core.Bind(styles.NewStyle, core.NewFuncButton(tab)).SetConfirm(true).SetShowReturn(true)
core.NewButton(tab).SetText("Inspector").OnClick(func(e events.Event) {
core.InspectorWindow(tab.Scene)
})
}
// Hello displays a greeting message and an age in weeks based on the given information.
func hello(firstName string, lastName string, age int, likesGo bool) (greeting string, weeksOld int) { //types:add
weeksOld = age * 52
greeting = "Hello, " + firstName + " " + lastName + "! "
if likesGo {
greeting += "I'm glad to hear that you like the best programming language!"
} else {
greeting += "You should reconsider what programming languages you like."
}
return
}
func collections(tab *core.Frame) {
core.NewText(tab).SetType(core.TextHeadlineLarge).SetText("Collections")
core.NewText(tab).SetText("Cogent Core provides powerful collection widgets that allow you to easily view and edit complex data types like structs, maps, and slices, allowing you to easily create widgets like lists, tables, and forms.")
vts := core.NewTabs(tab)
str := testStruct{
Name: "Go",
Condition: 2,
Value: 3.1415,
Vector: math32.Vec2(5, 7),
Inline: inlineStruct{Value: 3},
Condition2: tableStruct{
Age: 22,
Score: 44.4,
Name: "foo",
File: "core.go",
},
Table: make([]tableStruct, 2),
List: []float32{0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7},
}
ftab, _ := vts.NewTab("Forms")
core.NewForm(ftab).SetStruct(&str)
sl := make([]string, 50)
for i := 0; i < len(sl); i++ {
sl[i] = fmt.Sprintf("element %d", i)
}
sl[10] = "this is a particularly long value"
ltab, _ := vts.NewTab("Lists")
core.NewList(ltab).SetSlice(&sl)
mp := map[string]string{}
mp["Go"] = "Elegant, fast, and easy-to-use"
mp["Python"] = "Slow and duck-typed"
mp["C++"] = "Hard to use and slow to compile"
ktab, _ := vts.NewTab("Keyed lists")
core.NewKeyedList(ktab).SetMap(&mp)
tbl := make([]*tableStruct, 50)
for i := range tbl {
ts := &tableStruct{Age: i, Score: float32(i) / 10}
tbl[i] = ts
}
tbl[0].Name = "this is a particularly long field"
ttab, _ := vts.NewTab("Tables")
core.NewTable(ttab).SetSlice(&tbl)
sp := core.NewSplits(vts.NewTab("Trees")).SetSplits(0.3, 0.7)
tr := core.NewTree(core.NewFrame(sp)).SetText("Root")
makeTree(tr, 0)
sv := core.NewForm(sp).SetStruct(tr)
tr.OnSelect(func(e events.Event) {
if len(tr.SelectedNodes) > 0 {
sv.SetStruct(tr.SelectedNodes[0]).Update()
}
})
}
func makeTree(tr *core.Tree, round int) {
if round > 2 {
return
}
for i := range 3 {
n := core.NewTree(tr).SetText("Child " + strconv.Itoa(i))
makeTree(n, round+1)
}
}
type tableStruct struct { //types:add
// an icon
Icon icons.Icon
// an integer field
Age int `default:"2"`
// a float field
Score float32
// a string field
Name string
// a file
File core.Filename
}
type inlineStruct struct { //types:add
// this is now showing
ShowMe string
// click to show next
On bool
// a condition
Condition int `default:"0"`
// if On && Condition == 0
Condition1 string
// if On && Condition <= 1
Condition2 tableStruct
// a value
Value float32 `default:"1"`
}
func (il *inlineStruct) ShouldDisplay(field string) bool {
switch field {
case "ShowMe", "Condition":
return il.On
case "Condition1":
return il.On && il.Condition == 0
case "Condition2":
return il.On && il.Condition <= 1
}
return true
}
type testStruct struct { //types:add
// An enum value
Enum core.ButtonTypes
// a string
Name string `default:"Go" width:"50"`
// click to show next
ShowNext bool
// this is now showing
ShowMe string
// inline struct
Inline inlineStruct `display:"inline"`
// a condition
Condition int
// if Condition == 0
Condition1 string
// if Condition >= 0
Condition2 tableStruct
// a value
Value float32
// a vector
Vector math32.Vector2
// a slice of structs
Table []tableStruct
// a slice of floats
List []float32
// a file
File core.Filename
}
func (ts *testStruct) ShouldDisplay(field string) bool {
switch field {
case "Name":
return ts.Enum <= core.ButtonElevated
case "ShowMe":
return ts.ShowNext
case "Condition1":
return ts.Condition == 0
case "Condition2":
return ts.Condition >= 0
}
return true
}
func dialogs(tab *core.Frame) {
core.NewText(tab).SetType(core.TextHeadlineLarge).SetText("Dialogs, snackbars, and windows")
core.NewText(tab).SetText("Cogent Core provides completely customizable dialogs, snackbars, and windows that allow you to easily display, obtain, and organize information.")
core.NewText(tab).SetType(core.TextHeadlineSmall).SetText("Dialogs")
drow := makeRow(tab)
md := core.NewButton(drow).SetText("Message")
md.OnClick(func(e events.Event) {
core.MessageDialog(md, "Something happened", "Message")
})
ed := core.NewButton(drow).SetText("Error")
ed.OnClick(func(e events.Event) {
core.ErrorDialog(ed, errors.New("invalid encoding format"), "Error loading file")
})
cd := core.NewButton(drow).SetText("Confirm")
cd.OnClick(func(e events.Event) {
d := core.NewBody("Confirm")
core.NewText(d).SetType(core.TextSupporting).SetText("Send message?")
d.AddBottomBar(func(bar *core.Frame) {
d.AddCancel(bar).OnClick(func(e events.Event) {
core.MessageSnackbar(cd, "Dialog canceled")
})
d.AddOK(bar).OnClick(func(e events.Event) {
core.MessageSnackbar(cd, "Dialog accepted")
})
})
d.RunDialog(cd)
})
td := core.NewButton(drow).SetText("Input")
td.OnClick(func(e events.Event) {
d := core.NewBody("Input")
core.NewText(d).SetType(core.TextSupporting).SetText("What is your name?")
tf := core.NewTextField(d)
d.AddBottomBar(func(bar *core.Frame) {
d.AddCancel(bar)
d.AddOK(bar).OnClick(func(e events.Event) {
core.MessageSnackbar(td, "Your name is "+tf.Text())
})
})
d.RunDialog(td)
})
tdd := core.NewButton(drow).SetText("Editor")
tdd.OnClick(func(e events.Event) {
d := core.NewBody("Editor")
core.NewText(d).SetType(core.TextSupporting).SetText("What is your name?")
ed := textcore.NewEditor(d)
d.AddBottomBar(func(bar *core.Frame) {
d.AddCancel(bar)
d.AddOK(bar).OnClick(func(e events.Event) {
core.MessageSnackbar(td, "Your name is "+ed.Lines.String())
})
})
d.RunDialog(tdd)
})
fd := core.NewButton(drow).SetText("Full window")
u := &core.User{}
fd.OnClick(func(e events.Event) {
d := core.NewBody("Full window dialog")
core.NewText(d).SetType(core.TextSupporting).SetText("Edit your information")
core.NewForm(d).SetStruct(u).OnInput(func(e events.Event) {
fmt.Println("Got input event")
})
d.OnClose(func(e events.Event) {
fmt.Println("Your information is:", u)
})
d.RunFullDialog(td)
})
nd := core.NewButton(drow).SetText("New window")
nd.OnClick(func(e events.Event) {
d := core.NewBody("New window dialog")
core.NewText(d).SetType(core.TextSupporting).SetText("This dialog opens in a new window on multi-window platforms")
d.RunWindowDialog(nd)
})
core.NewText(tab).SetType(core.TextHeadlineSmall).SetText("Snackbars")
srow := makeRow(tab)
ms := core.NewButton(srow).SetText("Message")
ms.OnClick(func(e events.Event) {
core.MessageSnackbar(ms, "New messages loaded")
})
es := core.NewButton(srow).SetText("Error")
es.OnClick(func(e events.Event) {
core.ErrorSnackbar(es, errors.New("file not found"), "Error loading page")
})
cs := core.NewButton(srow).SetText("Custom")
cs.OnClick(func(e events.Event) {
core.NewBody().AddSnackbarText("Files updated").
AddSnackbarButton("Refresh", func(e events.Event) {
core.MessageSnackbar(cs, "Refreshed files")
}).AddSnackbarIcon(icons.Close).RunSnackbar(cs)
})
core.NewText(tab).SetType(core.TextHeadlineSmall).SetText("Windows")
wrow := makeRow(tab)
nw := core.NewButton(wrow).SetText("New window")
nw.OnClick(func(e events.Event) {
d := core.NewBody("New window")
core.NewText(d).SetType(core.TextHeadlineSmall).SetText("New window")
core.NewText(d).SetType(core.TextSupporting).SetText("A standalone window that opens in a new window on multi-window platforms")
d.RunWindow()
})
fw := core.NewButton(wrow).SetText("Full window")
fw.OnClick(func(e events.Event) {
d := core.NewBody("Full window")
core.NewText(d).SetType(core.TextSupporting).SetText("A standalone window that opens in the same system window")
d.NewWindow().SetNewWindow(false).SetDisplayTitle(true).Run()
})
core.NewText(tab).SetType(core.TextHeadlineSmall).SetText("Window manipulations")
mrow := makeRow(tab)
rw := core.NewButton(mrow).SetText("Resize to content")
rw.SetTooltip("Resizes this window to fit the current content on multi-window platforms")
rw.OnClick(func(e events.Event) {
mrow.Scene.ResizeToContent(image.Pt(0, 40)) // note: size is not correct due to wrapping? #1307
})
fs := core.NewButton(mrow).SetText("Fullscreen")
fs.SetTooltip("Toggle fullscreen mode on desktop and web platforms")
fs.OnClick(func(e events.Event) {
mrow.Scene.SetFullscreen(!mrow.Scene.IsFullscreen())
})
sg := core.NewButton(mrow).SetText("Set geometry")
sg.SetTooltip("Move the window to the top-left corner of the second screen and resize it on desktop platforms")
sg.OnClick(func(e events.Event) {
mrow.Scene.SetGeometry(false, image.Pt(30, 100), image.Pt(1000, 1000), 1)
})
}
func makeStyles(tab *core.Frame) {
core.NewText(tab).SetType(core.TextHeadlineLarge).SetText("Styles and layouts")
core.NewText(tab).SetText("Cogent Core provides a fully customizable styling and layout system that allows you to easily control the position, size, and appearance of all widgets. You can edit the style properties of the outer frame below.")
// same as docs advanced styling demo
sp := core.NewSplits(tab)
fm := core.NewForm(sp)
fr := core.NewFrame(core.NewFrame(sp)) // can not control layout when directly in splits
fr.Styler(func(s *styles.Style) {
s.Background = colors.Scheme.Select.Container
s.Grow.Set(1, 1)
})
fr.Style() // must style immediately to get correct default values
fm.SetStruct(&fr.Styles)
fm.OnChange(func(e events.Event) {
fr.OverrideStyle = true
fr.Update()
})
frameSizes := []math32.Vector2{
{X: 20, Y: 100},
{X: 80, Y: 20},
{X: 60, Y: 80},
{X: 40, Y: 120},
{X: 150, Y: 100},
}
for _, sz := range frameSizes {
core.NewFrame(fr).Styler(func(s *styles.Style) {
s.Min.Set(units.Dp(sz.X), units.Dp(sz.Y))
s.Background = colors.Scheme.Primary.Base
})
}
}
package main
import (
"cogentcore.org/core/base/errors"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/styles"
"cogentcore.org/core/video"
)
func main() {
b := core.NewBody("Video Example")
v := video.NewVideo(b)
// the standard controls, shown when the mouse is over the video
// (those of the browser on the web)
v.Controls = true
// v.Rotation = -90
v.Styler(func(s *styles.Style) {
s.Grow.Set(1, 1)
})
errors.Log(v.Open("deer.mp4"))
v.OnShow(func(e events.Event) {
v.Play(0, 0)
})
b.RunMainWindow()
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"image/color"
"math"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/colors"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/styles"
"cogentcore.org/core/text/text"
"cogentcore.org/core/tree"
"cogentcore.org/core/xyz"
"cogentcore.org/core/xyz/examples/assets"
_ "cogentcore.org/core/xyz/io/obj"
"cogentcore.org/core/xyz/xyzcore"
"cogentcore.org/core/math32"
)
func main() {
animOn := false
animSpeed := float32(0.01)
animGopher := true
animHoop := true
animAngle := float32(0)
bigGopher := true
b := core.NewBody("XYZ Demo")
core.NewText(b).SetText(`This is a demonstration of <b>XYZ</b>, the <a href="https://cogentcore.org/core">Cogent Core</a> <i>3D</i> framework`).
SetType(core.TextHeadlineSmall).
Styler(func(s *styles.Style) {
s.Text.Align = text.Center
s.Text.AlignV = text.Center
})
tf := core.NewFrame(b)
tf.Styler(func(s *styles.Style) {
s.Direction = styles.Row
})
se := xyzcore.NewSceneEditor(b)
se.UpdateWidget() // needed to create sub nodes:
sw := se.SceneWidget()
sc := se.SceneXYZ()
sw.SelectionMode = xyzcore.Manipulable
// options - must be set here
// sc.MultiSample = 1
// se.Wireframe = true
// sc.NoNav = true
core.Bind(&animOn, core.NewSwitch(tf).SetText("Toggle animation"))
bgs := core.NewSwitch(tf).SetText("Toggle big Gopher")
bgs.OnChange(func(e events.Event) {
sw.Update()
})
core.Bind(&bigGopher, bgs)
se.Styler(func(s *styles.Style) {
sc.Background = colors.Scheme.Select.Container
})
xyz.NewAmbient(sc, "ambient", 0.3, xyz.DirectSun)
xyz.NewDirectional(sc, "directional", 1, xyz.DirectSun).Pos.Set(0, 2, 1)
// xyz.NewPoint(sc, "point", 1, xyz.DirectSun).Pos.Set(-5, 0, 2)
// xyz.NewSpot(sc, "spot", 1, xyz.DirectSun).Pose.Pos.Set(0, 5, 5)
// se.Camera.Pose.Pos.Set(-2, 9, 3)
sc.Camera.Pose.Pos.Set(0, 2, 10)
// se.Camera.Pose.Pos.Set(0, 0, 10) // default position
sc.Camera.LookAt(math32.Vector3{}, math32.Vec3(0, 1, 0)) // defaults to looking at origin
cube := xyz.NewBox(sc, "cube1", 1, 1, 1)
cube.Segs.Set(10, 10, 10) // not clear if any diff really..
tree.AddChild(sc, func(g *xyz.Group) {
tree.AddChild(g, func(n *xyz.Solid) {
n.SetMesh(cube).SetColor(colors.Red).SetShiny(500).SetPos(-1, 0, 0)
})
tree.AddChild(g, func(n *xyz.Solid) {
n.SetMesh(cube).SetColor(colors.Blue).SetShiny(10).SetReflective(0.2).
SetPos(1, 1, 0)
n.Pose.Scale.X = 2
})
tree.AddChild(g, func(n *xyz.Solid) {
// alpha = .5 -- note: colors are NOT premultiplied here: will become so when rendered!
n.SetMesh(cube).SetColor(color.RGBA{0, 255, 0, 128}).SetShiny(20).SetPos(0, 0, 1)
})
})
grtx := xyz.NewTextureFileFS(assets.Content, sc, "ground", "ground.png")
floorp := xyz.NewPlane(sc, "floor-plane", 100, 100)
tree.AddChild(sc, func(n *xyz.Solid) {
n.SetMesh(floorp).SetColor(colors.Tan).SetTexture(grtx).SetPos(0, -5, 0)
n.Material.Tiling.Repeat.Set(40, 40)
// n.Mat.Emissive.SetName("brown")
// n.Mat.Bright = 2 // .5 for wood / brown
// n.SetDisabled() // not selectable
})
lines := xyz.NewLines(sc, "Lines", []math32.Vector3{{X: -3, Y: -1, Z: 0}, {X: -2, Y: 1, Z: 0}, {X: 2, Y: 1, Z: 0}, {X: 3, Y: -1, Z: 0}}, math32.Vec2(.2, .1), xyz.CloseLines)
tree.AddChild(sc, func(n *xyz.Solid) {
n.SetMesh(lines).SetColor(color.RGBA{255, 255, 0, 128}).SetPos(0, 0, 1)
})
// this line should go from lower left front of red cube to upper vertex of above hi-line
tree.AddChild(sc, func(g *xyz.Group) {
xyz.InitArrow(g, math32.Vec3(-1.5, -.5, .5), math32.Vec3(2, 1, 1), .05, colors.Cyan, xyz.StartArrow, xyz.EndArrow, 4, .5, 8)
})
cylinder := xyz.NewCylinder(sc, "cylinder", 1.5, .5, 32, 1, xyz.WithTop, xyz.WithBottom)
tree.AddChild(sc, func(n *xyz.Solid) {
n.SetMesh(cylinder).SetPos(-2.25, 0, 0)
})
capsule := xyz.NewCapsule(sc, "capsule", 1.5, .5, 32, 1)
tree.AddChild(sc, func(n *xyz.Solid) {
n.SetMesh(capsule).SetColor(colors.Tan).SetPos(3.25, 0, 0)
})
sphere := xyz.NewSphere(sc, "sphere", .75, 32)
tree.AddChild(sc, func(n *xyz.Solid) {
n.SetMesh(sphere).SetColor(colors.Orange).SetPos(0, -2, 0)
n.Material.Color.A = 200
})
// Good strategy for objects if used in multiple places is to load
// into library, then add from there.
lgo := errors.Log1(sc.OpenToLibraryFS(assets.Content, "gopher.obj", ""))
lgo.Pose.SetAxisRotation(0, 1, 0, -90) // for all cases
var smallGo *xyz.Object
var goPos math32.Vector3
tree.AddChild(sc, func(g *xyz.Group) {
g.Maker(func(p *tree.Plan) {
if bigGopher {
tree.Add(p, func(n *xyz.Object) {
n.SetObjectName("gopher").SetScale(.5, .5, .5).SetPos(1.4, -2.5, 0)
n.SetAxisRotation(0, 1, 0, -60)
})
}
tree.Add(p, func(n *xyz.Object) {
smallGo = n
n.SetObjectName("gopher").SetPos(-1.5, -2, 0).SetScale(.2, .2, .2)
goPos = n.Pose.Pos
})
})
})
torus := xyz.NewTorus(sc, "torus", .75, .1, 32)
var hoop *xyz.Solid
var hoopPos math32.Vector3
tree.AddChild(sc, func(n *xyz.Solid) {
n.SetMesh(torus).SetColor(colors.White).SetPos(-1.6, -1.6, -.2).SetAxisRotation(1, 0, 0, 90)
n.Material.Color.A = 200
hoop = n
hoopPos = hoop.Pose.Pos
})
tree.AddChild(sc, func(n *xyz.Text2D) {
n.SetText("Text2D can put <b>HTML</b> formatted Text<br> anywhere you might <i>want</i>").SetPos(0, 2.2, 0)
n.Styles.Text.Align = text.Center
n.Pose.Scale.SetScalar(0.2)
})
// automatically tracks camera -- FPS effect
tree.AddChildAt(sc, xyz.TrackCameraName, func(g *xyz.Group) {
tree.AddChild(g, func(n *xyz.Solid) {
// in front of camera
n.SetMesh(cube).SetScale(.1, .1, 1).SetPos(.5, -.5, -2.5).
SetColor(color.RGBA{255, 0, 255, 128})
})
})
/////// Animation & Embedded controls
radius := float32(0.3)
sw.Animate(func(a *core.Animation) {
if !animOn {
return
}
if animHoop {
tdx := radius * math32.Cos(animAngle)
tdz := radius * math32.Sin(animAngle)
tp := hoopPos
tp.X += tdx
tp.Z += tdz
hoop.SetPosePos(tp)
}
if animGopher {
gdx := 0.1 * radius * math32.Cos(animAngle+math.Pi)
gdz := 0.1 * radius * math32.Sin(animAngle+math.Pi)
gp := goPos
gp.X += gdx
gp.Z += gdz
smallGo.SetPosePos(gp)
}
sw.NeedsRender()
animAngle += animSpeed * a.Dt
})
/*
emb := xyz.NewEmbed2D(sc, sc, "embed-but", 150, 100, xyz.FitContent)
emb.Pose.Pos.Set(-2, 2, 0)
// emb.Zoom = 1.5 // this is how to rescale overall size
evlay := core.NewFrame(emb.Viewport, "vlay", core.LayoutVert)
evlay.SetProp("margin", units.Ex(1))
eabut := core.NewCheckBox(evlay, "anim-but")
eabut.SetText("Animate")
eabut.Tooltip = "toggle animation on and off"
eabut.ButtonSig.Connect(win.This, func(recv, send tree.Node, sig int64, data any) {
if sig == int64(core.ButtonToggled) {
anim.On = eabut.IsChecked()
}
})
cmb := core.NewButton(evlay, "anim-ctrl")
cmb.SetText("Anim Ctrl")
cmb.Tooltip = "options for what is animated (note: menu only works when not animating -- checkboxes would be more useful here but wanted to test menu function)"
cmb.Menu.AddAction(core.ActOpts{Label: "Toggle Torus"},
win.This, func(recv, send tree.Node, sig int64, data any) {
anim.DoTorus = !anim.DoTorus
})
cmb.Menu.AddAction(core.ActOpts{Label: "Toggle Gopher"},
win.This, func(recv, send tree.Node, sig int64, data any) {
anim.DoGopher = !anim.DoGopher
})
cmb.Menu.AddAction(core.ActOpts{Label: "Edit Anim"},
win.This, func(recv, send tree.Node, sig int64, data any) {
core.FormDialog(vp, anim, core.DlgOpts{Title: "Animation Parameters"}, nil, nil)
})
sprw := core.NewFrame(evlay, "speed-lay", core.LayoutHoriz)
core.NewText(sprw, "speed-text", "Speed: ")
sb := core.NewSpinBox(sprw, "anim-speed")
sb.SetMin(0.01)
sb.Step = 0.01
sb.SetValue(anim.Speed)
sb.Tooltip = "determines the speed of rotation (step size)"
spsld := core.NewSlider(evlay, "speed-slider")
spsld.Dim = math32.X
spsld.Min = 0.01
spsld.Max = 1
spsld.Step = 0.01
spsld.PageStep = 0.1
spsld.SetMinPrefWidth(units.Em(20))
spsld.SetMinPrefHeight(units.Em(2))
spsld.SetValue(anim.Speed)
// spsld.Tracking = true
spsld.Icon = icons.RadioButtonUnchecked
sb.SpinBoxSig.Connect(rec.This, func(recv, send tree.Node, sig int64, data any) {
anim.Speed = sb.Value
spsld.SetValue(anim.Speed)
})
spsld.SliderSig.Connect(rec.This, func(recv, send tree.Node, sig int64, data any) {
if core.SliderSignals(sig) == core.SliderValueChanged {
anim.Speed = data.(float32)
sb.SetValue(anim.Speed)
}
})
*/
b.RunMainWindow()
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package filetree
import (
"fmt"
"io/fs"
"log/slog"
"os"
"path/filepath"
"slices"
"strings"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/fileinfo"
"cogentcore.org/core/base/fileinfo/mimedata"
"cogentcore.org/core/base/fsx"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/text/textcore"
"cogentcore.org/core/tree"
)
// MimeData adds mimedata for this node: three items, a text/plain of the
// tree path, text/plain of the file path, and the file contents (or a
// text/plain message for a directory or a file that is too big or can't be read).
func (fn *Node) MimeData(md *mimedata.Mimes) {
froot := fn.FileRoot()
path := string(fn.Filepath)
punq := fn.PathFrom(froot) // note: tree paths have . escaped -> \,
*md = append(*md, mimedata.NewTextData(punq))
*md = append(*md, mimedata.NewTextData(path))
switch {
case fn.IsDir():
*md = append(*md, mimedata.NewTextData("Folder"))
case int(fn.Info.Size) >= core.SystemSettings.BigFileSize:
*md = append(*md, mimedata.NewTextData("File exceeds BigFileSize"))
default:
var b []byte
var err error
if froot.FS != nil {
b, err = fs.ReadFile(froot.FS, path)
} else {
b, err = os.ReadFile(path) // closes the file, which Windows can't delete while open
}
if err != nil {
slog.Error(err.Error())
*md = append(*md, mimedata.NewTextData(err.Error()))
return
}
*md = append(*md, &mimedata.Data{Type: fn.Info.Mime, Data: b})
}
}
// Cut copies the selected files to the clipboard and then deletes them.
func (fn *Node) Cut() { //types:add
if fn.IsRoot("Cut") {
return
}
fn.Copy()
// todo: move files somewhere temporary, then use those temps for paste..
core.MessageDialog(fn, "File names were copied to clipboard and can be pasted to copy elsewhere, but files are not deleted because contents of files are not placed on the clipboard and thus cannot be pasted as such. Use Delete to delete files.")
}
// Paste copies the files on the clipboard, from [Node.Copy] or as
// absolute paths in text, into this directory, or the directory of this file.
func (fn *Node) Paste() { //types:add
if !fn.canCopy() {
core.ErrorSnackbar(fn, errUnsupported)
return
}
fn.pasteMimeData(fn.Clipboard().Read([]string{fileinfo.TextPlain}))
}
// pasteMimeData pastes the files of the given clipboard data (see
// [Node.Paste]): those of a file tree of the same [Tree.FS] for a tree of
// an FS.
func (fn *Node) pasteMimeData(md mimedata.Mimes) {
if fn.isFS() { // only the files of this filesystem, from its trees
var paths []string
if isNodeData(md, false) {
for _, p := range filePaths(md) {
if fn.pathExists(p) {
paths = append(paths, p)
}
}
}
fn.pasteFiles(paths, false, nil)
return
}
fn.pasteFiles(clipboardPaths(md), false, nil)
}
func (fn *Node) DragDrop(e events.Event) {
de := e.(*events.DragDrop)
e.SetHandled()
md, _ := de.Data.(mimedata.Mimes)
var paths []string
var src *Node
if sn, ok := de.Source.(tree.Node); ok {
src = AsNode(sn)
}
if src != nil { // from a file tree, possibly in another window
paths = filePaths(md)
} else { // from another widget or app
paths = core.DroppedFiles(de)
}
if fn.isFS() || (src != nil && src.isFS()) {
// files of a [Tree.FS] only move and copy within its tree
switch {
case src == nil || src.FileRoot() != fn.FileRoot():
core.MessageSnackbar(fn, "Files can only be moved or copied within the same filesystem")
return
case !fn.canCopy() || (de.DropMod == events.DropMove && !src.canRemove()):
core.ErrorSnackbar(fn, errUnsupported)
return
}
}
fn.pasteFiles(paths, de.DropMod == events.DropMove, func(inPlace []string) {
if len(inPlace) > 0 { // already where they were moved to: not to be deleted
de.Data = withoutFiles(md, inPlace)
}
fn.DropFinalize(de)
})
}
// DragFiles returns the files of this node and the other selected nodes,
// for dragging them to other apps (see [core.FileDragger]), which are none
// for those of a [Tree.FS].
func (fn *Node) DragFiles() []string {
if fn.isFS() { // (not files of the os)
return nil
}
files := []string{string(fn.Filepath)}
for _, sn := range fn.GetSelectedNodes() {
if sfn := AsNode(sn); sfn != nil && sfn != fn {
files = append(files, string(sfn.Filepath))
}
}
return topPaths(files)
}
// filePaths returns the file paths in the given mime data from [Node.MimeData],
// which has three items per file, with the file path second.
func filePaths(md mimedata.Mimes) []string {
nf := len(md) / 3
paths := make([]string, nf)
for i := range nf {
paths[i] = string(md[i*3+1].Data)
}
return paths
}
// isNodeData returns whether the given mime data is from [Node.MimeData],
// with absolute paths if abs, as of the files of the os.
func isNodeData(md mimedata.Mimes, abs bool) bool {
if len(md) == 0 || len(md)%3 != 0 {
return false
}
for i := 0; i < len(md); i += 3 {
if md[i].Type != fileinfo.TextPlain || md[i+1].Type != fileinfo.TextPlain || (abs && !filepath.IsAbs(string(md[i+1].Data))) {
return false
}
}
return true
}
// clipboardPaths returns the paths of the existing files in the given
// clipboard data: those from [Node.MimeData], or the absolute paths
// (or file:// URLs) on the lines of text.
func clipboardPaths(md mimedata.Mimes) []string {
if isNodeData(md, true) {
return filePaths(md)
}
var paths []string
for _, d := range md {
if !mimedata.IsText(d.Type) {
continue
}
for ln := range strings.SplitSeq(string(d.Data), "\n") {
p := strings.TrimPrefix(strings.TrimSpace(ln), "file://")
if filepath.IsAbs(p) && fsx.Exists(p) {
paths = append(paths, p)
}
}
}
return paths
}
// withoutFiles returns the given mime data from [Node.MimeData]
// without the items for the given file paths.
func withoutFiles(md mimedata.Mimes, paths []string) mimedata.Mimes {
var res mimedata.Mimes
for i := 0; i+2 < len(md); i += 3 {
if !slices.Contains(paths, string(md[i+1].Data)) {
res = append(res, md[i:i+3]...)
}
}
return res
}
// pasteDone reports any error from copying the files of a paste or drop,
// and otherwise calls dropFinal if non-nil, which deletes the source
// files of a move (except those in inPlace): these are kept if anything failed.
func (fn *Node) pasteDone(err error, inPlace []string, dropFinal func(inPlace []string)) {
if err != nil {
core.ErrorSnackbar(fn, err, "Error copying file")
return
}
if dropFinal != nil {
dropFinal(inPlace)
}
}
// pasteFiles copies the files at the given paths into or onto this node,
// for a paste or drop. For a move, dropFinal deletes the source files,
// except the given ones that were already in place (it is nil for a paste).
// Multiple files, and directories, are copied into this directory or the
// directory of this file. A single file can also replace this file.
func (fn *Node) pasteFiles(paths []string, move bool, dropFinal func(inPlace []string)) {
paths = topPaths(paths)
if len(paths) == 0 || fn.isExternal() {
return
}
if fn.IsDir() {
fn.pasteToDir(fn, paths, move, dropFinal)
return
}
if len(paths) > 1 || fn.isDirPath(paths[0]) {
fn.pasteToDir(AsNode(fn.Parent), paths, move, dropFinal)
return
}
fn.pasteOntoFile(paths[0], dropFinal)
}
// pasteToDir copies the files at the given paths into the given directory,
// first asking whether to overwrite any existing files. Files that are already
// in the directory are duplicated for a copy, and left alone for a move.
func (fn *Node) pasteToDir(tdir *Node, paths []string, move bool, dropFinal func(inPlace []string)) {
dir := string(tdir.Filepath)
var copies, inPlace, existing []string
for _, p := range paths {
tp := fn.joinPath(dir, fn.baseOf(p))
switch {
case tp == fn.cleanPath(p):
inPlace = append(inPlace, p)
case fn.pathExists(tp):
existing = append(existing, fn.baseOf(p))
fallthrough
default:
copies = append(copies, p)
}
}
paste := func() {
var errs []error
if !move {
for _, p := range inPlace {
if fn.isFS() {
_, err := fn.duplicatePath(p)
errs = append(errs, err)
continue
}
fi, err := fileinfo.NewFileInfo(p)
if err == nil {
_, err = fi.Duplicate()
}
errs = append(errs, err)
}
}
for _, p := range copies {
errs = append(errs, tdir.copyFileToDir(p))
}
fn.FileRoot().UpdatePath(dir)
fn.pasteDone(errors.Join(errs...), inPlace, dropFinal)
}
if len(existing) == 0 {
paste()
return
}
d := core.NewBody("Overwrite?")
core.NewText(d).SetType(core.TextSupporting).SetText(fmt.Sprintf("Overwrite existing file(s) in %s: %s?", dir, strings.Join(existing, ", ")))
d.AddBottomBar(func(bar *core.Frame) {
d.AddCancel(bar)
d.AddOK(bar).SetText("Overwrite").OnClick(func(e events.Event) {
paste()
})
})
d.RunDialog(fn)
}
// pasteOntoFile copies the file at the given path onto this file, or into
// the directory of this file, as chosen by the user, who can also compare them.
func (fn *Node) pasteOntoFile(srcpath string, dropFinal func(inPlace []string)) {
tpath := string(fn.Filepath)
if fn.cleanPath(srcpath) == tpath { // dropped onto itself
return
}
fname := fn.baseOf(srcpath)
tdir := AsNode(fn.Parent)
npath := fn.joinPath(string(tdir.Filepath), fname) // the source if in this directory
srcpath = fn.cleanPath(srcpath)
diff := !fn.isFS() // (files of the os)
copyTo := func(dst string) {
err := fn.copyPath(dst, srcpath)
fn.FileRoot().UpdatePath(dst)
fn.pasteDone(err, nil, dropFinal)
}
d := core.NewBody("Overwrite?")
text := core.NewText(d).SetType(core.TextSupporting)
d.AddBottomBar(func(bar *core.Frame) {
d.AddCancel(bar)
switch {
case fname == fn.Name:
text.SetText(fmt.Sprintf("Overwrite target file: %s with source file of same name?, or diff (compare) two files?", fn.Name))
if diff {
d.AddOK(bar).SetText("Diff (compare)").OnClick(func(e events.Event) {
textcore.DiffFiles(fn, tpath, srcpath)
})
}
d.AddOK(bar).SetText("Overwrite").OnClick(func(e events.Event) {
copyTo(tpath)
})
case npath == srcpath || !fn.pathExists(npath):
if npath == srcpath { // in this directory: can only replace the target
text.SetText(fmt.Sprintf("Overwrite target file: %s with source file: %s, or diff (compare) the two files?", fn.Name, fname))
} else {
text.SetText(fmt.Sprintf("Overwrite target file: %s with source file: %s, or copy to: %s in current folder (which doesn't yet exist), or diff (compare) the two files?", fn.Name, fname, fname))
}
if diff {
d.AddOK(bar).SetText("Diff (compare)").OnClick(func(e events.Event) {
textcore.DiffFiles(fn, tpath, srcpath)
})
}
d.AddOK(bar).SetText("Overwrite target").OnClick(func(e events.Event) {
copyTo(tpath)
})
if npath != srcpath {
d.AddOK(bar).SetText("Copy new file").OnClick(func(e events.Event) {
copyTo(npath)
})
}
default:
text.SetText(fmt.Sprintf("Overwrite target file: %s with source file: %s, or overwrite existing file with same name as source file (%s), or diff (compare) files?", fn.Name, fname, fname))
if diff {
d.AddOK(bar).SetText("Diff to target").OnClick(func(e events.Event) {
textcore.DiffFiles(fn, tpath, srcpath)
})
d.AddOK(bar).SetText("Diff to existing").OnClick(func(e events.Event) {
textcore.DiffFiles(fn, npath, srcpath)
})
}
d.AddOK(bar).SetText("Overwrite target").OnClick(func(e events.Event) {
copyTo(tpath)
})
d.AddOK(bar).SetText("Overwrite existing").OnClick(func(e events.Event) {
copyTo(npath)
})
}
})
d.RunDialog(fn)
}
// DropDeleteSource is called after target accepts the drop -- we just remove
// elements that were moved
// satisfies core.DragNDropper interface and can be overridden by subtypes
func (fn *Node) DropDeleteSource(e events.Event) {
de := e.(*events.DragDrop)
froot := fn.FileRoot()
if froot == nil || fn.isExternal() {
return
}
md := de.Data.(mimedata.Mimes)
top := topPaths(filePaths(md))
nf := len(md) / 3 // always internal
var errs []error
for i := range nf {
if !slices.Contains(top, string(md[i*3+1].Data)) { // deleted with its directory
continue
}
npath := string(md[i*3].Data)
sfni := froot.FindPath(npath)
if sfni == nil {
slog.Error("filetree.Node: could not find path", "path", npath)
continue
}
sfn := AsNode(sfni)
if sfn == nil {
continue
}
// fmt.Printf("dnd deleting: %v path: %v\n", sfn.Path(), sfn.FPath)
errs = append(errs, sfn.DeleteFile())
}
core.ErrorSnackbar(froot, errors.Join(errs...), "Error moving file")
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package filetree
import (
"maps"
"os"
"path/filepath"
"slices"
"sync"
)
// dirFlags are flags on directories: Open.
// These flags are stored in the DirFlagMap for persistence.
// This map is saved to a file, so these flags must be stored
// as bit flags instead of a struct to ensure efficient serialization.
type dirFlags int32 //enums:bitflag -trim-prefix dir
const (
// dirIsOpen means directory is open -- else closed
dirIsOpen dirFlags = iota
// dirSortByName is no longer used: the sort order of a directory is
// that of [dirsort.For]. It is kept for the flags that were saved.
dirSortByName
// dirSortByModTime is no longer used: the sort order of a directory is
// that of [dirsort.For]. It is kept for the flags that were saved.
dirSortByModTime
)
// DirFlagMap is a map for encoding open directories.
// The strings are typically relative paths. Map access is protected by Mutex.
type DirFlagMap struct {
// map of paths and associated flags
Map map[string]dirFlags
// mutex for accessing map
sync.Mutex
}
// Copy copies flag map from another map, safely avoiding copying the mutex.
func (dm *DirFlagMap) Copy(cp *DirFlagMap) {
dm.init()
defer dm.Unlock()
if cp.Map == nil {
return
}
maps.Copy(dm.Map, cp.Map)
}
// init initializes the map, and sets the Mutex lock; must unlock manually.
func (dm *DirFlagMap) init() {
dm.Lock()
if dm.Map == nil {
dm.Map = make(map[string]dirFlags)
}
}
// isOpen returns true if path has isOpen bit flag set
func (dm *DirFlagMap) isOpen(path string) bool {
dm.init()
defer dm.Unlock()
if df, ok := dm.Map[path]; ok {
return df.HasFlag(dirIsOpen)
}
return false
}
// SetOpenState sets the given directory's open flag
func (dm *DirFlagMap) setOpen(path string, open bool) {
dm.init()
defer dm.Unlock()
df := dm.Map[path]
df.SetFlag(open, dirIsOpen)
dm.Map[path] = df
}
// openPaths returns a list of open paths
func (dm *DirFlagMap) openPaths(root string) []string {
dm.init()
defer dm.Unlock()
var paths []string
for fn, df := range dm.Map {
if !df.HasFlag(dirIsOpen) {
continue
}
fpath := filepath.Join(root, fn)
_, err := os.Stat(fpath)
if err != nil {
delete(dm.Map, fn)
continue
}
rootClosed := false
par := fn
for {
par = filepath.Dir(par)
if par == "" || par == "." {
break
}
if pdf, ook := dm.Map[par]; ook {
if !pdf.HasFlag(dirIsOpen) {
rootClosed = true
break
}
}
}
if rootClosed {
continue
}
paths = append(paths, fpath)
}
slices.Sort(paths)
return paths
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package filetree
import (
"errors"
"fmt"
"os"
"cogentcore.org/core/base/fsx"
"cogentcore.org/core/base/vcs"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"github.com/hack-pad/hackpadfs"
)
// Filer is an interface for file tree file actions that all [Node]s satisfy.
// This allows apps to intervene and apply any additional logic for these actions.
type Filer interface { //types:add
core.Treer
// AsFileNode returns the [Node]
AsFileNode() *Node
// RenameFiles renames any selected files.
RenameFiles()
// DeleteFiles deletes any selected files.
DeleteFiles()
// GetFileInfo updates the .Info for this file
GetFileInfo() error
// OpenFile opens the file for node. This is called by OpenFilesDefault
OpenFile() error
}
var _ Filer = (*Node)(nil)
// SelectedPaths returns the paths of selected nodes.
func (fn *Node) SelectedPaths() []string {
sels := fn.GetSelectedNodes()
n := len(sels)
if n == 0 {
return nil
}
paths := make([]string, 0, n)
fn.SelectedFunc(func(sn *Node) {
paths = append(paths, string(sn.Filepath))
})
return paths
}
// OpenFilesDefault opens selected files with default app for that file type (os defined).
// runs open on Mac, xdg-open on Linux, and start on Windows
func (fn *Node) OpenFilesDefault() { //types:add
fn.SelectedFunc(func(sn *Node) {
sn.This.(Filer).OpenFile()
})
}
// OpenFile just does OpenFileDefault
func (fn *Node) OpenFile() error {
return fn.OpenFileDefault()
}
// OpenFileDefault opens file with default app for that file type (os defined)
// runs open on Mac, xdg-open on Linux, and start on Windows
func (fn *Node) OpenFileDefault() error {
openURL(fsx.FileURL(string(fn.Filepath)))
return nil
}
// openURL opens the given URL in its default app.
// It is a variable for the tests, which do not open apps.
var openURL = func(url string) { core.TheApp.OpenURL(url) }
// duplicateFiles makes a copy of selected files
func (fn *Node) duplicateFiles() { //types:add
root := fn.FileRoot()
root.NeedsLayout()
var errs []error
fn.SelectedFunc(func(sn *Node) {
errs = append(errs, sn.duplicateFile())
})
core.ErrorSnackbar(root, errors.Join(errs...), "Error duplicating file")
}
// duplicateFile creates a copy of given file -- only works for regular files, not
// directories
func (fn *Node) duplicateFile() error {
var err error
if fn.isFS() {
_, err = fn.duplicatePath(string(fn.Filepath))
} else {
_, err = fn.Info.Duplicate()
}
if err == nil && fn.Parent != nil {
fnp := AsNode(fn.Parent)
fnp.Update()
}
return err
}
// DeleteFiles deletes any selected files or directories. If any directory is selected,
// all files and subdirectories in that directory are also deleted.
func (fn *Node) DeleteFiles() { //types:add
d := core.NewBody("Delete Files?")
text := "OK to delete file(s)? They are moved to the trash / recycle bin where available, and otherwise permanently deleted. If any selections are directories, all files and subdirectories in them are also deleted."
if fn.isFS() {
text = "OK to delete file(s)? They are permanently deleted. If any selections are directories, all files and subdirectories in them are also deleted."
}
core.NewText(d).SetType(core.TextSupporting).SetText(text)
d.AddBottomBar(func(bar *core.Frame) {
d.AddCancel(bar)
d.AddOK(bar).SetText("Delete Files").OnClick(func(e events.Event) {
fn.DeleteFilesNoPrompts()
})
})
d.RunDialog(fn)
}
// DeleteFilesNoPrompts does the actual deletion, no prompts.
// Errors are reported in a snackbar.
func (fn *Node) DeleteFilesNoPrompts() {
root := fn.FileRoot()
root.NeedsLayout()
var errs []error
for _, sn := range fn.selectedTop() {
errs = append(errs, sn.DeleteFile())
}
core.ErrorSnackbar(root, errors.Join(errs...), "Error deleting file")
}
// DeleteFile deletes this file
func (fn *Node) DeleteFile() error {
if fn.isExternal() {
return nil
}
pari := fn.Parent
var parent *Node
if pari != nil {
parent = AsNode(pari)
}
repo, _ := fn.Repo()
var err error
switch {
case fn.isFS() && !fn.canRemove():
return errUnsupported
case fn.isFS():
err = fn.removeAll(string(fn.Filepath))
case !fn.Info.IsDir() && repo != nil && fn.Info.VCS >= vcs.Stored:
err = repo.Delete(string(fn.Filepath))
if err != nil && fsx.Exists(string(fn.Filepath)) { // not in the repository (status not yet known)
err = fn.Info.Delete()
}
default:
err = fn.Info.Delete()
}
if err == nil {
fn.Delete()
}
if parent != nil {
parent.Update()
}
return err
}
// RenameFiles renames any selected files.
func (fn *Node) RenameFiles() { //types:add
fn.FileRoot().NeedsLayout()
fn.SelectedFunc(func(sn *Node) {
fb := core.NewSoloFuncButton(sn).SetFunc(sn.RenameFile)
fb.Args[0].SetValue(sn.Name)
fb.CallFunc()
})
}
// RenameFile renames file to new name
func (fn *Node) RenameFile(newpath string) error { //types:add
if fn.isExternal() {
return nil
}
root := fn.FileRoot()
isFS := fn.isFS()
if isFS && !fn.canRename() {
return errUnsupported
}
var err error
orgpath := fn.Filepath
if isFS {
newpath, err = fn.fsRenamePath(newpath)
} else {
newpath, err = fn.Info.RenamePath(newpath) // the rename is done below
}
if len(newpath) == 0 || err != nil {
return err
}
if fn.IsDir() {
if fn.FileRoot().isDirOpen(orgpath) {
fn.FileRoot().setDirOpen(core.Filename(newpath))
}
}
repo, _ := fn.Repo()
switch {
case isFS:
err = fn.rename(string(orgpath), newpath)
case repo != nil && (fn.IsDir() || fn.Info.VCS >= vcs.Stored):
err = repo.Move(string(orgpath), newpath)
if err != nil && fsx.Exists(string(orgpath)) { // not in the repository (status not yet known)
err = os.Rename(string(orgpath), newpath)
}
default:
err = os.Rename(string(orgpath), newpath)
}
if err == nil && isFS {
fn.Filepath = core.Filename(newpath)
err = fn.This.(Filer).GetFileInfo()
} else if err == nil {
err = fn.Info.InitFile(newpath)
fn.Filepath = core.Filename(fn.Info.Path)
}
if err == nil {
name := fn.baseOf(string(fn.Filepath))
fn.SetName(name)
fn.SetText(name)
if fn.IsDir() {
fn.movedDir(string(orgpath))
}
}
if root != nil {
root.UpdatePath(string(orgpath))
root.UpdatePath(newpath)
}
return err
}
// movedDir updates the paths of the nodes within this directory node,
// which has been renamed (moved) from the given path, along with the
// open state of the directories. Existing nodes are kept by name when
// the directory is updated, with their paths unchanged.
func (fn *Node) movedDir(orgpath string) {
root := fn.FileRoot()
newpath := string(fn.Filepath)
for k := range fn.All() {
sfn := AsNode(k)
if sfn == nil || sfn == fn {
continue
}
opath := string(sfn.Filepath)
if !isWithin(opath, orgpath) {
continue
}
sfn.Filepath = core.Filename(newpath + opath[len(orgpath):])
sfn.This.(Filer).GetFileInfo()
if sfn.IsDir() && root.isDirOpen(core.Filename(opath)) {
root.setDirOpen(sfn.Filepath)
}
}
}
// newFiles makes a new file in selected directory
func (fn *Node) newFiles(filename string, addToVCS bool) { //types:add
done := false
fn.SelectedFunc(func(sn *Node) {
if !done {
sn.newFile(filename, addToVCS)
done = true
}
})
}
// newFile makes a new file in this directory node
func (fn *Node) newFile(filename string, addToVCS bool) { //types:add
if fn.isExternal() {
return
}
ppath := string(fn.Filepath)
if !fn.IsDir() {
ppath = fn.dirOf(ppath)
}
np := fn.joinPath(ppath, filename)
var err error
switch {
case fn.isFS() && !fn.canCreate():
err = errUnsupported
case fn.isFS() && fn.pathExists(np): // not truncating an existing file
err = fmt.Errorf("cannot make %s: it already exists", np)
case fn.isFS():
err = fsErr(hackpadfs.WriteFullFile(fn.FileRoot().FS, np, nil, 0o666))
default:
var f *os.File
f, err = os.OpenFile(np, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666) // not truncating an existing file
if err == nil {
err = f.Close()
}
}
if err != nil {
core.ErrorSnackbar(fn, err, "Error creating file")
return
}
if addToVCS {
fn.FileRoot().UpdatePath(ppath)
nfn, ok := fn.FileRoot().FindFile(np)
if ok && !nfn.IsRoot() && string(nfn.Filepath) == np {
core.MessageSnackbar(fn, "Adding new file to VCS: "+fsx.DirAndFile(string(nfn.Filepath)))
nfn.AddToVCS()
}
}
fn.FileRoot().UpdatePath(ppath)
}
// makes a new folder in the given selected directory
func (fn *Node) newFolders(foldername string) { //types:add
done := false
fn.SelectedFunc(func(sn *Node) {
if !done {
sn.newFolder(foldername)
done = true
}
})
}
// newFolder makes a new folder (directory) in this directory node
func (fn *Node) newFolder(foldername string) { //types:add
if fn.isExternal() {
return
}
ppath := string(fn.Filepath)
if !fn.IsDir() {
ppath = fn.dirOf(ppath)
}
np := fn.joinPath(ppath, foldername)
var err error
switch {
case fn.isFS() && !fn.canMkdir():
err = errUnsupported
case fn.isFS():
err = fn.mkdirAll(np)
default:
err = os.MkdirAll(np, 0775)
}
if err != nil {
core.ErrorSnackbar(fn, err, "Error creating folder")
return
}
fn.FileRoot().UpdatePath(ppath)
}
// copyFileToDir copies the file or directory at the given path into this
// directory node, overwriting any existing file. A copy of a file that is
// in version control in this tree is added to version control.
func (fn *Node) copyFileToDir(filename string) error {
if fn.isExternal() {
return nil
}
ppath := string(fn.Filepath)
tpath := fn.joinPath(ppath, fn.baseOf(filename))
err := fn.copyPath(tpath, filename)
fn.FileRoot().UpdatePath(ppath)
if err != nil || fn.isFS() {
return err
}
ofn, ok := fn.FileRoot().FindFile(filename)
if ok && !ofn.IsDir() && ofn.Info.VCS >= vcs.Stored {
nfn, ok := fn.FileRoot().FindFile(tpath)
if ok && !nfn.IsRoot() {
if string(nfn.Filepath) != tpath {
fmt.Printf("error: nfn.FPath != tpath; %q != %q, see bug #453\n", nfn.Filepath, tpath)
} else {
nfn.AddToVCS() // todo: this sometimes is not just tpath! See bug #453
}
nfn.Update()
}
}
return nil
}
// Shows file information about selected file(s)
func (fn *Node) showFileInfo() { //types:add
fn.SelectedFunc(func(sn *Node) {
d := core.NewBody("File info")
core.NewForm(d).SetStruct(&sn.Info).SetReadOnly(true)
d.AddOKOnly().RunWindowDialog(sn)
})
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package filetree
import (
"path/filepath"
"sort"
"strings"
"time"
"cogentcore.org/core/base/fileinfo"
)
// FindFile finds first node representing given file (false if not found) --
// looks for full path names that have the given string as their suffix, so
// you can include as much of the path (including whole thing) as is relevant
// to disambiguate. See FilesMatching for a list of files that match a given
// string.
func (fn *Node) FindFile(fnm string) (*Node, bool) {
if fnm == "" {
return nil, false
}
fneff := fnm
if len(fneff) > 2 && fneff[:2] == ".." { // relative path -- get rid of it and just look for relative part
dirs := strings.Split(fneff, string(filepath.Separator))
for i, dr := range dirs {
if dr != ".." {
fneff = filepath.Join(dirs[i:]...)
break
}
}
}
if efn, err := fn.FileRoot().externalNodeByPath(fnm); err == nil {
return efn, true
}
if strings.HasPrefix(fneff, string(fn.Filepath)) { // full path
ffn, err := fn.dirsTo(fneff)
if err == nil {
return ffn, true
}
return nil, false
}
var ffn *Node
found := false
for cw := range fn.AllWidgets() {
sfn := AsNode(cw)
if sfn == nil {
continue
}
if strings.HasSuffix(string(sfn.Filepath), fneff) {
ffn = sfn
found = true
break
}
}
return ffn, found
}
// NodeNameCount is used to report counts of different string-based things
// in the file tree
type NodeNameCount struct {
Name string
Count int
}
func NodeNameCountSort(ecs []NodeNameCount) {
sort.Slice(ecs, func(i, j int) bool {
return ecs[i].Count > ecs[j].Count
})
}
// FileExtensionCounts returns a count of all the different file extensions, sorted
// from highest to lowest.
// If cat is != fileinfo.Unknown then it only uses files of that type
// (e.g., fileinfo.Code to find any code files)
func (fn *Node) FileExtensionCounts(cat fileinfo.Categories) []NodeNameCount {
cmap := make(map[string]int)
for cw := range fn.AllWidgets() {
sfn := AsNode(cw)
if sfn == nil {
continue
}
if cat != fileinfo.UnknownCategory {
if sfn.Info.Cat != cat {
continue
}
}
ext := strings.ToLower(filepath.Ext(sfn.Name))
if ec, has := cmap[ext]; has {
cmap[ext] = ec + 1
} else {
cmap[ext] = 1
}
}
ecs := make([]NodeNameCount, len(cmap))
idx := 0
for key, val := range cmap {
ecs[idx] = NodeNameCount{Name: key, Count: val}
idx++
}
NodeNameCountSort(ecs)
return ecs
}
// LatestFileMod returns the most recent mod time of files in the tree.
// If cat is != fileinfo.Unknown then it only uses files of that type
// (e.g., fileinfo.Code to find any code files)
func (fn *Node) LatestFileMod(cat fileinfo.Categories) time.Time {
tmod := time.Time{}
for cw := range fn.AllWidgets() {
sfn := AsNode(cw)
if sfn == nil {
continue
}
if cat != fileinfo.UnknownCategory {
if sfn.Info.Cat != cat {
continue
}
}
ft := (time.Time)(sfn.Info.ModTime)
if ft.After(tmod) {
tmod = ft
}
}
return tmod
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package filetree
import (
"errors"
"fmt"
"io/fs"
"path"
"path/filepath"
"strings"
"cogentcore.org/core/base/dirsort"
"cogentcore.org/core/base/fsx"
"github.com/hack-pad/hackpadfs"
)
// The files of a [Tree.FS] are changed with the interfaces of hackpadfs
// for each operation, which extend those of [io/fs], as the os functions:
// [hackpadfs.MkdirAllFS] (or MkdirFS) for New folder, [hackpadfs.RenameFS]
// for Rename, [hackpadfs.RemoveAllFS] (or RemoveFS) for Delete,
// [hackpadfs.WriteFileFS] (or OpenFileFS) for New file, and [CopyFS], or
// else those of making directories and writing files, for copying, as in
// Duplicate, drag and drop, and copy and paste. Those that an FS does not
// have are disabled, as for a read-only FS. A [hackpadfs.MountFS] can
// have any of them, in its mounted filesystems.
// CopyFS is an [fs.FS] that copies its own files and directories, as for
// those that are more than their bytes, such as typed data. Those of
// another FS are copied by reading and writing them (see [Tree.FS]).
type CopyFS interface {
fs.FS
// CopyPath copies the file or directory at the source path to the
// destination path, replacing anything there.
CopyPath(dst, src string) error
}
// errUnsupported is the error of a change to the files of a [Tree.FS] that
// it does not support, as for a read-only one.
var errUnsupported = errors.New("the filesystem of the files does not support this change")
// fsErr returns the given error of an operation of hackpadfs, with
// [errUnsupported] for an operation that the FS does not have.
func fsErr(err error) error {
if errors.Is(err, hackpadfs.ErrNotImplemented) {
return fmt.Errorf("%w: %w", errUnsupported, err)
}
return err
}
// fsHas returns whether the [Tree.FS] of the node has any of the
// interfaces of the given values, or is a [hackpadfs.MountFS], which can
// have them in its mounted filesystems. It is true for the os.
func fsHas(fn *Node, has ...func(fs.FS) bool) bool {
fsys := fn.FileRoot().FS
if fsys == nil {
return true
}
if _, ok := fsys.(hackpadfs.MountFS); ok {
return true
}
for _, h := range has {
if h(fsys) {
return true
}
}
return false
}
// is returns whether the given FS has the interface T.
func is[T any](fsys fs.FS) bool {
_, ok := fsys.(T)
return ok
}
// canMkdir, canRename, canRemove, canCreate, and canCopy return whether
// the files of the tree of the node can be changed with the operations of
// those names (see [CopyFS]), as those of the os can.
func (fn *Node) canMkdir() bool {
return fsHas(fn, is[hackpadfs.MkdirAllFS], is[hackpadfs.MkdirFS])
}
func (fn *Node) canRename() bool {
return fsHas(fn, is[hackpadfs.RenameFS])
}
func (fn *Node) canRemove() bool {
return fsHas(fn, is[hackpadfs.RemoveAllFS], is[hackpadfs.RemoveFS])
}
func (fn *Node) canCreate() bool {
return fsHas(fn, is[hackpadfs.WriteFileFS], is[hackpadfs.OpenFileFS])
}
func (fn *Node) canCopy() bool {
return fsHas(fn, is[CopyFS]) || (fn.canMkdir() && fn.canCreate())
}
// mkdirAll, rename, and removeAll do those operations of hackpadfs on the
// [Tree.FS] of the node.
func (fn *Node) mkdirAll(p string) error {
return fsErr(hackpadfs.MkdirAll(fn.FileRoot().FS, p, 0o775))
}
func (fn *Node) rename(oldpath, newpath string) error {
return fsErr(hackpadfs.Rename(fn.FileRoot().FS, oldpath, newpath))
}
func (fn *Node) removeAll(p string) error {
return fsErr(hackpadfs.RemoveAll(fn.FileRoot().FS, p))
}
// isFS returns whether the tree of the node is of a [Tree.FS].
func (fn *Node) isFS() bool {
return fn.FileRoot().FS != nil
}
// cleanPath, dirOf, and baseOf are [filepath.Clean], [filepath.Dir], and
// [filepath.Base] for the paths of the tree of the node, which use / in a
// [Tree.FS] (see [Node.joinPath]).
func (fn *Node) cleanPath(p string) string {
if fn.isFS() {
return path.Clean(p)
}
return filepath.Clean(p)
}
func (fn *Node) dirOf(p string) string {
if fn.isFS() {
return path.Dir(p)
}
return filepath.Dir(p)
}
func (fn *Node) baseOf(p string) string {
if fn.isFS() {
return path.Base(p)
}
return filepath.Base(p)
}
// pathExists returns whether a file or directory exists at the given path
// of the tree of the node.
func (fn *Node) pathExists(p string) bool {
if fsys := fn.FileRoot().FS; fsys != nil {
_, err := fs.Stat(fsys, p)
return err == nil
}
return fsx.Exists(p)
}
// isDirPath returns whether there is a directory at the given path of the
// tree of the node.
func (fn *Node) isDirPath(p string) bool {
if fsys := fn.FileRoot().FS; fsys != nil {
info, err := fs.Stat(fsys, p)
return err == nil && info.IsDir()
}
ok, _ := fsx.DirExists(p)
return ok
}
// copyPath copies the file or directory at the source path to the
// destination path, in the tree of the node: with [CopyFS] in a
// [Tree.FS] that has it, and otherwise by reading and writing the files.
func (fn *Node) copyPath(dst, src string) error {
fsys := fn.FileRoot().FS
if fsys == nil {
return fsx.CopyPath(dst, src)
}
if cfs, ok := fsys.(CopyFS); ok {
return cfs.CopyPath(dst, src)
}
if !fn.canCopy() {
return errUnsupported
}
return fs.WalkDir(fsys, src, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
to := dst + p[len(src):]
info, err := d.Info()
if err != nil {
return err
}
if d.IsDir() {
return fsErr(hackpadfs.MkdirAll(fsys, to, info.Mode().Perm()|0o700))
}
b, err := fs.ReadFile(fsys, p)
if err != nil {
return err
}
return fsErr(hackpadfs.WriteFullFile(fsys, to, b, info.Mode().Perm()))
})
}
// duplicatePath copies the file or directory at the given path to a new
// one in the same directory, named with _Copy, as [fileinfo.FileInfo.Duplicate],
// returning its path.
func (fn *Node) duplicatePath(p string) (string, error) {
name := fn.baseOf(p)
ext := path.Ext(name)
if fn.isDirPath(p) || ext == name {
ext = ""
}
noext := strings.TrimSuffix(p, ext)
dst := noext + "_Copy" + ext
for i := 1; fn.pathExists(dst); i++ {
dst = noext + fmt.Sprintf("_Copy%d", i) + ext
}
return dst, fn.copyPath(dst, p)
}
// fsSort returns the sort order of the directory at the given path of a
// [Tree.FS]: the one set for it with Sort by, or else the [Tree.FSSort].
func (ft *Tree) fsSort(dir string) dirsort.Sort {
if s, ok := ft.fsSorts[dir]; ok {
return s
}
return ft.FSSort
}
// dirSort returns the sort order of the files of this directory: that of
// [dirsort.For], or of [Tree.fsSort] in a [Tree.FS].
func (fn *Node) dirSort() dirsort.Sort {
if fn.isFS() {
return fn.FileRoot().fsSort(string(fn.Filepath))
}
return dirsort.For(string(fn.Filepath))
}
// fsRenamePath returns the new path of this node of a [Tree.FS] for
// renaming it to the given name, or path within the tree, or "" if it is
// the same, with an error if something else is there.
func (fn *Node) fsRenamePath(name string) (string, error) {
if name == "" {
return "", errors.New("the new name is empty")
}
newpath := name
if !strings.Contains(name, "/") {
newpath = path.Join(path.Dir(string(fn.Filepath)), name)
}
newpath = path.Clean(newpath)
if newpath == path.Clean(string(fn.Filepath)) {
return "", nil
}
if fn.pathExists(newpath) {
return "", fmt.Errorf("cannot rename %s: %s already exists", fn.Name, newpath)
}
return newpath, nil
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package filetree
import (
"image"
"strings"
"cogentcore.org/core/base/vcs"
"cogentcore.org/core/core"
"cogentcore.org/core/icons"
"cogentcore.org/core/keymap"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/system"
)
// vcsLabelFunc gets the appropriate label for removing from version control
func vcsLabelFunc(fn *Node, label string) string {
repo, _ := fn.Repo()
if repo != nil {
label = strings.Replace(label, "VCS", repo.Type().String(), 1)
}
return label
}
func (fn *Node) VCSContextMenu(m *core.Scene, pos image.Point) {
if fn.FileRoot().FS != nil {
return
}
core.NewFuncButton(m).SetFunc(fn.addToVCSSelected).SetText(vcsLabelFunc(fn, "Add to VCS")).SetIcon(icons.Add).
Styler(func(s *styles.Style) {
s.SetState(!fn.HasSelection() || fn.Info.VCS != vcs.Untracked, states.Disabled)
})
core.NewFuncButton(m).SetFunc(fn.deleteFromVCSSelected).SetText(vcsLabelFunc(fn, "Delete from VCS")).SetIcon(icons.Delete).
Styler(func(s *styles.Style) {
s.SetState(!fn.HasSelection() || fn.Info.VCS == vcs.Untracked, states.Disabled)
})
core.NewFuncButton(m).SetFunc(fn.commitToVCSSelected).SetText(vcsLabelFunc(fn, "Commit to VCS")).SetIcon(icons.Star).
Styler(func(s *styles.Style) {
s.SetState(!fn.HasSelection() || fn.Info.VCS == vcs.Untracked, states.Disabled)
})
core.NewFuncButton(m).SetFunc(fn.revertVCSSelected).SetText(vcsLabelFunc(fn, "Revert from VCS")).SetIcon(icons.Undo).
Styler(func(s *styles.Style) {
s.SetState(!fn.HasSelection() || fn.Info.VCS == vcs.Untracked, states.Disabled)
})
core.NewSeparator(m)
core.NewFuncButton(m).SetFunc(fn.diffVCSSelected).SetText(vcsLabelFunc(fn, "Diff VCS")).SetIcon(icons.Add).
Styler(func(s *styles.Style) {
s.SetState(!fn.HasSelection() || fn.Info.VCS == vcs.Untracked, states.Disabled)
})
core.NewFuncButton(m).SetFunc(fn.logVCSSelected).SetText(vcsLabelFunc(fn, "Log VCS")).SetIcon(icons.List).
Styler(func(s *styles.Style) {
s.SetState(!fn.HasSelection() || fn.Info.VCS == vcs.Untracked, states.Disabled)
})
core.NewFuncButton(m).SetFunc(fn.blameVCSSelected).SetText(vcsLabelFunc(fn, "Blame VCS")).SetIcon(icons.CreditScore).
Styler(func(s *styles.Style) {
s.SetState(!fn.HasSelection() || fn.Info.VCS == vcs.Untracked, states.Disabled)
})
}
func (fn *Node) contextMenu(m *core.Scene, pos image.Point) {
core.NewFuncButton(m).SetFunc(fn.showFileInfo).SetText("Info").
SetIcon(icons.Info).SetEnabled(fn.HasSelection())
open := core.NewFuncButton(m).SetFunc(fn.OpenFilesDefault).SetText("Open").
SetIcon(icons.Open)
open.SetEnabled(fn.HasSelection())
if core.TheApp.Platform() == system.Web {
open.SetText("Download").SetIcon(icons.Download).SetTooltip("Download this file to your device")
}
if fn.HasSelection() && !fn.IsDir() && !fn.isFS() {
core.OpenWithMenuItems(m, string(fn.Filepath))
}
sel := fn.HasSelection()
core.NewSeparator(m)
core.NewFuncButton(m).SetFunc(fn.duplicateFiles).SetText("Duplicate").
SetIcon(icons.Copy).SetKey(keymap.Duplicate).SetEnabled(sel && fn.canCopy())
core.NewFuncButton(m).SetFunc(fn.This.(Filer).DeleteFiles).SetText("Delete").
SetIcon(icons.Delete).SetKey(keymap.Delete).SetEnabled(sel && fn.canRemove())
core.NewFuncButton(m).SetFunc(fn.This.(Filer).RenameFiles).SetText("Rename").
SetIcon(icons.NewLabel).SetEnabled(sel && fn.canRename())
core.NewSeparator(m)
core.NewFuncButton(m).SetFunc(fn.openAll).SetText("Open all").
SetIcon(icons.KeyboardArrowDown).SetEnabled(fn.HasSelection() && fn.IsDir())
core.NewFuncButton(m).SetFunc(fn.CloseAll).SetIcon(icons.KeyboardArrowRight).
SetEnabled(fn.HasSelection() && fn.IsDir())
sb := core.NewFuncButton(m).SetFunc(fn.sortBys)
sb.SetText("Sort by").SetIcon(icons.Sort).SetEnabled(fn.HasSelection() && fn.IsDir())
if fn.IsDir() { // (the current sort order of the directory)
s := fn.dirSort()
sb.Args[0].SetValue(s.By)
sb.Args[1].SetValue(s.Down)
}
core.NewSeparator(m)
fb := core.NewFuncButton(m).SetFunc(fn.newFiles)
fb.SetText("New file").SetIcon(icons.OpenInNew).SetEnabled(sel && fn.canCreate())
fb.Args[1].SetValue(true) // todo: not working
core.NewFuncButton(m).SetFunc(fn.newFolders).SetText("New folder").
SetIcon(icons.CreateNewFolder).SetEnabled(sel && fn.canMkdir())
core.NewSeparator(m)
fn.VCSContextMenu(m, pos)
core.NewSeparator(m)
if !fn.isFS() {
core.NewFuncButton(m).SetFunc(fn.removeFromExterns).
SetIcon(icons.Delete).SetEnabled(fn.HasSelection())
core.NewSeparator(m)
}
core.NewFuncButton(m).SetFunc(fn.Copy).SetIcon(icons.Copy).
SetKey(keymap.Copy).SetEnabled(fn.HasSelection())
core.NewFuncButton(m).SetFunc(fn.Cut).SetIcon(icons.Cut).
SetKey(keymap.Cut).SetEnabled(sel && fn.canCopy())
paste := core.NewFuncButton(m).SetFunc(fn.Paste).
SetIcon(icons.Paste).SetKey(keymap.Paste).SetEnabled(sel && fn.canCopy())
cb := fn.Events().Clipboard()
if cb != nil && sel && fn.canCopy() {
paste.SetState(cb.IsEmpty(), states.Disabled)
}
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package filetree provides a GUI tree interface to a filesystem.
package filetree
//go:generate core generate
import (
"fmt"
"io/fs"
"log"
"log/slog"
"os"
"path"
"path/filepath"
"runtime"
"slices"
"strings"
"cogentcore.org/core/base/dirsort"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/fileinfo"
"cogentcore.org/core/base/fsx"
"cogentcore.org/core/base/vcs"
"cogentcore.org/core/colors"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/events/key"
"cogentcore.org/core/icons"
"cogentcore.org/core/keymap"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/highlighting"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/tree"
)
// NodeHighlighting is the default style for syntax highlighting to use for
// file node buffers
var NodeHighlighting = highlighting.StyleDefault
// Node represents a file in the file system, as a [core.Tree] node.
// The name of the node is the name of the file.
// Folders have children containing further nodes.
type Node struct { //core:embedder
core.Tree
// Filepath is the full path to this file.
Filepath core.Filename `edit:"-" set:"-" json:"-" xml:"-" copier:"-"`
// Info is the full standard file info about this file.
Info fileinfo.FileInfo `edit:"-" set:"-" json:"-" xml:"-" copier:"-"`
// FileIsOpen indicates that this file has been opened, indicated by Italics.
FileIsOpen bool
// DirRepo is the version control system repository for this directory,
// only non-nil if this is the highest-level directory in the tree under vcs control.
DirRepo vcs.Repo `edit:"-" set:"-" json:"-" xml:"-" copier:"-"`
}
func (fn *Node) AsFileNode() *Node {
return fn
}
// FileRoot returns the Root node as a [Tree].
func (fn *Node) FileRoot() *Tree {
return AsTree(fn.Root)
}
func (fn *Node) Init() {
fn.Tree.Init()
fn.IconOpen = icons.FolderOpen
fn.IconClosed = icons.Folder
fn.ContextMenus = nil // do not include tree
fn.AddContextMenu(fn.contextMenu)
fn.Styler(func(s *styles.Style) {
s.IconSize.Set(units.Em(1))
fn.styleFromStatus()
})
fn.On(events.KeyChord, func(e events.Event) {
if core.DebugSettings.KeyEventTrace {
fmt.Printf("Tree KeyInput: %v\n", fn.Path())
}
kf := keymap.Of(e.KeyChord())
selMode := events.SelectModeBits(e.Modifiers())
if selMode == events.SelectOne {
if fn.SelectMode {
selMode = events.ExtendContinuous
}
}
// first all the keys that work for ReadOnly and active
if !fn.IsReadOnly() && !e.IsHandled() {
switch kf {
case keymap.Delete:
fn.This.(Filer).DeleteFiles()
e.SetHandled()
case keymap.Backspace:
fn.This.(Filer).DeleteFiles()
e.SetHandled()
case keymap.Duplicate:
fn.duplicateFiles()
e.SetHandled()
case keymap.Insert: // New File
core.CallFunc(fn, fn.newFile)
e.SetHandled()
case keymap.InsertAfter: // New Folder
core.CallFunc(fn, fn.newFolder)
e.SetHandled()
}
}
})
fn.Parts.Styler(func(s *styles.Style) {
s.Gap.X.Em(0.4)
})
fn.Parts.OnClick(func(e events.Event) {
// (an app opens by double-clicking; its arrow still opens it as a directory)
if !e.HasAnyModifier(key.Control, key.Meta, key.Alt, key.Shift) && !fn.IsApp() {
fn.Open()
}
})
fn.Parts.OnDoubleClick(func(e events.Event) {
e.SetHandled()
switch {
case fn.IsApp():
fn.OpenFileDefault() // (not OpenFile, which can open it in an editor)
case fn.IsDir():
fn.ToggleClose()
default:
fn.This.(Filer).OpenFile()
}
})
tree.AddChildInit(fn.Parts, "text", func(w *core.Text) {
w.Styler(func(s *styles.Style) {
if fn.IsExec() && !fn.IsDir() {
s.Font.Weight = rich.Bold
}
if fn.FileIsOpen {
s.Font.Slant = rich.Italic
}
})
})
fn.Updater(func() {
fn.setFileIcon()
if fn.IsDir() {
repo, rnode := fn.Repo()
if repo != nil && rnode.This == fn.This {
rnode.updateRepoFiles()
}
} else {
fn.This.(Filer).GetFileInfo()
}
fn.Text = fn.Info.Name
cc := fn.Styles.Color
fn.styleFromStatus()
if fn.Styles.Color != cc && fn.Parts != nil {
fn.Parts.StyleTree()
}
})
fn.Maker(func(p *tree.Plan) {
if fn.Filepath == "" {
return
}
if fn.Name == externalFilesName {
files := fn.FileRoot().externalFiles
for _, fi := range files {
tree.AddNew(p, fi, func() Filer {
return tree.NewOfType(fn.FileRoot().FileNodeType).(Filer)
}, func(wf Filer) {
w := wf.AsFileNode()
w.Root = fn.Root
w.NeedsLayout()
w.Filepath = core.Filename(fi)
w.Info.Mode = os.ModeIrregular
w.Info.VCS = vcs.Stored
})
}
return
}
if !fn.IsDir() || fn.IsIrregular() {
return
}
if (!fn.FileRoot().inOpenAll || fn.Info.IsHidden()) && !fn.FileRoot().isDirOpen(fn.Filepath) {
return
}
repo, _ := fn.Repo()
files := fn.dirFileList()
for _, fi := range files {
fpath := fn.joinPath(string(fn.Filepath), fi.Name())
if fn.FileRoot().FilterFunc != nil && !fn.FileRoot().FilterFunc(fpath, fi) {
continue
}
tree.AddNew(p, fi.Name(), func() Filer {
return tree.NewOfType(fn.FileRoot().FileNodeType).(Filer)
}, func(wf Filer) {
w := wf.AsFileNode()
w.Root = fn.Root
w.NeedsLayout()
w.Filepath = core.Filename(fpath)
w.This.(Filer).GetFileInfo()
if w.FileRoot().FS == nil {
if w.IsDir() && repo == nil {
w.detectVCSRepo()
}
}
})
}
})
}
// joinPath joins the given directory and name of a file in it: paths in
// [Tree.FS] always use / (see [io/fs]), whereas os paths use the separator
// of the platform (\ on Windows).
func (fn *Node) joinPath(dir, name string) string {
if fn.FileRoot().FS != nil {
return path.Join(dir, name)
}
return filepath.Join(dir, name)
}
// styleFromStatus updates font color from
func (fn *Node) styleFromStatus() {
status := fn.Info.VCS
hex := ""
switch status {
case vcs.Untracked:
hex = "#808080"
case vcs.Modified:
hex = "#4b7fd1"
case vcs.Added:
hex = "#008800"
case vcs.Deleted:
hex = "#ff4252"
case vcs.Conflicted:
hex = "#ce8020"
case vcs.Updated:
hex = "#008060"
case vcs.Stored:
fn.Styles.Color = colors.Scheme.OnSurface
}
if fn.Info.Generated {
hex = "#8080C0"
}
if hex != "" {
fn.Styles.Color = colors.Uniform(colors.ToBase(errors.Must1(colors.FromHex(hex))))
} else {
fn.Styles.Color = colors.Scheme.OnSurface
}
// if fn.Name == "test.go" {
// rep, err := fn.Repo()
// fmt.Println("style updt:", status, hex, rep != nil, err)
// }
}
// IsDir returns true if file is a directory (folder)
func (fn *Node) IsDir() bool {
return fn.Info.IsDir()
}
// AppBundles is whether directories named *.app are app bundles, which
// are shown and opened as apps (see [Node.IsApp]): on macOS, as in the Finder.
var AppBundles = runtime.GOOS == "darwin"
// IsAppBundle returns whether the given path, which is a directory if
// isDir, is an app bundle: a directory named *.app, when [AppBundles].
func IsAppBundle(path string, isDir bool) bool {
return AppBundles && isDir && strings.EqualFold(filepath.Ext(path), ".app")
}
// IsApp returns whether the node is an app bundle (see [IsAppBundle]),
// unless the tree shows them as directories ([Tree.AppsAsDirs]): it has
// the icon of an app, and double-clicking opens it as an app, without
// opening it in the tree, which its arrow does, for its files.
func (fn *Node) IsApp() bool {
if !IsAppBundle(string(fn.Filepath), fn.IsDir()) {
return false
}
root := fn.FileRoot()
return root == nil || !root.AppsAsDirs
}
// IsIrregular returns true if file is a special "Irregular" node
func (fn *Node) IsIrregular() bool {
return (fn.Info.Mode & os.ModeIrregular) != 0
}
// isExternal returns true if file is external to main file tree
func (fn *Node) isExternal() bool {
isExt := false
fn.WalkUp(func(k tree.Node) bool {
sfn := AsNode(k)
if sfn == nil {
return tree.Break
}
// the node of the external files is the parent of each of them,
// whose own file info (mode) is that of their files
if sfn.IsIrregular() || sfn.Filepath == externalFilesName {
isExt = true
return tree.Break
}
return tree.Continue
})
return isExt
}
// IsExec returns true if file is an executable file
func (fn *Node) IsExec() bool {
return fn.Info.IsExec()
}
// isOpen returns true if file is flagged as open
func (fn *Node) isOpen() bool {
return !fn.Closed
}
// RelativePath returns the relative path from root for this node
func (fn *Node) RelativePath() string {
if fn.IsIrregular() || fn.FileRoot() == nil {
return fn.Name
}
return fsx.RelativeFilePath(string(fn.Filepath), string(fn.FileRoot().Filepath))
}
// dirFileList returns the list of files in this directory, in its sort
// order (see [Node.dirSort]), with the directories first if DirsOnTop.
func (fn *Node) dirFileList() []fs.FileInfo {
path := string(fn.Filepath)
var files []fs.FileInfo
var dirs []fs.FileInfo // for DirsOnTop mode
var di []fs.DirEntry
sort := fn.dirSort()
if fn.FileRoot().FS == nil {
di = errors.Log1(os.ReadDir(path))
} else {
di = errors.Log1(fs.ReadDir(fn.FileRoot().FS, path))
}
for _, d := range di {
info, err := d.Info()
if err != nil {
continue // (as one that was removed since it was read)
}
if fn.FileRoot().DirsOnTop && d.IsDir() {
dirs = append(dirs, info)
} else {
files = append(files, info)
}
}
sort.SortInfos(dirs)
sort.SortInfos(files)
return append(dirs, files...)
}
func (fn *Node) setFileIcon() {
if fn.Info.Ic == "" {
ic, hasic := fn.Info.FindIcon()
if hasic {
fn.Info.Ic = ic
} else {
fn.Info.Ic = icons.Blank
}
}
fn.IconLeaf = fn.Info.Ic
on, off := icons.FolderOpen, icons.Folder
if fn.IsApp() {
on, off = icons.Apps, icons.Apps
}
// the branch is made with these, when it is made after this update,
// as on the first one; an app had the icon of a folder until the next
fn.IconOpen, fn.IconClosed = on, off
if br := fn.Branch; br != nil {
if br.IconIndeterminate != fn.IconLeaf || br.IconOff != off {
br.SetIconOn(on).SetIconOff(off).SetIconIndeterminate(fn.IconLeaf)
br.UpdateTree()
}
}
}
// GetFileInfo is a Filer interface method that can be overwritten
// to do custom file info.
func (fn *Node) GetFileInfo() error {
return fn.InitFileInfo()
}
// InitFileInfo initializes file info
func (fn *Node) InitFileInfo() error {
if fn.Filepath == "" {
return nil
}
var err error
if fn.FileRoot().FS == nil { // deal with symlinks
var ls os.FileInfo
ls, err = os.Lstat(string(fn.Filepath))
if errors.Log(err) != nil {
return err
}
if ls.Mode()&os.ModeSymlink != 0 {
effpath, err := filepath.EvalSymlinks(string(fn.Filepath))
if err != nil {
// this happens too often for links -- skip
// log.Printf("filetree.Node Path: %v could not be opened -- error: %v\n", fn.Filepath, err)
return err
}
fn.Filepath = core.Filename(effpath)
}
err = fn.Info.InitFile(string(fn.Filepath))
} else {
err = fn.Info.InitFileFS(fn.FileRoot().FS, string(fn.Filepath))
}
if err != nil {
emsg := fmt.Errorf("filetree.Node InitFileInfo Path %q: Error: %v", fn.Filepath, err)
log.Println(emsg)
return emsg
}
repo, rnode := fn.Repo()
if repo != nil {
if fn.IsDir() {
fn.Info.VCS = vcs.Stored // always
} else {
rstat := rnode.DirRepo.StatusFast(string(fn.Filepath))
if rstat != fn.Info.VCS {
fn.Info.VCS = rstat
fn.NeedsRender()
}
}
} else {
fn.Info.VCS = vcs.Stored
}
return nil
}
// SelectedFunc runs the given function on all selected nodes in reverse order.
func (fn *Node) SelectedFunc(fun func(n *Node)) {
sels := fn.GetSelectedNodes()
for ri := len(sels) - 1; ri >= 0; ri-- {
sel := sels[ri]
sn := AsNode(sel)
if tree.IsNil(sn) {
continue
}
fun(sn)
}
}
// selectedTop returns the selected nodes that are not within another
// selected directory, for operations that also apply to the contents of
// directories (such as deleting).
func (fn *Node) selectedTop() []*Node {
var sels []*Node
fn.SelectedFunc(func(sn *Node) {
sels = append(sels, sn)
})
var top []*Node
for _, sn := range sels {
if !slices.ContainsFunc(sels, func(dn *Node) bool { return isWithin(string(sn.Filepath), string(dn.Filepath)) }) {
top = append(top, sn)
}
}
return top
}
// isWithin returns whether the given path is within the given directory path.
func isWithin(path, dir string) bool {
return strings.HasPrefix(path, dir+string(filepath.Separator))
}
// topPaths returns the given paths without those within another of them.
func topPaths(paths []string) []string {
var top []string
for _, p := range paths {
if !slices.ContainsFunc(paths, func(d string) bool { return isWithin(p, d) }) {
top = append(top, p)
}
}
return top
}
func (fn *Node) OnOpen() {
fn.openDir()
}
func (fn *Node) OnClose() {
if !fn.IsDir() {
return
}
fn.FileRoot().setDirClosed(fn.Filepath)
fn.FileRoot().syncWatchDirs()
}
func (fn *Node) CanOpen() bool {
return fn.HasChildren() || fn.IsDir()
}
// openDir opens given directory node
func (fn *Node) openDir() {
if !fn.IsDir() {
return
}
fn.FileRoot().setDirOpen(fn.Filepath)
fn.Update()
if !fn.FileRoot().inOpenAll {
fn.FileRoot().syncWatchDirs()
}
}
// sortBys sets the sort order of the selected directories, by the given
// field of their files, up (ascending) or down, which is their sort order
// in all apps (see [dirsort.Set]).
func (fn *Node) sortBys(by dirsort.Fields, down bool) { //types:add
fn.SelectedFunc(func(sn *Node) {
sn.sortBy(dirsort.Sort{By: by, Down: down})
})
}
// sortBy sets the sort order of the files in this directory, which is its
// sort order in all apps (see [dirsort.Set]), or in this tree for a
// directory of a [Tree.FS].
func (fn *Node) sortBy(s dirsort.Sort) {
if root := fn.FileRoot(); root.FS != nil {
if root.fsSorts == nil {
root.fsSorts = map[string]dirsort.Sort{}
}
root.fsSorts[string(fn.Filepath)] = s
} else {
core.ErrorSnackbar(fn, dirsort.Set(string(fn.Filepath), s), "Could not save the sort order")
}
fn.Update()
}
// openAll opens all directories under this one
func (fn *Node) openAll() { //types:add
fn.FileRoot().inOpenAll = true // causes chaining of opening
fn.OpenAll()
fn.FileRoot().inOpenAll = false
fn.FileRoot().syncWatchDirs()
}
// removeFromExterns removes file from list of external files
func (fn *Node) removeFromExterns() { //types:add
fn.SelectedFunc(func(sn *Node) {
if !sn.isExternal() {
return
}
sn.FileRoot().removeExternalFile(string(sn.Filepath))
sn.Delete()
})
}
// RelativePathFrom returns the relative path from node for given full path
func (fn *Node) RelativePathFrom(fpath core.Filename) string {
return fsx.RelativeFilePath(string(fpath), string(fn.Filepath))
}
// dirsTo opens all the directories above the given filename, and returns the node
// for element at given path (can be a file or directory itself -- not opened -- just returned)
func (fn *Node) dirsTo(path string) (*Node, error) {
pth := path
sep := string(filepath.Separator)
var err error
if fn.isFS() { // (paths within the FS, separated by /)
sep = "/"
} else if pth, err = filepath.Abs(path); err != nil {
log.Printf("filetree.Node DirsTo path %v could not be turned into an absolute path: %v\n", path, err)
return nil, err
}
rpath := fn.RelativePathFrom(core.Filename(pth))
if fn.isFS() {
rpath = filepath.ToSlash(rpath)
}
if rpath == "." {
return fn, nil
}
dirs := strings.Split(rpath, sep)
cfn := fn
sz := len(dirs)
for i := range sz {
dr := dirs[i]
sfni := cfn.ChildByName(dr, 0)
if sfni == nil {
if i == sz-1 { // ok for terminal -- might not exist yet
return cfn, nil
}
err = fmt.Errorf("filetree.Node could not find node %v in: %v, orig: %v, rel: %v", dr, cfn.Filepath, pth, rpath)
// slog.Error(err.Error()) // note: this is expected sometimes
return nil, err
}
sfn := AsNode(sfni)
if sfn.IsDir() || i == sz-1 {
if i < sz-1 && !sfn.isOpen() {
sfn.openDir()
} else {
cfn = sfn
}
} else {
err := fmt.Errorf("filetree.Node non-terminal node %v is not a directory in: %v", dr, cfn.Filepath)
slog.Error(err.Error())
return nil, err
}
cfn = sfn
}
return cfn, nil
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package filetree
import (
"cogentcore.org/core/base/dirsort"
"fmt"
"io/fs"
"os"
"path/filepath"
"sync/atomic"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/vcs"
"cogentcore.org/core/core"
"cogentcore.org/core/tree"
"cogentcore.org/core/types"
)
const (
// externalFilesName is the name of the node that represents external files
externalFilesName = "[external files]"
)
// Treer is an interface for getting the Root node if it implements [Treer].
type Treer interface {
AsFileTree() *Tree
}
// AsTree returns the given value as a [Tree] if it has
// an AsFileTree() method, or nil otherwise.
func AsTree(n tree.Node) *Tree {
if t, ok := n.(Treer); ok {
return t.AsFileTree()
}
return nil
}
// Tree is the root widget of a file tree representing files in a given directory
// (and subdirectories thereof), and has some overall management state for how to
// view things.
type Tree struct {
Node
// externalFiles are external files outside the root path of the tree.
// They are stored in terms of their absolute paths. These are shown
// in the first sub-node if present; use [Tree.AddExternalFile] to add one.
externalFiles []string
// Dirs records state of directories within the tree (encoded using paths relative to root),
// e.g., open (have been opened by the user) -- can persist this to restore prior view of a tree
Dirs DirFlagMap `set:"-"`
// DirsOnTop indicates whether all directories are placed at the top of the tree.
// Otherwise everything is mixed. This is the default.
DirsOnTop bool
// FileNodeType is the type of node to create; defaults to [Node] but can use custom node types
FileNodeType *types.Type `display:"-" json:"-" xml:"-"`
// FilterFunc, if set, determines whether to include the given node in the tree.
// return true to include, false to not. This applies to files and directories alike.
FilterFunc func(path string, info fs.FileInfo) bool
// AppsAsDirs shows app bundles as directories, which open by clicking,
// instead of as apps, which open as apps by double-clicking
// (see [Node.IsApp]).
AppsAsDirs bool
// FS is the file system we are browsing, if it is an FS (nil = os filesystem).
// Its files can be changed, as those of the os, with the operations
// that it has, with the interfaces of hackpadfs (see [CopyFS]),
// and otherwise it is read-only.
FS fs.FS
// FSSort is the sort order of the directories of the [Tree.FS], other
// than those set with Sort by, which is by name by default. That of
// the directories of the os is shared by all apps (see [dirsort.For]).
FSSort dirsort.Sort
// fsSorts are the sort orders of the directories of the [Tree.FS] set
// with Sort by, by path.
fsSorts map[string]dirsort.Sort
// inOpenAll indicates whether we are in midst of an OpenAll call; nodes should open all dirs.
inOpenAll bool
// NoWatch disables the file system watcher, which otherwise updates
// the tree when files change on disk. It must be set before [Tree.OpenPath].
NoWatch bool
// WatchFunc, if set, is called with each batch of changes detected by
// the file system watcher, after the tree has been updated for them.
// It is called under [core.WidgetBase.AsyncLock], so it can update the GUI
// directly. Only the files directly within the root and the open
// directories of the tree are watched, excluding hidden directories.
WatchFunc func(changes []FileChange) `display:"-" json:"-" xml:"-"`
// watch is the active file system watcher, if any.
watch atomic.Pointer[treeWatcher]
}
func (ft *Tree) Init() {
ft.Node.Init()
ft.Root = ft
ft.FileNodeType = types.For[Node]()
ft.OpenDepth = 4
ft.DirsOnTop = true
ft.FirstMaker(func(p *tree.Plan) {
if len(ft.externalFiles) == 0 {
return
}
tree.AddNew(p, externalFilesName, func() Filer {
return tree.NewOfType(ft.FileNodeType).(Filer)
}, func(wf Filer) {
w := wf.AsFileNode()
w.Root = ft.Root
w.Filepath = externalFilesName
w.Info.Mode = os.ModeDir
w.Info.VCS = vcs.Stored
})
})
}
func (ft *Tree) Destroy() {
ft.stopWatcher()
ft.Tree.Destroy()
}
func (ft *Tree) AsFileTree() *Tree {
return ft
}
// OpenPath opens the filetree at the given os file system directory path.
// It reads all the files at the given path into this tree.
// Only paths listed in [Tree.Dirs] will be opened.
func (ft *Tree) OpenPath(path string) *Tree {
if ft.FileNodeType == nil {
ft.FileNodeType = types.For[Node]()
}
effpath, err := filepath.EvalSymlinks(path)
if err != nil {
effpath = path
}
abs, err := filepath.Abs(effpath)
if errors.Log(err) != nil {
abs = effpath
}
ft.resetForPath(nil, abs)
ft.FS = nil
ft.Filepath = core.Filename(abs)
ft.setDirOpen(core.Filename(abs))
ft.detectVCSRepo()
ft.This.(Filer).GetFileInfo()
ft.Open()
ft.Update()
ft.startWatcher()
return ft
}
// resetForPath deletes the nodes of the tree if it is opened at another
// path than its current one, or in a file system instead of the os one,
// or the reverse: the nodes are made once for each name, with their
// paths, so that a node of a directory with the same name would keep the
// path of the old one. (File systems are not compared, which can panic.)
func (ft *Tree) resetForPath(fsys fs.FS, path string) {
if ft.Filepath != "" && (ft.Filepath != core.Filename(path) || (ft.FS == nil) != (fsys == nil)) {
ft.DeleteChildren()
}
}
// OpenPathFS opens the filetree at the given [fs] file system directory path.
// It reads all the files at the given path into this tree.
// Only paths listed in [Tree.Dirs] will be opened.
func (ft *Tree) OpenPathFS(fsys fs.FS, path string) *Tree {
if ft.FileNodeType == nil {
ft.FileNodeType = types.For[Node]()
}
ft.stopWatcher()
ft.resetForPath(fsys, path)
ft.FS = fsys
ft.Filepath = core.Filename(path)
ft.setDirOpen(core.Filename(path))
ft.This.(Filer).GetFileInfo()
ft.Open()
ft.Update()
return ft
}
// UpdatePath updates the tree at the directory level for given path
// and everything below it. It flags that it needs render update,
// but if a deletion or insertion happened, then NeedsLayout should also
// be called.
func (ft *Tree) UpdatePath(path string) {
ft.NeedsRender()
path = ft.cleanPath(path)
if path == ft.cleanPath(string(ft.Filepath)) { // (such as "." in an FS)
ft.Update()
return
}
ft.dirsTo(path)
if fn, ok := ft.FindFile(path); ok {
if fn.IsDir() {
fn.Update()
return
}
}
fpath := ft.dirOf(path)
if fn, ok := ft.FindFile(fpath); ok {
fn.Update()
return
}
// core.MessageSnackbar(ft, "UpdatePath: path not found in tree: "+path)
}
// OpenPaths returns a list of open paths.
func (ft *Tree) OpenPaths() []string {
return ft.Dirs.openPaths(string(ft.Filepath))
}
// isDirOpen returns true if given directory path is open (i.e., has been
// opened in the view)
func (ft *Tree) isDirOpen(fpath core.Filename) bool {
if fpath == ft.Filepath { // we are always open
return true
}
return ft.Dirs.isOpen(ft.RelativePathFrom(fpath))
}
// setDirOpen sets the given directory path to be open
func (ft *Tree) setDirOpen(fpath core.Filename) {
rp := ft.RelativePathFrom(fpath)
// fmt.Printf("setdiropen: %s\n", rp)
ft.Dirs.setOpen(rp, true)
}
// setDirClosed sets the given directory path to be closed
func (ft *Tree) setDirClosed(fpath core.Filename) {
rp := ft.RelativePathFrom(fpath)
ft.Dirs.setOpen(rp, false)
}
// AddExternalFile adds an external file outside of root of file tree
// and triggers an update, returning the Node for it, or
// error if [filepath.Abs] fails.
func (ft *Tree) AddExternalFile(fpath string) (*Node, error) {
pth, err := filepath.Abs(fpath)
if err != nil {
return nil, err
}
if _, err := os.Stat(pth); err != nil {
return nil, err
}
if has, _ := ft.hasExternalFile(pth); has {
return ft.externalNodeByPath(pth)
}
newExt := len(ft.externalFiles) == 0
ft.externalFiles = append(ft.externalFiles, pth)
if newExt {
ft.Update()
} else {
ft.Child(0).(Filer).AsFileNode().Update()
}
return ft.externalNodeByPath(pth)
}
// removeExternalFile removes external file from maintained list; returns true if removed.
func (ft *Tree) removeExternalFile(fpath string) bool {
for i, ef := range ft.externalFiles {
if ef == fpath {
ft.externalFiles = append(ft.externalFiles[:i], ft.externalFiles[i+1:]...)
return true
}
}
return false
}
// hasExternalFile returns true and index if given abs path exists on ExtFiles list.
// false and -1 if not.
func (ft *Tree) hasExternalFile(fpath string) (bool, int) {
for i, f := range ft.externalFiles {
if f == fpath {
return true, i
}
}
return false, -1
}
// externalNodeByPath returns Node for given file path, and true, if it
// exists in the external files list. Otherwise returns nil, false.
func (ft *Tree) externalNodeByPath(fpath string) (*Node, error) {
ehas, i := ft.hasExternalFile(fpath)
if !ehas {
return nil, fmt.Errorf("ExtFile not found on list: %v", fpath)
}
ekid := ft.ChildByName(externalFilesName, 0)
if ekid == nil {
return nil, errors.New("ExtFile not updated -- no ExtFiles node")
}
if n := ekid.AsTree().Child(i); n != nil {
return AsNode(n), nil
}
return nil, errors.New("ExtFile not updated; index invalid")
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package filetree
import (
"bytes"
"fmt"
"log/slog"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/fsx"
"cogentcore.org/core/base/vcs"
"cogentcore.org/core/core"
"cogentcore.org/core/styles"
"cogentcore.org/core/text/lines"
"cogentcore.org/core/text/text"
"cogentcore.org/core/text/textcore"
"cogentcore.org/core/tree"
)
// FirstVCS returns the first VCS repository starting from this node and going down.
// also returns the node having that repository
func (fn *Node) FirstVCS() (vcs.Repo, *Node) {
if fn.FileRoot().FS != nil {
return nil, nil
}
var repo vcs.Repo
var rnode *Node
for cw := range fn.AllWidgets() {
sfn := AsNode(cw)
if sfn == nil {
continue
}
sfn.detectVCSRepo()
if sfn.DirRepo != nil {
repo = sfn.DirRepo
rnode = sfn
break
}
}
return repo, rnode
}
// detectVCSRepo detects and configures DirRepo if this directory is root of
// a VCS repository, or for the root of the tree, within one.
// Returns true if a repository was newly found here.
func (fn *Node) detectVCSRepo() bool {
repo, _ := fn.Repo()
if repo != nil {
return false
}
path := string(fn.Filepath)
if fn.IsRoot() { // the tree can be within a repository
path, _ = vcs.DetectRepoRoot(path)
} else if vcs.DetectRepo(path) == vcs.NoVCS {
return false
}
if path == "" {
return false
}
var err error
repo, err = vcs.NewRepo("origin", path)
if err != nil {
slog.Error(err.Error())
return false
}
fn.DirRepo = repo
return true
}
// Repo returns the version control repository associated with this file,
// and the node for the directory where the repo is based.
// Goes up the tree until a repository is found.
func (fn *Node) Repo() (vcs.Repo, *Node) {
fr := fn.FileRoot()
if fr == nil {
return nil, nil
}
if fn.isExternal() || fr.FS != nil {
return nil, nil
}
if fn.DirRepo != nil {
return fn.DirRepo, fn
}
var repo vcs.Repo
var rnode *Node
for k := range fn.Ancestors() {
sfn := AsNode(k)
if sfn == nil {
break
}
if sfn.IsIrregular() {
break
}
if sfn.DirRepo != nil {
repo = sfn.DirRepo
rnode = sfn
break
}
}
return repo, rnode
}
// setVCSStatus sets the VCS status of the node after a VCS operation on
// it, and updates the files of its repository, whose cached status of the
// file is stale until then (so the node is not updated from it now).
func (fn *Node) setVCSStatus(status vcs.FileStatus) {
fn.Info.VCS = status
fn.NeedsRender()
if _, rnode := fn.Repo(); rnode != nil {
rnode.updateRepoFiles()
}
}
func (fn *Node) updateRepoFiles() {
if fn.DirRepo == nil {
return
}
fn.DirRepo.Files(func(f vcs.Files) { // need the func to make it work
fr := fn.FileRoot()
fr.AsyncLock()
fn.Update()
fr.AsyncUnlock()
})
}
// addToVCSSelected adds selected files to version control system
func (fn *Node) addToVCSSelected() { //types:add
fn.SelectedFunc(func(sn *Node) {
sn.AddToVCS()
})
}
// AddToVCS adds file to version control
func (fn *Node) AddToVCS() {
repo, _ := fn.Repo()
if repo == nil {
return
}
err := repo.Add(string(fn.Filepath))
if err != nil {
core.ErrorSnackbar(fn, err, "Error adding file to VCS")
return
}
fn.setVCSStatus(vcs.Added)
}
// deleteFromVCSSelected removes selected files from version control system
func (fn *Node) deleteFromVCSSelected() { //types:add
fn.SelectedFunc(func(sn *Node) {
sn.deleteFromVCS()
})
}
// deleteFromVCS removes file from version control
func (fn *Node) deleteFromVCS() {
repo, _ := fn.Repo()
if repo == nil {
return
}
// fmt.Printf("deleting remote from vcs: %v\n", fn.FPath)
err := repo.DeleteRemote(string(fn.Filepath))
if err != nil {
core.ErrorSnackbar(fn, err, "Error deleting file from VCS")
return
}
fn.setVCSStatus(vcs.Deleted)
}
// commitToVCSSelected commits to version control system based on last selected file
func (fn *Node) commitToVCSSelected() { //types:add
done := false
fn.SelectedFunc(func(sn *Node) {
if !done {
core.CallFunc(sn, fn.commitToVCS)
done = true
}
})
}
// commitToVCS commits file changes to version control system
func (fn *Node) commitToVCS(message string) (err error) {
repo, _ := fn.Repo()
if repo == nil {
return
}
if fn.Info.VCS == vcs.Untracked {
return errors.New("file not in vcs repo: " + string(fn.Filepath))
}
err = repo.CommitFile(string(fn.Filepath), message)
if err != nil {
return err
}
fn.setVCSStatus(vcs.Stored)
return err
}
// revertVCSSelected removes selected files from version control system
func (fn *Node) revertVCSSelected() { //types:add
var errs []error
fn.SelectedFunc(func(sn *Node) {
errs = append(errs, sn.revertVCS())
})
core.ErrorSnackbar(fn, errors.Join(errs...), "Error reverting file")
}
// revertVCS reverts file changes since last commit
func (fn *Node) revertVCS() (err error) {
repo, _ := fn.Repo()
if repo == nil {
return
}
if fn.Info.VCS == vcs.Untracked {
return errors.New("file not in vcs repo: " + string(fn.Filepath))
}
err = repo.RevertFile(string(fn.Filepath))
if err != nil {
return err
}
status := fn.Info.VCS
if status == vcs.Modified {
status = vcs.Stored
} // an added file stays added
// todo:
// if fn.Lines != nil {
// fn.Lines.Revert()
// }
fn.setVCSStatus(status)
return err
}
// diffVCSSelected shows the diffs between two versions of selected files, given by the
// revision specifiers -- if empty, defaults to A = current HEAD, B = current WC file.
// -1, -2 etc also work as universal ways of specifying prior revisions.
// Diffs are shown in a DiffEditorDialog.
func (fn *Node) diffVCSSelected(revA string, revB string) { //types:add
var errs []error
fn.SelectedFunc(func(sn *Node) {
errs = append(errs, sn.diffVCS(revA, revB))
})
core.ErrorSnackbar(fn, errors.Join(errs...), "Error showing VCS diffs")
}
// diffVCS shows the diffs between two versions of this file, given by the
// revision specifiers -- if empty, defaults to A = current HEAD, B = current WC file.
// -1, -2 etc also work as universal ways of specifying prior revisions.
// Diffs are shown in a DiffEditorDialog.
func (fn *Node) diffVCS(revA, revB string) error {
repo, _ := fn.Repo()
if repo == nil {
return errors.New("file not in vcs repo: " + string(fn.Filepath))
}
if fn.Info.VCS == vcs.Untracked {
return errors.New("file not in vcs repo: " + string(fn.Filepath))
}
// todo:
_, err := textcore.DiffEditorDialogFromRevs(fn, repo, string(fn.Filepath) /*fn.Lines*/, nil, revA, revB)
return err
}
// logVCSSelected shows the VCS log of commits for selected files.
func (fn *Node) logVCSSelected() { //types:add
var errs []error
fn.SelectedFunc(func(sn *Node) {
_, err := sn.LogVCS(false, "")
errs = append(errs, err)
})
core.ErrorSnackbar(fn, errors.Join(errs...), "Error showing VCS log")
}
// LogVCS shows the VCS log of commits for this file, optionally with a
// since date qualifier: If since is non-empty, it should be
// a date-like expression that the VCS will understand, such as
// 1/1/2020, yesterday, last year, etc. SVN only understands a
// number as a maximum number of items to return.
// If allFiles is true, then the log will show revisions for all files, not just
// this one.
// Returns the Log and also shows it in a VCSLog which supports further actions.
func (fn *Node) LogVCS(allFiles bool, since string) (vcs.Log, error) {
repo, _ := fn.Repo()
if repo == nil {
return nil, errors.New("file not in vcs repo: " + string(fn.Filepath))
}
if fn.Info.VCS == vcs.Untracked {
return nil, errors.New("file not in vcs repo: " + string(fn.Filepath))
}
fnm := string(fn.Filepath)
if allFiles {
fnm = ""
}
lg, err := repo.Log(fnm, since)
if err != nil {
return lg, err
}
vcsLogDialog(nil, repo, lg, fnm, since)
return lg, nil
}
// blameVCSSelected shows the VCS blame report for this file, reporting for each line
// the revision and author of the last change.
func (fn *Node) blameVCSSelected() { //types:add
var errs []error
fn.SelectedFunc(func(sn *Node) {
_, err := sn.blameVCS()
errs = append(errs, err)
})
core.ErrorSnackbar(fn, errors.Join(errs...), "Error showing VCS blame")
}
// blameDialog opens a dialog for displaying VCS blame data using textview.TwinViews.
// blame is the annotated blame code, while fbytes is the original file contents.
func blameDialog(ctx core.Widget, fname string, blame, fbytes []byte) *textcore.TwinEditors {
title := "VCS Blame: " + fsx.DirAndFile(fname)
d := core.NewBody(title)
tv := textcore.NewTwinEditors(d)
tv.SetSplits(.3, .7)
tv.SetFiles(fname, fname)
flns := bytes.Split(fbytes, []byte("\n"))
lns := bytes.Split(blame, []byte("\n"))
nln := min(len(lns), len(flns))
blns := make([][]byte, nln)
stidx := 0
for i := range nln {
fln := flns[i]
bln := lns[i]
if stidx == 0 {
if len(fln) == 0 {
stidx = len(bln)
} else {
stidx = bytes.LastIndex(bln, fln)
}
}
blns[i] = bln[:stidx]
}
btxt := bytes.Join(blns, []byte("\n")) // makes a copy, so blame is disposable now
tv.BufferA.SetText(btxt)
tv.BufferB.SetText(fbytes)
tv.Update()
tva, tvb := tv.Editors()
tva.Styler(func(s *styles.Style) {
s.Text.WhiteSpace = text.WhiteSpacePre
s.Min.X.Ch(30)
s.Min.Y.Em(40)
})
tvb.Styler(func(s *styles.Style) {
s.Text.WhiteSpace = text.WhiteSpacePre
s.Min.X.Ch(80)
s.Min.Y.Em(40)
})
d.AddOKOnly()
d.RunWindowDialog(ctx)
return tv
}
// blameVCS shows the VCS blame report for this file, reporting for each line
// the revision and author of the last change.
func (fn *Node) blameVCS() ([]byte, error) {
repo, _ := fn.Repo()
if repo == nil {
return nil, errors.New("file not in vcs repo: " + string(fn.Filepath))
}
if fn.Info.VCS == vcs.Untracked {
return nil, errors.New("file not in vcs repo: " + string(fn.Filepath))
}
fnm := string(fn.Filepath)
fb, err := lines.FileBytes(fnm)
if err != nil {
return nil, err
}
blm, err := repo.Blame(fnm)
if err != nil {
return blm, err
}
blameDialog(nil, fnm, blm, fb)
return blm, nil
}
// UpdateAllVCS does an update on any repositories below this one in file tree
func (fn *Node) UpdateAllVCS() {
fn.WidgetWalkDown(func(cw core.Widget, cwb *core.WidgetBase) bool {
sfn := AsNode(cw)
if sfn == nil {
return tree.Continue
}
if !sfn.IsDir() {
return tree.Continue
}
if sfn.DirRepo == nil {
if !sfn.detectVCSRepo() {
return tree.Continue
}
}
repo := sfn.DirRepo
fmt.Printf("Updating %v repository: %s from: %s\n", repo.Type(), sfn.RelativePath(), repo.Remote())
core.ErrorSnackbar(fn, repo.Update(), "Error updating VCS repository")
return tree.Break
})
}
// Copyright (c) 2020, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package filetree
import (
"image"
"cogentcore.org/core/base/fileinfo/mimedata"
"cogentcore.org/core/base/fsx"
"cogentcore.org/core/base/vcs"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/styles"
"cogentcore.org/core/text/diffbrowser"
"cogentcore.org/core/text/lines"
"cogentcore.org/core/text/textcore"
"cogentcore.org/core/tree"
)
// VCSLog is a widget that represents VCS log data.
type VCSLog struct {
core.Frame
// current log
Log vcs.Log
// file that this is a log of -- if blank then it is entire repository
File string
// date expression for how long ago to include log entries from
Since string
// version control system repository
Repo vcs.Repo `json:"-" xml:"-" copier:"-"`
// revision A -- defaults to HEAD
revisionA string
// revision B -- blank means current working copy
revisionB string
// double-click will set the A revision -- else B
setA bool
arev, brev *core.Switch
atf, btf *core.TextField
}
func (lv *VCSLog) Init() {
lv.Frame.Init()
lv.revisionA = "HEAD"
lv.revisionB = ""
lv.setA = true
lv.Styler(func(s *styles.Style) {
s.Direction = styles.Column
s.Grow.Set(1, 1)
})
tree.AddChildAt(lv, "toolbar", func(w *core.Toolbar) {
w.Maker(lv.makeToolbar)
})
tree.AddChildAt(lv, "log", func(w *core.Table) {
w.SetReadOnly(true)
w.SetSlice(&lv.Log)
w.AddContextMenu(func(m *core.Scene, pos image.Point) {
core.NewButton(m).SetText("Set Revision A").
SetTooltip("Set Buffer A's revision to this").
OnClick(func(e events.Event) {
cmt := lv.Log[w.SelectedIndex]
lv.setRevisionA(cmt.Rev)
})
core.NewButton(m).SetText("Set Revision B").
SetTooltip("Set Buffer B's revision to this").
OnClick(func(e events.Event) {
cmt := lv.Log[w.SelectedIndex]
lv.setRevisionB(cmt.Rev)
})
core.NewButton(m).SetText("Copy Revision ID").
SetTooltip("Copies the revision number / hash for this").
OnClick(func(e events.Event) {
cmt := lv.Log[w.SelectedIndex]
w.Clipboard().Write(mimedata.NewText(cmt.Rev))
})
core.NewButton(m).SetText("View Revision").
SetTooltip("Views the file at this revision").
OnClick(func(e events.Event) {
cmt := lv.Log[w.SelectedIndex]
fileAtRevisionDialog(lv, lv.Repo, lv.File, cmt.Rev)
})
core.NewButton(m).SetText("Checkout Revision").
SetTooltip("Checks out this revision").
OnClick(func(e events.Event) {
cmt := lv.Log[w.SelectedIndex]
if err := lv.Repo.UpdateVersion(cmt.Rev); err != nil {
core.ErrorSnackbar(lv, err, "Error checking out revision")
return
}
core.MessageSnackbar(lv, "Checked out revision "+cmt.Rev)
})
})
w.OnSelect(func(e events.Event) {
idx := w.SelectedIndex
if idx < 0 || idx >= len(lv.Log) {
return
}
cmt := lv.Log[idx]
if lv.setA {
lv.setRevisionA(cmt.Rev)
} else {
lv.setRevisionB(cmt.Rev)
}
lv.toggleRevision()
})
w.OnDoubleClick(func(e events.Event) {
idx := w.SelectedIndex
if idx < 0 || idx >= len(lv.Log) {
return
}
cmt := lv.Log[idx]
if lv.File != "" {
if lv.setA {
lv.setRevisionA(cmt.Rev)
} else {
lv.setRevisionB(cmt.Rev)
}
lv.toggleRevision()
}
cinfo, err := lv.Repo.CommitDesc(cmt.Rev, false)
if err != nil {
core.ErrorSnackbar(lv, err, "Error getting commit info")
return
}
d := core.NewBody("Commit Info: " + cmt.Rev)
buf := lines.NewLines()
buf.SetFilename(lv.File)
buf.Settings.LineNumbers = true
buf.Stat()
textcore.NewEditor(d).SetLines(buf).Styler(func(s *styles.Style) {
s.Grow.Set(1, 1)
})
buf.SetText(cinfo)
d.AddBottomBar(func(bar *core.Frame) {
core.NewButton(bar).SetText("Copy to clipboard").SetIcon(icons.ContentCopy).
OnClick(func(e events.Event) {
d.Clipboard().Write(mimedata.NewTextBytes(cinfo))
})
d.AddOK(bar)
})
d.RunFullDialog(lv)
})
})
}
// setRevisionA sets the revision to use for buffer A
func (lv *VCSLog) setRevisionA(rev string) {
lv.revisionA = rev
lv.atf.Update()
}
// setRevisionB sets the revision to use for buffer B
func (lv *VCSLog) setRevisionB(rev string) {
lv.revisionB = rev
lv.btf.Update()
}
// toggleRevision switches the active revision to set
func (lv *VCSLog) toggleRevision() {
lv.setA = !lv.setA
lv.arev.UpdateRender()
lv.brev.UpdateRender()
}
func (lv *VCSLog) makeToolbar(p *tree.Plan) {
tree.Add(p, func(w *core.Text) {
w.SetText("File: " + fsx.DirAndFile(lv.File))
})
tree.AddAt(p, "a-rev", func(w *core.Switch) {
lv.arev = w
core.Bind(&lv.setA, w)
w.SetText("A Rev: ")
w.SetTooltip("If selected, clicking in log will set this A Revision to use for Diff")
w.OnChange(func(e events.Event) {
lv.brev.UpdateRender()
})
})
tree.AddAt(p, "a-tf", func(w *core.TextField) {
lv.atf = w
core.Bind(&lv.revisionA, w)
w.SetTooltip("A revision: typically this is the older, base revision to compare")
})
tree.Add(p, func(w *core.Button) {
w.SetText("View A").SetIcon(icons.Document).
SetTooltip("View file at revision A").
OnClick(func(e events.Event) {
fileAtRevisionDialog(lv, lv.Repo, lv.File, lv.revisionA)
})
})
tree.Add(p, func(w *core.Separator) {})
tree.AddAt(p, "b-rev", func(w *core.Switch) {
lv.brev = w
w.SetText("B Rev: ")
w.SetTooltip("If selected, clicking in log will set this B Revision to use for Diff")
w.Updater(func() {
w.SetChecked(!lv.setA)
})
w.OnChange(func(e events.Event) {
lv.setA = !w.IsChecked()
lv.arev.UpdateRender()
})
})
tree.AddAt(p, "b-tf", func(w *core.TextField) {
lv.btf = w
core.Bind(&lv.revisionB, w)
w.SetTooltip("B revision: typically this is the newer revision to compare. Leave blank for the current working directory.")
})
tree.Add(p, func(w *core.Button) {
w.SetText("View B").SetIcon(icons.Document).
SetTooltip("View file at revision B").
OnClick(func(e events.Event) {
fileAtRevisionDialog(lv, lv.Repo, lv.File, lv.revisionB)
})
})
tree.Add(p, func(w *core.Separator) {})
tree.Add(p, func(w *core.Button) {
w.SetText("Diff").SetIcon(icons.Difference).
SetTooltip("Show the diffs between two revisions; if blank, A is current HEAD, and B is current working copy").
OnClick(func(e events.Event) {
if lv.File == "" {
diffbrowser.NewDiffBrowserVCS(lv.Repo, lv.revisionA, lv.revisionB)
} else {
textcore.DiffEditorDialogFromRevs(lv, lv.Repo, lv.File, nil, lv.revisionA, lv.revisionB)
}
})
})
}
// vcsLogDialog returns a VCS Log View for given repo, log and file (file could be empty)
func vcsLogDialog(ctx core.Widget, repo vcs.Repo, lg vcs.Log, file, since string) *core.Body {
title := "VCS Log: "
if file == "" {
title += "All files"
} else {
title += fsx.DirAndFile(file)
}
if since != "" {
title += " since: " + since
}
d := core.NewBody(title)
lv := NewVCSLog(d)
lv.SetRepo(repo).SetLog(lg).SetFile(file).SetSince(since)
d.RunWindowDialog(ctx)
return d
}
// fileAtRevisionDialog shows a file at a given revision in a new dialog window
func fileAtRevisionDialog(ctx core.Widget, repo vcs.Repo, file, rev string) *core.Body {
if rev == "" { // FileContents returns the working copy for ""
rev = "HEAD"
}
fb, err := repo.FileContents(file, rev)
if err != nil {
core.ErrorDialog(ctx, err)
return nil
}
title := "File at VCS Revision: " + fsx.DirAndFile(file) + "@" + rev
d := core.NewBody(title)
tb := lines.NewLines().SetText(fb).SetFilename(file) // file is key for getting lang
textcore.NewEditor(d).SetLines(tb).SetReadOnly(true).Styler(func(s *styles.Style) {
s.Grow.Set(1, 1)
})
d.RunWindowDialog(ctx)
tb.ReMarkup() // update markup
return d
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package filetree
import (
"cmp"
"context"
"errors"
"io/fs"
"log/slog"
"maps"
"os"
"path/filepath"
"slices"
"strings"
"time"
"cogentcore.org/core/base/vcs"
)
// FileChange is a change to a file or directory on disk,
// detected by the file system watcher of a [Tree].
// See [Tree.WatchFunc].
type FileChange struct {
// Path is the absolute path of the file or directory.
Path string
// Removed is true if the path no longer exists
// (it was deleted or renamed to another path).
Removed bool
// IsDir is true if the path is a directory. Files within a changed
// directory may have changed without being listed separately,
// for example when the watcher could not keep up with all events.
IsDir bool
}
// watchBatch is how long the watcher collects changes before applying them.
const watchBatch = 200 * time.Millisecond
// treeWatcher is a running file system watcher for a [Tree].
type treeWatcher struct {
// root is the root directory of the tree.
root string
// ctx is canceled when the watcher is stopped.
ctx context.Context
// cancel stops the watcher.
cancel context.CancelFunc
// ready is closed when the watcher has started watching.
ready chan struct{}
// backend is the platform file system watcher.
backend *watchBackend
// watched are the directories being watched.
// It is only used in the event loop.
watched map[string]bool
// gitDirs are the git directories of the repositories in the tree
// being watched, with the nodes of the repositories, whose version
// control status is updated when they change (see [Tree.gitDirs]).
// It is only used in the event loop.
gitDirs map[string]*Node
}
// watchBackend is the interface to the platform file system watcher.
type watchBackend struct {
// events receives the changed paths. An empty path
// means that events were lost, so anything may have changed.
events <-chan string
// add starts watching the files in the given directory,
// and drop stops it. They do not block.
add, drop func(dir string)
// busy returns whether add or drop operations are in progress.
busy func() bool
}
// startWatcher starts watching the open directories of the tree
// for changes, stopping any watcher of a different root directory.
// Only the files directly within open, non-hidden directories are
// watched, so the watched directories are updated as directories
// are opened and closed (see [Tree.syncWatchDirs]).
func (ft *Tree) startWatcher() {
root := string(ft.Filepath)
if tw := ft.watch.Load(); tw != nil {
if tw.root == root {
return
}
ft.stopWatcher()
}
if ft.NoWatch || ft.FS != nil || root == "" {
return
}
ctx, cancel := context.WithCancel(context.Background())
tw := &treeWatcher{root: root, ctx: ctx, cancel: cancel, ready: make(chan struct{}), watched: make(map[string]bool)}
tw.gitDirs = ft.gitDirs()
dirs := append(ft.watchableDirs(), slices.Sorted(maps.Keys(tw.gitDirs))...)
be, err := watchDirs(ctx, dirs, tw.ready)
if err != nil || be == nil {
cancel()
if err != nil {
slog.Error("filetree: could not watch directory", "path", root, "err", err)
}
return
}
tw.backend = be
for _, d := range dirs {
tw.watched[d] = true
}
ft.watch.Store(tw)
go ft.watchEvents(tw, be.events)
}
// watchableDirs returns the directories that should be watched:
// the root and the open directories shown in the tree, excluding
// hidden ones (starting with a .) and those within them.
func (ft *Tree) watchableDirs() []string {
dirs := []string{string(ft.Filepath)}
var walk func(n *Node)
walk = func(n *Node) {
for _, c := range n.Children {
cn := AsNode(c)
if cn == nil || !cn.IsDir() || cn.IsIrregular() || cn.Name == externalFilesName || strings.HasPrefix(cn.Name, ".") {
continue
}
if !ft.isDirOpen(cn.Filepath) {
continue
}
dirs = append(dirs, string(cn.Filepath))
walk(cn)
}
}
walk(&ft.Node)
return dirs
}
// gitDirs returns the git directories of the repositories in the tree:
// of the root and the open directories that are repositories, with their
// nodes. A commit, a switch of branch, or a change of what is staged
// changes the files in them (as index, HEAD, and COMMIT_EDITMSG), but
// not the files of the repository, so they are watched to update the
// version control status of its files.
func (ft *Tree) gitDirs() map[string]*Node {
dirs := make(map[string]*Node)
add := func(n *Node) {
if n.DirRepo == nil || n.DirRepo.Type() != vcs.Git {
return
}
if gd := gitDir(n.DirRepo.LocalPath()); gd != "" { // the tree can be in it
dirs[gd] = n
}
}
add(&ft.Node)
var walk func(n *Node)
walk = func(n *Node) {
for _, c := range n.Children {
cn := AsNode(c)
if cn == nil || !cn.IsDir() || !ft.isDirOpen(cn.Filepath) {
continue
}
add(cn)
walk(cn)
}
}
walk(&ft.Node)
return dirs
}
// gitDir returns the git directory of the repository in the given
// directory: its .git directory, or the directory named by its .git
// file, as for a worktree, or "" if there is none.
func gitDir(dir string) string {
gp := filepath.Join(dir, ".git")
fi, err := os.Stat(gp)
if err != nil {
return ""
}
if fi.IsDir() {
return gp
}
b, err := os.ReadFile(gp)
if err != nil {
return ""
}
gd, ok := strings.CutPrefix(strings.TrimSpace(string(b)), "gitdir:")
if !ok {
return ""
}
gd = strings.TrimSpace(gd)
if !filepath.IsAbs(gd) {
gd = filepath.Join(dir, gd)
}
return filepath.Clean(gd)
}
// syncWatchDirs updates the watched directories to match
// the open directories in the tree, and their git directories.
func (ft *Tree) syncWatchDirs() {
tw := ft.watch.Load()
if tw == nil {
return
}
tw.gitDirs = ft.gitDirs()
want := make(map[string]bool)
for d := range tw.gitDirs {
want[d] = true
if !tw.watched[d] {
tw.watched[d] = true
tw.backend.add(d)
}
}
for _, d := range ft.watchableDirs() {
want[d] = true
if !tw.watched[d] {
tw.watched[d] = true
tw.backend.add(d)
}
}
for d := range tw.watched {
if !want[d] {
delete(tw.watched, d)
tw.backend.drop(d)
}
}
}
// stopWatcher stops the file system watcher, if any.
func (ft *Tree) stopWatcher() {
if tw := ft.watch.Swap(nil); tw != nil {
tw.cancel()
}
}
// waitWatchReady waits until the watcher has started watching and
// has finished adding and dropping directories, returning false if
// there is no watcher or it does not get there in time.
func (ft *Tree) waitWatchReady(timeout time.Duration) bool {
tw := ft.watch.Load()
if tw == nil {
return false
}
deadline := time.After(timeout)
select {
case <-tw.ready:
case <-deadline:
return false
}
for tw.backend.busy() {
select {
case <-deadline:
return false
case <-time.After(10 * time.Millisecond):
}
}
return true
}
// watchEvents collects the changed paths sent by the watcher
// into batches and applies them to the tree. An empty path means
// that events were lost, so anything may have changed.
func (ft *Tree) watchEvents(tw *treeWatcher, events <-chan string) {
pending := make(map[string]bool)
timer := time.NewTimer(watchBatch)
timer.Stop()
for {
select {
case <-tw.ctx.Done():
return
case path, ok := <-events:
if !ok {
return
}
if len(pending) == 0 {
timer.Reset(watchBatch)
}
pending[path] = true
case <-timer.C:
if !ft.applyChanges(tw, slices.Sorted(maps.Keys(pending))) {
timer.Reset(watchBatch) // not shown yet; try again
continue
}
clear(pending)
}
}
}
// applyChanges updates the tree for the given changed paths and calls
// [Tree.WatchFunc]. The state of each path is read from disk, as event
// types are not reliable (FSEvents accumulates flags for a path).
// It returns false if the tree is not shown, so the changes can be
// applied later.
func (ft *Tree) applyChanges(tw *treeWatcher, paths []string) bool {
if !ft.AsyncLockIfShown() {
return tw.ctx.Err() != nil
}
defer ft.AsyncUnlock()
if ft.watch.Load() != tw {
return true
}
changes := make([]FileChange, 0, len(paths))
update := make(map[*Node]bool)
repos := make(map[*Node]bool)
for _, path := range paths {
if path == "" { // lost events
update[&ft.Node] = true
changes = append(changes, FileChange{Path: tw.root, IsDir: true})
continue
}
if rn := tw.gitDirs[filepath.Dir(path)]; rn != nil {
repos[rn] = true // the git state, not the files of the tree
continue
}
if isGitPath(path) { // other changes in git directories
continue
}
fc := FileChange{Path: path}
fi, err := os.Stat(path)
switch {
case err == nil:
fc.IsDir = fi.IsDir()
case errors.Is(err, fs.ErrNotExist):
fc.Removed = true
default:
continue
}
changes = append(changes, fc)
ft.nodeToUpdate(fc, update)
if dn := ft.dirNode(filepath.Dir(path)); dn != nil {
if _, rn := dn.Repo(); rn != nil {
repos[rn] = true // as a modified file
}
}
}
ft.updateNodes(update)
// the version control status of the files of the repositories
// whose files or git directories changed, as for a commit
for rn := range repos {
if rn.This != nil {
rn.updateRepoFiles() // updates the nodes when it has the status
}
}
ft.syncWatchDirs()
if ft.WatchFunc != nil && len(changes) > 0 {
ft.WatchFunc(changes)
}
return true
}
// isGitPath returns whether the given path is a .git directory,
// or within one.
func isGitPath(path string) bool {
return slices.Contains(strings.Split(filepath.ToSlash(path), "/"), ".git")
}
// nodeToUpdate adds the node that needs to be updated for the
// given change to update: the parent directory if a node must be
// added or removed, or the node of a modified file.
func (ft *Tree) nodeToUpdate(fc FileChange, update map[*Node]bool) {
if fc.Path == string(ft.Filepath) {
return
}
dn := ft.dirNode(filepath.Dir(fc.Path))
if dn == nil || !ft.isDirOpen(dn.Filepath) {
return
}
cn := dn.ChildByName(filepath.Base(fc.Path), 0)
if cn == nil {
if !fc.Removed {
update[dn] = true
}
return
}
n := AsNode(cn)
if fc.Removed || n.IsDir() != fc.IsDir {
update[dn] = true
return
}
if !n.IsDir() {
update[n] = true
}
}
// updateNodes updates the given nodes, skipping those
// within a directory that is updated, as that updates them too.
func (ft *Tree) updateNodes(update map[*Node]bool) {
nodes := slices.SortedFunc(maps.Keys(update), func(a, b *Node) int {
return cmp.Compare(len(a.Filepath), len(b.Filepath))
})
var dirs []string
for _, n := range nodes {
if n.This == nil {
continue
}
path := string(n.Filepath)
if slices.ContainsFunc(dirs, func(dir string) bool {
return strings.HasPrefix(path, dir+string(filepath.Separator))
}) {
continue
}
if n.IsDir() {
dirs = append(dirs, path)
}
n.Update()
}
if len(dirs) > 0 {
ft.NeedsLayout()
}
}
// dirNode returns the node for the given directory path
// if it is in the tree, or nil otherwise.
func (ft *Tree) dirNode(path string) *Node {
rp, err := filepath.Rel(string(ft.Filepath), path)
if err != nil || rp == ".." || strings.HasPrefix(rp, ".."+string(filepath.Separator)) {
return nil
}
n := &ft.Node
if rp == "." {
return n
}
for name := range strings.SplitSeq(rp, string(filepath.Separator)) {
c := n.ChildByName(name, 0)
if c == nil {
return nil
}
n = AsNode(c)
if !n.IsDir() {
return nil
}
}
return n
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !js && !ios
package filetree
import (
"context"
"log/slog"
"slices"
"sync"
"github.com/sgtdi/fswatcher"
)
// watchDirs starts watching the files directly within the given
// directories, until ctx is canceled. ready is closed when watching
// has started. The changes in version control directories are
// filtered by [Tree.applyChanges], as it watches git directories.
func watchDirs(ctx context.Context, dirs []string, ready chan struct{}) (*watchBackend, error) {
opts := []fswatcher.WatcherOpt{
fswatcher.WithReadyChannel(ready),
}
for _, d := range dirs {
opts = append(opts, fswatcher.WithPath(d, fswatcher.WithDepth(fswatcher.WatchTopLevel)))
}
w, err := fswatcher.New(opts...)
if err != nil {
return nil, err
}
go func() {
if err := w.Watch(ctx); err != nil {
slog.Error("filetree: file watcher failed", "err", err)
}
}()
paths := make(chan string, 256)
go func() {
defer close(paths)
for ev := range w.Events() {
path := ev.Path
if slices.Contains(ev.Types, fswatcher.EventOverflow) {
path = ""
}
select {
case paths <- path:
case <-ctx.Done():
return
}
}
}()
// Directories can only be added and dropped while the watcher is
// running, so the operations are queued and run in order once it is.
var mu sync.Mutex
var ops []func()
running := false
signal := make(chan struct{}, 1)
push := func(op func()) {
mu.Lock()
ops = append(ops, op)
mu.Unlock()
select {
case signal <- struct{}{}:
default:
}
}
go func() {
select {
case <-ready:
case <-ctx.Done():
return
}
for {
select {
case <-signal:
case <-ctx.Done():
return
}
mu.Lock()
do := ops
ops = nil
running = len(do) > 0
mu.Unlock()
for _, op := range do {
op()
}
mu.Lock()
running = false
mu.Unlock()
}
}()
return &watchBackend{
events: paths,
// errors are expected for directories that were just deleted
add: func(dir string) {
push(func() { w.AddPath(dir, fswatcher.WithDepth(fswatcher.WatchTopLevel)) })
},
drop: func(dir string) {
push(func() { w.DropPath(dir) })
},
busy: func() bool {
mu.Lock()
defer mu.Unlock()
return running || len(ops) > 0
},
}, nil
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gpu
import (
"fmt"
"cogentcore.org/core/base/errors"
"github.com/oliverbestmann/webgpu/wgpu"
)
// note: WriteBuffer is the preferred method for writing, so we only need to manage Read
// BufferMapAsyncError returns an error message if the status is not success.
func BufferMapAsyncError(status wgpu.MapAsyncStatus) error {
if status != wgpu.MapAsyncStatusSuccess {
return errors.New("gpu BufferMapAsync was not successful")
}
return nil
}
// BufferReadSync does a MapAsync on given buffer, waiting on the device
// until the sync is complete, and returning error if any issues.
func BufferReadSync(device *Device, size int, buffer *wgpu.Buffer) error {
var status wgpu.MapAsyncStatus
err := buffer.TryMapAsync(wgpu.MapModeRead, 0, uint64(size), func(s wgpu.MapAsyncStatus) {
status = s
})
if errors.Log(err) != nil {
return err
}
device.WaitDone()
return BufferMapAsyncError(status)
}
// ValueReadSync does a MapAsync on given Values, waiting on the device
// until the sync is complete, and returning error if any issues.
// It is more efficient to get all relevant buffers at the same time.
func ValueReadSync(device *Device, values ...*Value) error {
nv := len(values)
if nv == 0 {
return nil
}
var errs []error
status := make([]wgpu.MapAsyncStatus, nv)
for i, vl := range values {
err := vl.readBuffer.TryMapAsync(wgpu.MapModeRead, 0, uint64(vl.AllocSize), func(s wgpu.MapAsyncStatus) {
status[i] = s
})
if err != nil {
errs = append(errs, err)
}
}
device.WaitDone()
for _, s := range status {
err := BufferMapAsyncError(s)
if err != nil {
errs = append(errs, err)
}
}
return errors.Join(errs...)
}
// ValueGroups provides named lists of value groups that can be
// used to simplify the calling of the multiple Read functions
// needed to read data back from the GPU.
type ValueGroups map[string][]*Value
func (vg *ValueGroups) init() {
if *vg == nil {
*vg = make(map[string][]*Value)
}
}
// Add Adds named group of values
func (vg *ValueGroups) Add(name string, vals ...*Value) {
vg.init()
(*vg)[name] = vals
}
func (vg ValueGroups) ValuesByName(name string) ([]*Value, error) {
vls, ok := vg[name]
if !ok {
return nil, fmt.Errorf("gpu.ValueGroups: %q not found", name)
}
return vls, nil
}
// GPUToRead adds commands to given command encoder to read values
// from the GPU to its read buffer. Next step is ReadSync after
// command has been submitted (EndComputePass).
func (vg ValueGroups) GPUToRead(name string, cmd *wgpu.CommandEncoder) error {
vls, err := vg.ValuesByName(name)
if errors.Log(err) != nil {
return err
}
var errs []error
for _, vl := range vls {
err := vl.GPUToRead(cmd)
if err != nil {
errs = append(errs, err)
}
}
return errors.Log(errors.Join(errs...))
}
// ReadSync does a MapAsync on values.
func (vg ValueGroups) ReadSync(name string) error {
vls, err := vg.ValuesByName(name)
if errors.Log(err) != nil {
return err
}
if len(vls) == 0 {
return nil
}
dev := &vls[0].device
return ValueReadSync(dev, vls...)
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !(js && goscript)
package gpu
import "github.com/oliverbestmann/webgpu/wgpu"
// sliceToBytes returns the bytes of the given slice, sharing its memory.
func sliceToBytes[E any](src []E) []byte {
return wgpu.ToBytes(src)
}
// readToSlice copies the read buffer data of the given value
// directly into the memory of the given slice.
func readToSlice[E any](vl *Value, dest []E) error {
return vl.ReadToBytes(wgpu.ToBytes(dest))
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This tool prints out information about your available WebGPU devices.
package main
import (
"fmt"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/gpu"
"github.com/oliverbestmann/webgpu/wgpu"
)
func main() {
instance := wgpu.CreateInstance(nil)
gpus := instance.EnumerateAdapters(nil)
gp := gpu.NewGPU(nil)
gpIndex := gp.SelectGraphicsGPU(gpus)
props := gpus[gpIndex].GetInfo()
fmt.Println("Default WebGPU Adapter number:", gpIndex, " Type:", props.AdapterType.String(), " Backend:", props.BackendType.String())
fmt.Println("Set the GPU_DEVICE environment variable to an adapter number to select a different GPU")
for i, a := range gpus {
props := a.GetInfo()
fmt.Println("\n#####################################################################")
fmt.Println("WebGPU Adapter number:", i, " Type:", props.AdapterType.String(), " Backend:", props.BackendType.String())
fmt.Println(reflectx.StringJSON(props))
limits := a.GetLimits()
fmt.Println(reflectx.StringJSON(limits))
}
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gpu
import (
"fmt"
"math"
"runtime"
"sync"
"cogentcore.org/core/base/errors"
"github.com/oliverbestmann/webgpu/wgpu"
)
// ComputeSystem manages a system of ComputePipelines that all share
// a common collection of Vars and Values.
type ComputeSystem struct {
// optional name of this ComputeSystem
Name string
// vars represents all the data variables used by the system,
// with one Var for each resource that is made visible to the shader,
// indexed by Group (@group) and Binding (@binding).
// Each Var has Value(s) containing specific instance values.
// Access through the System.Vars() method.
vars Vars
// ComputePipelines by name.
ComputePipelines map[string]*ComputePipeline
// ComputeEncoder is the compute specific command encoder for the
// current [BeginComputePass], and released in [EndComputePass].
ComputeEncoder *wgpu.ComputePassEncoder
// CommandEncoder is the command encoder created in
// [BeginComputePass], and released in [EndComputePass].
CommandEncoder *wgpu.CommandEncoder
// logical device for this ComputeSystem, which we own.
device *Device
// gpu is our GPU device, which has properties
// and alignment factors.
gpu *GPU
}
// NewComputeSystem returns a new ComputeSystem, initialized with
// its own new device that is owned by the system.
func NewComputeSystem(gp *GPU, name string) *ComputeSystem {
sy := &ComputeSystem{}
sy.init(gp, name)
return sy
}
// System interface:
func (sy *ComputeSystem) Vars() *Vars { return &sy.vars }
func (sy *ComputeSystem) Device() *Device { return sy.device }
func (sy *ComputeSystem) GPU() *GPU { return sy.gpu }
func (sy *ComputeSystem) Render() *Render { return nil }
// init initializes the ComputeSystem
func (sy *ComputeSystem) init(gp *GPU, name string) {
sy.gpu = gp
sy.Name = name
sy.device = errors.Log1(NewComputeDevice(gp))
sy.vars.device = *sy.device
sy.vars.sys = sy
sy.ComputePipelines = make(map[string]*ComputePipeline)
}
// WaitDone waits until device is done with current processing steps
func (sy *ComputeSystem) WaitDone() {
sy.device.WaitDone()
}
func (sy *ComputeSystem) Release() {
sy.WaitDone()
for _, pl := range sy.ComputePipelines {
pl.Release()
}
sy.ComputePipelines = nil
sy.vars.Release()
sy.gpu = nil
}
// AddComputePipeline adds a new ComputePipeline to the system
func (sy *ComputeSystem) AddComputePipeline(name string) *ComputePipeline {
pl := NewComputePipeline(name, sy)
sy.ComputePipelines[pl.Name] = pl
return pl
}
// Config configures the entire system, after Pipelines and Vars
// have been initialized. After this point, just need to set
// values for the vars, and then do compute passes. This should
// not need to be called more than once.
func (sy *ComputeSystem) Config() {
sy.vars.Config(sy.device)
if Debug {
fmt.Printf("%s\n", sy.vars.StringDoc())
}
for _, pl := range sy.ComputePipelines {
pl.Config(true)
}
}
// NewCommandEncoder returns a new CommandEncoder for encoding
// compute commands. This is automatically called by
// BeginRenderPass and the result maintained in [CommandEncoder].
func (sy *ComputeSystem) NewCommandEncoder() (*wgpu.CommandEncoder, error) {
cmd, err := sy.device.Device.TryCreateCommandEncoder(nil)
if errors.Log(err) != nil {
return nil, err
}
return cmd, nil
}
// BeginComputePass adds commands to the given command buffer
// to start the compute pass, returning the encoder object
// to which further compute commands should be added.
// Call [EndComputePass] when done.
// If an existing [ComputeSystem.ComputeEncoder] is already set from
// a prior BeginComputePass call, then that is returned, so this
// is safe and efficient to call for every compute shader dispatch,
// where the first call will create and the rest add to the ongoing job.
func (sy *ComputeSystem) BeginComputePass() (*wgpu.ComputePassEncoder, error) {
if sy.ComputeEncoder != nil {
return sy.ComputeEncoder, nil
}
cmd, err := sy.NewCommandEncoder()
if errors.Log(err) != nil {
return nil, err
}
sy.CommandEncoder = cmd
sy.ComputeEncoder = cmd.BeginComputePass(nil) // optional name in the encoder
return sy.ComputeEncoder, nil
}
// EndComputePass submits the current compute commands to the device
// Queue and releases the [ComputeSystem.CommandEncoder] and
// [ComputeSystem.ComputeEncoder]. You must call ce.End prior to calling this.
// Can insert other commands after ce.End, e.g., to copy data back
// from the GPU, prior to calling EndComputePass.
func (sy *ComputeSystem) EndComputePass() error {
ce := sy.ComputeEncoder
cmd := sy.CommandEncoder
sy.ComputeEncoder = nil
sy.CommandEncoder = nil
ce.Release() // must happen before Finish
cmdBuffer, err := cmd.TryFinish(nil)
if errors.Log(err) != nil {
return err
}
sy.device.Queue.Submit(cmdBuffer)
cmdBuffer.Release()
cmd.Release()
for _, pl := range sy.ComputePipelines {
pl.releaseOldBindGroups()
}
return nil
}
// NumThreads is the number of threads to use for parallel threading,
// in the [VectorizeFunc] that is used for CPU versions of GPU functions.
// The default of 0 causes the [runtime.GOMAXPROCS] to be used.
var NumThreads = 0
// DefaultNumThreads returns the default number of threads to use:
// NumThreads if non-zero, otherwise [runtime.GOMAXPROCS].
func DefaultNumThreads() int {
if NumThreads > 0 {
return NumThreads
}
return runtime.GOMAXPROCS(0)
}
// VectorizeFunc runs given GPU kernel function taking a uint32 index
// on the CPU, using given number of threads with goroutines, for n iterations.
// If threads is 0, then GOMAXPROCS is used.
func VectorizeFunc(threads, n int, fun func(idx uint32)) {
if threads == 0 {
threads = DefaultNumThreads()
}
if threads <= 1 {
for idx := range n {
fun(uint32(idx))
}
return
}
nper := int(math.Ceil(float64(n) / float64(threads)))
wait := sync.WaitGroup{}
for start := 0; start < n; start += nper {
end := min(start+nper, n)
wait.Go(func() {
for idx := start; idx < end; idx++ {
fun(uint32(idx))
}
})
}
wait.Wait()
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gpu
import (
"io/fs"
"math"
"path"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/fsx"
"github.com/oliverbestmann/webgpu/wgpu"
)
// ComputePipeline is a compute pipeline, which runs shader code on vars data.
type ComputePipeline struct {
Pipeline
// VarsUsed is a list of variables actually used by this pipeline.
// If non-empty, only these variables are registered for this pipeline.
// This is necessary for larger compute systems with more than the
// 8 maxStorageBuffersPerShaderStage default limit of variables, which is
// actually 10 on chrome, and will be raised to 16 at some point:
// https://github.com/gpuweb/gpuweb/issues/4235
// The lab/gosl system automatically sets these for you based on what
// the shader actually uses.
VarsUsed []*Var
// computePipeline is the configured, instantiated wgpu pipeline
computePipeline *wgpu.ComputePipeline
}
// NewComputePipeline returns a new ComputePipeline.
func NewComputePipeline(name string, sy System) *ComputePipeline {
pl := &ComputePipeline{}
pl.Name = name
pl.System = sy
return pl
}
// NewComputePipelineShaderFS returns a new ComputePipeline,
// opening the given shader code file from given filesystem,
// and setting the name of the pipeline to the filename
// (without paths or extensions). The shader entry point is "main".
// This is a convenience method for standard case where there is
// one shader program per pipeline.
func NewComputePipelineShaderFS(fsys fs.FS, fname string, sy *ComputeSystem) *ComputePipeline {
name, _ := fsx.ExtSplit(path.Base(fname))
pl := &ComputePipeline{}
pl.Name = name
pl.System = sy
sh := pl.AddShader(name)
errors.Log(sh.OpenFileFS(fsys, fname))
pl.AddEntry(sh, ComputeShader, "main")
sy.ComputePipelines[pl.Name] = pl
return pl
}
// AddVarUsed adds given variable name in given group as a variable used
// by this compute pipeline.
func (pl *ComputePipeline) AddVarUsed(group int, varName string) {
vr := errors.Log1(pl.System.Vars().VarByName(group, varName))
if vr != nil {
pl.VarsUsed = append(pl.VarsUsed, vr)
}
}
// Dispatch adds commands to given compute encoder to run this
// pipeline for given number of *warps* (work groups of compute threads)
// along 3 dimensions, which then generate indexes passed into the shader.
// Calls BindPipeline and then DispatchWorkgroups.
// In WGSL, the @workgroup_size(x, y, z) directive specifies the number
// of threads allocated per warp -- the actual number of elements
// processed is threads * warps per each dimension. See Warps function.
// The hardware typically has 32 (NVIDIA, M1, M2) or 64 (AMD) hardware
// threads per warp, and so 64 is typically used as a default sum of
// threads per warp across all of the dimensions.
// Can use subsets of dimensions by using 1 for the other dimensions,
// and see [Dispatch1D] for a convenience method that automatically
// computes the number of warps for a 1D compute shader (everthing in x).
func (pl *ComputePipeline) Dispatch(ce *wgpu.ComputePassEncoder, nx, ny, nz int) error {
err := pl.BindPipeline(ce)
if err != nil {
return err
}
ce.DispatchWorkgroups(uint32(nx), uint32(ny), uint32(nz))
return nil
}
// Dispatch1D adds commands to given compute encoder to run this
// pipeline for given number of computational elements along the first
// (X) dimension, for given number *elements* (threads) per warp (typically 64).
// See [Dispatch] for full info.
// This is just a convenience method for common 1D case that calls
// the NumWorkgroups1D function with threads for you.
func (pl *ComputePipeline) Dispatch1D(ce *wgpu.ComputePassEncoder, n, threads int) error {
nx, ny := NumWorkgroups1D(n, threads)
return pl.Dispatch(ce, nx, ny, 1)
}
// MaxWorkgroupsPerDimension is the maximum number of work groups per
// dimension of a dispatch, which is the default limit of WebGPU
// (maxComputeWorkgroupsPerDimension), and that of many adapters,
// as the software GPU of the CI (lavapipe).
const MaxWorkgroupsPerDimension = 65535
// NumWorkgroups1D returns the number of work groups of compute threads
// that is sufficient to compute n total elements, given specified number
// of threads in the x dimension, subject to constraint that no more than
// [MaxWorkgroupsPerDimension] work groups can be deployed per dimension.
func NumWorkgroups1D(n, threads int) (nx, ny int) {
mxn := MaxWorkgroupsPerDimension
ny = 1
nx = int(math.Ceil(float64(n) / float64(threads)))
if nx <= mxn {
return
}
xsz := mxn * threads
ny = int(math.Ceil(float64(n) / float64(xsz)))
nx = int(math.Ceil(float64(n) / float64(ny*threads)))
return
}
// NumWorkgroups2D returns the number of work groups of compute threads
// that is sufficient to compute n total elements, given specified number
// of threads per x, y dimension, subject to constraint that no more than
// [MaxWorkgroupsPerDimension] work groups can be deployed per dimension.
func NumWorkgroups2D(n, x, y int) (nx, ny int) {
mxn := MaxWorkgroupsPerDimension
sz := x * y
ny = 1
nx = int(math.Ceil(float64(n) / float64(sz)))
if nx <= mxn {
return
}
xsz := mxn * x // size of full x chunk
ny = int(math.Ceil(float64(n) / float64(xsz*y)))
nx = int(math.Ceil(float64(n) / float64(x*ny*y)))
return
}
// BindAllGroups binds the Current Value for all variables across all
// variable groups, as the Value to use by shader.
// Automatically called in BindPipeline at start of render for pipeline.
// Be sure to set Current index to correct value before calling!
func (pl *ComputePipeline) BindAllGroups(ce *wgpu.ComputePassEncoder) {
vs := pl.Vars()
ngp := vs.NGroups()
for gi := range ngp {
pl.BindGroup(ce, gi)
}
}
// BindGroup binds the Current Value for all variables in given
// variable group, as the Value to use by shader.
// Be sure to set Current index to correct value before calling!
func (pl *ComputePipeline) BindGroup(ce *wgpu.ComputePassEncoder, group int) {
vg := pl.Vars().Groups[group]
bg, dynOffs, err := pl.bindGroup(vg, pl.VarsUsed...)
if err == nil {
ce.SetBindGroup(uint32(vg.Group), bg, dynOffs)
}
}
// BindPipeline binds this pipeline as the one to use for next commands in
// the given compute pass.
// This also calls BindAllGroups, to bind the Current Value for all variables.
// Be sure to set the desired Current value prior to calling.
func (pl *ComputePipeline) BindPipeline(ce *wgpu.ComputePassEncoder) error {
if pl.computePipeline == nil {
err := pl.Config(false)
if errors.Log(err) != nil {
return err
}
}
ce.SetPipeline(pl.computePipeline)
pl.BindAllGroups(ce)
return nil
}
// Config is called once all the Config options have been set
// using Set* methods, and the shaders have been loaded.
// The parent ComputeSystem has already done what it can for its config.
// The rebuild flag indicates whether pipelines should rebuild
func (pl *ComputePipeline) Config(rebuild bool) error {
if pl.computePipeline != nil {
if !rebuild {
return nil
}
pl.releasePipeline() // starting over: note: requires keeping shaders around
}
play, err := pl.bindLayout(pl.VarsUsed...)
if errors.Log(err) != nil {
return err
}
defer play.Release()
sh := pl.EntryByType(ComputeShader)
cp, err := pl.System.Device().Device.TryCreateComputePipeline(&wgpu.ComputePipelineDescriptor{
Layout: play,
Compute: wgpu.ProgrammableStageDescriptor{
Module: sh.Shader.module,
EntryPoint: sh.Entry,
},
})
if errors.Log(err) != nil {
return err
}
pl.computePipeline = cp
return nil
}
func (pl *ComputePipeline) Release() {
pl.releaseShaders()
pl.releasePipeline()
}
func (pl *ComputePipeline) releasePipeline() {
if pl.computePipeline != nil {
pl.computePipeline.Release()
pl.computePipeline = nil
}
}
// Copyright (c) 2022, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gpu
import (
"fmt"
"cogentcore.org/core/base/errors"
"github.com/oliverbestmann/webgpu/wgpu"
)
// Device holds Device and associated Queue info.
// A Device is a usable instance of the GPU Adapter hardware.
// Each device has one Queue.
type Device struct {
// logical device
Device *wgpu.Device
// queue for device
Queue *wgpu.Queue
}
// NewDevice returns a new device for given GPU.
// It gets the Queue for this device.
func NewDevice(gpu *GPU) (*Device, error) {
wdev, err := gpu.GPU.RequestDevice(nil)
if errors.Log(err) != nil {
return nil, err
}
dev := &Device{Device: wdev}
dev.Queue = wdev.GetQueue()
return dev, nil
}
// NewComputeDevice returns a new device for given GPU,
// for compute functionality, which requests maximum buffer sizes.
// It gets the Queue for this device.
func NewComputeDevice(gpu *GPU) (*Device, error) {
// we only request max buffer sizes so compute can go as big as it needs to
limits := wgpu.DefaultLimits()
// Per https://github.com/cogentcore/core/issues/1362 -- this may cause issues on "downlevel"
// hardware, so we may need to detect that. OTOH it probably won't be useful for compute anyway,
// but we can just sort that out later
// note: on web / chromium / dawn, limited to 10: https://issues.chromium.org/issues/366151398?pli=1
limits.MaxStorageBuffersPerShaderStage = gpu.Limits.MaxStorageBuffersPerShaderStage
// fmt.Println("MaxStorageBuffersPerShaderStage:", gpu.Limits.MaxStorageBuffersPerShaderStage)
// note: these limits are being processed and allow the MaxBufferSize to be the
// controlling factor -- if we don't set these, then the slrand example doesn't
// work above a smaller limit.
// TODO: converting these limits to int may cause issues on 32-bit systems
limits.MaxUniformBufferBindingSize = uint64(MemSizeAlignDown(int(gpu.Limits.MaxUniformBufferBindingSize), int(gpu.Limits.MinUniformBufferOffsetAlignment)))
limits.MaxStorageBufferBindingSize = uint64(MemSizeAlignDown(int(gpu.Limits.MaxStorageBufferBindingSize), int(gpu.Limits.MinStorageBufferOffsetAlignment)))
// note: this limit is not working properly:
g4 := uint64(0xFFFFFF00)
limits.MaxBufferSize = uint64(MemSizeAlignDown(int(min(gpu.Limits.MaxBufferSize, g4)), int(gpu.Limits.MinStorageBufferOffsetAlignment)))
if limits.MaxBufferSize == 0 {
limits.MaxBufferSize = g4
}
// limits.MaxBindGroups = gpu.Limits.MaxBindGroups // note: no point in changing -- web constraint
if Debug {
fmt.Printf("Requesting sizes: MaxStorageBufferBindingSize: %X MaxBufferSize: %X\n", limits.MaxStorageBufferBindingSize, limits.MaxBufferSize)
}
desc := wgpu.DeviceDescriptor{
RequiredLimits: &limits,
}
wdev, err := gpu.GPU.RequestDevice(&desc)
if errors.Log(err) != nil {
return nil, err
}
dev := &Device{Device: wdev}
dev.Queue = wdev.GetQueue()
return dev, nil
}
func (dv *Device) Release() {
if dv.Device == nil {
return
}
dv.Queue.OnSubmittedWorkDone(func(wgpu.QueueWorkDoneStatus) {
dv.Device.Release()
dv.Device = nil
dv.Queue = nil
})
}
// WaitDoneFunc waits until the device is idle and then calls
// given function, if the device is ready. If it is in some other
// bad state, that generates a panic.
func (dv *Device) WaitDoneFunc(fun func()) {
dv.Queue.OnSubmittedWorkDone(func(stat wgpu.QueueWorkDoneStatus) {
if stat == wgpu.QueueWorkDoneStatusSuccess {
fun()
return
}
panic("Device.WaitDoneFunc: bad queue status: " + stat.String())
})
}
// WaitDone does a blocking wait until the device is done with current work.
func (dv *Device) WaitDone() {
if dv.Device == nil {
return
}
dv.Device.Poll(true, nil)
}
// Copyright 2024 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package drawmatrix provides the matrices for drawing images at given
// positions and sizes with the GPU drawer.
package drawmatrix
import (
"image"
"cogentcore.org/core/math32"
)
// Matrix holds the projection matricies.
type Matrix struct {
// MVP is the vertex projection matrix,
// for positioning the vertex points
MVP math32.Matrix4
// UVP is the U,V texture coordinate projection matrix
// for positioning the texture. For fill mode, the
// last column holds the fill color.
UVP math32.Matrix4
}
// Config configures the draw matrix for given draw parameters:
// xform is the transform mapping source to destination
// coordinates (translation, scaling), txsz is the size of the texture to draw,
// sr is the source region (set to tex.Format.Bounds() for all)
// flipY inverts the Y axis of the source image.
func Config(destSz image.Point, xform math32.Matrix3, txsz image.Point, sr image.Rectangle, flipY math32.YFlip) *Matrix {
var tmat Matrix
sr = sr.Intersect(image.Rectangle{Max: txsz})
if sr.Empty() {
tmat.MVP.SetIdentity()
tmat.UVP.SetIdentity()
return &tmat
}
// Start with src-space left, top, right and bottom.
srcL := float32(sr.Min.X)
srcT := float32(sr.Min.Y)
srcR := float32(sr.Max.X)
srcB := float32(sr.Max.Y)
// Transform to dst-space via the xform matrix, then to a MVP matrix.
matMVP := calcMVP(destSz.X, destSz.Y,
xform[0]*srcL+xform[3]*srcT+xform[6],
xform[1]*srcL+xform[4]*srcT+xform[7],
xform[0]*srcR+xform[3]*srcT+xform[6],
xform[1]*srcR+xform[4]*srcT+xform[7],
xform[0]*srcL+xform[3]*srcB+xform[6],
xform[1]*srcL+xform[4]*srcB+xform[7],
)
tmat.MVP.SetFromMatrix3(&matMVP) // todo render direct
// OpenGL's fragment shaders' UV coordinates run from (0,0)-(1,1),
// unlike vertex shaders' XY coordinates running from (-1,+1)-(+1,-1).
//
// We are drawing a rectangle PQRS, defined by two of its
// corners, onto the entire texture. The two quads may actually
// be equal, but in the general case, PQRS can be smaller.
//
// (0,0) +---------------+ (1,0)
// | P +-----+ Q |
// | | | |
// | S +-----+ R |
// (0,1) +---------------+ (1,1)
//
// The PQRS quad is always axis-aligned. First of all, convert
// from pixel space to texture space.
tw := float32(txsz.X)
th := float32(txsz.Y)
px := float32(sr.Min.X-0) / tw
py := float32(sr.Min.Y-0) / th
qx := float32(sr.Max.X-0) / tw
sy := float32(sr.Max.Y-0) / th
// Due to axis alignment, qy = py and sx = px.
//
// The simultaneous equations are:
// 0 + 0 + a02 = px
// 0 + 0 + a12 = py
// a00 + 0 + a02 = qx
// a10 + 0 + a12 = qy = py
// 0 + a01 + a02 = sx = px
// 0 + a11 + a12 = sy
if !flipY { // note: reversed from openGL for vulkan
tmat.UVP.SetFromMatrix3(&math32.Matrix3{
qx - px, 0, 0,
0, sy - py, 0, // sy - py
px, py, 1})
} else {
tmat.UVP.SetFromMatrix3(&math32.Matrix3{
qx - px, 0, 0,
0, py - sy, 0, // py - sy
px, sy, 1})
}
return &tmat
}
// calcMVP returns the Model View Projection matrix that maps the quadCoords
// unit square, (0, 0) to (1, 1), to a quad QV, such that QV in vertex shader
// space corresponds to the quad QP in pixel space, where QP is defined by
// three of its four corners - the arguments to this function. The three
// corners are nominally the top-left, top-right and bottom-left, but there is
// no constraint that e.g. tlx < trx.
//
// In pixel space, the window ranges from (0, 0) to (widthPx, heightPx). The
// Y-axis points downwards (unless flipped).
//
// In vertex shader space, the window ranges from (-1, +1) to (+1, -1), which
// is a 2-unit by 2-unit square. The Y-axis points upwards.
func calcMVP(widthPx, heightPx int, tlx, tly, trx, try, blx, bly float32) math32.Matrix3 {
// Convert from pixel coords to vertex shader coords.
invHalfWidth := 2 / float32(widthPx)
invHalfHeight := 2 / float32(heightPx)
tlx = tlx*invHalfWidth - 1
tly = 1 - tly*invHalfHeight // 1 - min
trx = trx*invHalfWidth - 1
try = 1 - try*invHalfHeight // 1 - min
blx = blx*invHalfWidth - 1
bly = 1 - bly*invHalfHeight // 1 - (min + max)
// The resultant affine matrix:
// - maps (0, 0) to (tlx, tly).
// - maps (1, 0) to (trx, try).
// - maps (0, 1) to (blx, bly).
return math32.Matrix3{
trx - tlx, try - tly, 0,
blx - tlx, bly - tly, 0,
tlx, tly, 1,
}
}
// Transform returns a transformation matrix for the
// generic Draw function that scales, translates, and rotates
// the source image by the given degrees, to make it fit within
// the destination rectangle dr, given its original size sr (unrotated).
// To avoid scaling, ensure that the dr and sr are the same
// dimensions (post rotation).
// rotDeg = rotation degrees to apply in the mapping:
// 90 = left, -90 = right, 180 = invert.
func Transform(dr image.Rectangle, sr image.Rectangle, rotDeg float32) math32.Matrix3 {
sx := float32(dr.Dx()) / float32(sr.Dx())
sy := float32(dr.Dy()) / float32(sr.Dy())
tx := float32(dr.Min.X) - sx*float32(sr.Min.X)
ty := float32(dr.Min.Y) - sy*float32(sr.Min.Y)
if rotDeg == 0 {
return math32.Matrix3{
sx, 0, 0,
0, sy, 0,
tx, ty, 1,
}
}
rad := math32.DegToRad(rotDeg)
dsz := math32.FromPoint(dr.Size())
rmat := math32.Rotate2D(rad)
dmnr := rmat.MulPoint(math32.FromPoint(dr.Min))
dmxr := rmat.MulPoint(math32.FromPoint(dr.Max))
sx = math32.Abs(dmxr.X-dmnr.X) / float32(sr.Dx())
sy = math32.Abs(dmxr.Y-dmnr.Y) / float32(sr.Dy())
tx = dmnr.X - sx*float32(sr.Min.X)
ty = dmnr.Y - sy*float32(sr.Min.Y)
if rotDeg < -45 && rotDeg > -135 {
ty -= dsz.X
} else if rotDeg > 45 && rotDeg < 135 {
tx -= dsz.Y
} else if rotDeg > 135 || rotDeg < -135 {
ty -= dsz.Y
tx -= dsz.X
}
mat := math32.Matrix3{
sx, 0, 0,
0, sy, 0,
tx, ty, 1,
}
// mat maps the source into the *rotated* destination frame, because
// the scale and translation above are derived from the destination
// corners after rotating them forward by rmat. So the inverse
// rotation is what brings it back into destination coordinates.
// rmat is a pure rotation, so its transpose is its inverse.
return math32.Matrix3FromMatrix2(rmat.Transpose()).Mul(mat)
/* stuff that didn't work, but theoretically should?
rad := math32.DegToRad(rotDeg)
dsz := math32.FromPoint(dr.Size())
dctr := dsz.MulScalar(0.5)
_ = dctr
// mat2 := math32.Translate2D(dctr.X, 0).Mul(math32.Rotate2D(rad)).Mul(math32.Translate2D(tx, ty)).Mul(math32.Scale2D(sx, sy))
mat2 := math32.Translate2D(tx, ty).Mul(math32.Scale2D(sx, sy)).Mul(math32.Translate2D(dctr.X, 0)).Mul(math32.Rotate2D(rad))
// mat2 := math32.Rotate2D(rad).MulCtr(math32.Translate2D(tx, ty).Mul(math32.Scale2D(sx, sy)), dctr)
mat := math32.Matrix3FromMatrix2(mat2)
*/
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"embed"
"fmt"
"math/rand"
"runtime"
"unsafe"
"cogentcore.org/core/base/timer"
"cogentcore.org/core/gpu"
"cogentcore.org/core/math32"
// "cogentcore.org/core/system/driver/web/jsfs"
)
//go:embed squares.wgsl
var shaders embed.FS
func init() {
// must lock main thread for gpu!
runtime.LockOSThread()
}
type Data struct {
A float32
B float32
C float32
D float32
}
func main() {
// errors.Log1(jsfs.Config(js.Global().Get("fs"))) // needed for printing etc to work
// time.Sleep(1 * time.Second)
// b := core.NewBody()
// bt := core.NewButton(b).SetText("Run Compute")
// bt.OnClick(func(e events.Event) {
n := 16_000_000 // near max capacity on Mac M*
// n := 200_000 // should fit in any webgpu
nerr := compute(n)
fmt.Printf("compute: n: %d errors: %d\n", n, nerr)
// })
// b.RunMainWindow()
// select {}
}
// compute runs the squares.wgsl compute shader on n items,
// returning the number of items that do not match the CPU result.
func compute(n int) int {
// gpu.SetDebug(true)
gp := gpu.NewComputeGPU()
fmt.Printf("Running on GPU: %s\n", gp.DeviceName)
// gp.PropertiesString(true) // print
sy := gpu.NewComputeSystem(gp, "compute")
pl := gpu.NewComputePipelineShaderFS(shaders, "squares.wgsl", sy)
vars := sy.Vars()
sgp := vars.AddGroup(gpu.Storage)
threads := 64
nx, ny := gpu.NumWorkgroups1D(n, threads)
fmt.Printf("workgroup sizes: %d, %d storage mem bytes: %X\n", nx, ny, n*int(unsafe.Sizeof(Data{})))
dv := sgp.AddStruct("Data", int(unsafe.Sizeof(Data{})), n, gpu.ComputeShader)
sgp.SetNValues(1)
sy.Config()
dvl := dv.Values.Values[0]
fillTmr := timer.Time{}
fillTmr.Start()
sd := make([]Data, n)
for i := range sd {
sd[i].A = rand.Float32()
sd[i].B = rand.Float32()
}
fillTmr.Stop()
upTmr := timer.Time{}
upTmr.Start()
gpu.SetValueFrom(dvl, sd)
upTmr.Stop()
in := make([]Data, n) // save inputs to check results
copy(in, sd)
gpuTmr := timer.Time{}
cpyTmr := timer.Time{}
readTmr := timer.Time{}
gpuTmr.Start()
nItr := 1
for range nItr {
ce, _ := sy.BeginComputePass()
pl.Dispatch1D(ce, n, threads)
ce.End()
dvl.GPUToRead(sy.CommandEncoder)
sy.EndComputePass()
cpyTmr.Start()
dvl.ReadSync()
cpyTmr.Stop()
readTmr.Start()
gpu.ReadToBytes(dvl, sd)
readTmr.Stop()
}
gpuTmr.Stop()
mx := min(n, 10)
for i := range mx {
tc := sd[i].A + sd[i].B
td := tc * tc
dc := sd[i].C - tc
dd := sd[i].D - td
fmt.Printf("%d\t A: %g\t B: %g\t C: %g\t trg: %g\t D: %g \t trg: %g \t difC: %g \t difD: %g\n", i, sd[i].A, sd[i].B, sd[i].C, tc, sd[i].D, td, dc, dd)
}
fmt.Printf("\n")
fmt.Println("fill:", fillTmr.Total, "total:", gpuTmr.Total, "copy:", cpyTmr.Total, "upload:", upTmr.Total, "read into slice:", readTmr.Total)
nerr := 0
for i := range sd {
tc := in[i].A + in[i].B
td := tc * tc
if sd[i].A != in[i].A || sd[i].B != in[i].B || math32.Abs(sd[i].C-tc) > 1.0e-6 || math32.Abs(sd[i].D-td) > 1.0e-5 {
nerr++
}
}
sy.Release()
gp.Release()
return nerr
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
_ "embed"
"fmt"
"image"
"image/color"
"runtime"
"time"
"unsafe"
"cogentcore.org/core/gpu"
"cogentcore.org/core/math32"
"github.com/oliverbestmann/webgpu/wgpu"
)
//go:embed indexed.wgsl
var indexed string
func init() {
// must lock main thread for gpu!
runtime.LockOSThread()
}
type CamView struct {
Model math32.Matrix4
View math32.Matrix4
Projection math32.Matrix4
}
func main() {
var resize func(size image.Point)
size := image.Point{1024, 768}
sp, terminate, pollEvents, size, err := gpu.GLFWCreateWindow(size, "Draw Triangle Indexed", &resize)
if err != nil {
return
}
gp := gpu.NewGPU(sp)
sf := gpu.NewSurface(gp, sp, size, 1, gpu.UndefinedType)
sy := gpu.NewGraphicsSystem(gp, "drawidx", sf)
fmt.Printf("format: %s\n", sf.Format.String())
resize = func(size image.Point) { sf.SetSize(size) }
destroy := func() {
sy.Release()
sf.Release()
gp.Release()
terminate()
}
pl := sy.AddGraphicsPipeline("drawidx")
pl.SetCullMode(wgpu.CullModeNone)
sy.SetClearColor(color.RGBA{50, 50, 50, 255})
sh := pl.AddShader("indexed")
sh.OpenCode(indexed)
pl.AddEntry(sh, gpu.VertexShader, "vs_main")
pl.AddEntry(sh, gpu.FragmentShader, "fs_main")
vgp := sy.Vars().AddVertexGroup()
ugp := sy.Vars().AddGroup(gpu.Uniform)
// vertex are dynamically sized in general, so using 0 here
posv := vgp.Add("Pos", gpu.Float32Vector3, 0, gpu.VertexShader)
clrv := vgp.Add("Color", gpu.Float32Vector3, 0, gpu.VertexShader)
// note: index goes last usually
idxv := vgp.Add("Index", gpu.Uint16, 0, gpu.VertexShader)
idxv.Role = gpu.Index
camv := ugp.AddStruct("Camera", int(unsafe.Sizeof(CamView{})), 1, gpu.VertexShader)
vgp.SetNValues(1)
ugp.SetNValues(1)
sy.Config()
triPos := posv.Values.Values[0]
gpu.SetValueFrom(triPos, []float32{
-0.5, 0.5, 0.0,
0.5, 0.5, 0.0,
0.0, -0.5, 0.0}) // negative point is UP in native Vulkan
triClr := clrv.Values.Values[0]
gpu.SetValueFrom(triClr, []float32{
1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0})
triIndex := idxv.Values.Values[0]
gpu.SetValueFrom(triIndex, []uint16{0, 1, 2})
// note: the only way to set indexes is at start..
// This is the standard camera view projection computation
cam := camv.Values.Values[0]
campos := math32.Vec3(0, 0, 2)
target := math32.Vec3(0, 0, 0)
var lookq math32.Quat
lookq.SetFromRotationMatrix(math32.NewLookAt(campos, target, math32.Vec3(0, 1, 0)))
scale := math32.Vec3(1, 1, 1)
var cview math32.Matrix4
cview.SetTransform(campos, lookq, scale)
view, _ := cview.Inverse()
var camo CamView
camo.Model.SetIdentity()
camo.View.CopyFrom(view)
aspect := float32(sf.Format.Size.X) / float32(sf.Format.Size.Y)
fmt.Printf("aspect: %g\n", aspect)
camo.Projection.SetPerspective(45, aspect, 0.01, 100)
gpu.SetValueFrom(cam, []CamView{camo}) // note: always use slice to copy
frameCount := 0
stTime := time.Now()
renderFrame := func() {
// fmt.Printf("frame: %d\n", frameCount)
// rt := time.Now()
camo.Model.SetRotationY(.1 * float32(frameCount))
gpu.SetValueFrom(cam, []CamView{camo})
rp, err := sy.BeginRenderPass()
if err != nil {
return
}
pl.BindPipeline(rp)
pl.BindDrawIndexed(rp)
rp.End()
sy.EndRenderPass(rp)
frameCount++
eTime := time.Now()
dur := float64(eTime.Sub(stTime)) / float64(time.Second)
if dur > 10 {
fps := float64(frameCount) / dur
fmt.Printf("fps: %.0f\n", fps)
frameCount = 0
stTime = eTime
}
}
exitC := make(chan struct{}, 2)
fpsDelay := time.Second / 60
fpsTicker := time.NewTicker(fpsDelay)
for {
select {
case <-exitC:
fpsTicker.Stop()
destroy()
return
case <-fpsTicker.C:
if !pollEvents() {
exitC <- struct{}{}
continue
}
renderFrame()
}
}
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
_ "embed"
"fmt"
"image"
"os"
"runtime"
"time"
"cogentcore.org/core/gpu"
)
//go:embed trianglelit.wgsl
var trianglelit string
func init() {
// must lock main thread for gpu!
runtime.LockOSThread()
gpu.Debug = true
os.Setenv("RUST_BACKTRACE", "full")
}
func main() {
var resize func(size image.Point)
size := image.Point{1024, 768}
sp, terminate, pollEvents, size, err := gpu.GLFWCreateWindow(size, "Draw Triangle", &resize)
if err != nil {
return
}
gp := gpu.NewGPU(sp)
sf := gpu.NewSurface(gp, sp, size, 1, gpu.UndefinedType)
sy := gpu.NewGraphicsSystem(gp, "drawtri", sf)
fmt.Printf("format: %s\n", sf.Format.String())
resize = func(size image.Point) { sf.SetSize(size) }
destroy := func() {
sy.Release()
sf.Release()
gp.Release()
terminate()
}
pl := sy.AddGraphicsPipeline("drawtri")
// pl.SetFrontFace(wgpu.FrontFaceCCW)
// pl.SetCullMode(wgpu.CullModeNone)
// pl.SetAlphaBlend(false)
sh := pl.AddShader("trianglelit")
sh.OpenCode(trianglelit)
pl.AddEntry(sh, gpu.VertexShader, "vs_main")
pl.AddEntry(sh, gpu.FragmentShader, "fs_main")
sy.Config()
// no vars..
frameCount := 0
stTime := time.Now()
renderFrame := func() {
// fmt.Printf("frame: %d\n", frameCount)
// rt := time.Now()
rp, err := sy.BeginRenderPass()
if err != nil { // error here is fatal
panic(err)
}
if rp == nil { // nil indicates need to reconfig
sf.Reconfig()
return
}
pl.BindPipeline(rp)
rp.Draw(3, 1, 0, 0)
rp.End()
sy.EndRenderPass(rp)
frameCount++
eTime := time.Now()
dur := float64(eTime.Sub(stTime)) / float64(time.Second)
if dur > 10 {
fps := float64(frameCount) / dur
fmt.Printf("fps: %.0f\n", fps)
frameCount = 0
stTime = eTime
}
}
exitC := make(chan struct{}, 2)
fpsDelay := time.Second / 6
fpsTicker := time.NewTicker(fpsDelay)
for {
select {
case <-exitC:
fpsTicker.Stop()
destroy()
return
case <-fpsTicker.C:
if !pollEvents() {
exitC <- struct{}{}
continue
}
renderFrame()
}
}
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"runtime"
"time"
"math/rand/v2"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/iox/imagex"
"cogentcore.org/core/gpu"
"cogentcore.org/core/gpu/examples/images"
"cogentcore.org/core/gpu/gpudraw"
)
func init() {
// must lock main thread for gpu!
runtime.LockOSThread()
}
func main() {
var resize func(size image.Point)
size := image.Point{1024, 768}
sp, terminate, pollEvents, size, err := gpu.GLFWCreateWindow(size, "GPU Draw", &resize)
if err != nil {
return
}
gp := gpu.NewGPU(sp)
sf := gpu.NewSurface(gp, sp, size, 1, gpu.UndefinedType) // note: 1, no depth for draw
drw := gpudraw.NewDrawer(gp, sf)
fmt.Printf("format: %s\n", sf.Format.String())
resize = func(size image.Point) { sf.SetSize(size) }
destroy := func() {
drw.Release()
sf.Release()
gp.Release()
terminate()
}
imgFiles := []string{"ground.png", "wood.png", "teximg.jpg"}
imgs := make([]image.Image, len(imgFiles))
for i, fnm := range imgFiles {
imgs[i], _, err = imagex.OpenFS(images.Images, fnm)
if err != nil {
errors.Log(err)
}
}
// icons loaded into a texture array
iconFiles := []string{"sound1.png", "text.png", "up.png", "world1.png"}
iconImgs := make([]image.Image, len(iconFiles))
for i, fnm := range iconFiles {
iconImgs[i], _, _ = imagex.OpenFS(images.Images, fnm)
}
rendImgs := func(idx int) {
drw.Start()
drw.Scale(image.Rectangle{}, imgs[idx], image.Rectangle{}, 0, gpudraw.Src, gpudraw.Unchanged)
for i := range imgFiles {
// dp := image.Point{rand.Intn(500), rand.Intn(500)}
dp := image.Point{i * 50, i * 50}
drw.Copy(dp, imgs[i], image.Rectangle{}, gpudraw.Src, gpudraw.Unchanged)
}
for i := range iconFiles {
dp := image.Point{rand.IntN(500), rand.IntN(500)}
drw.Copy(dp, iconImgs[i], image.Rectangle{}, gpudraw.Over, gpudraw.Unchanged)
}
drw.End()
}
_ = rendImgs
red := color.RGBA{128, 0, 0, 128}
green := color.RGBA{0, 128, 0, 128}
blue := color.RGBA{0, 0, 255, 255}
colors := []color.Color{color.White, color.Black, red, green, blue}
rendFill := func() {
nclr := len(colors)
drw.Start()
for i := range 5 {
// sp := image.Point{rand.Intn(500), rand.Intn(500)}
// sz := image.Point{rand.Intn(500), rand.Intn(500)}
sp := image.Point{i * 30, i * 40}
sz := image.Point{(i + 1) * 20, (i + 1) * 20}
sr := image.Rectangle{Min: sp, Max: sp.Add(sz)}
drw.Fill(colors[i%nclr], sr, draw.Over)
}
drw.End()
}
_ = rendFill
frameCount := 0
stTime := time.Now()
renderFrame := func() {
fcr := frameCount % 4
_ = fcr
switch {
case fcr < 3:
rendImgs(fcr)
default:
rendFill()
}
frameCount++
eTime := time.Now()
dur := float64(eTime.Sub(stTime)) / float64(time.Second)
if dur > 100 {
fps := float64(frameCount) / dur
fmt.Printf("fps: %.0f\n", fps)
frameCount = 0
stTime = eTime
}
}
exitC := make(chan struct{}, 2)
fpsDelay := time.Second / 6
fpsTicker := time.NewTicker(fpsDelay)
for {
select {
case <-exitC:
fpsTicker.Stop()
destroy()
return
case <-fpsTicker.C:
if !pollEvents() {
exitC <- struct{}{}
continue
}
renderFrame()
}
}
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
_ "embed"
"fmt"
"image"
"image/color"
"image/draw"
"runtime"
"time"
"unsafe"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/iox/imagex"
"cogentcore.org/core/gpu"
"cogentcore.org/core/gpu/gpudraw"
"cogentcore.org/core/math32"
"github.com/oliverbestmann/webgpu/wgpu"
)
//go:embed indexed.wgsl
var indexed string
func init() {
// must lock main thread for gpu!
runtime.LockOSThread()
}
type CamView struct {
Model math32.Matrix4
View math32.Matrix4
Projection math32.Matrix4
}
func main() {
var resize func(size image.Point)
size := image.Point{1024, 768}
sp, terminate, pollEvents, size, err := gpu.GLFWCreateWindow(size, "Offscreen Render", &resize)
if err != nil {
return
}
gp := gpu.NewGPU(sp)
sf := gpu.NewSurface(gp, sp, size, 1, gpu.UndefinedType)
drw := gpudraw.NewDrawer(gp, sf)
rt := gpu.NewRenderTexture(gp, sf.Device(), size, 4, gpu.UndefinedType)
sy := gpu.NewGraphicsSystem(gp, "drawidx", rt)
fmt.Println("format:", rt.Frames[0].Format.String())
resize = func(size image.Point) {
sf.SetSize(size)
rt.SetSize(size)
}
destroy := func() {
drw.Release()
sy.Release()
sf.Release()
gp.Release()
terminate()
}
pl := sy.AddGraphicsPipeline("drawidx")
pl.SetCullMode(wgpu.CullModeNone)
sy.SetClearColor(color.RGBA{50, 50, 50, 255})
sh := pl.AddShader("indexed")
sh.OpenCode(indexed)
pl.AddEntry(sh, gpu.VertexShader, "vs_main")
pl.AddEntry(sh, gpu.FragmentShader, "fs_main")
vgp := sy.Vars().AddVertexGroup()
ugp := sy.Vars().AddGroup(gpu.Uniform)
// vertex are dynamically sized in general, so using 0 here
posv := vgp.Add("Pos", gpu.Float32Vector3, 0, gpu.VertexShader)
clrv := vgp.Add("Color", gpu.Float32Vector3, 0, gpu.VertexShader)
// note: index goes last usually
idxv := vgp.Add("Index", gpu.Uint16, 0, gpu.VertexShader)
idxv.Role = gpu.Index
camv := ugp.AddStruct("Camera", int(unsafe.Sizeof(CamView{})), 1, gpu.VertexShader)
vgp.SetNValues(1)
ugp.SetNValues(1)
sy.Config()
triPos := posv.Values.Values[0]
gpu.SetValueFrom(triPos, []float32{
-0.5, 0.5, 0.0,
0.5, 0.5, 0.0,
0.0, -0.5, 0.0}) // negative point is UP in native Vulkan
triClr := clrv.Values.Values[0]
gpu.SetValueFrom(triClr, []float32{
1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0})
triIndex := idxv.Values.Values[0]
gpu.SetValueFrom(triIndex, []uint16{0, 1, 2})
// note: the only way to set indexes is at start..
// This is the standard camera view projection computation
cam := camv.Values.Values[0]
campos := math32.Vec3(0, 0, 2)
target := math32.Vec3(0, 0, 0)
var lookq math32.Quat
lookq.SetFromRotationMatrix(math32.NewLookAt(campos, target, math32.Vec3(0, 1, 0)))
scale := math32.Vec3(1, 1, 1)
var cview math32.Matrix4
cview.SetTransform(campos, lookq, scale)
view, _ := cview.Inverse()
var camo CamView
camo.Model.SetIdentity()
camo.View.CopyFrom(view)
aspect := float32(sf.Format.Size.X) / float32(sf.Format.Size.Y)
camo.Projection.SetPerspective(45, aspect, 0.01, 100)
gpu.SetValueFrom(cam, []CamView{camo}) // note: always use slice to copy
updateAspect := func() {
aspect := rt.Format.Aspect()
fmt.Printf("aspect: %g\n", aspect)
camo.Projection.SetPerspective(45, aspect, 0.01, 100)
gpu.SetValueFrom(cam, []CamView{camo}) // note: always use slice to copy
}
updateAspect()
// todo:
// drw.ConfigTexture(0, &rt.Format)
frameCount := 0
stTime := time.Now()
didSave := runtime.GOOS == "js" // don't save png on web
renderFrame := func() {
// fmt.Printf("frame: %d\n", frameCount)
// rt := time.Now()
camo.Model.SetRotationY(.1 * float32(frameCount))
gpu.SetValueFrom(cam, []CamView{camo})
rt.CurrentFrame().ConfigReadBuffer() // ensure configed with proper size
rp, err := sy.BeginRenderPass()
if err != nil {
return
}
pl.BindPipeline(rp)
pl.BindDrawIndexed(rp)
rp.End()
if !didSave {
didSave = true
rt.ReadFrame(sy.CommandEncoder)
sy.EndRenderPass(rp)
img, err := rt.CurrentFrame().ReadGoImage()
if errors.Log(err) != nil {
return
}
imagex.Save(img, "render.png")
fmt.Println("saved image", rt.CurrentFrame().ReadBufferDims)
} else {
sy.EndRenderPass(rp)
}
drw.Start()
drw.UseTexture(rt.Frames[0])
drw.ScaleUsed(image.Rectangle{}, image.Rectangle{}, 0, draw.Src, math32.NoFlipY)
drw.End()
// fmt.Printf("present %v\n\n", time.Since(rt))
frameCount++
eTime := time.Now()
dur := float64(eTime.Sub(stTime)) / float64(time.Second)
if dur > 10 {
fps := float64(frameCount) / dur
fmt.Printf("fps: %.0f\n", fps)
sz := rt.Format.Size
sz.X -= 10
rt.SetSize(sz)
updateAspect()
frameCount = 0
stTime = eTime
}
}
exitC := make(chan struct{}, 2)
fpsDelay := time.Second / 60
fpsTicker := time.NewTicker(fpsDelay)
for {
select {
case <-exitC:
fpsTicker.Stop()
destroy()
return
case <-fpsTicker.C:
if !pollEvents() {
exitC <- struct{}{}
continue
}
renderFrame()
}
}
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"image"
"image/color"
"runtime"
"strconv"
"strings"
"time"
"cogentcore.org/core/base/iox/imagex"
"cogentcore.org/core/gpu"
"cogentcore.org/core/gpu/examples/images"
"cogentcore.org/core/gpu/phong"
"cogentcore.org/core/gpu/shape"
"cogentcore.org/core/math32"
"github.com/oliverbestmann/webgpu/wgpu"
)
func init() {
// must lock main thread for gpu! really
runtime.LockOSThread()
}
type Object struct {
Mesh string
Color color.Color
Texture string
Matrix math32.Matrix4
}
func main() {
var resize func(size image.Point)
size := image.Point{1024, 768}
sp, terminate, pollEvents, size, err := gpu.GLFWCreateWindow(size, "Phong", &resize)
if err != nil {
return
}
gp := gpu.NewGPU(sp)
sf := gpu.NewSurface(gp, sp, size, 4, gpu.Depth32)
ph := phong.NewPhong(sf.GPU, sf)
fmt.Printf("format: %s\n", sf.Format.String())
resize = func(size image.Point) { sf.SetSize(size) }
destroy := func() {
ph.Release()
sf.Release()
gp.Release()
terminate()
}
/////////////////////////////
// Lights
ph.AddAmbient(math32.NewVector3Color(color.White).MulScalar(.1))
ph.AddDirectional(math32.NewVector3Color(color.White), math32.Vec3(0, 1, 1))
// ph.AddPoint(math32.NewVector3Color(color.White), math32.Vec3(-5, 0, 2), .01, .001)
// ph.AddSpot(math32.NewVector3Color(color.White), math32.Vec3(-2, 5, -2), math32.Vec3(0, -1, 0), 10, 45, .01, .001)
/////////////////////////////
// Meshes
// Note: 100 segs improves lighting differentiation significantly
ph.SetMesh("floor",
shape.NewPlane(math32.Y, 100, 100).SetSegs(math32.Vec2i(100, 100)).SetNormalNeg(false))
ph.SetMesh("cube",
shape.NewBox(1, 1, 1).SetSegs(math32.Vec3i(50, 50, 50)))
ph.SetMesh("sphere", shape.NewSphere(.5, 64))
ph.SetMesh("cylinder", shape.NewCylinder(1, .5, 64, 64, shape.WithTop, shape.WithBottom))
ph.SetMesh("cone", shape.NewCone(1, .5, 64, 64, shape.WithBottom))
ph.SetMesh("capsule", shape.NewCapsule(1, .5, 64, 64))
ph.SetMesh("torus", shape.NewTorus(2, .2, 64))
lines := shape.NewLines([]math32.Vector3{{X: -3, Y: -1, Z: 0}, {X: -2, Y: 1, Z: 0}, {X: 2, Y: 1, Z: 0}, {X: 3, Y: -1, Z: 0}}, math32.Vec2(.2, .1), false)
ph.SetMesh("lines", lines)
/////////////////////////////
// Textures
imgFiles := []string{"ground.png", "wood.png", "teximg.jpg"}
imgs := make([]image.Image, len(imgFiles))
for i, fnm := range imgFiles {
imgs[i], _, _ = imagex.OpenFS(images.Images, fnm)
fn, _, _ := strings.Cut(fnm, ".")
ph.SetTexture(fn, phong.NewTexture(imgs[i]))
}
/////////////////////////////
// Colors
dark := color.RGBA{20, 20, 20, 255}
_ = dark
blue := color.RGBA{0, 0, 255, 255}
blueTr := color.RGBA{0, 0, 200, 200}
red := color.RGBA{255, 0, 0, 255}
redTr := color.RGBA{200, 0, 0, 200}
green := color.RGBA{0, 255, 0, 255}
orange := color.RGBA{180, 130, 0, 255}
tan := color.RGBA{210, 180, 140, 255}
/////////////////////////////
// Camera / Matrix
// This is the standard camera view projection computation
campos := math32.Vec3(0, 2, 10)
view := phong.CameraViewMat(campos, math32.Vec3(0, 0, 0), math32.Vec3(0, 1, 0))
aspect := sf.Format.Aspect()
var projection math32.Matrix4
projection.SetPerspective(45, aspect, 0.01, 100)
ph.SetCamera(view, &projection)
objs := []Object{
{Mesh: "floor", Color: blue, Texture: "ground"},
{Mesh: "cube", Color: red, Texture: "teximg"},
{Mesh: "cylinder", Color: blue, Texture: "wood"},
{Mesh: "cone", Color: green},
{Mesh: "lines", Color: orange},
{Mesh: "capsule", Color: tan},
{Mesh: "sphere", Color: redTr},
{Mesh: "torus", Color: blueTr},
}
objs[0].Matrix.SetTranslation(0, -2, -2)
// objs[0].Colors.SetTextureRepeat(math32.Vector2{50, 50})
objs[1].Matrix.SetTranslation(-2, 0, 0)
objs[2].Matrix.SetTranslation(0, 0, -2)
objs[3].Matrix.SetTranslation(-1, 0, -2)
objs[4].Matrix.SetTranslation(1, 0, -1)
objs[5].Matrix.SetTranslation(1, 0, -1)
objs[6].Matrix.SetRotationY(0.5)
objs[7].Matrix.SetTranslation(1, 0, -1)
for i, ob := range objs {
nm := strconv.Itoa(i)
ph.SetObject(nm, phong.NewObject(&ob.Matrix, phong.NewColors(ob.Color, color.Black, 30, 1, 1)))
}
/////////////////////////////
// Config!
updateCamera := func() {
aspect := sf.Format.Aspect()
view = phong.CameraViewMat(campos, math32.Vec3(0, 0, 0), math32.Vec3(0, 1, 0))
projection.SetPerspective(45, aspect, 0.01, 100)
ph.SetCamera(view, &projection)
}
updateCamera()
updateObs := func() {
for i, ob := range objs {
nm := strconv.Itoa(i)
od := phong.NewObject(&ob.Matrix, phong.NewColors(ob.Color, color.Black, 30, 1, 1))
if i == 0 {
od.SetTilingRepeat(math32.Vec2(50, 50))
}
if i == 3 { // cone
od.SetColors(dark, green, 30, .1, 1) // emissive, not reflective
}
ph.SetObject(nm, od)
}
}
updateObs() // gotta do at least once
render1 := func(rp *wgpu.RenderPassEncoder) {
for i, ob := range objs {
ph.UseObjectIndex(i)
ph.UseMesh(ob.Mesh)
if ob.Texture != "" {
ph.UseTexture(ob.Texture)
} else {
ph.UseNoTexture()
}
ph.Render(rp)
}
}
frameCount := 0
stTime := time.Now()
renderFrame := func() {
fcr := frameCount % 10
_ = fcr
campos.X = float32(frameCount) * 0.01
campos.Z = 10 - float32(frameCount)*0.03
frameCount++
updateCamera()
rp, err := ph.RenderStart()
if err != nil {
return
}
render1(rp)
ph.RenderEnd(rp)
eTime := time.Now()
dur := float64(eTime.Sub(stTime)) / float64(time.Second)
if dur > 10 {
fps := float64(frameCount) / dur
fmt.Printf("fps: %.0f\n", fps)
frameCount = 0
stTime = eTime
}
}
exitC := make(chan struct{}, 2)
fpsDelay := time.Second / 60
fpsTicker := time.NewTicker(fpsDelay)
for {
select {
case <-exitC:
fpsTicker.Stop()
destroy()
return
case <-fpsTicker.C:
if !pollEvents() {
exitC <- struct{}{}
continue
}
renderFrame()
}
}
}
// Copyright (c) 2022, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
_ "embed"
"fmt"
"image"
"image/color"
"runtime"
"time"
"cogentcore.org/core/base/iox/imagex"
"cogentcore.org/core/gpu"
"cogentcore.org/core/gpu/examples/images"
"cogentcore.org/core/math32"
)
//go:embed texture.wgsl
var texture string
func init() {
// a must lock main thread for gpu!
runtime.LockOSThread()
}
type CamView struct {
Model math32.Matrix4
View math32.Matrix4
Projection math32.Matrix4
}
func main() {
var resize func(size image.Point)
size := image.Point{1024, 768}
sp, terminate, pollEvents, size, err := gpu.GLFWCreateWindow(size, "Draw Texture", &resize)
if err != nil {
return
}
gp := gpu.NewGPU(sp)
sf := gpu.NewSurface(gp, sp, size, 4, gpu.UndefinedType)
sy := gpu.NewGraphicsSystem(gp, "texture", sf)
fmt.Printf("format: %s\n", sf.Format.String())
resize = func(size image.Point) { sf.SetSize(size) }
destroy := func() {
sy.Release()
sf.Release()
gp.Release()
terminate()
}
pl := sy.AddGraphicsPipeline("texture")
sy.SetClearColor(color.RGBA{50, 50, 50, 255})
// pl.SetFrontFace(wgpu.FrontFaceCW)
// pl.SetCullMode(wgpu.CullModeBack)
sh := pl.AddShader("texture")
sh.OpenCode(texture)
pl.AddEntry(sh, gpu.VertexShader, "vs_main")
pl.AddEntry(sh, gpu.FragmentShader, "fs_main")
vgp := sy.Vars().AddVertexGroup()
tgp := sy.Vars().AddGroup(gpu.SampledTexture) // texture in 0 so frag only gets 0
ugp := sy.Vars().AddGroup(gpu.Uniform)
posv := vgp.Add("Pos", gpu.Float32Vector3, 0, gpu.VertexShader)
clrv := vgp.Add("Color", gpu.Float32Vector3, 0, gpu.VertexShader)
txcv := vgp.Add("TexCoord", gpu.Float32Vector2, 0, gpu.VertexShader)
idxv := vgp.Add("Index", gpu.Uint16, 0, gpu.VertexShader)
idxv.Role = gpu.Index
camv := ugp.AddStruct("Camera", gpu.Float32Matrix4.Bytes()*3, 1, gpu.VertexShader)
txv := tgp.Add("TexSampler", gpu.TextureRGBA32, 1, gpu.FragmentShader)
vgp.SetNValues(1)
ugp.SetNValues(1)
tgp.SetNValues(3)
sy.Config()
imgFiles := []string{"ground.png", "wood.png", "teximg.jpg"}
imgs := make([]image.Image, len(imgFiles))
for i, fnm := range imgFiles {
imgs[i], _, _ = imagex.OpenFS(images.Images, fnm)
img := txv.Values.Values[i]
img.SetFromGoImage(imgs[i], 0)
// img.Texture.Sampler.Border = gpu.BorderBlack
// img.Texture.Sampler.UMode = gpu.ClampToBorder
// img.Texture.Sampler.VMode = gpu.ClampToBorder
}
gpu.SetValueFrom(posv.Values.Values[0], []float32{
-0.5, -0.5, 0.0,
0.5, -0.5, 0.0,
0.5, 0.5, 0.0,
-0.5, 0.5, 0.0})
gpu.SetValueFrom(clrv.Values.Values[0], []float32{
1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0,
1.0, 1.0, 0.0})
gpu.SetValueFrom(txcv.Values.Values[0], []float32{
1.0, 0.0,
0.0, 0.0,
0.0, 1.0,
1.0, 1.0})
gpu.SetValueFrom(idxv.Values.Values[0], []uint16{3, 2, 0, 2, 1, 0}) // reversed binding
// This is the standard camera view projection computation
campos := math32.Vec3(0, 0, 2)
target := math32.Vec3(0, 0, 0)
var lookq math32.Quat
lookq.SetFromRotationMatrix(math32.NewLookAt(campos, target, math32.Vec3(0, 1, 0)))
scale := math32.Vec3(1, 1, 1)
var cview math32.Matrix4
cview.SetTransform(campos, lookq, scale)
view, _ := cview.Inverse()
var camo CamView
camo.Model.SetIdentity()
camo.View.CopyFrom(view)
aspect := float32(sf.Format.Size.X) / float32(sf.Format.Size.Y)
camo.Projection.SetPerspective(45, aspect, 0.01, 100)
cam := camv.Values.Values[0]
gpu.SetValueFrom(cam, []CamView{camo}) // note: always use slice to copy
frameCount := 0
stTime := time.Now()
renderFrame := func() {
// fmt.Printf("frame: %d\n", frameCount)
// rt := time.Now()
camo.Model.SetRotationY(.004 * float32(frameCount))
gpu.SetValueFrom(cam, []CamView{camo})
imgIndex := (frameCount / 10) % len(imgs)
pl.Vars().SetCurrentValue(0, "TexSampler", imgIndex)
rp, err := sy.BeginRenderPass()
if err != nil {
return
}
pl.BindPipeline(rp)
pl.BindDrawIndexed(rp)
rp.End()
sy.EndRenderPass(rp)
frameCount++
eTime := time.Now()
dur := float64(eTime.Sub(stTime)) / float64(time.Second)
if dur > 10 {
fps := float64(frameCount) / dur
fmt.Printf("fps: %.0f\n", fps)
frameCount = 0
stTime = eTime
}
}
exitC := make(chan struct{}, 2)
fpsDelay := time.Second / 60
fpsTicker := time.NewTicker(fpsDelay)
for {
select {
case <-exitC:
fpsTicker.Stop()
destroy()
return
case <-fpsTicker.C:
if !pollEvents() {
exitC <- struct{}{}
continue
}
renderFrame()
}
}
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gpu
import (
"fmt"
"image"
"log"
"github.com/oliverbestmann/webgpu/wgpu"
)
// TextureFormat describes the size and WebGPU format of a Texture.
// If Layers > 1, all must be the same size.
type TextureFormat struct {
// Size of image
Size image.Point
// Texture format: RGBA8UnormSrgb is default
Format wgpu.TextureFormat
// number of samples. set higher for RenderTexture rendering
// but otherwise default of 1
Samples int
// number of layers for texture arrays
Layers int
}
// NewTextureFormat returns a new TextureFormat with default format and given size
// and number of layers
func NewTextureFormat(width, height, layers int) *TextureFormat {
im := &TextureFormat{}
im.Defaults()
im.Size = image.Point{width, height}
im.Layers = layers
return im
}
func (im *TextureFormat) Defaults() {
im.Format = wgpu.TextureFormatRGBA8UnormSrgb
im.Samples = 1
im.Layers = 1
}
// String returns human-readable version of format
func (im *TextureFormat) String() string {
return fmt.Sprintf("Size: %v Format: %s MultiSample: %d Layers: %d", im.Size, TextureFormatNames[im.Format], im.Samples, im.Layers)
}
// IsStdRGBA returns true if image format is the standard
// wgpu.TextureFormatRGBA8UnormSrgb
// which is compatible with go image.RGBA format.
func (im *TextureFormat) IsStdRGBA() bool {
return im.Format == wgpu.TextureFormatRGBA8UnormSrgb
}
// IsRGBAUnorm returns true if image format is the
// wgpu.TextureFormatRGBA8Unorm format
// which is compatible with go image.RGBA format with colorspace conversion.
func (im *TextureFormat) IsRGBAUnorm() bool {
return im.Format == wgpu.TextureFormatRGBA8Unorm
}
// SetSize sets the width, height
func (im *TextureFormat) SetSize(w, h int) {
im.Size = image.Point{X: w, Y: h}
}
// Set sets width, height and format
func (im *TextureFormat) Set(w, h int, ft wgpu.TextureFormat) {
im.SetSize(w, h)
im.Format = ft
}
// SetFormat sets the format using vgpu standard Types
func (im *TextureFormat) SetFormat(ft Types) {
im.Format = ft.TextureFormat()
}
// SetMultisample sets the number of multisampling to decrease aliasing
// 4 is typically sufficient. Values must be power of 2.
func (im *TextureFormat) SetMultisample(nsamp int) {
im.Samples = nsamp
}
// Size32 returns size as uint32 values
func (im *TextureFormat) Size32() (width, height uint32) {
width = uint32(im.Size.X)
height = uint32(im.Size.Y)
return
}
func (im *TextureFormat) Extent3D() wgpu.Extent3D {
ex := wgpu.Extent3D{
Width: uint32(im.Size.X),
Height: uint32(im.Size.Y),
DepthOrArrayLayers: uint32(im.Layers),
}
return ex
}
// Aspect returns the aspect ratio X / Y
func (im *TextureFormat) Aspect() float32 {
if im.Size.Y > 0 {
return float32(im.Size.X) / float32(im.Size.Y)
}
return 1.3
}
// Bounds returns the rectangle defining this image: 0,0,w,h
func (im *TextureFormat) Bounds() image.Rectangle {
return image.Rectangle{Max: im.Size}
}
// BytesPerPixel returns number of bytes required to represent
// one Pixel (in Host memory at least). TODO only works
// for known formats -- need to add more as needed.
func (im *TextureFormat) BytesPerPixel() int {
bpp := TextureFormatSizes[im.Format]
if bpp > 0 {
return bpp
}
log.Println("gpu.TextureFormat:BytesPerPixel() -- format not yet supported!")
return 0
}
// LayerByteSize returns number of bytes required to represent one layer of
// image in Host memory. TODO only works
// for known formats -- need to add more as needed.
func (im *TextureFormat) LayerByteSize() int {
return im.BytesPerPixel() * im.Size.X * im.Size.Y
}
// TotalByteSize returns total number of bytes required to represent all layers of
// images in Host memory. TODO only works
// for known formats -- need to add more as needed.
func (im *TextureFormat) TotalByteSize() int {
return im.LayerByteSize() * im.Layers
}
// Stride returns number of bytes per image row. TODO only works
// for known formats -- need to add more as needed.
func (im *TextureFormat) Stride() int {
return im.BytesPerPixel() * im.Size.X
}
//////////////////////////////////////////////////////////////////////
// TextureBufferDims represents the sizes required in Buffer to
// represent a texture of a given size.
type TextureBufferDims struct {
Width uint64
Height uint64
UnpaddedRowSize uint64
PaddedRowSize uint64
}
func NewTextureBufferDims(size image.Point) *TextureBufferDims {
td := &TextureBufferDims{}
td.Set(size)
return td
}
func (td *TextureBufferDims) Set(size image.Point) {
td.Width = uint64(size.X)
td.Height = uint64(size.Y)
const bytesPerPixel = 4 // unsafe.Sizeof(uint32(0))
td.UnpaddedRowSize = uint64(td.Width * bytesPerPixel)
align := uint64(wgpu.CopyBytesPerRowAlignment)
padding := (align - td.UnpaddedRowSize%align) % align
td.PaddedRowSize = td.UnpaddedRowSize + padding
}
// PaddedSize returns the total padded size of data
func (td *TextureBufferDims) PaddedSize() uint64 {
return td.PaddedRowSize * td.Height
}
// UnpaddedSize returns the total unpadded size of data
func (td *TextureBufferDims) UnpaddedSize() uint64 {
return td.UnpaddedRowSize * td.Height
}
// HasNoPadding returns true if the Unpadded and Padded row sizes
// are the same.
func (td *TextureBufferDims) HasNoPadding() bool {
return td.UnpaddedRowSize == td.PaddedRowSize
}
// Copyright (c) 2022, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build (darwin && !ios) || windows || (linux && !android) || dragonfly || openbsd
package gpu
import (
"image"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/gpu/wgpuglfw"
"cogentcore.org/core/system"
"github.com/cogentcore/glfw4/v3.4/glfw"
"github.com/oliverbestmann/webgpu/wgpu"
)
// note: this file contains the glfw dependencies, for desktop platform builds
// other platforms (mobile, web) need to provide their own Init() and Terminate()
// methods.
// Init initializes WebGPU system for Display-enabled use, using glfw.
// Must call before doing any vgpu stuff.
// Calls glfw.Init and sets the Vulkan instance proc addr and calls Init.
// IMPORTANT: must be called on the main initial thread!
func Init() error {
err := glfw.Init()
if err != nil {
return errors.Log(err)
}
// vk.SetGetInstanceProcAddr(glfw.GetVulkanGetInstanceProcAddress())
// return errors.Log(vk.Init())
return nil
}
// Terminate shuts down the WebGPU system -- call as last thing before quitting.
// IMPORTANT: must be called on the main initial thread!
func Terminate() {
glfw.Terminate()
}
// GLFWPollEvents is a wrapper around glfw.PollEvents that is a no-op on web
func GLFWPollEvents() {
glfw.PollEvents()
}
// GLFWCreateWindow is a helper function intended only for use in simple examples that makes a
// new window with glfw on platforms that support it and is largely a no-op on other platforms.
func GLFWCreateWindow(size image.Point, title string, resize *func(size image.Point)) (surface *wgpu.Surface, terminate func(), pollEvents func() bool, actualSize image.Point, err error) {
if system.GenerateHTMLArg() {
return
}
if err = Init(); err != nil {
return
}
glfw.WindowHint(glfw.ClientAPI, glfw.NoAPI)
window, err := glfw.CreateWindow(size.X, size.Y, title, nil, nil)
if err != nil {
return
}
inst := Instance()
surface = inst.CreateSurface(wgpuglfw.GetSurfaceDescriptor(window))
terminate = func() {
window.Destroy()
Terminate()
}
pollEvents = func() bool {
if window.ShouldClose() {
return false
}
glfw.PollEvents()
return true
}
window.SetSizeCallback(func(w *glfw.Window, width, height int) {
if resize != nil {
(*resize)(image.Point{width, height})
}
})
actualSize = size
return
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gpu
import (
"cogentcore.org/core/base/errors"
"github.com/oliverbestmann/webgpu/wgpu"
)
// GraphicsPipeline is a Pipeline specifically for the Graphics stack.
// In this context, each pipeline could handle a different
// class of materials (textures, Phong lighting, etc).
// There must be two shader-names
type GraphicsPipeline struct {
Pipeline
// Primitive has various settings for graphics primitives,
// e.g., TriangleList
Primitive wgpu.PrimitiveState
Multisample wgpu.MultisampleState
// AlphaBlend determines whether to do alpha blending or not.
AlphaBlend bool
// renderPipeline is the configured, instantiated wgpu pipeline
renderPipeline *wgpu.RenderPipeline
}
// NewGraphicsPipeline returns a new GraphicsPipeline.
func NewGraphicsPipeline(name string, sy *GraphicsSystem) *GraphicsPipeline {
pl := &GraphicsPipeline{}
pl.Name = name
pl.System = sy
pl.SetGraphicsDefaults()
return pl
}
// BindAllGroups binds the Current Value for all variables across all
// variable groups, as the Value to use by shader.
// Automatically called in BindPipeline at start of render for pipeline.
// Be sure to set Current index to correct value before calling!
func (pl *GraphicsPipeline) BindAllGroups(rp *wgpu.RenderPassEncoder) {
vs := pl.Vars()
ngp := vs.NGroups()
for gi := range ngp {
pl.BindGroup(rp, gi)
}
}
// BindGroup binds the Current Value for all variables in given
// variable group, as the Value to use by shader.
// Be sure to set Current index to correct value before calling!
func (pl *GraphicsPipeline) BindGroup(rp *wgpu.RenderPassEncoder, group int) {
vg := pl.Vars().Groups[group]
bg, dynOffs, err := pl.bindGroup(vg)
if err == nil {
rp.SetBindGroup(uint32(vg.Group), bg, dynOffs)
}
}
// BindPipeline binds this pipeline as the one to use for next commands in
// the given render pass.
// This also calls BindAllGroups, to bind the Current Value for all variables,
// excluding Vertex level variables: use BindVertex for that.
// Be sure to set the desired Current value prior to calling.
func (pl *GraphicsPipeline) BindPipeline(rp *wgpu.RenderPassEncoder) error {
if pl.renderPipeline == nil {
err := pl.Config(false)
if errors.Log(err) != nil {
return err
}
}
rp.SetPipeline(pl.renderPipeline)
pl.BindAllGroups(rp)
return nil
}
// BindDrawIndexed binds the Current Value for all VertexGroup variables,
// as the vertex data, and then does a DrawIndexed call.
func (pl *GraphicsPipeline) BindDrawIndexed(rp *wgpu.RenderPassEncoder) {
pl.BindVertex(rp)
pl.DrawIndexed(rp)
}
// BindVertex binds the Current Value for all VertexGroup variables,
// as the vertex data to use for next DrawIndexed call.
func (pl *GraphicsPipeline) BindVertex(rp *wgpu.RenderPassEncoder) {
vs := pl.Vars()
vg := vs.Groups[VertexGroup]
if vg == nil {
return
}
for _, vr := range vg.Vars {
vl := vr.Values.CurrentValue()
if vr.Role == Index {
rp.SetIndexBuffer(vl.buffer, vr.Type.IndexType(), 0, wgpu.WholeSize)
} else {
if vl.buffer != nil {
rp.SetVertexBuffer(uint32(vr.Binding), vl.buffer, 0, wgpu.WholeSize)
}
}
}
}
// DrawIndexed adds commands to the given command encoder
// to Draw based on current Index and Vertex values.
func (pl *GraphicsPipeline) DrawIndexed(rp *wgpu.RenderPassEncoder) {
vs := pl.Vars()
vg := vs.Groups[VertexGroup]
if vg == nil {
return
}
ix := vg.IndexVar()
if ix == nil {
return
}
iv := ix.Values.CurrentValue()
rp.DrawIndexed(uint32(iv.dynamicN), 1, 0, 0, 0)
}
// VertexEntry returns the [ShaderEntry] for [VertexShader].
// Can be nil if no vertex shader defined.
func (pl *GraphicsPipeline) VertexEntry() *ShaderEntry {
return pl.EntryByType(VertexShader)
}
// FragmentEntry returns the [ShaderEntry] for [FragmentShader].
// Can be nil if no vertex shader defined.
func (pl *GraphicsPipeline) FragmentEntry() *ShaderEntry {
return pl.EntryByType(FragmentShader)
}
// Config is called once all the Config options have been set
// using Set* methods, and the shaders have been loaded.
// The parent GraphicsSystem has already done what it can for its config.
// The rebuild flag indicates whether pipelines should rebuild
func (pl *GraphicsPipeline) Config(rebuild bool) error {
if pl.renderPipeline != nil {
if !rebuild {
return nil
}
pl.releasePipeline() // starting over: note: requires keeping shaders around
}
play, err := pl.bindLayout()
if errors.Log(err) != nil {
return err
}
defer play.Release()
pl.Multisample.Count = uint32(pl.System.Render().Format.Samples)
pd := &wgpu.RenderPipelineDescriptor{
Label: pl.Name,
Layout: play,
Primitive: pl.Primitive,
Multisample: pl.Multisample,
}
ve := pl.VertexEntry()
if ve != nil {
vtxLay := pl.Vars().VertexLayout()
// todo: err if vtxlay is nil
pd.Vertex = wgpu.VertexState{
Module: ve.Shader.module,
EntryPoint: ve.Entry,
Buffers: vtxLay,
}
}
fe := pl.FragmentEntry()
if fe != nil {
pd.Fragment = &wgpu.FragmentState{
Module: fe.Shader.module,
EntryPoint: fe.Entry,
Targets: []wgpu.ColorTargetState{{
Format: pl.System.Render().Format.Format,
Blend: &wgpu.BlendStatePremultipliedAlphaBlending,
WriteMask: wgpu.ColorWriteMaskAll, // todo
}},
}
if !pl.AlphaBlend {
pd.Fragment.Targets[0].Blend = &wgpu.BlendStateReplace
}
}
if pl.System.Render().Depth.texture != nil {
pd.DepthStencil = &wgpu.DepthStencilState{
Format: pl.System.Render().Depth.Format.Format,
DepthWriteEnabled: wgpu.OptionalBoolTrue,
DepthCompare: wgpu.CompareFunctionLess,
StencilFront: wgpu.StencilFaceState{
Compare: wgpu.CompareFunctionAlways,
},
StencilBack: wgpu.StencilFaceState{
Compare: wgpu.CompareFunctionAlways,
},
}
}
rp, err := pl.System.Device().Device.TryCreateRenderPipeline(pd)
if errors.Log(err) != nil {
return err
}
pl.renderPipeline = rp
return nil
}
func (pl *GraphicsPipeline) Release() {
pl.releaseShaders()
pl.releasePipeline()
}
func (pl *GraphicsPipeline) releasePipeline() {
if pl.renderPipeline != nil {
pl.renderPipeline.Release()
pl.renderPipeline = nil
}
}
//////////////////////////////////////////////////////////////
// Set graphics options
// SetGraphicsDefaults configures all the default settings for a
// graphics rendering pipeline (not for a compute pipeline)
func (pl *GraphicsPipeline) SetGraphicsDefaults() *GraphicsPipeline {
pl.SetTopology(TriangleList, false)
pl.SetFrontFace(wgpu.FrontFaceCW)
pl.SetCullMode(wgpu.CullModeBack)
pl.SetAlphaBlend(true) // alpha blending
pl.Multisample.Count = 1
pl.Multisample.Mask = 0xFFFFFFFF // todo
pl.Multisample.AlphaToCoverageEnabled = false // todo
return pl
}
// SetTopology sets the topology of vertex position data.
// TriangleList is the default.
// Also for Strip modes, restartEnable allows restarting a new
// strip by inserting a ??
func (pl *GraphicsPipeline) SetTopology(topo Topologies, restartEnable bool) *GraphicsPipeline {
pl.Primitive.Topology = topo.Primitive()
return pl
}
// SetFrontFace sets the winding order for what counts as a front face.
// Default is CW.
func (pl *GraphicsPipeline) SetFrontFace(face wgpu.FrontFace) *GraphicsPipeline {
pl.Primitive.FrontFace = face
return pl
}
// SetCullMode sets the face culling mode.
func (pl *GraphicsPipeline) SetCullMode(mode wgpu.CullMode) *GraphicsPipeline {
pl.Primitive.CullMode = mode
return pl
}
// SetLineWidth sets the rendering line width -- 1 is default.
func (pl *GraphicsPipeline) SetLineWidth(lineWidth float32) {
// pl.VkConfig.PRasterizationState.LineWidth = lineWidth
}
// SetAlphaBlend determines the alpha (transparency) blending function:
// either 1-source alpha (alphaBlend) or no blending:
// new color overwrites old. Default is alphaBlend = true
func (pl *GraphicsPipeline) SetAlphaBlend(alphaBlend bool) {
pl.AlphaBlend = alphaBlend
}
////////////////////////////////////////////////////////
// Graphics render
// Push pushes given value as a push constant for given
// registered push constant variable.
// Note: it is *essential* to use a local, stack variable for the push value
// as cgo will likely complain if it is inside some other structure.
// BindPipeline must have been called before this.
// func (pl *GraphicsPipeline) Push(cmd *wgpu.CommandEncoder, vr *Var, val unsafe.Pointer) {
// vs := pl.Vars()
// vk.CmdPushConstants(cmd, vs.VkDescLayout, vk.ShaderStageFlags(vr.Shaders), uint32(vr.Offset), uint32(vr.SizeOf), val)
// }
// Topologies are the different vertex topology
type Topologies int32 //enum:enum
const (
PointList Topologies = iota
LineList
LineStrip
TriangleList
TriangleStrip
)
func (tp Topologies) Primitive() wgpu.PrimitiveTopology {
return WebGPUTopologies[tp]
}
var WebGPUTopologies = map[Topologies]wgpu.PrimitiveTopology{
PointList: wgpu.PrimitiveTopologyPointList,
LineList: wgpu.PrimitiveTopologyLineList,
LineStrip: wgpu.PrimitiveTopologyLineStrip,
TriangleList: wgpu.PrimitiveTopologyTriangleList,
TriangleStrip: wgpu.PrimitiveTopologyTriangleStrip,
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gpu
//go:generate core generate
import (
"fmt"
"log"
"os"
"runtime"
"strconv"
"strings"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/reflectx"
"github.com/oliverbestmann/webgpu/wgpu"
)
func init() {
// Don't remove this; it is needed to silence various irrelevant wgpu warnings
SetDebug(false)
}
var (
// Debug is whether to enable debug mode, getting
// more diagnostic output about GPU configuration and rendering.
// It should be set using [SetDebug].
Debug = false
// DebugAdapter provides detailed information about the selected
// GPU adpater device (i.e., the type and limits of the hardware).
DebugAdapter = false
// SelectAdapter selects the given adapter number if >= 0.
// If there are multiple discrete gpu adapters, then all of them
// are listed in order 0..n-1.
SelectAdapter = -1
// theInstance is the initialized WebGPU instance, initialized
// for the first call to NewGPU.
theInstance *wgpu.Instance
)
// Instance returns the highest-level GPU handle: the Instance.
func Instance() *wgpu.Instance {
if theInstance == nil {
theInstance = wgpu.CreateInstance(nil)
}
return theInstance
}
// ReleaseInstance should only be called at final termination.
func ReleaseInstance() {
if theInstance != nil {
theInstance.Release()
theInstance = nil
}
}
// SetDebug sets [Debug] (debug mode). If it is set to true,
// it calls [wgpu.SetLogLevel]([wgpu.LogLevelDebug]). Otherwise,
// it calls [wgpu.SetLogLevel]([wgpu.LogLevelError]).
// It is called automatically with false in init().
// You can also manually set the log level with
// [wgpu.SetLogLevel].
func SetDebug(debug bool) {
Debug = debug
if Debug {
wgpu.SetLogLevel(wgpu.LogLevelDebug)
} else {
wgpu.SetLogLevel(wgpu.LogLevelError)
}
}
// GPU represents the GPU hardware
type GPU struct {
// GPU represents the specific GPU hardware device used.
// You can call GetInfo() to get info.
GPU *wgpu.Adapter
// name of the physical GPU device
DeviceName string
// Properties are the general properties of the GPU adapter.
Properties wgpu.AdapterInfo
// Limits are the limits of the current GPU adapter.
Limits wgpu.Limits
// ComputeOnly indicates if this GPU is only used for compute,
// which determines if it listens to GPU_COMPUTE_DEVICE
// environment variable, allowing different compute devices to be
// selected vs. graphics devices.
ComputeOnly bool
// maximum number of compute threads per compute shader invocation,
// for a 1D number of threads per Warp, which is generally greater
// than MaxComputeWorkGroup, which allows for the maxima as well.
// This is not defined anywhere in the formal spec, unfortunately,
// but has been determined empirically for Mac and NVIDIA which are
// two of the most relevant use-cases. If not a known case,
// the MaxComputeWorkGroupvalue is used, which can significantly
// slow down compute processing if more could actually be used.
// Please file an issue or PR for other GPUs with known larger values.
MaxComputeWorkGroupCount1D int
}
// NewGPU returns a new GPU, configured and ready to use.
// If only doing compute, use [NewComputeGPU].
// The surface can be used to select an appropriate adapter, and
// is recommended but not essential. Returns nil and logs an error
// if the current platform is not supported by WebGPU.
func NewGPU(sf *wgpu.Surface) *GPU {
gp := &GPU{}
if errors.Log(gp.init(sf)) == nil {
return gp
}
return nil
}
// NewComputeGPU returns a new GPU, configured and ready to use,
// for purely compute use, which causes it to listen to
// use the GPU_COMPUTE_DEVICE variable for which GPU device to use.
// Returns nil and logs an error if the current platform
// is not supported by WebGPU.
func NewComputeGPU() *GPU {
gp := &GPU{}
gp.ComputeOnly = true
if errors.Log(gp.init(nil)) == nil {
return gp
}
return nil
}
// init configures the GPU
func (gp *GPU) init(_ *wgpu.Surface) error {
inst := Instance()
if inst == nil {
return errors.New("WebGPU is not supported on this machine: could not create an instance")
}
gpIndex := 0
if gp.ComputeOnly {
gpus := inst.EnumerateAdapters(nil)
if len(gpus) == 0 {
return errors.New("WebGPU is not supported on this machine: no adapters available")
}
gpIndex = gp.SelectComputeGPU(gpus)
gp.GPU = gpus[gpIndex]
} else {
gpus := inst.EnumerateAdapters(nil)
if len(gpus) == 0 {
return errors.New("WebGPU is not supported on this machine: no adapters available")
}
gpIndex = gp.SelectGraphicsGPU(gpus)
gp.GPU = gpus[gpIndex]
// note: below is a more standard way of doing it, but until we fix the issues
// with NVIDIA adapters on linux (#1247), we are using our custom logic.
//
// opts := &wgpu.RequestAdapterOptions{
// CompatibleSurface: sf,
// PowerPreference: wgpu.PowerPreferenceHighPerformance,
// }
// ad, err := inst.RequestAdapter(opts)
// if errors.Log(err) != nil {
// return err
// }
// gp.GPU = ad
}
gp.Properties = gp.GPU.GetInfo()
gp.DeviceName = adapterName(&gp.Properties)
if Debug || DebugAdapter {
fmt.Println("gpu: Selected Device:", gpIndex, gp.DeviceName, " (set DebugAdapter to get more adapter info)")
}
gp.Limits = gp.GPU.GetLimits()
if DebugAdapter {
fmt.Println(gp.PropertiesString())
}
gp.MaxComputeWorkGroupCount1D = int(gp.Limits.MaxComputeWorkgroupsPerDimension)
dv := actualVendorName(&gp.Properties)
if Debug || DebugAdapter {
fmt.Println("GPU device vendor:", dv)
}
switch dv {
case "nvidia":
// all NVIDIA are either 1 << 31 or -1 of that.
gp.MaxComputeWorkGroupCount1D = (1 << 31) - 1
case "apple":
gp.MaxComputeWorkGroupCount1D = (1 << 31) - 1
}
// note: if known to be higher for any specific case, please file an issue or PR
// todo: where are the errors!?
return nil
}
// actualVendorName returns the actual vendor name from the coded
// string that the adapter VendorName contains,
// or, failing that, from the description.
func actualVendorName(ai *wgpu.AdapterInfo) string {
nm := strings.ToLower(ai.Vendor)
// source: https://www.reddit.com/r/vulkan/comments/4ta9nj/is_there_a_comprehensive_list_of_the_names_and/
switch nm {
case "0x10de":
return "nvidia"
case "0x1002":
return "amd"
case "0x1010":
return "imgtec"
case "0x13b5":
return "arm"
case "0x5143":
return "qualcomm"
case "0x8086":
return "intel"
}
vd := strings.ToLower(ai.Description)
if strings.Contains(vd, "apple") {
return "apple"
}
return nm
}
func adapterName(ai *wgpu.AdapterInfo) string {
if ai.Description != "" && !strings.HasPrefix(ai.Description, "0x") {
return ai.Description
}
return ai.Vendor
}
func (gp *GPU) SelectGraphicsGPU(gpus []*wgpu.Adapter) int {
n := len(gpus)
if n == 1 {
return 0
}
if SelectAdapter >= 0 && SelectAdapter < n {
return SelectAdapter
}
trgDevNm := ""
if ev := os.Getenv("GPU_DEVICE"); ev != "" {
trgDevNm = ev
}
if trgDevNm != "" {
idx, err := strconv.Atoi(trgDevNm)
if err == nil && idx >= 0 && idx < n {
return idx
}
for gi := range n {
props := gpus[gi].GetInfo()
if gpuIsBadBackend(props.BackendType) {
continue
}
pnm := adapterName(&props)
if strings.Contains(pnm, trgDevNm) {
devNm := pnm
if Debug {
log.Printf("gpu: selected device named: %s, specified in GPU_DEVICE or GPU_COMPUTE_DEVICE environment variable, index: %d\n", devNm, gi)
}
return gi
}
}
if Debug {
log.Printf("gpu: unable to find device named: %s, specified in GPU_DEVICE or GPU_COMPUTE_DEVICE environment variable\n", trgDevNm)
}
}
// scoring system has 1 point for discrete and 1 for non-gl backend
hiscore := 0
best := 0
for gi := range n {
score := 0
props := gpus[gi].GetInfo()
if gpuIsBadBackend(props.BackendType) {
continue
}
if props.AdapterType == wgpu.AdapterTypeDiscreteGPU {
vnm := actualVendorName(&props)
if (runtime.GOOS == "linux" || runtime.GOOS == "windows") && vnm == "nvidia" {
if Debug || DebugAdapter {
fmt.Println("not selecting discrete nvidia GPU: tends to crash when resizing windows")
}
score--
} else {
score++
}
}
if !gpuIsGLdBackend(props.BackendType) {
score++
}
if score > hiscore {
hiscore = score
best = gi
}
}
return best
}
func (gp *GPU) SelectComputeGPU(gpus []*wgpu.Adapter) int {
n := len(gpus)
if n == 1 {
return 0
}
var discrete []int
for gi := range n {
props := gpus[gi].GetInfo()
if gpuIsBadBackend(props.BackendType) {
continue
}
if props.AdapterType == wgpu.AdapterTypeDiscreteGPU {
discrete = append(discrete, gi)
}
}
ndisc := len(discrete)
if ndisc > 0 && SelectAdapter >= 0 && SelectAdapter < ndisc {
return discrete[SelectAdapter]
}
trgDevNm := ""
if ev := os.Getenv("GPU_DEVICE"); ev != "" {
trgDevNm = ev
}
if gp.ComputeOnly {
if ev := os.Getenv("GPU_COMPUTE_DEVICE"); ev != "" {
trgDevNm = ev
}
}
if trgDevNm != "" {
idx, err := strconv.Atoi(trgDevNm)
if err == nil && idx >= 0 && idx < ndisc {
return discrete[idx]
}
if err == nil && idx >= 0 && idx < n {
return idx
}
for gi := range n {
props := gpus[gi].GetInfo()
if gpuIsBadBackend(props.BackendType) {
continue
}
pnm := adapterName(&props)
if strings.Contains(pnm, trgDevNm) {
if Debug {
log.Printf("gpu: selected device named: %s, specified in GPU_DEVICE or GPU_COMPUTE_DEVICE environment variable, index: %d\n", pnm, gi)
}
return gi
}
}
if Debug {
log.Printf("gpu: unable to find device named: %s, specified in GPU_DEVICE or GPU_COMPUTE_DEVICE environment variable\n", trgDevNm)
}
}
// scoring system has 1 point for discrete and 1 for non-gl backend
hiscore := 0
best := 0
for gi := range n {
score := 0
props := gpus[gi].GetInfo()
if gpuIsBadBackend(props.BackendType) {
continue
}
if props.AdapterType == wgpu.AdapterTypeDiscreteGPU {
score++
}
if !gpuIsGLdBackend(props.BackendType) {
score++
}
if score > hiscore {
hiscore = score
best = gi
}
}
return best
}
func gpuIsGLdBackend(bet wgpu.BackendType) bool {
return bet == wgpu.BackendTypeOpenGL || bet == wgpu.BackendTypeOpenGLES
}
func gpuIsBadBackend(bet wgpu.BackendType) bool {
return bet == wgpu.BackendTypeUndefined || bet == wgpu.BackendTypeNull
}
// Release releases GPU resources -- call after everything else has been destroyed
func (gp *GPU) Release() {
if gp.GPU != nil {
gp.GPU.Release()
gp.GPU = nil
}
}
// NewDevice returns a new device for given GPU.
// It gets the Queue for this device.
func (gp *GPU) NewDevice() (*Device, error) {
return NewDevice(gp)
}
// PropertiesString returns a human-readable summary of the GPU properties.
func (gp *GPU) PropertiesString() string {
return "\n######## GPU Properties\n" + reflectx.StringJSON(&gp.Properties) + reflectx.StringJSON(gp.Limits)
}
// NoDisplayGPU Initializes WebGPU and returns that and a new
// GPU device, without using an existing surface window.
func NoDisplayGPU() (*GPU, *Device, error) {
gp := NewGPU(nil)
dev, err := NewDevice(gp)
return gp, dev, err
}
// Copyright 2024 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gpudraw
import (
"image"
"image/draw"
"cogentcore.org/core/math32"
)
// this file contains the official image/draw like interface
const (
// Unchanged should be used for the unchanged argument in drawer calls,
// when the caller knows that the image is unchanged.
Unchanged = true
// Changed should be used for the unchanged argument to drawer calls,
// when the image has changed since last time or its status is unknown.
Changed = false
)
// Copy copies the given Go source image to the render target, with the
// same semantics as golang.org/x/image/draw.Copy, with the destination
// implicit in the Drawer target.
// - Must have called Start first!
// - dp is the destination point.
// - src is the source image. If an image.Uniform, fast Fill is done.
// - sr is the source region, if zero full src is used; must have for Uniform.
// - op is the drawing operation: Src = copy source directly (blit),
// Over = alpha blend with existing.
// - unchanged should be true if caller knows that this image is unchanged
// from the last time it was used -- saves re-uploading to gpu.
func (dw *Drawer) Copy(dp image.Point, src image.Image, sr image.Rectangle, op draw.Op, unchanged bool) {
if u, ok := src.(*image.Uniform); ok {
dr := sr
del := dp.Sub(sr.Min)
dr.Min = dp
dr.Max = dr.Max.Add(del)
dw.Fill(u.At(0, 0), dr, op)
return
}
dw.UseGoImage(src, unchanged)
dw.CopyUsed(dp, sr, op, math32.NoFlipY)
}
// Scale copies the given Go source image to the render target,
// scaling the region defined by src and sr to the destination
// such that sr in src-space is mapped to dr in dst-space,
// and applying an optional rotation of the source image.
// Has the same general semantics as golang.org/x/image/draw.Scale, with the
// destination implicit in the Drawer target.
// If src image is an
// - Must have called Start first!
// - dr is the destination rectangle; if zero uses full dest image.
// - src is the source image. Uniform does not work (or make sense) here.
// - sr is the source region, if zero full src is used; must have for Uniform.
// - rotateDeg = rotation degrees to apply in the mapping:
// 90 = left, -90 = right, 180 = invert.
// - op is the drawing operation: Src = copy source directly (blit),
// Over = alpha blend with existing.
// - unchanged should be true if caller knows that this image is unchanged
// from the last time it was used -- saves re-uploading to gpu.
func (dw *Drawer) Scale(dr image.Rectangle, src image.Image, sr image.Rectangle, rotateDeg float32, op draw.Op, unchanged bool) {
dw.UseGoImage(src, unchanged)
dw.ScaleUsed(dr, sr, rotateDeg, op, math32.NoFlipY)
}
// Transform copies the given Go source image to the render target,
// with the same semantics as golang.org/x/image/draw.Transform, with the
// destination implicit in the Drawer target.
// - xform is the transform mapping source to destination coordinates.
// - src is the source image. Uniform does not work (or make sense) here.
// - sr is the source region, if zero full src is used; must have for Uniform.
// - op is the drawing operation: Src = copy source directly (blit),
// Over = alpha blend with existing.
// - unchanged should be true if caller knows that this image is unchanged
// from the last time it was used -- saves re-uploading to gpu.
func (dw *Drawer) Transform(xform math32.Matrix3, src image.Image, sr image.Rectangle, op draw.Op, unchanged bool) {
dw.UseGoImage(src, unchanged)
dw.TransformUsed(xform, sr, op, math32.NoFlipY)
}
// Copyright 2024 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package gpudraw draws images and fills onto a render surface or texture
// with the GPU, as for compositing the windows of an app.
package gpudraw
//go:generate core generate
import (
"image"
"image/draw"
"sync"
"cogentcore.org/core/colors"
"cogentcore.org/core/gpu"
)
// These draw.Op constants are provided so that users of this package don't
// have to explicitly import "image/draw". We also add the fill operations.
const (
// Over = alpha blend with existing content.
Over = draw.Over
// Src = copy source to destination with no blending ("blit").
Src = draw.Src
// fillOver is used internally for the fill version of Over.
fillOver = draw.Src + 1
// fillSrc is used internally for the fill version of Src.
fillSrc = draw.Src + 2
)
// AllocChunk is number of images / matrix elements to allocate
// at a time, to reduce number of reallocations.
// Should be set to the rough scale of number of items expected.
var AllocChunk = 16
// Drawer is the overall GPUDraw implementation, which draws Textures
// or Fills solid colors to a render target.
// A sequence of drawing operations is programmed for each render pass,
// between Start and End calls, which is then uploaded and performed
// in one GPU render pass, according to the recorded order of operations.
type Drawer struct {
// drawing system
System *gpu.GraphicsSystem
// opList is the list of drawing operations made on the current pass.
// This is recorded after Start and executed at End.
opList []draw.Op
// lastOpN is the number of items in the last opList, which is
// reset to 0, but can be recovered for Redraw.
lastOpN int
// images manages the list of images and their allocation
// to Value indexes.
images images
// size of current image, set via Use* methods
curImageSize image.Point
// use Lock, Unlock on Drawer for all impl routines
sync.Mutex
}
// AsGPUDrawer represents a type that can be used as a [Drawer].
type AsGPUDrawer interface {
// AsGPUDrawer returns the drawer as a [Drawer].
// It may return nil if it cannot be used as a [Drawer].
AsGPUDrawer() *Drawer
}
// NewDrawer returns a new [Drawer] configured for rendering
// to given Renderer.
func NewDrawer(gp *gpu.GPU, rd gpu.Renderer) *Drawer {
dw := &Drawer{}
dw.configSystem(gp, rd)
return dw
}
// AsGPUDrawer implements [AsGPUDrawer].
func (dw *Drawer) AsGPUDrawer() *Drawer {
return dw
}
func (dw *Drawer) Release() {
if dw.System == nil {
return
}
dw.System.Release()
dw.System = nil
}
func (dw *Drawer) Renderer() any {
if dw.System == nil {
return nil
}
return dw.System.Renderer
}
// DestSize returns the size of the render destination
func (dw *Drawer) DestSize() image.Point {
return dw.System.Renderer.Render().Format.Size
}
// DestBounds returns the bounds of the render destination
func (dw *Drawer) DestBounds() image.Rectangle {
return dw.System.Renderer.Render().Format.Bounds()
}
// Start starts recording a sequence of draw / fill actions,
// which will be performed on the GPU at End().
// This must be called prior to any Drawer operations.
func (dw *Drawer) Start() {
dw.Lock()
defer dw.Unlock()
// always use the default background color for clearing in general
dw.System.SetClearColor(colors.ToUniform(colors.Scheme.Surface))
dw.opList = dw.opList[:0]
dw.images.start()
}
// End ends image drawing rendering process on render target.
func (dw *Drawer) End() {
dw.Lock()
defer dw.Unlock()
dw.lastOpN = len(dw.opList)
if dw.lastOpN == 0 {
return
}
// write up to GPU
dw.drawAll()
dw.opList = dw.opList[:0]
}
// Occluded returns whether the render target is a surface that was occluded
// (hidden) at the last draw, so that nothing was drawn (see
// [gpu.Surface.Occluded]).
func (dw *Drawer) Occluded() bool {
if dw.System == nil { // released, as when the app quits
return false
}
sf, ok := dw.System.Renderer.(*gpu.Surface)
return ok && sf.Occluded()
}
// Redraw re-renders the last draw
func (dw *Drawer) Redraw() {
dw.Lock()
defer dw.Unlock()
if dw.lastOpN == 0 {
return
}
dw.opList = dw.opList[:dw.lastOpN]
dw.drawAll()
dw.opList = dw.opList[:0]
}
// Copyright 2024 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gpudraw
import (
"image"
"image/draw"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/gpu"
"cogentcore.org/core/gpu/drawmatrix"
"cogentcore.org/core/math32"
)
// UseGoImage uses the given Go image.Image as the source image
// for the next Draw operation. unchanged is a hint from the source
// about whether the image is unchanged from last use, in which case
// it does not need to be re-uploaded (if found).
func (dw *Drawer) UseGoImage(img image.Image, unchanged bool) {
dw.Lock()
defer dw.Unlock()
dw.curImageSize = img.Bounds().Size()
idx, exists := dw.images.use(img)
if exists && unchanged {
return
}
tvr := errors.Log1(dw.System.Vars().VarByName(1, "TexSampler"))
nv := len(tvr.Values.Values)
if idx >= nv { // new allocation
tvr.SetNValues(dw.System.Device(), dw.images.capacity)
}
tvv := tvr.Values.Values[idx]
tvv.SetFromGoImage(img, 0)
}
// UseTexture uses the given GPU resident Texture as the source image
// for the next Draw operation.
func (dw *Drawer) UseTexture(tx *gpu.Texture) {
dw.Lock()
defer dw.Unlock()
dw.curImageSize = tx.Format.Bounds().Size()
idx, _ := dw.images.use(tx)
// if exists && unchanged {
// return
// }
tvr := errors.Log1(dw.System.Vars().VarByName(1, "TexSampler"))
nv := len(tvr.Values.Values)
if idx >= nv { // new allocation
tvr.SetNValues(dw.System.Device(), dw.images.capacity)
}
tvv := tvr.Values.Values[idx]
tvv.SetFromTexture(tx)
}
// CopyUsed copies the current Use* texture to render target.
// Must have called Start and a Use* method first!
// - dp is the destination point.
// - src is the source image. If an image.Uniform, fast Fill is done.
// - sr is the source region, if zero full src is used.
// - op is the drawing operation: Src = copy source directly (blit),
// Over = alpha blend with existing.
// - flipY = flipY axis when drawing this image.
func (dw *Drawer) CopyUsed(dp image.Point, sr image.Rectangle, op draw.Op, flipY math32.YFlip) {
if sr == (image.Rectangle{}) {
sr.Max = dw.curImageSize
}
mat := math32.Matrix3{
1, 0, 0,
0, 1, 0,
float32(dp.X - sr.Min.X), float32(dp.Y - sr.Min.Y), 1,
}
dw.TransformUsed(mat, sr, op, flipY)
}
// ScaleUsed copies the current Use* texture to render target,
// scaling the region defined by src and sr to the destination
// such that sr in src-space is mapped to dr in dst-space.
// Must have called Start and a Use* method first!
// - dr is the destination rectangle; if zero uses full dest image.
// - sr is the source region; if zero uses full src image.
// - rotateDeg = rotation degrees to apply in the mapping:
// 90 = left, -90 = right, 180 = invert.
// - op is the drawing operation: Src = copy source directly (blit),
// Over = alpha blend with existing.
// - flipY = flipY axis when drawing this image.
func (dw *Drawer) ScaleUsed(dr, sr image.Rectangle, rotateDeg float32, op draw.Op, flipY math32.YFlip) {
if dr == (image.Rectangle{}) {
dr.Max = dw.DestSize()
}
if sr == (image.Rectangle{}) {
sr.Max = dw.curImageSize
}
dw.TransformUsed(drawmatrix.Transform(dr, sr, rotateDeg), sr, op, flipY)
}
// TransformUsed draws the current Use* texture to render target
// Must have called Start and a Use* method first!
// - xform is the transform mapping source to destination coordinates.
// - sr is the source region; if zero uses full src image.
// - op is the drawing operation: Src = copy source directly (blit),
// Over = alpha blend with existing.
func (dw *Drawer) TransformUsed(xform math32.Matrix3, sr image.Rectangle, op draw.Op, flipY math32.YFlip) {
dw.Lock()
defer dw.Unlock()
if sr == (image.Rectangle{}) {
sr.Max = dw.curImageSize
}
tmat := drawmatrix.Config(dw.DestSize(), xform, dw.curImageSize, sr, flipY)
dw.addOp(op, tmat)
}
// addOp adds matrix for given operation
func (dw *Drawer) addOp(op draw.Op, mtx *drawmatrix.Matrix) {
oi := len(dw.opList)
mvr := errors.Log1(dw.System.Vars().VarByName(0, "Matrix"))
mvl := mvr.Values.Values[0]
nv := mvl.DynamicN()
if oi >= nv {
mvl.SetDynamicN(nv + AllocChunk)
}
gpu.SetDynamicValueFrom(mvl, oi, []drawmatrix.Matrix{*mtx})
dw.opList = append(dw.opList, op)
}
// Copyright 2024 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gpudraw
import (
"image"
"image/color"
"image/draw"
"cogentcore.org/core/colors/cam/cie"
"cogentcore.org/core/gpu/drawmatrix"
"cogentcore.org/core/math32"
"github.com/oliverbestmann/webgpu/wgpu"
)
// Fill fills given color to render target, to given destination region dr.
// - op is the drawing operation: Src = copy source directly (blit),
// Over = alpha blend with existing
func (dw *Drawer) Fill(clr color.Color, dr image.Rectangle, op draw.Op) {
dsz := dw.DestSize()
tmat := drawmatrix.Config(dsz, math32.Identity3(), dr.Max, dr, math32.NoFlipY)
clr4 := math32.NewVector4Color(clr)
if dw.destIsSRGB() {
clr4 = linearColor(clr4)
}
clr4.ToSlice(tmat.UVP[:], 12) // last column holds color
if op == Over {
dw.addOp(fillOver, tmat)
} else {
dw.addOp(fillSrc, tmat)
}
}
// destIsSRGB returns whether the render destination has an sRGB format,
// which encodes the linear colors of the shaders as sRGB, as surfaces do.
func (dw *Drawer) destIsSRGB() bool {
switch dw.System.Renderer.Render().Format.Format {
case wgpu.TextureFormatRGBA8UnormSrgb, wgpu.TextureFormatBGRA8UnormSrgb:
return true
}
return false
}
// linearColor returns the given (premultiplied) sRGB color in linear
// space, for a fill of an sRGB destination, which encodes it back to the
// given color (which would otherwise be lighter: 18 becomes 75).
func linearColor(c math32.Vector4) math32.Vector4 {
if c.W <= 0 {
return c
}
lin := func(v float32) float32 {
return cie.SRGBToLinearComp(v/c.W) * c.W
}
return math32.Vec4(lin(c.X), lin(c.Y), lin(c.Z), c.W)
}
// Copyright 2024 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gpudraw
// imgrec records tracking data for a specific image
type imgrec struct {
// img is the image, or texture
img any
// index is where it is used in the Values list.
index int
// used flag indicates whether this image was used on last pass.
// all unused images are recycled.
used bool
}
// images manages the current set of images
type images struct {
// all records all the images used.
all map[any]*imgrec
// capacity is the total number of Values slots currently available.
capacity int
// free is a list of all the available Values indexes
// up to the current number of total Values,
// initialized in *reverse* sorted order, so the last item
// is consumed first (saves repacking the list every time,
// works like a stack).
free []int
// used is the sequential list of images used this pass,
// in one-to-one correspondence with image use in opList.
used []*imgrec
}
// init does initialization for AllocChunk total images
func (im *images) init() {
n := AllocChunk
im.all = make(map[any]*imgrec, n)
im.capacity = n
im.free = make([]int, n)
for i := range n {
im.free[i] = n - 1 - i
}
im.used = make([]*imgrec, 0, n)
}
// start gets ready for the next pass, resetting used
// flags and recycling unused indexes.
func (im *images) start() {
im.used = im.used[:0]
for _, ir := range im.all {
if !ir.used {
im.free = append(im.free, ir.index)
delete(im.all, ir.img)
} else {
ir.used = false
}
}
}
// use uses the given image, either re-using or taking a new spot.
// returns the value index to store it at, and whether it already existed.
// If there are no more free spots, then the index will be at the
// previous capacity level, which should be len(Values), at which
// point the drawer can allocate the current capacity amount.
func (im *images) use(img any) (int, bool) {
if ir, ok := im.all[img]; ok {
ir.used = true
im.used = append(im.used, ir)
return ir.index, true
}
ni := -1
nf := len(im.free)
if nf == 0 {
ni = im.capacity
im.capacity += AllocChunk
// the new indexes after ni, in reverse order, so that the next
// one is used first
for i := im.capacity - 1; i > ni; i-- {
im.free = append(im.free, i)
}
} else {
ni = im.free[nf-1]
im.free = im.free[:nf-1]
}
ir := &imgrec{img: img, index: ni, used: true}
im.all[img] = ir
im.used = append(im.used, ir)
return ni, false
}
// Copyright 2024 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gpudraw
import (
"embed"
"image"
"image/draw"
"unsafe"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/slicesx"
"cogentcore.org/core/gpu"
"cogentcore.org/core/gpu/drawmatrix"
"github.com/oliverbestmann/webgpu/wgpu"
)
//go:embed shaders/*.wgsl
var shaders embed.FS
// ConfigPipeline configures graphics settings on the pipeline
func (dw *Drawer) ConfigPipeline(pl *gpu.GraphicsPipeline, blend bool) {
pl.SetGraphicsDefaults()
pl.SetCullMode(wgpu.CullModeBack)
pl.SetFrontFace(wgpu.FrontFaceCCW)
pl.SetAlphaBlend(blend)
}
// configSystem configures GPUDraw sytem
func (dw *Drawer) configSystem(gp *gpu.GPU, rd gpu.Renderer) {
dw.opList = slicesx.SetLength(dw.opList, AllocChunk) // allocate
dw.opList = dw.opList[:0]
dw.images.init()
dw.System = gpu.NewGraphicsSystem(gp, "gpudraw", rd)
sy := dw.System
// note: requires different pipelines for src vs. over draw op modes
dopl := sy.AddGraphicsPipeline("drawover")
dw.ConfigPipeline(dopl, true)
dspl := sy.AddGraphicsPipeline("drawsrc")
dw.ConfigPipeline(dspl, false)
fopl := sy.AddGraphicsPipeline("fillover")
dw.ConfigPipeline(fopl, true)
fspl := sy.AddGraphicsPipeline("fillsrc")
dw.ConfigPipeline(fspl, false)
sh := dopl.AddShader("draw")
sh.OpenFileFS(shaders, "shaders/draw.wgsl")
dopl.AddEntry(sh, gpu.VertexShader, "vs_main")
dopl.AddEntry(sh, gpu.FragmentShader, "fs_main")
sh = dspl.AddShader("draw")
sh.OpenFileFS(shaders, "shaders/draw.wgsl")
dspl.AddEntry(sh, gpu.VertexShader, "vs_main")
dspl.AddEntry(sh, gpu.FragmentShader, "fs_main")
sh = fopl.AddShader("fill")
sh.OpenFileFS(shaders, "shaders/fill.wgsl")
fopl.AddEntry(sh, gpu.VertexShader, "vs_main")
fopl.AddEntry(sh, gpu.FragmentShader, "fs_main")
sh = fspl.AddShader("fill")
sh.OpenFileFS(shaders, "shaders/fill.wgsl")
fspl.AddEntry(sh, gpu.VertexShader, "vs_main")
fspl.AddEntry(sh, gpu.FragmentShader, "fs_main")
vgp := sy.Vars().AddVertexGroup()
mgp := sy.Vars().AddGroup(gpu.Uniform, "Matrix") // 0
tgp := sy.Vars().AddGroup(gpu.SampledTexture, "Texture") // 1
posv := vgp.Add("Pos", gpu.Float32Vector2, 0, gpu.VertexShader)
idxv := vgp.Add("Index", gpu.Uint16, 0, gpu.VertexShader)
idxv.Role = gpu.Index
mv := mgp.AddStruct("Matrix", int(unsafe.Sizeof(drawmatrix.Matrix{})), 1, gpu.VertexShader, gpu.FragmentShader)
mv.DynamicOffset = true
tgp.Add("TexSampler", gpu.TextureRGBA32, 1, gpu.FragmentShader)
vgp.SetNValues(1)
mgp.SetNValues(1)
tgp.SetNValues(AllocChunk)
sy.Config()
rectPos := posv.Values.Values[0]
gpu.SetValueFrom(rectPos, []float32{
0.0, 0.0,
0.0, 1.0,
1.0, 0.0,
1.0, 1.0})
rectIndex := idxv.Values.Values[0]
gpu.SetValueFrom(rectIndex, []uint16{0, 1, 2, 2, 1, 3})
vl := errors.Log1(sy.Vars().ValueByIndex(0, "Matrix", 0))
vl.SetDynamicN(AllocChunk)
// need a dummy texture in case only using fill
dimg := image.NewRGBA(image.Rectangle{Max: image.Point{2, 2}})
img := errors.Log1(tgp.ValueByIndex("TexSampler", 0))
img.SetFromGoImage(dimg, 0)
}
func (dw *Drawer) drawAll() error {
sy := dw.System
vars := sy.Vars()
vl := errors.Log1(vars.ValueByIndex(0, "Matrix", 0))
vl.WriteDynamicBuffer()
mvr := errors.Log1(vars.VarByName(0, "Matrix"))
mvl := mvr.Values.Values[0]
tvr := errors.Log1(vars.VarByName(1, "TexSampler"))
tvr.SetCurrentValue(0)
rp, err := sy.BeginRenderPass() // NoClear() // TODO: NoClear not working!
if errors.Log(err) != nil {
return err
}
if rp == nil { // nothing to render to (see [gpu.Surface.GetCurrentTexture])
return nil
}
imgIdx := 0
lastOp := draw.Op(-1)
_ = lastOp
for i, op := range dw.opList {
var pl *gpu.GraphicsPipeline
switch op {
case draw.Over:
pl = sy.GraphicsPipelines["drawover"]
case draw.Src:
pl = sy.GraphicsPipelines["drawsrc"]
case fillOver:
pl = sy.GraphicsPipelines["fillover"]
case fillSrc:
pl = sy.GraphicsPipelines["fillsrc"]
}
mvl.DynamicIndex = i
if op < fillOver {
tvr.SetCurrentValue(dw.images.used[imgIdx].index)
imgIdx++
}
if op != lastOp {
pl.BindPipeline(rp)
lastOp = op
} else {
pl.BindAllGroups(rp)
}
pl.BindDrawIndexed(rp)
}
rp.End()
sy.EndRenderPass(rp)
return nil
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gpu
import (
"fmt"
"image"
"image/color"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/iox/imagex"
"cogentcore.org/core/colors"
"github.com/oliverbestmann/webgpu/wgpu"
)
// GraphicsSystem manages a system of Pipelines that all share
// a common collection of Vars and Values.
// For example, this could be a collection of different
// pipelines for different material types.
// The System provides a simple top-level API for the whole
// render process.
type GraphicsSystem struct {
// optional name of this GraphicsSystem
Name string
// vars represents all the data variables used by the system,
// with one Var for each resource that is made visible to the shader,
// indexed by Group (@group) and Binding (@binding).
// Each Var has Value(s) containing specific instance values.
// Access through the System.Vars() method.
vars Vars
// GraphicsPipelines by name
GraphicsPipelines map[string]*GraphicsPipeline
// Renderer is the rendering target for this system,
// It is either a Surface or a RenderTexture.
Renderer Renderer
// CurrentCommandEncoder is the command encoder created in
// [GraphicsSystem.BeginRenderPass], and released in [GraphicsSystem.EndRenderPass].
CommandEncoder *wgpu.CommandEncoder
// logical device for this GraphicsSystem, from the Renderer.
device Device
// gpu is our GPU device, which has properties
// and alignment factors.
gpu *GPU
}
// NewGraphicsSystem returns a new GraphicsSystem, using
// the given Renderer as the render target.
func NewGraphicsSystem(gp *GPU, name string, rd Renderer) *GraphicsSystem {
sy := &GraphicsSystem{}
sy.init(gp, name, rd)
return sy
}
// System interface:
func (sy *GraphicsSystem) Vars() *Vars { return &sy.vars }
func (sy *GraphicsSystem) Device() *Device { return &sy.device }
func (sy *GraphicsSystem) GPU() *GPU { return sy.gpu }
func (sy *GraphicsSystem) Render() *Render { return sy.Renderer.Render() }
// init initializes the GraphicsSystem
func (sy *GraphicsSystem) init(gp *GPU, name string, rd Renderer) {
sy.gpu = gp
sy.Name = name
sy.Renderer = rd
sy.device = *rd.Device()
sy.vars.device = sy.device
sy.vars.sys = sy
sy.GraphicsPipelines = make(map[string]*GraphicsPipeline)
}
// WaitDone waits until device is done with current processing steps
func (sy *GraphicsSystem) WaitDone() {
sy.device.WaitDone()
}
func (sy *GraphicsSystem) Release() {
sy.WaitDone()
for _, pl := range sy.GraphicsPipelines {
pl.Release()
}
sy.GraphicsPipelines = nil
sy.vars.Release()
sy.gpu = nil
}
// AddGraphicsPipeline adds a new GraphicsPipeline to the system
func (sy *GraphicsSystem) AddGraphicsPipeline(name string) *GraphicsPipeline {
pl := NewGraphicsPipeline(name, sy)
sy.GraphicsPipelines[pl.Name] = pl
return pl
}
// SetSize must be called when the render surface (e.g., window) is resized.
// WebGPU does not have any internal mechanism for tracking this, so we
// need to drive it from external events.
func (sy *GraphicsSystem) SetSize(size image.Point) {
sy.Renderer.SetSize(size)
}
// Config configures the entire system, after Pipelines and Vars
// have been initialized. After this point, just need to set
// values for the vars, and then do render passes. This should
// not need to be called more than once.
func (sy *GraphicsSystem) Config() {
sy.vars.Config(&sy.device)
if Debug {
fmt.Printf("%s\n", sy.vars.StringDoc())
}
for _, pl := range sy.GraphicsPipelines {
pl.Config(true)
}
}
//////////////////////////////////////////////////////////////
// Set graphics options
// SetGraphicsDefaults configures all the default settings for all
// graphics rendering pipelines (not for a compute pipeline)
func (sy *GraphicsSystem) SetGraphicsDefaults() *GraphicsSystem {
for _, pl := range sy.GraphicsPipelines {
pl.SetGraphicsDefaults()
}
sy.SetClearColor(colors.ToUniform(colors.Scheme.Surface))
sy.SetClearDepthStencil(1, 0)
return sy
}
// SetTopology sets the topology of vertex position data.
// TriangleList is the default.
// Also for Strip modes, restartEnable allows restarting a new
// strip by inserting a ??
// For all pipelines, to keep graphics settings consistent.
func (sy *GraphicsSystem) SetTopology(topo Topologies, restartEnable bool) *GraphicsSystem {
for _, pl := range sy.GraphicsPipelines {
pl.SetTopology(topo, restartEnable)
}
return sy
}
// SetCullMode sets the face culling mode.
func (sy *GraphicsSystem) SetCullMode(mode wgpu.CullMode) *GraphicsSystem {
for _, pl := range sy.GraphicsPipelines {
pl.SetCullMode(mode)
}
return sy
}
// SetFrontFace sets the winding order for what counts as a front face.
func (sy *GraphicsSystem) SetFrontFace(face wgpu.FrontFace) *GraphicsSystem {
for _, pl := range sy.GraphicsPipelines {
pl.SetFrontFace(face)
}
return sy
}
// SetLineWidth sets the rendering line width -- 1 is default.
func (sy *GraphicsSystem) SetLineWidth(lineWidth float32) *GraphicsSystem {
for _, pl := range sy.GraphicsPipelines {
pl.SetLineWidth(lineWidth)
}
return sy
}
// SetAlphaBlend determines the alpha (transparency) blending function:
// either 1-source alpha (alphaBlend) or no blending:
// new color overwrites old. Default is alphaBlend = true
// For all pipelines, to keep graphics settings consistent.
func (sy *GraphicsSystem) SetAlphaBlend(alphaBlend bool) *GraphicsSystem {
for _, pl := range sy.GraphicsPipelines {
pl.SetAlphaBlend(alphaBlend)
}
return sy
}
// SetClearColor sets the RGBA colors to set when starting new render
// For all pipelines, to keep graphics settings consistent.
func (sy *GraphicsSystem) SetClearColor(c color.Color) *GraphicsSystem {
sy.Render().ClearColor = c
return sy
}
// SetClearDepthStencil sets the depth and stencil values when starting new render
// For all pipelines, to keep graphics settings consistent.
func (sy *GraphicsSystem) SetClearDepthStencil(depth float32, stencil uint32) *GraphicsSystem {
rd := sy.Render()
rd.ClearDepth = depth
rd.ClearStencil = stencil
return sy
}
//////// Rendering
// NewCommandEncoder returns a new CommandEncoder for encoding
// rendering commands. This is automatically called by
// BeginRenderPass and the result maintained in CurrentCommandEncoder.
func (sy *GraphicsSystem) NewCommandEncoder() (*wgpu.CommandEncoder, error) {
cmd, err := sy.device.Device.TryCreateCommandEncoder(nil)
if errors.Log(err) != nil {
return nil, err
}
return cmd, nil
}
func (sy *GraphicsSystem) beginRenderPass() (*Render, *wgpu.TextureView, error) {
rd := sy.Renderer
view, err := rd.GetCurrentTexture()
if view == nil || errors.Log(err) != nil {
// Nothing is rendered, as the surface is occluded (see
// [Surface.GetCurrentTexture]), but the writes to the buffers and
// textures for this frame were made already: they are submitted,
// with no commands, so that they are done and their staging memory
// is freed. The queue keeps them until a submit, so they piled up
// with every frame of a window that stayed covered (gigabytes in
// seconds, for a window updated continuously).
sy.device.Queue.Submit()
return nil, nil, err
}
cmd, err := sy.NewCommandEncoder()
if errors.Log(err) != nil {
return nil, nil, err
}
sy.CommandEncoder = cmd
return rd.Render(), view, nil
}
// BeginRenderPass adds commands to the given command buffer
// to start the render pass using the Renderer configured for
// this system, and returns the encoder object to which further
// rendering commands should be added.
// Call [GraphicsSystem.EndRenderPass] when done.
// This version Clears the target texture first, using ClearValues.
// The RenderPassEncoder can be nil AND the err also nil, which
// indicates the need to reconfigure the surface and try again.
func (sy *GraphicsSystem) BeginRenderPass() (*wgpu.RenderPassEncoder, error) {
rd, view, err := sy.beginRenderPass()
if view == nil || errors.Log(err) != nil {
return nil, err
}
return rd.BeginRenderPass(sy.CommandEncoder, view), nil
}
// BeginRenderPassNoClear adds commands to the given command buffer
// to start the render pass using the Renderer configured for
// this system, and returns the encoder object to which further
// rendering commands should be added.
// Call [GraphicsSystem.EndRenderPass] when done.
// This version does NOT clear the target texture first,
// so the prior render output is carried over.
// The RenderPassEncoder can be nil AND the err also nil, which
// indicates the need to reconfigure the surface and try again.
func (sy *GraphicsSystem) BeginRenderPassNoClear() (*wgpu.RenderPassEncoder, error) {
rd, view, err := sy.beginRenderPass()
if view == nil || errors.Log(err) != nil {
return nil, err
}
return rd.BeginRenderPassNoClear(sy.CommandEncoder, view), nil
}
// SubmitRender submits the current render commands to the device
// Queue and releases the [GraphicsSystem.CurrentCommandEncoder] and the given
// RenderPassEncoder. You must call rp.End prior to calling this.
// Can insert other commands after rp.End, e.g., to copy the rendered image,
// prior to calling SubmitRender.
func (sy *GraphicsSystem) SubmitRender(rp *wgpu.RenderPassEncoder) error {
cmd := sy.CommandEncoder
sy.CommandEncoder = nil
rp.Release() // must happen before Finish
cmdBuffer, err := cmd.TryFinish(nil)
if errors.Log(err) != nil {
return err
}
sy.device.Queue.Submit(cmdBuffer)
cmdBuffer.Release()
cmd.Release()
for _, pl := range sy.GraphicsPipelines {
pl.releaseOldBindGroups()
}
return nil
}
// EndRenderPass ends the render pass started by [GraphicsSystem.BeginRenderPass],
// by calling [GraphicsSystem.SubmitRender] to submit the rendering commands to the
// device, and calling Present() on the Renderer to show results.
func (sy *GraphicsSystem) EndRenderPass(rp *wgpu.RenderPassEncoder) {
sy.SubmitRender(rp)
sy.Renderer.Present()
}
// EndRenderPassGrabImage ends the render pass started by [GraphicsSystem.BeginRenderPass],
// as in [GraphicsSystem.EndRenderPass]
func (sy *GraphicsSystem) EndRenderPassGrabImage(rp *wgpu.RenderPassEncoder) *image.NRGBA {
rt, ok := sy.Renderer.(*RenderTexture)
if !ok {
sy.EndRenderPass(rp)
return nil
}
rt.ReadFrame(sy.CommandEncoder)
sy.EndRenderPass(rp)
img := errors.Log1(rt.CurrentFrame().ReadGoImage())
return img
}
// AssertImage asserts the currend render image at the given
// filename using [imagex.Assert].
// It runs [GraphicsSystem.EndRenderPassGrabImage].
func (sy *GraphicsSystem) AssertImage(t imagex.TestingT, rp *wgpu.RenderPassEncoder, filename string) {
img := sy.EndRenderPassGrabImage(rp)
if img == nil {
t.Errorf("GraphicsSystem.AssertImage: failure getting image")
return
}
imagex.Assert(t, img, filename)
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gpu
import (
"image"
"cogentcore.org/core/math32"
)
// SRGBToLinearComp converts an sRGB rgb component to linear space (removes gamma).
// Used in converting from sRGB to XYZ colors.
func SRGBToLinearComp(srgb float32) float32 {
if srgb <= 0.04045 {
return srgb / 12.92
}
return math32.Pow((srgb+0.055)/1.055, 2.4)
}
// SRGBFromLinearComp converts an sRGB rgb linear component
// to non-linear (gamma corrected) sRGB value
// Used in converting from XYZ to sRGB.
func SRGBFromLinearComp(lin float32) float32 {
if lin <= 0.0031308 {
return 12.92 * lin
}
return 1.055*math32.Pow(lin, 1/2.4) - 0.055
}
// SRGBToLinear converts set of sRGB components to linear values,
// removing gamma correction.
func SRGBToLinear(r, g, b float32) (rl, gl, bl float32) {
rl = SRGBToLinearComp(r)
gl = SRGBToLinearComp(g)
bl = SRGBToLinearComp(b)
return
}
// SRGBFromLinear converts set of sRGB components from linear values,
// adding gamma correction.
func SRGBFromLinear(rl, gl, bl float32) (r, g, b float32) {
r = SRGBFromLinearComp(rl)
g = SRGBFromLinearComp(gl)
b = SRGBFromLinearComp(bl)
return
}
// ImgCompToUint8 converts a color component in the 0-1 range to a uint8,
// clamped to that range, and rounded.
func ImgCompToUint8(val float32) uint8 {
val = math32.Clamp(val, 0, 1)
return uint8(val*float32(0xff) + 0.5)
}
// TextureSRGBFromLinear returns a sRGB colorspace version of given linear
// colorspace image
func TextureSRGBFromLinear(img *image.RGBA) *image.RGBA {
out := image.NewRGBA(img.Rect)
sz := len(img.Pix)
tof := 1.0 / float32(0xff)
for i := 0; i < sz; i += 4 {
r := float32(img.Pix[i]) * tof
g := float32(img.Pix[i+1]) * tof
b := float32(img.Pix[i+2]) * tof
a := img.Pix[i+3]
rs, gs, bs := SRGBFromLinear(r, g, b)
out.Pix[i] = ImgCompToUint8(rs)
out.Pix[i+1] = ImgCompToUint8(gs)
out.Pix[i+2] = ImgCompToUint8(bs)
out.Pix[i+3] = a
}
return out
}
// TextureSRGBToLinear returns a linear colorspace version of sRGB
// colorspace image
func TextureSRGBToLinear(img *image.RGBA) *image.RGBA {
out := image.NewRGBA(img.Rect)
sz := len(img.Pix)
tof := 1.0 / float32(0xff)
for i := 0; i < sz; i += 4 {
r := float32(img.Pix[i]) * tof
g := float32(img.Pix[i+1]) * tof
b := float32(img.Pix[i+2]) * tof
a := img.Pix[i+3]
rs, gs, bs := SRGBToLinear(r, g, b)
out.Pix[i] = ImgCompToUint8(rs)
out.Pix[i+1] = ImgCompToUint8(gs)
out.Pix[i+2] = ImgCompToUint8(bs)
out.Pix[i+3] = a
}
return out
}
// SetTextureSRGBFromLinear sets in place the pixel values to sRGB colorspace
// version of given linear colorspace image.
// This directly modifies the given image!
func SetTextureSRGBFromLinear(img *image.RGBA) {
sz := len(img.Pix)
tof := 1.0 / float32(0xff)
for i := 0; i < sz; i += 4 {
r := float32(img.Pix[i]) * tof
g := float32(img.Pix[i+1]) * tof
b := float32(img.Pix[i+2]) * tof
a := img.Pix[i+3]
rs, gs, bs := SRGBFromLinear(r, g, b)
img.Pix[i] = ImgCompToUint8(rs)
img.Pix[i+1] = ImgCompToUint8(gs)
img.Pix[i+2] = ImgCompToUint8(bs)
img.Pix[i+3] = a
}
}
// SetTextureSRGBToLinear sets in place the pixel values to linear colorspace
// version of sRGB colorspace image.
// This directly modifies the given image!
func SetTextureSRGBToLinear(img *image.RGBA) {
sz := len(img.Pix)
tof := 1.0 / float32(0xff)
for i := 0; i < sz; i += 4 {
r := float32(img.Pix[i]) * tof
g := float32(img.Pix[i+1]) * tof
b := float32(img.Pix[i+2]) * tof
a := img.Pix[i+3]
rs, gs, bs := SRGBToLinear(r, g, b)
img.Pix[i] = ImgCompToUint8(rs)
img.Pix[i+1] = ImgCompToUint8(gs)
img.Pix[i+2] = ImgCompToUint8(bs)
img.Pix[i+3] = a
}
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gpu
import (
"io/fs"
"log/slog"
"path"
"slices"
"strings"
"cogentcore.org/core/base/stringsx"
)
// IncludeFS processes #include "file" statements in
// the given code string, using the given file system
// and default path to locate the included files.
func IncludeFS(fsys fs.FS, fpath, code string) string {
included := map[string]struct{}{}
return includeFS(fsys, fpath, code, included)
}
func includeFS(fsys fs.FS, fpath, code string, included map[string]struct{}) string {
fl := stringsx.SplitLines(code)
nl := len(fl)
for li := range nl {
ln := fl[li]
if !strings.HasPrefix(ln, `#include "`) {
continue
}
fn := ln[10:]
before, _, ok := strings.Cut(fn, `"`)
if !ok {
slog.Error("IncludeFS: malformed #include: no final quote")
continue
}
fname := before
fp := path.Join(fpath, fname)
if _, ok := included[fname]; ok {
fl[li] = "// " + ln
continue
}
if _, ok := included[fp]; ok {
fl[li] = "// " + ln
continue
}
inc := fname
b, err := fs.ReadFile(fsys, fname)
if err != nil {
b, err = fs.ReadFile(fsys, fp)
if err != nil {
slog.Error("IncludeFS: could not find include", "file", fname, "fpath", fpath)
continue
}
inc = fp
}
ins := includeFS(fsys, fpath, string(b), included)
ol := stringsx.SplitLines(ins)
fl[li] = "// " + ln
nl += len(ol)
fl = slices.Insert(fl, li+1, ol...)
li += len(ol)
included[inc] = struct{}{}
}
return strings.Join(fl, "\n")
}
// Copyright 2024 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package phong
import (
"cogentcore.org/core/base/errors"
"cogentcore.org/core/gpu"
"cogentcore.org/core/math32"
)
// Camera contains the camera view and projection matricies, for uniform uploading.
type Camera struct {
// View Camera: transforms world into camera-centered, 3D coordinates.
View math32.Matrix4
// Projection Camera: transforms camera coords into 2D render coordinates.
Projection math32.Matrix4
}
// SetCamera the camera view and projection matrixes, and updates
// uniform data, so they are ready to use.
func (ph *Phong) SetCamera(view, projection *math32.Matrix4) {
ph.Camera.View = *view
ph.Camera.Projection = *projection
vl := errors.Log1(ph.System.Vars().ValueByIndex(int(CameraGroup), "Camera", 0))
gpu.SetValueFrom(vl, []Camera{{View: *view, Projection: *projection}})
ph.cameraUpdated = true
}
// CameraViewMat returns the camera view matrix, based position
// of camera facing at target position, with given up vector.
func CameraViewMat(pos, target, up math32.Vector3) *math32.Matrix4 {
var lookq math32.Quat
lookq.SetFromRotationMatrix(math32.NewLookAt(pos, target, up))
scale := math32.Vec3(1, 1, 1)
var cview math32.Matrix4
cview.SetTransform(pos, lookq, scale)
view, _ := cview.Inverse()
return view
}
// Copyright 2024 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package phong
import (
"image/color"
"cogentcore.org/core/math32"
)
// Tiling are the texture tiling parameters
type Tiling struct {
// how often to repeat the texture in each direction
Repeat math32.Vector2
// offset for when to start the texure in each direction
Offset math32.Vector2
}
// Defaults sets default tiling params if not yet initialized
func (tl *Tiling) Defaults() {
if tl.Repeat == (math32.Vector2{}) {
tl.Repeat.Set(1, 1)
}
}
// Colors are the material colors with padding for direct uploading to shader.
type Colors struct {
// main color of surface, used for both ambient and diffuse color
// in standard Phong model. Alpha component determines transparency.
// Note that transparent objects require more complex rendering.
Color math32.Vector4
// ShinyBright has shininess and brightness factors:
//
// X = shininess spread factor (30 default), which determines
// how focally the surface shines back directional light, which
// is an exponential factor, where 0 = very broad diffuse reflection,
// and higher values (typically max of 128) have a smaller more
// focal specular reflection.
//
// Y = shine reflection factor (1 default), which determines how much
// of the incident light is reflected back (0 = no shine).
//
// Z = brightness factor (1 default), which is an overall multiplier
// on final computed color value, which can be used to tune the
// overall brightness of various surfaces relative to each other
// for a given set of lighting parameters.
ShinyBright math32.Vector4
// color that surface emits independent of any lighting,
// i.e., glow. Can be used for marking lights with an object.
Emissive math32.Vector4
// texture tiling repeat and offset factors.
Tiling Tiling
}
// NewColors returns a new Colors with given values.
// Texture defaults to using full texture with 0 offset.
func NewColors(clr, emis color.Color, shiny, reflect, bright float32) *Colors {
cl := &Colors{}
cl.SetColors(clr, emis, shiny, reflect, bright)
cl.Tiling.Defaults()
return cl
}
func (cl *Colors) Defaults() {
cl.ShinyBright.X = 30
cl.ShinyBright.Y = 1
cl.ShinyBright.Z = 1
}
// SetColors sets the colors from standard Go colors.
func (cl *Colors) SetColors(clr, emis color.Color, shiny, reflect, bright float32) *Colors {
cl.Color = math32.NewVector4Color(clr).SRGBToLinear()
cl.Emissive = math32.NewVector4Color(emis).SRGBToLinear()
cl.ShinyBright.X = shiny
cl.ShinyBright.Y = reflect
cl.ShinyBright.Z = bright
return cl
}
// UseFullTexture sets the texture parameters
// to render the full texture: repeat = 1,1; offset = 0,0
func (cl *Colors) UseFullTexture() *Colors {
cl.Tiling.Repeat = math32.Vec2(1, 1)
cl.Tiling.Offset = math32.Vec2(0, 0)
return cl
}
// SetTilingRepeat sets how often to repeat the texture in each direction
func (cl *Colors) SetTilingRepeat(repeat math32.Vector2) *Colors {
cl.Tiling.Repeat = repeat
return cl
}
// SetTilingOffset sets texture start offsets in each direction
func (cl *Colors) SetTilingOffset(offset math32.Vector2) *Colors {
cl.Tiling.Offset = offset
return cl
}
// Copyright 2024 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package phong
import (
"cogentcore.org/core/base/errors"
"cogentcore.org/core/gpu"
"cogentcore.org/core/math32"
)
// NLights is the number of different lights active.
type NLights struct {
Ambient int32
Directional int32
Point int32
Spot int32
}
func (nl *NLights) Reset() {
nl.Ambient = 0
nl.Directional = 0
nl.Point = 0
nl.Spot = 0
}
// Ambient provides diffuse uniform lighting. Typically only one of these.
type Ambient struct {
// color of light, which multiplies ambient color of materials.
Color math32.Vector3
pad0 float32
}
// Directional is directional light, which is assumed to project light toward
// the origin based on its position, with no attenuation, like the Sun.
// For rendering, the position is negated and normalized to get the direction
// vector (i.e., absolute distance doesn't matter).
type Directional struct {
// color of light at full intensity.
Color math32.Vector3
pad0 float32
// position of light vector. Think of it shining down from
// this position toward the origin, i.e., the negation of
// this position is the vector.
Pos math32.Vector3
pad1 float32
}
// Point is an omnidirectional light with a position
// and associated decay factors, which divide the light
// intensity as a function of linear and quadratic distance.
// The quadratic factor dominates at longer distances.
type Point struct {
// color of light a full intensity.
Color math32.Vector3
pad0 float32
// position of light in world coordinates.
Pos math32.Vector3
pad1 float32
// X = Linear distance decay factor (default .01).
// Y = Quadratic distance quadratic decay factor
// (default .001, dominates at longer distances)
Decay math32.Vector3
pad2 float32
}
// Spot is a spotlight: a light with a position and direction and
// associated decay factors and angles,
// which divide the light intensity as a function of
// linear and quadratic distance.
// The quadratic factor dominates at longer distances.
type Spot struct {
// color of light a full intensity.
Color math32.Vector3
pad0 float32
// position of light in world coordinates.
Pos math32.Vector3
pad1 float32
// direction of light vector.
Dir math32.Vector3
pad2 float32
// X = Angular decay, in degrees (15 default)
// Y = CutAngle is cutoff angle in degrees beyond which no light (45 default).
// Z = LinDecay distance linear decay (.01 default)
// W = QuadDecay distance Distance quadratic decay factor (0.001 default),
// which dominates at longer distances
Decay math32.Vector4
}
// ResetLights resets number of lights to 0 -- for reconfig
func (ph *Phong) ResetLights() {
ph.lightsUpdated = true
ph.NLights.Reset()
}
// AddAmbient adds Ambient light at given position
func (ph *Phong) AddAmbient(color math32.Vector3) {
ph.SetAmbient(int(ph.NLights.Ambient), color)
ph.NLights.Ambient++
ph.lightsUpdated = true
}
// SetAmbient sets Ambient light at index to given position
func (ph *Phong) SetAmbient(idx int, color math32.Vector3) {
ph.Ambient[idx].Color = color
ph.lightsUpdated = true
}
// AddDirectional adds directional light
func (ph *Phong) AddDirectional(color, pos math32.Vector3) {
ph.SetDirectional(int(ph.NLights.Directional), color, pos)
ph.NLights.Directional++
ph.lightsUpdated = true
}
// SetDirectional sets directional light at given index
func (ph *Phong) SetDirectional(idx int, color, pos math32.Vector3) {
ph.Directional[idx].Color = color
ph.Directional[idx].Pos = pos
ph.lightsUpdated = true
}
// AddPoint adds point light.
// Defaults: linDecay=.1, quadDecay=.01
func (ph *Phong) AddPoint(color, pos math32.Vector3, linDecay, quadDecay float32) {
ph.SetPoint(int(ph.NLights.Point), color, pos, linDecay, quadDecay)
ph.NLights.Point++
ph.lightsUpdated = true
}
// SetPoint sets point light at given index.
// Defaults: linDecay=.1, quadDecay=.01
func (ph *Phong) SetPoint(idx int, color, pos math32.Vector3, linDecay, quadDecay float32) {
ph.Point[idx].Color = color
ph.Point[idx].Pos = pos
ph.Point[idx].Decay = math32.Vector3{X: linDecay, Y: quadDecay}
ph.lightsUpdated = true
}
// AddSpot adds spot light
// Defaults: angDecay=15, cutAngle=45 (max 90), linDecay=.01, quadDecay=0.001
func (ph *Phong) AddSpot(color, pos, dir math32.Vector3, angDecay, cutAngle, linDecay, quadDecay float32) {
ph.SetSpot(int(ph.NLights.Spot), color, pos, dir, angDecay, cutAngle, linDecay, quadDecay)
ph.NLights.Spot++
ph.lightsUpdated = true
}
// SetSpot sets spot light at given index
// Defaults: angDecay=15, cutAngle=45 (max 90), linDecay=.01, quadDecay=0.001
func (ph *Phong) SetSpot(idx int, color, pos, dir math32.Vector3, angDecay, cutAngle, linDecay, quadDecay float32) {
ph.Spot[idx].Color = color
ph.Spot[idx].Pos = pos
ph.Spot[idx].Dir = dir
ph.Spot[idx].Decay = math32.Vec4(angDecay, cutAngle, linDecay, quadDecay)
ph.lightsUpdated = true
}
// configLights configures the rendering for the lights that have been added.
func (ph *Phong) configLights() {
if !ph.lightsUpdated {
return
}
ph.lightsUpdated = false
sy := ph.System
vg := sy.Vars().Groups[int(LightGroup)]
gpu.SetValueFrom(errors.Log1(vg.ValueByIndex("NLights", 0)), []NLights{ph.NLights})
gpu.SetValueFrom(errors.Log1(vg.ValueByIndex("Ambient", 0)), ph.Ambient[:])
gpu.SetValueFrom(errors.Log1(vg.ValueByIndex("Directional", 0)), ph.Directional[:])
gpu.SetValueFrom(errors.Log1(vg.ValueByIndex("Point", 0)), ph.Point[:])
gpu.SetValueFrom(errors.Log1(vg.ValueByIndex("Spot", 0)), ph.Spot[:])
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package phong
import (
"fmt"
"log"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/gpu"
"cogentcore.org/core/gpu/shape"
)
// ResetMeshes resets the meshes for reconfiguring.
func (ph *Phong) ResetMeshes() {
ph.Lock()
defer ph.Unlock()
ph.meshes.Reset()
vgp := ph.System.Vars().VertexGroup()
vgp.SetNValues(1)
}
// SetMesh sets a Mesh using the [shape.Mesh] interface for the source
// of the mesh data, and sets the values directly.
// If Mesh already exists, then data is updated.
// It is ready for [UseMesh] after this point.
func (ph *Phong) SetMesh(name string, mesh shape.Mesh) {
ph.Lock()
defer ph.Unlock()
vgp := ph.System.Vars().VertexGroup()
md := shape.NewMeshData(mesh)
idx, ok := ph.meshes.IndexByKeyTry(name)
if !ok {
idx = ph.meshes.Len()
ph.meshes.Set(name, md)
vgp.SetNValues(ph.meshes.Len())
} else {
ph.meshes.Values[idx] = md
}
ph.configMesh(md, idx)
gpu.SetValueFrom(errors.Log1(vgp.ValueByIndex("Pos", idx)), md.Vertex)
gpu.SetValueFrom(errors.Log1(vgp.ValueByIndex("Normal", idx)), md.Normal)
gpu.SetValueFrom(errors.Log1(vgp.ValueByIndex("TexCoord", idx)), md.TexCoord)
if md.HasColor {
gpu.SetValueFrom(errors.Log1(vgp.ValueByIndex("VertexColor", idx)), md.Colors)
} else if idx == 0 { // set dummy vertexcolor for first guy
gpu.SetValueFrom(errors.Log1(vgp.ValueByIndex("VertexColor", idx)), make([]float32, md.NumVertex*4))
}
gpu.SetValueFrom(errors.Log1(vgp.ValueByIndex("Index", idx)), md.Index)
}
func (ph *Phong) configMesh(md *shape.MeshData, idx int) {
vgp := ph.System.Vars().VertexGroup()
errors.Log1(vgp.ValueByIndex("Pos", idx)).SetDynamicN(md.NumVertex)
errors.Log1(vgp.ValueByIndex("Normal", idx)).SetDynamicN(md.NumVertex)
errors.Log1(vgp.ValueByIndex("TexCoord", idx)).SetDynamicN(md.NumVertex)
errors.Log1(vgp.ValueByIndex("Index", idx)).SetDynamicN(md.NumIndex)
vc := errors.Log1(vgp.ValueByIndex("VertexColor", idx))
if md.HasColor {
vc.SetDynamicN(md.NumVertex)
} else {
vc.SetDynamicN(1)
}
}
// UseMesh selects mesh by name for current render step.
// Mesh must have been added / updated via SetMesh method.
// If mesh has per-vertex colors, these are selected for rendering,
// and texture is turned off. UseTexture* after this to override.
func (ph *Phong) UseMesh(name string) error {
ph.Lock()
defer ph.Unlock()
idx, ok := ph.meshes.IndexByKeyTry(name)
if !ok {
err := fmt.Errorf("phong:UseMeshName -- name not found: %s", name)
if gpu.Debug {
log.Println(err)
}
return err
}
return ph.useMeshIndex(idx)
}
// useMeshIndex selects mesh by index for current render step.
// If mesh has per-vertex colors, these are selected for rendering,
// and texture is turned off. UseTexture* after this to override.
func (ph *Phong) useMeshIndex(idx int) error {
sy := ph.System
md := ph.meshes.Values[idx]
sy.Vars().SetCurrentValue(gpu.VertexGroup, "Pos", idx)
sy.Vars().SetCurrentValue(gpu.VertexGroup, "Normal", idx)
sy.Vars().SetCurrentValue(gpu.VertexGroup, "TexCoord", idx)
sy.Vars().SetCurrentValue(gpu.VertexGroup, "Index", idx)
if md.HasColor {
sy.Vars().SetCurrentValue(gpu.VertexGroup, "VertexColor", idx)
ph.UseVertexColor = true
ph.UseCurTexture = false
} else {
sy.Vars().SetCurrentValue(gpu.VertexGroup, "VertexColor", 0)
ph.UseVertexColor = false
}
return nil
}
// Copyright 2024 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package phong
import (
"fmt"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/gpu"
"cogentcore.org/core/math32"
)
// Object is the object-specific data: Colors and transform Matrix.
// It must be updated on a per-object basis prior to each render pass.
// It is 8 vec4 in size = 8 * 4 * 4 = 128 bytes.
type Object struct {
Colors
// Matrix specifies the transformation matrix for this specific Object ("model").
Matrix math32.Matrix4
// WorldMatrix is the transpose of the inverse of the
// Camera.View matrix * Object "model" Matrix, used to
// compute the proper normals. WebGPU does not
// have the transpose function. This is managed entirely by the
// Phong system and is not set by the user.
worldMatrix math32.Matrix4
}
// NewObject returns a new object with given matrix and colors.
func NewObject(mtx *math32.Matrix4, clr *Colors) *Object {
ob := &Object{}
ob.Matrix = *mtx
ob.Colors = *clr
return ob
}
// SetObject sets Object data with given unique name identifier.
// If object already exists, then data is updated if different.
func (ph *Phong) SetObject(name string, ob *Object) {
ph.Lock()
defer ph.Unlock()
idx, ok := ph.objects.IndexByKeyTry(name)
if !ok {
ph.objects.Set(name, ob)
ph.objectUpdated = true
// note: allocation of DynamicN happens in updateObjects pass.
return
}
cob := ph.objects.Values[idx]
if *ob != *cob {
ph.objects.Values[idx] = ob
ph.objectUpdated = true
}
}
// ResetObjects resets the objects for reconfiguring
func (ph *Phong) ResetObjects() {
ph.Lock()
defer ph.Unlock()
ph.objects.Reset()
// updateObjects is auto-resetting
}
func (ph *Phong) setWorldMatrix(ob *Object) {
mvm := math32.Matrix3FromMatrix4(ph.Camera.View.Mul(&ob.Matrix))
nm := mvm.Inverse().Transpose()
ob.worldMatrix.SetFromMatrix3(&nm)
}
// UseObject selects object by name for current render step.
// Object must have already been added / updated via [SetObject].
// If object has per-vertex colors, these are selected for rendering,
// and texture is turned off. UseTexture* after this to override.
func (ph *Phong) UseObject(name string) error {
ph.Lock()
defer ph.Unlock()
idx, ok := ph.objects.IndexByKeyTry(name)
if !ok {
return errors.Log(fmt.Errorf("phong:UseObject: name not found: %s", name))
}
ph.System.Vars().SetDynamicIndex(int(ObjectGroup), "Object", idx)
return nil
}
// UseObjectIndex selects object by index for current render step.
// If object has per-vertex colors, these are selected for rendering,
// and texture is turned off. UseTexture* after this to override.
func (ph *Phong) UseObjectIndex(idx int) error {
ph.Lock()
defer ph.Unlock()
ph.System.Vars().SetDynamicIndex(int(ObjectGroup), "Object", idx)
return nil
}
// updateObjects updates the object specific data to the GPU,
// updating the WorldMatrix based on current Camera settings first.
// This is called in the RenderStart function.
func (ph *Phong) updateObjects() {
if !ph.objectUpdated && !ph.cameraUpdated {
return
}
vl := errors.Log1(ph.System.Vars().ValueByIndex(int(ObjectGroup), "Object", 0))
vl.SetDynamicN(ph.objects.Len())
for i, ob := range ph.objects.Values {
ph.setWorldMatrix(ob)
gpu.SetDynamicValueFrom(vl, i, []Object{*ob})
}
vl.WriteDynamicBuffer()
ph.objectUpdated = false
ph.cameraUpdated = false
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package phong renders 3D meshes with Blinn-Phong lighting on the GPU, with
// lights, materials, textures, and a camera.
package phong
//go:generate core generate
import (
"image"
"sync"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/keylist"
"cogentcore.org/core/gpu"
"cogentcore.org/core/gpu/shape"
"github.com/oliverbestmann/webgpu/wgpu"
)
// MaxLights is upper limit on number of any given type of light
const MaxLights = 8
// Phong implements standard Blinn-Phong rendering pipelines
// in a gpu GraphicsSystem.
// Add Lights and call SetMesh, SetTexture, SetObject to config.
//
// Rendering starts with RenderStart, followed by Use* calls
// to specify the render parameters for each item,
// followed by the Render() method that calls the proper
// pipeline's render methods.
type Phong struct {
// The current camera view and projection matricies.
// This is used for updating the object WorldMatrix.
Camera Camera
// number of each type of light
NLights NLights
// ambient lights
Ambient [MaxLights]Ambient
// directional lights
Directional [MaxLights]Directional
// point lights
Point [MaxLights]Point
// spot lights
Spot [MaxLights]Spot
// a texture was selected for next draw via [UseTexture].
// if true, overrides other options.
UseCurTexture bool
// a per-vertex color was selected for next draw.
UseVertexColor bool
// render using wireframe instead of filled polygons.
// this must be set prior to configuring the Phong rendering system.
// note: not currently supported in WebGPU.
Wireframe bool `default:"false"`
// Meshes holds all of the mesh data, managed by [SetMesh],
// [ResetMeshes] methods.
meshes keylist.List[string, *shape.MeshData]
// Textures holds all of the texture images, managed by [SetTexture],
// [ResetTextures] methods.
textures keylist.List[string, *Texture]
// Objects holds per-object data, keyed by unique name / path id.
// All objects must be added in a pre-Render pass via [SetObject].
objects keylist.List[string, *Object]
// cameraUpdated is set whenver SetCamera is called.
// it triggers an up date of the object's WorldMatrix.
cameraUpdated bool
// objectUpdated is set whenever SetObject is called,
// and cleared when the objects have been updated to the GPU.
objectUpdated bool
// lightsUpdated indicates a change has been made to lights.
lightsUpdated bool
// rendering system
System *gpu.GraphicsSystem
// overall lock on Phong operations, use Lock, Unlock on Phong
sync.Mutex
}
// NewPhong returns a new Phong system that is ready to be
// configured by calls to SetMesh, SetTexture, SetObject,
// in addition to adding lights.
// Renderer can either be a Surface or a RenderTexture.
func NewPhong(gp *gpu.GPU, rd gpu.Renderer) *Phong {
ph := &Phong{}
ph.System = gpu.NewGraphicsSystem(gp, "phong", rd)
ph.configGraphicsSystem()
return ph
}
// Release should be called to release all the GPU resources.
func (ph *Phong) Release() {
ph.Lock()
defer ph.Unlock()
if ph.System == nil {
return
}
ph.System.Release()
ph.System = nil
ph.meshes.Reset()
ph.textures.Reset()
ph.objects.Reset()
}
// ConfigLights can be called after initial Config
// whenver the Lights data has changed, to sync changes
// up to the GPU.
func (ph *Phong) ConfigLights() *Phong {
ph.Lock()
defer ph.Unlock()
ph.configLights()
return ph
}
// ResetAll resets all the dynamic resources: Objects, Meshes, Textures
// and Lights.
func (ph *Phong) ResetAll() {
ph.ResetObjects()
ph.ResetMeshes()
ph.ResetTextures()
ph.ResetLights()
}
///////////////////////////////////////////////////
// Rendering
// RenderStart starts the render pass, returning the
// RenderPassEncoder used for encoding the rendering commands
// for this pass.
// This also ensures that all updated object data from SetObject*
// calls is transferred to the GPU.
func (ph *Phong) RenderStart() (*wgpu.RenderPassEncoder, error) {
ph.Lock()
defer ph.Unlock()
ph.configLights() // if needed
ph.configDummyTexture() // if needed
ph.updateObjects()
if rt, ok := ph.System.Renderer.(*gpu.RenderTexture); ok {
rt.CurrentFrame().ConfigReadBuffer()
}
return ph.System.BeginRenderPass()
}
// RenderEnd ends the render pass. Must be paired after RenderStart.
func (ph *Phong) RenderEnd(rp *wgpu.RenderPassEncoder) {
rp.End()
ph.System.EndRenderPass(rp)
}
// RenderEndGrabImage grabs the rendered image from rendering.
// The command to read the image must be inserted at the end of the
// render commands, so this is an alternative to standard RenderEnd.
// This only works if the system Renderer is a [RenderTexture],
// otherwise it will return nil.
func (ph *Phong) RenderEndGrabImage(rp *wgpu.RenderPassEncoder) *image.NRGBA {
rp.End()
sy := ph.System
rt, ok := sy.Renderer.(*gpu.RenderTexture)
if !ok {
sy.EndRenderPass(rp)
return nil
}
rt.ReadFrame(sy.CommandEncoder)
sy.EndRenderPass(rp)
img := errors.Log1(rt.CurrentFrame().ReadGoImage())
return img
}
// Render does one step of rendering given current Use* settings,
// which can be updated in between subsequent Render calls.
func (ph *Phong) Render(rp *wgpu.RenderPassEncoder) {
ph.Lock()
defer ph.Unlock()
switch {
case ph.UseCurTexture:
ph.RenderTexture(rp)
case ph.UseVertexColor:
ph.RenderVertexColor(rp)
default:
ph.RenderOneColor(rp)
}
}
// RenderOneColor renders current settings to onecolor pipeline.
func (ph *Phong) RenderOneColor(rp *wgpu.RenderPassEncoder) {
pl := ph.System.GraphicsPipelines["onecolor"]
pl.BindPipeline(rp)
pl.BindDrawIndexed(rp)
}
// RenderTexture renders current settings to texture pipeline
func (ph *Phong) RenderTexture(rp *wgpu.RenderPassEncoder) {
pl := ph.System.GraphicsPipelines["texture"]
pl.BindPipeline(rp)
pl.BindDrawIndexed(rp)
}
// RenderVertexColor renders current settings to vertexcolor pipeline
func (ph *Phong) RenderVertexColor(rp *wgpu.RenderPassEncoder) {
pl := ph.System.GraphicsPipelines["pervertex"]
pl.BindPipeline(rp)
pl.BindDrawIndexed(rp)
}
// Copyright 2024 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package phong
import (
"embed"
"unsafe"
"cogentcore.org/core/gpu"
"github.com/oliverbestmann/webgpu/wgpu"
)
//go:embed shaders/*.wgsl
var shaders embed.FS
// ConfigPipeline configures graphics settings on the pipeline
func (ph *Phong) configPipeline(pl *gpu.GraphicsPipeline) {
pl.SetGraphicsDefaults()
pl.SetCullMode(wgpu.CullModeNone)
}
// Groups are the VarGroup numbers.
type Groups int32 //enums:enum
const (
CameraGroup Groups = iota
ObjectGroup
LightGroup
TextureGroup
)
// configGraphicsSystem configures the Phong GraphicsSystem and pipelines.
func (ph *Phong) configGraphicsSystem() {
sy := ph.System
opl := sy.AddGraphicsPipeline("onecolor")
ph.configPipeline(opl)
tpl := sy.AddGraphicsPipeline("texture")
ph.configPipeline(tpl)
vpl := sy.AddGraphicsPipeline("pervertex")
ph.configPipeline(vpl)
sh := opl.AddShader("onecolor")
sh.OpenFileFS(shaders, "shaders/onecolor.wgsl")
opl.AddEntry(sh, gpu.VertexShader, "vs_main")
opl.AddEntry(sh, gpu.FragmentShader, "fs_main")
sh = tpl.AddShader("texture")
sh.OpenFileFS(shaders, "shaders/texture.wgsl")
tpl.AddEntry(sh, gpu.VertexShader, "vs_main")
tpl.AddEntry(sh, gpu.FragmentShader, "fs_main")
sh = opl.AddShader("pervertex")
sh.OpenFileFS(shaders, "shaders/pervertex.wgsl")
// sh.OpenFileFS(shaders, "shaders/onecolor.wgsl")
vpl.AddEntry(sh, gpu.VertexShader, "vs_main")
vpl.AddEntry(sh, gpu.FragmentShader, "fs_main")
vgp := sy.Vars().AddVertexGroup()
cgp := sy.Vars().AddGroup(gpu.Uniform, "Camera") // group = 0
ogp := sy.Vars().AddGroup(gpu.Uniform, "Objects") // group = 1
lgp := sy.Vars().AddGroup(gpu.Uniform, "Lights") // group = 2
tgp := sy.Vars().AddGroup(gpu.SampledTexture, "Texture") // group = 3
vector4sz := gpu.Float32Vector4.Bytes()
vgp.Add("Pos", gpu.Float32Vector3, 0, gpu.VertexShader)
vgp.Add("Normal", gpu.Float32Vector3, 0, gpu.VertexShader)
vgp.Add("TexCoord", gpu.Float32Vector2, 0, gpu.VertexShader)
vgp.Add("VertexColor", gpu.Float32Vector4, 0, gpu.VertexShader)
ix := vgp.Add("Index", gpu.Uint32, 0, gpu.VertexShader)
ix.Role = gpu.Index
cgp.AddStruct("Camera", gpu.Float32Matrix4.Bytes()*2, 1, gpu.VertexShader, gpu.FragmentShader)
ov := ogp.AddStruct("Object", int(unsafe.Sizeof(Object{})), 1, gpu.VertexShader, gpu.FragmentShader)
ov.DynamicOffset = true
lgp.AddStruct("NLights", int(unsafe.Sizeof(NLights{})), 1, gpu.FragmentShader)
lgp.AddStruct("Ambient", vector4sz*1, MaxLights, gpu.FragmentShader)
lgp.AddStruct("Directional", vector4sz*2, MaxLights, gpu.FragmentShader)
lgp.AddStruct("Point", vector4sz*3, MaxLights, gpu.FragmentShader)
lgp.AddStruct("Spot", vector4sz*4, MaxLights, gpu.FragmentShader)
tgp.Add("TexSampler", gpu.TextureRGBA32, 1, gpu.FragmentShader)
vgp.SetNValues(1)
cgp.SetNValues(1)
ogp.SetNValues(1)
lgp.SetNValues(1)
tgp.SetNValues(1)
sy.Config()
}
// Copyright 2024 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package phong
import (
"fmt"
"image"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/iox/imagex"
)
// Texture has texture image and other params.
// Stored as image.RGBA for GPU compatibility.
type Texture struct {
Image *image.RGBA
}
func NewTexture(img image.Image) *Texture {
tx := &Texture{}
return tx.Set(img)
}
// Set sets texture from Go image.
func (tx *Texture) Set(img image.Image) *Texture {
tx.Image = imagex.AsRGBA(img)
return tx
}
// SetTexture sets given [Texture] to be available for
// [UseTexture] call during render. If it already exists, it
// is updated, otherwise added.
func (ph *Phong) SetTexture(name string, tx *Texture) {
ph.Lock()
defer ph.Unlock()
tgp := ph.System.Vars().Groups[int(TextureGroup)]
tvr := errors.Log1(tgp.VarByName("TexSampler"))
idx, ok := ph.textures.IndexByKeyTry(name)
if !ok {
idx = ph.textures.Len()
ph.textures.Set(name, tx)
tgp.SetNValues(ph.textures.Len())
} else {
ph.textures.Values[idx] = tx
}
tvv := tvr.Values.Values[idx]
tvv.SetFromGoImage(tx.Image, 1)
}
// configDummyTextureIfNone configures a dummy texture, if none configured.
func (ph *Phong) configDummyTexture() {
if ph.textures.Len() > 0 {
return
}
// there must be one texture -- otherwise get gpu error
tgp := ph.System.Vars().Groups[int(TextureGroup)]
tgp.SetNValues(1)
dimg := image.NewRGBA(image.Rectangle{Max: image.Point{2, 2}})
tvv := errors.Log1(tgp.ValueByIndex("TexSampler", 0))
tvv.SetFromGoImage(dimg, 0)
}
// ResetTextures resets all textures
func (ph *Phong) ResetTextures() {
ph.Lock()
defer ph.Unlock()
ph.textures.Reset()
tgp := ph.System.Vars().Groups[int(TextureGroup)]
tgp.SetNValues(1)
}
// UseNoTexture turns off texture rendering
func (ph *Phong) UseNoTexture() {
ph.UseCurTexture = false
}
// UseTexture selects texture by name for current render step.
func (ph *Phong) UseTexture(name string) error {
idx, ok := ph.textures.IndexByKeyTry(name)
if !ok {
return errors.Log(fmt.Errorf("phong:UseTexture: name not found: %s", name))
}
ph.System.Vars().SetCurrentValue(int(TextureGroup), "TexSampler", idx)
ph.UseCurTexture = true
return nil
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gpu
import (
"log"
"log/slog"
"cogentcore.org/core/base/errors"
"github.com/oliverbestmann/webgpu/wgpu"
)
// Pipeline is the shared Base for Graphics and Compute Pipelines.
// It manages Shader program(s) that accomplish a specific
// type of rendering or compute function, using Vars / Values
// defined by the overall GraphicsSystem.
// In the graphics context, each pipeline could handle a different
// class of materials (textures, Phong lighting, etc).
type Pipeline struct {
// unique name of this pipeline
Name string
// System that we belong to and manages shared resources:
// Vars, Values, etc
System System
// Shaders contains actual shader code loaded for this pipeline.
// A single shader can have multiple entry points: see Entries.
Shaders map[string]*Shader
// Entries contains the entry points into shader code,
// which are what is actually called.
Entries map[string]*ShaderEntry
// current bind groups for each var group used.
currentBindGroups map[int]*wgpu.BindGroup
// current counter for bind groups, to detect if needs updating.
currentBindGroupsCount map[int]int
// oldBindGroups are prior bind groups that need to be released
// after current render or compute pass.
oldBindGroups []*wgpu.BindGroup
}
// Vars returns a pointer to the vars for this pipeline,
// which has Values within it.
func (pl *Pipeline) Vars() *Vars {
return pl.System.Vars()
}
// AddShader adds Shader with given name to the pipeline
func (pl *Pipeline) AddShader(name string) *Shader {
if pl.Shaders == nil {
pl.Shaders = make(map[string]*Shader)
}
if sh, has := pl.Shaders[name]; has {
log.Printf("gpu.Pipeline AddShader: Shader named: %s already exists in pipline: %s\n", name, pl.Name)
return sh
}
sh := NewShader(name, pl.System.Device())
pl.Shaders[name] = sh
return sh
}
// ShaderByName returns Shader by name.
// Returns nil if not found (error auto logged).
func (pl *Pipeline) ShaderByName(name string) *Shader {
sh, ok := pl.Shaders[name]
if !ok {
slog.Error("gpu.Pipeline ShaderByName", "Shader", name, "not found in pipeline", pl.Name)
return nil
}
return sh
}
// EntryByName returns ShaderEntry by name, which is Shader:Entry.
// Returns nil if not found (error auto logged).
func (pl *Pipeline) EntryByName(name string) *ShaderEntry {
sh, ok := pl.Entries[name]
if !ok {
slog.Error("gpu.Pipeline EntryByName", "Entry", name, "not found in pipeline", pl.Name)
return nil
}
return sh
}
// EntryByType returns ShaderEntry by ShaderType.
// Returns nil if not found.
func (pl *Pipeline) EntryByType(typ ShaderTypes) *ShaderEntry {
for _, sh := range pl.Entries {
if sh.Type == typ {
return sh
}
}
return nil
}
// AddEntry adds ShaderEntry for given shader, [ShaderTypes], and entry function name.
func (pl *Pipeline) AddEntry(sh *Shader, typ ShaderTypes, entry string) *ShaderEntry {
if pl.Entries == nil {
pl.Entries = make(map[string]*ShaderEntry)
}
name := sh.Name + ":" + entry
if se, has := pl.Entries[name]; has {
slog.Error("gpu.Pipeline AddEntry", "ShaderEntry named", name, "already exists in pipline", pl.Name)
return se
}
se := NewShaderEntry(sh, typ, entry)
pl.Entries[name] = se
return se
}
// releaseShaders releases the shaders
func (pl *Pipeline) releaseShaders() {
pl.releaseOldBindGroups()
pl.releaseCurrentBindGroups()
for _, sh := range pl.Shaders {
sh.Release()
}
pl.Shaders = nil
pl.Entries = nil
}
// bindLayout returns a PipeLineLayout based on Vars
func (pl *Pipeline) bindLayout(used ...*Var) (*wgpu.PipelineLayout, error) {
lays := pl.Vars().bindLayout(pl.System.Device(), used...)
if lays != nil {
defer func() {
for _, bgl := range lays {
bgl.Release()
}
}()
}
rpl, err := pl.System.Device().Device.TryCreatePipelineLayout(&wgpu.PipelineLayoutDescriptor{
Label: pl.Name,
BindGroupLayouts: lays,
})
if errors.Log(err) != nil {
return nil, err
}
return rpl, nil
}
// bindGroup returns a BindGroup for given var group,
// along with dynamic offsets. manages whether updates are needed
// or can re-use existing.
func (pl *Pipeline) bindGroup(vg *VarGroup, used ...*Var) (*wgpu.BindGroup, []uint32, error) {
if pl.currentBindGroups == nil {
pl.currentBindGroups = make(map[int]*wgpu.BindGroup)
pl.currentBindGroupsCount = make(map[int]int)
}
dynamicOffsets := vg.dynamicOffsets(used...)
cbg, ok := pl.currentBindGroups[vg.Group]
ccount := pl.currentBindGroupsCount[vg.Group]
vgcount := vg.BindGroupUpdateCount()
if ok && ccount == vgcount {
return cbg, dynamicOffsets, nil
}
if cbg != nil {
pl.oldBindGroups = append(pl.oldBindGroups, cbg) // to be released
}
bg, err := vg.bindGroup(pl.Vars(), used...)
if err == nil {
pl.currentBindGroups[vg.Group] = bg
pl.currentBindGroupsCount[vg.Group] = vgcount
}
return bg, dynamicOffsets, err
}
// releaseCurrentBindGroups releases current bind groups.
func (pl *Pipeline) releaseCurrentBindGroups() {
if pl.currentBindGroups == nil {
return
}
og := pl.currentBindGroups
pl.currentBindGroups = nil
for _, bg := range og {
bg.Release()
}
}
// releaseOldBindGroups releases old bind groups.
func (pl *Pipeline) releaseOldBindGroups() {
if pl.oldBindGroups == nil {
return
}
og := pl.oldBindGroups
pl.oldBindGroups = nil
for _, bg := range og {
bg.Release()
}
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gpu
import (
"errors"
"image"
"image/color"
"log"
"cogentcore.org/core/colors"
"github.com/oliverbestmann/webgpu/wgpu"
)
// Render manages various elements needed for rendering,
// including a function to get a WebGPU RenderPass object,
// which specifies parameters for rendering to a Texture.
// It holds the Depth buffer if one is used, and a multisampling image too.
// The Render object is owned by a Renderer (Surface or RenderTexture).
type Render struct {
// texture format information for the texture target we render to.
// critically, this can be different from the surface actual format
// in the case when that format is non-srgb, as is the case in web browsers.
Format TextureFormat
// the associated depth buffer, if set
Depth Texture
// if this is not UndefinedType, depth format is used
DepthFormat Types
// for multisampling, this is the multisampled image that is the actual render target
Multi Texture
// is true if multsampled image configured
HasMulti bool
// host-accessible image that is used to transfer back
// from a render color attachment to host memory.
// Requires a different format than color attachment
Grab Texture
// values for clearing image when starting render pass
ClearColor color.Color
ClearDepth float32
ClearStencil uint32
device Device
}
// Config configures the render pass for given device,
// Using standard parameters for graphics rendering,
// based on the given image format and depth image format
// (pass UndefinedType for no depth buffer, or Depth32).
func (rd *Render) Config(dev *Device, imgFmt *TextureFormat, depthFmt Types) {
rd.device = *dev
rd.Format = *imgFmt
rd.ClearColor = colors.Black
rd.ClearDepth = 1
rd.ClearStencil = 0
rd.DepthFormat = depthFmt
if depthFmt != UndefinedType {
rd.Depth.ConfigDepth(dev, rd.DepthFormat, imgFmt)
}
if rd.Format.Samples > 1 {
rd.Multi.ConfigMulti(dev, imgFmt)
rd.HasMulti = true
}
}
func (rd *Render) Release() {
rd.Depth.Release()
rd.Multi.Release()
rd.Grab.Release()
// rp.GrabDepth.Free(rp.Dev)
}
func (rd *Render) SetSize(sz image.Point) {
if rd.Format.Size == sz {
return
}
rd.Format.Size = sz
if rd.HasMulti {
rd.Multi.ConfigMulti(&rd.device, &rd.Format)
}
if rd.DepthFormat != UndefinedType {
rd.Depth.ConfigDepth(&rd.device, rd.DepthFormat, &rd.Format)
}
}
// ClearRenderPass returns a render pass descriptor that clears the framebuffer
func (rd *Render) ClearRenderPass(view *wgpu.TextureView) *wgpu.RenderPassDescriptor {
r, g, b, a := colors.ToFloat32(rd.ClearColor)
r, g, b = SRGBToLinear(r, g, b)
clearColor := wgpu.Color{R: float64(r), G: float64(g), B: float64(b), A: float64(a)}
rpd := &wgpu.RenderPassDescriptor{}
if rd.Format.Samples > 1 && rd.Multi.view != nil {
rpd.Label = "ClearMulti1"
rpd.ColorAttachments = []wgpu.RenderPassColorAttachment{{
View: rd.Multi.view,
ResolveTarget: view,
LoadOp: wgpu.LoadOpClear,
ClearValue: clearColor,
StoreOp: wgpu.StoreOpStore,
}}
} else {
rpd.Label = "Clear1"
rpd.ColorAttachments = []wgpu.RenderPassColorAttachment{{
View: view,
LoadOp: wgpu.LoadOpClear,
ClearValue: clearColor,
StoreOp: wgpu.StoreOpStore,
}}
}
rd.SetDepthDescriptor(rpd)
return rpd
}
// LoadRenderPass returns a render pass descriptor that loads previous framebuffer
func (rd *Render) LoadRenderPass(view *wgpu.TextureView) *wgpu.RenderPassDescriptor {
rpd := &wgpu.RenderPassDescriptor{}
if rd.Format.Samples > 1 && rd.Multi.view != nil {
rpd.Label = "LoadMulti"
rpd.ColorAttachments = []wgpu.RenderPassColorAttachment{{
View: rd.Multi.view,
ResolveTarget: view,
LoadOp: wgpu.LoadOpLoad,
StoreOp: wgpu.StoreOpStore,
}}
} else {
rpd.Label = "Load1"
rpd.ColorAttachments = []wgpu.RenderPassColorAttachment{{
View: view,
LoadOp: wgpu.LoadOpLoad,
StoreOp: wgpu.StoreOpStore,
}}
}
rd.SetDepthDescriptor(rpd)
return rpd
}
func (rd *Render) SetDepthDescriptor(rpd *wgpu.RenderPassDescriptor) {
if rd.Depth.texture == nil {
return
}
rpd.DepthStencilAttachment = &wgpu.RenderPassDepthStencilAttachment{
View: rd.Depth.view,
DepthClearValue: rd.ClearDepth,
DepthLoadOp: wgpu.LoadOpClear,
DepthStoreOp: wgpu.StoreOpStore,
DepthReadOnly: false,
StencilClearValue: rd.ClearStencil,
StencilLoadOp: wgpu.LoadOpClear,
StencilStoreOp: wgpu.StoreOpStore,
StencilReadOnly: true,
}
}
// BeginRenderPass adds commands to the given command buffer
// to start the render pass on given framebuffer.
// Clears the frame first, according to the ClearValues
// See BeginRenderPassNoClear for non-clearing version.
func (rd *Render) BeginRenderPass(cmd *wgpu.CommandEncoder, view *wgpu.TextureView) *wgpu.RenderPassEncoder {
return rd.beginRenderPass(cmd, view, true)
}
// BeginRenderPassNoClear adds commands to the given command buffer
// to start the render pass on given framebuffer.
// does NOT clear the frame first -- loads prior state.
func (rd *Render) BeginRenderPassNoClear(cmd *wgpu.CommandEncoder, view *wgpu.TextureView) *wgpu.RenderPassEncoder {
return rd.beginRenderPass(cmd, view, false)
}
func (rd *Render) beginRenderPass(cmd *wgpu.CommandEncoder, view *wgpu.TextureView, clear bool) *wgpu.RenderPassEncoder {
// w, h := fr.Texture.Format.Size32()
// clearValues := rp.ClearValues
// vrp := rp.VkClearPass
// if !clear && fr.HasCleared {
// clearValues = nil
// vrp = rp.VkLoadPass
// }
// fr.HasCleared = true
var rpd *wgpu.RenderPassDescriptor
if clear {
rpd = rd.ClearRenderPass(view)
} else {
rpd = rd.LoadRenderPass(view)
}
return cmd.BeginRenderPass(rpd)
}
// ConfigGrab configures the Grab for copying rendered image
// back to host memory. Uses format of current Texture.
func (rd *Render) ConfigGrab(dev *Device) {
if rd.Grab.texture != nil && rd.Grab.Format.Size == rd.Format.Size {
return
}
rd.Grab.Format.Defaults()
rd.Grab.Format = rd.Format
rd.Grab.Format.SetMultisample(1) // can't have for grabs
rd.Grab.device = *dev
rd.Grab.CreateTexture(wgpu.TextureUsageCopySrc) // todo: not sure what else?
}
// https://www.reddit.com/r/WebGPU/comments/7yhvep/retrieve_depth_attachment_from_framebuffer/
// https://pastebin.com/33MxSNmh
// have to copy to a buffer then sync that back down
// create the buffer as the GrabDepth item
// ConfigGrabDepth configures the GrabDepth for copying depth image
// back to host memory. Uses format of current Depth image.
func (rd *Render) ConfigGrabDepth(dev *Device) {
// bsz := rp.Format.Size.X * rp.Format.Size.Y * 4 // 32 bit = 4 bytes per pixel
// if rp.GrabDepth.Active {
// if rp.GrabDepth.Size == bsz {
// return
// }
// rp.GrabDepth.Free(dev)
// }
// rp.GrabDepth.Type = StorageBuffer
// rp.GrabDepth.AllocMem(dev, bsz)
}
// GrabDepthTexture grabs the current render depth image, using given command buffer
// which must have the cmdBegin called already. Uses the GrabDepth Storage Buffer.
// call this after: sys.MemCmdEndSubmitWaitFree()
func (rd *Render) GrabDepthTexture(dev *Device, cmd *wgpu.CommandEncoder) error {
nsamp := rd.Format.Samples
if nsamp > 1 {
err := errors.New("gpu.Render.GrabDepthTexture(): does not work if multisampling is > 1")
if Debug {
log.Println(err)
}
return err
}
rd.ConfigGrabDepth(dev) // ensure image grab setup
return nil
}
// DepthTextureArray returns the float values from the last GrabDepthTexture call
// automatically handles down-sampling from multisampling.
func (rd *Render) DepthTextureArray() ([]float32, error) {
return nil, nil
}
// Copyright (c) 2022, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gpu
import (
"image"
"github.com/oliverbestmann/webgpu/wgpu"
)
// RenderTexture is an offscreen, non-window-backed rendering target,
// functioning like a Surface.
type RenderTexture struct {
// Render helper for this RenderTexture.
render Render
// Format has the current image format and dimensions.
// The Samples here are the desired value, whereas our Frames
// always have Samples = 1, and use render for multisampling.
Format TextureFormat
// number of frames to maintain in the simulated swapchain.
// e.g., 2 = double-buffering, 3 = triple-buffering.
NFrames int
// Textures that we iterate through in rendering subsequent frames.
Frames []*Texture
// pointer to gpu device, for convenience
GPU *GPU
// current frame number is the one that has just been rendered to.
curFrame int
// next frame number is the one that will be rendered to next.
nextFrame int
// device, which we do NOT own.
device Device
}
// NewRenderTexture returns a new standalone texture render
// target for given GPU and device, suitable for offscreen rendering
// or intermediate use of the render output for other purposes.
// - device should be from a Surface if one is being used, otherwise
// can be created anew for offscreen rendering, and released at end.
// - size should reflect the actual size of the surface,
// and can be updated with SetSize method.
// - samples is the multisampling anti-aliasing parameter: 1 = none
// 4 = typical default value for smooth "no jaggy" edges.
// - depthFmt is the depth buffer format. use UndefinedType for none
// or Depth32 recommended for best performance.
func NewRenderTexture(gp *GPU, dev *Device, size image.Point, samples int, depthFmt Types) *RenderTexture {
rt := &RenderTexture{}
rt.Defaults()
rt.init(gp, dev, size, samples, depthFmt)
return rt
}
func (rt *RenderTexture) Defaults() {
rt.NFrames = 1
rt.Format.Defaults()
// note: screen-correct results obtained by using Srgb here, which forces
// this format in the final output. Looks like what comes out from direct rendering.
rt.Format.Set(1024, 768, wgpu.TextureFormatRGBA8UnormSrgb)
rt.Format.SetMultisample(4)
}
func (rt *RenderTexture) init(gp *GPU, dev *Device, size image.Point, samples int, depthFmt Types) {
rt.GPU = gp
rt.device = *dev
rt.Format.Size = size
rt.Format.SetMultisample(samples)
rt.render.Config(&rt.device, &rt.Format, depthFmt)
rt.ConfigFrames()
}
func (rt *RenderTexture) Device() *Device { return &rt.device }
func (rt *RenderTexture) Render() *Render { return &rt.render }
func (rt *RenderTexture) CurrentFrameNumber() int { return rt.curFrame }
// GetCurrentTexture returns a TextureView that is the current
// target for rendering.
func (rt *RenderTexture) GetCurrentTexture() (*wgpu.TextureView, error) {
rt.curFrame = rt.nextFrame
rt.nextFrame = (rt.curFrame + 1) % rt.NFrames
return rt.Frames[rt.curFrame].view, nil
}
// CurrentFrame returns the current frame texture object.
func (rt *RenderTexture) CurrentFrame() *Texture {
return rt.Frames[rt.curFrame]
}
// ConfigFrames configures the frames, calling ReleaseFrames
// so it is safe for re-use.
func (rt *RenderTexture) ConfigFrames() {
rt.ReleaseFrames()
rt.Frames = make([]*Texture, rt.NFrames)
for i := range rt.NFrames {
fr := NewTexture(&rt.device)
fr.ConfigRenderTexture(&rt.device, &rt.Format)
rt.Frames[i] = fr
}
}
// SetSize sets the size for the render frame,
// doesn't do anything if already that size.
func (rt *RenderTexture) SetSize(size image.Point) {
if rt.Format.Size == size {
return
}
rt.render.SetSize(size)
rt.Format.Size = size
if len(rt.Frames) != rt.NFrames {
rt.ConfigFrames()
return
}
// The frames are remade in place, destroying their old textures, so
// that a [Texture] obtained from [RenderTexture.CurrentFrame] stays
// valid and has the new texture.
for _, fr := range rt.Frames {
fr.ConfigRenderTexture(&rt.device, &rt.Format)
}
}
func (rt *RenderTexture) Size() image.Point {
return rt.Format.Bounds().Size()
}
func (rt *RenderTexture) ReleaseFrames() {
for _, fr := range rt.Frames {
fr.Release()
}
rt.Frames = nil
}
func (rt *RenderTexture) Release() {
rt.ReleaseFrames()
rt.render.Release()
}
func (rt *RenderTexture) Present() {
// no-op
}
// ReadFrame adds a command to given command encoder to read the current
// Frame into the texture read buffer, so it can be available for
// ReadGoImage after the current render pass is done.
func (rt *RenderTexture) ReadFrame(cmd *wgpu.CommandEncoder) {
rt.CurrentFrame().CopyToReadBuffer(cmd)
}
// ReadDepthTexture adds a command to given command encoder to read the current
// depth texture into the texture read buffer, so it can be available for
// ReadGoImage after the current render pass is done.
func (rt *RenderTexture) ReadDepthTexture(cmd *wgpu.CommandEncoder) {
// rt.render.GrabDepthTexture(&rt.device, cmd)
}
// Copyright (c) 2022, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gpu
import "github.com/oliverbestmann/webgpu/wgpu"
// VarRoles are the functional roles of variables,
type VarRoles int32 //enums:enum
const (
UndefVarRole VarRoles = iota
// Vertex is vertex shader input data: mesh geometry points, normals, etc.
// These are automatically located in a separate Set, VertexSet (-2),
// and managed separately.
Vertex
// Index is for indexes to access to Vertex data, also located in VertexSet (-2).
// Only one such Var per VarGroup should be present, and will
// automatically be used if a value is set.
Index
// Push is push constants, NOT CURRENTLY SUPPORTED in WebGPU.
// They have a minimum of 128 bytes and are
// stored directly in the command buffer. They do not require any
// host-device synchronization or buffering, and are fully dynamic.
// They are ideal for transformation matricies or indexes for accessing data.
// They are stored in a special PushSet (-1) and managed separately.
Push
// Uniform is read-only general purpose data, with a more limited capacity.
// Compared to Storage, Uniform items can be put in local cache for each
// shader and thus can be much faster to access. Use for a smaller number
// of parameters such as transformation matricies.
Uniform
// Storage is read-write general purpose data. This is a larger but slower
// pool of memory, with more flexible alignment constraints, used primarily
// for compute data.
Storage
// StorageTexture is read-write storage-based texture data, for compute shaders
// that operate on image data, not for standard use of textures in fragment
// shader to texturize objects (which is SampledTexture).
StorageTexture
// SampledTexture is a Texture + Sampler that is used to texturize objects
// in the fragment shader. The variable for this specifies the role for
// the texture (typically there is just one main such texture), and
// the different Values of the variable hold each instance, with
// binding used to switch which texture to use.
// The Texture takes the first Binding position, and the Sampler is +1.
SampledTexture
)
// IsDynamic returns true if role has dynamic offset binding
func (vr VarRoles) IsDynamic() bool {
return vr == Uniform || vr == Storage
}
func (vr VarRoles) BindingType() wgpu.BufferBindingType {
return RoleBindingTypes[vr]
}
var RoleBindingTypes = map[VarRoles]wgpu.BufferBindingType{
UndefVarRole: wgpu.BufferBindingTypeStorage,
Uniform: wgpu.BufferBindingTypeUniform,
Storage: wgpu.BufferBindingTypeStorage,
StorageTexture: wgpu.BufferBindingTypeStorage,
// also defined: wgpu.BufferBindingTypeReadOnlyStorage,
}
func (vr VarRoles) BufferUsages() wgpu.BufferUsage {
return RoleBufferUsages[vr]
}
// RoleBufferUsages maps VarRoles into buffer usage flags
var RoleBufferUsages = map[VarRoles]wgpu.BufferUsage{
Vertex: wgpu.BufferUsageVertex | wgpu.BufferUsageCopyDst,
Index: wgpu.BufferUsageIndex | wgpu.BufferUsageCopyDst,
Uniform: wgpu.BufferUsageUniform | wgpu.BufferUsageCopyDst,
Storage: wgpu.BufferUsageStorage | wgpu.BufferUsageCopyDst | wgpu.BufferUsageCopySrc,
StorageTexture: wgpu.BufferUsageStorage | wgpu.BufferUsageCopyDst | wgpu.BufferUsageCopySrc,
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gpu
import (
"cogentcore.org/core/base/errors"
"github.com/oliverbestmann/webgpu/wgpu"
)
// Sampler represents a WebGPU image sampler
type Sampler struct {
Name string
// for U (horizontal) axis -- what to do when going off the edge
UMode SamplerModes
// for V (vertical) axis -- what to do when going off the edge
VMode SamplerModes
// for W (horizontal) axis -- what to do when going off the edge
WMode SamplerModes
// border color for Clamp modes
Border BorderColors
// the WebGPU sampler
sampler *wgpu.Sampler
}
func (sm *Sampler) Defaults() {
sm.UMode = Repeat
sm.VMode = Repeat
sm.WMode = Repeat
sm.Border = BorderTrans
}
// Config configures sampler on device. If the sampler
// already exists, then it is not reconfigured.
// Use Release first to force a reconfigure.
func (sm *Sampler) Config(dev *Device) error {
if sm.sampler != nil {
return nil
}
samp, err := dev.Device.TryCreateSampler(&wgpu.SamplerDescriptor{
AddressModeU: sm.UMode.Mode(),
AddressModeV: sm.VMode.Mode(),
AddressModeW: sm.WMode.Mode(),
MagFilter: wgpu.FilterModeLinear, // nearest?
MinFilter: wgpu.FilterModeLinear,
MipmapFilter: wgpu.MipmapFilterModeLinear,
LodMinClamp: 0,
LodMaxClamp: 32,
Compare: wgpu.CompareFunctionUndefined,
MaxAnisotropy: 1,
})
// MaxAnisotropy: gp.GPUProperties.Limits.MaxSamplerAnisotropy,
// BorderColor: sm.Border.VkColor(),
// UnnormalizedCoordinates: vk.False,
// CompareEnable: vk.False,
if errors.Log(err) != nil {
return err
}
sm.sampler = samp
return nil
}
func (sm *Sampler) Release() {
if sm.sampler == nil {
return
}
sm.sampler.Release()
sm.sampler = nil
}
// SamplerModes are the texture image sampler modes.
type SamplerModes int32 //enums:enum
const (
// Repeat the texture when going beyond the image dimensions.
Repeat SamplerModes = iota
// Like repeat, but inverts the coordinates to mirror the image when going beyond the dimensions.
MirrorRepeat
// Take the color of the edge closest to the coordinate beyond the image dimensions.
ClampToEdge
// Return a solid color when sampling beyond the dimensions of the image.
// ClampToBorder
// Like clamp to edge, but instead uses the edge opposite to the closest edge.
// MirrorClampToEdge
)
func (sm SamplerModes) Mode() wgpu.AddressMode {
return WebGPUSamplerModes[sm]
}
var WebGPUSamplerModes = map[SamplerModes]wgpu.AddressMode{
Repeat: wgpu.AddressModeRepeat,
MirrorRepeat: wgpu.AddressModeMirrorRepeat,
ClampToEdge: wgpu.AddressModeClampToEdge,
}
//////////////////////////////////////////////////////
// BorderColors are the border colors of the texture image sampler.
type BorderColors int32 //enums:enum -trim-prefix Border
const (
// Repeat the texture when going beyond the image dimensions.
BorderTrans BorderColors = iota
BorderBlack
BorderWhite
)
// todo: not (yet) supported
//
// func (bc BorderColors) VkColor() vk.BorderColor {
// return VulkanBorderColors[bc]
// }
//
// var VulkanBorderColors = map[BorderColors]vk.BorderColor{
// BorderTrans: vk.BorderColorIntTransparentBlack,
// BorderBlack: vk.BorderColorIntOpaqueBlack,
// BorderWhite: vk.BorderColorIntOpaqueWhite,
// }
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gpu
import (
"io/fs"
"os"
"path/filepath"
"cogentcore.org/core/base/errors"
"github.com/oliverbestmann/webgpu/wgpu"
)
// Shader manages a single Shader program, which can have multiple
// entry points. See ShaderEntry for entry points into Shaders.
type Shader struct {
Name string
module *wgpu.ShaderModule
device Device
}
func NewShader(name string, dev *Device) *Shader {
sh := &Shader{Name: name}
sh.device = *dev
return sh
}
// OpenFile loads given WGSL ".wgl" code from file for the Shader.
func (sh *Shader) OpenFile(fname string) error {
if sh.Name == "" {
sh.Name = fname
}
b, err := os.ReadFile(fname)
if errors.Log(err) != nil {
return err
}
cp := errors.Log1(os.Getwd())
return sh.OpenCode(IncludeFS(os.DirFS(cp), "", string(b))) // todo: maybe not ideal
}
// OpenFileFS loads given WGSL ".wgl" code from file for the Shader.
func (sh *Shader) OpenFileFS(fsys fs.FS, fname string) error {
if sh.Name == "" {
sh.Name = fname
}
b, err := fs.ReadFile(fsys, fname)
if errors.Log(err) != nil {
return err
}
return sh.OpenCode(IncludeFS(fsys, filepath.Dir(fname), string(b)))
}
// OpenCode loads given WGSL ".wgl" code for the Shader.
func (sh *Shader) OpenCode(code string) error {
module, err := sh.device.Device.TryCreateShaderModule(&wgpu.ShaderModuleDescriptor{
Label: sh.Name,
WGSLSource: &wgpu.ShaderSourceWGSL{Code: code},
})
if errors.Log(err) != nil {
return err
}
sh.module = module
return nil
}
// Release destroys the shader
func (sh *Shader) Release() {
if sh.module == nil {
return
}
sh.module.Release()
sh.module = nil
}
// ShaderEntry is an entry point into a Shader. There can be multiple
// entry points per shader.
type ShaderEntry struct {
// Shader has the code
Shader *Shader
// Type of shader entry point.
Type ShaderTypes
// Entry is the name of the function to call for this Entry.
// Conventionally, it is some variant on "main"
Entry string
}
// NewShaderEntry returns a new ShaderEntry with given settings
func NewShaderEntry(sh *Shader, typ ShaderTypes, entry string) *ShaderEntry {
se := &ShaderEntry{Shader: sh, Type: typ, Entry: entry}
return se
}
// ShaderTypes is a list of GPU shader types
type ShaderTypes int32
const (
UnknownShader ShaderTypes = iota
VertexShader
FragmentShader
ComputeShader
)
var ShaderStageFlags = map[ShaderTypes]wgpu.ShaderStage{
UnknownShader: wgpu.ShaderStageNone,
VertexShader: wgpu.ShaderStageVertex,
FragmentShader: wgpu.ShaderStageFragment,
ComputeShader: wgpu.ShaderStageCompute,
}
// Copyright 2022 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package shape
import "cogentcore.org/core/math32"
// Box is a rectangular-shaped solid (cuboid)
type Box struct { //types:add -setters
ShapeBase
// size along each dimension
Size math32.Vector3
// number of segments to divide each plane into
// (enforced to be at least 1).
// Can generally increase rendering quality to have > 1.
Segs math32.Vector3i
}
// NewBox returns a Box shape with given size.
func NewBox(width, height, depth float32) *Box {
bx := &Box{}
bx.Defaults()
bx.Size.Set(width, height, depth)
return bx
}
func (bx *Box) Defaults() {
bx.Size.Set(1, 1, 1)
bx.Segs.Set(1, 1, 1)
}
func (bx *Box) MeshSize() (numVertex, nIndex int, hasColor bool) {
numVertex, nIndex = BoxN(bx.Segs)
return
}
// Set sets points in given allocated arrays.
func (bx *Box) Set(vertex, normal, texcoord, clrs math32.ArrayF32, index math32.ArrayU32) {
hSz := SetBox(vertex, normal, texcoord, index, bx.VertexOffset, bx.IndexOffset, bx.Size, bx.Segs, bx.Pos)
mn := bx.Pos.Sub(hSz)
mx := bx.Pos.Add(hSz)
bx.CBBox.Set(&mn, &mx)
}
// BoxN returns the N's for a single plane's worth of
// vertex and index data with given number of segments.
// Note: In *vertex* units, not float units (i.e., x3 to get
// actual float offset in Vtx array).
func BoxN(segs math32.Vector3i) (numVertex, nIndex int) {
nv, ni := PlaneN(int(segs.X), int(segs.Y))
numVertex += 2 * nv
nIndex += 2 * ni
nv, ni = PlaneN(int(segs.X), int(segs.Z))
numVertex += 2 * nv
nIndex += 2 * ni
nv, ni = PlaneN(int(segs.Z), int(segs.Y))
numVertex += 2 * nv
nIndex += 2 * ni
return
}
// SetBox sets box vertex, normal, tex, index data at
// given starting *vertex* index (i.e., multiply this *3 to get
// actual float offset in Vtx array), and starting Index index.
// for given 3D size, and given number of segments per side.
// finely subdividing a plane allows for higher-quality lighting
// and texture rendering (minimum of 1 will be enforced).
// pos is a 3D position offset. returns 3D size of plane.
func SetBox(vertex, normal, texcoord math32.ArrayF32, index math32.ArrayU32, vtxOff, idxOff int, size math32.Vector3, segs math32.Vector3i, pos math32.Vector3) math32.Vector3 {
hSz := size.DivScalar(2)
numVertex, nIndex := PlaneN(int(segs.X), int(segs.Y))
voff := vtxOff
ioff := idxOff
// start with neg z as typically back
SetPlane(vertex, normal, texcoord, index, voff, ioff, math32.X, math32.Y, -1, -1, size.X, size.Y, -hSz.X, -hSz.Y, -hSz.Z, int(segs.X), int(segs.Y), pos) // nz
voff += numVertex
ioff += nIndex
SetPlane(vertex, normal, texcoord, index, voff, ioff, math32.X, math32.Z, 1, -1, size.X, size.Z, -hSz.X, -hSz.Z, -hSz.Y, int(segs.X), int(segs.Z), pos) // ny
voff += numVertex
ioff += nIndex
SetPlane(vertex, normal, texcoord, index, voff, ioff, math32.Z, math32.Y, -1, -1, size.Z, size.Y, -hSz.Z, -hSz.Y, hSz.X, int(segs.Z), int(segs.Y), pos) // px
voff += numVertex
ioff += nIndex
SetPlane(vertex, normal, texcoord, index, voff, ioff, math32.Z, math32.Y, 1, -1, size.Z, size.Y, -hSz.Z, -hSz.Y, -hSz.X, int(segs.Z), int(segs.Y), pos) // nx
voff += numVertex
ioff += nIndex
SetPlane(vertex, normal, texcoord, index, voff, ioff, math32.X, math32.Z, 1, 1, size.X, size.Z, -hSz.X, -hSz.Z, hSz.Y, int(segs.X), int(segs.Z), pos) // py
voff += numVertex
ioff += nIndex
SetPlane(vertex, normal, texcoord, index, voff, ioff, math32.X, math32.Y, 1, -1, size.X, size.Y, -hSz.X, -hSz.Y, hSz.Z, int(segs.X), int(segs.Y), pos) // pz
return hSz
}
// Copyright 2022 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package shape
import "cogentcore.org/core/math32"
// Capsule is a generalized capsule shape: a cylinder with hemisphere end caps.
// Supports different radii on each end.
// Height is along the Y axis -- total height is Height + TopRad + BotRad.
type Capsule struct { //types:add -setters
ShapeBase
// height of the cylinder portion
Height float32
// radius of the top -- set to 0 to omit top cap
TopRad float32
// radius of the bottom -- set to 0 to omit bottom cap
BotRad float32
// number of radial segments (32 is a reasonable default for full circle)
RadialSegs int `min:"1"`
// number of height segments
HeightSegs int
// number of segments in the hemisphere cap ends (16 is a reasonable default)
CapSegs int
// starting angle in degrees, relative to -1,0,0 left side starting point
AngStart float32 `min:"0" max:"360" step:"5"`
// total angle to generate in degrees (max 360)
AngLen float32 `min:"0" max:"360" step:"5"`
}
// NewCapsule returns a Capsule shape with given radius, height,
// number of radial segments, number of height segments,
// and presence of a top and/or bottom cap.
// Height is along the Y axis.
func NewCapsule(height, radius float32, segs, heightSegs int) *Capsule {
cp := &Capsule{}
cp.Defaults()
cp.Height = height
cp.TopRad = radius
cp.BotRad = radius
cp.RadialSegs = segs
cp.CapSegs = segs
cp.HeightSegs = heightSegs
return cp
}
func (cp *Capsule) Defaults() {
cp.Height = 1
cp.TopRad = 0.5
cp.BotRad = 0.5
cp.RadialSegs = 32
cp.HeightSegs = 32
cp.CapSegs = 32
cp.AngStart = 0
cp.AngLen = 360
}
func (cp *Capsule) MeshSize() (numVertex, nIndex int, hasColor bool) {
numVertex, nIndex = CylinderSectorN(cp.RadialSegs, cp.HeightSegs, NoTop, NoBottom)
if cp.BotRad > 0 {
nv, ni := SphereSectorN(cp.RadialSegs, cp.CapSegs, 90, 90)
numVertex += nv
nIndex += ni
}
if cp.TopRad > 0 {
nv, ni := SphereSectorN(cp.RadialSegs, cp.CapSegs, 0, 90)
numVertex += nv
nIndex += ni
}
return
}
// Set sets points in given allocated arrays.
func (cp *Capsule) Set(vertex, normal, texcoord, clrs math32.ArrayF32, index math32.ArrayU32) {
voff := cp.VertexOffset
ioff := cp.IndexOffset
cp.CBBox = SetCylinderSector(vertex, normal, texcoord, index, voff, ioff, cp.Height, cp.TopRad, cp.BotRad, cp.RadialSegs, cp.HeightSegs, cp.AngStart, cp.AngLen, NoTop, NoBottom, cp.Pos)
nv, ni := CylinderSectorN(cp.RadialSegs, cp.HeightSegs, NoTop, NoBottom)
voff += nv
ioff += ni
if cp.BotRad > 0 {
ps := cp.Pos
ps.Y -= cp.Height / 2
cbb := SetSphereSector(vertex, normal, texcoord, index, voff, ioff, cp.BotRad, cp.RadialSegs, cp.CapSegs, cp.AngStart, cp.AngLen, 90, 90, ps)
cp.CBBox.ExpandByBox(cbb)
nv, ni = SphereSectorN(cp.RadialSegs, cp.CapSegs, 90, 90)
voff += nv
ioff += ni
}
if cp.TopRad > 0 {
ps := cp.Pos
ps.Y += cp.Height / 2
cbb := SetSphereSector(vertex, normal, texcoord, index, voff, ioff, cp.TopRad, cp.RadialSegs, cp.CapSegs, cp.AngStart, cp.AngLen, 0, 90, ps)
cp.CBBox.ExpandByBox(cbb)
}
}
// Copyright 2022 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package shape
import (
"cogentcore.org/core/math32"
)
// Cylinder is a generalized cylinder shape, including a cone
// or truncated cone by having different size circles at either end.
// Height is up along the Y axis.
type Cylinder struct { //types:add -setters
ShapeBase
// height of the cylinder
Height float32
// radius of the top -- set to 0 for a cone
TopRad float32
// radius of the bottom
BotRad float32
// number of radial segments (32 is a reasonable default for full circle)
RadialSegs int `min:"1"`
// number of height segments
HeightSegs int
// render the top disc
Top bool
// render the bottom disc
Bottom bool
// starting angle in degrees, relative to -1,0,0 left side starting point
AngStart float32 `min:"0" max:"360" step:"5"`
// total angle to generate in degrees (max 360)
AngLen float32 `min:"0" max:"360" step:"5"`
}
// TopCap specifies whether a cylinder has a top cap: [WithTop] or [NoTop].
type TopCap bool
const (
// WithTop adds the top cap.
WithTop TopCap = true
// NoTop leaves the top open.
NoTop TopCap = false
)
// BottomCap specifies whether a cylinder or cone has a bottom cap:
// [WithBottom] or [NoBottom].
type BottomCap bool
const (
// WithBottom adds the bottom cap.
WithBottom BottomCap = true
// NoBottom leaves the bottom open.
NoBottom BottomCap = false
)
// NewCylinder returns a Cylinder shape with given radius, height,
// number of radial segments, number of height segments,
// and presence of a top and/or bottom cap.
// Height is along the Y axis.
func NewCylinder(height, radius float32, radialSegs, heightSegs int, top TopCap, bottom BottomCap) *Cylinder {
cy := &Cylinder{}
cy.Defaults()
cy.Height = height
cy.TopRad = radius
cy.BotRad = radius
cy.RadialSegs = radialSegs
cy.HeightSegs = heightSegs
cy.Top = bool(top)
cy.Bottom = bool(bottom)
return cy
}
// NewCone returns a cone shape with the specified base radius, height,
// number of radial segments, number of height segments, and presence of a bottom cap.
// Height is along the Y axis.
func NewCone(height, radius float32, radialSegs, heightSegs int, bottom BottomCap) *Cylinder {
cy := &Cylinder{}
cy.Defaults()
cy.Height = height
cy.TopRad = 0
cy.BotRad = radius
cy.RadialSegs = radialSegs
cy.HeightSegs = heightSegs
cy.Top = false
cy.Bottom = bool(bottom)
return cy
}
func (cy *Cylinder) Defaults() {
cy.Height = 1
cy.TopRad = 0.5
cy.BotRad = 0.5
cy.RadialSegs = 32
cy.HeightSegs = 32
cy.Top = true
cy.Bottom = true
cy.AngStart = 0
cy.AngLen = 360
}
func (cy *Cylinder) MeshSize() (numVertex, nIndex int, hasColor bool) {
numVertex, nIndex = CylinderSectorN(cy.RadialSegs, cy.HeightSegs, TopCap(cy.Top), BottomCap(cy.Bottom))
return
}
// Set sets points in given allocated arrays.
func (cy *Cylinder) Set(vertex, normal, texcoord, clrs math32.ArrayF32, index math32.ArrayU32) {
cy.CBBox = SetCylinderSector(vertex, normal, texcoord, index, cy.VertexOffset, cy.IndexOffset, cy.Height, cy.TopRad, cy.BotRad, cy.RadialSegs, cy.HeightSegs, cy.AngStart, cy.AngLen, TopCap(cy.Top), BottomCap(cy.Bottom), cy.Pos)
}
////////////////////////////////////////////////////////////////
// CylinderSectorN returns the N's for the cylinder (truncated cone) sector
// vertex and index data with given parameters
func CylinderSectorN(radialSegs, heightSegs int, top TopCap, bottom BottomCap) (numVertex, nIndex int) {
numVertex = (heightSegs + 1) * (radialSegs + 1)
nIndex = radialSegs * heightSegs * 6
if top {
numVertex += radialSegs*2 + 2
nIndex += radialSegs * 3
}
if bottom {
numVertex += radialSegs*2 + 2
nIndex += radialSegs * 3
}
return
}
// SetCone creates a cone mesh with the specified base radius, height,
// vertex, normal, tex, index data at given starting *vertex* index
// (i.e., multiply this *3 to get actual float offset in Vtx array),
// number of radial segments, number of height segments, and presence of a bottom cap.
// Height is along the Y axis.
// pos is an arbitrary offset (for composing shapes).
func SetCone(vertex, normal, texcoord math32.ArrayF32, index math32.ArrayU32, vtxOff, idxOff int, height, radius float32, radialSegs, heightSegs int, bottom BottomCap, pos math32.Vector3) math32.Box3 {
return SetCylinderSector(vertex, normal, texcoord, index, vtxOff, idxOff, height, 0, radius, radialSegs, heightSegs, 0, 360, NoTop, bottom, pos)
}
// SetCylinderSector creates a generalized cylinder (truncated cone) sector
// vertex, normal, tex, index data at given starting *vertex* index
// (i.e., multiply this *3 to get actual float offset in Vtx array),
// with the specified top and bottom radii, height, number of radial segments,
// number of height segments, sector start angle in degrees (start = -1,0,0)
// sector size angle in degrees, and presence of a top and/or bottom cap.
// Height is along the Y axis.
// pos is an arbitrary offset (for composing shapes).
func SetCylinderSector(vertex, normal, texcoord math32.ArrayF32, index math32.ArrayU32, vtxOff, idxOff int, height, topRad, botRad float32, radialSegs, heightSegs int, angStart, angLen float32, top TopCap, bottom BottomCap, pos math32.Vector3) math32.Box3 {
hHt := height / 2
vtxs := [][]int{}
uvsOrig := [][]math32.Vector2{}
angStRad := math32.DegToRad(angStart)
angLenRad := math32.DegToRad(angLen)
bb := math32.Box3{}
bb.SetEmpty()
idx := 0
vidx := vtxOff * 3
tidx := vtxOff * 2
var pt math32.Vector3
for y := 0; y <= heightSegs; y++ {
var vtxsRow = []int{}
var uvsRow = []math32.Vector2{}
v := float32(y) / float32(heightSegs)
radius := v*(botRad-topRad) + topRad
for x := 0; x <= radialSegs; x++ {
u := float32(x) / float32(radialSegs)
pt.X = -radius * math32.Cos(u*angLenRad+angStRad)
pt.Y = -v*height + hHt
pt.Z = radius * math32.Sin(u*angLenRad+angStRad)
pt.SetAdd(pos)
vertex.SetVector3(vidx+idx*3, pt)
bb.ExpandByPoint(pt)
vtxsRow = append(vtxsRow, idx)
uvsRow = append(uvsRow, math32.Vec2(u, 1.0-v))
idx++
}
vtxs = append(vtxs, vtxsRow)
uvsOrig = append(uvsOrig, uvsRow)
}
tanTheta := (botRad - topRad) / height
var na, nb math32.Vector3
vOff := uint32(vtxOff)
ii := idxOff
for x := range radialSegs {
if topRad != 0 {
vertex.GetVector3(3*vtxs[0][x], &na)
vertex.GetVector3(3*vtxs[0][x+1], &nb)
} else {
vertex.GetVector3(3*vtxs[1][x], &na)
vertex.GetVector3(3*vtxs[1][x+1], &nb)
}
na.Y = math32.Sqrt(na.X*na.X+na.Z*na.Z) * tanTheta
na.SetNormal()
nb.Y = math32.Sqrt(nb.X*nb.X+nb.Z*nb.Z) * tanTheta
nb.SetNormal()
for y := range heightSegs {
v1 := vtxs[y][x]
v2 := vtxs[y+1][x]
v3 := vtxs[y+1][x+1]
v4 := vtxs[y][x+1]
n1 := na
n2 := na
n3 := nb
n4 := nb
uv1 := uvsOrig[y][x]
uv2 := uvsOrig[y+1][x]
uv3 := uvsOrig[y+1][x+1]
uv4 := uvsOrig[y][x+1]
index.Set(ii, vOff+uint32(v1), vOff+uint32(v2), vOff+uint32(v4))
ii += 3
normal.SetVector3(3*v1, n1)
normal.SetVector3(3*v2, n2)
normal.SetVector3(3*v4, n4)
index.Set(ii, vOff+uint32(v2), vOff+uint32(v3), vOff+uint32(v4))
ii += 3
normal.SetVector3(3*v2, n2)
normal.SetVector3(3*v3, n3)
normal.SetVector3(3*v4, n4)
texcoord.SetVector2(2*v1, uv1)
texcoord.SetVector2(2*v2, uv2)
texcoord.SetVector2(2*v3, uv3)
texcoord.SetVector2(2*v4, uv4)
}
}
// Top cap
if top && topRad > 0 {
// Array of vertex indicesOrig to build used to build the faces.
idxsOrig := []uint32{}
// Appends top segments vtxs and builds array of its idxsOrig
var uv1, uv2, uv3 math32.Vector2
for x := range radialSegs {
uv1 = uvsOrig[0][x]
uv2 = uvsOrig[0][x+1]
uv3 = math32.Vec2(uv2.X, 0)
// Appends CENTER with its own UV.
vertex.Set(vidx+idx*3, 0, hHt, 0)
normal.Set(vidx+idx*3, 0, 1, 0)
texcoord.SetVector2(tidx+idx*2, uv3)
idxsOrig = append(idxsOrig, uint32(idx))
idx++
// Appends vertex
v := math32.Vector3{}
vi := vtxs[0][x]
vertex.GetVector3(3*vi, &v)
vertex.SetVector3(vidx+idx*3, v)
normal.Set(vidx+idx*3, 0, 1, 0)
texcoord.SetVector2(tidx+idx*2, uv1)
idxsOrig = append(idxsOrig, uint32(idx))
idx++
}
// Appends copy of first vertex (center)
var pt, norm math32.Vector3
var uv math32.Vector2
vertex.GetVector3(3*int(idxsOrig[0]), &pt)
normal.GetVector3(3*int(idxsOrig[0]), &norm)
texcoord.GetVector2(2*int(idxsOrig[0]), &uv)
vertex.SetVector3(vidx+idx*3, pt)
normal.SetVector3(vidx+idx*3, norm)
texcoord.SetVector2(tidx+idx*2, uv)
idxsOrig = append(idxsOrig, uint32(idx))
idx++
// Appends copy of second vertex (v1) USING LAST UVec2
vertex.GetVector3(3*int(idxsOrig[1]), &pt)
normal.GetVector3(3*int(idxsOrig[1]), &norm)
vertex.SetVector3(vidx+idx*3, pt)
normal.SetVector3(vidx+idx*3, norm)
texcoord.SetVector2(tidx+idx*2, uv2)
idxsOrig = append(idxsOrig, uint32(idx))
idx++
// Append faces idxsOrig
for x := range radialSegs {
pos := 2 * x
i1 := idxsOrig[pos]
i2 := idxsOrig[pos+1]
i3 := idxsOrig[pos+3]
index.Set(ii, uint32(vOff+i1), uint32(vOff+i2), uint32(vOff+i3))
ii += 3
}
}
// Bottom cap
if bottom && botRad > 0 {
// Array of vertex idxsOrig to build used to build the faces.
idxsOrig := []uint32{}
// Appends top segments vtxs and builds array of its idxsOrig
var uv1, uv2, uv3 math32.Vector2
for x := range radialSegs {
uv1 = uvsOrig[heightSegs][x]
uv2 = uvsOrig[heightSegs][x+1]
uv3 = math32.Vec2(uv2.X, 1)
// Appends CENTER with its own UV.
vertex.Set(vidx+idx*3, 0, -hHt, 0)
normal.Set(vidx+idx*3, 0, -1, 0)
texcoord.SetVector2(tidx+idx*2, uv3)
idxsOrig = append(idxsOrig, uint32(idx))
idx++
// Appends vertex
v := math32.Vector3{}
vi := vtxs[heightSegs][x]
vertex.GetVector3(3*vi, &v)
vertex.SetVector3(vidx+idx*3, v)
normal.Set(vidx+idx*3, 0, -1, 0)
texcoord.SetVector2(tidx+idx*2, uv1)
idxsOrig = append(idxsOrig, uint32(idx))
idx++
}
// Appends copy of first vertex (center)
var pt, norm math32.Vector3
var uv math32.Vector2
vertex.GetVector3(3*int(idxsOrig[0]), &pt)
normal.GetVector3(3*int(idxsOrig[0]), &norm)
texcoord.GetVector2(2*int(idxsOrig[0]), &uv)
vertex.SetVector3(vidx+idx*3, pt)
normal.SetVector3(vidx+idx*3, norm)
texcoord.SetVector2(tidx+idx*2, uv)
idxsOrig = append(idxsOrig, uint32(idx))
idx++
// Appends copy of second vertex (v1) USING LAST UVec2
vertex.GetVector3(3*int(idxsOrig[1]), &pt)
normal.GetVector3(3*int(idxsOrig[1]), &norm)
vertex.SetVector3(vidx+idx*3, pt)
normal.SetVector3(vidx+idx*3, norm)
texcoord.SetVector2(tidx+idx*2, uv2)
idxsOrig = append(idxsOrig, uint32(idx))
// Appends faces idxsOrig
for x := range radialSegs {
pos := 2 * x
i1 := idxsOrig[pos]
i2 := idxsOrig[pos+3]
i3 := idxsOrig[pos+1]
index.Set(ii, uint32(vOff+i1), uint32(vOff+i2), uint32(vOff+i3))
ii += 3
}
}
return bb
}
// Copyright 2022 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package shape
import "cogentcore.org/core/math32"
// ShapeGroup is a group of shapes.
// Returns summary data for shape elements.
type ShapeGroup struct { //types:add -setters
ShapeBase
// list of shapes in group
Shapes []Mesh
}
var _ Mesh = (*ShapeGroup)(nil)
// MeshSize returns number of vertex, index points in this shape element.
func (sb *ShapeGroup) MeshSize() (numVertex, numIndex int, hasColor bool) {
numVertex = 0
numIndex = 0
hasColor = false
for _, sh := range sb.Shapes {
nv, ni, hc := sh.MeshSize()
numVertex += nv
numIndex += ni
hasColor = hasColor || hc // todo: not good if inconsistent..
}
return
}
// Set sets points in given allocated arrays, also updates offsets
func (sb *ShapeGroup) Set(vertex, normal, texcoord, clrs math32.ArrayF32, index math32.ArrayU32) {
vo := sb.VertexOffset
io := sb.IndexOffset
sb.CBBox.SetEmpty()
for _, sh := range sb.Shapes {
sh.SetOffsets(vo, io)
sh.Set(vertex, normal, texcoord, clrs, index)
sb.CBBox.ExpandByBox(sh.MeshBBox())
nv, ni, _ := sh.MeshSize()
vo += nv
io += ni
}
}
// Copyright 2022 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package shape
import (
"fmt"
"cogentcore.org/core/math32"
)
// HeightfieldData2D is an interface for accessing the 2D Heightfield data.
type HeightfieldData2D interface {
// HeightfieldValue returns the data value at given coordinate.
HeightfieldValue(x, y int) float32
}
// Heightfield represents planar 2D data with the third dimension
// provided by the data values, which can be visualized as either
// a triangulated plane or discrete bars.
type Heightfield struct { //types:add -setters
ShapeBase
// Bars represents the data using discrete bars, else triangles on the plane.
Bars bool
// axis along which the normal perpendicular to the plane points.
// E.g., if the Y axis is specified, then it is a standard X-Z ground plane.
// See also NormalNeg for whether it is facing in the positive or
// negative of the given axis.
NormalAxis math32.Dims
// if false, the plane normal is facing in the positive direction
// along specified NormalAxis, otherwise it faces in the negative.
NormalNeg bool
// Size is the 2D size of the heightfield data values.
Size math32.Vector2i
// 3D visual size, with the Z value providing scaling for data heights.
VisSize math32.Vector3
// Data for the heights of points in the field.
Data HeightfieldData2D
// BarPct is proportion (0-1) that the bar occupies within its unit square
// (i.e., 1-BarPct is the spacing between bars).
BarPct float32
// Offset from origin along direction of normal to the plane.
Offset float32
}
// NewHeightfield returns a Heightfield with given data and visual size.
func NewHeightfield(axis math32.Dims, data HeightfieldData2D, nx, ny int, width, height, zscale float32) *Heightfield {
hf := &Heightfield{}
hf.Defaults()
hf.NormalAxis = axis
hf.Data = data
hf.Size.Set(int32(nx), int32(ny))
hf.VisSize.Set(width, height, zscale)
return hf
}
func (hf *Heightfield) Defaults() {
hf.NormalAxis = math32.Y
hf.NormalNeg = false
hf.VisSize.Set(1, 1, 1)
hf.BarPct = 0.9
hf.Offset = 0
}
func (hf *Heightfield) MeshSize() (numVertex, nIndex int, hasColor bool) {
if hf.Bars {
numVertex, nIndex = HeightfieldBarsN(int(hf.Size.X), int(hf.Size.Y))
} else {
numVertex, nIndex = HeightfieldN(int(hf.Size.X), int(hf.Size.Y))
}
return
}
// Set sets points in given allocated arrays.
func (hf *Heightfield) Set(vertex, normal, texcoord, clrs math32.ArrayF32, index math32.ArrayU32) {
waxis, haxis, wdir, hdir := NormPlaneAxes(hf.NormalAxis, hf.NormalNeg)
vo, io := hf.VertexOffset, hf.IndexOffset
if hf.Bars {
SetHeightfieldBars(vertex, normal, texcoord, index, vo, io, int(hf.Size.X), int(hf.Size.Y), hf.Data, waxis, haxis, wdir, hdir, hf.VisSize.X, hf.VisSize.Y, 0, 0, hf.Offset, hf.VisSize.Z, hf.BarPct, hf.Pos)
} else {
SetHeightfield(vertex, normal, texcoord, index, vo, io, int(hf.Size.X), int(hf.Size.Y), hf.Data, waxis, haxis, wdir, hdir, hf.VisSize.X, hf.VisSize.Y, 0, 0, hf.Offset, hf.VisSize.Z, hf.Pos)
}
nv, _, _ := hf.MeshSize()
hf.CBBox = BBoxFromVtxs(vertex, vo, nv)
}
//////// Planar representation
func HeightfieldN(nx, ny int) (numVertex, nIndex int) {
numVertex = ny * nx
nIndex = 6 * (ny - 1) * (nx - 1) // two triangles per square
return
}
// SetHeightfield sets planar Heightfield vertex, normal, tex, index data
// at given starting *vertex* index
// (i.e., multiply this *3 to get actual float offset in Vtx array), and starting Index index.
// nx, ny are number of data points along each axis of the data (wrap in
// a struct that implements HeightfieldData2D): a min of 2 in each dim required.
// waxis, haxis = width, height axis, wdir, hdir are the directions for width
// and height dimensions. zscale multiplies the heightfield values.
// offset is the distance to place the plane along the orthogonal axis.
// pos is a 3D position offset.
func SetHeightfield(vertex, normal, texcoord math32.ArrayF32, index math32.ArrayU32, vtxOff, idxOff int, nx, ny int, data HeightfieldData2D, waxis, haxis math32.Dims, wdir, hdir int, width, height, woff, hoff, zoff, zscale float32, pos math32.Vector3) error {
if ny < 2 || nx < 2 {
return fmt.Errorf("SetHeightfield: must have at least 2 data points along each dimension")
}
zaxis := OrthoAxis(waxis, haxis)
fwdir := float32(wdir) * width
fhdir := float32(hdir) * height
if wdir < 0 {
woff = width + woff
}
if hdir < 0 {
hoff = height + hoff
}
vidx := vtxOff // vertex index
var vtx, norm, a, b, c, d math32.Vector3
var tex math32.Vector2
// have to write all verticies first, so have access to all the data
// for computing norms!
for yi := ny - 1; yi >= 0; yi-- {
for xi := range nx {
val := data.HeightfieldValue(xi, yi)
vtx.SetDim(waxis, float32(xi)*fwdir+woff)
vtx.SetDim(haxis, float32(yi)*fhdir+hoff)
vtx.SetDim(zaxis, val*zscale)
vtx.Add(pos).ToSlice(vertex, vidx*3)
tex.Set(float32(xi)/float32(nx-1), (float32(yi) / float32(ny-1)))
tex.ToSlice(texcoord, vidx*2)
vidx++
}
}
// b c
// a d
// abd, bcd
// because y is inverted, a is higher y, b is lower
ny1 := ny - 1
vIdx := func(y, x int) int {
return ((ny1-y)*nx + x)
}
nidx := vtxOff * 3
iidx := idxOff // index index
for yi := ny1; yi >= 0; yi-- {
for xi := range nx {
if yi == 0 { // no index
if xi == nx-1 { // no right
vertex.GetVector3(vIdx(1, xi-1)*3, &a) // a = yi=1, xi=left
vertex.GetVector3(vIdx(0, xi-1)*3, &b) // b = yi=0, xi=left
vertex.GetVector3(vIdx(0, xi)*3, &c) // c = yi=0, xi=us
} else {
vertex.GetVector3(vIdx(1, xi)*3, &a) // a = yi=1, xi=us
vertex.GetVector3(vIdx(0, xi)*3, &b) // b = yi=0, xi=us
vertex.GetVector3(vIdx(0, xi+1)*3, &c) // c = yi=0, xi=right
}
} else { // do indexes
if xi == nx-1 { // no right, no index
vertex.GetVector3(vIdx(yi, xi-1)*3, &a) // a = yi, xi=left
vertex.GetVector3(vIdx(yi-1, xi-1)*3, &b) // b = yi-1, xi=left
vertex.GetVector3(vIdx(yi-1, xi)*3, &c) // c = yi-1, xi=us
} else {
ai := vIdx(yi, xi) // a = yi, xi=us
bi := vIdx(yi-1, xi) // b = yi-1, xi=us
ci := vIdx(yi-1, xi+1) // c = yi-1, xi=right
di := vIdx(yi, xi+1) // d = yi, xi=right
vertex.GetVector3(ai*3, &a)
vertex.GetVector3(bi*3, &b)
vertex.GetVector3(ci*3, &c)
vertex.GetVector3(di*3, &d)
index.Set(iidx, uint32(ai), uint32(bi), uint32(di), uint32(bi), uint32(ci), uint32(di))
iidx += 6
}
}
norm = math32.Normal(a, b, c)
norm.ToSlice(normal, nidx)
nidx += 3
}
}
return nil
}
//////// Bars representation
func HeightfieldBarsN(nx, ny int) (numVertex, nIndex int) {
nper := 5
vtxSz, idxSz := PlaneN(1, 1)
numVertex = vtxSz * nper * ny * nx
nIndex = idxSz * nper * ny * nx
return
}
// MinBarHeight ensures that there is always at least some dimensionality
// to the bars. Affects transparency rendering etc
var MinBarHeight = float32(1.0e-6)
// SetHeightfieldBars sets bars Heightfield vertex, normal, index data
// at given starting *vertex* index
// (i.e., multiply this *3 to get actual float offset in Vtx array), and starting Index index.
// nx, ny are number of data points along each axis of the data (wrap in
// a struct that implements HeightfieldData2D): a min of 2 in each dim required.
// waxis, haxis = width, height axis, wdir, hdir are the directions for width
// and height dimensions. zscale multiplies the heightfield values,
// and barPct is proportion (0-1) that the bar occupies within its unit square
// (i.e., 1-barPct is the spacing between bars).
// offset is the distance to place the plane along the orthogonal axis.
// pos is a 3D position offset.
func SetHeightfieldBars(vertex, normal, texcoord math32.ArrayF32, index math32.ArrayU32, vtxOff, idxOff int, nx, ny int, data HeightfieldData2D, waxis, haxis math32.Dims, wdir, hdir int, width, height, woff, hoff, zoff, zscale, barPct float32, pos math32.Vector3) error {
zaxis := OrthoAxis(waxis, haxis)
barSpc := (1.0 - barPct)
segs := 1
vtxSz, idxSz := PlaneN(segs, segs)
pidx := 0
for yi := ny - 1; yi >= 0; yi-- {
y0 := barSpc - float32(yi+1)
for xi := range nx {
poff := vtxOff + pidx*vtxSz*5
ioff := idxOff + pidx*idxSz*5
x0 := barSpc + float32(xi)
val := data.HeightfieldValue(xi, yi)
ht := zscale * math32.Abs(val)
if ht < MinBarHeight {
ht = MinBarHeight
}
base := float32(0)
if val >= 0 {
// back
SetPlane(vertex, normal, texcoord, index, poff, ioff, waxis, zaxis, -1, -1, barPct, ht, x0, base, y0, segs, segs, pos)
// left
SetPlane(vertex, normal, texcoord, index, poff+1*vtxSz, ioff+1*idxSz, haxis, zaxis, -1, -1, barPct, ht, y0, base, x0+barPct, segs, segs, pos)
// right
SetPlane(vertex, normal, texcoord, index, poff+2*vtxSz, ioff+2*idxSz, haxis, zaxis, 1, -1, barPct, ht, y0, base, x0, segs, segs, pos)
// top
SetPlane(vertex, normal, texcoord, index, poff+3*vtxSz, ioff+3*idxSz, waxis, haxis, 1, 1, barPct, barPct, x0, y0, ht, segs, segs, pos)
// front
SetPlane(vertex, normal, texcoord, index, poff+4*vtxSz, ioff+4*idxSz, waxis, zaxis, 1, -1, barPct, ht, x0, base, y0+barPct, segs, segs, pos)
} else {
base = -ht
// back
SetPlane(vertex, normal, texcoord, index, poff, ioff, waxis, zaxis, 1, -1, barPct, ht, x0, base, y0, segs, segs, pos)
// bottom
SetPlane(vertex, normal, texcoord, index, poff+1*vtxSz, ioff+1*idxSz, waxis, haxis, 1, 1, barPct, barPct, x0, y0, base, segs, segs, pos)
// left
SetPlane(vertex, normal, texcoord, index, poff+2*vtxSz, ioff+2*idxSz, haxis, zaxis, 1, -1, barPct, ht, y0, base, x0+barPct, segs, segs, pos)
// right
SetPlane(vertex, normal, texcoord, index, poff+3*vtxSz, ioff+3*idxSz, haxis, zaxis, 1, -1, barPct, ht, y0, base, x0, segs, segs, pos)
// front
SetPlane(vertex, normal, texcoord, index, poff+4*vtxSz, ioff+4*idxSz, waxis, zaxis, 1, -1, barPct, ht, x0, base, y0+barPct, segs, segs, pos)
}
pidx++
}
}
return nil
}
// Copyright 2022 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package shape
import (
"image/color"
"log"
"math"
"cogentcore.org/core/math32"
)
// Lines are lines rendered as long thin boxes defined by points
// and width parameters. The Mesh must be drawn in the XY plane (i.e., use Z = 0
// or a constant unless specifically relevant to have full 3D variation).
// Rotate the solid to put into other planes.
type Lines struct { //types:add -setters
ShapeBase
// line points (must be 2 or more)
Points []math32.Vector3
// line width, Y = height perpendicular to line direction, and X = depth
Width math32.Vector2
// optional colors for each point -- actual color interpolates between
Colors []color.Color
// if true, connect the first and last points to form a closed shape
Closed bool
}
// NewLines returns a Lines shape with given size
func NewLines(points []math32.Vector3, width math32.Vector2, closed bool) *Lines {
ln := &Lines{}
ln.Defaults()
ln.Points = points
ln.Width = width
ln.Closed = closed
return ln
}
func (ln *Lines) Defaults() {
ln.Width.Set(.1, .1)
}
func (ln *Lines) MeshSize() (numVertex, nIndex int, hasColor bool) {
numVertex, nIndex = LinesN(len(ln.Points), ln.Closed)
return
}
// Set sets points in given allocated arrays
func (ln *Lines) Set(vertex, normal, texcoord, clrs math32.ArrayF32, index math32.ArrayU32) {
ln.CBBox = SetLines(vertex, normal, texcoord, index, ln.VertexOffset, ln.IndexOffset, ln.Points, ln.Width, ln.Closed, ln.Pos)
// todo: colors!
}
/////////////////////////////////////////////////////////////////////
// LinesN returns number of vertex and idx points
func LinesN(npoints int, closed bool) (numVertex, nIndex int) {
qvn, qin := QuadN()
nv, ni := 4*(npoints-1)*qvn, 4*(npoints-1)*qin
if closed {
nv += 4 * qvn
ni += 4 * qin
} else {
nv += 2 * qvn
ni += 2 * qin
}
return nv, ni
}
// SetLines sets lines rendered as long thin boxes defined by points
// and width parameters. The Mesh must be drawn in the XY plane (i.e., use Z = 0
// or a constant unless specifically relevant to have full 3D variation).
// Rotate to put into other planes.
func SetLines(vertex, normal, texcoord math32.ArrayF32, index math32.ArrayU32, vtxOff, idxOff int, points []math32.Vector3, width math32.Vector2, closed bool, pos math32.Vector3) math32.Box3 {
np := len(points)
if np < 2 {
log.Printf("vshape.SetLines: need 2 or more Points\n")
return math32.Box3{}
}
pts := points
if closed {
pts = append(pts, points[0])
np++
}
vidx := vtxOff * 3
voff := vidx
ioff := idxOff
qvn, qin := QuadN()
wdy := width.Y / 2
wdz := width.X / 2
pi2 := float32(math.Pi / 2)
// logic for miter joins: https://math.stackexchange.com/questions/1849784/calculate-miter-points-of-stroked-vectors-in-cartesian-plane
for li := 0; li < np-1; li++ {
sp := pts[li]
sp.SetAdd(pos)
ep := pts[li+1]
ep.SetAdd(pos)
spSt := !closed && li == 0
epEd := !closed && li == np-2
swap := false
if ep.X < sp.X {
sp, ep = ep, sp
spSt, epEd = epEd, spSt
swap = true
}
v := ep.Sub(sp)
vn := v.Normal()
xyang := math32.Atan2(vn.Y, vn.X)
xy := math32.Vec2(wdy*math32.Cos(xyang+pi2), wdy*math32.Sin(xyang+pi2))
// sypzm --- eypzm
// / | / |
// sypzp -- eypzp |// ToAlphaPreMult converts a non-alpha-premultiplied color to a premultiplied one.
// | symzm --| eymzm
// | / | /
// symzp -- eymzp
sypzp, sypzm, symzp, symzm := sp, sp, sp, sp
eypzp, eypzm, eymzp, eymzm := ep, ep, ep, ep
if !spSt {
pp := sp
if swap {
if closed && li == np-2 {
pp = pts[1]
} else {
pp = pts[li+2]
}
pp.SetAdd(pos)
} else {
if closed && li == 0 {
pp = pts[np-2]
} else {
pp = pts[li-1]
}
pp.SetAdd(pos)
}
xy = MiterPts(pp.X, pp.Y, sp.X, sp.Y, ep.X, ep.Y, wdy)
}
sypzp.X += xy.X
sypzp.Y += xy.Y
sypzp.Z += wdz
sypzm.X += xy.X
sypzm.Y += xy.Y
sypzm.Z += -wdz
symzp.X += -xy.X
symzp.Y += -xy.Y
symzp.Z += wdz
symzm.X += -xy.X
symzm.Y += -xy.Y
symzm.Z += -wdz
if !epEd {
xp := ep
if swap {
if closed && li == 0 {
xp = pts[np-2]
} else {
xp = pts[li-1]
}
xp.SetAdd(pos)
} else {
if closed && li == np-2 {
xp = pts[1]
} else {
xp = pts[li+2]
}
xp.SetAdd(pos)
}
xy = MiterPts(xp.X, xp.Y, ep.X, ep.Y, sp.X, sp.Y, wdy)
}
eypzp.X += xy.X
eypzp.Y += xy.Y
eypzp.Z += wdz
eypzm.X += xy.X
eypzm.Y += xy.Y
eypzm.Z += -wdz
eymzp.X += -xy.X
eymzp.Y += -xy.Y
eymzp.Z += wdz
eymzm.X += -xy.X
eymzm.Y += -xy.Y
eymzm.Z += -wdz
// front back
// 0 3 1 2
// 1 2 0 3
// two triangles are: 0,1,2; 0,2,3
if swap {
SetQuad(vertex, normal, texcoord, index, voff, ioff, []math32.Vector3{sypzm, symzm, eymzm, eypzm}, nil, pos)
voff += qvn
ioff += qin
SetQuad(vertex, normal, texcoord, index, voff, ioff, []math32.Vector3{sypzp, sypzm, eypzm, eypzp}, nil, pos) // bottom (yp, upside down)
voff += qvn
ioff += qin
SetQuad(vertex, normal, texcoord, index, voff, ioff, []math32.Vector3{symzm, symzp, eymzp, eymzm}, nil, pos) // top (ym)
voff += qvn
ioff += qin
SetQuad(vertex, normal, texcoord, index, voff, ioff, []math32.Vector3{symzp, sypzp, eypzp, eymzp}, nil, pos) // front (zp)
voff += qvn
ioff += qin
} else {
SetQuad(vertex, normal, texcoord, index, voff, ioff, []math32.Vector3{symzm, sypzm, eypzm, eymzm}, nil, pos) // back (zm)
voff += qvn
ioff += qin
SetQuad(vertex, normal, texcoord, index, voff, ioff, []math32.Vector3{symzp, symzm, eymzm, eymzp}, nil, pos) // bottom (ym)
voff += qvn
ioff += qin
SetQuad(vertex, normal, texcoord, index, voff, ioff, []math32.Vector3{sypzm, sypzp, eypzp, eypzm}, nil, pos) // top (yp)
voff += qvn
ioff += qin
SetQuad(vertex, normal, texcoord, index, voff, ioff, []math32.Vector3{sypzp, symzp, eymzp, eypzp}, nil, pos) // front (zp)
voff += qvn
ioff += qin
}
if spSt { // do cap
SetQuad(vertex, normal, texcoord, index, voff, ioff, []math32.Vector3{sypzm, symzm, symzp, sypzp}, nil, pos)
voff += qvn
ioff += qin
}
if epEd {
SetQuad(vertex, normal, texcoord, index, voff, ioff, []math32.Vector3{eypzp, eymzp, eymzm, eypzm}, nil, pos)
voff += qvn
ioff += qin
}
}
vn := voff - vtxOff
return BBoxFromVtxs(vertex, vtxOff, vn)
}
// MiterPts returns the miter points
func MiterPts(ax, ay, bx, by, cx, cy, w2 float32) math32.Vector2 {
ppd := math32.Vec2(ax-bx, ay-by)
ppu := ppd.Normal()
epd := math32.Vec2(cx-bx, cy-by)
epv := epd.Normal()
dp := ppu.Dot(epv)
jang := math32.Acos(dp)
wfact := w2 / math32.Sin(jang)
uv := ppu.MulScalar(-wfact)
vv := epv.MulScalar(-wfact)
sv := uv.Add(vv)
return sv
}
// Copyright 2024 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package shape
import (
"cogentcore.org/core/base/slicesx"
"cogentcore.org/core/math32"
)
// Mesh is an interface for specifying the triangle Mesh data for 3D shapes.
// This is used for all mesh / shape data in the phong system.
type Mesh interface {
// MeshSize returns number of vertex, index points in this shape element,
// and whether it has per-vertex color values.
MeshSize() (numVertex, nIndex int, hasColor bool)
// Set sets points in given allocated arrays.
Set(vertex, normal, texcoord, clrs math32.ArrayF32, index math32.ArrayU32)
// Offsets returns starting offset for vertices, indexes in full shape array,
// in terms of points, not floats.
Offsets() (vtxOffset, idxOffset int)
// SetOffsets sets starting offset for vertices, indexes in full shape array,
// in terms of points, not floats.
SetOffsets(vtxOffset, idxOffset int)
// MeshBBox returns the bounding box for the shape vertex points,
// typically centered around 0.
// This is only valid after Set has been called.
MeshBBox() math32.Box3
}
// MeshData provides storage buffers for shapes specified using the [Mesh]
// interface.
type MeshData struct {
// number of vertex points allocated for the Vertex, Normal, TexCoord,
// and optional Colors data (if HasColor).
NumVertex int
// number of indexes.
NumIndex int
// whether this mech has per-vertex colors, as math32.Vector4 per vertex.
HasColor bool
// MeshBBox is the bounding box for the shape vertex points,
// typically centered around 0.
MeshBBox math32.Box3
// buffers that hold mesh data for the [Mesh.Set] method.
Vertex, Normal, TexCoord, Colors math32.ArrayF32
Index math32.ArrayU32
}
// NewMeshData returns a new MeshData and sets our buffer data
// from [Mesh] interface.
func NewMeshData(mesh Mesh) *MeshData {
md := &MeshData{}
return md.Set(mesh)
}
// Set sets mesh data into our buffers, from [shape.Mesh].
func (md *MeshData) Set(mesh Mesh) *MeshData {
md.NumVertex, md.NumIndex, md.HasColor = mesh.MeshSize()
md.Vertex = slicesx.SetLength(md.Vertex, md.NumVertex*3)
md.Normal = slicesx.SetLength(md.Normal, md.NumVertex*3)
md.TexCoord = slicesx.SetLength(md.TexCoord, md.NumVertex*2)
md.Index = slicesx.SetLength(md.Index, md.NumIndex)
if md.HasColor {
md.Colors = slicesx.SetLength(md.Colors, md.NumVertex*4)
}
mesh.Set(md.Vertex, md.Normal, md.TexCoord, md.Colors, md.Index)
md.MeshBBox = mesh.MeshBBox()
return md
}
// Copyright 2022 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package shape
import (
"cogentcore.org/core/math32"
)
// Plane is a flat 2D plane, which can be oriented along any
// axis facing either positive or negative
type Plane struct { //types:add -setters
ShapeBase
// axis along which the normal perpendicular to the plane points.
// E.g., if the Y axis is specified, then it is a standard X-Z ground plane.
// See also NormalNeg for whether it is facing in the positive or
// negative of the given axis.
NormalAxis math32.Dims
// if false, the plane normal is facing in the positive direction
// along specified NormalAxis, otherwise it faces in the negative.
NormalNeg bool
// 2D size of plane
Size math32.Vector2
// number of segments to divide plane into (enforced to be at least 1).
// Can generally increase rendering quality to have > 1.
Segs math32.Vector2i
// offset from origin along direction of normal to the plane.
Offset float32
}
// NewPlane returns a Plane shape with given size.
func NewPlane(axis math32.Dims, width, height float32) *Plane {
pl := &Plane{}
pl.Defaults()
pl.NormalAxis = axis
pl.Size.Set(width, height)
return pl
}
func (pl *Plane) Defaults() {
pl.NormalAxis = math32.Y
pl.NormalNeg = false
pl.Size.Set(1, 1)
pl.Segs.Set(1, 1)
pl.Offset = 0
}
// MeshSize returns number of vertex, index points in this shape element
func (pl *Plane) MeshSize() (numVertex, nIndex int, hasColor bool) {
numVertex, nIndex = PlaneN(int(pl.Segs.X), int(pl.Segs.Y))
return
}
// Set sets points in given allocated arrays.
func (pl *Plane) Set(vertex, normal, texcoord, clrs math32.ArrayF32, index math32.ArrayU32) {
sz := SetPlaneAxisSize(vertex, normal, texcoord, index, pl.VertexOffset, pl.IndexOffset, pl.NormalAxis, pl.NormalNeg, pl.Size, pl.Segs, pl.Offset, pl.Pos)
mn := pl.Pos.Sub(sz)
mx := pl.Pos.Add(sz)
pl.CBBox.Set(&mn, &mx)
}
// PlaneN returns the N's for a single plane's worth of
// vertex and index data with given number of segments.
// Note: In *vertex* units, not float units (i.e., x3 to get
// actual float offset in Vtx array).
// numVertex = (wsegs + 1) * (hsegs + 1)
// nIndex = wsegs * hsegs * 6.
func PlaneN(wsegs, hsegs int) (numVertex, nIndex int) {
wsegs = max(wsegs, 1)
hsegs = max(hsegs, 1)
numVertex = (wsegs + 1) * (hsegs + 1)
nIndex = wsegs * hsegs * 6
return
}
// OrthoAxis returns the orthogonal axis relative to given "x" and "y"
// (width and height) axis dimensions.
func OrthoAxis(waxis, haxis math32.Dims) math32.Dims {
zaxis := math32.Z
if (waxis == math32.X && haxis == math32.Y) || (waxis == math32.Y && haxis == math32.X) {
zaxis = math32.Z
} else if (waxis == math32.X && haxis == math32.Z) || (waxis == math32.Z && haxis == math32.X) {
zaxis = math32.Y
} else if (waxis == math32.Z && haxis == math32.Y) || (waxis == math32.Y && haxis == math32.Z) {
zaxis = math32.X
}
return zaxis
}
// NormPlaneAxes returns the orthogonal plane axes for given normal axis,
// and directions to orient these axes.
func NormPlaneAxes(normalAxis math32.Dims, normalNeg bool) (waxis, haxis math32.Dims, wdir, hdir int) {
switch normalAxis {
case math32.X:
waxis = math32.Z
haxis = math32.Y
case math32.Y:
waxis = math32.X
haxis = math32.Z
case math32.Z:
waxis = math32.X
haxis = math32.Y
}
wdir = 1
hdir = -1
if normalAxis == math32.X && !normalNeg || normalAxis == math32.Z && !normalNeg {
wdir = -1
}
if normalAxis == math32.Y && normalNeg {
hdir = 1
}
return
}
// SetPlaneAxisSize sets plane vertex, normal, tex, index data at
// given starting *vertex* index (i.e., multiply this *3 to get
// actual float offset in Vtx array), and starting Index index.
// using Normal Axis, offset, and size params.
// wsegs, hsegs = number of segments to create in each dimension --
// more finely subdividing a plane allows for higher-quality lighting
// and texture rendering (minimum of 1 will be enforced).
// offset is the distance to place the plane along the orthogonal axis.
// pos is a 3D position offset. returns 3D size of plane.
// returns bounding box.
func SetPlaneAxisSize(vertex, normal, texcoord math32.ArrayF32, index math32.ArrayU32, vtxOff, idxOff int, normalAxis math32.Dims, normalNeg bool, size math32.Vector2, segs math32.Vector2i, offset float32, pos math32.Vector3) math32.Vector3 {
hSz := size.DivScalar(2)
thin := float32(.0000001)
sz := math32.Vector3{}
waxis, haxis, wdir, hdir := NormPlaneAxes(normalAxis, normalNeg)
negoff := offset
if normalNeg {
negoff = -negoff
}
sz.SetDim(waxis, hSz.X)
sz.SetDim(haxis, hSz.Y)
sz.SetDim(normalAxis, thin)
SetPlane(vertex, normal, texcoord, index, vtxOff, idxOff, waxis, haxis, wdir, hdir, size.X, size.Y, -hSz.X, -hSz.Y, negoff, int(segs.X), int(segs.Y), pos)
sz.SetDim(normalAxis, negoff+sz.Dim(normalAxis))
return sz
}
// SetPlane sets plane vertex, normal, tex, index data at given starting *vertex* index
// (i.e., multiply this *3 to get actual float offset in Vtx array), and starting Index index.
// waxis, haxis = width, height axis, wdir, hdir are the directions for width
// and height dimensions.
// wsegs, hsegs = number of segments to create in each dimension --
// more finely subdividing a plane allows for higher-quality lighting
// and texture rendering (minimum of 1 will be enforced).
// offset is the distance to place the plane along the orthogonal axis.
// pos is a 3D position offset.
func SetPlane(vertex, normal, texcoord math32.ArrayF32, index math32.ArrayU32, vtxOff, idxOff int, waxis, haxis math32.Dims, wdir, hdir int, width, height, woff, hoff, zoff float32, wsegs, hsegs int, pos math32.Vector3) {
zaxis := OrthoAxis(waxis, haxis)
wsegs = max(wsegs, 1)
hsegs = max(hsegs, 1)
norm := math32.Vector3{}
if zoff > 0 {
norm.SetDim(zaxis, 1)
} else {
norm.SetDim(zaxis, -1)
}
wsegs1 := wsegs + 1
hsegs1 := hsegs + 1
segWidth := width / float32(wsegs)
segHeight := height / float32(hsegs)
fwdir := float32(wdir) * segWidth
fhdir := float32(hdir) * segHeight
if wdir < 0 {
woff = width + woff
}
if hdir < 0 {
hoff = height + hoff
}
vtx := math32.Vector3{}
tex := math32.Vector2{}
vidx := vtxOff * 3
tidx := vtxOff * 2
for iy := range hsegs1 {
for ix := range wsegs1 {
vtx.SetDim(waxis, float32(ix)*fwdir+woff)
vtx.SetDim(haxis, float32(iy)*fhdir+hoff)
vtx.SetDim(zaxis, zoff)
vtx.Add(pos).ToSlice(vertex, vidx)
norm.ToSlice(normal, vidx)
tex.Set(float32(ix)/float32(wsegs), float32(1)-(float32(iy)/float32(hsegs)))
tex.ToSlice(texcoord, tidx)
vidx += 3
tidx += 2
}
}
// b c
// a d
// abd, bcd
sidx := idxOff
for iy := 0; iy < hsegs; iy++ {
for ix := 0; ix < wsegs; ix++ {
a := ix + wsegs1*iy
b := ix + wsegs1*(iy+1)
c := (ix + 1) + wsegs1*(iy+1)
d := (ix + 1) + wsegs1*iy
index.Set(sidx, uint32(a+vtxOff), uint32(b+vtxOff), uint32(d+vtxOff), uint32(b+vtxOff), uint32(c+vtxOff), uint32(d+vtxOff))
sidx += 6
}
}
}
// Copyright 2022 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package shape
//go:generate core generate
import "cogentcore.org/core/math32"
// ShapeBase is the base shape element
type ShapeBase struct { //types:add -setters
// vertex offset, in points
VertexOffset int
// index offset, in points
IndexOffset int
// cubic bounding box in local coords
CBBox math32.Box3
// all shapes take a 3D position offset to enable composition
Pos math32.Vector3
}
// Offsets returns starting offset for vertices, indexes in full shape array,
// in terms of points, not floats
func (sb *ShapeBase) Offsets() (vtxOffset, idxOffset int) {
vtxOffset, idxOffset = sb.VertexOffset, sb.IndexOffset
return
}
// SetOffsets sets starting offsets for vertices, indexes in full shape array
func (sb *ShapeBase) SetOffsets(vtxOffset, idxOffset int) {
sb.VertexOffset, sb.IndexOffset = vtxOffset, idxOffset
}
// MeshBBox returns the bounding box for the shape, typically centered around 0
// This is only valid after Set has been called.
func (sb *ShapeBase) MeshBBox() math32.Box3 {
return sb.CBBox
}
// SetColor sets color for given range of vertex indexes
func SetColor(clrs math32.ArrayF32, vtxOff int, numVertex int, clr math32.Vector4) {
cidx := vtxOff * 4
for vi := range numVertex {
clr.ToSlice(clrs, cidx+vi*4)
}
}
// BBoxFromVtxs returns the bounding box updated from the range of vertex points
func BBoxFromVtxs(vertex math32.ArrayF32, vtxOff int, numVertex int) math32.Box3 {
bb := math32.B3Empty()
vidx := vtxOff * 3
var vtx math32.Vector3
for vi := range numVertex {
vtx.FromSlice(vertex, vidx+vi*3)
bb.ExpandByPoint(vtx)
}
return bb
}
// Copyright 2022 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package shape
import (
"math"
"cogentcore.org/core/math32"
)
// Sphere is a sphere shape (can be a partial sphere too)
type Sphere struct { //types:add -setters
ShapeBase
// radius of the sphere
Radius float32
// number of segments around the width of the sphere (32 is reasonable default for full circle)
WidthSegs int `min:"3"`
// number of height segments (32 is reasonable default for full height)
HeightSegs int `min:"3"`
// starting radial angle in degrees, relative to -1,0,0 left side starting point
AngStart float32 `min:"0" max:"360" step:"5"`
// total radial angle to generate in degrees (max = 360)
AngLen float32 `min:"0" max:"360" step:"5"`
// starting elevation (height) angle in degrees - 0 = top of sphere, and Pi is bottom
ElevStart float32 `min:"0" max:"180" step:"5"`
// total angle to generate in degrees (max = 180)
ElevLen float32 `min:"0" max:"180" step:"5"`
}
// NewSphere returns a Sphere shape with given size
func NewSphere(radius float32, segs int) *Sphere {
sp := &Sphere{}
sp.Defaults()
sp.Radius = radius
sp.WidthSegs = segs
sp.HeightSegs = segs
return sp
}
func (sp *Sphere) Defaults() {
sp.Radius = 1
sp.WidthSegs = 32
sp.HeightSegs = 32
sp.AngStart = 0
sp.AngLen = 360
sp.ElevStart = 0
sp.ElevLen = 180
}
func (sp *Sphere) MeshSize() (numVertex, nIndex int, hasColor bool) {
numVertex, nIndex = SphereSectorN(sp.WidthSegs, sp.HeightSegs, sp.ElevStart, sp.ElevLen)
return
}
// Set sets points in given allocated arrays.
func (sp *Sphere) Set(vertex, normal, texcoord, clrs math32.ArrayF32, index math32.ArrayU32) {
sp.CBBox = SetSphereSector(vertex, normal, texcoord, index, sp.VertexOffset, sp.IndexOffset, sp.Radius, sp.WidthSegs, sp.HeightSegs, sp.AngStart, sp.AngLen, sp.ElevStart, sp.ElevLen, sp.Pos)
}
// SphereSectorN returns the N's for a sphere sector's
// vertex and index data with given number of segments.
// Note: In *vertex* units, not float units (i.e., x3 to get
// actual float offset in Vtx array).
func SphereSectorN(widthSegs, heightSegs int, elevStart, elevLen float32) (numVertex, nIndex int) {
numVertex = (widthSegs + 1) * (heightSegs + 1)
elevStRad := math32.DegToRad(elevStart)
elevLenRad := math32.DegToRad(elevLen)
elevEndRad := elevStRad + elevLenRad
h1idx := heightSegs - 1
if elevStRad > 0 {
h1idx++
}
h2idx := heightSegs - 1
if elevEndRad < math.Pi {
h2idx++
}
nIndex = 3*h1idx*widthSegs + 3*h2idx*widthSegs
return
}
// SetSphereSector sets a sphere sector vertex, normal, tex, index data at
// given starting *vertex* index (i.e., multiply this *3 to get
// actual float offset in Vtx array), and starting Index index,
// with the specified radius, number of radial segments in each
// dimension (min 3), radial sector start
// angle and length in degrees (0 - 360), start = -1,0,0,
// elevation start angle and length in degrees (0 - 180), top = 0, bot = 180.
// pos is an arbitrary offset (for composing shapes),
// returns bounding box.
func SetSphereSector(vertex, normal, texcoord math32.ArrayF32, index math32.ArrayU32, vtxOff, idxOff int, radius float32, widthSegs, heightSegs int, angStart, angLen, elevStart, elevLen float32, pos math32.Vector3) math32.Box3 {
angStRad := math32.DegToRad(angStart)
angLenRad := math32.DegToRad(angLen)
elevStRad := math32.DegToRad(elevStart)
elevLenRad := math32.DegToRad(elevLen)
elevEndRad := elevStRad + elevLenRad
if widthSegs < 3 || heightSegs < 3 {
panic("Invalid argument: segments. The number of segments needs to be greater or equal to 3.")
}
bb := math32.Box3{}
bb.SetEmpty()
idx := 0
vidx := vtxOff * 3
tidx := vtxOff * 2
vtxs := make([][]uint32, 0)
var pt, norm math32.Vector3
for y := 0; y <= heightSegs; y++ {
vtxsRow := make([]uint32, 0)
v := float32(y) / float32(heightSegs)
for x := 0; x <= widthSegs; x++ {
u := float32(x) / float32(widthSegs)
px := -radius * math32.Cos(angStRad+u*angLenRad) * math32.Sin(elevStRad+v*elevLenRad)
py := radius * math32.Cos(elevStRad+v*elevLenRad)
pz := radius * math32.Sin(angStRad+u*angLenRad) * math32.Sin(elevStRad+v*elevLenRad)
pt.Set(px, py, pz)
pt.SetAdd(pos)
norm.Set(px, py, pz)
norm.SetNormal()
vertex.SetVector3(vidx+idx*3, pt)
normal.SetVector3(vidx+idx*3, norm)
texcoord.Set(tidx+idx*2, u, v)
vtxsRow = append(vtxsRow, uint32(idx))
bb.ExpandByPoint(pt)
idx++
}
vtxs = append(vtxs, vtxsRow)
}
vOff := uint32(vtxOff)
ii := idxOff
for y := range heightSegs {
for x := range widthSegs {
v1 := vtxs[y][x+1]
v2 := vtxs[y][x]
v3 := vtxs[y+1][x]
v4 := vtxs[y+1][x+1]
if y != 0 || elevStRad > 0 {
index.Set(ii, vOff+v1, vOff+v2, vOff+v4)
ii += 3
}
if y != heightSegs-1 || elevEndRad < math.Pi {
index.Set(ii, vOff+v2, vOff+v3, vOff+v4)
ii += 3
}
}
}
return bb
}
// DiskSectorN returns the N's for a disk sector's
// vertex and index data with given number of segments.
// Note: In *vertex* units, not float units (i.e., x3 to get
// actual float offset in Vtx array).
func DiskSectorN(segs int) (numVertex, nIndex int) {
numVertex = segs + 2
nIndex = 2 * (segs - 1)
return
}
// SetDiskSector sets a disk sector vertex, normal, tex, index data at
// given starting *vertex* index (i.e., multiply this *3 to get
// actual float offset in Vtx array), and starting Index index,
// with the specified radius, number of radial segments (minimum 3),
// sector start angle and angle length in degrees.
// The center of the disk is at the origin,
// and angle runs counter-clockwise on the XY plane, starting at (x,y,z)=(1,0,0).
// pos is an arbitrary offset (for composing shapes),
// returns bounding box.
func SetDiskSector(vertex, normal, texcoord math32.ArrayF32, index math32.ArrayU32, vtxOff, idxOff int, radius float32, segs int, angStart, angLen float32, pos math32.Vector3) math32.Box3 {
// Validate arguments
if segs < 3 {
panic("Invalid argument: segments. The number of segments needs to be greater or equal to 3.")
}
angStRad := math32.DegToRad(angStart)
angLenRad := math32.DegToRad(angLen)
idx := 0
vidx := vtxOff * 3
tidx := vtxOff * 2
bb := math32.Box3{}
bb.SetEmpty()
// center position
center := pos
vertex.SetVector3(vidx, center)
var norm math32.Vector3
norm.Z = 1
normal.SetVector3(vidx, norm)
centerUV := math32.Vec2(0.5, 0.5)
texcoord.SetVector2(tidx, centerUV)
idx++
var pt math32.Vector3
// Generate the segments
for i := 0; i <= segs; i++ {
segment := angStRad + float32(i)/float32(segs)*angLenRad
vx := float32(radius * math32.Cos(segment))
vy := float32(radius * math32.Sin(segment))
pt.Set(vx, vy, 0)
pt.SetAdd(pos)
// Appends vertex position, normal and uv coordinates
vertex.Set(vidx+idx*3, vx, vy, 0)
normal.SetVector3(vidx+idx*3, norm)
texcoord.Set(tidx+idx*2, (vx/radius+1)/2, (vy/radius+1)/2)
bb.ExpandByPoint(pt)
idx++
}
vOff := uint32(vtxOff)
ii := idxOff
for i := 1; i <= segs; i++ {
index.Set(ii, vOff+uint32(i), vOff+uint32(i)+1, vOff) // ctr = last
}
return bb
}
// Copyright 2022 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package shape
import (
"math"
"cogentcore.org/core/math32"
)
// Torus is a torus mesh, defined by the radius of the solid tube and the
// larger radius of the ring.
type Torus struct { //types:add -setters
ShapeBase
// larger radius of the torus ring
Radius float32
// radius of the solid tube
TubeRadius float32
// number of segments around the radius of the torus (32 is reasonable default for full circle)
RadialSegs int `min:"1"`
// number of segments for the tube itself (32 is reasonable default for full height)
TubeSegs int `min:"1"`
// starting radial angle in degrees relative to 1,0,0 starting point
AngStart float32 `min:"0" max:"360" step:"5"`
// total radial angle to generate in degrees (max = 360)
AngLen float32 `min:"0" max:"360" step:"5"`
}
// NewTorus returns a Torus mesh with the specified outer ring radius,
// solid tube radius, and number of segments (resolution).
func NewTorus(radius, tubeRadius float32, segs int) *Torus {
tr := &Torus{}
tr.Defaults()
tr.Radius = radius
tr.TubeRadius = tubeRadius
tr.RadialSegs = segs
tr.TubeSegs = segs
return tr
}
func (tr *Torus) Defaults() {
tr.Radius = 1
tr.TubeRadius = .1
tr.RadialSegs = 32
tr.TubeSegs = 32
tr.AngStart = 0
tr.AngLen = 360
}
func (tr *Torus) MeshSize() (numVertex, nIndex int, hasColor bool) {
numVertex, nIndex = TorusSectorN(tr.RadialSegs, tr.TubeSegs)
return
}
// Set sets points for torus in given allocated arrays
func (tr *Torus) Set(vertex, normal, texcoord, clrs math32.ArrayF32, index math32.ArrayU32) {
tr.CBBox = SetTorusSector(vertex, normal, texcoord, index, tr.VertexOffset, tr.IndexOffset, tr.Radius, tr.TubeRadius, tr.RadialSegs, tr.TubeSegs, tr.AngStart, tr.AngLen, tr.Pos)
}
// TorusSectorN returns N's for a torus geometry with
// number of radial segments, number of tubular segments,
// radial sector start angle and length in degrees (0 - 360)
func TorusSectorN(radialSegs, tubeSegs int) (numVertex, nIndex int) {
numVertex = (radialSegs + 1) * (tubeSegs + 1)
nIndex = radialSegs * tubeSegs * 6
return
}
// SetTorusSector sets torus sector vertex, normal, tex, index data
// at given starting *vertex* index (i.e., multiply this *3 to get
// actual float offset in Vtx array), and starting Index index,
// with the specified revolution radius, tube radius,
// number of radial segments, number of tubular segments,
// radial sector start angle and length in degrees (0 - 360)
// pos is an arbitrary offset (for composing shapes),
// returns bounding box.
func SetTorusSector(vertex, normal, texcoord math32.ArrayF32, index math32.ArrayU32, vtxOff, idxOff int, radius, tubeRadius float32, radialSegs, tubeSegs int, angStart, angLen float32, pos math32.Vector3) math32.Box3 {
angStRad := math32.DegToRad(angStart)
angLenRad := math32.DegToRad(angLen)
idx := 0
vidx := vtxOff * 3
tidx := vtxOff * 2
bb := math32.Box3{}
bb.SetEmpty()
var center math32.Vector3
for j := 0; j <= radialSegs; j++ {
for i := 0; i <= tubeSegs; i++ {
u := angStRad + float32(i)/float32(tubeSegs)*angLenRad
v := float32(j) / float32(radialSegs) * math.Pi * 2
center.X = radius * math32.Cos(u)
center.Y = radius * math32.Sin(u)
var pt math32.Vector3
pt.X = (radius + tubeRadius*math32.Cos(v)) * math32.Cos(u)
pt.Y = (radius + tubeRadius*math32.Cos(v)) * math32.Sin(u)
pt.Z = tubeRadius * math32.Sin(v)
pt.SetAdd(pos)
vertex.SetVector3(vidx+idx*3, pt)
texcoord.Set(tidx+idx*2, float32(i)/float32(tubeSegs), float32(j)/float32(radialSegs))
normal.SetVector3(vidx+idx*3, pt.Sub(center).Normal())
bb.ExpandByPoint(pt)
idx++
}
}
vOff := uint32(vtxOff)
ii := idxOff
for j := 1; j <= radialSegs; j++ {
for i := 1; i <= tubeSegs; i++ {
a := (tubeSegs+1)*j + i - 1
b := (tubeSegs+1)*(j-1) + i - 1
c := (tubeSegs+1)*(j-1) + i
d := (tubeSegs+1)*j + i
index.Set(ii, vOff+uint32(a), vOff+uint32(b), vOff+uint32(d), vOff+uint32(b), vOff+uint32(c), vOff+uint32(d))
ii += 6
}
}
return bb
}
// Copyright 2022 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package shape
import (
"cogentcore.org/core/math32"
)
////////////////////////////////////////////////////////////////
// Triangle
// TriangleN returns 3, 3
func TriangleN() (numVertex, nIndex int) {
return 3, 3
}
// SetTriangle sets one triangle of vertex data indexes, and optionally
// texUV coords, at given starting *vertex* index (i.e., multiply this *3
// to get actual float offset in Vtx array), and starting Index index.
// Normal is auto-computed, and bounds expanded.
// pos is a 3D position offset. returns 3D size of plane.
// returns bounding box.
func SetTriangle(vertex, normal, texcoord math32.ArrayF32, index math32.ArrayU32, vtxOff, idxOff int, a, b, c math32.Vector3, texs []math32.Vector2, pos math32.Vector3) math32.Box3 {
hasTex := texs != nil
vidx := vtxOff * 3
tidx := vtxOff * 2
norm := math32.Normal(a, b, c)
a.Add(pos).ToSlice(vertex, vidx)
norm.ToSlice(normal, vidx)
b.Add(pos).ToSlice(vertex, vidx+3)
norm.ToSlice(normal, vidx+3)
c.Add(pos).ToSlice(vertex, vidx+6)
norm.ToSlice(normal, vidx+6)
if hasTex {
texs[0].ToSlice(texcoord, tidx)
texs[1].ToSlice(texcoord, tidx+2)
texs[2].ToSlice(texcoord, tidx+4)
}
index.Set(idxOff, uint32(vtxOff), uint32(vtxOff+1), uint32(vtxOff+2))
bb := math32.B3Empty()
bb.ExpandByPoints([]math32.Vector3{a, b, c})
return bb
}
////////////////////////////////////////////////////////////////
// Quad
// QuadN returns 4, 6
func QuadN() (numVertex, nIndex int) {
return 4, 6
}
// SetQuad sets quad vertex data (optionally texUV, color, and indexes)
// at given starting *vertex* index (i.e., multiply this *3 to get actual float
// offset in Vtx array), and starting Index index.
// Normal is auto-computed, and bbox expanded by points.
// pos is a 3D position offset. returns 3D size of plane.
// returns bounding box.
func SetQuad(vertex, normal, texcoord math32.ArrayF32, index math32.ArrayU32, vtxOff, idxOff int, vtxs []math32.Vector3, texs []math32.Vector2, pos math32.Vector3) math32.Box3 {
hasTex := texs != nil
vidx := vtxOff * 3
tidx := vtxOff * 2
norm := math32.Normal(vtxs[0], vtxs[1], vtxs[2])
for vi := range vtxs {
vtxs[vi].Add(pos).ToSlice(vertex, vidx)
norm.ToSlice(normal, vidx)
vidx += 3
if hasTex {
texs[vi].ToSlice(texcoord, tidx)
tidx += 2
}
}
index.Set(idxOff, uint32(vtxOff), uint32(vtxOff+1), uint32(vtxOff+2),
uint32(vtxOff), uint32(vtxOff+2), uint32(vtxOff+3))
bb := math32.B3Empty()
bb.ExpandByPoints(vtxs)
return bb
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gpu
import (
"image"
"sync"
"sync/atomic"
"cogentcore.org/core/base/errors"
"github.com/oliverbestmann/webgpu/wgpu"
)
// Surface manages the physical device for the visible image
// of a window surface, and the swapchain for presenting images.
// It provides an encapsulated source of TextureView textures
// for the rendering process to draw on.
// It implements the Renderer interface, which defines the
// primary API (GetCurrentTexture() -> Present()).
type Surface struct {
// Render helper for this Surface.
render Render
// Format has the current rendering surface size and
// rendering texture format. This format may be different
// from the actual physical swapchain format, in case there
// is a different view (e.g., srgb)
Format TextureFormat
// pointer to gpu device, needed for properties.
GPU *GPU
// Device for this surface, which we own.
// Each window surface has its own device, configured for that surface.
device *Device
// WebGPU handle for surface
surface *wgpu.Surface
config *wgpu.SurfaceConfiguration
// curTexture is the view of the current surface texture,
// released in Present.
curTexture *wgpu.TextureView
// curSurfaceTexture is the current texture of the surface, which
// we own until Present (see [wgpu.Surface.GetCurrentTexture]).
// It belongs to the surface, so it is released, not destroyed.
curSurfaceTexture *wgpu.Texture
// occluded is whether the surface was occluded (hidden) when
// [Surface.GetCurrentTexture] was last called (see [Surface.Occluded]).
occluded atomic.Bool
// pending is the texture that [Surface.Occluded] got when the surface
// was no longer occluded, for the next [Surface.GetCurrentTexture].
pending *wgpu.SurfaceTexture
sync.Mutex
}
// NewSurface returns a new surface initialized for given GPU and WebGPU
// Surface handle, obtained from a valid window.
// - size should reflect the actual size of the surface,
// and can be updated with SetSize method.
// - samples is the multisampling anti-aliasing parameter: 1 = none
// 4 = typical default value for smooth "no jaggy" edges.
// - depthFmt is the depth buffer format. use UndefinedType for none
// or Depth32 recommended for best performance.
func NewSurface(gp *GPU, wsurf *wgpu.Surface, size image.Point, samples int, depthFmt Types) *Surface {
sf := &Surface{}
sf.Defaults()
sf.init(gp, wsurf, size, samples, depthFmt)
return sf
}
func (sf *Surface) Defaults() {
// sf.NFrames = 3 // requested, will be updated with actual
sf.Format.Defaults()
sf.Format.Set(1024, 768, wgpu.TextureFormatRGBA8UnormSrgb)
sf.Format.SetMultisample(4)
}
func (sf *Surface) init(gp *GPU, ws *wgpu.Surface, size image.Point, samples int, depthFmt Types) error {
sf.GPU = gp
sf.surface = ws
dev, err := gp.NewDevice() // surface owns this device
if errors.Log(err) != nil {
return err
}
sf.device = dev
// note: Format.Format will be determined in InitConfig,
// based on GetCapabilities call.
sf.Format.SetMultisample(samples)
sf.Format.Size = size
sf.InitConfig() // can change the format
sf.render.Config(sf.device, &sf.Format, depthFmt)
return nil
}
func (sf *Surface) Device() *Device { return sf.device }
func (sf *Surface) Render() *Render { return &sf.render }
// SetSize must be called when the render surface (e.g., window) is resized.
// WebGPU does not have any internal mechanism for tracking this, so we
// need to drive it from external events.
func (sf *Surface) SetSize(sz image.Point) {
if sf.Format.Size == sz || sz.X == 0 || sz.Y == 0 {
return
}
// The depth and multisample textures are remade by Reconfig, under
// the lock held from GetCurrentTexture to Present, so that they are
// not destroyed while a frame that uses them is being rendered.
sf.Format.Size = sz
sf.config.Width = uint32(sf.Format.Size.X)
sf.config.Height = uint32(sf.Format.Size.Y)
sf.Reconfig()
}
func (sf *Surface) Size() image.Point {
return sf.Format.Bounds().Size()
}
// GetCurrentTexture returns a TextureView that is the current
// target for rendering. The TextureView can be nil AND the err
// also nil, in which case nothing is to be rendered: the surface
// needs to be reconfigured, or it is occluded (see [Surface.Occluded]).
func (sf *Surface) GetCurrentTexture() (*wgpu.TextureView, error) {
sf.Lock() // we remain locked until submit!
var stexture wgpu.SurfaceTexture
if sf.pending != nil {
stexture = *sf.pending
sf.pending = nil
} else {
var err error
stexture, err = sf.surface.TryGetCurrentTexture()
if errors.Log(err) != nil {
sf.Unlock()
return nil, err
}
}
// An occluded surface (as of a window that is covered, or on another
// space) has no texture until it is shown again. The frame is skipped,
// instead of waiting for it, as the caller can hold the lock of its
// window, which other windows then wait on, such as to open a new one.
occluded := stexture.Status == wgpu.SurfaceGetCurrentTextureStatusOccluded
sf.occluded.Store(occluded)
if occluded {
sf.Unlock()
return nil, nil
}
texture, ok := stexture.Get()
if !ok {
if texture != nil {
texture.Release()
}
sf.Unlock()
return nil, nil
}
// Note: we need to specify a descriptor here so that we use the correct
// format, which may be different from the default format, such as when
// it is srgb.
view, err := texture.TryCreateView(&wgpu.TextureViewDescriptor{
MipLevelCount: texture.GetMipLevelCount(),
ArrayLayerCount: texture.GetDepthOrArrayLayers(),
Format: sf.Format.Format,
})
if errors.Log(err) != nil {
texture.Release()
sf.Unlock()
return nil, err
}
sf.curSurfaceTexture = texture
sf.curTexture = view
return view, nil
}
// Occluded returns whether the surface is occluded (hidden), as it was
// when [Surface.GetCurrentTexture] was last called, so that nothing was
// rendered: the frame is to be rendered again once it is shown. While it
// was, it checks whether it still is, which is much cheaper than rendering
// to find out; the texture that it gets when it is not is kept for the next
// [Surface.GetCurrentTexture].
func (sf *Surface) Occluded() bool {
if !sf.occluded.Load() {
return false
}
sf.Lock()
defer sf.Unlock()
if sf.pending != nil || sf.surface == nil {
return false
}
stexture, err := sf.surface.TryGetCurrentTexture()
if err != nil { // (rendering reports it)
return false
}
if stexture.Status == wgpu.SurfaceGetCurrentTextureStatusOccluded {
return true
}
sf.pending = &stexture
sf.occluded.Store(false)
return false
}
// releasePending releases the texture got by [Surface.Occluded], if it
// was not used, as the surface is changed. It must be called locked.
func (sf *Surface) releasePending() {
if sf.pending != nil && sf.pending.Texture != nil {
sf.pending.Texture.Release()
}
sf.pending = nil
}
// Present is the final step for showing the rendered texture to the window.
// The current texture is automatically Released and Unlock() is called.
func (sf *Surface) Present() {
sf.surface.Present()
if sf.curTexture != nil {
sf.curTexture.Release()
sf.curTexture = nil
}
// We own the surface texture natively, so it must be released after
// Present and before the next one, or it leaks with its device
// reference (see [wgpu.Surface.GetCurrentTexture]).
if sf.curSurfaceTexture != nil {
sf.curSurfaceTexture.Release()
sf.curSurfaceTexture = nil
}
sf.Unlock()
}
// InitConfig does the initial configuration of the surface.
// This assumes that all existing items have been destroyed.
func (sf *Surface) InitConfig() error {
caps := sf.surface.GetCapabilities(sf.GPU.GPU)
trgFmt := caps.Formats[0]
// fmt.Println(reflectx.StringJSON(caps), trgFmt)
viewFmt := trgFmt
switch trgFmt {
case wgpu.TextureFormatBGRA8Unorm:
viewFmt = wgpu.TextureFormatBGRA8UnormSrgb
case wgpu.TextureFormatRGBA8Unorm:
viewFmt = wgpu.TextureFormatRGBA8UnormSrgb
}
var viewFmts []wgpu.TextureFormat
if viewFmt != trgFmt {
viewFmts = append(viewFmts, viewFmt)
}
sf.config = &wgpu.SurfaceConfiguration{
Usage: wgpu.TextureUsageRenderAttachment,
Format: trgFmt,
Width: uint32(sf.Format.Size.X),
Height: uint32(sf.Format.Size.Y),
PresentMode: wgpu.PresentModeFifo,
AlphaMode: caps.AlphaModes[0],
ViewFormats: viewFmts,
}
sf.Format.Format = viewFmt
sf.Config()
return nil
}
// Config configures the surface based on the surface configuration.
func (sf *Surface) Config() {
sf.surface.Configure(sf.device.Device, sf.config)
}
// Reconfig reconfigures the surface.
// This must be called when the window is resized.
// Must update the swapChainConfig parameters prior to calling!
// It returns false if the swapchain size is zero.
func (sf *Surface) Reconfig() bool {
sf.Lock()
defer sf.Unlock()
sf.releasePending()
sf.Config()
sf.render.SetSize(sf.Format.Size)
return true
}
func (sf *Surface) Release() {
sf.render.Release()
sf.Lock() // (see [Surface.Occluded])
sf.releasePending()
if sf.surface != nil {
sf.surface.Release()
sf.surface = nil
}
sf.Unlock()
if sf.device != nil {
sf.device.Release()
sf.device = nil
}
sf.GPU = nil
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gpu
import (
"os"
"sync"
)
// Skipper is the subset of [testing.TB] that [SkipIfNoGPU] uses.
type Skipper interface {
Helper()
Skip(args ...any)
Fatal(args ...any)
}
var (
availableOnce sync.Once
available bool
)
// Available returns whether WebGPU has at least one adapter on this
// machine, which a CI runner without a GPU (hardware or software)
// does not have. It is computed once.
func Available() bool {
availableOnce.Do(func() {
inst := Instance()
available = inst != nil && len(inst.EnumerateAdapters(nil)) > 0
})
return available
}
// SkipIfNoGPU skips the test if there is no GPU adapter (see [Available]).
// If the CORE_REQUIRE_GPU environment variable is set, as on a CI runner
// that has a software GPU, it fails the test instead, so that a missing
// GPU is not silently skipped.
func SkipIfNoGPU(t Skipper) {
t.Helper()
if Available() {
return
}
if os.Getenv("CORE_REQUIRE_GPU") != "" {
t.Fatal("no GPU adapter is available, and CORE_REQUIRE_GPU is set")
}
t.Skip("no GPU adapter is available")
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gpu
import (
"image"
"sync/atomic"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/iox/imagex"
"cogentcore.org/core/base/slicesx"
"github.com/oliverbestmann/webgpu/wgpu"
)
// Texture represents a WebGPU Texture with an associated TextureView.
// The WebGPU Texture is in device memory, in an optimized format.
type Texture struct {
// Name of the texture, e.g., same as Value name if used that way.
// This is helpful for debugging. Is auto-set to filename if loaded from
// a file and otherwise empty.
Name string
// Format & size of texture
Format TextureFormat
// Sampler defines how the texture is sampled on the GPU.
// Needed for textures used as fragment shader inputs.
Sampler Sampler
// shared indicates that this texture is shared from another
// Texture, which owns it (see [Texture.SetShared]).
shared bool
// holders counts the Textures that hold the current texture and view,
// when it has been shared (see [Texture.SetShared]): the owner and each
// sharer hold the same counter. The last one to let go of it destroys
// and releases it (see [Texture.ReleaseTexture]). It is nil when the
// texture has not been shared, so the owner alone holds it.
holders *atomic.Int32
// WebGPU texture handle, in device memory
texture *wgpu.Texture `display:"-"`
// WebGPU texture view -- needed for most textures
view *wgpu.TextureView `display:"-"`
// keep track of device for destroying view
device Device `display:"-"`
// readBuffer is an optional buffer for reading the contents of a texture
readBuffer *wgpu.Buffer
// current size of the readBuffer
ReadBufferDims TextureBufferDims
}
func NewTexture(dev *Device) *Texture {
tx := &Texture{}
tx.device = *dev
tx.Format.Defaults()
return tx
}
// ConfigGoImage configures the texture for storing an texture
// of the given size. Texture format will be set to default
// unless format is already set. Layers is number of separate textures
// of given size allocated in a texture array.
func (tx *Texture) ConfigGoImage(sz image.Point, layers int) {
if tx.Format.Format != wgpu.TextureFormatRGBA8UnormSrgb {
tx.Format.Defaults()
}
tx.Format.Size = sz
if layers <= 0 {
layers = 1
}
tx.Format.Layers = layers
}
// SetFromGoImage sets texture data from a standard Go texture at given layer.
// This is most efficiently done using an texture.RGBA, but other
// formats will be converted as necessary.
// This starts the full WriteTexture call to upload to device.
func (tx *Texture) SetFromGoImage(img image.Image, layer int) error {
rimg := imagex.AsRGBA(img)
sz := rimg.Rect.Size()
nfmt := TextureFormat{Size: sz, Format: wgpu.TextureFormatRGBA8UnormSrgb, Layers: 1, Samples: 1}
// A shared texture belongs to another Texture: we make our own
// instead of writing into it.
if tx.texture == nil || tx.shared || tx.Format != nfmt {
tx.Format = nfmt
err := tx.CreateTexture(wgpu.TextureUsageTextureBinding | wgpu.TextureUsageCopyDst)
if err != nil { // already logged
return err
}
}
size := tx.Format.Extent3D()
// https://www.w3.org/TR/webgpu/#gpuimagecopytexture
tx.device.Queue.WriteTexture(
&wgpu.TexelCopyTextureInfo{
Aspect: wgpu.TextureAspectAll,
Texture: tx.texture,
MipLevel: 0,
Origin: wgpu.Origin3D{X: 0, Y: 0, Z: 0},
},
rimg.Pix,
&wgpu.TexelCopyBufferLayout{
Offset: 0,
BytesPerRow: 4 * uint32(sz.X),
RowsPerImage: uint32(sz.Y),
},
&size,
)
return nil
}
// CreateTexture creates the texture based on current settings,
// and a view of that texture. Calls release first.
func (tx *Texture) CreateTexture(usage wgpu.TextureUsage) error {
tx.ReleaseTexture()
size := tx.Format.Extent3D()
t, err := tx.device.Device.TryCreateTexture(&wgpu.TextureDescriptor{
Label: tx.Name,
Size: size,
MipLevelCount: 1,
SampleCount: uint32(tx.Format.Samples),
Dimension: wgpu.TextureDimension2D,
Format: tx.Format.Format,
Usage: usage,
})
if errors.Log(err) != nil {
return err
}
tx.texture = t
vw, err := t.TryCreateView(nil)
if errors.Log(err) != nil {
return err
}
tx.view = vw
return nil
}
// https://eliemichel.github.io/LearnWebGPU/advanced-techniques/headless.html
// ConfigRenderTexture configures this texture as a render texture
// using format. Sets multisampling to 1, layers to 1.
func (tx *Texture) ConfigRenderTexture(dev *Device, imgFmt *TextureFormat) error {
tx.device = *dev
nfmt := *imgFmt
nfmt.SetMultisample(1)
if tx.texture != nil && tx.Format == nfmt {
return nil
}
tx.Format = nfmt
return tx.CreateTexture(wgpu.TextureUsageRenderAttachment | wgpu.TextureUsageCopySrc | wgpu.TextureUsageTextureBinding)
}
// ConfigDepth configures this texture as a depth texture
// using given depth texture format, and other format information
// from the given render texture format.
// If current texture is identical format, does not recreate.
func (tx *Texture) ConfigDepth(dev *Device, depthType Types, imgFmt *TextureFormat) error {
tx.device = *dev
nfmt := *imgFmt
nfmt.Format = depthType.TextureFormat()
if tx.texture != nil && tx.Format == nfmt {
return nil
}
tx.Format = nfmt
return tx.CreateTexture(wgpu.TextureUsageRenderAttachment | wgpu.TextureUsageCopySrc)
}
// ConfigMulti configures this texture as a mutisampling texture
// using format.
func (tx *Texture) ConfigMulti(dev *Device, imgFmt *TextureFormat) error {
tx.device = *dev
if tx.texture != nil && tx.Format == *imgFmt {
return nil
}
tx.Format = *imgFmt
return tx.CreateTexture(wgpu.TextureUsageRenderAttachment)
}
// SetShared sets this texture to point to the given Texture's
// underlying GPU texture and view, with the shared flag set.
// Both Textures hold the texture until they let go of it, by
// [Texture.ReleaseTexture] or by getting another one, and it is
// destroyed by the last of them. Thus, the owner can replace its
// texture (for example on a resize) while the sharer still uses the
// old one in its bind group, and the old texture is destroyed when
// the sharer gets the new one, before its next submit.
func (tx *Texture) SetShared(ot *Texture) {
if tx.shared && tx.texture == ot.texture && tx.view == ot.view {
return
}
tx.ReleaseTexture()
if ot.texture == nil {
return
}
if ot.holders == nil {
ot.holders = &atomic.Int32{}
ot.holders.Store(1)
}
ot.holders.Add(1)
tx.holders = ot.holders
tx.texture = ot.texture
tx.view = ot.view
tx.shared = true
tx.Format = ot.Format
}
// ReleaseView releases the view, if we are the last holder of it.
// The texture is not released: see [Texture.ReleaseTexture].
func (tx *Texture) ReleaseView() {
if tx.view == nil {
return
}
if tx.holders == nil {
tx.view.Release()
}
tx.view = nil
}
// ReleaseTexture lets go of the texture and its view, and frees them if
// no other Texture holds them (see [Texture.SetShared]). The texture is
// destroyed, which frees its memory right away instead of when it is
// garbage collected, as on the web, where Release does nothing, or when
// its last reference is released. WebGPU destroys it only after the work
// already submitted, but it must not be used in any new submit, so a
// bind group that uses it must be remade first: a texture [Value] has a
// new bind group made when its view changes.
func (tx *Texture) ReleaseTexture() {
view, texture := tx.view, tx.texture
last := tx.holders == nil || tx.holders.Add(-1) == 0
tx.view = nil
tx.texture = nil
tx.holders = nil
tx.shared = false
if !last {
return
}
if view != nil {
view.Release()
}
if texture != nil {
texture.Destroy()
texture.Release()
}
}
// Release destroys any existing view, nils fields
func (tx *Texture) Release() {
tx.ReleaseTexture()
tx.Sampler.Release()
if tx.readBuffer != nil {
tx.readBuffer.Release()
tx.readBuffer = nil
}
}
///////////////////////////////////////////////////////////////
// ReadBuffer
// ConfigReadBuffer configures the [readBuffer] for this Texture.
// Must have this in place prior to render pass with a
// [CopyToReadBuffer] command added to it.
func (tx *Texture) ConfigReadBuffer() error {
dims := NewTextureBufferDims(tx.Format.Size)
buffSize := dims.PaddedSize()
if tx.readBuffer != nil && tx.ReadBufferDims == *dims {
return nil
}
b, err := tx.device.Device.TryCreateBuffer(&wgpu.BufferDescriptor{
Size: buffSize,
Usage: wgpu.BufferUsageMapRead | wgpu.BufferUsageCopyDst,
})
if errors.Log(err) != nil {
return err
}
tx.readBuffer = b
tx.ReadBufferDims = *dims
return nil
}
// CopyToReadBuffer adds a command to the given command encoder
// to copy this texture to its [readBuffer]. Must have called
// [ConfigReadBuffer] prior to start of render pass for this to work.
func (tx *Texture) CopyToReadBuffer(cmd *wgpu.CommandEncoder) error {
if tx.readBuffer == nil {
err := errors.New("gpu.Texture.CopyToReadBuffer: must configure readBuffer prior to render pass")
return errors.Log(err)
}
size := tx.Format.Extent3D()
cmd.CopyTextureToBuffer(
tx.texture.AsImageCopy(),
&wgpu.TexelCopyBufferInfo{
Buffer: tx.readBuffer,
Layout: wgpu.TexelCopyBufferLayout{
Offset: 0,
BytesPerRow: uint32(tx.ReadBufferDims.PaddedRowSize),
RowsPerImage: wgpu.CopyStrideUndefined,
},
},
&size,
)
return nil
}
// ReadGoImage reads the GPU-resident Texture and returns
// a Go image.NRGBA image of the texture.
func (tx *Texture) ReadGoImage() (*image.NRGBA, error) {
var data []byte
err := tx.ReadData(&data, true)
if err != nil {
return nil, err
}
img := &image.NRGBA{
Pix: data,
Stride: int(tx.ReadBufferDims.UnpaddedRowSize), // note: this is actually unpadded here
Rect: image.Rect(0, 0, int(tx.ReadBufferDims.Width), int(tx.ReadBufferDims.Height)),
}
return img, nil
}
// ReadData reads the data from a GPU-resident Texture,
// setting the given data bytes, which will be resized to fit
// the data. If removePadding is true, then extra padding will be
// removed, if present.
func (tx *Texture) ReadData(data *[]byte, removePadding bool) error {
ud, err := tx.ReadDataMapped()
if err != nil {
return err
}
if !removePadding || tx.ReadBufferDims.HasNoPadding() {
buffSize := tx.ReadBufferDims.PaddedSize()
*data = slicesx.SetLength(*data, int(buffSize))
copy(*data, ud)
tx.UnmapReadData()
return nil
}
dataSize := tx.ReadBufferDims.UnpaddedSize()
*data = slicesx.SetLength(*data, int(dataSize))
dims := tx.ReadBufferDims
for r := range dims.Height {
dStart := r * dims.UnpaddedRowSize
dEnd := dStart + dims.UnpaddedRowSize
sStart := r * dims.PaddedRowSize
sEnd := sStart + dims.UnpaddedRowSize
copy((*data)[dStart:dEnd], ud[sStart:sEnd])
}
tx.UnmapReadData()
return nil
}
// ReadDataMapped reads the data from a GPU-resident Texture,
// returning the bytes as mapped from the readBuffer,
// so they must be used immediately, followed by an [UnmapReadData]
// call to unmap the data. See [ReadData] for a version that copies
// the data into a bytes slice, which is safe for indefinite use.
// There is alignment padding as reflected in the
// [ReadBufferDims] data.
func (tx *Texture) ReadDataMapped() ([]byte, error) {
dims := NewTextureBufferDims(tx.Format.Size)
buffSize := dims.PaddedSize()
if tx.readBuffer == nil || tx.ReadBufferDims != *dims {
b, err := tx.device.Device.TryCreateBuffer(&wgpu.BufferDescriptor{
Size: buffSize,
Usage: wgpu.BufferUsageMapRead | wgpu.BufferUsageCopyDst,
})
if errors.Log(err) != nil {
return nil, err
}
tx.readBuffer = b
tx.ReadBufferDims = *dims
}
err := BufferReadSync(&tx.device, int(buffSize), tx.readBuffer)
if errors.Log(err) != nil {
return nil, err
}
return tx.readBuffer.GetMappedRange(0, uint(buffSize)), nil
}
// UnmapReadData unmaps the data from a prior ReadDataMapped call.
func (tx *Texture) UnmapReadData() error {
if tx.readBuffer == nil {
return errors.Log(errors.New("gpu.Texture.UnmapReadData: buffer is nil"))
}
tx.readBuffer.Unmap()
return nil
}
// Copyright (c) 2019, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gpu
import (
"github.com/oliverbestmann/webgpu/wgpu"
)
// See: https://www.khronos.org/opengl/wiki/Data_Type_(GLSL)
// Types is a list of supported GPU data types, which can be stored
// properly aligned in device memory, and used by the shader code.
// Note that a Vector3 or arrays of single scalar values such as Float32
// are not well supported outside of Vertex due to the std410 convention:
// http://www.opengl.org/registry/doc/glspec45.core.pdf#page=159
// The Struct type is particularly challenging as each member
// must be aligned in general on a 16 byte boundary (i.e., vector4)
// (unless all elements are exactly 4 bytes, which might work?).
// Go automatically aligns members to 8 bytes on 64 bit machines,
// but that doesn't quite cut it.
type Types int32 //enums:enum
const (
UndefinedType Types = iota
Bool32
Int16
Uint16
Int32
Int32Vector2
Int32Vector4
Uint32
Uint32Vector2
Uint32Vector4
Float32
Float32Vector2
Float32Vector3 // note: only use for vertex data -- not properly aligned for uniforms
Float32Vector4
Float32Matrix4 // std transform matrix: math32.Matrix4 works directly
Float32Matrix3 // std transform matrix: math32.Matrix3 works directly
TextureRGBA32 // 32 bits with 8 bits per component of R,G,B,A -- std image format
TextureBGRA32
Depth32 // standard float32 depth buffer
Depth24Stencil8 // standard 24 bit float with 8 bit stencil
Struct
)
// VertexFormat returns the WebGPU VertexFormat for given type.
func (tp Types) VertexFormat() wgpu.VertexFormat {
return TypeToVertexFormat[tp]
}
// TextureFormat returns the WebGPU TextureFormat for given type.
func (tp Types) TextureFormat() wgpu.TextureFormat {
return TypeToTextureFormat[tp]
}
// IndexType returns the WebGPU VertexFormat for Index var.
// must be either Uint16 or Uint32.
func (tp Types) IndexType() wgpu.IndexFormat {
if tp == Uint16 {
return wgpu.IndexFormatUint16
}
return wgpu.IndexFormatUint32
}
// Bytes returns number of bytes for this type
func (tp Types) Bytes() int {
return TypeSizes[tp]
}
var TypeToTextureFormat = map[Types]wgpu.TextureFormat{
TextureRGBA32: wgpu.TextureFormatRGBA8UnormSrgb,
TextureBGRA32: wgpu.TextureFormatBGRA8UnormSrgb,
Depth32: wgpu.TextureFormatDepth32Float,
Depth24Stencil8: wgpu.TextureFormatDepth24PlusStencil8,
}
// TextureFormatSizes gives size of known WebGPU
// TextureFormats in bytes
var TextureFormatSizes = map[wgpu.TextureFormat]int{
wgpu.TextureFormatUndefined: 0,
wgpu.TextureFormatR16Sint: 2,
wgpu.TextureFormatR16Uint: 2,
wgpu.TextureFormatR32Sint: 4,
wgpu.TextureFormatRG32Sint: 8,
wgpu.TextureFormatR32Uint: 4,
wgpu.TextureFormatRG32Uint: 8,
wgpu.TextureFormatRGBA32Uint: 16,
wgpu.TextureFormatR32Float: 4,
wgpu.TextureFormatRG32Float: 8,
wgpu.TextureFormatRGBA32Float: 16,
wgpu.TextureFormatRGBA8Sint: 4,
wgpu.TextureFormatRGBA8Unorm: 4,
wgpu.TextureFormatRGBA8UnormSrgb: 4,
wgpu.TextureFormatBGRA8Unorm: 4,
wgpu.TextureFormatBGRA8UnormSrgb: 4,
wgpu.TextureFormatDepth32Float: 4,
wgpu.TextureFormatDepth24PlusStencil8: 4,
}
// TypeSizes gives our data type sizes in bytes
var TypeSizes = map[Types]int{
Bool32: 4,
Int16: 2,
Uint16: 2,
Int32: 4,
Int32Vector2: 8,
Int32Vector4: 16,
Uint32: 4,
Uint32Vector2: 8,
Uint32Vector4: 16,
Float32: 4,
Float32Vector2: 8,
Float32Vector3: 12,
Float32Vector4: 16,
Float32Matrix4: 64,
Float32Matrix3: 36,
TextureRGBA32: 4,
Depth32: 4,
Depth24Stencil8: 4,
}
// TypeToVertexFormat maps gpu.Types to WebGPU VertexFormat
var TypeToVertexFormat = map[Types]wgpu.VertexFormat{
UndefinedType: wgpu.VertexFormat(0),
// Bool32: wgpu.VertexFormatUint32,
// Int16: wgpu.VertexFormatR16Sint,
// Uint16: wgpu.VertexFormatR16Uint,
Int32: wgpu.VertexFormatSint32,
Int32Vector2: wgpu.VertexFormatSint32x2,
Int32Vector4: wgpu.VertexFormatSint32x4,
Uint32: wgpu.VertexFormatUint32,
Uint32Vector2: wgpu.VertexFormatUint32x2,
Uint32Vector4: wgpu.VertexFormatUint32x4,
Float32: wgpu.VertexFormatFloat32,
Float32Vector2: wgpu.VertexFormatFloat32x2,
Float32Vector3: wgpu.VertexFormatFloat32x3,
Float32Vector4: wgpu.VertexFormatFloat32x4,
// TextureRGBA32: wgpu.TextureFormatR8g8b8a8Srgb,
// Depth32: wgpu.VertexFormatD32Sfloat,
// Depth24Stencil8: wgpu.VertexFormatD24UnormS8Uint,
}
// most commonly available formats: https://WebGPU.gpuinfo.org/listsurfaceformats.php
// TextureFormatNames translates image format into human-readable string
// for most commonly available formats
var TextureFormatNames = map[wgpu.TextureFormat]string{
wgpu.TextureFormatRGBA8UnormSrgb: "RGBA 8bit sRGB colorspace",
wgpu.TextureFormatRGBA8Unorm: "RGBA 8bit unsigned linear colorspace",
// wgpu.TextureFormatR5g6b5UnormPack16: "RGB 5bit (pack 16bit total) unsigned linear colorspace",
// wgpu.TextureFormatA2b10g10r10UnormPack32: "ABGR 10bit, 2bit alpha (pack 32bit total), unsigned linear colorspace",
// wgpu.TextureFormatB8g8r8a8Srgb: "BGRA 8bit sRGB colorspace",
// wgpu.TextureFormatB8g8r8a8Unorm: "BGRA 8bit unsigned linear colorspace",
// wgpu.TextureFormatR16g16b16a16Sfloat: "RGBA 16bit signed floating point linear colorspace",
// wgpu.TextureFormatA2r10g10b10UnormPack32: "ARGB 10bit, 2bit alpha (pack 32bit total), unsigned linear colorspace",
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gpu
import (
"fmt"
"image"
"log/slog"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/slicesx"
"github.com/oliverbestmann/webgpu/wgpu"
)
// Value represents a specific value of a Var variable, with
// its own WebGPU Buffer or Texture associated with it.
// The Current active Value index can be set in the corresponding Var.Values.
// The Buffer for a Uniform or Storage value is created on the first
// [SetValueFrom] call, or explicitly in [CreateBuffer].
// To read memory back from the GPU, you must do [CreateReadBuffer]
// and use the steps oulined in [GPUToRead]. Use ad-hoc [ValueGroup]s
// to organize these batched read operations efficiently for the different
// groups of values that need to be read back in the different compute stages.
type Value struct {
// name of this value, named by default as the variable name_idx
Name string
// index of this value within the Var list of values
Index int
// VarSize is the size of each Var element, which includes any fixed Var.ArrayN
// array size specified on the Var.
// The actual buffer size is VarSize * Value.ArrayN (or DynamicN for dynamic).
VarSize int
// ArrayN is the actual number of array elements, for Uniform or Storage
// variables without a fixed array size (i.e., the Var ArrayN = 1).
// This is set when the buffer is actually created, based on the data,
// or can be set directly prior to buffer creation.
ArrayN int
// DynamicIndex is the current index into a DynamicOffset variable
// to use for the SetBindGroup call. Note that this is an index,
// not an offset, so it indexes the DynamicN Vars in the Value,
// using the AlignVarSize to compute the dynamicOffset, which
// is what is actually used.
DynamicIndex int
// AlignVarSize is VarSize subject to memory alignment constraints,
// for DynamicN case.
AlignVarSize int
// AllocSize is total memory size of this value in bytes,
// as allocated in the buffer. For non-dynamic case, it is just VarSize.
// For dynamic, it is dynamicN * AlignVarSize.
AllocSize int
role VarRoles
// for this variable type, this is the alignment requirement in bytes,
// for DynamicOffset variables. This is 1 for Vertex buffer variables.
alignBytes int
// true if this is a dynamic variable (Vertex, DynamicOffset Uniform or Storage)
isDynamic bool
device Device
// buffer for this value, makes it accessible to the GPU
buffer *wgpu.Buffer
// readBuffer is a CPU-based read buffer for compute values
// to read data back from the GPU.
readBuffer *wgpu.Buffer
// dynamicN is the number of Var elements to encode within one
// Value buffer, for Vertex values or DynamicOffset values
// (otherwise it is always effectively 1).
dynamicN int
// dynamicBuffer is a CPU-based staging buffer for dynamic values
// so you can separately set individual dynamic index values and
// then efficiently copy the entire thing to the device buffer
// once everything has been set.
dynamicBuffer []byte
// for SampledTexture Var roles, this is the Texture.
// Can set Sampler parameters directly on this.
Texture *Texture
// variable for this value
vvar *Var
}
func NewValue(vr *Var, dev *Device, idx int) *Value {
vl := &Value{}
vl.init(vr, dev, idx)
return vl
}
// MemSizeAlign returns the size aligned according to align byte increments
// e.g., if align = 16 and size = 12, it returns 16
func MemSizeAlign(size, align int) int {
if size%align == 0 {
return size
}
nb := size / align
return (nb + 1) * align
}
// MemSizeAlignDown returns the size aligned according to align byte increments,
// rounding down, not up.
func MemSizeAlignDown(size, align int) int {
if size%align == 0 {
return size
}
nb := size / align
return nb * align
}
// init initializes value based on variable and index
// within list of vals for this var.
func (vl *Value) init(vr *Var, dev *Device, idx int) {
vl.vvar = vr
vl.role = vr.Role
vl.device = *dev
vl.Index = idx
vl.Name = fmt.Sprintf("%s_%d", vr.Name, vl.Index)
vl.VarSize = vr.MemSize()
vl.ArrayN = 1
vl.alignBytes = vr.alignBytes
vl.AlignVarSize = MemSizeAlign(vl.VarSize, vl.alignBytes)
vl.isDynamic = vl.role == Vertex || vl.role == Index || vr.DynamicOffset
vl.dynamicN = 1
if vr.Role >= SampledTexture {
vl.Texture = NewTexture(dev)
}
}
func (vl *Value) String() string {
return fmt.Sprintf("Bytes: 0x%X", vl.MemSize())
}
// MemSize returns the memory allocation size for this value, in bytes.
func (vl *Value) MemSize() int {
if vl.Texture != nil {
return vl.Texture.Format.TotalByteSize()
}
if vl.isDynamic {
return vl.AlignVarSize * vl.dynamicN
}
return vl.ArrayN * vl.VarSize
}
// CreateBuffer creates the GPU buffer for this value if it does not
// yet exist or is not the right size.
// For !ReadOnly [Storage] buffers, calls [Value.CreateReadBuffer].
func (vl *Value) CreateBuffer() error {
if vl.role == SampledTexture {
return nil
}
sz := vl.MemSize()
if sz == 0 {
vl.Release()
return nil
}
if sz == vl.AllocSize && vl.buffer != nil {
return nil
}
vl.Release()
buf, err := vl.device.Device.TryCreateBuffer(&wgpu.BufferDescriptor{
Size: uint64(sz),
Label: vl.Name,
Usage: vl.vvar.bufferUsages(),
MappedAtCreation: false,
})
if errors.Log(err) != nil {
return err
}
vl.AllocSize = sz
vl.buffer = buf
if vl.role == Storage && !vl.vvar.ReadOnly {
vl.CreateReadBuffer()
}
return nil
}
// Release releases the buffer / texture for this value
func (vl *Value) Release() {
if vl.buffer != nil {
vl.buffer.Release()
vl.buffer = nil
}
if vl.Texture != nil {
if vl.Texture.view != nil {
vl.varGroupDirty()
}
vl.Texture.Release()
vl.Texture = nil
}
vl.ReleaseRead()
}
// ReleaseRead releases the read buffer
func (vl *Value) ReleaseRead() {
if vl.readBuffer != nil {
vl.readBuffer.Release()
vl.readBuffer = nil
}
}
// NilBufferCheck checks if buffer is nil, returning error if so
func (vl *Value) NilBufferCheck() error {
if vl.buffer == nil {
return fmt.Errorf("gpu.Value NilBufferCheck: buffer is nil for value: %s", vl.Name)
}
return nil
}
// DynamicN returns the number of dynamic values currently configured.
func (vl *Value) DynamicN() int {
return vl.dynamicN
}
// varGroupDirty tells our VarGroup that our buffers have changed,
// so a new bindGroup needs to be created when it is next requested.
func (vl *Value) varGroupDirty() {
vl.vvar.VarGroup.ValuesUpdated()
}
// SetDynamicN sets the number of dynamic values for this Value.
// If different, a new bindgroup must be generated.
func (vl *Value) SetDynamicN(n int) {
if n == vl.dynamicN {
return
}
vl.varGroupDirty()
vl.dynamicN = n
}
// SetValueFrom copies given values into value buffer memory,
// making the buffer if it has not yet been constructed.
// The actual ArrayN size of Storage or Uniform variables will
// be computed based on the size of the from bytes, relative to
// the variable size.
// IMPORTANT: do not use this for dynamic offset Uniform or
// Storage variables, as the alignment will not be correct;
// See [SetDynamicFromBytes].
func SetValueFrom[E any](vl *Value, from []E) error {
return vl.SetFromBytes(sliceToBytes(from))
}
// SetFromBytes copies given bytes into value buffer memory,
// making the buffer if it has not yet been constructed.
// For !ReadOnly [Storage] buffers, calls [Value.CreateReadBuffer].
// IMPORTANT: do not use this for dynamic offset Uniform or
// Storage variables, as the alignment will not be correct;
// See [SetDynamicFromBytes].
func (vl *Value) SetFromBytes(from []byte) error {
if vl.isDynamic && vl.alignBytes != 1 {
err := fmt.Errorf("gpu.Value SetFromBytes %s: Cannot call this on a DynamicOffset Uniform or Storage variable; use SetDynamicValueFrom instead", vl.Name)
return errors.Log(err)
}
nb := len(from)
an := nb / vl.VarSize
aover := nb % vl.VarSize
if aover != 0 {
err := fmt.Errorf("gpu.Value SetFromBytes %s, Size passed: %d is not an even multiple of the variable size: %d", vl.Name, nb, vl.VarSize)
return errors.Log(err)
}
if vl.isDynamic { // Vertex, Index at this point
vl.SetDynamicN(an)
} else {
vl.ArrayN = an
}
tb := vl.MemSize()
if nb != tb { // this should never happen, but justin case
err := fmt.Errorf("gpu.Value SetFromBytes %s, Size passed: %d != Size expected %d", vl.Name, nb, tb)
return errors.Log(err)
}
if vl.buffer == nil || vl.AllocSize != tb {
vl.varGroupDirty() // only if tb is different; buffer created in bindGroupEntry so not nil here
vl.Release()
buf, err := vl.device.Device.TryCreateBufferInit(&wgpu.BufferInitDescriptor{
Label: vl.Name,
Contents: from,
Usage: vl.vvar.bufferUsages(),
})
if errors.Log(err) != nil {
return err
}
vl.buffer = buf
vl.AllocSize = nb
if vl.role == Storage && !vl.vvar.ReadOnly {
vl.CreateReadBuffer()
}
} else {
err := vl.device.Queue.TryWriteBuffer(vl.buffer, 0, from)
if errors.Log(err) != nil {
return err
}
}
return nil
}
// SetDynamicValueFrom copies given values into a staging buffer
// at the given dynamic variable index, for dynamic offset
// Uniform or Storage variables, which have alignment constraints.
// Must call [WriteDynamicBuffer] after all such values have been updated,
// to actually copy the entire staging buffer data to the GPU device.
// Vertex variables must have separate values for each, and do not
// support dynamic indexing.
// It is essential that [DynamicN] is set properly before
// calling this. Existing values will be preserved with
// changes in DynamicN to the extent possible.
func SetDynamicValueFrom[E any](vl *Value, idx int, from []E) error {
return vl.SetDynamicFromBytes(idx, sliceToBytes(from))
}
// SetDynamicFromBytes copies given values into a staging buffer
// at the given dynamic variable index, for dynamic offset
// Uniform or Storage variables, which have alignment constraints.
// See [SetDynamicValueFrom], which should generally be used,
// for further info.
func (vl *Value) SetDynamicFromBytes(idx int, from []byte) error {
if !vl.isDynamic || vl.alignBytes == 1 {
err := fmt.Errorf("gpu.Value SetDynamicFromBytes %s: Cannot call this on a non-DynamicOffset Uniform or Storage variable; use SetValueFrom instead", vl.Name)
return errors.Log(err)
}
if idx >= vl.dynamicN {
err := fmt.Errorf("gpu.Value SetDynamicFromBytes %s: Index: %d >= DynamicN: %d", vl.Name, idx, vl.dynamicN)
return errors.Log(err)
}
sz := vl.MemSize()
vl.dynamicBuffer = slicesx.SetLength(vl.dynamicBuffer, sz) // preserves data
nb := len(from)
if nb != vl.VarSize {
err := fmt.Errorf("gpu.Value SetDynamicFromBytes %s, Size passed: %d != Size expected %d", vl.Name, nb, vl.VarSize)
return errors.Log(err)
}
off := idx * vl.AlignVarSize
copy(vl.dynamicBuffer[off:off+vl.VarSize], from)
return nil
}
// WriteDynamicBuffer writes the staging buffer up to the GPU
// device, after calling SetDynamicValueFrom for all the individual
// dynamic index cases that need to be updated.
// If this is not called, then the data will not be used!
func (vl *Value) WriteDynamicBuffer() error {
sz := vl.MemSize()
nb := len(vl.dynamicBuffer)
if sz != nb {
err := fmt.Errorf("gpu.Value WriteDynamicBuffer %s, Staging buffer size: %d != Size expected %d; must call SetDynamicValueFrom to establish correct staging buffer size", vl.Name, nb, sz)
return errors.Log(err)
}
if vl.buffer == nil || nb != vl.AllocSize {
vl.varGroupDirty() // only if nb is different; buffer created in bindGroupEntry so not nil here
vl.Release()
buf, err := vl.device.Device.TryCreateBufferInit(&wgpu.BufferInitDescriptor{
Label: vl.Name,
Contents: vl.dynamicBuffer,
Usage: vl.vvar.bufferUsages(),
})
if errors.Log(err) != nil {
return err
}
vl.buffer = buf
vl.AllocSize = nb
} else {
err := vl.device.Queue.TryWriteBuffer(vl.buffer, 0, vl.dynamicBuffer)
if errors.Log(err) != nil {
return err
}
}
return nil
}
// SetDynamicIndex sets the dynamic index to use for
// the current value, returning the value or nil if if the index
// was out of range (logs an error too).
func (vl *Value) SetDynamicIndex(idx int) *Value {
if idx >= vl.dynamicN {
slog.Error("gpu.Values.SetDynamicIndex", "index", idx, "is out of range", vl.dynamicN)
return nil
}
vl.DynamicIndex = idx
return vl
}
func (vl *Value) bindGroupEntry(vr *Var) []wgpu.BindGroupEntry {
if vr.Role >= SampledTexture {
return []wgpu.BindGroupEntry{
{
Binding: uint32(vr.Binding),
TextureView: vl.Texture.view,
},
{
Binding: uint32(vr.Binding + 1),
Sampler: vl.Texture.Sampler.sampler,
},
}
}
vl.CreateBuffer() // ensure made
if vr.DynamicOffset {
return []wgpu.BindGroupEntry{{
Binding: uint32(vr.Binding),
Buffer: vl.buffer,
Offset: 0,
Size: uint64(vl.VarSize), // note: size of one element
},
}
}
return []wgpu.BindGroupEntry{{
Binding: uint32(vr.Binding),
Buffer: vl.buffer,
Offset: 0,
Size: wgpu.WholeSize,
},
}
}
// SetFromGoImage sets Texture image data from an image.Image standard Go image,
// at given layer. This is most efficiently done using an image.RGBA, but other
// formats will be converted as necessary.
// The Sampler is also configured at this point, with the current settings,
// so set those before making this call. It will not be re-configured
// without manually releasing it.
func (vl *Value) SetFromGoImage(img image.Image, layer int) *Texture {
view := vl.Texture.view
err := vl.Texture.SetFromGoImage(img, layer)
errors.Log(err)
err = vl.Texture.Sampler.Config(&vl.device)
errors.Log(err)
vl.textureChanged(view)
return vl.Texture
}
// SetFromTexture sets Texture from an existing gpu Texture.
// The Sampler is also ensured configured at this point,
// with the current settings, so set those before making this call.
// It will not be re-configured without manually releasing it.
func (vl *Value) SetFromTexture(tx *Texture) *Texture {
view := vl.Texture.view
vl.Texture.SetShared(tx)
err := vl.Texture.Sampler.Config(&vl.device)
errors.Log(err)
vl.textureChanged(view)
return vl.Texture
}
// textureChanged tells our VarGroup to make a new bind group if the view
// of our Texture is no longer the given prior one, as when the texture
// was remade at a new size: the bind group refers to the view, so it
// would show the old texture, which is destroyed (see
// [Texture.ReleaseTexture]) and must not be used in a new submit.
func (vl *Value) textureChanged(prior *wgpu.TextureView) {
if vl.Texture.view != prior {
vl.varGroupDirty()
}
}
// CreateReadBuffer creates a read buffer for this value,
// for [Storage] values only. Automatically called for !ReadOnly.
// Read buffer is needed for reading values back from the GPU.
func (vl *Value) CreateReadBuffer() error {
if (vl.role != Storage && vl.role != StorageTexture) || vl.vvar.ReadOnly {
return nil
}
sz := vl.MemSize()
if sz == 0 {
vl.ReleaseRead()
return nil
}
if sz == vl.AllocSize && vl.readBuffer != nil {
return nil
}
vl.ReleaseRead()
buf, err := vl.device.Device.TryCreateBuffer(&wgpu.BufferDescriptor{
Size: uint64(sz),
Label: vl.Name,
Usage: wgpu.BufferUsageMapRead | wgpu.BufferUsageCopyDst,
MappedAtCreation: false,
})
if errors.Log(err) != nil {
return err
}
vl.readBuffer = buf
return nil
}
func (vl *Value) readNilCheck() error {
if vl.readBuffer == nil {
return fmt.Errorf("gpu.Value %q: read buffer is nil", vl.Name)
}
return nil
}
// GPUToRead adds commands to the given command encoder
// to copy given value from its GPU buffer to the read buffer,
// which must have already been created.
// This is the first step for reading values back from the GPU,
// which starts with this command to be executed in the compute pass,
// and then requires ReadSync to actually read the data into
// the CPU side of the read buffer from the GPU, and ends with
// a final ReadToBytes call to copy the raw read bytes into
// a target data structure.
func (vl *Value) GPUToRead(cmd *wgpu.CommandEncoder) error {
if err := vl.readNilCheck(); err != nil {
return errors.Log(err)
}
return cmd.TryCopyBufferToBuffer(vl.buffer, 0, vl.readBuffer, 0, uint64(vl.AllocSize))
}
// ReadSync reads data from GPU to CPU side of the read buffer.
// It is much more efficient to call [ValueReadSync] with _all_ values that
// need to be sync'd at the same time, so only use this when copying one value.
// See [GPUToRead] for overview of the process.
func (vl *Value) ReadSync() error {
if err := vl.readNilCheck(); err != nil {
return errors.Log(err)
}
return ValueReadSync(&vl.device, vl)
}
// ReadToBytes copies value read buffer data into
// the memory bytes occupied by the given object.
// You must have called [ReadSync] on the value
// prior to calling this, so that the memory is mapped.
// This automatically calls Unmap() after copying,
// which is essential for being able to re-use the read buffer again.
func ReadToBytes[E any](vl *Value, dest []E) error {
return readToSlice(vl, dest)
}
// ReadToBytes copies data from read buffer into given byte slice
// which is enforced to be the correct size if not already.
func (vl *Value) ReadToBytes(to []byte) error {
if err := vl.readNilCheck(); err != nil {
return errors.Log(err)
}
copy(to, vl.readBuffer.GetMappedRange(0, uint(vl.AllocSize)))
vl.readBuffer.Unmap()
return nil
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gpu
import (
"fmt"
"log"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/slicesx"
"github.com/oliverbestmann/webgpu/wgpu"
)
// Values is a list container of Value values, accessed by index or name.
type Values struct {
// values in indexed order.
Values []*Value
// current specifies the current value to use in rendering.
current int
// map of vals by name, only for specifically named vals
// vs. generically allocated ones. Names must be unique.
NameMap map[string]*Value
}
// Add adds a new Value for given variable.
func (vs *Values) Add(vr *Var, dev *Device, name ...string) *Value {
if len(name) == 1 && vs.NameMap == nil {
vs.NameMap = make(map[string]*Value)
}
cn := len(vs.Values)
vl := NewValue(vr, dev, cn)
vs.Values = append(vs.Values, vl)
if len(name) == 1 {
vl.Name = name[0]
vs.NameMap[vl.Name] = vl
}
return vl
}
// SetN sets specific number of values, returning true if changed.
func (vs *Values) SetN(vr *Var, dev *Device, nvals int) bool {
cn := len(vs.Values)
if cn == nvals {
return false
}
// Values that are dropped release their buffers and textures now,
// instead of when they are garbage collected.
for i := nvals; i < cn; i++ {
vs.Values[i].Release()
}
vs.Values = slicesx.SetLength(vs.Values, nvals)
for i := cn; i < nvals; i++ {
vl := NewValue(vr, dev, i)
vs.Values[i] = vl
}
if vs.current >= nvals {
vs.current = 0
}
vr.VarGroup.ValuesUpdated()
return true
}
// CurrentValue returns the current Value according to Current index.
func (vs *Values) CurrentValue() *Value {
return vs.Values[vs.current]
}
// SetCurrentValue sets the Current value to given index,
// returning the value or nil if if the index
// was out of range (logs an error too).
func (vs *Values) SetCurrentValue(idx int) (*Value, error) {
if idx >= len(vs.Values) {
err := fmt.Errorf("gpu.Values.SetCurrentValue index %d is out of range %d", idx, len(vs.Values))
errors.Log(err)
return nil, err
}
if vs.current != idx {
vs.current = idx
vs.Values[0].vvar.VarGroup.ValuesUpdated()
}
return vs.CurrentValue(), nil
}
// SetDynamicIndex sets the dynamic index to use for
// the current value, returning the value or nil if if the index
// was out of range (logs an error too).
func (vs *Values) SetDynamicIndex(idx int) *Value {
vl := vs.CurrentValue()
return vl.SetDynamicIndex(idx)
}
// SetName sets name of given Value, by index, adds name to map, checking
// that it is not already there yet. Returns val.
func (vs *Values) SetName(idx int, name string) (*Value, error) {
vl, err := vs.ValueByIndex(idx)
if err != nil {
return nil, err
}
_, has := vs.NameMap[name]
if has {
err := fmt.Errorf("gpu.Values:SetName name %s exists", name)
if Debug {
log.Println(err)
}
return nil, err
}
vl.Name = name
vs.NameMap[name] = vl
return vl, nil
}
// ValueByIndex returns Value at given index with range checking error message.
func (vs *Values) ValueByIndex(idx int) (*Value, error) {
if idx >= len(vs.Values) || idx < 0 {
err := fmt.Errorf("gpu.Values:ValueByIndexTry index %d out of range", idx)
if Debug {
log.Println(err)
}
return nil, err
}
return vs.Values[idx], nil
}
// ValueByName returns value by name, returning error if not found
func (vs *Values) ValueByName(name string) (*Value, error) {
vl, ok := vs.NameMap[name]
if !ok {
err := fmt.Errorf("gpu.Values:ValueByNameTry name %s not found", name)
if Debug {
log.Println(err)
}
return nil, err
}
return vl, nil
}
// Release frees all the value buffers / textures
func (vs *Values) Release() {
for _, vl := range vs.Values {
vl.Release()
}
vs.Values = nil
vs.NameMap = nil
}
// MemSize returns size in bytes across all Values in list
func (vs *Values) MemSize() int {
tsz := 0
for _, vl := range vs.Values {
tsz += vl.MemSize()
}
return tsz
}
// bindGroupEntry returns the BindGroupEntry for Current
// value for this variable.
func (vs *Values) bindGroupEntry(vr *Var) []wgpu.BindGroupEntry {
vl := vs.CurrentValue()
return vl.bindGroupEntry(vr)
}
func (vs *Values) dynamicOffset() uint32 {
vl := vs.CurrentValue()
return uint32(vl.AlignVarSize * vl.DynamicIndex)
}
// Copyright (c) 2022, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gpu
import (
"fmt"
"github.com/oliverbestmann/webgpu/wgpu"
)
// Var specifies a variable used in a pipeline, accessed in shader programs
// at a specific @group (from VarGroup owner) and @binding location.
// There must be a different Var for each type of input or output into
// the GPU program, including things like Vertex arrays, transformation
// matricies (Uniforms), Textures, and arbitrary Storage data (Structs)
// for Compute shaders.
// There are one or more corresponding Value items for each Var, which represent
// the actual value of the variable: Var only represents the type-level info.
// Each Var belongs to a VarGroup, and its Binding location is sequential within that.
// The entire Group is updated at the same time from the hardware perspective,
// and less-frequently-updated items should be in the lower-numbered groups.
// The Role
type Var struct {
// variable name
Name string
// Type of data in variable. Note that there are strict contraints
// on the alignment of fields within structs. If you can keep all fields
// at 4 byte increments, that works, but otherwise larger fields trigger
// a 16 byte alignment constraint. Textures do not have such alignment
// constraints, and are stored separately or in arrays organized by size.
// Use Float32Matrix4 for model matricies in Vertex role, which will
// automatically be sent as 4 interleaved Float32Vector4 chuncks.
Type Types
// ArrayN is the number of elements in an array, only if there is a
// fixed array size. Otherwise, for single elements or dynamic arrays
// use a value of 1. There can be alignment issues with arrays
// so make sure your elemental types are compatible.
// Note that DynamicOffset variables can have Value buffers with multiple
// instances of the variable (with proper alignment stride),
// which goes on top of any array value for the variable itself.
ArrayN int
// Role of variable: Vertex is configured separately, and everything else
// is configured in a BindGroup. This is inherited from the VarGroup
// and all Vars in a Group must have the same Role, except Index is also
// included in the VertexGroup (-2).
// Note: Push is not yet supported.
Role VarRoles
// VertexInstance is whether this Vertex role variable is specified
// per instance (true) or per vertex (false, default).
// Instance variables can be used for sending per-object data like
// the model matrix (as Float32Matrix4 which is serialized as 4
// Float32Vector4 values). Can also send texture indexes,
// per object color, etc.
VertexInstance bool
// bit flags for set of shaders that this variable is used in, determined
// by the Role.
shaders wgpu.ShaderStage `edit:"-"`
// Group binding for this variable, indicated by @group in WGSL shader.
// In general, put data that is updated at the same point in time in the same
// group, as everything within a group is updated together.
Group int
// binding number for this variable, indicated by @binding in WGSL shader.
// These are automatically assigned sequentially within Group.
Binding int `edit:"-"`
// size in bytes of one element (exclusive of array size).
// Note that arrays in Uniform require 16 byte alignment for each element,
// so if using arrays, it is best to work within that constraint.
// In Storage, 4 byte (e.g., float32 or int32) works fine as an array type.
// For Push role, SizeOf must be set exactly, as no vals are created.
SizeOf int
// DynamicOffset indicates whether the specific Value to use
// is specified using a dynamic offset specified in the Value
// via DynamicIndex. There are limits on the number of dynamic
// variables within each group (as few as 4).
// Only for Uniform and Storage variables.
DynamicOffset bool
// ReadOnly applies only to [Storage] variables, and indicates that
// they are never read back from the GPU, so the additional staging
// buffers needed to do so are not created for these variables.
ReadOnly bool
// Values is the the array of Values allocated for this variable.
// Each value has its own corresponding Buffer or Texture.
// The currently-active Value is specified by the Current index,
// and this is what will be used for Binding.
Values Values
// offset: for push constants, not currently used.
offset int `edit:"-"`
// the alignment requirement in bytes for DynamicOffset variables.
// This is 1 for Vertex buffer variables.
alignBytes int
// var group we are in
VarGroup *VarGroup
}
// NewVar returns a new Var in given var group
func NewVar(vg *VarGroup, name string, typ Types, arrayN int, shaders ...ShaderTypes) *Var {
vr := &Var{}
vr.init(vg, name, typ, arrayN, shaders...)
return vr
}
// init initializes the main values
func (vr *Var) init(vg *VarGroup, name string, typ Types, arrayN int, shaders ...ShaderTypes) {
vr.VarGroup = vg
vr.Name = name
vr.Type = typ
vr.ArrayN = max(arrayN, 1)
vr.Role = vg.Role
vr.SizeOf = typ.Bytes()
vr.Group = vg.Group
vr.alignBytes = vg.alignBytes
vr.shaders = 0
for _, sh := range shaders {
vr.shaders |= ShaderStageFlags[sh]
}
}
func (vr *Var) String() string {
typ := vr.Type.String()
if vr.ArrayN > 1 {
if vr.ArrayN > 10000 {
typ = fmt.Sprintf("%s[0x%X]", typ, vr.ArrayN)
} else {
typ = fmt.Sprintf("%s[%d]", typ, vr.ArrayN)
}
}
s := fmt.Sprintf("%d:\t%s\t%s\t(size: %d)\tValues: %d", vr.Binding, vr.Name, typ, vr.SizeOf, len(vr.Values.Values))
if len(vr.Values.Values) == 1 {
s += "\t" + vr.Values.Values[0].String()
}
return s
}
// MemSize returns the memory allocation size for this value, in bytes
func (vr *Var) MemSize() int {
if vr.ArrayN < 1 {
vr.ArrayN = 1
}
switch {
case vr.Role >= SampledTexture:
return 0
default:
return vr.SizeOf * vr.ArrayN
}
}
// Release resets the MemPtr for values, resets any self-owned resources (Textures)
func (vr *Var) Release() {
vr.Values.Release()
}
// SetNValues sets specified number of Values for this var.
// returns true if changed.
func (vr *Var) SetNValues(dev *Device, nvals int) bool {
return vr.Values.SetN(vr, dev, nvals)
}
// SetCurrentValue sets the Current Value index, which is
// the Value that will be used in rendering, via BindGroup
func (vr *Var) SetCurrentValue(i int) {
vr.Values.SetCurrentValue(i)
}
// bindGroupEntry returns the BindGroupEntry for Current
// value for this variable.
func (vr *Var) bindGroupEntry() []wgpu.BindGroupEntry {
return vr.Values.bindGroupEntry(vr)
}
func (vr *Var) bindingType() wgpu.BufferBindingType {
if vr.Role == Storage && vr.ReadOnly {
return wgpu.BufferBindingTypeReadOnlyStorage
}
return vr.Role.BindingType()
}
func (vr *Var) bufferUsages() wgpu.BufferUsage {
if vr.Role == Storage && vr.ReadOnly {
return wgpu.BufferUsageStorage | wgpu.BufferUsageCopyDst
}
return vr.Role.BufferUsages()
}
// Copyright (c) 2022, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gpu
import (
"fmt"
"slices"
"strconv"
"sync"
"cogentcore.org/core/base/errors"
"github.com/oliverbestmann/webgpu/wgpu"
)
const (
// MaxTextureLayers is the maximum number of layers per image
MaxTextureLayers = 128
// VertexGroup is the group number for Vertex and Index variables,
// which have special treatment.
VertexGroup = -2
// PushGroup is the group number for Push Constants, which
// do not appear in the BindGroupLayout and are managed separately.
PushGroup = -1
)
// VarGroup contains a group of Var variables, accessed via @group number
// in shader code, with @binding allocated sequentially within group
// (or @location in the case of VertexGroup).
type VarGroup struct {
// name is optional, for user reference, documentation
Name string
// variables in order
Vars []*Var
// map of vars by name; names must be unique
VarMap map[string]*Var
// Group index is assigned sequentially, with special VertexGroup and
// PushGroup having negative numbers, not accessed via @group in shader.
Group int
// Role is default Role of variables within this group.
// Vertex is configured separately, and everything else
// is configured in a BindGroup.
// Note: Push is not yet supported.
Role VarRoles
// map of vars by different roles, within this group.
// Updated in Config(), after all vars added
RoleMap map[VarRoles][]*Var
// number of variables with DynamicOffset set
nDynamicOffsets int
device Device
// the alignment requirement in bytes for DynamicOffset variables.
// This is 1 for Vertex buffer variables.
alignBytes int
// this counter updates when when a Values.current has been changed.
// pipelines record the count that they last used to determine if time
// to change. Use BindGroupUpdateCount() to access under lock.
bindGroupUpdateCount int
// mutex used for bindGroupsUpdateCount
sync.Mutex
}
// addVar adds given variable
func (vg *VarGroup) addVar(vr *Var) {
if vg.VarMap == nil {
vg.VarMap = make(map[string]*Var)
}
vg.Vars = append(vg.Vars, vr)
vg.VarMap[vr.Name] = vr
}
// Add adds a new variable of given type, role, arrayN, and shaders where used
func (vg *VarGroup) Add(name string, typ Types, arrayN int, shaders ...ShaderTypes) *Var {
vr := NewVar(vg, name, typ, arrayN, shaders...)
vg.addVar(vr)
return vr
}
// AddStruct adds a new struct variable of given total number of bytes in size,
// type, role, set, and shaders where used
func (vg *VarGroup) AddStruct(name string, size int, arrayN int, shaders ...ShaderTypes) *Var {
vr := NewVar(vg, name, Struct, arrayN, shaders...)
vr.SizeOf = size
vg.addVar(vr)
return vr
}
// VarByName returns Var by name, returning error if not found
func (vg *VarGroup) VarByName(name string) (*Var, error) {
vr, ok := vg.VarMap[name]
if !ok {
err := fmt.Errorf("variable named %s not found", name)
if Debug {
errors.Log(err)
}
return nil, err
}
return vr, nil
}
// ValueByName returns value by first looking up variable name, then value name,
// returning error if not found.
func (vg *VarGroup) ValueByName(varName, valName string) (*Value, error) {
vr, err := vg.VarByName(varName)
if err != nil {
return nil, err
}
vl, err := vr.Values.ValueByName(valName)
return vl, err
}
// ValueByIndex returns value by first looking up variable name, then value index,
// returning error if not found.
func (vg *VarGroup) ValueByIndex(varName string, valIndex int) (*Value, error) {
vr, err := vg.VarByName(varName)
if err != nil {
return nil, err
}
return vr.Values.ValueByIndex(valIndex)
}
// SetCurrentValue sets the index of the Current Value to use
// for given variable name.
func (vg *VarGroup) SetCurrentValue(name string, valueIndex int) (*Var, error) {
vr, err := vg.VarByName(name)
if err != nil {
return nil, err
}
if _, err := vr.Values.SetCurrentValue(valueIndex); err != nil {
return nil, err
}
return vr, nil
}
// SetDynamicIndex sets the dynamic offset index for Value to use
// for given variable name.
func (vg *VarGroup) SetDynamicIndex(name string, dynamicIndex int) (*Var, error) {
vr, err := vg.VarByName(name)
if err != nil {
return nil, err
}
vr.Values.SetDynamicIndex(dynamicIndex)
return vr, nil
}
// SetNValues sets all vars in this group to have specified
// number of Values.
func (vg *VarGroup) SetNValues(nvals int) {
for _, vr := range vg.Vars {
vr.SetNValues(&vg.device, nvals)
}
}
// SetAllCurrentValue sets the Current Value index, which is
// the Value that will be used in rendering, via BindGroup,
// for all vars in group.
func (vg *VarGroup) SetAllCurrentValue(i int) {
for _, vr := range vg.Vars {
vr.Values.SetCurrentValue(i)
}
}
// ValuesUpdated is called whenever values have been updated in a way
// that requires new a new bind group to be computed.
func (vg *VarGroup) ValuesUpdated() {
vg.Lock()
vg.bindGroupUpdateCount++
vg.Unlock()
}
// BindGroupUpdateCount is the count of the times that values have been updated in a way
// that requires new a new bind group to be computed.
func (vg *VarGroup) BindGroupUpdateCount() int {
vg.Lock()
defer vg.Unlock()
return vg.bindGroupUpdateCount
}
// Config must be called after all variables have been added.
// Configures binding / location for all vars based on sequential order.
// also does validation and returns error message.
func (vg *VarGroup) Config(dev *Device) error {
if vg.Name == "" {
switch vg.Group {
case VertexGroup:
vg.Name = "VertexGroup"
case PushGroup:
vg.Name = "PushGroup"
default:
vg.Name = fmt.Sprintf("Group%d", vg.Group)
}
}
vg.device = *dev
vg.RoleMap = make(map[VarRoles][]*Var)
var errs []error
bnum := 0
for _, vr := range vg.Vars {
if vg.Group == VertexGroup && vr.Role > Index {
err := fmt.Errorf("gpu.VarGroup:Config VertexGroup cannot contain variables of role: %s var: %s", vr.Role.String(), vr.Name)
errs = append(errs, err)
errors.Log(err)
continue
}
if vg.Group >= 0 && vr.Role <= Index {
err := errors.New("gpu.VarGroup:Config Vertex or Index Vars must be located in a VertexGroup! Use AddVertexGroup() method instead of AddGroup()")
errs = append(errs, err)
errors.Log(err)
}
rl := vg.RoleMap[vr.Role]
rl = append(rl, vr)
vg.RoleMap[vr.Role] = rl
if vr.Role == Index && len(rl) > 1 {
err := fmt.Errorf("gpu.VarGroup:Config VertexGroup should not contain multiple Index variables: %v", rl)
errs = append(errs, err)
errors.Log(err)
}
if vr.Role > Storage && (len(vg.RoleMap[Uniform]) > 0 || len(vg.RoleMap[Storage]) > 0) {
err := fmt.Errorf("gpu.VarGroup:Config Group with dynamic Uniform or Storage variables should not contain static variables (e.g., textures): %s", vr.Role.String())
errs = append(errs, err)
errors.Log(err)
}
if vr.Role != Index { // index doesn't count
vr.Binding = bnum
bnum++
}
if vr.Role == Vertex && vr.Type == Float32Matrix4 { // special case
bnum += 3
}
if vr.Role == SampledTexture { // sampler too
bnum++
}
}
return errors.Join(errs...)
}
// Release destroys infrastructure for Group, Vars and Values.
func (vg *VarGroup) Release() {
for _, vr := range vg.Vars {
vr.Release()
}
}
// bindLayout creates the BindGroupLayout for given group.
// Only for non-VertexGroup sets.
// Must have set NValuesPer for any SampledTexture vars,
// which require separate descriptors per.
func (vg *VarGroup) bindLayout(_ *Vars, used ...*Var) (*wgpu.BindGroupLayout, error) {
var binds []wgpu.BindGroupLayoutEntry
vg.nDynamicOffsets = 0
// https://eliemichel.github.io/LearnWebGPU/basic-3d-rendering/shader-uniforms/dynamic-uniforms.html
// https://toji.dev/webgpu-best-practices/bind-groups.html
for _, vr := range vg.Vars {
if len(used) > 0 && !slices.Contains(used, vr) {
continue
}
if vr.Role == Vertex || vr.Role == Index { // shouldn't happen
continue
}
bd := wgpu.BindGroupLayoutEntry{
Binding: uint32(vr.Binding),
Visibility: vr.shaders,
}
switch vr.Role {
case SampledTexture:
binds = append(binds, wgpu.BindGroupLayoutEntry{
Binding: uint32(vr.Binding),
Visibility: vr.shaders,
Texture: wgpu.TextureBindingLayout{
Multisampled: false,
ViewDimension: wgpu.TextureViewDimension2D, // todo:
SampleType: wgpu.TextureSampleTypeFloat,
},
})
bd.Binding = uint32(vr.Binding + 1)
bd.Sampler = wgpu.SamplerBindingLayout{
Type: wgpu.SamplerBindingTypeFiltering,
}
default:
bd.Buffer = wgpu.BufferBindingLayout{
Type: vr.bindingType(),
HasDynamicOffset: false,
MinBindingSize: 0, // 0 is fine
}
if vr.DynamicOffset {
bd.Buffer.HasDynamicOffset = true
vg.nDynamicOffsets++
}
}
binds = append(binds, bd)
}
// fmt.Println(reflectx.StringJSON(binds))
bgld := wgpu.BindGroupLayoutDescriptor{
Label: strconv.Itoa(vg.Group),
Entries: binds,
}
bgl, err := vg.device.Device.TryCreateBindGroupLayout(&bgld)
if errors.Log(err) != nil {
return nil, err
}
return bgl, nil
}
// dynamicOffsets returns any current dynamic offsets for this group
func (vg *VarGroup) dynamicOffsets(used ...*Var) []uint32 {
var do []uint32
if vg.Role == Vertex || vg.Role == SampledTexture {
return do
}
curDynIdx := 0
for _, vr := range vg.Vars {
if len(used) > 0 && !slices.Contains(used, vr) {
continue
}
if vr.DynamicOffset {
do = append(do, vr.Values.dynamicOffset())
curDynIdx++
}
}
return do
}
// bindGroup returns the Current Value bindings for all variables
// within this Group, subject to the used filter if present.
// This determines what Values of the Vars the current Render
// actions will use. Only for non-VertexGroup groups.
func (vg *VarGroup) bindGroup(vs *Vars, used ...*Var) (*wgpu.BindGroup, error) {
bgl, err := vg.bindLayout(vs, used...)
if err != nil {
return nil, err
}
defer bgl.Release()
var bgs []wgpu.BindGroupEntry
for _, vr := range vg.Vars {
if len(used) > 0 && !slices.Contains(used, vr) {
continue
}
bgs = append(bgs, vr.bindGroupEntry()...)
}
bg, err := vg.device.Device.TryCreateBindGroup(&wgpu.BindGroupDescriptor{
Layout: bgl,
Entries: bgs,
Label: vg.Name,
})
if errors.Log(err) != nil {
return nil, err
}
return bg, nil
}
// IndexVar returns the Index variable within this VertexGroup.
// returns nil if not found.
func (vg *VarGroup) IndexVar() *Var {
n := len(vg.Vars)
for i := n - 1; i >= 0; i-- { // typically at end, go in reverse
vr := vg.Vars[i]
if vr.Role == Index {
return vr
}
}
return nil
}
// vertexLayout returns the VertexBufferLayout based on Vertex role
// variables within this VertexGroup.
// Note: there is no support for interleaved arrays
// so each location is sequential number, recorded in var Binding
func (vg *VarGroup) vertexLayout() []wgpu.VertexBufferLayout {
var vbls []wgpu.VertexBufferLayout
for _, vr := range vg.Vars {
if vr.Role != Vertex { // not Index
continue
}
stepMode := wgpu.VertexStepModeVertex
if vr.VertexInstance {
stepMode = wgpu.VertexStepModeInstance
}
if vr.Type == Float32Matrix4 {
vbls = append(vbls, wgpu.VertexBufferLayout{
ArrayStride: uint64(vr.SizeOf),
StepMode: stepMode,
Attributes: []wgpu.VertexAttribute{
{
Offset: 0,
ShaderLocation: uint32(vr.Binding),
Format: Float32Vector4.VertexFormat(),
},
{
Offset: 4,
ShaderLocation: uint32(vr.Binding + 1),
Format: Float32Vector4.VertexFormat(),
},
{
Offset: 8,
ShaderLocation: uint32(vr.Binding + 2),
Format: Float32Vector4.VertexFormat(),
},
{
Offset: 12,
ShaderLocation: uint32(vr.Binding + 3),
Format: Float32Vector4.VertexFormat(),
},
},
})
} else {
vbls = append(vbls, wgpu.VertexBufferLayout{
ArrayStride: uint64(vr.SizeOf),
StepMode: stepMode,
Attributes: []wgpu.VertexAttribute{
{
Offset: 0,
ShaderLocation: uint32(vr.Binding),
Format: vr.Type.VertexFormat(),
},
},
})
}
}
return vbls
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gpu
import (
"fmt"
"log"
"strings"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/indent"
"github.com/oliverbestmann/webgpu/wgpu"
)
// Vars are all the variables that are used by a pipeline,
// organized into Groups (optionally including the special VertexGroup
// or PushGroup).
// Vars are allocated to bindings sequentially in the order added.
type Vars struct {
// map of Groups, by group number: VertexGroup is -2, PushGroup is -1,
// rest are added incrementally.
Groups map[int]*VarGroup
// map of vars by different roles across all Groups, updated in Config(),
// after all vars added.
RoleMap map[VarRoles][]*Var
// full set of BindGroupLayouts, one for each VarGroup >= 0
layouts []*wgpu.BindGroupLayout `display:"-"`
// true if a VertexGroup has been added
hasVertex bool `edit:"-"`
// true if PushGroup has been added. Note: not yet supported in WebGPU.
hasPush bool `edit:"-"`
sys System
device Device
}
func (vs *Vars) Release() {
for _, vg := range vs.Groups {
vg.Release()
}
}
// AddVertexGroup adds a new Vertex Group.
// This is a special Group holding Vertex, Index vars
func (vs *Vars) AddVertexGroup() *VarGroup {
if vs.Groups == nil {
vs.Groups = make(map[int]*VarGroup)
}
vg := &VarGroup{Name: "Vertex", Group: VertexGroup, Role: Vertex, alignBytes: 1, device: vs.device}
vs.Groups[VertexGroup] = vg
vs.hasVertex = true
return vg
}
// VertexGroup returns the Vertex Group -- a special Group holding Vertex, Index vars
func (vs *Vars) VertexGroup() *VarGroup {
return vs.Groups[VertexGroup]
}
// AddPushGroup adds a new push constant Group -- this is a special Group holding
// values sent directly in the command buffer.
func (vs *Vars) AddPushGroup() *VarGroup {
if vs.Groups == nil {
vs.Groups = make(map[int]*VarGroup)
}
vg := &VarGroup{Name: "Push", Group: PushGroup, alignBytes: 1, device: vs.device}
vs.Groups[PushGroup] = vg
vs.hasPush = true
return vg
}
// PushGroup returns the Push Group -- a special Group holding push constants
func (vs *Vars) PushGroup() *VarGroup {
return vs.Groups[PushGroup]
}
// AddGroup adds a new non-Vertex Group for holding data for given Role
// (Uniform, Storage, etc).
// Groups are automatically numbered sequentially in order added.
// Name is optional and just provides documentation.
// Important limit: there can only be a maximum of 4 Groups!
func (vs *Vars) AddGroup(role VarRoles, name ...string) *VarGroup {
if vs.Groups == nil {
vs.Groups = make(map[int]*VarGroup)
}
idx := vs.NGroups()
if idx >= 4 {
panic("gpu.AddGroup: there is a hard limit of 4 on the number of VarGroups imposed by the WebGPU system, on Web platforms!")
}
vg := &VarGroup{Group: idx, Role: role, device: vs.device}
if len(name) == 1 {
vg.Name = name[0]
}
vg.alignBytes = 1
switch role {
case Uniform:
vg.alignBytes = int(vs.sys.GPU().Limits.MinUniformBufferOffsetAlignment)
// note: wgpu-native reports alignment sizes of 64
// but then barfs when that is used. 256 seems to keep it happy
vg.alignBytes = max(vg.alignBytes, 256)
case Storage:
vg.alignBytes = int(vs.sys.GPU().Limits.MinStorageBufferOffsetAlignment)
vg.alignBytes = max(vg.alignBytes, 256)
}
vs.Groups[idx] = vg
return vg
}
// VarByName returns Var by name in given group number,
// returning error if not found
func (vs *Vars) VarByName(group int, name string) (*Var, error) {
vg, err := vs.Group(group)
if err != nil {
return nil, err
}
return vg.VarByName(name)
}
// ValueByName returns value by first looking up variable name, then value name,
// within given group number, returning error if not found
func (vs *Vars) ValueByName(group int, varName, valName string) (*Value, error) {
vg, err := vs.Group(group)
if err != nil {
return nil, err
}
return vg.ValueByName(varName, valName)
}
// ValueByIndex returns value by first looking up variable name, then value index,
// returning error if not found
func (vs *Vars) ValueByIndex(group int, varName string, valIndex int) (*Value, error) {
vg, err := vs.Group(group)
if err != nil {
return nil, err
}
return vg.ValueByIndex(varName, valIndex)
}
// SetCurrentValue sets the index of the current Value to use
// for given variable name, in given group number.
func (vs *Vars) SetCurrentValue(group int, name string, valueIndex int) (*Var, error) {
vg, err := vs.Group(group)
if err != nil {
return nil, err
}
vr, err := vg.VarByName(name)
if err != nil {
return nil, err
}
if _, err := vr.Values.SetCurrentValue(valueIndex); err != nil {
return nil, err
}
return vr, nil
}
// SetDynamicIndex sets the dynamic offset index for Value to use
// for given variable name, in given group number.
func (vs *Vars) SetDynamicIndex(group int, name string, dynamicIndex int) *Var {
vr, err := vs.VarByName(group, name)
if errors.Log(err) != nil {
return nil
}
vr.Values.SetDynamicIndex(dynamicIndex)
return vr
}
// Config must be called after all variables have been added.
// Configures all Groups and also does validation, returning error
// does DescLayout too, so all ready for Pipeline config.
func (vs *Vars) Config(dev *Device) error {
ns := vs.NGroups()
var cerr error
vs.RoleMap = make(map[VarRoles][]*Var)
for gi := vs.StartGroup(); gi < ns; gi++ {
vg := vs.Groups[gi]
if vg == nil {
continue
}
err := vg.Config(dev)
if err != nil {
cerr = err
}
for ri, rl := range vg.RoleMap {
vs.RoleMap[ri] = append(vs.RoleMap[ri], rl...)
}
}
vs.bindLayout(dev)
return cerr
}
// StringDoc returns info on variables
func (vs *Vars) StringDoc() string {
ispc := 4
var sb strings.Builder
ns := vs.NGroups()
for gi := vs.StartGroup(); gi < ns; gi++ {
vg := vs.Groups[gi]
if vg == nil {
continue
}
fmt.Fprintf(&sb, "Group: %d %s\n", vg.Group, vg.Name)
for ri := Vertex; ri < VarRolesN; ri++ {
rl, has := vg.RoleMap[ri]
if !has || len(rl) == 0 {
continue
}
fmt.Fprintf(&sb, "%sRole: %s\n", indent.Spaces(1, ispc), ri.String())
for _, vr := range rl {
fmt.Fprintf(&sb, "%sVar: %s\n", indent.Spaces(2, ispc), vr.String())
}
}
}
return sb.String()
}
// NGroups returns the number of regular non-VertexGroup groups
func (vs *Vars) NGroups() int {
ex := 0
if vs.hasVertex {
ex++
}
if vs.hasPush {
ex++
}
return len(vs.Groups) - ex
}
// StartGroup returns the starting group to use for iterating groups
func (vs *Vars) StartGroup() int {
switch {
case vs.hasVertex:
return VertexGroup
case vs.hasPush:
return PushGroup
default:
return 0
}
}
// Group returns group by index, returning nil and error if not found
func (vs *Vars) Group(group int) (*VarGroup, error) {
vg, has := vs.Groups[group]
if !has {
err := fmt.Errorf("gpu.Vars:GroupTry gp number %d not found", group)
if Debug {
log.Println(err)
}
return nil, err
}
return vg, nil
}
// VertexLayout returns WebGPU vertex layout, for VertexGroup only!
func (vs *Vars) VertexLayout() []wgpu.VertexBufferLayout {
if vs.hasVertex {
return vs.Groups[VertexGroup].vertexLayout()
}
return nil
}
/*
// VkPushConfig returns WebGPU push constant ranges, only if PushGroup used.
func (vs *Vars) VkPushConfig() []vk.PushConstantRange {
if vs.hasPush {
return vs.Groups[PushGroup].VkPushConfig()
}
return nil
}
*/
// bindLayout configures the Layouts slice of BindGroupLayouts
// for all of the non-Vertex vars
func (vs *Vars) bindLayout(_ *Device, used ...*Var) []*wgpu.BindGroupLayout {
ngp := vs.NGroups()
if ngp == 0 {
vs.layouts = nil
return nil
}
var lays []*wgpu.BindGroupLayout
for gi := range ngp { // auto-skips vertex, push
vg := vs.Groups[gi]
if vg == nil {
continue
}
vgl, err := vg.bindLayout(vs, used...)
if err != nil {
continue
}
lays = append(lays, vgl)
}
return lays
}
// Adapted from github.com/oliverbestmann/webgpu/wgpuglfw, which is
// licensed under the Apache License, Version 2.0, to use the Cogent Core
// fork of glfw, github.com/cogentcore/glfw4.
//go:build (linux || freebsd || netbsd || openbsd) && !android && ((!x11 && !wayland) || (x11 && wayland))
package wgpuglfw
import (
"unsafe"
"github.com/cogentcore/glfw4/v3.4/glfw"
"github.com/oliverbestmann/webgpu/wgpu"
)
func GetSurfaceDescriptor(w *glfw.Window) *wgpu.SurfaceDescriptor {
switch glfw.GetPlatform() {
case glfw.PlatformX11:
return &wgpu.SurfaceDescriptor{
XlibWindow: &wgpu.SurfaceSourceXlibWindow{
Display: unsafe.Pointer(glfw.GetX11Display()),
Window: uint32(w.GetX11Window()),
},
}
case glfw.PlatformWayland:
return &wgpu.SurfaceDescriptor{
WaylandSurface: &wgpu.SurfaceSourceWaylandSurface{
Display: unsafe.Pointer(glfw.GetWaylandDisplay()),
Surface: unsafe.Pointer(w.GetWaylandWindow()),
},
}
default:
panic("unsupported glfw platform")
}
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package css
import (
"strconv"
"strings"
)
// CalcPx returns the value in px of the given length, which can be a
// calc() expression of lengths in px, em, and rem (of 16px), and numbers,
// with +, -, *, / and parentheses, as in media queries.
func CalcPx(v string) (float32, bool) {
v = strings.TrimSpace(strings.ToLower(v))
if inner, ok := strings.CutPrefix(v, "calc("); ok {
v = "(" + inner
}
p := &calcParser{s: v}
f, ok := p.sum()
p.space()
return float32(f), ok && p.i == len(p.s)
}
// calcParser parses calc expressions.
type calcParser struct {
s string
i int
}
func (p *calcParser) space() {
for p.i < len(p.s) && p.s[p.i] == ' ' {
p.i++
}
}
func (p *calcParser) sum() (float64, bool) {
f, ok := p.product()
for ok {
p.space()
if p.i >= len(p.s) || (p.s[p.i] != '+' && p.s[p.i] != '-') {
break
}
op := p.s[p.i]
p.i++
g, gok := p.product()
if !gok {
return 0, false
}
if op == '+' {
f += g
} else {
f -= g
}
}
return f, ok
}
func (p *calcParser) product() (float64, bool) {
f, ok := p.factor()
for ok {
p.space()
if p.i >= len(p.s) || (p.s[p.i] != '*' && p.s[p.i] != '/') {
break
}
op := p.s[p.i]
p.i++
g, gok := p.factor()
if !gok || (op == '/' && g == 0) {
return 0, false
}
if op == '*' {
f *= g
} else {
f /= g
}
}
return f, ok
}
func (p *calcParser) factor() (float64, bool) {
p.space()
if p.i < len(p.s) && p.s[p.i] == '(' {
p.i++
f, ok := p.sum()
p.space()
if !ok || p.i >= len(p.s) || p.s[p.i] != ')' {
return 0, false
}
p.i++
return f, true
}
start := p.i
for p.i < len(p.s) && (p.s[p.i] >= '0' && p.s[p.i] <= '9' || p.s[p.i] == '.' || (p.i == start && p.s[p.i] == '-')) {
p.i++
}
n, err := strconv.ParseFloat(p.s[start:p.i], 64)
if err != nil {
return 0, false
}
switch {
case strings.HasPrefix(p.s[p.i:], "px"):
p.i += 2
case strings.HasPrefix(p.s[p.i:], "rem"):
p.i += 3
n *= 16
case strings.HasPrefix(p.s[p.i:], "em"):
p.i += 2
n *= 16
}
return n, true
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package css
import (
"image"
"image/color"
"math"
"strconv"
"strings"
"cogentcore.org/core/colors"
"cogentcore.org/core/colors/gradient"
)
// BackgroundColor returns the color of the given background value.
func BackgroundColor(v string) string {
for _, f := range SplitColors(v) {
lf := strings.ToLower(f)
if strings.HasPrefix(lf, "url(") || strings.Contains(lf, "gradient(") {
continue
}
if lf == "transparent" || lf == "none" {
return lf
}
if ParseColor(f) != nil {
return f
}
}
return ""
}
// ParseColor returns the given CSS color, or nil if it is not one.
func ParseColor(v string) image.Image {
v = strings.TrimSpace(v)
if v == "" {
return nil
}
if strings.EqualFold(v, "transparent") {
return colors.Uniform(colors.Transparent)
}
if !strings.HasPrefix(v, "#") && !strings.Contains(v, "(") {
// legacy colors without a #, as in bgcolor="ffffff"
if len(v) == 6 || len(v) == 3 {
if _, err := strconv.ParseUint(v, 16, 32); err == nil {
v = "#" + v
}
}
}
if cl, ok := ColorFunction(v); ok {
return colors.Uniform(cl)
}
cl, err := colors.FromString(v)
if err != nil {
img, err := gradient.FromString(v)
if err != nil {
return nil
}
return img
}
return colors.Uniform(cl)
}
// ColorFunction returns the color of the given CSS rgb(), rgba(),
// hsl() or hsla() function, with the syntax of CSS: components that
// are numbers or percentages, separated by commas or spaces, and an
// alpha (after a comma or a /) from 0 to 1 or a percentage.
func ColorFunction(v string) (color.RGBA, bool) {
lv := strings.ToLower(strings.TrimSpace(v))
name, args, ok := strings.Cut(lv, "(")
if !ok || !strings.HasSuffix(args, ")") {
return color.RGBA{}, false
}
if name == "light-dark" { // the light color, as for the light color scheme
light, _, _ := CutTopLevel(strings.TrimSuffix(args, ")"), ',')
if cl, ok := ColorFunction(light); ok {
return cl, true
}
cl, err := colors.FromString(light)
return color.RGBA(colors.AsRGBA(cl)), err == nil
}
switch name {
case "rgb", "rgba", "hsl", "hsla", "color", "oklab", "oklch":
default:
return color.RGBA{}, false
}
args = strings.NewReplacer(",", " ", "/", " ").Replace(strings.TrimSuffix(args, ")"))
fs := strings.Fields(args)
space := ""
if name == "color" && len(fs) > 0 { // color(space c1 c2 c3 [/ alpha])
space, fs = fs[0], fs[1:]
}
if len(fs) < 3 {
return color.RGBA{}, false
}
// num returns the component, with a percentage of the given scale
num := func(f string, scale float64) float64 {
f = strings.TrimSuffix(f, "deg")
if p, ok := strings.CutSuffix(f, "%"); ok {
n, _ := strconv.ParseFloat(p, 64)
return n / 100 * scale
}
n, _ := strconv.ParseFloat(f, 64)
return n
}
a := 1.0
if len(fs) > 3 {
a = math.Max(0, math.Min(1, num(fs[3], 1)))
}
var r, g, b float64
switch name {
case "color":
r, g, b = num(fs[0], 1), num(fs[1], 1), num(fs[2], 1)
switch space {
case "srgb-linear":
r, g, b = srgbGamma(r), srgbGamma(g), srgbGamma(b)
case "display-p3":
r, g, b = p3ToSRGB(r, g, b)
} // others (as a98-rgb) are approximated as sRGB
return rgbaFloat(r, g, b, a), true
case "oklab", "oklch":
l := num(fs[0], 1)
var ca, cb float64
if name == "oklab" {
ca, cb = num(fs[1], 0.4), num(fs[2], 0.4)
} else {
c, h := num(fs[1], 0.4), num(fs[2], 360)*math.Pi/180
ca, cb = c*math.Cos(h), c*math.Sin(h)
}
r, g, b = oklabToSRGB(l, ca, cb)
return rgbaFloat(r, g, b, a), true
}
if name[0] == 'r' {
r, g, b = num(fs[0], 255)/255, num(fs[1], 255)/255, num(fs[2], 255)/255
} else {
h := math.Mod(num(fs[0], 360), 360) / 360
if h < 0 {
h++
}
sat, l := num(fs[1], 1), num(fs[2], 1)
if !strings.HasSuffix(fs[1], "%") {
sat /= 100
}
if !strings.HasSuffix(fs[2], "%") {
l /= 100
}
hue := func(p, q, t float64) float64 {
if t < 0 {
t++
} else if t > 1 {
t--
}
switch {
case t < 1.0/6:
return p + (q-p)*6*t
case t < 0.5:
return q
case t < 2.0/3:
return p + (q-p)*(2.0/3-t)*6
}
return p
}
q := l + sat - l*sat
if l < 0.5 {
q = l * (1 + sat)
}
p := 2*l - q
r, g, b = hue(p, q, h+1.0/3), hue(p, q, h), hue(p, q, h-1.0/3)
}
return rgbaFloat(r, g, b, a), true
}
// rgbaFloat returns the color of the given sRGB components and alpha,
// from 0 to 1 (clipped to that range).
func rgbaFloat(r, g, b, a float64) color.RGBA {
c8 := func(f float64) uint8 { return uint8(math.Round(math.Max(0, math.Min(1, f)) * 255)) }
return colors.FromNRGBA(c8(r), c8(g), c8(b), c8(a))
}
// srgbLinear returns the linear value of the given sRGB component.
func srgbLinear(c float64) float64 {
if math.Abs(c) <= 0.04045 {
return c / 12.92
}
return math.Copysign(math.Pow((math.Abs(c)+0.055)/1.055, 2.4), c)
}
// srgbGamma returns the sRGB component of the given linear value.
func srgbGamma(c float64) float64 {
if math.Abs(c) <= 0.0031308 {
return c * 12.92
}
return math.Copysign(1.055*math.Pow(math.Abs(c), 1/2.4)-0.055, c)
}
// p3ToSRGB returns the sRGB components of the given display-p3 ones
// (which have the same transfer function as sRGB).
func p3ToSRGB(r, g, b float64) (float64, float64, float64) {
r, g, b = srgbLinear(r), srgbLinear(g), srgbLinear(b)
lr := 1.2249401*r - 0.2249404*g + 0.0000000*b
lg := -0.0420569*r + 1.0420571*g + 0.0000000*b
lb := -0.0196376*r - 0.0786361*g + 1.0982735*b
return srgbGamma(lr), srgbGamma(lg), srgbGamma(lb)
}
// oklabToSRGB returns the sRGB components of the given OKLab color.
func oklabToSRGB(l, a, b float64) (float64, float64, float64) {
l_ := l + 0.3963377774*a + 0.2158037573*b
m_ := l - 0.1055613458*a - 0.0638541728*b
s_ := l - 0.0894841775*a - 1.2914855480*b
L, M, S := l_*l_*l_, m_*m_*m_, s_*s_*s_
r := 4.0767416621*L - 3.3077115913*M + 0.2309699292*S
g := -1.2684380046*L + 2.6097574011*M - 0.3413193965*S
bl := -0.0041960863*L - 0.7034186147*M + 1.7076147010*S
return srgbGamma(r), srgbGamma(g), srgbGamma(bl)
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package css
import (
"regexp"
"strings"
)
// Origin is the origin of a CSS declaration, which orders the cascade.
type Origin int
// PropertyName returns the name of the property of a declaration with the
// given name: in lower case, and the standard one of a legacy alias of it
// (see [legacyAliases]).
func PropertyName(p string) string {
p = strings.ToLower(strings.TrimSpace(p))
if a, ok := legacyAliases[p]; ok {
return a
}
return p
}
// legacyAliases are the old names of properties that browsers still
// support as aliases of the standard ones, by their standard names (as the
// grid-column-gap of the grids of nytimes.com, without which their columns
// had no gaps between them).
var legacyAliases = map[string]string{
"grid-gap": "gap", "grid-row-gap": "row-gap", "grid-column-gap": "column-gap",
}
// otherVendorValue matches a keyword of the vendor prefix of another
// browser engine (as -moz-available), which is invalid in browsers of
// WebKit and Blink, as Cogent Core is.
var otherVendorValue = regexp.MustCompile(`(^|[\s,(])-(moz|ms|o)-[a-z]`)
// ValidDeclaration returns whether a declaration of the given property
// and value is valid, as in browsers, which drop the declarations that
// are not when they are parsed, so that the declarations before them of
// the same property apply (as height: 100vh before height:
// -webkit-fill-available, of the captcha frames of DataDome for Safari,
// which were of the height of no content). A size of
// -webkit-fill-available is invalid here too, as it is not laid out, and
// the declaration before it is meant as a fallback for it. Custom
// properties and values with variables are only known when they are used.
func ValidDeclaration(prop, value string) bool {
if strings.HasPrefix(prop, "--") || strings.Contains(value, "var(") {
return true
}
if otherVendorValue.MatchString(strings.ToLower(value)) {
return false
}
switch prop {
case "width", "height", "min-width", "min-height", "max-width", "max-height", "inline-size", "block-size":
if strings.Contains(strings.ToLower(value), "-webkit-fill-available") {
return false
}
}
return true
}
// LegacyDisplay returns the display for the given value of the display
// property, which is that of the prefixed legacy values: -webkit-box (as
// with -webkit-line-clamp, in a column) is a block, and -webkit-flex flex;
// unset and initial are inline.
func LegacyDisplay(v string) string {
switch strings.ToLower(strings.TrimSpace(v)) {
case "-webkit-box", "-moz-box":
return "block"
case "-webkit-inline-box", "-moz-inline-box":
return "inline-block"
case "-webkit-flex":
return "flex"
case "-webkit-inline-flex":
return "inline-flex"
case "unset", "initial":
// display is not inherited, so these are its initial value (as
// display: unset of the widgets of the masthead of nytimes.com, in
// a flex row, which had no box of its own, so that its ticker was
// as wide as the row, over the logo)
return "inline"
}
return v
}
// FontShorthandValid returns whether the given value of the font shorthand
// is valid: a size (as 14px or medium, after any style, variant and
// weight) and a family after it, or a CSS-wide keyword or system font.
func FontShorthandValid(v string) bool {
fs := strings.Fields(strings.ToLower(v))
if len(fs) == 1 {
switch fs[0] {
case "inherit", "initial", "unset", "revert", "revert-layer", "caption", "icon", "menu",
"message-box", "small-caption", "status-bar":
return true
}
}
for i, f := range fs {
if len(f) > 0 && (f[0] >= '0' && f[0] <= '9' || f[0] == '.') || FontSizes[f] > 0 ||
strings.HasPrefix(f, "calc(") || strings.HasPrefix(f, "clamp(") || strings.HasPrefix(f, "min(") || strings.HasPrefix(f, "max(") {
return i+1 < len(fs) // (the family after the size)
}
}
return false
}
const (
// OriginUserAgent is for the user agent (default) styles.
OriginUserAgent Origin = iota
// OriginHint is for the presentational attributes of
// elements (width, bgcolor etc), which come before author styles.
OriginHint
// OriginAuthor is for the styles of the page.
OriginAuthor
// OriginInline is for the style attribute of an element.
OriginInline
)
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package css
import (
"image"
"image/color"
"math"
"strconv"
"strings"
)
// Filter is the filter property of CSS for images: a list of the
// functions that transform the colors of their pixels, in order (as the
// white submenu wedges of pkg.go.dev, grey icons with a filter of
// brightness(0) saturate(1) invert(1)).
type Filter []filterFunc
// filterFunc is a function of a filter, with its amount.
type filterFunc struct {
name string
amount float64 // a factor (1 is 100%), or degrees for hue-rotate
}
// ParseFilter returns the color functions of the given filter value, or
// nil if it has none (or none that is supported).
func ParseFilter(v string) Filter {
var f Filter
for rest := strings.TrimSpace(strings.ToLower(v)); rest != ""; {
name, args, ok := strings.Cut(rest, "(")
if !ok {
break
}
before, after, ok := strings.Cut(args, ")")
if !ok {
break
}
arg := strings.TrimSpace(before)
rest = strings.TrimSpace(after)
name = strings.TrimSpace(name)
amount := 1.0
if name == "hue-rotate" {
amount = 0
}
if arg != "" {
a, ok := filterAmount(arg, name == "hue-rotate")
if !ok {
continue
}
amount = a
}
switch name {
case "brightness", "contrast", "grayscale", "invert", "opacity", "saturate", "sepia", "hue-rotate":
f = append(f, filterFunc{name, amount})
}
}
return f
}
// filterAmount returns the amount of the given argument of a filter
// function: a number or a percentage, or an angle for hue-rotate.
func filterAmount(arg string, angle bool) (float64, bool) {
if angle {
for _, u := range []struct {
suffix string
deg float64
}{{"deg", 1}, {"grad", 0.9}, {"rad", 180 / math.Pi}, {"turn", 360}} {
if n, ok := strings.CutSuffix(arg, u.suffix); ok {
f, err := strconv.ParseFloat(strings.TrimSpace(n), 64)
return f * u.deg, err == nil
}
}
f, err := strconv.ParseFloat(arg, 64)
return f, err == nil && f == 0
}
if n, ok := strings.CutSuffix(arg, "%"); ok {
f, err := strconv.ParseFloat(strings.TrimSpace(n), 64)
return f / 100, err == nil
}
f, err := strconv.ParseFloat(arg, 64)
return f, err == nil
}
// Apply returns the given image with the colors of its pixels transformed
// by the filter.
func (f Filter) Apply(img image.Image) *image.RGBA {
b := img.Bounds()
dst := image.NewRGBA(image.Rectangle{Max: b.Size()})
for y := b.Min.Y; y < b.Max.Y; y++ {
for x := b.Min.X; x < b.Max.X; x++ {
c := color.NRGBAModel.Convert(img.At(x, y)).(color.NRGBA)
dst.Set(x-b.Min.X, y-b.Min.Y, f.Color(c))
}
}
return dst
}
// Color returns the given color transformed by the filter, as in CSS (the
// matrices of the filter effects spec, on unpremultiplied colors).
func (f Filter) Color(c color.NRGBA) color.NRGBA {
r, g, b, a := float64(c.R)/255, float64(c.G)/255, float64(c.B)/255, float64(c.A)/255
matrix := func(m [9]float64) {
r, g, b = m[0]*r+m[1]*g+m[2]*b, m[3]*r+m[4]*g+m[5]*b, m[6]*r+m[7]*g+m[8]*b
}
for _, fn := range f {
v := fn.amount
switch fn.name {
case "brightness":
r, g, b = r*v, g*v, b*v
case "contrast":
r, g, b = (r-0.5)*v+0.5, (g-0.5)*v+0.5, (b-0.5)*v+0.5
case "invert":
v = min(v, 1)
r, g, b = r*(1-v)+(1-r)*v, g*(1-v)+(1-g)*v, b*(1-v)+(1-b)*v
case "opacity":
a *= min(v, 1)
case "grayscale":
v = 1 - min(v, 1)
matrix([9]float64{0.2126 + 0.7874*v, 0.7152 - 0.7152*v, 0.0722 - 0.0722*v,
0.2126 - 0.2126*v, 0.7152 + 0.2848*v, 0.0722 - 0.0722*v,
0.2126 - 0.2126*v, 0.7152 - 0.7152*v, 0.0722 + 0.9278*v})
case "sepia":
v = 1 - min(v, 1)
matrix([9]float64{0.393 + 0.607*v, 0.769 - 0.769*v, 0.189 - 0.189*v,
0.349 - 0.349*v, 0.686 + 0.314*v, 0.168 - 0.168*v,
0.272 - 0.272*v, 0.534 - 0.534*v, 0.131 + 0.869*v})
case "saturate":
matrix([9]float64{0.213 + 0.787*v, 0.715 - 0.715*v, 0.072 - 0.072*v,
0.213 - 0.213*v, 0.715 + 0.285*v, 0.072 - 0.072*v,
0.213 - 0.213*v, 0.715 - 0.715*v, 0.072 + 0.928*v})
case "hue-rotate":
rad := v * math.Pi / 180
cs, sn := math.Cos(rad), math.Sin(rad)
matrix([9]float64{0.213 + cs*0.787 - sn*0.213, 0.715 - cs*0.715 - sn*0.715, 0.072 - cs*0.072 + sn*0.928,
0.213 - cs*0.213 + sn*0.143, 0.715 + cs*0.285 + sn*0.140, 0.072 - cs*0.072 - sn*0.283,
0.213 - cs*0.213 - sn*0.787, 0.715 - cs*0.715 + sn*0.715, 0.072 + cs*0.928 + sn*0.072})
}
r, g, b = clamp01(r), clamp01(g), clamp01(b)
}
return color.NRGBA{uint8(r*255 + 0.5), uint8(g*255 + 0.5), uint8(b*255 + 0.5), uint8(clamp01(a)*255 + 0.5)}
}
func clamp01(v float64) float64 { return min(max(v, 0), 1) }
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package css
import (
"strconv"
"strings"
"cogentcore.org/core/styles"
"cogentcore.org/core/text/fonts"
"cogentcore.org/core/text/rich"
)
// FontSizes are the absolute font size keywords, in px.
var FontSizes = map[string]float32{
"xx-small": 9, "x-small": 10, "small": 13, "medium": 16, "large": 18,
"x-large": 24, "xx-large": 32, "xxx-large": 48,
}
// LineHeightNormal is the line height of the "normal" value, which
// is given by the metrics of the font in browsers; this is the value
// for the default Noto Sans font.
const LineHeightNormal = 1.362
// SetFontWeight sets the font weight.
func SetFontWeight(s, ps *styles.Style, v string) {
w := 400
switch v {
case "normal":
case "bold":
w = 700
case "bolder":
w = 700
if ps != nil && ps.Font.Weight >= rich.Bold {
w = 900
}
case "lighter":
w = 300
default:
n, err := strconv.Atoi(v)
if err != nil {
return
}
w = n
}
s.Font.Weight = rich.Weights(min(max((w+50)/100-1, 0), 8))
}
// FontFamily returns the font family for the given CSS font-family list,
// the first generic family in it, or one for a common font name.
func FontFamily(v string) rich.Family {
for f := range strings.SplitSeq(v, ",") {
f = strings.ToLower(strings.Trim(strings.TrimSpace(f), `"'`))
switch f {
case "monospace", "courier", "courier new", "consolas", "menlo", "monaco", "roboto mono", "ui-monospace", "sfmono-regular":
return rich.Monospace
case "serif", "times", "times new roman", "georgia", "garamond", "ui-serif":
return rich.Serif
case "sans-serif", "arial", "helvetica", "helvetica neue", "verdana", "tahoma", "system-ui", "-apple-system", "segoe ui", "roboto", "noto sans", "ui-sans-serif":
return rich.SansSerif
case "cursive":
return rich.Cursive
case "fantasy":
return rich.Fantasy
}
}
return rich.SansSerif
}
// FontSizeKeywords are the font sizes of the absolute size keywords, in px.
var FontSizeKeywords = map[string]float32{"xx-small": 9, "x-small": 10, "small": 13, "medium": 16,
"large": 18, "x-large": 24, "xx-large": 32, "xxx-large": 48}
// IsFontData returns whether the given data is a font that the text
// shapers read: TrueType, OpenType (and collections of them), or WOFF.
func IsFontData(data []byte) bool {
if len(data) < 4 {
return false
}
switch string(data[:4]) {
case "\x00\x01\x00\x00", "OTTO", "true", "ttcf", "wOFF":
return true
}
return false
}
// FontSource returns the URL and format of the given source of the src of
// an @font-face rule: url(...) format(...), or "" for local(...).
func FontSource(s string) (url, format string) {
s = strings.TrimSpace(s)
if !strings.HasPrefix(strings.ToLower(s), "url(") {
return "", ""
}
end := strings.Index(s, ")")
if end < 0 {
return "", ""
}
url = strings.Trim(strings.TrimSpace(s[4:end]), `"'`)
rest := strings.ToLower(s[end+1:])
if _, after, ok := strings.Cut(rest, "format("); ok {
f := after
if before, _, ok := strings.Cut(f, ")"); ok {
format = strings.Trim(strings.TrimSpace(before), `"'`)
}
}
return url, format
}
// UnicodeRangeHas returns whether the given unicode-range includes the
// given rune.
func UnicodeRangeHas(urange string, r rune) bool {
for part := range strings.SplitSeq(urange, ",") {
part = strings.ToUpper(strings.TrimSpace(part))
part = strings.TrimPrefix(part, "U+")
lo, hi := part, part
if a, b, ok := strings.Cut(part, "-"); ok {
lo, hi = a, b
} else if strings.Contains(part, "?") { // as U+4??
lo, hi = strings.ReplaceAll(part, "?", "0"), strings.ReplaceAll(part, "?", "F")
}
l, err1 := strconv.ParseUint(lo, 16, 32)
h, err2 := strconv.ParseUint(hi, 16, 32)
if err1 == nil && err2 == nil && uint64(r) >= l && uint64(r) <= h {
return true
}
}
return false
}
// WebFontFamily returns the first of the families of the given value of
// font-family that is a web font that has been loaded, or "".
func WebFontFamily(v string) string {
for f := range strings.SplitSeq(v, ",") {
f = strings.Trim(strings.TrimSpace(f), `"'`)
if f != "" && fonts.HasWebFont(f) {
return f
}
}
return ""
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package css
import (
"hash/maphash"
"strings"
"golang.org/x/net/html"
)
// KeyMask is a set of keys of elements (see [AncestorKeys]), as bits of a
// Bloom filter: a set that has a key has its bit, and a set may have the
// bit of a key that it does not have.
type KeyMask [2]uint64
// KeySeed is the seed of the hashes of the bits of keys.
var KeySeed = maphash.MakeSeed()
// KeyBit returns the mask of the given key ("#id", ".class", or a name).
func KeyBit(key string) KeyMask {
h := maphash.String(KeySeed, key)
var m KeyMask
m[(h>>6)&1] = 1 << (h & 63)
return m
}
// Or returns the union of the masks.
func (m KeyMask) Or(o KeyMask) KeyMask {
return KeyMask{m[0] | o[0], m[1] | o[1]}
}
// Has returns whether the mask may have all of the keys of the given one.
func (m KeyMask) Has(o KeyMask) bool {
return m[0]&o[0] == o[0] && m[1]&o[1] == o[1]
}
// OwnKeys returns the mask of the keys of the given element: its name,
// id, and classes.
func OwnKeys(n *html.Node) KeyMask {
m := KeyBit(strings.ToLower(n.Data))
for _, a := range n.Attr {
if a.Namespace != "" {
continue
}
switch a.Key {
case "id":
if a.Val != "" {
m = m.Or(KeyBit("#" + a.Val))
}
case "class":
for cl := range strings.FieldsSeq(a.Val) {
m = m.Or(KeyBit("." + cl))
}
}
}
return m
}
// AncestorKeys returns the mask of the keys that the elements that an
// element that the given selector selects is in must have: those of its
// compound selectors that are followed by a combinator of descendants or
// children (whose elements are ones that it is in, also before a
// combinator of siblings, as the siblings of an element are in the same
// elements), outside of parentheses (as of :not), or none for a selector
// with escapes or namespaces.
func AncestorKeys(sel string) KeyMask {
var m KeyMask
if strings.ContainsAny(sel, "\\|") {
return m
}
// the compound selectors and the combinators after them, at the top
// level of the selector
depth, start := 0, -1
var compounds []string
var combs []byte
comb := byte(0)
flush := func(end int) {
if start >= 0 {
if len(compounds) > len(combs) { // (two compounds without a combinator)
combs = append(combs, ' ')
}
compounds = append(compounds, sel[start:end])
start = -1
}
}
for i := 0; i < len(sel); i++ {
ch := sel[i]
if depth == 0 && (ch == ' ' || ch == '\t' || ch == '\n' || ch == '>' || ch == '+' || ch == '~') {
flush(i)
if ch != ' ' && ch != '\t' && ch != '\n' {
comb = ch
} else if comb == 0 {
comb = ' '
}
continue
}
switch ch {
case '(', '[':
depth++
case ')', ']':
depth--
}
if start < 0 {
if len(compounds) > 0 {
combs = append(combs, comb)
}
comb = 0
start = i
}
}
flush(len(sel))
for i := 0; i < len(compounds)-1 && i < len(combs); i++ {
if combs[i] != ' ' && combs[i] != '>' {
continue // a sibling of the element of the next one
}
m = m.Or(CompoundKeys(compounds[i]))
}
return m
}
// CompoundKeys returns the mask of the keys that an element that the given
// compound selector selects has: its name, and its ids and classes outside
// of parentheses and brackets.
func CompoundKeys(cs string) KeyMask {
var m KeyMask
isName := func(ch byte) bool {
return ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9' || ch == '-' || ch == '_' || ch >= 0x80
}
name := func(i int) string {
j := i
for j < len(cs) && isName(cs[j]) {
j++
}
return cs[i:j]
}
if t := name(0); t != "" {
m = m.Or(KeyBit(strings.ToLower(t)))
}
depth := 0
for i := 0; i < len(cs); i++ {
switch ch := cs[i]; ch {
case '[':
if depth == 0 {
m = m.Or(attrKeys(cs[i:]))
}
depth++
case '(':
depth++
case ')', ']':
depth--
case '.', '#':
if depth == 0 {
if k := name(i + 1); k != "" {
m = m.Or(KeyBit(string(ch) + k))
}
}
}
}
return m
}
// attrKeys returns the mask of the key that an element that the given
// attribute selector (at the start of the text) selects has, as for
// [class~=name] (as .name) and [id=name] (as #name), or none.
func attrKeys(text string) KeyMask {
end := strings.IndexByte(text, ']')
if end < 0 {
return KeyMask{}
}
in := strings.TrimSpace(text[1:end])
var prefix, value string
if v, ok := strings.CutPrefix(in, "class~="); ok {
prefix, value = ".", v
} else if v, ok := strings.CutPrefix(in, "id="); ok {
prefix, value = "#", v
} else {
return KeyMask{}
}
value = strings.TrimSpace(value)
if len(value) >= 2 && (value[0] == '"' || value[0] == '\'') && value[len(value)-1] == value[0] {
value = value[1 : len(value)-1]
}
if value == "" || strings.ContainsAny(value, " \t\"'\\") {
return KeyMask{} // (as with a flag, as i)
}
return KeyBit(prefix + value)
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package css
import (
"fmt"
"math"
"slices"
"strconv"
"strings"
"sync"
"sync/atomic"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/shaped"
"cogentcore.org/core/text/text"
)
// LengthEnv has the sizes that relative lengths are resolved with, in px:
// the em (font size of the element), the rem (font size of the html
// element), and 1% of the viewport width and height. fixedVh is whether
// Vh is from htmlcore.Context.MediaHeight, to which all vh lengths are then
// relative (as dp); otherwise vh stays a unit of core, except in calc().
// Each style pass of a widget has its own (see htmlcore.Context.browserStyler),
// and reading a page uses that of the page (see htmlcore.Context.readEnv).
type LengthEnv struct {
Em, Vw, Vh float64
FixedVh bool
Rem float64
// VhUsed, if set, is set when a length uses vh (or vmin and vmax) of
// the viewport (see htmlcore.Context.ViewportHeightUsed).
VhUsed *atomic.Bool
// Cqw and Cqh are the container query units (1% of the width and the
// height of the container of the element; see container.go), which
// are those of the viewport (vw, vh) if they are not set.
Cqw, Cqh float64
// Ch, if set, returns the size of the ch unit of the element in px:
// the advance of the 0 glyph of its font, as in CSS.
Ch func() float64
}
// DefaultLengthEnv returns the length environment of a 16px font
// and an 800x600 viewport, for lengths that are absolute.
func DefaultLengthEnv() *LengthEnv {
return &LengthEnv{Em: 16, Vw: 8, Vh: 6, Rem: 16}
}
// Length parses the given CSS length, with px as dp (which is
// what px is in browsers), % as the given unit, and lengths without
// units, as in the attributes of HTML elements, as dp.
func (e *LengthEnv) Length(v string, pct units.Units) (units.Value, bool) {
v = strings.TrimSpace(v)
switch v {
case "", "auto", "none", "normal", "inherit", "initial":
return units.Value{}, false
}
if strings.HasSuffix(v, ")") {
return e.math(v, pct)
}
if r, ok := strings.CutSuffix(v, "ch"); ok && e.Ch != nil {
if f, err := strconv.ParseFloat(r, 32); err == nil {
if ch := e.Ch(); ch > 0 {
return units.Dp(float32(f * ch)), true
}
}
}
if l, ok := e.containerLength(v); ok {
return l, true
}
if r, ok := strings.CutSuffix(v, "rem"); ok { // of the font size of the html element
if f, err := strconv.ParseFloat(r, 32); err == nil {
return units.Dp(float32(f) * float32(e.Rem)), true
}
}
if before, ok := strings.CutSuffix(v, "%"); ok {
f, err := strconv.ParseFloat(before, 32)
if err != nil {
return units.Value{}, false
}
return units.Value{Value: float32(f), Unit: pct}, true
}
if f, err := strconv.ParseFloat(v, 32); err == nil {
return units.Dp(float32(f)), true
}
// absolute units are relative to px in CSS (96px per inch)
for _, u := range cssAbsoluteUnits {
if num, ok := strings.CutSuffix(v, u.suffix); ok {
f, err := strconv.ParseFloat(num, 32)
if err != nil {
return units.Value{}, false
}
return units.Dp(float32(f) * u.px), true
}
}
var l units.Value
if err := l.SetString(v); err != nil {
return units.Value{}, false
}
switch l.Unit {
case units.UnitVh, units.UnitVmin, units.UnitVmax:
e.useVh()
}
if l.Unit == units.UnitVh && e.FixedVh {
return units.Dp(l.Value * float32(e.Vh)), true
}
return l, true
}
// useVh records that a length uses the height of the viewport.
func (e *LengthEnv) useVh() {
if e.VhUsed != nil {
e.VhUsed.Store(true)
}
}
// containerUnits returns the size in px of 1% of the width and height of
// the container of the element (cqw, cqh), or of the viewport if none.
func (e *LengthEnv) containerUnits() (cqw, cqh float64) {
cqw, cqh = e.Cqw, e.Cqh
if cqw <= 0 {
cqw = e.Vw
}
if cqh <= 0 {
cqh = e.Vh
}
return
}
// cqUnits are the container query units of CSS, by how they are of the
// width (cqw, cqi) and height (cqh, cqb) of the container, or the smaller
// (cqmin) or larger (cqmax) of them.
var cqUnits = []string{"cqmin", "cqmax", "cqw", "cqh", "cqi", "cqb"}
// cqUnit returns the size in px of the given container query unit.
func (e *LengthEnv) cqUnit(u string) float64 {
cqw, cqh := e.containerUnits()
switch u {
case "cqw", "cqi":
return cqw
case "cqh", "cqb":
return cqh
case "cqmin":
return math.Min(cqw, cqh)
}
return math.Max(cqw, cqh)
}
// containerLength returns the given length if it is in a container
// query unit (as 50cqw), in dp.
func (e *LengthEnv) containerLength(v string) (units.Value, bool) {
for _, u := range cqUnits {
if num, ok := strings.CutSuffix(v, u); ok {
f, err := strconv.ParseFloat(num, 64)
if err != nil {
return units.Value{}, false
}
return units.Dp(float32(f * e.cqUnit(u))), true
}
}
return units.Value{}, false
}
// cssAbsoluteUnits are the absolute units of CSS, in px.
var cssAbsoluteUnits = []struct {
suffix string
px float32
}{{"px", 1}, {"pt", 96.0 / 72}, {"pc", 16}, {"in", 96}, {"cm", 96 / 2.54}, {"mm", 96 / 25.4}, {"q", 96 / 101.6}}
// LengthPtr returns the given length, or nil if it is not one (as auto).
func (e *LengthEnv) LengthPtr(v string, pct units.Units) *units.Value {
l, ok := e.Length(v, pct)
if !ok {
return nil
}
return &l
}
// BorderWidth returns the given CSS border width.
func (e *LengthEnv) BorderWidth(v string) units.Value {
switch v {
case "thin":
return units.Dp(1)
case "medium":
return units.Dp(3)
case "thick":
return units.Dp(5)
}
l, _ := e.Length(v, units.UnitDp)
return l
}
// Linear is a length that is a percentage plus an absolute length in px,
// the value of a calc() expression of CSS.
type Linear struct {
Pct, Px float64
}
// linear evaluates the given calc() expression (or length) as a
// linear combination of a percentage and px. It returns false if it
// is not valid (as with a product of two lengths).
func (e *LengthEnv) linear(v string) (Linear, bool) {
v = strings.TrimSpace(strings.ToLower(v))
if inner, ok := strings.CutPrefix(v, "calc("); ok {
v = "(" + inner
}
p := &linearParser{s: v, em: e.Em, vw: e.Vw, vh: e.Vh, rem: e.Rem, env: e}
l, ok := p.sum()
p.space()
return l, ok && p.i == len(p.s)
}
// linearParser parses calc expressions into linear lengths.
type linearParser struct {
s string
i int
em, vw, vh float64
rem float64 // px per rem
env *LengthEnv // for the container query units
// lengths is the number of lengths parsed.
lengths int
}
func (p *linearParser) space() {
for p.i < len(p.s) && p.s[p.i] == ' ' {
p.i++
}
}
func (p *linearParser) sum() (Linear, bool) {
l, ok := p.product()
for ok {
p.space()
if p.i >= len(p.s) || (p.s[p.i] != '+' && p.s[p.i] != '-') {
break
}
sign := 1.0
if p.s[p.i] == '-' {
sign = -1
}
p.i++
r, rok := p.product()
if !rok {
return Linear{}, false
}
l.Pct += sign * r.Pct
l.Px += sign * r.Px
}
return l, ok
}
// product parses a product, in which at most one factor is a length.
func (p *linearParser) product() (Linear, bool) {
l, isLen, ok := p.factor()
for ok {
p.space()
if p.i >= len(p.s) || (p.s[p.i] != '*' && p.s[p.i] != '/') {
break
}
op := p.s[p.i]
p.i++
r, rLen, rok := p.factor()
if !rok || (isLen && rLen) || (op == '/' && rLen) {
return Linear{}, false
}
var n float64 // the number factor
if rLen {
n = l.Px // l is a number, as px
l = r
isLen = true
} else {
n = r.Px
}
if op == '/' {
if n == 0 {
return Linear{}, false
}
n = 1 / n
}
l.Pct *= n
l.Px *= n
}
return l, ok
}
// factor parses a number or length, or an expression in parentheses,
// returning whether it is a length (as opposed to a number, in px).
func (p *linearParser) factor() (Linear, bool, bool) {
p.space()
if p.i < len(p.s) && p.s[p.i] == '(' {
p.i++
before := p.lengths
l, ok := p.sum()
p.space()
if !ok || p.i >= len(p.s) || p.s[p.i] != ')' {
return Linear{}, false, false
}
p.i++
return l, p.lengths > before, true
}
if strings.HasPrefix(p.s[p.i:], "calc(") {
p.i += 4
return p.factor()
}
if p.env != nil {
for _, fn := range []string{"min(", "max(", "clamp("} {
if !strings.HasPrefix(p.s[p.i:], fn) {
continue
}
// a math function in a calc() (as the gutters of github.com, in
// calc(100% - 2 * clamp(1.25rem, calc((100vw - 768px) / 4), 8rem))),
// of lengths that are not percentages
depth, end := 0, -1
for j := p.i + len(fn) - 1; j < len(p.s); j++ {
if p.s[j] == '(' {
depth++
} else if p.s[j] == ')' {
depth--
if depth == 0 {
end = j
break
}
}
}
if end < 0 {
return Linear{}, false, false
}
v, ok := p.env.math(p.s[p.i:end+1], units.UnitPw)
if !ok || v.Custom != nil || v.Unit != units.UnitDp {
return Linear{}, false, false
}
p.i = end + 1
p.lengths++
return Linear{Px: float64(v.Value)}, true, true
}
}
start := p.i
for p.i < len(p.s) && (p.s[p.i] >= '0' && p.s[p.i] <= '9' || p.s[p.i] == '.' || (p.i == start && (p.s[p.i] == '-' || p.s[p.i] == '+'))) {
p.i++
}
n, err := strconv.ParseFloat(p.s[start:p.i], 64)
if err != nil {
return Linear{}, false, false
}
rest := p.s[p.i:]
unit := func(u string, scale float64) (Linear, bool, bool) {
p.i += len(u)
p.lengths++
return Linear{Px: n * scale}, true, true
}
if p.env != nil {
for _, u := range cqUnits {
if strings.HasPrefix(rest, u) {
return unit(u, p.env.cqUnit(u))
}
}
}
switch {
case strings.HasPrefix(rest, "%"):
p.i++
p.lengths++
return Linear{Pct: n}, true, true
case strings.HasPrefix(rest, "px"):
return unit("px", 1)
case strings.HasPrefix(rest, "rem"):
return unit("rem", p.rem)
case strings.HasPrefix(rest, "em"):
return unit("em", p.em)
case strings.HasPrefix(rest, "vw"):
return unit("vw", p.vw)
case strings.HasPrefix(rest, "vh"):
p.env.useVh()
return unit("vh", p.vh)
case strings.HasPrefix(rest, "vmin"):
p.env.useVh()
return unit("vmin", math.Min(p.vw, p.vh))
case strings.HasPrefix(rest, "vmax"):
p.env.useVh()
return unit("vmax", math.Max(p.vw, p.vh))
case strings.HasPrefix(rest, "pt"):
return unit("pt", 96.0/72)
}
return Linear{Px: n}, false, true // a number
}
// math returns the length of the given CSS math function (calc(),
// min(), max(), clamp()), as a percentage of the given unit, or in dp.
// A length with both a percentage and an absolute part is approximated
// by its percentage, as units have one unit.
func (e *LengthEnv) math(v string, pct units.Units) (units.Value, bool) {
name, args, ok := strings.Cut(v, "(")
if !ok || !strings.HasSuffix(args, ")") {
return units.Value{}, false
}
args = strings.TrimSuffix(args, ")")
eval := func(x string) (Linear, bool) {
x = strings.TrimSpace(x)
if l, ok := e.math(x, pct); ok && strings.Contains(x, "(") && !strings.HasPrefix(x, "(") {
if l.Unit == pct {
return Linear{Pct: float64(l.Value)}, true
}
return Linear{Px: float64(l.Value)}, true
}
return e.linear(x)
}
var l Linear
switch name {
case "calc":
l, ok = eval(args)
case "min", "max", "clamp":
parts := SplitSelectors(args) // at the top-level commas
var vals []Linear
for _, p := range parts {
pl, pok := eval(p)
if !pok {
return units.Value{}, false
}
vals = append(vals, pl)
}
if len(vals) == 0 || (name == "clamp" && len(vals) != 3) {
return units.Value{}, false
}
// Percentages cannot be compared with absolute lengths here, so the
// absolute ones (with no percentage) decide, if there are any.
pick := func(a, b Linear, less bool) Linear {
if a.Pct != 0 || b.Pct != 0 {
if a.Pct == 0 {
return a
}
return b
}
if (a.Px < b.Px) == less {
return a
}
return b
}
if mixed := slices.ContainsFunc(vals, func(l Linear) bool { return l.Pct != 0 }) &&
slices.ContainsFunc(vals, func(l Linear) bool { return l.Px != 0 || l.Pct == 0 }); mixed {
// compared when the size of the parent is known, in the layout
return CustomLength(name, vals, pct), true
}
switch name {
case "min":
l = vals[0]
for _, v := range vals[1:] {
l = pick(l, v, true)
}
case "max":
l = vals[0]
for _, v := range vals[1:] {
l = pick(l, v, false)
}
case "clamp":
l = pick(pick(vals[1], vals[2], true), vals[0], false)
}
ok = true
default:
return units.Value{}, false
}
if !ok {
return units.Value{}, false
}
if l.Pct != 0 && l.Px != 0 { // as the width of calc(100% - 256px)
return CustomLength("calc", []Linear{l}, pct), true
}
if l.Pct != 0 {
return units.Value{Value: float32(l.Pct), Unit: pct}, true
}
return units.Dp(float32(l.Px)), true
}
// CustomLength returns a custom length (see [units.Value.Custom]) of the
// given CSS math function (calc, min, max, or clamp) of the given linear
// lengths, with percentages of the given unit, which core computes with the
// size of the parent in the layout: a percentage and a length cannot be
// one unit (as the width of calc(100% - 256px) of the grids of github.com,
// which was taken to be 100%).
func CustomLength(fn string, vals []Linear, pct units.Units) units.Value {
vals = slices.Clone(vals)
return units.Custom(func(uc *units.Context) float32 {
base := uc.Paw
switch pct {
case units.UnitPh:
base = uc.Pah
case units.UnitEw:
base = uc.Elw
case units.UnitEh:
base = uc.Elh
}
dp := uc.Dots(units.UnitDp)
dots := func(l Linear) float32 { return float32(l.Pct/100)*base + float32(l.Px)*dp }
v := dots(vals[0])
switch fn {
case "min":
for _, l := range vals[1:] {
v = min(v, dots(l))
}
case "max":
for _, l := range vals[1:] {
v = max(v, dots(l))
}
case "clamp":
if len(vals) == 3 {
v = max(dots(vals[0]), min(dots(vals[1]), dots(vals[2])))
}
}
return v
})
}
// LengthPx returns the given CSS length in px, for lengths that are
// absolute or relative to the font size (taken to be 16px for em).
func (e *LengthEnv) LengthPx(v string) (float32, bool) {
v = strings.TrimSpace(v)
if f, ok := strings.CutSuffix(v, "rem"); ok {
if x, err := strconv.ParseFloat(f, 32); err == nil {
return float32(x) * float32(e.Rem), true
}
}
if f, ok := strings.CutSuffix(v, "em"); ok {
if x, err := strconv.ParseFloat(f, 32); err == nil {
return float32(x) * 16, true
}
}
l, ok := e.Length(v, units.UnitPw)
if !ok || l.Unit != units.UnitDp {
return 0, false
}
return l.Value, true
}
// chShaper is the text shaper that measures the ch unit when the scene
// of an element has none yet.
var (
chShaper shaped.Shaper
chShaperOnce sync.Once
)
// chRatios are the advances of the 0 glyph of fonts relative to their
// size, by their family and weight, for the ch unit.
var chRatios struct {
sync.Mutex
ratios map[string]float64
}
// ChOf returns the size of the ch unit of CSS in px for the font of the
// given style (whose font size is the given em, in px), measured with the
// given text shaper: the advance of its 0 glyph, as in browsers. It is 0
// if it cannot be measured.
func ChOf(sh shaped.Shaper, s *styles.Style, em float64) float64 {
if em <= 0 {
return 0
}
key := fmt.Sprintf("%v %s %v", s.Font.Family, s.Font.CustomFont, s.Font.Weight)
chRatios.Lock()
r, ok := chRatios.ratios[key]
chRatios.Unlock()
if !ok {
if sh == nil { // before the scene has one
chShaperOnce.Do(func() { chShaper = shaped.NewShaper() })
sh = chShaper
}
sty := rich.NewStyle()
sty.Family, sty.Weight = s.Font.Family, s.Font.Weight
tsty := text.NewStyle()
tsty.CustomFont = s.Font.CustomFont
tsty.FontSize.Dots = 100
var adv float32
for _, run := range sh.Shape(rich.NewText(sty, []rune("0")), tsty) {
adv += run.Advance()
}
r = float64(adv) / 100
chRatios.Lock()
if chRatios.ratios == nil {
chRatios.ratios = map[string]float64{}
}
chRatios.ratios[key] = r
chRatios.Unlock()
}
return r * em
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package css
import (
"strconv"
"strings"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles/units"
)
// MaskSize returns the size of the mask image in the given box, for the
// given mask-size (as "20px auto", "contain", "cover", or "50%"), and the
// intrinsic size of the image, in pixels, with the given dots per px.
func MaskSize(v string, box, intrinsic math32.Vector2, dp float32) math32.Vector2 {
aspect := intrinsic.Y / intrinsic.X
switch strings.TrimSpace(v) {
case "contain", "cover":
sx, sy := box.X/intrinsic.X, box.Y/intrinsic.Y
s := min(sx, sy)
if v == "cover" {
s = max(sx, sy)
}
return intrinsic.MulScalar(s)
case "", "auto", "auto auto":
return intrinsic
}
fs := strings.Fields(v)
length := func(f string, ref float32) (float32, bool) {
if pct, ok := strings.CutSuffix(f, "%"); ok {
n, err := strconv.ParseFloat(pct, 32)
return float32(n) / 100 * ref, err == nil
}
if f == "auto" {
return 0, false
}
n, err := strconv.ParseFloat(strings.TrimSuffix(f, "px"), 32)
return float32(n) * dp, err == nil
}
w, wok := length(fs[0], box.X)
h, hok := float32(0), false
if len(fs) > 1 {
h, hok = length(fs[1], box.Y)
}
switch {
case wok && hok:
return math32.Vec2(w, h)
case wok:
return math32.Vec2(w, w*aspect)
case hok:
return math32.Vec2(h/aspect, h)
}
return intrinsic
}
// MaskPosition returns the fractions of the extra space of the box on each
// axis that are before the mask image, for the given mask-position (as
// "50% 50%", "center", or "left top").
func MaskPosition(v string) (x, y float32) {
fs := strings.Fields(strings.ToLower(v))
if len(fs) == 0 {
return 0, 0
}
if len(fs) == 1 {
fs = append(fs, "center")
}
frac := func(f string) float32 {
switch f {
case "left", "top":
return 0
case "center":
return 0.5
case "right", "bottom":
return 1
}
if pct, ok := strings.CutSuffix(f, "%"); ok {
n, _ := strconv.ParseFloat(pct, 32)
return float32(n) / 100
}
return 0
}
if fs[0] == "top" || fs[0] == "bottom" || fs[1] == "left" || fs[1] == "right" {
fs[0], fs[1] = fs[1], fs[0] // as "top left"
}
return frac(fs[0]), frac(fs[1])
}
// MaskOffset returns the offsets in px of the given mask-position (or
// background-position) that are lengths (as the positions of the images
// in a sprite, as "0 -261px"), which are from the left and top.
func MaskOffset(v string) (x, y float32) {
fs := strings.Fields(strings.ToLower(v))
if len(fs) == 0 {
return 0, 0
}
if len(fs) == 1 {
fs = append(fs, "center")
}
if fs[0] == "top" || fs[0] == "bottom" || fs[1] == "left" || fs[1] == "right" {
fs[0], fs[1] = fs[1], fs[0]
}
px := func(f string) float32 {
if n, ok := strings.CutSuffix(f, "px"); ok {
v, _ := strconv.ParseFloat(n, 32)
return float32(v)
}
return 0
}
return px(fs[0]), px(fs[1])
}
// MaskURL returns the URL of the url() of the given value of mask-image
// (or the mask shorthand), or "" if it has none (as none).
func MaskURL(v string) string {
i := strings.Index(strings.ToLower(v), "url(")
if i < 0 {
return ""
}
rest := v[i+4:]
before, _, ok := strings.Cut(rest, ")")
if t := strings.TrimSpace(rest); strings.HasPrefix(t, `"`) || strings.HasPrefix(t, `'`) {
// a CSS string, with backslash escapes (as the quotes of the
// attributes of an SVG in a data URL)
q := t[0]
var sb strings.Builder
for i := 1; i < len(t); i++ {
switch c := t[i]; {
case c == '\\' && i+1 < len(t):
i++
sb.WriteByte(t[i])
case c == q:
return sb.String()
default:
sb.WriteByte(c)
}
}
return ""
}
if !ok {
return ""
}
return strings.TrimSpace(before)
}
// ResolveMaskSize returns the given mask-size with its lengths (as em and
// calc()) resolved to px with the given length environment, as maskSize
// reads px, percentages, auto, contain, and cover.
func ResolveMaskSize(env *LengthEnv, v string) string {
parts := SplitTopLevelSpaces(v)
for i, p := range parts {
switch {
case p == "auto" || p == "contain" || p == "cover" || strings.HasSuffix(p, "%"):
continue
}
if l, ok := env.Length(p, units.UnitPw); ok && l.Unit == units.UnitDp { // (% are of the box)
parts[i] = strconv.FormatFloat(float64(l.Value), 'f', -1, 32) + "px"
}
}
return strings.Join(parts, " ")
}
// IsPositionWord returns whether the given word is one of a position (a
// keyword or a length), not a color.
func IsPositionWord(f string) bool {
switch f {
case "left", "right", "top", "bottom", "center":
return true
}
return f != "" && (f[0] >= '0' && f[0] <= '9' || f[0] == '-' || f[0] == '.')
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package css
import (
"regexp"
"strings"
)
// mediaRangeOp matches the comparison operators of the range syntax
// of media features, as in (width >= 50rem) or (30rem < width <= 60rem).
var mediaRangeOp = regexp.MustCompile(`<=|>=|<|>|=`)
// MediaRangeMatches returns whether the given media feature in the range
// syntax matches the given viewport width and height.
func MediaRangeMatches(f string, width, height float32) bool {
ops := mediaRangeOp.FindAllString(f, -1)
parts := mediaRangeOp.Split(f, -1)
if len(parts) != len(ops)+1 || len(ops) == 0 || len(ops) > 2 {
return false
}
// value returns the value of an operand: the feature or a length.
value := func(s string) (float32, bool, bool) { // value, ok, isFeature
switch strings.TrimSpace(s) {
case "width":
return width, true, true
case "height":
return height, true, true
case "aspect-ratio":
return width / height, true, true
}
v, ok := CalcPx(strings.TrimSpace(s))
return v, ok, false
}
feature := false
for i, op := range ops {
a, aok, af := value(parts[i])
b, bok, bf := value(parts[i+1])
if !aok || !bok {
return false // as browsers do for a query that is not valid
}
feature = feature || af || bf
var r bool
switch op {
case "<=":
r = a <= b
case ">=":
r = a >= b
case "<":
r = a < b
case ">":
r = a > b
case "=":
r = a == b
}
if !r {
return false
}
}
return feature
}
// SupportsMatches returns whether the given condition of an @supports rule
// is true in Chrome, which this follows: its features are supported,
// except the properties and values of other browsers (-moz-, -ms-, -o-) and
// of iOS, so that the fallbacks in @supports not (...) do not apply (as
// the widths of the sections of theguardian.com for browsers without
// display: grid, which made them narrow). The preludes of the other
// grouping rules that are parsed as @supports (as @layer name) are true.
func SupportsMatches(cond string) bool {
p := supportsParser{s: cond}
return p.condition()
}
// supportsParser parses and evaluates an @supports condition.
type supportsParser struct {
s string
i int
}
// skipSpace skips the white space at the current position.
func (p *supportsParser) skipSpace() {
for p.i < len(p.s) && strings.ContainsRune(" \t\n\r\f", rune(p.s[p.i])) {
p.i++
}
}
// keyword consumes the given keyword (as and) if it is next.
func (p *supportsParser) keyword(kw string) bool {
p.skipSpace()
rest := p.s[p.i:]
if len(rest) < len(kw) || !strings.EqualFold(rest[:len(kw)], kw) {
return false
}
if len(rest) > len(kw) && !strings.ContainsRune(" \t\n\r\f(", rune(rest[len(kw)])) {
return false
}
p.i += len(kw)
return true
}
// condition evaluates the terms joined by and or or from the current
// position.
func (p *supportsParser) condition() bool {
v := p.term()
for {
switch {
case p.keyword("and"):
v = p.term() && v
case p.keyword("or"):
v = p.term() || v
default:
return v
}
}
}
// term evaluates a not, a condition or declaration in parentheses, a
// function (as selector(...)), or a name, which are true.
func (p *supportsParser) term() bool {
if p.keyword("not") {
return !p.term()
}
p.skipSpace()
start := p.i
for p.i < len(p.s) && p.s[p.i] != '(' && !strings.ContainsRune(" \t\n\r\f)", rune(p.s[p.i])) {
p.i++ // the name of a function or of a layer
}
if p.i >= len(p.s) || p.s[p.i] != '(' {
return true
}
// the text in the parentheses
depth, open := 0, p.i
for ; p.i < len(p.s); p.i++ {
if p.s[p.i] == '(' {
depth++
} else if p.s[p.i] == ')' {
depth--
if depth == 0 {
break
}
}
}
inner := strings.TrimSpace(p.s[open+1 : min(p.i, len(p.s))])
p.i++
if open > start {
return true // a function, as selector(:has(a))
}
if prop, value, ok := CutTopLevel(inner, ':'); ok && !strings.ContainsAny(prop, "( ") {
return supportedDeclaration(strings.ToLower(prop), strings.ToLower(value))
}
sub := supportsParser{s: inner}
return sub.condition()
}
// supportedDeclaration returns whether the given property and value of an
// @supports condition are supported in Chrome (see [SupportsMatches]).
func supportedDeclaration(prop, value string) bool {
for _, other := range []string{"-moz-", "-ms-", "-o-"} {
if strings.HasPrefix(prop, other) || strings.Contains(value, other) {
return false
}
}
switch prop {
case "-webkit-touch-callout", "-webkit-overflow-scrolling":
return false
}
return true
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package css
import (
"regexp"
"strings"
)
// ScopeKind is the kind of the elements that a rule of a style sheet of a
// shadow tree selects (see htmlcore.Context.inScope).
type ScopeKind int8
const (
// ScopeAll is the elements of its tree (or, for a rule of the
// document, the elements of the document).
ScopeAll ScopeKind = iota
// ScopeHost is the host of the shadow root (:host).
ScopeHost
// ScopeSlotted is the children of the host in the slots of the shadow
// tree (::slotted()).
ScopeSlotted
// ScopeAny is all elements, of the document and of shadow trees, for
// the rules of the user agent.
ScopeAny
)
// hostFunc matches :host and :host() at the start of a selector, with its
// argument.
var hostFunc = regexp.MustCompile(`^:host(?:\(([^()]*(?:\([^()]*\))?[^()]*)\))?`)
// slottedFunc matches ::slotted() in a selector, with the compound before it
// and its argument.
var slottedFunc = regexp.MustCompile(`([^\s>+~]*)::slotted\(([^()]*(?:\([^()]*\))?[^()]*)\)`)
// ScopedSelector returns the given selector of a style sheet of a shadow
// tree as one of the elements of the composed tree, and the kind of the
// elements that it selects, or false if it can not be: :host (or :host(X))
// alone selects the host (as X); :host before other compounds is the host
// (as X, or any element, which the host is of the elements of its tree);
// ::slotted(X) selects the children X of the slots (as slot > X);
// :host-context() and ::part() are not supported.
func ScopedSelector(sel string) (string, ScopeKind, bool) {
if strings.Contains(sel, ":host-context") || strings.Contains(sel, "::part") {
return "", 0, false
}
kind := ScopeAll
if m := hostFunc.FindStringSubmatchIndex(sel); m != nil {
// the compound of the host: the argument of :host, and what is
// after it before a combinator (as :host(.open):hover)
host := ""
if m[2] >= 0 {
host = strings.TrimSpace(sel[m[2]:m[3]])
}
rest := sel[m[1]:]
end := strings.IndexAny(rest, " >+~")
if end < 0 {
end = len(rest)
}
host += rest[:end]
if host == "" {
host = "*"
}
rest = rest[end:]
if strings.TrimSpace(rest) == "" {
return host, ScopeHost, true
}
sel = host + rest
}
if strings.Contains(sel, "::slotted(") {
sel = slottedFunc.ReplaceAllStringFunc(sel, func(s string) string {
m := slottedFunc.FindStringSubmatch(s)
pre := m[1]
if pre == "" {
pre = "slot"
}
return pre + " > " + m[2]
})
kind = ScopeSlotted
}
if strings.Contains(sel, ":host") || strings.Contains(sel, "::") && !strings.Contains(sel, "::before") && !strings.Contains(sel, "::after") {
return "", 0, false
}
return sel, kind, true
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package css
import (
"slices"
"strings"
"sync"
"github.com/andybalholm/cascadia"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
// CompiledSelector is a compiled selector, with its specificity.
type CompiledSelector struct {
Sel cascadia.Sel
Specificity int
// KeyKind and Key are a part of the last compound selector that every
// node that it selects has, for finding them in a [SelectorIndex]:
// an id ('#'), a class ('.'), or an element name ('t'), or none (0).
KeyKind byte
Key string
// Anc is the mask of the keys of the elements that the elements that
// it selects are in (see [AncestorKeys]).
Anc KeyMask
}
// selectorCache has the compiled selectors, with nil for ones
// that are not supported (as pseudo-elements, which select no nodes).
// It is shared by the contexts that read pages, as in other goroutines.
var selectorCache = map[string]*CompiledSelector{}
// selectorCacheMu protects selectorCache.
var selectorCacheMu sync.Mutex
// CompileSelector returns the compiled selector, or nil if it is not supported.
func CompileSelector(sel string) *CompiledSelector {
selectorCacheMu.Lock()
defer selectorCacheMu.Unlock()
if cs, ok := selectorCache[sel]; ok {
return cs
}
var cs *CompiledSelector
if s, err := cascadia.Parse(RewriteSelector(sel)); err == nil && s.PseudoElement() == "" {
sp := s.Specificity()
cs = &CompiledSelector{Sel: s, Specificity: sp[0]*10000 + sp[1]*100 + sp[2]}
cs.KeyKind, cs.Key = SelectorKey(sel)
cs.Anc = AncestorKeys(sel)
}
selectorCache[sel] = cs
return cs
}
// RewriteSelector rewrites the parts of the given selector that the selector
// library does not support as ones that it does: :is(X) and :where(X) as
// :not(:not(X)), and :focus-within and :focus-visible as :focus (which
// selects nothing, as for :hover, in a static rendering).
func RewriteSelector(sel string) string {
// :hover selects the elements that are marked hovered (see
// htmlcore.Context.Hovered), or none
sel = strings.ReplaceAll(sel, ":hover", "["+HoverAttr+"]")
// :modal selects the dialogs that scripts show as modal (with
// showModal), which they mark with ModalAttr
sel = strings.ReplaceAll(sel, ":modal", "["+ModalAttr+"]")
if !strings.Contains(sel, ":is(") && !strings.Contains(sel, ":where(") && !strings.Contains(sel, ":focus-") {
return sel
}
sel = strings.ReplaceAll(sel, ":focus-within", ":focus")
sel = strings.ReplaceAll(sel, ":focus-visible", ":focus")
var sb strings.Builder
var closes []bool // for each open parenthesis, whether its close is doubled
for i := 0; i < len(sel); i++ {
switch {
case strings.HasPrefix(sel[i:], ":is("):
sb.WriteString(":not(:not(")
closes = append(closes, true)
i += len(":is(") - 1
case strings.HasPrefix(sel[i:], ":where("):
sb.WriteString(":not(:not(")
closes = append(closes, true)
i += len(":where(") - 1
case sel[i] == '(':
sb.WriteByte('(')
closes = append(closes, false)
case sel[i] == ')':
sb.WriteByte(')')
if n := len(closes); n > 0 {
if closes[n-1] {
sb.WriteByte(')')
}
closes = closes[:n-1]
}
default:
sb.WriteByte(sel[i])
}
}
return sb.String()
}
// SelectorKey returns a part of the last compound selector of the given
// selector that every node that it selects has (see compiledSelector.key):
// its id, else its first class, else its element name, or none if it has
// none of them outside of functions and attribute selectors (or has
// escapes, which are not decoded here).
func SelectorKey(sel string) (byte, string) {
if strings.ContainsAny(sel, "\\|") { // escapes and namespaces
return 0, ""
}
// the start of the last compound selector, after the last combinator
// at the top level
start, depth := 0, 0
for i := 0; i < len(sel); i++ {
switch ch := sel[i]; ch {
case '(', '[':
depth++
case ')', ']':
depth--
case ' ', '>', '+', '~', '\t', '\n':
if depth == 0 {
start = i + 1
}
}
}
last := sel[start:]
isName := func(ch byte) bool {
return ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9' || ch == '-' || ch == '_' || ch >= 0x80
}
name := func(i int) string {
j := i
for j < len(last) && isName(last[j]) {
j++
}
return last[i:j]
}
var class string
depth = 0
for i := 0; i < len(last); i++ {
switch ch := last[i]; {
case ch == '(' || ch == '[':
depth++
case ch == ')' || ch == ']':
depth--
case depth == 0 && ch == '#':
if id := name(i + 1); id != "" {
return '#', id
}
case depth == 0 && ch == '.' && class == "":
class = name(i + 1)
}
}
if class != "" {
return '.', class
}
if tag := name(0); tag != "" {
return 't', strings.ToLower(tag)
}
return 0, ""
}
// SelectorIndex has the element nodes of a document by id, class, and
// element name, in document order, for selecting the nodes of style rules
// (see htmlcore.Context.selectNodes), so that each selector is only matched
// against the nodes that have its key, as in browsers.
type SelectorIndex struct {
Root *html.Node
ByID, ByClass, ByTag map[string][]*html.Node
all []*html.Node
}
// NewSelectorIndex returns the index of the element nodes under root.
func NewSelectorIndex(root *html.Node) *SelectorIndex {
ix := &SelectorIndex{Root: root, ByID: map[string][]*html.Node{}, ByClass: map[string][]*html.Node{}, ByTag: map[string][]*html.Node{}}
var walk func(n *html.Node)
walk = func(n *html.Node) {
for c := n.FirstChild; c != nil; c = c.NextSibling {
if c.Type != html.ElementNode {
continue
}
ix.all = append(ix.all, c)
ix.ByTag[strings.ToLower(c.Data)] = append(ix.ByTag[strings.ToLower(c.Data)], c)
for _, a := range c.Attr {
if a.Namespace != "" {
continue
}
switch a.Key {
case "id":
ix.ByID[a.Val] = append(ix.ByID[a.Val], c)
case "class":
seen := map[string]bool{}
for cl := range strings.FieldsSeq(a.Val) {
if !seen[cl] {
seen[cl] = true
ix.ByClass[cl] = append(ix.ByClass[cl], c)
}
}
}
}
walk(c)
}
}
walk(root)
return ix
}
// SelectNodes returns the nodes under root that the given selector selects.
func SelectNodes(root *html.Node, sel string) []*html.Node {
// Selectors of element names, such as the user agent styles have, select
// the elements with those names, which one walk of the tree finds.
if a := atom.Lookup([]byte(sel)); a != 0 && a.String() == sel {
var matches []*html.Node
var walk func(n *html.Node)
walk = func(n *html.Node) {
if n.DataAtom == a {
matches = append(matches, n)
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
if c.Type == html.ElementNode {
walk(c)
}
}
}
walk(root)
return matches
}
cs := CompileSelector(sel)
if cs == nil {
return nil
}
return cascadia.QueryAll(root, cs.Sel)
}
// Specificity returns the specificity of the given selector,
// as ids*10000 + (classes, attributes, pseudo-classes)*100 + types.
func Specificity(sel string) int {
ids, classes, types := 0, 0, 0
start := true // at the start of a compound selector
for i := 0; i < len(sel); i++ {
ch := sel[i]
switch ch {
case '#':
ids++
start = false
case '.':
classes++
start = false
case '[':
classes++
for i < len(sel) && sel[i] != ']' {
i++
}
start = false
case ':':
if i+1 < len(sel) && sel[i+1] == ':' {
types++ // pseudo-element
i++
} else {
classes++
}
start = false
case ' ', '>', '+', '~', ',':
start = true
continue
case '*':
start = false
default:
if start && (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z') {
types++
}
start = false
}
// skip the rest of the name
for i+1 < len(sel) && IsNameChar(sel[i+1]) {
i++
}
}
return ids*10000 + classes*100 + types
}
func IsNameChar(ch byte) bool {
return ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9' || ch == '-' || ch == '_'
}
// SplitSelectors splits the given selector list at the commas that are
// not in parentheses, brackets, or quotes.
func SplitSelectors(list string) []string {
var sels []string
depth := 0
var quote byte
start := 0
for i := 0; i < len(list); i++ {
ch := list[i]
switch {
case quote != 0:
switch ch {
case '\\':
i++
case quote:
quote = 0
}
case ch == '"' || ch == '\'':
quote = ch
case ch == '(' || ch == '[':
depth++
case ch == ')' || ch == ']':
depth--
case ch == ',' && depth == 0:
sels = append(sels, strings.TrimSpace(list[start:i]))
start = i + 1
}
}
return append(sels, strings.TrimSpace(list[start:]))
}
// ModalAttr is the attribute of the dialogs that are shown as modal (as
// by the showModal of scripts), which the :modal selector of CSS selects
// (and the style of browsers for them, in the top layer).
const ModalAttr = "data-htmlcore-modal"
// HoverAttr is the attribute of the elements that are hovered while a page
// is read (see htmlcore.Context.Hovered), which no element of a document has.
const HoverAttr = "data-htmlcore-hover"
// PseudoSelector returns the selector of the elements of the given
// selector of a ::before or ::after pseudo-element (also :before and
// :after), and which of them it is, or false if it is not one.
func PseudoSelector(sel string) (base, kind string, ok bool) {
lsel := strings.ToLower(sel)
for _, k := range []string{"before", "after"} {
for _, p := range []string{"::" + k, ":" + k} {
if strings.HasSuffix(lsel, p) {
base = strings.TrimSpace(sel[:len(sel)-len(p)])
if base == "" || strings.HasSuffix(base, " ") || strings.HasSuffix(base, ">") {
base += "*"
}
return base, k, true
}
}
}
return "", "", false
}
// KeyIn returns whether the given element has the key of the selector
// (see [CompiledSelector.key]), which every element that it selects has,
// or it has none.
func (cs *CompiledSelector) KeyIn(n *html.Node) bool {
switch cs.KeyKind {
case '#':
return attrOf(n, "id") == cs.Key
case '.':
return slices.Contains(strings.Fields(attrOf(n, "class")), cs.Key)
case 't':
return strings.EqualFold(n.Data, cs.Key)
}
return true
}
// attrOf returns the value of the given attribute of the given node,
// or "" if it has none, as [GetAttr].
func attrOf(n *html.Node, key string) string {
res := ""
for _, a := range n.Attr {
if a.Key == key {
res = a.Val
}
}
return res
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package css
import (
"regexp"
"strings"
"sync"
douceur "github.com/aymerick/douceur/css"
"github.com/aymerick/douceur/parser"
"github.com/gorilla/css/scanner"
)
// ImportURL returns the URL and the media query list of the given
// prelude of an @import rule (url("x") media, or "x" media).
func ImportURL(prelude string) (url, media string) {
p := strings.TrimSpace(prelude)
if rest, ok := strings.CutPrefix(p, "url("); ok {
before, after, ok := strings.Cut(rest, ")")
if !ok {
return "", ""
}
url, media = before, after
} else if len(p) > 0 && (p[0] == '"' || p[0] == '\'') {
end := strings.IndexByte(p[1:], p[0])
if end < 0 {
return "", ""
}
url, media = p[:end+2], p[end+2:]
} else {
return "", ""
}
url = strings.Trim(strings.TrimSpace(url), `"'`)
media = strings.TrimSpace(media)
// layer() and supports() conditions are not supported, and are ignored
if strings.HasPrefix(media, "layer") || strings.HasPrefix(media, "supports(") {
media = ""
}
return url, media
}
// URLPattern matches the url() of CSS values, with its URL quoted or not.
var URLPattern = regexp.MustCompile(`url\(\s*(?:"([^"]*)"|'([^']*)'|([^)'"\s]*))\s*\)`)
// ContainerCond is the condition of an @container rule: the name of the
// container that it queries ("" for the nearest one), and its query (as
// (width <= 799px)), and that of an @container rule that it is in.
type ContainerCond struct {
Name, Query string
Outer *ContainerCond
}
// ParseContainerCond returns the condition of an @container rule of the
// given prelude (as "spotlight (width <= 799px)"), in the given one.
func ParseContainerCond(prelude string, outer *ContainerCond) *ContainerCond {
prelude = strings.TrimSpace(prelude)
cc := &ContainerCond{Query: prelude, Outer: outer}
if i := strings.IndexAny(prelude, "( "); i > 0 && !strings.HasPrefix(strings.ToLower(prelude), "not") {
name := strings.TrimSpace(prelude[:i])
if name != "" && !strings.ContainsAny(name, "()") {
cc.Name = name
cc.Query = strings.TrimSpace(prelude[i:])
}
}
return cc
}
// Parse parses the given style sheet. If it does not parse as a whole,
// as with constructs that the parser does not support, each of its top-level
// rules is parsed on its own, so that only the rules that do not parse are
// left out.
func Parse(style string) *douceur.Stylesheet {
// The style sheets of a page are parsed again each time that it is read
// (as for each change that its scripts make), so they are cached (as
// they are not changed after they are parsed).
parsedCSSMu.Lock()
ss, ok := parsedCSS[style]
parsedCSSMu.Unlock()
if ok {
return ss
}
ss = parseCSSText(style)
if len(style) >= minCachedCSS {
parsedCSSMu.Lock()
if parsedCSSSize+len(style) > maxParsedCSS {
parsedCSS, parsedCSSSize = map[string]*douceur.Stylesheet{}, 0
}
parsedCSS[style] = ss
parsedCSSSize += len(style)
parsedCSSMu.Unlock()
}
return ss
}
// parsedCSS has the style sheets that have been parsed, by their text,
// up to maxParsedCSS bytes of text (after which it is cleared). Only style
// sheets of at least minCachedCSS bytes are cached (as small ones, as of
// style attributes, are parsed quickly).
var (
parsedCSSMu sync.Mutex
parsedCSS = map[string]*douceur.Stylesheet{}
parsedCSSSize int
)
const (
maxParsedCSS = 16 << 20
minCachedCSS = 1024
)
// parseCSSText parses the given style sheet (see [parseCSS]).
func parseCSSText(style string) *douceur.Stylesheet {
// (the condition of an @container rule is kept, after containerMark)
style = containerRule.ReplaceAllString(style, "@supports "+ContainerMark+"$1{")
style = unknownGroupingRule.ReplaceAllString(style, "@supports$1{")
style = RemoveStray(style) // last: the parser must get what it leaves
if ss, err := parser.Parse(style); err == nil {
return ss
}
ss := douceur.NewStylesheet()
for _, block := range topLevelBlocks(style) {
bs, err := parser.Parse(block)
if err != nil {
continue
}
ss.Rules = append(ss.Rules, bs.Rules...)
}
return ss
}
// unknownGroupingRule matches the start of the block of a grouping
// at-rule that the parser does not know has rules in it (and parses as
// declarations, failing at the end of the first rule in it, as for the
// @container rules in the @layer of the style sheet of github.com), which
// are parsed as @supports rules, whose rules apply (see addRuleList).
var unknownGroupingRule = regexp.MustCompile(`@(?:layer|container|scope|starting-style)\b([^;{}]*)\{`)
// containerRule matches the start of the block of an @container rule, which
// is parsed as an @supports rule with its condition after containerMark.
var containerRule = regexp.MustCompile(`@container\b([^;{}]*)\{`)
// ContainerMark marks the prelude of an @supports rule that is an
// @container rule (see [containerRule]).
const ContainerMark = "--container:"
// groupingRules are the at-rules whose blocks have rules (not declarations).
var groupingRules = []string{"@media", "@supports", "@layer", "@container", "@document", "@-moz-document", "@scope", "@starting-style"}
// RemoveStray returns the given style sheet without what cannot be a
// rule where rules are expected (at the top level and in the blocks of
// grouping at-rules such as @media): statements that end with a semicolon
// but are not at-rules (as "a;b{...}"), and blocks without a selector
// (as "{a:b}", which CSS-in-JS libraries can make). It also removes blocks
// in declarations (nested rules, as made by an @media rule cut short by a
// semicolon in its condition). The parser does not support any of these,
// and loops forever on a semicolon where a rule is expected. The style
// sheet is read in the tokens of the parser's own scanner, so that what
// is in a string, a comment, a url or an escape is never taken for the
// structure of the style sheet. It ends where the scanner fails, where
// the parser stops.
func RemoveStray(style string) string {
if !strings.ContainsAny(style, ";{") {
return style
}
type level struct {
rules bool // whether rules are expected (not declarations)
stmtOut int // the start of the current statement in out
stmt []byte // the current statement, without comments
}
out := make([]byte, 0, len(style))
levels := []level{{rules: true}}
skip := 0 // the depth in a block being removed
sc := scanner.New(style)
for {
tok := sc.Next()
if tok.Type == scanner.TokenEOF || tok.Type == scanner.TokenError {
break
}
lv := &levels[len(levels)-1]
brace := ""
if tok.Type == scanner.TokenChar {
brace = tok.Value
}
if skip > 0 {
switch brace {
case "{":
skip++
case "}":
skip--
}
continue
}
switch brace {
case "{":
prelude := strings.TrimSpace(string(lv.stmt))
if !lv.rules || prelude == "" { // a nested rule, or no selector
skip = 1
out = out[:lv.stmtOut]
lv.stmt = lv.stmt[:0]
continue
}
rules := false
for _, g := range groupingRules {
if strings.HasPrefix(strings.ToLower(prelude), g) {
rules = true
}
}
out = append(out, tok.Value...)
levels = append(levels, level{rules: rules, stmtOut: len(out)})
case "}":
if lv.rules && strings.TrimSpace(string(lv.stmt)) != "" {
out = out[:lv.stmtOut] // a rule without a block
}
if len(levels) == 1 { // a stray brace
lv.stmtOut, lv.stmt = len(out), lv.stmt[:0]
continue
}
levels = levels[:len(levels)-1]
out = append(out, tok.Value...)
lv = &levels[len(levels)-1]
lv.stmtOut, lv.stmt = len(out), lv.stmt[:0]
case ";":
if lv.rules && !isAtRule(string(lv.stmt)) {
out = out[:lv.stmtOut] // a stray statement
} else {
out = append(out, tok.Value...)
}
lv.stmtOut, lv.stmt = len(out), lv.stmt[:0]
default:
out = append(out, tok.Value...)
if tok.Type != scanner.TokenComment {
lv.stmt = append(lv.stmt, tok.Value...)
}
}
}
return string(out)
}
// isAtRule returns whether the given CSS statement is an at-rule: an @
// followed by a name, as the parser's scanner reads it.
func isAtRule(stmt string) bool {
return scanner.New(strings.TrimSpace(stmt)).Next().Type == scanner.TokenAtKeyword
}
// topLevelBlocks splits the given style sheet into its top-level rules,
// at the closing braces (or semicolons of at-rules without blocks) that
// are not nested, read in the tokens of the parser's scanner (see
// [RemoveStray]).
func topLevelBlocks(style string) []string {
var blocks []string
var block []byte
depth := 0
sc := scanner.New(style)
for {
tok := sc.Next()
if tok.Type == scanner.TokenEOF || tok.Type == scanner.TokenError {
break
}
block = append(block, tok.Value...)
if tok.Type != scanner.TokenChar {
continue
}
switch {
case tok.Value == "{":
depth++
case tok.Value == "}":
depth--
if depth <= 0 {
blocks = append(blocks, string(block))
block, depth = block[:0], 0
}
case tok.Value == ";" && depth == 0:
blocks = append(blocks, string(block))
block = block[:0]
}
}
return blocks
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package css
import (
"strings"
)
// CutTopLevel cuts s around the first sep that is not in parentheses.
func CutTopLevel(s string, sep byte) (before, after string, found bool) {
depth := 0
for i := 0; i < len(s); i++ {
switch s[i] {
case '(':
depth++
case ')':
depth--
case sep:
if depth == 0 {
return strings.TrimSpace(s[:i]), strings.TrimSpace(s[i+1:]), true
}
}
}
return s, "", false
}
// SplitTopLevelSpaces splits the given value at the spaces that are not in
// parentheses (as "calc(1rem + 4px) auto").
func SplitTopLevelSpaces(v string) []string {
var parts []string
depth, start := 0, -1
for i, r := range v {
switch {
case r == '(':
depth++
case r == ')':
depth--
case r == ' ' && depth == 0:
if start >= 0 {
parts = append(parts, v[start:i])
start = -1
}
continue
}
if start < 0 {
start = i
}
}
if start >= 0 {
parts = append(parts, v[start:])
}
return parts
}
// SplitTopLevel splits the given string at the given separator where it is
// not in parentheses or quotes (as a list of sources with url()s).
func SplitTopLevel(s string, sep byte) []string {
var parts []string
for {
before, after, found := CutTopLevel(s, sep)
parts = append(parts, before)
if !found {
return parts
}
s = after
}
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package css
import (
"strconv"
"strings"
"time"
"golang.org/x/net/html"
)
// Transition is a transition of a property of an element, which a change
// of its declarations starts (see htmlcore.Context.OnTransition). It is not
// rendered: the element has its new style at once, but the transitionend
// event is dispatched when it would end, as pages wait for it.
type Transition struct {
// Node is the element.
Node *html.Node
// Property is the name of the property, as for the propertyName of
// its transitionend event.
Property string
// Delay is the time before the transition starts.
Delay time.Duration
// Duration is the time that the transition takes.
Duration time.Duration
}
// TransitionsOf returns the transitions of the given properties of the
// given element, which have changed, for its given declarations (with
// their transition, transition-property, transition-duration and
// transition-delay).
func TransitionsOf(n *html.Node, decls map[string]string, changed []string) []Transition {
items := transitionItems(decls)
var ts []Transition
for _, p := range changed {
if !animatable(p) {
continue
}
for _, it := range items {
if it.duration <= 0 || !transitionMatches(it.property, p) {
continue
}
ts = append(ts, Transition{Node: n, Property: p, Delay: it.delay, Duration: it.duration})
break
}
}
return ts
}
// transitionItem is a transition of the transition declarations of an
// element: a property (or all), with its duration and delay.
type transitionItem struct {
property string
duration, delay time.Duration
}
// transitionItems returns the transitions of the given declarations: the
// longhands (transition-property, with the lists of the durations and
// delays repeated for the properties), or else the transition shorthand.
func transitionItems(decls map[string]string) []transitionItem {
get := func(p string) string {
if v, ok := decls[p]; ok {
return v
}
return decls["-webkit-"+p]
}
var items []transitionItem
if v := get("transition"); v != "" {
for _, part := range SplitTopLevel(v, ',') {
it := transitionItem{property: "all"}
times := 0
for f := range strings.FieldsSeq(part) {
if d, ok := cssTime(f); ok {
if times == 0 {
it.duration = d
} else {
it.delay = d
}
times++
} else if !timingKeyword(f) {
it.property = strings.ToLower(f)
}
}
items = append(items, it)
}
}
props, durs, delays := get("transition-property"), get("transition-duration"), get("transition-delay")
if props == "" && durs == "" && delays == "" {
return items
}
// longhands after the shorthand (as they are declared after it, which
// is the order of most styles)
pl := SplitTopLevel(props, ',')
if props == "" {
pl = []string{"all"}
if len(items) > 0 {
pl = nil
for _, it := range items {
pl = append(pl, it.property)
}
}
}
timesOf := func(v string, from func(it transitionItem) time.Duration) []time.Duration {
var ds []time.Duration
for _, f := range SplitTopLevel(v, ',') {
d, _ := cssTime(strings.TrimSpace(f))
ds = append(ds, d)
}
if len(ds) == 0 {
for _, it := range items {
ds = append(ds, from(it))
}
}
return ds
}
dl := timesOf(durs, func(it transitionItem) time.Duration { return it.duration })
yl := timesOf(delays, func(it transitionItem) time.Duration { return it.delay })
items = nil
for i, p := range pl {
it := transitionItem{property: strings.ToLower(strings.TrimSpace(p))}
if len(dl) > 0 {
it.duration = dl[i%len(dl)]
}
if len(yl) > 0 {
it.delay = yl[i%len(yl)]
}
items = append(items, it)
}
return items
}
// transitionMatches returns whether a transition of the given property (as
// in transition-property) is of the given changed property: all, the same
// property, or a shorthand of it or one of its longhands (as margin and
// margin-top).
func transitionMatches(tp, p string) bool {
return tp == "all" || tp == p || strings.HasPrefix(p, tp+"-") || strings.HasPrefix(tp, p+"-")
}
// animatable returns whether a change of the given property can be a
// transition (not of custom properties, or of the transitions themselves,
// or of display and content).
func animatable(p string) bool {
return !strings.HasPrefix(p, "--") && !strings.Contains(p, "transition") && !strings.Contains(p, "animation") &&
p != "display" && p != "content" && p != "position" && p != "will-change"
}
// timingKeyword returns whether the given word of a transition is a
// timing function or a keyword that is not a property.
func timingKeyword(f string) bool {
f = strings.ToLower(f)
switch f {
case "ease", "linear", "ease-in", "ease-out", "ease-in-out", "step-start", "step-end", "normal", "allow-discrete", "initial", "inherit", "unset":
return true
}
return strings.HasPrefix(f, "cubic-bezier(") || strings.HasPrefix(f, "steps(") || strings.HasPrefix(f, "linear(") || strings.HasPrefix(f, "var(")
}
// cssTime returns the duration of the given CSS time (as .3s or 200ms).
func cssTime(v string) (time.Duration, bool) {
v = strings.ToLower(strings.TrimSpace(v))
mult := float64(time.Second)
switch {
case strings.HasSuffix(v, "ms"):
v, mult = strings.TrimSuffix(v, "ms"), float64(time.Millisecond)
case strings.HasSuffix(v, "s"):
v = strings.TrimSuffix(v, "s")
default:
return 0, false
}
f, err := strconv.ParseFloat(v, 64)
if err != nil {
return 0, false
}
return time.Duration(f * mult), true
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package css
import (
"image"
"math"
"strconv"
"strings"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/sides"
"cogentcore.org/core/styles/units"
)
// SplitColors splits the given value into fields at spaces
// that are not inside of parentheses, as in rgb(...) and calc(...).
func SplitColors(v string) []string {
var fs []string
depth := 0
start := -1
for i, r := range v {
switch r {
case '(':
depth++
case ')':
depth--
case ' ', '\t', '\n':
if depth == 0 {
if start >= 0 {
fs = append(fs, v[start:i])
}
start = -1
continue
}
}
if start < 0 {
start = i
}
}
if start >= 0 {
fs = append(fs, v[start:])
}
return fs
}
// ZeroAreaClip returns whether the given value of clip (a rect) or of
// clip-path (an inset) clips the element to nothing, as in the visually
// hidden elements of pages (rect(0 0 0 0), rect(1px, 1px, 1px, 1px),
// inset(50%)).
func ZeroAreaClip(prop, v string) bool {
fn := "rect("
if prop == "clip-path" {
if strings.HasPrefix(v, "rect(") { // as clip (as rect(0 0 0 0) of the .sr-only of GitHub)
return ZeroAreaClip("clip", v)
}
fn = "inset("
}
args, ok := strings.CutPrefix(v, fn)
if !ok || !strings.HasSuffix(args, ")") {
return false
}
f := strings.Fields(strings.ReplaceAll(strings.TrimSuffix(args, ")"), ",", " "))
if prop == "clip-path" { // insets of 50% or more from opposite sides
if len(f) == 0 || len(f) > 4 || strings.Contains(args, "round") {
return false
}
pct := func(x string) float64 {
if x == "0" || x == "0px" {
return 0
}
n, ok := strings.CutSuffix(x, "%")
if !ok {
return -1
}
p, err := strconv.ParseFloat(n, 64)
if err != nil {
return -1
}
return p
}
// the sides of the shorthand: top, right, bottom, left
var sides [4]float64
for i := range sides {
j := [4][4]int{{0, 0, 0, 0}, {0, 1, 0, 1}, {0, 1, 2, 1}, {0, 1, 2, 3}}[len(f)-1][i]
sides[i] = pct(f[j])
}
top, right, bottom, left := sides[0], sides[1], sides[2], sides[3]
return top >= 0 && bottom >= 0 && top+bottom >= 100 || right >= 0 && left >= 0 && right+left >= 100
}
if len(f) != 4 { // top, right, bottom, left, of the top left corner
return false
}
env := DefaultLengthEnv()
var px [4]float32
for i, x := range f {
if x == "auto" {
return false
}
l, ok := env.LengthPx(x)
if !ok {
return false
}
px[i] = l
}
return px[2] <= px[0] || px[1] <= px[3]
}
// ColorFunc returns a function that returns the given CSS color (or nil if
// it is not one). A uniform color is parsed once, and is shared by the
// styles; other colors (as gradients) are parsed for each style, so that
// each has its own.
func ColorFunc(v string) func() image.Image {
cl := ParseColor(v)
if _, ok := cl.(*image.Uniform); ok || cl == nil {
return func() image.Image { return cl }
}
return func() image.Image { return ParseColor(v) }
}
// ParseFlex returns the grow, shrink, and basis of the given value of the
// flex shorthand, as in CSS, where a number alone (as flex: 1) has a basis
// of 0, not of the width of the item.
func ParseFlex(v string) (grow, shrink float32, basis string, ok bool) {
switch v {
case "none":
return 0, 0, "auto", true
case "auto":
return 1, 1, "auto", true
case "initial":
return 0, 1, "auto", true
}
fs := strings.Fields(v)
if len(fs) == 0 {
return 0, 0, "", false
}
shrink, basis = 1, "0"
nums := 0
for _, f := range fs {
x, err := strconv.ParseFloat(f, 32)
switch {
case err == nil && nums == 0:
grow = float32(x)
nums++
case err == nil && nums == 1:
shrink = float32(x)
nums++
default:
basis = f
if nums == 0 { // flex: <basis> has a grow of 1
grow = 1
}
}
}
return grow, shrink, basis, true
}
// ExpandSides expands the 1 to 4 values of a CSS shorthand for
// the sides of a box into the values for top, right, bottom, left.
func ExpandSides(vals []string) []string {
switch len(vals) {
case 0:
return nil
case 1:
return []string{vals[0], vals[0], vals[0], vals[0]}
case 2:
return []string{vals[0], vals[1], vals[0], vals[1]}
case 3:
return []string{vals[0], vals[1], vals[2], vals[1]}
}
return vals[:4]
}
// SideIndex returns the index (top, right, bottom, left) of the side in
// the name of the given property, such as "margin-left".
func SideIndex(prop string) int {
switch {
case strings.Contains(prop, "-top"):
return 0
case strings.Contains(prop, "-right"):
return 1
case strings.Contains(prop, "-bottom"):
return 2
}
return 3
}
// SetSide sets the given side (top, right, bottom, left) of the given sides.
func SetSide[T any](s *sides.Sides[T], i int, v T) {
setSidePtr(&s.Top, &s.Right, &s.Bottom, &s.Left, i, v)
}
// SetValueSide sets the given side (top, right, bottom, left) of the given values.
func SetValueSide(s *sides.Values, i int, v units.Value) {
setSidePtr(&s.Top, &s.Right, &s.Bottom, &s.Left, i, v)
}
func setSidePtr[T any](top, right, bottom, left *T, i int, v T) {
s := struct{ Top, Right, Bottom, Left *T }{top, right, bottom, left}
switch i {
case 0:
*s.Top = v
case 1:
*s.Right = v
case 2:
*s.Bottom = v
case 3:
*s.Left = v
}
}
// SetBorderStyle sets the style of the given side of the border.
func SetBorderStyle(s *styles.Style, i int, v string) {
if v == "none" || v == "hidden" {
SetValueSide(&s.Border.Width, i, units.Dp(0))
SetSide(&s.Border.Style, i, styles.BorderNone)
return
}
var bs styles.BorderStyles
if bs.SetString(v) == nil {
SetSide(&s.Border.Style, i, bs)
}
}
// AlignValue returns the alignment for the given CSS value.
func AlignValue(v string) styles.Aligns {
switch v {
case "flex-start", "start", "left", "self-start", "normal", "stretch":
return styles.Start
case "flex-end", "end", "right", "self-end":
return styles.End
case "center":
return styles.Center
case "baseline", "first baseline":
return styles.Baseline
case "space-between":
return styles.SpaceBetween
case "space-around":
return styles.SpaceAround
case "space-evenly":
return styles.SpaceEvenly
}
return styles.Auto
}
// GridColumns returns the number of columns of a grid-template-columns value.
func GridColumns(v string) int {
if after, ok := strings.CutPrefix(v, "repeat("); ok {
n, _, _ := strings.Cut(after, ",")
if i, err := strconv.Atoi(strings.TrimSpace(n)); err == nil {
return i
}
}
return len(SplitColors(v))
}
// cssTranslate returns the translation of the given value of the transform
// property (the sum of its translate functions; the other functions, as
// rotate and scale, are not supported), or of the translate property, as
// the lengths of x and y. It returns false if it is not valid.
// AspectRatio returns the ratio of width to height of the given value
// of the aspect-ratio property (as 16 / 9, 1.5, or auto 4/3), or 0 for
// none (auto).
func AspectRatio(v string) float32 {
v = strings.TrimSpace(strings.Replace(v, "auto", "", 1))
a, b, slash := strings.Cut(v, "/")
w, err := strconv.ParseFloat(strings.TrimSpace(a), 32)
if err != nil || w <= 0 {
return 0
}
h := 1.0
if slash {
if h, err = strconv.ParseFloat(strings.TrimSpace(b), 32); err != nil || h <= 0 {
return 0
}
}
return float32(w / h)
}
// ZeroScale returns whether the given transform scales the element
// to nothing in either dimension (as scaleX(0), for a progress bar
// that is not started), which is then not shown.
func ZeroScale(v string) bool {
for rest := v; rest != ""; {
name, args, found := strings.Cut(rest, "(")
if !found {
break
}
before, after, ok := strings.Cut(args, ")")
if !ok {
break
}
as := strings.Split(before, ",")
zero := func(i int) bool {
if i >= len(as) {
return false
}
f, err := strconv.ParseFloat(strings.TrimSpace(as[i]), 64)
return err == nil && f == 0
}
switch strings.TrimSpace(name) {
case "scale", "scale3d":
if zero(0) || (len(as) > 1 && zero(1)) {
return true
}
case "scalex", "scaley":
if zero(0) {
return true
}
}
rest = strings.TrimSpace(after)
}
return false
}
func Translate(prop, v string) (x, y string, ok bool) {
x, y = "0", "0"
if v == "none" || v == "" {
return x, y, true
}
if prop == "translate" { // x [y [z]]
fs := strings.Fields(v)
if len(fs) > 0 {
x = fs[0]
}
if len(fs) > 1 {
y = fs[1]
}
return x, y, true
}
var xs, ys []string
for rest := v; rest != ""; {
name, args, found := strings.Cut(rest, "(")
if !found {
break
}
before, after, ok := strings.Cut(args, ")")
if !ok {
return "", "", false
}
as := strings.Split(before, ",")
for i := range as {
as[i] = strings.TrimSpace(as[i])
}
switch strings.TrimSpace(name) {
case "translate", "translate3d":
xs = append(xs, as[0])
if len(as) > 1 {
ys = append(ys, as[1])
}
case "translatex":
xs = append(xs, as[0])
case "translatey":
ys = append(ys, as[0])
}
rest = strings.TrimSpace(after)
}
sum := func(ls []string) string {
switch len(ls) {
case 0:
return "0"
case 1:
return ls[0]
}
return "calc(" + strings.Join(ls, " + ") + ")"
}
return sum(xs), sum(ys), true
}
// Rotate returns the sum of the angles of the rotate functions of the
// given transform, in degrees.
func Rotate(_, v string) float32 {
var deg float32
for rest := v; rest != ""; {
name, args, found := strings.Cut(rest, "(")
if !found {
break
}
before, after, ok := strings.Cut(args, ")")
if !ok {
break
}
if n := strings.TrimSpace(name); n == "rotate" || n == "rotatez" {
deg += Angle(strings.TrimSpace(before))
}
rest = strings.TrimSpace(after)
}
return deg
}
// Angle returns the given CSS angle in degrees (deg, rad, grad, turn).
func Angle(v string) float32 {
for _, u := range []struct {
suffix string
deg float64
}{{"deg", 1}, {"grad", 0.9}, {"rad", 180 / math.Pi}, {"turn", 360}} {
if n, ok := strings.CutSuffix(v, u.suffix); ok {
f, _ := strconv.ParseFloat(strings.TrimSpace(n), 64)
return float32(f * u.deg)
}
}
f, _ := strconv.ParseFloat(v, 64)
return float32(f)
}
// EmLength returns the given CSS length in em, with px for 16px to the
// em (and rem as em), or 0 if it is not one of these.
func EmLength(v string) float64 {
v = strings.TrimSpace(strings.ToLower(v))
for _, u := range []struct {
suffix string
scale float64
}{{"rem", 1}, {"em", 1}, {"px", 1.0 / 16}} {
if num, ok := strings.CutSuffix(v, u.suffix); ok {
f, err := strconv.ParseFloat(num, 64)
if err != nil {
return 0
}
return f * u.scale
}
}
return 0
}
// EmSpaces returns a string of space characters (which are not collapsed
// or trimmed) about as wide as the given number of em.
func EmSpaces(em float64) string {
var sb strings.Builder
for _, sp := range []struct {
r rune
w float64
}{{'\u2003', 1}, {'\u2002', 0.5}, {'\u2004', 1.0 / 3}, {'\u2005', 0.25}, {'\u2006', 1.0 / 6}, {'\u200A', 0.1}} {
for em >= sp.w-0.04 && sb.Len() < 64 {
sb.WriteRune(sp.r)
em -= sp.w
}
}
return sb.String()
}
// PercentUnit returns whether the given unit is a percentage of a size of
// the parent or the element, which is not definite for a replaced element.
func PercentUnit(u units.Units) bool {
return u == units.UnitPw || u == units.UnitPh || u == units.UnitEw || u == units.UnitEh
}
// UnitlessCalc returns the value of the given calc() expression of numbers
// only (no lengths or percentages), and whether it is one.
func UnitlessCalc(v string) (float32, bool) {
inner, ok := strings.CutPrefix(strings.ToLower(strings.TrimSpace(v)), "calc(")
if !ok || strings.ContainsAny(inner, "abcdefghijklmnopqrstuvwxyz%") {
return 0, false
}
return CalcPx(v)
}
// ZeroLength returns whether the given CSS length is zero (as 0, 0px, 0%).
func ZeroLength(v string) bool {
v = strings.TrimSpace(v)
v = strings.TrimRight(v, "abcdefghijklmnopqrstuvwxyz%")
f, err := strconv.ParseFloat(v, 32)
return err == nil && f == 0
}
// SideDots returns the given sides in dots, using the given function.
func SideDots(v *sides.Values, dots func(v *units.Value) float32) sides.Floats {
return sides.NewFloats(dots(&v.Top), dots(&v.Right), dots(&v.Bottom), dots(&v.Left))
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
_ "embed"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/core"
"cogentcore.org/core/htmlcore"
)
//go:embed example.html
var content string
func main() {
b := core.NewBody("HTML Example")
errors.Log(htmlcore.ReadHTMLString(htmlcore.NewContext(), b, content))
b.RunMainWindow()
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
_ "embed"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/core"
"cogentcore.org/core/htmlcore"
"cogentcore.org/core/styles"
_ "cogentcore.org/core/text/tex" // include this to get math
)
//go:embed example.md
var content string
func main() {
b := core.NewBody("MD Example")
ctx := htmlcore.NewContext()
ctx.AddWidgetHandler(func(w core.Widget) {
switch x := w.(type) {
case *core.Text:
x.Styler(func(s *styles.Style) {
s.Max.X.Ch(80)
})
}
})
errors.Log(htmlcore.ReadMDString(ctx, b, content))
b.RunMainWindow()
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package htmlcore converts HTML and Markdown into Cogent Core widgets.
//
// It is the API for apps and content sites: make a [Context] with
// [NewContext], set it up with its handlers and settings, and read HTML or
// Markdown into a parent widget with [ReadHTML], [ReadHTMLString], [ReadMD]
// or [ReadMDString].
//
// The engine that does the reading (the CSS cascade, layout of the
// elements, re-reading and restyling changed documents) is package
// [htmlengine], which apps that show web pages, as a browser does, use
// directly.
package htmlcore
import (
"io"
"io/fs"
"net/http"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/htmlcore/htmlengine"
"github.com/yuin/goldmark/v2/ast"
"golang.org/x/net/html"
)
// Context is the context for reading HTML and Markdown into widgets: its
// settings, its handlers of elements, attributes, wikilinks and widgets,
// and, in the handlers, the state of the current read (the current
// [Context.Node] and the parents that its widgets are added to).
type Context struct {
// e is the engine context that reads.
e *htmlengine.Context
}
// NewContext returns a new [Context] with basic defaults.
func NewContext() *Context {
return &Context{e: htmlengine.NewContext()}
}
// wrap returns the Context for the given engine context, as for the
// handlers, which are called with the engine context that reads.
func wrap(e *htmlengine.Context) *Context {
return &Context{e: e}
}
// Node returns the node that is currently being read.
func (c *Context) Node() *html.Node { return c.e.Node }
// SetNode sets the node that is currently being read, as for
// [ExtractText] of another node in an element handler.
func (c *Context) SetNode(n *html.Node) *Context {
c.e.Node = n
return c
}
// Parent returns the current parent widget that a widget associated with
// the current node should be added to. It may make changes to the widget
// tree, so the widget must be added to the resulting parent immediately.
func (c *Context) Parent() core.Widget { return c.e.Parent() }
// BlockParent returns the current parent widget that block-level
// (non-inline) elements are added to, as for the widgets that an element
// handler makes.
func (c *Context) BlockParent() core.Widget { return c.e.BlockParent }
// PageURL returns the URL of the current page, which relative URLs are
// relative to, or "" if there is none.
func (c *Context) PageURL() string { return c.e.PageURL }
// SetPageURL sets the URL of the current page (see [Context.PageURL]).
func (c *Context) SetPageURL(url string) *Context {
c.e.PageURL = url
return c
}
// SetOpenURL sets the function used to open URLs, as of links, which
// defaults to [system.App.OpenURL].
func (c *Context) SetOpenURL(f func(url string, e events.Event)) *Context {
c.e.OpenURL = f
return c
}
// GetURL returns the function used to get resources from URLs (see
// [Context.SetGetURL]), as for one that gets some URLs itself and the
// others with it.
func (c *Context) GetURL() func(url string) (*http.Response, error) { return c.e.GetURL }
// SetGetURL sets the function used to get resources from URLs, as images
// and style sheets, which defaults to [http.Get].
func (c *Context) SetGetURL(f func(url string) (*http.Response, error)) *Context {
c.e.GetURL = f
return c
}
// SetStyle sets CSS that is added to the style sheets of each page that is
// read, before those of the page, as for the margins of the pages of an app.
func (c *Context) SetStyle(style string) *Context {
c.e.Style = style
return c
}
// SetDelayedImageLoad sets whether images are loaded with a delay,
// rather than immediately.
func (c *Context) SetDelayedImageLoad(delayed bool) *Context {
c.e.DelayedImageLoad = delayed
return c
}
// SetStageSize sets the size of the content of a page (in runes of text,
// with estimates for other elements) after which [ReadHTML] stops adding
// the widgets of its top-level elements, leaving the rest for
// [Context.ReadRest], so that the first part of a long page is shown
// sooner. 0 reads all of it.
func (c *Context) SetStageSize(size int) *Context {
c.e.StageSize = size
return c
}
// ImageCache returns the cache of the decoded images, if any.
func (c *Context) ImageCache() *ImageCache { return c.e.ImageCache }
// SetImageCache sets the cache of the decoded images of img elements, by
// their URL, so that reading a page again does not decode them again (see
// [NewImageCache]). It must only be set when the GetURL function returns
// the same content for the same URL until the cache is reset.
func (c *Context) SetImageCache(ic *ImageCache) *Context {
c.e.ImageCache = ic
return c
}
// AddElementHandler adds a handler of the elements with the given tag
// (as for custom elements), which makes their widgets, as in the
// [Context.BlockParent], in place of those that would be made for them. If
// it returns false, the default widgets of the element are made.
func (c *Context) AddElementHandler(tag string, f func(ctx *Context) bool) *Context {
c.e.ElementHandlers[tag] = func(e *htmlengine.Context) bool { return f(wrap(e)) }
return c
}
// AddAttributeHandler adds a handler of the given tag of the custom
// {tag: value} attributes of Markdown elements, which is called with the
// Markdown node as it is converted to HTML. It can write alternative or
// additional HTML to the given writer; if it returns true, the default HTML
// of the node is not written.
func (c *Context) AddAttributeHandler(tag string, f func(ctx *Context, w io.Writer, node ast.Node, entering bool, tag, value string) bool) *Context {
c.e.AttributeHandlers[tag] = func(e *htmlengine.Context, w io.Writer, node ast.Node, entering bool, tag, value string) bool {
return f(wrap(e), w, node, entering, tag, value)
}
return c
}
// AddWikilinkHandler adds a handler of wikilinks. If it returns "", "",
// the handlers added before it are tried.
func (c *Context) AddWikilinkHandler(h WikilinkHandler) *Context {
c.e.AddWikilinkHandler(h)
return c
}
// AddWidgetHandler adds a function that is called for each widget that is
// made, after it is configured, as for styling widgets of a type.
func (c *Context) AddWidgetHandler(f func(w core.Widget)) *Context {
c.e.AddWidgetHandler(f)
return c
}
// HasRest returns whether [ReadHTML] has left elements to read with
// [Context.ReadRest] (see [Context.SetStageSize]).
func (c *Context) HasRest() bool { return c.e.HasRest() }
// ReadRest adds the widgets of the elements that [ReadHTML] left (see
// [Context.SetStageSize]), and returns the widget that they are added to
// and the index of the first child added, which need to be updated.
// The context must not have been used to read other HTML since.
func (c *Context) ReadRest() (core.Widget, int, error) { return c.e.ReadRest() }
// LinkButton makes the given button open the given URL when it is
// clicked, with the OpenURL function of the context, and sets its
// tooltip to the URL. The URL is also the "href" property of the button,
// so that the HTML generated for the app has a link for it.
func (c *Context) LinkButton(bt *core.Button, url string) *core.Button {
return c.e.LinkButton(bt, url)
}
// LinkButtonUpdating is a version of [Context.LinkButton] for a URL that
// changes, from the given function.
func (c *Context) LinkButtonUpdating(bt *core.Button, url func() string) *core.Button {
return c.e.LinkButtonUpdating(bt, url)
}
// ReadHTML reads HTML from the given reader and adds the widgets of its
// elements to the given parent widget.
func ReadHTML(ctx *Context, parent core.Widget, r io.Reader) error {
return htmlengine.ReadHTML(ctx.e, parent, r)
}
// ReadHTMLString reads HTML from the given string and adds the widgets of
// its elements to the given parent widget.
func ReadHTMLString(ctx *Context, parent core.Widget, s string) error {
return htmlengine.ReadHTMLString(ctx.e, parent, s)
}
// ParseHTML parses HTML from the given reader into a document of nodes,
// as browsers parse it, which [ReadDocument] reads.
func ParseHTML(ctx *Context, r io.Reader) (*html.Node, error) {
return htmlengine.ParseHTML(ctx.e, r)
}
// ReadDocument adds the widgets of the elements of the given parsed
// document (see [ParseHTML]) to the given parent widget.
func ReadDocument(ctx *Context, parent core.Widget, n *html.Node) error {
return htmlengine.ReadDocument(ctx.e, parent, n)
}
// ReadMD reads Markdown from the given bytes and adds the widgets of its
// elements to the given parent widget.
func ReadMD(ctx *Context, parent core.Widget, b []byte) error {
return htmlengine.ReadMD(ctx.e, parent, b)
}
// ReadMDString reads Markdown from the given string and adds the widgets
// of its elements to the given parent widget.
func ReadMDString(ctx *Context, parent core.Widget, s string) error {
return htmlengine.ReadMDString(ctx.e, parent, s)
}
// MDToHTML converts the given Markdown to HTML, with the attribute and
// wikilink handlers of the context.
func MDToHTML(ctx *Context, md []byte) []byte {
return htmlengine.MDToHTML(ctx.e, md)
}
// ExtractText returns the text of the children of the current node of the
// context (see [Context.SetNode]), with inline markup for formatted text.
func ExtractText(ctx *Context) string {
return htmlengine.ExtractText(ctx.e)
}
// WikilinkHandler is a function that converts the text of a wikilink
// ([[text]]) to the URL and label of a link, or returns "", "" if it does
// not handle it.
type WikilinkHandler = htmlengine.WikilinkHandler
// GoDocWikilink returns a [WikilinkHandler] that converts wikilinks of the
// form [[prefix:identifier]] to a pkg.go.dev URL starting at pkg. For
// example, with prefix="doc" and pkg="cogentcore.org/core", the wikilink
// [[doc:core.Button]] links to https://pkg.go.dev/cogentcore.org/core/core#Button.
func GoDocWikilink(prefix string, pkg string) WikilinkHandler {
return htmlengine.GoDocWikilink(prefix, pkg)
}
// ImageCache caches the decoded images of img elements by their URL
// (see [Context.SetImageCache]).
type ImageCache = htmlengine.ImageCache
// NewImageCache returns a new [ImageCache] of at most the given number of
// bytes of decoded images.
func NewImageCache(maxBytes int) *ImageCache {
return htmlengine.NewImageCache(maxBytes)
}
// GetURLFromFS returns the response for the given URL from the given
// filesystem, as for a GetURL function of the files of an app.
func GetURLFromFS(fsys fs.FS, rawURL string) (*http.Response, error) {
return htmlengine.GetURLFromFS(fsys, rawURL)
}
// NodeOf returns the HTML node of the element that the given widget is
// for, or that of the nearest widget that it is in that has one (as for the
// text of an element), or nil if there is none.
func NodeOf(w core.Widget) *html.Node { return htmlengine.NodeOf(w) }
// GetAttr returns the value of the given attribute of the given node,
// or "" if it has none.
func GetAttr(n *html.Node, attr string) string { return htmlengine.GetAttr(n, attr) }
// HasAttr returns whether the given node has the given attribute.
func HasAttr(n *html.Node, attr string) bool { return htmlengine.HasAttr(n, attr) }
// GetLanguage returns the 'x' in a `language-x` class from the given
// string of class(es).
func GetLanguage(class string) string { return htmlengine.GetLanguage(class) }
// MDGetAttr returns the value of the given attribute of the given Markdown
// node, or "" if it has none.
func MDGetAttr(n ast.Node, attr string) string { return htmlengine.MDGetAttr(n, attr) }
// MDSetAttr sets the given attribute of the given Markdown node.
func MDSetAttr(n ast.Node, attr, value string) { htmlengine.MDSetAttr(n, attr, value) }
// TextTag returns the name of the HTML element that the given text is the
// text of, such as "h2" for the text of a heading, or "" if there is none.
func TextTag(tx *core.Text) string { return htmlengine.TextTag(tx) }
// TagTexts gives each text in the given widget the "tag" and "id"
// properties of the HTML element that it is the text of, if it does not
// have its own, as for printing it apart from the widget of its element (as
// in a PDF, which styles headings by their tags, and links to their ids).
func TagTexts(w core.Widget) { htmlengine.TagTexts(w) }
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"golang.org/x/net/html"
"cogentcore.org/core/htmlcore/css"
)
// The ancestor filter of selectors, as browsers have (a Bloom filter of
// the keys of the elements that an element is in): a selector whose
// compound selectors before its last one, that are of the elements that
// the element that it selects is in (as .menu in .menu .item), have keys
// (ids, classes, and names of elements) that no element that an element
// is in has, does not select it, which is found without matching it (most
// of the time of matching the elements of npr.org again, as its scripts
// changed them, was of the ancestors of each element).
// ancestorMask returns the mask of the keys of the elements that the given
// element is in, from c.ancestorMasks while it is set (for the elements
// matched at once, whose ancestors do not change meanwhile).
func (c *Context) ancestorMask(n *html.Node) css.KeyMask {
p := n.Parent
if p == nil || p.Type != html.ElementNode {
return css.KeyMask{}
}
if c.ancestorMasks != nil {
if m, ok := c.ancestorMasks[n]; ok {
return m
}
}
m := c.ancestorMask(p).Or(css.OwnKeys(p))
if c.ancestorMasks != nil {
c.ancestorMasks[n] = m
}
return m
}
// selMatch returns whether the given selector selects the given element,
// without matching it if it can not for its ancestors (see
// [css.AncestorKeys]).
func (c *Context) selMatch(cs *css.CompiledSelector, n *html.Node) bool {
if cs.Anc != (css.KeyMask{}) && !c.ancestorMask(n).Has(cs.Anc) {
return false
}
return cs.Sel.Match(n)
}
// keepAncestorMasks keeps the masks of the ancestors of the elements as
// they are matched (see [Context.ancestorMask]), until the returned
// function is called, for elements that do not change meanwhile.
func (c *Context) keepAncestorMasks() func() {
if c.ancestorMasks != nil {
return func() {}
}
c.ancestorMasks = map[*html.Node]css.KeyMask{}
return func() { c.ancestorMasks = nil }
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"io"
"slices"
"sort"
"strings"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/htmlcore/css"
"github.com/andybalholm/cascadia"
douceur "github.com/aymerick/douceur/css"
"github.com/aymerick/douceur/parser"
"golang.org/x/net/html"
)
// cssDecl is a CSS declaration that applies to an element,
// with what orders it in the cascade.
type cssDecl struct {
Property string
Value string
Important bool
// invalid is whether the value is invalid, as with a var()
// of a custom property in a cycle.
invalid bool
origin css.Origin
specificity int
order int
// container is the condition of the @container rule that the
// declaration is in, if any (see [Context.containerMatches]).
container *css.ContainerCond
// rule is the index of the style rule of the declaration in the
// rules of the context plus one, or 0 if it is not of a rule (see
// [Context.Restyle]).
rule int
}
// rank returns the rank of the declaration in the cascade,
// before the specificity and order: important declarations
// come after the others, with those of the user agent last.
func (d *cssDecl) rank() int {
if !d.Important {
return int(d.origin)
}
if d.origin == css.OriginUserAgent {
return 10
}
return 5 + int(d.origin)
}
// addRules adds the rules of the given style sheet with the given
// origin to the declarations of the elements under root that they select.
func (c *Context) addRules(root *html.Node, ss *douceur.Stylesheet, origin css.Origin) {
if c.styles == nil {
c.styles = map[*html.Node][]*cssDecl{}
}
c.addRuleList(root, ss.Rules, origin)
}
// addRuleList adds the given rules, including those in @media rules
// that match and in @supports rules.
func (c *Context) addRuleList(root *html.Node, rules []*douceur.Rule, origin css.Origin) {
for _, rule := range rules {
if rule.Kind == douceur.AtRule {
switch strings.ToLower(rule.Name) {
case "@media":
if c.mediaMatches(rule.Prelude) {
c.addRuleList(root, rule.Rules, origin)
}
case "@container":
prev := c.curContainer
c.curContainer = css.ParseContainerCond(rule.Prelude, prev)
c.addRuleList(root, rule.Rules, origin)
c.curContainer = prev
case "@supports", "@layer", "@scope":
if cond, ok := strings.CutPrefix(strings.TrimSpace(rule.Prelude), css.ContainerMark); ok {
prev := c.curContainer
c.curContainer = css.ParseContainerCond(cond, prev)
c.addRuleList(root, rule.Rules, origin)
c.curContainer = prev
continue
}
if strings.ToLower(rule.Name) == "@supports" && !css.SupportsMatches(rule.Prelude) {
continue
}
c.addRuleList(root, rule.Rules, origin)
case "@font-face":
if c.WebFonts {
c.addFontFace(rule.Declarations)
}
case "@import":
// url("x") or "x", and a media query list
url, media := css.ImportURL(rule.Prelude)
if url != "" && c.mediaMatches(media) {
c.addLinkedStyle(url)
}
}
continue
}
// the parser splits the selectors at commas in parentheses,
// as in :is(a, b), so they are split from the prelude
selectors := rule.Selectors
if strings.Contains(rule.Prelude, "(") {
selectors = css.SplitSelectors(rule.Prelude)
}
for _, sel := range selectors {
sel = strings.TrimSpace(sel)
kind := css.ScopeAll
if c.curScope != nil {
var ok bool
if sel, kind, ok = css.ScopedSelector(sel); !ok {
continue
}
} else if strings.Contains(sel, ":host") || strings.Contains(sel, "::slotted") {
continue // (of shadow trees only)
} else if origin == css.OriginUserAgent {
kind = css.ScopeAny // (the styles of the user agent apply to all)
}
c.curScopeKind = kind
if strings.Contains(sel, ":hover") {
c.addHoverTrigger(sel)
}
if base, kind, ok := css.PseudoSelector(sel); ok {
c.addPseudoRule(root, base, kind, rule.Declarations, origin)
continue
}
spec := css.Specificity(sel)
cs := css.CompileSelector(sel)
if cs != nil {
spec = cs.Specificity
c.recordRule(root, sel, cs, rule.Declarations, origin, spec)
}
if !c.recordOnly && !c.deferMatch { // (see Context.addedStyle and Context.ReuseStyles)
if kind == css.ScopeHost {
if cs != nil && c.selMatch(cs, c.curScope) {
c.addDecls(c.curScope, rule.Declarations, origin, spec)
}
} else {
for _, n := range c.selectNodes(root, sel) {
if c.inScope(n, c.curScope, kind) {
c.addDecls(n, rule.Declarations, origin, spec)
}
}
}
}
c.curScopeKind = css.ScopeAll
c.curRule = 0
}
}
}
// addDecls adds the given declarations to the given node.
func (c *Context) addDecls(n *html.Node, decls []*douceur.Declaration, origin css.Origin, spec int) {
custom := false
for _, d := range decls {
prop, value := css.PropertyName(d.Property), strings.TrimSpace(d.Value)
if !css.ValidDeclaration(prop, value) {
continue // dropped, so that the declaration before it applies
}
c.cssOrder++
c.noteVars(value)
custom = custom || strings.HasPrefix(prop, "--")
c.styles[n] = append(c.styles[n], &cssDecl{Property: prop,
Value: c.absoluteURLs(value), Important: d.Important, origin: origin, specificity: spec, order: c.cssOrder,
container: c.curContainer, rule: c.curRule})
}
if custom {
// (the memo has the values of custom properties only, which the
// hints and inline styles of each element, as they were added,
// otherwise cleared for each element, so that each var() looked
// up the elements that it is in again)
c.varMemo = nil
}
if c.curContainer != nil {
if c.containerQueried == nil {
c.containerQueried = map[*html.Node]bool{}
}
c.containerQueried[n] = true
}
delete(c.sorted, n)
}
// addHint adds a declaration of a presentational attribute to the node.
func (c *Context) addHint(n *html.Node, prop, value string) {
c.addDecls(n, []*douceur.Declaration{{Property: prop, Value: value}}, css.OriginHint, 0)
}
// declarations returns the declarations that apply to the given node, in
// the order of the cascade, so that the last one of each property wins.
func (c *Context) declarations(n *html.Node) []*cssDecl {
if n == nil {
return nil
}
if c.sorted == nil {
c.sorted = map[*html.Node]bool{}
c.hinted = map[*html.Node]bool{}
}
if !c.hinted[n] {
c.hinted[n] = true
if n.Type == html.ElementNode {
c.addHints(n)
if st := GetAttr(n, "style"); st != "" {
c.addInline(n, st)
}
}
}
if !c.sorted[n] {
c.sorted[n] = true
ds := c.styles[n]
defer c.resolveVars(n, ds)
sort.SliceStable(ds, func(i, j int) bool {
a, b := ds[i], ds[j]
if a.rank() != b.rank() {
return a.rank() < b.rank()
}
if a.specificity != b.specificity {
return a.specificity < b.specificity
}
return a.order < b.order
})
}
if c.containerQueried[n] {
return c.containerDecls(n, c.styles[n])
}
return c.styles[n]
}
// allDeclarations returns the declarations of the given node as
// [Context.declarations] does, but with those of all of its @container
// rules, whatever their conditions.
func (c *Context) allDeclarations(n *html.Node) []*cssDecl {
if n == nil {
return nil
}
if !c.containerQueried[n] {
return c.declarations(n)
}
c.declarations(n) // (sorted, with hints)
return c.styles[n]
}
// declaration returns the value of the given property for the given node
// from its declarations (not inherited), or "" if it has none.
func (c *Context) declaration(n *html.Node, prop string) string {
return declarationIn(c.declarations(n), prop)
}
// declarationIn returns the value of the given property in the given
// declarations, as [Context.declaration].
func declarationIn(ds []*cssDecl, prop string) string {
for ri := len(ds) - 1; ri >= 0; ri-- {
d := ds[ri]
if d.Property == prop {
if d.invalid {
return ""
}
if prop == "display" {
return css.LegacyDisplay(d.Value)
}
return d.Value
}
}
return ""
}
// lastDeclaration returns the property and value of the declaration of
// the given element that applies of those of the given properties (as a
// shorthand and its longhand): the last of them in the cascade, or "" if
// there is none (or it is invalid).
func (c *Context) lastDeclaration(n *html.Node, props ...string) (prop, value string) {
ds := c.declarations(n)
for ri := len(ds) - 1; ri >= 0; ri-- {
d := ds[ri]
if slices.Contains(props, d.Property) {
if d.invalid {
return d.Property, ""
}
return d.Property, d.Value
}
}
return "", ""
}
// ComputedValue returns the value of the given CSS property for the given
// element, as cascaded by the style sheets of the page that it was read
// with (with var() resolved): that of the declaration of the element that
// applies, or, for an inherited property (or one that is inherit), that
// of its nearest ancestor with one, or "" if there is none (as for the
// initial value). It is for the computed styles of scripts, which can
// convert its values (as colors and relative lengths) as they need.
func (c *Context) ComputedValue(n *html.Node, prop string) string {
prop = strings.TrimSpace(prop)
if strings.HasPrefix(prop, "--") { // custom properties are inherited
v, _ := c.customProperty(n, prop)
return strings.TrimSpace(v)
}
prop = strings.ToLower(prop)
for ; n != nil; n = n.Parent {
if n.Type != html.ElementNode {
continue
}
v := strings.TrimSpace(c.declaration(n, prop))
switch strings.ToLower(v) {
case "inherit":
continue
case "initial", "revert", "revert-layer":
return ""
case "unset":
if !css.InheritedProperties[prop] {
return ""
}
continue
case "":
if !css.InheritedProperties[prop] {
return ""
}
continue
}
return v
}
return ""
}
// addInline adds the declarations of the given style attribute.
func (c *Context) addInline(n *html.Node, style string) {
// our CSS parser is strict about semicolons, but
// they aren't needed in normal inline styles in HTML
if !strings.HasSuffix(strings.TrimSpace(style), ";") {
style += ";"
}
decls, err := parser.ParseDeclarations(style)
if err != nil {
return
}
c.addDecls(n, decls, css.OriginInline, 0)
}
// SetStyleAttr adds the declarations of the given style attribute
// string to the styles of the current node.
func (c *Context) SetStyleAttr(node *html.Node, style string) error {
if !strings.HasSuffix(strings.TrimSpace(style), ";") {
style += ";"
}
decls, err := parser.ParseDeclarations(style)
if err != nil {
return err
}
if c.styles == nil {
c.styles = map[*html.Node][]*cssDecl{}
}
c.addDecls(c.Node, decls, css.OriginInline, 0)
return nil
}
// selectNodes returns the nodes under root that the given selector selects,
// using the index of the nodes of root, which it makes for the first root
// (the nodes of a document do not change while it is read).
func (c *Context) selectNodes(root *html.Node, sel string) []*html.Node {
cs := css.CompileSelector(sel)
if cs == nil || cs.KeyKind == 0 {
return css.SelectNodes(root, sel)
}
if c.selIndex == nil || c.selIndex.Root != root {
c.selIndex = css.NewSelectorIndex(root)
}
var cands []*html.Node
switch cs.KeyKind {
case '#':
cands = c.selIndex.ByID[cs.Key]
case '.':
cands = c.selIndex.ByClass[cs.Key]
case 't':
cands = c.selIndex.ByTag[cs.Key]
}
var matches []*html.Node
for _, n := range cands {
if c.selMatch(cs, n) {
matches = append(matches, n)
}
}
return matches
}
// resolveVars substitutes the values of the custom properties (variables)
// in the var() functions of the given declarations of the given node.
// A custom property whose value is in a cycle is invalid, as is a property
// with a var() of an invalid custom property and no fallback.
func (c *Context) resolveVars(n *html.Node, ds []*cssDecl) {
for _, d := range ds {
if !strings.Contains(d.Value, "var(") {
continue
}
var visiting map[string]bool
if strings.HasPrefix(d.Property, "--") {
visiting = map[string]bool{d.Property: true}
}
v, ok := c.substituteVars(n, d.Value, visiting)
if ok && d.Property == "font" && !css.FontShorthandValid(v) {
// a value of var() that is not a valid font, as a style and a
// family without a size, is invalid at computed-value time,
// which unsets the font (as the rules of reddit.com, whose
// headings had the font of a theme that had no size, which
// browsers draw in the font of the text around them)
ok = false
}
d.Value = v
d.invalid = !ok
}
}
// substituteVars returns the given value with its var() functions replaced
// by the values of the custom properties for the given node, which are
// inherited, or their fallback values, and whether it is valid. The names
// being substituted are in visiting: a reference to one is a cycle, which
// makes the value invalid.
func (c *Context) substituteVars(n *html.Node, value string, visiting map[string]bool) (string, bool) {
var sb strings.Builder
for {
i := strings.Index(value, "var(")
if i < 0 {
sb.WriteString(value)
return sb.String(), true
}
// the matching parenthesis
end, level := -1, 0
for j := i + 3; j < len(value); j++ {
if value[j] == '(' {
level++
} else if value[j] == ')' {
level--
if level == 0 {
end = j
break
}
}
}
if end < 0 {
return "", false
}
name, fallback, hasFallback := strings.Cut(value[i+4:end], ",")
name = strings.ToLower(strings.TrimSpace(name)) // property names are lowercase
if visiting[name] {
return "", false // a cycle
}
v, ok := c.customProperty(n, name)
if ok && strings.Contains(v, "var(") {
if visiting == nil {
visiting = map[string]bool{}
}
visiting[name] = true
v, ok = c.substituteVars(n, v, visiting)
delete(visiting, name)
}
if !ok {
if !hasFallback {
return "", false
}
v, ok = c.substituteVars(n, strings.TrimSpace(fallback), visiting)
if !ok {
return "", false
}
}
sb.WriteString(value[:i])
sb.WriteString(v)
value = value[end+1:]
}
}
// customProperty returns the value of the given custom property for the
// given node, from it or the nearest ancestor that declares it.
func (c *Context) customProperty(n *html.Node, name string) (string, bool) {
// the values of the elements on the way to the one that has it are
// memoized (see varMemo), as they are looked up for each var() of
// each element, through all of the elements that it is in
var path []*html.Node
found := func(v varValue) (string, bool) {
if strings.Contains(v.value, "var(") {
return v.value, v.ok // (not substituted yet, so not memoized)
}
if c.varMemo == nil {
c.varMemo = map[varKey]varValue{}
}
for _, p := range path {
c.varMemo[varKey{p, name}] = v
}
return v.value, v.ok
}
for p := n; p != nil; p = p.Parent {
if p.Type != html.ElementNode {
continue
}
if v, ok := c.varMemo[varKey{p, name}]; ok {
return found(v)
}
ds := c.styles[p]
if !c.hinted[p] || !c.sorted[p] {
ds = c.declarations(p)
}
path = append(path, p)
if d := c.customDecl(p, ds, name); d != nil {
if strings.EqualFold(strings.TrimSpace(d.Value), "initial") {
return found(varValue{}) // the guaranteed-invalid value, as when not set
}
return found(varValue{d.Value, !d.invalid})
}
}
return found(varValue{})
}
// varKey is the key of [Context.varMemo]: an element and the name of a
// custom property.
type varKey struct {
n *html.Node
name string
}
// varValue is the value of a custom property of an element (see
// [Context.customProperty]).
type varValue struct {
value string
ok bool
}
// customIndex is an index of the custom properties of the sorted
// declarations of an element (see [Context.customDecl]).
type customIndex struct {
ds []*cssDecl // the declarations that it is of
m map[string]*cssDecl // the last declaration of each custom property
}
// minCustomIndex is the number of declarations of an element from which
// its custom properties are indexed.
const minCustomIndex = 32
// customDecl returns the last of the given sorted declarations of the
// given element of the given property (a custom property), or nil. The
// custom properties of elements with many declarations are indexed, as
// they are looked up for each var() of the elements in them (as those of
// the root of nytimes.com, hundreds of them, which took seconds to scan
// in each read of its page). The index is made again when the
// declarations are others (or more).
func (c *Context) customDecl(n *html.Node, ds []*cssDecl, name string) *cssDecl {
if len(ds) < minCustomIndex {
for ri := len(ds) - 1; ri >= 0; ri-- {
d := ds[ri]
if d.Property == name {
return d
}
}
return nil
}
idx := c.customIndexes[n]
if idx == nil || len(idx.ds) != len(ds) || &idx.ds[0] != &ds[0] {
idx = &customIndex{ds: ds, m: map[string]*cssDecl{}}
for _, d := range ds {
if strings.HasPrefix(d.Property, "--") {
idx.m[d.Property] = d
}
}
if c.customIndexes == nil {
c.customIndexes = map[*html.Node]*customIndex{}
}
c.customIndexes[n] = idx
}
return idx.m[name]
}
// displayOf returns the display of the given node, with the children of
// flex and grid containers blockified, as in CSS:
// they are flex or grid items, which are block-level.
func (c *Context) displayOf(n *html.Node) string {
if c.Scripting && n != nil && n.Type == html.ElementNode && n.Data == "noscript" {
return "none" // its content is for browsers without scripts
}
if c.Unrendered != nil && n != nil && n.Type == html.ElementNode && c.Unrendered(n) {
return "none" // as a child of a shadow host that is in no slot
}
d := c.declaration(n, "display")
if n == nil || n.Type != html.ElementNode {
return d
}
parent := c.parentOf(n) // (in the composed tree, see shadow.go)
if parent == nil || parent.Type != html.ElementNode {
return d
}
// absolutely positioned and floating elements are blockified too
pos := c.declaration(n, "position")
if f := c.declaration(n, "float"); f != "" && f != "none" && pos != "absolute" && pos != "fixed" {
pos = "absolute"
}
switch pos {
case "absolute", "fixed":
switch d {
case "", "inline", "inline-block", "list-item":
return "block"
case "inline-flex":
return "flex"
}
}
// (the parent of an element whose own box is none, as a slot, is that of
// the box that its children are in)
for i := 0; i < 8 && parent != nil && parent.Type == html.ElementNode && c.declaration(parent, "display") == "contents"; i++ {
parent = c.parentOf(parent)
}
if parent == nil || parent.Type != html.ElementNode {
return d
}
switch c.declaration(parent, "display") {
case "flex", "inline-flex", "grid", "inline-grid":
switch d {
case "", "inline", "inline-block", "list-item", "flow-root":
return "block"
case "inline-flex":
return "flex"
case "inline-grid":
return "grid"
case "inline-table":
return "table"
}
}
if (d == "" || d == "inline") && richTags[n.Data] && n.Data != "br" && c.isInlineBox(n) {
return "inline-block" // a box of its own in its line (see isInlineBox)
}
return d
}
// addStyleSheets adds the style sheets of the style and link elements of
// the document of the given root node, in document order, so that they
// apply to all of the elements, as in browsers, wherever they are.
func (c *Context) addStyleSheets(root *html.Node) {
var walk func(n *html.Node)
walk = func(n *html.Node) {
if n.Type == html.ElementNode {
switch n.Data {
case "template":
return
case "style":
c.recordSheet(n)
if c.mediaMatches(GetAttr(n, "media")) {
defer c.enterScope(n)()
c.addStyleOrigin(nodeText(n), css.OriginAuthor)
}
return
case "link":
c.recordSheet(n)
if strings.EqualFold(GetAttr(n, "rel"), "stylesheet") && c.mediaMatches(GetAttr(n, "media")) {
defer c.enterScope(n)()
c.addLinkedStyle(GetAttr(n, "href"))
}
return
case "svg":
return
}
}
for ch := n.FirstChild; ch != nil; ch = ch.NextSibling {
walk(ch)
}
}
walk(root)
}
// addLinkedStyle adds the style sheet at the given URL.
// Its URL is relative to the URL of the style sheet that it is in,
// cssBase, if it is imported by one, or else to the page.
func (c *Context) addLinkedStyle(href string) {
if strings.TrimSpace(href) == "" {
return // as in browsers (it would be the page itself)
}
u, err := parseRelativeURL(href, c.cssBaseURL())
if errors.Log(err) != nil {
return
}
if c.cssImports == nil {
c.cssImports = map[string]bool{}
}
if c.cssImports[u.String()] || len(c.cssImports) > 100 { // cycles
return
}
c.cssImports[u.String()] = true
resp, err := Get(c, u.String())
if logGetError(err) != nil {
return
}
defer resp.Body.Close()
if ct := strings.ToLower(resp.Header.Get("Content-Type")); ct != "" && !strings.Contains(ct, "css") && !strings.Contains(ct, "text/plain") && !strings.Contains(ct, "octet-stream") {
// as in browsers, a style sheet must be CSS (not, as for a link
// of a style sheet that is missing, a page of HTML, on which the
// CSS parser does not end)
return
}
b, err := io.ReadAll(resp.Body)
if errors.Log(err) != nil {
return
}
base := c.cssBase
c.cssBase = u.String()
c.addStyleOrigin(string(b), css.OriginAuthor)
c.cssBase = base
}
// absoluteURLs returns the given CSS value with the relative URLs of its
// url() functions made absolute, for the URL of the current style sheet
// (to which they are relative, as the icons of MDN in its style sheets),
// as they are used later relative to the page (see [Context.cssBaseURL]).
func (c *Context) absoluteURLs(v string) string {
if c.cssBase == "" || !strings.Contains(v, "url(") {
return v
}
return css.URLPattern.ReplaceAllStringFunc(v, func(m string) string {
sm := css.URLPattern.FindStringSubmatch(m)
u := sm[1] + sm[2] + sm[3]
if u == "" || strings.HasPrefix(u, "data:") || strings.HasPrefix(u, "#") {
return m
}
abs, err := parseRelativeURL(u, c.cssBase)
if err != nil {
return m
}
return `url("` + strings.ReplaceAll(abs.String(), `"`, `%22`) + `")`
})
}
// cssBaseURL returns the URL that the URLs in the current style sheet are
// relative to: the URL of the style sheet, or that of the page.
func (c *Context) cssBaseURL() string {
if c.cssBase != "" {
return c.cssBase
}
return c.PageURL
}
// addHoverTrigger adds the trigger of the given selector with :hover, if
// the compound selector with :hover is followed by others (as .menuItem of
// .menuItem:hover > a ~ .submenu): the hover of the elements that it
// selects changes the style of others (see [Context.HoverAffects]).
func (c *Context) addHoverTrigger(sel string) {
i := strings.Index(sel, ":hover")
if i < 0 {
return
}
isCombinator := func(b byte) bool { return b == ' ' || b == '>' || b == '+' || b == '~' }
depth, start := 0, 0
for j := i - 1; j >= 0; j-- {
switch sel[j] {
case ')':
depth++
case '(':
depth--
}
if depth == 0 && isCombinator(sel[j]) {
start = j + 1
break
}
}
end := len(sel)
depth = 0
for j := i + len(":hover"); j < len(sel); j++ {
switch sel[j] {
case '(':
depth++
case ')':
depth--
}
if depth == 0 && isCombinator(sel[j]) {
end = j
break
}
}
if strings.TrimSpace(sel[end:]) == "" {
return // the hovered element itself, which its widget shows
}
compound := strings.ReplaceAll(sel[start:end], ":hover", "")
if strings.TrimSpace(compound) == "" {
compound = "*"
}
if m, err := cascadia.Parse(css.RewriteSelector(compound)); err == nil {
c.hoverTriggers = append(c.hoverTriggers, m)
}
}
// HoverAffects returns whether the hover of the given element changes the
// styles of other elements, by the :hover selectors of the style sheets of
// the page that was read (as the menu items of pkg.go.dev, whose submenus
// are shown on their hover), for which an app that sets [Context.Hovered]
// reads the page again when the hover of the element changes.
func (c *Context) HoverAffects(n *html.Node) bool {
if n == nil || n.Type != html.ElementNode {
return false
}
for _, m := range c.hoverTriggers {
if m.Match(n) {
return true
}
}
return false
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"strconv"
"strings"
"cogentcore.org/core/core"
"cogentcore.org/core/htmlcore/css"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/tree"
"golang.org/x/net/html"
)
// The CSS multi-column layout of an element (columns, column-count, and
// column-width) is approximated by moving its children into frames for
// the columns, side by side, filled in order and balanced by the length
// of their text (see [Context.arrangeColumns]). The number of columns is
// from column-count, or from column-width and an estimate of the width
// that the element has (from the viewport and the widths and spaces of
// the elements that it is in), as it is set when the page is read.
// columnCount returns the number of columns of the given element, or 0
// if it does not have a multi-column layout.
func (c *Context) columnCount(n *html.Node) int {
has := false
for _, d := range c.declarations(n) {
if d.Property == "columns" || d.Property == "column-count" || d.Property == "column-width" {
has = true
break
}
}
if !has {
return 0
}
env := c.readEnv()
count := 0
width := float32(0)
set := func(v string) {
if v == "auto" {
return
}
if i, err := strconv.Atoi(v); err == nil {
count = i
} else if px, ok := env.LengthPx(v); ok {
width = px
}
}
for _, d := range c.declarations(n) {
v := strings.ToLower(strings.TrimSpace(d.Value))
switch d.Property {
case "columns":
count, width = 0, 0
for f := range strings.FieldsSeq(v) {
set(f)
}
case "column-count":
count = 0
set(v)
case "column-width":
width = 0
set(v)
}
}
if width <= 0 {
if count > 1 {
return count
}
return 0
}
gap := float32(16) // the normal column gap is 1em
if g, ok := env.LengthPx(c.declaration(n, "column-gap")); ok {
gap = g
}
fit := int((c.availableWidth(env, n) + gap) / (width + gap))
if count > 0 {
fit = min(fit, count)
}
if fit < 2 {
fit = 0
}
if !c.checkingMedia { // it depends on the width of the viewport
if c.columnUses == nil {
c.columnUses = map[*html.Node]int{}
}
c.columnUses[n] = fit
}
return fit
}
// availableWidth returns an estimate of the width of the content of the
// given element, in px: that of the viewport, within the widths and max
// widths of it and the elements that it is in, less their spaces.
func (c *Context) availableWidth(env *css.LengthEnv, n *html.Node) float32 {
w := c.mediaWidth()
var chain []*html.Node
for p := n; p != nil && p.Type == html.ElementNode; p = p.Parent {
chain = append(chain, p)
}
for ri := len(chain) - 1; ri >= 0; ri-- { // from the top down
p := chain[ri]
// the spaces are outside of the width (of the content box)
for _, base := range []string{"padding", "margin"} {
l, r := c.horizontalSides(env, p, base)
w -= max(l, 0) + max(r, 0)
}
for _, prop := range []string{"width", "max-width"} {
if px, ok := env.LengthPx(c.declaration(p, prop)); ok && px > 0 {
w = min(w, px)
}
}
}
return max(w, 0)
}
// arrangeColumns moves the children of the given widget for the given
// element into frames for its columns, as above.
func (c *Context) arrangeColumns(n *html.Node, fr *core.Frame) {
count := c.columnCount(n)
if count < 2 {
return
}
// The content of an element with only one child (as a list in a div
// with columns, as for the references of Wikipedia) is that of the
// child, which is split into the columns, as in CSS.
for fr.NumChildren() == 1 {
k := frameOf(fr.Child(0))
ok := k != nil
if !ok || k.NumChildren() < 2 {
break
}
fr = k
}
kids := append([]tree.Node(nil), fr.Children...)
if len(kids) < 2 {
return
}
count = min(count, len(kids))
gap := units.Em(1)
if g, ok := c.readEnv().Length(c.declaration(n, "column-gap"), units.UnitPw); ok {
gap = g
}
fr.FinalStyler(func(s *styles.Style) {
s.Display = styles.Flex
s.Direction = styles.Row
s.Wrap = false
s.Align.Items = styles.Start
s.Gap.X = gap
})
// the weight of a child is the length of its text (as its height)
weights := make([]int, len(kids))
total := 0
for i, k := range kids {
w := 40
for d := range k.AsTree().All() {
if tx, ok := d.(*core.Text); ok {
w += len(tx.Text)
}
}
weights[i] = w
total += w
}
var cols []*core.Frame
for range count {
col := core.NewFrame(fr)
col.SetName("column")
tree.SetUniqueName(col)
c.Node = nil
c.browserStyler(nil, col, nil)
c.blocks[col].display = "block"
col.FinalStyler(func(s *styles.Style) {
s.Direction = styles.Column
s.Grow.X, s.Shrink.X = 1, 1
s.Min.X = units.Value{}
s.Max.X = units.Pw(100 / float32(count))
})
cols = append(cols, col)
}
// each column is filled up to its share of the total weight
ci, sum := 0, 0
for i, k := range kids {
if ci < count-1 && sum > 0 && sum+weights[i]/2 > total*(ci+1)/count {
ci++
}
tree.MoveToParent(k, cols[ci])
sum += weights[i]
}
}
// horizontalSides returns the left and right lengths in px of the given
// sides property (padding or margin) of the given element, from its
// declarations in the order of the cascade (with the shorthand).
func (c *Context) horizontalSides(env *css.LengthEnv, n *html.Node, base string) (left, right float32) {
px := func(v string) float32 {
l, _ := env.LengthPx(v)
return l
}
for _, d := range c.declarations(n) {
switch d.Property {
case base:
if vals := css.ExpandSides(css.SplitColors(d.Value)); len(vals) == 4 {
right, left = px(vals[1]), px(vals[3])
}
case base + "-left", base + "-inline-start":
left = px(d.Value)
case base + "-right", base + "-inline-end":
right = px(d.Value)
case base + "-inline":
fs := css.SplitColors(d.Value)
if len(fs) > 0 {
left, right = px(fs[0]), px(fs[len(fs)-1])
}
}
}
return
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"slices"
"strings"
"cogentcore.org/core/core"
"cogentcore.org/core/htmlcore/css"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles/units"
"golang.org/x/net/html"
)
// This file has the containers of CSS (container-type: size or
// inline-size), for the container query units (cqw, cqh, cqi, cqb, cqmin,
// cqmax), which are percentages of the size of the content box of the
// nearest container that an element is in. They are resolved when the
// element is styled, as the other lengths of CSS (in [css.LengthEnv]), from the
// size of its container in its last layout: after a layout in which the
// size of a container changed, the elements in it are styled again and
// laid out again (as for the screenshots of the platform features of
// github.com). Before the first layout of a container, they are of the
// viewport, as in CSS for an element that is in no container, or of the
// size that it had when the page was last read (see
// [Context.KeepContainerSizes]).
// containerFrame is the frame of an element that is a container.
type containerFrame struct {
core.Frame
// inline is whether only the width of the container is queried
// (container-type: inline-size), so that its height is not used.
inline bool
// size is the size of the content box of the container (in dots) in
// its last layout, which the elements in it are styled for, and prev
// is the size before it, for stopping sizes that alternate (set with
// the containerMu of ctx held, for [Context.KeepContainerSizes]).
size, prev math32.Vector2
// ctx is the context that read the container.
ctx *Context
}
// containerSizes are the sizes of a container (see [containerFrame]).
type containerSizes struct {
size, prev math32.Vector2
}
// KeepContainerSizes sets the containers of the page that the context
// reads, which is the document that the given context read, read again
// (as after its scripts change it), to start with the sizes that they had
// in its last layout, so that the elements in them are styled for those
// first, not for the viewport until they are laid out (as the panels of
// repositories of github.com, of font-size: 1cqw, which were shown at
// the size of the viewport each time that the page was read again).
// It can be called as the given context's page is laid out.
func (c *Context) KeepContainerSizes(prev *Context) {
if prev == nil {
return
}
prev.containerMu.Lock()
defer prev.containerMu.Unlock()
c.keptContainers = make(map[*html.Node]containerSizes, len(prev.containers))
for n, cf := range prev.containers {
if cf.size.X > 0 {
c.keptContainers[n] = containerSizes{cf.size, cf.prev}
}
}
}
// isContainer returns whether the given element is a container, and
// whether only its width is queried (container-type: inline-size).
//
// Its container-type is that of all of its declarations, of its @container
// rules whatever their conditions: the conditions of those of an element
// are those of the containers that it is in, which are found with this
// for each of the elements that it is in, so that with them, the
// declarations of each were found again for each element in it, and for
// each of its own (reading volkskrant.nl, of many @container rules, took
// 30s).
func (c *Context) isContainer(n *html.Node) (container, inline bool) {
ds := c.allDeclarations(n)
typ := strings.ToLower(declarationIn(ds, "container-type"))
if v := declarationIn(ds, "container"); v != "" { // name / type
if _, t, ok := strings.Cut(v, "/"); ok {
typ = strings.ToLower(t)
}
}
switch strings.TrimSpace(typ) {
case "size":
return true, false
case "inline-size":
return true, true
}
return false, false
}
// SizeFinal sizes the container, and when the size of its content box
// changed (by more than a dot) from the one that the elements in it were
// styled for, it styles them again for it, and lays them out again, after
// this render (not during the layout).
func (cf *containerFrame) SizeFinal() {
cf.Frame.SizeFinal()
sz := cf.Geom.Size.Actual.Content
if cf.inline {
sz.Y = 0
}
changed := func(a, b math32.Vector2) bool {
return math32.Abs(a.X-b.X) > 1 || math32.Abs(a.Y-b.Y) > 1
}
if !changed(sz, cf.size) || !changed(sz, cf.prev) && cf.prev != (math32.Vector2{}) {
return
}
cf.ctx.containerMu.Lock()
cf.prev, cf.size = cf.size, sz
cf.ctx.containerMu.Unlock()
cf.ctx.containersChanged()
cf.Defer(func() {
cf.Restyle()
cf.NeedsLayout()
})
}
// containerUnits returns the size of 1% of the width and the height of the
// nearest containers that the given widget is in (cqw and cqh), in dp, or
// the given ones (of the viewport) if it is in none, or none has been laid
// out yet.
func containerUnits(w core.Widget, vw, vh float64) (cqw, cqh float64) {
cqw, cqh = vw, vh
gotW, gotH := false, false
for p := w.AsTree().Parent; p != nil && (!gotW || !gotH); p = p.AsTree().Parent {
cf, ok := p.(*containerFrame)
if !ok {
continue
}
dp := cf.Styles.UnitContext.Dots(units.UnitDp)
if dp <= 0 || cf.size.X <= 0 {
continue
}
if !gotW {
cqw, gotW = float64(cf.size.X/dp/100), true
}
if !gotH && !cf.inline {
cqh, gotH = float64(cf.size.Y/dp/100), true
}
}
return
}
// frameOf returns the given widget as the frame of an element (a plain
// frame or that of a container), or nil if it is not one.
func frameOf(w any) *core.Frame {
switch f := w.(type) {
case *core.Frame:
return f
case *containerFrame:
return &f.Frame
}
return nil
}
// containerDecls returns the given declarations of the given element
// without those of @container rules whose conditions it does not match.
//
// They are kept for the element (see [queriedDecls]), as they are found
// for each of its properties, until its declarations or the containers
// change (see [Context.containersChanged]).
func (c *Context) containerDecls(n *html.Node, ds []*cssDecl) []*cssDecl {
if len(ds) == 0 {
return ds
}
c.containerQueryMu.Lock()
q, ok := c.queried[n]
gen := c.containerGen
c.containerQueryMu.Unlock()
if ok && q.gen == gen && q.first == ds[0] && q.n == len(ds) {
return q.decls
}
out := make([]*cssDecl, 0, len(ds))
for _, d := range ds {
if d.container == nil || c.containerMatches(n, d.container) {
out = append(out, d)
}
}
c.containerQueryMu.Lock()
if c.queried == nil {
c.queried = map[*html.Node]queriedDecls{}
}
c.queried[n] = queriedDecls{decls: out, first: ds[0], n: len(ds), gen: gen}
c.containerQueryMu.Unlock()
return out
}
// queriedDecls are the declarations of an element without those of the
// @container rules whose conditions it does not match (see
// [Context.containerDecls]), for its declarations of the given first one
// and number, and the given generation of the containers.
type queriedDecls struct {
decls []*cssDecl
first *cssDecl
n int
gen int
}
// containersChanged marks the declarations of the elements with
// @container rules to be found again (see [Context.containerDecls]), as a
// container has been read, or styled, or resized.
func (c *Context) containersChanged() {
c.containerQueryMu.Lock()
c.containerGen++
c.containerQueryMu.Unlock()
}
// containerMatches returns whether the given element matches the given
// @container condition: of the width of its nearest container (of that
// name) in its last layout, as the container query units (see
// [containerUnits]), or of the viewport before it is laid out, as the
// spotlight cards of edition.cnn.com, whose aspect ratios were those of
// the last of their @container rules, which all applied.
func (c *Context) containerMatches(n *html.Node, cc *css.ContainerCond) bool {
for ; cc != nil; cc = cc.Outer {
width := c.mediaWidth()
for p := n.Parent; p != nil && p.Type == html.ElementNode; p = p.Parent {
if ok, _ := c.isContainer(p); !ok {
continue
}
if cc.Name != "" && !c.containerNamed(p, cc.Name) {
continue
}
if cf := c.containers[p]; cf != nil && cf.size.X > 0 {
if dp := cf.Styles.UnitContext.Dots(units.UnitDp); dp > 0 {
width = cf.size.X / dp
}
}
break
}
if !c.containerQueryMatches(cc.Query, width) {
return false
}
}
return true
}
// containerNamed returns whether the given container has the given name
// (of container-name, or the container shorthand).
func (c *Context) containerNamed(n *html.Node, name string) bool {
ds := c.allDeclarations(n) // (as for isContainer)
names := declarationIn(ds, "container-name")
if v := declarationIn(ds, "container"); v != "" {
names, _, _ = strings.Cut(v, "/")
}
return slices.Contains(strings.Fields(names), name)
}
// containerQueryKey is a query of an @container rule for a width of its
// container, for [Context.containerQueries].
type containerQueryKey struct {
query string
width, height float32
}
// containerQueryMatches returns whether the given query of an @container
// rule matches for the given width of its container. The matches are kept,
// as the queries are matched for each property of the elements that they
// are for (see [Context.declaration]), and parsed each time.
func (c *Context) containerQueryMatches(query string, width float32) bool {
key := containerQueryKey{query, width, c.MediaHeight}
c.containerQueryMu.Lock()
m, ok := c.containerQueries[key]
c.containerQueryMu.Unlock()
if ok {
return m
}
saved, checking := c.MediaWidth, c.checkingMedia
c.MediaWidth, c.checkingMedia = width, true
m = c.mediaListMatches(strings.ToLower(query))
c.MediaWidth, c.checkingMedia = saved, checking
c.containerQueryMu.Lock()
if c.containerQueries == nil {
c.containerQueries = map[containerQueryKey]bool{}
}
c.containerQueries[key] = m
c.containerQueryMu.Unlock()
return m
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"io"
"net/http"
neturl "net/url"
"os"
"path"
"path/filepath"
"runtime"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/andybalholm/cascadia"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/htmlcore/css"
"cogentcore.org/core/styles"
"cogentcore.org/core/system"
"cogentcore.org/core/tree"
"github.com/yuin/goldmark/v2/ast"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
// Context contains context information about the current state of a htmlcore
// reader and its surrounding context. It should be created with [NewContext].
type Context struct {
// Node is the node that is currently being read.
Node *html.Node
// RefreshURL is the URL of the first meta element with an http-equiv
// of refresh in the HTML read, if any, which an app that shows web pages
// can open next, as browsers do (as for a page that redirects browsers
// without JavaScript to another one). It must be reset before each read.
RefreshURL string
// Style is CSS that is added to the style sheets of each page that is
// read, before those of the page (as a user
// style sheet of a browser), as for the margins of an app's pages.
Style string
// Title is the text of the first title element in the HTML read,
// if any, as for the title of a window or tab that shows the page.
Title string
// MediaWidth, if positive, is the width of the viewport in CSS px (dp)
// that the @media rules of style sheets are for; otherwise, it is the
// width of the screen.
MediaWidth float32
// MediaHeight, if positive, is the height of the viewport in CSS px (dp)
// that vh lengths (and percentage heights of the viewport) are
// relative to; otherwise, they are relative to the height of the scene.
// Whether the page used it is [Context.ViewportHeightUsed].
MediaHeight float32
// viewportHeightUsed is whether the page has used the height of the
// viewport (see [Context.ViewportHeightUsed]).
viewportHeightUsed atomic.Bool
// Zoom, if positive, is the zoom factor of the page, as in browsers:
// all of its sizes are multiplied by it (see
// [styles.Style.Zoom]). MediaWidth and MediaHeight are then the size of
// the viewport divided by it, as its CSS px are larger (or smaller).
Zoom float32
// WebFonts is whether the web fonts of the @font-face rules of the
// style sheets of pages are loaded (once for each URL, for all pages),
// and used for the font families that they are for (see
// [fonts.AddWebFont]). Fonts in the WOFF2 format need a [FontDecoder].
WebFonts bool
// Scripting is whether the scripts of the pages are run (by the app
// that reads them, as htmlcore does not run them): the HTML is then
// parsed with scripting enabled (see [ParseHTML]), and noscript
// elements are not displayed, as in browsers with JavaScript.
Scripting bool
// Checked, if set, returns whether the given checkbox or radio input
// element is checked, for the :checked selector of CSS, as for a control
// that the user or a script has checked (as the CSS menus of Wikipedia,
// which show when their hidden checkbox is checked). By default, it is
// the checked attribute (the initial state).
Checked func(n *html.Node) bool
// Unrendered, if set, returns whether the given element is not rendered
// for a reason outside of its styles, as a child of an element with a
// shadow root (made by a script) that it is not assigned to a slot of,
// as the closed dropdown panels of the menus of MDN, which its shadow
// root shows (in a slot) only when they are open.
Unrendered func(n *html.Node) bool
// ShadowScope, if set, returns the host of the shadow root whose tree
// the given node is in, or nil if it is in the document, for a page that
// is read as its composed tree, with the content of the shadow roots of
// elements in their place (see shadow.go). The rules of the style sheets
// of a shadow tree apply only to it, and those of the document not to it.
ShadowScope func(n *html.Node) *html.Node
// ComposedParent, if set, returns the parent of the given node in the
// composed tree of the page (see ShadowScope), as it was read, which is
// not its parent in the document for the content of shadow roots and
// the nodes in slots.
ComposedParent func(n *html.Node) *html.Node
// ToggleDetails, if set, toggles the given details element open or
// closed in the document that the page is read from (its open
// attribute), on a click of its summary, as for an app that runs
// scripts, which reads the page again then: its [open] selectors
// apply (as the rotated chevrons of the sidebar of MDN), and it stays
// open when the page is read again. It returns whether it toggled them:
// otherwise (or if it is not set), the details of the page that is read
// are shown or hidden in place (as when the scripts were stopped).
ToggleDetails func(n *html.Node) bool
// Hovered, if set, returns whether the mouse is over the given element
// (in it, or in an element in it), for the :hover selectors of CSS (as
// the submenus of pkg.go.dev, shown on the :hover of their menu items),
// as for an app that reads the page again when that changes for the
// elements for which [Context.HoverAffects] is true. Otherwise, :hover
// selects nothing.
Hovered func(n *html.Node) bool
// hoverTriggers are the parts of the selectors of the style sheets with
// :hover that are followed by others (as .menuItem of
// .menuItem:hover > .submenu), without :hover (see [Context.HoverAffects]).
hoverTriggers []cascadia.Sel
// NewParent is the current parent widget that children of
// the previously read element should be added to, if any.
NewParent core.Widget
// BlockParent is the current parent widget that non-inline elements
// should be added to.
BlockParent core.Widget
// TableParent is the current table being generated.
TableParent *core.Frame
// inlineParent is the current parent widget that inline
// elements should be added to; it must be got through
// [Context.InlineParent], as it may need to be constructed
// on the fly. However, it can be set directly.
inlineParent core.Widget
// PageURL, if not "", is the URL of the current page.
// Otherwise, there is no current page.
PageURL string
// OpenURL is the function used to open URLs,
// which defaults to [system.App.OpenURL].
OpenURL func(url string, e events.Event)
// OpenLink, if set, is used in place of OpenURL for the clicks on the
// frames of links (and the widgets in them), with the link element
// (as for a page with scripts, which get the click of the element
// that is clicked, not of another link to the same URL).
OpenLink func(link *html.Node, url string, e events.Event)
// GetURL is the function used to get resources from URLs,
// which defaults to [http.Get].
GetURL func(url string) (*http.Response, error)
// PostURL, if not nil, is the function used to open URLs with a POST
// request with the given body of the given content type, as for
// submitting forms with the POST method. If it is nil, those forms
// can not be submitted.
PostURL func(url, contentType string, body []byte, e events.Event)
// ElementHandlers is a map of handler functions for each HTML element
// type (eg: "button", "input", "p"). It is empty by default, but can be
// used by anyone in need of behavior different than the default behavior
// defined in [handleElement] (for example, for custom elements).
// If the handler for an element returns false, then the default behavior
// for an element is used.
ElementHandlers map[string]func(ctx *Context) bool
// WikilinkHandlers is a list of handlers to use for wikilinks.
// If one returns "", "", the next ones will be tried instead.
// The functions are tried in sequential ascending order.
// See [Context.AddWikilinkHandler] to add a new handler.
WikilinkHandlers []WikilinkHandler
// AttributeHandlers is a map of markdown render handler functions
// for custom attribute values that are specified in {tag: value}
// attributes prior to markdown elements in the markdown source.
// The map key is the tag in the attribute, which is then passed
// to the function, along with the markdown node being rendered.
// Alternative or additional HTML output can be written to the given writer.
// If the handler function returns true, then the default HTML code
// will not be generated.
AttributeHandlers map[string]func(ctx *Context, w io.Writer, node ast.Node, entering bool, tag, value string) bool
// markdown is the goldmark converter of markdown for this context,
// made once on first use by [MDToHTML].
markdown *Markdown
markdownOnce sync.Once
// OnTransition, if set, is called with the transitions of the
// properties of elements that a restyle (as for a change of a class by
// a script) starts, for the app to dispatch their transitionend events
// when they end (as Google sign-in waits for, to show its next step).
OnTransition func(ts []css.Transition)
// WidgetHandlers is a list of handler functions for each Widget,
// called in sequential order for each widget that is created,
// after it has been configured by the existing handlers etc.
// This allows for additional styling to be applied based on the
// type of widget, for example.
WidgetHandlers []func(w core.Widget)
// DelayedImageLoad causes images to be loaded at a delay.
// if not set, then they are loaded immediately.
DelayedImageLoad bool
// ImageCache, if non-nil, caches the decoded images of img elements
// by their resolved URL, so that rebuilding a page does not decode
// them again. It must only be set when [Context.GetURL] returns the
// same content for the same URL until the cache is reset. It is nil
// by default; see [NewImageCache].
ImageCache *ImageCache
// AsyncImages, if set, is how the images of the noscripts of lazy
// images (see Context.noscriptImage) are set as they are gotten in the
// background: it calls the given function, which sets them, with the
// lock of the widgets of the page held (or not, if the page is gone).
// If it is nil, they are gotten as the page is read.
AsyncImages func(f func())
// StageSize, if positive, is the size of the content of the body (in
// runes of text, with estimates for other elements) after which
// [ReadHTML] stops adding the widgets of its top-level elements,
// leaving the rest for [Context.ReadRest]. This allows the first part
// of a long page to be shown sooner.
StageSize int
// pageState is the state of the pages read with the context: their
// style sheets and the state of their widgets.
pageState
// readState is the state of the current read of HTML.
readState
// reading is whether HTML is being read, so that HTML read by an
// element handler meanwhile is read within that read (see [ReadHTML]).
reading bool
// keepRead has the elements that are kept as they are, with their old
// widgets, as elements are read again (see [Context.keptElements]).
keepRead map[*html.Node]core.Widget
// matchKept has the elements that may be kept as they are as elements
// are read again, whose declarations are found again only for
// themselves, not those in them (see [Context.shallowKept]).
matchKept map[*html.Node]bool
// matchAll is whether all of the elements in those whose declarations
// are found again are matched again (see [Context.invalidation]), as
// for rules added to the style sheets.
matchAll bool
// addRoot, if set (as elements are read again; see Context.Reread),
// adds the element that the given element is in that is read again
// for a change of it that its widgets can not be styled again for (as
// of its display or pseudo-elements), returning whether it can be.
addRoot func(n *html.Node) bool
}
// pageState is the state of the pages read with a [Context], which
// [Context.NewPage] starts anew: the style sheets and declarations of
// their elements, and the state of their widgets for styling them.
type pageState struct {
// selIndex is the index of the nodes of the document for selecting
// the nodes of style rules (see [Context.selectNodes]).
selIndex *css.SelectorIndex
// styles are the CSS declarations for each node, which are
// sorted in the order of the cascade by [Context.declarations].
styles map[*html.Node][]*cssDecl
// pseudoStyles are the declarations of the ::before and ::after
// pseudo-elements of the elements (see pseudo.go).
pseudoStyles map[pseudoKey][]*cssDecl
// sorted records the nodes whose declarations are sorted,
// and hinted those whose attributes have been added.
sorted, hinted map[*html.Node]bool
// customIndexes are the indexes of the custom properties of the
// elements with many declarations (see [Context.customDecl]).
customIndexes map[*html.Node]*customIndex
// fallback is why the last Reread or Restyle could not make its
// changes (see [Context.Fallback]).
fallback string
// varMemo has the values of the custom properties of elements, as
// they are inherited, for var() (see [Context.customProperty]). It is
// cleared when the declarations of any element change.
varMemo map[varKey]varValue
// cssOrder is the order of the last declaration added.
cssOrder int
// cssBase is the URL of the style sheet being added, if it is from a
// URL, which the URLs in it are relative to, and cssImports has the
// URLs of the style sheets that have been added (for cycles of @import).
cssBase string
cssImports map[string]bool
// tableRowState has the state of the rows of the tables being read
// (see [Context.endTableRow]).
tableRowState map[*html.Node]*tableRows
// hoverTargets are the elements after checkboxes and radio buttons,
// which show their hover when they are transparent (see
// [Context.handleHoverTarget]).
hoverTargets map[*html.Node]*core.Switch
// iconNodes are the elements that are the icons of text fields (see
// [Context.inputIcons]), which are not rendered themselves.
iconNodes map[*html.Node]bool
// curContainer is the condition of the @container rule whose rules
// are being added, containerQueried has the elements with declarations
// in such rules, and containers has the frames of the containers by
// their elements (see [Context.containerMatches]); keptContainers has
// the sizes that they start with (see [Context.KeepContainerSizes]),
// and containerMu guards the sizes of the containers in containers.
curContainer *css.ContainerCond
containerQueried map[*html.Node]bool
// curScope is the host of the shadow root of the style sheet whose
// rules are being added, if it is in a shadow tree (see shadowScope).
curScope *html.Node
curScopeKind css.ScopeKind
containers map[*html.Node]*containerFrame
keptContainers map[*html.Node]containerSizes
containerMu sync.Mutex
// styleMu guards the styles of the elements (their declarations and
// the state of reading them), which the stylers of the widgets of the
// context read (see [core.StyleLockProperty]) while they are found
// again without the lock of the widgets (see [Context.PrepareReread]).
styleMu sync.Mutex
// containerQueries are the matches of the queries of @container rules
// for the widths of their containers (see
// [Context.containerQueryMatches]), guarded by containerQueryMu.
containerQueries map[containerQueryKey]bool
// varsUsed are the custom properties that the declarations of the
// page use (with var()), for [Context.unusedCustomProps].
varsUsed map[string]bool
// attrsSelected are whether the style rules select elements by the
// attributes (see Context.inertAttr), for attrsRules rules.
attrsSelected map[string]bool
attrsRules int
containerQueryMu sync.Mutex
// queried are the declarations of the elements with @container rules
// that apply to them, for containerGen, the generation of the
// containers and the declarations (see [Context.containerDecls]),
// guarded by containerQueryMu.
queried map[*html.Node]queriedDecls
containerGen int
// sheets has the style and link elements whose style sheets have
// been added, and rereads is the number of times that elements have
// been read again (see [Context.Reread]).
sheets map[*html.Node]bool
rereads int
// sheetTexts are the texts of the style elements whose style sheets
// have been added, so that the rules added to them can be added (see
// [Context.addedStyle]), and recordOnly is set while they are, for
// their rules to be recorded but not applied to the elements, as
// [Context.Restyle] finds the declarations of the elements again.
sheetTexts map[*html.Node]string
recordOnly bool
// reuseFrom is the context whose matches of the style rules are
// reused, deferMatch is set while the rules are recorded but not yet
// matched for that, reused is how they were (see
// [Context.ReuseStyles]), and snaps has the states of the elements
// with which their declarations were found.
reuseFrom *Context
deferMatch bool
reused string
snaps map[*html.Node]nodeSnap
snapRoot *html.Node
// matchedRules is the number of the rules that the declarations of
// all of the elements are from (not those recorded since, as those
// added to style sheets, whose elements were not matched again).
matchedRules int
// matchedPseudo is the number of the rules of pseudo-elements that the
// declarations of the elements have been matched with, as matchedRules.
matchedPseudo int
// ancestorMasks are the masks of the keys of the ancestors of the
// elements, while they are kept (see [Context.keepAncestorMasks]).
ancestorMasks map[*html.Node]css.KeyMask
// addedShallow and addedDeep are the elements that the rules added to
// the style sheets select (see [Context.addedRuleTargets]), whose
// declarations are found again, with those in the deep ones (for the
// custom properties of the rules, which they inherit).
addedShallow, addedDeep []*html.Node
// rules are the style rules that have been added, in order, by which
// the declarations of elements are found again when they change (see
// [Context.Restyle]), with ruleIndex, and pseudoRules those of the
// pseudo-elements; curRule is the index of the rule being added plus
// one. relational is whether a rule has a :has() selector, which
// selects elements by those after and in them.
rules []*styleRule
ruleIndex *ruleIndex
pseudoRules []*pseudoRule
curRule int
relational bool
// elementWidgets has the widgets that are styled by the declarations
// of each element (see [Context.Restyle]).
elementWidgets map[*html.Node][]core.Widget
// nodeWidgets has the widgets of the controls of forms.
nodeWidgets map[*html.Node]core.Widget
// floatSiblings has whether the unstyled blocks in each element
// have floats in them, for flattensBlock.
floatSiblings map[*html.Node]bool
// linkFrames has the URLs of the links that are frames (blocks), by
// their nodes, for the widgets in them (see linkFrame).
linkFrames map[*html.Node]string
// flattened has the blocks that are flattened (see flattensBlock).
flattened map[*html.Node]bool
// rootFont is the font size of the html element in px, once it is known
// (see rootFontSize).
rootFont float32
// blocks has the margin collapsing state of the block widgets.
blocks map[core.Widget]*blockState
// mediaUses has the media query lists evaluated in reading the pages,
// with their results, and columnUses the numbers of columns estimated
// from the width of the viewport, for [Context.MediaChanged], while
// checkingMedia is whether it is evaluating them for another width.
mediaUses map[string]bool
columnUses map[*html.Node]int
checkingMedia bool
}
// readState is the state of a read of HTML by [ReadHTML].
type readState struct {
// tables has the widget of each table element.
tables map[*html.Node]*core.Frame
// stageSize is the size of the content of the body read so far.
stageSize int
// rest is the first top-level element of the body that has not been read,
// and restParent the widget that its widgets are added to.
rest *html.Node
restParent core.Widget
}
// HasRest returns whether [ReadHTML] has left elements to read with
// [Context.ReadRest] (see [Context.StageSize]).
func (c *Context) HasRest() bool {
return c.rest != nil
}
// ReadRest adds the widgets of the elements that [ReadHTML] left (see
// [Context.StageSize]), and returns the widget that they are added to
// and the index of the first child added, which need to be updated.
// The context must not have been used to read other HTML since.
func (c *Context) ReadRest() (core.Widget, int, error) {
if c.rest == nil {
return nil, 0, nil
}
n, parent := c.rest, c.restParent
c.rest, c.restParent = nil, nil
c.StageSize = 0
start := parent.AsTree().NumChildren()
c.reading = true
defer func() { c.reading = false }()
err := readHTMLNode(c, parent, n)
for _, k := range parent.AsTree().Children[start:] {
if w, ok := k.(core.Widget); ok {
c.lockStylesOf(w)
}
}
return parent, start, err
}
// stageAt returns whether the given node is a top-level element of the body
// that starts the rest of a staged body (see [Context.StageSize]), adding
// its size to the size of the body read so far otherwise. The rest starts at
// a block element, whose widgets are new children of the body.
func (c *Context) stageAt(n *html.Node) bool {
if c.StageSize <= 0 || n.Parent == nil || n.Parent.DataAtom != atom.Body {
return false
}
if c.stageSize >= c.StageSize && n.Type == html.ElementNode && stageBlocks[n.DataAtom] {
return true
}
c.stageSize += nodeSize(n)
return false
}
// stageBlocks are the block elements that the rest of a staged body can start at.
var stageBlocks = map[atom.Atom]bool{
atom.P: true, atom.H1: true, atom.H2: true, atom.H3: true, atom.H4: true, atom.H5: true, atom.H6: true,
atom.Ul: true, atom.Ol: true, atom.Pre: true, atom.Table: true, atom.Div: true, atom.Blockquote: true,
atom.Hr: true, atom.Section: true, atom.Figure: true, atom.Details: true, atom.Dl: true,
}
// nodeSize returns an estimate of the size of the content of the node, in
// runes of text, with fixed sizes for elements, larger for media.
func nodeSize(n *html.Node) int {
size := 0
switch n.Type {
case html.TextNode:
size = len(strings.TrimSpace(n.Data))
case html.ElementNode:
size = 40
switch n.DataAtom {
case atom.Img, atom.Video, atom.Iframe, atom.Svg, atom.Embed, atom.Object, atom.Canvas:
size = 2000
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
size += nodeSize(c)
}
return size
}
// NewContext returns a new [Context] with basic defaults.
func NewContext() *Context {
return &Context{
styles: map[*html.Node][]*cssDecl{},
OpenURL: func(url string, e events.Event) { system.TheApp.OpenURL(url) },
GetURL: getURL,
ElementHandlers: map[string]func(ctx *Context) bool{},
AttributeHandlers: map[string]func(ctx *Context, w io.Writer, node ast.Node, entering bool, tag, value string) bool{},
}
}
// Parent returns the current parent widget that a widget
// associated with the current node should be added to.
// It may make changes to the widget tree, so the widget
// must be added to the resulting parent immediately.
func (c *Context) Parent() core.Widget {
display := c.displayOf(c.Node)
var parent core.Widget
switch display {
case "inline", "inline-block", "":
parent = c.InlineParent()
default:
parent = c.BlockParent
c.inlineParent = nil
}
return parent
}
// config configures the given widget. It needs to be called
// on all widgets that are not configured through the [New]
// pathway.
func (c *Context) config(w core.Widget) {
wb := w.AsWidget()
for _, attr := range c.Node.Attr {
switch attr.Key {
case "id":
wb.SetName(attr.Val)
uniqueName(wb)
wb.SetProperty("id", attr.Val)
case "style": // in the cascade
default:
wb.SetProperty(attr.Key, attr.Val)
}
}
wb.SetProperty("tag", c.Node.Data) // this is needed by handleWidget in general
wb.SetProperty("node", c.Node) // for the grid-area of a grid item
}
// InlineParent returns the current parent widget that inline
// elements should be added to.
func (c *Context) InlineParent() core.Widget {
if c.inlineParent != nil {
return c.inlineParent
}
c.inlineParent = core.NewFrame(c.BlockParent)
c.inlineParent.AsTree().SetName("inline-container")
tree.SetUniqueName(c.inlineParent)
c.inlineParent.AsWidget().Styler(func(s *styles.Style) {
s.Grow.Set(1, 0)
})
return c.inlineParent
}
// addStyleOrigin adds the given CSS style string with the given origin.
func (c *Context) addStyleOrigin(style string, origin css.Origin) {
root := rootNode(c.Node)
if c.curScope != nil { // (of a style sheet of a shadow tree, see shadow.go)
root = c.curScope
}
c.addRules(root, css.Parse(style), origin)
}
// LinkButton is a helper function that makes the given button
// open the given link when clicked on, using [Context.OpenURL].
// The advantage of using this is that it does [tree.NodeBase.SetProperty]
// of "href" to the given url, allowing generatehtml to create an <a> element
// for HTML preview and SEO purposes. It also sets the tooltip to the URL.
//
// See also [Context.LinkButtonUpdating] for a dynamic version.
func (c *Context) LinkButton(bt *core.Button, url string) *core.Button {
bt.SetProperty("tag", "a")
bt.SetProperty("href", url)
bt.SetTooltip(url)
bt.OnClick(func(e events.Event) {
c.OpenURL(url, e)
})
return bt
}
// LinkButtonUpdating is a version of [Context.LinkButton] that is robust to a changing/dynamic
// URL, using an Updater and a URL function instead of a variable.
func (c *Context) LinkButtonUpdating(bt *core.Button, url func() string) *core.Button {
bt.SetProperty("tag", "a")
bt.Updater(func() {
u := url()
bt.SetProperty("href", u)
bt.SetTooltip(u)
})
bt.OnClick(func(e events.Event) {
c.OpenURL(url(), e)
})
return bt
}
// AddWidgetHandler adds given widget handler function
func (c *Context) AddWidgetHandler(f func(w core.Widget)) {
c.WidgetHandlers = append(c.WidgetHandlers, f)
}
func (c *Context) applyStyleRules(node *html.Node, w core.Widget) {
if node == nil || node.Type != html.ElementNode {
node = nil // text nodes only inherit
}
wb := w.AsWidget()
if node != nil {
if c.elementWidgets == nil {
c.elementWidgets = map[*html.Node][]core.Widget{}
}
c.elementWidgets[node] = append(c.elementWidgets[node], w)
}
decls := c.declarations(node)
for _, d := range decls {
if strings.HasPrefix(d.Property, "paginate-") {
wb.SetProperty(d.Property, d.Value)
}
}
c.browserStyler(node, w, decls)
}
// handleWidget applies accumulated style rules,
// and calls WidgetHandlers functions on given widget,
// in order added so last one has override priority.
func (c *Context) handleWidget(node *html.Node, w core.Widget) {
c.applyStyleRules(node, w)
c.handleFormWidget(node, w)
c.handleHoverTarget(node, w)
c.handleInLink(node, w)
for _, f := range c.WidgetHandlers {
f(w)
}
}
// NewPage returns a new context for reading a new page, with the settings
// of this context (as for media, styles, URLs, and handlers), but none of
// the state from reading a page (as its style sheets). A context that is
// used to read pages one after another (as in a browser) should get a new
// one for each page with this, so that nothing of one page affects the next.
func (c *Context) NewPage() *Context {
n := NewContext()
n.MediaWidth, n.MediaHeight, n.Zoom = c.MediaWidth, c.MediaHeight, c.Zoom
n.Scripting, n.WebFonts, n.Checked, n.Unrendered = c.Scripting, c.WebFonts, c.Checked, c.Unrendered
n.ToggleDetails, n.Hovered = c.ToggleDetails, c.Hovered
n.PageURL = c.PageURL
n.OpenURL, n.GetURL, n.PostURL = c.OpenURL, c.GetURL, c.PostURL
n.OpenLink = c.OpenLink
n.ElementHandlers = c.ElementHandlers
n.WikilinkHandlers = c.WikilinkHandlers
n.AttributeHandlers = c.AttributeHandlers
n.WidgetHandlers = c.WidgetHandlers
n.DelayedImageLoad = c.DelayedImageLoad
n.ImageCache = c.ImageCache
n.AsyncImages = c.AsyncImages
n.StageSize = c.StageSize
n.Style = c.Style
return n
}
// ViewportHeightUsed returns whether the page that the context has read
// used the height of the viewport ([Context.MediaHeight]): in vh lengths,
// percentage heights of the viewport (as html and body of height: 100%),
// or media queries of height, so that it is read again for another
// height of its viewport (as the footer of google.com, which was below
// the bottom of the viewport, as it was as high as the window).
func (c *Context) ViewportHeightUsed() bool {
return c.viewportHeightUsed.Load()
}
// UserAgent is the User-Agent header of the requests of the default
// [Context.GetURL] (see [SetRequestHeaders]). It has the form of the user
// agents of browsers, for the platform that the app runs on, naming
// Cogent Core: sites treat the "compatible; ...; +url" form of crawlers
// (and the default of the Go HTTP client) as bots. Scripts should report
// the same value (navigator.userAgent), since sites check that they match.
var UserAgent = "Mozilla/5.0 (" + userAgentPlatform() + ") AppleWebKit/537.36 (KHTML, like Gecko) CogentCore/1.0 Safari/537.36"
// userAgentPlatform returns the platform part of the [UserAgent], as
// browsers report it for the platform that the app runs on.
func userAgentPlatform() string {
switch runtime.GOOS {
case "windows":
return "Windows NT 10.0; Win64; x64"
case "linux":
return "X11; Linux x86_64"
case "android":
return "Linux; Android 10; K"
case "ios":
return "iPhone; CPU iPhone OS 17_0 like Mac OS X"
default:
return "Macintosh; Intel Mac OS X 10_15_7"
}
}
// AcceptLanguage is the Accept-Language header of the requests of the
// default [Context.GetURL] (see [SetRequestHeaders]), from the locale of
// the system (the LC_ALL, LC_MESSAGES, or LANG environment variable) or
// US English. Some sites send reduced pages to requests without it.
var AcceptLanguage = acceptLanguage(firstEnv("LC_ALL", "LC_MESSAGES", "LANG"))
// firstEnv returns the value of the first of the given environment
// variables that is set.
func firstEnv(names ...string) string {
for _, n := range names {
if v := os.Getenv(n); v != "" {
return v
}
}
return ""
}
// acceptLanguage returns the Accept-Language header for the given POSIX
// locale (as "fr_CA.UTF-8"): "fr-CA,fr;q=0.9,en;q=0.8". It is US English
// for the C and POSIX locales and for an empty one.
func acceptLanguage(locale string) string {
loc, _, _ := strings.Cut(locale, ".")
loc, _, _ = strings.Cut(loc, "@")
if loc == "" || loc == "C" || loc == "POSIX" {
return "en-US,en;q=0.9"
}
tag := strings.ReplaceAll(loc, "_", "-")
lang, _, _ := strings.Cut(tag, "-")
h := tag
if lang != tag {
h += "," + lang + ";q=0.9"
}
if lang != "en" {
h += ",en;q=0.8"
}
return h
}
// acceptHeader is the Accept header of requests, as browsers send it for
// pages (and accepted for their resources), without image/avif, which
// images cannot be decoded from (and which image servers send to those
// who accept it, as those of theguardian.com and nytimes.com, whose
// images were blank).
const acceptHeader = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"
// SetRequestHeaders sets the headers of the given request that browsers
// send: the [UserAgent], [AcceptLanguage], and Accept. (Accept-Encoding is
// set by the Go HTTP client, which decompresses the gzip responses.)
func SetRequestHeaders(req *http.Request) {
req.Header.Set("User-Agent", UserAgent)
req.Header.Set("Accept", acceptFor(req.URL))
req.Header.Set("Accept-Language", AcceptLanguage)
}
// acceptFor returns the Accept header of a request of the given URL: that
// of browsers for an image, style sheet or script (by the extension of its
// path), as the image servers of reddit.com send pages that show images to
// requests that accept pages (whose images were not shown), or else that
// of pages ([acceptHeader]).
func acceptFor(u *neturl.URL) string {
if u == nil {
return acceptHeader
}
switch strings.ToLower(path.Ext(u.Path)) {
case ".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".bmp", ".ico", ".avif", ".apng":
return imageAcceptHeader
case ".css":
return "text/css,*/*;q=0.1"
case ".js", ".mjs":
return "*/*"
}
return acceptHeader
}
// imageAcceptHeader is the Accept header of the requests of images, as
// browsers send it, without image/avif (see [acceptHeader]).
const imageAcceptHeader = "image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8"
// httpClient is the client of the default [Context.GetURL], with a timeout
// so that a server that does not respond does not stop the reading of a
// page (as a style sheet or image of the page).
var httpClient = &http.Client{Timeout: 15 * time.Second}
// getURL gets the given URL with an HTTP GET request, with the headers of
// [SetRequestHeaders].
func getURL(url string) (*http.Response, error) {
if strings.HasPrefix(url, "file:") {
return getFileURL(url)
}
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, err
}
SetRequestHeaders(req)
return httpClient.Do(req)
}
// getFileURL gets the local file at the given file: URL, as a response
// with the status of a server: 404 Not Found if it does not exist.
func getFileURL(rawURL string) (*http.Response, error) {
u, err := neturl.Parse(rawURL)
if err != nil {
return nil, err
}
path := u.Path
if runtime.GOOS == "windows" {
path = strings.TrimPrefix(path, "/") // file:///C:/dir
}
f, err := os.Open(path)
if err != nil {
return &http.Response{StatusCode: http.StatusNotFound, Status: "404 Not Found",
Body: io.NopCloser(strings.NewReader("")), Request: &http.Request{URL: u}}, nil
}
if fi, err := f.Stat(); err == nil && fi.IsDir() { // its index.html, as servers do
f.Close()
if f, err = os.Open(filepath.Join(path, "index.html")); err != nil {
return &http.Response{StatusCode: http.StatusNotFound, Status: "404 Not Found",
Body: io.NopCloser(strings.NewReader("")), Request: &http.Request{URL: u}}, nil
}
}
return &http.Response{StatusCode: http.StatusOK, Status: "200 OK", Body: f, Request: &http.Request{URL: u}}, nil
}
// TextElement returns the widget of the HTML element that the given text
// is the text of: the text itself if it has a "tag" property, or else the
// widget with a tag that it is in (possibly in an inline container of it),
// as the text of a paragraph or heading is in the frame of its element.
func TextElement(tx *core.Text) *core.WidgetBase {
if _, ok := tx.Property("tag").(string); ok {
return tx.AsWidget()
}
pw := core.AsWidget(tx.Parent)
if pw != nil && strings.HasPrefix(pw.Name, "inline-container") {
pw = core.AsWidget(pw.Parent)
}
if pw != nil {
if _, ok := pw.Property("tag").(string); ok {
return pw
}
}
return tx.AsWidget()
}
// TextTag returns the name of the HTML element that the given text is the
// text of (see [TextElement]), such as "h2" for the text of a heading,
// or "" if there is none.
func TextTag(tx *core.Text) string {
// note: checking ok, as a failed assertion of a nil value to a
// string is null instead of "" under goscript (js)
if tag, ok := TextElement(tx).Property("tag").(string); ok {
return tag
}
return ""
}
// TagTexts gives each text in the given widget the "tag" and "id"
// properties of the HTML element that it is the text of (see
// [TextElement]), if it does not have its own, as for printing it apart
// from the widget of its element (as in a PDF, which styles headings by
// their tags, and links to their ids).
func TagTexts(w core.Widget) {
for cw, cwb := range w.AsWidget().AllWidgets() {
tx, ok := cw.(*core.Text)
if !ok {
continue
}
if el := TextElement(tx); el != cwb {
for _, k := range []string{"tag", "id"} {
if v, ok := el.Property(k).(string); ok {
cwb.SetProperty(k, v)
}
}
}
}
}
// NodeOf returns the HTML node of the element that the given widget is
// for, or that of the nearest widget that it is in that has one (as for
// the text of an element), or nil if there is none. The nodes are those
// of the document that was read (see [ReadDocument]).
func NodeOf(w core.Widget) *html.Node {
for wb := w.AsWidget(); wb != nil; wb = core.AsWidget(wb.Parent) {
if n, ok := wb.Property("node").(*html.Node); ok && n != nil {
return n
}
}
return nil
}
// uniqueName makes the name of the given widget unique among its siblings
// (as for an id that is on more than one element of a page), as tree
// updates require (as of the inspector).
func uniqueName(wb *core.WidgetBase) {
p := wb.Parent
if p == nil {
return
}
for _, k := range p.AsTree().Children {
if k != wb.This && k.AsTree().Name == wb.Name {
tree.SetUniqueName(wb)
return
}
}
}
// openLink opens the URL of the given link element, with OpenLink if it
// is set, or else OpenURL.
func (c *Context) openLink(link *html.Node, url string, e events.Event) {
if c.OpenLink != nil && link != nil {
c.OpenLink(link, url, e)
return
}
c.OpenURL(url, e)
}
// LockStyles locks the styles of the elements of the context (see
// [Context.PrepareReread]), as for reading them without the lock of the
// widgets of the page, as the stylers of its widgets do (see
// [core.StyleLockProperty]); they must not be locked while the lock of the
// widgets is taken.
func (c *Context) LockStyles() { c.styleMu.Lock() }
// UnlockStyles unlocks the styles of the elements (see [Context.LockStyles]).
func (c *Context) UnlockStyles() { c.styleMu.Unlock() }
// lockStylesOf makes the given widget and those in it hold the lock of the
// styles of the context as they are styled (see [core.StyleLockProperty]).
func (c *Context) lockStylesOf(root core.Widget) {
for _, cwb := range root.AsWidget().AllWidgets() {
cwb.SetProperty(core.StyleLockProperty, &c.styleMu)
}
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"slices"
"strings"
"cogentcore.org/core/core"
"cogentcore.org/core/cursors"
"cogentcore.org/core/events"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/tree"
"golang.org/x/net/html"
)
// arrangeDetails makes the given widget for a details element open and
// close on a click of its summary (the first summary element in it), as
// browsers do without JavaScript: when it is closed (without the open
// attribute, at first), only its summary is shown. The summary has a
// disclosure marker (▸ or ▾), unless its list-style (type) is none.
func (c *Context) arrangeDetails(n *html.Node, fr *core.Frame) {
var summary *core.Frame
for _, k := range fr.Children {
if kf := frameOf(k); kf != nil && kf.Property("tag") == "summary" {
summary = kf
break
}
}
open := HasAttr(n, "open")
for _, k := range fr.Children {
if k == tree.Node(summary) {
continue
}
if kw, ok := k.(core.Widget); ok {
kw.AsWidget().FinalStyler(func(s *styles.Style) {
if !open {
s.Display = styles.DisplayNone
}
})
}
}
if summary == nil {
return
}
var marker *core.Text
if sn, _ := summary.Property("node").(*html.Node); sn != nil && c.declaration(sn, "display") == "list-item" &&
!c.noListMarker(sn) {
marker = core.NewText(summary).SetText("▸ ")
c.handleWidget(nil, marker)
marker.Styler(func(s *styles.Style) {
s.SetAbilities(false, abilities.Selectable) // not in a selection, as in browsers
})
kids := summary.Children
summary.Children = append([]tree.Node{marker}, kids[:len(kids)-1]...) // first
summary.FinalStyler(func(s *styles.Style) {
s.Direction = styles.Row // beside its content
s.Align.Items = styles.Start
})
}
setMarker := func() {
if marker != nil {
if open {
marker.SetText("▾ ")
} else {
marker.SetText("▸ ")
}
}
}
setMarker()
summary.Styler(func(s *styles.Style) {
// hoverable for summary:hover (as the highlight of the items of
// the sidebar of MDN)
s.SetAbilities(true, abilities.Clickable, abilities.Hoverable)
s.Cursor = cursors.Pointer
})
toggle := c.ToggleDetails
summary.OnClick(func(e events.Event) {
if toggle != nil && toggle(n) { // in the document, which is read again
return
}
e.SetHandled()
open = !open
setMarker()
fr.Update()
})
}
// noListMarker returns whether the given list item has no marker, by a
// list-style-type of none, or a list-style shorthand with none and no image
// (as the summaries of the tooltips of pkg.go.dev, with list-style: none).
func (c *Context) noListMarker(n *html.Node) bool {
// the longhand or the shorthand, whichever is last in the cascade
prop, v := c.lastDeclaration(n, "list-style-type", "list-style")
v = strings.ToLower(v)
if prop == "list-style-type" {
return strings.TrimSpace(v) == "none"
}
return slices.Contains(strings.Fields(v), "none") && !strings.Contains(v, "url(")
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"slices"
"strconv"
"strings"
"cogentcore.org/core/core"
"cogentcore.org/core/cursors"
"cogentcore.org/core/events"
"cogentcore.org/core/htmlcore/css"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/tree"
"golang.org/x/net/html"
)
// The widgets of an element are made by the builder of its kind, in
// handleElement: the document and metadata elements, blocks of text,
// list items (list.go), form controls (forms.go), replaced elements
// (images and svg, image.go), tables (table.go), inline elements of text
// (inline.go), and boxes for the other elements by their display. The
// children of an element are then read into the widget that its builder
// sets as [Context.NewParent], and the formatting contexts that arrange
// the widgets of the children (grid, multi-column, details) do so after
// they are read (see [Context.arrange]).
// documentTags are the elements of the document and its metadata, which
// are handled whatever their display (as head, which is not displayed).
var documentTags = map[string]bool{"style": true, "link": true, "script": true, "title": true,
"meta": true, "head": true, "html": true}
// boxTags are the elements that have a box even with a display of
// contents (as replaced elements and form controls).
var boxTags = map[string]bool{"html": true, "head": true, "body": true, "img": true, "input": true,
"button": true, "select": true, "textarea": true, "svg": true, "video": true, "audio": true, "iframe": true,
"canvas": true, "br": true}
// textBlockTags are the elements that are blocks of text, with
// a frame for their text and any other content.
var textBlockTags = map[string]bool{"pre": true, "p": true, "h1": true, "h2": true, "h3": true,
"h4": true, "h5": true, "h6": true, "hr": true, "dt": true, "dd": true, "figcaption": true,
"caption": true, "summary": true, "legend": true}
// clippedRows returns whether the given rows of a table (a row group or
// row) are positioned out of the table and clipped to nothing, as visually
// hidden headers for screen readers (as the thead.sr-only of the diffs of
// GitHub), which are then not in it, as in browsers, rather than a row of
// its grid (of which only the clip would hide the text).
func (c *Context) clippedRows(n *html.Node) bool {
pos := c.declaration(n, "position")
if pos != "absolute" && pos != "fixed" {
return false
}
return css.ZeroAreaClip("clip", strings.TrimSpace(c.declaration(n, "clip"))) ||
css.ZeroAreaClip("clip-path", strings.TrimSpace(c.declaration(n, "clip-path")))
}
// handleElement makes the widgets of the current node with the handler in
// [Context.ElementHandlers] for its tag, if any, or else with the builder
// of its kind.
func handleElement(ctx *Context) {
tag := ctx.Node.Data
if h, ok := ctx.ElementHandlers[tag]; ok && h(ctx) {
return
}
if ctx.iconNodes[ctx.Node] {
return // the icon of a text field (see [Context.inputIcons])
}
display := ctx.displayOf(ctx.Node)
if display == "none" && !documentTags[tag] {
return // not rendered, and neither are its children
}
if (tag == "thead" || tag == "tbody" || tag == "tfoot" || tag == "tr") && ctx.clippedRows(ctx.Node) {
return // (see clippedRows)
}
if display == "contents" && !boxTags[tag] {
// it has no box, and its children are in its parent
ctx.NewParent = ctx.BlockParent
ctx.inlineParent = nil
return
}
var newWidget core.Widget
switch tag {
case "html", "head":
ctx.NewParent = ctx.BlockParent
case "script", "link", "style":
// nothing is rendered, and the style sheets are added first
case "title":
// it is not rendered, but it is the title of the page (the first one)
if ctx.Title == "" {
ctx.Title = strings.Join(strings.Fields(ExtractText(ctx)), " ")
}
case "meta":
if strings.EqualFold(GetAttr(ctx.Node, "http-equiv"), "refresh") && ctx.RefreshURL == "" {
// content is "delay" or "delay;url=URL"
_, u, _ := strings.Cut(GetAttr(ctx.Node, "content"), ";")
u = strings.TrimSpace(u)
if len(u) > 4 && strings.EqualFold(u[:4], "url=") {
ctx.RefreshURL = strings.Trim(strings.TrimSpace(u[4:]), `'"`)
}
}
case "li":
// as a list item when its display is list-item (the default),
// also when it is blockified (as in a flex container)
if d := ctx.declaration(ctx.Node, "display"); d == "" || d == "list-item" {
handleListItem(ctx)
} else { // as a box of its display (as inline-flex), without a marker
newWidget = handleBox(ctx, tag, display)
}
case "select":
handleSelect(ctx)
case "button":
handleButton(ctx)
case "input":
if typ := strings.ToLower(GetAttr(ctx.Node, "type")); typ == "submit" || typ == "button" || typ == "reset" {
handleInputButton(ctx, typ)
} else {
newWidget = handleInput(ctx)
}
case "textarea":
// a text field, which wraps its text on lines (an editor is only
// for monospaced text)
tf := New[core.TextField](ctx).SetText(ExtractText(ctx)).SetType(core.TextFieldOutlined)
cssFieldBorder(tf)
fieldWidth(ctx.Node, tf)
tf.SetPlaceholder(GetAttr(ctx.Node, "placeholder"))
newWidget = tf
case "svg":
handleSVG(ctx)
case "img":
newWidget = handleImage(ctx, tag)
case "iframe":
newWidget = handleIframe(ctx)
case "video":
newWidget = handleVideo(ctx)
case "audio": // (with controls, as it is not displayed without them)
newWidget = handleAudio(ctx)
case "table":
newWidget = handleTable(ctx)
case "th", "td":
newWidget = handleCell(ctx, tag)
case "thead", "tbody", "tfoot", "tr":
ctx.NewParent = ctx.tableFor(ctx.Node)
case "colgroup", "col":
// the columns of a table, which have no boxes of their own (and
// the white space in a colgroup is not a cell of the table)
default:
switch {
case textBlockTags[tag]:
handleTextBlock(ctx, tag)
case slices.Contains(textTags, tag): // not in a run of inline content
handleInlineElement(ctx, tag, display)
default:
newWidget = handleBox(ctx, tag, display)
}
}
if newWidget != nil {
ctx.handleWidget(ctx.Node, newWidget)
}
}
// handleTextBlock handles an element that is a block of text (as p).
func handleTextBlock(ctx *Context, tag string) {
w := New[core.Frame](ctx)
ctx.NewParent = w
ctx.handleWidget(ctx.Node, w)
if p := ctx.Node.Parent; tag == "caption" && p != nil && p.Data == "table" {
// the caption is above the cells, across all of the columns
span := ctx.tableColumns(p)
w.FinalStyler(func(s *styles.Style) { s.ColSpan = span })
}
if p := ctx.Node.Parent; p != nil && p.Data != "table" && ctx.displayOf(ctx.Node) == "table-caption" {
// The caption of an element displayed as a table wraps in the
// width of the table without widening it, which for a figure is
// that of its image when it has a width (as for a thumbnail).
if iw := tableImageWidth(p); iw > 0 {
w.FinalStyler(func(s *styles.Style) { s.Max.X = units.Dp(iw); s.BoxSizing = styles.BoxBorderBox })
}
}
}
// handleInlineElement handles an inline element of text (as a or span)
// that is not in a run of inline content, with the given display.
func handleInlineElement(ctx *Context, tag, display string) {
switch display {
case "none":
return
case "", "inline":
if !ctx.isTextElement(ctx.Node) {
// an inline element with widgets in it, which are in the run
// of inline content that it is in
ctx.NewParent = ctx.Parent()
return
}
ctx.handleWidget(ctx.Node, handleTextTag(ctx))
return
}
w := New[core.Frame](ctx)
ctx.NewParent = w
ctx.handleWidget(ctx.Node, w)
if href := GetAttr(ctx.Node, "href"); tag == "a" && href != "" {
ctx.linkFrame(w, href)
}
}
// handleBox handles the other elements by their display: a block (or
// inline block) has a frame for its children, and the children of an
// inline element are in the run of inline content that it is in.
// It returns the new widget, if any.
func handleBox(ctx *Context, tag, display string) core.Widget {
switch {
case display == "contents" && tag != "body":
// it has no box, and its children are in its parent
ctx.NewParent = ctx.BlockParent
ctx.inlineParent = nil
case display == "block" && ctx.flattensBlock(ctx.Node):
// its children are in its parent, as it has no box of its own
ctx.NewParent = ctx.BlockParent
ctx.inlineParent = nil
case isBlockDisplay(display) || tag == "body" || strings.HasPrefix(display, "inline-"):
if container, inline := ctx.isContainer(ctx.Node); container {
w := New[containerFrame](ctx)
w.inline, w.ctx = inline, ctx
if ks, ok := ctx.keptContainers[ctx.Node]; ok {
w.size, w.prev = ks.size, ks.prev
}
if ctx.containers == nil {
ctx.containers = map[*html.Node]*containerFrame{}
}
ctx.containers[ctx.Node] = w
ctx.containersChanged()
ctx.NewParent = w
return w
}
w := New[core.Frame](ctx)
ctx.NewParent = w
return w
default:
ctx.NewParent = ctx.Parent()
}
return nil
}
// arrange arranges the widgets of the children of the given element in
// the given frame of it, after they are read, for the formatting contexts
// that place them other than in order: grid areas, multiple columns, and
// the content of details.
func (c *Context) arrange(n *html.Node, fr *core.Frame) {
switch c.displayOf(n) {
case "flex", "inline-flex", "grid", "inline-grid":
c.arrangeOrder(fr)
}
switch c.displayOf(n) {
case "flex", "inline-flex":
if strings.HasSuffix(c.flexDirection(n), "-reverse") {
// the items from the end (as the image of the lead story of
// theguardian.com, on the right of its text by row-reverse)
slices.Reverse(fr.Children)
}
}
switch c.displayOf(n) {
case "grid", "inline-grid":
c.arrangeGrid(n, fr)
case "block", "list-item", "flow-root", "inline-block":
c.arrangeColumns(n, fr)
}
if n.Data == "details" {
c.arrangeDetails(n, fr)
}
}
// arrangeOrder puts the children of the given flex or grid container in
// the order of their order property (stably: those of the same order are
// in the order of the document), as in CSS (as the images of the stories
// of npr.org, before their titles by an order of -1).
func (c *Context) arrangeOrder(fr *core.Frame) {
orders := map[tree.Node]int{}
for _, k := range fr.Children {
kw, ok := k.(core.Widget)
if !ok {
continue
}
if kn := NodeOf(kw); kn != nil {
if o, err := strconv.Atoi(strings.TrimSpace(c.declaration(kn, "order"))); err == nil && o != 0 {
orders[k] = o
}
}
}
if len(orders) == 0 {
return
}
slices.SortStableFunc(fr.Children, func(a, b tree.Node) int { return orders[a] - orders[b] })
}
// flexDirection returns the flex-direction of the given element, of the
// longhand or the flex-flow shorthand that is last in the cascade.
func (c *Context) flexDirection(n *html.Node) string {
prop, v := c.lastDeclaration(n, "flex-direction", "flex-flow")
v = strings.ToLower(strings.TrimSpace(v))
if prop == "flex-flow" {
for f := range strings.FieldsSeq(v) {
if strings.HasPrefix(f, "row") || strings.HasPrefix(f, "column") {
return f
}
}
return ""
}
return v
}
// linkFrame makes the given frame of an a element open the given URL.
func (c *Context) linkFrame(w *core.Frame, href string) {
if c.linkFrames == nil {
c.linkFrames = map[*html.Node]string{}
}
link := c.Node
c.linkFrames[link] = href
w.SetProperty("href", href)
w.SetTooltip(href)
w.Styler(func(s *styles.Style) {
s.SetAbilities(true, abilities.Clickable)
s.Cursor = cursors.Pointer
})
w.OnClick(func(e events.Event) {
e.SetHandled()
c.openLink(link, href, e)
})
}
// handleInLink makes the given widget of the given node, if it is in a
// link that is a frame (see linkFrame), open the link when clicked on, as
// the frame does: the widgets in it that can be pressed, as its text,
// otherwise get the clicks instead of the frame.
func (c *Context) handleInLink(node *html.Node, w core.Widget) {
c.handleInButton(node, w)
if len(c.linkFrames) == 0 {
return
}
for n := node; n != nil; n = n.Parent {
href, ok := c.linkFrames[n]
if !ok {
continue
}
if n == node {
if frameOf(w) != nil {
return // the link frame itself
}
}
wb := w.AsWidget()
wb.Styler(func(s *styles.Style) { s.Cursor = cursors.Pointer })
link := n
wb.OnClick(func(e events.Event) {
if e.IsHandled() {
return
}
e.SetHandled()
c.openLink(link, href, e)
})
return
}
}
// flattensBlock returns whether the given block element, in the flow of
// blocks of its parent, has no styles of its own (only its display), so
// that its children can be read into its parent. Then the floats in it
// are beside the blocks after it, as in CSS, where they are not limited
// to the block that they are in (as they are in core). Such blocks are
// common wrappers, as the section elements of Wikipedia.
func (c *Context) flattensBlock(n *html.Node) bool {
switch n.Data {
case "body", "html", "form", "a", "button", "label", "details", "dialog", "fieldset":
return false // they have widgets with a function
}
p := n.Parent
if p == nil || p.Type != html.ElementNode || p.Data == "html" {
return false
}
switch c.displayOf(p) {
case "block", "list-item", "flow-root", "table-cell":
default:
return false // a flex, grid, or table item
}
if !c.unstyledBlock(n) {
return false
}
// Only the blocks among siblings that have floats in them are
// flattened, so that the floats are beside all of their content.
if c.floatSiblings == nil {
c.floatSiblings = map[*html.Node]bool{}
}
if c.flattened[n] { // flattened already
return true
}
has, ok := c.floatSiblings[p]
if !ok && c.flattened[p] {
has, ok = true, true // in a flattened block, as beside its floats
}
if !ok {
for k := p.FirstChild; k != nil && !has; k = k.NextSibling {
if k.Type == html.ElementNode && c.unstyledBlock(k) {
has = c.hasFloatChild(k)
}
}
c.floatSiblings[p] = has
}
if has {
if c.flattened == nil {
c.flattened = map[*html.Node]bool{}
}
c.flattened[n] = true
}
return has
}
// unstyledBlock returns whether the given element has no declarations
// other than its display (and custom properties).
func (c *Context) unstyledBlock(n *html.Node) bool {
for _, d := range c.declarations(n) {
switch d.Property {
case "display", "unicode-bidi", "will-change", "orphans", "widows", "user-select", "-webkit-user-select":
default:
if !strings.HasPrefix(d.Property, "--") && !noBoxProperty(d.Property) {
return false
}
}
}
return c.displayOf(n) == "block"
}
// noBoxProperty returns whether the given property does not change the box
// of an element or what is drawn for it (as the animations and transitions
// of the rule for reduced motion of Wikipedia, for all elements, so that
// its sections were not flattened, and the next one was below the floats
// of one).
func noBoxProperty(prop string) bool {
for _, p := range []string{"animation", "transition", "scroll-", "page-break-", "break-"} {
if strings.HasPrefix(prop, p) {
return true
}
}
return false
}
// hasFloatChild returns whether the given element has a child that floats.
func (c *Context) hasFloatChild(n *html.Node) bool {
for k := n.FirstChild; k != nil; k = k.NextSibling {
if k.Type != html.ElementNode {
continue
}
if f := c.declaration(k, "float"); f != "" && f != "none" && c.displayOf(k) != "none" {
return true
}
}
return false
}
// handleInButton makes the text of the given widget, if it is in a button
// element (at the given node or in it), not selectable, as in browsers, so
// that the button gets the presses and clicks on it (as the toggles of the
// contents of Wikipedia, whose text is in elements in the button).
func (c *Context) handleInButton(node *html.Node, w core.Widget) {
if _, isText := w.(*core.Text); !isText {
return
}
for n := node; n != nil; n = n.Parent {
if n.Type == html.ElementNode && n.Data == "button" {
buttonText(w)
return
}
}
}
// buttonText makes the given text of a button not selectable, so that the
// button gets the presses and clicks on it.
func buttonText(w core.Widget) {
w.AsWidget().Styler(func(s *styles.Style) {
s.SetAbilities(false, abilities.Selectable, abilities.DoubleClickable, abilities.TripleClickable, abilities.LongPressable, abilities.Slideable)
})
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"strconv"
"strings"
"cogentcore.org/core/core"
"cogentcore.org/core/htmlcore/css"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/rich"
"golang.org/x/net/html"
)
// setFontSize sets the font size, relative to the inherited one.
func setFontSize(env *css.LengthEnv, s, ps *styles.Style, v string) {
inherited := s.Font.Size
if ps != nil {
inherited = ps.Font.Size
inherited.Value /= core.AppearanceSettings.FontSize / 100
}
scale := func(f float32) {
s.Font.Size = units.Value{Value: inherited.Value * f, Unit: inherited.Unit}
}
if px, ok := css.FontSizes[v]; ok {
s.Font.Size = units.Dp(px)
return
}
switch v {
case "smaller":
scale(1 / 1.2)
return
case "larger":
scale(1.2)
return
}
if before, ok := strings.CutSuffix(v, "%"); ok {
if f, err := strconv.ParseFloat(before, 32); err == nil {
scale(float32(f) / 100)
}
return
}
if before, ok := strings.CutSuffix(v, "rem"); ok {
if f, err := strconv.ParseFloat(before, 32); err == nil {
s.Font.Size = units.Dp(float32(env.Rem) * float32(f))
}
return
}
if before, ok := strings.CutSuffix(v, "em"); ok {
if f, err := strconv.ParseFloat(before, 32); err == nil {
scale(float32(f))
}
return
}
if l, ok := env.Length(v, units.UnitDp); ok {
s.Font.Size = l
}
}
// setFont sets the font shorthand: [style] [weight] size[/line-height] family,
// returning the family list if it is valid.
func setFont(st *cssState, s, ps *styles.Style, v string) string {
// the shorthand resets the properties that it does not set, as
// font-weight to normal, once it is valid (with a size and family)
fs := strings.Fields(v)
slant, weight := rich.SlantNormal, ""
for i, f := range fs {
lf := strings.ToLower(f)
switch {
case lf == "italic" || lf == "oblique":
slant = rich.Italic
case lf == "bold" || lf == "bolder" || lf == "lighter" || (len(lf) == 3 && lf[1] == '0' && lf[2] == '0'):
weight = lf
case lf == "normal" || lf == "small-caps":
case len(lf) > 0 && (lf[0] >= '0' && lf[0] <= '9' || lf[0] == '.') || css.FontSizes[lf] > 0:
s.Font.Slant = slant
s.Font.Weight = rich.Normal
if weight != "" {
css.SetFontWeight(s, ps, weight)
}
size, lh, _ := strings.Cut(lf, "/")
setFontSize(st.env, s, ps, size)
st.lineHeight = "normal"
if lh != "" {
st.lineHeight = lh
}
family := strings.Join(fs[i+1:], " ")
s.Font.Family = css.FontFamily(family)
return family
}
}
return ""
}
// rootFontSize returns the font size of the html element of the page in px,
// which rem lengths are relative to (16 unless the page sets it), as the
// html element has no widget.
func (c *Context) rootFontSize() float32 {
if c.rootFont > 0 {
return c.rootFont
}
c.rootFont = 16
if c.Node == nil {
return c.rootFont
}
root := rootNode(c.Node)
var htmlNode *html.Node
if root.Type == html.ElementNode && root.Data == "html" {
htmlNode = root
}
for n := root.FirstChild; n != nil && htmlNode == nil; n = n.NextSibling {
if n.Type == html.ElementNode && n.Data == "html" {
htmlNode = n
}
}
if htmlNode == nil {
return c.rootFont
}
v := strings.TrimSpace(strings.ToLower(c.declaration(htmlNode, "font-size")))
num := func(suffix string) (float32, bool) {
f, err := strconv.ParseFloat(strings.TrimSuffix(v, suffix), 32)
return float32(f), err == nil && strings.HasSuffix(v, suffix)
}
if f, ok := num("%"); ok {
c.rootFont = 16 * f / 100
} else if f, ok := num("rem"); ok {
c.rootFont = 16 * f
} else if f, ok := num("em"); ok {
c.rootFont = 16 * f
} else if f, ok := num("px"); ok {
c.rootFont = f
} else if px, ok := css.FontSizeKeywords[v]; ok {
c.rootFont = px
}
return c.rootFont
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"bytes"
"fmt"
"image/color"
"log/slog"
"mime/multipart"
"net/url"
"strconv"
"strings"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/colors"
"cogentcore.org/core/core"
"cogentcore.org/core/cursors"
"cogentcore.org/core/events"
"cogentcore.org/core/htmlcore/css"
"cogentcore.org/core/icons"
"cogentcore.org/core/keymap"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/text"
"cogentcore.org/core/tree"
"golang.org/x/net/html"
)
// The forms are submitted as browsers do, when a submit button is clicked
// or Enter is pressed in one of their text fields: with the GET method by
// opening the URL of their action with the values of their controls in the
// query, and with the POST method by [Context.PostURL].
// ancestorForm returns the form element that the given node is in.
func ancestorForm(n *html.Node) *html.Node {
for p := n.Parent; p != nil; p = p.Parent {
if p.Type == html.ElementNode && p.Data == "form" {
return p
}
}
return nil
}
// isSubmitter returns whether the given element submits its form.
func isSubmitter(n *html.Node) bool {
typ := strings.ToLower(GetAttr(n, "type"))
switch n.Data {
case "button":
return typ == "" || typ == "submit"
case "input":
return typ == "submit" || typ == "image"
}
return false
}
// handleFormWidget records the widget of the given node, and makes it
// submit its form, for the controls of forms.
func (c *Context) handleFormWidget(n *html.Node, w core.Widget) {
if n == nil || n.Type != html.ElementNode {
return
}
switch n.Data {
case "input", "button", "textarea", "select":
default:
return
}
if c.nodeWidgets == nil {
c.nodeWidgets = map[*html.Node]core.Widget{}
}
c.nodeWidgets[n] = w
if sw, ok := w.(*core.Switch); ok {
// the element after it, which shows the hover of a transparent
// control over it (see [Context.handleHoverTarget])
for k := n.NextSibling; k != nil; k = k.NextSibling {
if k.Type == html.ElementNode {
if c.hoverTargets == nil {
c.hoverTargets = map[*html.Node]*core.Switch{}
}
c.hoverTargets[k] = sw
break
}
}
}
if sw, ok := w.(*core.Switch); ok && strings.EqualFold(GetAttr(n, "type"), "radio") && GetAttr(n, "name") != "" {
// a radio button that is checked unchecks the others of its group
// (with its name, in its form or outside of forms)
sw.OnChange(func(e events.Event) {
if !sw.IsChecked() {
return
}
c.styleMu.Lock() // (for the widgets of the elements; see Context.LockStyles)
defer c.styleMu.Unlock()
for on, ow := range c.nodeWidgets {
osw, ok := ow.(*core.Switch)
if !ok || on == n || !strings.EqualFold(GetAttr(on, "type"), "radio") ||
GetAttr(on, "name") != GetAttr(n, "name") || ancestorForm(on) != ancestorForm(n) {
continue
}
if osw.IsChecked() {
osw.SetChecked(false)
osw.NeedsRender()
}
}
})
}
form := ancestorForm(n)
if form == nil {
return
}
if isSubmitter(n) {
w.AsWidget().OnClick(func(e events.Event) {
e.SetHandled()
c.submitForm(form, n, e)
})
return
}
if tf, ok := w.(*core.TextField); ok && n.Data != "textarea" { // enter submits, but not in a textarea
tf.OnFirst(events.KeyChord, func(e events.Event) {
if kf := keymap.Of(e.KeyChord()); kf == keymap.Enter || kf == keymap.Accept {
e.SetHandled()
c.submitForm(form, nil, e)
}
})
}
}
// submitForm submits the given form, with the given submit button,
// if it was submitted by one: with the GET method, by opening the URL of
// its action with the values of its controls in the query, and with the
// POST method, by [Context.PostURL] with them in the body.
func (c *Context) submitForm(form, submitter *html.Node, e events.Event) {
c.styleMu.Lock() // (for the widgets of the elements; see Context.LockStyles)
defer c.styleMu.Unlock()
// the method, action and encoding, which the submit button can override
attr := func(name string) string {
if submitter != nil && HasAttr(submitter, "form"+name) {
return GetAttr(submitter, "form"+name)
}
return GetAttr(form, name)
}
method := strings.ToLower(attr("method"))
post := method == "post"
if method != "" && method != "get" && !post || post && c.PostURL == nil {
slog.Error("htmlcore: forms with this method can not be submitted", "method", method)
return
}
// the values of the controls, in order
var names, values []string
var walk func(n *html.Node)
walk = func(n *html.Node) {
if n.Type == html.ElementNode {
if name := GetAttr(n, "name"); name != "" && !HasAttr(n, "disabled") {
if v, ok := c.controlValue(n, submitter); ok {
names = append(names, name)
values = append(values, v)
}
}
}
for ch := n.FirstChild; ch != nil; ch = ch.NextSibling {
walk(ch)
}
}
walk(form)
// the URL of the action
action := attr("action")
if action == "" {
action = c.PageURL
}
u, err := parseRelativeURL(action, c.PageURL)
if err != nil {
slog.Error("htmlcore: invalid form action", "action", action, "err", err)
return
}
if post {
contentType, body := encodeForm(strings.ToLower(attr("enctype")), names, values)
c.PostURL(u.String(), contentType, body, e)
return
}
u.RawQuery = urlEncode(names, values)
c.OpenURL(u.String(), e)
}
// urlEncode returns the given names and values encoded as for a query,
// in their order.
func urlEncode(names, values []string) string {
var b strings.Builder
for i, name := range names {
if i > 0 {
b.WriteByte('&')
}
b.WriteString(url.QueryEscape(name))
b.WriteByte('=')
b.WriteString(url.QueryEscape(values[i]))
}
return b.String()
}
// encodeForm returns the content type and body of a POST request for the
// given names and values of the controls of a form, with the given
// encoding (its enctype attribute).
func encodeForm(enctype string, names, values []string) (string, []byte) {
switch enctype {
case "multipart/form-data":
var b bytes.Buffer
w := multipart.NewWriter(&b)
for i, name := range names {
w.WriteField(name, values[i])
}
w.Close()
return w.FormDataContentType(), b.Bytes()
case "text/plain":
var b strings.Builder
for i, name := range names {
b.WriteString(name)
b.WriteByte('=')
b.WriteString(values[i])
b.WriteString("\r\n")
}
return "text/plain", []byte(b.String())
}
return "application/x-www-form-urlencoded", []byte(urlEncode(names, values))
}
// controlValue returns the value of the given form control element,
// and whether it has one to submit.
func (c *Context) controlValue(n, submitter *html.Node) (string, bool) {
w := c.nodeWidgets[n]
switch n.Data {
case "input":
typ := strings.ToLower(GetAttr(n, "type"))
switch typ {
case "submit", "image", "button", "reset":
if n != submitter {
return "", false
}
return GetAttr(n, "value"), true
case "checkbox", "radio":
checked := c.isChecked(n)
if w != nil {
checked = w.AsWidget().StateIs(states.Checked)
}
if !checked {
return "", false
}
if v := GetAttr(n, "value"); v != "" {
return v, true
}
return "on", true
}
if tf, ok := w.(*core.TextField); ok {
return tf.Text(), true
}
return GetAttr(n, "value"), true
case "button":
if n != submitter {
return "", false
}
return GetAttr(n, "value"), true
case "textarea":
if tf, ok := w.(*core.TextField); ok {
return tf.Text(), true
}
return nodeText(n), true
case "select":
if ch, ok := w.(*core.Chooser); ok && ch.CurrentIndex >= 0 {
return fmt.Sprint(ch.CurrentItem.Value), true
}
for o := range optionNodes(n) {
if HasAttr(o, "selected") {
return optionValue(o), true
}
}
for o := range optionNodes(n) {
return optionValue(o), true
}
}
return "", false
}
// optionNodes returns the option elements of a select element.
func optionNodes(sel *html.Node) func(yield func(*html.Node) bool) {
return func(yield func(*html.Node) bool) {
var walk func(n *html.Node) bool
walk = func(n *html.Node) bool {
for ch := n.FirstChild; ch != nil; ch = ch.NextSibling {
if ch.Type == html.ElementNode && ch.Data == "option" {
if !yield(ch) {
return false
}
} else if !walk(ch) {
return false
}
}
return true
}
walk(sel)
}
}
// optionValue returns the value of an option element.
func optionValue(o *html.Node) string {
if HasAttr(o, "value") {
return GetAttr(o, "value")
}
return strings.TrimSpace(nodeText(o))
}
// handleSelect handles a select element: a chooser of its options,
// which are not read as content.
func handleSelect(ctx *Context) {
ch := New[core.Chooser](ctx)
current := -1
for o := range optionNodes(ctx.Node) {
if HasAttr(o, "selected") && current < 0 {
current = len(ch.Items)
}
ch.Items = append(ch.Items, core.ChooserItem{Value: optionValue(o), Text: strings.TrimSpace(nodeText(o))})
}
ch.SetCurrentIndex(max(current, 0))
// with no appearance, the page draws its own arrow (as a background)
if a := ctx.declaration(ctx.Node, "appearance"); a == "none" || ctx.declaration(ctx.Node, "-webkit-appearance") == "none" {
ch.SetIndicator(icons.None)
}
alignDeclared := ctx.declaration(ctx.Node, "text-align") != ""
ctx.handleWidget(ctx.Node, ch)
// as in browsers, the text of the current option is at the start, on
// one line with the arrow at the end, in a select of any display (as
// the navigation select of pkg.go.dev, a block of 100% width)
ch.FinalStyler(func(s *styles.Style) {
s.Display = styles.Flex
s.Direction = styles.Row
s.Wrap = false
s.Align.Items = styles.Center
s.Justify.Content = styles.Start
if !alignDeclared {
s.Text.Align = text.Start
}
})
ch.Maker(func(p *tree.Plan) {
tree.AddInit(p, "text", func(w *core.Text) {
w.FinalStyler(func(s *styles.Style) {
s.Grow.X = 1
s.Text.Align = ch.Styles.Text.Align
})
})
})
}
// handleButton handles a button element: a block of its content,
// styled by CSS, that is clickable.
func handleButton(ctx *Context) {
w := New[core.Frame](ctx)
ctx.NewParent = w
ctx.handleWidget(ctx.Node, w)
w.Styler(func(s *styles.Style) {
// hoverable for the state layer of buttons when the mouse is over
// them (as the darkening of buttons in browsers, by their :hover)
s.SetAbilities(true, abilities.Clickable, abilities.Hoverable)
s.Cursor = cursors.Pointer
})
}
// handleInputButton handles an input element of the given type that is
// a button (submit, button or reset): a block of its label, as a button.
func handleInputButton(ctx *Context, typ string) {
label := GetAttr(ctx.Node, "value")
if !HasAttr(ctx.Node, "value") {
label = map[string]string{"submit": "Submit", "reset": "Reset"}[typ]
}
w := New[core.Frame](ctx)
ctx.handleWidget(ctx.Node, w)
w.Styler(func(s *styles.Style) {
// hoverable for the state layer of buttons when the mouse is over
// them (as the darkening of buttons in browsers, by their :hover)
s.SetAbilities(true, abilities.Clickable, abilities.Hoverable)
s.Cursor = cursors.Pointer
})
tx := core.NewText(w).SetText(html.EscapeString(label))
ctx.handleWidget(nil, tx)
buttonText(tx) // the button gets the clicks on its label
}
// handleInput handles an input element.
func handleInput(ctx *Context) core.Widget {
var newWidget core.Widget
{
ityp := GetAttr(ctx.Node, "type")
val := GetAttr(ctx.Node, "value")
switch ityp {
case "number":
fval := float32(errors.Log1(strconv.ParseFloat(val, 32)))
sp := New[core.Spinner](ctx).SetValue(fval)
// a field of its value, as in browsers, which step it with
// the arrow keys (without the buttons of a spinner)
sp.SetType(core.TextFieldOutlined)
sp.SetLeadingIcon(icons.None).SetTrailingIcon(icons.None)
cssFieldBorder(&sp.TextField)
fieldWidth(ctx.Node, &sp.TextField)
newWidget = sp
case "checkbox", "radio":
// (SetState returns the WidgetBase, which is not the widget)
sw := New[core.Switch](ctx).SetType(core.SwitchCheckbox)
if ityp == "radio" {
sw.SetType(core.SwitchRadioButton)
}
sw.SetState(ctx.isChecked(ctx.Node), states.Checked)
newWidget = sw
case "range":
fval := float32(errors.Log1(strconv.ParseFloat(val, 32)))
newWidget = New[core.Slider](ctx).SetValue(fval)
case "button", "submit":
newWidget = New[core.Button](ctx).SetText(val)
case "color":
newWidget = colorInput(ctx, val)
case "datetime":
newWidget = core.Bind(val, New[core.TimeInput](ctx))
case "file":
newWidget = core.Bind(val, New[core.FileButton](ctx))
default:
// outlined, so that its borders are those of its CSS, on all
// sides (filled ones have only a line at the bottom)
tf := New[core.TextField](ctx).SetText(val).SetType(core.TextFieldOutlined)
tf.SetPlaceholder(GetAttr(ctx.Node, "placeholder"))
cssFieldBorder(tf)
fieldWidth(ctx.Node, tf)
tf.FinalStyler(func(s *styles.Style) { s.SetTextWrap(false) }) // an input is one line
ctx.inputIcons(ctx.Node, tf)
newWidget = tf
}
}
return newWidget
}
// fieldWidth sets the width of the given text field of the given input or
// textarea element to that of browsers when its CSS gives it none: of its
// size (or cols for a textarea) in characters, 20 by default, of the
// average width of a character of its font (0.55em, or 0.6em for the
// monospace font of a textarea, with its scrollbar), and the height of a
// textarea to its rows of text (2 by default). It does not
// grow (as a core text field does), as in browsers, where a text input was
// as wide as it could be, up to 40ch, in a row of controls (wider than the
// 156px of Chrome).
func fieldWidth(n *html.Node, tf *core.TextField) {
attr := "size"
if n.Data == "textarea" {
attr = "cols"
}
chars := 20
if v, err := strconv.Atoi(strings.TrimSpace(GetAttr(n, attr))); err == nil && v > 0 {
chars = v
}
rows := 0
if n.Data == "textarea" {
rows = 2
if v, err := strconv.Atoi(strings.TrimSpace(GetAttr(n, "rows"))); err == nil && v > 0 {
rows = v
}
}
w := units.Em(float32(chars) * 0.55)
if rows > 0 {
w = units.Em(float32(chars)*0.6 + 1.15) // and its scrollbar of 15px
}
// (before the styler of its CSS, which sets the width that it gives)
tf.Styler(func(s *styles.Style) {
if rows > 0 {
s.Min.Y = units.Em(float32(rows) * 1.2)
}
s.Min.X, s.Max.X = w, w
s.Grow.X = 0
})
// one that its CSS makes grow (as by flex-grow: 1, as the search field
// of pkg.go.dev, which fills the header) is not limited to it
tf.FinalStyler(func(s *styles.Style) {
if s.Grow.X > 0 && s.Max.X.Unit == w.Unit && s.Max.X.Value == w.Value {
s.Max.X = units.Value{}
}
})
}
// colorInput returns the widget of an input of type color with the given
// value: a swatch of the color with a border, of the size of that of
// browsers (50 by 27px in Chrome), which opens a color picker when it is
// clicked (it was a large button of Cogent Core, with a label and icon).
func colorInput(ctx *Context, val string) core.Widget {
cb := core.Bind(val, New[core.ColorButton](ctx))
cb.SetText("").SetIcon(icons.None)
// (before the styler of its CSS, which sets the sizes that it gives)
cb.Styler(func(s *styles.Style) {
s.Min.Set(units.Dp(48), units.Dp(25)) // (the content box, in CSS px)
s.Max = s.Min
s.Margin.Zero()
s.Padding.Zero()
s.BoxShadow, s.MaxBoxShadow = nil, nil // (the room of its shadow is around it)
s.Border.Width.Set(units.Dp(1))
s.Border.Color.Set(colors.Uniform(color.RGBA{0x76, 0x76, 0x76, 0xff}))
s.Border.Radius.Set(units.Dp(3))
s.MaxBorder = s.Border
})
return cb
}
// inputIcons makes the icons that are positioned over the given text input
// element the icons of its text field: elements after it with no content
// that are absolutely positioned and have an SVG mask or background image
// (as the search icon of the search field of Wikipedia, at its start). It
// is the leading icon for one at the left (or else the trailing one, for
// one at the right), with the padding of the field on its side as the
// space before the icon. The elements are not rendered.
func (c *Context) inputIcons(n *html.Node, tf *core.TextField) {
for s := n.NextSibling; s != nil; s = s.NextSibling {
if s.Type == html.TextNode && strings.TrimSpace(s.Data) == "" || s.Type == html.CommentNode {
continue
}
icon, side, ok := c.iconElement(s)
if !ok {
return
}
if c.iconNodes == nil {
c.iconNodes = map[*html.Node]bool{}
}
c.iconNodes[s] = true
inset := strings.TrimSpace(c.declaration(s, side))
env := c.readEnv()
pad, hasPad := env.Length(inset, units.UnitPw)
if side == "left" {
tf.SetLeadingIcon(icon)
} else {
tf.SetTrailingIcon(icon)
}
tf.FinalStyler(func(st *styles.Style) {
if !hasPad {
return
}
if side == "left" {
st.Padding.Left = pad
} else {
st.Padding.Right = pad
}
})
}
}
// iconElement returns the icon of the given element if it is an icon over
// a text input (see [Context.inputIcons]), and the side of the input that
// it is at ("left" or "right").
func (c *Context) iconElement(n *html.Node) (icon icons.Icon, side string, ok bool) {
if n.Type != html.ElementNode || c.declaration(n, "position") != "absolute" || c.displayOf(n) == "none" {
return
}
for k := n.FirstChild; k != nil; k = k.NextSibling {
if k.Type != html.TextNode || strings.TrimSpace(k.Data) != "" {
return // it has content
}
}
mask := true
u := css.MaskURL(c.declaration(n, "mask-image"))
if u == "" {
u = css.MaskURL(c.declaration(n, "-webkit-mask-image"))
}
if u == "" {
u = css.MaskURL(c.declaration(n, "mask"))
}
if u == "" {
u, mask = css.MaskURL(c.declaration(n, "background-image")), false
}
if u == "" {
return
}
src := c.maskSourceOf(u)
if src == nil || len(src.svg) == 0 {
return
}
svg := string(src.svg)
if mask { // the shape of a mask has the color of the text
for _, black := range []string{`fill="#000"`, `fill="#000000"`, `fill="black"`} {
svg = strings.ReplaceAll(svg, black, `fill="currentColor"`)
}
}
side = "left"
if c.declaration(n, "left") == "" && c.declaration(n, "right") != "" {
side = "right"
}
return icons.Icon(svg), side, true
}
// isChecked returns whether the given checkbox or radio input element is
// checked: from [Context.Checked] if it is set, or else its attribute.
func (c *Context) isChecked(n *html.Node) bool {
if c.Checked != nil {
return c.Checked(n)
}
return HasAttr(n, "checked")
}
// setCheckedAttrs sets the checked attributes of the checkbox and radio
// inputs of the given document to their state from [Context.Checked], if
// it is set, for the :checked selectors of the style sheets (the selector
// library matches the attribute), and returns a function that restores
// them.
func (c *Context) setCheckedAttrs(root *html.Node) func() {
if c.Checked == nil && c.Hovered == nil {
return func() {}
}
var changed []*html.Node
var hovered []*html.Node
var walk func(n *html.Node)
walk = func(n *html.Node) {
if c.Hovered != nil && n.Type == html.ElementNode && c.Hovered(n) {
n.Attr = append(n.Attr, html.Attribute{Key: css.HoverAttr}) // for :hover
hovered = append(hovered, n)
}
if c.Checked != nil && n.Type == html.ElementNode && n.Data == "input" {
if typ := strings.ToLower(GetAttr(n, "type")); typ == "checkbox" || typ == "radio" {
if c.Checked(n) != HasAttr(n, "checked") {
toggleAttr(n, "checked")
changed = append(changed, n)
}
}
}
for k := n.FirstChild; k != nil; k = k.NextSibling {
walk(k)
}
}
walk(root)
return func() {
for _, n := range changed {
toggleAttr(n, "checked")
}
for _, n := range hovered {
toggleAttr(n, css.HoverAttr)
}
}
}
// toggleAttr removes the given attribute of the given element if it has
// it, or else adds it (with no value).
func toggleAttr(n *html.Node, key string) {
for i, a := range n.Attr {
if a.Key == key && a.Namespace == "" {
n.Attr = append(n.Attr[:i], n.Attr[i+1:]...)
return
}
}
n.Attr = append(n.Attr, html.Attribute{Key: key})
}
// handleHoverTarget makes the widget of the given element show the hover
// of the control before it, if that is transparent: a checkbox or radio
// button over the element that shows it, as the hidden checkboxes of the
// menu buttons of Wikipedia (over their labels) and its radio buttons
// (over their icons), which browsers style with :hover of the control.
func (c *Context) handleHoverTarget(n *html.Node, w core.Widget) {
sw := c.hoverTargets[n]
if sw == nil {
return
}
delete(c.hoverTargets, n)
target := w.AsWidget()
hover := func(on bool) {
if sw.Styles.Opacity > 0 || target.StateIs(states.Hovered) == on {
return // a visible control shows its own hover
}
target.SetState(on, states.Hovered)
target.Restyle()
}
sw.On(events.MouseEnter, func(e events.Event) { hover(true) })
sw.On(events.MouseLeave, func(e events.Event) { hover(false) })
}
// cssFieldBorder makes the border of the given text field of an input (or
// textarea) that of its CSS when it has the focus too, with no space for
// the thicker border of an outlined field with the focus (which made it
// higher than its CSS height, as for the search box of duckduckgo.com).
func cssFieldBorder(tf *core.TextField) {
tf.FinalStyler(func(s *styles.Style) {
s.MaxBorder = s.Border
})
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"regexp"
"slices"
"strconv"
"strings"
"cogentcore.org/core/core"
"cogentcore.org/core/htmlcore/css"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/tree"
"golang.org/x/net/html"
)
// The CSS grid template areas of a grid container (grid-template-areas,
// or the areas of the grid-template shorthand) place its children with a
// grid-area at the rows and columns of their areas, which is done by
// ordering their widgets as a core grid places them, with spans and
// empty widgets for the empty cells (see [Context.arrangeGrid]).
// The column tracks (grid-template-columns, or the columns of the
// grid-template shorthand) size the children in the columns.
// gridArea is the rectangle of the cells of a named grid area.
type gridArea struct {
row, col, rows, cols int
}
// contains returns whether the given area is in this one.
func (a gridArea) contains(o gridArea) bool {
return o.row >= a.row && o.col >= a.col && o.row+o.rows <= a.row+a.rows && o.col+o.cols <= a.col+a.cols
}
// hasContent returns whether the given node has elements or text in it.
func hasContent(n *html.Node) bool {
for k := n.FirstChild; k != nil; k = k.NextSibling {
if k.Type == html.ElementNode || (k.Type == html.TextNode && strings.TrimSpace(k.Data) != "") {
return true
}
}
return false
}
// gridAreaStrings matches the quoted rows of grid template areas.
var gridAreaStrings = regexp.MustCompile(`"([^"]*)"|'([^']*)'`)
// gridTemplate returns the areas, the number of columns, and the column
// tracks of the grid template of the given grid container.
func (c *Context) gridTemplate(n *html.Node) (areas map[string]gridArea, ncols int, tracks []string) {
areasDecl := ""
tracks = gridTracksAuto(c.gridColumnsDecl(n), func(track string, fit bool) int { return c.autoRepeatCount(n, track, fit) })
if prop, v := c.lastDeclaration(n, "grid-template-areas", "grid-template"); prop == "grid-template" {
if strings.ContainsAny(v, `"'`) {
areasDecl = v
}
} else {
areasDecl = v
}
var rows [][]string
for _, m := range gridAreaStrings.FindAllStringSubmatch(areasDecl, -1) {
row := strings.Fields(m[1] + m[2])
rows = append(rows, row)
ncols = max(ncols, len(row))
}
if len(rows) == 0 {
return nil, len(tracks), tracks
}
areas = map[string]gridArea{}
for r, row := range rows {
for col, name := range row {
if strings.Trim(name, ".") == "" {
continue // a null cell
}
a, ok := areas[name]
if !ok {
areas[name] = gridArea{r, col, 1, 1}
continue
}
a.rows = max(a.rows, r-a.row+1)
a.cols = max(a.cols, col-a.col+1)
areas[name] = a
}
}
return areas, max(ncols, len(tracks)), tracks
}
// gridColumnsDecl returns the column track list of the given grid
// container: of the shorthand or the longhand that is last in the cascade
// (as a grid-template-columns of a more specific rule).
func (c *Context) gridColumnsDecl(n *html.Node) string {
prop, v := c.lastDeclaration(n, "grid-template-columns", "grid-template")
if prop != "grid-template" {
return v
}
_, cols, _ := css.CutTopLevel(v, '/')
return cols
}
// gridRowsDecl returns the row track list of the given grid container: of
// grid-template-rows, or before the / of a grid-template without areas.
func (c *Context) gridRowsDecl(n *html.Node) string {
prop, v := c.lastDeclaration(n, "grid-template-rows", "grid-template")
if prop != "grid-template" {
return v
}
if r, _, ok := css.CutTopLevel(v, '/'); ok && !strings.ContainsAny(r, `"'`) {
return r
}
return ""
}
// gridNames are the numbers (from 1) of the named lines of the columns and
// rows of a grid, by name, in order.
type gridNames struct {
cols, rows map[string][]int
}
// gridLineNumbers returns the numbers (from 1) of the lines of the given
// track list by their names (as [content-start] repeat(12, 60px)
// [content-end] of the grids of theguardian.com), with the given count of
// the tracks of a repeat(auto-fit or auto-fill). The names in a repeat()
// are not numbered, but its tracks are counted.
func gridLineNumbers(v string, autoCount func(track string, fit bool) int) map[string][]int {
var names map[string][]int
line, prev := 1, 0
for _, m := range gridLineNames.FindAllStringIndex(v, -1) {
line += len(gridTracksAuto(v[prev:m[0]], autoCount)) // the tracks before the names
prev = m[1]
if strings.Count(v[:m[0]], "(") != strings.Count(v[:m[0]], ")") {
continue // in a repeat()
}
if names == nil {
names = map[string][]int{}
}
for name := range strings.FieldsSeq(strings.Trim(v[m[0]:m[1]], "[]")) {
names[name] = append(names[name], line)
}
}
return names
}
// resolveGridLines returns the given grid-column or grid-row value (start /
// end) with its named lines replaced by their numbers from the given names:
// a name x is the line x-start at the start and x-end at the end (of the
// area that they make), or else the line x, with an optional number for
// its nth line, and a name alone is also the end (as grid-area: headline
// / title, of rows from headline-start to headline-end). An unknown name
// is auto.
func resolveGridLines(v string, names map[string][]int) string {
if v == "" || names == nil {
return v
}
resolve := func(side, suffix string) (string, bool) {
f := strings.Fields(side)
if len(f) == 0 || f[0] == "auto" || f[0] == "span" {
return side, false
}
name, nth := f[0], 1
if k, err := strconv.Atoi(f[0]); err == nil {
if len(f) == 1 {
return side, false
}
name, nth = f[1], k
} else if len(f) > 1 {
if k, err := strconv.Atoi(f[1]); err == nil {
nth = k
}
}
lines, ok := names[name+suffix]
if !ok {
lines = names[name]
}
if nth < 0 {
nth += len(lines) + 1
}
if nth < 1 || nth > len(lines) {
return "auto", true
}
return strconv.Itoa(lines[nth-1]), true
}
start, end, slash := css.CutTopLevel(v, '/')
rs, named := resolve(start, "-start")
if !slash {
if !named {
return v
}
end = start // the end of the area of the name
}
re, _ := resolve(end, "-end")
return rs + " / " + re
}
// gridLineNames matches the line names of a track list, as [a b].
var gridLineNames = regexp.MustCompile(`\[[^\]]*\]`)
// gridTracks returns the track sizes of a grid-template-columns value,
// with repeat() of a number expanded and line names removed.
func gridTracks(v string) []string {
return gridTracksAuto(v, nil)
}
// gridTracksAuto is [gridTracks] with repeat(auto-fit, ...) and
// repeat(auto-fill, ...) expanded to the number of tracks that the given
// function returns for the repeated track (and whether it is auto-fit).
func gridTracksAuto(v string, autoCount func(track string, fit bool) int) []string {
var tracks []string
v = gridLineNames.ReplaceAllString(v, " ")
for _, f := range css.SplitColors(v) { // fields outside of parentheses
if after, ok := strings.CutPrefix(f, "repeat("); ok {
inner := strings.TrimSuffix(after, ")")
n, rest, _ := strings.Cut(inner, ",")
n = strings.TrimSpace(n)
count, err := strconv.Atoi(n)
if err != nil && (n == "auto-fit" || n == "auto-fill") && autoCount != nil {
count, err = autoCount(strings.TrimSpace(rest), n == "auto-fit"), nil
}
if err == nil {
for range count {
tracks = append(tracks, gridTracksAuto(rest, autoCount)...)
}
}
continue
}
tracks = append(tracks, f)
}
return tracks
}
// autoRepeatCount returns the number of tracks of the given track of a
// repeat(auto-fit or auto-fill) of the grid of the given node: as many as
// fit in its width at their minimum size (of minmax(), or their size), with
// the column gap, as in CSS, in the width that the grid has before it is
// laid out (see [Context.availableWidth]: as the cards of
// repeat(auto-fill, minmax(180px, 1fr)) in a body of max-width: 720px,
// which were in 4 tracks for a page 800px wide, not 3), and at most as many as the grid has items for auto-fit, whose
// empty tracks collapse (as the 3 cards of repeat(auto-fit, minmax(25%,
// 1fr)) of edition.cnn.com, which were in one column).
func (c *Context) autoRepeatCount(n *html.Node, track string, fit bool) int {
mn := track
if inner, ok := strings.CutPrefix(track, "minmax("); ok {
mn, _, _ = strings.Cut(strings.TrimSuffix(inner, ")"), ",")
mn = strings.TrimSpace(mn)
}
env := c.readEnv()
width := c.availableWidth(env, n)
gap := c.gridColumnGap(n, env)
size := float32(0)
if p, ok := strings.CutSuffix(mn, "%"); ok {
if f, err := strconv.ParseFloat(p, 32); err == nil {
size = width * float32(f) / 100
}
} else if px, ok := env.LengthPx(mn); ok {
size = px
}
count := 1
if size > 0 {
count = max(int((width+gap)/(size+gap)), 1)
}
if fit && n != nil {
items := 0
for k := n.FirstChild; k != nil; k = k.NextSibling {
if k.Type == html.ElementNode && c.inFlexFlow(k) {
items++
}
}
count = max(min(count, items), 1)
}
return count
}
// flexibleTrack returns whether the given track is flexible: of fr, or a
// minmax() of fr (as minmax(0px, 1fr) of the margins of the grids of
// theguardian.com, whose last one had no share of the width without its
// filler, which went to the first one).
func flexibleTrack(t string) bool {
return strings.HasSuffix(t, "fr") || strings.HasSuffix(t, "fr)")
}
// gridColumnGap returns the column gap of the given grid container in px.
func (c *Context) gridColumnGap(n *html.Node, env *css.LengthEnv) float32 {
g := strings.TrimSpace(c.declaration(n, "column-gap"))
if g == "" {
if _, col, ok := css.CutTopLevel(strings.TrimSpace(c.declaration(n, "gap")), ' '); ok {
g = col
} else {
g = strings.TrimSpace(c.declaration(n, "gap"))
}
}
px, _ := env.LengthPx(g)
return px
}
// spanStyle sets the width of a child of a grid that spans the given
// tracks, if they are all lengths in px, to them and the given gaps between
// them, less its horizontal margins, unless it has a width of its own: its
// content does not size the tracks, as in CSS (as the sections of
// theguardian.com, whose content spans 12 tracks of 60px, which were as
// wide as their content, wider than the page).
func (c *Context) spanStyle(env *css.LengthEnv, kn *html.Node, s *styles.Style, tracks []string, gap float32) {
if kn == nil || strings.TrimSpace(c.declaration(kn, "width")) != "" {
return
}
width := gap * float32(len(tracks)-1)
for _, t := range tracks {
px, ok := env.LengthPx(t)
if !ok || strings.HasSuffix(t, "%") {
return
}
width += px
}
for _, m := range []units.Value{s.Margin.Left, s.Margin.Right} {
if m.Unit != units.UnitDp && m.Value != 0 {
return
}
width -= m.Value
}
s.BoxSizing = styles.BoxBorderBox
s.Min.X, s.Max.X = units.Dp(width), units.Dp(width)
s.Grow.X, s.Shrink.X = 0, 0
}
// noAutoMin returns whether the given child of a grid has no automatic
// minimum width, as in CSS: a min-width of 0, or an overflow that makes it
// a scroll container, so that its content does not widen the flexible
// tracks that it is in (as the cells of the top stories of nytimes.com,
// of min-width: 0 in 14 and 6 of 20 tracks of 1fr, whose carousels of
// stories, as wide as all of them, made the first wider than the page).
func (c *Context) noAutoMin(kn *html.Node) bool {
if kn == nil {
return false
}
if mw := strings.TrimSpace(c.declaration(kn, "min-width")); mw == "0" || mw == "0px" {
return true
}
ov := strings.TrimSpace(c.declaration(kn, "overflow-x"))
if ov == "" {
ov, _, _ = strings.Cut(strings.TrimSpace(c.declaration(kn, "overflow")), " ")
}
return ov == "hidden" || ov == "auto" || ov == "scroll"
}
// containFlexible makes the content of a child in the given flexible
// tracks not size them (see [Context.noAutoMin]): the tracks share the
// width by their fr, and it overflows them.
func containFlexible(s *styles.Style, tracks []string, noMin bool) {
if noMin && s.Contain == styles.ContainNone && !slices.ContainsFunc(tracks, func(t string) bool { return !strings.HasSuffix(t, "fr") }) {
s.Contain = styles.ContainInlineSize
}
}
// gridTrackStyle sets the style of a child in a grid column with the given
// track size: a length is its width, a flexible (fr) track grows by its
// factor (and minmax(0, length) grows up to the length), and the other
// tracks are as wide as their content when other tracks are flexible
// (and auto tracks share the rest of the width when none are).
func gridTrackStyle(env *css.LengthEnv, s *styles.Style, track string, flexible bool) {
if after, ok := strings.CutPrefix(track, "minmax("); ok {
inner := strings.TrimSuffix(after, ")")
mn, mx, _ := strings.Cut(inner, ",")
mx = strings.TrimSpace(mx)
if strings.HasSuffix(mx, "fr") || mx == "auto" {
if mn = strings.TrimSpace(mn); (mn == "0" || mn == "0px") && s.Contain == styles.ContainNone {
// the content of a cell does not size its track, so the
// tracks share the width by their fr (as the cells of the
// repository grid of github.com, whose hidden panels
// widened their columns), or an auto track has the rest of
// it (as the documentation of pkg.go.dev, in minmax(0,
// auto), whose long lines of code made the page wider than
// the window), and it overflows them
s.Contain = styles.ContainInlineSize
}
if mn != "0" && mn != "0px" && mn != "auto" {
if l, ok := env.Length(mn, units.UnitPw); ok {
// the track is at least the length (as the first column
// of minmax(64px, 1fr) of the results of google.com,
// empty, which was narrower, so that the header was to
// the left of where it is in browsers)
s.Min.X = l
s.BoxSizing = styles.BoxBorderBox
}
}
track = mx
} else if l, ok := env.Length(mx, units.UnitPw); ok {
s.Grow.X, s.Shrink.X = 1, 1
s.Max.X = l
s.BoxSizing = styles.BoxBorderBox
return
}
}
if fr, ok := strings.CutSuffix(track, "fr"); ok {
if f, err := strconv.ParseFloat(fr, 32); err == nil {
s.Grow.X, s.Shrink.X = float32(f), 1
}
return
}
if l, ok := env.Length(track, units.UnitPw); ok {
s.BoxSizing = styles.BoxBorderBox
// a length or a percentage of the grid is the width of the track,
// which its content does not narrow (as the 21.5% navigation of
// pkg.go.dev, beside documentation with wide lines of code)
s.Min.X, s.Max.X = l, l
s.Grow.X, s.Shrink.X = 0, 0
return
}
if flexible { // auto, min-content, max-content, and fit-content()
s.Grow.X = 0
} else if track == "auto" { // auto tracks share the rest of the width
s.Grow.X, s.Shrink.X = 1, 1
}
}
// stackGrid makes the given grid container widget a stack, showing its
// last child, if all of its children (two or more) are in the same cell
// of it by number (as grid-area: 1 / 1), over each other (as the counters
// of github.com, with a hidden copy of the value under it, for its width),
// and returns whether it did. (Core grids do not overlap their cells.)
func (c *Context) stackGrid(w core.Widget) bool {
fr := core.AsFrame(w)
if fr == nil || fr.NumChildren() < 2 {
return false
}
cell := ""
for _, k := range fr.Children {
kw, ok := k.(core.Widget)
if !ok {
return false
}
kn, _ := kw.AsWidget().Property("node").(*html.Node)
if kn == nil {
return false
}
row, col, _ := css.CutTopLevel(c.declaration(kn, "grid-area"), '/')
row, col = strings.TrimSpace(row), strings.TrimSpace(col)
if row == "" {
// (lines with an end, as 1 / span 2, are not one cell)
row, col = c.gridLines(kn, "row", nil), c.gridLines(kn, "column", nil)
}
if _, err := strconv.Atoi(row); err != nil {
return false
}
if col == "" {
col = "1"
}
if _, err := strconv.Atoi(strings.TrimSpace(col)); err != nil {
return false
}
if cell != "" && cell != row+"/"+col {
return false
}
cell = row + "/" + col
}
// the one on top that is shown: the last that is not transparent or
// hidden (as the name of a repository of github.com, before a copy of
// it for the accessibility tree, of opacity 0, which hid it)
top := fr.NumChildren() - 1
for i := top; i >= 0; i-- {
kn, _ := core.AsWidget(fr.Child(i)).Property("node").(*html.Node)
op := strings.TrimSpace(c.declaration(kn, "opacity"))
vis := strings.TrimSpace(c.declaration(kn, "visibility"))
if op != "0" && vis != "hidden" {
top = i
break
}
}
fr.FinalStyler(func(s *styles.Style) { s.Display = styles.Stacked })
fr.StackTop = top
return true
}
// gridFiller returns a new empty widget of the given grid, for a cell in
// a column of the given track that no child is in, which the caller moves
// into its place in the children.
func (c *Context) gridFiller(w core.Widget, env *css.LengthEnv, track string, flexible bool) *core.Frame {
filler := core.NewFrame(w)
filler.SetName("grid-filler")
tree.SetUniqueName(filler) // (names of children must be unique, as for the inspector)
filler.Styler(func(s *styles.Style) {
s.Padding.Zero()
s.Margin.Zero()
s.Gap.Zero()
s.Background = nil
gridTrackStyle(env, s, track, flexible)
})
return filler
}
// gridLines returns the lines of the given element in the given axis of
// its grid (column or row) as "start / end", from its grid-column (or
// grid-row) shorthand and its -start and -end longhands, in the order of
// the cascade (as the 12 column grid of nytimes.com/wirecutter, of
// grid-column-end: span 8 and grid-column-start: 10), or "" if it has none.
func (c *Context) gridLines(n *html.Node, axis string, names map[string][]int) string {
if n == nil {
return ""
}
short := "grid-" + axis
start, end := "", ""
for _, d := range c.declarations(n) {
if d.invalid {
continue
}
v := strings.TrimSpace(d.Value)
switch d.Property {
case short:
st, en, _ := css.CutTopLevel(v, '/')
start, end = strings.TrimSpace(st), strings.TrimSpace(en)
case short + "-start":
start = v
case short + "-end":
end = v
}
}
if start == "" && end == "" {
return ""
}
if start == "" {
start = "auto"
}
if end == "" {
return resolveGridLines(start, names)
}
return resolveGridLines(start+" / "+end, names)
}
// gridPlacement returns the area of the given child of a grid with the
// given number of columns from the numbers of its start lines in its
// grid-row and grid-column (or grid-area), if it has both (as the cells
// of the repository grid of github.com, as grid-column: 1; grid-row: 1).
func (c *Context) gridPlacement(n *html.Node, ncols, nrows int, names gridNames) (gridArea, bool) {
if n == nil {
return gridArea{}, false
}
row, col := c.gridLines(n, "row", names.rows), c.gridLines(n, "column", names.cols)
if ga := c.declaration(n, "grid-area"); ga != "" && row == "" && col == "" {
parts := strings.Split(ga, "/")
if len(parts) >= 2 {
row, col = strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1])
if len(parts) >= 3 {
row += " / " + strings.TrimSpace(parts[2])
}
if len(parts) >= 4 {
col += " / " + strings.TrimSpace(parts[3])
}
row, col = resolveGridLines(row, names.rows), resolveGridLines(col, names.cols)
}
}
start := func(v string) (int, bool) {
s, _, _ := css.CutTopLevel(v, '/')
k, err := strconv.Atoi(strings.TrimSpace(s))
return k, err == nil && k > 0
}
r, okr := start(row)
cl, okc := start(col)
if !okc || cl > ncols {
return gridArea{}, false
}
a := gridArea{row: r - 1, col: cl - 1, rows: gridSpan(row, nrows), cols: min(gridSpan(col, ncols), ncols-cl+1)}
if !okr {
a.row = -1 // auto: in the first row where its columns are free
}
return a, true
}
// placeAutoRows places the given grid items that have a column and an auto
// row (-1) in the first rows where their columns are free of the others,
// in order, as the auto-placement of CSS (as the middle column of the top
// stories of bbc.com, which was in a row of its own below the others).
func placeAutoRows[T any](items []T, area func(*T) *gridArea) {
covered := map[[2]int]bool{}
cover := func(a *gridArea) {
for r := a.row; r < a.row+a.rows; r++ {
for c := a.col; c < a.col+a.cols; c++ {
covered[[2]int{r, c}] = true
}
}
}
for i := range items {
if a := area(&items[i]); a.row >= 0 {
cover(a)
}
}
for i := range items {
a := area(&items[i])
if a.row >= 0 {
continue
}
for r := 0; ; r++ {
free := true
for rr := r; rr < r+a.rows && free; rr++ {
for c := a.col; c < a.col+a.cols; c++ {
if covered[[2]int{rr, c}] {
free = false
break
}
}
}
if free {
a.row = r
break
}
}
cover(a)
}
}
// gridSpan returns the number of tracks that the given value of
// grid-column or grid-row spans: span N (with auto or a start line before
// or after it), or from a start line to an end line (with -1 the last line
// of the given number of tracks, if known), or 1.
func gridSpan(v string, ntracks int) int {
start, end, slash := css.CutTopLevel(strings.ToLower(v), '/')
start, end = strings.TrimSpace(start), strings.TrimSpace(end)
for _, p := range []string{start, end} {
if n, ok := strings.CutPrefix(p, "span"); ok {
if k, err := strconv.Atoi(strings.TrimSpace(n)); err == nil && k > 0 {
return k
}
}
}
if !slash {
return 1
}
a, errA := strconv.Atoi(start)
b, errB := strconv.Atoi(end)
if errA != nil || errB != nil {
return 1
}
lines := ntracks + 1
if a < 0 && ntracks > 0 {
a += lines + 1
}
if b < 0 && ntracks > 0 {
b += lines + 1
}
if b <= a || a <= 0 {
return 1
}
return b - a
}
// columnFlowOrder returns the given auto-placed children of a grid of
// grid-auto-flow: column, with the given numbers of columns and rows, in
// the row-major order of the core grid: they fill each column before the
// next (as the two lists of 10 of the "Most popular" of theguardian.com,
// in 2 columns of 11 rows, which were interleaved), with fillers from the
// given function for the empty cells. They are as they are if any of them
// spans or is placed, or if they need more columns.
func (c *Context) columnFlowOrder(auto []tree.Node, ncols, nrows int, names gridNames, filler func(col int) tree.Node) []tree.Node {
if ncols < 2 || nrows < 1 {
return auto
}
// The children in cells, and the others (out of the flow, or not
// widgets), which are after them.
var cells, rest []tree.Node
for _, k := range auto {
kw, ok := k.(core.Widget)
if !ok {
rest = append(rest, k)
continue
}
kn, _ := kw.AsWidget().Property("node").(*html.Node)
if kn != nil {
pos := strings.TrimSpace(c.declaration(kn, "position"))
if pos == "absolute" || pos == "fixed" || c.displayOf(kn) == "none" {
rest = append(rest, k)
continue
}
if c.gridLines(kn, "column", names.cols) != "" || c.gridLines(kn, "row", names.rows) != "" {
return auto
}
}
cells = append(cells, k)
}
if len(cells) > ncols*nrows {
return auto
}
// Each row in turn, with fillers for the empty cells before the last
// child.
var kids []tree.Node
left := len(cells)
for r := 0; r < nrows && left > 0; r++ {
for col := 0; col < ncols && left > 0; col++ {
if i := col*nrows + r; i < len(cells) {
kids = append(kids, cells[i])
left--
} else {
kids = append(kids, filler(col))
}
}
}
return append(kids, rest...)
}
// arrangeGrid places the children of the given grid container widget for
// its node by its grid template (see the comment at the top of grid.go).
func (c *Context) arrangeGrid(n *html.Node, w core.Widget) {
if c.stackGrid(w) {
return
}
areas, ncols, tracks := c.gridTemplate(n)
env := c.readEnv() // for the lengths of the tracks
if ncols == 0 {
return
}
flexible := slices.ContainsFunc(tracks, flexibleTrack)
if fr := frameOf(w); fr != nil && len(tracks) > 0 && !slices.ContainsFunc(tracks, func(t string) bool { return !flexibleTrack(t) }) {
fr.FrColumns = true // all of its tracks are fr (see core.Frame.FrColumns)
}
rowsDecl := c.gridRowsDecl(n)
rowTracks := gridTracks(rowsDecl)
names := gridNames{
cols: gridLineNumbers(c.gridColumnsDecl(n), func(track string, fit bool) int { return c.autoRepeatCount(n, track, fit) }),
rows: gridLineNumbers(rowsDecl, nil),
}
if fr := frameOf(w); fr != nil {
// the last row is flexible, and the others are auto (see core.Frame.FrLastRow)
fr.FrLastRow = len(rowTracks) > 1 && strings.HasSuffix(rowTracks[len(rowTracks)-1], "fr") &&
!slices.ContainsFunc(rowTracks[:len(rowTracks)-1], func(t string) bool { return t != "auto" && t != "min-content" && t != "max-content" })
}
trackOf := func(col int) string {
if col < len(tracks) {
return tracks[col]
}
return "auto"
}
gap := c.gridColumnGap(n, env)
spanned := func(col, cols int) []string {
var ts []string
for i := col; i < col+cols; i++ {
ts = append(ts, trackOf(i))
}
return ts
}
type placed struct {
w core.Widget
area gridArea
}
var items []placed
var auto []tree.Node
// Children with a column and an auto row are placed only with others
// placed in rows (or areas), as otherwise they are in the order of the
// children, with the others.
explicitRow := false
for _, k := range w.AsTree().Children {
if kw, ok := k.(core.Widget); ok {
kn, _ := kw.AsWidget().Property("node").(*html.Node)
name, _, _ := css.CutTopLevel(c.declaration(kn, "grid-area"), '/')
if a, ok := c.gridPlacement(kn, ncols, len(rowTracks), names); (ok && a.row >= 0) || (name != "" && areas[name] != (gridArea{})) {
explicitRow = true
break
}
}
}
for _, k := range w.AsTree().Children {
kw, ok := k.(core.Widget)
if !ok {
auto = append(auto, k)
continue
}
kn, _ := kw.AsWidget().Property("node").(*html.Node)
name := ""
if kn != nil {
name, _, _ = css.CutTopLevel(c.declaration(kn, "grid-area"), '/')
}
if a, ok := areas[name]; ok && name != "" {
items = append(items, placed{kw, a})
} else if a, ok := c.gridPlacement(kn, ncols, len(rowTracks), names); ok && (a.row >= 0 || explicitRow) {
items = append(items, placed{kw, a})
} else {
auto = append(auto, k)
}
}
placeAutoRows(items, func(p *placed) *gridArea { return &p.area })
// An empty item whose area has others in it is not shown, as core grids
// do not overlap their cells (as the decoration of the sections of
// theguardian.com, of grid-area: 1 / decoration / -1, which drew their
// side borders, and took the cells of their content).
items = slices.DeleteFunc(items, func(it placed) bool {
kn, _ := it.w.AsWidget().Property("node").(*html.Node)
if kn == nil || hasContent(kn) {
return false
}
for _, o := range items {
if o.w != it.w && it.area.contains(o.area) {
it.w.AsWidget().FinalStyler(func(s *styles.Style) { s.Display = styles.DisplayNone })
auto = append(auto, it.w)
return true
}
}
return false
})
w.AsWidget().FinalStyler(func(s *styles.Style) { s.Columns = ncols })
if len(items) == 0 {
// The children in order, with the columns and rows that they span
// (as the 12 columns of the grids of github.com, of which its
// features span 6 or 4), and the tracks of the columns that they
// are in.
// An item with a column start (and an auto row) is placed at it,
// in the next row if the cells before it in this one are taken
// (as the sidebar of nytimes.com/wirecutter at column 10, after
// the text in columns 1 to 8), with empty cells before it.
col := 0
var kids []tree.Node
filled := false
if strings.Contains(c.declaration(n, "grid-auto-flow"), "column") {
ordered := c.columnFlowOrder(auto, ncols, len(rowTracks), names, func(col int) tree.Node {
return c.gridFiller(w, env, trackOf(col), flexible)
})
filled = !slices.Equal(ordered, auto) // (children are set from kids)
auto = ordered
}
fill := func(n int) { // the n cells from col
for i := range n {
kids = append(kids, c.gridFiller(w, env, trackOf((col+i)%ncols), flexible))
}
filled = filled || n > 0
}
for _, k := range auto {
kw, ok := k.(core.Widget)
if !ok {
kids = append(kids, k)
continue
}
cs, rs := 1, 1
if kn, _ := kw.AsWidget().Property("node").(*html.Node); kn != nil {
// children out of the flow are in no cell (as a visually
// hidden heading, which took the first column of the
// testimonials of github.com, so the others were in the
// tracks after theirs)
pos := strings.TrimSpace(c.declaration(kn, "position"))
if pos == "absolute" || pos == "fixed" || c.displayOf(kn) == "none" {
continue
}
cols := c.gridLines(kn, "column", names.cols)
cs = gridSpan(cols, ncols)
rs = gridSpan(c.gridLines(kn, "row", names.rows), 0)
st, _, _ := css.CutTopLevel(cols, '/')
if start, err := strconv.Atoi(strings.TrimSpace(st)); err == nil && start > 0 && start <= ncols {
if start-1 < col { // in the next row
fill(ncols - col)
col = 0
}
fill(start - 1 - col)
col = start - 1
cs = min(cs, ncols-col)
}
}
cs = min(cs, ncols)
if col > 0 && col+cs > ncols { // it starts the next row
col = 0
}
kids = append(kids, k)
i := col
kn, _ := kw.AsWidget().Property("node").(*html.Node)
span := spanned(col, cs)
noMin := c.noAutoMin(kn)
kw.AsWidget().FinalStyler(func(s *styles.Style) {
if cs > 1 {
s.ColSpan = cs
c.spanStyle(env, kn, s, span, gap)
} else if len(tracks) > 0 {
gridTrackStyle(env, s, trackOf(i), flexible)
}
if len(tracks) > 0 {
containFlexible(s, span, noMin)
}
if rs > 1 {
s.RowSpan = rs
}
})
col = (col + cs) % ncols
}
if filled && col > 0 {
// the flexible tracks after the last item take their share
for ; col < ncols && flexibleTrack(trackOf(col)); col++ {
fill(1)
}
}
if filled {
w.AsTree().Children = kids
}
return
}
slices.SortStableFunc(items, func(a, b placed) int {
if a.area.row != b.area.row {
return a.area.row - b.area.row
}
return a.area.col - b.area.col
})
// The cells in row-major order, as the core grid places them: the
// items at the start of their areas, and empty widgets in the cells
// that are not in any area, up to the last item.
covered := map[[2]int]bool{}
for _, it := range items {
for r := it.area.row; r < it.area.row+it.area.rows; r++ {
for col := it.area.col; col < it.area.col+it.area.cols; col++ {
covered[[2]int{r, col}] = true
}
}
}
last := items[len(items)-1].area
var kids []tree.Node
next := 0
for r := 0; r <= last.row; r++ {
for col := range ncols {
if r == last.row && col > last.col && !flexibleTrack(trackOf(col)) {
// the cells after the last item are empty, but those of
// flexible tracks take their share of the width (as the
// third column of 1fr 1024px 1fr of nytimes.com/wirecutter,
// whose space went to the first)
break
}
if next < len(items) && items[next].area.row == r && items[next].area.col == col {
it := items[next]
next++
kids = append(kids, it.w)
a := it.area
track := trackOf(col)
kn, _ := it.w.AsWidget().Property("node").(*html.Node)
span := spanned(col, a.cols)
noMin := c.noAutoMin(kn)
it.w.AsWidget().FinalStyler(func(s *styles.Style) {
s.ColSpan, s.RowSpan = a.cols, a.rows
if a.cols == 1 {
gridTrackStyle(env, s, track, flexible)
} else {
c.spanStyle(env, kn, s, span, gap)
}
containFlexible(s, span, noMin)
})
continue
}
if covered[[2]int{r, col}] {
continue
}
kids = append(kids, c.gridFiller(w, env, trackOf(col), flexible)) // moved into its place below
}
}
for ; next < len(items); next++ { // items that share a start with another
auto = append(auto, items[next].w)
}
w.AsTree().Children = append(kids, auto...)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"bytes"
"context"
"encoding/base64"
"fmt"
"io"
"net/http"
neturl "net/url"
"slices"
"strings"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/tree"
"golang.org/x/net/html"
)
// New adds a new widget of the given type to the context parent.
// It automatically calls [Context.config] on the resulting widget.
func New[T tree.NodeValue](ctx *Context) *T {
parent := ctx.Parent()
w := tree.New[T](parent)
ctx.config(any(w).(core.Widget))
return w
}
// handleTextTag creates a new [core.Text] from the given information, setting the text and
// the text click function so that URLs are opened according to [Context.OpenURL]. Also,
// it wraps the text with the [nodeString] of the given node, meaning that it
// should be used for standalone elements that are meant to only exist in text
// (eg: a, span, b, code, etc).
func handleTextTag(ctx *Context) *core.Text {
start, end := nodeString(ctx.Node)
str := start + ExtractText(ctx) + end
tx := New[core.Text](ctx).SetText(str)
tx.HandleTextClick(func(tl *rich.Hyperlink, e events.Event) {
ctx.OpenURL(tl.URL, e)
})
return tx
}
// GetAttr gets the given attribute from the given node, returning ""
// if the attribute is not found.
func GetAttr(n *html.Node, attr string) string {
res := ""
for _, a := range n.Attr {
if a.Key == attr {
res = a.Val
}
}
return res
}
// HasAttr returns whether the given node has the given attribute defined.
func HasAttr(n *html.Node, attr string) bool {
return slices.ContainsFunc(n.Attr, func(a html.Attribute) bool {
return a.Key == attr
})
}
// GetLanguage returns the 'x' in a `language-x` class from the given
// string of class(es).
func GetLanguage(class string) string {
fields := strings.FieldsSeq(class)
for field := range fields {
if after, ok := strings.CutPrefix(field, "language-"); ok {
return after
}
}
return ""
}
// Get is a helper function that calls [Context.GetURL] with the given URL, parsed
// relative to the page URL of the given context. It also checks the status
// code of the response and closes the response body and returns an error if
// it is not [http.StatusOK]. If the error is nil, then the response body is
// not closed and must be closed by the caller.
// logGetError logs the given error of [Get], if any, unless it is because
// the getting was canceled (as for a page whose opening was stopped, as
// when a page is opened while its style sheets are gotten), and returns it.
func logGetError(err error) error {
if err != nil && !errors.Is(err, context.Canceled) {
errors.Log(err)
}
return err
}
func Get(ctx *Context, url string) (*http.Response, error) {
if strings.HasPrefix(url, "data:") {
return dataURL(url)
}
u, err := parseRelativeURL(url, ctx.PageURL)
if err != nil {
return nil, err
}
resp, err := ctx.GetURL(u.String())
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
resp.Body.Close()
return resp, fmt.Errorf("got error status %q (code %d)", resp.Status, resp.StatusCode)
}
return resp, nil
}
// nodeText returns all of the text in the given node.
func nodeText(n *html.Node) string {
if n.Type == html.TextNode {
return n.Data
}
var sb strings.Builder
for c := n.FirstChild; c != nil; c = c.NextSibling {
sb.WriteString(nodeText(c))
}
return sb.String()
}
// dataURL returns a response with the data of the given data URL.
func dataURL(u string) (*http.Response, error) {
meta, data, ok := strings.Cut(strings.TrimPrefix(u, "data:"), ",")
if !ok {
return nil, fmt.Errorf("invalid data URL")
}
var b []byte
if strings.HasSuffix(meta, ";base64") {
var err error
b, err = base64.StdEncoding.DecodeString(data)
if err != nil {
b, err = base64.RawStdEncoding.DecodeString(data)
if err != nil {
return nil, err
}
}
} else {
d, err := neturl.PathUnescape(data)
if err != nil {
return nil, err
}
b = []byte(d)
}
return &http.Response{StatusCode: http.StatusOK, Status: "200 OK", Body: io.NopCloser(bytes.NewReader(b)),
Header: http.Header{"Content-Type": {strings.Split(meta, ";")[0]}}}, nil
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"strconv"
"strings"
"golang.org/x/net/html"
)
// addHints adds declarations for the presentational attributes of the
// given element, such as the width of an img or the bgcolor of a td.
func (c *Context) addHints(n *html.Node) {
for _, a := range n.Attr {
v := strings.TrimSpace(a.Val)
switch a.Key {
case "width", "height":
switch n.Data {
case "img", "table", "td", "th", "col", "iframe", "video", "canvas", "embed", "object", "hr", "svg":
c.addHint(n, a.Key, v)
}
case "bgcolor":
c.addHint(n, "background-color", v)
case "color":
if n.Data == "font" {
c.addHint(n, "color", v)
}
case "face":
if n.Data == "font" {
c.addHint(n, "font-family", v)
}
case "size":
if n.Data == "font" {
if sz, ok := fontElementSize(v); ok {
c.addHint(n, "font-size", sz)
}
}
case "valign":
c.addHint(n, "vertical-align", strings.ToLower(v))
case "text":
if n.Data == "body" {
c.addHint(n, "color", v)
}
case "align":
switch strings.ToLower(v) {
case "center", "middle":
if n.Data == "table" {
c.addHint(n, "margin-left", "auto")
c.addHint(n, "margin-right", "auto")
} else if n.Data != "img" {
c.addHint(n, "text-align", "-webkit-center")
}
case "left", "right", "justify":
if n.Data != "img" && n.Data != "table" {
c.addHint(n, "text-align", strings.ToLower(v))
}
}
case "hidden":
c.addHint(n, "display", "none")
case "nowrap":
c.addHint(n, "white-space", "nowrap")
case "border":
switch n.Data {
case "table":
if bw, err := strconv.Atoi(v); err == nil || v == "" {
if v == "" {
bw = 1
}
if bw > 0 {
c.addHint(n, "border", strconv.Itoa(bw)+"px outset #808080")
}
}
case "img":
c.addHint(n, "border-width", v)
}
case "cellspacing":
if n.Data == "table" {
c.addHint(n, "border-spacing", v)
}
}
}
// cells get the cellpadding and border of their table
if n.Data == "td" || n.Data == "th" {
if t := ancestorTable(n); t != nil {
if cp := GetAttr(t, "cellpadding"); cp != "" {
c.addHint(n, "padding", cp)
}
if b := GetAttr(t, "border"); HasAttr(t, "border") && b != "0" {
c.addHint(n, "border", "1px inset #808080")
}
}
}
}
// fontElementSize returns the CSS font size for the size attribute of a font element.
func fontElementSize(v string) (string, bool) {
sizes := []string{"x-small", "small", "medium", "large", "x-large", "xx-large", "xxx-large"}
n, err := strconv.Atoi(strings.TrimLeft(v, "+-"))
if err != nil {
return "", false
}
switch {
case strings.HasPrefix(v, "+"):
n += 3
case strings.HasPrefix(v, "-"):
n = 3 - n
}
return sizes[min(max(n, 1), 7)-1], true
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package htmlengine is the engine that reads HTML and Markdown into
// Cogent Core widget trees: parsing documents, the CSS cascade and the
// browser styles of elements, making and laying out the widgets of the
// elements, and reading and restyling the changed elements of documents
// (as by the scripts of pages) in place. Package htmlcore is the API of it
// for apps and content sites; apps that show whole web pages, as a browser
// does, use it directly.
package htmlengine
import (
"bytes"
"fmt"
"io"
"strings"
"cogentcore.org/core/core"
"cogentcore.org/core/htmlcore/css"
"golang.org/x/net/html"
)
// ReadHTML reads HTML from the given [io.Reader] and adds corresponding
// Cogent Core widgets to the given [core.Widget], using the given context.
func ReadHTML(ctx *Context, parent core.Widget, r io.Reader) error {
n, err := ParseHTML(ctx, r)
if err != nil {
return err
}
return ReadDocument(ctx, parent, n)
}
// ParseHTML parses the given HTML as browsers do: with scripting enabled
// if [Context.Scripting] is set (so that the content of noscript elements
// is their text, which is not shown), and otherwise as browsers do without
// JavaScript, so that the content of noscript elements is shown.
func ParseHTML(ctx *Context, r io.Reader) (*html.Node, error) {
n, err := html.ParseWithOptions(r, html.ParseOptionEnableScripting(ctx.Scripting))
if err != nil {
return nil, fmt.Errorf("error parsing HTML: %w", err)
}
return n, nil
}
// ReadDocument adds the Cogent Core widgets for the given parsed HTML
// document (or other node, with its next siblings) to the given widget,
// using the given context, as [ReadHTML] does after it parses its HTML.
// It allows the document to be read again after it is changed, as by the
// scripts of a page (which need its nodes), with a new context for each
// read (see [Context.NewPage]); the nodes of the document are those of the
// widgets (see [NodeOf]).
func ReadDocument(ctx *Context, parent core.Widget, n *html.Node) error {
// HTML that an element handler reads while HTML is being read, such as
// the page that content embeds for an <embed-page>, is read whole, and
// the state of the outer read, including its staging, is kept.
if ctx.reading {
outer, stageSize := ctx.readState, ctx.StageSize
ctx.readState, ctx.StageSize = readState{}, 0
defer func() { ctx.readState, ctx.StageSize = outer, stageSize }()
return readHTMLNode(ctx, parent, n)
}
ctx.readState = readState{}
if ctx.ImageCache != nil {
ctx.ImageCache.NewRead() // (its images are kept over the others)
}
// the style sheets of the new page are imported again, and it has its title
ctx.cssImports = nil
ctx.mediaUses, ctx.columnUses = nil, nil // of the new page
ctx.Title = ""
ctx.reading = true
defer func() { ctx.reading = false }()
err := readHTMLNode(ctx, parent, n)
ctx.lockStylesOf(parent)
return err
}
// ReadHTMLString reads HTML from the given string and adds corresponding
// Cogent Core widgets to the given [core.Widget], using the given context.
func ReadHTMLString(ctx *Context, parent core.Widget, s string) error {
b := bytes.NewBufferString(s)
return ReadHTML(ctx, parent, b)
}
// readHTMLNode reads HTML from the given [*html.Node] and its next siblings
// and adds corresponding Cogent Core widgets to the given [core.Widget],
// using the given context.
func readHTMLNode(ctx *Context, parent core.Widget, n *html.Node) error {
// the text of the ::before and ::after of the element, as texts of
// their own when its first and last children are not in a run of
// inline content (which has them; see [Context.readInlineRun])
el := n.Parent
if el != nil && el.Type == html.ElementNode && el.FirstChild == n && !ctx.isInlineLevel(n) {
ctx.pseudoText(parent, el, "before")
}
for ; n != nil; n = n.NextSibling {
// The rest of a staged body is left for later.
if ctx.stageAt(n) {
ctx.rest, ctx.restParent = n, parent
return nil
}
if n.NextSibling == nil && el != nil && el.Type == html.ElementNode && el.LastChild == n && !ctx.isInlineLevel(n) {
defer ctx.pseudoText(parent, el, "after")
}
if n.Parent != nil && ctx.isInlineLevel(n) {
last := n
for last.NextSibling != nil && ctx.isInlineLevel(last.NextSibling) && !ctx.stageAt(last.NextSibling) {
last = last.NextSibling
}
ctx.readInlineRun(parent, n, last)
n = last
continue
}
if ctx.keepRead[n] != nil {
keptPlaceholder(parent, n) // kept as it is (see Context.keptElements)
continue
}
readOneNode(ctx, parent, n)
}
return nil
}
// readOneNode reads the given node and its children (but not its
// siblings), adding the widgets for it to the given parent.
func readOneNode(ctx *Context, parent core.Widget, n *html.Node) {
// nil parent means we are root, so we add user agent styles here
if n.Parent == nil {
ctx.Node = n
prev := ctx.reuseFrom
ctx.reuseFrom = nil // (not kept, with all of its widgets)
reuse := prev != nil && prev.snaps != nil && prev.snapRoot == n && prev.matchedRules == len(prev.rules)
ctx.deferMatch = reuse
ctx.addStyleOrigin(browserStyles, css.OriginUserAgent)
if ctx.Style != "" { // before the style sheets of the page, which override it
ctx.addStyleOrigin(ctx.Style, css.OriginAuthor)
}
restore := ctx.setCheckedAttrs(n)
keptMasks := ctx.keepAncestorMasks() // (as the rules are matched)
ctx.addStyleSheets(n)
ctx.deferMatch = false
if reuse && !ctx.reuseMatches(n, prev) {
ctx.applyRules()
}
if ctx.snaps == nil || !reuse {
ctx.snapshot(n)
}
ctx.matchedRules = len(ctx.rules)
ctx.matchedPseudo = len(ctx.pseudoRules)
keptMasks()
restore()
ctx.rootFont = 0
ctx.rootFontSize() // of this document, while ctx.Node is it
}
switch n.Type {
case html.TextNode:
str := strings.TrimSpace(n.Data)
if str != "" {
ctx.handleWidget(n, New[core.Text](ctx).SetText(str))
}
case html.ElementNode:
ctx.Node = n
ctx.BlockParent = parent
ctx.NewParent = nil
handleElement(ctx)
default:
ctx.NewParent = parent
}
np := ctx.NewParent
// the boxes of the ::before and ::after of an element (see
// [Context.pseudoBoxNode]) are its first and last children while they
// are read, in its flow (as in a run of its inline content)
if np != nil && n.Type == html.ElementNode && n.Parent != nil && ctx.pseudoStyles != nil {
if before := ctx.pseudoBoxNode(n, "before"); before != nil {
n.InsertBefore(before, n.FirstChild)
defer n.RemoveChild(before)
}
if after := ctx.pseudoBoxNode(n, "after"); after != nil {
n.AppendChild(after)
defer n.RemoveChild(after)
}
}
if np != nil && n.FirstChild == nil && n.Type == html.ElementNode && n.Parent != nil && ctx.pseudoStyles != nil {
// the text of the ::before and ::after of an empty element (as the
// markers of the lines of the diffs of Wikipedia, in empty cells)
if t := strings.TrimSpace(ctx.pseudoContent(n, "before") + ctx.pseudoContent(n, "after")); t != "" {
ctx.pseudoText(np, n, "before")
ctx.pseudoText(np, n, "after")
}
}
if np != nil && n.FirstChild != nil {
readHTMLNode(ctx, np, n.FirstChild)
if n.Type == html.ElementNode && ctx.rest == nil {
if fr := frameOf(np); fr != nil && fr.Property("node") == n {
ctx.arrange(n, fr)
}
}
}
if n.Type == html.ElementNode && n.Data == "tr" && ctx.rest == nil && ctx.displayOf(n) != "none" {
ctx.endTableRow(n) // the next row starts in the next row of the grid
}
}
// rootNode returns the root node of the given node.
func rootNode(n *html.Node) *html.Node {
for n.Parent != nil {
n = n.Parent
}
return n
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"bytes"
"encoding/binary"
"errors"
"image"
"image/color"
"image/png"
"io"
)
// The ICO format of favicons, the largest image of which is decoded: a
// PNG (as in most modern icons), or a BMP (a DIB of 32 bits per pixel with
// alpha, 24 bits, or a palette of 1, 4 or 8 bits, with a mask of the
// transparent pixels), as the favicons of github.com that duckduckgo.com
// shows by its results.
func init() {
image.RegisterFormat("ico", "\x00\x00\x01\x00", decodeICO, decodeICOConfig)
}
// icoImage returns the data of the largest image in the given ICO file,
// its size, and whether it is a PNG (or else a DIB).
func icoImage(r io.Reader) (img []byte, w, h int, isPNG bool, err error) {
data, err := io.ReadAll(r)
if err != nil {
return nil, 0, 0, false, err
}
if len(data) < 6 {
return nil, 0, 0, false, errors.New("ico: too short")
}
n := int(binary.LittleEndian.Uint16(data[4:6]))
bestArea := -1
for i := range n {
e := 6 + 16*i
if e+16 > len(data) {
break
}
ew, eh := int(data[e]), int(data[e+1])
if ew == 0 {
ew = 256
}
if eh == 0 {
eh = 256
}
size := int(binary.LittleEndian.Uint32(data[e+8 : e+12]))
off := int(binary.LittleEndian.Uint32(data[e+12 : e+16]))
if off < 0 || size <= 0 || off+size > len(data) || ew*eh <= bestArea {
continue
}
img, w, h, isPNG, bestArea = data[off:off+size], ew, eh, bytes.HasPrefix(data[off:], []byte("\x89PNG")), ew*eh
}
if img == nil {
return nil, 0, 0, false, errors.New("ico: no image")
}
return img, w, h, isPNG, nil
}
func decodeICO(r io.Reader) (image.Image, error) {
b, w, h, isPNG, err := icoImage(r)
if err != nil {
return nil, err
}
if isPNG {
return png.Decode(bytes.NewReader(b))
}
return decodeDIB(b, w, h)
}
func decodeICOConfig(r io.Reader) (image.Config, error) {
b, w, h, isPNG, err := icoImage(r)
if err != nil {
return image.Config{}, err
}
if isPNG {
return png.DecodeConfig(bytes.NewReader(b))
}
return image.Config{ColorModel: color.NRGBAModel, Width: w, Height: h}, nil
}
// decodeDIB decodes the given DIB of an ICO file (a BMP with no file
// header, whose height is that of its image and of its mask), of the given
// size: its rows are from the bottom, of 32, 24, 8, 4 or 1 bits per pixel
// (with a palette for 8 and fewer), padded to 4 bytes, followed by the
// mask of 1 bit per pixel (1 for a transparent pixel).
func decodeDIB(b []byte, w, h int) (image.Image, error) {
if len(b) < 40 {
return nil, errors.New("ico: short BMP header")
}
hdr := int(binary.LittleEndian.Uint32(b[0:4]))
if dw := int(int32(binary.LittleEndian.Uint32(b[4:8]))); dw > 0 {
w = dw
}
if dh := int(int32(binary.LittleEndian.Uint32(b[8:12]))); dh > 0 {
h = dh / 2 // with the mask
}
bpp := int(binary.LittleEndian.Uint16(b[14:16]))
if c := binary.LittleEndian.Uint32(b[16:20]); c != 0 && c != 3 { // BI_RGB (or bitfields, as BGRA)
return nil, errors.New("ico: compressed BMP")
}
var palette []color.NRGBA
pos := hdr
if bpp <= 8 {
n := int(binary.LittleEndian.Uint32(b[32:36]))
if n == 0 {
n = 1 << bpp
}
for i := 0; i < n && pos+4 <= len(b); i++ {
palette = append(palette, color.NRGBA{b[pos+2], b[pos+1], b[pos], 255})
pos += 4
}
}
stride := (w*bpp + 31) / 32 * 4
maskStride := (w + 31) / 32 * 4
if pos+stride*h > len(b) {
return nil, errors.New("ico: short BMP")
}
mask := b[pos+stride*h:]
img := image.NewNRGBA(image.Rect(0, 0, w, h))
hasAlpha := false
for y := range h {
row := b[pos+stride*(h-1-y):]
for x := range w {
var c color.NRGBA
switch bpp {
case 32:
c = color.NRGBA{row[4*x+2], row[4*x+1], row[4*x], row[4*x+3]}
hasAlpha = hasAlpha || c.A != 0
case 24:
c = color.NRGBA{row[3*x+2], row[3*x+1], row[3*x], 255}
case 8, 4, 1:
bit := x * bpp
i := int(row[bit/8]>>(8-bpp-bit%8)) & (1<<bpp - 1)
if i < len(palette) {
c = palette[i]
}
default:
return nil, errors.New("ico: unsupported BMP bits per pixel")
}
img.SetNRGBA(x, y, c)
}
}
if bpp == 32 && hasAlpha {
return img, nil // its alpha, which the mask is not needed for
}
for y := range h {
mrow := maskStride * (h - 1 - y)
for x := range w {
i := mrow + x/8
transparent := i < len(mask) && mask[i]&(0x80>>(x%8)) != 0
c := img.NRGBAAt(x, y)
c.A = 255
if transparent {
c.A = 0
}
img.SetNRGBA(x, y, c)
}
}
return img, nil
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"strings"
"cogentcore.org/core/colors"
"cogentcore.org/core/core"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/units"
)
// IframeDefaultWidth and IframeDefaultHeight are the size in CSS pixels
// of an iframe without a width or height, as in browsers.
const (
IframeDefaultWidth = 300
IframeDefaultHeight = 150
)
// handleIframe handles an iframe element: a box of its size (300 by 150
// by default, as a replaced element), with the border of browsers unless
// it has frameborder="0". Its children are only for browsers without
// frames, and are not shown. The document in it is not read here: an app
// that shows them (as a web browser) puts it in the frame of the iframe
// from a widget handler (see [Context.WidgetHandlers]), as it has its own
// scripts and history.
func handleIframe(ctx *Context) core.Widget {
fr := New[core.Frame](ctx)
fb := strings.ToLower(strings.TrimSpace(GetAttr(ctx.Node, "frameborder")))
border := fb != "0" && fb != "no"
fr.Styler(func(s *styles.Style) {
// (its size is that of a replaced element: see [resolver.sizes])
s.Overflow.Set(styles.OverflowHidden) // its document scrolls itself
s.Padding.Zero()
s.Gap.Zero()
s.Direction = styles.Column
if border {
s.Border.Width.Set(units.Dp(2))
s.Border.Style.Set(styles.BorderInset)
s.Border.Color.Set(colors.Uniform(colors.Gray))
}
})
return fr
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"bytes"
"image"
"io"
"log/slog"
"net/http"
"regexp"
"sort"
"strconv"
"strings"
"cogentcore.org/core/htmlcore/css"
"cogentcore.org/core/styles"
svgpkg "cogentcore.org/core/svg"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/iox/imagex"
"cogentcore.org/core/core"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles/units"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
// handleSVG handles an svg element, which is rendered by an SVG widget.
func handleSVG(ctx *Context) {
var b strings.Builder
if err := html.Render(&b, ctx.svgForRender(ctx.Node)); err != nil {
return
}
sv := New[core.SVG](ctx)
errors.Log(sv.ReadString(b.String()))
ctx.handleWidget(ctx.Node, sv)
}
// svgProperties are the CSS properties of SVG elements that the SVG
// reader gets from their style attribute, which are given to it from the
// cascade of the page (as the rules of its style sheets for SVG icons).
var svgProperties = map[string]bool{
"fill": true, "fill-opacity": true, "fill-rule": true, "stroke": true, "stroke-width": true,
"stroke-opacity": true, "stroke-linecap": true, "stroke-linejoin": true, "stroke-dasharray": true,
"stroke-dashoffset": true, "stroke-miterlimit": true, "opacity": true, "display": true,
"color": true, "clip-path": true, "clip-rule": true, "mask": true, "font-size": true,
"font-family": true, "font-weight": true, "font-style": true, "text-anchor": true,
"stop-color": true, "stop-opacity": true, "vector-effect": true, "transform": true,
"visibility": true,
}
// svgRootSkip are the svgProperties that are not given for the svg element
// itself, which are those of its widget.
var svgRootSkip = map[string]bool{"display": true, "visibility": true, "opacity": true, "transform": true}
// svgForRender returns the given svg element as it is to be rendered: a
// copy of it whose elements have the values of the SVG properties of the
// cascade of the page (as of its style sheets, which the SVG reader does
// not know) in their style attribute, with the var() functions in their
// attributes (as in fill, as in the icons of BBC News) replaced by the
// values of the custom properties of their elements, and the attributes
// whose var() functions are invalid removed.
func (c *Context) svgForRender(n *html.Node) *html.Node {
var clone func(n *html.Node) *html.Node
clone = func(n *html.Node) *html.Node {
cn := &html.Node{Type: n.Type, Data: n.Data, DataAtom: n.DataAtom, Namespace: n.Namespace}
style := c.svgStyle(n, n == c.Node || n.Data == "svg" && n.Parent != nil && n.Parent.Namespace != "svg")
for _, a := range n.Attr {
if a.Key == "style" && n.Type == html.ElementNode {
continue // in style
}
if _, ok := style[a.Key]; ok {
continue // the style has precedence over presentation attributes
}
if strings.Contains(a.Val, "var(") {
v, ok := c.substituteVars(n, a.Val, nil)
if !ok {
continue
}
a.Val = v
}
cn.Attr = append(cn.Attr, a)
}
if len(style) > 0 {
props := make([]string, 0, len(style))
for p := range style {
props = append(props, p)
}
sort.Strings(props)
var sb strings.Builder
for i, p := range props {
if i > 0 {
sb.WriteString("; ")
}
sb.WriteString(p)
sb.WriteString(": ")
sb.WriteString(style[p])
}
cn.Attr = append(cn.Attr, html.Attribute{Key: "style", Val: sb.String()})
}
for ch := n.FirstChild; ch != nil; ch = ch.NextSibling {
cn.AppendChild(clone(ch))
}
return cn
}
return clone(n)
}
// svgStyle returns the values of the SVG properties of the given element
// in the cascade of the page (its style sheets and style attribute, with
// var() resolved, not the defaults of the browser), as the SVG reader
// understands them; for the root svg element, without those of its widget.
func (c *Context) svgStyle(n *html.Node, root bool) map[string]string {
if n.Type != html.ElementNode {
return nil
}
var style map[string]string
for _, d := range c.declarations(n) { // in the order of the cascade: the last one wins
if d.origin == css.OriginUserAgent || !svgProperties[d.Property] || (root && svgRootSkip[d.Property]) {
continue
}
if style == nil {
style = map[string]string{}
}
v := strings.TrimSpace(d.Value)
if d.invalid || v == "" || strings.Contains(v, "var(") {
delete(style, d.Property)
continue
}
switch d.Property {
case "visibility": // hidden as not displayed (the SVG reader has no visibility)
if strings.EqualFold(v, "hidden") || strings.EqualFold(v, "collapse") {
style["display"] = "none"
}
continue
case "transform": // CSS units, which SVG transforms do not have
t, ok := svgTransform(c.readEnv(), v)
if !ok {
delete(style, d.Property) // (as an invalid declaration)
continue
}
v = t
}
style[d.Property] = v
}
return style
}
// cssTransformUnits matches the units of the numbers of CSS transforms that
// are the user units of SVG transforms (px, and deg for angles).
// svgTransform returns the given CSS transform as an SVG transform, of
// numbers in user units (px) and degrees, with the given lengths, or false
// if it cannot be one (as for percentages, which are of the box of the
// element, or calc): the SVG reader logged errors for the units of CSS (as
// translate(-.5em, 0), whose e it read as an exponent, on bicycling.com).
func svgTransform(env *css.LengthEnv, v string) (string, bool) {
v = strings.TrimSpace(v)
if strings.EqualFold(v, "none") {
return v, true
}
var out []string
for rest := v; rest != ""; {
p, e := strings.IndexByte(rest, '('), strings.IndexByte(rest, ')')
if p <= 0 || e < p {
return "", false
}
name := strings.ToLower(strings.TrimSpace(rest[:p]))
args := strings.FieldsFunc(rest[p+1:e], func(r rune) bool { return r == ',' || r == ' ' || r == '\t' })
rest = strings.TrimSpace(rest[e+1:])
nums := make([]string, len(args))
for i, a := range args {
var f float32
switch name {
case "rotate", "skew", "skewx", "skewy":
if _, err := strconv.ParseFloat(strings.TrimRight(a, "degratun"), 32); err != nil {
return "", false
}
f = css.Angle(a)
case "scale", "scalex", "scaley", "matrix":
n, err := strconv.ParseFloat(a, 32)
if err != nil {
return "", false
}
f = float32(n)
case "translate", "translatex", "translatey":
px, ok := env.LengthPx(a)
if !ok {
if n, err := strconv.ParseFloat(a, 32); err == nil && n == 0 {
px, ok = 0, true
}
}
if !ok {
return "", false
}
f = px
default:
return "", false // (as translate3d, which SVG has not)
}
nums[i] = strconv.FormatFloat(float64(f), 'g', -1, 32)
}
out = append(out, name+"("+strings.Join(nums, ",")+")")
}
return strings.Join(out, " "), len(out) > 0
}
func handleImage(ctx *Context, _ string) core.Widget {
n := ctx.Node
src, density := ctx.imageSource(n) // of its srcset or picture, or its src
if src == "" {
if n.DataAtom != atom.Img {
return nil // an image without a source is not shown
}
// an img without a source (as a lazy image, whose source its
// scripts set as it is shown) has an image widget without an
// image, which shows nothing, in which its image is set when its
// source is (see Context.imageChange)
img := New[core.Image](ctx)
img.Styler(func(s *styles.Style) { s.ObjectFit = styles.FitFill })
img.NaturalDp = true
img.SetTooltip(GetAttr(n, "alt"))
if fsrc, fdensity := ctx.noscriptImage(n); fsrc != "" {
// the image of its noscript, until its scripts set its source
// (as the many lazy images of nytimes.com, which were gray
// boxes until its scripts set them, 20-50s later), gotten in
// the background if it can be (see Context.AsyncImages), as it
// is gotten before the page is read (see Context.PrefetchURLs)
img.Density = fdensity
img.SetProperty("src", fsrc)
if ctx.AsyncImages == nil {
if im, err := readImage(ctx, fsrc); err == nil {
img.SetImage(im)
}
return img
}
async := ctx.AsyncImages
go func() {
im, err := readImage(ctx, fsrc)
if err != nil || im == nil {
return
}
async(func() {
if img.Scene == nil || img.Parent == nil || img.Image != nil {
return // (not in the page, or its scripts set its image)
}
if s, _ := img.Property("src").(string); s != fsrc {
return // (its scripts set its source)
}
img.SetImage(im)
img.NeedsLayout()
})
}()
}
return img
}
alt := GetAttr(n, "alt")
isSVG := strings.HasSuffix(src, ".svg") || strings.HasPrefix(src, "data:image/svg")
var newWidget core.Widget
var resp *http.Response
var err error
// imageError handles an error getting the image, which is only logged
// at the debug level, as browsers just do not show images that are
// missing or not supported.
imageError := func(err error) bool {
if err == nil {
return false
}
slog.Debug("error loading image", "url", src, "err", err)
return true
}
var svgData []byte
if !ctx.DelayedImageLoad && isSVG {
resp, err = getImage(ctx, src)
if imageError(err) {
return nil
}
defer resp.Body.Close()
}
var im image.Image
if !ctx.DelayedImageLoad && !isSVG && ctx.ImageCache == nil {
// An image is an svg by its type (not only the extension of its URL).
resp, err = getImage(ctx, src)
if imageError(err) {
return nil
}
data, err := io.ReadAll(resp.Body)
resp.Body.Close()
if imageError(err) {
return nil
}
if strings.Contains(resp.Header.Get("Content-Type"), "svg") || looksLikeSVG(data) {
isSVG, svgData = true, data
} else if im, err = decodeImage(bytes.NewReader(data)); imageError(err) {
return nil
}
} else if !ctx.DelayedImageLoad && !isSVG {
im, err = readImage(ctx, src)
if imageError(err) {
return nil
}
}
// A filter (as the white wedges of pkg.go.dev, grey icons inverted) is
// applied to the pixels of the image, and to those of an svg rendered
// at twice its size (shown as an image of its size).
var filteredSize math32.Vector2
if filter := css.ParseFilter(ctx.declaration(n, "filter")); filter != nil && !ctx.DelayedImageLoad {
if isSVG {
data := svgData
if data == nil && resp != nil {
data, _ = io.ReadAll(resp.Body)
svgData = data
}
w, h, ok := svgSize(data)
if !ok {
w, h = 24, 24
}
sv := svgpkg.NewSVG(math32.Vec2(math32.Ceil(2*w), math32.Ceil(2*h)))
if sv.ReadXML(bytes.NewReader(data)) == nil {
im, isSVG = filter.Apply(sv.RenderImage()), false
filteredSize = math32.Vec2(w, h)
}
} else if im != nil {
im = filter.Apply(im)
}
}
// Can be either image or svg.
var img *core.Image
var svg *core.SVG
if isSVG {
svg = New[core.SVG](ctx)
svg.SetTooltip(alt)
if !ctx.DelayedImageLoad {
data, err := svgData, error(nil)
if data == nil {
data, err = io.ReadAll(resp.Body)
}
if errors.Log(err) == nil {
errors.Log(svg.Read(bytes.NewReader(data)))
if w, h, ok := svgSize(data); ok { // its intrinsic size
svg.SetProperty("svg-size", math32.Vec2(w, h))
}
}
}
newWidget = svg
} else {
img = New[core.Image](ctx)
// stretched to its box, as for object-fit: fill, the default of
// CSS (it kept its aspect ratio, as the tiles of the challenges of
// reCAPTCHA, of the image of all of the tiles, which showed the
// wrong parts of it); before the styler of its CSS (object-fit)
img.Styler(func(s *styles.Style) { s.ObjectFit = styles.FitFill })
img.NaturalDp = true // in CSS px (see core.Image.NaturalDp)
img.Density = density // of its srcset candidate
img.SetTooltip(alt)
img.SetProperty("src", src) // for generatehtml
img.SetImage(im)
if filteredSize != (math32.Vector2{}) {
img.SetProperty("svg-size", filteredSize) // its intrinsic size
}
newWidget = img
}
if !ctx.DelayedImageLoad {
return newWidget
}
go func() {
if svg == nil {
im, err := readImage(ctx, src)
if logGetError(err) != nil {
return
}
img.AsyncLock()
img.SetImage(im)
img.Update()
img.AsyncUnlock()
return
}
resp, err := getImage(ctx, src)
if logGetError(err) != nil {
return
}
defer resp.Body.Close()
svg.AsyncLock()
errors.Log(svg.Read(resp.Body))
svg.Update()
svg.AsyncUnlock()
}()
return newWidget
}
// readImage returns the decoded image at the given URL, using
// [Context.ImageCache] if it is set. A decoding error is logged
// and gives a nil image without an error, as the image widget is
// still made then.
func readImage(ctx *Context, src string) (image.Image, error) {
cache := ctx.ImageCache
key := ""
if cache != nil {
u, err := parseRelativeURL(src, ctx.PageURL)
if err != nil {
return nil, err
}
key = u.String()
cache.waitDecoding(key) // (as it is gotten before the page is read)
if im := cache.Get(key); im != nil {
return im, nil
}
if cache.Failed(key) {
return nil, nil // (not tried again)
}
}
resp, err := getImage(ctx, src)
if err != nil {
if cache != nil {
cache.AddFailed(key)
}
return nil, err
}
defer resp.Body.Close()
im, err := decodeImage(resp.Body)
if err != nil {
// browsers just do not show images that are not supported
slog.Debug("error loading image", "url", src, "err", err)
if cache != nil {
cache.AddFailed(key)
}
return nil, nil
}
if cache != nil {
cache.Add(key, im)
}
return im, nil
}
// getImage returns the response for the image at the given URL, also
// for an error status if it has an image (as the default icon of the
// favicons of duckduckgo.com, which browsers show, with a status of 404).
func getImage(ctx *Context, src string) (*http.Response, error) {
resp, err := Get(ctx, src)
if err == nil || resp == nil || !strings.HasPrefix(resp.Header.Get("Content-Type"), "image/") {
return resp, err
}
u, perr := parseRelativeURL(src, ctx.PageURL)
if perr != nil {
return resp, err
}
again, gerr := ctx.GetURL(u.String()) // with its body, which Get closed
if gerr != nil {
return resp, err
}
return again, nil
}
// decodeImage decodes the image in the given reader, of any format that
// is registered, as ICO (see ico.go), which [imagex.Read] decodes but
// returns an error for, as it is not one of its formats.
func decodeImage(r io.Reader) (image.Image, error) {
im, _, err := imagex.Read(r)
if im != nil {
return im, nil
}
return nil, err
}
// looksLikeSVG returns whether the given image data is an SVG document.
func looksLikeSVG(data []byte) bool {
head := data[:min(len(data), 512)]
return bytes.Contains(head, []byte("<svg")) || (bytes.HasPrefix(bytes.TrimSpace(head), []byte("<?xml")) && bytes.Contains(data[:min(len(data), 4096)], []byte("<svg")))
}
// svgRootTag matches the start tag of the root svg element.
var svgRootTag = regexp.MustCompile(`(?is)<svg\b[^>]*>`)
// svgAttr matches an attribute of a start tag.
var svgAttr = regexp.MustCompile(`(?is)\s(width|height|viewBox)\s*=\s*["']([^"']*)["']`)
// svgSize returns the intrinsic size of the given SVG document, in px,
// from the width and height of its root element, or the size of its view
// box for those that are not set, as for the size of an img of it.
func svgSize(data []byte) (w, h float32, ok bool) {
env := css.DefaultLengthEnv() // only absolute lengths are used
tag := svgRootTag.Find(data)
if tag == nil {
return 0, 0, false
}
var vw, vh float32
for _, m := range svgAttr.FindAllSubmatch(tag, -1) {
v := string(m[2])
switch strings.ToLower(string(m[1])) {
case "width":
if l, lok := env.Length(v, units.UnitPw); lok && l.Unit == units.UnitDp {
w = l.Value
}
case "height":
if l, lok := env.Length(v, units.UnitPh); lok && l.Unit == units.UnitDp {
h = l.Value
}
case "viewbox":
vb := strings.Fields(strings.ReplaceAll(v, ",", " "))
if len(vb) == 4 {
x, _ := strconv.ParseFloat(vb[2], 32)
y, _ := strconv.ParseFloat(vb[3], 32)
vw, vh = float32(x), float32(y)
}
}
}
switch {
case w > 0 && h == 0 && vw > 0:
h = w * vh / vw
case h > 0 && w == 0 && vh > 0:
w = h * vw / vh
case w == 0 && h == 0:
w, h = vw, vh
}
return w, h, w > 0 && h > 0
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"bytes"
"container/list"
"image"
"sync"
)
// ImageCache is a cache of decoded images, keyed by their resolved URL,
// so that rebuilding a page does not decode the same images again.
// It keeps the most recently used images up to a total size in bytes,
// and it is safe for concurrent use.
//
// The images of the current read of a page (see [ImageCache.NewRead]) are
// not removed for others: when they do not all fit, the rest are not
// cached, so that the next read finds most of them, not none (a plain
// LRU, read in the same order each time, removes each image before the
// next read gets to it, as the photos of nytimes.com, which were decoded
// again in each of the reads of the page that its scripts make, in 4-7s).
// The URLs of images that could not be gotten or decoded are kept too,
// so that they are not tried again.
//
// The cached images are shared by all of the widgets that show them,
// so they must not be modified. Images are only read when they are
// rendered: [core.Image] and the resizing and cropping functions of
// imagex make new images.
type ImageCache struct {
// MaxBytes is the maximum total size of the cached images, in bytes
// of decoded pixels. The least recently used images are removed
// to keep the total size within it, and an image larger than it
// is not cached.
MaxBytes int
// mu protects the fields below.
mu sync.Mutex
// images has the element of lru for each cached URL.
images map[string]*list.Element
// lru has the cached images, most recently used first.
lru list.List
// bytes is the total size of the cached images.
bytes int
// read is the number of the current read (see [ImageCache.NewRead]).
read uint64
// failed has the URLs of the images that could not be gotten or
// decoded.
failed map[string]bool
// decoding has the URLs of the images that are being decoded (see
// [ImageCache.Decode]), with a channel that is closed when they have
// been.
decoding map[string]chan struct{}
}
// imageCacheEntry is an entry of [ImageCache.lru].
type imageCacheEntry struct {
url string
image image.Image
bytes int
read uint64 // the read that last used it
}
// NewImageCache returns a new [ImageCache] that keeps images up to
// the given total size in bytes.
func NewImageCache(maxBytes int) *ImageCache {
return &ImageCache{MaxBytes: maxBytes, images: map[string]*list.Element{}}
}
// Get returns the cached image for the given resolved URL, or nil.
func (ic *ImageCache) Get(url string) image.Image {
ic.mu.Lock()
defer ic.mu.Unlock()
e := ic.images[url]
if e == nil {
return nil
}
ic.lru.MoveToFront(e)
ent := e.Value.(*imageCacheEntry)
ent.read = ic.read
return ent.image
}
// NewRead starts a new read of a page, whose images are then kept over
// those of the reads before it (see [ImageCache]).
func (ic *ImageCache) NewRead() {
ic.mu.Lock()
defer ic.mu.Unlock()
ic.read++
}
// Failed returns whether the image of the given resolved URL could not be
// gotten or decoded before (see [ImageCache.AddFailed]).
func (ic *ImageCache) Failed(url string) bool {
ic.mu.Lock()
defer ic.mu.Unlock()
return ic.failed[url]
}
// AddFailed records that the image of the given resolved URL could not be
// gotten or decoded, so that it is not tried again.
func (ic *ImageCache) AddFailed(url string) {
ic.mu.Lock()
defer ic.mu.Unlock()
if ic.failed == nil {
ic.failed = map[string]bool{}
}
ic.failed[url] = true
}
// Add adds the given image for the given resolved URL to the cache,
// removing the least recently used images as needed to stay within
// [ImageCache.MaxBytes].
func (ic *ImageCache) Add(url string, img image.Image) {
n := imageBytes(img)
ic.mu.Lock()
defer ic.mu.Unlock()
if e := ic.images[url]; e != nil {
ic.remove(e)
}
if n > ic.MaxBytes {
return
}
// the least recently used images that are not of the current read
for ic.bytes+n > ic.MaxBytes {
back := ic.lru.Back()
if back == nil || ic.read != 0 && back.Value.(*imageCacheEntry).read == ic.read {
return // (no room: the images of this read are kept)
}
ic.remove(back)
}
ic.images[url] = ic.lru.PushFront(&imageCacheEntry{url: url, image: img, bytes: n, read: ic.read})
ic.bytes += n
}
// Reset removes all of the images from the cache.
func (ic *ImageCache) Reset() {
ic.mu.Lock()
defer ic.mu.Unlock()
clear(ic.images)
clear(ic.failed)
ic.lru.Init()
ic.bytes = 0
}
// remove removes the given element of lru from the cache.
func (ic *ImageCache) remove(e *list.Element) {
ent := ic.lru.Remove(e).(*imageCacheEntry)
delete(ic.images, ent.url)
ic.bytes -= ent.bytes
}
// imageBytes returns the size of the decoded pixels of the given image.
func imageBytes(img image.Image) int {
sz := img.Bounds().Size()
bpp := 4
switch img.(type) {
case *image.Gray, *image.Alpha, *image.Paletted:
bpp = 1
case *image.Gray16, *image.Alpha16:
bpp = 2
case *image.RGBA64, *image.NRGBA64:
bpp = 8
}
return sz.X * sz.Y * bpp
}
// Decode decodes the given data of the image at the given (absolute) URL
// and adds it to the cache, or records that it failed, unless it is
// cached or being decoded already, as for the images of a page that are
// gotten before it is read, in parallel (as browsers do), so that reading
// the page, which decodes its images one at a time, finds them decoded
// (the large photos of bbc.com took most of the 2s of its first read). A
// page that reads it meanwhile waits for it (see [ImageCache.waitDecoding]).
// SVG images are not decoded (they are rendered as they are read).
func (ic *ImageCache) Decode(url string, data []byte) {
if looksLikeSVG(data) {
return
}
ic.mu.Lock()
if ic.images[url] != nil || ic.failed[url] || ic.decoding[url] != nil {
ic.mu.Unlock()
return
}
if ic.decoding == nil {
ic.decoding = map[string]chan struct{}{}
}
done := make(chan struct{})
ic.decoding[url] = done
ic.mu.Unlock()
defer func() {
ic.mu.Lock()
delete(ic.decoding, url)
ic.mu.Unlock()
close(done)
}()
im, err := decodeImage(bytes.NewReader(data))
if err != nil || im == nil {
ic.AddFailed(url)
return
}
ic.Add(url, im)
}
// waitDecoding waits for the image at the given URL to be decoded, if it
// is being decoded (see [ImageCache.Decode]).
func (ic *ImageCache) waitDecoding(url string) {
ic.mu.Lock()
done := ic.decoding[url]
ic.mu.Unlock()
if done != nil {
<-done
}
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"image"
"strings"
"cogentcore.org/core/core"
"cogentcore.org/core/htmlcore/css"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
// The images of img elements whose sources change (as lazy loaders set
// them as they are shown) are set in their widgets, without reading
// anything again: the img elements are inline, so they were read again
// with the nearest elements that they are in that could be, which for the
// lazy images of nytimes.com, set at once, was its #app (4600 elements,
// for 0.9s).
// imageSwap is the new image of the widget of an img element whose source
// has changed (see [Context.imageChange]).
type imageSwap struct {
n, img *html.Node // the changed element, and its img
w *core.Image
src string
density float32
im image.Image
// restyle is whether its class or style changed too, for which it is
// styled again (see Context.updateDecls)
restyle bool
}
// imageAttrs are the attributes of img and source elements that only
// choose their images.
var imageAttrs = map[string]bool{"src": true, "srcset": true, "sizes": true, "loading": true,
"decoding": true, "fetchpriority": true, "media": true, "type": true}
// imageChange returns the new image of the img element whose image the
// change of the given element changes, if that is all that it changes:
// the attributes that choose the image (see [imageAttrs]) of an img, or of
// a source of its picture, with a widget of its own (see [handleImage]),
// that no style rule selects by those attributes. It does not get the
// image (see [imageSwap.load]).
func (c *Context) imageChange(n *html.Node, srcRules *int) (*imageSwap, bool) {
if c.snaps == nil || c.DelayedImageLoad || n.Type != html.ElementNode || n.Namespace != "" {
return nil, false
}
o, ok := c.snaps[n]
if !ok || o.id != GetAttr(n, "id") {
return nil, false
}
// (its class and style may change too, as lazy loaders mark the images
// that they have loaded, for which it is restyled; see restyle)
restyle := o.class != GetAttr(n, "class") || o.style != GetAttr(n, "style")
ov, nv := attrValues(o.others), attrValues(otherAttrs(n))
for k, v := range ov {
if w, ok := nv[k]; (!ok || w != v) && !imageAttrs[k] && !c.inertAttr(k) {
return nil, false
}
}
for k := range nv {
if _, ok := ov[k]; !ok && !imageAttrs[k] && !c.inertAttr(k) {
return nil, false
}
}
img := n
switch n.DataAtom {
case atom.Img:
case atom.Source:
img = nil
if p := n.Parent; p != nil && p.DataAtom == atom.Picture {
for k := n.NextSibling; k != nil && img == nil; k = k.NextSibling {
if k.Type == html.ElementNode && k.DataAtom == atom.Img {
img = k
}
}
}
if img == nil {
return nil, false
}
default:
return nil, false
}
ws := c.elementWidgets[img]
if len(ws) != 1 || ownNode(ws[0]) != img {
return nil, false
}
w, ok := ws[0].(*core.Image)
if !ok || css.ParseFilter(c.declaration(img, "filter")) != nil {
return nil, false
}
src, density := c.imageSource(img)
if src == "" || strings.HasSuffix(src, ".svg") || strings.HasPrefix(src, "data:image/svg") {
return nil, false // (no image, or an svg, which has another widget)
}
if *srcRules < 0 {
*srcRules = 0
for _, r := range c.rules {
if strings.Contains(r.text, "[src") || strings.Contains(r.text, "[loading") || strings.Contains(r.text, "[sizes") {
*srcRules = 1
break
}
}
}
if *srcRules > 0 {
return nil, false // (selected by them, which are not matched again)
}
return &imageSwap{n: n, img: img, w: w, src: src, density: density, restyle: restyle && n == img}, !restyle || n == img
}
// load gets the image of the swap, and records the state of its element,
// as it has been styled for it.
func (sw *imageSwap) load(c *Context) {
// (from the image cache, if it has been gotten, as for the image of
// its noscript; the widget is not read here, without its lock)
sw.im, _ = readImage(c, sw.src) // (none if it can not be gotten, as for an error)
if !sw.restyle {
c.resnap(sw.n) // (as updateDecls does for those that it styles again)
}
}
// resnap records the state of the given element (see [nodeSnap]), as its
// declarations are for it.
func (c *Context) resnap(n *html.Node) {
if p := n.Parent; p != nil {
snapChildren(p, func(k *html.Node, s nodeSnap) {
if k == n {
c.snaps[k] = s
}
})
}
}
// inertAttr returns whether a change of the given attribute changes nothing
// that is rendered: a custom one, with a hyphen (as data-*, and the
// pinger-seen that the analytics of nytimes.com add to the images that they
// have seen, for which they were read again; not those of the context, as
// for :hover), that no style rule selects elements by.
func (c *Context) inertAttr(name string) bool {
if !strings.Contains(name, "-") || strings.HasPrefix(name, "data-htmlcore-") || strings.Contains(name, ":") ||
name == "http-equiv" || name == "accept-charset" {
return false
}
if n := len(c.rules) + len(c.pseudoRules); c.attrsSelected == nil || c.attrsRules != n {
c.attrsSelected, c.attrsRules = map[string]bool{}, n
}
sel, ok := c.attrsSelected[name]
if !ok {
for _, r := range c.rules {
if sel = hasAttrSelector(r.text, name); sel {
break
}
}
for _, r := range c.pseudoRules {
if sel = sel || hasAttrSelector(r.text, name); sel {
break
}
}
c.attrsSelected[name] = sel
}
return !sel
}
// inertChange returns whether the given element, which has widgets of its
// own, has changed only in its attributes whose changes change nothing that
// is rendered (see [Context.inertAttr]). (The attributes of the elements
// without widgets, in runs of text, are in the markup of the text.)
func (c *Context) inertChange(n *html.Node) bool {
if c.snaps == nil || n.Type != html.ElementNode {
return false
}
if ws := c.elementWidgets[n]; len(ws) == 0 || ownNode(ws[0]) != n {
return false
}
o, ok := c.snaps[n]
if !ok || o.class != GetAttr(n, "class") || o.id != GetAttr(n, "id") || o.style != GetAttr(n, "style") {
return false
}
others := otherAttrs(n)
if others == o.others {
return false // (a change of its states, as for :hover)
}
ov, nv := attrValues(o.others), attrValues(others)
for k, v := range ov {
if w, ok := nv[k]; (!ok || w != v) && !c.inertAttr(k) {
return false
}
}
for k := range nv {
if _, ok := ov[k]; !ok && !c.inertAttr(k) {
return false
}
}
return true
}
// apply sets the image of the swap in its widget, with the lock of the
// widgets of the page held.
func (sw *imageSwap) apply() {
w := sw.w
w.Density = sw.density
w.SetProperty("src", sw.src)
w.SetImage(sw.im)
w.NeedsLayout()
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"fmt"
"html"
"regexp"
"strconv"
"strings"
"unicode"
"unicode/utf8"
"cogentcore.org/core/colors"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/htmlcore/css"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/tree"
xhtml "golang.org/x/net/html"
)
// The inline content of block elements is read
// in runs of consecutive inline-level nodes: the text of a run (its text
// nodes and the elements of text, such as span and b) is made into one
// [core.Text], with the inline elements as rich text markup, and a run that
// also has inline widgets (such as img and button) is put in a row that
// wraps, an inline container.
// anonymousInline is the display of an inline container.
const anonymousInline = "anonymous-inline"
// isInlineLevel returns whether the given node is inline-level content,
// which is read in a run of inline content.
func (c *Context) isInlineLevel(n *xhtml.Node) bool {
switch n.Type {
case xhtml.TextNode, xhtml.CommentNode:
return true
case xhtml.ElementNode:
if _, ok := c.ElementHandlers[n.Data]; ok {
return false
}
if n.Data == "colgroup" || n.Data == "col" {
return false // the columns of a table, which have no boxes
}
if c.absoluteInRun(n) {
// out of the flow, in the run where it is, which it does not
// break into lines (as the reply info of the postings of
// craigslist.org, between the reply button and the actions)
return true
}
switch c.displayOf(n) {
case "", "inline", "inline-block", "inline-flex", "inline-grid", "inline-table":
return true
}
}
return false
}
// isInlineBox returns whether the given inline element is a box of its
// own in its line, which is not all text in the markup of a [core.Text]
// (which has no borders or padding): an element with a border that does
// not wrap (as the tags of lobste.rs, with rounded corners), or with a
// border or horizontal padding and no text beside it (as the padded links
// of the footer of lobste.rs, in a nav). Elements in text that wraps (as
// links with a bottom border, or code with padding) are text.
func (c *Context) isInlineBox(n *xhtml.Node) bool {
// only an element of text, which is text otherwise (with no images)
for ch := n.FirstChild; ch != nil; ch = ch.NextSibling {
if !c.isTextElement(ch) {
return false
}
}
border := false
for _, prop := range []string{"border", "border-top", "border-right", "border-bottom", "border-left", "border-width", "border-style"} {
if v := strings.ToLower(strings.TrimSpace(c.declaration(n, prop))); !noLength(v) {
border = true
break
}
}
if ws := strings.TrimSpace(c.declaration(n, "white-space")); border && (ws == "nowrap" || ws == "pre") {
return true
}
padding := border
for _, prop := range []string{"padding-left", "padding-right", "padding-inline", "padding-inline-start", "padding-inline-end"} {
if !noLength(strings.TrimSpace(c.declaration(n, prop))) {
padding = true
}
}
if v := strings.Fields(c.declaration(n, "padding")); len(v) > 0 {
// the horizontal padding is the second value, or the only one
h := v[0]
if len(v) > 1 {
h = v[1]
}
padding = padding || !noLength(h)
}
if !padding || n.Parent == nil || n.Parent.Type != xhtml.ElementNode {
return false
}
// in a block, not in an inline element (whose margins would be lost,
// as the links of the navigation of w3.org, in inline items)
switch strings.TrimSpace(c.declaration(n.Parent, "display")) {
case "", "inline", "contents":
return false
}
for s := n.Parent.FirstChild; s != nil; s = s.NextSibling {
if s.Type == xhtml.TextNode && strings.TrimSpace(s.Data) != "" {
return false
}
}
return true
}
// noLength returns whether the given CSS value is no length (or none).
func noLength(v string) bool {
v = strings.ToLower(v)
return v == "" || strings.Contains(v, "none") || strings.Contains(v, "hidden") || v == "0" || strings.HasPrefix(v, "0 ") || strings.HasPrefix(v, "0px")
}
// absoluteInRun returns whether the given element is absolutely positioned
// (or fixed) between inline-level content in a block container, which it is
// in the run of, as it is out of the flow (in CSS, it is blockified, but it
// does not break the line that it is in).
func (c *Context) absoluteInRun(n *xhtml.Node) bool {
pos := strings.TrimSpace(c.declaration(n, "position"))
if (pos != "absolute" && pos != "fixed") || n.Parent == nil || c.displayOf(n) == "none" {
return false
}
switch c.displayOf(n.Parent) {
case "flex", "inline-flex", "grid", "inline-grid":
return false
}
// the element (or text) before and after it, which are inline-level
sibling := func(next bool) *xhtml.Node {
s := n.PrevSibling
if next {
s = n.NextSibling
}
for s != nil {
if s.Type == xhtml.ElementNode || (s.Type == xhtml.TextNode && strings.TrimSpace(s.Data) != "") {
return s
}
if next {
s = s.NextSibling
} else {
s = s.PrevSibling
}
}
return nil
}
inline := func(s *xhtml.Node) bool {
if s == nil {
return false
}
if s.Type == xhtml.TextNode {
return true
}
if p := strings.TrimSpace(c.declaration(s, "position")); p == "absolute" || p == "fixed" {
return false
}
return c.isInlineLevel(s)
}
return inline(sibling(false)) && inline(sibling(true))
}
// isTextElement returns whether the given element is all text, which is
// represented in the markup of a [core.Text]: an element of text (such as
// span and b) that is displayed inline, with only text in it.
func (c *Context) isTextElement(n *xhtml.Node) bool {
switch n.Type {
case xhtml.TextNode, xhtml.CommentNode:
return true
case xhtml.ElementNode:
if _, ok := c.ElementHandlers[n.Data]; ok {
return false
}
switch n.Data {
case "img", "button", "input", "select", "textarea", "svg", "video", "audio", "iframe", "canvas", "object", "embed", "math":
return false
}
switch c.displayOf(n) {
case "", "inline", "none":
default:
return false
}
for ch := n.FirstChild; ch != nil; ch = ch.NextSibling {
if !c.isTextElement(ch) {
return false
}
}
return true
}
return false
}
// readInlineRun reads the run of inline content from first to last.
func (c *Context) readInlineRun(parent core.Widget, first, last *xhtml.Node) {
hasWidget := false
for n := first; ; n = n.NextSibling {
if n.Type == xhtml.ElementNode && !c.isTextElement(n) && c.displayOf(n) != "none" {
hasWidget = true
}
if n == last {
break
}
}
pre := c.isPre(first.Parent)
container := parent
newContainer := func() core.Widget {
fr := core.NewFrame(parent)
fr.SetName("inline-container")
tree.SetUniqueName(fr)
c.Node = nil
c.browserStyler(nil, fr, nil)
c.blocks[fr].display = anonymousInline
return fr
}
if hasWidget && c.display(parent) != anonymousInline {
container = newContainer()
}
var buf strings.Builder
start := true // at the start of the run
// flush makes a text of the inline content so far; between is whether
// it is between inline widgets (before one, after content)
flush := func(between bool) {
str := buf.String()
buf.Reset()
if pre && last.NextSibling == nil { // a last line break makes no line
str = lastBreak.ReplaceAllString(str, "$1")
}
if str != "" && strings.TrimSpace(str) == "" && !pre && between && container != parent {
// White space between inline widgets (as the words in inline
// blocks of the heading of github.com) is a space, as in
// browsers: a box as wide as one in the font, as a text of
// only a no-break space has no width (as trailing space).
sp := core.NewFrame(container)
sp.SetName("space")
tree.SetUniqueName(sp)
c.handleWidget(nil, sp)
sp.FinalStyler(func(s *styles.Style) {
s.Min.X = units.Em(0.28)
s.Grow.Set(0, 0)
})
c.blocks[sp].display = "inline"
return
}
if str == "" || (strings.TrimSpace(str) == "" && !pre) {
return
}
if !pre && !hasInlineContent(str) {
// a run of only empty elements (as a span with a tabindex,
// before the payload of reCAPTCHA) makes no line, as in browsers
return
}
if !pre {
// Spaces at the start and end of the run are not shown, but
// those next to inline widgets are, as non-breaking spaces.
lead, trail := "", ""
if !start && strings.HasPrefix(str, " ") {
lead = "\u00a0"
}
if strings.HasSuffix(str, " ") && container != parent {
trail = "\u00a0"
}
str = lead + strings.TrimSpace(str) + trail
// white space at the start of a line is not shown
str = brSpace.ReplaceAllString(str, "$1")
}
tx := core.NewText(container).SetText(str)
tx.HandleTextClick(func(tl *rich.Hyperlink, e events.Event) {
c.OpenURL(tl.URL, e)
})
c.handleWidget(nil, tx)
c.handleInLink(first.Parent, tx) // the element that the run is in
if container != parent || c.display(parent) == anonymousInline {
c.blocks[tx].display = "inline"
} else {
c.blocks[tx].display = "block"
}
}
// the text of the ::before and ::after of the element that the run is
// in, at its start and end (as for elements that are widgets, as the
// edit links of Wikipedia, which are inline blocks)
if el := first.Parent; el != nil && el.FirstChild == first {
buf.WriteString(c.pseudoMarkup(el, "before"))
}
for n := first; ; n = n.NextSibling {
if container != parent && n.Type == xhtml.ElementNode && n.Data == "br" {
// a line break in a row of widgets ends the row, and the
// widgets after it are in another row (each is aligned); one
// that ends an empty row (as the second of two after the logo
// of google.com) makes an empty line, as in browsers
if start && buf.Len() == 0 && !container.AsTree().HasChildren() {
buf.WriteString(" ")
}
flush(false)
start = true
container = newContainer()
if n == last {
break
}
continue
}
if n.Type == xhtml.ElementNode && !c.isTextElement(n) && c.displayOf(n) != "none" {
flush(!start)
start = false
c.inlineParent = container
c.BlockParent = container
readOneNode(c, container, n)
} else {
buf.WriteString(c.inlineMarkup(n, pre))
}
if n == last {
break
}
}
if el := last.Parent; el != nil && el.LastChild == last {
buf.WriteString(c.pseudoMarkup(el, "after"))
}
flush(false)
c.inlineParent = nil
}
// isPre returns whether the white space of the content of the given
// element is preserved.
func (c *Context) isPre(n *xhtml.Node) bool {
for ; n != nil; n = n.Parent {
if n.Type != xhtml.ElementNode {
continue
}
switch c.declaration(n, "white-space") {
case "pre", "pre-wrap", "pre-line", "break-spaces":
return true
case "normal", "nowrap":
return false
}
}
return false
}
// markupTag matches a tag of rich text markup.
var markupTag = regexp.MustCompile(`<[^>]*>`)
// hasInlineContent returns whether the given rich text markup has content
// that makes a line: text other than collapsible white space (a no-break
// space is content), or a line break.
func hasInlineContent(markup string) bool {
if strings.Contains(markup, "<br") {
return true
}
text := html.UnescapeString(markupTag.ReplaceAllString(markup, ""))
return strings.Trim(text, " \t\n\r\f") != ""
}
// brSpace matches a line break with the white space after it.
var brSpace = regexp.MustCompile(`(<br\s*/?>)[ \t\n\r\f]+`)
var spaceRun = regexp.MustCompile(`[ \t\n\r\f]+`)
// lastBreak matches a line break at the end of markup, before end tags.
var lastBreak = regexp.MustCompile(`\n((?:</[a-z0-9]+>)*)$`)
// inlineMarkup returns the rich text markup for the given node of text.
func (c *Context) inlineMarkup(n *xhtml.Node, pre bool) string {
switch n.Type {
case xhtml.TextNode:
t := n.Data
if !pre {
t = spaceRun.ReplaceAllString(t, " ")
}
return html.EscapeString(c.transformText(n, t))
case xhtml.ElementNode:
if c.displayOf(n) == "none" {
return ""
}
if n.Data == "br" {
return "<br>"
}
var sb strings.Builder
start, end := c.nodeMarkup(n, pre)
sb.WriteString(start)
sb.WriteString(c.pseudoMarkup(n, "before"))
for ch := n.FirstChild; ch != nil; ch = ch.NextSibling {
sb.WriteString(c.inlineMarkup(ch, pre))
}
sb.WriteString(c.pseudoMarkup(n, "after"))
sb.WriteString(end)
return sb.String()
}
return ""
}
// cssStyledTags are the rich text tags that have styles of their own in
// rich text (as a background for code), which are spans in preformatted
// text (as of pre elements), so that they only have their CSS styles
// there, without boxes behind the code in the boxes of the pre elements.
// Elsewhere they have their styles of rich text (code is monospace on a
// background), as in Cogent Core.
var cssStyledTags = map[string]bool{"code": true, "kbd": true, "samp": true, "tt": true, "mark": true}
// richTags are the tags that rich text markup has, which other inline
// elements are made into spans in place of.
var richTags = map[string]bool{
"a": true, "b": true, "strong": true, "i": true, "em": true, "var": true, "cite": true,
"u": true, "ins": true, "s": true, "del": true, "strike": true, "small": true, "big": true,
"sub": true, "sup": true, "code": true, "kbd": true, "samp": true, "tt": true, "q": true,
"mark": true, "abbr": true, "acronym": true, "span": true, "br": true, "dfn": true, "bdo": true,
}
// inlineProperties are the CSS properties of inline elements
// that are given to the rich text markup.
var inlineProperties = map[string]bool{
"color": true, "background-color": true, "background": true, "font-weight": true,
"font-style": true, "font-size": true, "font-family": true, "text-decoration": true,
"text-decoration-line": true,
}
// nodeMarkup returns the start and end tags of the markup for the given
// element of text, with the CSS styles of the element in its style,
// in preformatted text if pre.
func (c *Context) nodeMarkup(n *xhtml.Node, pre bool) (start, end string) {
tag := n.Data
if !richTags[tag] || (pre && cssStyledTags[tag]) {
tag = "span"
}
var sb strings.Builder
sb.WriteByte('<')
sb.WriteString(tag)
for _, a := range n.Attr {
if a.Key == "class" && (a.Val == "math inline" || a.Val == "math display") {
// the math of markdown, which rich text renders
fmt.Fprintf(&sb, ` class="%s"`, a.Val)
continue
}
if a.Key == "style" || a.Key == "class" || a.Key == "id" || strings.HasPrefix(a.Key, "data-") {
continue
}
fmt.Fprintf(&sb, ` %s="%s"`, a.Key, html.EscapeString(a.Val))
}
// The last declaration of each property is the one that applies,
// and one that inherits is that of the parent, which the span has.
var props []string
vals := map[string]string{}
for _, d := range c.declarations(n) {
if !inlineProperties[d.Property] || d.origin == css.OriginUserAgent || d.invalid {
continue
}
prop, val := d.Property, d.Value
if prop == "background" {
prop, val = "background-color", css.BackgroundColor(val)
if val == "" {
continue
}
}
if _, ok := vals[prop]; !ok {
props = append(props, prop)
}
vals[prop] = val
}
var style strings.Builder
for _, prop := range props {
val := vals[prop]
switch strings.ToLower(val) {
case "inherit", "unset", "revert", "revert-layer":
continue
}
switch prop {
case "font-weight":
if w, err := strconv.Atoi(val); err == nil {
val = "normal"
if w >= 600 {
val = "bold"
}
}
case "font-size":
val = c.relativeFontSize(n)
if val == "" {
continue
}
case "font-family":
if c.WebFonts && css.WebFontFamily(val) != "" {
// the custom font of the text (as the web font of the
// element of the text, which runs cannot have their own)
val = rich.Custom.String()
} else {
val = css.FontFamily(val).String()
}
case "color", "background-color":
if cl, ok := css.ColorFunction(val); ok { // as colors.FromString does not parse CSS alpha
val = colors.AsHex(cl)
} else if strings.Contains(val, "(") {
continue // a function that is not supported (as color-mix())
}
}
fmt.Fprintf(&style, "%s:%s;", prop, val)
}
if style.Len() > 0 {
fmt.Fprintf(&sb, ` style="%s"`, html.EscapeString(style.String()))
}
sb.WriteString(">")
return sb.String(), "</" + tag + ">"
}
// relativeFontSize returns the font size of the given inline element
// as a percentage of that of its parent, for rich text markup.
func (c *Context) relativeFontSize(n *xhtml.Node) string {
if n.Parent == nil {
return ""
}
f := c.fontSizePx(n) / c.fontSizePx(n.Parent)
if f <= 0 {
return ""
}
return strconv.FormatFloat(float64(100*f), 'f', 1, 32) + "%"
}
// fontSizePx returns the computed font size in px of the given element,
// from the declarations of it and its ancestors.
func (c *Context) fontSizePx(n *xhtml.Node) float32 {
if n == nil {
return 16
}
if n.Type != xhtml.ElementNode {
return c.fontSizePx(n.Parent)
}
v := strings.ToLower(c.declaration(n, "font-size"))
if v == "" || v == "inherit" {
return c.fontSizePx(n.Parent)
}
if px, ok := css.FontSizes[v]; ok {
return px
}
parent := c.fontSizePx(n.Parent)
num := func(suffix string) (float32, bool) {
f, err := strconv.ParseFloat(strings.TrimSuffix(v, suffix), 32)
return float32(f), err == nil
}
switch {
case v == "smaller":
return parent / 1.2
case v == "larger":
return parent * 1.2
case strings.HasSuffix(v, "%"):
if f, ok := num("%"); ok {
return parent * f / 100
}
case strings.HasSuffix(v, "rem"):
if f, ok := num("rem"); ok {
return 16 * f
}
case strings.HasSuffix(v, "em"):
if f, ok := num("em"); ok {
return parent * f
}
case strings.HasSuffix(v, "px"):
if f, ok := num("px"); ok {
return f
}
case strings.HasSuffix(v, "pt"):
if f, ok := num("pt"); ok {
return f * 96 / 72
}
}
return parent
}
// textTransform returns the text-transform of the element that the given
// text node is in, which is inherited ("" for none).
func (c *Context) textTransform(n *xhtml.Node) string {
for p := n.Parent; p != nil && p.Type == xhtml.ElementNode; p = p.Parent {
switch v := strings.ToLower(strings.TrimSpace(c.declaration(p, "text-transform"))); v {
case "", "inherit", "unset":
continue
case "none", "initial":
return ""
default:
return v
}
}
return ""
}
// transformText returns the given text of the given text node transformed
// by its text-transform: uppercase, lowercase, or capitalize, which makes
// the first letter of each word uppercase (as the headings of the results
// of google.com, as "Gesponsorde Producten").
func (c *Context) transformText(n *xhtml.Node, t string) string {
switch c.textTransform(n) {
case "uppercase":
return strings.ToUpper(t)
case "lowercase":
return strings.ToLower(t)
case "capitalize":
rs := []rune(t)
start := !continuesWord(n) // a word starts at the start of the text
for i, r := range rs {
if unicode.IsSpace(r) {
start = true
continue
}
if start && unicode.IsLetter(r) {
rs[i] = unicode.ToTitle(r)
}
start = false
}
return string(rs)
}
return t
}
// continuesWord returns whether the given text node continues a word that
// the text before it in its parent ends with (as "<b>Ge</b>sponsord").
func continuesWord(n *xhtml.Node) bool {
p := n.PrevSibling
for p != nil && p.Type == xhtml.CommentNode {
p = p.PrevSibling
}
if p == nil {
return false
}
t := nodeText(p)
if t == "" {
return false
}
r, _ := utf8.DecodeLastRuneInString(t)
return !unicode.IsSpace(r)
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"strconv"
"strings"
"cogentcore.org/core/core"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/text"
"golang.org/x/net/html"
)
// markerWidth is the width of the box of a list marker,
// which is in the padding of the list.
var markerWidth = units.Em(1.5)
// handleListItem handles a li element:
// it is a row of the marker and a block of the content of the item.
// The marker is to the left of the box of the item, in the padding
// of the list, as in browsers.
func handleListItem(ctx *Context) {
n := ctx.Node
li := New[core.Frame](ctx)
ctx.handleWidget(n, li)
li.Styler(func(s *styles.Style) {
s.Direction = styles.Row
// the marker is on the baseline of the first line of the content
s.Align.Items = styles.Baseline
})
if marker := listMarker(ctx, n); marker != "" {
mk := core.NewText(li).SetText(marker)
mk.SetName("marker")
ctx.handleWidget(nil, mk)
mk.Styler(func(s *styles.Style) {
s.SetAbilities(false, abilities.Selectable) // not in a selection, as in browsers
s.Min.X = markerWidth
s.Max.X = markerWidth
s.Grow.X = 0
s.GrowWrap = false
s.Text.Align = text.End
s.Text.WhiteSpace = text.WrapNever
})
}
content := core.NewFrame(li)
content.SetName("content")
ctx.handleWidget(nil, content)
if fid := li.Property("data-fid"); fid != nil { // the box of the item is that of its content
content.SetProperty("data-fid", fid)
delete(li.Properties, "data-fid")
}
ctx.blocks[content].display = "block"
content.FinalStyler(func(s *styles.Style) { s.Shrink.X = 1 }) // beside its marker
ctx.Node = n
ctx.NewParent = content
}
// listMarker returns the marker text for the given li element.
func listMarker(ctx *Context, n *html.Node) string {
list := n.Parent
styleType := ""
for p := n; p != nil && styleType == ""; p = p.Parent {
// the last of list-style-type and list-style applies
for _, d := range ctx.declarations(p) {
switch d.Property {
case "list-style-type":
styleType = strings.TrimSpace(d.Value)
case "list-style":
if fs := strings.Fields(d.Value); len(fs) > 0 {
styleType = fs[0]
for _, f := range fs {
if f != "inside" && f != "outside" && !strings.HasPrefix(f, "url(") {
styleType = f
break
}
}
}
}
}
if p == list {
break
}
}
if list == nil {
return "• "
}
if styleType == "" {
if list.Data == "ol" {
styleType = "decimal"
} else {
depth := 0
for p := list; p != nil; p = p.Parent {
if p.Data == "ul" || p.Data == "ol" {
depth++
}
}
switch depth {
case 1:
styleType = "disc"
case 2:
styleType = "circle"
default:
styleType = "square"
}
}
}
switch styleType {
case "none":
return ""
case "disc":
return "• "
case "circle":
return "◦ "
case "square":
return "▪ "
}
// numbered
num := 1
if st, err := strconv.Atoi(GetAttr(list, "start")); err == nil {
num = st
}
for p := list.FirstChild; p != nil && p != n; p = p.NextSibling {
if p.Type == html.ElementNode && p.Data == "li" {
num++
}
}
if v, err := strconv.Atoi(GetAttr(n, "value")); err == nil {
num = v
}
switch styleType {
case "lower-alpha", "lower-latin":
return string(rune('a'+(num-1)%26)) + ". "
case "upper-alpha", "upper-latin":
return string(rune('A'+(num-1)%26)) + ". "
}
return strconv.Itoa(num) + ". "
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"cogentcore.org/core/core"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/sides"
)
// collapseMargins collapses the given top and bottom margins (in dots) of
// the given block widget with the adjoining margins of its previous
// sibling and its parent, as browsers do. The margins of the widgets stay
// within their parents, but the space between them is that of the
// collapsed margins.
func (c *Context) collapseMargins(wb *core.WidgetBase, s, _ *styles.Style, bs, pbs *blockState, pad, bw sides.Floats, top, bottom *float32) {
flow := s.Display == styles.Flex && s.Direction == styles.Column
bs.openTop = flow && pad.Top == 0 && bw.Top == 0
bs.openBottom = flow && pad.Bottom == 0 && bw.Bottom == 0 && s.Min.Y.Value == 0
bs.topBase, bs.bottomBase = *top, *bottom
if pbs == nil || !bs.block || pbs.display != "block" && pbs.display != "list-item" && pbs.display != "table-cell" && pbs.display != "inline-block" {
return
}
pw := wb.Parent.(core.Widget)
prev, isLast := c.blockSiblings(pw, wb.This.(core.Widget))
adj := float32(0)
switch {
case prev != nil:
adj = c.chainBelow(prev)
case pbs.openTop:
adj = pbs.topBase
}
if *top >= 0 && adj > 0 {
*top = max(0, *top-adj)
}
bs.topBase = adj + *top
if isLast && pbs.openBottom {
base := pbs.bottomBase
if *bottom >= 0 && base > 0 {
*bottom = max(0, *bottom-base)
}
bs.bottomBase = base + *bottom
}
}
// blockSiblings returns the previous block sibling of the given widget,
// and whether it is the last child of the parent.
func (c *Context) blockSiblings(pw, w core.Widget) (prev core.Widget, isLast bool) {
kids := pw.AsTree().Children
idx := -1
for i, k := range kids {
if k == w {
idx = i
break
}
}
for i := idx - 1; i >= 0; i-- {
kw, ok := kids[i].(core.Widget)
if !ok {
continue
}
if kbs := c.blocks[kw]; kbs != nil && kbs.block && kw.AsWidget().Styles.Display != styles.DisplayNone {
prev = kw
break
}
}
return prev, idx == len(kids)-1
}
// chainBelow returns the total of the collapsed margins below the given
// block widget, through its last descendants.
func (c *Context) chainBelow(w core.Widget) float32 {
bs := c.blocks[w]
total := bs.bottomBase
for bs != nil && bs.openBottom {
kids := w.AsTree().Children
if len(kids) == 0 {
break
}
kw, ok := kids[len(kids)-1].(core.Widget)
if !ok {
break
}
kbs := c.blocks[kw]
if kbs == nil || !kbs.block {
break
}
w, bs = kw, kbs
total = bs.bottomBase
}
return total
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"bytes"
"image"
"image/color"
"io"
"strings"
"sync"
"cogentcore.org/core/base/iox/imagex"
"cogentcore.org/core/colors"
"cogentcore.org/core/colors/gradient"
"cogentcore.org/core/htmlcore/css"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/svg"
"golang.org/x/image/draw"
)
// cssMask is the mask of an element (mask-image and its size, position,
// and repeat), as for the icons of Wikipedia, which are the background
// color of empty elements shown through the mask of an SVG image.
type cssMask struct {
url, size, position string
repeat bool
noRepeatX, noRepeatY bool // (for repeat-y and repeat-x, which repeat on one axis)
hasRepeat bool
}
// maskSources are the data of the images of masks, by URL, for all pages,
// as they are used by many elements (as icons).
var maskSources struct {
sync.Mutex
data map[string]*maskSource
}
// maskSource is the image of a mask: an SVG (rasterized at the size of
// its use) or a raster image.
type maskSource struct {
svg []byte
raster image.Image
// size is the intrinsic size of the image in CSS px (0 if unknown).
size math32.Vector2
}
// maxMaskSources is the number of mask images that are kept.
const maxMaskSources = 512
// maskSourceOf returns the image of the mask at the given URL, getting it
// once for all pages, or nil if it cannot be gotten.
func (c *Context) maskSourceOf(u string) *maskSource {
key := u
if !strings.HasPrefix(u, "data:") {
if pu, err := parseRelativeURL(u, c.PageURL); err == nil {
key = pu.String()
}
}
maskSources.Lock()
src, ok := maskSources.data[key]
maskSources.Unlock()
if ok {
return src
}
src = c.fetchMaskSource(key)
maskSources.Lock()
if maskSources.data == nil || len(maskSources.data) >= maxMaskSources {
maskSources.data = map[string]*maskSource{}
}
maskSources.data[key] = src
maskSources.Unlock()
return src
}
// fetchMaskSource gets the image of a mask at the given URL.
func (c *Context) fetchMaskSource(u string) *maskSource {
resp, err := Get(c, u)
if err != nil {
return nil
}
defer resp.Body.Close()
data, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
if err != nil {
return nil
}
if strings.Contains(resp.Header.Get("Content-Type"), "svg") || looksLikeSVG(data) {
src := &maskSource{svg: data}
sv := svg.NewSVG(math32.Vec2(16, 16))
if sv.ReadXML(bytes.NewReader(data)) == nil {
src.size = math32.Vec2(sv.PhysicalWidth.Dots, sv.PhysicalHeight.Dots)
if src.size.X <= 0 || src.size.Y <= 0 {
src.size = sv.Root.ViewBox.Size
}
}
return src
}
img, _, err := imagex.Read(bytes.NewReader(data))
if err != nil {
return nil
}
return &maskSource{raster: img, size: math32.FromPoint(img.Bounds().Size())}
}
// maskFill is the background of an element with a mask: its color where
// the mask image (placed in the box of the element by the size, position
// and repeat of the mask) is opaque. It is a [gradient.Gradient] so that
// it is updated with the box of the element before it is rendered.
type maskFill struct {
base gradient.Base
color color.RGBA
src *maskSource
mask cssMask
// image is whether it is a background image (background-image), whose
// colors are drawn over the color, rather than a mask of the color.
image bool
// rgba is the tile of a background image.
rgba *image.RGBA
// dp is the number of dots per CSS px.
dp float32
mu sync.Mutex
placed image.Rectangle // the tile of the mask in the pixels of the box
box image.Rectangle
tile *image.Alpha
opacity float32
// inverse is the inverse of the rotation of the rendering (as of a
// caret with a rotate transform), if any, around the center of the
// box, with which pixels are mapped to the mask.
inverse math32.Matrix2
isRotated bool
}
func (mf *maskFill) AsBase() *gradient.Base { return &mf.base }
// CopyGradient returns a copy of the mask fill (as for its state colors),
// which places its mask again.
func (mf *maskFill) CopyGradient() gradient.Gradient {
cp := &maskFill{color: mf.color, src: mf.src, mask: mf.mask, dp: mf.dp, image: mf.image}
cp.base.ApplyFuncs = mf.base.ApplyFuncs.Clone()
return cp
}
func (mf *maskFill) ColorModel() color.Model { return color.RGBAModel }
func (mf *maskFill) Bounds() image.Rectangle { return image.Rect(-1e9, -1e9, 1e9, 1e9) }
// Update places the mask in the given box (in pixels), rendering its image
// at the size that it is placed at.
func (mf *maskFill) Update(opacity float32, box math32.Box2, objTransform math32.Matrix2) {
mf.mu.Lock()
defer mf.mu.Unlock()
mf.opacity = opacity
// the rotation (and skew) of the transform, without its translation
// and scale, which the box already has
rot := objTransform
rot.X0, rot.Y0 = 0, 0
sx, sy := rot.ExtractScale()
mf.isRotated = rot.XY != 0 || rot.YX != 0
if mf.isRotated && sx != 0 && sy != 0 {
c := box.Center()
rot = rot.Scale(1/sx, 1/sy)
mf.inverse = math32.Translate2D(c.X, c.Y).Mul(rot.Inverse()).Mul(math32.Translate2D(-c.X, -c.Y))
}
b := box.ToRect()
if b == mf.box && (mf.tile != nil || mf.rgba != nil) {
return
}
mf.box = b
bsz := math32.FromPoint(b.Size())
isz := mf.src.size.MulScalar(mf.dp)
if isz.X <= 0 || isz.Y <= 0 {
isz = bsz
}
sz := css.MaskSize(mf.mask.size, bsz, isz, mf.dp)
px, py := css.MaskPosition(mf.mask.position)
ox, oy := css.MaskOffset(mf.mask.position)
pos := math32.Vec2(px*(bsz.X-sz.X)+ox*mf.dp, py*(bsz.Y-sz.Y)+oy*mf.dp)
mf.placed = image.Rect(0, 0, int(math32.Round(sz.X)), int(math32.Round(sz.Y))).Add(b.Min).Add(image.Pt(int(math32.Round(pos.X)), int(math32.Round(pos.Y))))
if mf.image {
mf.rgba = mf.renderRGBA(mf.placed.Size())
return
}
mf.tile = mf.render(mf.placed.Size())
}
// renderRGBA renders the background image at the given size.
func (mf *maskFill) renderRGBA(size image.Point) *image.RGBA {
if size.X <= 0 || size.Y <= 0 || size.X > 4096 || size.Y > 4096 {
return nil
}
dst := image.NewRGBA(image.Rectangle{Max: size})
if mf.src.svg != nil {
sv := svg.NewSVG(math32.FromPoint(size))
if sv.ReadXML(bytes.NewReader(mf.src.svg)) != nil {
return nil
}
img := sv.RenderImage()
draw.Draw(dst, dst.Bounds(), img, img.Bounds().Min, draw.Src)
} else {
draw.CatmullRom.Scale(dst, dst.Bounds(), mf.src.raster, mf.src.raster.Bounds(), draw.Src, nil)
}
return dst
}
// render renders the mask image at the given size, as its alpha.
func (mf *maskFill) render(size image.Point) *image.Alpha {
if size.X <= 0 || size.Y <= 0 || size.X > 4096 || size.Y > 4096 {
return nil
}
var img image.Image
if mf.src.svg != nil {
sv := svg.NewSVG(math32.FromPoint(size))
if sv.ReadXML(bytes.NewReader(mf.src.svg)) != nil {
return nil
}
img = sv.RenderImage()
} else {
dst := image.NewRGBA(image.Rectangle{Max: size})
draw.CatmullRom.Scale(dst, dst.Bounds(), mf.src.raster, mf.src.raster.Bounds(), draw.Src, nil)
img = dst
}
a := image.NewAlpha(image.Rectangle{Max: size})
draw.Draw(a, a.Bounds(), img, img.Bounds().Min, draw.Src)
return a
}
// At returns the color of the background at the given pixel: its color,
// with the alpha of the mask there.
func (mf *maskFill) At(x, y int) color.Color {
mf.mu.Lock()
defer mf.mu.Unlock()
if mf.image {
return mf.imageAt(x, y)
}
if mf.tile == nil {
return color.RGBA{}
}
pt := image.Pt(x, y)
if mf.isRotated {
q := mf.inverse.MulPoint(math32.Vec2(float32(x)+0.5, float32(y)+0.5))
pt = image.Pt(int(math32.Floor(q.X)), int(math32.Floor(q.Y)))
}
p := pt.Sub(mf.placed.Min)
ts := mf.placed.Size()
p, in := mf.mask.tilePoint(p, ts)
if !in {
return color.RGBA{}
}
a := float32(mf.tile.AlphaAt(p.X, p.Y).A) / 255 * mf.opacity
c := mf.color
res := color.Color(color.RGBA{uint8(float32(c.R) * a), uint8(float32(c.G) * a), uint8(float32(c.B) * a), uint8(float32(c.A) * a)})
if len(mf.base.ApplyFuncs) > 0 {
res = mf.base.ApplyFuncs.Apply(res)
}
return res
}
// tilePoint returns the point in the tile of the image for the given point
// relative to its placement, with the tile of the given size repeated on
// the axes that it repeats on, and whether it is in the image.
func (m *cssMask) tilePoint(p, ts image.Point) (image.Point, bool) {
if ts.X <= 0 || ts.Y <= 0 {
return p, false
}
if m.repeat && !m.noRepeatX {
p.X = ((p.X % ts.X) + ts.X) % ts.X
} else if p.X < 0 || p.X >= ts.X {
return p, false
}
if m.repeat && !m.noRepeatY {
p.Y = ((p.Y % ts.Y) + ts.Y) % ts.Y
} else if p.Y < 0 || p.Y >= ts.Y {
return p, false
}
return p, true
}
// repeatValue sets the repeat of the mask from the given value of
// mask-repeat or background-repeat (one or two keywords).
func (m *cssMask) repeatValue(v string) {
m.hasRepeat = true
fs := strings.Fields(v)
m.repeat, m.noRepeatX, m.noRepeatY = true, false, false
switch {
case len(fs) == 1 && fs[0] == "no-repeat":
m.repeat = false
case len(fs) == 1 && fs[0] == "repeat-x":
m.noRepeatY = true
case len(fs) == 1 && fs[0] == "repeat-y":
m.noRepeatX = true
case len(fs) == 2:
m.noRepeatX, m.noRepeatY = fs[0] == "no-repeat", fs[1] == "no-repeat"
m.repeat = !m.noRepeatX || !m.noRepeatY
}
}
// imageAt returns the color of a background image at the given pixel: that
// of the image (where it is placed, or repeated) over the color.
func (mf *maskFill) imageAt(x, y int) color.Color {
c := mf.color
res := color.RGBA{uint8(float32(c.R) * mf.opacity), uint8(float32(c.G) * mf.opacity), uint8(float32(c.B) * mf.opacity), uint8(float32(c.A) * mf.opacity)}
if mf.rgba != nil {
p := image.Pt(x, y).Sub(mf.placed.Min)
ts := mf.placed.Size()
p, in := mf.mask.tilePoint(p, ts)
if in { // premultiplied: the image over the color
ic := mf.rgba.RGBAAt(p.X, p.Y)
o := mf.opacity
ia := float32(ic.A) * o / 255
res = color.RGBA{uint8(float32(ic.R)*o + float32(res.R)*(1-ia)), uint8(float32(ic.G)*o + float32(res.G)*(1-ia)),
uint8(float32(ic.B)*o + float32(res.B)*(1-ia)), uint8(float32(ic.A)*o + float32(res.A)*(1-ia))}
}
}
if len(mf.base.ApplyFuncs) > 0 {
return mf.base.ApplyFuncs.Apply(res)
}
return res
}
// applyBackgroundImage sets the background of the given style to its
// background image (over its color, if any), if the given state has one,
// as for the icons of the browsers of MDN and the chevrons of go.dev.
func (c *Context) applyBackgroundImage(st *cssState, s *styles.Style) {
m := st.bgImage
if m == nil || m.url == "" || (st.mask != nil && st.mask.url != "") {
return
}
src := c.maskSourceOf(m.url)
if src == nil {
return
}
var base color.RGBA
if u, ok := s.Background.(*image.Uniform); ok {
base = colors.AsRGBA(u.C)
}
dp := s.UnitContext.Dots(units.UnitDp)
if dp <= 0 {
dp = 1
}
mk := *m
if !mk.hasRepeat { // a background repeats by default, as in CSS
mk.repeat = true
}
s.Background = &maskFill{color: base, src: src, mask: mk, dp: dp, image: true}
}
// applyMask sets the background of the given style to its color through
// the mask of the given state, if it has one and a color.
func (c *Context) applyMask(st *cssState, s *styles.Style) {
m := st.mask
if m == nil || m.url == "" {
return
}
u, ok := s.Background.(*image.Uniform)
if !ok {
return
}
src := c.maskSourceOf(m.url)
if src == nil {
s.Background = nil // the mask hides everything
return
}
dp := s.UnitContext.Dots(units.UnitDp)
if dp <= 0 {
dp = 1
}
mk := *m
if !mk.hasRepeat { // the mask repeats by default, as in CSS
mk.repeat = true
}
s.Background = &maskFill{color: colors.AsRGBA(u.C), src: src, mask: mk, dp: dp}
}
// compileMask compiles the given mask property (mask-image, mask-size,
// mask-position, mask-repeat, or the mask shorthand, also with the -webkit-
// prefix), or returns nil if it is not one.
func compileMask(prop, val string) styleOp {
return compileImageLayer(prop, val, func(st *cssState) **cssMask { return &st.mask })
}
// compileBackgroundImage compiles the given background image property
// (background-image, background-size, background-position,
// background-repeat, or the url() of the background shorthand), as the
// properties of masks (see [compileMask]), or returns nil.
func compileBackgroundImage(prop, val string) styleOp {
if prop == "background-image" && css.MaskURL(val) == "" {
return func(st *cssState, s, ps *styles.Style) { st.bgImage = nil } // (as none or a gradient)
}
return compileImageLayer(strings.Replace(prop, "background", "mask", 1), val, func(st *cssState) **cssMask { return &st.bgImage })
}
// compileImageLayer compiles the given mask property (or the corresponding
// background property) into the image layer of the state that the given
// function returns.
func compileImageLayer(prop, val string, layer func(st *cssState) **cssMask) styleOp {
prop = strings.TrimPrefix(prop, "-webkit-")
lval := strings.ToLower(strings.TrimSpace(val))
get := func(st *cssState) *cssMask {
l := layer(st)
if *l == nil {
*l = &cssMask{}
}
return *l
}
set := func(f func(m *cssMask)) styleOp {
return func(st *cssState, s, ps *styles.Style) {
f(get(st))
}
}
switch prop {
case "mask-image":
u := css.MaskURL(val)
return set(func(m *cssMask) { m.url = u })
case "mask-size":
return func(st *cssState, s, ps *styles.Style) {
get(st).size = css.ResolveMaskSize(st.env, lval)
}
case "mask-position":
return set(func(m *cssMask) { m.position = lval })
case "mask-repeat":
return set(func(m *cssMask) { m.repeatValue(lval) })
case "mask":
u := css.MaskURL(val)
rest := lval
if i := strings.Index(rest, "url("); i >= 0 {
if j := strings.Index(rest[i:], ")"); j >= 0 {
rest = rest[:i] + rest[i+j+1:]
}
}
pos, size, _ := strings.Cut(rest, "/")
var keep, repeats []string
for f := range strings.FieldsSeq(pos) {
switch f {
case "no-repeat", "repeat", "repeat-x", "repeat-y", "round", "space":
repeats = append(repeats, f)
case "alpha", "luminance", "match-source", "add", "subtract", "intersect", "exclude",
"border-box", "padding-box", "content-box", "fill-box", "stroke-box", "view-box", "no-clip",
"fixed", "scroll", "local", "none", "transparent":
default:
if css.ParseColor(f) != nil && !css.IsPositionWord(f) {
continue // the color of the background shorthand
}
keep = append(keep, f)
}
}
return func(st *cssState, s, ps *styles.Style) {
m := &cssMask{url: u, position: strings.Join(keep, " "), size: css.ResolveMaskSize(st.env, strings.TrimSpace(size))}
if len(repeats) > 0 {
m.repeatValue(strings.Join(repeats, " "))
}
l := layer(st) // (not *layer(st) = m, which goscript cannot compile)
*l = m
}
}
return nil
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"bytes"
"io"
"regexp"
"strings"
"unicode"
"cogentcore.org/core/core"
"github.com/yuin/goldmark/v2/ast"
"github.com/yuin/goldmark/v2/extension"
east "github.com/yuin/goldmark/v2/extension/ast"
"github.com/yuin/goldmark/v2/parser"
"github.com/yuin/goldmark/v2/renderer"
"github.com/yuin/goldmark/v2/renderer/html"
"github.com/yuin/goldmark/v2/text"
"github.com/yuin/goldmark/v2/util"
)
// Markdown is a goldmark markdown parser and HTML renderer.
type Markdown struct {
Parser parser.Parser
Renderer html.Renderer
}
// Convert converts the given markdown to HTML, written to w.
func (md *Markdown) Convert(source []byte, w io.Writer) error {
return md.Renderer.Render(w, source, md.Parser.Parse(source))
}
// NewMarkdown returns a goldmark converter with the extensions used for
// Cogent Core content: GitHub flavored markdown, heading ids, raw HTML,
// block attributes in a {...} line before a block, links opening in a new
// tab, and, if ctx is non-nil, wikilinks and its AttributeHandlers.
func NewMarkdown(ctx *Context) *Markdown {
// The parser has the GFM syntax, heading ids, and block attributes.
popts := []parser.Option{
parser.WithExtensions(extension.NewGFMParser(), extension.NewTypographerParser()),
parser.WithAutoHeadingID(),
parser.WithAttribute(),
parser.WithIDGenerator(headingIDs{}),
parser.WithBlockParsers(util.Prioritized[parser.BlockParser](attrBlockParser{}, 50), util.Prioritized[parser.BlockParser](mathBlockParser{}, 60)),
parser.WithASTTransformers(util.Prioritized[parser.ASTTransformer](attrTransformer{}, 100)),
parser.WithInlineParsers(util.Prioritized[parser.InlineParser](mathParser{}, 500)),
}
if ctx != nil {
popts = append(popts, parser.WithInlineParsers(util.Prioritized[parser.InlineParser](wikilinkParser{ctx}, 199)))
}
// The renderer writes raw HTML, and the attribute handlers run before
// the default renderers of blocks.
r := &hookRenderer{ctx: ctx}
decorators := map[ast.NodeKind]html.NodeRendererDecorator{}
for _, k := range hookKinds {
decorators[k] = r.decorate
}
ropts := []html.Option{
html.WithUnsafe(),
html.WithExtensions(extension.NewGFMHTMLRenderer()),
html.WithNodeRenderers(map[ast.NodeKind]html.NodeRenderer{
ast.KindCodeBlock: html.NodeRendererFunc(renderCode),
ast.KindImage: html.NodeRendererFunc(renderImage),
ast.KindLink: html.NodeRendererFunc(renderLink),
kindMath: html.NodeRendererFunc(renderMath),
kindMathBlock: html.NodeRendererFunc(renderMathBlock),
}),
html.WithNodeRendererDecorators(decorators),
}
return &Markdown{Parser: parser.New(popts...), Renderer: html.New(ropts...)}
}
// MDToHTML converts the given markdown to HTML, using the given context
// for wikilinks and attribute handlers.
func MDToHTML(ctx *Context, md []byte) []byte {
var buf bytes.Buffer
md = escapeTableMath(md)
if err := ctx.converter().Convert(md, &buf); err != nil {
core.ErrorSnackbar(nil, err)
}
htm := buf.Bytes()
if bytes.Contains(htm, []byte("><img ")) {
// The attributes of a paragraph that is just an image, as
// {id="figure_one" style="height:10em"} before it, are of the image.
htm = imageParagraph.ReplaceAll(htm, []byte("<p><img${1}${2}/></p>"))
}
return htm
}
// converter returns the goldmark converter of the context, made once on
// first use, or a new one without Cogent Core extensions for a nil context.
func (c *Context) converter() *Markdown {
if c == nil {
return NewMarkdown(nil)
}
c.markdownOnce.Do(func() { c.markdown = NewMarkdown(c) })
return c.markdown
}
// imageParagraph matches a paragraph with attributes that is just an image.
var imageParagraph = regexp.MustCompile(`<p((?: [a-z-]+="[^"]*")+)><img((?: [a-z-]+="[^"]*")*) ?/?></p>`)
// ReadMD reads MD (markdown) from the given bytes and adds corresponding
// Cogent Core widgets to the given [core.Widget], using the given context.
func ReadMD(ctx *Context, parent core.Widget, b []byte) error {
htm := MDToHTML(ctx, b)
// os.WriteFile("htmlcore_tmp.html", htm, 0666) // note: keep here, needed for debugging
buf := bytes.NewBuffer(htm)
return ReadHTML(ctx, parent, buf)
}
// ReadMDString reads MD (markdown) from the given string and adds
// corresponding Cogent Core widgets to the given [core.Widget], using the given context.
func ReadMDString(ctx *Context, parent core.Widget, s string) error {
return ReadMD(ctx, parent, []byte(s))
}
// headingIDs generates heading ids as gomarkdown did: lowercase letters
// and numbers, with a dash for each run of other characters between them.
// The parser adds -1, -2, ... to repeated ids.
type headingIDs struct{}
func (headingIDs) Generate(value []byte, kind ast.NodeKind) []byte {
var id []rune
dash := false
for _, r := range string(value) {
if !unicode.IsLetter(r) && !unicode.IsNumber(r) {
dash = true
continue
}
if dash && len(id) > 0 {
id = append(id, '-')
}
dash = false
id = append(id, unicode.ToLower(r))
}
if len(id) == 0 {
return []byte("heading")
}
return []byte(string(id))
}
// kindAttrBlock is the kind of an [attrBlock].
var kindAttrBlock = ast.NewNodeKind("AttrBlock")
// attrBlock is a line with only {...} attributes, which apply to the
// next block (the mmark / gomarkdown block attribute syntax).
type attrBlock struct {
ast.BaseBlock
}
func (n *attrBlock) Kind() ast.NodeKind { return kindAttrBlock }
func (n *attrBlock) Dump(source []byte) *ast.NodeDump { return ast.NewNodeDump(n, nil) }
// attrBlockParser parses a line of only {...} attributes into an [attrBlock].
type attrBlockParser struct{}
func (attrBlockParser) Trigger() []byte { return []byte{'{'} }
func (attrBlockParser) Open(parent ast.Node, reader text.Reader, pc parser.Context) (ast.Node, parser.State) {
// The line must be the attributes alone.
line, _ := reader.PeekLine()
trim := bytes.TrimSpace(line)
if len(trim) < 2 || trim[len(trim)-1] != '}' {
return nil, parser.NoChildren
}
l, pos := reader.Position()
attrs, ok := parser.ParseAttributes(reader)
rest, _ := reader.PeekLine()
if !ok || len(util.TrimRightSpace(rest)) != 0 {
reader.SetPosition(l, pos)
return nil, parser.NoChildren
}
reader.Advance(len(rest) - 1) // the parser advances past the newline
n := &attrBlock{}
n.Init(n)
for _, a := range attrs {
n.SetAttribute(a.Name, a.Value)
}
return n, parser.Close
}
func (attrBlockParser) Continue(node ast.Node, reader text.Reader, pc parser.Context) parser.State {
return parser.Close
}
func (attrBlockParser) Close(node ast.Node, reader text.Reader, pc parser.Context) {}
func (attrBlockParser) CanInterruptParagraph() bool { return false }
func (attrBlockParser) CanAcceptIndentedLine() bool { return false }
// attrTransformer moves the attributes of each [attrBlock] to the next
// block. It also makes the values of all attributes strings, so that they
// do not need the source (for [MDGetAttr] and the attribute handlers).
type attrTransformer struct{}
func (attrTransformer) Transform(doc *ast.Document, reader text.Reader, pc parser.Context) {
source := reader.Source()
var blocks []ast.Node
ast.Walk(doc, func(n ast.Node, entering bool) (ast.WalkStatus, error) {
if !entering {
return ast.WalkContinue, nil
}
if n.Kind() == kindAttrBlock {
blocks = append(blocks, n)
}
for _, a := range n.Attributes() {
n.SetAttribute(a.Name, text.NewMultiLineValueFromString(a.Value.Value(source), text.IdentityDecoder))
}
return ast.WalkContinue, nil
})
for _, n := range blocks {
if next := n.NextSibling(); next != nil {
for _, a := range n.Attributes() {
next.SetAttribute(a.Name, a.Value)
}
}
n.Parent().RemoveChild(n)
}
}
// hookRenderer runs the [Context.AttributeHandlers] for blocks with
// attributes, before their renderers.
type hookRenderer struct {
ctx *Context
}
// hookKinds are the kinds of blocks that the [hookRenderer] handles.
var hookKinds = []ast.NodeKind{ast.KindParagraph, ast.KindHeading, ast.KindCodeBlock, ast.KindBlockquote, ast.KindList, ast.KindThematicBreak, ast.KindHTMLBlock, east.KindTable, kindMathBlock}
// runHandlers runs the attribute handler for the first attribute of
// the node that has one, returning whether it handled the node.
func (r *hookRenderer) runHandlers(w io.Writer, n ast.Node, entering bool) bool {
if r.ctx == nil || len(r.ctx.AttributeHandlers) == 0 {
return false
}
for _, a := range n.Attributes() {
if f, has := r.ctx.AttributeHandlers[a.Name]; has {
return f(r.ctx, w, n, entering, a.Name, a.Value.Value(nil))
}
}
return false
}
// decorate returns a renderer that runs the attribute handlers before next.
func (r *hookRenderer) decorate(next html.NodeRenderer) html.NodeRenderer {
return html.NodeRendererFunc(func(w io.Writer, source []byte, n ast.Node, entering bool, rc renderer.Context) (ast.WalkStatus, error) {
if n.Attributes() != nil && r.runHandlers(w, n, entering) {
return ast.WalkContinue, nil
}
return next.Render(w, source, n, entering, rc)
})
}
// renderCode renders a code block with all of its attributes on its code
// element, as gomarkdown did.
func renderCode(writer io.Writer, source []byte, node ast.Node, entering bool, rc renderer.Context) (ast.WalkStatus, error) {
w := writer.(util.BufWriter)
n := node.(*ast.CodeBlock)
if !entering {
w.WriteString("</code></pre>\n")
return ast.WalkContinue, nil
}
w.WriteString("<pre><code")
if lang, ok := n.Language(source); ok {
w.WriteString(` class="language-`)
html.ContextTextWriter(rc).WriteString(lang)
w.WriteByte('"')
}
if n.Attributes() != nil {
html.RenderAttributes(w, source, n, nil, rc)
}
w.WriteByte('>')
n.Value.WriteTo(html.ContextTextWriter(rc), source)
return ast.WalkContinue, nil
}
// renderImage renders an image with its alt text as written, including
// any markdown or HTML in it (the caption of a figure), as gomarkdown did.
func renderImage(writer io.Writer, source []byte, node ast.Node, entering bool, rc renderer.Context) (ast.WalkStatus, error) {
if !entering {
return ast.WalkContinue, nil
}
w := writer.(util.BufWriter)
n := node.(*ast.Image)
w.WriteString(`<img src="`)
html.ContextLinkURLWriter(rc).WriteString(n.Destination.Value(source))
w.WriteString(`" alt="`)
html.ContextTextWriter(rc).Write(smartPunct(imageAlt(source, n.Pos())))
w.WriteByte('"')
if !n.Title.IsEmpty() {
w.WriteString(` title="`)
n.Title.WriteTo(html.ContextTextWriter(rc), source)
w.WriteByte('"')
}
if n.Attributes() != nil {
html.RenderAttributes(w, source, n, html.ImageAttributeFilter, rc)
}
w.WriteString(">")
return ast.WalkSkipChildren, nil
}
// imageAlt returns the source of the alt text of the image at pos (the
// position of its "!["): the text up to the matching "]".
func imageAlt(source []byte, pos int) []byte {
if pos < 0 || !bytes.HasPrefix(source[pos:], []byte("![")) {
return nil
}
start := pos + 2
depth := 0
for i := start; i < len(source); i++ {
switch source[i] {
case '\\':
i++
case '`':
// A code span is skipped up to its closing backtick.
if e := bytes.IndexByte(source[i+1:], '`'); e >= 0 {
i += e + 1
}
case '[':
depth++
case ']':
if depth == 0 {
return source[start:i]
}
depth--
}
}
return nil
}
// renderLink renders a link, with target="_blank" for an absolute URL,
// as gomarkdown did with HrefTargetBlank. The destination is not URL
// escaped, since wikilink handlers return URLs with spaces.
func renderLink(writer io.Writer, source []byte, node ast.Node, entering bool, rc renderer.Context) (ast.WalkStatus, error) {
w := writer.(util.BufWriter)
n := node.(*ast.Link)
if !entering {
w.WriteString("</a>")
return ast.WalkContinue, nil
}
dest := n.Destination.Value(source)
w.WriteString(`<a href="`)
html.ContextTextWriter(rc).WriteString(dest)
w.WriteByte('"')
if !n.Title.IsEmpty() {
w.WriteString(` title="`)
n.Title.WriteTo(html.ContextTextWriter(rc), source)
w.WriteByte('"')
}
if strings.Contains(dest, "://") {
w.WriteString(` target="_blank"`)
}
if n.Attributes() != nil {
html.RenderAttributes(w, source, n, html.LinkAttributeFilter, rc)
}
w.WriteByte('>')
return ast.WalkContinue, nil
}
// smartPunct returns the text with the typographic punctuation of the
// Typographer extension (as gomarkdown's Smartypants did for image alt
// text, the caption of a figure): dashes for -- and ---, an ellipsis, and
// curly quotes. HTML tags, `code`, and $math$ are left as they are.
func smartPunct(b []byte) []byte {
var out []byte
// quote returns the opening quote o or the closing one c for a quote at i.
quote := func(i int, o, c string) string {
if i == 0 || bytes.IndexByte([]byte(" \t\n([>"), b[i-1]) >= 0 {
return o
}
return c
}
for i := 0; i < len(b); i++ {
c := b[i]
switch c {
case '<', '`', '$':
// Tags, code, and math are copied as they are.
end := map[byte]byte{'<': '>', '`': '`', '$': '$'}[c]
if e := bytes.IndexByte(b[i+1:], end); e >= 0 {
out = append(out, b[i:i+e+2]...)
i += e + 1
continue
}
case '-':
if bytes.HasPrefix(b[i:], []byte("---")) {
out = append(out, "\u2014"...)
i += 2
continue
}
if bytes.HasPrefix(b[i:], []byte("--")) {
out = append(out, "\u2013"...)
i++
continue
}
case '.':
if bytes.HasPrefix(b[i:], []byte("...")) {
out = append(out, "\u2026"...)
i += 2
continue
}
case '"':
out = append(out, quote(i, "\u201c", "\u201d")...)
continue
case '\'':
if i+1 < len(b) && b[i+1] == '\'' { // '' is a double quote
out = append(out, quote(i, "\u201c", "\u201d")...)
i++
continue
}
out = append(out, quote(i, "\u2018", "\u2019")...)
continue
}
out = append(out, c)
}
return out
}
// MDGetAttr gets the given attribute from the given markdown node, returning ""
// if the attribute is not found.
func MDGetAttr(n ast.Node, attr string) string {
v, ok := n.Attribute(attr)
if !ok {
return ""
}
return v.Value(nil)
}
// MDSetAttr sets the given attribute on the given markdown node
func MDSetAttr(n ast.Node, attr, value string) {
n.SetAttribute(attr, text.NewMultiLineValueFromString(value, text.IdentityDecoder))
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"bytes"
"io"
"github.com/yuin/goldmark/v2/ast"
"github.com/yuin/goldmark/v2/parser"
"github.com/yuin/goldmark/v2/renderer"
"github.com/yuin/goldmark/v2/renderer/html"
"github.com/yuin/goldmark/v2/text"
"github.com/yuin/goldmark/v2/util"
)
// kindMath is the kind of a [mathNode].
var kindMath = ast.NewNodeKind("Math")
// mathNode is $inline$ or $$display$$ math, rendered as gomarkdown did:
// <span class="math inline">\(...\)</span> or class="math display" with \[...\].
type mathNode struct {
ast.BaseInline
Value []byte
Display bool
// Segment is the source of the math, with its dollar signs.
Segment text.Segment
}
func (n *mathNode) Kind() ast.NodeKind { return kindMath }
func (n *mathNode) Dump(source []byte) *ast.NodeDump { return ast.NewNodeDump(n, nil) }
// newMathNode returns a new [mathNode].
func newMathNode(value []byte, display bool, seg text.Segment) *mathNode {
n := &mathNode{Value: value, Display: display, Segment: seg}
n.Init(n)
return n
}
// mathParser parses $inline$ math, on one line, and $$display$$ math,
// which may span lines of a paragraph.
type mathParser struct{}
func (mathParser) Trigger() []byte { return []byte{'$'} }
func (mathParser) Parse(parent ast.Node, block text.Reader, pc parser.Context) ast.Node {
line, seg := block.PeekLine()
if len(line) > 1 && line[1] == '$' {
return parseDisplayMath(block)
}
rest := line[1:]
i := inlineMathEnd(rest)
if i < 0 {
return nil
}
block.Advance(i + 2)
return newMathNode(append([]byte{}, rest[:i]...), false, text.NewSegment(seg.Start, seg.Start+i+2))
}
// inlineMathEnd returns the index in s, the text after an opening $, of
// the closing $ of inline math, or -1 if it is not math: the opening $ is
// not followed by a space, and the closing $ is not followed by a digit,
// so that "$5 and $6" is not math.
func inlineMathEnd(s []byte) int {
if len(s) == 0 || s[0] == ' ' || s[0] == '\t' || s[0] == '$' {
return -1
}
for i := 1; i < len(s); i++ {
if s[i] == '\\' {
i++
continue
}
if s[i] == '$' {
if i+1 < len(s) && s[i+1] >= '0' && s[i+1] <= '9' {
continue
}
return i
}
}
return -1
}
// parseDisplayMath parses $$display$$ math up to the next $$.
func parseDisplayMath(block text.Reader) ast.Node {
l, pos := block.Position()
_, seg := block.PeekLine()
block.Advance(2)
var buf []byte
for {
line, _ := block.PeekLine()
if line == nil {
block.SetPosition(l, pos)
return nil
}
if i := bytes.Index(line, []byte("$$")); i >= 0 {
buf = append(buf, line[:i]...)
_, end := block.PeekLine()
block.Advance(i + 2)
return newMathNode(buf, true, text.NewSegment(seg.Start, end.Start+i+2))
}
buf = append(buf, line...)
block.AdvanceLine()
}
}
// renderMath renders a [mathNode].
func renderMath(writer io.Writer, source []byte, node ast.Node, entering bool, rc renderer.Context) (ast.WalkStatus, error) {
w := writer.(util.BufWriter)
if !entering {
return ast.WalkContinue, nil
}
n := node.(*mathNode)
v := bytes.ReplaceAll(n.Value, []byte(mathPipe), []byte("|"))
if n.Display {
w.WriteString(`<span class="math display">\[`)
w.Write(util.EscapeHTML(v))
w.WriteString(`\]</span>`)
} else {
w.WriteString(`<span class="math inline">\(`)
w.Write(util.EscapeHTML(v))
w.WriteString(`\)</span>`)
}
return ast.WalkContinue, nil
}
// mathPipe stands for a | in the math of a table line (see [escapeTableMath]).
const mathPipe = "\uE000"
// escapeTableMath returns the markdown with each | inside of $math$ on a
// table line (starting with |) replaced by [mathPipe], so that a table cell
// can have math such as $|\psi\rangle$: GFM splits the cells of a row at
// every unescaped |, before it parses the inlines of the cells, and \| can
// not be used, since it is also LaTeX. [renderMath] restores the pipes.
// Lines of fenced code blocks are left as they are.
func escapeTableMath(md []byte) []byte {
if !bytes.Contains(md, []byte("$")) || !bytes.Contains(md, []byte("|")) {
return md
}
var out []byte
fence := false
for line := range bytes.Lines(md) {
trim := bytes.TrimLeft(line, " \t")
if bytes.HasPrefix(trim, []byte("```")) || bytes.HasPrefix(trim, []byte("~~~")) {
fence = !fence
}
if fence || len(trim) == 0 || trim[0] != '|' || !bytes.Contains(line, []byte("$")) {
out = append(out, line...)
continue
}
out = append(out, escapeLineMath(line)...)
}
return out
}
// escapeLineMath replaces each | inside of the $math$ of the given line,
// with the rules of [mathParser], skipping `code` spans.
func escapeLineMath(line []byte) []byte {
var out []byte
for i := 0; i < len(line); i++ {
c := line[i]
switch {
case c == '\\' && i+1 < len(line):
out = append(out, c, line[i+1])
i++
continue
case c == '`':
// A code span is copied up to its closing backtick.
if e := bytes.IndexByte(line[i+1:], '`'); e >= 0 {
out = append(out, line[i:i+e+2]...)
i += e + 1
continue
}
case c == '$':
delim := 1
if i+1 < len(line) && line[i+1] == '$' {
delim = 2
}
start := i + delim
e := -1
if delim == 2 {
e = bytes.Index(line[start:], []byte("$$"))
} else {
e = inlineMathEnd(line[start:])
}
if e > 0 {
out = append(out, line[i:start]...)
out = append(out, bytes.ReplaceAll(line[start:start+e], []byte("|"), []byte(mathPipe))...)
out = append(out, line[i:start]...)
i = start + e + delim - 1
continue
}
}
out = append(out, c)
}
return out
}
// kindMathBlock is the kind of a [mathBlock].
var kindMathBlock = ast.NewNodeKind("MathBlock")
// mathBlock is a block of $$display$$ math that starts with $$ at the start
// of a line and ends with the next $$, the raw lines of which are not
// parsed as markdown, rendered as gomarkdown did:
// <p><span class="math display">\[...\]</span></p>.
type mathBlock struct {
ast.BaseBlock
// lines are the raw lines of the math.
lines text.Lines
// closed is whether the closing $$ has been read.
closed bool
}
func (n *mathBlock) Kind() ast.NodeKind { return kindMathBlock }
func (n *mathBlock) Dump(source []byte) *ast.NodeDump { return ast.NewNodeDump(n, nil) }
// mathBlockParser parses a [mathBlock].
type mathBlockParser struct{}
func (mathBlockParser) Trigger() []byte { return []byte{'$'} }
func (mathBlockParser) Open(parent ast.Node, reader text.Reader, pc parser.Context) (ast.Node, parser.State) {
line, seg := reader.PeekLine()
pos := pc.BlockOffset()
if pos < 0 || !bytes.HasPrefix(line[pos:], []byte("$$")) {
return nil, parser.NoChildren
}
if pc.LastOpenedBlock().Node != nil {
if open, ok := pc.LastOpenedBlock().Node.(*ast.Paragraph); ok && openDisplayMath(open, reader.Source()) {
// This $$ closes the display math of the paragraph.
return nil, parser.NoChildren
}
}
start := pos + 2
rest := line[start:]
n := &mathBlock{}
n.Init(n)
if e := bytes.Index(rest, []byte("$$")); e >= 0 {
// The math is on this line, which must have nothing after it.
if !util.IsBlank(rest[e+2:]) {
return nil, parser.NoChildren
}
n.lines.AppendSegment(text.NewSegment(seg.Start+start, seg.Start+start+e))
n.closed = true
reader.AdvanceToEOL()
return n, parser.Close
}
// The newline of the first line is kept, as gomarkdown did.
n.lines.AppendSegment(text.NewSegment(seg.Start+start, seg.Stop))
reader.AdvanceToEOL()
return n, parser.NoChildren
}
// openDisplayMath returns whether the paragraph has $$display$$ math that
// is not closed yet: an odd number of $$.
func openDisplayMath(p *ast.Paragraph, source []byte) bool {
n := 0
for _, seg := range p.Source() {
n += bytes.Count(seg.Bytes(source), []byte("$$"))
}
return n%2 == 1
}
func (mathBlockParser) Continue(node ast.Node, reader text.Reader, pc parser.Context) parser.State {
if node.(*mathBlock).closed {
// goldmark continues a block that Open closed.
return parser.Close
}
line, seg := reader.PeekLine()
if e := bytes.Index(line, []byte("$$")); e >= 0 {
if e > 0 {
node.(*mathBlock).lines.AppendSegment(text.NewSegment(seg.Start, seg.Start+e))
}
reader.AdvanceToEOL()
return parser.Close
}
node.(*mathBlock).lines.AppendSegment(seg)
reader.AdvanceToEOL()
return parser.Continue | parser.NoChildren
}
func (mathBlockParser) Close(node ast.Node, reader text.Reader, pc parser.Context) {}
func (mathBlockParser) CanInterruptParagraph() bool { return true }
func (mathBlockParser) CanAcceptIndentedLine() bool { return false }
// renderMathBlock renders a [mathBlock]. Its attributes are only for the
// [Context.AttributeHandlers] (as the label of an equation).
func renderMathBlock(writer io.Writer, source []byte, node ast.Node, entering bool, rc renderer.Context) (ast.WalkStatus, error) {
w := writer.(util.BufWriter)
if !entering {
return ast.WalkContinue, nil
}
w.WriteString(`<p><span class="math display">\[`)
node.(*mathBlock).lines.WriteTo(html.ContextTextWriter(rc), source)
w.WriteString("\\]</span></p>\n")
return ast.WalkContinue, nil
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"strings"
"cogentcore.org/core/htmlcore/css"
"cogentcore.org/core/system"
)
// MediaWidth is the width of the viewport in CSS px (dp) that @media rules
// are evaluated for, when it is set for the context; otherwise it is the
// width of the screen.
func (c *Context) mediaWidth() float32 {
if c.MediaWidth > 0 {
return c.MediaWidth
}
return ScreenMediaWidth()
}
// ScreenMediaWidth returns the width of the screen in CSS px (dp), for the
// @media rules of style sheets when [Context.MediaWidth] is not set, or
// 1024 if there is no screen. An app that reads HTML in another goroutine
// should set MediaWidth (as to this) in its main goroutine first, as the
// screens can change in it (as when a window is made).
func ScreenMediaWidth() float32 {
if system.TheApp != nil && system.TheApp.NScreens() > 0 {
sc := system.TheApp.Screen(0)
if sc.LogicalDPI > 0 && sc.PixelSize.X > 0 {
return float32(sc.PixelSize.X) * 160 / sc.LogicalDPI
}
}
return 1024
}
// MediaMatches returns whether the given media query list (as of an
// @media rule) matches the viewport of the context, as for matchMedia
// in the scripts of a page.
func (c *Context) MediaMatches(query string) bool {
return c.mediaMatches(query)
}
// mediaMatches returns whether the given media query list matches,
// recording its result for [Context.MediaChanged].
func (c *Context) mediaMatches(query string) bool {
query = strings.ToLower(strings.TrimSpace(query))
if query == "" {
return true
}
m := c.mediaListMatches(query)
if !c.checkingMedia {
if c.mediaUses == nil {
c.mediaUses = map[string]bool{}
}
c.mediaUses[query] = m
}
return m
}
// MediaChanged returns whether the HTML read with the context would be
// read differently for a viewport of the given width in CSS px (dp):
// whether a media query of its style sheets (as of an @media rule) or a
// number of columns estimated from the width (for column-width) has
// another result for it. An app that shows pages in a viewport whose
// width can change, as when its window is resized, can then read the
// page again with a new context (see [Context.NewPage]) with that
// [Context.MediaWidth], as browsers apply the rules of the new width.
// It must be called in the goroutine that styles the widgets of the page,
// once the page has been read.
func (c *Context) MediaChanged(width float32) bool {
if width <= 0 {
return false
}
saved := c.MediaWidth
c.MediaWidth, c.checkingMedia = width, true
defer func() { c.MediaWidth, c.checkingMedia = saved, false }()
for q, m := range c.mediaUses {
if c.mediaListMatches(q) != m {
return true
}
}
for n, count := range c.columnUses {
if c.columnCount(n) != count {
return true
}
}
return false
}
// mediaListMatches returns whether the given (non-empty, lowercase)
// media query list matches.
func (c *Context) mediaListMatches(query string) bool {
for q := range strings.SplitSeq(query, ",") {
if c.mediaQueryMatches(strings.TrimSpace(q)) {
return true
}
}
return false
}
// mediaQueryMatches returns whether the given media query matches.
func (c *Context) mediaQueryMatches(q string) bool {
not := false
if rest, ok := strings.CutPrefix(q, "not "); ok {
not, q = true, rest
}
q = strings.TrimPrefix(q, "only ")
match := true
for part := range strings.SplitSeq(q, " and ") {
part = strings.TrimSpace(part)
if part == "" {
continue
}
if !strings.HasPrefix(part, "(") { // media type
switch part {
case "all", "screen":
default:
match = false
}
continue
}
if !c.mediaFeatureMatches(strings.Trim(part, "()")) {
match = false
}
}
return match != not
}
// mediaFeatureMatches returns whether the given media feature matches,
// treating features that are not supported as matching.
func (c *Context) mediaFeatureMatches(f string) bool {
name, value, _ := strings.Cut(f, ":")
name, value = strings.TrimSpace(name), strings.TrimSpace(value)
length := func() (float32, bool) {
return css.CalcPx(value)
}
width := c.mediaWidth()
height := width * 3 / 4
if c.MediaHeight > 0 {
height = c.MediaHeight
}
if strings.Contains(f, "height") || strings.Contains(f, "aspect-ratio") || strings.Contains(f, "orientation") {
c.viewportHeightUsed.Store(true)
}
if !strings.Contains(f, ":") && strings.ContainsAny(f, "<>=") {
return css.MediaRangeMatches(f, width, height)
}
// the device is taken to be the size of the viewport, as for the
// screen of a phone (and the window of headless Chrome)
name = strings.Replace(name, "device-", "", 1)
switch name {
case "min-width", "max-width", "min-height", "max-height":
l, ok := length()
if !ok {
return false // as browsers do for a query that is not valid
}
v := width
if strings.HasSuffix(name, "height") {
v = height
}
if strings.HasPrefix(name, "min") {
return v >= l
}
return v <= l
case "prefers-color-scheme":
return value == "light"
case "prefers-reduced-motion":
// CSS animations and transitions are not run, so pages show the
// final states of what they animate (as the headings of github.com
// that fade in, which were hidden)
return value == "reduce" || value == ""
case "prefers-contrast", "forced-colors":
return value == "no-preference" || value == "none"
case "orientation":
return value == "landscape"
case "hover", "any-hover":
return value == "hover"
case "pointer", "any-pointer":
return value == "fine"
}
return true
}
// readEnv returns the length environment for parsing lengths when a page
// is read (outside of styling): an em of 16px (as the font size of the
// element is not known yet), the rem of the page, and its viewport.
func (c *Context) readEnv() *css.LengthEnv {
e := css.DefaultLengthEnv()
e.Rem = float64(c.rootFontSize())
e.Vw = float64(c.mediaWidth()) / 100
e.FixedVh = c.MediaHeight > 0
if e.FixedVh {
e.Vh = float64(c.MediaHeight) / 100
}
e.VhUsed = &c.viewportHeightUsed
return e
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"strings"
douceur "github.com/aymerick/douceur/css"
"golang.org/x/net/html"
"cogentcore.org/core/htmlcore/css"
)
// The URLs of the resources that a page gets as it is read, for an app to
// get them in parallel before it is read (as the preload scanners of
// browsers do), as reading a page gets them one at a time: the first read
// of volkskrant.nl got 255 of them in 8s before it was shown.
// PrefetchURLs returns the absolute URLs of the resources that reading the
// given document with the context gets, as [Context.GetURL] gets them: its
// style sheets (and those that they import, and their web fonts, if they
// are inline; see [StyleSheetURLs] for those of the others), its scripts
// (if [Context.Scripting]), and its images (as chosen from their srcsets
// for the width of the context), in that order. It does not change the
// context.
func (c *Context) PrefetchURLs(doc *html.Node) []string {
var sheets, scripts, images []string
seen := map[string]bool{}
add := func(list *[]string, raw, base string) {
raw = strings.TrimSpace(raw)
if raw == "" || strings.HasPrefix(raw, "data:") || strings.HasPrefix(raw, "blob:") {
return
}
u, err := parseRelativeURL(raw, base)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") {
return
}
s := u.String()
if !seen[s] {
seen[s] = true
*list = append(*list, s)
}
}
var walk func(n *html.Node)
walk = func(n *html.Node) {
if n.Type == html.ElementNode && n.Namespace == "" {
switch n.Data {
case "link":
rel := strings.ToLower(GetAttr(n, "rel"))
switch {
case rel == "stylesheet" && c.mediaMatches(GetAttr(n, "media")):
add(&sheets, GetAttr(n, "href"), c.PageURL)
case rel == "preload" || rel == "modulepreload":
switch strings.ToLower(GetAttr(n, "as")) {
case "style":
add(&sheets, GetAttr(n, "href"), c.PageURL)
case "script", "":
if c.Scripting {
add(&scripts, GetAttr(n, "href"), c.PageURL)
}
case "font":
if c.WebFonts {
add(&sheets, GetAttr(n, "href"), c.PageURL)
}
case "image":
add(&images, GetAttr(n, "href"), c.PageURL)
}
}
case "style":
if c.mediaMatches(GetAttr(n, "media")) {
for _, u := range StyleSheetURLs(nodeText(n), c.PageURL, c.WebFonts) {
add(&sheets, u, c.PageURL)
}
}
case "script":
if c.Scripting && !HasAttr(n, "nomodule") {
add(&scripts, GetAttr(n, "src"), c.PageURL)
}
case "img":
src, _ := c.imageSource(n)
if src == "" {
src, _ = c.noscriptImage(n) // (shown until its scripts set its source)
}
add(&images, src, c.PageURL)
}
}
for k := n.FirstChild; k != nil; k = k.NextSibling {
walk(k)
}
}
walk(doc)
return append(append(sheets, scripts...), images...)
}
// StyleSheetURLs returns the absolute URLs of the resources that the given
// style sheet, at the given URL (or in the page at it), gets as it is
// added to a page: the style sheets that it imports, and the web fonts of
// its @font-face rules (as [Context.addFontFace] chooses them), if
// webFonts and they have not been loaded yet. Its media and supports
// conditions are not checked.
func StyleSheetURLs(sheet, base string, webFonts bool) []string {
var urls []string
var walk func(rules []*douceur.Rule)
walk = func(rules []*douceur.Rule) {
for _, rule := range rules {
if rule.Kind != douceur.AtRule {
continue
}
switch strings.ToLower(rule.Name) {
case "@import":
if u, _ := css.ImportURL(rule.Prelude); u != "" {
if pu, err := parseRelativeURL(u, base); err == nil {
urls = append(urls, pu.String())
}
}
case "@font-face":
if webFonts {
if u := fontFaceURL(rule.Declarations, base); u != "" {
urls = append(urls, u)
}
}
default:
walk(rule.Rules) // (as @media and @supports)
}
}
}
walk(css.Parse(sheet).Rules)
return urls
}
// fontFaceURL returns the URL of the web font that [Context.addFontFace]
// would get for the given declarations of an @font-face rule in a style
// sheet at the given URL, or "" if it would get none, or has gotten it.
func fontFaceURL(decls []*douceur.Declaration, base string) string {
var family, src, urange string
for _, d := range decls {
switch strings.ToLower(strings.TrimSpace(d.Property)) {
case "font-family":
family = strings.Trim(strings.TrimSpace(d.Value), `"'`)
case "src":
src = d.Value
case "unicode-range":
urange = d.Value
}
}
if family == "" || src == "" || (urange != "" && !css.UnicodeRangeHas(urange, 'A')) {
return ""
}
for _, s := range css.SplitTopLevel(src, ',') {
u, format := css.FontSource(s)
if u == "" {
continue
}
switch format {
case "", "woff", "woff2", "truetype", "opentype", "woff-variations", "woff2-variations", "truetype-variations", "opentype-variations":
default:
continue
}
pu, err := parseRelativeURL(u, base)
if err != nil {
continue
}
key := strings.ToLower(family) + " " + pu.String()
webFontURLs.Lock()
_, tried := webFontURLs.loaded[key]
webFontURLs.Unlock()
if tried {
return "" // (loaded once for all pages)
}
return pu.String()
}
return ""
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"image"
"strconv"
"strings"
"cogentcore.org/core/colors"
"cogentcore.org/core/htmlcore/css"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/text"
)
// styleOp applies a compiled CSS declaration to the given style, with the
// state of the style pass (as its length environment) and the parent style.
type styleOp func(st *cssState, s, ps *styles.Style)
// compileDecls compiles the given declarations, in the order of the cascade
// (see [Context.compileCSS]). One that is invalid, of a var() that has no
// value (invalid at computed-value time), is unset, as in CSS: inherited,
// or initial (as the headings of the rules of reddit.com, of a font of a
// variable of a theme that it did not use, which were of the font of h2,
// not of the text that they were in).
// The font properties are first, as in CSS the font size of an element
// is computed before the lengths that are relative to it (as the ch unit,
// and em in calc()).
func (c *Context) compileDecls(decls []*cssDecl) []styleOp {
var ops []styleOp
for _, font := range []bool{true, false} {
for _, d := range decls {
if css.FontProperties[d.Property] != font {
continue
}
v := d.Value
if d.invalid {
v = "unset"
}
ops = append(ops, c.compileCSS(d.Property, v)...)
}
}
return ops
}
// compileCSS compiles the declaration of the given CSS property with the
// given value into the operations that apply it to a style. The parts of
// the value that are the same for every element, as keywords, numbers and
// colors, are parsed once here; lengths are parsed when it is applied, as
// they depend on the length environment of the style pass (as for em, rem
// and calc()). It returns nil for a property that is not supported, or
// a value that is not valid.
func (c *Context) compileCSS(prop, val string) []styleOp {
if p, ok := strings.CutPrefix(prop, "-webkit-"); ok && css.WebkitAliases[p] {
// the old prefixed property is the standard one (as the
// -webkit-transform with which the slider of the photos of the
// postings of craigslist.org moves its slides); the last of them
// in the cascade applies, as in browsers
prop = p
}
val = strings.TrimSpace(val)
lval := strings.ToLower(val)
op := func(f styleOp) []styleOp { return []styleOp{f} }
if lval == "unset" { // inherit for the inherited properties, initial otherwise
lval = "initial"
if css.InheritedProperties[prop] {
lval = "inherit"
}
}
if ls, ok := css.KeywordLonghands[prop]; ok && (lval == "inherit" || lval == "initial") {
// a shorthand is its longhands (as the font of a var() that has no
// value, which is unset, inherited)
var ops []styleOp
for _, l := range ls {
ops = append(ops, c.compileCSS(l, lval)...)
}
return ops
}
if prop == "clip" || prop == "clip-path" {
// a clip to nothing hides the element (as the visually hidden
// skip links of go.dev, of clip: rect(0 0 0 0), unset on focus);
// other clips are not applied
zero := css.ZeroAreaClip(prop, lval)
return op(func(st *cssState, s, ps *styles.Style) { st.clippedOut = zero })
}
if prop == "visibility" && (lval == "inherit" || lval == "initial") {
// that of the parent, or visible (as the repository panels of
// github.com, which a script shows with visibility: inherit over
// the hidden of their class, which was kept)
v := "visible"
if lval == "inherit" {
v = "" // (see resolve: that of the parent)
}
return op(func(st *cssState, s, ps *styles.Style) { st.visibility = v })
}
if lval == "initial" && (prop == "background" || prop == "background-color") {
// transparent, over the background of a control (as the menu
// buttons of MDN, which were gray)
return op(func(st *cssState, s, ps *styles.Style) {
st.background, st.hasBg, st.bgCurrentColor = nil, true, false
})
}
if lval == "inherit" && (prop == "background" || prop == "background-color") {
// that of the parent, over a background of an earlier rule (as
// the code of the Python docs, pre with background-color: inherit
// of the gray of its highlight block, over a green for pre)
return op(func(st *cssState, s, ps *styles.Style) {
var bg image.Image
if ps != nil {
bg = ps.Background
}
st.background, st.hasBg, st.bgCurrentColor = bg, true, false
})
}
if lval == "initial" && (prop == "margin-top" || prop == "margin-right" || prop == "margin-bottom" || prop == "margin-left") {
// the margins of the cascade are those of the state (see setMargin)
i := css.SideIndex(prop)
return op(func(st *cssState, s, ps *styles.Style) { setMargin(st, i, "0") })
}
if lval == "inherit" || lval == "initial" {
return op(func(st *cssState, s, ps *styles.Style) {
s.FromProperty(ps, prop, lval, colors.BaseContext(colors.ToUniform(s.Color)))
})
}
if p, ok := css.LogicalProperties[prop]; ok {
prop = p
}
switch prop {
case "margin-inline", "margin-block", "padding-inline", "padding-block":
fs := css.SplitColors(val)
if len(fs) == 0 {
return nil
}
start, end := fs[0], fs[0]
if len(fs) > 1 {
end = fs[1]
}
base, dir, _ := strings.Cut(prop, "-")
if dir == "inline" {
return append(c.compileCSS(base+"-left", start), c.compileCSS(base+"-right", end)...)
}
return append(c.compileCSS(base+"-top", start), c.compileCSS(base+"-bottom", end)...)
case "display":
d := css.LegacyDisplay(lval)
return op(func(st *cssState, s, ps *styles.Style) { st.display = d })
case "-webkit-line-clamp", "line-clamp":
n, err := strconv.Atoi(lval)
if lval == "none" || lval == "initial" {
n, err = 0, nil
}
if err != nil || n < 0 {
return nil
}
return op(func(st *cssState, s, ps *styles.Style) { s.Text.LineClamp = n })
case "text-overflow":
e := lval == "ellipsis"
return op(func(st *cssState, s, ps *styles.Style) { s.Text.Ellipsis = e })
case "margin":
vals := css.ExpandSides(css.SplitColors(lval))
return op(func(st *cssState, s, ps *styles.Style) {
for i, v := range vals {
setMargin(st, i, v)
}
})
case "margin-top", "margin-right", "margin-bottom", "margin-left":
i := css.SideIndex(prop)
return op(func(st *cssState, s, ps *styles.Style) { setMargin(st, i, lval) })
case "padding":
vals := css.ExpandSides(css.SplitColors(lval))
return op(func(st *cssState, s, ps *styles.Style) {
for i, v := range vals {
if l, ok := st.env.Length(v, units.UnitPw); ok {
css.SetValueSide(&s.Padding, i, l)
}
}
})
case "padding-top", "padding-right", "padding-bottom", "padding-left":
i := css.SideIndex(prop)
return op(func(st *cssState, s, ps *styles.Style) {
if l, ok := st.env.Length(lval, units.UnitPw); ok {
css.SetValueSide(&s.Padding, i, l)
}
})
case "border":
return op(compileBorder(-1, val))
case "border-top", "border-right", "border-bottom", "border-left":
return op(compileBorder(css.SideIndex(prop), val))
case "border-width":
vals := css.ExpandSides(css.SplitColors(lval))
return op(func(st *cssState, s, ps *styles.Style) {
for i, v := range vals {
css.SetValueSide(&s.Border.Width, i, st.env.BorderWidth(v))
}
})
case "border-style":
vals := css.ExpandSides(css.SplitColors(lval))
return op(func(st *cssState, s, ps *styles.Style) {
for i, v := range vals {
css.SetBorderStyle(s, i, v)
}
})
case "border-color":
var cfs []func() image.Image
for _, v := range css.ExpandSides(css.SplitColors(val)) {
cfs = append(cfs, css.ColorFunc(v))
}
return op(func(st *cssState, s, ps *styles.Style) {
for i, cf := range cfs {
css.SetSide(&s.Border.Color, i, cf())
}
})
case "border-top-width", "border-right-width", "border-bottom-width", "border-left-width":
i := css.SideIndex(prop)
return op(func(st *cssState, s, ps *styles.Style) {
css.SetValueSide(&s.Border.Width, i, st.env.BorderWidth(lval))
})
case "border-top-style", "border-right-style", "border-bottom-style", "border-left-style":
i := css.SideIndex(prop)
return op(func(st *cssState, s, ps *styles.Style) { css.SetBorderStyle(s, i, lval) })
case "border-top-color", "border-right-color", "border-bottom-color", "border-left-color":
i, cf := css.SideIndex(prop), css.ColorFunc(val)
return op(func(st *cssState, s, ps *styles.Style) { css.SetSide(&s.Border.Color, i, cf()) })
case "border-top-left-radius", "border-top-right-radius", "border-bottom-right-radius", "border-bottom-left-radius":
v := strings.Fields(lval + " 0")[0]
i := map[string]int{"border-top-left-radius": 0, "border-top-right-radius": 1,
"border-bottom-right-radius": 2, "border-bottom-left-radius": 3}[prop]
return op(func(st *cssState, s, ps *styles.Style) {
if l, ok := st.env.Length(v, units.UnitEw); ok {
css.SetValueSide(&s.Border.Radius, i, l)
}
})
case "border-radius":
vals := css.ExpandSides(strings.Fields(strings.Split(lval, "/")[0]))
return op(func(st *cssState, s, ps *styles.Style) {
for i, v := range vals {
if l, ok := st.env.Length(v, units.UnitEw); ok {
css.SetValueSide(&s.Border.Radius, i, l)
}
}
})
case "background-image", "background-size", "background-position", "background-repeat":
if m := compileBackgroundImage(prop, val); m != nil {
return op(m)
}
return nil
case "background", "background-color":
var imageOp []styleOp
if prop == "background" {
imageOp = op(compileBackgroundImage(prop, val))
}
bg := css.BackgroundColor(val)
if bg == "" && prop == "background" && !strings.Contains(lval, "url(") && !strings.Contains(lval, "gradient(") {
// The shorthand without a color (as "0 0" or "none", as
// github.com resets its buttons with) sets the color to
// transparent; with an image or gradient, which are not
// supported, the color before it (a fallback) is kept.
switch lval {
case "inherit", "unset", "revert", "revert-layer":
default:
bg = "transparent"
}
}
if bg == "" {
return imageOp
}
none := bg == "transparent" || bg == "none"
current := strings.EqualFold(bg, "currentcolor")
cf := css.ColorFunc(bg)
return append(imageOp, op(func(st *cssState, s, ps *styles.Style) {
st.background, st.hasBg, st.bgCurrentColor = cf(), true, current
if none || current {
st.background = nil
}
})...)
case "color":
if css.ParseColor(val) == nil {
return nil
}
cf := css.ColorFunc(val)
return op(func(st *cssState, s, ps *styles.Style) { s.Color = cf() })
case "width", "height", "min-width", "min-height", "max-width", "max-height":
pct := units.UnitPw
if strings.HasSuffix(prop, "height") {
pct = units.UnitPh
}
return op(func(st *cssState, s, ps *styles.Style) {
if prop == "width" {
// as wide as its content on one line (see styles.MaxContentWidth)
s.MaxContentWidth = lval == "max-content"
}
if prop == "height" { // the height of its content (as for a modal dialog)
st.heightFit = strings.Contains(lval, "fit-content") || lval == "max-content" || lval == "min-content"
}
st.setSize(prop, st.env.LengthPtr(lval, pct))
})
case "position":
pos := styles.PositionStatic
switch lval {
case "sticky":
pos = styles.PositionSticky
case "relative":
pos = styles.PositionRelative
case "absolute":
pos = styles.PositionAbsolute
case "fixed":
pos = styles.PositionFixed
}
return op(func(st *cssState, s, ps *styles.Style) { s.Position = pos })
case "top", "right", "bottom", "left":
i := css.SideIndex("-" + prop)
return op(func(st *cssState, s, ps *styles.Style) { setInset(st.env, s, i, lval) })
case "inset":
vals := css.ExpandSides(css.SplitColors(lval))
return op(func(st *cssState, s, ps *styles.Style) {
for i, v := range vals {
setInset(st.env, s, i, v)
}
})
case "inset-inline", "inset-block":
fs := css.SplitColors(lval)
if len(fs) == 0 {
return nil
}
start, end := fs[0], fs[0]
if len(fs) > 1 {
end = fs[1]
}
first, second := 3, 1 // the sides of the start and end
if prop == "inset-block" {
first, second = 0, 2
}
return op(func(st *cssState, s, ps *styles.Style) {
setInset(st.env, s, first, start)
setInset(st.env, s, second, end)
})
case "float":
f := styles.FloatNone
switch lval {
case "left", "inline-start":
f = styles.FloatLeft
case "right", "inline-end":
f = styles.FloatRight
}
return op(func(st *cssState, s, ps *styles.Style) { s.Float = f })
case "clear":
cl := styles.ClearNone
switch lval {
case "left", "inline-start":
cl = styles.ClearLeft
case "right", "inline-end":
cl = styles.ClearRight
case "both":
cl = styles.ClearBoth
}
return op(func(st *cssState, s, ps *styles.Style) { s.Clear = cl })
case "mask", "mask-image", "mask-size", "mask-position", "mask-repeat",
"-webkit-mask", "-webkit-mask-image", "-webkit-mask-size", "-webkit-mask-position", "-webkit-mask-repeat":
if m := compileMask(prop, val); m != nil {
return op(m)
}
return nil
case "transform", "translate":
x, y, ok := css.Translate(prop, lval)
if !ok {
return nil
}
rot := css.Rotate(prop, lval)
zero := prop == "transform" && css.ZeroScale(lval)
return op(func(st *cssState, s, ps *styles.Style) {
s.Translate.X, _ = st.env.Length(x, units.UnitEw)
s.Translate.Y, _ = st.env.Length(y, units.UnitEh)
if prop == "transform" {
s.Rotate = rot
}
st.zeroScale = zero // (see resolve)
})
case "container-type", "container", "contain":
c := styles.ContainNone
v := lval
if prop == "container" { // name / type
_, v, _ = strings.Cut(lval, "/")
}
for f := range strings.FieldsSeq(v) {
switch f {
case "size", "strict":
c = styles.ContainSize
case "inline-size":
if c == styles.ContainNone {
c = styles.ContainInlineSize
}
}
}
return op(func(st *cssState, s, ps *styles.Style) { s.Contain = c })
case "contain-intrinsic-width", "contain-intrinsic-height", "contain-intrinsic-size":
// the lengths of the values, without auto (the size that a box
// last had, which is the length until it is laid out); none is no size
var vals []string
for f := range strings.FieldsSeq(lval) {
if f != "auto" {
vals = append(vals, f)
}
}
if len(vals) == 0 {
return nil
}
return op(func(st *cssState, s, ps *styles.Style) {
length := func(v string) *units.Value {
if v == "none" {
return nil
}
return st.env.LengthPtr(v, units.UnitPw)
}
if prop != "contain-intrinsic-height" {
st.intrinsicWidth = length(vals[0])
}
if prop != "contain-intrinsic-width" {
st.intrinsicHeight = length(vals[len(vals)-1])
}
})
case "aspect-ratio":
r := css.AspectRatio(lval)
return op(func(st *cssState, s, ps *styles.Style) { s.AspectRatio = r })
case "rotate":
rot := css.Angle(lval)
return op(func(st *cssState, s, ps *styles.Style) { s.Rotate = rot })
case "z-index":
z, err := strconv.Atoi(lval)
if err != nil {
return nil
}
return op(func(st *cssState, s, ps *styles.Style) { s.ZIndex = z })
case "vertical-align":
return op(func(st *cssState, s, ps *styles.Style) { st.verticalAlign = lval })
case "border-collapse":
collapse := lval == "collapse"
return op(func(st *cssState, s, ps *styles.Style) { st.borderCollapse = collapse })
case "box-sizing":
borderBox := lval == "border-box"
return op(func(st *cssState, s, ps *styles.Style) { st.borderBox = borderBox })
case "font-size":
return op(func(st *cssState, s, ps *styles.Style) { setFontSize(st.env, s, ps, lval) })
case "font-weight":
return op(func(st *cssState, s, ps *styles.Style) { css.SetFontWeight(s, ps, lval) })
case "font-style":
slant := rich.SlantNormal
if lval == "italic" || lval == "oblique" {
slant = rich.Italic
}
return op(func(st *cssState, s, ps *styles.Style) { s.Font.Slant = slant })
case "font-family":
family := css.FontFamily(val)
return op(func(st *cssState, s, ps *styles.Style) { c.setFontFamily(s, val, family) })
case "font":
return op(func(st *cssState, s, ps *styles.Style) {
if family := setFont(st, s, ps, val); family != "" {
c.setFontFamily(s, family, s.Font.Family)
}
})
case "line-height":
return op(func(st *cssState, s, ps *styles.Style) { st.lineHeight = lval })
case "text-align":
align, legacy := text.Start, false
switch lval {
case "left", "start":
case "right", "end":
align = text.End
case "center":
align = text.Center
case "-webkit-center":
// the legacy center of the align attribute,
// which also centers the blocks in the element
align, legacy = text.Center, true
case "justify":
align = text.Justify
default:
return nil
}
return op(func(st *cssState, s, ps *styles.Style) {
s.Text.Align = align
if legacy {
st.legacyCenter = true
}
})
case "white-space":
ws := text.WrapAsNeeded
switch lval {
case "nowrap":
ws = text.WrapNever
case "pre":
ws = text.WhiteSpacePre
case "pre-wrap", "pre-line", "break-spaces":
ws = text.WhiteSpacePreWrap
}
return op(func(st *cssState, s, ps *styles.Style) { s.Text.WhiteSpace = ws })
case "text-indent":
return op(func(st *cssState, s, ps *styles.Style) {
if l, ok := st.env.Length(lval, units.UnitPw); ok {
s.Text.Indent = l
// the text is moved out of view (as the labels of icons,
// which have it), as an indent is not otherwise supported
st.hideText = (l.Unit == units.UnitDp || l.Unit == units.UnitPx) && l.Value <= -500
}
})
case "text-decoration", "text-decoration-line":
var deco rich.Decorations
for f := range strings.FieldsSeq(lval) {
switch f {
case "underline":
deco.SetFlag(true, rich.Underline)
case "overline":
deco.SetFlag(true, rich.Overline)
case "line-through":
deco.SetFlag(true, rich.LineThrough)
}
}
return op(func(st *cssState, s, ps *styles.Style) { s.Font.Decoration = deco })
case "flex-direction":
dir := styles.Row
if strings.HasPrefix(lval, "column") {
dir = styles.Column
}
return op(func(st *cssState, s, ps *styles.Style) { s.Direction = dir })
case "flex-wrap":
wrap := lval == "wrap" || lval == "wrap-reverse"
return op(func(st *cssState, s, ps *styles.Style) { s.Wrap = wrap })
case "flex-flow":
// a direction and a wrap, in any order, each initial when omitted
// (the wrap is not a direction: a flex-flow of column nowrap, as
// the election results of nytimes.com, is a column)
dir, wrap := "row", "nowrap"
for f := range strings.FieldsSeq(lval) {
if strings.Contains(f, "wrap") {
wrap = f
} else {
dir = f
}
}
return append(c.compileCSS("flex-direction", dir), c.compileCSS("flex-wrap", wrap)...)
case "flex-grow", "flex-shrink":
f, err := strconv.ParseFloat(lval, 32)
if err != nil {
return nil
}
if prop == "flex-grow" {
return op(func(st *cssState, s, ps *styles.Style) { st.flexGrow, st.hasGrow = float32(f), true })
}
return op(func(st *cssState, s, ps *styles.Style) { st.flexShrink, st.hasShrink = float32(f), true })
case "flex":
grow, shrink, basis, ok := css.ParseFlex(lval)
if !ok {
return nil
}
return op(func(st *cssState, s, ps *styles.Style) {
st.flexGrow, st.hasGrow = grow, true
st.flexShrink, st.hasShrink = shrink, true
st.flexBasis = basis
})
case "flex-basis":
return op(func(st *cssState, s, ps *styles.Style) { st.flexBasis = lval })
case "gap", "grid-gap":
fs := css.SplitColors(lval)
return op(func(st *cssState, s, ps *styles.Style) {
if len(fs) > 0 {
if l, ok := st.env.Length(fs[0], units.UnitPh); ok {
s.Gap.Y = l
s.Gap.X = l
}
}
if len(fs) > 1 {
if l, ok := st.env.Length(fs[1], units.UnitPw); ok {
s.Gap.X = l
}
}
})
case "row-gap":
return op(func(st *cssState, s, ps *styles.Style) {
if l, ok := st.env.Length(lval, units.UnitPh); ok {
s.Gap.Y = l
}
})
case "column-gap":
return op(func(st *cssState, s, ps *styles.Style) {
if l, ok := st.env.Length(lval, units.UnitPw); ok {
s.Gap.X = l
}
})
case "border-spacing":
fs := css.SplitColors(lval)
return op(func(st *cssState, s, ps *styles.Style) {
if len(fs) > 0 {
if l, ok := st.env.Length(fs[0], units.UnitPw); ok {
s.Gap.Set(l)
}
}
if len(fs) > 1 {
if l, ok := st.env.Length(fs[1], units.UnitPh); ok {
s.Gap.Y = l
}
}
})
case "justify-content", "justify-items", "justify-self", "align-content":
a := css.AlignValue(lval)
return op(func(st *cssState, s, ps *styles.Style) {
switch prop {
case "justify-content":
s.Justify.Content = a
case "justify-items":
s.Justify.Items = a
case "justify-self":
s.Justify.Self = a
default:
s.Align.Content = a
}
})
case "align-items":
a := css.AlignValue(lval)
return op(func(st *cssState, s, ps *styles.Style) {
st.alignItems = lval
s.Align.Items = a
})
case "align-self":
a := css.AlignValue(lval)
return op(func(st *cssState, s, ps *styles.Style) {
st.alignSelf = lval
s.Align.Self = a
})
case "overflow", "overflow-x", "overflow-y":
// Overflow that is hidden is clipped to the size of the box, which
// does not grow to fit it, as with a scrolling overflow in core, but
// without scrollbars (OverflowHidden in core does not clip).
vals := strings.Fields(lval)
if len(vals) == 0 {
return nil
}
if len(vals) == 1 {
vals = append(vals, vals[0])
}
type dimOverflow struct {
dim math32.Dims
ov styles.Overflows
hidden bool
}
var dims []dimOverflow
for d, v := range vals[:2] {
if prop == "overflow-x" && d == 1 || prop == "overflow-y" && d == 0 {
continue
}
do := dimOverflow{dim: math32.Dims(d), ov: styles.OverflowVisible}
switch v {
case "hidden", "clip":
do.ov, do.hidden = styles.OverflowAuto, true
case "auto", "scroll":
do.ov = styles.OverflowAuto
}
dims = append(dims, do)
}
return op(func(st *cssState, s, ps *styles.Style) {
for _, do := range dims {
st.overflowHidden[do.dim] = do.hidden
s.Overflow.SetDim(do.dim, do.ov)
}
})
case "box-shadow":
if lval == "none" {
return op(func(st *cssState, s, ps *styles.Style) { s.BoxShadow = nil })
}
items := css.SplitTopLevel(val, ',')
return op(func(st *cssState, s, ps *styles.Style) {
s.BoxShadow = nil
for _, item := range items {
if sh, ok := boxShadow(st.env, item); ok {
s.BoxShadow = append(s.BoxShadow, sh)
}
}
s.BoxShadowOutside = true // they take no space, as in CSS
})
case "grid-template-columns":
cols := css.GridColumns(lval)
return op(func(st *cssState, s, ps *styles.Style) { s.Columns = cols })
case "object-fit":
fit, ok := map[string]styles.ObjectFits{"fill": styles.FitFill, "contain": styles.FitContain, "cover": styles.FitCover,
"none": styles.FitNone, "scale-down": styles.FitScaleDown}[lval]
if !ok {
return nil
}
return op(func(st *cssState, s, ps *styles.Style) { s.ObjectFit = fit })
case "opacity":
f, err := strconv.ParseFloat(lval, 32)
if err != nil {
return nil
}
return op(func(st *cssState, s, ps *styles.Style) { s.Opacity = float32(f) })
case "pointer-events":
none := lval == "none"
return op(func(st *cssState, s, ps *styles.Style) { s.SetAbilities(none, abilities.NoPointerEvents) })
case "visibility":
// (applied with the inherited visibility; see resolveCSS)
return op(func(st *cssState, s, ps *styles.Style) { st.visibility = lval })
}
return nil
}
// setSize sets the given size property (as max-width) to the given length.
func (st *cssState) setSize(prop string, v *units.Value) {
switch prop {
case "width":
st.width = v
case "height":
st.height = v
case "min-width":
st.minWidth = v
case "min-height":
st.minHeight = v
case "max-width":
st.maxWidth = v
default:
st.maxHeight = v
}
}
// compileBorder compiles the border shorthand for the given side, or all if -1.
func compileBorder(side int, val string) styleOp {
style, width := "none", ""
var color func() image.Image // the color of the text if none
for _, f := range css.SplitColors(val) {
lf := strings.ToLower(f)
switch {
case css.BorderStyleNames[lf]:
style = lf
case lf == "thin" || lf == "medium" || lf == "thick" || (len(lf) > 0 && (lf[0] >= '0' && lf[0] <= '9' || lf[0] == '.')):
width = lf
default:
if css.ParseColor(f) != nil {
color = css.ColorFunc(f)
}
}
}
return func(st *cssState, s, ps *styles.Style) {
w := units.Dp(3) // medium
if width != "" {
w = st.env.BorderWidth(width)
}
cl := image.Image(colors.Uniform(colors.ToUniform(s.Color)))
if color != nil {
cl = color()
}
for i := range 4 {
if side >= 0 && i != side {
continue
}
css.SetSide(&s.Border.Color, i, cl)
css.SetBorderStyle(s, i, style)
if style != "none" && style != "hidden" {
css.SetValueSide(&s.Border.Width, i, w)
}
}
}
}
// setInset sets the given side (top, right, bottom, left) of the inset
// of a positioned element; auto is not set.
func setInset(env *css.LengthEnv, s *styles.Style, i int, v string) {
pct := units.UnitPw
if i == 0 || i == 2 {
pct = units.UnitPh
}
l, ok := env.Length(v, pct)
css.SetSide(&s.InsetSet, i, ok)
if ok {
css.SetValueSide(&s.Inset, i, l)
}
}
func setMargin(st *cssState, i int, v string) {
if v == "auto" {
st.marginAuto[i] = true
st.margin[i] = nil
return
}
st.marginAuto[i] = false
if l, ok := st.env.Length(v, units.UnitPw); ok {
st.margin[i] = &l
}
}
// boxShadow returns the shadow of the given item of a box-shadow value:
// [inset] offset-x offset-y [blur [spread]] [color], and whether it is
// one (an inset shadow is not supported, and is not rendered).
func boxShadow(env *css.LengthEnv, item string) (styles.Shadow, bool) {
var sh styles.Shadow
var lens []units.Value
clr := ""
for _, f := range css.SplitColors(item) {
if strings.EqualFold(f, "inset") {
return sh, false
}
if l, ok := env.Length(f, units.UnitDp); ok && len(lens) < 4 && (f == "0" || strings.ContainsAny(f, "0123456789")) && css.ParseColor(f) == nil {
lens = append(lens, l)
continue
}
clr = f
}
if len(lens) < 2 {
return sh, false
}
sh.OffsetX, sh.OffsetY = lens[0], lens[1]
if len(lens) > 2 {
sh.Blur = lens[2]
}
if len(lens) > 3 {
sh.Spread = lens[3]
}
sh.Color = colors.Uniform(colors.Black)
if c := css.ParseColor(clr); c != nil {
sh.Color = c
}
return sh, true
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"strconv"
"strings"
"cogentcore.org/core/core"
"cogentcore.org/core/htmlcore/css"
"cogentcore.org/core/tree"
douceur "github.com/aymerick/douceur/css"
"golang.org/x/net/html"
)
// pseudoKey is an element and one of its ::before and ::after
// pseudo-elements.
type pseudoKey struct {
node *html.Node
kind string // "before" or "after"
}
// addPseudoRule adds the given declarations of a rule for the given
// pseudo-element of the elements under root that the given selector
// selects.
func (c *Context) addPseudoRule(root *html.Node, sel, kind string, decls []*douceur.Declaration, origin css.Origin) {
cs := css.CompileSelector(sel)
if cs == nil {
return
}
spec := cs.Specificity + 1 // the pseudo-element
if c.pseudoStyles == nil {
c.pseudoStyles = map[pseudoKey][]*cssDecl{}
}
c.pseudoRules = append(c.pseudoRules, &pseudoRule{root: root, sel: css.CompileSelector(sel), text: sel, kind: kind, decls: decls, origin: origin, spec: spec})
if strings.Contains(sel, ":has(") {
c.relational = true
}
if c.recordOnly {
return // (see Context.addedStyle)
}
for _, n := range c.selectNodes(root, sel) {
key := pseudoKey{n, kind}
for _, d := range decls {
p := css.PropertyName(d.Property)
c.cssOrder++
c.noteVars(d.Value)
c.pseudoStyles[key] = append(c.pseudoStyles[key], &cssDecl{Property: p, Value: c.absoluteURLs(strings.TrimSpace(d.Value)),
Important: d.Important, origin: origin, specificity: spec, order: c.cssOrder})
}
}
}
// pseudoBox returns whether the given pseudo-element ("before" or "after")
// of the given element is a box, which has a widget of its own (see
// [Context.pseudoBoxWidget]): it has content without text (as "", for the
// decorations of pages, as the line under the title of Wikipedia), is
// displayed, and has a background, a border, a size, padding, or an
// absolute or fixed position.
func (c *Context) pseudoBox(n *html.Node, kind string) bool {
win := c.pseudoDecls(n, kind)
if win == nil {
return false
}
ct := win["content"]
if ct == nil {
return false
}
switch strings.ToLower(strings.TrimSpace(ct.Value)) {
case "none", "normal":
return false
}
if strings.TrimSpace(contentText(n, ct.Value)) != "" {
return false // text, in the text of the element (see [Context.pseudoMarkup])
}
if d := win["display"]; d != nil && strings.EqualFold(strings.TrimSpace(d.Value), "none") {
return false
}
if d := win["position"]; d != nil {
switch strings.ToLower(strings.TrimSpace(d.Value)) {
case "absolute", "fixed":
return true
}
}
for prop, d := range win {
v := strings.ToLower(strings.TrimSpace(d.Value))
switch {
case prop == "background" || prop == "background-color" || prop == "background-image":
if v != "none" && v != "transparent" && v != "" {
return true
}
case strings.HasPrefix(prop, "border") && !strings.Contains(prop, "radius"):
if v != "none" && v != "0" && v != "" {
return true
}
case prop == "width" || prop == "height" || prop == "min-width" || prop == "min-height" || prop == "aspect-ratio":
if v != "auto" && v != "" && v != "0" {
return true
}
case strings.HasPrefix(prop, "padding"):
// as the boxes of the aspect ratios of the images of
// edition.cnn.com, of padding-bottom: 56.25%
if strings.Trim(v, "0 .pxem%") != "" || strings.ContainsAny(v, "123456789") {
return true
}
}
}
return false
}
// pseudoAttr is the attribute of the elements of the boxes of
// pseudo-elements (see [Context.pseudoBoxNode]), which no element of a
// document has, and which no selector matches.
const pseudoAttr = ":pseudo"
// PseudoElement returns the kind of the pseudo-element ("before" or
// "after") whose box the given element is (an element that is not in the
// document; see the widgets of [NodeOf]), or "" if it is not one, as for
// an app that gives the elements of the document events: the clicks on a
// pseudo-element are those of its element (as the chevrons of the sidebar
// of MDN).
func PseudoElement(n *html.Node) string {
if n == nil || n.Type != html.ElementNode || len(n.Attr) != 1 || n.Attr[0].Key != pseudoAttr {
return ""
}
return n.Attr[0].Val
}
// pseudoBoxNode returns an element for the given pseudo-element of the
// given element if it is a box (see [Context.pseudoBox]), or nil: an
// element that is not in the document, with the declarations of the
// pseudo-element, which is read as a child of the element.
func (c *Context) pseudoBoxNode(el *html.Node, kind string) *html.Node {
if !c.pseudoBox(el, kind) {
return nil
}
pn := &html.Node{Type: html.ElementNode, Data: "span", Attr: []html.Attribute{{Key: pseudoAttr, Val: kind}}}
var decls []*cssDecl
for _, d := range c.pseudoStyles[pseudoKey{el, kind}] {
if d.Property != "content" {
nd := *d
decls = append(decls, &nd)
}
}
c.styles[pn] = decls
if hasCustomDecls(decls) {
c.varMemo = nil
}
if c.hinted == nil {
c.hinted = map[*html.Node]bool{}
}
c.hinted[pn] = true // no attributes
return pn
}
// pseudoDecls returns the winning declaration of each property of the
// given pseudo-element ("before" or "after") of the given element, as in
// the cascade, or nil if it has none.
func (c *Context) pseudoDecls(n *html.Node, kind string) map[string]*cssDecl {
ds := c.pseudoStyles[pseudoKey{n, kind}]
if len(ds) == 0 {
return nil
}
win := map[string]*cssDecl{}
for _, d := range ds {
w := win[d.Property]
if w == nil || d.rank() > w.rank() || d.rank() == w.rank() && (d.specificity > w.specificity || d.specificity == w.specificity && d.order > w.order) {
win[d.Property] = d
}
}
return win
}
// pseudoMarkup returns the rich text markup of the given pseudo-element
// ("before" or "after") of the given element: its text, in its color, with
// its horizontal margins and padding as spaces of their widths (as the
// space between the brackets and the edit links of Wikipedia), or "".
func (c *Context) pseudoMarkup(n *html.Node, kind string) string {
t := c.pseudoContent(n, kind)
if t == "" || c.pseudoBox(n, kind) { // (a box has a widget of its own)
return ""
}
win := c.pseudoDecls(n, kind)
// the margin and padding of each side: the declaration of it that is
// last in the cascade (as margin-inline after margin-right)
type side struct {
v string
order int
}
sides := map[string]side{} // margin-left, padding-right, ...
set := func(d *cssDecl, prop, v string) {
if s, ok := sides[prop]; !ok || d.order > s.order {
sides[prop] = side{v, d.order}
}
}
for _, pre := range []string{"margin", "padding"} {
if d := win[pre]; d != nil {
fs := strings.Fields(d.Value)
switch len(fs) {
case 1:
set(d, pre+"-left", fs[0])
set(d, pre+"-right", fs[0])
case 2, 3:
set(d, pre+"-left", fs[1])
set(d, pre+"-right", fs[1])
case 4:
set(d, pre+"-left", fs[3])
set(d, pre+"-right", fs[1])
}
}
if d := win[pre+"-inline"]; d != nil {
fs := strings.Fields(d.Value)
if len(fs) == 1 {
fs = append(fs, fs[0])
}
set(d, pre+"-left", fs[0])
set(d, pre+"-right", fs[1])
}
for _, sd := range [][2]string{{"-left", "-left"}, {"-inline-start", "-left"}, {"-right", "-right"}, {"-inline-end", "-right"}} {
if d := win[pre+sd[0]]; d != nil {
set(d, pre+sd[1], d.Value)
}
}
}
left := css.EmLength(sides["margin-left"].v) + css.EmLength(sides["padding-left"].v)
right := css.EmLength(sides["margin-right"].v) + css.EmLength(sides["padding-right"].v)
m := html.EscapeString(t)
// the word joiners keep the spaces from being trimmed (at the start
// or end of a text)
if sp := css.EmSpaces(left); sp != "" {
m = "\u2060" + sp + m
}
if sp := css.EmSpaces(right); sp != "" {
m += sp + "\u2060"
}
if d := win["color"]; d != nil {
clr, ok := c.substituteVars(n, d.Value, nil)
if ok && clr != "" && !strings.ContainsAny(clr, `"<>`) {
m = `<span style="color: ` + clr + `">` + m + `</span>`
}
}
return m
}
// pseudoContent returns the text of the given pseudo-element ("before" or
// "after") of the given element: that of its content property, with the
// strings (with their escapes), attr() values, and quotes of it, without
// its alternative text (after a /), or "" if it has none.
func (c *Context) pseudoContent(n *html.Node, kind string) string {
win := c.pseudoDecls(n, kind)
if win == nil {
return ""
}
if d := win["display"]; d != nil && strings.EqualFold(d.Value, "none") {
return ""
}
if d := win["visibility"]; d != nil && (strings.EqualFold(d.Value, "hidden") || strings.EqualFold(d.Value, "collapse")) {
return "" // (as anchors that show on hover)
}
if d := win["opacity"]; d != nil && strings.TrimSpace(d.Value) == "0" {
return ""
}
d := win["content"]
if d == nil {
return ""
}
return contentText(n, d.Value)
}
// contentText returns the text of the given value of the content property
// for the given element.
func contentText(n *html.Node, v string) string {
var sb strings.Builder
for i := 0; i < len(v); {
switch ch := v[i]; ch {
case '"', '\'':
s, end := cssString(v, i)
sb.WriteString(s)
i = end
case '/': // the alternative text, for speech
return sb.String()
case ' ', '\t', '\n':
i++
default:
j := i
for j < len(v) && v[j] != ' ' && v[j] != '"' && v[j] != '\'' && v[j] != '/' {
if v[j] == '(' {
if k := strings.IndexByte(v[j:], ')'); k >= 0 {
j += k
}
}
j++
}
word := strings.ToLower(v[i:j])
switch {
case word == "none" || word == "normal":
return ""
case word == "open-quote":
sb.WriteString("“")
case word == "close-quote":
sb.WriteString("”")
case strings.HasPrefix(word, "attr(") && strings.HasSuffix(word, ")"):
sb.WriteString(GetAttr(n, strings.TrimSpace(v[i+5:j-1])))
}
i = j
}
}
return sb.String()
}
// cssString returns the CSS string that starts at the given index of the
// given value (at its quote), with its escapes (as \2022 and \"), and the
// index after it.
func cssString(v string, start int) (string, int) {
q := v[start]
var sb strings.Builder
i := start + 1
for i < len(v) {
ch := v[i]
switch {
case ch == q:
return sb.String(), i + 1
case ch == '\\' && i+1 < len(v):
j := i + 1
for j < len(v) && j < i+7 && strings.IndexByte("0123456789abcdefABCDEF", v[j]) >= 0 {
j++
}
if j > i+1 { // a hexadecimal code point, with an optional space after it
if r, err := strconv.ParseUint(v[i+1:j], 16, 32); err == nil {
sb.WriteRune(rune(r))
}
if j < len(v) && v[j] == ' ' {
j++
}
i = j
continue
}
sb.WriteByte(v[i+1])
i += 2
continue
default:
sb.WriteByte(ch)
}
i++
}
return sb.String(), i
}
// pseudoText adds a text with the content of the ::before or ::after (the
// given kind) of the given element to the given parent, if it has any.
func (c *Context) pseudoText(parent core.Widget, el *html.Node, kind string) {
if strings.TrimSpace(c.pseudoContent(el, kind)) == "" || c.pseudoBox(el, kind) {
return
}
tx := core.NewText(parent).SetText(c.pseudoMarkup(el, kind))
tx.SetName(kind)
tree.SetUniqueName(tx)
c.handleWidget(nil, tx)
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"fmt"
"slices"
"strconv"
"strings"
"cogentcore.org/core/core"
"cogentcore.org/core/htmlcore/css"
"cogentcore.org/core/tree"
douceur "github.com/aymerick/douceur/css"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
// Fallback returns why the last [Context.Reread] or [Context.Restyle]
// could not make its changes, for the page to be read again whole (as for
// the verbose console of an app), or "" if it could.
func (c *Context) Fallback() string {
return c.fallback
}
// noChange records the given reason why the changes of the page can not
// be made (see [Context.Fallback]), and returns false.
func (c *Context) noChange(why string) bool {
c.fallback = why
return false
}
// describeNode returns a short description of the given element, as
// div#id.class, for the reasons of [Context.Fallback].
func describeNode(n *html.Node) string {
if n == nil {
return "nothing"
}
if n.Type != html.ElementNode {
return "a text"
}
d := n.Data
if id := GetAttr(n, "id"); id != "" {
d += "#" + id
}
if cl := strings.Fields(GetAttr(n, "class")); len(cl) > 0 {
d += "." + cl[0]
}
return d
}
// maxReread is the number of elements beyond which the elements that
// [Context.Reread] would read again are read with the rest of the page,
// on a page of few elements; on a page of more elements, two thirds of
// them may be read again (see [Context.rereadLimit]), as they are read
// without the lock of the widgets of the page (see
// [Context.PrepareReread]), and only their widgets are put in the page
// with it, while those of all of the page are for a page read whole (as
// for the main element of npr.org, of 4000 of its 6000 elements, for
// which it was read whole, as the limit was a third).
const maxReread = 1000
// rereadLimit returns the number of elements beyond which the elements to
// read again are read with the rest of the page: [maxReread], or two thirds
// of the elements of a large page, which takes far longer to read again
// whole (as the pull request files of GitHub, of 35000 elements, read
// again whole in 9s for each 3000 elements of the diffs that it loads as
// it is scrolled, which seemed stuck).
func (c *Context) rereadLimit(root *html.Node) int {
n := 0
if root != nil {
walkElements(root, func(*html.Node) { n++ })
}
return max(maxReread, n*2/3)
}
// recordSheet records the given style or link element as one whose style
// sheet has been added (or not, as for its media), so that a page with a
// new one is read again whole (see [Context.Reread]).
func (c *Context) recordSheet(n *html.Node) {
if c.sheets == nil {
c.sheets = map[*html.Node]bool{}
}
c.sheets[n] = true
if n.DataAtom == atom.Style {
if c.sheetTexts == nil {
c.sheetTexts = map[*html.Node]string{}
}
c.sheetTexts[n] = nodeText(n)
}
}
// addedStyle adds the rules added to the given style element (or the
// rules of the given new style element), whose text is that before with
// more at its end, as CSS-in-JS libraries add them as a page is made (as
// emotion on nytimes.com, for each part of the page, each of which read
// the page again whole, which resized its elements each time). The rules
// are recorded, not applied: the declarations of the elements are found
// again with them (see [Context.updateDecls]). It returns false for
// another change of the text of a style sheet, for which the page is
// read again.
func (c *Context) addedStyle(n *html.Node) bool {
text := nodeText(n)
old, ok := c.sheetTexts[n]
if !c.sheets[n] {
old, ok = "", true // a new style element
}
if !ok || !strings.HasPrefix(text, old) {
return false
}
c.recordSheet(n)
added := text[len(old):]
if strings.TrimSpace(added) == "" || !c.mediaMatches(GetAttr(n, "media")) {
return true
}
base := c.cssBase
c.cssBase = ""
c.recordOnly = true
defer c.enterScope(n)() // (of a shadow tree, see shadow.go)
root := rootNode(n)
if c.curScope != nil {
root = c.curScope
}
c.addRules(root, css.Parse(added), css.OriginAuthor)
c.recordOnly = false
c.cssBase = base
return true
}
// addedSheet adds the rules of the given new style or link element (see
// [Context.addedStyle]): those of a link to a style sheet are gotten
// (with the media of the link, and its imports), and recorded, not
// applied, as those added to style elements, so that the elements that
// they may select are matched again (see [Context.addedRuleTargets]),
// instead of the page being read again whole (as for the style sheets of
// the parts of nytimes.com, which its scripts add as it loads). It returns
// false for a change of a style element that is not an addition to it.
func (c *Context) addedSheet(n *html.Node) bool {
if n.DataAtom == atom.Style {
return c.addedStyle(n)
}
c.recordSheet(n)
if !strings.EqualFold(strings.TrimSpace(GetAttr(n, "rel")), "stylesheet") || !c.mediaMatches(GetAttr(n, "media")) {
return true
}
base, node := c.cssBase, c.Node
c.cssBase, c.Node = "", n
c.recordOnly = true
defer c.enterScope(n)() // (of a shadow tree, see shadow.go)
c.addLinkedStyle(GetAttr(n, "href"))
c.recordOnly = false
c.cssBase, c.Node = base, node
return true
}
// headChanged handles a change of the children of the given head element:
// a new style element, or link to a style sheet, adds its rules (see
// [Context.addedSheet]), and the other elements of the head are not
// rendered. It returns false for a change of a style element that is not
// an addition to it.
func (c *Context) headChanged(head *html.Node) bool {
for k := head.FirstChild; k != nil; k = k.NextSibling {
if k.Type != html.ElementNode || c.sheets[k] {
continue
}
if (k.DataAtom == atom.Style || k.DataAtom == atom.Link) && !c.addedSheet(k) {
return false
}
}
return true
}
// Reread updates the widgets of the page that the context has read for
// changes of its document, as scripts make, without reading all of it
// again (which makes new widgets for all of it): self has the elements
// that have changed themselves (as their attributes), and children those
// whose children have changed (as nodes added to them, or the text of
// their text nodes). The nearest element of each that has a frame of its
// own, whose widgets can be made alone (as one that is not a cell of a
// table or an item of a grid), is read again, into new widgets, which
// are reconciled with the old ones with [tree.Plan]: the widgets of the
// elements that have not changed, nor those in them, are kept, as are the
// frames of the elements that have not changed themselves, whose children
// are reconciled in turn, and the others are replaced. The declarations
// of the elements are found again as for [Context.Restyle], and the
// widgets of those that are not read again are styled again. It returns
// false, leaving the page as it was, if the changes can not be made so,
// for the page to be read again: for a new style sheet, a change of the
// html element itself, or more elements to read than [Context.rereadLimit].
func (c *Context) Reread(self, children []*html.Node) bool {
apply := c.PrepareReread(self, children)
if apply == nil {
return false
}
apply()
return true
}
// PrepareReread reads the given elements again as [Context.Reread] does,
// into new widgets, with the styles of the context locked (see
// [Context.LockStyles]), and without the lock of the widgets of the page
// (as it takes time: as long as a second, on nytimes.com, in which the app
// did not respond), and returns the function that puts the new widgets in
// the page, with the lock of the widgets held, or nil if they can not be
// read again (see [Context.Fallback]).
func (c *Context) PrepareReread(self, children []*html.Node) func() {
c.styleMu.Lock()
defer c.styleMu.Unlock()
var apply func()
if !c.prepareReread(self, children, &apply) {
return nil
}
if apply == nil {
apply = func() {}
}
return apply
}
// prepareReread is [Context.PrepareReread], setting the function that
// applies it, if any, and returning whether it can.
func (c *Context) prepareReread(self, children []*html.Node, apply *func()) bool {
c.containersChanged() // (declarations may change)
defer c.containersChanged()
if len(self) == 0 && len(children) == 0 {
return true
}
c.fallback = ""
if c.reading || c.rest != nil || c.elementWidgets == nil {
return c.noChange("the page is being read")
}
// the changed elements (that of a text node is its parent, whose
// children have changed)
var root *html.Node
selfDirty, childDirty := map[*html.Node]bool{}, map[*html.Node]bool{}
var changed []*html.Node // for the declarations of the elements after them
var roots []*html.Node
restyleAll := false // for rules added to style sheets (see addedStyle)
var htmlChildren *html.Node // the html element, if its children changed
addChanged := func(n *html.Node, own bool) bool {
if n != nil && n.Type == html.CommentNode || !own && n != nil && n.Type == html.ElementNode && unshown(n) {
return true // (not rendered)
}
if n != nil && n.Type != html.ElementNode {
n, own = n.Parent, false
}
if own && unshown(n) {
return true
}
if n == nil || n.Type != html.ElementNode {
return c.noChange("a change of the document itself")
}
if !own && n.DataAtom == atom.Style && c.sheets[n] {
if !c.addedStyle(n) {
return c.noChange("a change of the style sheet of " + describeNode(n) + " that is not an addition to it")
}
if root == nil {
root = rootNode(n)
}
restyleAll = true
return true
}
if n.DataAtom == atom.Title && inHead(n) {
// the title of the page (as scripts set it), which is not
// rendered: it is the title of the context (see Context.Title)
c.Title = strings.Join(strings.Fields(nodeText(n)), " ")
return true
}
if !own && n.DataAtom == atom.Head {
if !c.headChanged(n) {
return c.noChange("a change of a style sheet in the head that is not an addition to it")
}
if root == nil {
root = rootNode(n)
}
restyleAll = true
return true
}
if root == nil {
root = rootNode(n)
} else if rootNode(n) != root {
return c.noChange("changes of different documents")
}
// (an element that has changed itself may have another box, as
// for its display, in that of its parent)
from := n
if own {
from = n.Parent
}
if from != nil && from.Type == html.ElementNode && !inHead(from) && c.undisplayed(from) && !hasNewSheet(c, from) {
// in an element that is not displayed, which has no widgets
// (as the video players of npr.org in its hidden dialogs,
// whose changes as they played read the page whole, as they
// were in main): its declarations are found again, and it is
// read when it is displayed (see Context.updateDecls)
if own {
changed = append(changed, n)
}
return true
}
r := c.rereadRoot(from)
if r == nil && own && (n.DataAtom == atom.Html || n.DataAtom == atom.Body) {
// a change of the attributes of the html or body element (as
// the classes that scripts add to them, for the page as it
// loads, as on npr.org): it is styled again, with the elements
// that the change may select differently (see
// Context.invalidation), unless it needs to be read again (as
// for its display; see Context.updateDecls)
changed = append(changed, n)
return true
}
if r == nil && !own && n.DataAtom == atom.Html {
// a change of the children of the html element, as an element
// added after the body (as scripts measure things with, as on
// npr.org): its children are read again, but the body, which
// is kept (see Context.rereadHTML)
htmlChildren = n
return true
}
if r == nil {
return c.noChange("no element of " + describeNode(from) + " can be read again alone")
}
roots = append(roots, r)
if own {
selfDirty[n] = true
changed = append(changed, n)
} else {
childDirty[n] = true
}
return true
}
// the images whose sources changed, which are set in their widgets
// (see Context.imageChange)
var swaps []*imageSwap
srcRules := -1
for _, n := range self {
if c.inertChange(n) {
c.resnap(n)
continue
}
if sw, ok := c.imageChange(n, &srcRules); ok {
swaps = append(swaps, sw)
if sw.restyle {
changed = append(changed, n) // (styled again, see updateDecls)
if root == nil {
root = rootNode(n)
}
}
continue
}
if !addChanged(n, true) {
return false
}
}
for _, sw := range swaps {
sw.load(c)
}
applySwaps := func() {
for _, sw := range swaps {
sw.apply()
}
}
if len(swaps) > 0 {
*apply = applySwaps
}
for _, n := range children {
if !addChanged(n, false) {
return false
}
}
roots = outermost(roots)
inRoots := func(n *html.Node) bool {
for _, r := range roots {
if contains(r, n) {
return true
}
}
return false
}
if htmlChildren != nil && !c.htmlRereadable(htmlChildren, roots, selfDirty) {
return c.noChange("a change of the children of the html element")
}
if len(roots) == 0 && !restyleAll && len(changed) == 0 && htmlChildren == nil {
return true // (only elements that are not rendered changed, or images)
}
// the children of the html element that are read again (see
// rereadHTML), its head and those but its body, have their
// declarations found too, with those of the elements that the scripts
// add to them (as the scripts and styles that the scripts of npr.org
// added to its head, as it added an element after the body, which had
// no display: none of their own, so that their text was shown at the
// top of the page), and their style sheets are added
var htmlKids []*html.Node
if htmlChildren != nil {
for k := htmlChildren.FirstChild; k != nil; k = k.NextSibling {
if htmlChildOf(k) == k {
htmlKids = append(htmlKids, k)
}
}
}
// the style sheets added in the elements to read again (as those that
// the scripts of nytimes.com add with the parts of the page) add their
// rules, as those added to the head
for _, r := range append(slices.Clip(roots), htmlKids...) {
ok := true
walkElements(r, func(n *html.Node) {
if ok && (n.DataAtom == atom.Style || n.DataAtom == atom.Link) && !c.sheets[n] {
ok = c.addedSheet(n)
restyleAll = true
}
})
if !ok {
return c.noChange("a change of a style sheet in " + describeNode(r) + " that is not an addition to it")
}
}
targeted := false
if restyleAll {
html := documentElement(root)
if shallow, deep, ok := c.addedRuleTargets(html); ok {
// only the elements that the added rules select (as for those
// that the CSS-in-JS of nytimes.com adds as it loads, each
// time matching its 10000 elements again, for 1s)
c.addedShallow, c.addedDeep = shallow, deep
targeted, restyleAll = true, false
defer func() { c.addedShallow, c.addedDeep = nil, nil }()
} else if html != nil {
// the declarations of all of the elements are found again,
// with the rules added to the style sheets, as for a restyle
changed = append(changed, html)
}
}
// the elements to read are not too many (not counting those that are
// kept without being read; see Context.keptElements), have no new
// style sheets, and their widgets are all in their frames, which have
// only theirs
size, limit := 0, c.rereadLimit(root)
prelim := c.keptElements(roots, touchedBy(selfDirty, childDirty), selfDirty)
for _, r := range roots {
ok := true
walkElements(r, func(n *html.Node) {
if !inKept(prelim, n) {
size++
}
for _, w := range c.elementWidgets[n] {
if !widgetIn(w, c.elementWidgets[r][0]) {
ok = false // (as one moved elsewhere)
}
}
})
if !ok {
return c.noChange("an element moved, in " + describeNode(r))
}
if size > limit {
return c.noChange(fmt.Sprintf("%d elements to read again (more than %d), in %s", size, limit, describeNode(r)))
}
if !c.readableRoot(r, root, inRoots) {
return c.noChange("widgets of other elements in those of " + describeNode(r))
}
}
// the elements whose changes as they are styled again their widgets can
// not be styled for (as of their display or pseudo-elements, as on
// nytimes.com) are read again too, with the elements that they are in,
// instead of the page whole
c.addRoot = func(n *html.Node) bool {
if n.Parent == nil {
return false
}
if htmlChildren != nil && htmlChildOf(n) != nil {
return true // (read again with the children of the html element)
}
r := c.rereadRoot(n.Parent)
if r == nil || !c.readableRoot(r, root, func(k *html.Node) bool { return contains(r, k) }) {
return false
}
roots = outermost(append(roots, r))
return true
}
defer func() { c.addRoot = nil }()
c.matchKept = c.shallowKept(prelim)
c.matchAll = restyleAll
u, ok := c.updateDecls(changed, append(slices.Clip(roots), htmlKids...), inRoots)
c.matchKept, c.matchAll = nil, false
if !ok {
return false // (with the fallback of updateDecls)
}
if targeted {
// (the other elements do not match the added rules)
c.matchedRules, c.matchedPseudo = len(c.rules), len(c.pseudoRules)
}
for n := range u.freeChanged {
selfDirty[n] = true
}
touched := touchedBy(selfDirty, childDirty)
keep := c.keptElements(roots, touched, selfDirty)
c.reading = true
defer func() { c.reading = false }()
stage := c.StageSize
c.StageSize = 0
defer func() { c.StageSize = stage }()
c.rereads++
c.keepRead = keep
defer func() { c.keepRead = nil }()
// the elements are read into new widgets (here, without the lock of
// the widgets of the page), which are put in the page by apply
type read struct {
r *html.Node
old, pw core.Widget
tmp *core.Frame
}
var reads []read
for _, r := range roots {
old := c.elementWidgets[r][0]
pw := old.AsTree().Parent.(core.Widget)
c.forgetRead(r, keep)
tmp := core.NewFrame()
c.inlineParent = nil
readOneNode(c, tmp, r)
c.lockStylesOf(tmp)
reads = append(reads, read{r, old, pw, tmp})
}
var applyHTML func()
if htmlChildren != nil {
applyHTML = c.rereadHTML(htmlChildren, touched, selfDirty)
}
*apply = func() {
for _, rd := range reads {
rc := &reconciler{c: c, touched: touched, selfDirty: selfDirty, kept: keep, pairs: map[core.Widget]core.Widget{}}
rc.replaceIn(rd.pw, rd.old, rd.tmp.Children)
rc.placeKept()
rc.remap(rd.r)
}
if applyHTML != nil {
applyHTML()
}
u.apply(c)
applySwaps()
}
return true
}
// htmlRereadable returns whether the children of the given html element
// can be read again with its body kept as it is (see [Context.rereadHTML]):
// its body has a frame of its own in the widget that the page is read
// into, and nothing in it changes.
func (c *Context) htmlRereadable(h *html.Node, roots []*html.Node, selfDirty map[*html.Node]bool) bool {
var body *html.Node
for k := h.FirstChild; k != nil; k = k.NextSibling {
if k.DataAtom == atom.Body {
body = k
}
}
if body == nil || !c.rereadable(body) || selfDirty[body] {
return false
}
for _, r := range roots {
if contains(body, r) {
return false
}
}
return true
}
// htmlChildOf returns the child of the html element that the given element
// is (or is in), other than its body, which are read again whole with the
// children of the html element (see [Context.rereadHTML]), or nil.
func htmlChildOf(n *html.Node) *html.Node {
for ; n != nil && n.Parent != nil; n = n.Parent {
if n.Parent.Type == html.ElementNode && n.Parent.DataAtom == atom.Html {
if n.Type == html.ElementNode && n.DataAtom != atom.Body {
return n
}
return nil
}
}
return nil
}
// rereadHTML reads the children of the given html element again, but its
// body, whose widgets are kept as they are (see [Context.keptElements]),
// in the widget that the page is read into, returning the function that
// puts them in it (with the lock of the widgets held).
func (c *Context) rereadHTML(h *html.Node, touched, selfDirty map[*html.Node]bool) func() {
var body *html.Node
for k := h.FirstChild; k != nil; k = k.NextSibling {
if k.DataAtom == atom.Body {
body = k
}
}
bw := c.elementWidgets[body][0]
content := bw.AsTree().Parent.(core.Widget)
keep := map[*html.Node]core.Widget{body: bw}
for k := h.FirstChild; k != nil; k = k.NextSibling {
if k.Type == html.ElementNode && k != body && k.DataAtom != atom.Head {
c.forgetRead(k, keep)
}
}
c.keepRead = keep
defer func() { c.keepRead = nil }()
tmp := core.NewFrame()
c.inlineParent = nil
c.Node = h
readHTMLNode(c, tmp, h.FirstChild)
c.lockStylesOf(tmp)
return func() {
rc := &reconciler{c: c, touched: touched, selfDirty: selfDirty, kept: keep, pairs: map[core.Widget]core.Widget{}}
p := &tree.Plan{EnforceEmpty: true}
rc.planChildren(p, content.AsTree().Children, tmp.Children, childNames(content))
p.Update(content)
rc.updateAdded()
rc.placeKept()
rc.remap(h)
content.AsWidget().NeedsLayout()
}
}
// unshown returns whether the given element is never shown, nor its
// children, so that its changes change nothing that is rendered: a
// script, or an element of the head other than those of style sheets and
// the title (as the meta elements that the scripts of github.com change).
func unshown(n *html.Node) bool {
if n == nil || n.Type != html.ElementNode {
return false
}
switch n.DataAtom {
case atom.Script, atom.Noscript, atom.Template:
return true
case atom.Style, atom.Link, atom.Title, atom.Base:
return false
}
return n.Parent != nil && n.Parent.DataAtom == atom.Head
}
// rereadRoot returns the element that is read again for a change of the
// given element (see [Context.Reread]): the nearest one that it is in (or
// it) that has a frame of its own, in the frame of its parent, whose
// widgets can be made alone (or the body), or nil if there is none (as for
// a change of the html element itself, which is read again whole).
func (c *Context) rereadRoot(n *html.Node) *html.Node {
for e := n; e != nil && e.Type == html.ElementNode; e = e.Parent {
switch e.DataAtom {
case atom.Html, atom.Head, atom.Style, atom.Link, atom.Title, atom.Base, atom.Meta, atom.Template:
return nil
}
if c.rereadable(e) {
return e
}
}
return nil
}
// rereadable returns whether the widgets of the given element can be made
// alone (see [Context.rereadRoot]).
func (c *Context) rereadable(e *html.Node) bool {
p := e.Parent
if p == nil || p.Type != html.ElementNode || e.Namespace != "" || inForeign(e) {
return false
}
ws := c.elementWidgets[e]
if len(ws) != 1 || ownNode(ws[0]) != e || frameOf(ws[0]) == nil {
return false
}
pw, ok := ws[0].AsTree().Parent.(core.Widget)
if ok && e.DataAtom == atom.Body {
return core.AsFrame(pw) != nil // (the widget that the page is read into)
}
if !ok || frameOf(pw) == nil || ownNode(pw) != p {
return false // (as in the frames of columns)
}
if c.isInlineLevel(e) || ancestorTable(e) != nil || tableElements[e.Data] {
return false // in a run of inline content, or in the grid of a table
}
if fl := c.declaration(e, "float"); fl != "" && fl != "none" || c.flattened[e] || c.floatSiblings[p] {
return false
}
// the items of grids and columns, which are arranged as they are read
return !c.arrangedChildren(p)
}
// tableElements are the elements of tables, which are read as the grids
// of their tables.
var tableElements = map[string]bool{"table": true, "td": true, "th": true, "tr": true, "col": true, "colgroup": true,
"caption": true, "thead": true, "tbody": true, "tfoot": true}
// arrangedChildren returns whether the widgets of the children of the
// given element are arranged once they are read (see [Context.arrange]),
// as in a grid, so that they can not be made alone, nor be kept when
// others are made (see [Context.Reread]).
func (c *Context) arrangedChildren(n *html.Node) bool {
d := c.displayOf(n)
if strings.Contains(d, "grid") || strings.Contains(d, "table") || n.Data == "details" || tableElements[n.Data] {
return true
}
if strings.Contains(d, "flex") && strings.HasSuffix(c.flexDirection(n), "-reverse") {
return true
}
for _, p := range []string{"columns", "column-count", "column-width"} {
if v := c.declaration(n, p); v != "" && v != "auto" {
return true
}
}
for k := n.FirstChild; k != nil; k = k.NextSibling {
if k.Type == html.ElementNode && strings.TrimSpace(c.declaration(k, "order")) != "" {
return true
}
}
return false
}
// forgetRead forgets the state of the reading of the given element and
// those in it, which are read again: their widgets (which are added again
// as they are read), and the state of their tables and floats. Their
// containers start with the sizes that they have.
func (c *Context) forgetRead(r *html.Node, keep map[*html.Node]core.Widget) {
walkElementsSkipping(r, keep, func(n *html.Node) {
delete(c.elementWidgets, n)
delete(c.tables, n)
delete(c.tableRowState, n)
delete(c.flattened, n)
delete(c.floatSiblings, n)
delete(c.columnUses, n)
if cf := c.containers[n]; cf != nil && cf.size.X > 0 {
if c.keptContainers == nil {
c.keptContainers = map[*html.Node]containerSizes{}
}
c.containerMu.Lock()
c.keptContainers[n] = containerSizes{cf.size, cf.prev}
c.containerMu.Unlock()
}
})
}
// reconciler reconciles the widgets of elements that are read again with
// their old ones (see [Context.Reread]).
type reconciler struct {
c *Context
// touched has the elements that have changed, or are in elements
// that have, and selfDirty those that have changed themselves.
touched, selfDirty map[*html.Node]bool
// pairs has the old widget that is kept for each new widget.
pairs map[core.Widget]core.Widget
// kept has the old widgets of the elements that are kept without
// being read again (see [Context.keptElements]), which are in the new
// widgets as placeholders (see [keptPlaceholder]), and placed has
// those that have been put in their places.
kept map[*html.Node]core.Widget
placed map[*html.Node]bool
// added has the new widgets that are added in place of old ones,
// and removed the old widgets that are removed.
added, removed []core.Widget
}
// replaceIn updates the children of the given parent for the given new
// widgets in place of the given old child.
func (rc *reconciler) replaceIn(parent core.Widget, old core.Widget, news []tree.Node) {
p := &tree.Plan{EnforceEmpty: true}
names := childNames(parent)
for _, k := range parent.AsTree().Children {
if k != tree.Node(old) {
rc.keep(p, k)
continue
}
rc.planChildren(p, []tree.Node{old}, news, names)
}
p.Update(parent)
rc.updateAdded()
}
// keep adds the given old child to the given plan, as it is.
func (rc *reconciler) keep(p *tree.Plan, k tree.Node) {
p.Add(k.AsTree().Name, func() tree.Node { return k }, func(tree.Node) {})
}
// childNames returns the names of the children of the given node.
func childNames(n tree.Node) map[string]bool {
names := map[string]bool{}
for _, k := range n.AsTree().Children {
names[k.AsTree().Name] = true
}
return names
}
// newWidgetName returns the given name of a new widget, or, if it is in the
// given names, a new one of it with the given number of the reread, and a
// count after it if that is in them too (as the new widgets of the same
// name in a reread, or a widget of that name from an earlier one, as the
// count of rereads starts again when the page is read whole: the names of
// the children of a parent must be unique, as for the frames of github.com
// as it loaded, which panicked).
func newWidgetName(names map[string]bool, name string, reread int) string {
if !names[name] {
return name
}
base := name + "~" + strconv.Itoa(reread)
name = base
for i := 2; names[name]; i++ {
name = base + "-" + strconv.Itoa(i)
}
return name
}
// planChildren adds to the given plan the given new children, each as
// the old one of the same element and type (among the given old ones)
// where it can be kept, reconciling the children of those kept for
// changes in them; the old ones that are not kept are removed. The new
// ones get names that are not in names (of the children of the parent).
func (rc *reconciler) planChildren(p *tree.Plan, olds, news []tree.Node, names map[string]bool) {
type key struct {
n *html.Node
typ string
i int
}
keyOf := func(k tree.Node, counts map[key]int) key {
w, _ := k.(core.Widget)
kk := key{typ: k.AsTree().NodeType().Name}
if w != nil {
kk.n = ownNode(w)
}
kk.i = counts[kk]
counts[kk]++
return kk
}
oldBy := map[key]tree.Node{}
counts := map[key]int{}
for _, k := range olds {
if kk := keyOf(k, counts); kk.n != nil {
oldBy[kk] = k
}
}
kept := map[tree.Node]bool{}
counts = map[key]int{}
for _, nk := range news {
if kn := keptPlaceholderNode(nk); kn != nil {
// an element kept as it is, without being read again
if old := rc.kept[kn]; old != nil && slices.Contains(olds, tree.Node(old)) {
kept[old] = true
rc.keep(p, old)
rc.markPlaced(kn)
continue
}
}
kk := keyOf(nk, counts)
ok := oldBy[kk]
if ok != nil && rc.reconcile(ok.(core.Widget), nk.(core.Widget)) {
kept[ok] = true
rc.keep(p, ok)
continue
}
// a new widget, with a name that no old one has (so that it is
// not taken for one of them)
name := newWidgetName(names, nk.AsTree().Name, rc.c.rereads)
names[name] = true
nw := nk
p.Add(name, func() tree.Node { return nw }, func(tree.Node) {})
if w, ok := nk.(core.Widget); ok {
rc.added = append(rc.added, w)
}
}
for _, k := range olds {
if !kept[k] {
if w, ok := k.(core.Widget); ok {
rc.removed = append(rc.removed, w)
}
}
}
}
// reconcile returns whether the given old widget is kept for the given
// new one (of the same element and type): as it is, if the element and
// those in it have not changed, and the widgets are of the same shape;
// with its children reconciled, if it is the frame of an element that has
// not changed itself, whose children are not arranged as they are read.
func (rc *reconciler) reconcile(old, nw core.Widget) bool {
n := ownNode(old)
if !rc.touched[n] {
if !sameShape(old, nw) {
return false
}
rc.pairShapes(old, nw)
return true
}
if rc.selfDirty[n] || frameOf(old) == nil || frameOf(nw) == nil || rc.c.arrangedChildren(n) {
return false
}
rc.pairs[nw] = old
p := &tree.Plan{EnforceEmpty: true}
rc.planChildren(p, old.AsTree().Children, nw.AsTree().Children, childNames(old))
p.Update(old)
old.AsWidget().NeedsLayout()
return true
}
// sameShape returns whether the given widgets are of the same type, of
// the same elements, with children of the same shapes.
func sameShape(a, b tree.Node) bool {
if a.AsTree().NodeType() != b.AsTree().NodeType() {
return false
}
aw, aok := a.(core.Widget)
bw, bok := b.(core.Widget)
if aok != bok || aok && ownNode(aw) != ownNode(bw) {
return false
}
ak, bk := a.AsTree().Children, b.AsTree().Children
if len(ak) != len(bk) {
return false
}
for i := range ak {
if !sameShape(ak[i], bk[i]) {
return false
}
}
return true
}
// pairShapes pairs the widgets of the given old widget with those of the
// given new one of the same shape, which are kept.
func (rc *reconciler) pairShapes(old, nw tree.Node) {
if ow, ok := old.(core.Widget); ok {
rc.pairs[nw.(core.Widget)] = ow
}
ok, nk := old.AsTree().Children, nw.AsTree().Children
for i := range ok {
rc.pairShapes(ok[i], nk[i])
}
}
// updateAdded styles the new widgets that have been added.
func (rc *reconciler) updateAdded() {
for _, w := range rc.added {
w.AsWidget().Update()
}
rc.added = nil
}
// remap updates the state of the context for the old widgets that are
// kept, in place of the new ones made for them, after the given element
// is read again, and forgets that of those that are removed.
func (rc *reconciler) remap(r *html.Node) {
c := rc.c
newOf := func(w core.Widget) core.Widget {
if o := rc.pairs[w]; o != nil {
return o
}
return w
}
walkElements(r, func(n *html.Node) {
ws := c.elementWidgets[n]
for i, w := range ws {
ws[i] = newOf(w)
}
if w := c.nodeWidgets[n]; w != nil {
c.nodeWidgets[n] = newOf(w)
}
if cf := c.containers[n]; cf != nil {
if o, ok := newOf(cf).(*containerFrame); ok {
c.containers[n] = o
}
}
if sw := c.hoverTargets[n]; sw != nil {
if o, ok := newOf(sw).(*core.Switch); ok {
c.hoverTargets[n] = o
}
}
})
for nw := range rc.pairs {
delete(c.blocks, nw)
}
// the state of the removed widgets, and of the elements that are no
// longer in the page
root := rootNode(r)
for _, w := range rc.removed {
for cw := range w.AsWidget().AllWidgets() {
delete(c.blocks, cw)
if n := ownNode(cw); n != nil && rootNode(n) != root {
if hasCustomDecls(c.styles[n]) {
c.varMemo = nil
}
delete(c.elementWidgets, n)
delete(c.nodeWidgets, n)
delete(c.styles, n)
delete(c.sorted, n)
delete(c.hinted, n)
delete(c.containers, n)
}
}
}
}
// ownNode returns the element of the given widget itself (not that of a
// widget that it is in, as [NodeOf] does), or nil.
func ownNode(w core.Widget) *html.Node {
n, _ := w.AsWidget().Property("node").(*html.Node)
return n
}
// widgetIn returns whether the given widget is the given one or in it.
func widgetIn(w, in core.Widget) bool {
for t := tree.Node(w); t != nil; t = t.AsTree().Parent {
if t == tree.Node(in) {
return true
}
}
return false
}
// walkElements calls the given function for the given element and the
// elements in it.
func walkElements(n *html.Node, f func(n *html.Node)) {
if n.Type == html.ElementNode {
f(n)
}
for k := n.FirstChild; k != nil; k = k.NextSibling {
walkElements(k, f)
}
}
// outermost returns the given elements without those in others of them
// (and duplicates).
func outermost(ns []*html.Node) []*html.Node {
var out []*html.Node
for i, n := range ns {
in := false
for j, o := range ns {
if i != j && o != n && contains(o, n) || o == n && j < i {
in = true
break
}
}
if !in {
out = append(out, n)
}
}
return out
}
// documentElement returns the root element (html) of the given document.
func documentElement(doc *html.Node) *html.Node {
if doc == nil {
return nil
}
for k := doc.FirstChild; k != nil; k = k.NextSibling {
if k.Type == html.ElementNode {
return k
}
}
return nil
}
// hasNewSheet returns whether the given element has a style sheet in it
// (or is one) that has not been added to the page.
func hasNewSheet(c *Context, n *html.Node) bool {
found := false
walkElements(n, func(k *html.Node) {
if (k.Data == "style" || k.Data == "link") && !c.sheets[k] {
found = true
}
})
return found
}
// touchedBy returns the elements that have changed (in the given sets),
// and those that they are in.
func touchedBy(sets ...map[*html.Node]bool) map[*html.Node]bool {
touched := map[*html.Node]bool{}
for _, set := range sets {
for n := range set {
for p := n; p != nil && !touched[p]; p = p.Parent {
touched[p] = true
}
}
}
return touched
}
// keptElements returns the elements in the given elements to read again
// (see [Context.Reread]) that are kept as they are, with their widgets,
// without being read again: as browsers lay out again only the boxes
// that have changed, or have changed boxes in them. They are those that
// have not changed, nor any element in them, in an element whose children
// have changed (only), whose frame is kept (see [reconciler.reconcile]),
// as the old widgets of those elements are kept anyway: a script that
// added an element to the body of npr.org read all of its 5000 elements
// again, many times as it loaded. The widgets of each must be its frame
// alone in that of its parent (see [Context.rereadable]), and not an item
// of a list (whose markers are numbered as they are read).
func (c *Context) keptElements(roots []*html.Node, touched, selfDirty map[*html.Node]bool) map[*html.Node]core.Widget {
keep := map[*html.Node]core.Widget{}
var find func(e *html.Node)
find = func(e *html.Node) {
if !touched[e] || selfDirty[e] || len(c.elementWidgets[e]) != 1 || frameOf(c.elementWidgets[e][0]) == nil || c.arrangedChildren(e) {
return
}
switch e.DataAtom {
case atom.Ol, atom.Ul, atom.Menu, atom.Dl:
return
}
var kids []*html.Node
for k := e.FirstChild; k != nil; k = k.NextSibling {
if k.Type == html.ElementNode {
kids = append(kids, k)
}
}
// new elements (not read yet), whose neighbors are read again
isNew := func(i int) bool { return i >= 0 && i < len(kids) && len(c.elementWidgets[kids[i]]) == 0 }
for i, k := range kids {
if touched[k] {
find(k)
continue
}
// the first and last elements, and those next to new ones,
// are read again if they have vertical margins, which may
// collapse with those of their parent or their new siblings
top, bottom := c.verticalMargins(k)
if (i == 0 || isNew(i-1)) && top || (i == len(kids)-1 || isNew(i+1)) && bottom {
if len(c.elementWidgets[k]) > 0 {
// (with new widgets, not the old ones that the
// reconciler would keep for them otherwise)
touched[k], selfDirty[k] = true, true
}
continue
}
if k.DataAtom != atom.Li && c.rereadable(k) {
keep[k] = c.elementWidgets[k][0]
}
}
}
for _, r := range roots {
find(r)
}
return keep
}
// inKept returns whether the given element is one of the given kept ones
// or in one.
func inKept(keep map[*html.Node]core.Widget, n *html.Node) bool {
for p := n; p != nil; p = p.Parent {
if keep[p] != nil {
return true
}
}
return false
}
// walkElementsSkipping calls the given function for the given element and
// the elements in it, except the given ones and those in them.
func walkElementsSkipping(n *html.Node, skip map[*html.Node]core.Widget, f func(n *html.Node)) {
if skip[n] != nil {
return
}
if n.Type == html.ElementNode {
f(n)
}
for k := n.FirstChild; k != nil; k = k.NextSibling {
walkElementsSkipping(k, skip, f)
}
}
// keptPlaceholder adds a placeholder to the given parent for the given
// element, which is kept as it is (see [Context.keptElements]): its old
// widget takes its place (see [reconciler.planChildren]).
func keptPlaceholder(parent core.Widget, n *html.Node) {
ph := core.NewFrame(parent)
ph.SetProperty("keptNode", n)
}
// keptPlaceholderNode returns the element of the given widget if it is a
// placeholder (see [keptPlaceholder]), or nil.
func keptPlaceholderNode(k tree.Node) *html.Node {
n, _ := k.AsTree().Property("keptNode").(*html.Node)
return n
}
// markPlaced records that the old widget of the given kept element has
// been put in its place.
func (rc *reconciler) markPlaced(n *html.Node) {
if rc.placed == nil {
rc.placed = map[*html.Node]bool{}
}
rc.placed[n] = true
}
// placeKept puts the old widgets of the kept elements that are not in
// their places yet (in new widgets, which are not reconciled with old
// ones) in the places of their placeholders.
func (rc *reconciler) placeKept() {
if len(rc.placed) == len(rc.kept) {
return
}
for n, old := range rc.kept {
if rc.placed[n] {
continue
}
// the placeholder, in the new widgets of the element that n is in
var ph core.Widget
for p := n.Parent; p != nil && ph == nil; p = p.Parent {
for _, w := range rc.c.elementWidgets[p] {
for cw := range w.AsWidget().AllWidgets() {
if keptPlaceholderNode(cw) == n {
ph = cw
break
}
}
if ph != nil {
break
}
}
}
if ph == nil {
continue // not read, as in an element that is not displayed
}
np := ph.AsTree().Parent
i := tree.IndexOf(np.AsTree().Children, tree.Node(ph))
if op := old.AsTree().Parent; op != nil {
if j := tree.IndexOf(op.AsTree().Children, tree.Node(old)); j >= 0 {
op.AsTree().Children = slices.Delete(op.AsTree().Children, j, j+1)
}
}
np.AsTree().Children[i] = old
tree.SetParent(old, np)
rc.markPlaced(n)
}
}
// shallowKept returns those of the given elements that may be kept as they
// are (see [Context.keptElements]) whose declarations are found again only
// for themselves (see [Context.updateDecls]), not for those in them, which
// match the style rules as they did: those whose place in their parents
// has not changed in a way that the selectors of the rules select the
// elements in them by (as .item:first-child a, or .tab + .panel p; see
// [Context.deepPlaces]), as browsers match only the elements that the
// changes may affect again (a script that added an element to the body of
// npr.org matched all of its 8000 elements again, for 1s).
func (c *Context) shallowKept(keep map[*html.Node]core.Widget) map[*html.Node]bool {
if len(keep) == 0 || c.snaps == nil {
return nil
}
places, siblingPlaces := c.deepPlaces()
_, inSiblings := c.siblingCombinators()
var sibSubjects []css.KeyMask
if inSiblings {
sibSubjects = c.siblingSubjects()
}
parents := map[*html.Node]bool{}
for k := range keep {
parents[k.Parent] = true
}
shallow := map[*html.Node]bool{}
for p := range parents {
newBefore := false // an element before it that is new (inserted)
snapChildren(p, func(k *html.Node, s nodeSnap) {
o, ok := c.snaps[k]
if keep[k] != nil && ok && !placeChangedDeep(k, o, s, places, siblingPlaces) && (!inSiblings || (!newBefore && o.index == s.index) || !siblingSelects(k, sibSubjects)) {
shallow[k] = true
}
newBefore = newBefore || !ok
})
}
return shallow
}
// verticalMargins returns whether the given element has a top and a bottom
// margin that is not zero (which may collapse with others).
func (c *Context) verticalMargins(n *html.Node) (top, bottom bool) {
nonZero := func(v string) bool {
v = strings.TrimSpace(v)
if v == "" || v == "auto" {
return false
}
f, err := strconv.ParseFloat(strings.TrimRight(v, "abcdefghijklmnopqrstuvwxyz%"), 64)
return err != nil || f != 0
}
if m := strings.Fields(c.declaration(n, "margin")); len(m) > 0 {
top = nonZero(m[0])
bottom = len(m) >= 3 && nonZero(m[2]) || len(m) < 3 && nonZero(m[0])
}
if m := strings.Fields(c.declaration(n, "margin-block")); len(m) > 0 {
top = top || nonZero(m[0])
bottom = bottom || nonZero(m[len(m)-1])
}
top = top || nonZero(c.declaration(n, "margin-top")) || nonZero(c.declaration(n, "margin-block-start"))
bottom = bottom || nonZero(c.declaration(n, "margin-bottom")) || nonZero(c.declaration(n, "margin-block-end"))
return
}
// addedRuleTargets returns the elements in the given root element that the
// rules added to the style sheets since the elements were matched select
// (see [Context.addedStyle]): those whose declarations of the rules have
// custom properties are deep (the elements in them inherit them), and the
// others are shallow, as browsers find the elements that new style sheets
// may select by the keys of their selectors (or, for those without one, as
// *, by matching them alone). It returns ok false, for all of the elements
// to be matched again, for a rule with :has().
func (c *Context) addedRuleTargets(root *html.Node) (shallow, deep []*html.Node, ok bool) {
if root == nil || c.matchedRules > len(c.rules) || c.matchedPseudo > len(c.pseudoRules) {
return nil, nil, false
}
type added struct {
cs *css.CompiledSelector
vars bool
}
byKey := map[string][]added{} // by "#id", ".class", or "tag"
var keyless []added // matched against all of the elements
addRule := func(cs *css.CompiledSelector, text string, decls []*douceur.Declaration) bool {
if cs == nil || strings.Contains(text, ":has(") {
return false
}
if cs.KeyKind == 0 {
keyless = append(keyless, added{cs, hasCustomProps(decls)})
return true
}
key := cs.Key
if cs.KeyKind != 't' {
key = string(cs.KeyKind) + key
}
byKey[key] = append(byKey[key], added{cs, hasCustomProps(decls)})
return true
}
for _, r := range c.rules[c.matchedRules:] {
if !addRule(r.sel, r.text, r.decls) {
return nil, nil, false
}
}
for _, r := range c.pseudoRules[c.matchedPseudo:] {
if !addRule(r.sel, r.text, nil) {
return nil, nil, false
}
}
if len(byKey) == 0 && len(keyless) == 0 {
return nil, nil, true
}
defer c.keepAncestorMasks()()
walkElements(root, func(n *html.Node) {
match, vars := false, false
check := func(key string) {
for _, a := range byKey[key] {
if c.selMatch(a.cs, n) {
match = true
vars = vars || a.vars
}
}
}
for _, a := range keyless {
if c.selMatch(a.cs, n) {
match = true
vars = vars || a.vars
}
}
check(n.Data)
if id := GetAttr(n, "id"); id != "" {
check("#" + id)
}
for cl := range strings.FieldsSeq(GetAttr(n, "class")) {
check("." + cl)
}
switch {
case vars:
deep = append(deep, n)
case match:
shallow = append(shallow, n)
}
})
return shallow, deep, true
}
// readableRoot returns whether the given element (in the document of the
// given root) can be read again (see [Context.Reread]): its widgets are all
// in its frame, which has only those of the elements for which in returns
// true (those read again).
func (c *Context) readableRoot(r, root *html.Node, in func(n *html.Node) bool) bool {
ws := c.elementWidgets[r]
if len(ws) == 0 {
return false
}
ok := true
walkElements(r, func(n *html.Node) {
for _, w := range c.elementWidgets[n] {
if !widgetIn(w, ws[0]) {
ok = false // (as one moved elsewhere)
}
}
})
if !ok {
return false
}
for cw := range ws[0].AsWidget().AllWidgets() {
if n := ownNode(cw); n != nil && rootNode(n) == root && !in(n) {
ok = false
break
}
}
return ok
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"strconv"
"strings"
"cogentcore.org/core/colors"
"cogentcore.org/core/htmlcore/css"
"cogentcore.org/core/core"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/sides"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/text"
"cogentcore.org/core/tree"
"golang.org/x/net/html"
)
// resolver resolves the declarations of a widget that depend on each other
// and on its parent, after all of them have been applied (see
// [Context.resolveCSS]), in steps that each have a method.
type resolver struct {
c *Context
wb *core.WidgetBase
node *html.Node
st *cssState
s, ps *styles.Style
bs, pbs *blockState
// uc is the unit context for converting the lengths of the widget to dots.
uc units.Context
// parentDisplay is the display of the parent, or "" if there is none.
parentDisplay string
// pad and bw are the padding and border widths of the widget, in dots.
pad, bw sides.Floats
}
// resolveCSS resolves the declarations that depend on each other
// and on the parent, after all of them have been set.
func (c *Context) resolveCSS(wb *core.WidgetBase, node *html.Node, st *cssState, s, ps *styles.Style, bs, pbs *blockState) {
r := &resolver{c: c, wb: wb, node: node, st: st, s: s, ps: ps, bs: bs, pbs: pbs}
r.blockState()
r.layoutDisplay()
r.replacedSize()
r.flow()
r.lineHeight()
r.itemGrowth()
r.flexBasis()
r.sizes()
r.intrinsicSize()
r.flexBasisGrowth()
r.textAlign()
r.tableBorders()
r.margins()
// visibility: hidden (inherited, unless visible) is not rendered, and
// gets no events (as the items of the closed menus of Wikipedia, over
// the page, which got the clicks there)
switch st.visibility {
case "hidden", "collapse":
bs.hidden = true
case "visible":
bs.hidden = false
default:
bs.hidden = pbs != nil && pbs.hidden
}
if bs.hidden {
s.Opacity = 0
setHiddenAbilities(s)
}
if st.clippedOut { // nothing of it is shown, nor gets events
s.Opacity = 0
s.Abilities = 0
}
if st.zeroScale { // a transform scales it to nothing, so it is not shown
s.Opacity = 0
}
if st.hideText { // the text is not shown, and its box is (with its background)
s.Color = colors.Uniform(colors.Transparent)
}
}
// intrinsicSize sets the minimum size of a box with size containment in a
// dimension to its contain-intrinsic size there, as the size of its
// content, which is otherwise empty (as the rows of the file trees of
// GitHub pull requests, of contain: strict and contain-intrinsic-height:
// auto 32px, which were of no height, over each other).
func (r *resolver) intrinsicSize() {
st, s := r.st, r.s
pad := css.SideDots(&s.Padding, r.dots)
border := css.SideDots(&s.Border.Width, r.dots)
set := func(v *units.Value, min *units.Value, extra float32) {
if v == nil {
return
}
d := r.dots(v)
if s.BoxSizing == styles.BoxBorderBox {
d += extra
}
if d > r.dots(min) {
*min = units.Dot(d)
}
}
if s.Contain == styles.ContainSize || s.Contain == styles.ContainInlineSize {
set(st.intrinsicWidth, &s.Min.X, pad.Left+pad.Right+border.Left+border.Right)
}
if s.Contain == styles.ContainSize {
set(st.intrinsicHeight, &s.Min.Y, pad.Top+pad.Bottom+border.Top+border.Bottom)
}
}
// dots returns the given length in dots, or 0 if it is nil.
func (r *resolver) dots(v *units.Value) float32 {
if v == nil {
return 0
}
return r.uc.ToDots(v.Value, v.Unit)
}
// blockState copies the state that the children need into the block state,
// and applies the legacy center and the background.
func (r *resolver) blockState() {
st, s, bs, pbs := r.st, r.s, r.bs, r.pbs
bs.display = st.display
bs.alignItems = st.alignItems
bs.borderCollapse = st.borderCollapse
bs.legacyCenter = st.legacyCenter
if st.legacyCenter {
s.Align.Items = styles.Center
s.Align.Content = styles.Center
}
if pbs != nil && pbs.legacyCenter && (st.display == "table" || st.display == "inline-table") {
s.Text.Align = text.Start // tables do not inherit the legacy center
}
if st.hasBg {
s.Background = st.background
if st.bgCurrentColor { // the color of the element, as it is styled
s.Background = s.Color
}
}
r.c.applyMask(st, s)
r.c.applyBackgroundImage(st, s)
}
// layoutDisplay sets the core layout for the display of the element.
func (r *resolver) layoutDisplay() {
node, st, s := r.node, r.st, r.s
isTable := node != nil && node.Data == "table" // laid out as a grid of its cells
switch st.display {
case "block", "list-item", "table-cell", "flow-root", "inline-block", "table-caption":
s.Display = styles.Flex
s.Direction = styles.Column
// flex-wrap (and flex-flow) only apply to flex containers (as the
// body of the postings of craigslist.org, a block with a flex-flow
// of column wrap for narrow screens, whose floats were not laid out)
s.Wrap = false
case "table", "inline-table", "table-row-group", "table-header-group", "table-footer-group":
if isTable && !strings.EqualFold(strings.TrimSpace(r.c.declaration(node, "table-layout")), "fixed") &&
st.width != nil && st.width.Unit != units.UnitPw {
// the width of a table is at least that of its cells (as the
// infoboxes of Wikipedia with images wider than their width)
s.ContentMinWidth = true
}
if !isTable && (node == nil || !strings.HasPrefix(node.Data, "t")) {
// other elements displayed as tables are approximated by their
// rows (or caption and content) in a column
s.Display = styles.Flex
s.Direction = styles.Column
}
case "flex", "inline-flex":
s.Display = styles.Flex
case "grid", "inline-grid":
s.Display = styles.Grid
if node != nil && s.Columns <= 1 && strings.Contains(r.c.declaration(node, "grid-auto-flow"), "column") &&
r.c.declaration(node, "grid-template-rows") == "" {
// the items are in a row of columns (one row without row
// tracks, as for a marquee)
n := 0
r.wb.ForWidgetChildren(func(i int, cw core.Widget, cwb *core.WidgetBase) bool {
if p := cwb.Styles.Position; p != styles.PositionAbsolute && p != styles.PositionFixed {
n++
}
return tree.Continue
})
s.Columns = max(n, 1)
}
if s.Columns == 0 { // one column without column tracks, as in CSS
s.Columns = 1
}
case "none":
s.Display = styles.DisplayNone
case anonymousInline:
s.Display = styles.Flex
s.Direction = styles.Row
s.Wrap = true
s.Align.Items = styles.Baseline // texts, and the end for images
// as wide as its content on one line, and wraps in less width
s.Shrink.X = 1
}
}
// replacedSize sets the size of an img of an svg and of an svg element, from
// the intrinsic size of the svg and the sizes of their containers.
func (r *resolver) replacedSize() {
c, wb, node, st, s := r.c, r.wb, r.node, r.st, r.s
if size, ok := wb.Property("svg-size").(math32.Vector2); ok {
// an img of an svg has the size of the svg, or that of its aspect,
// within percentage max sizes of a parent with a size
cb := node // the containing block: the nearest block it is in
for cb != nil && cb.Parent != nil && cb.Parent.Type == html.ElementNode {
cb = cb.Parent
if d := c.displayOf(cb); d != "" && d != "inline" && d != "contents" {
break
}
}
if cb != nil && cb != node && cb.Type == html.ElementNode {
scale := float32(1)
for i, mx := range []*units.Value{st.maxWidth, st.maxHeight} {
if mx == nil || (mx.Unit != units.UnitPw && mx.Unit != units.UnitPh) {
continue
}
prop := "width"
if i == 1 {
prop = "height"
}
if px, ok := st.env.LengthPx(c.declaration(cb, prop)); ok && px > 0 {
scale = min(scale, px*mx.Value/100/size.Dim(math32.Dims(i)))
}
}
size = size.MulScalar(scale)
}
if st.width == nil && st.height == nil && node != nil {
// an absolute max-width or max-height scales it down to it,
// keeping its aspect, as its width and height are auto
for i, prop := range []string{"max-width", "max-height"} {
d := math32.Dims(i)
if px, ok := st.env.LengthPx(c.declaration(node, prop)); ok && px > 0 && px < size.Dim(d) {
size = size.MulScalar(px / size.Dim(d))
}
}
}
switch {
case st.width != nil && st.height != nil && st.height.Unit != units.UnitPh:
mh := *st.height
s.Max.Y = mh // as an image is not higher than its height
case st.width == nil && st.height == nil:
s.Min.Set(units.Dp(size.X), units.Dp(size.Y))
s.Max = s.Min
// the other dimension is of the aspect of the svg, in the same unit
case st.height == nil && st.width.Unit != units.UnitPw:
s.Min.Y = units.Value{Value: st.width.Value * size.Y / size.X, Unit: st.width.Unit}
s.Max.Y = s.Min.Y
case st.width == nil && st.height.Unit != units.UnitPh && st.height.Unit != units.UnitPw:
s.Min.X = units.Value{Value: st.height.Value * size.X / size.Y, Unit: st.height.Unit}
s.Max.X = s.Min.X
mh := *st.height
s.Max.Y = mh // as an image is not higher than its height
}
}
if _, isSVG := wb.This.(*core.SVG); isSVG && node != nil && node.Data == "svg" {
// an svg without a size is as wide as its container, and as
// high as the aspect ratio of its view box makes it
aspect := float32(0.5)
hasAspect := false
vb := strings.Fields(strings.ReplaceAll(GetAttr(node, "viewBox")+GetAttr(node, "viewbox"), ",", " "))
if len(vb) == 4 {
w, _ := strconv.ParseFloat(vb[2], 32)
h, _ := strconv.ParseFloat(vb[3], 32)
if w > 0 && h > 0 {
aspect, hasAspect = float32(h/w), true
}
}
switch {
case st.width == nil && st.height != nil && !css.PercentUnit(st.height.Unit) && hasAspect:
// as wide as its height makes it, in the same unit (as the
// logos of github.com, which were as wide as their container,
// and the quotation marks of height: 0.7em of the opinion
// headlines of theguardian.com, which were as wide as theirs)
s.Min.X = units.Value{Value: st.height.Value / aspect, Unit: st.height.Unit}
s.Max.X = s.Min.X
case st.width == nil:
s.Min.X, s.Max.X = units.Pw(100), units.Pw(100)
}
if st.height == nil {
if st.width != nil && st.width.Unit == units.UnitDp {
s.Min.Y = units.Dp(st.width.Value * aspect)
} else if st.width != nil && st.width.Unit == units.UnitPw {
// of its percentage of the width (as the illustration of
// width: 20% of the article footer of MDN, which was as high
// as the width of the footer)
s.Min.Y = units.Pw(st.width.Value * aspect)
} else {
s.Min.Y = units.Pw(100 * aspect)
}
s.Max.Y = s.Min.Y
}
}
}
// isVideo returns whether the widget is the box of a video element that
// is not an image (see handleVideo), which has its own size.
func (r *resolver) isVideo() bool {
_, ok := r.wb.Property("video-size").(math32.Vector2)
return ok
}
// videoSize sets the size of the box of a video element, a replaced
// element of the size of its video (see [VideoDefaultWidth] until it is
// known), or of its aspect when only its width or height is set.
func (r *resolver) videoSize() {
st, s := r.st, r.s
if r.wb.Property("audio") == true {
r.audioSize()
return
}
size := r.wb.Property("video-size").(math32.Vector2)
if size.X <= 0 || size.Y <= 0 {
size = math32.Vec2(VideoDefaultWidth, VideoDefaultHeight)
}
if s.AspectRatio <= 0 {
s.AspectRatio = size.X / size.Y
}
switch {
case st.width == nil && st.height == nil:
s.Min.X = units.Dp(size.X)
s.Max.X, s.Grow.X = s.Min.X, 0
case st.width == nil && st.height.Unit == units.UnitDp:
s.Min.X = units.Dp(st.height.Value * s.AspectRatio)
s.Max.X, s.Grow.X = s.Min.X, 0
}
}
// audioSize sets the size of the box of an audio element with controls
// (see handleAudio): [AudioDefaultWidth] by [AudioDefaultHeight], as in
// browsers, unless its CSS sets them, without an aspect ratio.
func (r *resolver) audioSize() {
st, s := r.st, r.s
if st.width == nil {
s.Min.X = units.Dp(AudioDefaultWidth)
s.Max.X, s.Grow.X = s.Min.X, 0
}
if st.height == nil {
s.Min.Y = units.Dp(AudioDefaultHeight)
s.Max.Y, s.Grow.Y = s.Min.Y, 0
}
}
// isIframe returns whether the element is an iframe.
// fixedHeight returns whether the box is exactly of the given height set
// in CSS, with overflow that is visible: one of a frame that does not clip
// its children (as is the default), and not of a part of a table, whose
// height is a minimum in CSS. The height is an absolute length (as px or
// em), not a percentage, a length of the viewport or a calc(), as of the
// containers of whole pages (as html and body), whose overflow is in the
// scrolling of the page, which that of a fixed box is not. Its content is
// only boxes (as the text of the instructions of reCAPTCHA, in a div), not
// inline content, whose lines can wrap differently than in browsers
// (it would overlap what is after the box when they do: the box grows).
func (r *resolver) fixedHeight(h *units.Value) bool {
if _, ok := r.wb.This.(*core.Frame); !ok || !r.s.NoClip || h.Custom != nil {
return false
}
switch h.Unit {
case units.UnitDp, units.UnitPx, units.UnitRem, units.UnitEm, units.UnitEx, units.UnitCh,
units.UnitCm, units.UnitMm, units.UnitQ, units.UnitIn, units.UnitPc, units.UnitPt:
default:
return false
}
if tag := r.wb.Property("tag"); tag == "html" || tag == "body" {
return false
}
if r.node == nil {
return false
}
for ch := r.node.FirstChild; ch != nil; ch = ch.NextSibling {
switch ch.Type {
case html.TextNode:
if strings.TrimSpace(ch.Data) != "" {
return false
}
case html.ElementNode:
if d := r.c.displayOf(ch); d != "none" && r.c.isInlineLevel(ch) {
return false
}
}
}
switch r.st.display {
case "table", "inline-table", "table-row", "table-cell", "table-row-group", "table-header-group", "table-footer-group":
return false
}
return true
}
func (r *resolver) isIframe() bool {
return r.node != nil && r.node.Data == "iframe"
}
// flow sets whether the widget is block-level, in the flow of blocks,
// and the alignment of an inline element in its line (or of the content
// of a table cell).
func (r *resolver) flow() {
wb, st, s, bs, pbs := r.wb, r.st, r.s, r.bs, r.pbs
if _, isImage := wb.This.(*core.Image); isImage && pbs != nil && pbs.display == anonymousInline {
// images are on the baseline, above the descent of the text
if st.margin[2] == nil {
m := units.Em(0.27)
st.margin[2] = &m
}
}
if pbs != nil && s.Float != styles.FloatNone {
switch pbs.display {
case "flex", "inline-flex", "grid", "inline-grid":
s.Float = styles.FloatNone // float does not apply to flex and grid items
}
}
bs.block = isBlockDisplay(st.display) || st.display == anonymousInline
if s.Position != styles.PositionStatic {
// positioned elements are painted after the others, which the
// background of the parent in their margins would cover (margins
// are transparent in CSS)
s.FillMargin = false
}
outOfFlow := s.Position == styles.PositionAbsolute || s.Position == styles.PositionFixed
if outOfFlow || s.Float != styles.FloatNone {
bs.block = false // not in the flow of blocks, and its width fits its content
}
if st.display == "table-cell" {
s.Grow.Set(1, 1)
switch st.verticalAlign {
case "top", "text-top":
s.Justify.Content = styles.Start
case "bottom", "text-bottom":
s.Justify.Content = styles.End
default:
s.Justify.Content = styles.Center // middle
}
} else if !bs.block {
// an inline element is aligned in the height of its line
switch st.verticalAlign {
case "middle":
s.Align.Self = styles.Center
case "top", "text-top":
s.Align.Self = styles.Start
case "bottom", "text-bottom":
s.Align.Self = styles.End
}
}
}
// lineHeight sets the unit context for converting the lengths of the widget
// to dots, and the line height.
func (r *resolver) lineHeight() {
st, s, ps := r.st, r.s, r.ps
uc, dots := &r.uc, r.dots
// units context for converting to dots
*uc = s.UnitContext
if ps != nil {
*uc = ps.UnitContext
}
uc.FontEm = uc.ToDots(s.Font.Size.Value, s.Font.Size.Unit) * core.AppearanceSettings.FontSize / 100
// line height
switch lh := st.lineHeight; lh {
case "":
case "normal":
s.Text.LineHeight = css.LineHeightNormal
default:
if f, err := strconv.ParseFloat(lh, 32); err == nil {
s.Text.LineHeight = float32(f)
} else if f, ok := css.UnitlessCalc(lh); ok {
// a number of calc() (as calc(1.25 / .875), the line height of
// the small text of Tailwind, which was taken to be in px: the
// text was 1.4px high, cut off by its boxes)
s.Text.LineHeight = f
} else if v, ok := st.env.Length(lh, units.UnitEm); ok {
if v.Unit == units.UnitEm {
s.Text.LineHeight = v.Value / 100 // from %
if !strings.HasSuffix(lh, "%") {
s.Text.LineHeight = v.Value
}
} else if uc.FontEm > 0 {
s.Text.LineHeight = dots(&v) / uc.FontEm
}
}
}
}
// itemGrowth sets how the widget grows and shrinks in the formatting context
// of its parent: block, flex, grid or table, or shrink-to-fit.
func (r *resolver) itemGrowth() {
c, node, wb, st, s, ps, bs, pbs := r.c, r.node, r.wb, r.st, r.s, r.ps, r.bs, r.pbs
// block-level elements fill the width of a block container,
// and flex items are stretched in the cross dimension
if ps != nil && pbs != nil {
r.parentDisplay = pbs.display
}
parentDisplay := r.parentDisplay
switch {
case parentDisplay == "flex" || parentDisplay == "inline-flex":
main := ps.Direction.Dim()
cross := main.Other()
if st.hasGrow {
s.Grow.SetDim(main, st.flexGrow)
}
// flex items shrink to fit in the main dimension (by flex-shrink,
// which is 1 by default), and are at most as wide as a column
s.Shrink.X = 1
if main == math32.X && st.hasShrink {
// a flex item that does not shrink (flex-shrink: 0) is still as
// wide as its content (on one line, for wrapped content), which
// core lays out for those that shrink, so it shrinks only a tiny bit
s.Shrink.X = max(st.flexShrink, 1e-4)
}
align := st.alignSelf
if align == "" || align == "auto" {
align = pbs.alignItems
}
if align == "" || align == "stretch" || align == "normal" {
if (cross == 0 && st.width == nil) || (cross == 1 && st.height == nil) {
s.Grow.SetDim(cross, 1)
}
}
case parentDisplay == "grid" || parentDisplay == "inline-grid":
// grid items are stretched to their cells by default
align := st.alignSelf
if align == "" || align == "auto" {
align = pbs.alignItems
}
// and to the width of their cells, unless they are justified in
// them (as the logo of Google, centered by justify-items)
justify := strings.TrimSpace(c.declaration(node, "justify-self"))
if (justify == "" || justify == "auto") && node != nil && node.Parent != nil {
justify = strings.TrimSpace(c.declaration(node.Parent, "justify-items"))
}
if st.width == nil {
switch justify {
case "", "auto", "normal", "stretch":
s.Grow.X = 1
default:
s.Justify.Self = css.AlignValue(justify)
}
}
if (align == "" || align == "stretch" || align == "normal") && st.height == nil {
s.Grow.Y = 1
}
s.Shrink.X = 1
case bs.block && st.display != "table":
s.Grow.X = 1
if w := strings.TrimSpace(r.c.declaration(r.node, "width")); ((st.width == nil && (w == "" || w == "auto")) || (st.width != nil && st.width.Unit == units.UnitPw)) && !s.MaxContentWidth &&
st.display == "flex" && s.Contain == styles.ContainNone && r.c.hasRigidItem(r.node) && r.c.inBlockFlow(r.node) {
// a flex container of an auto (or percentage) width in blocks in
// the flow, with
// an item that does not shrink, is as wide as its containing
// block, which its content that is wider overflows, as in CSS,
// and does not widen (as the header of edition.cnn.com, with
// the items of its navigation, which its script hides until
// the rest fit in it, by its width)
s.Contain = styles.ContainInlineSize
}
if st.width == nil && s.Contain == styles.ContainNone && !s.MaxContentWidth && (st.display == "block" || st.display == "flow-root") &&
r.node != nil && r.node.Data != "body" && r.node.Data != "html" && r.c.hasFixedWidthChild(r.node) && r.c.inBlockFlow(r.node) {
// a block of an auto width in blocks in the flow is as wide as
// its containing block, which a child of a fixed width that is
// wider overflows, as in CSS, and does not widen (as the blue
// instructions of the reCAPTCHA challenge, with a div of 400px
// and padding, which overflowed its frame of 400px in width)
s.Contain = styles.ContainInlineSize
}
case st.display == "table-cell":
s.Shrink.X = 1 // the columns of a table fit in its width
case st.width == nil:
// shrink-to-fit (tables, inline blocks, cells, and inline elements):
// as wide as the content, up to the available width
s.Shrink.X = 1
}
if _, isText := wb.This.(*core.Text); isText {
s.Shrink.X = 1 // wraps in the available width
}
if s.IsFlexWrap() && s.Direction == styles.Row && s.Shrink.X == 0 {
// a row that wraps is as wide as its content on one line, and wraps
// in less width, as in CSS, wherever it is (as the social icons in
// the footer of github.com, in a block in a flex item, which were
// in a column at its min-content width)
s.Shrink.X = 1
}
}
// flexBasis sets the width of a flex item in a row from its flex-basis,
// which overrides its width, as in CSS. A basis of 0 (as of flex: 1) is
// none: when all of the items of the row have one, they are as wide as
// their share of the grow of the row, of its width less its gaps (as the
// columns of edition.cnn.com, of flex: 3 1 0, 4 1 0 and 3 1 0, with a
// width of 100%, which put each in a row of its own).
func (r *resolver) flexBasis() {
c, node, st, ps, pbs := r.c, r.node, r.st, r.ps, r.pbs
if ps == nil || pbs == nil || (pbs.display != "flex" && pbs.display != "inline-flex") || ps.Direction != styles.Row {
return
}
switch st.flexBasis {
case "", "auto", "content":
return
}
if !css.ZeroLength(st.flexBasis) {
if st.hasGrow && st.flexGrow > 0 && (!st.hasShrink || st.flexShrink > 0) {
// an item that grows and shrinks from its basis is sized by
// its content and grow in core, which can break a row that
// wraps into lines by the width of its content (as the events
// of the current events portal of Wikipedia, of flex: 100 1
// 200px, which were 200px wide with the basis as a width)
// (its basis is where it starts from in a row that wraps)
st.width = nil
if l, ok := st.env.Length(st.flexBasis, units.UnitPw); ok {
r.s.FlexBasis = l
}
return
}
if l, ok := st.env.Length(st.flexBasis, units.UnitPw); ok {
st.width = &l
}
return
}
st.width = nil
if node == nil || node.Parent == nil || st.flexGrow <= 0 {
return
}
if ps.IsFlexWrap() && st.minWidth != nil && r.s.Contain == styles.ContainNone {
// an item of a basis of 0 with a min-width (not auto) in a row
// that wraps is in a line by its min-width, not its content, which
// it grows from to fill the line, as in CSS (as the content of the
// page of a repository of GitHub, of flex: 1 1 0 and min-width:
// 1px, beside which its sidebar did not fit)
r.s.Contain = styles.ContainInlineSize
}
sum, n := float32(0), 0
for sib := node.Parent.FirstChild; sib != nil; sib = sib.NextSibling {
if sib.Type != html.ElementNode || !c.inFlexFlow(sib) {
continue
}
grow, basis := c.flexOf(sib)
if !css.ZeroLength(basis) || grow <= 0 {
return
}
sum += grow
n++
}
if n < 2 {
return
}
// (percentages of the width of a row in core are of it less its gaps;
// a custom length, not a percentage width, which a row that wraps
// would need room for in a line)
l := css.CustomLength("calc", []css.Linear{{Pct: float64(100 * st.flexGrow / sum)}}, units.UnitPw)
st.width = &l
}
// flexBasisGrowth restores the grow of a flex item with a flex-basis after
// [resolver.sizes], which does not grow elements with a width: the basis
// is where it starts from.
func (r *resolver) flexBasisGrowth() {
st, s, ps, pbs := r.st, r.s, r.ps, r.pbs
if ps == nil || pbs == nil || (pbs.display != "flex" && pbs.display != "inline-flex") || ps.Direction != styles.Row {
return
}
switch st.flexBasis {
case "", "auto", "content":
return
}
if st.width == nil {
return
}
if !css.ZeroLength(st.flexBasis) {
if st.hasGrow && st.flexGrow > 0 {
s.Grow.X = st.flexGrow
return
}
if b := strings.TrimSpace(st.flexBasis); strings.HasSuffix(b, "%") && ps.IsFlexWrap() {
// in a row that wraps, an item that does not grow needs its
// basis in its line (its hypothetical main size in CSS), not
// its content (as the columns of Bootstrap, of flex: 0 0 75%,
// whose cards on one line made it wrap below the column of 25%
// beside it, on stella.nl)
if p, err := strconv.ParseFloat(strings.TrimSuffix(b, "%"), 32); err == nil {
s.FlexBasis = units.Pw(float32(p))
}
return
}
if strings.HasSuffix(strings.TrimSpace(st.flexBasis), "%") && !ps.IsFlexWrap() && s.Max.X.Unit == units.UnitPw {
// an item that does not grow is as wide as its percentage
// basis (of the row less its gaps in core), not only up to
// it, and starts from it, so that the items that grow have
// only the rest of the row (as the images of the cards of
// theguardian.com, of flex-basis: 50%, beside text of
// flex-grow: 1 that took their width)
s.Min.X, s.FlexBasis = s.Max.X, s.Max.X
s.Grow.X = 0
}
return
}
if !st.hasGrow || st.flexGrow <= 0 {
return
}
// the share of the row, as a percentage width: it grows up to it,
// from no minimum, so that the items are in one row while the
// percentage is resolved
s.Min.X = units.Value{}
s.Grow.X = 1
s.Shrink.X = 1
}
// flexOf returns the flex grow and basis of the given element, from its
// flex, flex-grow and flex-basis declarations, as for its siblings.
func (c *Context) flexOf(n *html.Node) (grow float32, basis string) {
for _, d := range c.declarations(n) {
if d.invalid {
continue
}
v := strings.ToLower(strings.TrimSpace(d.Value))
switch d.Property {
case "flex", "-webkit-flex":
if g, _, b, ok := css.ParseFlex(v); ok {
grow, basis = g, b
}
case "flex-grow", "-webkit-flex-grow":
if f, err := strconv.ParseFloat(v, 32); err == nil {
grow = float32(f)
}
case "flex-basis", "-webkit-flex-basis":
basis = v
}
}
return
}
// inBlockFlow returns whether the given element is in blocks in the flow
// up to the body of a page of a known width ([Context.MediaWidth]) or an
// element with a width: each of its ancestors is a
// block (not a float, an absolute or fixed element, or a flex or grid
// item, which can be as wide as their content), so its width does not
// depend on its content, as in CSS.
func (c *Context) inBlockFlow(n *html.Node) bool {
for p := n.Parent; p != nil && p.Type == html.ElementNode; p = p.Parent {
if p.Data == "body" || p.Data == "html" {
// the body is as wide as the viewport of a page whose width is
// known (not as wide as its content, as in a window or a
// dialog sized to its content)
return c.MediaWidth > 0
}
switch strings.TrimSpace(c.displayOf(p)) {
case "block", "flow-root", "list-item":
default:
return false
}
switch strings.TrimSpace(c.declaration(p, "position")) {
case "absolute", "fixed":
return false
}
if f := strings.TrimSpace(c.declaration(p, "float")); f != "" && f != "none" {
return false
}
if pp := p.Parent; pp != nil && pp.Type == html.ElementNode {
switch strings.TrimSpace(c.displayOf(pp)) {
case "flex", "inline-flex", "grid", "inline-grid", "table-cell", "inline-block":
return false
}
}
if w := strings.TrimSpace(c.declaration(p, "width")); w != "" && w != "auto" && !strings.Contains(w, "content") {
return true
}
}
return false
}
// hasRigidItem returns whether the given flex container has an item that
// does not shrink (of flex: none, or a flex-shrink of 0).
func (c *Context) hasRigidItem(n *html.Node) bool {
for k := n.FirstChild; k != nil; k = k.NextSibling {
if k.Type != html.ElementNode {
continue
}
shrink := float32(1)
for _, d := range c.declarations(k) {
if d.invalid {
continue
}
v := strings.ToLower(strings.TrimSpace(d.Value))
switch d.Property {
case "flex":
if _, sh, _, ok := css.ParseFlex(v); ok {
shrink = sh
}
case "flex-shrink":
if f, err := strconv.ParseFloat(v, 32); err == nil {
shrink = float32(f)
}
}
}
if shrink == 0 {
return true
}
}
return false
}
// hasFixedWidthChild returns whether the given element has a child element
// with a fixed width, of an absolute length (as px or em), in the flow.
func (c *Context) hasFixedWidthChild(n *html.Node) bool {
for k := n.FirstChild; k != nil; k = k.NextSibling {
if k.Type != html.ElementNode {
continue
}
switch strings.TrimSpace(c.declaration(k, "position")) {
case "absolute", "fixed":
continue
}
w := strings.ToLower(strings.TrimSpace(c.declaration(k, "width")))
if strings.ContainsAny(w, "(%") {
continue
}
for _, u := range []string{"px", "rem", "em"} {
if num, ok := strings.CutSuffix(w, u); ok {
if _, err := strconv.ParseFloat(num, 32); err == nil {
return true
}
break
}
}
}
return false
}
// inFlexFlow returns whether the given element is an item in the flow of
// its flex container: it is displayed, and not absolute or fixed.
func (c *Context) inFlexFlow(n *html.Node) bool {
switch strings.TrimSpace(c.declaration(n, "display")) {
case "none", "contents":
return false
}
switch strings.TrimSpace(c.declaration(n, "position")) {
case "absolute", "fixed":
return false
}
switch n.Data {
case "script", "style", "template", "link", "meta":
return false
}
return true
}
// sizes sets the sizes (Min and Max, of the content box), with percentage
// heights only of a parent with a definite height, and the overflow.
func (r *resolver) sizes() {
c, wb, node, st, s, bs, pbs := r.c, r.wb, r.node, r.st, r.s, r.bs, r.pbs
dots := r.dots
// sizes: Min and Max are the size of the content box (or of the
// border box, for box-sizing: border-box, of which core subtracts
// the padding and border; see styles.BoxSizing)
pad := css.SideDots(&s.Padding, dots)
if bs.markers { // the markers of the items take the space of the padding
mw := dots(&markerWidth)
pl := max(pad.Left-mw, 0)
s.Padding.Left = units.Dot(pl)
pad.Left = pl
}
r.pad = pad
r.bw = css.SideDots(&s.Border.Width, dots)
if st.borderBox {
s.BoxSizing = styles.BoxBorderBox
}
if st.width != nil {
intrinsic := s.Min.X
s.Min.X, s.Max.X = *st.width, *st.width
s.Grow.X = 0
_, isImage := wb.This.(*core.Image)
isImage = isImage || r.isIframe() // (replaced elements)
if st.width.Unit == units.UnitPw && st.width.Value == 0 {
// A width of 0% is no width, not a Max of 0, which is no Max
// (as the bar of the other parties of the election results of
// nytimes.com, which took a share of the width of the bars).
s.Min.X, s.Max.X = units.Dot(0), units.Dot(0)
} else if st.width.Unit == units.UnitPw && !isImage {
// A percentage of the width of the parent fills that much
// of it, which as a minimum would make a parent that is as
// wide as its content grow without end.
s.Min.X = units.Value{}
s.Grow.X = 1
if _, isField := wb.This.(*core.TextField); isField && intrinsic.Value > 0 {
// A text field (input) is as wide as its intrinsic width
// in a parent that is as wide as its content, and can
// shrink, as in CSS (as the email field of github.com).
s.Min.X = intrinsic
s.Shrink.X = 1
}
if r.ps != nil && r.pbs != nil && r.pbs.display == "flex" && r.ps.Wrap && r.ps.Direction == styles.Row {
// In a row that wraps, an item needs its width in its
// line, as for its hypothetical main size in CSS (as the
// containers of width: 100% of edition.cnn.com, each on a
// line of its own, which were all on one line): a Min of
// 0 in percent of the width marks it for core (as no Min).
s.Min.X = units.Pw(0)
}
}
if st.display == "table-cell" && st.width.Unit != units.UnitPw {
// the width of a cell is the least width of its column, which
// it fills (as the cells of the names under the photos of the
// infoboxes of Wikipedia, narrower than the photos), without
// taking the extra width of the table, which the columns of
// automatic width get (as for the logo of Hacker News)
s.Max.X = units.Value{}
s.Grow.X = 0.001
}
nowrap := s.Text.WhiteSpace == text.WrapNever || s.Text.WhiteSpace == text.WhiteSpacePre
if st.display == "table-cell" && st.width.Unit == units.UnitPw && nowrap {
// The column of a table cell is at least as wide as its content,
// as in CSS, which for text that does not wrap is its whole
// width: then a percentage width is not a limit (as for a cell
// with a width of 1% to be as narrow as its text). Text that
// wraps fits the percentage, which is kept (as for halves).
s.Max.X = units.Value{}
}
}
// A percentage height is only of a parent with a definite height,
// and the viewport is definite. Content that overflows a height is
// shown in CSS, but it is clipped in core, so the height is only a
// minimum unless the overflow is clipped anyway.
parentDefinite := pbs == nil || pbs.definiteHeight
if pbs != nil && pbs.display == anonymousInline {
// An element in a run of inline content (as an image), in the
// anonymous frame of the run, whose height is that of its line:
// the percentages of its heights and of its top and bottom are of
// its containing block, the block that the run is in, as in CSS
// (as the tiles of the challenges of reCAPTCHA, images of height:
// 300% and top: -100% in wrappers of 126px, of which only the
// first row showed).
if cbh, ok := r.containingBlockHeight(); ok {
for _, h := range []**units.Value{&st.height, &st.minHeight, &st.maxHeight} {
if *h != nil && (*h).Unit == units.UnitPh {
v := units.Dp((*h).Value * cbh / 100)
*h = &v
}
}
for _, side := range []*units.Value{&s.Inset.Top, &s.Inset.Bottom} {
if side.Unit == units.UnitPh {
*side = units.Dp(side.Value * cbh / 100)
}
}
}
}
if pbs == nil && node != nil && node.Parent != nil && node.Parent.Data == "html" {
// The html element (which has no widget) has a definite height,
// taken to be that of the viewport, only when it has a height.
parentDefinite = c.declaration(node.Parent, "height") != ""
}
for _, h := range []**units.Value{&st.height, &st.minHeight, &st.maxHeight} {
if *h == nil || (*h).Unit != units.UnitPh {
continue
}
switch {
case !parentDefinite:
*h = nil // auto
case pbs == nil:
// a percentage of the viewport (the containing block of the
// top element), not of the scene, which is as high as the page
c.viewportHeightUsed.Store(true)
v := (*h).Value
if c.MediaHeight > 0 {
*h = new(units.Value)
**h = units.Dp(v * c.MediaHeight / 100)
} else {
*h = new(units.Value)
**h = units.Vh(v)
}
}
}
if r.isIframe() {
// an iframe is a replaced element, of 300 by 150 without a width
// or height (as of a percentage of a parent with an auto height),
// and exactly of its height, as its document scrolls in it
if st.width == nil {
s.Min.X = units.Dp(IframeDefaultWidth)
s.Max.X, s.Grow.X = s.Min.X, 0
}
if st.height == nil {
h := units.Dp(IframeDefaultHeight)
st.height = &h
}
defer func() { s.Max.Y = s.Min.Y }()
}
if r.isVideo() {
r.videoSize()
}
if (st.overflowHidden[0] || s.Overflow.X == styles.OverflowVisible) &&
(st.overflowHidden[1] || s.Overflow.Y == styles.OverflowVisible) && (st.overflowHidden[0] || st.overflowHidden[1]) {
s.ScrollbarWidth.Zero() // hidden, not scrolled
} else if s.ScrollbarWidth.Value == 0 && (s.Overflow.X >= styles.OverflowAuto || s.Overflow.Y >= styles.OverflowAuto) {
// a box that scrolls has scrollbars, whose width is inherited in
// core but not in CSS: not the zero width of a box that it is in
// whose overflow is hidden (as the body of pexels.com while its
// dialog is open, whose overflow: auto overlay did not scroll)
s.ScrollbarWidth = styles.DefaultScrollbarWidth
s.ScrollbarWidth.ToDots(&s.UnitContext)
}
if s.Overflow.X >= styles.OverflowAuto && s.Shrink.X == 0 {
// a box that scrolls is as wide as its content, narrowed to fit
// (to nothing), as in CSS (as the scrolling list of the chapters of
// the video of github.com)
s.Shrink.X = 1
}
// Overflow only scrolls (or clips) a box whose height is limited,
// and that of the body is that of the viewport, which scrolls anyway.
// A box that is out of flow with its top and bottom set is as high as
// they make it (in its containing block), so it can scroll too.
insetHeight := (s.Position == styles.PositionAbsolute || s.Position == styles.PositionFixed) &&
s.InsetSet.Top && s.InsetSet.Bottom
// (an aspect ratio makes the height follow the width, which is
// definite, and the top and bottom of a box out of flow make its height
// that of its containing block between them, as in CSS: the player of
// youtube.com, of height: 100% in its container of inset 0, was of no
// height)
// The height of a flex item is definite when that of its flex container
// is, and it is stretched across a row or grows in a column, so that it
// can scroll too (as the navigation and the page of the sites made with
// Cogent Core content, in a row that grows in a column of the height of
// the viewport, which did not scroll).
flexHeight := r.flexDefiniteHeight()
bs.definiteHeight = st.height != nil || s.AspectRatio > 0 || insetHeight || flexHeight
// (a max-height of a length, or inherited, not a percentage, which is
// of no height in an element whose height is not definite)
bs.maxHeight = (st.maxHeight != nil && st.maxHeight.Unit != units.UnitPh) ||
(st.height == nil && s.Max.Y.Value > 0 && s.Max.Y.Unit != units.UnitPh)
if st.height == nil && st.maxHeight == nil && s.Overflow.Y != styles.OverflowVisible && r.flexMaxColumn() && r.ps.Max.Y.Value > 0 && r.ps.Max.Y.Unit != units.UnitPh {
// it is as high as its content up to the max-height of its column,
// and it shrinks in it to fit the others (see flexMaxColumn)
s.Max.Y = r.ps.Max.Y
}
if tag := wb.Property("tag"); tag == "body" || tag == "html" ||
(st.height == nil && st.maxHeight == nil && !insetHeight && !flexHeight && !r.flexMaxColumn() && s.Overflow.Y != styles.OverflowVisible) {
s.Overflow.Y = styles.OverflowVisible
}
if s.Position == styles.PositionAbsolute || s.Position == styles.PositionFixed {
// an element with both insets in a dimension, auto margins in it,
// and a definite size in it is centered between the insets, not
// stretched to them (as the modal dialogs of pkg.go.dev, centered
// in the window)
s.InsetCenter[0] = s.InsetSet.Left && s.InsetSet.Right && st.marginAuto[1] && st.marginAuto[3] && st.width != nil
s.InsetCenter[1] = s.InsetSet.Top && s.InsetSet.Bottom && st.marginAuto[0] && st.marginAuto[2] && (st.height != nil || st.heightFit)
}
if st.height != nil {
mn, mx := *st.height, *st.height
s.Min.Y = mn
if s.Overflow.Y != styles.OverflowVisible {
s.Max.Y = mx
} else if r.fixedHeight(st.height) && st.minHeight == nil && st.maxHeight == nil {
// a box of a fixed height is of that height, and its content
// overflows it visibly (as the instructions of the reCAPTCHA
// challenge, whose text is higher than them): its overflow is
// hidden in the layout, but not clipped (NoClip)
if r.dots(&mx) <= 0 {
// a height of 0 (as the edition bar of nytimes.com, whose
// content hangs above it, aligned at its end), which is not
// a Max in core (that is none)
mx = units.Dot(0.001)
}
s.Max.Y = mx
s.Overflow.Y = styles.OverflowHidden
}
s.Grow.Y = 0
}
if st.minWidth != nil {
_, isField := r.wb.This.(*core.TextField)
// a fixed width larger than the min-width is kept, as min-width
// only raises the width in CSS
keepWidth := st.width != nil && st.width.Unit != units.UnitPw && r.dots(st.width) >= r.dots(st.minWidth)
if !(isField && st.minWidth.Value == 0 && s.Shrink.X > 0) && !keepWidth {
// (a text field that can shrink keeps its intrinsic width)
s.Min.X = *st.minWidth
}
}
defer func() { // min-width wins over width and max-width, as in CSS
if st.minWidth != nil && st.minWidth.Unit != units.UnitPw && s.Max.X.Value > 0 && s.Max.X.Unit != units.UnitPw &&
r.dots(st.minWidth) > r.dots(&s.Max.X) {
s.Max.X = *st.minWidth
}
}()
if st.minHeight != nil {
keepHeight := st.height != nil && st.height.Unit != units.UnitPh && r.dots(st.height) >= r.dots(st.minHeight)
if !keepHeight {
s.Min.Y = *st.minHeight
}
}
_, isImage := wb.This.(*core.Image)
_, isSVG := wb.This.(*core.SVG)
switch {
case st.maxWidth == nil:
case (isImage || isSVG) && st.width != nil && st.maxWidth.Unit == units.UnitPw:
// an image is the smaller of its width and its percentage
// max-width (as the responsive images of max-width: 100%, as the
// photos of the picks of nytimes.com/wirecutter, of width="399"
// in boxes of 200px, which they overflowed): the smaller of the two
// (as the ducky of github.com, of width: 2rem and max-width: 100%,
// which was as wide as its container)
s.Max.X = *st.maxWidth
if st.width.Unit == units.UnitDp {
s.Max.X = css.CustomLength("min", []css.Linear{{Px: float64(st.width.Value)}, {Pct: float64(st.maxWidth.Value)}}, units.UnitPw)
}
case st.width != nil && st.width.Unit != units.UnitPw && st.maxWidth.Unit == units.UnitPw:
// a fixed width with a percentage max-width (as max-width: 100%) is
// the width (the smaller of the two in CSS, as the width is, but
// for a narrower parent, in which it overflows), as for the
// percentage bars of Wikipedia (which filled the max-width)
case st.width != nil && st.width.Unit != units.UnitPw:
if r.dots(st.maxWidth) < r.dots(st.width) { // the smaller of the two
s.Min.X, s.Max.X = *st.maxWidth, *st.maxWidth
}
default:
s.Max.X = *st.maxWidth
}
if st.maxHeight != nil {
s.Max.Y = *st.maxHeight
}
}
// containingBlockHeight returns the height in px of the containing block
// of the element of an anonymous frame of a run of inline content (the
// block that the run is in), from its height in CSS, if that is an
// absolute length.
func (r *resolver) containingBlockHeight() (float32, bool) {
pw, _ := r.wb.Parent.(core.Widget)
for pw != nil {
pbs := r.c.blocks[pw]
if pbs == nil || pbs.display != anonymousInline {
break
}
pw, _ = pw.AsWidget().Parent.(core.Widget)
}
if pw == nil {
return 0, false
}
n, _ := pw.AsWidget().Property("node").(*html.Node)
if n == nil {
return 0, false
}
return r.st.env.LengthPx(strings.TrimSpace(r.c.declaration(n, "height")))
}
// textAlign aligns text and inline rows within their block for text-align.
func (r *resolver) textAlign() {
wb, st, s, bs := r.wb, r.st, r.s, r.bs
// Text is only as wide as its lines, so it is aligned
// within its block for text-align, as are inline rows.
if _, isText := wb.This.(*core.Text); isText && bs.block {
switch s.Text.Align {
case text.Center:
s.Align.Self = styles.Center
case text.End:
s.Align.Self = styles.End
}
}
if st.display == anonymousInline {
switch s.Text.Align {
case text.Center:
s.Justify.Content = styles.Center
case text.End:
s.Justify.Content = styles.End
}
}
}
// tableBorders approximates border-collapse and border-spacing of tables.
func (r *resolver) tableBorders() {
st, s, ps, pbs := r.st, r.s, r.ps, r.pbs
// border-collapse is approximated by the cells drawing their right
// and bottom borders, and the table the top and left ones
if st.borderCollapse {
s.Gap.Zero()
} else if st.display == "table" && s.Padding.Top.Value == 0 && s.Padding.Left.Value == 0 {
// border-spacing is also between the cells and the table
s.Padding.Set(s.Gap.Y, s.Gap.X)
}
if pbs != nil && pbs.borderCollapse && st.display == "table-cell" {
if ps.Border.Width.Top.Value == 0 && ps.Border.Width.Left.Value == 0 {
ps.Border.Width.Top = s.Border.Width.Top
ps.Border.Width.Left = s.Border.Width.Left
ps.Border.Color.Top = s.Border.Color.Top
ps.Border.Color.Left = s.Border.Color.Left
ps.Border.Style.Top = s.Border.Style.Top
ps.Border.Style.Left = s.Border.Style.Left
ps.Border.Width.ToDots(&ps.UnitContext)
}
s.Border.Width.Top.Value = 0
s.Border.Width.Left.Value = 0
}
}
// margins sets the margins: auto margins align a block, and the vertical
// margins of blocks collapse.
func (r *resolver) margins() {
c, wb, st, s, ps, bs, pbs := r.c, r.wb, r.st, r.s, r.ps, r.bs, r.pbs
dots, parentDisplay, pad, bw := r.dots, r.parentDisplay, r.pad, r.bw
// margins: auto horizontal margins align a block that does not fill
// the width, which it then does not grow to fill
if st.marginAuto[1] || st.marginAuto[3] {
if st.marginAuto[1] && st.marginAuto[3] {
s.Align.Self = styles.Center
} else if st.marginAuto[3] {
s.Align.Self = styles.End
}
// A block of a fixed width grows to its width (its Max), so that
// it is aligned within the width of its parent.
if st.width != nil && st.width.Unit == units.UnitDp && bs.block && parentDisplay != "flex" && parentDisplay != "inline-flex" {
s.Grow.X = 1
}
}
// align-items of a flex container on one line aligns the line
if (st.display == "flex" || st.display == "inline-flex") && !s.Wrap {
switch s.Align.Items {
case styles.Center, styles.End:
s.Align.Content = s.Align.Items
}
}
if st.margin[1] != nil {
s.Margin.Right = *st.margin[1]
}
if st.margin[3] != nil {
s.Margin.Left = *st.margin[3]
}
if tag := wb.Property("tag"); tag == "body" && st.width == nil {
// it fills the width of its parent (the viewport, as in a browser,
// or a panel of a page, as in content), and no more
s.Grow.X, s.Shrink.X = 1, 1
}
top, bottom := dots(st.margin[0]), dots(st.margin[2])
bs.marginTop, bs.marginBottom = top, bottom
c.collapseMargins(wb, s, ps, bs, pbs, pad, bw, &top, &bottom)
s.Margin.Top = units.Dot(top)
s.Margin.Bottom = units.Dot(bottom)
}
// flexDefiniteHeight returns whether the element is a flex item whose
// height is definite, as in CSS: its flex container has a definite height,
// and it is stretched across the row of a row container, or it grows in a
// column container.
func (r *resolver) flexDefiniteHeight() bool {
st, ps, pbs := r.st, r.ps, r.pbs
if ps == nil || pbs == nil || !pbs.definiteHeight || (pbs.display != "flex" && pbs.display != "inline-flex") {
return false
}
switch ps.Direction {
case styles.Row:
align := st.alignSelf
if align == "" || align == "auto" {
align = pbs.alignItems
}
return align == "" || align == "normal" || align == "stretch"
case styles.Column:
return st.flexGrow > 0
}
return false
}
// flexMaxColumn returns whether the element is a flex item of a column with
// a max-height, which it shrinks in to fit (see core.Frame.shrinkColumnHeights),
// so that its overflow scrolls (or clips) it, as in CSS (as the content of
// the cookie dialog of reddit.com, above its buttons).
func (r *resolver) flexMaxColumn() bool {
ps, pbs := r.ps, r.pbs
return ps != nil && pbs != nil && pbs.maxHeight && (pbs.display == "flex" || pbs.display == "inline-flex") && ps.Direction == styles.Column
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"fmt"
"slices"
"strings"
"cogentcore.org/core/core"
"cogentcore.org/core/htmlcore/css"
douceur "github.com/aymerick/douceur/css"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
// styleRule is a style rule that has been added to a context, with one
// selector, by which the declarations of elements are found again when
// they change (see [Context.Restyle]).
type styleRule struct {
root *html.Node
// scope is the host of the shadow root of its style sheet, if it is
// in a shadow tree, and scopeKind is the elements that it selects there
// (see [Context.inScope]).
scope *html.Node
scopeKind css.ScopeKind
sel *css.CompiledSelector
text string // of its selector
decls []*douceur.Declaration
origin css.Origin
spec int
// container is the condition of the @container rule that it is in.
container *css.ContainerCond
// cssBase is the URL that the URLs of the rule are relative to.
cssBase string
// relational is whether its selector has :has().
relational bool
// subjectHas is whether its :has() selectors are all in the compound
// of the elements that it selects (as .a:has(.b), not .a:has(.b) .c),
// so that it only selects other elements when the descendants or later
// siblings of an element change (see [Context.relationalChanges]).
subjectHas bool
// hasCompound is, for a rule whose :has() selectors are all in one
// compound that is not its subject (as .a:has(.b) .c), that compound
// without them (.a), and hasSiblings whether a sibling combinator
// follows it: the rule only selects other elements in the elements
// that match it whose descendants (or later siblings) change, and their
// later siblings if hasSiblings (see [Context.relationalChanges]).
hasCompound *css.CompiledSelector
hasSiblings bool
}
// pseudoRule is a style rule of a ::before or ::after pseudo-element that
// has been added to a context (see [styleRule]).
type pseudoRule struct {
root *html.Node
sel *css.CompiledSelector
text string // of its selector
kind string
decls []*douceur.Declaration
origin css.Origin
spec int
}
// ruleIndex has the indexes of the style rules of a context by the key of
// their selectors (see [css.SelectorKey]), so that only the rules that may
// select an element are matched against it, and those without a key.
type ruleIndex struct {
byID, byClass, byTag map[string][]int
other []int
// relational has the rules with :has() selectors, except those whose
// :has() selectors are in their subject compound, in subjectHas, and
// those whose :has() selectors are in one other compound, in hasAbove.
relational, subjectHas, hasAbove []int
// n is the number of rules indexed.
n int
}
// recordRule records the given style rule (of one selector), which is
// being added, as the rule of the declarations that it adds (see
// [Context.Restyle]).
func (c *Context) recordRule(root *html.Node, sel string, cs *css.CompiledSelector, decls []*douceur.Declaration, origin css.Origin, spec int) {
has := strings.Contains(sel, ":has(")
subject := has && strings.Index(sel, ":has(") >= subjectStart(sel)
r := &styleRule{root: root, scope: c.curScope, scopeKind: c.curScopeKind, sel: cs, text: sel, decls: decls, origin: origin, spec: spec, container: c.curContainer, cssBase: c.cssBase, relational: has, subjectHas: subject}
if has && !subject {
r.hasCompound, r.hasSiblings = hasCompound(sel)
}
c.rules = append(c.rules, r)
c.curRule = len(c.rules)
c.relational = c.relational || has
}
// index returns the index of the rules of the context, updated for the
// rules added since it was made.
func (c *Context) index() *ruleIndex {
ix := c.ruleIndex
if ix == nil {
ix = &ruleIndex{byID: map[string][]int{}, byClass: map[string][]int{}, byTag: map[string][]int{}}
c.ruleIndex = ix
}
for ; ix.n < len(c.rules); ix.n++ {
i, r := ix.n, c.rules[ix.n]
switch r.sel.KeyKind {
case '#':
ix.byID[r.sel.Key] = append(ix.byID[r.sel.Key], i)
case '.':
ix.byClass[r.sel.Key] = append(ix.byClass[r.sel.Key], i)
case 't':
ix.byTag[r.sel.Key] = append(ix.byTag[r.sel.Key], i)
default:
ix.other = append(ix.other, i)
}
switch {
case r.subjectHas:
ix.subjectHas = append(ix.subjectHas, i)
case r.hasCompound != nil:
ix.hasAbove = append(ix.hasAbove, i)
case r.relational:
ix.relational = append(ix.relational, i)
}
}
return ix
}
// candidates returns the indexes of the rules that may select the given
// element, in order.
func (ix *ruleIndex) candidates(n *html.Node) []int {
cands := slices.Clone(ix.other)
cands = append(cands, ix.byTag[strings.ToLower(n.Data)]...)
for _, a := range n.Attr {
if a.Namespace != "" {
continue
}
switch a.Key {
case "id":
cands = append(cands, ix.byID[a.Val]...)
case "class":
for cl := range strings.FieldsSeq(a.Val) {
cands = append(cands, ix.byClass[cl]...)
}
}
}
slices.Sort(cands)
return slices.Compact(cands)
}
// matchDecls returns the declarations of the style rules that select the
// given element (without those of its attributes, which
// [Context.declarations] adds), as they are added when a page is read.
func (c *Context) matchDecls(n *html.Node) []*cssDecl {
var ds []*cssDecl
base, container := c.cssBase, c.curContainer
defer func() { c.cssBase, c.curContainer = base, container }()
for _, i := range c.index().candidates(n) {
r := c.rules[i]
if !contains(r.root, n) || !c.inScope(n, r.scope, r.scopeKind) || !c.selMatch(r.sel, n) {
continue
}
c.cssBase = r.cssBase // for its URLs
for _, d := range r.decls {
prop, value := css.PropertyName(d.Property), strings.TrimSpace(d.Value)
if !css.ValidDeclaration(prop, value) {
continue
}
c.cssOrder++
c.noteVars(value)
ds = append(ds, &cssDecl{Property: prop, Value: c.absoluteURLs(value), Important: d.Important,
origin: r.origin, specificity: r.spec, order: c.cssOrder, container: r.container, rule: i + 1})
}
}
return ds
}
// matchPseudo returns the declarations of the given pseudo-element of the
// given element, as [Context.addPseudoRule] adds them.
func (c *Context) matchPseudo(n *html.Node, kind string) []*cssDecl {
var ds []*cssDecl
for _, r := range c.pseudoRules {
if r.kind != kind || r.sel == nil || !contains(r.root, n) || !c.selMatch(r.sel, n) {
continue
}
for _, d := range r.decls {
c.cssOrder++
c.noteVars(d.Value)
ds = append(ds, &cssDecl{Property: css.PropertyName(d.Property), Value: c.absoluteURLs(strings.TrimSpace(d.Value)),
Important: d.Important, origin: r.origin, specificity: r.spec, order: c.cssOrder})
}
}
return ds
}
// contains returns whether the given node is a or is in it.
func contains(a, n *html.Node) bool {
for ; n != nil; n = n.Parent {
if n == a {
return true
}
}
return false
}
// maxRestyled is the number of elements that [Context.Restyle] matches the
// style rules against, beyond which the page is read again.
const maxRestyled = 20000
// nodeStyles is the state of the declarations of an element in a context,
// which [Context.Restyle] restores if it can not restyle the page.
type nodeStyles struct {
styles []*cssDecl
sorted, hinted, queried bool
before, after []*cssDecl
hasBefore, hasAfter bool
snap nodeSnap
hasSnap bool
}
// Restyle updates the styles of the widgets of the page that the context
// has read for the given elements, whose attributes that select them in
// style rules (as their class and style) or states (as their :hover) have
// changed, as for the changes that scripts make to the styles of a page,
// without reading it again (which makes new widgets for all of it). The
// declarations of the elements, those in them and those after them are
// found again from the style rules of the page, and the widgets of those
// whose declarations change are styled again, laid out again if they may
// have another size. It returns false, leaving the styles as they were, if
// a change can not be made so, for the page to be read again: one of a
// property that changes the widgets that elements have (as display, or
// the content of a pseudo-element) or how they are arranged (as in a grid
// or a table), or one of an element that has no widget of its own (as an
// inline element in a run of text).
func (c *Context) Restyle(changed []*html.Node) bool {
apply := c.PrepareRestyle(changed)
if apply == nil {
return false
}
apply()
return true
}
// PrepareRestyle finds the declarations of the given changed elements as
// [Context.Restyle] does, with the styles of the context locked (see
// [Context.LockStyles]), and without the lock of the widgets of the page
// (as it takes time), and returns the function that styles the widgets
// again, with the lock of the widgets held, or nil if they can not be (see
// [Context.Fallback]).
func (c *Context) PrepareRestyle(changed []*html.Node) func() {
c.styleMu.Lock()
defer c.styleMu.Unlock()
c.containersChanged() // (declarations may change)
defer c.containersChanged()
c.fallback = ""
if len(changed) == 0 {
return func() {}
}
u, ok := c.updateDecls(changed, nil, nil)
if !ok {
return nil
}
return func() { u.apply(c) }
}
// declUpdate is an update of the declarations of the elements of a page
// (see [Context.updateDecls]): the widgets to style again, whether they
// are to be laid out again, and the function that undoes it.
type declUpdate struct {
widgets []core.Widget
layout bool
undo func()
// freeChanged has the elements read again whose declarations (or
// those of their pseudo-elements) have changed.
freeChanged map[*html.Node]bool
// transitions are the transitions of the properties that changed.
transitions []css.Transition
}
// apply styles the widgets of the update again, and lays them out again
// if needed.
func (u *declUpdate) apply(c *Context) {
if c.OnTransition != nil && len(u.transitions) > 0 {
defer c.OnTransition(u.transitions)
}
for _, w := range u.widgets {
if bs := c.blocks[w]; bs != nil {
wb := w.AsWidget()
n := NodeOf(w)
bs.ops = c.compileDecls(c.declarations(n))
bs.inherit = c.inlineInheritedOps(n, wb)
}
}
for _, w := range u.widgets {
wb := w.AsWidget()
wb.StyleTree()
if u.layout {
wb.NeedsLayout()
}
wb.NeedsRender()
}
}
// updateDecls finds the declarations of the elements whose declarations
// may change again (see [Context.Restyle]): the given changed elements,
// those in them, and those after them (and those in them), and the given
// whole elements and those in them. Those for which free returns true
// (if not nil) are read again (see [Context.Reread]), so that their
// declarations may change in any way; for the others, it returns false,
// leaving the declarations as they were, if they change in a way that
// their widgets can not be styled again for, and otherwise the widgets to
// style again.
func (c *Context) updateDecls(changed, whole []*html.Node, free func(n *html.Node) bool) (*declUpdate, bool) {
isFree := func(n *html.Node) bool { return free != nil && free(n) }
var root *html.Node
if len(changed) > 0 {
root = rootNode(changed[0])
} else if len(whole) > 0 {
root = rootNode(whole[0])
} else if len(c.addedShallow) > 0 {
root = rootNode(c.addedShallow[0])
} else if len(c.addedDeep) > 0 {
root = rootNode(c.addedDeep[0])
} else {
return &declUpdate{undo: func() {}}, true
}
// the elements whose declarations may change: those changed, those
// in them, and those after them (for the combinators of siblings),
// and those in them
affected := map[*html.Node]bool{}
var order []*html.Node
var add func(n *html.Node) bool
add = func(n *html.Node) bool {
if n.Type != html.ElementNode || affected[n] {
return true
}
if len(order) >= maxRestyled {
return false
}
affected[n] = true
order = append(order, n)
if c.matchKept[n] {
// kept with its widgets (see Context.keptElements): the
// elements in it match as they did (see Context.shallowKept)
return true
}
for k := n.FirstChild; k != nil; k = k.NextSibling {
if !add(k) {
return false
}
}
return true
}
tooMany := fmt.Sprintf("more than %d elements to style again", maxRestyled)
for _, n := range c.addedShallow {
if !affected[n] {
affected[n] = true
order = append(order, n)
}
}
for _, n := range c.addedDeep {
if !add(n) {
return nil, c.noChange(tooMany)
}
}
for _, n := range whole {
if !add(n) {
return nil, c.noChange(tooMany)
}
}
for _, n := range changed {
if n == nil || n.Type != html.ElementNode || rootNode(n) != root {
return nil, c.noChange("a change that is not of an element of the page")
}
if (n.Namespace != "" || inForeign(n)) && !isFree(n) {
// svg and math, which are read differently
return nil, c.noChange("a change in svg or math: " + describeNode(n))
}
selects, siblings, ok := c.invalidation(n)
if ok {
// only the elements that the rules of its changed classes
// and id may select, as the invalidation sets of browsers (a
// class of the html or body element of npr.org matched all of
// its 8000 elements again)
var walk func(k *html.Node) bool
walk = func(k *html.Node) bool {
for ; k != nil; k = k.NextSibling {
if k.Type != html.ElementNode {
continue
}
if selects(k) && !affected[k] {
if len(order) >= maxRestyled {
return false
}
affected[k] = true
order = append(order, k)
}
if !walk(k.FirstChild) {
return false
}
}
return true
}
if !affected[n] {
affected[n] = true
order = append(order, n)
}
if !walk(n.FirstChild) {
return nil, c.noChange(tooMany)
}
if siblings {
for s := n.NextSibling; s != nil; s = s.NextSibling {
if !add(s) {
return nil, c.noChange(tooMany)
}
}
}
continue
}
for s := n; s != nil; s = s.NextSibling {
if !add(s) {
return nil, c.noChange(tooMany)
}
}
}
restore := c.setCheckedAttrs(root) // for :checked and :hover
defer c.keepAncestorMasks()()
defer restore()
if c.relational {
// the elements that :has() selectors select, which may be any,
// whose matches have changed
if !c.relationalChanges(root, append(append([]*html.Node{}, changed...), whole...), add) {
return nil, c.noChange("the elements that :has() selects")
}
}
// the declarations as they were (all of them first, as those of an
// element depend on those of the elements that it is in, for var())
saved := map[*html.Node]*nodeStyles{}
old := map[*html.Node]map[string]string{}
oldDisplay := map[*html.Node]string{}
for _, n := range order {
// (an element that was not read, as one in an element that is
// not displayed, has the declarations that it has now)
old[n] = effectiveDecls(c.declarations(n))
oldDisplay[n] = c.displayOf(n)
ns := &nodeStyles{styles: c.styles[n], sorted: c.sorted[n], hinted: c.hinted[n], queried: c.containerQueried[n]}
ns.snap, ns.hasSnap = c.snaps[n]
ns.before, ns.hasBefore = c.pseudoStyles[pseudoKey{n, "before"}]
ns.after, ns.hasAfter = c.pseudoStyles[pseudoKey{n, "after"}]
saved[n] = ns
}
undo := func() {
c.varMemo = nil
for n, ns := range saved {
c.styles[n], c.sorted[n], c.hinted[n] = ns.styles, ns.sorted, ns.hinted
if c.containerQueried != nil {
c.containerQueried[n] = ns.queried
}
c.setPseudo(n, "before", ns.before, ns.hasBefore)
c.setPseudo(n, "after", ns.after, ns.hasAfter)
if c.snaps != nil {
if ns.hasSnap {
c.snaps[n] = ns.snap
} else {
delete(c.snaps, n)
}
}
}
}
// the states of the elements, with which their declarations are found
// (see Context.ReuseStyles)
if c.snaps != nil {
parents := map[*html.Node]bool{}
for _, n := range order {
if n.Parent != nil {
parents[n.Parent] = true
}
}
for p := range parents {
snapChildren(p, func(k *html.Node, s nodeSnap) {
if affected[k] {
c.snaps[k] = s
}
})
}
}
// the declarations as they are now (the values of custom properties
// are found again if any of them changed)
pseudoChanged := map[*html.Node]bool{}
varsChanged := false
for _, n := range order {
ds := c.matchDecls(n)
queried := false
for _, d := range ds {
queried = queried || d.container != nil
}
if hasCustomDecls(c.styles[n]) || hasCustomDecls(ds) {
varsChanged = true
c.varMemo = nil // (as the elements in it inherit them)
}
c.styles[n] = ds
delete(c.sorted, n)
delete(c.hinted, n) // its attributes are added again
if queried {
if c.containerQueried == nil {
c.containerQueried = map[*html.Node]bool{}
}
c.containerQueried[n] = true
} else if c.containerQueried != nil {
delete(c.containerQueried, n)
}
for _, kind := range []string{"before", "after"} {
nd := c.matchPseudo(n, kind)
od := saved[n].before
if kind == "after" {
od = saved[n].after
}
if samePseudo(od, nd) {
continue
}
if c.undisplayed(n) {
// not rendered (as the icons of the video players of
// npr.org in a hidden dialog, which changed as they
// played, each time reading the page whole, as no element
// that they are in had widgets of its own)
c.setPseudo(n, kind, nd, len(nd) > 0)
continue
}
if !isFree(n) && (c.addRoot == nil || !c.addRoot(n)) {
undo()
// its pseudo-element, which may be a widget
return nil, c.noChange("a change of the ::" + kind + " of " + describeNode(n))
}
c.setPseudo(n, kind, nd, len(nd) > 0)
pseudoChanged[n] = true
}
}
if varsChanged {
c.varMemo = nil
}
u := &declUpdate{undo: undo, freeChanged: pseudoChanged}
for _, n := range order {
if inHead(n) || neverRendered(n) {
// not rendered (as a style element that is added, or the
// source elements of a picture, whose display the slideshows
// of npr.org changed many times a second, each reading the
// page again)
continue
}
nw := effectiveDecls(c.declarations(n))
props := changedProps(old[n], nw)
if len(props) == 0 {
continue
}
if oldDisplay[n] != "none" && c.displayOf(n) != "none" {
u.transitions = append(u.transitions, css.TransitionsOf(n, nw, props)...)
}
if isFree(n) {
u.freeChanged[n] = true
continue
}
if c.hiddenAbove(n, affected, oldDisplay) {
continue // not rendered, before and after
}
ws := c.elementWidgets[n]
// a change that the widgets can not be styled again for is read
// again, with the elements that it is in, as elements are read
// again (see Context.addRoot), or else the page is
readAgain := func() bool {
if c.addRoot != nil && c.addRoot(n) {
u.freeChanged[n] = true
return true
}
return false
}
if d := c.displayOf(n); d != oldDisplay[n] {
if readAgain() {
continue
}
undo()
return nil, c.noChange(fmt.Sprintf("display of %s from %q to %q", describeNode(n), oldDisplay[n], d))
}
if len(ws) == 0 && !c.undisplayed(n) && !c.unusedCustomProps(props) {
if readAgain() {
continue
}
undo()
return nil, c.noChange(fmt.Sprintf("%s of %s, which has no widget of its own", strings.Join(props, ", "), describeNode(n)))
}
read := false
for _, p := range props {
if p == "position" && inFlowPosition(old[n][p]) && inFlowPosition(nw[p]) {
// static and relative are both in the flow, so the widget
// is restyled for the change, with the layout (as for the
// images of npr.org as they load, hundreds of times)
u.layout = true
continue
}
if !c.restylable(n, p) {
if read = readAgain(); read {
break
}
undo()
return nil, c.noChange(fmt.Sprintf("%s of %s", p, describeNode(n)))
}
u.layout = u.layout || !paintProperties[p]
}
if read {
continue
}
u.widgets = append(u.widgets, ws...)
}
for _, n := range whole {
if htmlChildOf(n) == n {
continue // (read again whole, as the scripts added it; see Context.rereadHTML)
}
if d := c.displayOf(n); d != oldDisplay[n] {
undo()
// it may not have a frame of its own
return nil, c.noChange(fmt.Sprintf("display of %s from %q to %q", describeNode(n), oldDisplay[n], d))
}
}
// the declarations of the elements, with those of their attributes, as
// the widgets are styled with them (not the attributes of the elements
// then, which the scripts of a page may be changing meanwhile)
for _, n := range order {
c.declarations(n)
}
if html := documentElement(root); html != nil && affected[html] {
// all of the elements have been matched with all of the rules (as
// with those added to style sheets; see Context.ReuseStyles)
c.matchedRules = len(c.rules)
c.matchedPseudo = len(c.pseudoRules)
}
return u, true
}
// setPseudo sets the declarations of the given pseudo-element of the
// given element, or deletes them if it has none.
func (c *Context) setPseudo(n *html.Node, kind string, ds []*cssDecl, has bool) {
key := pseudoKey{n, kind}
if !has {
delete(c.pseudoStyles, key)
return
}
if c.pseudoStyles == nil {
c.pseudoStyles = map[pseudoKey][]*cssDecl{}
}
c.pseudoStyles[key] = ds
}
// samePseudo returns whether the given declarations of a pseudo-element
// are the same.
func samePseudo(a, b []*cssDecl) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i].Property != b[i].Property || a[i].Value != b[i].Value || a[i].Important != b[i].Important {
return false
}
}
return true
}
// relationalChanges adds the elements that the rules of :has() selectors
// select now, or did, to the elements whose declarations may change,
// with add, returning false if there are too many of them. A change of an
// element (in changed) only changes what :has() matches for the elements
// that it is in and their previous siblings (for :has(+ x) and :has(~ x)),
// so those are the only ones that the rules whose :has() selectors are in
// their subject compound are matched against. The others are matched
// against all of the elements. (All of them for all of the rules, about
// 600 of them, over the 5000 elements of npr.org, took long enough on each
// read of the layout by its scripts that the page hung.)
func (c *Context) relationalChanges(root *html.Node, changed []*html.Node, add func(n *html.Node) bool) bool {
ix := c.index()
if len(ix.relational) == 0 && len(ix.subjectHas) == 0 && len(ix.hasAbove) == 0 {
return true
}
check := func(n *html.Node, rules []int) bool {
if n.Type != html.ElementNode {
return true
}
ds := c.styles[n]
had := func(i int) bool { // (without a map, as it is called for each rule)
for _, d := range ds {
if d.rule-1 == i {
return true
}
}
return false
}
for _, i := range rules {
r := c.rules[i]
// (the key of its selector first, which most elements do not
// have, then its scope, after a match, as it walks up)
if had(i) != (r.sel.KeyIn(n) && c.selMatch(r.sel, n) && contains(r.root, n) && c.inScope(n, r.scope, r.scopeKind)) {
return add(n)
}
}
return true
}
if len(ix.relational) > 0 {
var walk func(n *html.Node) bool
walk = func(n *html.Node) bool {
if !check(n, ix.relational) {
return false
}
for k := n.FirstChild; k != nil; k = k.NextSibling {
if !walk(k) {
return false
}
}
return true
}
if !walk(root) {
return false
}
}
if len(ix.subjectHas) == 0 && len(ix.hasAbove) == 0 {
return true
}
// the rules whose :has() is in another compound are matched against
// the elements in those that match it (without its :has()), and their
// later siblings if a sibling combinator follows it: the elements that
// match them are found first (in above), then the elements in each are
// walked once, matched only against the rules whose key they have
// (most of them are matched in the body, as of npr.org)
regions := map[*html.Node][]int{} // the rules of each
var regionOrder []*html.Node
above := func(h *html.Node) bool {
if h.Type != html.ElementNode {
return true
}
for _, i := range ix.hasAbove {
if c.rules[i].hasCompound.Sel.Match(h) {
if _, ok := regions[h]; !ok {
regionOrder = append(regionOrder, h)
}
regions[h] = append(regions[h], i)
}
}
return true
}
walkRegions := func() bool {
inOuter := func(h *html.Node, i int) bool { // (walked with an outer region)
for p := h.Parent; p != nil; p = p.Parent {
if slices.Contains(regions[p], i) {
return true
}
}
return false
}
for _, h := range regionOrder {
var rules []int
for _, i := range regions[h] {
if !inOuter(h, i) {
rules = append(rules, i)
}
}
if len(rules) == 0 {
continue
}
sub := &ruleIndex{byID: map[string][]int{}, byClass: map[string][]int{}, byTag: map[string][]int{}}
siblings := false
for _, i := range rules {
r := c.rules[i]
siblings = siblings || r.hasSiblings
switch r.sel.KeyKind {
case '#':
sub.byID[r.sel.Key] = append(sub.byID[r.sel.Key], i)
case '.':
sub.byClass[r.sel.Key] = append(sub.byClass[r.sel.Key], i)
case 't':
sub.byTag[r.sel.Key] = append(sub.byTag[r.sel.Key], i)
default:
sub.other = append(sub.other, i)
}
}
var walk func(n *html.Node) bool
walk = func(n *html.Node) bool {
if n.Type == html.ElementNode && !check(n, sub.candidates(n)) {
return false
}
for k := n.FirstChild; k != nil; k = k.NextSibling {
if !walk(k) {
return false
}
}
return true
}
for k := h.FirstChild; k != nil; k = k.NextSibling {
if !walk(k) {
return false
}
}
if siblings {
for k := h.NextSibling; k != nil; k = k.NextSibling {
if !walk(k) {
return false
}
}
}
}
return true
}
seen := map[*html.Node]bool{}
for _, ch := range changed {
if ch == nil {
continue
}
// (from its last sibling: those after it changed too)
last := ch
for last.NextSibling != nil {
last = last.NextSibling
}
for a := last; a != nil; a = a.Parent {
for s := a; s != nil; s = s.PrevSibling {
if seen[s] {
continue
}
seen[s] = true
if !check(s, ix.subjectHas) || !above(s) {
return false
}
}
}
}
return walkRegions()
}
// hasCompound returns, for the given selector (of one complex selector)
// whose :has() selectors are all in one compound that is not its last,
// that compound without them, compiled, and whether a sibling combinator
// follows it, or nil if they are not (or it does not compile).
func hasCompound(sel string) (*css.CompiledSelector, bool) {
at := strings.Index(sel, ":has(")
combs := combinators(sel)
start, end, siblings := 0, len(sel), false
for _, cb := range combs {
switch {
case cb.at <= at:
start = cb.at + 1
case end == len(sel):
end = cb.start
fallthrough
default:
siblings = siblings || cb.sibling
}
}
if strings.Contains(sel[end:], ":has(") {
return nil, false
}
// the compound without its pseudo-classes that have :has() selectors
// (as :where(:not(:has(.c))) in .a.b:where(:not(:has(.c))) .x), which
// is what an element must match for them to matter
comp := sel[start:end]
var b strings.Builder
for k := 0; k < len(comp); {
if comp[k] != ':' || k+1 >= len(comp) || comp[k+1] == ':' {
b.WriteByte(comp[k])
k++
continue
}
// a pseudo-class, to the end of its arguments if it has any
e := k + 1
for e < len(comp) && (comp[e] == '-' || comp[e] == '_' || comp[e] >= 'a' && comp[e] <= 'z' || comp[e] >= 'A' && comp[e] <= 'Z' || comp[e] >= '0' && comp[e] <= '9') {
e++
}
if e < len(comp) && comp[e] == '(' {
depth := 0
for ; e < len(comp); e++ {
if comp[e] == '(' {
depth++
} else if comp[e] == ')' {
if depth--; depth == 0 {
e++
break
}
}
}
}
if !strings.Contains(comp[k:e], ":has(") {
b.WriteString(comp[k:e])
}
k = e
}
compound := strings.TrimSpace(b.String())
if compound == "" {
compound = "*"
}
cs := css.CompileSelector(compound)
if cs == nil {
return nil, false
}
return cs, siblings
}
// combinator is a combinator of a selector, from the index of its first
// character (start) to that of its last (at), which is a sibling
// combinator (+ or ~) or not (a descendant or child one).
type combinator struct {
start, at int
sibling bool
}
// combinators returns the combinators of the given selector (of one
// complex selector) that are not in parentheses, brackets or quotes, one
// for each run of them (as " > ").
func combinators(sel string) []combinator {
var combs []combinator
depth := 0
var quote byte
in := false // in a run of combinator characters
for i := 0; i < len(sel); i++ {
ch := sel[i]
isComb := false
switch {
case quote != 0:
switch ch {
case '\\':
i++
case quote:
quote = 0
}
case ch == '"' || ch == '\'':
quote = ch
case ch == '\\':
i++
case ch == '(' || ch == '[':
depth++
case ch == ')' || ch == ']':
depth--
case depth == 0 && (ch == ' ' || ch == '>' || ch == '+' || ch == '~' || ch == '\t' || ch == '\n'):
isComb = true
if !in {
combs = append(combs, combinator{start: i, at: i})
}
if ch == '+' || ch == '~' {
combs[len(combs)-1].sibling = true
}
combs[len(combs)-1].at = i // (its last character)
}
in = isComb
}
return combs
}
// subjectStart returns the index in the given selector (of one complex
// selector) of its last compound selector, the one of the elements that it
// selects: after its last combinator that is not in parentheses, brackets
// or quotes.
func subjectStart(sel string) int {
combs := combinators(sel)
if len(combs) == 0 {
return 0
}
return combs[len(combs)-1].at + 1
}
// inForeign returns whether the given element is in an svg or math element.
func inForeign(n *html.Node) bool {
for p := n.Parent; p != nil; p = p.Parent {
if p.Type == html.ElementNode && (p.Namespace != "" || p.Data == "svg" || p.Data == "math") {
return true
}
}
return false
}
// hiddenAbove returns whether an element that the given element is in
// has a display of none, and had one before the declarations of the given
// affected elements changed (with the given displays before), so that the
// given element was not rendered, nor is (see [Context.updateDecls]).
func (c *Context) hiddenAbove(n *html.Node, affected map[*html.Node]bool, oldDisplay map[*html.Node]string) bool {
for p := n.Parent; p != nil && p.Type == html.ElementNode; p = p.Parent {
if c.displayOf(p) == "none" && (!affected[p] || oldDisplay[p] == "none") {
return true
}
}
return false
}
// undisplayed returns whether the given element is not displayed (it or
// an element that it is in has a display of none), so that it has no
// widget.
func (c *Context) undisplayed(n *html.Node) bool {
for p := n; p != nil && p.Type == html.ElementNode; p = p.Parent {
if c.displayOf(p) == "none" {
return true
}
}
return false
}
// effectiveDecls returns the values of the properties of the given
// declarations, in the order of the cascade, that apply (the last of each).
func effectiveDecls(ds []*cssDecl) map[string]string {
m := make(map[string]string, len(ds))
for _, d := range ds {
v := d.Value
if d.invalid {
v = "\x00invalid"
}
m[d.Property] = v
}
return m
}
// changedProps returns the properties whose values differ.
func changedProps(a, b map[string]string) []string {
var props []string
for p, v := range a {
if bv, ok := b[p]; !ok || bv != v {
props = append(props, p)
}
}
for p := range b {
if _, ok := a[p]; !ok {
props = append(props, p)
}
}
return props
}
// restylable returns whether a change of the given property of the given
// element can be made by styling its widgets again, without reading the
// page again: it only applies in styling them, not in reading the page.
func (c *Context) restylable(n *html.Node, prop string) bool {
if strings.HasPrefix(prop, "--") {
return true // its uses are changes of their own
}
if p, ok := strings.CutPrefix(prop, "-webkit-"); ok && css.WebkitAliases[p] {
prop = p
}
if !restylableProperties[prop] {
return false
}
if c.displayOf(n) == "inline" {
// an inline element with a widget is a box by its padding and
// border (see isInlineBox), and its text is in a run
return paintProperties[prop] && prop != "color" && prop != "background-color" && prop != "background"
}
if prop == "filter" && n.Data == "img" {
return false // in the image as it is read
}
if n.Data == "tr" && strings.HasPrefix(prop, "background") {
return false // in the backgrounds of its cells as they are read
}
if c.arranged(n) {
// the sizes of the items of tables, grids and columns, which are
// arranged as they are read (as are those hidden in the stacks of
// grids, by their opacity and visibility)
return paintProperties[prop] && prop != "opacity" && prop != "visibility"
}
switch n.Data {
case "input", "select", "textarea", "button", "img", "iframe", "video", "audio", "canvas", "object", "embed":
// the widgets of controls and replaced elements, which are made
// for their styles in part
return paintProperties[prop] || prop == "margin" || strings.HasPrefix(prop, "margin-") ||
prop == "top" || prop == "bottom" || prop == "left" || prop == "right" || prop == "inset"
}
return true
}
// inFlowPosition returns whether the given value of the position property
// (as declared, "" for none) keeps an element in the flow of the layout of
// its parent (static and relative, not absolute, fixed, or sticky).
func inFlowPosition(v string) bool {
v = strings.TrimSpace(strings.TrimSuffix(strings.TrimSpace(v), "!important"))
return v == "" || v == "static" || v == "relative" || v == "initial" || v == "unset" || v == "revert"
}
// arranged returns whether the given element is or is in a table, a grid,
// or an element of columns, which are arranged as they are read.
func (c *Context) arranged(n *html.Node) bool {
switch n.Data {
case "table", "td", "th", "tr", "col", "colgroup", "caption", "thead", "tbody", "tfoot":
return true
}
for _, e := range []*html.Node{n, n.Parent} {
if e == nil || e.Type != html.ElementNode {
continue
}
if d := c.displayOf(e); strings.Contains(d, "grid") || strings.Contains(d, "table") {
return true
}
for _, p := range []string{"columns", "column-count", "column-width"} {
if v := c.declaration(e, p); v != "" && v != "auto" {
return true
}
}
}
return false
}
// paintProperties are the properties whose changes only change how the
// widgets are rendered, not their sizes or positions in their layout
// (transforms are applied to the positions of widgets in the layout).
var paintProperties = map[string]bool{
"color": true, "background-color": true, "background": true, "opacity": true,
"visibility": true, "cursor": true, "pointer-events": true, "z-index": true,
"box-shadow": true, "outline": true, "outline-color": true, "outline-style": true, "outline-width": true, "outline-offset": true,
"border-color": true, "border-top-color": true, "border-right-color": true, "border-bottom-color": true, "border-left-color": true,
"border-radius": true, "border-top-left-radius": true, "border-top-right-radius": true, "border-bottom-left-radius": true, "border-bottom-right-radius": true,
"text-decoration": true, "text-decoration-line": true, "text-decoration-color": true, "text-decoration-style": true,
"filter": true, "backdrop-filter": true, "will-change": true, "user-select": true,
"transition": true, "transition-property": true, "transition-duration": true, "transition-delay": true, "transition-timing-function": true,
"animation": true, "animation-name": true, "animation-duration": true, "animation-delay": true, "animation-iteration-count": true,
"animation-fill-mode": true, "animation-play-state": true, "animation-timing-function": true, "animation-direction": true,
"fill": true, "stroke": true, "caret-color": true, "accent-color": true, "outline-radius": true,
}
// restylableProperties are the properties whose changes can be made by
// styling the widgets of elements again (see [Context.restylable]): those
// that apply in styling them, not in reading the page.
var restylableProperties = func() map[string]bool {
m := map[string]bool{
"width": true, "height": true, "min-width": true, "min-height": true, "max-width": true, "max-height": true,
"inline-size": true, "block-size": true, "min-inline-size": true, "min-block-size": true, "max-inline-size": true, "max-block-size": true,
"top": true, "right": true, "bottom": true, "left": true, "inset": true,
"inset-block": true, "inset-inline": true, "inset-block-start": true, "inset-block-end": true, "inset-inline-start": true, "inset-inline-end": true,
"margin": true, "margin-top": true, "margin-right": true, "margin-bottom": true, "margin-left": true,
"margin-block": true, "margin-inline": true, "margin-block-start": true, "margin-block-end": true, "margin-inline-start": true, "margin-inline-end": true,
"padding": true, "padding-top": true, "padding-right": true, "padding-bottom": true, "padding-left": true,
"padding-block": true, "padding-inline": true, "padding-block-start": true, "padding-block-end": true, "padding-inline-start": true, "padding-inline-end": true,
"border": true, "border-width": true, "border-style": true,
"border-top": true, "border-right": true, "border-bottom": true, "border-left": true,
"border-top-width": true, "border-right-width": true, "border-bottom-width": true, "border-left-width": true,
"border-top-style": true, "border-right-style": true, "border-bottom-style": true, "border-left-style": true,
"overflow": true, "overflow-x": true, "overflow-y": true,
"font-weight": true, "font-style": true, "text-align": true,
"flex": true, "flex-grow": true, "flex-shrink": true, "flex-basis": true,
"align-items": true, "align-self": true, "justify-content": true, "align-content": true, "gap": true, "row-gap": true, "column-gap": true,
"box-sizing": true,
"transform": true, "translate": true, "rotate": true, "scale": true, "transform-origin": true,
}
for p := range paintProperties {
m[p] = true
}
return m
}()
// inHead returns whether the given node is the head element or in it.
func inHead(n *html.Node) bool {
for p := n; p != nil; p = p.Parent {
if p.Type == html.ElementNode && p.DataAtom == atom.Head {
return true
}
}
return false
}
// unusedCustomProps returns whether the given properties are all custom
// properties that no declaration of the page uses (with var()), so that
// their changes change nothing (as the --vwo-el-* properties that the
// A/B testing scripts of volkskrant.nl set on the html element, which has
// no widget of its own, for which the page was read whole).
func (c *Context) unusedCustomProps(props []string) bool {
for _, p := range props {
if !strings.HasPrefix(p, "--") {
return false
}
}
for _, p := range props {
if c.varsUsed[p] {
return false
}
}
return true
}
// noteVars records the custom properties that the given value of a
// declaration uses (with var()), for [Context.unusedCustomProps].
func (c *Context) noteVars(value string) {
for {
i := strings.Index(value, "var(")
if i < 0 {
return
}
value = strings.TrimLeft(value[i+4:], " \t\n")
j := 0
for j < len(value) && css.IsNameChar(value[j]) {
j++
}
if j > 0 {
if c.varsUsed == nil {
c.varsUsed = map[string]bool{}
}
c.varsUsed[value[:j]] = true
}
value = value[j:]
}
}
// invalidation returns, for the given element whose attributes have
// changed, whether the elements in it are selected by a rule that may
// select them differently for the change, and whether its siblings after
// it may be, if only its class and id changed (and its style, which
// applies to it alone): the invalidation sets of browsers, as for a class
// added to the body element, which only the rules that have the class
// before their last compound selectors (as .modal-open .modal) select the
// elements in it differently for. It returns ok false, for all of the
// elements in it and after it to be matched again, if it can not tell.
func (c *Context) invalidation(n *html.Node) (selects func(k *html.Node) bool, siblings, ok bool) {
old, has := c.snaps[n]
if !has || c.matchAll {
// (as for rules added to the style sheets)
return nil, false, false
}
var tokens []string
if old.attrs == attrsHash(n) {
// not a change of its attributes: of its states (as :hover and
// :checked), or an attribute set to the value that it had
tokens = statePseudoClasses
}
if style := GetAttr(n, "style"); style != old.style && (strings.Contains(old.style, "--") || strings.Contains(style, "--")) {
// custom properties, which the elements in it inherit (only if its
// style changed: the html element of nytimes.com has them, and
// the changes of its lang and class matched its 7000 elements
// again, for 1s each)
return nil, false, false
}
oldClasses, newClasses := strings.Fields(old.class), strings.Fields(GetAttr(n, "class"))
for _, cl := range oldClasses {
if !slices.Contains(newClasses, cl) {
tokens = append(tokens, "."+cl)
}
}
for _, cl := range newClasses {
if !slices.Contains(oldClasses, cl) {
tokens = append(tokens, "."+cl)
}
}
if id := GetAttr(n, "id"); id != old.id {
for _, v := range []string{old.id, id} {
if v != "" {
tokens = append(tokens, "#"+v)
}
}
}
// the other attributes, as [data-state] or [aria-expanded=true]
var attrTokens []string
if others := otherAttrs(n); others != old.others {
ov, nv := attrValues(old.others), attrValues(others)
for k, v := range ov {
if w, ok := nv[k]; !ok || w != v {
attrTokens = append(attrTokens, k)
}
}
for k := range nv {
if _, ok := ov[k]; !ok {
attrTokens = append(attrTokens, k)
}
}
for _, a := range attrTokens {
if a == css.HoverAttr {
// (the attribute of :hover, while the states are set)
tokens = append(tokens, ":hover")
}
tokens = append(tokens, attrPseudoClasses[a]...)
}
}
// whether its keys (classes and id) are as they were, so that the
// compound selectors that it may be selected by are known (see
// compoundMaySelect)
keysChanged := false // (its classes or id, as tokens; not :lang for its lang)
for _, t := range tokens {
keysChanged = keysChanged || !sameStates(tokens) && (t[0] == '.' || t[0] == '#')
}
sameKeys := !keysChanged
var keys []*css.CompiledSelector
all := false
check := func(text string, cs *css.CompiledSelector, decls []*douceur.Declaration) bool {
prefix, sib, last := splitLastCompound(text)
if keysChanged && (strings.Contains(prefix, "[class") || strings.Contains(prefix, "[id")) {
// (selected by its class or id other than by the names of
// them, as [class*=icon-])
if sib {
siblings = true
}
if cs == nil || cs.KeyKind == 0 {
all = true
} else {
keys = append(keys, cs)
}
}
for _, a := range attrTokens {
// (the selectors of attributes, of [name, as with a value)
inLast, inPrefix := hasAttrSelector(last, a), hasAttrSelector(prefix, a)
if inPrefix && sameKeys && !compoundMaySelect(prefix, n, func(comp string) bool { return hasAttrSelector(comp, a) }) {
inPrefix = false
}
if inLast && hasCustomProps(decls) {
return false
}
if inPrefix {
if sib {
siblings = true
}
if cs == nil || cs.KeyKind == 0 {
all = true
} else {
keys = append(keys, cs)
}
}
}
// whether the rule may select it differently: for its states, if
// it may select it at all, by its key (its classes, id, and name
// are as they were; a rule of the :hover of a class with custom
// properties matched the 7000 elements of nytimes.com again as
// its scripts set the attributes of its html element to the
// values that they had)
mayChange := func() bool {
if sameStates(tokens) {
return cs == nil || cs.KeyIn(n)
}
return len(attrTokens) > 0 || cs == nil || c.matchChanged(n, old, cs)
}
for _, t := range tokens {
if hasToken(last, t) && hasCustomProps(decls) && mayChange() {
// a rule that selects it differently, with custom
// properties, which the elements in it inherit
return false
}
if !hasToken(prefix, t) || sameKeys && !compoundMaySelect(prefix, n, func(comp string) bool { return hasToken(comp, t) }) {
continue
}
if sib {
siblings = true
}
if cs == nil || cs.KeyKind == 0 {
all = true
} else {
keys = append(keys, cs)
}
}
return true
}
for _, r := range c.rules {
if !check(r.text, r.sel, r.decls) {
return nil, false, false
}
}
for _, r := range c.pseudoRules {
if !check(r.text, r.sel, nil) {
return nil, false, false
}
}
selects = func(k *html.Node) bool {
if all {
return true
}
for _, cs := range keys {
if cs.KeyIn(k) {
return true
}
}
return false
}
return selects, siblings, true
}
// compoundMaySelect returns whether a compound selector of the given part
// of a selector before its subject for which has returns true (one that has
// the pseudo-class of a state or the attribute that changed) may select the
// given element (by its keys; see [css.CompoundKeys]), whose change those of
// the elements in it and after it are selected by (as .menu:hover .item,
// or [lang=en] .x, for an element that is not a .menu, or has no lang).
func compoundMaySelect(prefix string, n *html.Node, has func(comp string) bool) bool {
if strings.ContainsAny(prefix, "\\|") {
return true
}
own := css.OwnKeys(n)
from := 0
check := func(comp string) bool {
return has(comp) && own.Has(css.CompoundKeys(comp))
}
for _, cb := range combinators(prefix) {
if check(prefix[from:cb.start]) {
return true
}
from = cb.at + 1
}
return check(prefix[from:])
}
// splitLastCompound returns the given selector before its last compound
// selector, whether it has a combinator of siblings (+ or ~) there, and
// the last compound selector.
func splitLastCompound(sel string) (prefix string, siblings bool, last string) {
depth, at := 0, -1
for i := 0; i < len(sel); i++ {
switch sel[i] {
case '(', '[':
depth++
case ')', ']':
depth--
case ' ', '>', '+', '~':
if depth == 0 {
at = i
}
}
}
if at < 0 {
return "", false, sel
}
prefix = sel[:at+1]
sib := false
for _, cb := range combinators(prefix) {
// (not as in [class~=a])
sib = sib || cb.sibling
}
return prefix, sib, sel[at+1:]
}
// hasToken returns whether the given selector text has the given class
// (.name) or id (#name), not as the start of a longer name.
func hasToken(text, token string) bool {
for i := 0; ; {
j := strings.Index(text[i:], token)
if j < 0 {
return false
}
end := i + j + len(token)
if end >= len(text) || !css.IsNameChar(text[end]) {
return true
}
i = end
}
}
// hasAttrSelector returns whether the given selector text selects elements
// by the given attribute ([name, [name=, [name~= and so on).
func hasAttrSelector(text, name string) bool {
for i := 0; ; {
j := strings.Index(text[i:], "[")
if j < 0 {
return false
}
rest := strings.TrimLeft(text[i+j+1:], " ")
if strings.HasPrefix(rest, name) && (len(rest) == len(name) || !css.IsNameChar(rest[len(name)])) {
return true
}
i += j + 1
}
}
// hasCustomProps returns whether the given declarations have custom
// properties (--name).
func hasCustomProps(decls []*douceur.Declaration) bool {
for _, d := range decls {
if strings.HasPrefix(strings.TrimSpace(d.Property), "--") {
return true
}
}
return false
}
// attrPseudoClasses are the pseudo-classes that select elements by the
// given attributes (see [Context.invalidation]).
var attrPseudoClasses = map[string][]string{
"disabled": {":disabled", ":enabled"},
"checked": {":checked", ":indeterminate", ":default"},
"selected": {":checked", ":default"},
"required": {":required", ":optional"},
"readonly": {":read-only", ":read-write"},
"open": {":open", ":closed"},
"lang": {":lang"},
"dir": {":dir"},
"href": {":link", ":any-link", ":visited"},
"placeholder": {":placeholder-shown"},
"value": {":placeholder-shown", ":valid", ":invalid"},
"type": {":checked", ":valid", ":invalid", ":read-only", ":read-write"},
"contenteditable": {":read-only", ":read-write"},
"hidden": {},
}
// statePseudoClasses are the pseudo-classes of the states of elements,
// which a change of them may select others by (see [Context.invalidation]).
var statePseudoClasses = []string{":hover", ":checked", ":focus", ":focus-within", ":focus-visible", ":active", ":target", ":default", ":indeterminate", ":open"}
// sameStates returns whether the given tokens are those of the states
// (see [statePseudoClasses]).
func sameStates(tokens []string) bool {
return len(tokens) > 0 && &tokens[0] == &statePseudoClasses[0]
}
// matchChanged returns whether the given selector matches the given
// element differently with its class and id now and with those of the
// given state of it (as before they changed).
func (c *Context) matchChanged(n *html.Node, old nodeSnap, cs *css.CompiledSelector) bool {
now := cs.Sel.Match(n)
saved := n.Attr
attrs := make([]html.Attribute, 0, len(saved)+2)
for _, a := range saved {
if a.Namespace == "" && (a.Key == "class" || a.Key == "id") {
continue
}
attrs = append(attrs, a)
}
if old.class != "" {
attrs = append(attrs, html.Attribute{Key: "class", Val: old.class})
}
if old.id != "" {
attrs = append(attrs, html.Attribute{Key: "id", Val: old.id})
}
n.Attr = attrs
before := cs.Sel.Match(n)
n.Attr = saved
return now != before
}
// neverRendered returns whether the given element never has a box of its
// own, whatever its styles: the sources and tracks of media, and the
// elements of scripts and of the head.
func neverRendered(n *html.Node) bool {
switch n.DataAtom {
case atom.Source, atom.Track, atom.Script, atom.Noscript, atom.Template, atom.Style, atom.Link, atom.Meta, atom.Base, atom.Param:
return true
}
return false
}
// hasCustomDecls returns whether the given declarations have custom
// properties.
func hasCustomDecls(ds []*cssDecl) bool {
for _, d := range ds {
if strings.HasPrefix(d.Property, "--") {
return true
}
}
return false
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"fmt"
"hash/maphash"
"reflect"
"slices"
"strings"
"golang.org/x/net/html"
"cogentcore.org/core/htmlcore/css"
)
// ReuseStyles makes the context, which is to read a document that the
// given context has read (as the page that the scripts of a page change
// is read again whole when its changes can not be made otherwise), match
// the style rules of the document only against the elements whose matches
// may have changed since: those that have changed (as their attributes),
// moved, or been added, and those that their changes may change the
// matches of. The others have the declarations of the rules that matched
// them in the given context, as long as its rules are the same (as
// without a new style sheet, or another width of the viewport for its
// media queries); otherwise all of the rules are matched. Matching the
// rules is most of the time of reading a page (as about a second for each
// of the many times that npr.org was read again as it loaded).
func (c *Context) ReuseStyles(prev *Context) {
c.reuseFrom = prev
}
// Reused returns how the declarations of the elements were found when
// the context read its page (see [Context.ReuseStyles]), for the verbose
// console: "" if they were all matched as usual.
func (c *Context) Reused() string {
return c.reused
}
// nodeSnap is the state of an element by which style rules select it,
// apart from those of the elements that it is in and those before it (see
// [Context.ReuseStyles]): its parent, attributes and place in its parent.
type nodeSnap struct {
parent *html.Node
attrs uint64
// class, id, and style are its class, id, and style attributes, and
// others its other attributes (as name=value lines), for the elements
// that a change of them may select (see [Context.invalidation]).
class, id, style, others string
// index and typeIndex are its index in the elements of its parent,
// and in those of the same name, as :nth-child selects it.
index, typeIndex int32
// last and lastType are whether it is the last element of its parent,
// and of those of its name, as :last-child and :last-of-type select it,
// count is the number of elements of its parent (for :nth-last-child),
// and empty is whether it has no elements or text (for :empty).
last, lastType, empty bool
count int32
}
// snapSeed is the seed of the hashes of the attributes of elements.
var snapSeed = maphash.MakeSeed()
// attrsHash returns the hash of the attributes of the given element.
func attrsHash(n *html.Node) uint64 {
var h maphash.Hash
h.SetSeed(snapSeed)
for _, a := range n.Attr {
h.WriteString(a.Namespace)
h.WriteByte(0)
h.WriteString(a.Key)
h.WriteByte(0)
h.WriteString(a.Val)
h.WriteByte(0)
}
return h.Sum64()
}
// otherAttrs returns the attributes of the given element but its class,
// id, and style, as name=value lines (with the namespaces of those that
// have one), or "" for none.
func otherAttrs(n *html.Node) string {
var sb strings.Builder
for _, a := range n.Attr {
if a.Namespace == "" && (a.Key == "class" || a.Key == "id" || a.Key == "style") {
continue
}
if a.Namespace != "" {
sb.WriteString(a.Namespace)
sb.WriteByte(':')
}
sb.WriteString(a.Key)
sb.WriteByte('=')
// (escaped, as the srcsets of nytimes.com have lines, which were
// other attributes, as their URLs have =)
sb.WriteString(attrEscaper.Replace(a.Val))
sb.WriteByte('\n')
}
return sb.String()
}
// attrEscaper escapes the values of attributes in [otherAttrs], whose
// lines they are in.
var attrEscaper = strings.NewReplacer("\\", "\\\\", "\n", "\\n")
// attrValues returns the names of the attributes in the given lines of
// [otherAttrs] with their values (escaped).
func attrValues(lines string) map[string]string {
m := map[string]string{}
for l := range strings.SplitSeq(lines, "\n") {
if k, v, ok := strings.Cut(l, "="); ok {
m[k] = v
}
}
return m
}
// snapChildren calls the given function with the state of each of the
// elements of the given parent (see [nodeSnap]).
func snapChildren(p *html.Node, f func(k *html.Node, s nodeSnap)) {
var kids []*html.Node
for k := p.FirstChild; k != nil; k = k.NextSibling {
if k.Type == html.ElementNode {
kids = append(kids, k)
}
}
snaps := make([]nodeSnap, len(kids))
var names []string // seen, for the indexes of the names
var counts []int32
for i, k := range kids {
j := slices.Index(names, k.Data)
if j < 0 {
j = len(names)
names = append(names, k.Data)
counts = append(counts, 0)
}
empty := true
for g := k.FirstChild; g != nil && empty; g = g.NextSibling {
empty = g.Type != html.ElementNode && (g.Type != html.TextNode || g.Data == "")
}
snaps[i] = nodeSnap{parent: p, attrs: attrsHash(k), class: GetAttr(k, "class"), id: GetAttr(k, "id"), style: GetAttr(k, "style"), others: otherAttrs(k),
index: int32(i), typeIndex: counts[j],
last: i == len(kids)-1, empty: empty, count: int32(len(kids))}
counts[j]++
}
names = names[:0]
for i := len(kids) - 1; i >= 0; i-- {
if !slices.Contains(names, kids[i].Data) {
names = append(names, kids[i].Data)
snaps[i].lastType = true
}
}
for i, k := range kids {
f(k, snaps[i])
}
}
// snapshot records the states of the elements of the given document (see
// [nodeSnap]), with which the declarations that the context has found
// for them are found.
func (c *Context) snapshot(root *html.Node) {
c.snaps, c.snapRoot = map[*html.Node]nodeSnap{}, root
var walk func(p *html.Node)
walk = func(p *html.Node) {
snapChildren(p, func(k *html.Node, s nodeSnap) {
c.snaps[k] = s
walk(k)
})
}
walk(root)
}
// sameRules returns whether the context has the same style rules as the
// given context, in the same order.
func (c *Context) sameRules(prev *Context) bool {
if len(c.rules) != len(prev.rules) {
return false
}
for i, r := range c.rules {
p := prev.rules[i]
if r.sel != p.sel || r.text != p.text || r.root != p.root || r.origin != p.origin || r.spec != p.spec ||
r.cssBase != p.cssBase || len(r.decls) != len(p.decls) || !reflect.DeepEqual(r.container, p.container) {
return false
}
for j, d := range r.decls {
e := p.decls[j]
if d.Property != e.Property || d.Value != e.Value || d.Important != e.Important {
return false
}
}
}
return true
}
// placeKinds are the kinds of pseudo-classes of the places of elements
// in their parents (as :first-child), by which the changes of the places
// of elements change their matches (see [nodeSnap]).
type placeKinds struct {
index, typeIndex, last, lastType, count, typeCount, empty bool
}
// placeClasses are the pseudo-classes of the places of elements, with
// the kinds of places that they select by.
var placeClasses = map[string]placeKinds{
":first-child": {index: true}, ":nth-child": {index: true}, ":only-child": {index: true, last: true},
":last-child": {last: true}, ":nth-last-child": {count: true},
":first-of-type": {typeIndex: true}, ":nth-of-type": {typeIndex: true}, ":only-of-type": {typeIndex: true, lastType: true},
":last-of-type": {lastType: true}, ":nth-last-of-type": {typeCount: true}, ":empty": {empty: true},
}
// or returns the kinds of both.
func (k placeKinds) or(o placeKinds) placeKinds {
return placeKinds{k.index || o.index, k.typeIndex || o.typeIndex, k.last || o.last, k.lastType || o.lastType,
k.count || o.count, k.typeCount || o.typeCount, k.empty || o.empty}
}
// differ returns whether the given states of an element differ in a way
// that may change its matches, for the kinds of places selected by.
func (k placeKinds) differ(o, s nodeSnap) bool {
return k.index && o.index != s.index || k.typeIndex && o.typeIndex != s.typeIndex ||
k.last && o.last != s.last || k.lastType && o.lastType != s.lastType ||
k.count && o.count != s.count || k.typeCount && (o.count != s.count || o.typeIndex != s.typeIndex) ||
k.empty && o.empty != s.empty
}
// deepPlace is a compound selector of a style rule before its subject
// that selects elements by their places, followed by a combinator of
// descendants or children (as li:first-child in li:first-child a): the
// elements in an element that it may select may have other matches as the
// place of that element changes.
type deepPlace struct {
kinds placeKinds
keys css.KeyMask // of the compound selector (see compoundKeys)
}
// deepPlaces returns the compound selectors of the style rules of the
// context before their subjects that select elements by their places,
// that are followed by combinators of descendants or children (see
// [deepPlace]), and the kinds of places that those followed by combinators
// of siblings select by (as p:last-of-type + div), for which the elements
// after an element whose place changes, and those in them, may have other
// matches. It refines the deep kinds of [Context.placeUses], with which
// the change of the place of an element made all of the elements in it
// match again: on nytimes.com, the scripts that added and removed a div at
// the end of the body changed whether its #app was the last of its type,
// which a rule selected another element by, matching its 6500 elements
// again, for 1s, each time.
func (c *Context) deepPlaces() (places []deepPlace, siblings placeKinds) {
seen := map[deepPlace]bool{}
for _, r := range c.rules {
t := r.text
if !strings.Contains(t, ":") || !hasPlaceClass(t) {
continue
}
from := 0
for _, cb := range combinators(t) {
comp := t[from:cb.start]
from = cb.at + 1
var k placeKinds
for pc, pk := range placeClasses {
if strings.Contains(comp, pc) {
k = k.or(pk)
}
}
if k == (placeKinds{}) {
continue
}
if cb.sibling {
siblings = siblings.or(k)
continue
}
var keys css.KeyMask // (none: it may select any element)
if !strings.ContainsAny(comp, "\\|") {
keys = css.CompoundKeys(comp)
}
dp := deepPlace{k, keys}
if !seen[dp] {
seen[dp] = true
places = append(places, dp)
}
}
}
return
}
// hasPlaceClass returns whether the given selector has a pseudo-class of
// places (see [placeClasses]).
func hasPlaceClass(sel string) bool {
for pc := range placeClasses {
if strings.Contains(sel, pc) {
return true
}
}
return false
}
// placeChangedDeep returns whether the given states of the given element
// differ in a way that may change the matches of the elements in it or
// after it, for the given compound selectors and kinds of places of
// siblings (see [Context.deepPlaces]): those that may select it (by its
// keys; see [css.AncestorKeys]) and select by a kind of place in which its
// states differ.
func placeChangedDeep(n *html.Node, o, s nodeSnap, places []deepPlace, siblings placeKinds) bool {
if siblings.differ(o, s) {
return true
}
var own css.KeyMask
gotOwn := false
for _, p := range places {
if !p.kinds.differ(o, s) {
continue
}
if !gotOwn {
own, gotOwn = css.OwnKeys(n), true
}
if own.Has(p.keys) {
return true
}
}
return false
}
// placeUses returns the kinds of places that the style rules of the
// context select elements by (see [Context.deepPlaces] for those that they
// select the elements in or after them by).
func (c *Context) placeUses() (uses placeKinds) {
for _, r := range c.rules {
t := r.text
if !strings.Contains(t, ":") {
continue
}
for pc, k := range placeClasses {
if strings.Contains(t, pc) {
uses = uses.or(k)
}
}
}
return
}
// siblingSubjects returns the keys of the compound selectors of the style
// rules of the context that follow combinators of siblings and are followed
// by combinators of descendants or children (as .b in .a ~ .b .c, and in
// .a + .b > .c): the elements in an element that one may select may have
// other matches as the elements before it change. (An element inserted at
// the start of the body of nytimes.com, by its ad scripts, matched the 6800
// elements of its #app again, which no such selector selects, as a rule
// had a combinator of siblings followed by one of descendants.)
func (c *Context) siblingSubjects() []css.KeyMask {
var masks []css.KeyMask
seen := map[css.KeyMask]bool{}
for _, r := range c.rules {
t := r.text
if !strings.ContainsAny(t, "+~") {
continue
}
combs := combinators(t)
from := 0
for i, cb := range combs {
comp := t[from:cb.start]
from = cb.at + 1
if i == 0 || !combs[i-1].sibling || cb.sibling {
continue
}
var keys css.KeyMask // (none: it may select any element)
if !strings.ContainsAny(comp, "\\|") {
keys = css.CompoundKeys(comp)
}
if !seen[keys] {
seen[keys] = true
masks = append(masks, keys)
}
}
}
return masks
}
// siblingSelects returns whether a compound selector of the given keys
// (see [Context.siblingSubjects]) may select the given element (or any,
// if there are none, for the selectors that it could not tell).
func siblingSelects(n *html.Node, masks []css.KeyMask) bool {
if len(masks) == 0 {
return true
}
own := css.OwnKeys(n)
return slices.ContainsFunc(masks, own.Has)
}
// siblingCombinators returns whether a style rule of the context may
// select elements by those before them (with + or ~), so that the changes
// of an element may change the matches of those after it, and whether
// one may select elements in those (as .a ~ .b .c).
func (c *Context) siblingCombinators() (siblings, in bool) {
for _, r := range c.rules {
s, i := siblingCombinator(r.text)
siblings, in = siblings || s, in || i
if in {
break
}
}
return
}
// siblingCombinator returns whether the given selector has a combinator
// of siblings (+ or ~, not in brackets or parentheses, as of :nth-child(2n+1)
// and [a~=b]), and whether one is followed by a combinator of descendants.
func siblingCombinator(sel string) (sibling, in bool) {
depth := 0
var quote byte
for i := 0; i < len(sel); i++ {
ch := sel[i]
switch {
case quote != 0:
switch ch {
case '\\':
i++
case quote:
quote = 0
}
case ch == '"' || ch == '\'':
quote = ch
case ch == '(' || ch == '[':
depth++
case ch == ')' || ch == ']':
depth--
case depth > 0:
case ch == '+' || ch == '~':
sibling = true
case sibling && ch == '>':
in = true
case sibling && ch == ' ':
// a combinator of descendants, not the spaces around another
prev := strings.TrimRight(sel[:i], " ")
next := strings.TrimLeft(sel[i:], " ")
if next != "" && prev != "" && !strings.ContainsAny(next[:1], "+~>") && !strings.ContainsAny(prev[len(prev)-1:], "+~>") {
in = true
}
}
}
return
}
// reuseMatches finds the declarations of the elements of the given
// document from the rules that matched them in the given context, which
// has read it, matching the rules again only against the elements whose
// matches may have changed (see [Context.ReuseStyles]). It returns false,
// with no declarations found, if the rules are not those of the given
// context, or too many elements are to be matched again.
func (c *Context) reuseMatches(root *html.Node, prev *Context) bool {
if !c.sameRules(prev) {
c.reused = "the style rules changed"
return false
}
c.snapshot(root)
// the elements to match again: those that have changed, moved, or
// are new, and those in them, and those after them for the
// combinators of siblings, and those whose children have changed
// (whole has those added with the elements in them)
affected, whole := map[*html.Node]bool{}, map[*html.Node]bool{}
var changed []*html.Node
var add func(n *html.Node) bool
add = func(n *html.Node) bool {
if n.Type != html.ElementNode || whole[n] {
return true
}
affected[n], whole[n] = true, true
for k := n.FirstChild; k != nil; k = k.NextSibling {
add(k)
}
return true
}
siblings, inSiblings := c.siblingCombinators()
uses := c.placeUses()
deepPlaces, siblingPlaces := c.deepPlaces()
// later adds the elements after the given one (from it, if first), for
// the combinators of siblings
later := func(k *html.Node) {
if !siblings {
return
}
for ; k != nil; k = k.NextSibling {
if inSiblings {
add(k)
} else if k.Type == html.ElementNode {
affected[k] = true
}
}
}
// the parents of the elements that were removed, with the least index
// that one had in it: those after it are at or after that index now
// (with those inserted before them)
removedFrom := map[*html.Node]int32{}
removed := func(p *html.Node, index int32) {
if i, ok := removedFrom[p]; !ok || index < i {
removedFrom[p] = index
}
}
for n, s := range c.snaps {
o, ok := prev.snaps[n]
switch {
case !ok || o.parent != s.parent || o.attrs != s.attrs || placeChangedDeep(n, o, s, deepPlaces, siblingPlaces):
// (and those of a place that selectors select those in or after
// it by)
changed = append(changed, n)
add(n)
later(n.NextSibling)
if ok && o.parent != s.parent && o.parent != nil {
removed(o.parent, o.index)
}
case uses.differ(o, s):
// moved in its parent, or with other children, as a
// selector of the place of elements selects them
changed = append(changed, n)
affected[n] = true
}
}
for n, o := range prev.snaps {
if _, ok := c.snaps[n]; !ok && o.parent != nil {
removed(o.parent, o.index)
}
}
for p, index := range removedFrom {
if _, ok := c.snaps[p]; !ok {
continue // (not in the document)
}
changed = append(changed, p)
affected[p] = true
i := int32(0)
for k := p.FirstChild; k != nil; k = k.NextSibling {
if k.Type != html.ElementNode {
continue
}
if i >= index {
later(k)
break
}
i++
}
}
if len(affected) > len(c.snaps)/2 {
c.reused = fmt.Sprintf("%d of %d elements changed", len(affected), len(c.snaps))
return false
}
// the declarations of the rules that matched the others
c.styles = map[*html.Node][]*cssDecl{}
var ids []int
for n, ds := range prev.styles {
if affected[n] {
continue
}
if _, ok := c.snaps[n]; !ok {
continue // (not in the document)
}
ids = ids[:0]
for _, d := range ds {
if d.rule > 0 {
ids = append(ids, d.rule-1)
}
}
slices.Sort(ids)
ids = slices.Compact(ids)
c.setMatched(n, c.ruleDecls(n, ids))
}
if c.relational {
// those that :has() selectors select, by the changed elements
// (only those whose matches change: the elements in them have
// those that they have, as the matches of selectors are by the
// elements of the document, not by those of others, and the
// checks of the :has() selectors find all of those that change)
one := func(n *html.Node) bool {
if n.Type == html.ElementNode {
affected[n] = true
}
return true
}
if !c.relationalChanges(root, changed, one) || len(affected) > len(c.snaps)/2 {
c.styles, c.containerQueried = nil, nil
c.reused = "too many elements that :has() selects changed"
return false
}
}
for n := range affected {
if n.Type == html.ElementNode {
c.setMatched(n, c.matchDecls(n))
}
}
c.reused = fmt.Sprintf("%d of %d elements matched again", len(affected), len(c.snaps))
return true
}
// setMatched sets the declarations of the rules that match the given
// element.
func (c *Context) setMatched(n *html.Node, ds []*cssDecl) {
if hasCustomDecls(ds) || hasCustomDecls(c.styles[n]) {
c.varMemo = nil
}
if len(ds) == 0 {
delete(c.styles, n)
} else {
c.styles[n] = ds
}
for _, d := range ds {
if d.container != nil {
if c.containerQueried == nil {
c.containerQueried = map[*html.Node]bool{}
}
c.containerQueried[n] = true
return
}
}
if c.containerQueried != nil {
delete(c.containerQueried, n)
}
}
// ruleDecls returns the declarations of the given rules (indexes in the
// rules of the context, in order) for the given element, which they
// select, as [Context.matchDecls] does.
func (c *Context) ruleDecls(_ *html.Node, ids []int) []*cssDecl {
var ds []*cssDecl
base := c.cssBase
defer func() { c.cssBase = base }()
for _, i := range ids {
r := c.rules[i]
c.cssBase = r.cssBase // for its URLs
for _, d := range r.decls {
prop, value := css.PropertyName(d.Property), strings.TrimSpace(d.Value)
if !css.ValidDeclaration(prop, value) {
continue
}
c.cssOrder++
c.noteVars(value)
ds = append(ds, &cssDecl{Property: prop, Value: c.absoluteURLs(value), Important: d.Important,
origin: r.origin, specificity: r.spec, order: c.cssOrder, container: r.container, rule: i + 1})
}
}
return ds
}
// applyRules adds the declarations of the style rules of the context to
// the elements that they select, as they are added when they are not
// only recorded (see [Context.addRuleList]).
func (c *Context) applyRules() {
if c.styles == nil {
c.styles = map[*html.Node][]*cssDecl{}
}
base, container := c.cssBase, c.curContainer
defer func() { c.cssBase, c.curContainer, c.curRule = base, container, 0 }()
for i, r := range c.rules {
c.cssBase, c.curContainer, c.curRule = r.cssBase, r.container, i+1
for _, n := range c.selectNodes(r.root, r.text) {
if c.inScope(n, r.scope, r.scopeKind) {
c.addDecls(n, r.decls, r.origin, r.spec)
}
}
}
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"golang.org/x/net/html"
"cogentcore.org/core/htmlcore/css"
)
// A page can be read as its composed tree (see [Context.ShadowScope]), in
// which the content of the shadow root of an element (as of the web
// components of reddit.com) is in its place, with the children of the
// element that are assigned to each slot of it in the slot. The style sheets
// of a shadow tree (style elements, and the style sheets that it adopts,
// which scripts put in style elements of it) apply only to its elements,
// with :host for its host, and ::slotted() for the children of the host in
// its slots; those of the document do not apply to the elements of shadow
// trees (which inherit the styles of the elements that they are in).
// enterScope sets the scope of the rules of the given style sheet element
// (see [Context.curScope]), and returns the function that sets it back.
func (c *Context) enterScope(n *html.Node) func() {
prev := c.curScope
if c.ShadowScope != nil {
c.curScope = c.ShadowScope(n)
}
return func() { c.curScope = prev }
}
// inScope returns whether a rule of the given scope (nil for the document)
// and kind can select the given element.
func (c *Context) inScope(n, scope *html.Node, kind css.ScopeKind) bool {
if kind == css.ScopeAny {
return true
}
if c.ShadowScope == nil {
return scope == nil
}
switch kind {
case css.ScopeHost:
return n == scope
case css.ScopeSlotted:
p := c.parentOf(n)
return p != nil && p.Type == html.ElementNode && p.Data == "slot" && c.ShadowScope(p) == scope
}
return c.ShadowScope(n) == scope
}
// parentOf returns the parent of the given node in the tree that the page
// is read as (see [Context.ComposedParent]).
func (c *Context) parentOf(n *html.Node) *html.Node {
if c.ComposedParent != nil {
return c.ComposedParent(n)
}
return n.Parent
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"slices"
"strconv"
"strings"
"cogentcore.org/core/system"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
// The responsive images of HTML: the source of an img is chosen from the
// source elements of its picture (by their media and type) and from the
// candidates of a srcset (by their density, or their width for the sizes
// of the image), as in browsers, as the images of nytimes.com/wirecutter,
// which have a srcset and no src.
// imageSource returns the URL of the image to show for the given img
// element, and its density (the number of its pixels per CSS px), or ""
// if it has none.
func (c *Context) imageSource(n *html.Node) (src string, density float32) {
sizes := GetAttr(n, "sizes")
if p := n.Parent; p != nil && p.Type == html.ElementNode && p.Data == "picture" {
for s := p.FirstChild; s != nil && s != n; s = s.NextSibling {
if s.Type != html.ElementNode || s.Data != "source" || !imageTypeSupported(GetAttr(s, "type")) {
continue
}
if m := GetAttr(s, "media"); m != "" && !c.mediaMatches(m) {
continue
}
if HasAttr(s, "sizes") {
sizes = GetAttr(s, "sizes")
}
if src, density = c.srcsetCandidate(GetAttr(s, "srcset"), sizes, ""); src != "" {
return src, density
}
}
}
src = strings.TrimSpace(GetAttr(n, "src"))
if s, d := c.srcsetCandidate(GetAttr(n, "srcset"), sizes, src); s != "" {
return s, d
}
return src, 1
}
// imageTypeSupported returns whether images of the given MIME type (of a
// source element) can be shown, which they all can if it is not set.
func imageTypeSupported(typ string) bool {
typ = strings.ToLower(strings.TrimSpace(typ))
if typ == "" {
return true
}
switch typ {
case "image/png", "image/jpeg", "image/jpg", "image/gif", "image/webp", "image/bmp", "image/svg+xml", "image/x-icon", "image/vnd.microsoft.icon":
return true
}
return false
}
// srcsetCandidate returns the URL and density of the candidate of the
// given srcset that is best for the pixel ratio of the screen: the one of
// the least density that is at least that ratio, or else the one of the
// most density. The density of a width descriptor is its width over that
// of the image from the given sizes. The given src (of the img) is a
// candidate of 1x if the srcset has density descriptors and none of 1x, as
// in browsers (as the images of wikipedia.org, with a src and a srcset of 2x).
func (c *Context) srcsetCandidate(srcset, sizes, src string) (string, float32) {
type candidate struct {
url string
density float32
}
var cands []candidate
var slot float32
for _, item := range splitSrcset(srcset) {
f := strings.Fields(item)
if len(f) == 0 {
continue
}
cd := candidate{url: f[0], density: 1}
if len(f) > 1 {
d := strings.ToLower(f[1])
x, err := strconv.ParseFloat(d[:len(d)-1], 32)
if err != nil || x <= 0 {
continue
}
switch d[len(d)-1] {
case 'x':
cd.density = float32(x)
case 'w':
if slot == 0 {
slot = c.imageSlotWidth(sizes)
}
cd.density = float32(x) / slot
default:
continue
}
}
cands = append(cands, cd)
}
if len(cands) == 0 {
return "", 0
}
if src != "" && slot == 0 && !slices.ContainsFunc(cands, func(cd candidate) bool { return cd.density == 1 }) {
cands = append(cands, candidate{url: src, density: 1})
}
slices.SortStableFunc(cands, func(a, b candidate) int {
switch {
case a.density < b.density:
return -1
case a.density > b.density:
return 1
}
return 0
})
ratio := devicePixelRatio() * max(c.Zoom, 1)
for _, cd := range cands {
if cd.density >= ratio-0.01 {
return cd.url, cd.density
}
}
last := cands[len(cands)-1]
return last.url, last.density
}
// splitSrcset splits the given srcset into its candidates, at the commas
// that follow white space or a descriptor (not those in the URLs, as in
// the query of crop=3:2,... of an image CDN).
func splitSrcset(srcset string) []string {
var items []string
start := 0
inURL := false // in the URL of the current candidate
seen := false // a URL has started
for i, r := range srcset {
switch {
case r == ' ' || r == '\t' || r == '\n' || r == '\r' || r == '\f':
if seen {
inURL = false
}
case r == ',' && !inURL && seen:
items = append(items, srcset[start:i])
start, seen = i+1, false
default:
if !seen {
seen, inURL = true, true
}
}
}
if seen {
items = append(items, srcset[start:])
}
return items
}
// imageSlotWidth returns the width of an image in CSS px from the given
// sizes attribute: the length of its first entry whose media condition
// matches, or the width of the viewport.
func (c *Context) imageSlotWidth(sizes string) float32 {
env := c.readEnv()
for entry := range strings.SplitSeq(sizes, ",") {
entry = strings.TrimSpace(entry)
if entry == "" {
continue
}
// the length is after the last white space outside of parentheses
cond, length := "", entry
depth := 0
for i, r := range entry {
switch {
case r == '(':
depth++
case r == ')':
depth--
case depth == 0 && (r == ' ' || r == '\t' || r == '\n'):
cond, length = strings.TrimSpace(entry[:i]), strings.TrimSpace(entry[i+1:])
}
}
if cond != "" && !c.mediaMatches(cond) {
continue
}
if length == "auto" {
break
}
if px, ok := env.LengthPx(length); ok && px > 0 {
return px
}
}
return c.mediaWidth()
}
// devicePixelRatio returns the ratio of the pixels of the screen to CSS
// px, or 1 if there is no screen.
func devicePixelRatio() float32 {
if system.TheApp != nil && system.TheApp.NScreens() > 0 {
if r := system.TheApp.Screen(0).DevicePixelRatio; r > 0 {
return r
}
}
return 1
}
// noscriptImage returns the source (and its density) of the image of the
// noscript element after the given img, which has no source, if the
// noscript is not read (with scripts, whose contents are its text): the
// image for pages without scripts of lazy images, whose scripts set their
// sources as they are shown (as <img loading="lazy"><noscript><img
// src="..."></noscript> on nytimes.com), or "" if there is none.
func (c *Context) noscriptImage(n *html.Node) (string, float32) {
ns := nextElement(n)
if ns == nil && n.Parent != nil && n.Parent.DataAtom == atom.Picture {
ns = nextElement(n.Parent)
}
if ns == nil || ns.DataAtom != atom.Noscript || ns.FirstChild == nil || ns.FirstChild.Type != html.TextNode {
return "", 0
}
text := nodeText(ns)
if !strings.Contains(text, "<img") {
return "", 0
}
kids, err := html.ParseFragment(strings.NewReader(text), &html.Node{Type: html.ElementNode, Data: "div", DataAtom: atom.Div})
if err != nil {
return "", 0
}
var img *html.Node
var find func(k *html.Node)
find = func(k *html.Node) {
for ; k != nil && img == nil; k = k.NextSibling {
if k.Type == html.ElementNode && k.DataAtom == atom.Img {
img = k
return
}
find(k.FirstChild)
}
}
for _, k := range kids {
find(k)
}
if img == nil {
return "", 0
}
src, density := c.imageSource(img)
if strings.HasSuffix(src, ".svg") || strings.HasPrefix(src, "data:image/svg") {
return "", 0 // (an svg, which has another widget)
}
return src, density
}
// nextElement returns the element after the given node, or nil.
func nextElement(n *html.Node) *html.Node {
for k := n.NextSibling; k != nil; k = k.NextSibling {
if k.Type == html.ElementNode {
return k
}
if k.Type == html.TextNode && strings.TrimSpace(k.Data) != "" {
return nil
}
}
return nil
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
_ "embed"
"fmt"
"image"
"strings"
"cogentcore.org/core/htmlcore/css"
"cogentcore.org/core/text/shaped"
"cogentcore.org/core/core"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/text"
"golang.org/x/net/html"
)
// browserStyles are the user agent styles, which follow those of web browsers.
//
//go:embed browser.css
var browserStyles string
// blockState is the state of a widget for laying out blocks,
// mainly for collapsing margins.
type blockState struct {
// ops are the style operations of the declarations of the element,
// and inherit those of the inherited properties of the inline
// elements that it is in (see [Context.inlineInheritedOps]).
ops, inherit []styleOp
// display is the CSS display of the element.
display string
// block is whether the widget is block-level.
block bool
// hidden is whether the element is not visible (visibility: hidden),
// which its descendants inherit.
hidden bool
// alignItems is the CSS align-items of a flex container.
alignItems string
// topBase is the total margin directly above the top border
// edge of the widget (including its own top margin), which the
// top margin of its first child collapses with, if openTop.
topBase float32
// bottomBase is the total margin directly below the bottom border
// edge of the widget (including its own bottom margin), which the
// bottom margin of its last child collapses with, if openBottom.
bottomBase float32
// borderCollapse is whether a table has collapsed borders.
borderCollapse bool
// legacyCenter is whether the element is centered by an align attribute.
legacyCenter bool
// markers is whether a list has markers, which are in the
// space of its left padding.
markers bool
// definiteHeight is whether the element has a definite height,
// which percentage heights of its children are relative to.
definiteHeight bool
// maxHeight is whether the element has a max-height, which the flex
// items of a column of it shrink to fit (see resolver.flexMaxColumn).
maxHeight bool
// openTop and openBottom are whether the margins of the first
// and last children collapse with those of the widget, when it
// has no padding or border there.
openTop, openBottom bool
// marginTop and marginBottom are the computed top and bottom margins
// of the element in dots, before they collapse (as in the computed
// style of a browser).
marginTop, marginBottom float32
// noPointer is whether the element has pointer-events: none (which is
// inherited), unlike the widgets that get no events as they are hidden.
noPointer bool
}
// cssState has the values of a widget's declarations that are
// resolved after all of them have been read.
type cssState struct {
// env is the length environment of the style pass.
env *css.LengthEnv
display string
hideText bool // a large negative text-indent, which moves the text out of view
zeroScale bool // a transform scales the box to nothing (as scaleX(0)), so it is not shown
clippedOut bool // a clip (or clip-path) to nothing hides it (see zeroAreaClip)
// intrinsicWidth and intrinsicHeight are the contain-intrinsic sizes:
// the sizes of the content of a box with size containment.
intrinsicWidth, intrinsicHeight *units.Value
// bgCurrentColor is whether the background color is currentcolor,
// the color of the element as it is styled (as the masked chevrons of
// the menus of MDN), which was transparent.
bgCurrentColor bool
visibility string // the visibility property, if any
width *units.Value
heightFit bool // a height of fit-content (or max- or min-content)
height *units.Value
minWidth *units.Value
minHeight *units.Value
maxWidth *units.Value
maxHeight *units.Value
margin [4]*units.Value // top, right, bottom, left; nil for auto
marginAuto [4]bool
lineHeight string
borderBox bool
flexGrow float32
hasGrow bool
flexShrink float32
hasShrink bool
flexBasis string // the flex-basis, or "" if it is not set
alignSelf string
alignItems string
background image.Image
hasBg bool
mask *cssMask
bgImage *cssMask // the background image, with its size, position and repeat
borderCollapse bool
legacyCenter bool
verticalAlign string
// overflowHidden is whether the overflow in each dimension is hidden.
overflowHidden [2]bool
}
// browserStyler adds the styler for the CSS declarations of the given node
// to the given widget.
func (c *Context) browserStyler(node *html.Node, w core.Widget, decls []*cssDecl) {
wb := w.AsWidget()
_, isText := w.(*core.Text)
isFrame := frameOf(w) != nil
plain := isText || isFrame // widgets whose look is all from CSS
tag := ""
if node != nil {
tag = node.Data
}
if c.blocks == nil {
c.blocks = map[core.Widget]*blockState{}
}
bs := &blockState{}
c.blocks[w] = bs
if tag == "ul" || tag == "ol" || tag == "menu" || tag == "dir" {
ls := c.declaration(node, "list-style-type") + " " + c.declaration(node, "list-style")
bs.markers = !strings.Contains(ls, "none")
}
var trBg image.Image // background of a table row, for its cells
isCell := (tag == "td" || tag == "th") && node.Parent != nil && node.Parent.Data == "tr"
if isCell {
if bg := c.declaration(node.Parent, "background-color"); bg != "" {
trBg = css.ParseColor(bg)
}
}
// (in the state of the block, as they are compiled again when the
// declarations of the element change; see Context.Restyle)
bs.ops = c.compileDecls(decls)
bs.inherit = c.inlineInheritedOps(node, wb)
wb.FinalStyler(func(s *styles.Style) {
if bs.hidden { // after the abilities of the widget (as scrolling)
setHiddenAbilities(s)
}
})
wb.Styler(func(s *styles.Style) {
pw, _ := wb.Parent.(core.Widget)
var ps *styles.Style
var pbs *blockState
if pw != nil {
ps = &pw.AsWidget().Styles
pbs = c.blocks[pw]
}
if c.Zoom > 0 {
s.Zoom = c.Zoom // (inherited, but set on each for widgets outside of the page)
}
fsz := core.AppearanceSettings.FontSize / 100
if plain {
// Only the inherited and CSS styles apply,
// not the Cogent Core styles of the widget.
if ps != nil {
s.Text.LineHeight = ps.Text.LineHeight
s.Font.Size = ps.Font.Size
s.Font.Size.Value /= fsz
s.Font.Weight = ps.Font.Weight
s.Font.Slant = ps.Font.Slant
s.Font.Family = ps.Font.Family
s.Font.CustomFont = ps.Font.CustomFont
}
s.Gap.Zero()
s.Padding.Zero()
s.Margin.Zero()
s.Grow.Set(0, 0)
s.Overflow.Set(styles.OverflowVisible)
if isFrame {
// content that overflows a box is shown, unless the
// overflow is hidden or scrolls
s.NoClip = true
}
if isText {
s.Text.WhiteSpace = text.WrapAsNeeded
}
if ps != nil { // white-space and text-align are inherited in CSS
s.Text.WhiteSpace = ps.Text.WhiteSpace
s.Text.Align = ps.Text.Align
}
}
if tag == "" && isText {
s.Text.WhiteSpace = text.WrapAsNeeded
if ps != nil { // white-space and text-align are inherited in CSS
s.Text.WhiteSpace = ps.Text.WhiteSpace
s.Text.Align = ps.Text.Align
// the lines of the text of a block are clamped by it, and
// its text is cut with an ellipsis when it clips it
s.Text.LineClamp = ps.Text.LineClamp
s.Text.Ellipsis = ps.Text.Ellipsis && ps.Overflow.X != styles.OverflowVisible
}
}
if tag != "" && isText { // texts for elements (as pre) fill their blocks
s.GrowWrap = false
}
st := &cssState{display: c.displayOf(node), env: css.DefaultLengthEnv()}
env := st.env
if node == nil { // anonymous text or block
st.display = bs.display
if st.display == "" && isFrame {
st.display = "block"
}
}
if trBg != nil {
st.background, st.hasBg = trBg, true
}
if ps != nil { // for calc()
uc := &ps.UnitContext
if dp := uc.Dots(units.UnitDp); dp > 0 {
env.Em = float64(uc.FontEm / dp)
env.Vw = float64(uc.Vpw / dp / 100)
env.Vh = float64(uc.Vph / dp / 100)
}
}
if c.MediaHeight > 0 { // (of the viewport, not of the scene)
env.Vh, env.FixedVh = float64(c.MediaHeight)/100, true
}
env.VhUsed = &c.viewportHeightUsed
env.Rem = float64(c.rootFontSize())
env.Ch = func() float64 { // of the font of the element as it is styled
em := env.Em
if s.Font.Size.Unit == units.UnitDp && s.Font.Size.Value > 0 {
em = float64(s.Font.Size.Value)
}
var sh shaped.Shaper
if wb.Scene != nil {
sh = wb.Scene.TextShaper()
}
return css.ChOf(sh, s, em)
}
env.FixedVh = c.MediaHeight > 0
if env.FixedVh {
env.Vh = float64(c.MediaHeight / 100)
}
// the container query units, of the container of the element
env.Cqw, env.Cqh = containerUnits(w, env.Vw, env.Vh)
if tag == "body" && c.declaration(node, "font-size") == "" {
// the font size of the html element (which has no widget)
if rf := c.rootFontSize(); rf != 16 {
for _, op := range c.compileCSS("font-size", fmt.Sprintf("%gpx", rf)) {
op(st, s, ps)
}
}
}
if pbs != nil { // pointer-events is inherited (not the hidden of visibility)
s.SetAbilities(pbs.noPointer, abilities.NoPointerEvents)
} else if ps != nil {
s.SetAbilities(ps.Abilities.HasFlag(abilities.NoPointerEvents), abilities.NoPointerEvents)
}
for _, op := range bs.inherit {
op(st, s, ps)
}
for _, op := range bs.ops {
op(st, s, ps)
}
if isCell && s.Float != styles.FloatNone {
// A floated cell of a row is made a block in an anonymous cell
// in browsers, which contains it, so it stays in the row with
// all of its content: it is not floated out of it (as the
// float:left of the #bodyCell of the emails of DHL, which only
// showed their header, in a row as high as that).
s.Float = styles.FloatNone
}
if node != nil {
st.display = c.displayOf(node)
}
bs.noPointer = s.Abilities.HasFlag(abilities.NoPointerEvents) // (as of pointer-events)
// the spacing of the page is that of its CSS, not scaled by the
// Spacing setting, which applies to Cogent Core widgets (for all of
// the widgets of the page: its images, svgs and form controls too)
s.FixedSpacing = true
c.resolveCSS(wb, node, st, s, ps, bs, pbs)
if node != nil && node.Type == html.ElementNode && st.display == "inline-block" && c.isInlineBox(node) {
if d := strings.TrimSpace(c.declaration(node, "display")); d == "" || d == "inline" {
// an inline element that is a box (see isInlineBox) does not
// change the height of its line by its vertical padding and
// border, as in CSS (as the padded links of the sidebar of
// daringfireball.net, in lines as high as their text)
// (in dots when the units are converted)
lessBy := func(m units.Value, by ...units.Value) units.Value {
return units.Value{Custom: func(uc *units.Context) float32 {
v := m.ToDots(uc)
for _, b := range by {
v -= b.ToDots(uc)
}
return v
}}
}
s.Margin.Top = lessBy(s.Margin.Top, s.Padding.Top, s.Border.Width.Top)
s.Margin.Bottom = lessBy(s.Margin.Bottom, s.Padding.Bottom, s.Border.Width.Bottom)
}
}
if node != nil && isButtonNode(node) && c.declaration(node, "justify-content") == "" {
// the content of a button is aligned by its text-align (center
// by default), and at the start of one with a display of flex
// or grid (as the jump button of pkg.go.dev, which is left
// aligned with both)
switch c.declaration(node, "display") {
case "flex", "inline-flex", "grid", "inline-grid":
s.Justify.Content = styles.Start
default:
if s.Direction == styles.Column {
// the content of a button that is a block is in the
// middle of its height, as in browsers, and its text is
// aligned by its text-align (as the listen buttons of
// npr.org, of text-align: left, whose labels were at
// their tops)
s.Justify.Content = styles.Center
break
}
switch s.Text.Align {
case text.Center:
s.Justify.Content = styles.Center
case text.End:
s.Justify.Content = styles.End
default:
s.Justify.Content = styles.Start
}
}
}
if s.ZIndex != 0 && s.Position == styles.PositionStatic && (pbs == nil || !isFlexOrGrid(pbs.display)) {
// as in CSS, the z-index of a static element only applies to
// flex and grid items (as the site header of pkg.go.dev, over
// the sticky header of the page)
s.ZIndex = 0
}
if tag == "body" && st.hasBg && pw != nil { // the canvas has the background of the body
pw.AsWidget().Styles.Background = st.background
}
})
}
// display returns the display of the given widget.
func (c *Context) display(w core.Widget) string {
if bs := c.blocks[w]; bs != nil {
return bs.display
}
return ""
}
// isFlexOrGrid returns whether the given display is that of a flex or grid
// container, whose items are stacked by their z-index (see
// [styles.Style.ZIndex]) even if they are not positioned.
func isFlexOrGrid(d string) bool {
switch d {
case "flex", "inline-flex", "grid", "inline-grid":
return true
}
return false
}
// isBlockDisplay returns whether the given display is block-level.
func isBlockDisplay(d string) bool {
switch d {
case "block", "list-item", "flex", "grid", "table", "flow-root":
return true
}
return false
}
// inlineInheritedOps returns the style operations of the inherited
// properties of the inline elements that the given element is in, between
// it and the element of its parent widget, outermost first. These have no
// widgets of their own (they are in the text of a run), but their
// inherited properties apply to the widgets of their children, as the font
// size of the edit links of Wikipedia, which are inline blocks.
func (c *Context) inlineInheritedOps(node *html.Node, wb *core.WidgetBase) []styleOp {
if node == nil || node.Type != html.ElementNode {
return nil
}
pw, _ := wb.Parent.(core.Widget)
if pw == nil {
return nil
}
pn := NodeOf(pw)
var chain []*html.Node
for p := node.Parent; p != nil && p != pn && p.Type == html.ElementNode; p = p.Parent {
switch c.displayOf(p) {
case "", "inline", "contents":
chain = append(chain, p)
continue
}
break
}
var ops []styleOp
for ri := len(chain) - 1; ri >= 0; ri-- {
c0 := chain[ri]
var inh []*cssDecl
for _, d := range c.declarations(c0) {
if css.InheritedProperties[d.Property] {
inh = append(inh, d)
}
}
ops = append(ops, c.compileDecls(inh)...)
}
return ops
}
// isButtonNode returns whether the given node is a button: a button element,
// or an input of a type of submit, button or reset.
func isButtonNode(n *html.Node) bool {
if n.Type != html.ElementNode {
return false
}
switch n.Data {
case "button":
return true
case "input":
switch strings.ToLower(GetAttr(n, "type")) {
case "submit", "button", "reset":
return true
}
}
return false
}
// setHiddenAbilities sets the abilities of a widget of an element with
// visibility: hidden, which gets no events, but whose children get them
// when they are visible (visibility: visible), as in CSS (as the items of
// the other ways to sign in with two factors on GitHub, in a hidden list,
// which could not be clicked), unlike those of an element that is clipped
// out or not rendered at all (no abilities).
func setHiddenAbilities(s *styles.Style) {
s.Abilities = 0
s.SetAbilities(true, abilities.NoPointerEvents)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"strconv"
"strings"
"cogentcore.org/core/core"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/tree"
"golang.org/x/net/html"
)
// handleTable handles a table element.
func handleTable(ctx *Context) core.Widget {
w := New[core.Frame](ctx)
ctx.NewParent = w
if ctx.tables == nil {
ctx.tables = map[*html.Node]*core.Frame{}
}
ctx.tables[ctx.Node] = w
ctx.TableParent = w
cols := ctx.tableColumns(ctx.Node)
w.SetProperty("cols", cols)
if ctx.declaration(ctx.Node, "width") == "" && ctx.hasPercentColumns(ctx.Node) {
// An auto-width table with percentage columns is as wide as it needs
// to be to give them their shares, which is approximated by filling
// the width that it has (in which they grow up to their shares).
w.FinalStyler(func(s *styles.Style) { s.Grow.X = 1 })
}
w.Styler(func(s *styles.Style) {
s.Display = styles.Grid
s.Columns = cols
})
return w
}
// tableFor returns the widget of the table that the given node is in.
func (c *Context) tableFor(n *html.Node) core.Widget {
if t := ancestorTable(n); t != nil {
if w := c.tables[t]; w != nil {
return w
}
}
if c.TableParent != nil {
return c.TableParent
}
return c.Parent()
}
// hasPercentColumns returns whether the given table has cells with
// percentage widths (in its rows, not in tables in it).
func (c *Context) hasPercentColumns(table *html.Node) bool {
var rows func(n *html.Node) bool
rows = func(n *html.Node) bool {
for k := n.FirstChild; k != nil; k = k.NextSibling {
switch k.Data {
case "thead", "tbody", "tfoot":
if rows(k) {
return true
}
case "tr":
for cell := k.FirstChild; cell != nil; cell = cell.NextSibling {
if (cell.Data == "td" || cell.Data == "th") && strings.HasSuffix(strings.TrimSpace(c.declaration(cell, "width")), "%") {
return true
}
}
}
}
return false
}
return rows(table)
}
// tableColumns returns the number of columns of the given table, the
// largest number of cells (with their column spans) in any of its rows,
// not counting those that are not displayed.
func (c *Context) tableColumns(table *html.Node) int {
cols := 0
var rows func(n *html.Node)
rows = func(n *html.Node) {
for k := n.FirstChild; k != nil; k = k.NextSibling {
switch k.Data {
case "thead", "tbody", "tfoot":
rows(k)
case "tr":
n := 0
for cell := k.FirstChild; cell != nil; cell = cell.NextSibling {
if (cell.Data == "td" || cell.Data == "th") && c.displayOf(cell) != "none" {
span, err := strconv.Atoi(GetAttr(cell, "colspan"))
if err != nil || span < 1 {
span = 1
}
n += span
}
}
cols = max(cols, n)
}
}
}
rows(table)
return max(cols, 1)
}
// handleCell handles a th or td element.
func handleCell(ctx *Context, _ string) core.Widget {
ctx.BlockParent = ctx.tableFor(ctx.Node)
ctx.inlineParent = nil
span, err := strconv.Atoi(GetAttr(ctx.Node, "colspan"))
if err != nil || span < 1 {
span = 1
}
w := New[core.Frame](ctx)
ctx.NewParent = w
// Columns grow by the size of their content, as in browsers, for
// which the length of the text is a proxy, only when the table
// has a width to grow into.
weight := float32(max(len([]rune(strings.TrimSpace(nodeText(ctx.Node)))), 1))
rspan, err := strconv.Atoi(GetAttr(ctx.Node, "rowspan"))
if err != nil || rspan < 1 {
rspan = 1
}
// a percentage width of a cell in a table that fills its width
// (see handleTable) is the width of its column
pct := float32(0)
if table := ancestorTable(ctx.Node); table != nil && ctx.declaration(table, "width") == "" && ctx.hasPercentColumns(table) {
if v, ok := strings.CutSuffix(strings.TrimSpace(ctx.declaration(ctx.Node, "width")), "%"); ok {
if f, err := strconv.ParseFloat(v, 32); err == nil {
pct = float32(f)
}
}
}
// the columns of a table with the fixed layout are as wide as its
// columns (col) say, not as its content, which wraps (as the diffs of
// Wikipedia, whose long lines are in columns of 48%)
// (and columns with widths in pixels are that wide)
fixed, fixedWeight, fixedPct, fixedPx := false, float32(0), float32(0), float32(0)
if table := ancestorTable(ctx.Node); table != nil && strings.EqualFold(strings.TrimSpace(ctx.declaration(table, "table-layout")), "fixed") {
fixed = true
cols, pxs := ctx.columnWidths(table)
start := cellColumn(ctx.Node)
allPct, allPx := true, true
for c := start; c < start+span; c++ {
if c < len(cols) && cols[c] > 0 {
fixedWeight += cols[c]
fixedPct += cols[c]
} else {
fixedWeight += 1
allPct = false
}
if c < len(pxs) && pxs[c] > 0 {
fixedPx += pxs[c]
} else {
allPx = false
}
}
if !allPct {
fixedPct = 0
}
if !allPx {
fixedPx = 0
}
}
w.FinalStyler(func(s *styles.Style) {
switch {
case pct >= 100:
// all of the width that the other columns leave it, which is
// what browsers give it (as the text of the message boxes of
// Wikipedia, beside their icons, which were as wide as their
// tables, which were wider than the article, over the column
// beside it)
s.Grow.X, s.Shrink.X = 1e6, 1
s.Min.X.Zero()
case pct > 0:
s.Min.X, s.Max.X = units.Pw(pct), units.Pw(pct)
s.BoxSizing = styles.BoxBorderBox
}
if fixed {
s.Overflow.X = styles.OverflowAuto // no min-content width (it wraps)
s.ScrollbarWidth.Zero()
s.Grow.X, s.Shrink.X = fixedWeight, 1
if fixedPct > 0 { // the percentage of the table of its columns
s.Min.X, s.Max.X = units.Pw(fixedPct), units.Pw(fixedPct)
s.BoxSizing = styles.BoxBorderBox
}
if fixedPx > 0 { // the width of its columns
s.Min.X, s.Max.X = units.Dp(fixedPx), units.Dp(fixedPx)
s.BoxSizing = styles.BoxBorderBox
s.Grow.X = 0
}
}
if span > 1 {
s.ColSpan = span
}
if rspan > 1 {
s.RowSpan = rspan
}
if s.Grow.X > 0 && !fixed && pct < 100 {
s.Grow.X = weight / float32(span)
}
})
return w
}
// columnWidths returns the widths of the columns of the given table from
// its col elements (with span): as percentages, or 0 for those without
// one (or with a width that is not a percentage), and in pixels (as
// width="52" of the line numbers of the diffs of GitHub), or 0.
func (c *Context) columnWidths(table *html.Node) ([]float32, []float32) {
var ws, pxs []float32
var walk func(n *html.Node)
walk = func(n *html.Node) {
for k := n.FirstChild; k != nil; k = k.NextSibling {
if k.Type != html.ElementNode {
continue
}
switch k.Data {
case "colgroup":
walk(k)
case "col":
span, err := strconv.Atoi(GetAttr(k, "span"))
if err != nil || span < 1 {
span = 1
}
w := strings.TrimSpace(c.declaration(k, "width"))
if w == "" {
w = GetAttr(k, "width")
}
pct, px := float32(0), float32(0)
if v, ok := strings.CutSuffix(w, "%"); ok {
if f, err := strconv.ParseFloat(v, 32); err == nil {
pct = float32(f)
}
} else if f, err := strconv.ParseFloat(strings.TrimSuffix(w, "px"), 32); err == nil && f > 0 {
px = float32(f)
}
for range span {
ws = append(ws, pct)
pxs = append(pxs, px)
}
}
}
}
walk(table)
return ws, pxs
}
// cellColumn returns the index of the first column of the given cell in
// its row, from the column spans of the cells before it.
func cellColumn(cell *html.Node) int {
col := 0
for k := cell.PrevSibling; k != nil; k = k.PrevSibling {
if k.Type == html.ElementNode && (k.Data == "td" || k.Data == "th") {
span, err := strconv.Atoi(GetAttr(k, "colspan"))
if err != nil || span < 1 {
span = 1
}
col += span
}
}
return col
}
// tableImageWidth returns the width attribute of the first image in the
// given element (other than in its caption), or 0 if it has none.
func tableImageWidth(n *html.Node) float32 {
for c := n.FirstChild; c != nil; c = c.NextSibling {
if c.Type != html.ElementNode || c.Data == "figcaption" || c.Data == "caption" {
continue
}
if c.Data == "img" {
w, err := strconv.ParseFloat(GetAttr(c, "width"), 32)
if err != nil {
return 0
}
return float32(w)
}
if w := tableImageWidth(c); w > 0 {
return w
}
}
return 0
}
// ancestorTable returns the table element that the given cell is in.
func ancestorTable(n *html.Node) *html.Node {
for p := n.Parent; p != nil; p = p.Parent {
if p.Data == "table" {
return p
}
}
return nil
}
// tableRows is the state of the rows of a table as they are read, for the
// slots of the rows below that cells with row spans take (see
// [Context.endTableRow]).
type tableRows struct {
cols int
spans []int // for each column, the number of rows below that it takes
}
// endTableRow fills the rest of the given row of a table (tr), after its
// cells, with empty cells, so that the cells of the next row are in the
// next row, as in HTML, and not in the slots that this row leaves empty
// (as the major debates table of Wikipedia, whose header row of parties
// has fewer cells than its columns). The slots of the row that cells
// above it take with their row spans are not filled.
func (c *Context) endTableRow(tr *html.Node) {
table := ancestorTable(tr)
if table == nil {
return
}
if c.tableRowState == nil {
c.tableRowState = map[*html.Node]*tableRows{}
}
st := c.tableRowState[table]
if st == nil {
cols := c.tableColumns(table)
st = &tableRows{cols: cols, spans: make([]int, cols)}
c.tableRowState[table] = st
}
taken := make([]bool, st.cols)
for i, n := range st.spans {
if n > 0 {
taken[i] = true
st.spans[i]--
}
}
col := 0
for cell := tr.FirstChild; cell != nil; cell = cell.NextSibling {
if cell.Type != html.ElementNode || (cell.Data != "td" && cell.Data != "th") || c.displayOf(cell) == "none" {
continue
}
for col < st.cols && taken[col] {
col++
}
span, err := strconv.Atoi(GetAttr(cell, "colspan"))
if err != nil || span < 1 {
span = 1
}
rspan, err := strconv.Atoi(GetAttr(cell, "rowspan"))
if err != nil || rspan < 1 {
rspan = 1
}
for k := col; k < col+span && k < st.cols; k++ {
taken[k] = true
if rspan > 1 {
st.spans[k] = rspan - 1
}
}
col += span
}
empty := 0
for _, t := range taken {
if !t {
empty++
}
}
w := c.tableFor(tr)
for range empty {
filler := core.NewFrame(w)
filler.SetName("row-filler")
tree.SetUniqueName(filler)
filler.Styler(func(s *styles.Style) {
s.Padding.Zero()
s.Margin.Zero()
s.Grow.Set(0, 0)
})
}
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"slices"
"strings"
"golang.org/x/net/html"
)
// ExtractText recursively extracts all of the text from the children
// of the given [*html.Node], adding any appropriate inline markup for
// formatted text. It adds any non-text elements to the given [core.Widget]
// using [readHTMLNode]. It should not be called on text nodes themselves;
// for that, you can directly access the [html.Node.Data] field. It uses
// the given page URL for context when resolving URLs, but it can be
// omitted if not available.
func ExtractText(ctx *Context) string {
if ctx.Node.FirstChild == nil {
return ""
}
tx, _ := extractTextExclude(ctx, ctx.Node.FirstChild)
return tx
}
// ExtractTextExclude recursively extracts all of the text from the children
// of the given [*html.Node], adding any appropriate inline markup for
// formatted text. It adds any non-text elements to the given [core.Widget]
// using [readHTMLNode], except those types listed in the excludeSubs list.
// If one of those types is encountered, it is returned.
func ExtractTextExclude(ctx *Context, excludeSubs ...string) (string, *html.Node) {
if ctx.Node.FirstChild == nil {
return "", nil
}
return extractTextExclude(ctx, ctx.Node.FirstChild, excludeSubs...)
}
func extractTextExclude(ctx *Context, n *html.Node, excludeSubs ...string) (string, *html.Node) {
str := ""
if n.Type == html.TextNode {
str += n.Data
}
it := isText(n)
if !it {
if slices.Contains(excludeSubs, n.Data) {
return str, n
}
readHTMLNode(ctx, ctx.Parent(), n)
// readHTMLNode already handles children and siblings, so we return.
// TODO: for something like [TestButtonInHeadingBug] this will not
// have the right behavior, but that is a rare use case and this
// heuristic is much simpler.
return str, nil
}
isBr := n.Type == html.ElementNode && n.Data == "br"
if n.FirstChild != nil {
start, end := nodeString(n)
tx, excl := extractTextExclude(ctx, n.FirstChild, excludeSubs...)
str = start + tx + end
if excl != nil {
return str, excl
}
} else if isBr {
// A <br> has no children, but it must be kept, both for
// the rendered text and for HTML generated from it (see [cogentcore.org/core/htmlcore/tohtml.Widget]).
str = "<br>"
}
if n.NextSibling != nil {
tx, excl := extractTextExclude(ctx, n.NextSibling, excludeSubs...)
if isBr {
// Markdown puts a newline after each <br>, which would
// otherwise be a second line break in pre-wrapped text.
tx = strings.TrimPrefix(tx, "\n")
}
str += tx
if excl != nil {
return str, excl
}
}
return str, nil
}
// nodeString returns the given node as starting and ending strings in the format:
//
// <tag attr0="value0" attr1="value1">
//
// and
//
// </tag>
//
// It returns "", "" if the given node is not an [html.ElementNode]
func nodeString(n *html.Node) (start, end string) {
if n.Type != html.ElementNode {
return
}
tag := n.Data
start = "<" + tag
for _, a := range n.Attr {
start += " " + a.Key + "=" + `"` + a.Val + `"`
}
start += ">"
end = "</" + tag + ">"
return
}
// textTags are all of the node tags that result in a true return value for [isText].
var textTags = []string{
"a", "abbr", "b", "bdi", "bdo", "br", "cite", "code", "data", "dfn",
"em", "i", "kbd", "mark", "q", "rp", "rt", "ruby", "s", "samp", "small",
"span", "strong", "sub", "sup", "time", "u", "var", "wbr",
}
// isText returns true if the given node is a [html.TextNode] or
// an [html.ElementNode] designed for holding text (a, span, b, code, etc),
// and false otherwise.
func isText(n *html.Node) bool {
if n.Type == html.TextNode {
return true
}
if n.Type == html.ElementNode {
tag := n.Data
return slices.Contains(textTags, tag)
}
return false
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"io/fs"
"net/http"
"net/url"
"strings"
)
// parseRelativeURL parses the given raw URL relative to the given base URL.
func parseRelativeURL(rawURL, base string) (*url.URL, error) {
u, err := url.Parse(rawURL)
if err != nil {
return u, err
}
b, err := url.Parse(base)
if err != nil {
return u, err
}
return b.ResolveReference(u), nil
}
// GetURLFromFS can be used for [Context.GetURL] to get
// resources from the given file system.
func GetURLFromFS(fsys fs.FS, rawURL string) (*http.Response, error) {
u, err := url.Parse(rawURL)
if err != nil {
return nil, err
}
if u.Scheme != "" {
return http.Get(rawURL)
}
rawURL = strings.TrimPrefix(rawURL, "/")
rawURL, _, _ = strings.Cut(rawURL, "?")
f, err := fsys.Open(rawURL)
if err != nil {
return nil, err
}
return &http.Response{
Status: http.StatusText(http.StatusOK),
StatusCode: http.StatusOK,
Body: f,
ContentLength: -1,
}, nil
}
// ParseRelativeURL parses the given raw URL relative to the given base URL.
func ParseRelativeURL(rawURL, base string) (*url.URL, error) {
return parseRelativeURL(rawURL, base)
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"strings"
"cogentcore.org/core/core"
"golang.org/x/net/html"
)
// The video element (see handleVideo) is a replaced element: a box of the
// size of its video, or of its poster image, which is 300 by 150 without
// either, as in browsers. Its children (its source and track elements, and
// the content for browsers without video) are not shown.
//
// On the web (js), the box is a [video.Video], which is a video element of
// the browser, with its attributes (autoplay, muted, loop, controls and
// poster). Elsewhere, it is a [core.Image] of the poster (if any), with
// the URL of the video in its "video-src" property (see [VideoSourceOf]),
// as htmlcore does not decode video itself there (which needs FFmpeg):
// an app that plays videos (as a web browser) shows the frames of a
// [video.Playback] in the image, from a widget handler (see
// [Context.WidgetHandlers]).
// VideoDefaultWidth and VideoDefaultHeight are the size in CSS pixels of
// a video element without a width or height, before its size is known,
// as in browsers.
const (
VideoDefaultWidth = 300
VideoDefaultHeight = 150
)
// An audio element (see handleAudio) is displayed only with controls (as
// the bar of a player), as a box of AudioDefaultWidth by AudioDefaultHeight
// CSS pixels unless its CSS sets its size, as in Chrome. It is the box of a
// video element (in which an app plays its audio, with its "video-src"),
// with the "audio" property: on desktop platforms, a [VideoBox] with
// [VideoBox.Audio], without an image. Audio elements that are not
// displayed (without controls, as those that the scripts of pages make)
// are played by an app too, as from its scripts.
const (
AudioDefaultWidth = 300
AudioDefaultHeight = 54
)
// VideoSource returns the absolute URL of the video of the given video
// element (or of the audio of an audio element): its src, or else the src
// of its first source element with one, or "" for none.
func (c *Context) VideoSource(n *html.Node) string {
src := strings.TrimSpace(GetAttr(n, "src"))
for ch := n.FirstChild; src == "" && ch != nil; ch = ch.NextSibling {
if ch.Type == html.ElementNode && ch.Data == "source" {
src = strings.TrimSpace(GetAttr(ch, "src"))
}
}
if src == "" {
return ""
}
if u, err := ParseRelativeURL(src, c.PageURL); err == nil && c.PageURL != "" {
return u.String()
}
return src
}
// VideoSourceOf returns the URL of the video of the given widget, if it is
// the image of a video element (see [Context.VideoSource]), or "".
func VideoSourceOf(w core.Widget) string {
src, _ := w.AsWidget().Property("video-src").(string)
return src
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !js
package htmlengine
import (
"image"
"log/slog"
"strings"
"cogentcore.org/core/core"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/types"
)
// VideoBox is the box of a video element on desktop platforms (see
// video.go), of the size of its video (see [resolver.videoSize]), with an
// [core.Image] in it ([VideoBox.Image]) that shows its poster, and the
// frames of the video, which an app that plays videos shows in it. The
// app can add controls over it (as video.Controls), for which the box is
// positioned (relative), and is rendered as a whole when they change
// ([VideoBox.RenderGroup]), as they are partly transparent over the image.
type VideoBox struct {
core.Frame
// Image shows the poster of the video, and its frames (nil for Audio).
Image *core.Image
// Audio is whether it is the box of an audio element with controls,
// a bar (see handleAudio).
Audio bool
}
// (the type is registered when the package is initialized, as typegen
// does, not when the first one is made, as when a page is read in another
// goroutine, which would change the types while others read them)
var _ = types.AddType(&types.Type{Name: "cogentcore.org/core/htmlcore/htmlengine.VideoBox", IDName: "video-box",
Doc: "VideoBox is the box of a video element on desktop platforms.", Embeds: []types.Field{{Name: "Frame"}}, Instance: &VideoBox{}})
func (vb *VideoBox) Init() {
vb.Frame.Init()
vb.Styler(func(s *styles.Style) {
s.Position = styles.PositionRelative // (the containing block of its image)
s.Padding.Zero()
s.Gap.Zero()
})
}
// RenderGroup returns true: the box is rendered as a whole when any widget
// in it needs to be rendered (see [VideoBox]).
func (vb *VideoBox) RenderGroup() bool { return true }
// SetVideoSize sets the size of the video, which is the size of the box,
// or of its aspect when only its width or its height is set by its CSS
// (as the size of a video once it is opened, which updates the box).
func (vb *VideoBox) SetVideoSize(width, height int) {
vb.SetProperty("video-size", math32.Vec2(float32(width), float32(height)))
}
// handleAudio handles an audio element with controls: a [VideoBox] that
// is Audio, without an image, with the URL of the audio in its "video-src"
// property, for an app to play it with its controls (see video.go).
func handleAudio(ctx *Context) core.Widget {
vb := New[VideoBox](ctx)
vb.Audio = true
vb.SetProperty("audio", true)
vb.SetProperty("video-src", ctx.VideoSource(ctx.Node))
vb.SetVideoSize(0, 0) // (sized as audio, see [resolver.audioSize])
return vb
}
// handleVideo handles a video element: a [VideoBox] with an image of its
// poster, of the default size without one, with the URL of the video in
// its "video-src" property, for an app to play it (see video.go).
func handleVideo(ctx *Context) core.Widget {
vb := New[VideoBox](ctx)
vb.SetProperty("video-src", ctx.VideoSource(ctx.Node))
vb.SetVideoSize(0, 0) // the default size
img := core.NewImage(vb)
vb.Image = img
img.Styler(func(s *styles.Style) {
// it fills the box, with the video contained in it, keeping its
// aspect ratio, as in browsers
s.Position = styles.PositionAbsolute
s.Inset.Set(units.Zero())
s.InsetSet.Set(true)
s.ObjectFit = styles.FitContain
s.Min.Zero()
})
img.NaturalDp = true // in CSS px (see core.Image.NaturalDp)
poster := strings.TrimSpace(GetAttr(ctx.Node, "poster"))
if poster == "" {
return vb
}
load := func() image.Image {
im, err := readImage(ctx, poster)
if err != nil || im == nil {
slog.Debug("error loading the poster of a video", "url", poster, "err", err)
return nil
}
return im
}
setPoster := func(im image.Image) {
img.SetImage(im)
sz := im.Bounds().Size()
vb.SetVideoSize(sz.X, sz.Y) // until the video is opened
}
if !ctx.DelayedImageLoad {
if im := load(); im != nil {
setPoster(im)
}
return vb
}
go func() {
if im := load(); im != nil && vb.AsyncLockIfShown() {
setPoster(im)
vb.Update()
vb.AsyncUnlock()
}
}()
return vb
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"bytes"
"io"
"log/slog"
"strings"
"sync"
"cogentcore.org/core/htmlcore/css"
"cogentcore.org/core/styles"
"cogentcore.org/core/text/fonts"
"cogentcore.org/core/text/rich"
douceur "github.com/aymerick/douceur/css"
)
// FontDecoder is, if set, a function that decodes the data of web fonts in formats that the
// text shapers do not read (as WOFF2) into TrueType or OpenType data, for
// [Context.WebFonts]. Fonts that it cannot decode (with an error) are not
// used.
var FontDecoder func(data []byte) ([]byte, error)
// maxWebFont is the largest size of a web font that is loaded.
const maxWebFont = 8 << 20
// webFontURLs are the URLs of the web fonts that have been loaded (or that
// could not be), as they are loaded once for all pages.
var webFontURLs struct {
sync.Mutex
loaded map[string]bool
}
// addFontFace loads the web font of the given declarations of an
// @font-face rule, if [Context.WebFonts]: the first of its sources that
// can be loaded, unless its unicode-range does not include Latin letters
// (as for the subsets of fonts for other scripts, which are not used).
func (c *Context) addFontFace(decls []*douceur.Declaration) {
var family, src, urange string
for _, d := range decls {
switch strings.ToLower(strings.TrimSpace(d.Property)) {
case "font-family":
family = strings.Trim(strings.TrimSpace(d.Value), `"'`)
case "src":
src = d.Value
case "unicode-range":
urange = d.Value
}
}
if family == "" || src == "" || (urange != "" && !css.UnicodeRangeHas(urange, 'A')) {
return
}
for _, s := range css.SplitTopLevel(src, ',') {
u, format := css.FontSource(s)
if u == "" {
continue // local() fonts, which are not used
}
switch format {
case "", "woff", "woff2", "truetype", "opentype", "woff-variations", "woff2-variations", "truetype-variations", "opentype-variations":
default:
continue // as svg and embedded-opentype
}
pu, err := parseRelativeURL(u, c.cssBaseURL())
if err != nil {
continue
}
if c.loadWebFont(family, pu.String()) {
return
}
}
}
// loadWebFont loads the web font of the given family at the given URL,
// once for all pages, and returns whether it is loaded.
func (c *Context) loadWebFont(family, u string) bool {
key := strings.ToLower(family) + " " + u
webFontURLs.Lock()
if webFontURLs.loaded == nil {
webFontURLs.loaded = map[string]bool{}
}
loaded, tried := webFontURLs.loaded[key]
webFontURLs.Unlock()
if tried {
return loaded
}
loaded = c.fetchWebFont(family, u)
webFontURLs.Lock()
webFontURLs.loaded[key] = loaded
webFontURLs.Unlock()
return loaded
}
// fetchWebFont gets the web font at the given URL and adds it for the
// given family, returning whether it did.
func (c *Context) fetchWebFont(family, u string) bool {
resp, err := Get(c, u)
if err != nil {
slog.Debug("htmlcore: getting web font", "url", u, "err", err)
return false
}
defer resp.Body.Close()
data, err := io.ReadAll(io.LimitReader(resp.Body, maxWebFont+1))
if err != nil || len(data) > maxWebFont {
return false
}
if bytes.HasPrefix(data, []byte("wOF2")) || !css.IsFontData(data) {
if FontDecoder == nil {
return false
}
if data, err = FontDecoder(data); err != nil {
slog.Debug("htmlcore: decoding web font", "url", u, "err", err)
return false
}
}
if err := fonts.AddWebFont(family, data); err != nil {
slog.Debug("htmlcore: adding web font", "url", u, "err", err)
return false
}
return true
}
// setFontFamily sets the font family of the given style to that of the
// given value of font-family: the first web font of it that is loaded (as
// the Custom family, with its generic family after it), if
// [Context.WebFonts], or else the given generic family.
func (c *Context) setFontFamily(s *styles.Style, v string, generic rich.Family) {
s.Font.Family = generic
if !c.WebFonts {
return
}
if wf := css.WebFontFamily(v); wf != "" {
s.Font.Family = rich.Custom
s.Font.CustomFont = rich.FontName(wf + ", " + rich.Settings.Family(generic))
}
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmlengine
import (
"bytes"
"log/slog"
"strings"
"unicode"
"cogentcore.org/core/core"
"cogentcore.org/core/system"
"github.com/yuin/goldmark/v2/ast"
"github.com/yuin/goldmark/v2/parser"
"github.com/yuin/goldmark/v2/text"
)
// WikilinkHandler is a function that converts wikilink text to
// a corresponding URL and label text. If it returns "", "", the
// handler will be skipped in favor of the next possible handlers.
// Wikilinks are of the form [[wikilink text]]. Only the text inside
// of the brackets is passed to the handler. If there is additional
// text directly after the closing brackets without spaces or punctuation,
// it will be appended to the label text after the handler is run
// (ex: [[widget]]s).
type WikilinkHandler func(text string) (url string, label string)
// AddWikilinkHandler adds a new [WikilinkHandler] to [Context.WikilinkHandlers].
// If it returns "", "", the next handlers will be tried instead.
// The functions are tried in sequential ascending order.
func (c *Context) AddWikilinkHandler(h WikilinkHandler) {
c.WikilinkHandlers = append(c.WikilinkHandlers, h)
}
// GoDocWikilink returns a [WikilinkHandler] that converts wikilinks of the form
// [[prefix:identifier]] to a pkg.go.dev URL starting at pkg. For example, with
// prefix="doc" and pkg="cogentcore.org/core", the wikilink [[doc:core.Button]] will
// result in the URL "https://pkg.go.dev/cogentcore.org/core/core#Button".
func GoDocWikilink(prefix string, pkg string) WikilinkHandler {
return func(text string) (url string, label string) {
if !strings.HasPrefix(text, prefix+":") {
return "", ""
}
text = strings.TrimPrefix(text, prefix+":")
// pkg.go.dev uses fragments for first dot within package
t := strings.Replace(text, ".", "#", 1)
url = "https://pkg.go.dev/" + pkg + "/" + t
return url, text
}
}
// reportInvalidWikilinks returns whether invalid wikilinks are logged, as
// a reminder to fix them: only when running natively on a desktop
// platform, as while working on the content locally, and not in tests
// (the offscreen platform), on the web, or on mobile, where it is noise.
func reportInvalidWikilinks() bool {
if core.TheApp == nil {
return false
}
switch core.TheApp.Platform() {
case system.MacOS, system.Windows, system.Linux:
return true
}
return false
}
// note: this is from: https://github.com/kensanata/oddmu/blob/main/parser.go
// wikilinkParser is a goldmark inline parser for [[wikilinks]], which
// runs before the link parser and leaves other text starting with [ to it.
type wikilinkParser struct {
ctx *Context
}
func (wp wikilinkParser) Trigger() []byte { return []byte{'['} }
func (wp wikilinkParser) Parse(parent ast.Node, block text.Reader, pc parser.Context) ast.Node {
data, _ := block.PeekLine()
// minimum: [[X]]
if len(data) < 5 || data[1] != '[' || !bytes.Contains(data[2:], []byte("]]")) {
return nil
}
inside, after := getWikilinkText(data)
url, label := runWikilinkHandlers(wp.ctx, inside)
block.Advance(len(inside) + len(after) + 4)
if len(url) == 0 && len(label) == 0 {
if reportInvalidWikilinks() {
slog.Error("invalid wikilink", "link", string(inside))
}
// TODO: we just treat broken wikilinks like plaintext for now, but we should
// make red links instead at some point
return newString(string(inside) + string(after))
}
link := ast.NewLink(text.NewSingleLineValueFromString(string(url), text.IdentityDecoder))
link.AppendChild(newString(string(label) + string(after)))
return link
}
// getWikilinkText gets the wikilink text from the given raw text data starting with [[.
// Inside contains the text inside the [[]], and after contains all of the text
// after the ]] until there is a space or punctuation.
// newString returns a text node with the given literal text.
func newString(s string) *ast.Text {
return ast.NewText(text.NewSingleLineValueFromString(s, text.IdentityDecoder))
}
func getWikilinkText(data []byte) (inside, after []byte) {
i := 2
for ; i < len(data); i++ {
if data[i] == ']' && data[i-1] == ']' {
inside = data[2 : i-1]
continue
}
r := rune(data[i])
// Space or punctuation after ]] means we are done.
if inside != nil && (unicode.IsSpace(r) || unicode.IsPunct(r)) {
break
}
}
after = data[len(inside)+4 : i]
return
}
// runWikilinkHandlers returns the first non-blank URL and label returned
// by [Context.WikilinkHandlers].
func runWikilinkHandlers(ctx *Context, text []byte) (url, label []byte) {
for _, h := range ctx.WikilinkHandlers {
u, l := h(string(text))
if u == "" && l == "" {
continue
}
url, label = []byte(u), []byte(l)
break
}
return
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tohtml
import (
"log/slog"
"os"
"cogentcore.org/core/core"
)
func init() {
if core.GenerateHTML == nil {
core.GenerateHTML = Generate
}
}
// Generate returns the HTML for the given widget (see [Widget]) after
// updating and styling it, for the -generatehtml argument (see
// [core.GenerateHTML]). It exits the program if there is an error.
func Generate(w core.Widget) string {
wb := w.AsWidget()
wb.UpdateTree()
wb.StyleTree()
h, err := Widget(w)
if err != nil {
slog.Error("error generating pre-render HTML", "err", err)
os.Exit(1)
}
return string(h)
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package tohtml converts Cogent Core widgets to HTML, which the core
// tool uses to pre-render apps for a preview while the app loads and for
// SEO purposes. Importing it sets [core.GenerateHTML] to [Generate],
// which the app calls when it runs with the -generatehtml argument.
// The core tool links it into the app for that run, so apps do not need
// to import it themselves.
package tohtml
import (
"bytes"
"encoding/xml"
"fmt"
"reflect"
"slices"
"strconv"
"strings"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/core"
"cogentcore.org/core/styles"
"cogentcore.org/core/svg"
"cogentcore.org/core/tree"
)
// Widget converts the given widget and all of its children to HTML.
// This is not guaranteed to be perfect HTML, and it should not be used as a
// replacement for a Cogent Core app. However, it is good enough to be used as
// a preview or for SEO purposes (see [Generate]). The following
// [tree.NodeBase.Properties] of widgets are used:
// - "tag": the HTML element name.
// - "id": the HTML id, which is otherwise only set for headings.
// - "class": the HTML class.
// - "href" and "src": the corresponding HTML attributes.
// - "data-*": the data attributes of the element (as htmlcore sets them).
// - "html": HTML that is used for the widget and its children instead.
func Widget(w core.Widget) ([]byte, error) {
b := &bytes.Buffer{}
e := xml.NewEncoder(b)
err := toHTML(w, e, b)
if err != nil {
return nil, err
}
return b.Bytes(), nil
}
// htmlElementNames is a map from widget [types.Type.IDName]s to HTML element
// names for cases in which those differ.
var htmlElementNames = map[string]string{
"body": "main", // we are typically placed in a different outer body
"frame": "div",
"text": "p",
"image": "img",
"icon": "svg",
"space": "div",
"separator": "hr",
"text-field": "input",
"spinner": "input",
"slider": "input",
"meter": "progress",
"chooser": "div", // a select element can only contain option elements
"switches": "div",
"switch": "input",
"splits": "div",
"tabs": "div",
"tab": "button",
"tree": "div",
"page": "main",
}
func addAttr(se *xml.StartElement, name, value string) {
if value == "" {
return
}
se.Attr = append(se.Attr, xml.Attr{Name: xml.Name{Local: name}, Value: value})
}
// toHTML is the recursive implementation of [Widget].
func toHTML(w core.Widget, e *xml.Encoder, b *bytes.Buffer) error {
wb := w.AsWidget()
if h, ok := wb.Property("html").(string); ok {
// Custom HTML for this widget and its children (see [Widget]).
err := e.Flush()
if err != nil {
return err
}
b.WriteString(h)
return nil
}
// Text without a tag of its own in a widget with a tag (as the text of an
// element in the browser style of htmlcore) is just its content, and an
// inline container of it is just its children.
_, hasTag := wb.Property("tag").(string)
if tx, ok := w.(*core.Text); ok && !hasTag {
if pw := core.AsWidget(wb.Parent); pw != nil {
if _, ok := pw.Property("tag").(string); ok || strings.HasPrefix(pw.Name, "inline-container") {
if err := e.Flush(); err != nil {
return err
}
// Text of a fixed width (as the marker of a list item) keeps it.
if width, mx := tx.Styles.Min.X, tx.Styles.Max.X; width.Value > 0 && mx.Value == width.Value && mx.Unit == width.Unit {
fmt.Fprintf(b, `<span style="display:inline-block;flex:none;width:%s">`, styles.ToCSSLength(&tx.Styles, width))
b.WriteString(textParagraphReplacer.Replace(tx.Text))
b.WriteString("</span>")
return nil
}
b.WriteString(textParagraphReplacer.Replace(tx.Text))
return nil
}
}
}
if _, ok := w.(*core.Frame); ok && !hasTag && strings.HasPrefix(wb.Name, "inline-container") {
var err error
wb.ForWidgetChildren(func(i int, cw core.Widget, cwb *core.WidgetBase) bool {
err = toHTML(cw, e, b)
return err == nil
})
return err
}
se := &xml.StartElement{}
typ := wb.NodeType()
idName := typ.IDName
se.Name.Local = idName
if tag, ok := wb.Property("tag").(string); ok {
se.Name.Local = tag
}
if se.Name.Local == "tree" { // trees not supported yet
return nil
}
if en, ok := htmlElementNames[se.Name.Local]; ok {
se.Name.Local = en
}
switch typ.Name {
case "cogentcore.org/cogent/canvas.Canvas", "cogentcore.org/cogent/code.Code":
se.Name.Local = "div"
case "cogentcore.org/core/textcore.Editor":
se.Name.Local = "textarea"
}
if se.Name.Local == "textarea" {
wb.Styles.Min.X.Pw(95)
}
// Only explicit ids and heading ids (used as link targets) are meaningful;
// automatic widget names are not unique in the resulting HTML.
if id, ok := wb.Property("id").(string); ok {
addAttr(se, "id", id)
} else if isHTMLHeading(se.Name.Local) {
addAttr(se, "id", wb.Name)
}
switch se.Name.Local {
case "table": // styled as a real table, not a grid
case "img":
src, _ := wb.Property("src").(string)
addAttr(se, "src", src)
addAttr(se, "alt", wb.Tooltip)
addAttr(se, "style", imageCSS(&wb.Styles))
default:
// An element of only inline text (as a paragraph in the browser
// style of htmlcore) has no layout of its own, so its text is inline.
// A container of floats has block layout, as floats have no effect
// in a flex layout.
cssID := idName
floats := hasFloats(wb)
// A table cell keeps the display of a cell: a flex layout (as of
// the frame of an empty cell) takes it out of its row.
if inlineOnly(wb) || floats || tableCells[se.Name.Local] {
cssID = "text"
}
css := styles.ToCSS(&wb.Styles, cssID, se.Name.Local) + growCSS(wb)
if floats {
css += ";display:flow-root" // a block that contains its floats
}
if _, ok := w.(*core.Button); ok && se.Name.Local == "a" {
css += ";text-decoration:none" // link button
}
// A widget of an inline element (as a span with a width) is a box.
if inlineElements[se.Name.Local] {
css += ";display:inline-block"
}
addAttr(se, "style", strings.TrimPrefix(css, ";"))
}
if class, ok := wb.Property("class").(string); ok {
addAttr(se, "class", class)
}
if href, ok := wb.Property("href").(string); ok {
addAttr(se, "href", href)
}
addDataAttrs(se, wb)
handleChildren := true
switch w := w.(type) {
case *core.TextField:
addAttr(se, "type", "text")
addAttr(se, "value", w.Text())
handleChildren = false
case *core.Spinner:
addAttr(se, "type", "number")
addAttr(se, "value", fmt.Sprintf("%g", w.Value))
handleChildren = false
case *core.Slider:
addAttr(se, "type", "range")
addAttr(se, "value", fmt.Sprintf("%g", w.Value))
handleChildren = false
case *core.Switch:
addAttr(se, "type", "checkbox")
addAttr(se, "value", strconv.FormatBool(w.IsChecked()))
case *core.Collapser:
se.Name.Local = "details"
if w.Open {
addAttr(se, "open", "open")
}
handleChildren = false
}
if se.Name.Local == "textarea" {
addAttr(se, "rows", "10")
addAttr(se, "cols", "30")
}
err := e.EncodeToken(*se)
if err != nil {
return err
}
err = e.Flush()
if err != nil {
return err
}
switch w := w.(type) {
case *core.Text:
// We don't want any escaping of HTML-formatted text, so we write directly.
// Paragraphs within the text (such as in a figure caption) are rendered
// inline in a Text, and are not allowed within a <p>, so we remove them.
b.WriteString(textParagraphReplacer.Replace(w.Text))
case *core.Icon:
// TODO: just remove the width and height attributes from the source SVGs?
icon := strings.ReplaceAll(string(w.Icon), ` width="48" height="48"`, "")
b.WriteString(icon)
case *core.SVG:
w.SVG.PhysicalWidth = wb.Styles.Min.X
w.SVG.PhysicalHeight = wb.Styles.Min.Y
err := w.SVG.WriteXML(b, svg.NoIndentXML)
if err != nil {
return err
}
}
if se.Name.Local == "textarea" && idName == "editor" {
b.WriteString(reflectx.Underlying(reflect.ValueOf(w)).FieldByName("Lines").Interface().(fmt.Stringer).String())
}
switch w := w.(type) {
case *core.Collapser:
err = collapserToHTML(w, e, b)
if err != nil {
return err
}
}
if se.Name.Local == "table" {
err = tableToHTML(wb, e, b)
if err != nil {
return err
}
handleChildren = false
}
if handleChildren {
wb.ForWidgetChildren(func(i int, cw core.Widget, cwb *core.WidgetBase) bool {
if idName == "switch" && cwb.Name == "stack" {
return tree.Continue
}
err = toHTML(cw, e, b)
if err != nil {
return tree.Break
}
return tree.Continue
})
if err != nil {
return err
}
}
err = e.EncodeToken(xml.EndElement{Name: se.Name})
if err != nil {
return err
}
return e.Flush()
}
// hasFloats returns whether any of the children of the widget float.
func hasFloats(wb *core.WidgetBase) bool {
floats := false
wb.ForWidgetChildren(func(i int, cw core.Widget, cwb *core.WidgetBase) bool {
floats = cwb.Styles.Float != styles.FloatNone
return !floats
})
return floats
}
// tableCells are the elements of the cells of a table, whose widgets have
// no layout of their own in the HTML.
var tableCells = map[string]bool{"td": true, "th": true}
// inlineElements are the HTML elements that are inline by default, which
// are boxes ("inline-block") when they are widgets of their own.
var inlineElements = map[string]bool{"span": true, "a": true, "b": true, "i": true, "em": true,
"strong": true, "code": true, "small": true, "label": true, "mark": true, "sub": true, "sup": true}
// inlineOnly returns whether all of the children of the widget are inline
// text: [core.Text] without a tag of its own and inline containers of it,
// which [toHTML] writes as the content of the element.
func inlineOnly(wb *core.WidgetBase) bool {
if _, ok := wb.Property("tag").(string); !ok || wb.NumChildren() == 0 {
return false
}
only := true
wb.ForWidgetChildren(func(i int, cw core.Widget, cwb *core.WidgetBase) bool {
_, tagged := cwb.Property("tag").(string)
_, isText := cw.(*core.Text)
inline := !tagged && (isText || strings.HasPrefix(cwb.Name, "inline-container"))
if !inline {
only = false
return tree.Break
}
return tree.Continue
})
return only
}
// addDataAttrs adds the data attributes of the widget, which are its
// string properties with a data- prefix, in sorted order.
func addDataAttrs(se *xml.StartElement, wb *core.WidgetBase) {
var names []string
for k, v := range wb.Properties {
if _, ok := v.(string); ok && strings.HasPrefix(k, "data-") {
names = append(names, k)
}
}
slices.Sort(names)
for _, k := range names {
addAttr(se, k, wb.Properties[k].(string))
}
}
// textParagraphReplacer removes paragraph tags within [core.Text.Text] in [Widget].
var textParagraphReplacer = strings.NewReplacer("<p>", "", "</p>", "")
// isHTMLHeading returns whether the given HTML element name is a heading (h1-h6).
func isHTMLHeading(name string) bool {
return len(name) == 2 && name[0] == 'h' && name[1] >= '1' && name[1] <= '6'
}
// imageCSS returns the CSS style for an image, which only needs its size.
func imageCSS(s *styles.Style) string {
parts := []string{}
if s.Min.X.Value > 0 {
parts = append(parts, "width:"+s.Min.X.StringCSSDp())
}
if s.Min.Y.Value > 0 {
parts = append(parts, "height:"+s.Min.Y.StringCSSDp())
}
if s.Max.X.Value > 0 {
parts = append(parts, "max-width:"+s.Max.X.StringCSSDp())
}
if s.Max.Y.Value > 0 {
parts = append(parts, "max-height:"+s.Max.Y.StringCSSDp())
}
if s.ObjectFit != styles.FitFill {
parts = append(parts, "object-fit:"+s.ObjectFit.String())
}
return strings.Join(parts, ";")
}
// tableToHTML writes the children of the given table frame, which are laid
// out in a grid, as the rows of an HTML table.
func tableToHTML(wb *core.WidgetBase, e *xml.Encoder, b *bytes.Buffer) error {
cols := max(wb.Styles.Columns, 1)
tr := xml.StartElement{Name: xml.Name{Local: "tr"}}
var err error
wb.ForWidgetChildren(func(i int, cw core.Widget, cwb *core.WidgetBase) bool {
if i%cols == 0 {
if i > 0 {
err = e.EncodeToken(tr.End())
if err != nil {
return tree.Break
}
}
err = e.EncodeToken(tr)
if err != nil {
return tree.Break
}
}
err = toHTML(cw, e, b)
if err != nil {
return tree.Break
}
return tree.Continue
})
if err != nil {
return err
}
if wb.NumChildren() > 0 {
err = e.EncodeToken(tr.End())
}
return err
}
// collapserToHTML writes the children of the given collapser as the
// <summary> and contents of a <details> element, excluding the toggle switch.
func collapserToHTML(cl *core.Collapser, e *xml.Encoder, b *bytes.Buffer) error {
sum := xml.StartElement{Name: xml.Name{Local: "summary"}}
err := e.EncodeToken(sum)
if err != nil {
return err
}
cl.Summary.ForWidgetChildren(func(i int, cw core.Widget, cwb *core.WidgetBase) bool {
if _, ok := cw.(*core.Switch); ok {
return tree.Continue
}
err = toHTML(cw, e, b)
if err != nil {
return tree.Break
}
return tree.Continue
})
if err != nil {
return err
}
err = e.EncodeToken(sum.End())
if err != nil {
return err
}
cl.Details.ForWidgetChildren(func(i int, cw core.Widget, cwb *core.WidgetBase) bool {
err = toHTML(cw, e, b)
if err != nil {
return tree.Break
}
return tree.Continue
})
return err
}
// growCSS returns additional CSS for the grow factors of the given widget
// relative to the layout direction of its parent, since [styles.ToCSS]
// does not have access to the parent.
func growCSS(wb *core.WidgetBase) string {
if wb.Parent == nil {
return ""
}
pw := core.AsWidget(wb.Parent)
if pw == nil || pw.Styles.Display != styles.Flex {
return ""
}
main, cross := wb.Styles.Grow.Y, wb.Styles.Grow.X
if pw.Styles.Direction == styles.Row {
main, cross = cross, main
}
css := fmt.Sprintf(";flex-grow:%g", main)
switch {
case wb.Styles.Align.Self != styles.Auto: // as for auto margins in htmlcore
css += ";align-self:" + wb.Styles.Align.Self.String()
case cross > 0:
css += ";align-self:stretch"
}
return css
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package icons provides Material Design Symbols as SVG icon variables.
package icons
import (
_ "embed"
"sync"
"golang.org/x/exp/maps"
)
//go:generate core generate -icons svg
// Icon represents the SVG data of an icon. It can be
// set to "" or [None] to indicate that no icon should be used.
type Icon string
var (
// None is an icon that indicates to not use an icon.
// It completely prevents the rendering of an icon,
// whereas [Blank] renders a blank icon.
None Icon = "none"
// Blank is a blank icon that can be used as a
// placeholder when no other icon is appropriate.
// It still renders an icon, just a blank one,
// whereas [None] indicates to not render one at all.
//
//go:embed svg/blank.svg
Blank Icon
// used is a map containing all icons that have been used.
// It is added to by [cogentcore.org/core/core.Icon].
used = map[Icon]struct{}{}
usedMu sync.Mutex
)
// IsSet returns whether the icon is set to a value other than "" or [None].
func (i Icon) IsSet() bool {
return i != "" && i != None
}
// AddUsed adds given icon to the list of icons that have been used
// (under mutex lock).
func AddUsed(i Icon) {
usedMu.Lock()
used[i] = struct{}{}
usedMu.Unlock()
}
// Used returns a list of icons that have been used so far in the app.
// This list is in indeterminate order.
func Used() []Icon {
usedMu.Lock()
defer usedMu.Unlock()
return maps.Keys(used)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package keymap
import (
"cogentcore.org/core/system"
// we have to import system/driver here so that it is initialized
// in time for us to the get the system platform
_ "cogentcore.org/core/system/driver"
)
func init() {
AvailableMaps.CopyFrom(StandardMaps)
switch system.TheApp.SystemPlatform() {
case system.MacOS:
DefaultMap = "MacStandard"
case system.Windows:
DefaultMap = "WindowsStandard"
default:
DefaultMap = "LinuxStandard"
}
SetActiveMapName(DefaultMap)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package keymap implements maps from keyboard shortcuts to
// semantic GUI keyboard functions.
package keymap
//go:generate core generate
import (
"encoding/json"
"log/slog"
"maps"
"slices"
"sort"
"strings"
"cogentcore.org/core/events/key"
)
// https://en.wikipedia.org/wiki/Table_of_keyboard_shortcuts
// https://www.cs.colorado.edu/~main/cs1300/lab/emacs.html
// https://help.ubuntu.com/community/KeyboardShortcuts
// Functions are semantic functions that keyboard events
// can perform in the GUI.
type Functions int32 //enums:enum
const (
None Functions = iota
MoveUp
MoveDown
MoveRight
MoveLeft
PageUp
PageDown
// PageRight
// PageLeft
Home // start-of-line
End // end-of-line
DocHome // start-of-doc -- Control / Alt / Shift +Home
DocEnd // end-of-doc Control / Alt / Shift +End
WordRight
WordLeft
// WordLeft is the final navigation function -- all above also allow Shift+ for selection.
FocusNext // Tab
FocusPrev // Shift-Tab
Enter // Enter / return key -- has various special functions
Accept // Ctrl+Enter = accept any changes and close dialog / move to next
CancelSelect
SelectMode
SelectAll
Abort
// EditItem
Copy
Cut
Paste
PasteHist // from history
Backspace
BackspaceWord
Delete
DeleteWord
Kill
Duplicate
Transpose
TransposeWord
Undo
Redo
Insert
InsertAfter
InsertChild // insert as the last child, as in a tree
ZoomOut
ZoomIn
Refresh
Recenter // Ctrl+L in emacs
Complete
Lookup
Search // Ctrl+S in emacs -- more interactive type of search
Find // Command+F full-dialog find
Replace
Jump // jump to line
HistPrev
HistNext
Menu // put focus on menu
ContextMenu // the context menu of the focused widget
WinFocusNext
WinClose
WinSnapshot
// NextTab selects the next tab of the tabs that the focus is in, after
// the last one the first, when no widget in them handles the key, which
// is bound to a navigation key with Shift: see [OfFallback].
NextTab
// PrevTab selects the previous tab of the tabs that the focus is in,
// before the first one the last, as [NextTab].
PrevTab
// Below are menu specific functions -- use these as shortcuts for menu buttons
// allows uniqueness of mapping and easy customization of all key buttons
New
NewAlt1 // alternative version (e.g., shift)
NewAlt2 // alternative version (e.g., alt)
Open
OpenAlt1 // alternative version (e.g., shift)
OpenAlt2 // alternative version (e.g., alt)
Save
SaveAs
SaveAlt // another alt (e.g., alt)
CloseAlt1 // alternative version (e.g., shift)
CloseAlt2 // alternative version (e.g., alt)
MultiA // multi-key sequence A: Emacs Control+C
MultiB // multi-key sequence B: Emacs Control+X
)
// Map is a map between a key sequence (chord) and a specific key
// function. This mapping must be unique, in that each chord has a
// unique function, but multiple chords can trigger the same function.
type Map map[key.Chord]Functions
// ActiveMap points to the active map -- users can set this to an
// alternative map in Settings
var ActiveMap *Map
// MapName has an associated Value for selecting from the list of
// available key map names, for use in preferences etc.
type MapName string
// ActiveMapName is the name of the active keymap
var ActiveMapName MapName
// SetActiveMap sets the current ActiveKeyMap, calling Update on the map
// prior to setting it to ensure that it is a valid, complete map
func SetActiveMap(km *Map, kmName MapName) {
km.Update(kmName)
ActiveMap = km
ActiveMapName = kmName
}
// SetActiveMapName sets the current ActiveKeyMap by name from those
// defined in AvailKeyMaps, calling Update on the map prior to setting it to
// ensure that it is a valid, complete map
func SetActiveMapName(mapnm MapName) {
km, _, ok := AvailableMaps.MapByName(mapnm)
if ok {
SetActiveMap(km, mapnm)
} else {
slog.Error("keymap.SetActiveKeyMapName: key map named not found, using default", "requested", mapnm, "default", DefaultMap)
km, _, ok = AvailableMaps.MapByName(DefaultMap)
if ok {
SetActiveMap(km, DefaultMap)
} else {
avail := make([]string, len(AvailableMaps))
for i, km := range AvailableMaps {
avail[i] = km.Name
}
slog.Error("keymap.SetActiveKeyMapName: DefaultKeyMap not found either; trying first one", "default", DefaultMap, "available", avail)
if len(AvailableMaps) > 0 {
nkm := AvailableMaps[0]
SetActiveMap(&nkm.Map, MapName(nkm.Name))
}
}
}
}
// Of converts the given [key.Chord] into a keyboard function.
// A navigation key with Shift is that navigation (selecting), unless it
// is bound to another function that is not a fallback (see [OfFallback]).
func Of(chord key.Chord) Functions {
f, ok := (*ActiveMap)[chord]
if ok && !f.isFallback() {
return f
}
if strings.Contains(string(chord), "Shift+") {
nsc := key.Chord(strings.ReplaceAll(string(chord), "Shift+", ""))
if nf, nok := (*ActiveMap)[nsc]; nok && nf <= WordLeft { // automatically allow +Shift for nav
return nf
}
}
if ok {
return f
}
return None
}
// isFallback returns whether the key function is one that widgets fall back
// to when no widget handles its key, which [Of] does not return for a
// navigation key with Shift, which selects: see [OfFallback].
func (kf Functions) isFallback() bool {
return kf == NextTab || kf == PrevTab
}
// OfFallback returns the key function of the given key chord, as [Of], or
// the fallback function bound to it, such as [NextTab], which [Of] does not
// return for a navigation key with Shift, which selects (as in text fields).
// It is for widgets that handle the keys that no widget in them handled,
// such as [core.Tabs] for [NextTab] and [PrevTab].
func OfFallback(chord key.Chord) Functions {
if f, ok := (*ActiveMap)[chord]; ok && f.isFallback() {
return f
}
return Of(chord)
}
// MapItem records one element of the key map, which is used for organizing the map.
type MapItem struct {
// the key chord that activates a function
Key key.Chord
// the function of that key
Fun Functions
}
// ToSlice copies this keymap to a slice of [MapItem]s.
func (km *Map) ToSlice() []MapItem {
kms := make([]MapItem, len(*km))
idx := 0
for key, fun := range *km {
kms[idx] = MapItem{key, fun}
idx++
}
return kms
}
// ChordFor returns all of the key chord triggers for the given
// key function in the map, separating them with newlines.
func (km *Map) ChordFor(kf Functions) key.Chord {
res := []string{}
for key, fun := range *km {
if fun == kf {
res = append(res, string(key))
}
}
slices.Sort(res)
return key.Chord(strings.Join(res, "\n"))
}
// Chord returns all of the key chord triggers for this
// key function in the current active map, separating them with newlines.
func (kf Functions) Chord() key.Chord {
return ActiveMap.ChordFor(kf)
}
// Label transforms the key function into a string representing
// its underlying key chord(s) in a form suitable for display to users.
func (kf Functions) Label() string {
return kf.Chord().Label()
}
// Update ensures that the given keymap has at least one entry for every
// defined key function, grabbing ones from the default map if not, and
// also eliminates any [None] entries which might reflect out-of-date
// functions.
func (km *Map) Update(kmName MapName) {
for key, val := range *km {
if val == None {
slog.Error("keymap.KeyMap: key function is nil; probably renamed", "key", key)
delete(*km, key)
}
}
kms := km.ToSlice()
addkm := make([]MapItem, 0)
sort.Slice(kms, func(i, j int) bool {
return kms[i].Fun < kms[j].Fun
})
lfun := None
for _, ki := range kms {
fun := ki.Fun
if fun != lfun {
del := fun - lfun
if del > 1 {
for mi := lfun + 1; mi < fun; mi++ {
// slog.Error("keymap.KeyMap: key map is missing a key for a key function", "keyMap", kmName, "function", mi)
s := mi.String()
s = "- Not Set - " + s
nski := MapItem{Key: key.Chord(s), Fun: mi}
addkm = append(addkm, nski)
}
}
lfun = fun
}
}
for _, ai := range addkm {
(*km)[ai.Key] = ai.Fun
}
}
// DefaultMap is the overall default keymap, which is set in init
// depending on the platform
var DefaultMap MapName = "LinuxStandard"
// MapsItem is an entry in a Maps list
type MapsItem struct { //types:add -setters
// name of keymap
Name string `width:"20"`
// description of keymap; good idea to include source it was derived from
Desc string
// to edit key sequence click button and type new key combination; to edit function mapped to key sequence choose from menu
Map Map
}
// Label satisfies the Labeler interface
func (km MapsItem) Label() string {
return km.Name
}
// Maps is a list of [MapsItem]s; users can edit these in their settings.
type Maps []MapsItem //types:add
// AvailableMaps is the current list of available keymaps for use.
// This can be loaded / saved / edited in user settings. This is set
// to [StandardMaps] at startup.
var AvailableMaps Maps
// MapByName returns a [Map] and index by name. It returns false
// and prints an error message if not found.
func (km *Maps) MapByName(name MapName) (*Map, int, bool) {
for i, it := range *km {
if it.Name == string(name) {
return &it.Map, i, true
}
}
slog.Error("keymap.KeyMaps.MapByName: key map not found", "name", name)
return nil, -1, false
}
// CopyFrom copies keymaps from given other map
func (km *Maps) CopyFrom(cp Maps) {
*km = make(Maps, 0, len(cp)) // reset
b, _ := json.Marshal(cp)
json.Unmarshal(b, km)
}
// MergeFrom merges keymaps from given other map
func (km *Maps) MergeFrom(cp Maps) {
for nm, mi := range cp {
tmi := (*km)[nm]
maps.Copy(tmi.Map, mi.Map)
}
}
// order is: Shift, Control, Alt, Meta
// note: shift and meta modifiers for navigation keys do select + move
// note: where multiple shortcuts exist for a given function, any shortcut
// display of such items in menus will randomly display one of the
// options. This can be considered a feature, not a bug!
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package keymap
import (
"strings"
"cogentcore.org/core/events/key"
)
// MarkdownDoc generates a markdown table of all the key mappings
func (km *Maps) MarkdownDoc() string { //types:add
mods := []string{"", "Shift", "Control", "Control+Shift", "Meta", "Meta+Shift", "Alt", "Alt+Shift", "Control+Alt", "Meta+Alt"}
var b strings.Builder
fmap := make([][][]string, len(*km)) // km, kf, ch
for i := range *km {
fmap[i] = make([][]string, FunctionsN)
}
// By function
b.WriteString("### By function\n\n")
b.WriteString("| Function ")
for _, m := range *km {
b.WriteString("| `")
b.WriteString(m.Name)
b.WriteString("` ")
}
b.WriteString("|\n")
b.WriteString("| ---------------------------- ")
for _, m := range *km {
b.WriteString("| ")
b.WriteString(strings.Repeat("-", len(m.Name)+2))
b.WriteString(" ")
}
b.WriteString("|\n")
for kf := MoveUp; kf < FunctionsN; kf++ {
b.WriteString("| ")
b.WriteString(kf.String())
b.WriteString(" ")
for mi, m := range *km {
f := fmap[mi][kf]
b.WriteString("| ")
if len(f) > 0 {
for fi, fs := range f {
b.WriteString(fs)
if fi < len(f)-1 {
b.WriteString(", ")
} else {
b.WriteString(" ")
}
}
} else {
b.WriteString(strings.Repeat(" ", len(m.Name)+2))
b.WriteString(" ")
}
}
b.WriteString("|\n")
}
b.WriteString("\n\n")
for _, md := range mods {
if md == "" {
b.WriteString("### No Modifiers\n\n")
} else {
b.WriteString("### ")
b.WriteString(md)
b.WriteString("\n\n")
}
b.WriteString("| Key ")
for _, m := range *km {
b.WriteString("| `")
b.WriteString(m.Name)
b.WriteString("` ")
}
b.WriteString("|\n")
b.WriteString("| ---------------------------- ")
for _, m := range *km {
b.WriteString("| ")
b.WriteString(strings.Repeat("-", len(m.Name)+2))
b.WriteString(" ")
}
b.WriteString("|\n")
for cd := key.CodeA; cd < key.CodesN; cd++ {
ch := key.Chord(md + "+" + cd.String())
if md == "" {
ch = key.Chord(cd.String())
}
has := false
for _, m := range *km {
_, ok := m.Map[ch]
if ok {
has = true
break
}
}
if !has {
continue
}
b.WriteString("| ")
b.WriteString(string(ch))
b.WriteString(" ")
for mi, m := range *km {
kf, ok := m.Map[ch]
if ok {
b.WriteString("| ")
b.WriteString(kf.String())
b.WriteString(" ")
fmap[mi][kf] = append(fmap[mi][kf], string(ch))
} else {
b.WriteString("| ")
b.WriteString(strings.Repeat(" ", len(m.Name)+2))
b.WriteString(" ")
}
}
b.WriteString("|\n")
}
b.WriteString("\n\n")
}
return b.String()
}
// Copyright 2019 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Initially copied from G3N: github.com/g3n/engine/math32
// Copyright 2016 The G3N Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// with modifications needed to suit Cogent Core functionality.
package math32
import (
"unsafe"
"cogentcore.org/core/base/slicesx"
)
// ArrayF32 is a slice of float32 with additional convenience methods
// for other math32 data types. Use slicesx.SetLength to set length
// efficiently.
type ArrayF32 []float32
// NewArrayF32 creates a returns a new array of floats
// with the specified initial size and capacity
func NewArrayF32(size, capacity int) ArrayF32 {
return make([]float32, size, capacity)
}
// NumBytes returns the size of the array in bytes
func (a *ArrayF32) NumBytes() int {
return len(*a) * int(unsafe.Sizeof(float32(0)))
}
// Append appends any number of values to the array
func (a *ArrayF32) Append(v ...float32) {
*a = append(*a, v...)
}
// AppendVector2 appends any number of Vector2 to the array
func (a *ArrayF32) AppendVector2(v ...Vector2) {
for i := range v {
*a = append(*a, v[i].X, v[i].Y)
}
}
// AppendVector3 appends any number of Vector3 to the array
func (a *ArrayF32) AppendVector3(v ...Vector3) {
for i := range v {
*a = append(*a, v[i].X, v[i].Y, v[i].Z)
}
}
// AppendVector4 appends any number of Vector4 to the array
func (a *ArrayF32) AppendVector4(v ...Vector4) {
for i := range v {
*a = append(*a, v[i].X, v[i].Y, v[i].Z, v[i].W)
}
}
// CopyFloat32s copies a []float32 slice from src into target,
// ensuring that the target is the correct size.
func CopyFloat32s(trg *[]float32, src []float32) {
*trg = slicesx.SetLength(*trg, len(src))
copy(*trg, src)
}
// CopyFloat64s copies a []float64 slice from src into target,
// ensuring that the target is the correct size.
func CopyFloat64s(trg *[]float64, src []float64) {
*trg = slicesx.SetLength(*trg, len(src))
copy(*trg, src)
}
func (a *ArrayF32) CopyFrom(src ArrayF32) {
CopyFloat32s((*[]float32)(a), src)
}
// GetVector2 stores in the specified Vector2 the
// values from the array starting at the specified pos.
func (a ArrayF32) GetVector2(pos int, v *Vector2) {
v.X = a[pos]
v.Y = a[pos+1]
}
// GetVector3 stores in the specified Vector3 the
// values from the array starting at the specified pos.
func (a ArrayF32) GetVector3(pos int, v *Vector3) {
v.X = a[pos]
v.Y = a[pos+1]
v.Z = a[pos+2]
}
// GetVector4 stores in the specified Vector4 the
// values from the array starting at the specified pos.
func (a ArrayF32) GetVector4(pos int, v *Vector4) {
v.X = a[pos]
v.Y = a[pos+1]
v.Z = a[pos+2]
v.W = a[pos+3]
}
// GetMatrix4 stores in the specified Matrix4 the
// values from the array starting at the specified pos.
func (a ArrayF32) GetMatrix4(pos int, m *Matrix4) {
m[0] = a[pos]
m[1] = a[pos+1]
m[2] = a[pos+2]
m[3] = a[pos+3]
m[4] = a[pos+4]
m[5] = a[pos+5]
m[6] = a[pos+6]
m[7] = a[pos+7]
m[8] = a[pos+8]
m[9] = a[pos+9]
m[10] = a[pos+10]
m[11] = a[pos+11]
m[12] = a[pos+12]
m[13] = a[pos+13]
m[14] = a[pos+14]
m[15] = a[pos+15]
}
// Set sets the values of the array starting at the specified pos
// from the specified values
func (a ArrayF32) Set(pos int, v ...float32) {
for i, vv := range v {
a[pos+i] = vv
}
}
// SetVector2 sets the values of the array at the specified pos
// from the XY values of the specified Vector2
func (a ArrayF32) SetVector2(pos int, v Vector2) {
a[pos] = v.X
a[pos+1] = v.Y
}
// SetVector3 sets the values of the array at the specified pos
// from the XYZ values of the specified Vector3
func (a ArrayF32) SetVector3(pos int, v Vector3) {
a[pos] = v.X
a[pos+1] = v.Y
a[pos+2] = v.Z
}
// SetVector4 sets the values of the array at the specified pos
// from the XYZ values of the specified Vector4
func (a ArrayF32) SetVector4(pos int, v Vector4) {
a[pos] = v.X
a[pos+1] = v.Y
a[pos+2] = v.Z
a[pos+3] = v.W
}
/////////////////////////////////////////////////////////////////////////////////////
// ArrayU32
// ArrayU32 is a slice of uint32 with additional convenience methods.
// Use slicesx.SetLength to set length efficiently.
type ArrayU32 []uint32
// NewArrayU32 creates a returns a new array of uint32
// with the specified initial size and capacity
func NewArrayU32(size, capacity int) ArrayU32 {
return make([]uint32, size, capacity)
}
// NumBytes returns the size of the array in bytes
func (a *ArrayU32) NumBytes() int {
return len(*a) * int(unsafe.Sizeof(uint32(0)))
}
// Append appends n elements to the array updating the slice if necessary
func (a *ArrayU32) Append(v ...uint32) {
*a = append(*a, v...)
}
// Set sets the values of the array starting at the specified pos
// from the specified values
func (a ArrayU32) Set(pos int, v ...uint32) {
for i, vv := range v {
a[pos+i] = vv
}
}
// Copyright 2019 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Initially copied from G3N: github.com/g3n/engine/math32
// Copyright 2016 The G3N Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// with modifications needed to suit Cogent Core functionality.
package math32
import (
"image"
"golang.org/x/image/math/fixed"
)
// Box2 represents a 2D bounding box defined by two points:
// the point with minimum coordinates and the point with maximum coordinates.
type Box2 struct {
Min Vector2
Max Vector2
}
// B2 returns a new [Box2] from the given minimum and maximum x and y coordinates.
func B2(x0, y0, x1, y1 float32) Box2 {
return Box2{Vec2(x0, y0), Vec2(x1, y1)}
}
// B2Empty returns a new [Box2] with empty minimum and maximum values
func B2Empty() Box2 {
bx := Box2{}
bx.SetEmpty()
return bx
}
// B2FromRect returns a new [Box2] from the given [image.Rectangle].
func B2FromRect(rect image.Rectangle) Box2 {
b := Box2{}
b.SetFromRect(rect)
return b
}
// B2FromFixed returns a new [Box2] from the given [fixed.Rectangle26_6].
func B2FromFixed(rect fixed.Rectangle26_6) Box2 {
b := Box2{}
b.Min.SetFixed(rect.Min)
b.Max.SetFixed(rect.Max)
return b
}
// SetEmpty set this bounding box to empty (min / max +/- Infinity)
func (b *Box2) SetEmpty() {
b.Min.SetScalar(Infinity)
b.Max.SetScalar(-Infinity)
}
// IsEmpty returns if this bounding box is empty (max < min on any coord).
func (b *Box2) IsEmpty() bool {
return (b.Max.X < b.Min.X) || (b.Max.Y < b.Min.Y)
}
// Set sets this bounding box minimum and maximum coordinates.
// If either min or max are nil, then corresponding values are set to +/- Infinity.
func (b *Box2) Set(min, max *Vector2) {
if min != nil {
b.Min = *min
} else {
b.Min.SetScalar(Infinity)
}
if max != nil {
b.Max = *max
} else {
b.Max.SetScalar(-Infinity)
}
}
// SetFromPoints set this bounding box from the specified array of points.
func (b *Box2) SetFromPoints(points []Vector2) {
b.SetEmpty()
for i := range points {
b.ExpandByPoint(points[i])
}
}
// SetFromRect set this bounding box from an image.Rectangle
func (b *Box2) SetFromRect(rect image.Rectangle) {
b.Min = FromPoint(rect.Min)
b.Max = FromPoint(rect.Max)
}
// ToRect returns image.Rectangle version of this bbox, using floor for min
// and Ceil for max.
func (b Box2) ToRect() image.Rectangle {
rect := image.Rectangle{}
rect.Min = b.Min.ToPointFloor()
rect.Max = b.Max.ToPointCeil()
return rect
}
// ToFixed returns fixed.Rectangle26_6 version of this bbox.
func (b Box2) ToFixed() fixed.Rectangle26_6 {
rect := fixed.Rectangle26_6{Min: b.Min.ToFixed(), Max: b.Max.ToFixed()}
return rect
}
// RectInNotEmpty returns true if rect r is contained within b box
// and r is not empty.
// The existing image.Rectangle.In method returns true if r is empty,
// but we typically expect that case to be false (out of range box)
func RectInNotEmpty(r, b image.Rectangle) bool {
if r.Empty() {
return false
}
return r.In(b)
}
// Canon returns the canonical version of the box.
// The returned rectangle has minimum and maximum coordinates swapped
// if necessary so that it is well-formed.
func (b Box2) Canon() Box2 {
if b.Max.X < b.Min.X {
b.Min.X, b.Max.X = b.Max.X, b.Min.X
}
if b.Max.Y < b.Min.Y {
b.Min.Y, b.Max.Y = b.Max.Y, b.Min.Y
}
return b
}
// ExpandByPoint may expand this bounding box to include the specified point.
func (b *Box2) ExpandByPoint(point Vector2) {
b.Min.SetMin(point)
b.Max.SetMax(point)
}
// ExpandByVector expands this bounding box by the specified vector.
func (b *Box2) ExpandByVector(vector Vector2) {
b.Min.SetSub(vector)
b.Max.SetAdd(vector)
}
// ExpandByScalar expands this bounding box by the specified scalar.
func (b *Box2) ExpandByScalar(scalar float32) {
b.Min.SetSubScalar(scalar)
b.Max.SetAddScalar(scalar)
}
// ExpandByBox may expand this bounding box to include the specified box
func (b *Box2) ExpandByBox(box Box2) {
b.ExpandByPoint(box.Min)
b.ExpandByPoint(box.Max)
}
// MulMatrix2 multiplies the specified matrix to the vertices of this bounding box
// and computes the resulting spanning Box2 of the transformed points
func (b Box2) MulMatrix2(m Matrix2) Box2 {
var cs [4]Vector2
cs[0] = m.MulPoint(Vec2(b.Min.X, b.Min.Y))
cs[1] = m.MulPoint(Vec2(b.Min.X, b.Max.Y))
cs[2] = m.MulPoint(Vec2(b.Max.X, b.Min.Y))
cs[3] = m.MulPoint(Vec2(b.Max.X, b.Max.Y))
nb := B2Empty()
for i := range 4 {
nb.ExpandByPoint(cs[i])
}
return nb
}
// SetFromCenterAndSize set this bounding box from a center point and size.
// Size is a vector from the minimum point to the maximum point.
func (b *Box2) SetFromCenterAndSize(center, size Vector2) {
halfSize := size.MulScalar(0.5)
b.Min = center.Sub(halfSize)
b.Max = center.Add(halfSize)
}
// Center calculates the center point of this bounding box.
func (b Box2) Center() Vector2 {
return b.Min.Add(b.Max).MulScalar(0.5)
}
// Size calculates the size of this bounding box: the vector from
// its minimum point to its maximum point.
func (b Box2) Size() Vector2 {
return b.Max.Sub(b.Min)
}
// ContainsPoint returns if this bounding box contains the specified point.
func (b Box2) ContainsPoint(point Vector2) bool {
if point.X < b.Min.X || point.X > b.Max.X ||
point.Y < b.Min.Y || point.Y > b.Max.Y {
return false
}
return true
}
// ContainsBox returns if this bounding box contains other box.
func (b Box2) ContainsBox(box Box2) bool {
return (b.Min.X <= box.Min.X) && (box.Max.X <= b.Max.X) && (b.Min.Y <= box.Min.Y) && (box.Max.Y <= b.Max.Y)
}
// IntersectsBox returns if other box intersects this one.
func (b Box2) IntersectsBox(other Box2) bool {
if other.Max.X < b.Min.X || other.Min.X > b.Max.X ||
other.Max.Y < b.Min.Y || other.Min.Y > b.Max.Y {
return false
}
return true
}
// ClampPoint calculates a new point which is the specified point clamped inside this box.
func (b Box2) ClampPoint(point Vector2) Vector2 {
point.Clamp(b.Min, b.Max)
return point
}
// DistanceToPoint returns the distance from this box to the specified point.
func (b Box2) DistanceToPoint(point Vector2) float32 {
clamp := b.ClampPoint(point)
return clamp.Sub(point).Length()
}
// Intersect returns the intersection with other box.
func (b Box2) Intersect(other Box2) Box2 {
other.Min.SetMax(b.Min)
other.Max.SetMin(b.Max)
return other
}
// Union returns the union with other box.
func (b Box2) Union(other Box2) Box2 {
other.Min.SetMin(b.Min)
other.Max.SetMax(b.Max)
return other
}
// Translate returns translated position of this box by offset.
func (b Box2) Translate(offset Vector2) Box2 {
nb := Box2{}
nb.Min = b.Min.Add(offset)
nb.Max = b.Max.Add(offset)
return nb
}
// ProjectX projects normalized value along the X dimension of this box
func (b Box2) ProjectX(v float32) float32 {
return b.Min.X + v*(b.Max.X-b.Min.X)
}
// ProjectY projects normalized value along the Y dimension of this box
func (b Box2) ProjectY(v float32) float32 {
return b.Min.Y + v*(b.Max.Y-b.Min.Y)
}
// Copyright 2019 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Initially copied from G3N: github.com/g3n/engine/math32
// Copyright 2016 The G3N Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// with modifications needed to suit Cogent Core functionality.
package math32
// Box3 represents a 3D bounding box defined by two points:
// the point with minimum coordinates and the point with maximum coordinates.
type Box3 struct {
Min Vector3
Max Vector3
}
// B3 returns a new [Box3] from the given minimum and maximum x, y, and z coordinates.
func B3(x0, y0, z0, x1, y1, z1 float32) Box3 {
return Box3{Vec3(x0, y0, z0), Vec3(x1, y1, z1)}
}
// B3Empty returns a new [Box3] with empty minimum and maximum values.
func B3Empty() Box3 {
bx := Box3{}
bx.SetEmpty()
return bx
}
// SetEmpty set this bounding box to empty (min / max +/- Infinity)
func (b *Box3) SetEmpty() {
b.Min.SetScalar(Infinity)
b.Max.SetScalar(-Infinity)
}
// IsEmpty returns true if this bounding box is empty (max < min on any coord).
func (b Box3) IsEmpty() bool {
return (b.Max.X < b.Min.X) || (b.Max.Y < b.Min.Y) || (b.Max.Z < b.Min.Z)
}
// Set sets this bounding box minimum and maximum coordinates.
// If either min or max are nil, then corresponding values are set to +/- Infinity.
func (b *Box3) Set(min, max *Vector3) {
if min != nil {
b.Min = *min
} else {
b.Min.SetScalar(Infinity)
}
if max != nil {
b.Max = *max
} else {
b.Max.SetScalar(-Infinity)
}
}
// SetMinMax sets this bounding box minimum and maximum coordinates
// using specific values (see also Set)
func (b *Box3) SetMinMax(min, max Vector3) {
b.Min = min
b.Max = max
}
// SetFromPoints sets this bounding box from the specified array of points.
func (b *Box3) SetFromPoints(points []Vector3) {
b.SetEmpty()
b.ExpandByPoints(points)
}
// ExpandByPoints may expand this bounding box from the specified array of points.
func (b *Box3) ExpandByPoints(points []Vector3) {
for i := range points {
b.ExpandByPoint(points[i])
}
}
// ExpandByPoint may expand this bounding box to include the specified point.
func (b *Box3) ExpandByPoint(point Vector3) {
b.Min.SetMin(point)
b.Max.SetMax(point)
}
// ExpandByBox may expand this bounding box to include the specified box
func (b *Box3) ExpandByBox(box Box3) {
b.ExpandByPoint(box.Min)
b.ExpandByPoint(box.Max)
}
// ExpandByVector expands this bounding box by the specified vector
// subtracting from min and adding to max.
func (b *Box3) ExpandByVector(vector Vector3) {
b.Min.SetSub(vector)
b.Max.SetAdd(vector)
}
// ExpandByScalar expands this bounding box by the specified scalar
// subtracting from min and adding to max.
func (b *Box3) ExpandByScalar(scalar float32) {
b.Min.SetSubScalar(scalar)
b.Max.SetAddScalar(scalar)
}
// SetFromCenterAndSize sets this bounding box from a center point and size.
// Size is a vector from the minimum point to the maximum point.
func (b *Box3) SetFromCenterAndSize(center, size Vector3) {
halfSize := size.MulScalar(0.5)
b.Min = center.Sub(halfSize)
b.Max = center.Add(halfSize)
}
// Center returns the center of the bounding box.
func (b Box3) Center() Vector3 {
return b.Min.Add(b.Max).MulScalar(0.5)
}
// Size calculates the size of this bounding box: the vector from
// its minimum point to its maximum point.
func (b Box3) Size() Vector3 {
return b.Max.Sub(b.Min)
}
// ContainsPoint returns if this bounding box contains the specified point.
func (b Box3) ContainsPoint(point Vector3) bool {
if point.X < b.Min.X || point.X > b.Max.X ||
point.Y < b.Min.Y || point.Y > b.Max.Y ||
point.Z < b.Min.Z || point.Z > b.Max.Z {
return false
}
return true
}
// ContainsBox returns if this bounding box contains other box.
func (b Box3) ContainsBox(box Box3) bool {
return (b.Min.X <= box.Max.X) && (box.Max.X <= b.Max.X) &&
(b.Min.Y <= box.Min.Y) && (box.Max.Y <= b.Max.Y) &&
(b.Min.Z <= box.Min.Z) && (box.Max.Z <= b.Max.Z)
}
// IntersectsBox returns if other box intersects this one.
func (b Box3) IntersectsBox(other Box3) bool {
// using 6 splitting planes to rule out intersections.
if other.Max.X < b.Min.X || other.Min.X > b.Max.X ||
other.Max.Y < b.Min.Y || other.Min.Y > b.Max.Y ||
other.Max.Z < b.Min.Z || other.Min.Z > b.Max.Z {
return false
}
return true
}
// ClampPoint returns a new point which is the specified point clamped inside this box.
func (b Box3) ClampPoint(point Vector3) Vector3 {
point.Clamp(b.Min, b.Max)
return point
}
// DistanceToPoint returns the distance from this box to the specified point.
func (b Box3) DistanceToPoint(point Vector3) float32 {
clamp := b.ClampPoint(point)
return clamp.Sub(point).Length()
}
// GetBoundingSphere returns a bounding sphere to this bounding box.
func (b Box3) GetBoundingSphere() Sphere {
return Sphere{b.Center(), b.Size().Length() * 0.5}
}
// Intersect returns the intersection with other box.
func (b Box3) Intersect(other Box3) Box3 {
other.Min.SetMax(b.Min)
other.Max.SetMin(b.Max)
return other
}
// Union returns the union with other box.
func (b Box3) Union(other Box3) Box3 {
other.Min.SetMin(b.Min)
other.Max.SetMax(b.Max)
return other
}
// MulMatrix4 multiplies the specified matrix to the vertices of this bounding box
// and computes the resulting spanning Box3 of the transformed points
func (b Box3) MulMatrix4(m *Matrix4) Box3 {
xax := m[0] * b.Min.X
xay := m[1] * b.Min.X
xaz := m[2] * b.Min.X
xbx := m[0] * b.Max.X
xby := m[1] * b.Max.X
xbz := m[2] * b.Max.X
yax := m[4] * b.Min.Y
yay := m[5] * b.Min.Y
yaz := m[6] * b.Min.Y
ybx := m[4] * b.Max.Y
yby := m[5] * b.Max.Y
ybz := m[6] * b.Max.Y
zax := m[8] * b.Min.Z
zay := m[9] * b.Min.Z
zaz := m[10] * b.Min.Z
zbx := m[8] * b.Max.Z
zby := m[9] * b.Max.Z
zbz := m[10] * b.Max.Z
nb := Box3{}
nb.Min.X = Min(xax, xbx) + Min(yax, ybx) + Min(zax, zbx) + m[12]
nb.Min.Y = Min(xay, xby) + Min(yay, yby) + Min(zay, zby) + m[13]
nb.Min.Z = Min(xaz, xbz) + Min(yaz, ybz) + Min(zaz, zbz) + m[14]
nb.Max.X = Max(xax, xbx) + Max(yax, ybx) + Max(zax, zbx) + m[12]
nb.Max.Y = Max(xay, xby) + Max(yay, yby) + Max(zay, zby) + m[13]
nb.Max.Z = Max(xaz, xbz) + Max(yaz, ybz) + Max(zaz, zbz) + m[14]
return nb
}
// MulQuat multiplies the specified quaternion to the vertices of this bounding box
// and computes the resulting spanning Box3 of the transformed points
func (b Box3) MulQuat(q Quat) Box3 {
var cs [8]Vector3
cs[0] = q.MulVector(Vec3(b.Min.X, b.Min.Y, b.Min.Z))
cs[1] = q.MulVector(Vec3(b.Min.X, b.Min.Y, b.Max.Z))
cs[2] = q.MulVector(Vec3(b.Min.X, b.Max.Y, b.Min.Z))
cs[3] = q.MulVector(Vec3(b.Max.X, b.Min.Y, b.Min.Z))
cs[4] = q.MulVector(Vec3(b.Max.X, b.Max.Y, b.Max.Z))
cs[5] = q.MulVector(Vec3(b.Max.X, b.Max.Y, b.Min.Z))
cs[6] = q.MulVector(Vec3(b.Max.X, b.Min.Y, b.Max.Z))
cs[7] = q.MulVector(Vec3(b.Min.X, b.Max.Y, b.Max.Z))
nb := B3Empty()
for i := range 8 {
nb.ExpandByPoint(cs[i])
}
return nb
}
// Translate returns translated position of this box by offset.
func (b Box3) Translate(offset Vector3) Box3 {
nb := Box3{}
nb.Min = b.Min.Add(offset)
nb.Max = b.Max.Add(offset)
return nb
}
// MVProjToNDC projects bounding box through given MVP model-view-projection Matrix4
// with perspective divide to return normalized display coordinates (NDC).
func (b Box3) MVProjToNDC(m *Matrix4) Box3 {
// all corners: i = min, a = max
var cs [8]Vector3
cs[0] = Vector4{b.Min.X, b.Min.Y, b.Min.Z, 1}.MulMatrix4(m).PerspDiv()
cs[1] = Vector4{b.Min.X, b.Min.Y, b.Max.Z, 1}.MulMatrix4(m).PerspDiv()
cs[2] = Vector4{b.Min.X, b.Max.Y, b.Min.Z, 1}.MulMatrix4(m).PerspDiv()
cs[3] = Vector4{b.Max.X, b.Min.Y, b.Min.Z, 1}.MulMatrix4(m).PerspDiv()
cs[4] = Vector4{b.Max.X, b.Max.Y, b.Max.Z, 1}.MulMatrix4(m).PerspDiv()
cs[5] = Vector4{b.Max.X, b.Max.Y, b.Min.Z, 1}.MulMatrix4(m).PerspDiv()
cs[6] = Vector4{b.Max.X, b.Min.Y, b.Max.Z, 1}.MulMatrix4(m).PerspDiv()
cs[7] = Vector4{b.Min.X, b.Max.Y, b.Max.Z, 1}.MulMatrix4(m).PerspDiv()
nb := B3Empty()
for i := range 8 {
nb.ExpandByPoint(cs[i])
}
return nb
}
// Copyright 2019 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package math32
import "image/color"
// official correct ones:
// SRGBFromLinear converts a color with linear gamma correction to SRGB standard 2.4 gamma
// with offsets.
func SRGBFromLinear(lin float32) float32 {
if lin <= 0.0031308 {
return lin * 12.92
}
return Pow(lin, 1.0/2.4)*1.055 - 0.055
}
// SRGBToLinear converts a color with SRGB gamma correction to SRGB standard 2.4 gamma
// with offsets
func SRGBToLinear(sr float32) float32 {
if sr <= 0.04045 {
return sr / 12.92
}
return Pow((sr+0.055)/1.055, 2.4)
}
/*
// rough-and-ready approx used in many cases:
func SRGBFromLinear(lin float32) float32 {
return Pow(lin, 1.0/2.2)
}
func SRGBToLinear(sr float32) float32 {
return Pow(sr, 2.2)
}
*/
// NewVector3Color returns a Vector3 from Go standard color.Color
// (R,G,B components only)
func NewVector3Color(clr color.Color) Vector3 {
v3 := Vector3{}
v3.SetColor(clr)
return v3
}
// SetColor sets from Go standard color.Color
// (R,G,B components only)
func (v *Vector3) SetColor(clr color.Color) {
r, g, b, _ := clr.RGBA()
v.X = float32(r) / 0xffff
v.Y = float32(g) / 0xffff
v.Z = float32(b) / 0xffff
}
// NewVector4Color returns a Vector4 from Go standard color.Color
// (full R,G,B,A components)
func NewVector4Color(clr color.Color) Vector4 {
v4 := Vector4{}
v4.SetColor(clr)
return v4
}
// SetColor sets a Vector4 from Go standard color.Color
func (v *Vector4) SetColor(clr color.Color) {
r, g, b, a := clr.RGBA()
v.X = float32(r) / 0xffff
v.Y = float32(g) / 0xffff
v.Z = float32(b) / 0xffff
v.W = float32(a) / 0xffff
}
// SRGBFromLinear returns an SRGB color space value from a linear source
func (v Vector3) SRGBFromLinear() Vector3 {
nv := Vector3{}
nv.X = SRGBFromLinear(v.X)
nv.Y = SRGBFromLinear(v.Y)
nv.Z = SRGBFromLinear(v.Z)
return nv
}
// SRGBToLinear returns a linear color space value from a SRGB source
func (v Vector3) SRGBToLinear() Vector3 {
nv := Vector3{}
nv.X = SRGBToLinear(v.X)
nv.Y = SRGBToLinear(v.Y)
nv.Z = SRGBToLinear(v.Z)
return nv
}
// SRGBFromLinear returns an SRGB color space value from a linear source
func (v Vector4) SRGBFromLinear() Vector4 {
nv := Vector4{}
nv.X = SRGBFromLinear(v.X)
nv.Y = SRGBFromLinear(v.Y)
nv.Z = SRGBFromLinear(v.Z)
nv.W = v.W
return nv
}
// SRGBToLinear returns a linear color space value from a SRGB source
func (v Vector4) SRGBToLinear() Vector4 {
nv := Vector4{}
nv.X = SRGBToLinear(v.X)
nv.Y = SRGBToLinear(v.Y)
nv.Z = SRGBToLinear(v.Z)
nv.W = v.W
return nv
}
// Copyright 2019 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package math32
// Dims is a list of vector dimension (component) names
type Dims int32 //enums:enum
const (
X Dims = iota
Y
Z
W
)
// OtherDim returns the other dimension for 2D X,Y
func OtherDim(d Dims) Dims {
switch d {
case X:
return Y
default:
return X
}
}
func (d Dims) Other() Dims {
return OtherDim(d)
}
// Copyright 2021 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package math32
import (
"math"
)
// This is a fast version of the natural exponential function, for highly
// time-sensitive uses where precision is less important.
// based on: N. N. Schraudolph. "A fast, compact approximation of the exponential function." Neural Computation, 11(4), May 1999, pp.853-862.
// as discussed and elaborated here: https://stackoverflow.com/questions/47025373/fastest-implementation-of-the-natural-exponential-function-using-sse
/*
// FastExpBad is the basic original N.N. Schraudolph version
// which has bad error and is no faster than the better cubic
// and quadratic cases.
func FastExpBad(x float32) float32 {
i := int32(1512775*x + 1072632447)
if x <= -88.76731 { // this doesn't add anything and -exp is main use-case anyway
return 0
}
return math.Float32frombits(uint32(i << 32))
}
// FastExp3 is less accurate and no faster than quartic version.
// FastExp3 is a cubic spline approximation to the Exp function, by N.N. Schraudolph
// It does not have any of the sanity checking of a standard method -- returns
// nonsense when arg is out of range. Runs in .24ns vs. 8.7ns for 64bit which is faster
// than math32.Exp actually.
func FastExp3(x float32) float32 {
// const (
// Overflow = 88.43114
// Underflow = -88.76731
// NearZero = 1.0 / (1 << 28) // 2**-28
// )
// special cases
// switch {
// these "sanity check" cases cost about 1 ns
// case IsNaN(x) || IsInf(x, 1): /
// return x
// case IsInf(x, -1):
// return 0
// these cases cost about 4+ ns
// case x >= Overflow:
// return Inf(1)
// case x <= Underflow:
// return 0
// case -NearZero < x && x < NearZero:
// return 1 + x
// }
if x <= -88.76731 { // this doesn't add anything and -exp is main use-case anyway
return 0
}
i := int32(12102203*x) + 127*(1<<23)
m := i >> 7 & 0xFFFF // copy mantissa
i += ((((((((1277 * m) >> 14) + 14825) * m) >> 14) - 79749) * m) >> 11) - 626
return math.Float32frombits(uint32(i))
}
*/
//gosl:start
// FastExp is a quartic spline approximation to the Exp function, by N.N. Schraudolph
// It does not have any of the sanity checking of a standard method -- returns
// nonsense when arg is out of range. Runs in 2.23ns vs. 6.3ns for 64bit which is faster
// than math32.Exp actually.
func FastExp(x float32) float32 {
if x <= -88.02969 { // this doesn't add anything and -exp is main use-case anyway
return 0.0
}
i := int32(12102203*x) + int32(127)*(int32(1)<<23)
m := (i >> 7) & 0xFFFF // copy mantissa
i += (((((((((((3537 * m) >> 16) + 13668) * m) >> 18) + 15817) * m) >> 14) - 80470) * m) >> 11)
return math.Float32frombits(uint32(i))
}
//gosl:end
// Copyright 2019 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package math32
import "golang.org/x/image/math/fixed"
// ToFixed converts a float32 value to a fixed.Int26_6
func ToFixed(x float32) fixed.Int26_6 {
return fixed.Int26_6(x * 64)
}
// FromFixed converts a fixed.Int26_6 to a float32
func FromFixed(x fixed.Int26_6) float32 {
const shift, mask = 6, 1<<6 - 1
if x >= 0 {
return float32(x>>shift) + float32(x&mask)/64
}
x = -x
if x >= 0 {
return -(float32(x>>shift) + float32(x&mask)/64)
}
return 0
}
// ToFixedPoint converts float32 x,y values to a fixed.Point26_6
func ToFixedPoint(x, y float32) fixed.Point26_6 {
return fixed.Point26_6{X: ToFixed(x), Y: ToFixed(y)}
}
// Copyright 2019 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Initially copied from G3N: github.com/g3n/engine/math32
// Copyright 2016 The G3N Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// with modifications needed to suit Cogent Core functionality.
package math32
// Frustum represents a frustum
type Frustum struct {
Planes [6]Plane
}
// NewFrustumFromMatrix creates and returns a Frustum based on the provided matrix
func NewFrustumFromMatrix(m *Matrix4) *Frustum {
f := new(Frustum)
f.SetFromMatrix(m)
return f
}
// NewFrustum returns a pointer to a new Frustum object made of 6 explicit planes
func NewFrustum(p0, p1, p2, p3, p4, p5 *Plane) *Frustum {
f := new(Frustum)
f.Set(p0, p1, p2, p3, p4, p5)
return f
}
// Set sets the frustum's planes
func (f *Frustum) Set(p0, p1, p2, p3, p4, p5 *Plane) {
if p0 != nil {
f.Planes[0] = *p0
}
if p1 != nil {
f.Planes[1] = *p1
}
if p2 != nil {
f.Planes[2] = *p2
}
if p3 != nil {
f.Planes[3] = *p3
}
if p4 != nil {
f.Planes[4] = *p4
}
if p5 != nil {
f.Planes[5] = *p5
}
}
// SetFromMatrix sets the frustum's planes based on the specified Matrix4
func (f *Frustum) SetFromMatrix(m *Matrix4) {
me0 := m[0]
me1 := m[1]
me2 := m[2]
me3 := m[3]
me4 := m[4]
me5 := m[5]
me6 := m[6]
me7 := m[7]
me8 := m[8]
me9 := m[9]
me10 := m[10]
me11 := m[11]
me12 := m[12]
me13 := m[13]
me14 := m[14]
me15 := m[15]
f.Planes[0].SetDims(me3-me0, me7-me4, me11-me8, me15-me12)
f.Planes[1].SetDims(me3+me0, me7+me4, me11+me8, me15+me12)
f.Planes[2].SetDims(me3+me1, me7+me5, me11+me9, me15+me13)
f.Planes[3].SetDims(me3-me1, me7-me5, me11-me9, me15-me13)
f.Planes[4].SetDims(me3-me2, me7-me6, me11-me10, me15-me14)
f.Planes[5].SetDims(me3+me2, me7+me6, me11+me10, me15+me14)
for i := range 6 {
f.Planes[i].Normalize()
}
}
// IntersectsSphere determines whether the specified sphere is intersecting the frustum
func (f *Frustum) IntersectsSphere(sphere Sphere) bool {
negRadius := -sphere.Radius
for i := range 6 {
dist := f.Planes[i].DistanceToPoint(sphere.Center)
if dist < negRadius {
return false
}
}
return true
}
// IntersectsBox determines whether the specified box is intersecting the frustum
func (f *Frustum) IntersectsBox(box Box3) bool {
var p1 Vector3
var p2 Vector3
for i := range 6 {
plane := &f.Planes[i]
if plane.Norm.X > 0 {
p1.X = box.Min.X
} else {
p1.X = box.Max.X
}
if plane.Norm.X > 0 {
p2.X = box.Max.X
} else {
p2.X = box.Min.X
}
if plane.Norm.Y > 0 {
p1.Y = box.Min.Y
} else {
p1.Y = box.Max.Y
}
if plane.Norm.Y > 0 {
p2.Y = box.Max.Y
} else {
p2.Y = box.Min.Y
}
if plane.Norm.Z > 0 {
p1.Z = box.Min.Z
} else {
p1.Z = box.Max.Z
}
if plane.Norm.Z > 0 {
p2.Z = box.Max.Z
} else {
p2.Z = box.Min.Z
}
d1 := plane.DistanceToPoint(p1)
d2 := plane.DistanceToPoint(p2)
// if both outside plane, no intersection
if d1 < 0 && d2 < 0 {
return false
}
}
return true
}
// ContainsPoint determines whether the frustum contains the specified point
func (f *Frustum) ContainsPoint(point Vector3) bool {
for i := range 6 {
if f.Planes[i].DistanceToPoint(point) < 0 {
return false
}
}
return true
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package math32
import (
"image"
)
// Geom2DInt defines a geometry in 2D dots units (int) -- this is just a more
// convenient format than image.Rectangle for cases where the size and
// position are independently updated (e.g., Viewport)
type Geom2DInt struct {
Pos image.Point
Size image.Point
}
// Bounds converts geom to equivalent image.Rectangle
func (gm *Geom2DInt) Bounds() image.Rectangle {
return image.Rect(gm.Pos.X, gm.Pos.Y, gm.Pos.X+gm.Size.X, gm.Pos.Y+gm.Size.Y)
}
// Box2 returns bounds as a [Box2].
func (gm *Geom2DInt) Box2() Box2 {
return B2FromRect(gm.Bounds())
}
// SizeRect converts geom to rect version of size at 0 pos.
func (gm *Geom2DInt) SizeRect() image.Rectangle {
return image.Rect(0, 0, gm.Size.X, gm.Size.Y)
}
// SetRect sets values from image.Rectangle.
func (gm *Geom2DInt) SetRect(r image.Rectangle) {
gm.Pos = r.Min
gm.Size = r.Size()
}
// FitGeomInWindow returns a position and size for a region (sub-window)
// within a larger window geom (pos and size) that fits entirely
// within that window to the extent possible,
// given an initial starting position and size.
// The position is first adjusted to try to fit the size, and then the size
// is adjusted to make it fit if it is still too big.
func FitGeomInWindow(stPos, stSz, winPos, winSz int) (pos, sz int) {
pos = stPos
sz = stSz
// we go through two iterations: one to fix our position and one to fix
// our size. this ensures that we adjust position and not size if we can,
// but we still always end up with valid dimensions by using size as a fallback.
if pos < winPos {
pos = winPos
}
if pos+sz > winPos+winSz { // our max > window max
pos = winPos + winSz - sz // window max - our size
}
if pos < winPos {
pos = winPos
}
if pos+sz > winPos+winSz { // our max > window max
sz = winSz + winPos - pos // window max - our min
}
return
}
// FitInWindow returns a position and size for a region (sub-window)
// within a larger window geom that fits entirely within that window to the
// extent possible, for the initial "ideal" starting position and size.
// The position is first adjusted to try to fit the size, and then the size
// is adjusted to make it fit if it is still too big.
func (gm *Geom2DInt) FitInWindow(win Geom2DInt) Geom2DInt {
var fit Geom2DInt
fit.Pos.X, fit.Size.X = FitGeomInWindow(gm.Pos.X, gm.Size.X, win.Pos.X, win.Size.X)
fit.Pos.Y, fit.Size.Y = FitGeomInWindow(gm.Pos.Y, gm.Size.Y, win.Pos.Y, win.Size.Y)
return fit
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !goscript
package fmath
import "github.com/chewxy/math32"
func Abs(x float32) float32 { return math32.Abs(x) }
func Acos(x float32) float32 { return math32.Acos(x) }
func Acosh(x float32) float32 { return math32.Acosh(x) }
func Asin(x float32) float32 { return math32.Asin(x) }
func Asinh(x float32) float32 { return math32.Asinh(x) }
func Atan(x float32) float32 { return math32.Atan(x) }
func Atan2(y, x float32) float32 { return math32.Atan2(y, x) }
func Atanh(x float32) float32 { return math32.Atanh(x) }
func Cbrt(x float32) float32 { return math32.Cbrt(x) }
func Ceil(x float32) float32 { return math32.Ceil(x) }
func Copysign(x, y float32) float32 { return math32.Copysign(x, y) }
func Cos(x float32) float32 { return math32.Cos(x) }
func Cosh(x float32) float32 { return math32.Cosh(x) }
func Dim(x, y float32) float32 { return math32.Dim(x, y) }
func Erf(x float32) float32 { return math32.Erf(x) }
func Erfc(x float32) float32 { return math32.Erfc(x) }
func Exp(x float32) float32 { return math32.Exp(x) }
func Exp2(x float32) float32 { return math32.Exp2(x) }
func Expm1(x float32) float32 { return math32.Expm1(x) }
func Floor(x float32) float32 { return math32.Floor(x) }
func Frexp(f float32) (float32, int) { return math32.Frexp(f) }
func Gamma(x float32) float32 { return math32.Gamma(x) }
func Hypot(p, q float32) float32 { return math32.Hypot(p, q) }
func Ilogb(x float32) int { return math32.Ilogb(x) }
func Inf(sign int) float32 { return math32.Inf(sign) }
func IsInf(f float32, sign int) bool { return math32.IsInf(f, sign) }
func IsNaN(f float32) bool { return math32.IsNaN(f) }
func J0(x float32) float32 { return math32.J0(x) }
func J1(x float32) float32 { return math32.J1(x) }
func Jn(n int, x float32) float32 { return math32.Jn(n, x) }
func Ldexp(frac float32, exp int) float32 { return math32.Ldexp(frac, exp) }
func Lgamma(x float32) (float32, int) { return math32.Lgamma(x) }
func Log(x float32) float32 { return math32.Log(x) }
func Log10(x float32) float32 { return math32.Log10(x) }
func Log1p(x float32) float32 { return math32.Log1p(x) }
func Log2(x float32) float32 { return math32.Log2(x) }
func Logb(x float32) float32 { return math32.Logb(x) }
func Max(x, y float32) float32 { return math32.Max(x, y) }
func Min(x, y float32) float32 { return math32.Min(x, y) }
func Mod(x, y float32) float32 { return math32.Mod(x, y) }
func Modf(f float32) (float32, float32) { return math32.Modf(f) }
func NaN() float32 { return math32.NaN() }
func Nextafter(x, y float32) float32 { return math32.Nextafter(x, y) }
func Pow(x, y float32) float32 { return math32.Pow(x, y) }
func Pow10(e int) float32 { return math32.Pow10(e) }
func Remainder(x, y float32) float32 { return math32.Remainder(x, y) }
func Round(x float32) float32 { return math32.Round(x) }
func Signbit(x float32) bool { return math32.Signbit(x) }
func Sin(x float32) float32 { return math32.Sin(x) }
func Sincos(x float32) (float32, float32) { return math32.Sincos(x) }
func Sinh(x float32) float32 { return math32.Sinh(x) }
func Sqrt(x float32) float32 { return math32.Sqrt(x) }
func Tan(x float32) float32 { return math32.Tan(x) }
func Tanh(x float32) float32 { return math32.Tanh(x) }
func Trunc(x float32) float32 { return math32.Trunc(x) }
func Y0(x float32) float32 { return math32.Y0(x) }
func Y1(x float32) float32 { return math32.Y1(x) }
func Yn(n int, x float32) float32 { return math32.Yn(n, x) }
// Copyright 2024 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package math32
// Line2 represents a 2D line segment defined by a start and an end point.
type Line2 struct {
Start Vector2
End Vector2
}
// NewLine2 creates and returns a new Line2 with the
// specified start and end points.
func NewLine2(start, end Vector2) Line2 {
return Line2{start, end}
}
// Set sets this line segment start and end points.
func (l *Line2) Set(start, end Vector2) {
l.Start = start
l.End = end
}
// Center calculates this line segment center point.
func (l *Line2) Center() Vector2 {
return l.Start.Add(l.End).MulScalar(0.5)
}
// Delta calculates the vector from the start to end point of this line segment.
func (l *Line2) Delta() Vector2 {
return l.End.Sub(l.Start)
}
// LengthSquared returns the square of the distance from the start point to the end point.
func (l *Line2) LengthSquared() float32 {
return l.Start.DistanceToSquared(l.End)
}
// Length returns the length from the start point to the end point.
func (l *Line2) Length() float32 {
return l.Start.DistanceTo(l.End)
}
// note: ClosestPointToPoint is adapted from https://math.stackexchange.com/questions/2193720/find-a-point-on-a-line-segment-which-is-the-closest-to-other-point-not-on-the-li
// ClosestPointToPoint returns the point along the line that is
// closest to the given point.
func (l *Line2) ClosestPointToPoint(point Vector2) Vector2 {
v := l.Delta()
u := point.Sub(l.Start)
vu := v.Dot(u)
ds := v.LengthSquared()
t := vu / ds
switch {
case t <= 0:
return l.Start
case t >= 1:
return l.End
default:
return l.Start.Add(v.MulScalar(t))
}
}
// Copyright 2019 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Initially copied from G3N: github.com/g3n/engine/math32
// Copyright 2016 The G3N Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// with modifications needed to suit Cogent Core functionality.
package math32
// Line3 represents a 3D line segment defined by a start and an end point.
type Line3 struct {
Start Vector3
End Vector3
}
// NewLine3 creates and returns a new Line3 with the
// specified start and end points.
func NewLine3(start, end Vector3) Line3 {
return Line3{start, end}
}
// Set sets this line segment start and end points.
func (l *Line3) Set(start, end Vector3) {
l.Start = start
l.End = end
}
// Center calculates this line segment center point.
func (l *Line3) Center() Vector3 {
return l.Start.Add(l.End).MulScalar(0.5)
}
// Delta calculates the vector from the start to end point of this line segment.
func (l *Line3) Delta() Vector3 {
return l.End.Sub(l.Start)
}
// DistanceSquared returns the square of the distance from the start point to the end point.
func (l *Line3) DistanceSquared() float32 {
return l.Start.DistanceToSquared(l.End)
}
// Dist returns the distance from the start point to the end point.
func (l *Line3) Dist() float32 {
return l.Start.DistanceTo(l.End)
}
// MulMatrix4 returns specified matrix multiplied to this line segment start and end points.
func (l *Line3) MulMatrix4(mat *Matrix4) Line3 {
return Line3{l.Start.MulMatrix4(mat), l.End.MulMatrix4(mat)}
}
// Copyright 2019 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Initially copied from G3N: github.com/g3n/engine/math32
// Copyright 2016 The G3N Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// with modifications needed to suit Cogent Core functionality.
// Package math32 is a float32 based vector, matrix, and math package
// for 2D & 3D graphics.
package math32
//go:generate core generate
import (
"cmp"
"math"
"strconv"
math32 "cogentcore.org/core/math32/internal/fmath"
)
// These are mostly just wrappers around chewxy/math32, which has
// some optimized implementations.
// Mathematical constants.
const (
E = math.E
Pi = math.Pi
Phi = math.Phi
Sqrt2 = math.Sqrt2
SqrtE = math.SqrtE
SqrtPi = math.SqrtPi
SqrtPhi = math.SqrtPhi
Ln2 = math.Ln2
Log2E = math.Log2E
Ln10 = math.Ln10
Log10E = math.Log10E
)
// Floating-point limit values.
// Max is the largest finite value representable by the type.
// SmallestNonzero is the smallest positive, non-zero value representable by the type.
const (
MaxFloat32 = math.MaxFloat32
SmallestNonzeroFloat32 = math.SmallestNonzeroFloat32
)
const (
// DegToRadFactor is the number of radians per degree.
DegToRadFactor = Pi / 180
// RadToDegFactor is the number of degrees per radian.
RadToDegFactor = 180 / Pi
)
// Infinity is positive infinity.
var Infinity = float32(math.Inf(1))
// DegToRad converts a number from degrees to radians
func DegToRad(degrees float32) float32 {
return degrees * DegToRadFactor
}
// RadToDeg converts a number from radians to degrees
func RadToDeg(radians float32) float32 {
return radians * RadToDegFactor
}
// Abs returns the absolute value of x.
//
// Special cases are:
//
// Abs(±Inf) = +Inf
// Abs(NaN) = NaN
func Abs(x float32) float32 {
return math32.Abs(x)
}
// Sign returns -1 if x < 0 and 1 otherwise.
func Sign(x float32) float32 {
if x < 0 {
return -1
}
return 1
}
// Acos returns the arccosine, in radians, of x.
//
// Special case is:
//
// Acos(x) = NaN if x < -1 or x > 1
func Acos(x float32) float32 {
return math32.Acos(x)
}
// Acosh returns the inverse hyperbolic cosine of x.
//
// Special cases are:
//
// Acosh(+Inf) = +Inf
// Acosh(x) = NaN if x < 1
// Acosh(NaN) = NaN
func Acosh(x float32) float32 {
return math32.Acosh(x)
}
// Asin returns the arcsine, in radians, of x.
//
// Special cases are:
//
// Asin(±0) = ±0
// Asin(x) = NaN if x < -1 or x > 1
func Asin(x float32) float32 {
return math32.Asin(x)
}
// Asinh returns the inverse hyperbolic sine of x.
//
// Special cases are:
//
// Asinh(±0) = ±0
// Asinh(±Inf) = ±Inf
// Asinh(NaN) = NaN
func Asinh(x float32) float32 {
return math32.Asinh(x)
}
// Atan returns the arctangent, in radians, of x.
//
// Special cases are:
//
// Atan(±0) = ±0
// Atan(±Inf) = ±Pi/2
func Atan(x float32) float32 {
return math32.Atan(x)
}
// Atan2 returns the arc tangent of y/x, using the signs of the two to determine the quadrant of the return value.
// Special cases are (in order):
//
// Atan2(y, NaN) = NaN
// Atan2(NaN, x) = NaN
// Atan2(+0, x>=0) = +0
// Atan2(-0, x>=0) = -0
// Atan2(+0, x<=-0) = +Pi
// Atan2(-0, x<=-0) = -Pi
// Atan2(y>0, 0) = +Pi/2
// Atan2(y<0, 0) = -Pi/2
// Atan2(+Inf, +Inf) = +Pi/4
// Atan2(-Inf, +Inf) = -Pi/4
// Atan2(+Inf, -Inf) = 3Pi/4
// Atan2(-Inf, -Inf) = -3Pi/4
// Atan2(y, +Inf) = 0
// Atan2(y>0, -Inf) = +Pi
// Atan2(y<0, -Inf) = -Pi
// Atan2(+Inf, x) = +Pi/2
// Atan2(-Inf, x) = -Pi/2
func Atan2(y, x float32) float32 {
return math32.Atan2(y, x)
}
// Atanh returns the inverse hyperbolic tangent of x.
//
// Special cases are:
//
// Atanh(1) = +Inf
// Atanh(±0) = ±0
// Atanh(-1) = -Inf
// Atanh(x) = NaN if x < -1 or x > 1
// Atanh(NaN) = NaN
func Atanh(x float32) float32 {
return math32.Atanh(x)
}
// Cbrt returns the cube root of x.
//
// Special cases are:
//
// Cbrt(±0) = ±0
// Cbrt(±Inf) = ±Inf
// Cbrt(NaN) = NaN
func Cbrt(x float32) float32 {
return math32.Cbrt(x)
}
// Ceil returns the least integer value greater than or equal to x.
//
// Special cases are:
//
// Ceil(±0) = ±0
// Ceil(±Inf) = ±Inf
// Ceil(NaN) = NaN
func Ceil(x float32) float32 {
return math32.Ceil(x)
}
// Copysign returns a value with the magnitude of f
// and the sign of sign.
func Copysign(f, sign float32) float32 {
return math32.Copysign(f, sign)
}
// Cos returns the cosine of the radian argument x.
//
// Special cases are:
//
// Cos(±Inf) = NaN
// Cos(NaN) = NaN
func Cos(x float32) float32 {
return math32.Cos(x)
}
// Cosh returns the hyperbolic cosine of x.
//
// Special cases are:
//
// Cosh(±0) = 1
// Cosh(±Inf) = +Inf
// Cosh(NaN) = NaN
func Cosh(x float32) float32 {
return math32.Cosh(x)
}
// Dim returns the maximum of x-y or 0.
//
// Special cases are:
//
// Dim(+Inf, +Inf) = NaN
// Dim(-Inf, -Inf) = NaN
// Dim(x, NaN) = Dim(NaN, x) = NaN
func Dim(x, y float32) float32 {
return math32.Dim(x, y)
}
// Erf returns the error function of x.
//
// Special cases are:
//
// Erf(+Inf) = 1
// Erf(-Inf) = -1
// Erf(NaN) = NaN
func Erf(x float32) float32 {
return math32.Erf(x)
}
// Erfc returns the complementary error function of x.
//
// Special cases are:
//
// Erfc(+Inf) = 0
// Erfc(-Inf) = 2
// Erfc(NaN) = NaN
func Erfc(x float32) float32 {
return math32.Erfc(x)
}
// Erfcinv returns the inverse of Erfc(x).
//
// Special cases are:
//
// Erfcinv(0) = +Inf
// Erfcinv(2) = -Inf
// Erfcinv(x) = NaN if x < 0 or x > 2
// Erfcinv(NaN) = NaN
func Erfcinv(x float32) float32 {
return float32(math.Erfcinv(float64(x)))
}
// Erfinv returns the inverse error function of x.
//
// Special cases are:
//
// Erfinv(1) = +Inf
// Erfinv(-1) = -Inf
// Erfinv(x) = NaN if x < -1 or x > 1
// Erfinv(NaN) = NaN
func Erfinv(x float32) float32 {
return float32(math.Erfinv(float64(x)))
}
// Exp returns e**x, the base-e exponential of x.
//
// Special cases are:
//
// Exp(+Inf) = +Inf
// Exp(NaN) = NaN
//
// Very large values overflow to 0 or +Inf.
// Very small values underflow to 1.
func Exp(x float32) float32 {
return math32.Exp(x)
}
// Exp2 returns 2**x, the base-2 exponential of x.
//
// Special cases are the same as Exp.
func Exp2(x float32) float32 {
return math32.Exp2(x)
}
// Expm1 returns e**x - 1, the base-e exponential of x minus 1.
// It is more accurate than Exp(x) - 1 when x is near zero.
//
// Special cases are:
//
// Expm1(+Inf) = +Inf
// Expm1(-Inf) = -1
// Expm1(NaN) = NaN
//
// Very large values overflow to -1 or +Inf.
func Expm1(x float32) float32 {
return math32.Expm1(x)
}
// FMA returns x * y + z, computed with only one rounding.
// (That is, FMA returns the fused multiply add of x, y, and z.)
func FMA(x, y, z float32) float32 {
return float32(math.FMA(float64(x), float64(y), float64(z)))
}
// Floor returns the greatest integer value less than or equal to x.
//
// Special cases are:
//
// Floor(±0) = ±0
// Floor(±Inf) = ±Inf
// Floor(NaN) = NaN
func Floor(x float32) float32 {
return math32.Floor(x)
}
// Frexp breaks f into a normalized fraction
// and an integral power of two.
// It returns frac and exp satisfying f == frac × 2**exp,
// with the absolute value of frac in the interval [½, 1).
//
// Special cases are:
//
// Frexp(±0) = ±0, 0
// Frexp(±Inf) = ±Inf, 0
// Frexp(NaN) = NaN, 0
func Frexp(f float32) (frac float32, exp int) {
return math32.Frexp(f)
}
// Gamma returns the Gamma function of x.
//
// Special cases are:
//
// Gamma(+Inf) = +Inf
// Gamma(+0) = +Inf
// Gamma(-0) = -Inf
// Gamma(x) = NaN for integer x < 0
// Gamma(-Inf) = NaN
// Gamma(NaN) = NaN
func Gamma(x float32) float32 {
return math32.Gamma(x)
}
// Hypot returns Sqrt(p*p + q*q), taking care to avoid
// unnecessary overflow and underflow.
//
// Special cases are:
//
// Hypot(±Inf, q) = +Inf
// Hypot(p, ±Inf) = +Inf
// Hypot(NaN, q) = NaN
// Hypot(p, NaN) = NaN
func Hypot(p, q float32) float32 {
return math32.Hypot(p, q)
}
// Ilogb returns the binary exponent of x as an integer.
//
// Special cases are:
//
// Ilogb(±Inf) = MaxInt32
// Ilogb(0) = MinInt32
// Ilogb(NaN) = MaxInt32
func Ilogb(x float32) float32 {
return float32(math32.Ilogb(x))
}
// Inf returns positive infinity if sign >= 0, negative infinity if sign < 0.
func Inf(sign int) float32 {
return math32.Inf(sign)
}
// IsInf reports whether f is an infinity, according to sign.
// If sign > 0, IsInf reports whether f is positive infinity.
// If sign < 0, IsInf reports whether f is negative infinity.
// If sign == 0, IsInf reports whether f is either infinity.
func IsInf(x float32, sign int) bool {
return math32.IsInf(x, sign)
}
// IsNaN reports whether f is an IEEE 754 “not-a-number” value.
func IsNaN(x float32) bool {
return math32.IsNaN(x)
}
// J0 returns the order-zero Bessel function of the first kind.
//
// Special cases are:
//
// J0(±Inf) = 0
// J0(0) = 1
// J0(NaN) = NaN
func J0(x float32) float32 {
return math32.J0(x)
}
// J1 returns the order-one Bessel function of the first kind.
//
// Special cases are:
//
// J1(±Inf) = 0
// J1(NaN) = NaN
func J1(x float32) float32 {
return math32.J1(x)
}
// Jn returns the order-n Bessel function of the first kind.
//
// Special cases are:
//
// Jn(n, ±Inf) = 0
// Jn(n, NaN) = NaN
func Jn(n int, x float32) float32 {
return math32.Jn(n, x)
}
// Ldexp is the inverse of Frexp.
// It returns frac × 2**exp.
//
// Special cases are:
//
// Ldexp(±0, exp) = ±0
// Ldexp(±Inf, exp) = ±Inf
// Ldexp(NaN, exp) = NaN
func Ldexp(frac float32, exp int) float32 {
return math32.Ldexp(frac, exp)
}
// Lerp returns the linear interpolation between start and stop in proportion to amount
func Lerp(start, stop, amount float32) float32 {
return (1-amount)*start + amount*stop
}
// Lgamma returns the natural logarithm and sign (-1 or +1) of Gamma(x).
//
// Special cases are:
//
// Lgamma(+Inf) = +Inf
// Lgamma(0) = +Inf
// Lgamma(-integer) = +Inf
// Lgamma(-Inf) = -Inf
// Lgamma(NaN) = NaN
func Lgamma(x float32) (lgamma float32, sign int) {
return math32.Lgamma(x)
}
// Log returns the natural logarithm of x.
//
// Special cases are:
//
// Log(+Inf) = +Inf
// Log(0) = -Inf
// Log(x < 0) = NaN
// Log(NaN) = NaN
func Log(x float32) float32 {
return math32.Log(x)
}
// Log10 returns the decimal logarithm of x.
// The special cases are the same as for Log.
func Log10(x float32) float32 {
return math32.Log10(x)
}
// Log1p returns the natural logarithm of 1 plus its argument x.
// It is more accurate than Log(1 + x) when x is near zero.
//
// Special cases are:
//
// Log1p(+Inf) = +Inf
// Log1p(±0) = ±0
// Log1p(-1) = -Inf
// Log1p(x < -1) = NaN
// Log1p(NaN) = NaN
func Log1p(x float32) float32 {
return math32.Log1p(x)
}
// Log2 returns the binary logarithm of x.
// The special cases are the same as for Log.
func Log2(x float32) float32 {
return math32.Log2(x)
}
// Logb returns the binary exponent of x.
//
// Special cases are:
//
// Logb(±Inf) = +Inf
// Logb(0) = -Inf
// Logb(NaN) = NaN
func Logb(x float32) float32 {
return math32.Logb(x)
}
// TODO(kai): should we use builtin max and min?
// Max returns the larger of x or y.
//
// Special cases are:
//
// Max(x, +Inf) = Max(+Inf, x) = +Inf
// Max(x, NaN) = Max(NaN, x) = NaN
// Max(+0, ±0) = Max(±0, +0) = +0
// Max(-0, -0) = -0
//
// Note that this differs from the built-in function max when called
// with NaN and +Inf.
func Max(x, y float32) float32 {
return math32.Max(x, y)
}
// Min returns the smaller of x or y.
//
// Special cases are:
//
// Min(x, -Inf) = Min(-Inf, x) = -Inf
// Min(x, NaN) = Min(NaN, x) = NaN
// Min(-0, ±0) = Min(±0, -0) = -0
//
// Note that this differs from the built-in function min when called
// with NaN and -Inf.
func Min(x, y float32) float32 {
return math32.Min(x, y)
}
// Mod returns the floating-point remainder of x/y.
// The magnitude of the result is less than y and its
// sign agrees with that of x.
//
// Special cases are:
//
// Mod(±Inf, y) = NaN
// Mod(NaN, y) = NaN
// Mod(x, 0) = NaN
// Mod(x, ±Inf) = x
// Mod(x, NaN) = NaN
func Mod(x, y float32) float32 {
return math32.Mod(x, y)
}
// Modf returns integer and fractional floating-point numbers
// that sum to f. Both values have the same sign as f.
//
// Special cases are:
//
// Modf(±Inf) = ±Inf, NaN
// Modf(NaN) = NaN, NaN
func Modf(f float32) (it float32, frac float32) {
return math32.Modf(f)
}
// NaN returns an IEEE 754 “not-a-number” value.
func NaN() float32 {
return math32.NaN()
}
// Nextafter returns the next representable float32 value after x towards y.
//
// Special cases are:
//
// Nextafter32(x, x) = x
// Nextafter32(NaN, y) = NaN
// Nextafter32(x, NaN) = NaN
func Nextafter(x, y float32) float32 {
return math32.Nextafter(x, y)
}
// Pow returns x**y, the base-x exponential of y.
//
// Special cases are (in order):
//
// Pow(x, ±0) = 1 for any x
// Pow(1, y) = 1 for any y
// Pow(x, 1) = x for any x
// Pow(NaN, y) = NaN
// Pow(x, NaN) = NaN
// Pow(±0, y) = ±Inf for y an odd integer < 0
// Pow(±0, -Inf) = +Inf
// Pow(±0, +Inf) = +0
// Pow(±0, y) = +Inf for finite y < 0 and not an odd integer
// Pow(±0, y) = ±0 for y an odd integer > 0
// Pow(±0, y) = +0 for finite y > 0 and not an odd integer
// Pow(-1, ±Inf) = 1
// Pow(x, +Inf) = +Inf for |x| > 1
// Pow(x, -Inf) = +0 for |x| > 1
// Pow(x, +Inf) = +0 for |x| < 1
// Pow(x, -Inf) = +Inf for |x| < 1
// Pow(+Inf, y) = +Inf for y > 0
// Pow(+Inf, y) = +0 for y < 0
// Pow(-Inf, y) = Pow(-0, -y)
// Pow(x, y) = NaN for finite x < 0 and finite non-integer y
func Pow(x, y float32) float32 {
return math32.Pow(x, y)
}
// Pow10 returns 10**n, the base-10 exponential of n.
//
// Special cases are:
//
// Pow10(n) = 0 for n < -323
// Pow10(n) = +Inf for n > 308
func Pow10(n int) float32 {
return math32.Pow10(n)
}
// Remainder returns the IEEE 754 floating-point remainder of x/y.
//
// Special cases are:
//
// Remainder(±Inf, y) = NaN
// Remainder(NaN, y) = NaN
// Remainder(x, 0) = NaN
// Remainder(x, ±Inf) = x
// Remainder(x, NaN) = NaN
func Remainder(x, y float32) float32 {
return math32.Remainder(x, y)
}
// Round returns the nearest integer, rounding half away from zero.
//
// Special cases are:
//
// Round(±0) = ±0
// Round(±Inf) = ±Inf
// Round(NaN) = NaN
func Round(x float32) float32 {
return math32.Round(x)
}
// RoundToEven returns the nearest integer, rounding ties to even.
//
// Special cases are:
//
// RoundToEven(±0) = ±0
// RoundToEven(±Inf) = ±Inf
// RoundToEven(NaN) = NaN
func RoundToEven(x float32) float32 {
return float32(math.RoundToEven(float64(x)))
}
// Signbit returns true if x is negative or negative zero.
func Signbit(x float32) bool {
return math32.Signbit(x)
}
// Sin returns the sine of the radian argument x.
//
// Special cases are:
//
// Sin(±0) = ±0
// Sin(±Inf) = NaN
// Sin(NaN) = NaN
func Sin(x float32) float32 {
return math32.Sin(x)
}
// Sincos returns Sin(x), Cos(x).
//
// Special cases are:
//
// Sincos(±0) = ±0, 1
// Sincos(±Inf) = NaN, NaN
// Sincos(NaN) = NaN, NaN
func Sincos(x float32) (sin, cos float32) {
return math32.Sincos(x)
}
// Sinh returns the hyperbolic sine of x.
//
// Special cases are:
//
// Sinh(±0) = ±0
// Sinh(±Inf) = ±Inf
// Sinh(NaN) = NaN
func Sinh(x float32) float32 {
return math32.Sinh(x)
}
// Sqrt returns the square root of x.
//
// Special cases are:
//
// Sqrt(+Inf) = +Inf
// Sqrt(±0) = ±0
// Sqrt(x < 0) = NaN
// Sqrt(NaN) = NaN
func Sqrt(x float32) float32 {
return math32.Sqrt(x)
}
// Tan returns the tangent of the radian argument x.
//
// Special cases are:
//
// Tan(±0) = ±0
// Tan(±Inf) = NaN
// Tan(NaN) = NaN
func Tan(x float32) float32 {
return math32.Tan(x)
}
// Tanh returns the hyperbolic tangent of x.
//
// Special cases are:
//
// Tanh(±0) = ±0
// Tanh(±Inf) = ±1
// Tanh(NaN) = NaN
func Tanh(x float32) float32 {
return math32.Tanh(x)
}
// Trunc returns the integer value of x.
//
// Special cases are:
//
// Trunc(±0) = ±0
// Trunc(±Inf) = ±Inf
// Trunc(NaN) = NaN
func Trunc(x float32) float32 {
return math32.Trunc(x)
}
// Y0 returns the order-zero Bessel function of the second kind.
//
// Special cases are:
//
// Y0(+Inf) = 0
// Y0(0) = -Inf
// Y0(x < 0) = NaN
// Y0(NaN) = NaN
func Y0(x float32) float32 {
return math32.Y0(x)
}
// Y1 returns the order-one Bessel function of the second kind.
//
// Special cases are:
//
// Y1(+Inf) = 0
// Y1(0) = -Inf
// Y1(x < 0) = NaN
// Y1(NaN) = NaN
func Y1(x float32) float32 {
return math32.Y1(x)
}
// Yn returns the order-n Bessel function of the second kind.
//
// Special cases are:
//
// Yn(n, +Inf) = 0
// Yn(n ≥ 0, 0) = -Inf
// Yn(n < 0, 0) = +Inf if n is odd, -Inf if n is even
// Yn(n, x < 0) = NaN
// Yn(n, NaN) = NaN
func Yn(n int, x float32) float32 {
return math32.Yn(n, x)
}
//////// Special additions to math. functions
// Clamp clamps x to the provided closed interval [a, b]
func Clamp[T cmp.Ordered](x, a, b T) T {
if x < a {
return a
}
if x > b {
return b
}
return x
}
// MinPos returns the minimum of the two values, excluding any that are <= 0
func MinPos(a, b float32) float32 {
if a > 0 && b > 0 {
return Min(a, b)
} else if a > 0 {
return a
} else if b > 0 {
return b
}
return a
}
// MaxPos returns the minimum of the two values, excluding any that are <= 0
func MaxPos(a, b float32) float32 {
if a > 0 && b > 0 {
return Max(a, b)
} else if a > 0 {
return a
} else if b > 0 {
return b
}
return a
}
// IntMultiple returns the interger multiple of mod closest to given value:
// Round(val / mod) * mod
func IntMultiple(val, mod float32) float32 {
return Round(val/mod) * mod
}
// IntMultipleGE returns the interger multiple of mod >= given value:
// Ceil(val / mod) * mod
func IntMultipleGE(val, mod float32) float32 {
return Ceil(val/mod) * mod
}
// TODO: maybe make these functions faster at some point
// Truncate rounds a float32 number to the given level of precision,
// which the number of significant digits to include in the result.
func Truncate(val float32, prec int) float32 {
frep := strconv.FormatFloat(float64(val), 'g', prec, 32)
tval, _ := strconv.ParseFloat(frep, 32)
return float32(tval)
// note: this unfortunately does not work. also Pow(prec) is not likely to be that much faster ;)
// pow := Pow(10, float32(prec))
// return Round(val*pow) / pow
}
// Truncate64 rounds a float64 number to the given level of precision,
// which the number of significant digits to include in the result.
func Truncate64(val float64, prec int) float64 {
frep := strconv.FormatFloat(val, 'g', prec, 64)
val, _ = strconv.ParseFloat(frep, 64)
return val
// note: this unfortunately does not work. also Pow(prec) is not likely to be that much faster ;)
// pow := math.Pow(10, float64(prec))
// return math.Round(val*pow) / pow
}
// WrapMax returns x wrapped in the interval [0..max).
func WrapMax(x, mx float32) float32 {
// integer math: (max + x % max) % max
return Mod(mx+Mod(x, mx), mx)
}
// WrapMinMax returns x wrapped in the interval [min..max).
func WrapMinMax(x, mn, mx float32) float32 {
return mn + WrapMax(x-mn, mx-mn)
}
// WrapPi wraps the value into the [-Pi, Pi) interval.
func WrapPi(x float32) float32 {
w := WrapMinMax(x, -Pi, Pi)
return w
}
// MinAngleDiff returns the minimum difference between two angles
// (in radians): a-b, dealing with the wrap-around issues with angles.
func MinAngleDiff(a, b float32) float32 {
d := WrapPi(a) - WrapPi(b)
if d > Pi {
d -= 2 * Pi
}
if d < -Pi {
d += 2 * Pi
}
return d
}
// Copyright (c) 2020, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package math32
import (
"fmt"
"log"
"strconv"
"strings"
"unicode"
"cogentcore.org/core/base/errors"
"golang.org/x/image/math/fixed"
)
/*
This is heavily modified from: https://github.com/fogleman/gg
Copyright (C) 2016 Michael Fogleman
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
// Matrix2 is a 3x2 matrix.
// [XX YX]
// [XY YY]
// [X0 Y0]
type Matrix2 struct {
XX, YX, XY, YY, X0, Y0 float32
}
// Identity2 returns a new identity [Matrix2] matrix.
func Identity2() Matrix2 {
return Matrix2{
1, 0,
0, 1,
0, 0,
}
}
func (a Matrix2) IsIdentity() bool {
return a.XX == 1 && a.YX == 0 && a.XY == 0 && a.YY == 1 && a.X0 == 0 && a.Y0 == 0
}
// Translate2D returns a Matrix2 2D matrix with given translations
func Translate2D(x, y float32) Matrix2 {
return Matrix2{
1, 0,
0, 1,
x, y,
}
}
// Scale2D returns a Matrix2 2D matrix with given scaling factors
func Scale2D(x, y float32) Matrix2 {
return Matrix2{
x, 0,
0, y,
0, 0,
}
}
// Rotate2D returns a Matrix2 2D matrix with given rotation, specified in radians.
// This uses the standard graphics convention where increasing Y goes _down_ instead
// of up, in contrast with the mathematical coordinate system where Y is up.
func Rotate2D(angle float32) Matrix2 {
s, c := Sincos(angle)
return Matrix2{
c, s,
-s, c,
0, 0,
}
}
// Rotate2DAround returns a Matrix2 2D matrix with given rotation, specified in radians,
// around given offset point that is translated to and from.
// This uses the standard graphics convention where increasing Y goes _down_ instead
// of up, in contrast with the mathematical coordinate system where Y is up.
func Rotate2DAround(angle float32, pos Vector2) Matrix2 {
return Identity2().Translate(pos.X, pos.Y).Rotate(angle).Translate(-pos.X, -pos.Y)
}
// Shear2D returns a Matrix2 2D matrix with given shearing
func Shear2D(x, y float32) Matrix2 {
return Matrix2{
1, y,
x, 1,
0, 0,
}
}
// Skew2D returns a Matrix2 2D matrix with given skewing
func Skew2D(x, y float32) Matrix2 {
return Matrix2{
1, Tan(y),
Tan(x), 1,
0, 0,
}
}
// Mul returns a*b
func (a Matrix2) Mul(b Matrix2) Matrix2 {
return Matrix2{
XX: a.XX*b.XX + a.XY*b.YX,
YX: a.YX*b.XX + a.YY*b.YX,
XY: a.XX*b.XY + a.XY*b.YY,
YY: a.YX*b.XY + a.YY*b.YY,
X0: a.XX*b.X0 + a.XY*b.Y0 + a.X0,
Y0: a.YX*b.X0 + a.YY*b.Y0 + a.Y0,
}
}
// SetMul sets a to a*b
func (a *Matrix2) SetMul(b Matrix2) {
*a = a.Mul(b)
}
// MulVector multiplies the Vector2 as a vector without adding translations.
// This is for directional vectors and not points.
func (a Matrix2) MulVector(v Vector2) Vector2 {
tx := a.XX*v.X + a.XY*v.Y
ty := a.YX*v.X + a.YY*v.Y
return Vec2(tx, ty)
}
// MulPoint multiplies the Vector2 as a point, including adding translations.
func (a Matrix2) MulPoint(v Vector2) Vector2 {
tx := a.XX*v.X + a.XY*v.Y + a.X0
ty := a.YX*v.X + a.YY*v.Y + a.Y0
return Vec2(tx, ty)
}
// MulFixedPoint multiplies the fixed point as a point, including adding translations.
func (a Matrix2) MulFixedPoint(fp fixed.Point26_6) fixed.Point26_6 {
x := fixed.Int26_6((float32(fp.X)*a.XX + float32(fp.Y)*a.XY) + a.X0*64) // 64 per unit
y := fixed.Int26_6((float32(fp.X)*a.YX + float32(fp.Y)*a.YY) + a.Y0*64)
return fixed.Point26_6{X: x, Y: y}
}
func (a Matrix2) Translate(x, y float32) Matrix2 {
return a.Mul(Translate2D(x, y))
}
func (a Matrix2) Scale(x, y float32) Matrix2 {
return a.Mul(Scale2D(x, y))
}
// ScaleAbout adds a scaling transformation about (x,y) in sx and sy.
// When scale is negative it will flip those axes.
func (a Matrix2) ScaleAbout(sx, sy, x, y float32) Matrix2 {
return a.Translate(x, y).Scale(sx, sy).Translate(-x, -y)
}
func (a Matrix2) Rotate(angle float32) Matrix2 {
return a.Mul(Rotate2D(angle))
}
// RotateAbout adds a rotation transformation about (x,y)
// with rot in radians counter clockwise.
func (a Matrix2) RotateAbout(rot, x, y float32) Matrix2 {
return a.Translate(x, y).Rotate(rot).Translate(-x, -y)
}
func (a Matrix2) Shear(x, y float32) Matrix2 {
return a.Mul(Shear2D(x, y))
}
func (a Matrix2) Skew(x, y float32) Matrix2 {
return a.Mul(Skew2D(x, y))
}
// ExtractRot does a simple extraction of the rotation matrix for
// a single rotation. See [Matrix2.Decompose] for two rotations.
func (a Matrix2) ExtractRot() float32 {
return Atan2(-a.XY, a.XX)
}
// ExtractScale extracts the X and Y scale factors after undoing any
// rotation present -- i.e., in the original X, Y coordinates
func (a Matrix2) ExtractScale() (scx, scy float32) {
_, _, _, scx, scy, _ = a.Decompose()
return
}
// Pos returns the translation values, X0, Y0
func (a Matrix2) Pos() (tx, ty float32) {
return a.X0, a.Y0
}
// Decompose extracts the translation, rotation, scaling and rotation components
// (applied in the reverse order) as (tx, ty, theta, sx, sy, phi) with rotation
// counter clockwise. This corresponds to:
// Identity.Translate(tx, ty).Rotate(phi).Scale(sx, sy).Rotate(theta).
func (a Matrix2) Decompose() (tx, ty, phi, sx, sy, theta float32) {
// see https://math.stackexchange.com/questions/861674/decompose-a-2d-arbitrary-transform-into-only-scaling-and-rotation
E := (a.XX + a.YY) / 2.0
F := (a.XX - a.YY) / 2.0
G := (a.YX + a.XY) / 2.0
H := (a.YX - a.XY) / 2.0
Q, R := Sqrt(E*E+H*H), Sqrt(F*F+G*G)
sx, sy = Q+R, Q-R
a1, a2 := Atan2(G, F), Atan2(H, E)
// note: our rotation matrix is inverted so we reverse the sign on these.
theta = -(a2 - a1) / 2.0
phi = -(a2 + a1) / 2.0
if sx == 1 && sy == 1 {
theta += phi
phi = 0
}
tx = a.X0
ty = a.Y0
return
}
// Transpose returns the transpose of the matrix
func (a Matrix2) Transpose() Matrix2 {
a.XY, a.YX = a.YX, a.XY
return a
}
// Det returns the determinant of the matrix
func (a Matrix2) Det() float32 {
return a.XX*a.YY - a.XY*a.YX // ad - bc
}
// Inverse returns inverse of matrix, for inverting transforms
func (a Matrix2) Inverse() Matrix2 {
// homogenous rep, rc indexes, mapping into Matrix3 code
// XX YX X0 n11 n12 n13 a b x
// XY YY Y0 n21 n22 n23 c d y
// 0 0 1 n31 n32 n33 0 0 1
// t11 := a.YY
// t12 := -a.YX
// t13 := a.Y0*a.YX - a.YY*a.X0
det := a.Det()
detInv := 1 / det
b := Matrix2{}
b.XX = a.YY * detInv // a = d
b.XY = -a.XY * detInv // c = -c
b.YX = -a.YX * detInv // b = -b
b.YY = a.XX * detInv // d = a
b.X0 = (a.Y0*a.XY - a.YY*a.X0) * detInv
b.Y0 = (a.X0*a.YX - a.XX*a.Y0) * detInv
return b
}
// mapping onto canvas, [col][row] matrix:
// m[0][0] = XX
// m[1][0] = YX
// m[0][1] = XY
// m[1][1] = YY
// m[0][2] = X0
// m[1][2] = Y0
// Eigen returns the matrix eigenvalues and eigenvectors.
// The first eigenvalue is related to the first eigenvector,
// and so for the second pair. Eigenvectors are normalized.
func (a Matrix2) Eigen() (float32, float32, Vector2, Vector2) {
if Abs(a.YX) < 1.0e-7 && Abs(a.XY) < 1.0e-7 {
return a.XX, a.YY, Vector2{1.0, 0.0}, Vector2{0.0, 1.0}
}
lambda1, lambda2 := solveQuadraticFormula(1.0, -a.XX-a.YY, a.Det())
if IsNaN(lambda1) && IsNaN(lambda2) {
// either m.XX or m.YY is NaN or the the affine matrix has no real eigenvalues
return lambda1, lambda2, Vector2{}, Vector2{}
} else if IsNaN(lambda2) {
lambda2 = lambda1
}
// see http://www.math.harvard.edu/archive/21b_fall_04/exhibits/2dmatrices/index.html
var v1, v2 Vector2
if a.YX != 0 {
v1 = Vector2{lambda1 - a.YY, a.YX}.Normal()
v2 = Vector2{lambda2 - a.YY, a.YX}.Normal()
} else if a.XY != 0 {
v1 = Vector2{a.XY, lambda1 - a.XX}.Normal()
v2 = Vector2{a.XY, lambda2 - a.XX}.Normal()
}
return lambda1, lambda2, v1, v2
}
// Numerically stable quadratic formula, lowest root is returned first,
// see https://math.stackexchange.com/a/2007723
func solveQuadraticFormula(a, b, c float32) (float32, float32) {
if a == 0 {
if b == 0 {
if c == 0 {
// all terms disappear, all x satisfy the solution
return 0.0, NaN()
}
// linear term disappears, no solutions
return NaN(), NaN()
}
// quadratic term disappears, solve linear equation
return -c / b, NaN()
}
if c == 0 {
// no constant term, one solution at zero and one from solving linearly
if b == 0 {
return 0.0, NaN()
}
return 0.0, -b / a
}
discriminant := b*b - 4.0*a*c
if discriminant < 0.0 {
return NaN(), NaN()
} else if discriminant == 0 {
return -b / (2.0 * a), NaN()
}
// Avoid catastrophic cancellation, which occurs when we subtract
// two nearly equal numbers and causes a large error.
// This can be the case when 4*a*c is small so that sqrt(discriminant) -> b,
// and the sign of b and in front of the radical are the same.
// Instead, we calculate x where b and the radical have different signs,
// and then use this result in the analytical equivalent of the formula,
// called the Citardauq Formula.
q := Sqrt(discriminant)
if b < 0.0 {
// apply sign of b
q = -q
}
x1 := -(b + q) / (2.0 * a)
x2 := c / (a * x1)
if x2 < x1 {
x1, x2 = x2, x1
}
return x1, x2
}
// ParseFloat32 logs any strconv.ParseFloat errors
func ParseFloat32(pstr string) (float32, error) {
r, err := strconv.ParseFloat(pstr, 32)
if err != nil {
log.Printf("core.ParseFloat32: error parsing float32 number from: %v, %v\n", pstr, err)
return float32(0.0), err
}
return float32(r), nil
}
// ParseAngle32 returns radians angle from string that can specify units (deg,
// grad, rad) -- deg is assumed if not specified
func ParseAngle32(pstr string) (float32, error) {
units := "deg"
lstr := strings.ToLower(pstr)
if strings.Contains(lstr, "deg") {
units = "deg"
lstr = strings.TrimSuffix(lstr, "deg")
} else if strings.Contains(lstr, "grad") {
units = "grad"
lstr = strings.TrimSuffix(lstr, "grad")
} else if strings.Contains(lstr, "rad") {
units = "rad"
lstr = strings.TrimSuffix(lstr, "rad")
}
r, err := strconv.ParseFloat(lstr, 32)
if err != nil {
log.Printf("core.ParseAngle32: error parsing float32 number from: %v, %v\n", lstr, err)
return float32(0.0), err
}
switch units {
case "deg":
return DegToRad(float32(r)), nil
case "grad":
return float32(r) * Pi / 200, nil
case "rad":
return float32(r), nil
}
return float32(r), nil
}
// ReadPoints reads a set of floating point values from a SVG format number
// string -- returns a slice or nil if there was an error
func ReadPoints(pstr string) []float32 {
lastIndex := -1
var pts []float32
lr := ' '
for i, r := range pstr {
if !unicode.IsNumber(r) && r != '.' && (r != '-' || lr != 'e') && r != 'e' {
if lastIndex != -1 {
s := pstr[lastIndex:i]
p, err := ParseFloat32(s)
if err != nil {
return nil
}
pts = append(pts, p)
}
if r == '-' {
lastIndex = i
} else {
lastIndex = -1
}
} else if lastIndex == -1 {
lastIndex = i
}
lr = r
}
if lastIndex != -1 && lastIndex != len(pstr) {
s := pstr[lastIndex:]
p, err := ParseFloat32(s)
if err != nil {
return nil
}
pts = append(pts, p)
}
return pts
}
// PointsCheckN checks the number of points read and emits an error if not equal to n
func PointsCheckN(pts []float32, n int, errmsg string) error {
if len(pts) != n {
return fmt.Errorf("%v incorrect number of points: %v != %v", errmsg, len(pts), n)
}
return nil
}
// SetString processes the standard SVG-style transform strings
func (a *Matrix2) SetString(str string) error {
errmsg := "math32.Matrix2.SetString:"
str = strings.ToLower(strings.TrimSpace(str))
*a = Identity2()
if str == "none" {
*a = Identity2()
return nil
}
// could have multiple transforms
for {
pidx := strings.IndexByte(str, '(')
if pidx < 0 {
err := fmt.Errorf("%s no params for transform: %v", errmsg, str)
return errors.Log(err)
}
cmd := str[:pidx]
vals := str[pidx+1:]
nxt := ""
eidx := strings.IndexByte(vals, ')')
if eidx > 0 {
nxt = strings.TrimSpace(vals[eidx+1:])
if after, ok := strings.CutPrefix(nxt, ";"); ok {
nxt = strings.TrimSpace(after)
}
vals = vals[:eidx]
}
pts := ReadPoints(vals)
switch cmd {
case "matrix":
if err := PointsCheckN(pts, 6, errmsg); err != nil {
errors.Log(err)
} else {
*a = Matrix2{pts[0], pts[1], pts[2], pts[3], pts[4], pts[5]}
}
case "translate":
if len(pts) == 1 {
*a = a.Translate(pts[0], 0)
} else if len(pts) == 2 {
*a = a.Translate(pts[0], pts[1])
} else {
errors.Log(PointsCheckN(pts, 2, errmsg))
}
case "translatex":
if err := PointsCheckN(pts, 1, errmsg); err != nil {
errors.Log(err)
} else {
*a = a.Translate(pts[0], 0)
}
case "translatey":
if err := PointsCheckN(pts, 1, errmsg); err != nil {
errors.Log(err)
} else {
*a = a.Translate(0, pts[0])
}
case "scale":
if len(pts) == 1 {
*a = a.Scale(pts[0], pts[0])
} else if len(pts) == 2 {
*a = a.Scale(pts[0], pts[1])
} else {
err := fmt.Errorf("%v incorrect number of points: 2 != %v", errmsg, len(pts))
errors.Log(err)
}
case "scalex":
if err := PointsCheckN(pts, 1, errmsg); err != nil {
errors.Log(err)
} else {
*a = a.Scale(pts[0], 1)
}
case "scaley":
if err := PointsCheckN(pts, 1, errmsg); err != nil {
errors.Log(err)
} else {
*a = a.Scale(1, pts[0])
}
case "rotate":
ang := DegToRad(pts[0]) // always in degrees in this form
if len(pts) == 3 {
*a = a.Translate(pts[1], pts[2]).Rotate(ang).Translate(-pts[1], -pts[2])
} else if len(pts) == 1 {
*a = a.Rotate(ang)
} else {
errors.Log(PointsCheckN(pts, 1, errmsg))
}
case "skew":
if err := PointsCheckN(pts, 2, errmsg); err != nil {
errors.Log(err)
} else {
*a = a.Skew(DegToRad(pts[0]), DegToRad(pts[1])) // in degrees, as rotate
}
case "skewx":
if err := PointsCheckN(pts, 1, errmsg); err != nil {
errors.Log(err)
} else {
*a = a.Skew(DegToRad(pts[0]), 0)
}
case "skewy":
if err := PointsCheckN(pts, 1, errmsg); err != nil {
errors.Log(err)
} else {
*a = a.Skew(0, DegToRad(pts[0]))
}
default:
return fmt.Errorf("unknown command %q", cmd)
}
if nxt == "" {
break
}
if !strings.Contains(nxt, "(") {
break
}
str = nxt
}
return nil
}
// String returns the XML-based string representation of the transform
func (a *Matrix2) String() string {
if a.IsIdentity() {
return "none"
}
if a.YX == 0 && a.XY == 0 { // no rotation, emit scale and translate
str := ""
if a.X0 != 0 || a.Y0 != 0 {
str += fmt.Sprintf("translate(%g,%g)", a.X0, a.Y0)
}
if a.XX != 1 || a.YY != 1 {
if str != "" {
str += " "
}
str += fmt.Sprintf("scale(%g,%g)", a.XX, a.YY)
}
return str
}
// just report the whole matrix
return fmt.Sprintf("matrix(%g,%g,%g,%g,%g,%g)", a.XX, a.YX, a.XY, a.YY, a.X0, a.Y0)
}
// Copyright 2019 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Initially copied from G3N: github.com/g3n/engine/math32
// Copyright 2016 The G3N Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// with modifications needed to suit Cogent Core functionality.
package math32
import "errors"
// Matrix3 is 3x3 matrix organized internally as column matrix,
// with columns as the inner dimension: element (row i, column j) is at
// index j*3+i.
//
// All of the Mul methods multiply the vector or point on the right
// (m * v), as in [Matrix2], [Matrix4] and the WGSL mat3x3f type, so a
// chain of [Matrix3.Mul] calls applies its transforms right to left.
type Matrix3 [9]float32
// note: matrix indexes and dimensions are row,column.
// Mat3 constructs a new Matrix3 from given values, in column-wise order.
func Mat3(n11, n21, n31, n12, n22, n32, n13, n23, n33 float32) Matrix3 {
m := Matrix3{}
m.Set(n11, n21, n31, n12, n22, n32, n13, n23, n33)
return m
}
// Identity3 returns a new identity [Matrix3] matrix.
func Identity3() Matrix3 {
m := Matrix3{}
m.SetIdentity()
return m
}
func Matrix3FromMatrix2(m Matrix2) Matrix3 {
nm := Matrix3{}
nm.SetFromMatrix2(m)
return nm
}
func Matrix3FromMatrix4(m *Matrix4) Matrix3 {
nm := Matrix3{}
nm.SetFromMatrix4(m)
return nm
}
// Matrix3Translate2D returns a Matrix3 2D matrix with given translations
func Matrix3Translate2D(x, y float32) Matrix3 {
return Matrix3FromMatrix2(Translate2D(x, y))
}
// Matrix3Scale2D returns a Matrix3 2D matrix with given scaling factors
func Matrix3Scale2D(x, y float32) Matrix3 {
return Matrix3FromMatrix2(Scale2D(x, y))
}
// Matrix3Rotate2D returns a Matrix3 2D matrix with given rotation, specified in radians
func Matrix3Rotate2D(angle float32) Matrix3 {
return Matrix3FromMatrix2(Rotate2D(angle))
}
// Set sets all the elements of the matrix col by col starting at row1, column1,
// row2, column1, row3, column1 and so forth.
func (m *Matrix3) Set(n11, n21, n31, n12, n22, n32, n13, n23, n33 float32) {
m[0] = n11
m[1] = n21
m[2] = n31
m[3] = n12
m[4] = n22
m[5] = n32
m[6] = n13
m[7] = n23
m[8] = n33
}
// SetFromMatrix4 sets the matrix elements based on a Matrix4.
func (m *Matrix3) SetFromMatrix4(src *Matrix4) {
m.Set(
src[0], src[1], src[2],
src[4], src[5], src[6],
src[8], src[9], src[10],
)
}
// SetFromMatrix2 sets the matrix elements based on a Matrix2,
// as a standard homogeneous 2D affine matrix with the translation
// in the third column, so that [Matrix3.MulPoint] on the result
// matches [Matrix2.MulPoint] on the source.
func (m *Matrix3) SetFromMatrix2(src Matrix2) {
m.Set(
src.XX, src.YX, 0,
src.XY, src.YY, 0,
src.X0, src.Y0, 1,
)
}
// FromArray sets this matrix array starting at offset.
func (m *Matrix3) FromArray(array []float32, offset int) {
copy(m[:], array[offset:])
}
// ToArray copies this matrix to array starting at offset.
func (m Matrix3) ToArray(array []float32, offset int) {
copy(array[offset:], m[:])
}
// SetIdentity sets this matrix as the identity matrix.
func (m *Matrix3) SetIdentity() {
m.Set(
1, 0, 0,
0, 1, 0,
0, 0, 1,
)
}
// SetZero sets this matrix as the zero matrix.
func (m *Matrix3) SetZero() {
m.Set(
0, 0, 0,
0, 0, 0,
0, 0, 0,
)
}
// CopyFrom copies from source matrix into this matrix
// (a regular = assign does not copy data, just the pointer!)
func (m *Matrix3) CopyFrom(src Matrix3) {
copy(m[:], src[:])
}
// MulMatrices sets this matrix as the matrix multiplication a * b,
// in the standard sense: element (row i, column j) of the result is
// row i of a dotted with column j of b. This matches
// [Matrix4.MulMatrices] and the WGSL mat3x3f * operator.
func (m *Matrix3) MulMatrices(a, b Matrix3) {
a11 := a[0]
a21 := a[1]
a31 := a[2]
a12 := a[3]
a22 := a[4]
a32 := a[5]
a13 := a[6]
a23 := a[7]
a33 := a[8]
b11 := b[0]
b21 := b[1]
b31 := b[2]
b12 := b[3]
b22 := b[4]
b32 := b[5]
b13 := b[6]
b23 := b[7]
b33 := b[8]
m[0] = a11*b11 + a12*b21 + a13*b31
m[1] = a21*b11 + a22*b21 + a23*b31
m[2] = a31*b11 + a32*b21 + a33*b31
m[3] = a11*b12 + a12*b22 + a13*b32
m[4] = a21*b12 + a22*b22 + a23*b32
m[5] = a31*b12 + a32*b22 + a33*b32
m[6] = a11*b13 + a12*b23 + a13*b33
m[7] = a21*b13 + a22*b23 + a23*b33
m[8] = a31*b13 + a32*b23 + a33*b33
}
// Mul returns this matrix times other matrix, as the standard product
// m * other (this matrix is unchanged). Because the Mul methods multiply
// the vector or point on the right, the transform of other is applied
// before the transform of this matrix.
func (m Matrix3) Mul(other Matrix3) Matrix3 {
nm := Matrix3{}
nm.MulMatrices(m, other)
return nm
}
// SetMul sets this matrix to the standard product of this matrix * other.
func (m *Matrix3) SetMul(other Matrix3) {
m.MulMatrices(*m, other)
}
// MulScalar returns each of this matrix's components multiplied by the specified
// scalar, leaving the original matrix unchanged.
func (m Matrix3) MulScalar(s float32) Matrix3 {
m.SetMulScalar(s)
return m
}
// SetMulScalar multiplies each of this matrix's components by the specified scalar.
func (m *Matrix3) SetMulScalar(s float32) {
m[0] *= s
m[1] *= s
m[2] *= s
m[3] *= s
m[4] *= s
m[5] *= s
m[6] *= s
m[7] *= s
m[8] *= s
}
// MulVector multiplies the Vector2 as a vector without adding translations.
// This is for directional vectors and not points.
func (m Matrix3) MulVector(v Vector2) Vector2 {
tx := m[0]*v.X + m[3]*v.Y
ty := m[1]*v.X + m[4]*v.Y
return Vec2(tx, ty)
}
// MulPoint multiplies the Vector2 as a point, including adding translations.
func (m Matrix3) MulPoint(v Vector2) Vector2 {
tx := m[0]*v.X + m[3]*v.Y + m[6]
ty := m[1]*v.X + m[4]*v.Y + m[7]
return Vec2(tx, ty)
}
// MulVector3 multiplies the Vector3 on the right (a * v),
// as a standard matrix multiply.
func (m Matrix3) MulVector3(v Vector3) Vector3 {
return Vec3(m[0]*v.X+m[3]*v.Y+m[6]*v.Z,
m[1]*v.X+m[4]*v.Y+m[7]*v.Z,
m[2]*v.X+m[5]*v.Y+m[8]*v.Z)
}
// MulVector3Array multiplies count vectors (i.e., 3 sequential array values per each increment in count)
// in the array starting at start index by this matrix.
func (m *Matrix3) MulVector3Array(array []float32, start, count int) {
var v1 Vector3
j := start
for range count {
v1.FromSlice(array, j)
mv := v1.MulMatrix3(m)
mv.ToSlice(array, j)
j += 3
}
}
// Determinant calculates and returns the determinant of this matrix.
func (m *Matrix3) Determinant() float32 {
return m[0]*m[4]*m[8] -
m[0]*m[5]*m[7] -
m[1]*m[3]*m[8] +
m[1]*m[5]*m[6] +
m[2]*m[3]*m[7] -
m[2]*m[4]*m[6]
}
// SetInverse sets this matrix to the inverse of the src matrix.
// If the src matrix cannot be inverted returns error and
// sets this matrix to the identity matrix.
func (m *Matrix3) SetInverse(src Matrix3) error {
n11 := src[0]
n21 := src[1]
n31 := src[2]
n12 := src[3]
n22 := src[4]
n32 := src[5]
n13 := src[6]
n23 := src[7]
n33 := src[8]
t11 := n33*n22 - n32*n23
t12 := n32*n13 - n33*n12
t13 := n23*n12 - n22*n13
det := n11*t11 + n21*t12 + n31*t13
// no inverse
if det == 0 {
m.SetIdentity()
return errors.New("cannot invert matrix, determinant is 0")
}
detInv := 1 / det
m[0] = t11 * detInv
m[1] = (n31*n23 - n33*n21) * detInv
m[2] = (n32*n21 - n31*n22) * detInv
m[3] = t12 * detInv
m[4] = (n33*n11 - n31*n13) * detInv
m[5] = (n31*n12 - n32*n11) * detInv
m[6] = t13 * detInv
m[7] = (n21*n13 - n23*n11) * detInv
m[8] = (n22*n11 - n21*n12) * detInv
return nil
}
// Inverse returns the inverse of this matrix.
// If the matrix cannot be inverted it silently
// sets this matrix to the identity matrix.
// See Try version for error.
func (m Matrix3) Inverse() Matrix3 {
nm := Matrix3{}
nm.SetInverse(m)
return nm
}
// InverseTry returns the inverse of this matrix.
// If the matrix cannot be inverted returns error and
// sets this matrix to the identity matrix.
func (m Matrix3) InverseTry() (Matrix3, error) {
nm := Matrix3{}
err := nm.SetInverse(m)
return nm, err
}
// SetTranspose transposes this matrix.
func (m *Matrix3) SetTranspose() {
m[1], m[3] = m[3], m[1]
m[2], m[6] = m[6], m[2]
m[5], m[7] = m[7], m[5]
}
// Transpose returns the transpose of this matrix.
func (m Matrix3) Transpose() Matrix3 {
nm := m
nm.SetTranspose()
return nm
}
// ScaleCols returns matrix with columns multiplied by the vector components.
// This can be used when multiplying this matrix by a diagonal matrix if we store
// the diagonal components as a vector.
func (m *Matrix3) ScaleCols(v Vector3) *Matrix3 {
nm := &Matrix3{}
*nm = *m
nm.SetScaleCols(v)
return nm
}
// SetScaleCols multiplies the matrix columns by the vector components.
// This can be used when multiplying this matrix by a diagonal matrix if we store
// the diagonal components as a vector.
func (m *Matrix3) SetScaleCols(v Vector3) {
m[0] *= v.X
m[1] *= v.X
m[2] *= v.X
m[3] *= v.Y
m[4] *= v.Y
m[5] *= v.Y
m[6] *= v.Z
m[7] *= v.Z
m[8] *= v.Z
}
//////// Special functions
// SetNormalMatrix set this matrix to the matrix that can transform the normal vectors
// from the src matrix which is used transform the vertices (e.g., a ModelView matrix).
// If the src matrix cannot be inverted returns error.
func (m *Matrix3) SetNormalMatrix(src *Matrix4) error {
var err error
*m, err = Matrix3FromMatrix4(src).InverseTry()
m.SetTranspose()
return err
}
// SetRotationFromQuat sets this matrix as a rotation matrix from the specified [Quat].
func (m *Matrix3) SetRotationFromQuat(q Quat) {
x := q.X
y := q.Y
z := q.Z
w := q.W
x2 := x + x
y2 := y + y
z2 := z + z
xx := x * x2
xy := x * y2
xz := x * z2
yy := y * y2
yz := y * z2
zz := z * z2
wx := w * x2
wy := w * y2
wz := w * z2
m[0] = 1 - (yy + zz)
m[3] = xy - wz
m[6] = xz + wy
m[1] = xy + wz
m[4] = 1 - (xx + zz)
m[7] = yz - wx
m[2] = xz - wy
m[5] = yz + wx
m[8] = 1 - (xx + yy)
}
// Copyright 2019 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Initially copied from G3N: github.com/g3n/engine/math32
// Copyright 2016 The G3N Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// with modifications needed to suit Cogent Core functionality.
package math32
import "errors"
// Matrix4 is 4x4 matrix organized internally as column matrix.
type Matrix4 [16]float32
// Identity4 returns a new identity [Matrix4] matrix.
func Identity4() *Matrix4 {
m := &Matrix4{}
m.SetIdentity()
return m
}
// Set sets all the elements of this matrix row by row starting at row1, column1,
// row1, column2, row1, column3 and so forth.
func (m *Matrix4) Set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 float32) {
m[0] = n11
m[4] = n12
m[8] = n13
m[12] = n14
m[1] = n21
m[5] = n22
m[9] = n23
m[13] = n24
m[2] = n31
m[6] = n32
m[10] = n33
m[14] = n34
m[3] = n41
m[7] = n42
m[11] = n43
m[15] = n44
}
// SetFromMatrix3 sets the matrix elements based on a Matrix3,
// filling in 0's for missing off-diagonal elements,
// and 1 on the diagonal.
func (m *Matrix4) SetFromMatrix3(src *Matrix3) {
m.Set(
src[0], src[3], src[6], 0,
src[1], src[4], src[7], 0,
src[2], src[5], src[8], 0,
0, 0, 0, 1,
)
}
// FromArray set this matrix elements from the array starting at offset.
func (m *Matrix4) FromArray(array []float32, offset int) {
copy(m[:], array[offset:])
}
// ToArray copies this matrix elements to array starting at offset.
func (m *Matrix4) ToArray(array []float32, offset int) {
copy(array[offset:], m[:])
}
// SetIdentity sets this matrix as the identity matrix.
func (m *Matrix4) SetIdentity() {
m.Set(
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1,
)
}
// SetZero sets this matrix as the zero matrix.
func (m *Matrix4) SetZero() {
m.Set(
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
)
}
// CopyFrom copies from source matrix into this matrix
// (a regular = assign does not copy data, just the pointer!)
func (m *Matrix4) CopyFrom(src *Matrix4) {
copy(m[:], src[:])
}
// CopyPos copies the position elements of the src matrix into this one.
func (m *Matrix4) CopyPos(src *Matrix4) {
m[12] = src[12]
m[13] = src[13]
m[14] = src[14]
}
// ExtractBasis returns the x,y,z basis vectors of this matrix.
func (m *Matrix4) ExtractBasis() (xAxis, yAxis, zAxis Vector3) {
xAxis.Set(m[0], m[1], m[2])
yAxis.Set(m[4], m[5], m[6])
zAxis.Set(m[8], m[9], m[10])
return
}
// SetBasis sets this matrix basis vectors from the specified vectors.
func (m *Matrix4) SetBasis(xAxis, yAxis, zAxis Vector3) {
m.Set(
xAxis.X, yAxis.X, zAxis.X, 0,
xAxis.Y, yAxis.Y, zAxis.Y, 0,
xAxis.Z, yAxis.Z, zAxis.Z, 0,
0, 0, 0, 1,
)
}
// MulMatrices sets this matrix as matrix multiplication a by b (i.e. a*b).
func (m *Matrix4) MulMatrices(a, b *Matrix4) {
a11 := a[0]
a12 := a[4]
a13 := a[8]
a14 := a[12]
a21 := a[1]
a22 := a[5]
a23 := a[9]
a24 := a[13]
a31 := a[2]
a32 := a[6]
a33 := a[10]
a34 := a[14]
a41 := a[3]
a42 := a[7]
a43 := a[11]
a44 := a[15]
b11 := b[0]
b12 := b[4]
b13 := b[8]
b14 := b[12]
b21 := b[1]
b22 := b[5]
b23 := b[9]
b24 := b[13]
b31 := b[2]
b32 := b[6]
b33 := b[10]
b34 := b[14]
b41 := b[3]
b42 := b[7]
b43 := b[11]
b44 := b[15]
m[0] = a11*b11 + a12*b21 + a13*b31 + a14*b41
m[4] = a11*b12 + a12*b22 + a13*b32 + a14*b42
m[8] = a11*b13 + a12*b23 + a13*b33 + a14*b43
m[12] = a11*b14 + a12*b24 + a13*b34 + a14*b44
m[1] = a21*b11 + a22*b21 + a23*b31 + a24*b41
m[5] = a21*b12 + a22*b22 + a23*b32 + a24*b42
m[9] = a21*b13 + a22*b23 + a23*b33 + a24*b43
m[13] = a21*b14 + a22*b24 + a23*b34 + a24*b44
m[2] = a31*b11 + a32*b21 + a33*b31 + a34*b41
m[6] = a31*b12 + a32*b22 + a33*b32 + a34*b42
m[10] = a31*b13 + a32*b23 + a33*b33 + a34*b43
m[14] = a31*b14 + a32*b24 + a33*b34 + a34*b44
m[3] = a41*b11 + a42*b21 + a43*b31 + a44*b41
m[7] = a41*b12 + a42*b22 + a43*b32 + a44*b42
m[11] = a41*b13 + a42*b23 + a43*b33 + a44*b43
m[15] = a41*b14 + a42*b24 + a43*b34 + a44*b44
}
// Mul returns this matrix times other matrix (this matrix is unchanged)
func (m *Matrix4) Mul(other *Matrix4) *Matrix4 {
nm := &Matrix4{}
nm.MulMatrices(m, other)
return nm
}
// SetMul sets this matrix to this matrix times other
func (m *Matrix4) SetMul(other *Matrix4) {
m.MulMatrices(m, other)
}
// MulScalar multiplies each element of this matrix by the specified scalar.
func (m *Matrix4) MulScalar(s float32) {
m[0] *= s
m[4] *= s
m[8] *= s
m[12] *= s
m[1] *= s
m[5] *= s
m[9] *= s
m[13] *= s
m[2] *= s
m[6] *= s
m[10] *= s
m[14] *= s
m[3] *= s
m[7] *= s
m[11] *= s
m[15] *= s
}
// MulVector3Array multiplies count vectors (i.e., 3 sequential array values per each increment in count)
// in the array starting at start index by this matrix.
func (m *Matrix4) MulVector3Array(array []float32, start, count int) {
var v1 Vector3
j := start
for range count {
v1.FromSlice(array, j)
mv := v1.MulMatrix4(m)
mv.ToSlice(array, j)
j += 3
}
}
// Determinant calculates and returns the determinant of this matrix.
func (m *Matrix4) Determinant() float32 {
n11 := m[0]
n12 := m[4]
n13 := m[8]
n14 := m[12]
n21 := m[1]
n22 := m[5]
n23 := m[9]
n24 := m[13]
n31 := m[2]
n32 := m[6]
n33 := m[10]
n34 := m[14]
n41 := m[3]
n42 := m[7]
n43 := m[11]
n44 := m[15]
return n41*(+n14*n23*n32-n13*n24*n32-n14*n22*n33+n12*n24*n33+n13*n22*n34-n12*n23*n34) +
n42*(+n11*n23*n34-n11*n24*n33+n14*n21*n33-n13*n21*n34+n13*n24*n31-n14*n23*n31) +
n43*(+n11*n24*n32-n11*n22*n34-n14*n21*n32+n12*n21*n34+n14*n22*n31-n12*n24*n31) +
n44*(-n13*n22*n31-n11*n23*n32+n11*n22*n33+n13*n21*n32-n12*n21*n33+n12*n23*n31)
}
// SetInverse sets this matrix to the inverse of the src matrix.
// If the src matrix cannot be inverted returns error and
// sets this matrix to the identity matrix.
func (m *Matrix4) SetInverse(src *Matrix4) error {
n11 := src[0]
n12 := src[4]
n13 := src[8]
n14 := src[12]
n21 := src[1]
n22 := src[5]
n23 := src[9]
n24 := src[13]
n31 := src[2]
n32 := src[6]
n33 := src[10]
n34 := src[14]
n41 := src[3]
n42 := src[7]
n43 := src[11]
n44 := src[15]
t11 := n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44
t12 := n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44
t13 := n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44
t14 := n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34
det := n11*t11 + n21*t12 + n31*t13 + n41*t14
if det == 0 {
m.SetIdentity()
return errors.New("cannot invert matrix, determinant is 0")
}
detInv := 1 / det
m[0] = t11 * detInv
m[1] = (n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44) * detInv
m[2] = (n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44) * detInv
m[3] = (n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43) * detInv
m[4] = t12 * detInv
m[5] = (n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44) * detInv
m[6] = (n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44) * detInv
m[7] = (n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43) * detInv
m[8] = t13 * detInv
m[9] = (n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44) * detInv
m[10] = (n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44) * detInv
m[11] = (n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43) * detInv
m[12] = t14 * detInv
m[13] = (n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34) * detInv
m[14] = (n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34) * detInv
m[15] = (n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33) * detInv
return nil
}
// Inverse returns the inverse of this matrix.
// If the matrix cannot be inverted returns error and
// sets this matrix to the identity matrix.
func (m *Matrix4) Inverse() (*Matrix4, error) {
nm := &Matrix4{}
err := nm.SetInverse(m)
return nm, err
}
// SetTranspose transposes this matrix.
func (m *Matrix4) SetTranspose() {
m[1], m[4] = m[4], m[1]
m[2], m[8] = m[8], m[2]
m[6], m[9] = m[9], m[6]
m[3], m[12] = m[12], m[3]
m[7], m[13] = m[13], m[7]
m[11], m[14] = m[14], m[11]
}
// Transpose returns the transpose of this matrix.
func (m *Matrix4) Transpose() *Matrix4 {
nm := *m
nm.SetTranspose()
return &nm
}
/////////////////////////////////////////////////////////////////////////////
// Translation, Rotation, Scaling transform
// ScaleCols returns matrix with first column of this matrix multiplied by the vector X component,
// the second column by the vector Y component and the third column by
// the vector Z component. The matrix fourth column is unchanged.
func (m *Matrix4) ScaleCols(v Vector3) *Matrix4 {
nm := &Matrix4{}
nm.SetScaleCols(v)
return nm
}
// SetScaleCols multiplies the first column of this matrix by the vector X component,
// the second column by the vector Y component and the third column by
// the vector Z component. The matrix fourth column is unchanged.
func (m *Matrix4) SetScaleCols(v Vector3) {
m[0] *= v.X
m[4] *= v.Y
m[8] *= v.Z
m[1] *= v.X
m[5] *= v.Y
m[9] *= v.Z
m[2] *= v.X
m[6] *= v.Y
m[10] *= v.Z
m[3] *= v.X
m[7] *= v.Y
m[11] *= v.Z
}
// GetMaxScaleOnAxis returns the maximum scale value of the 3 axes.
func (m *Matrix4) GetMaxScaleOnAxis() float32 {
scaleXSq := m[0]*m[0] + m[1]*m[1] + m[2]*m[2]
scaleYSq := m[4]*m[4] + m[5]*m[5] + m[6]*m[6]
scaleZSq := m[8]*m[8] + m[9]*m[9] + m[10]*m[10]
return Sqrt(Max(scaleXSq, Max(scaleYSq, scaleZSq)))
}
// SetTranslation sets this matrix to a translation matrix from the specified x, y and z values.
func (m *Matrix4) SetTranslation(x, y, z float32) {
m.Set(
1, 0, 0, x,
0, 1, 0, y,
0, 0, 1, z,
0, 0, 0, 1,
)
}
// SetRotationX sets this matrix to a rotation matrix of angle theta around the X axis.
func (m *Matrix4) SetRotationX(theta float32) {
c := Cos(theta)
s := Sin(theta)
m.Set(
1, 0, 0, 0,
0, c, -s, 0,
0, s, c, 0,
0, 0, 0, 1,
)
}
// SetRotationY sets this matrix to a rotation matrix of angle theta around the Y axis.
func (m *Matrix4) SetRotationY(theta float32) {
c := Cos(theta)
s := Sin(theta)
m.Set(
c, 0, s, 0,
0, 1, 0, 0,
-s, 0, c, 0,
0, 0, 0, 1,
)
}
// SetRotationZ sets this matrix to a rotation matrix of angle theta around the Z axis.
func (m *Matrix4) SetRotationZ(theta float32) {
c := Cos(theta)
s := Sin(theta)
m.Set(
c, -s, 0, 0,
s, c, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1,
)
}
// SetRotationAxis sets this matrix to a rotation matrix of the specified angle around the specified axis.
func (m *Matrix4) SetRotationAxis(axis *Vector3, angle float32) {
c := Cos(angle)
s := Sin(angle)
t := 1 - c
x := axis.X
y := axis.Y
z := axis.Z
tx := t * x
ty := t * y
m.Set(
tx*x+c, tx*y-s*z, tx*z+s*y, 0,
tx*y+s*z, ty*y+c, ty*z-s*x, 0,
tx*z-s*y, ty*z+s*x, t*z*z+c, 0,
0, 0, 0, 1,
)
}
// SetScale sets this matrix to a scale transformation matrix using the specified x, y and z values.
func (m *Matrix4) SetScale(x, y, z float32) {
m.Set(
x, 0, 0, 0,
0, y, 0, 0,
0, 0, z, 0,
0, 0, 0, 1,
)
}
// SetPos sets this transformation matrix position fields from the specified vector v.
func (m *Matrix4) SetPos(v Vector3) {
m[12] = v.X
m[13] = v.Y
m[14] = v.Z
}
// Pos returns the position component of the matrix
func (m *Matrix4) Pos() Vector3 {
pos := Vector3{}
pos.X = m[12]
pos.Y = m[13]
pos.Z = m[14]
return pos
}
// SetTransform sets this matrix to a transformation matrix for the specified position,
// rotation specified by the quaternion and scale.
func (m *Matrix4) SetTransform(pos Vector3, quat Quat, scale Vector3) {
m.SetRotationFromQuat(quat)
m.SetScaleCols(scale)
m.SetPos(pos)
}
// Decompose updates the position vector, quaternion and scale from this transformation matrix.
func (m *Matrix4) Decompose() (pos Vector3, quat Quat, scale Vector3) {
sx := Vec3(m[0], m[1], m[2]).Length()
sy := Vec3(m[4], m[5], m[6]).Length()
sz := Vec3(m[8], m[9], m[10]).Length()
// If determinant is negative, we need to invert one scale
det := m.Determinant()
if det < 0 {
sx = -sx
}
pos.X = m[12]
pos.Y = m[13]
pos.Z = m[14]
// Scale the rotation part
invSX := 1 / sx
invSY := 1 / sy
invSZ := 1 / sz
mat := *m
mat[0] *= invSX
mat[1] *= invSX
mat[2] *= invSX
mat[4] *= invSY
mat[5] *= invSY
mat[6] *= invSY
mat[8] *= invSZ
mat[9] *= invSZ
mat[10] *= invSZ
quat.SetFromRotationMatrix(&mat)
scale.X = sx
scale.Y = sy
scale.Z = sz
return
}
// ExtractRotation sets this matrix as rotation matrix from the src transformation matrix.
func (m *Matrix4) ExtractRotation(src *Matrix4) {
scaleX := 1 / Vec3(src[0], src[1], src[2]).Length()
scaleY := 1 / Vec3(src[4], src[5], src[6]).Length()
scaleZ := 1 / Vec3(src[8], src[9], src[10]).Length()
m[0] = src[0] * scaleX
m[1] = src[1] * scaleX
m[2] = src[2] * scaleX
m[4] = src[4] * scaleY
m[5] = src[5] * scaleY
m[6] = src[6] * scaleY
m[8] = src[8] * scaleZ
m[9] = src[9] * scaleZ
m[10] = src[10] * scaleZ
}
// SetRotationFromEuler set this a matrix as a rotation matrix from the specified euler angles.
func (m *Matrix4) SetRotationFromEuler(euler Vector3) {
x := euler.X
y := euler.Y
z := euler.Z
a := Cos(x)
b := Sin(x)
c := Cos(y)
d := Sin(y)
e := Cos(z)
f := Sin(z)
ae := a * e
af := a * f
be := b * e
bf := b * f
m[0] = c * e
m[4] = -c * f
m[8] = d
m[1] = af + be*d
m[5] = ae - bf*d
m[9] = -b * c
m[2] = bf - ae*d
m[6] = be + af*d
m[10] = a * c
// Last column
m[3] = 0
m[7] = 0
m[11] = 0
// Bottom row
m[12] = 0
m[13] = 0
m[14] = 0
m[15] = 1
}
// SetRotationFromQuat sets this matrix as a rotation matrix from the specified quaternion.
func (m *Matrix4) SetRotationFromQuat(q Quat) {
x := q.X
y := q.Y
z := q.Z
w := q.W
x2 := x + x
y2 := y + y
z2 := z + z
xx := x * x2
xy := x * y2
xz := x * z2
yy := y * y2
yz := y * z2
zz := z * z2
wx := w * x2
wy := w * y2
wz := w * z2
m[0] = 1 - (yy + zz)
m[4] = xy - wz
m[8] = xz + wy
m[1] = xy + wz
m[5] = 1 - (xx + zz)
m[9] = yz - wx
m[2] = xz - wy
m[6] = yz + wx
m[10] = 1 - (xx + yy)
// last column
m[3] = 0
m[7] = 0
m[11] = 0
// bottom row
m[12] = 0
m[13] = 0
m[14] = 0
m[15] = 1
}
// LookAt sets this matrix as view transform matrix with origin at eye,
// looking at target and using the up vector.
func (m *Matrix4) LookAt(eye, target, up Vector3) {
z := eye.Sub(target)
if z.LengthSquared() == 0 {
// Eye and target are in the same position
z.Z = 1
}
z.SetNormal()
x := up.Cross(z)
if x.LengthSquared() == 0 { // Up and Z are parallel
if Abs(up.Z) == 1 {
z.X += 0.0001
} else {
z.Z += 0.0001
}
z.SetNormal()
x = up.Cross(z)
}
x.SetNormal()
y := z.Cross(x)
m[0] = x.X
m[1] = x.Y
m[2] = x.Z
m[4] = y.X
m[5] = y.Y
m[6] = y.Z
m[8] = z.X
m[9] = z.Y
m[10] = z.Z
}
// NewLookAt returns Matrix4 matrix as view transform matrix with origin at eye,
// looking at target and using the up vector.
func NewLookAt(eye, target, up Vector3) *Matrix4 {
rotMat := &Matrix4{}
rotMat.LookAt(eye, target, up)
return rotMat
}
// SetFrustum sets this matrix to a projection frustum matrix bounded
// by the specified planes.
func (m *Matrix4) SetFrustum(left, right, bottom, top, near, far float32) {
fmn := far - near
m[0] = 2 * near / (right - left)
m[1] = 0
m[2] = 0
m[3] = 0
m[4] = 0
m[5] = 2 * near / (top - bottom)
m[6] = 0
m[7] = 0
m[8] = (right + left) / (right - left)
m[9] = (top + bottom) / (top - bottom)
m[10] = -(far + near) / fmn
m[11] = -1
m[12] = 0
m[13] = 0
m[14] = -(2 * far * near) / fmn
m[15] = 0
}
// SetPerspective sets this matrix to a perspective projection matrix
// with the specified field of view in degrees,
// aspect ratio (width/height) and near and far planes.
func (m *Matrix4) SetPerspective(fov, aspect, near, far float32) {
ymax := near * Tan(DegToRad(fov*0.5))
ymin := -ymax
xmin := ymin * aspect
xmax := ymax * aspect
m.SetFrustum(xmin, xmax, ymin, ymax, near, far)
}
// SetOrthographic sets this matrix to an orthographic projection matrix.
func (m *Matrix4) SetOrthographic(width, height, near, far float32) {
p := far - near
z := (far + near) / p
m[0] = 2 / width
m[4] = 0
m[8] = 0
m[12] = 0
m[1] = 0
m[5] = 2 / height
m[9] = 0
m[13] = 0
m[2] = 0
m[6] = 0
m[10] = -2 / p
m[14] = -z
m[3] = 0
m[7] = 0
m[11] = 0
m[15] = 1
}
// SetVkFrustum sets this matrix to a projection frustum matrix bounded by the specified planes.
// This version is for use with Vulkan, and does the equivalent of GLM_DEPTH_ZERO_ONE in glm
// and also multiplies the Y axis by -1, preserving the original OpenGL Y-up system.
// OpenGL provides a "natural" coordinate system for the physical world
// so it is useful to retain that for the world system and just convert
// on the way out to the render using this projection matrix.
func (m *Matrix4) SetVkFrustum(left, right, bottom, top, near, far float32) {
fmn := far - near
m[0] = 2 * near / (right - left)
m[1] = 0
m[2] = 0
m[3] = 0
m[4] = 0
m[5] = -2 * near / (top - bottom)
m[6] = 0
m[7] = 0
m[8] = (right + left) / (right - left)
m[9] = (top + bottom) / (top - bottom)
m[10] = -far / fmn
m[11] = -1
m[12] = 0
m[13] = 0
m[14] = -(far * near) / fmn
m[15] = 0
}
// SetVkPerspective sets this matrix to a vulkan appropriate perspective
// projection matrix, assuming the use of the OpenGL Y-up
// coordinate system for the geometry points.
// OpenGL provides a "natural" coordinate system for the physical world
// so it is useful to retain that for the world system and just convert
// on the way out to the render using this projection matrix.
// The specified field of view is in degrees,
// aspect ratio (width/height) and near and far planes.
func (m *Matrix4) SetVkPerspective(fov, aspect, near, far float32) {
ymax := near * Tan(DegToRad(fov*0.5))
ymin := -ymax
xmin := ymin * aspect
xmax := ymax * aspect
m.SetVkFrustum(xmin, xmax, ymin, ymax, near, far)
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package minmax
import (
"fmt"
"math"
)
//gosl:start
const (
MaxFloat32 float32 = 3.402823466e+38
MinFloat32 float32 = 1.175494351e-38
)
// AvgMax32 holds average and max statistics
type AvgMax32 struct {
Avg float32
Max float32
// sum for computing average
Sum float32
// index of max item
MaxIndex int32
// number of items in sum
N int32
pad, pad1, pad2 int32
}
// Init initializes prior to new updates
func (am *AvgMax32) Init() {
am.Avg = 0
am.Sum = 0
am.N = 0
am.Max = -MaxFloat32
am.MaxIndex = -1
}
// UpdateValue updates stats from given value
func (am *AvgMax32) UpdateValue(val float32, idx int32) {
am.Sum += val
am.N++
if val > am.Max {
am.Max = val
am.MaxIndex = idx
}
}
// UpdateFromOther updates these values from other AvgMax32 values
func (am *AvgMax32) UpdateFromOther(oSum, oMax float32, oN, oMaxIndex int32) {
am.Sum += oSum
am.N += oN
if oMax > am.Max {
am.Max = oMax
am.MaxIndex = oMaxIndex
}
}
// CalcAvg computes the average given the current Sum and N values
func (am *AvgMax32) CalcAvg() {
if am.N > 0 {
am.Avg = am.Sum / float32(am.N)
} else {
am.Avg = am.Sum
am.Max = am.Avg // prevents Max from being -MaxFloat..
}
}
//gosl:end
func (am *AvgMax32) String() string {
return fmt.Sprintf("{Avg: %g, Max: %g, Sum: %g, MaxIndex: %d, N: %d}", am.Avg, am.Max, am.Sum, am.MaxIndex, am.N)
}
// UpdateFrom updates these values from other AvgMax32 values
func (am *AvgMax32) UpdateFrom(oth *AvgMax32) {
am.UpdateFromOther(oth.Sum, oth.Max, oth.N, oth.MaxIndex)
}
// CopyFrom copies from other AvgMax32
func (am *AvgMax32) CopyFrom(oth *AvgMax32) {
*am = *oth
}
///////////////////////////////////////////////////////////////////////////
// 64
// AvgMax64 holds average and max statistics
type AvgMax64 struct {
Avg float64
Max float64
// sum for computing average
Sum float64
// index of max item
MaxIndex int32
// number of items in sum
N int32
}
// Init initializes prior to new updates
func (am *AvgMax64) Init() {
am.Avg = 0
am.Sum = 0
am.N = 0
am.Max = math.Inf(-1)
am.MaxIndex = -1
}
// UpdateValue updates stats from given value
func (am *AvgMax64) UpdateValue(val float64, idx int) {
am.Sum += val
am.N++
if val > am.Max {
am.Max = val
am.MaxIndex = int32(idx)
}
}
// CalcAvg computes the average given the current Sum and N values
func (am *AvgMax64) CalcAvg() {
if am.N > 0 {
am.Avg = am.Sum / float64(am.N)
} else {
am.Avg = am.Sum
am.Max = am.Avg // prevents Max from being -MaxFloat..
}
}
// UpdateFrom updates these values from other AvgMax64
func (am *AvgMax64) UpdateFrom(oth *AvgMax64) {
am.Sum += oth.Sum
am.N += oth.N
if oth.Max > am.Max {
am.Max = oth.Max
am.MaxIndex = oth.MaxIndex
}
}
// CopyFrom copies from other AvgMax64
func (am *AvgMax64) CopyFrom(oth *AvgMax64) {
am.Avg = oth.Avg
am.Max = oth.Max
am.MaxIndex = oth.MaxIndex
am.Sum = oth.Sum
am.N = oth.N
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package minmax
import (
"fmt"
"cogentcore.org/core/math32"
)
//gosl:start
// F32 represents a min / max range for float32 values.
// Supports clipping, renormalizing, etc
type F32 struct {
Min float32
Max float32
pad, pad1 int32 // for gpu use
}
// Set sets the min and max values
func (mr *F32) Set(mn, mx float32) {
mr.Min = mn
mr.Max = mx
}
// SetInfinity sets the Min to +Inf, Max to -Inf -- suitable for
// iteratively calling Fit*InRange. See also Sanitize when done.
func (mr *F32) SetInfinity() {
mr.Min = math32.Inf(1)
mr.Max = math32.Inf(-1)
}
// IsValid returns true if Min <= Max
func (mr *F32) IsValid() bool {
return mr.Min <= mr.Max
}
// InRange tests whether value is within the range (>= Min and <= Max)
func (mr *F32) InRange(val float32) bool {
return ((val >= mr.Min) && (val <= mr.Max))
}
// IsLow tests whether value is lower than the minimum
func (mr *F32) IsLow(val float32) bool {
return (val < mr.Min)
}
// IsHigh tests whether value is higher than the maximum
func (mr *F32) IsHigh(val float32) bool {
return (val > mr.Max)
}
// Range returns Max - Min
func (mr *F32) Range() float32 {
return mr.Max - mr.Min
}
// Scale returns 1 / Range -- if Range = 0 then returns 0
func (mr *F32) Scale() float32 {
r := mr.Range()
if r != 0 {
return 1.0 / r
}
return 0
}
// Midpoint returns point halfway between Min and Max
func (mr *F32) Midpoint() float32 {
return 0.5 * (mr.Max + mr.Min)
}
// FitValInRange adjusts our Min, Max to fit given value within Min, Max range
// returns true if we had to adjust to fit.
func (mr *F32) FitValInRange(val float32) bool {
adj := false
if val < mr.Min {
mr.Min = val
adj = true
}
if val > mr.Max {
mr.Max = val
adj = true
}
return adj
}
// NormValue normalizes value to 0-1 unit range relative to current Min / Max range
// Clips the value within Min-Max range first.
func (mr *F32) NormValue(val float32) float32 {
return (mr.ClampValue(val) - mr.Min) * mr.Scale()
}
// ProjValue projects a 0-1 normalized unit value into current Min / Max range (inverse of NormValue)
func (mr *F32) ProjValue(val float32) float32 {
return mr.Min + (val * mr.Range())
}
// ClampValue clamps given value within Min / Max range
// Note: a NaN will remain as a NaN.
func (mr *F32) ClampValue(val float32) float32 {
if val < mr.Min {
return mr.Min
}
if val > mr.Max {
return mr.Max
}
return val
}
// ClipNormValue clips then normalizes given value within 0-1
// Note: a NaN will remain as a NaN
func (mr *F32) ClipNormValue(val float32) float32 {
if val < mr.Min {
return 0
}
if val > mr.Max {
return 1
}
return mr.NormValue(val)
}
//gosl:end
func (mr *F32) String() string {
return fmt.Sprintf("{%g %g}", mr.Min, mr.Max)
}
// FitInRange adjusts our Min, Max to fit within those of other F32
// returns true if we had to adjust to fit.
func (mr *F32) FitInRange(oth F32) bool {
adj := false
if oth.Min < mr.Min {
mr.Min = oth.Min
adj = true
}
if oth.Max > mr.Max {
mr.Max = oth.Max
adj = true
}
return adj
}
// Sanitize ensures that the Min / Max range is not infinite or contradictory.
func (mr *F32) Sanitize() {
if math32.IsInf(mr.Min, 0) {
mr.Min = 0
}
if math32.IsInf(mr.Max, 0) {
mr.Max = 0
}
if mr.Min > mr.Max {
mr.Min, mr.Max = mr.Max, mr.Min
}
if mr.Min == mr.Max {
mr.Min--
mr.Max++
}
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package minmax provides a struct that holds Min and Max values.
package minmax
import "math"
//go:generate core generate
// F64 represents a min / max range for float64 values.
// Supports clipping, renormalizing, etc
type F64 struct {
Min float64
Max float64
}
// Set sets the min and max values
func (mr *F64) Set(mn, mx float64) {
mr.Min = mn
mr.Max = mx
}
// SetInfinity sets the Min to +Inf, Max to -Inf, suitable for
// iteratively calling Fit*InRange. See also Sanitize when done.
func (mr *F64) SetInfinity() {
mr.Min = math.Inf(1)
mr.Max = math.Inf(-1)
}
// IsValid returns true if Min <= Max.
func (mr *F64) IsValid() bool {
return mr.Min <= mr.Max
}
// InRange tests whether value is within the range (>= Min and <= Max).
func (mr *F64) InRange(val float64) bool {
return ((val >= mr.Min) && (val <= mr.Max))
}
// IsLow tests whether value is lower than the minimum.
func (mr *F64) IsLow(val float64) bool {
return (val < mr.Min)
}
// IsHigh tests whether value is higher than the maximum.
func (mr *F64) IsHigh(val float64) bool {
return (val > mr.Max)
}
// Range returns Max - Min.
func (mr *F64) Range() float64 {
return mr.Max - mr.Min
}
// Scale returns 1 / Range -- if Range = 0 then returns 0.
func (mr *F64) Scale() float64 {
r := mr.Range()
if r != 0 {
return 1 / r
}
return 0
}
// Midpoint returns point halfway between Min and Max
func (mr *F64) Midpoint() float64 {
return 0.5 * (mr.Max + mr.Min)
}
// FitValInRange adjusts our Min, Max to fit given value within Min, Max range
// returns true if we had to adjust to fit.
func (mr *F64) FitValInRange(val float64) bool {
adj := false
if val < mr.Min {
mr.Min = val
adj = true
}
if val > mr.Max {
mr.Max = val
adj = true
}
return adj
}
// NormValue normalizes value to 0-1 unit range relative to current Min / Max range
// Clips the value within Min-Max range first.
func (mr *F64) NormValue(val float64) float64 {
return (mr.ClampValue(val) - mr.Min) * mr.Scale()
}
// ProjValue projects a 0-1 normalized unit value into current Min / Max range (inverse of NormValue)
func (mr *F64) ProjValue(val float64) float64 {
return mr.Min + (val * mr.Range())
}
// ClampValue clips given value within Min / Max range
// Note: a NaN will remain as a NaN
func (mr *F64) ClampValue(val float64) float64 {
if val < mr.Min {
return mr.Min
}
if val > mr.Max {
return mr.Max
}
return val
}
// ClipNormValue clips then normalizes given value within 0-1
// Note: a NaN will remain as a NaN
func (mr *F64) ClipNormValue(val float64) float64 {
if val < mr.Min {
return 0
}
if val > mr.Max {
return 1
}
return mr.NormValue(val)
}
// FitInRange adjusts our Min, Max to fit within those of other F64
// returns true if we had to adjust to fit.
func (mr *F64) FitInRange(oth F64) bool {
adj := false
if oth.Min < mr.Min {
mr.Min = oth.Min
adj = true
}
if oth.Max > mr.Max {
mr.Max = oth.Max
adj = true
}
return adj
}
// Sanitize ensures that the Min / Max range is not infinite or contradictory.
func (mr *F64) Sanitize() {
if math.IsInf(mr.Min, 0) {
mr.Min = 0
}
if math.IsInf(mr.Max, 0) {
mr.Max = 0
}
if mr.Min > mr.Max {
mr.Min, mr.Max = mr.Max, mr.Min
}
if mr.Min == mr.Max {
mr.Min--
mr.Max++
}
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package minmax
import "math"
// Int represents a min / max range for int values.
// Supports clipping, renormalizing, etc
type Int struct {
Min int
Max int
}
// Set sets the min and max values
func (mr *Int) Set(mn, mx int) {
mr.Min, mr.Max = mn, mx
}
// SetInfinity sets the Min to +MaxFloat, Max to -MaxFloat -- suitable for
// iteratively calling Fit*InRange
func (mr *Int) SetInfinity() {
mr.Min, mr.Max = math.MaxInt, -math.MaxInt
}
// IsValid returns true if Min <= Max
func (mr *Int) IsValid() bool {
return mr.Min <= mr.Max
}
// InRange tests whether value is within the range (>= Min and <= Max)
func (mr *Int) InRange(val int) bool {
return ((val >= mr.Min) && (val <= mr.Max))
}
// IsLow tests whether value is lower than the minimum
func (mr *Int) IsLow(val int) bool {
return (val < mr.Min)
}
// IsHigh tests whether value is higher than the maximum
func (mr *Int) IsHigh(val int) bool {
return (val > mr.Max)
}
// Range returns Max - Min
func (mr *Int) Range() int {
return mr.Max - mr.Min
}
// Scale returns 1 / Range -- if Range = 0 then returns 0
func (mr *Int) Scale() float32 {
r := mr.Range()
if r != 0 {
return 1 / float32(r)
}
return 0
}
// Midpoint returns point halfway between Min and Max
func (mr *Int) Midpoint() float32 {
return 0.5 * float32(mr.Max+mr.Min)
}
// FitInRange adjusts our Min, Max to fit within those of other Int
// returns true if we had to adjust to fit.
func (mr *Int) FitInRange(oth Int) bool {
adj := false
if oth.Min < mr.Min {
mr.Min = oth.Min
adj = true
}
if oth.Max > mr.Max {
mr.Max = oth.Max
adj = true
}
return adj
}
// FitValInRange adjusts our Min, Max to fit given value within Min, Max range
// returns true if we had to adjust to fit.
func (mr *Int) FitValInRange(val int) bool {
adj := false
if val < mr.Min {
mr.Min = val
adj = true
}
if val > mr.Max {
mr.Max = val
adj = true
}
return adj
}
// NormValue normalizes value to 0-1 unit range relative to current Min / Max range
// Clips the value within Min-Max range first.
func (mr *Int) NormValue(val int) float32 {
return float32(mr.Clamp(val)-mr.Min) * mr.Scale()
}
// ProjValue projects a 0-1 normalized unit value into current Min / Max range (inverse of NormValue)
func (mr *Int) ProjValue(val float32) float32 {
return float32(mr.Min) + (val * float32(mr.Range()))
}
// Clamp clips given value within Min / Max range
func (mr *Int) Clamp(val int) int {
if val < mr.Min {
return mr.Min
}
if val > mr.Max {
return mr.Max
}
return val
}
// ClipNormValue clips then normalizes given value within 0-1
func (mr *Int) ClipNormValue(val int) float32 {
if val < mr.Min {
return 0
}
if val > mr.Max {
return 1
}
return mr.NormValue(val)
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package minmax
import "math"
// notes: gonum/plot has function labelling: talbotLinHanrahan
// based on this algorithm: http://vis.stanford.edu/files/2010-TickLabels-InfoVis.pdf
// but it is goes beyond this basic functionality, and is not exported in any case..
// but could be accessed using DefaultTicks api.
// NiceRoundNumber returns the closest nice round number either above or below
// the given number, based on the observation that numbers 1, 2, 5
// at any power are "nice".
// This is used for choosing graph labels, and auto-scaling ranges to contain
// a given value.
// if below == true then returned number is strictly less than given number
// otherwise it is strictly larger.
func NiceRoundNumber(x float64, below bool) float64 {
rn := x
neg := false
if x < 0 {
neg = true
below = !below // reverses..
}
abs := math.Abs(x)
exp := int(math.Floor(math.Log10(abs)))
order := math.Pow(10, float64(exp))
f := abs / order // fraction between 1 and 10
if below {
switch {
case f >= 5:
rn = 5
case f >= 2:
rn = 2
default:
rn = 1
}
} else {
switch {
case f <= 1:
rn = 1
case f <= 2:
rn = 2
case f <= 5:
rn = 5
default:
rn = 10
}
}
if neg {
return -rn * order
}
return rn * order
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package minmax
// Range32 represents a range of values for plotting, where the min or max can optionally be fixed
type Range32 struct {
F32
// fix the minimum end of the range
FixMin bool
// fix the maximum end of the range
FixMax bool
}
// SetMin sets a fixed min value
func (rr *Range32) SetMin(mn float32) *Range32 {
rr.FixMin = true
rr.Min = mn
return rr
}
// SetMax sets a fixed max value
func (rr *Range32) SetMax(mx float32) *Range32 {
rr.FixMax = true
rr.Max = mx
return rr
}
// Range returns Max - Min
func (rr *Range32) Range() float32 {
return rr.Max - rr.Min
}
// Clamp returns min, max values clamped according to Fixed min / max of range.
func (rr *Range32) Clamp(mnIn, mxIn float32) (mn, mx float32) {
mn, mx = mnIn, mxIn
if rr.FixMin && rr.Min < mn {
mn = rr.Min
}
if rr.FixMax && rr.Max > mx {
mx = rr.Max
}
return
}
///////////////////////////////////////////////////////////////////////
// 64
// Range64 represents a range of values for plotting, where the min or max can optionally be fixed
type Range64 struct {
F64
// fix the minimum end of the range
FixMin bool
// fix the maximum end of the range
FixMax bool
}
// SetMin sets a fixed min value
func (rr *Range64) SetMin(mn float64) *Range64 {
rr.FixMin = true
rr.Min = mn
return rr
}
// SetMax sets a fixed max value
func (rr *Range64) SetMax(mx float64) *Range64 {
rr.FixMax = true
rr.Max = mx
return rr
}
// Range returns Max - Min
func (rr *Range64) Range() float64 {
return rr.Max - rr.Min
}
// Clamp returns min, max values clamped according to Fixed min / max of range.
func (rr *Range64) Clamp(mnIn, mxIn float64) (mn, mx float64) {
mn, mx = mnIn, mxIn
if rr.FixMin && rr.Min < mn {
mn = rr.Min
}
if rr.FixMax && rr.Max > mx {
mx = rr.Max
}
return
}
// Copyright 2019 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Initially copied from G3N: github.com/g3n/engine/math32
// Copyright 2016 The G3N Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// with modifications needed to suit Cogent Core functionality.
package math32
import "log"
// Plane represents a plane in 3D space by its normal vector and a constant offset.
// When the the normal vector is the unit vector the offset is the distance from the origin.
type Plane struct {
Norm Vector3
Off float32
}
// NewPlane creates and returns a new plane from a normal vector and a offset.
func NewPlane(normal Vector3, offset float32) *Plane {
p := &Plane{normal, offset}
return p
}
// Set sets this plane normal vector and offset.
func (p *Plane) Set(normal Vector3, offset float32) {
p.Norm = normal
p.Off = offset
}
// SetDims sets this plane normal vector dimensions and offset.
func (p *Plane) SetDims(x, y, z, w float32) {
p.Norm.Set(x, y, z)
p.Off = w
}
// SetFromNormalAndCoplanarPoint sets this plane from a normal vector and a point on the plane.
func (p *Plane) SetFromNormalAndCoplanarPoint(normal Vector3, point Vector3) {
p.Norm = normal
p.Off = -point.Dot(p.Norm)
}
// SetFromCoplanarPoints sets this plane from three coplanar points.
func (p *Plane) SetFromCoplanarPoints(a, b, c Vector3) {
norm := c.Sub(b).Cross(a.Sub(b))
norm.SetNormal()
if norm == (Vector3{}) {
log.Printf("math32.SetFromCoplanarPonts: points not actually coplanar: %v %v %v\n", a, b, c)
}
p.SetFromNormalAndCoplanarPoint(norm, a)
}
// Normalize normalizes this plane normal vector and adjusts the offset.
// Note: will lead to a divide by zero if the plane is invalid.
func (p *Plane) Normalize() {
invLen := 1.0 / p.Norm.Length()
p.Norm.SetMulScalar(invLen)
p.Off *= invLen
}
// Negate negates this plane normal.
func (p *Plane) Negate() {
p.Off *= -1
p.Norm = p.Norm.Negate()
}
// DistanceToPoint returns the distance of this plane from point.
func (p *Plane) DistanceToPoint(point Vector3) float32 {
return p.Norm.Dot(point) + p.Off
}
// DistanceToSphere returns the distance of this place from the sphere.
func (p *Plane) DistanceToSphere(sphere Sphere) float32 {
return p.DistanceToPoint(sphere.Center) - sphere.Radius
}
// IsIntersectionLine returns the line intersects this plane.
func (p *Plane) IsIntersectionLine(line Line3) bool {
startSign := p.DistanceToPoint(line.Start)
endSign := p.DistanceToPoint(line.End)
return (startSign < 0 && endSign > 0) || (endSign < 0 && startSign > 0)
}
// IntersectLine calculates the point in the plane which intersets the specified line.
// Returns false if the line does not intersects the plane.
func (p *Plane) IntersectLine(line Line3) (Vector3, bool) {
dir := line.Delta()
denom := p.Norm.Dot(dir)
if denom == 0 {
// line is coplanar, return origin
if p.DistanceToPoint(line.Start) == 0 {
return line.Start, true
}
// Unsure if this is the correct method to handle this case.
return dir, false
}
var t = -(line.Start.Dot(p.Norm) + p.Off) / denom
if t < 0 || t > 1 {
return dir, false
}
return dir.MulScalar(t).Add(line.Start), true
}
// CoplanarPoint returns a point in the plane that is the closest point from the origin.
func (p *Plane) CoplanarPoint() Vector3 {
return p.Norm.MulScalar(-p.Off)
}
// SetTranslate translates this plane in the direction of its normal by offset.
func (p *Plane) SetTranslate(offset Vector3) {
p.Off -= offset.Dot(p.Norm)
}
// Copyright 2019 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Initially copied from G3N: github.com/g3n/engine/math32
// Copyright 2016 The G3N Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// with modifications needed to suit Cogent Core functionality.
package math32
import "fmt"
// Quat is quaternion with X,Y,Z and W components.
type Quat struct {
X float32
Y float32
Z float32
W float32
}
// NewQuat returns a new quaternion from the specified components.
func NewQuat(x, y, z, w float32) Quat {
return Quat{X: x, Y: y, Z: z, W: w}
}
// NewQuatIdentity returns a new quaternion with the identity rotation.
func NewQuatIdentity() Quat {
return Quat{X: 0, Y: 0, Z: 0, W: 1}
}
// NewQuatAxisAngle returns a new quaternion from given axis and angle rotation (radians).
func NewQuatAxisAngle(axis Vector3, angle float32) Quat {
nq := Quat{}
nq.SetFromAxisAngle(axis, angle)
return nq
}
// NewQuatEuler returns a new quaternion from given Euler angles.
func NewQuatEuler(euler Vector3) Quat {
nq := Quat{}
nq.SetFromEuler(euler)
return nq
}
// Set sets this quaternion's components.
func (q *Quat) Set(x, y, z, w float32) {
q.X = x
q.Y = y
q.Z = z
q.W = w
}
// FromArray sets this quaternion's components from array starting at offset.
func (q *Quat) FromArray(array []float32, offset int) {
q.X = array[offset]
q.Y = array[offset+1]
q.Z = array[offset+2]
q.W = array[offset+3]
}
// ToArray copies this quaternions's components to array starting at offset.
func (q Quat) ToArray(array []float32, offset int) {
array[offset] = q.X
array[offset+1] = q.Y
array[offset+2] = q.Z
array[offset+3] = q.W
}
// SetIdentity sets this quanternion to the identity quaternion.
func (q *Quat) SetIdentity() {
q.X = 0
q.Y = 0
q.Z = 0
q.W = 1
}
// IsIdentity returns if this is an identity quaternion.
func (q Quat) IsIdentity() bool {
return q.X == 0 && q.Y == 0 && q.Z == 0 && q.W == 1
}
// IsNil returns true if all values are 0 (uninitialized).
func (q Quat) IsNil() bool {
return q.X == 0 && q.Y == 0 && q.Z == 0 && q.W == 0
}
func (q Quat) IsNaN() bool {
return IsNaN(q.X) || IsNaN(q.Y) || IsNaN(q.Z) || IsNaN(q.W)
}
func (q Quat) String() string {
return fmt.Sprintf("(%v, %v, %v, %v)", q.X, q.Y, q.Z, q.W)
}
// SetFromEuler sets this quaternion from the specified vector with
// Euler angles for each axis. It is assumed that the Euler angles
// are in XYZ order.
func (q *Quat) SetFromEuler(euler Vector3) {
c1 := Cos(euler.X / 2)
c2 := Cos(euler.Y / 2)
c3 := Cos(euler.Z / 2)
s1 := Sin(euler.X / 2)
s2 := Sin(euler.Y / 2)
s3 := Sin(euler.Z / 2)
q.X = s1*c2*c3 - c1*s2*s3
q.Y = c1*s2*c3 + s1*c2*s3
q.Z = c1*c2*s3 - s1*s2*c3
q.W = c1*c2*c3 + s1*s2*s3
}
// ToEuler returns a Vector3 with components as the Euler angles
// from the given quaternion.
func (q Quat) ToEuler() Vector3 {
// columns
x := q.MulVector(Vec3(1, 0, 0))
y := q.MulVector(Vec3(0, 1, 0))
z := q.MulVector(Vec3(0, 0, 1))
phi := Atan2(z.Y, z.Z)
sinp := -z.X
var theta float32
if Abs(sinp) >= 1 {
theta = 0.5 * Pi * Sign(sinp)
} else {
theta = Asin(sinp)
}
psi := Atan2(y.X, x.X)
return Vec3(-phi, -theta, -psi)
// rot := Vector3{}
// rot.SetEulerAnglesFromQuat(q)
// return rot
}
// SetFromAxisAngle sets this quaternion with the rotation
// specified by the given axis and angle.
func (q *Quat) SetFromAxisAngle(axis Vector3, angle float32) {
halfAngle := angle / 2
s := Sin(halfAngle)
q.X = axis.X * s
q.Y = axis.Y * s
q.Z = axis.Z * s
q.W = Cos(halfAngle)
}
// ToAxisAngle returns the Vector4 holding axis and angle of this Quaternion
func (q Quat) ToAxisAngle() Vector4 {
aa := Vector4{}
aa.SetAxisAngleFromQuat(q)
return aa
}
// GenGoSet returns code to set values in object at given path (var.member etc)
func (q Quat) GenGoSet(path string) string {
aa := q.ToAxisAngle()
return fmt.Sprintf("%s.SetFromAxisAngle(math32.Vec3(%g, %g, %g), %g)", path, aa.X, aa.Y, aa.Z, aa.W)
}
// GenGoNew returns code to create new
func (q Quat) GenGoNew() string {
return fmt.Sprintf("math32.Quat{%g, %g, %g, %g}", q.X, q.Y, q.Z, q.W)
}
// SetFromRotationMatrix sets this quaternion from the specified rotation matrix.
func (q *Quat) SetFromRotationMatrix(m *Matrix4) {
m11 := m[0]
m12 := m[4]
m13 := m[8]
m21 := m[1]
m22 := m[5]
m23 := m[9]
m31 := m[2]
m32 := m[6]
m33 := m[10]
trace := m11 + m22 + m33
var s float32
if trace > 0 {
s = 0.5 / Sqrt(trace+1.0)
q.W = 0.25 / s
q.X = (m32 - m23) * s
q.Y = (m13 - m31) * s
q.Z = (m21 - m12) * s
} else if m11 > m22 && m11 > m33 {
s = 2.0 * Sqrt(1.0+m11-m22-m33)
q.W = (m32 - m23) / s
q.X = 0.25 * s
q.Y = (m12 + m21) / s
q.Z = (m13 + m31) / s
} else if m22 > m33 {
s = 2.0 * Sqrt(1.0+m22-m11-m33)
q.W = (m13 - m31) / s
q.X = (m12 + m21) / s
q.Y = 0.25 * s
q.Z = (m23 + m32) / s
} else {
s = 2.0 * Sqrt(1.0+m33-m11-m22)
q.W = (m21 - m12) / s
q.X = (m13 + m31) / s
q.Y = (m23 + m32) / s
q.Z = 0.25 * s
}
}
// SetFromUnitVectors sets this quaternion to the rotation from vector vFrom to vTo.
// The vectors must be normalized.
func (q *Quat) SetFromUnitVectors(vFrom, vTo Vector3) {
var v1 Vector3
var EPS float32 = 0.000001
r := vFrom.Dot(vTo) + 1
if r < EPS {
r = 0
if Abs(vFrom.X) > Abs(vFrom.Z) {
v1.Set(-vFrom.Y, vFrom.X, 0)
} else {
v1.Set(0, -vFrom.Z, vFrom.Y)
}
} else {
v1 = vFrom.Cross(vTo)
}
q.X = v1.X
q.Y = v1.Y
q.Z = v1.Z
q.W = r
q.Normalize()
}
// SetInverse sets this quaternion to its inverse.
func (q *Quat) SetInverse() {
q.SetConjugate()
q.Normalize()
}
// Inverse returns the inverse of this quaternion.
func (q Quat) Inverse() Quat {
q.SetInverse()
return q
}
// SetConjugate sets this quaternion to its conjugate.
func (q *Quat) SetConjugate() {
q.X *= -1
q.Y *= -1
q.Z *= -1
}
// Conjugate returns the conjugate of this quaternion.
func (q Quat) Conjugate() Quat {
q.SetConjugate()
return q
}
// Dot returns the dot products of this quaternion with other.
func (q Quat) Dot(o Quat) float32 {
return q.X*o.X + q.Y*o.Y + q.Z*o.Z + q.W*o.W
}
// LengthSq returns this quanternion's length squared
func (q Quat) LengthSq() float32 {
return q.X*q.X + q.Y*q.Y + q.Z*q.Z + q.W*q.W
}
// Length returns the length of this quaternion
func (q Quat) Length() float32 {
return Sqrt(q.X*q.X + q.Y*q.Y + q.Z*q.Z + q.W*q.W)
}
// Normalize normalizes this quaternion.
func (q *Quat) Normalize() {
l := q.Length()
if l == 0 {
q.X = 0
q.Y = 0
q.Z = 0
q.W = 1
} else {
l = 1 / l
q.X *= l
q.Y *= l
q.Z *= l
q.W *= l
}
}
// NormalizeFast approximates normalizing this quaternion.
// Works best when the quaternion is already almost-normalized.
func (q *Quat) NormalizeFast() {
f := (3.0 - (q.X*q.X + q.Y*q.Y + q.Z*q.Z + q.W*q.W)) / 2.0
if f == 0 {
q.X = 0
q.Y = 0
q.Z = 0
q.W = 1
} else {
q.X *= f
q.Y *= f
q.Z *= f
q.W *= f
}
}
// MulQuats returns a * b quaternion multiplication.
func MulQuats(a, b Quat) Quat {
// from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
var q Quat
q.X = a.X*b.W + a.W*b.X + a.Y*b.Z - a.Z*b.Y
q.Y = a.Y*b.W + a.W*b.Y + a.Z*b.X - a.X*b.Z
q.Z = a.Z*b.W + a.W*b.Z + a.X*b.Y - a.Y*b.X
q.W = a.W*b.W - a.X*b.X - a.Y*b.Y - a.Z*b.Z
return q
}
// SetMul sets this quaternion to the multiplication of itself by other.
func (q *Quat) SetMul(o Quat) {
*q = MulQuats(*q, o)
}
// Mul returns returns multiplication of this quaternion with other
func (q Quat) Mul(o Quat) Quat {
q.SetMul(o)
return q
}
// MulScalar returns values multiplied by scalar
func (q Quat) MulScalar(s float32) Quat {
return NewQuat(q.X*s, q.Y*s, q.Z*s, q.W*s)
}
// Add returns values added
func (q Quat) Add(o Quat) Quat {
return NewQuat(q.X+o.X, q.Y+o.Y, q.Z+o.Z, q.W+o.W)
}
// MulVector applies the rotation encoded in the quaternion to the [Vector3].
func (q Quat) MulVector(v Vector3) Vector3 {
xyz := Vec3(q.X, q.Y, q.Z)
t := xyz.Cross(v).MulScalar(2)
return v.Add(t.MulScalar(q.W)).Add(xyz.Cross(t))
}
// MulVectorInverse applies the inverse of the rotation encoded in the quaternion
// to the [Vector3].
func (q Quat) MulVectorInverse(v Vector3) Vector3 {
xyz := Vec3(q.X, q.Y, q.Z)
t := xyz.Cross(v).MulScalar(2)
return v.Sub(t.MulScalar(q.W)).Add(xyz.Cross(t))
}
// Slerp sets this quaternion to another quaternion which is the
// spherically linear interpolation from this quaternion to other using t.
func (q *Quat) Slerp(o Quat, t float32) {
if t == 0 {
return
}
if t == 1 {
*q = o
return
}
x := q.X
y := q.Y
z := q.Z
w := q.W
cosHalfTheta := w*o.W + x*o.X + y*o.Y + z*o.Z
if cosHalfTheta < 0 {
q.W = -o.W
q.X = -o.X
q.Y = -o.Y
q.Z = -o.Z
cosHalfTheta = -cosHalfTheta
} else {
*q = o
}
if cosHalfTheta >= 1.0 {
q.W = w
q.X = x
q.Y = y
q.Z = z
return
}
sqrSinHalfTheta := 1.0 - cosHalfTheta*cosHalfTheta
if sqrSinHalfTheta < 0.001 {
s := 1 - t
q.W = s*w + t*q.W
q.X = s*x + t*q.X
q.Y = s*y + t*q.Y
q.Z = s*z + t*q.Z
q.Normalize()
return
}
sinHalfTheta := Sqrt(sqrSinHalfTheta)
halfTheta := Atan2(sinHalfTheta, cosHalfTheta)
ratioA := Sin((1-t)*halfTheta) / sinHalfTheta
ratioB := Sin(t*halfTheta) / sinHalfTheta
q.W = w*ratioA + q.W*ratioB
q.X = x*ratioA + q.X*ratioB
q.Y = y*ratioA + q.Y*ratioB
q.Z = z*ratioA + q.Z*ratioB
}
// Copyright 2019 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Initially copied from G3N: github.com/g3n/engine/math32
// Copyright 2016 The G3N Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// with modifications needed to suit Cogent Core functionality.
package math32
// Ray represents an oriented 3D line segment defined by an origin point and a direction vector.
type Ray struct {
Origin Vector3
Dir Vector3
}
// NewRay creates and returns a pointer to a Ray object with
// the specified origin and direction vectors.
// If a nil pointer is supplied for any of the parameters,
// the zero vector will be used.
func NewRay(origin, dir Vector3) *Ray {
return &Ray{origin, dir}
}
// Set sets the origin and direction vectors of this Ray.
func (ray *Ray) Set(origin, dir Vector3) {
ray.Origin = origin
ray.Dir = dir
}
// At calculates the point in the ray which is at the specified t distance from the origin
// along its direction.
func (ray *Ray) At(t float32) Vector3 {
return ray.Dir.MulScalar(t).Add(ray.Origin)
}
// Recast sets the new origin of the ray at the specified distance t
// from its origin along its direction.
func (ray *Ray) Recast(t float32) {
ray.Origin = ray.At(t)
}
// ClosestPointToPoint calculates the point in the ray which is closest to the specified point.
func (ray *Ray) ClosestPointToPoint(point Vector3) Vector3 {
dirDist := point.Sub(ray.Origin).Dot(ray.Dir)
if dirDist < 0 {
return ray.Origin
}
return ray.Dir.MulScalar(dirDist).Add(ray.Origin)
}
// DistanceToPoint returns the smallest distance
// from the ray direction vector to the specified point.
func (ray *Ray) DistanceToPoint(point Vector3) float32 {
return Sqrt(ray.DistanceSquaredToPoint(point))
}
// DistanceSquaredToPoint returns the smallest squared distance
// from the ray direction vector to the specified point.
// If the ray was pointed directly at the point this distance would be 0.
func (ray *Ray) DistanceSquaredToPoint(point Vector3) float32 {
dirDist := point.Sub(ray.Origin).Dot(ray.Dir)
// point behind the ray
if dirDist < 0 {
return ray.Origin.DistanceTo(point)
}
return ray.Dir.MulScalar(dirDist).Add(ray.Origin).DistanceToSquared(point)
}
// DistanceSquaredToSegment returns the smallest squared distance
// from this ray to the line segment from v0 to v1.
// If optPointOnRay Vector3 is not nil,
// it is set with the coordinates of the point on the ray.
// if optPointOnSegment Vector3 is not nil,
// it is set with the coordinates of the point on the segment.
func (ray *Ray) DistanceSquaredToSegment(v0, v1 Vector3, optPointOnRay, optPointOnSegment *Vector3) float32 {
segCenter := v0.Add(v1).MulScalar(0.5)
segDir := v1.Sub(v0).Normal()
diff := ray.Origin.Sub(segCenter)
segExtent := v0.DistanceTo(v1) * 0.5
a01 := -ray.Dir.Dot(segDir)
b0 := diff.Dot(ray.Dir)
b1 := -diff.Dot(segDir)
c := diff.LengthSquared()
det := Abs(1 - a01*a01)
var s0, s1, sqrDist, extDet float32
if det > 0 {
// The ray and segment are not parallel.
s0 = a01*b1 - b0
s1 = a01*b0 - b1
extDet = segExtent * det
if s0 >= 0 {
if s1 >= -extDet {
if s1 <= extDet {
// region 0
// Minimum at interior points of ray and segment.
invDet := 1 / det
s0 *= invDet
s1 *= invDet
sqrDist = s0*(s0+a01*s1+2*b0) + s1*(a01*s0+s1+2*b1) + c
} else {
// region 1
s1 = segExtent
s0 = Max(0, -(a01*s1 + b0))
sqrDist = -s0*s0 + s1*(s1+2*b1) + c
}
} else {
// region 5
s1 = -segExtent
s0 = Max(0, -(a01*s1 + b0))
sqrDist = -s0*s0 + s1*(s1+2*b1) + c
}
} else {
if s1 <= -extDet {
// region 4
s0 = Max(0, -(-a01*segExtent + b0))
if s0 > 0 {
s1 = -segExtent
} else {
s1 = Min(Max(-segExtent, -b1), segExtent)
}
sqrDist = -s0*s0 + s1*(s1+2*b1) + c
} else if s1 <= extDet {
// region 3
s0 = 0
s1 = Min(Max(-segExtent, -b1), segExtent)
sqrDist = s1*(s1+2*b1) + c
} else {
// region 2
s0 = Max(0, -(a01*segExtent + b0))
if s0 > 0 {
s1 = segExtent
} else {
s1 = Min(Max(-segExtent, -b1), segExtent)
}
sqrDist = -s0*s0 + s1*(s1+2*b1) + c
}
}
} else {
// Ray and segment are parallel.
if a01 > 0 {
s1 = -segExtent
} else {
s1 = segExtent
}
s0 = Max(0, -(a01*s1 + b0))
sqrDist = -s0*s0 + s1*(s1+2*b1) + c
}
if optPointOnRay != nil {
*optPointOnRay = ray.Dir.MulScalar(s0).Add(ray.Origin)
}
if optPointOnSegment != nil {
*optPointOnSegment = segDir.MulScalar(s1).Add(segCenter)
}
return sqrDist
}
// IsIntersectionSphere returns if this ray intersects with the specified sphere.
func (ray *Ray) IsIntersectionSphere(sphere Sphere) bool {
return ray.DistanceToPoint(sphere.Center) <= sphere.Radius
}
// IntersectSphere calculates the point which is the intersection of this ray with the specified sphere.
// If no intersection is found it returns false.
func (ray *Ray) IntersectSphere(sphere Sphere) (Vector3, bool) {
v1 := sphere.Center.Sub(ray.Origin)
tca := v1.Dot(ray.Dir)
d2 := v1.Dot(v1) - tca*tca
radius2 := sphere.Radius * sphere.Radius
if d2 > radius2 {
return v1, false
}
thc := Sqrt(radius2 - d2)
// t0 = first intersect point - entrance on front of sphere
t0 := tca - thc
// t1 = second intersect point - exit point on back of sphere
t1 := tca + thc
// test to see if both t0 and t1 are behind the ray - if so, return null
if t0 < 0 && t1 < 0 {
return v1, false
}
// test to see if t0 is behind the ray:
// if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
// in order to always return an intersect point that is in front of the ray.
if t0 < 0 {
return ray.At(t1), true
}
// else t0 is in front of the ray, so return the first collision point scaled by t0
return ray.At(t0), true
}
// IsIntersectPlane returns if this ray intersects the specified plane.
func (ray *Ray) IsIntersectPlane(plane Plane) bool {
distToPoint := plane.DistanceToPoint(ray.Origin)
if distToPoint == 0 {
return true
}
denom := plane.Norm.Dot(ray.Dir)
// if false, ray origin is behind the plane (and is pointing behind it)
return denom*distToPoint < 0
}
// DistanceToPlane returns the distance of this ray origin to its intersection point in the plane.
// If the ray does not intersects the plane, returns NaN.
func (ray *Ray) DistanceToPlane(plane Plane) float32 {
denom := plane.Norm.Dot(ray.Dir)
if denom == 0 {
// line is coplanar, return origin
if plane.DistanceToPoint(ray.Origin) == 0 {
return 0
}
return NaN()
}
t := -(ray.Origin.Dot(plane.Norm) + plane.Off) / denom
// Return if the ray never intersects the plane
if t >= 0 {
return t
}
return NaN()
}
// IntersectPlane calculates the point which is the intersection of this ray with the specified plane.
// If no intersection is found false is returned.
func (ray *Ray) IntersectPlane(plane Plane) (Vector3, bool) {
t := ray.DistanceToPlane(plane)
if IsNaN(t) {
return ray.Origin, false
}
return ray.At(t), true
}
// IntersectBox calculates the point which is the intersection of this ray with the specified box.
// If no intersection is found false is returned.
func (ray *Ray) IntersectBox(box Box3) (Vector3, bool) {
// http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/
var tmin, tmax, tymin, tymax, tzmin, tzmax float32
invdirx := 1 / ray.Dir.X
invdiry := 1 / ray.Dir.Y
invdirz := 1 / ray.Dir.Z
var origin = ray.Origin
if invdirx >= 0 {
tmin = (box.Min.X - origin.X) * invdirx
tmax = (box.Max.X - origin.X) * invdirx
} else {
tmin = (box.Max.X - origin.X) * invdirx
tmax = (box.Min.X - origin.X) * invdirx
}
if invdiry >= 0 {
tymin = (box.Min.Y - origin.Y) * invdiry
tymax = (box.Max.Y - origin.Y) * invdiry
} else {
tymin = (box.Max.Y - origin.Y) * invdiry
tymax = (box.Min.Y - origin.Y) * invdiry
}
if (tmin > tymax) || (tymin > tmax) {
return ray.Origin, false
}
if tymin > tmin || IsNaN(tmin) {
tmin = tymin
}
if tymax < tmax || IsNaN(tmax) {
tmax = tymax
}
if invdirz >= 0 {
tzmin = (box.Min.Z - origin.Z) * invdirz
tzmax = (box.Max.Z - origin.Z) * invdirz
} else {
tzmin = (box.Max.Z - origin.Z) * invdirz
tzmax = (box.Min.Z - origin.Z) * invdirz
}
if (tmin > tzmax) || (tzmin > tmax) {
return ray.Origin, false
}
if tzmin > tmin || IsNaN(tmin) {
tmin = tzmin
}
if tzmax < tmax || IsNaN(tmax) {
tmax = tzmax
}
// return point closest to the ray (positive side)
if tmax < 0 {
return ray.Origin, false
}
if tmin >= 0 {
return ray.At(tmin), true
}
return ray.At(tmax), true
}
// IntersectTriangle returns if this ray intersects the triangle with the face
// defined by points a, b, c. Returns true if it intersects and the point
// parameter with the intersected point coordinates.
// If backfaceCulling is false it ignores the intersection if the face is not oriented
// in the ray direction.
func (ray *Ray) IntersectTriangle(a, b, c Vector3, backfaceCulling bool) (Vector3, bool) {
edge1 := b.Sub(a)
edge2 := c.Sub(a)
normal := edge1.Cross(edge2)
// Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
// E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
// |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
// |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
// |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
DdN := ray.Dir.Dot(normal)
var sign float32
if DdN > 0 {
if backfaceCulling {
return ray.Origin, false
}
sign = 1
} else if DdN < 0 {
sign = -1
DdN = -DdN
} else {
return ray.Origin, false
}
diff := ray.Origin.Sub(a)
DdQxE2 := sign * ray.Dir.Dot(diff.Cross(edge2))
// b1 < 0, no intersection
if DdQxE2 < 0 {
return ray.Origin, false
}
DdE1xQ := sign * ray.Dir.Dot(edge1.Cross(diff))
// b2 < 0, no intersection
if DdE1xQ < 0 {
return ray.Origin, false
}
// b1+b2 > 1, no intersection
if DdQxE2+DdE1xQ > DdN {
return ray.Origin, false
}
// Line intersects triangle, check if ray does.
QdN := -sign * diff.Dot(normal)
// t < 0, no intersection
if QdN < 0 {
return ray.Origin, false
}
// Ray intersects triangle.
return ray.At(QdN / DdN), true
}
// ApplyMatrix4 multiplies this ray origin and direction
// by the specified matrix4, basically transforming this ray coordinates.
func (ray *Ray) ApplyMatrix4(mat4 *Matrix4) {
ray.Dir = ray.Dir.Add(ray.Origin).MulMatrix4(mat4)
ray.Origin = ray.Origin.MulMatrix4(mat4)
ray.Dir.SetSub(ray.Origin)
ray.Dir.SetNormal()
}
// Copyright 2019 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Initially copied from G3N: github.com/g3n/engine/math32
// Copyright 2016 The G3N Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// with modifications needed to suit Cogent Core functionality.
package math32
// Sphere represents a 3D sphere defined by its center point and a radius
type Sphere struct {
Center Vector3 // center of the sphere
Radius float32 // radius of the sphere
}
// NewSphere creates and returns a pointer to a new sphere with
// the specified center and radius.
func NewSphere(center Vector3, radius float32) *Sphere {
return &Sphere{center, radius}
}
// Set sets the center and radius of this sphere.
func (s *Sphere) Set(center Vector3, radius float32) {
s.Center = center
s.Radius = radius
}
// SetFromBox sets the center and radius of this sphere to surround given box
func (s *Sphere) SetFromBox(box Box3) {
s.Center = box.Center()
s.Radius = 0.5 * box.Size().Length()
}
// SetFromPoints sets this sphere from the specified points array and optional center.
func (s *Sphere) SetFromPoints(points []Vector3, optCenter *Vector3) {
box := B3Empty()
if optCenter != nil {
s.Center = *optCenter
} else {
box.SetFromPoints(points)
s.Center = box.Center()
}
var maxRadiusSq float32
for i := range points {
maxRadiusSq = Max(maxRadiusSq, s.Center.DistanceToSquared(points[i]))
}
s.Radius = Sqrt(maxRadiusSq)
}
// IsEmpty checks if this sphere is empty (radius <= 0)
func (s *Sphere) IsEmpty(sphere *Sphere) bool {
return s.Radius <= 0
}
// ContainsPoint returns if this sphere contains the specified point.
func (s *Sphere) ContainsPoint(point Vector3) bool {
return point.DistanceToSquared(s.Center) <= (s.Radius * s.Radius)
}
// DistanceToPoint returns the distance from the sphere surface to the specified point.
func (s *Sphere) DistanceToPoint(point Vector3) float32 {
return point.DistanceTo(s.Center) - s.Radius
}
// IntersectSphere returns if other sphere intersects this one.
func (s *Sphere) IntersectSphere(other Sphere) bool {
radiusSum := s.Radius + other.Radius
return other.Center.DistanceToSquared(s.Center) <= (radiusSum * radiusSum)
}
// ClampPoint clamps the specified point inside the sphere.
// If the specified point is inside the sphere, it is the clamped point.
// Otherwise the clamped point is the the point in the sphere surface in the
// nearest of the specified point.
func (s *Sphere) ClampPoint(point Vector3) Vector3 {
deltaLengthSq := s.Center.DistanceToSquared(point)
rv := point
if deltaLengthSq > (s.Radius * s.Radius) {
rv = point.Sub(s.Center).Normal().MulScalar(s.Radius).Add(s.Center)
}
return rv
}
// GetBoundingBox calculates a [Box3] which bounds this sphere.
func (s *Sphere) GetBoundingBox() Box3 {
box := Box3{s.Center, s.Center}
box.ExpandByScalar(s.Radius)
return box
}
// MulMatrix4 applies the specified matrix transform to this sphere.
func (s *Sphere) MulMatrix4(mat *Matrix4) {
s.Center = s.Center.MulMatrix4(mat)
s.Radius = s.Radius * mat.GetMaxScaleOnAxis()
}
// Translate translates this sphere by the specified offset.
func (s *Sphere) Translate(offset Vector3) {
s.Center.SetAdd(offset)
}
// Copyright 2019 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Initially copied from G3N: github.com/g3n/engine/math32
// Copyright 2016 The G3N Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// with modifications needed to suit Cogent Core functionality.
package math32
// Triangle represents a triangle made of three vertices.
type Triangle struct {
A Vector3
B Vector3
C Vector3
}
// NewTriangle returns a new Triangle object.
func NewTriangle(a, b, c Vector3) Triangle {
return Triangle{a, b, c}
}
// Normal returns the triangle's normal.
func Normal(a, b, c Vector3) Vector3 {
nv := c.Sub(b).Cross(a.Sub(b))
lenSq := nv.LengthSquared()
if lenSq > 0 {
return nv.MulScalar(1 / Sqrt(lenSq))
}
return Vector3{}
}
// BarycoordFromPoint returns the barycentric coordinates for the specified point.
func BarycoordFromPoint(point, a, b, c Vector3) Vector3 {
v0 := c.Sub(a)
v1 := b.Sub(a)
v2 := point.Sub(a)
dot00 := v0.Dot(v0)
dot01 := v0.Dot(v1)
dot02 := v0.Dot(v2)
dot11 := v1.Dot(v1)
dot12 := v1.Dot(v2)
denom := dot00*dot11 - dot01*dot01
// colinear or singular triangle
if denom == 0 {
// arbitrary location outside of triangle?
// not sure if this is the best idea, maybe should be returning undefined
return Vec3(-2, -1, -1)
}
invDenom := 1 / denom
u := (dot11*dot02 - dot01*dot12) * invDenom
v := (dot00*dot12 - dot01*dot02) * invDenom
// barycoordinates must always sum to 1
return Vec3(1-u-v, v, u)
}
// ContainsPoint returns whether a triangle contains a point.
func ContainsPoint(point, a, b, c Vector3) bool {
rv := BarycoordFromPoint(point, a, b, c)
return (rv.X >= 0) && (rv.Y >= 0) && ((rv.X + rv.Y) <= 1)
}
// Set sets the triangle's three vertices.
func (t *Triangle) Set(a, b, c Vector3) {
t.A = a
t.B = b
t.C = c
}
// SetFromPointsAndIndices sets the triangle's vertices based on the specified points and indices.
func (t *Triangle) SetFromPointsAndIndices(points []Vector3, i0, i1, i2 int) {
t.A = points[i0]
t.B = points[i1]
t.C = points[i2]
}
// Area returns the triangle's area.
func (t *Triangle) Area() float32 {
v0 := t.C.Sub(t.B)
v1 := t.A.Sub(t.B)
return v0.Cross(v1).Length() * 0.5
}
// Midpoint returns the triangle's midpoint.
func (t *Triangle) Midpoint() Vector3 {
return t.A.Add(t.B).Add(t.C).MulScalar(float32(1) / 3)
}
// Normal returns the triangle's normal.
func (t *Triangle) Normal() Vector3 {
return Normal(t.A, t.B, t.C)
}
// Plane returns a Plane object aligned with the triangle.
func (t *Triangle) Plane() Plane {
pv := Plane{}
pv.SetFromCoplanarPoints(t.A, t.B, t.C)
return pv
}
// BarycoordFromPoint returns the barycentric coordinates for the specified point.
func (t *Triangle) BarycoordFromPoint(point Vector3) Vector3 {
return BarycoordFromPoint(point, t.A, t.B, t.C)
}
// ContainsPoint returns whether the triangle contains a point.
func (t *Triangle) ContainsPoint(point Vector3) bool {
return ContainsPoint(point, t.A, t.B, t.C)
}
// Copyright (c) 2019, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Initially copied from G3N: github.com/g3n/engine/math32
// Copyright 2016 The G3N Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// with modifications needed to suit Cogent Core functionality.
// Package vecint has vector types for emergent, including Vector2i which is a 2D
// vector with int values, using the API based on math32.Vector2i.
// This is distinct from math32.Vector2i because it uses int instead of int32, and
// the int is significantly easier to deal with for some use-cases.
package vecint
//go:generate core generate
import "cogentcore.org/core/math32"
// Vector2i is a 2D vector/point with X and Y int components.
type Vector2i struct {
X int
Y int
}
// Vec2i returns a new [Vector2i] with the given x and y components.
func Vec2i(x, y int) Vector2i {
return Vector2i{X: x, Y: y}
}
// Vector2iScalar returns a new Vector2i with all components set to scalar.
func Vector2iScalar(scalar int) Vector2i {
return Vector2i{X: scalar, Y: scalar}
}
// Vector2iFromVector2Round converts from floating point math32.Vector2 vector to int, using rounding
func Vector2iFromVector2Round(v math32.Vector2) Vector2i {
return Vector2i{int(math32.Round(v.X)), int(math32.Round(v.Y))}
}
// Vector2iFromVector2Floor converts from floating point math32.Vector2 vector to int, using floor
func Vector2iFromVector2Floor(v math32.Vector2) Vector2i {
return Vector2i{int(math32.Floor(v.X)), int(math32.Floor(v.Y))}
}
// Vector2iFromVector2Ceil converts from floating point math32.Vector2 vector to int, using ceil
func Vector2iFromVector2Ceil(v math32.Vector2) Vector2i {
return Vector2i{X: int(math32.Ceil(v.X)), Y: int(math32.Ceil(v.Y))}
}
// ToVector2 returns floating point [math32.Vector2] from int.
func (v Vector2i) ToVector2() math32.Vector2 {
return math32.Vec2(float32(v.X), float32(v.Y))
}
// Set sets this vector X and Y components.
func (v *Vector2i) Set(x, y int) {
v.X = x
v.Y = y
}
// SetScalar sets all vector components to same scalar value.
func (v *Vector2i) SetScalar(scalar int) {
v.X = scalar
v.Y = scalar
}
// SetDim sets this vector component value by its dimension index
func (v *Vector2i) SetDim(dim math32.Dims, value int) {
switch dim {
case math32.X:
v.X = value
case math32.Y:
v.Y = value
default:
panic("dim is out of range")
}
}
// Dim returns this vector component
func (v Vector2i) Dim(dim math32.Dims) int {
switch dim {
case math32.X:
return v.X
case math32.Y:
return v.Y
default:
panic("dim is out of range")
}
}
// SetZero sets all of the vector's components to zero.
func (v *Vector2i) SetZero() {
v.SetScalar(0)
}
// FromSlice sets this vector's components from the given slice, starting at offset.
func (v *Vector2i) FromSlice(array []int, offset int) {
v.X = array[offset]
v.Y = array[offset+1]
}
// ToSlice copies this vector's components to the given slice, starting at offset.
func (v Vector2i) ToSlice(array []int, offset int) {
array[offset] = v.X
array[offset+1] = v.Y
}
// Basic math operations:
// Add adds the other given vector to this one and returns the result as a new vector.
func (v Vector2i) Add(other Vector2i) Vector2i {
return Vector2i{v.X + other.X, v.Y + other.Y}
}
// AddScalar adds scalar s to each component of this vector and returns new vector.
func (v Vector2i) AddScalar(s int) Vector2i {
return Vector2i{v.X + s, v.Y + s}
}
// SetAdd sets this to addition with other vector (i.e., += or plus-equals).
func (v *Vector2i) SetAdd(other Vector2i) {
v.X += other.X
v.Y += other.Y
}
// SetAddScalar sets this to addition with scalar.
func (v *Vector2i) SetAddScalar(s int) {
v.X += s
v.Y += s
}
// Sub subtracts other vector from this one and returns result in new vector.
func (v Vector2i) Sub(other Vector2i) Vector2i {
return Vector2i{v.X - other.X, v.Y - other.Y}
}
// SubScalar subtracts scalar s from each component of this vector and returns new vector.
func (v Vector2i) SubScalar(s int) Vector2i {
return Vector2i{v.X - s, v.Y - s}
}
// SetSub sets this to subtraction with other vector (i.e., -= or minus-equals).
func (v *Vector2i) SetSub(other Vector2i) {
v.X -= other.X
v.Y -= other.Y
}
// SetSubScalar sets this to subtraction of scalar.
func (v *Vector2i) SetSubScalar(s int) {
v.X -= s
v.Y -= s
}
// Mul multiplies each component of this vector by the corresponding one from other
// and returns resulting vector.
func (v Vector2i) Mul(other Vector2i) Vector2i {
return Vector2i{v.X * other.X, v.Y * other.Y}
}
// MulScalar multiplies each component of this vector by the scalar s and returns resulting vector.
func (v Vector2i) MulScalar(s int) Vector2i {
return Vector2i{v.X * s, v.Y * s}
}
// SetMul sets this to multiplication with other vector (i.e., *= or times-equals).
func (v *Vector2i) SetMul(other Vector2i) {
v.X *= other.X
v.Y *= other.Y
}
// SetMulScalar sets this to multiplication by scalar.
func (v *Vector2i) SetMulScalar(s int) {
v.X *= s
v.Y *= s
}
// Div divides each component of this vector by the corresponding one from other vector
// and returns resulting vector.
func (v Vector2i) Div(other Vector2i) Vector2i {
return Vector2i{v.X / other.X, v.Y / other.Y}
}
// DivScalar divides each component of this vector by the scalar s and returns resulting vector.
// If scalar is zero, returns zero.
func (v Vector2i) DivScalar(scalar int) Vector2i {
if scalar != 0 {
return Vector2i{v.X / scalar, v.Y / scalar}
}
return Vector2i{}
}
// SetDiv sets this to division by other vector (i.e., /= or divide-equals).
func (v *Vector2i) SetDiv(other Vector2i) {
v.X /= other.X
v.Y /= other.Y
}
// SetDivScalar sets this to division by scalar.
func (v *Vector2i) SetDivScalar(scalar int) {
if scalar != 0 {
v.X /= scalar
v.Y /= scalar
} else {
v.SetZero()
}
}
// Min returns min of this vector components vs. other vector.
func (v Vector2i) Min(other Vector2i) Vector2i {
return Vector2i{min(v.X, other.X), min(v.Y, other.Y)}
}
// SetMin sets this vector components to the minimum values of itself and other vector.
func (v *Vector2i) SetMin(other Vector2i) {
v.X = min(v.X, other.X)
v.Y = min(v.Y, other.Y)
}
// Max returns max of this vector components vs. other vector.
func (v Vector2i) Max(other Vector2i) Vector2i {
return Vector2i{max(v.X, other.X), max(v.Y, other.Y)}
}
// SetMax sets this vector components to the maximum value of itself and other vector.
func (v *Vector2i) SetMax(other Vector2i) {
v.X = max(v.X, other.X)
v.Y = max(v.Y, other.Y)
}
// Clamp sets this vector's components to be no less than the corresponding
// components of min and not greater than the corresponding component of max.
// Assumes min < max; if this assumption isn't true, it will not operate correctly.
func (v *Vector2i) Clamp(min, max Vector2i) {
if v.X < min.X {
v.X = min.X
} else if v.X > max.X {
v.X = max.X
}
if v.Y < min.Y {
v.Y = min.Y
} else if v.Y > max.Y {
v.Y = max.Y
}
}
// Negate returns the vector with each component negated.
func (v Vector2i) Negate() Vector2i {
return Vector2i{-v.X, -v.Y}
}
// Copyright 2019 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Initially copied from G3N: github.com/g3n/engine/math32
// Copyright 2016 The G3N Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// with modifications needed to suit Cogent Core functionality.
package math32
import (
"fmt"
"image"
math32 "cogentcore.org/core/math32/internal/fmath"
"golang.org/x/image/math/fixed"
)
// Vector2 is a 2D vector/point with X and Y components.
type Vector2 struct {
X float32
Y float32
}
// Vec2 returns a new [Vector2] with the given x and y components.
func Vec2(x, y float32) Vector2 {
return Vector2{x, y}
}
// Vector2Scalar returns a new [Vector2] with all components set to the given scalar value.
func Vector2Scalar(scalar float32) Vector2 {
return Vector2{scalar, scalar}
}
// Vector2Polar returns a new [Vector2] from polar coordinates,
// with angle in radians CCW and radius the distance from (0,0).
func Vector2Polar(angle, radius float32) Vector2 {
return Vector2{radius * math32.Cos(angle), radius * math32.Sin(angle)}
}
// FromPoint returns a new [Vector2] from the given [image.Point].
func FromPoint(pt image.Point) Vector2 {
v := Vector2{}
v.SetPoint(pt)
return v
}
// Vector2FromFixed returns a new [Vector2] from the given [fixed.Point26_6].
func Vector2FromFixed(pt fixed.Point26_6) Vector2 {
v := Vector2{}
v.SetFixed(pt)
return v
}
// Set sets this vector's X and Y components.
func (v *Vector2) Set(x, y float32) {
v.X = x
v.Y = y
}
// SetScalar sets all vector components to the same scalar value.
func (v *Vector2) SetScalar(scalar float32) {
v.X = scalar
v.Y = scalar
}
// SetFromVector2i sets from a [Vector2i] (int32) vector.
func (v *Vector2) SetFromVector2i(vi Vector2i) {
v.X = float32(vi.X)
v.Y = float32(vi.Y)
}
// SetZero sets all of the vector's components to zero.
func (v *Vector2) SetZero() {
v.SetScalar(0)
}
// Basic math operations:
// Add adds the other given vector to this one and returns the result as a new vector.
func (v Vector2) Add(other Vector2) Vector2 {
return Vec2(v.X+other.X, v.Y+other.Y)
}
// AddScalar adds scalar s to each component of this vector and returns new vector.
func (v Vector2) AddScalar(s float32) Vector2 {
return Vec2(v.X+s, v.Y+s)
}
// SetAdd sets this to addition with other vector (i.e., += or plus-equals).
func (v *Vector2) SetAdd(other Vector2) {
v.X += other.X
v.Y += other.Y
}
// SetAddScalar sets this to addition with scalar.
func (v *Vector2) SetAddScalar(s float32) {
v.X += s
v.Y += s
}
// Sub subtracts other vector from this one and returns result in new vector.
func (v Vector2) Sub(other Vector2) Vector2 {
return Vec2(v.X-other.X, v.Y-other.Y)
}
// SubScalar subtracts scalar s from each component of this vector and returns new vector.
func (v Vector2) SubScalar(s float32) Vector2 {
return Vec2(v.X-s, v.Y-s)
}
// SetSub sets this to subtraction with other vector (i.e., -= or minus-equals).
func (v *Vector2) SetSub(other Vector2) {
v.X -= other.X
v.Y -= other.Y
}
// SetSubScalar sets this to subtraction of scalar.
func (v *Vector2) SetSubScalar(s float32) {
v.X -= s
v.Y -= s
}
// Mul multiplies each component of this vector by the corresponding one from other
// and returns resulting vector.
func (v Vector2) Mul(other Vector2) Vector2 {
return Vec2(v.X*other.X, v.Y*other.Y)
}
// MulScalar multiplies each component of this vector by the scalar s and returns resulting vector.
func (v Vector2) MulScalar(s float32) Vector2 {
return Vec2(v.X*s, v.Y*s)
}
// SetMul sets this to multiplication with other vector (i.e., *= or times-equals).
func (v *Vector2) SetMul(other Vector2) {
v.X *= other.X
v.Y *= other.Y
}
// SetMulScalar sets this to multiplication by scalar.
func (v *Vector2) SetMulScalar(s float32) {
v.X *= s
v.Y *= s
}
// Div divides each component of this vector by the corresponding one from other vector
// and returns resulting vector.
func (v Vector2) Div(other Vector2) Vector2 {
return Vec2(v.X/other.X, v.Y/other.Y)
}
// DivScalar divides each component of this vector by the scalar s and returns resulting vector.
// If scalar is zero, returns zero.
func (v Vector2) DivScalar(scalar float32) Vector2 {
if scalar != 0 {
return v.MulScalar(1 / scalar)
}
return Vector2{}
}
// SetDiv sets this to division by other vector (i.e., /= or divide-equals).
func (v *Vector2) SetDiv(other Vector2) {
v.X /= other.X
v.Y /= other.Y
}
// SetDivScalar sets this to division by scalar.
func (v *Vector2) SetDivScalar(scalar float32) {
if scalar != 0 {
v.SetMulScalar(1 / scalar)
} else {
v.SetZero()
}
}
// Abs returns the vector with [Abs] applied to each component.
func (v Vector2) Abs() Vector2 {
return Vec2(Abs(v.X), Abs(v.Y))
}
// Min returns min of this vector components vs. other vector.
func (v Vector2) Min(other Vector2) Vector2 {
return Vec2(Min(v.X, other.X), Min(v.Y, other.Y))
}
// SetMin sets this vector components to the minimum values of itself and other vector.
func (v *Vector2) SetMin(other Vector2) {
v.X = Min(v.X, other.X)
v.Y = Min(v.Y, other.Y)
}
// Max returns max of this vector components vs. other vector.
func (v Vector2) Max(other Vector2) Vector2 {
return Vec2(Max(v.X, other.X), Max(v.Y, other.Y))
}
// SetMax sets this vector components to the maximum value of itself and other vector.
func (v *Vector2) SetMax(other Vector2) {
v.X = Max(v.X, other.X)
v.Y = Max(v.Y, other.Y)
}
// Clamp sets this vector's components to be no less than the corresponding
// components of min and not greater than the corresponding component of max.
// Assumes min < max; if this assumption isn't true, it will not operate correctly.
func (v *Vector2) Clamp(min, max Vector2) {
if v.X < min.X {
v.X = min.X
} else if v.X > max.X {
v.X = max.X
}
if v.Y < min.Y {
v.Y = min.Y
} else if v.Y > max.Y {
v.Y = max.Y
}
}
// Negate returns the vector with each component negated.
func (v Vector2) Negate() Vector2 {
return Vec2(-v.X, -v.Y)
}
// Distance, Normal:
// Dot returns the dot product of this vector with the given other vector.
func (v Vector2) Dot(other Vector2) float32 {
return v.X*other.X + v.Y*other.Y
}
// Length returns the length (magnitude) of this vector.
func (v Vector2) Length() float32 {
return Sqrt(v.LengthSquared())
}
// LengthSquared returns the length squared of this vector.
// LengthSquared can be used to compare the lengths of vectors
// without the need to perform a square root.
func (v Vector2) LengthSquared() float32 {
return v.X*v.X + v.Y*v.Y
}
// Normal returns this vector divided by its length (its unit vector).
func (v Vector2) Normal() Vector2 {
l := v.Length()
if l == 0 {
return Vector2{}
}
return v.DivScalar(l)
}
// DistanceTo returns the distance between these two vectors as points.
func (v Vector2) DistanceTo(other Vector2) float32 {
return Sqrt(v.DistanceToSquared(other))
}
// DistanceToSquared returns the squared distance between these two vectors as points.
func (v Vector2) DistanceToSquared(other Vector2) float32 {
dx := v.X - other.X
dy := v.Y - other.Y
return dx*dx + dy*dy
}
// Cross returns the cross product of this vector with other.
func (v Vector2) Cross(other Vector2) float32 {
return v.X*other.Y - v.Y*other.X
}
// CosTo returns the cosine (normalized dot product) between this vector and other.
func (v Vector2) CosTo(other Vector2) float32 {
return v.Dot(other) / (v.Length() * other.Length())
}
// AngleTo returns the angle between this vector and other.
// Returns angles in range of -PI to PI (not 0 to 2 PI).
func (v Vector2) AngleTo(other Vector2) float32 {
ang := Acos(Clamp(v.CosTo(other), -1, 1))
cross := v.Cross(other)
if cross > 0 {
ang = -ang
}
return ang
}
// Lerp returns vector with each components as the linear interpolated value of
// alpha between itself and the corresponding other component.
func (v Vector2) Lerp(other Vector2, alpha float32) Vector2 {
return Vec2(v.X+(other.X-v.X)*alpha, v.Y+(other.Y-v.Y)*alpha)
}
// InTriangle returns whether the vector is inside the specified triangle.
func (v Vector2) InTriangle(p0, p1, p2 Vector2) bool {
A := 0.5 * (-p1.Y*p2.X + p0.Y*(-p1.X+p2.X) + p0.X*(p1.Y-p2.Y) + p1.X*p2.Y)
sign := float32(1)
if A < 0 {
sign = float32(-1)
}
s := (p0.Y*p2.X - p0.X*p2.Y + (p2.Y-p0.Y)*v.X + (p0.X-p2.X)*v.Y) * sign
t := (p0.X*p1.Y - p0.Y*p1.X + (p0.Y-p1.Y)*v.X + (p1.X-p0.X)*v.Y) * sign
return s >= 0 && t >= 0 && (s+t) < 2*A*sign
}
// Rot90CW rotates the line OP by 90 degrees CW.
func (v Vector2) Rot90CW() Vector2 {
return Vector2{v.Y, -v.X}
}
// Rot90CCW rotates the line OP by 90 degrees CCW.
func (v Vector2) Rot90CCW() Vector2 {
return Vector2{-v.Y, v.X}
}
// Rot rotates the line OP by phi radians CCW.
func (v Vector2) Rot(phi float32, p0 Vector2) Vector2 {
sinphi, cosphi := math32.Sincos(phi)
return Vector2{
p0.X + cosphi*(v.X-p0.X) - sinphi*(v.Y-p0.Y),
p0.Y + sinphi*(v.X-p0.X) + cosphi*(v.Y-p0.Y),
}
}
func (v Vector2) String() string {
return fmt.Sprintf("(%v, %v)", v.X, v.Y)
}
// SetDim sets the given vector component value by its dimension index.
func (v *Vector2) SetDim(dim Dims, value float32) {
switch dim {
case X:
v.X = value
case Y:
v.Y = value
default:
panic("dim is out of range")
}
}
// Dim returns the given vector component.
func (v Vector2) Dim(dim Dims) float32 {
switch dim {
case X:
return v.X
case Y:
return v.Y
default:
panic("dim is out of range")
}
}
// SetPointDim sets the given dimension of the given [image.Point] to the given value.
func SetPointDim(pt *image.Point, dim Dims, value int) {
switch dim {
case X:
pt.X = value
case Y:
pt.Y = value
default:
panic("dim is out of range")
}
}
// PointDim returns the given dimension of the given [image.Point].
func PointDim(pt image.Point, dim Dims) int {
switch dim {
case X:
return pt.X
case Y:
return pt.Y
default:
panic("dim is out of range")
}
}
// AddDim returns the vector with the given value added on the given dimension.
func (v Vector2) AddDim(d Dims, value float32) Vector2 {
switch d {
case X:
v.X += value
case Y:
v.Y += value
default:
panic("dim is out of range")
}
return v
}
// SubDim returns the vector with the given value subtracted on the given dimension.
func (v Vector2) SubDim(d Dims, value float32) Vector2 {
switch d {
case X:
v.X -= value
case Y:
v.Y -= value
default:
panic("dim is out of range")
}
return v
}
// MulDim returns the vector with the given value multiplied by on the given dimension.
func (v Vector2) MulDim(d Dims, value float32) Vector2 {
switch d {
case X:
v.X *= value
case Y:
v.Y *= value
default:
panic("dim is out of range")
}
return v
}
// DivDim returns the vector with the given value divided by on the given dimension.
func (v Vector2) DivDim(d Dims, value float32) Vector2 {
switch d {
case X:
v.X /= value
case Y:
v.Y /= value
default:
panic("dim is out of range")
}
return v
}
// SetPoint sets the vector from the given [image.Point].
func (v *Vector2) SetPoint(pt image.Point) {
v.X = float32(pt.X)
v.Y = float32(pt.Y)
}
// SetFixed sets the vector from the given [fixed.Point26_6].
func (v *Vector2) SetFixed(pt fixed.Point26_6) {
v.X = FromFixed(pt.X)
v.Y = FromFixed(pt.Y)
}
// ToPoint returns the vector as an [image.Point].
func (v Vector2) ToPoint() image.Point {
return image.Point{int(v.X), int(v.Y)}
}
// ToPointFloor returns the vector as an [image.Point] with all values [Floor]ed.
func (v Vector2) ToPointFloor() image.Point {
return image.Point{int(Floor(v.X)), int(Floor(v.Y))}
}
// ToPointCeil returns the vector as an [image.Point] with all values [Ceil]ed.
func (v Vector2) ToPointCeil() image.Point {
return image.Point{int(Ceil(v.X)), int(Ceil(v.Y))}
}
// ToPointRound returns the vector as an [image.Point] with all values [Round]ed.
func (v Vector2) ToPointRound() image.Point {
return image.Point{int(Round(v.X)), int(Round(v.Y))}
}
// ToFixed returns the vector as a [fixed.Point26_6].
func (v Vector2) ToFixed() fixed.Point26_6 {
return ToFixedPoint(v.X, v.Y)
}
// RectFromPosSizeMax returns an [image.Rectangle] from the floor of pos
// and ceil of size.
func RectFromPosSizeMax(pos, size Vector2) image.Rectangle {
tp := pos.ToPointFloor()
ts := size.ToPointCeil()
return image.Rect(tp.X, tp.Y, tp.X+ts.X, tp.Y+ts.Y)
}
// RectFromPosSizeMin returns an [image.Rectangle] from the ceil of pos
// and floor of size.
func RectFromPosSizeMin(pos, size Vector2) image.Rectangle {
tp := pos.ToPointCeil()
ts := size.ToPointFloor()
return image.Rect(tp.X, tp.Y, tp.X+ts.X, tp.Y+ts.Y)
}
// FromSlice sets this vector's components from the given slice, starting at offset.
func (v *Vector2) FromSlice(slice []float32, offset int) {
v.X = slice[offset]
v.Y = slice[offset+1]
}
// ToSlice copies this vector's components to the given slice, starting at offset.
func (v Vector2) ToSlice(slice []float32, offset int) {
slice[offset] = v.X
slice[offset+1] = v.Y
}
// Floor returns this vector with [Floor] applied to each of its components.
func (v Vector2) Floor() Vector2 {
return Vec2(Floor(v.X), Floor(v.Y))
}
// Ceil returns this vector with [Ceil] applied to each of its components.
func (v Vector2) Ceil() Vector2 {
return Vec2(Ceil(v.X), Ceil(v.Y))
}
// Round returns this vector with [Round] applied to each of its components.
func (v Vector2) Round() Vector2 {
return Vec2(Round(v.X), Round(v.Y))
}
// Copyright 2019 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Initially copied from G3N: github.com/g3n/engine/math32
// Copyright 2016 The G3N Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// with modifications needed to suit Cogent Core functionality.
package math32
// Vector2i is a 2D vector/point with X and Y int32 components.
type Vector2i struct {
X int32
Y int32
}
// Vec2i returns a new [Vector2i] with the given x and y components.
func Vec2i(x, y int) Vector2i {
return Vector2i{X: int32(x), Y: int32(y)}
}
// Vector2iScalar returns a new [Vector2i] with all components set to the given scalar value.
func Vector2iScalar(scalar int32) Vector2i {
return Vector2i{X: scalar, Y: scalar}
}
// Set sets this vector X and Y components.
func (v *Vector2i) Set(x, y int32) {
v.X = x
v.Y = y
}
// SetScalar sets all vector components to the same scalar value.
func (v *Vector2i) SetScalar(scalar int32) {
v.X = scalar
v.Y = scalar
}
// SetFromVector2 sets from a [Vector2] (float32) vector.
func (v *Vector2i) SetFromVector2(vf Vector2) {
v.X = int32(vf.X)
v.Y = int32(vf.Y)
}
// SetDim sets the given vector component value by its dimension index.
func (v *Vector2i) SetDim(dim Dims, value int32) {
switch dim {
case X:
v.X = value
case Y:
v.Y = value
default:
panic("dim is out of range")
}
}
// Dim returns the given vector component.
func (v Vector2i) Dim(dim Dims) int32 {
switch dim {
case X:
return v.X
case Y:
return v.Y
default:
panic("dim is out of range")
}
}
// SetZero sets all of the vector's components to zero.
func (v *Vector2i) SetZero() {
v.SetScalar(0)
}
// FromSlice sets this vector's components from the given slice, starting at offset.
func (v *Vector2i) FromSlice(array []int32, offset int) {
v.X = array[offset]
v.Y = array[offset+1]
}
// ToSlice copies this vector's components to the given slice, starting at offset.
func (v Vector2i) ToSlice(array []int32, offset int) {
array[offset] = v.X
array[offset+1] = v.Y
}
// Basic math operations:
// Add adds the other given vector to this one and returns the result as a new vector.
func (v Vector2i) Add(other Vector2i) Vector2i {
return Vector2i{v.X + other.X, v.Y + other.Y}
}
// AddScalar adds scalar s to each component of this vector and returns new vector.
func (v Vector2i) AddScalar(s int32) Vector2i {
return Vector2i{v.X + s, v.Y + s}
}
// SetAdd sets this to addition with other vector (i.e., += or plus-equals).
func (v *Vector2i) SetAdd(other Vector2i) {
v.X += other.X
v.Y += other.Y
}
// SetAddScalar sets this to addition with scalar.
func (v *Vector2i) SetAddScalar(s int32) {
v.X += s
v.Y += s
}
// Sub subtracts other vector from this one and returns result in new vector.
func (v Vector2i) Sub(other Vector2i) Vector2i {
return Vector2i{v.X - other.X, v.Y - other.Y}
}
// SubScalar subtracts scalar s from each component of this vector and returns new vector.
func (v Vector2i) SubScalar(s int32) Vector2i {
return Vector2i{v.X - s, v.Y - s}
}
// SetSub sets this to subtraction with other vector (i.e., -= or minus-equals).
func (v *Vector2i) SetSub(other Vector2i) {
v.X -= other.X
v.Y -= other.Y
}
// SetSubScalar sets this to subtraction of scalar.
func (v *Vector2i) SetSubScalar(s int32) {
v.X -= s
v.Y -= s
}
// Mul multiplies each component of this vector by the corresponding one from other
// and returns resulting vector.
func (v Vector2i) Mul(other Vector2i) Vector2i {
return Vector2i{v.X * other.X, v.Y * other.Y}
}
// MulScalar multiplies each component of this vector by the scalar s and returns resulting vector.
func (v Vector2i) MulScalar(s int32) Vector2i {
return Vector2i{v.X * s, v.Y * s}
}
// SetMul sets this to multiplication with other vector (i.e., *= or times-equals).
func (v *Vector2i) SetMul(other Vector2i) {
v.X *= other.X
v.Y *= other.Y
}
// SetMulScalar sets this to multiplication by scalar.
func (v *Vector2i) SetMulScalar(s int32) {
v.X *= s
v.Y *= s
}
// Div divides each component of this vector by the corresponding one from other vector
// and returns resulting vector.
func (v Vector2i) Div(other Vector2i) Vector2i {
return Vector2i{v.X / other.X, v.Y / other.Y}
}
// DivScalar divides each component of this vector by the scalar s and returns resulting vector.
// If scalar is zero, returns zero.
func (v Vector2i) DivScalar(scalar int32) Vector2i {
if scalar != 0 {
return Vector2i{v.X / scalar, v.Y / scalar}
}
return Vector2i{}
}
// SetDiv sets this to division by other vector (i.e., /= or divide-equals).
func (v *Vector2i) SetDiv(other Vector2i) {
v.X /= other.X
v.Y /= other.Y
}
// SetDivScalar sets this to division by scalar.
func (v *Vector2i) SetDivScalar(scalar int32) {
if scalar != 0 {
v.X /= scalar
v.Y /= scalar
} else {
v.SetZero()
}
}
// Min returns min of this vector components vs. other vector.
func (v Vector2i) Min(other Vector2i) Vector2i {
return Vector2i{min(v.X, other.X), min(v.Y, other.Y)}
}
// SetMin sets this vector components to the minimum values of itself and other vector.
func (v *Vector2i) SetMin(other Vector2i) {
v.X = min(v.X, other.X)
v.Y = min(v.Y, other.Y)
}
// Max returns max of this vector components vs. other vector.
func (v Vector2i) Max(other Vector2i) Vector2i {
return Vector2i{max(v.X, other.X), max(v.Y, other.Y)}
}
// SetMax sets this vector components to the maximum value of itself and other vector.
func (v *Vector2i) SetMax(other Vector2i) {
v.X = max(v.X, other.X)
v.Y = max(v.Y, other.Y)
}
// Clamp sets this vector's components to be no less than the corresponding
// components of min and not greater than the corresponding component of max.
// Assumes min < max; if this assumption isn't true, it will not operate correctly.
func (v *Vector2i) Clamp(min, max Vector2i) {
if v.X < min.X {
v.X = min.X
} else if v.X > max.X {
v.X = max.X
}
if v.Y < min.Y {
v.Y = min.Y
} else if v.Y > max.Y {
v.Y = max.Y
}
}
// Negate returns the vector with each component negated.
func (v Vector2i) Negate() Vector2i {
return Vector2i{-v.X, -v.Y}
}
// Copyright 2019 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Initially copied from G3N: github.com/g3n/engine/math32
// Copyright 2016 The G3N Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// with modifications needed to suit Cogent Core functionality.
package math32
import "fmt"
// Vector3 is a 3D vector/point with X, Y and Z components.
type Vector3 struct {
X float32
Y float32
Z float32
}
// Vec3 returns a new [Vector3] with the given x, y and z components.
func Vec3(x, y, z float32) Vector3 {
return Vector3{x, y, z}
}
// Vector3Scalar returns a new [Vector3] with all components set to the given scalar value.
func Vector3Scalar(scalar float32) Vector3 {
return Vector3{scalar, scalar, scalar}
}
// Vector3FromVector4 returns a new [Vector3] from the given [Vector4].
func Vector3FromVector4(v Vector4) Vector3 {
nv := Vector3{}
nv.SetFromVector4(v)
return nv
}
// Set sets this vector X, Y and Z components.
func (v *Vector3) Set(x, y, z float32) {
v.X = x
v.Y = y
v.Z = z
}
// SetScalar sets all vector components to the same scalar value.
func (v *Vector3) SetScalar(scalar float32) {
v.X = scalar
v.Y = scalar
v.Z = scalar
}
// SetFromVector4 sets this vector from a Vector4
func (v *Vector3) SetFromVector4(other Vector4) {
v.X = other.X
v.Y = other.Y
v.Z = other.Z
}
// SetFromVector3i sets from a Vector3i (int32) vector.
func (v *Vector3) SetFromVector3i(vi Vector3i) {
v.X = float32(vi.X)
v.Y = float32(vi.Y)
v.Z = float32(vi.Z)
}
// SetDim sets this vector component value by dimension index.
func (v *Vector3) SetDim(dim Dims, value float32) {
switch dim {
case X:
v.X = value
case Y:
v.Y = value
case Z:
v.Z = value
default:
panic("dim is out of range: ")
}
}
// Dim returns this vector component
func (v Vector3) Dim(dim Dims) float32 {
switch dim {
case X:
return v.X
case Y:
return v.Y
case Z:
return v.Z
default:
panic("dim is out of range")
}
}
func (v Vector3) String() string {
return fmt.Sprintf("(%v, %v, %v)", v.X, v.Y, v.Z)
}
// GenGoSet returns code to set values in object at given path (var.member etc).
func (v *Vector3) GenGoSet(path string) string {
return fmt.Sprintf("%s.Set(%g, %g, %g)", path, v.X, v.Y, v.Z)
}
// SetZero sets all of the vector's components to zero.
func (v *Vector3) SetZero() {
v.SetScalar(0)
}
// FromSlice sets this vector's components from the given slice, starting at offset.
func (v *Vector3) FromSlice(array []float32, offset int) {
v.X = array[offset]
v.Y = array[offset+1]
v.Z = array[offset+2]
}
// ToSlice copies this vector's components to the given slice, starting at offset.
func (v Vector3) ToSlice(array []float32, offset int) {
array[offset] = v.X
array[offset+1] = v.Y
array[offset+2] = v.Z
}
func (v Vector3) IsNaN() bool {
return IsNaN(v.X) || IsNaN(v.Y) || IsNaN(v.Z)
}
// Basic math operations:
// Add adds the other given vector to this one and returns the result as a new vector.
func (v Vector3) Add(other Vector3) Vector3 {
return Vec3(v.X+other.X, v.Y+other.Y, v.Z+other.Z)
}
// AddScalar adds scalar s to each component of this vector and returns new vector.
func (v Vector3) AddScalar(s float32) Vector3 {
return Vec3(v.X+s, v.Y+s, v.Z+s)
}
// SetAdd sets this to addition with other vector (i.e., += or plus-equals).
func (v *Vector3) SetAdd(other Vector3) {
v.X += other.X
v.Y += other.Y
v.Z += other.Z
}
// SetAddScalar sets this to addition with scalar.
func (v *Vector3) SetAddScalar(s float32) {
v.X += s
v.Y += s
v.Z += s
}
// Sub subtracts other vector from this one and returns result in new vector.
func (v Vector3) Sub(other Vector3) Vector3 {
return Vec3(v.X-other.X, v.Y-other.Y, v.Z-other.Z)
}
// SubScalar subtracts scalar s from each component of this vector and returns new vector.
func (v Vector3) SubScalar(s float32) Vector3 {
return Vec3(v.X-s, v.Y-s, v.Z-s)
}
// SetSub sets this to subtraction with other vector (i.e., -= or minus-equals).
func (v *Vector3) SetSub(other Vector3) {
v.X -= other.X
v.Y -= other.Y
v.Z -= other.Z
}
// SetSubScalar sets this to subtraction of scalar.
func (v *Vector3) SetSubScalar(s float32) {
v.X -= s
v.Y -= s
v.Z -= s
}
// Mul multiplies each component of this vector by the corresponding one from other
// and returns resulting vector.
func (v Vector3) Mul(other Vector3) Vector3 {
return Vec3(v.X*other.X, v.Y*other.Y, v.Z*other.Z)
}
// MulScalar multiplies each component of this vector by the scalar s and returns resulting vector.
func (v Vector3) MulScalar(s float32) Vector3 {
return Vec3(v.X*s, v.Y*s, v.Z*s)
}
// SetMul sets this to multiplication with other vector (i.e., *= or times-equals).
func (v *Vector3) SetMul(other Vector3) {
v.X *= other.X
v.Y *= other.Y
v.Z *= other.Z
}
// SetMulScalar sets this to multiplication by scalar.
func (v *Vector3) SetMulScalar(s float32) {
v.X *= s
v.Y *= s
v.Z *= s
}
// Div divides each component of this vector by the corresponding one from other vector
// and returns resulting vector.
func (v Vector3) Div(other Vector3) Vector3 {
return Vec3(v.X/other.X, v.Y/other.Y, v.Z/other.Z)
}
// DivScalar divides each component of this vector by the scalar s and returns resulting vector.
// If scalar is zero, returns zero.
func (v Vector3) DivScalar(scalar float32) Vector3 {
if scalar != 0 {
return v.MulScalar(1 / scalar)
}
return Vector3{}
}
// SetDiv sets this to division by other vector (i.e., /= or divide-equals).
func (v *Vector3) SetDiv(other Vector3) {
v.X /= other.X
v.Y /= other.Y
v.Z /= other.Z
}
// SetDivScalar sets this to division by scalar.
func (v *Vector3) SetDivScalar(scalar float32) {
if scalar != 0 {
v.SetMulScalar(1 / scalar)
} else {
v.SetZero()
}
}
// Min returns min of this vector components vs. other vector.
func (v Vector3) Min(other Vector3) Vector3 {
return Vec3(Min(v.X, other.X), Min(v.Y, other.Y), Min(v.Z, other.Z))
}
// SetMin sets this vector components to the minimum values of itself and other vector.
func (v *Vector3) SetMin(other Vector3) {
v.X = Min(v.X, other.X)
v.Y = Min(v.Y, other.Y)
v.Z = Min(v.Z, other.Z)
}
// Max returns max of this vector components vs. other vector.
func (v Vector3) Max(other Vector3) Vector3 {
return Vec3(Max(v.X, other.X), Max(v.Y, other.Y), Max(v.Z, other.Z))
}
// SetMax sets this vector components to the maximum value of itself and other vector.
func (v *Vector3) SetMax(other Vector3) {
v.X = Max(v.X, other.X)
v.Y = Max(v.Y, other.Y)
v.Z = Max(v.Z, other.Z)
}
// Clamp sets this vector's components to be no less than the corresponding
// components of min and not greater than the corresponding component of max.
// Assumes min < max; if this assumption isn't true, it will not operate correctly.
func (v *Vector3) Clamp(min, max Vector3) {
if v.X < min.X {
v.X = min.X
} else if v.X > max.X {
v.X = max.X
}
if v.Y < min.Y {
v.Y = min.Y
} else if v.Y > max.Y {
v.Y = max.Y
}
if v.Z < min.Z {
v.Z = min.Z
} else if v.Z > max.Z {
v.Z = max.Z
}
}
// Floor returns this vector with [Floor] applied to each of its components.
func (v Vector3) Floor() Vector3 {
return Vec3(Floor(v.X), Floor(v.Y), Floor(v.Z))
}
// Ceil returns this vector with [Ceil] applied to each of its components.
func (v Vector3) Ceil() Vector3 {
return Vec3(Ceil(v.X), Ceil(v.Y), Ceil(v.Z))
}
// Round returns this vector with [Round] applied to each of its components.
func (v Vector3) Round() Vector3 {
return Vec3(Round(v.X), Round(v.Y), Round(v.Z))
}
// Negate returns the vector with each component negated.
func (v Vector3) Negate() Vector3 {
return Vec3(-v.X, -v.Y, -v.Z)
}
// Abs returns the vector with [Abs] applied to each component.
func (v Vector3) Abs() Vector3 {
return Vec3(Abs(v.X), Abs(v.Y), Abs(v.Z))
}
// Distance, Normal:
// Dot returns the dot product of this vector with the given other vector.
func (v Vector3) Dot(other Vector3) float32 {
return v.X*other.X + v.Y*other.Y + v.Z*other.Z
}
// Length returns the length (magnitude) of this vector.
func (v Vector3) Length() float32 {
return Sqrt(v.X*v.X + v.Y*v.Y + v.Z*v.Z)
}
// LengthSquared returns the length squared of this vector.
// LengthSquared can be used to compare the lengths of vectors
// without the need to perform a square root.
func (v Vector3) LengthSquared() float32 {
return v.X*v.X + v.Y*v.Y + v.Z*v.Z
}
// Normal returns this vector divided by its length (its unit vector).
func (v Vector3) Normal() Vector3 {
return v.DivScalar(v.Length())
}
// SetNormal normalizes this vector so its length will be 1.
func (v *Vector3) SetNormal() {
v.SetDivScalar(v.Length())
}
// DistanceTo returns the distance between these two vectors as points.
func (v Vector3) DistanceTo(other Vector3) float32 {
return Sqrt(v.DistanceToSquared(other))
}
// DistanceToSquared returns the squared distance between these two vectors as points.
func (v Vector3) DistanceToSquared(other Vector3) float32 {
dx := v.X - other.X
dy := v.Y - other.Y
dz := v.Z - other.Z
return dx*dx + dy*dy + dz*dz
}
// Lerp returns vector with each components as the linear interpolated value of
// alpha between itself and the corresponding other component.
func (v Vector3) Lerp(other Vector3, alpha float32) Vector3 {
return Vec3(v.X+(other.X-v.X)*alpha, v.Y+(other.Y-v.Y)*alpha, v.Z+(other.Z-v.Z)*alpha)
}
// Matrix operations:
// MulMatrix3 returns the vector multiplied by the given 3x3 matrix.
func (v Vector3) MulMatrix3(m *Matrix3) Vector3 {
return Vector3{m[0]*v.X + m[3]*v.Y + m[6]*v.Z,
m[1]*v.X + m[4]*v.Y + m[7]*v.Z,
m[2]*v.X + m[5]*v.Y + m[8]*v.Z}
}
// MulMatrix4 returns the vector multiplied by the given 4x4 matrix.
func (v Vector3) MulMatrix4(m *Matrix4) Vector3 {
return Vector3{m[0]*v.X + m[4]*v.Y + m[8]*v.Z + m[12],
m[1]*v.X + m[5]*v.Y + m[9]*v.Z + m[13],
m[2]*v.X + m[6]*v.Y + m[10]*v.Z + m[14]}
}
// MulMatrix4AsVector4 returns 3-dim vector multiplied by specified 4x4 matrix
// using a 4-dim vector with given 4th dimensional value, then reduced back to
// a 3-dimensional vector. This is somehow different from just straight
// MulMatrix4 on the 3-dim vector. Use 0 for normals and 1 for positions
// as the 4th dim to set.
func (v Vector3) MulMatrix4AsVector4(m *Matrix4, w float32) Vector3 {
return Vector3FromVector4(Vector4FromVector3(v, w).MulMatrix4(m))
}
// NDCToWindow converts normalized display coordinates (NDC) to window
// (pixel) coordinates, using given window size parameters.
// near, far are 0, 1 by default (glDepthRange defaults).
// flipY if true means flip the Y axis (top = 0 for windows vs. bottom = 0 for 3D coords)
func (v Vector3) NDCToWindow(size, off Vector2, near, far float32, flipY YFlip) Vector3 {
w := Vector3{}
half := size.MulScalar(0.5)
w.X = half.X*v.X + half.X
w.Y = half.Y*v.Y + half.Y
w.Z = 0.5*(far-near)*v.Z + 0.5*(far+near)
if flipY {
w.Y = size.Y - w.Y
}
w.X += off.X
w.Y += off.Y
return w
}
// WindowToNDC converts window (pixel) coordinates to
// normalized display coordinates (NDC), using given window size parameters.
// The Z depth coordinate (0-1) must be set manually or by reading from framebuffer
// flipY if true means flip the Y axis (top = 0 for windows vs. bottom = 0 for 3D coords)
func (v Vector2) WindowToNDC(size, off Vector2, flipY YFlip) Vector3 {
n := Vector3{}
half := size.MulScalar(0.5)
n.X = v.X - off.X
n.Y = v.Y - off.Y
if flipY {
n.Y = size.Y - n.Y
}
n.X = n.X/half.X - 1
n.Y = n.Y/half.Y - 1
return n
}
// MulProjection returns vector multiplied by the projection matrix m.
func (v Vector3) MulProjection(m *Matrix4) Vector3 {
d := 1 / (m[3]*v.X + m[7]*v.Y + m[11]*v.Z + m[15]) // perspective divide
return Vector3{(m[0]*v.X + m[4]*v.Y + m[8]*v.Z + m[12]) * d,
(m[1]*v.X + m[5]*v.Y + m[9]*v.Z + m[13]) * d,
(m[2]*v.X + m[6]*v.Y + m[10]*v.Z + m[14]) * d}
}
// Cross returns the cross product of this vector with other.
func (v Vector3) Cross(other Vector3) Vector3 {
return Vec3(v.Y*other.Z-v.Z*other.Y, v.Z*other.X-v.X*other.Z, v.X*other.Y-v.Y*other.X)
}
// ProjectOnVector returns vector projected on other vector.
func (v *Vector3) ProjectOnVector(other Vector3) Vector3 {
on := other.Normal()
return on.MulScalar(v.Dot(on))
}
// ProjectOnPlane returns vector projected on the plane specified by normal vector.
func (v *Vector3) ProjectOnPlane(planeNormal Vector3) Vector3 {
return v.Sub(v.ProjectOnVector(planeNormal))
}
// Reflect returns vector reflected relative to the normal vector (assumed to be
// already normalized).
func (v *Vector3) Reflect(normal Vector3) Vector3 {
return v.Sub(normal.MulScalar(2 * v.Dot(normal)))
}
// CosTo returns the cosine (normalized dot product) between this vector and other.
func (v Vector3) CosTo(other Vector3) float32 {
return v.Dot(other) / (v.Length() * other.Length())
}
// AngleTo returns the angle between this vector and other.
// Returns angles in range of -PI to PI (not 0 to 2 PI).
func (v Vector3) AngleTo(other Vector3) float32 {
ang := Acos(Clamp(v.CosTo(other), -1, 1))
cross := v.Cross(other)
switch {
case Abs(cross.Z) >= Abs(cross.Y) && Abs(cross.Z) >= Abs(cross.X):
if cross.Z > 0 {
ang = -ang
}
case Abs(cross.Y) >= Abs(cross.Z) && Abs(cross.Y) >= Abs(cross.X):
if cross.Y > 0 {
ang = -ang
}
case Abs(cross.X) >= Abs(cross.Z) && Abs(cross.X) >= Abs(cross.Y):
if cross.X > 0 {
ang = -ang
}
}
return ang
}
// SetFromMatrixPos set this vector from the translation coordinates
// in the specified transformation matrix.
func (v *Vector3) SetFromMatrixPos(m *Matrix4) {
v.X = m[12]
v.Y = m[13]
v.Z = m[14]
}
// SetEulerAnglesFromMatrix sets this vector components to the Euler angles
// from the specified pure rotation matrix.
func (v *Vector3) SetEulerAnglesFromMatrix(m *Matrix4) {
m11 := m[0]
m12 := m[4]
m13 := m[8]
m22 := m[5]
m23 := m[9]
m32 := m[6]
m33 := m[10]
v.Y = Asin(Clamp(m13, -1, 1))
if Abs(m13) < 0.99999 {
v.X = Atan2(-m23, m33)
v.Z = Atan2(-m12, m11)
} else {
v.X = Atan2(m32, m22)
v.Z = 0
}
}
// NewEulerAnglesFromMatrix returns a Vector3 with components as the Euler angles
// from the specified pure rotation matrix.
func NewEulerAnglesFromMatrix(m *Matrix4) Vector3 {
rot := Vector3{}
rot.SetEulerAnglesFromMatrix(m)
return rot
}
// SetEulerAnglesFromQuat sets this vector components to the Euler angles
// from the specified quaternion.
func (v *Vector3) SetEulerAnglesFromQuat(q Quat) {
mat := Identity4()
mat.SetRotationFromQuat(q)
v.SetEulerAnglesFromMatrix(mat)
}
// RandomTangents computes and returns two arbitrary tangents to the vector.
func (v *Vector3) RandomTangents() (Vector3, Vector3) {
t1 := Vector3{}
t2 := Vector3{}
length := v.Length()
if length > 0 {
n := v.Normal()
randVec := Vector3{}
if Abs(n.X) < 0.9 {
randVec.X = 1
t1 = n.Cross(randVec)
} else if Abs(n.Y) < 0.9 {
randVec.Y = 1
t1 = n.Cross(randVec)
} else {
randVec.Z = 1
t1 = n.Cross(randVec)
}
t2 = n.Cross(t1)
} else {
t1.X = 1
t2.Y = 1
}
return t1, t2
}
// YFlip specifies whether to flip the Y axis between coordinate systems
// (e.g., normalized device coordinates and window coordinates):
// [FlipY] or [NoFlipY].
type YFlip bool
const (
// FlipY flips the Y axis.
FlipY YFlip = true
// NoFlipY does not flip the Y axis.
NoFlipY YFlip = false
)
// Copyright 2019 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Initially copied from G3N: github.com/g3n/engine/math32
// Copyright 2016 The G3N Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// with modifications needed to suit Cogent Core functionality.
package math32
// Vector3i is a 3D vector/point with X, Y and Z int32 components.
type Vector3i struct {
X int32
Y int32
Z int32
}
// Vec3i returns a new [Vector3i] with the given x, y and y components.
func Vec3i(x, y, z int32) Vector3i {
return Vector3i{X: x, Y: y, Z: z}
}
// Vector3iScalar returns a new [Vector3i] with all components set to the given scalar value.
func Vector3iScalar(scalar int32) Vector3i {
return Vector3i{X: scalar, Y: scalar, Z: scalar}
}
// Set sets this vector X, Y and Z components.
func (v *Vector3i) Set(x, y, z int32) {
v.X = x
v.Y = y
v.Z = z
}
// SetScalar sets all vector components to the same scalar value.
func (v *Vector3i) SetScalar(scalar int32) {
v.X = scalar
v.Y = scalar
v.Z = scalar
}
// SetFromVector3 sets from a Vector3 (float32) vector.
func (v *Vector3i) SetFromVector3(vf Vector3) {
v.X = int32(vf.X)
v.Y = int32(vf.Y)
v.Z = int32(vf.Z)
}
// SetDim sets the given vector component value by its dimension index.
func (v *Vector3i) SetDim(dim Dims, value int32) {
switch dim {
case X:
v.X = value
case Y:
v.Y = value
case Z:
v.Z = value
default:
panic("dim is out of range: ")
}
}
// Dim returns the given vector component.
func (v Vector3i) Dim(dim Dims) int32 {
switch dim {
case X:
return v.X
case Y:
return v.Y
case Z:
return v.Z
default:
panic("dim is out of range")
}
}
// SetZero sets all of the vector's components to zero.
func (v *Vector3i) SetZero() {
v.SetScalar(0)
}
// FromSlice sets this vector's components from the given slice, starting at offset.
func (v *Vector3i) FromSlice(array []int32, offset int) {
v.X = array[offset]
v.Y = array[offset+1]
v.Z = array[offset+2]
}
// ToSlice copies this vector's components to the given slice, starting at offset.
func (v Vector3i) ToSlice(array []int32, offset int) {
array[offset] = v.X
array[offset+1] = v.Y
array[offset+2] = v.Z
}
// Basic math operations:
// Add adds the other given vector to this one and returns the result as a new vector.
func (v Vector3i) Add(other Vector3i) Vector3i {
return Vector3i{v.X + other.X, v.Y + other.Y, v.Z + other.Z}
}
// AddScalar adds scalar s to each component of this vector and returns new vector.
func (v Vector3i) AddScalar(s int32) Vector3i {
return Vector3i{v.X + s, v.Y + s, v.Z + s}
}
// SetAdd sets this to addition with other vector (i.e., += or plus-equals).
func (v *Vector3i) SetAdd(other Vector3i) {
v.X += other.X
v.Y += other.Y
v.Z += other.Z
}
// SetAddScalar sets this to addition with scalar.
func (v *Vector3i) SetAddScalar(s int32) {
v.X += s
v.Y += s
v.Z += s
}
// Sub subtracts other vector from this one and returns result in new vector.
func (v Vector3i) Sub(other Vector3i) Vector3i {
return Vector3i{v.X - other.X, v.Y - other.Y, v.Z - other.Z}
}
// SubScalar subtracts scalar s from each component of this vector and returns new vector.
func (v Vector3i) SubScalar(s int32) Vector3i {
return Vector3i{v.X - s, v.Y - s, v.Z - s}
}
// SetSub sets this to subtraction with other vector (i.e., -= or minus-equals).
func (v *Vector3i) SetSub(other Vector3i) {
v.X -= other.X
v.Y -= other.Y
v.Z -= other.Z
}
// SetSubScalar sets this to subtraction of scalar.
func (v *Vector3i) SetSubScalar(s int32) {
v.X -= s
v.Y -= s
v.Z -= s
}
// Mul multiplies each component of this vector by the corresponding one from other
// and returns resulting vector.
func (v Vector3i) Mul(other Vector3i) Vector3i {
return Vector3i{v.X * other.X, v.Y * other.Y, v.Z * other.Z}
}
// MulScalar multiplies each component of this vector by the scalar s and returns resulting vector.
func (v Vector3i) MulScalar(s int32) Vector3i {
return Vector3i{v.X * s, v.Y * s, v.Z * s}
}
// SetMul sets this to multiplication with other vector (i.e., *= or times-equals).
func (v *Vector3i) SetMul(other Vector3i) {
v.X *= other.X
v.Y *= other.Y
v.Z *= other.Z
}
// SetMulScalar sets this to multiplication by scalar.
func (v *Vector3i) SetMulScalar(s int32) {
v.X *= s
v.Y *= s
v.Z *= s
}
// Div divides each component of this vector by the corresponding one from other vector
// and returns resulting vector.
func (v Vector3i) Div(other Vector3i) Vector3i {
return Vector3i{v.X / other.X, v.Y / other.Y, v.Z / other.Z}
}
// DivScalar divides each component of this vector by the scalar s and returns resulting vector.
// If scalar is zero, returns zero.
func (v Vector3i) DivScalar(scalar int32) Vector3i {
if scalar != 0 {
return Vector3i{v.X / scalar, v.Y / scalar, v.Z / scalar}
}
return Vector3i{}
}
// SetDiv sets this to division by other vector (i.e., /= or divide-equals).
func (v *Vector3i) SetDiv(other Vector3i) {
v.X /= other.X
v.Y /= other.Y
v.Z /= other.Z
}
// SetDivScalar sets this to division by scalar.
func (v *Vector3i) SetDivScalar(scalar int32) {
if scalar != 0 {
v.X /= scalar
v.Y /= scalar
v.Z /= scalar
} else {
v.SetZero()
}
}
// Min returns min of this vector components vs. other vector.
func (v Vector3i) Min(other Vector3i) Vector3i {
return Vector3i{min(v.X, other.X), min(v.Y, other.Y), min(v.Z, other.Z)}
}
// SetMin sets this vector components to the minimum values of itself and other vector.
func (v *Vector3i) SetMin(other Vector3i) {
v.X = min(v.X, other.X)
v.Y = min(v.Y, other.Y)
v.Z = min(v.Z, other.Z)
}
// Max returns max of this vector components vs. other vector.
func (v Vector3i) Max(other Vector3i) Vector3i {
return Vector3i{max(v.X, other.X), max(v.Y, other.Y), max(v.Z, other.Z)}
}
// SetMax sets this vector components to the maximum value of itself and other vector.
func (v *Vector3i) SetMax(other Vector3i) {
v.X = max(v.X, other.X)
v.Y = max(v.Y, other.Y)
v.Z = max(v.Z, other.Z)
}
// Clamp sets this vector's components to be no less than the corresponding
// components of min and not greater than the corresponding component of max.
// Assumes min < max; if this assumption isn't true, it will not operate correctly.
func (v *Vector3i) Clamp(min, max Vector3i) {
if v.X < min.X {
v.X = min.X
} else if v.X > max.X {
v.X = max.X
}
if v.Y < min.Y {
v.Y = min.Y
} else if v.Y > max.Y {
v.Y = max.Y
}
if v.Z < min.Z {
v.Z = min.Z
} else if v.Z > max.Z {
v.Z = max.Z
}
}
// Negate returns the vector with each component negated.
func (v Vector3i) Negate() Vector3i {
return Vector3i{-v.X, -v.Y, -v.Z}
}
// Copyright 2019 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Initially copied from G3N: github.com/g3n/engine/math32
// Copyright 2016 The G3N Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// with modifications needed to suit Cogent Core functionality.
package math32
import "fmt"
// Vector4 is a vector/point in homogeneous coordinates with X, Y, Z and W components.
type Vector4 struct {
X float32
Y float32
Z float32
W float32
}
// Vec4 returns a new [Vector4] with the given x, y, z, and w components.
func Vec4(x, y, z, w float32) Vector4 {
return Vector4{X: x, Y: y, Z: z, W: w}
}
// Vector4Scalar returns a new [Vector4] with all components set to the given scalar value.
func Vector4Scalar(scalar float32) Vector4 {
return Vector4{X: scalar, Y: scalar, Z: scalar, W: scalar}
}
// Vector4FromVector3 returns a new [Vector4] from the given [Vector3] and w component.
func Vector4FromVector3(v Vector3, w float32) Vector4 {
nv := Vector4{}
nv.SetFromVector3(v, w)
return nv
}
// Set sets this vector X, Y, Z and W components.
func (v *Vector4) Set(x, y, z, w float32) {
v.X = x
v.Y = y
v.Z = z
v.W = w
}
// SetScalar sets all vector components to the same scalar value.
func (v *Vector4) SetScalar(scalar float32) {
v.X = scalar
v.Y = scalar
v.Z = scalar
v.W = scalar
}
// SetFromVector3 sets this vector from a Vector3 and W
func (v *Vector4) SetFromVector3(other Vector3, w float32) {
v.X = other.X
v.Y = other.Y
v.Z = other.Z
v.W = w
}
// SetFromVector2 sets this vector from a Vector2 with 0,1 for Z,W
func (v *Vector4) SetFromVector2(other Vector2) {
v.X = other.X
v.Y = other.Y
v.Z = 0
v.W = 1
}
// SetDim sets this vector component value by dimension index.
func (v *Vector4) SetDim(dim Dims, value float32) {
switch dim {
case X:
v.X = value
case Y:
v.Y = value
case Z:
v.Z = value
case W:
v.W = value
default:
panic("dim is out of range")
}
}
// Dim returns this vector component.
func (v Vector4) Dim(dim Dims) float32 {
switch dim {
case X:
return v.X
case Y:
return v.Y
case Z:
return v.Z
case W:
return v.W
default:
panic("dim is out of range")
}
}
func (v Vector4) String() string {
return fmt.Sprintf("(%v, %v, %v, %v)", v.X, v.Y, v.Z, v.W)
}
// SetZero sets all of the vector's components to zero,
// except for the W component, which it sets to 1, as is standard.
func (v *Vector4) SetZero() {
v.X = 0
v.Y = 0
v.Z = 0
v.W = 1
}
// FromSlice sets this vector's components from the given slice, starting at offset.
func (v *Vector4) FromSlice(array []float32, offset int) {
v.X = array[offset]
v.Y = array[offset+1]
v.Z = array[offset+2]
v.W = array[offset+3]
}
// ToSlice copies this vector's components to the given slice, starting at offset.
func (v Vector4) ToSlice(array []float32, offset int) {
array[offset] = v.X
array[offset+1] = v.Y
array[offset+2] = v.Z
array[offset+3] = v.W
}
// Basic math operations:
// Add adds the other given vector to this one and returns the result as a new vector.
func (v Vector4) Add(other Vector4) Vector4 {
return Vector4{v.X + other.X, v.Y + other.Y, v.Z + other.Z, v.W + other.W}
}
// AddScalar adds scalar s to each component of this vector and returns new vector.
func (v Vector4) AddScalar(s float32) Vector4 {
return Vector4{v.X + s, v.Y + s, v.Z + s, v.W + s}
}
// SetAdd sets this to addition with other vector (i.e., += or plus-equals).
func (v *Vector4) SetAdd(other Vector4) {
v.X += other.X
v.Y += other.Y
v.Z += other.Z
v.W += other.W
}
// SetAddScalar sets this to addition with scalar.
func (v *Vector4) SetAddScalar(s float32) {
v.X += s
v.Y += s
v.Z += s
v.W += s
}
// Sub subtracts other vector from this one and returns result in new vector.
func (v Vector4) Sub(other Vector4) Vector4 {
return Vector4{v.X - other.X, v.Y - other.Y, v.Z - other.Z, v.W - other.W}
}
// SubScalar subtracts scalar s from each component of this vector and returns new vector.
func (v Vector4) SubScalar(s float32) Vector4 {
return Vector4{v.X - s, v.Y - s, v.Z - s, v.W - s}
}
// SetSub sets this to subtraction with other vector (i.e., -= or minus-equals).
func (v *Vector4) SetSub(other Vector4) {
v.X -= other.X
v.Y -= other.Y
v.Z -= other.Z
v.W -= other.W
}
// SetSubScalar sets this to subtraction of scalar.
func (v *Vector4) SetSubScalar(s float32) {
v.X -= s
v.Y -= s
v.Z -= s
v.W -= s
}
// Mul multiplies each component of this vector by the corresponding one from other
// and returns resulting vector.
func (v Vector4) Mul(other Vector4) Vector4 {
return Vector4{v.X * other.X, v.Y * other.Y, v.Z * other.Z, v.W * other.W}
}
// MulScalar multiplies each component of this vector by the scalar s and returns resulting vector.
func (v Vector4) MulScalar(s float32) Vector4 {
return Vector4{v.X * s, v.Y * s, v.Z * s, v.W * s}
}
// SetMul sets this to multiplication with other vector (i.e., *= or times-equals).
func (v *Vector4) SetMul(other Vector4) {
v.X *= other.X
v.Y *= other.Y
v.Z *= other.Z
v.W *= other.W
}
// SetMulScalar sets this to multiplication by scalar.
func (v *Vector4) SetMulScalar(s float32) {
v.X *= s
v.Y *= s
v.Z *= s
v.W *= s
}
// Div divides each component of this vector by the corresponding one from other vector
// and returns resulting vector.
func (v Vector4) Div(other Vector4) Vector4 {
return Vector4{v.X / other.X, v.Y / other.Y, v.Z / other.Z, v.W / other.W}
}
// DivScalar divides each component of this vector by the scalar s and returns resulting vector.
// If scalar is zero, returns zero.
func (v Vector4) DivScalar(scalar float32) Vector4 {
if scalar != 0 {
return v.MulScalar(1 / scalar)
}
return Vector4{}
}
// SetDiv sets this to division by other vector (i.e., /= or divide-equals).
func (v *Vector4) SetDiv(other Vector4) {
v.X /= other.X
v.Y /= other.Y
v.Z /= other.Z
v.W /= other.W
}
// SetDivScalar sets this to division by scalar.
func (v *Vector4) SetDivScalar(s float32) {
if s != 0 {
v.SetMulScalar(1 / s)
} else {
v.SetZero()
}
}
// Min returns min of this vector components vs. other vector.
func (v Vector4) Min(other Vector4) Vector4 {
return Vector4{Min(v.X, other.X), Min(v.Y, other.Y), Min(v.Z, other.Z), Min(v.W, other.W)}
}
// SetMin sets this vector components to the minimum values of itself and other vector.
func (v *Vector4) SetMin(other Vector4) {
v.X = Min(v.X, other.X)
v.Y = Min(v.Y, other.Y)
v.Z = Min(v.Z, other.Z)
v.W = Min(v.W, other.W)
}
// Max returns max of this vector components vs. other vector.
func (v Vector4) Max(other Vector4) Vector4 {
return Vector4{Max(v.X, other.X), Max(v.Y, other.Y), Max(v.Z, other.Z), Max(v.W, other.W)}
}
// SetMax sets this vector components to the maximum value of itself and other vector.
func (v *Vector4) SetMax(other Vector4) {
v.X = Max(v.X, other.X)
v.Y = Max(v.Y, other.Y)
v.Z = Max(v.Z, other.Z)
v.W = Max(v.W, other.W)
}
// Clamp sets this vector's components to be no less than the corresponding
// components of min and not greater than the corresponding component of max.
// Assumes min < max; if this assumption isn't true, it will not operate correctly.
func (v *Vector4) Clamp(min, max Vector4) {
if v.X < min.X {
v.X = min.X
} else if v.X > max.X {
v.X = max.X
}
if v.Y < min.Y {
v.Y = min.Y
} else if v.Y > max.Y {
v.Y = max.Y
}
if v.Z < min.Z {
v.Z = min.Z
} else if v.Z > max.Z {
v.Z = max.Z
}
if v.W < min.W {
v.W = min.W
} else if v.W > max.W {
v.W = max.W
}
}
// Floor returns this vector with [Floor] applied to each of its components.
func (v Vector4) Floor() Vector4 {
return Vector4{Floor(v.X), Floor(v.Y), Floor(v.Z), Floor(v.W)}
}
// Ceil returns this vector with [Ceil] applied to each of its components.
func (v Vector4) Ceil() Vector4 {
return Vector4{Ceil(v.X), Ceil(v.Y), Ceil(v.Z), Ceil(v.W)}
}
// Round returns this vector with [Round] applied to each of its components.
func (v Vector4) Round() Vector4 {
return Vector4{Round(v.X), Round(v.Y), Round(v.Z), Round(v.W)}
}
// Negate returns the vector with each component negated.
func (v Vector4) Negate() Vector4 {
return Vector4{-v.X, -v.Y, -v.Z, -v.W}
}
// Distance, Normal:
// Dot returns the dot product of this vector with the given other vector.
func (v Vector4) Dot(other Vector4) float32 {
return v.X*other.X + v.Y*other.Y + v.Z*other.Z + v.W*other.W
}
// Length returns the length (magnitude) of this vector.
func (v Vector4) Length() float32 {
return Sqrt(v.X*v.X + v.Y*v.Y + v.Z*v.Z + v.W*v.W)
}
// LengthSquared returns the length squared of this vector.
// LengthSquared can be used to compare the lengths of vectors
// without the need to perform a square root.
func (v Vector4) LengthSquared() float32 {
return v.X*v.X + v.Y*v.Y + v.Z*v.Z + v.W*v.W
}
// Normal returns this vector divided by its length (its unit vector).
func (v Vector4) Normal() Vector4 {
return v.DivScalar(v.Length())
}
// SetNormal normalizes this vector so its length will be 1.
func (v *Vector4) SetNormal() {
v.SetDivScalar(v.Length())
}
// Lerp returns vector with each components as the linear interpolated value of
// alpha between itself and the corresponding other component.
func (v Vector4) Lerp(other Vector4, alpha float32) Vector4 {
return Vector4{v.X + (other.X-v.X)*alpha, v.Y + (other.Y-v.Y)*alpha, v.Z + (other.Z-v.Z)*alpha,
v.W + (other.W-v.W)*alpha}
}
// Matrix operations:
// MulMatrix4 returns vector multiplied by specified 4x4 matrix.
func (v Vector4) MulMatrix4(m *Matrix4) Vector4 {
return Vector4{m[0]*v.X + m[4]*v.Y + m[8]*v.Z + m[12]*v.W,
m[1]*v.X + m[5]*v.Y + m[9]*v.Z + m[13]*v.W,
m[2]*v.X + m[6]*v.Y + m[10]*v.Z + m[14]*v.W,
m[3]*v.X + m[7]*v.Y + m[11]*v.Z + m[15]*v.W}
}
// SetAxisAngleFromQuat set this vector to be the axis (x, y, z) and angle (w)
// of a rotation specified the quaternion q.
// Assumes q is normalized.
func (v *Vector4) SetAxisAngleFromQuat(q Quat) {
// http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
qw := Clamp(q.W, -1, 1)
v.W = 2 * Acos(qw)
s := Sqrt(1 - qw*qw)
if s < 0.0001 {
v.X = 1
v.Y = 0
v.Z = 0
} else {
v.X = q.X / s
v.Y = q.Y / s
v.Z = q.Z / s
}
}
// PerspDiv returns the 3-vector of normalized display coordinates (NDC) from given 4-vector
// By dividing by the 4th W component
func (v Vector4) PerspDiv() Vector3 {
return Vec3(v.X/v.W, v.Y/v.W, v.Z/v.W)
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package basesymbols
import (
"reflect"
"strings"
"github.com/cogentcore/mvm/goparser"
"github.com/cogentcore/mvm/interp"
"github.com/cogentcore/mvm/stdlib"
"github.com/cogentcore/mvm/symbol"
)
// Import imports the symbols of the given packages, as [Values], into the
// given interpreter, and makes all of its packages usable without an import,
// by their names. Packages outside of the standard library take the names
// that they share with standard library packages, as cogentcore.org/core/base/errors
// does that of errors, whose functions it also has. It also gives the
// interpreter the source of the standard library packages that it
// interprets, if mvm does not have it embedded (see [StdSource]).
func Import(in *interp.Interp, values ...map[string]map[string]reflect.Value) {
if stdlib.EmbeddedStd() == nil {
in.SetStdlibFS(StdSource())
}
for _, v := range values {
in.ImportPackageValues(v)
}
in.AutoImportPackages()
for path := range in.Packages {
if first, _, _ := strings.Cut(path, "/"); !strings.Contains(first, ".") {
continue
}
name := goparser.PackageName(path)
in.SymSet(name, &symbol.Symbol{Kind: symbol.Pkg, PkgPath: path, Index: symbol.UnsetAddr, Name: name, AutoImport: true})
}
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package basesymbols
import (
"archive/zip"
"bytes"
_ "embed"
"io/fs"
)
//go:generate go run genstdsrc.go
// stdsrcZip has the sources of the generic standard library packages, such
// as slices, which interpreted code imports from source, since they cannot
// be bound as values (see genstdsrc.go).
//
//go:embed stdsrc.zip
var stdsrcZip []byte
// StdSource returns the file system of the sources of [stdsrcZip], by
// package import path, which an interpreter without the standard library
// sources of mvm (which the mvmnosrc build tag leaves out to keep apps
// small) is given with SetStdlibFS.
func StdSource() fs.FS {
r, err := zip.NewReader(bytes.NewReader(stdsrcZip), int64(len(stdsrcZip)))
if err != nil {
panic(err)
}
return r
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package basesymbols has the mvm symbols of the packages that do not use
// the GUI, which interpreted code can use: the Cogent Core base packages,
// and the standard library packages that the mvm stdlib/core package does
// not have. It does not import the GUI, so that interpreters without it,
// such as that of Goal, can use it (see coresymbols for the GUI packages).
package basesymbols
//go:generate ./make
import (
"maps"
"reflect"
"sync"
)
// Values are the symbols of the packages, by import path and name, in the
// form that mvm's ImportPackageValues takes. They are added by [Load], which
// is called at init time except on the web (see [Load]).
var Values = map[string]map[string]reflect.Value{}
var (
// loaders are the functions that add the symbols of each package
// to [Values], which are registered at init time.
loaders []func()
// loadOnce makes [Load] add the symbols once.
loadOnce sync.Once
)
// register adds the given function that adds symbols to [Values]
// to the functions that [Load] calls.
func register(loader func()) bool {
loaders = append(loaders, loader)
return true
}
// add adds the symbols of the given packages to [Values].
func add(pkgs map[string]map[string]reflect.Value) {
maps.Copy(Values, pkgs)
}
// Load adds the symbols of all packages to [Values], once. Natively, it is
// called at init time. On the web, making the symbols at init time is a
// noticeable part of the startup time of an app, so it is instead called
// by mvmcore when it first makes an interpreter; other code using [Values]
// on the web must call it first.
func Load() {
loadOnce.Do(func() {
for _, loader := range loaders {
loader()
}
loaders = nil
})
}
func init() {
if !lazyLoad {
Load()
}
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package coresymbols
import (
"reflect"
"cogentcore.org/core/icons"
)
// iconsList is a subset of icons to include in the symbols.
// It is based on the icons used in the core docs.
var iconsList = map[string]icons.Icon{"Download": icons.Download, "Share": icons.Share, "Send": icons.Send, "Computer": icons.Computer, "Smartphone": icons.Smartphone, "Sort": icons.Sort, "Home": icons.Home, "HomeFill": icons.HomeFill, "DeployedCodeFill": icons.DeployedCodeFill, "Close": icons.Close, "Explore": icons.Explore, "History": icons.History, "Euro": icons.Euro, "OpenInNew": icons.OpenInNew, "Add": icons.Add}
var _ = register(func() {
m := map[string]reflect.Value{}
for name, icon := range iconsList {
m[name] = reflect.ValueOf(icon)
}
add(map[string]map[string]reflect.Value{"cogentcore.org/core/icons": m})
})
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package coresymbols has the mvm symbols of the GUI packages that
// interpreted code in Cogent Core apps can use, such as the code of the
// docs (see basesymbols for the packages that do not use the GUI).
package coresymbols
//go:generate ./make
import (
"maps"
"reflect"
"sync"
)
// Values are the symbols of the packages, by import path and name, in the
// form that mvm's ImportPackageValues takes. They are added by [Load], which
// is called at init time except on the web (see [Load]).
var Values = map[string]map[string]reflect.Value{}
var (
// loaders are the functions that add the symbols of each package
// to [Values], which are registered at init time.
loaders []func()
// loadOnce makes [Load] add the symbols once.
loadOnce sync.Once
)
// register adds the given function that adds symbols to [Values]
// to the functions that [Load] calls.
func register(loader func()) bool {
loaders = append(loaders, loader)
return true
}
// add adds the symbols of the given packages to [Values].
func add(pkgs map[string]map[string]reflect.Value) {
maps.Copy(Values, pkgs)
}
// Load adds the symbols of all packages to [Values], once. Natively, it is
// called at init time. On the web, making the symbols at init time is a
// noticeable part of the startup time of an app, so it is instead called
// by mvmcore when it first makes an interpreter; other code using [Values]
// on the web must call it first.
func Load() {
loadOnce.Do(func() {
for _, loader := range loaders {
loader()
}
loaders = nil
})
}
func init() {
if !lazyLoad {
Load()
}
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package mvmcore provides functions connecting the mvm Go interpreter
// (https://github.com/cogentcore/mvm, a fork of github.com/mvm-sh/mvm) to
// Cogent Core, such that content code blocks can be edited and run.
package mvmcore
import (
"bytes"
"fmt"
"io"
"reflect"
"strings"
"sync/atomic"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/content"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/mvmcore/basesymbols"
"cogentcore.org/core/mvmcore/coresymbols"
"cogentcore.org/core/text/textcore"
"github.com/cogentcore/mvm/interp"
"github.com/cogentcore/mvm/lang/golang"
"github.com/cogentcore/mvm/stdlib"
_ "github.com/cogentcore/mvm/stdlib/core" // the core standard library
)
// Interpreters is a map from language names (such as "Go") to functions that
// make a new [Interpreter] for that language, writing its output to out. The
// base implementation is an mvm interpreter for Go (see [NewGo]), but other
// packages can add other languages, as cogentcore.org/lab/mvmlab does Goal.
var Interpreters = map[string]func(out io.Writer) (Interpreter, error){
"Go": func(out io.Writer) (Interpreter, error) { return NewGo(out) },
}
// Interpreter is an interpreter of a language, which runs code.
type Interpreter interface {
// Eval runs the given code.
Eval(src string) (reflect.Value, error)
}
// DotPackage is the import path of the package of the names that code can
// use without a package: b, the parent widget of the code, and the names of
// [content.CodeSymbols]. Its symbols are [DotValues].
const DotPackage = "cogentcore.org/core/mvmcore/dot"
var (
autoPlanNameCounter atomic.Uint64
// interpreterParent is the parent widget of the code, b, which is
// updated before the code runs.
interpreterParent = new(*core.Frame)
// interpOutput is the output of the code. It is global because the
// Goal interpreter of a page is used for all of its code blocks.
interpOutput bytes.Buffer
// currentGoal is the Goal interpreter of the current page, which runs
// all of its Goal code blocks, so that they share their variables.
currentGoal Interpreter
// BeforeEval, if set, is called before the code of a text editor bound
// by [BindTextEditor] runs, with its parent widget, so that an app can
// set up the context of the code, as a notebook does for its output.
// It returns a function that is called after the code runs, or nil.
BeforeEval func(parent *core.Frame) (after func())
)
func init() {
content.BindTextEditor = BindTextEditor
content.NewPageInitFunc = ResetGoalInterpreter
}
// Load adds the symbols of [basesymbols] and [coresymbols] to their Values,
// once, with tree.AutoPlanName replaced by one that works for interpreted
// code (see [autoPlanName]). It must be called before importing them.
func Load() {
basesymbols.Load()
coresymbols.Load()
coresymbols.Values["cogentcore.org/core/tree"]["AutoPlanName"] = reflect.ValueOf(autoPlanName)
}
// Go is an mvm interpreter of Go code.
type Go struct {
*interp.Interp
}
// NewGo returns a new interpreter of Go code, writing its output to out,
// with the symbols of [basesymbols.Values], [coresymbols.Values], the mvm
// core standard library and [DotPackage] imported, and with all of these
// packages usable without an import.
func NewGo(out io.Writer) (*Go, error) {
Load()
in := interp.NewInterpreter(golang.GoSpec)
in.SetIO(strings.NewReader(""), out, out)
basesymbols.Import(in, stdlib.Values, basesymbols.Values, coresymbols.Values, map[string]map[string]reflect.Value{DotPackage: DotValues()})
return &Go{in}, nil
}
// DotValues returns the values of the names of [DotPackage].
func DotValues() map[string]reflect.Value {
values := map[string]reflect.Value{
"b": reflect.ValueOf(interpreterParent),
}
// Each is bound as a variable holding the value, a pointer to it, as mvm
// binds package variables: a pointer value bound as itself would be
// taken for a variable of its element type.
for name, v := range content.CodeSymbols {
rv := reflect.New(reflect.TypeOf(v))
rv.Elem().Set(reflect.ValueOf(v))
values[name] = rv
}
return values
}
// Eval runs the given Go code. Code without a main function is run in one,
// so that it can be a list of statements, which then also handles type
// declarations correctly; code with a main function, with declarations
// outside of it, runs it. The names of [DotPackage] are imported in the
// same source, as each Eval makes a new main function.
func (g *Go) Eval(src string) (reflect.Value, error) {
lines := 1 // added before the code
if !strings.Contains(src, "func main()") {
src = "func main() {\n" + src + "\n}"
lines++
}
v, err := g.Interp.Eval("code", fmt.Sprintf("import . %q\n", DotPackage)+src)
if err == nil {
return v, nil
}
if d, ok := g.Diagnose(err); ok && d.Source == "code" && d.Line > lines {
return v, &Error{Line: d.Line - lines, Col: d.Col, Msg: d.Msg, Err: err}
}
return v, err
}
// Error is an error of Go code at a position in it, which
// content.ShowCodeErrors shows there.
type Error struct {
// Line and Col are the 1-based line and column (in bytes) of the error.
Line, Col int
// Msg is the message of the error, without its position.
Msg string
// Err is the error of the interpreter.
Err error
}
func (e *Error) Error() string { return fmt.Sprintf("%d:%d: %s", e.Line, e.Col, e.Msg) }
func (e *Error) Unwrap() error { return e.Err }
// CodePos returns the 1-based line and column of the error in the code.
func (e *Error) CodePos() (line, col int) { return e.Line, e.Col }
// CodeMessage returns the message of the error, without its position.
func (e *Error) CodeMessage() string { return e.Msg }
// ResetGoalInterpreter makes the next Goal code block use a new Goal
// interpreter. It is the value of [content.NewPageInitFunc], so that each
// page has its own.
func ResetGoalInterpreter() {
currentGoal = nil
}
// getInterpreter returns the interpreter for the given language: a new one,
// except for Goal, whose interpreter of the current page is used for all of
// its code blocks. new is whether it is a new one.
func getInterpreter(language string) (in Interpreter, new bool, err error) {
if language == "Goal" && currentGoal != nil {
return currentGoal, false, nil
}
f := Interpreters[language]
if f == nil {
return nil, false, fmt.Errorf("no entry in mvmcore.Interpreters for language %q", language)
}
in, err = f(&interpOutput)
if err != nil {
return nil, false, fmt.Errorf("making the %s interpreter: %w", language, err)
}
if language == "Goal" {
currentGoal = in
}
return in, true, nil
}
// replayGoal runs in the new Goal interpreter in the Goal code blocks of the
// page that ran compiled before ([content.GoalReplay]), so that it has the
// variables that they made.
func replayGoal(in Interpreter) {
replay := content.GoalReplay
content.GoalReplay = nil
for _, src := range replay {
interpOutput.Reset()
if _, err := in.Eval(src); err != nil {
errors.Log(fmt.Errorf("mvmcore: running the compiled Goal code of the page again: %w", err))
}
}
interpOutput.Reset()
}
// BindTextEditor binds the given text editor to an mvm interpreter such that
// the contents of the text editor are interpreted as code of the given
// language, which is run in the context of the given parent widget. It is
// the value of [content.BindTextEditor] when this package is imported.
func BindTextEditor(ed *textcore.Editor, parent *core.Frame, language string) {
oc := func() {
in, new, err := getInterpreter(language)
if err != nil {
core.ErrorSnackbar(ed, err)
return
}
SetParent(parent)
// a program that runs a window adds it to parent, but only while it runs
defer func() { core.ExternalParent = nil }()
if BeforeEval != nil {
if after := BeforeEval(parent); after != nil {
defer after()
}
}
if new && language == "Goal" {
replayGoal(in)
}
parent.DeleteChildren()
interpOutput.Reset()
_, err = in.Eval(ed.Lines.String())
if ostr := interpOutput.String(); len(ostr) > 0 {
out := textcore.NewEditor(parent)
out.SetReadOnly(true)
out.Lines.Settings.LineNumbers = false
out.Lines.SetString(ostr)
}
content.ShowCodeErrors(ed, parent, err)
parent.Update()
}
ed.OnChange(func(e events.Event) { oc() })
oc()
}
// SetParent sets the parent widget of the code that runs next, b, in which
// the widgets that it makes are added (see [core.ExternalParent]).
func SetParent(parent *core.Frame) {
core.ExternalParent = parent
*interpreterParent = parent
}
// autoPlanName returns a unique name for each tree.AddChild call of the
// code, replacing tree.AutoPlanName, whose name from the call stack would
// not tell apart the calls of interpreted code.
func autoPlanName(int) string {
return fmt.Sprintf("mvm-%v", autoPlanNameCounter.Add(1))
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package paint
import (
"cogentcore.org/core/math32"
)
// EdgeBlurFactors returns multiplicative factors that replicate the effect
// of a Gaussian kernel applied to a sharp edge transition in the middle of
// a line segment, with a given Gaussian sigma, and radius = sigma * radiusFactor.
// The returned line factors go from -radius to +radius.
// For low-contrast (opacity) cases, radiusFactor = 1 works well,
// because values beyond 1 sigma are effectively invisible, but 2 looks
// better for greater contrast cases.
func EdgeBlurFactors(sigma, radiusFactor float32) []float32 {
radius := math32.Ceil(sigma * radiusFactor)
irad := int(radius)
klen := irad*2 + 1
sfactor := -0.5 / (sigma * sigma)
if klen < 0 {
return []float32{}
}
k := make([]float32, klen)
sum := float32(0)
rstart := -radius + 0.5
for i, x := 0, rstart; i < klen; i, x = i+1, x+1 {
v := math32.FastExp(sfactor * (x * x))
sum += v
k[i] = v
}
for i, v := range k {
k[i] = v / sum
}
line := make([]float32, klen)
for li := range line {
sum := float32(0)
for ki, v := range k {
if ki >= (klen - li) {
break
}
sum += v
}
line[li] = sum
}
return line
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package paint
import (
"image"
"cogentcore.org/core/colors/gradient"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/sides"
)
// StandardBox draws the CSS standard box model using the given styling information,
// position, size, and parent actual background. This is used for rendering
// widgets such as buttons, text fields, etc in a GUI.
func (pc *Painter) StandardBox(st *styles.Style, pos math32.Vector2, size math32.Vector2, pabg image.Image) {
if !st.RenderBox || size == (math32.Vector2{}) {
return
}
encroach, pr := pc.boundsEncroachParent(pos, size)
tm := st.TotalMargin().Round()
mpos := pos.Add(tm.Pos())
msize := size.Sub(tm.Size())
if msize == (math32.Vector2{}) && sides.AreZero(st.Border.Width.Dots().Sides) {
return // a box of no size is still rendered with its borders (as a CSS triangle)
}
radius := st.Border.Radius.Dots()
if encroach { // if we encroach, we must limit ourselves to the parent radius
radius = radius.Max(pr)
}
if st.ActualBackground == nil {
// we need to do this to prevent
// elements from rendering over themselves
// (see https://github.com/cogentcore/core/issues/565)
st.ActualBackground = pabg
}
// note that we always set the fill opacity to 1 because we are already applying
// the opacity of the background color in ComputeActualBackground above
pc.Fill.Opacity = 1
if st.FillMargin {
// We need to fill the whole box where the
// box shadows / element can go to prevent growing
// box shadows and borders. We couldn't just
// do this when there are box shadows, as they
// may be removed and then need to be covered up.
// This also fixes https://github.com/cogentcore/core/issues/579.
// This isn't an ideal solution because of performance,
// so TODO: maybe come up with a better solution for this.
// We need to use raw geom data because we need to clear
// any box shadow that may have gone in margin.
if encroach { // if we encroach, we must limit ourselves to the parent radius
pc.Fill.Color = pabg
pc.RoundedRectangleSides(pos.X, pos.Y, size.X, size.Y, radius)
pc.Draw()
} else {
pc.BlitBox(pos, size, pabg)
}
}
pc.Stroke.Opacity = st.Opacity
// pc.Font.Opacity = st.Opacity // todo:
// first do any shadow
if st.HasBoxShadow() {
// CSS effectively goes in reverse order
for ri := len(st.BoxShadow) - 1; ri >= 0; ri-- {
shadow := st.BoxShadow[ri]
pc.Stroke.Color = nil
// note: applying 0.5 here does a reasonable job of matching
// material design shadows, at their specified alpha levels.
if st.BoxShadowOutside { // CSS shadows have their color
pc.Fill.Color = shadow.Color
} else {
pc.Fill.Color = gradient.ApplyOpacity(shadow.Color, 0.5)
}
spos := shadow.BasePos(mpos)
ssz := shadow.BaseSize(msize)
// note: we are using EdgeBlurFactors with radiusFactor = 1
// (sigma == radius), so we divide Blur / 2 relative to the
// CSS standard of sigma = blur / 2 (i.e., our sigma = blur,
// so we divide Blur / 2 to achieve the same effect).
// This works fine for low-opacity blur factors (the edges are
// so transparent that you can't really see beyond 1 sigma,
// if you used radiusFactor = 2).
// If a higher-contrast shadow is used, it would look better
// with radiusFactor = 2, and you'd have to remove this /2 factor.
pc.RoundedShadowBlur(shadow.Blur.Dots/2, 1, spos.X, spos.Y, ssz.X, ssz.Y, radius)
}
}
// then draw the box over top of that.
// we need to draw things twice here because we need to clear
// the whole area with the background color first so the border
// doesn't render weirdly
if sides.AreZero(radius.Sides) {
pc.FillBox(mpos, msize, st.ActualBackground)
} else {
pc.Fill.Color = st.ActualBackground
// no border; fill on
pc.RoundedRectangleSides(mpos.X, mpos.Y, msize.X, msize.Y, radius)
pc.Draw()
}
// now that we have drawn background color
// above, we can draw the border
if pc.borderSides(mpos, msize, radius, &st.Border) {
return
}
mpos.SetSub(st.Border.Width.Dots().Pos().MulScalar(0.5))
msize.SetAdd(st.Border.Width.Dots().Size().MulScalar(0.5))
mpos.SetSub(st.Border.Offset.Dots().Pos())
msize.SetAdd(st.Border.Offset.Dots().Size())
pc.Fill.Color = nil
pc.Border(mpos.X, mpos.Y, msize.X, msize.Y, st.Border)
}
// boundsEncroachParent returns whether the current box encroaches on the
// parent bounds, taking into account the parent radius, which is also returned.
func (pc *Painter) boundsEncroachParent(pos, size math32.Vector2) (bool, sides.Floats) {
if len(pc.Stack) <= 1 {
return false, sides.Floats{}
}
ctx := pc.Stack[len(pc.Stack)-2]
pr := ctx.Bounds.Radius
if sides.AreZero(pr.Sides) {
return false, pr
}
pbox := ctx.Bounds.Rect.ToRect()
psz := ctx.Bounds.Rect.Size()
pr = ClampBorderRadius(pr, psz.X, psz.Y)
rect := math32.Box2{Min: pos, Max: pos.Add(size)}
// logic is currently based on consistent radius for all corners
radius := max(pr.Top, pr.Left, pr.Right, pr.Bottom)
// each of these is how much the element is encroaching into each
// side of the bounding rectangle, within the radius curve.
// if the number is negative, then it isn't encroaching at all and can
// be ignored.
top := radius - (rect.Min.Y - float32(pbox.Min.Y))
left := radius - (rect.Min.X - float32(pbox.Min.X))
right := radius - (float32(pbox.Max.X) - rect.Max.X)
bottom := radius - (float32(pbox.Max.Y) - rect.Max.Y)
return top > 0 || left > 0 || right > 0 || bottom > 0, pr
}
// borderSides draws the sides of the given border around the given inner
// (padding) box, if they differ in color or width and the box has square
// corners and solid borders, and returns whether it did: as in CSS, each
// side is filled between the outer and inner edges of the border, with
// mitered corners, which makes triangles of the borders of a box of no
// size with transparent sides (as the arrows of selects in CSS).
func (pc *Painter) borderSides(pos, size math32.Vector2, radius sides.Floats, bs *styles.Border) bool {
w := bs.Width.Dots()
if !sides.AreZero(radius.Sides) || !sides.AreZero(bs.Offset.Dots().Sides) {
return false
}
if sides.AreSame(bs.Color) && sides.AreSame(w.Sides) {
return false
}
for _, st := range []styles.BorderStyles{bs.Style.Top, bs.Style.Right, bs.Style.Bottom, bs.Style.Left} {
if st != styles.BorderSolid && st != styles.BorderNone {
return false
}
}
ix0, iy0 := pos.X, pos.Y
ix1, iy1 := pos.X+size.X, pos.Y+size.Y
ox0, oy0 := ix0-w.Left, iy0-w.Top
ox1, oy1 := ix1+w.Right, iy1+w.Bottom
side := func(width float32, st styles.BorderStyles, clr image.Image, pts ...float32) {
if width <= 0 || st == styles.BorderNone || clr == nil {
return
}
pc.MoveTo(pts[0], pts[1])
for i := 2; i < len(pts); i += 2 {
pc.LineTo(pts[i], pts[i+1])
}
pc.Close()
pc.Stroke.Color = nil
pc.Fill.Color = clr
pc.Draw()
}
side(w.Top, bs.Style.Top, bs.Color.Top, ox0, oy0, ox1, oy0, ix1, iy0, ix0, iy0)
side(w.Right, bs.Style.Right, bs.Color.Right, ox1, oy0, ox1, oy1, ix1, iy1, ix1, iy0)
side(w.Bottom, bs.Style.Bottom, bs.Color.Bottom, ox1, oy1, ox0, oy1, ix0, iy1, ix1, iy1)
side(w.Left, bs.Style.Left, bs.Color.Left, ox0, oy1, ox0, oy0, ix0, iy0, ix0, iy1)
pc.Fill.Color = nil
return true
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package paint
import (
"image"
"image/color"
"cogentcore.org/core/colors"
"cogentcore.org/core/colors/gradient"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint/pimage"
"cogentcore.org/core/paint/ppath"
"cogentcore.org/core/paint/render"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/sides"
"cogentcore.org/core/text/shaped"
"golang.org/x/image/draw"
)
/*
The original version borrowed heavily from: https://github.com/fogleman/gg
Copyright (C) 2016 Michael Fogleman
and https://github.com/srwiley/rasterx:
Copyright 2018 by the rasterx Authors. All rights reserved.
Created 2018 by S.R.Wiley
The new version is more strongly based on https://github.com/tdewolff/canvas
Copyright (c) 2015 Taco de Wolff, under an MIT License.
*/
// Painter provides the rendering state, styling parameters, and methods for
// painting. It accumulates all painting actions in a [render.Render]
// list, which should be obtained by a call to the [Painter.RenderDone] method
// when done painting (resets list to start fresh).
//
// Pass this [render.Render] list to one or more [render.Renderers] to actually
// generate the resulting output. Renderers are independent of the Painter
// and the [render.Render] state is entirely self-contained, so rendering
// can be done in a separate goroutine etc.
//
// You must import _ "cogentcore.org/core/paint/renderers" to get the default
// renderers if using this outside of core which already does this for you.
// This sets the New*Renderer functions to point to default implementations.
type Painter struct {
*State
*styles.Paint
}
// NewPainter returns a new [Painter] with default styles and given size.
func NewPainter(size math32.Vector2) *Painter {
pc := &Painter{&State{}, styles.NewPaint()}
pc.Init(pc.Paint, size)
pc.SetUnitContextExt(size.ToPointCeil())
return pc
}
// Cumulative returns the current cumulative transform function,
// including the current transform.
func (pc *Painter) Cumulative() math32.Matrix2 {
return pc.Context().Cumulative.Mul(pc.Transform)
}
//////// Path basics
// MoveTo starts a new subpath within the current path starting at the
// specified point.
func (pc *Painter) MoveTo(x, y float32) {
pc.State.Path.MoveTo(x, y)
}
// LineTo adds a line segment to the current path starting at the current
// point. If there is no current point, it is equivalent to MoveTo(x, y)
func (pc *Painter) LineTo(x, y float32) {
pc.State.Path.LineTo(x, y)
}
// QuadTo adds a quadratic Bézier path with control point (cpx,cpy) and end point (x,y).
func (pc *Painter) QuadTo(cpx, cpy, x, y float32) {
pc.State.Path.QuadTo(cpx, cpy, x, y)
}
// CubeTo adds a cubic Bézier path with control points
// (cpx1,cpy1) and (cpx2,cpy2) and end point (x,y).
func (pc *Painter) CubeTo(cp1x, cp1y, cp2x, cp2y, x, y float32) {
pc.State.Path.CubeTo(cp1x, cp1y, cp2x, cp2y, x, y)
}
// ArcTo adds an arc with radii rx and ry, with rot the counter clockwise
// rotation with respect to the coordinate system in radians, large and sweep booleans
// (see https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths#Arcs),
// and (x,y) the end position of the pen. The start position of the pen was
// given by a previous command's end point.
func (pc *Painter) ArcTo(rx, ry, rot float32, large ppath.ArcSize, sweep ppath.ArcSweep, x, y float32) {
pc.State.Path.ArcTo(rx, ry, rot, large, sweep, x, y)
}
// Close closes a (sub)path with a LineTo to the start of the path
// (the most recent MoveTo command). It also signals the path closes
// as opposed to being just a LineTo command, which can be significant
// for stroking purposes for example.
func (pc *Painter) Close() {
pc.State.Path.Close()
}
// Draw puts the current path on the render stack, capturing the style
// settings present at this point, which will be used to render the path,
// and creates a new current path.
func (pc *Painter) Draw() {
pc.ToDots()
pt := render.NewPath(pc.State.Path.Clone(), pc.Paint, pc.Context())
pc.Render.Add(pt)
pc.State.Path.Reset()
}
//////// basic shape functions
// note: the path shapes versions can be used when you want to add to an existing path
// using ppath.Join. These functions produce distinct standalone shapes, starting with
// a MoveTo generally.
// Line adds a separate line (MoveTo, LineTo).
func (pc *Painter) Line(x1, y1, x2, y2 float32) {
pc.State.Path.Line(x1, y1, x2, y2)
}
// Polyline adds multiple connected lines, with no final Close.
func (pc *Painter) Polyline(points ...math32.Vector2) {
pc.State.Path.Polyline(points...)
}
// PolylinePx adds multiple connected lines, with no final Close,
// with coordinates in Px units.
func (pc *Painter) PolylinePx(points ...math32.Vector2) {
pu := &pc.UnitContext
sz := len(points)
if sz < 2 {
return
}
p := &pc.State.Path
p.MoveTo(pu.PxToDots(points[0].X), pu.PxToDots(points[0].Y))
for i := 1; i < sz; i++ {
p.LineTo(pu.PxToDots(points[i].X), pu.PxToDots(points[i].Y))
}
}
// Polygon adds multiple connected lines with a final Close.
func (pc *Painter) Polygon(points ...math32.Vector2) {
pc.Polyline(points...)
pc.Close()
}
// PolygonPx adds multiple connected lines with a final Close,
// with coordinates in Px units.
func (pc *Painter) PolygonPx(points ...math32.Vector2) {
pc.PolylinePx(points...)
pc.Close()
}
// Rectangle adds a rectangle of width w and height h at position x,y.
func (pc *Painter) Rectangle(x, y, w, h float32) {
pc.State.Path.Rectangle(x, y, w, h)
}
// RoundedRectangle adds a rectangle of width w and height h
// with rounded corners of radius r at postion x,y.
// A negative radius will cast the corners inwards (i.e. concave).
func (pc *Painter) RoundedRectangle(x, y, w, h, r float32) {
pc.State.Path.RoundedRectangle(x, y, w, h, r)
}
// RoundedRectangleSides adds a standard rounded rectangle
// with a consistent border and with the given x and y position,
// width and height, and border radius for each corner.
func (pc *Painter) RoundedRectangleSides(x, y, w, h float32, r sides.Floats) {
pc.State.Path.RoundedRectangleSides(x, y, w, h, r)
}
// BeveledRectangle adds a rectangle of width w and height h
// with beveled corners at distance r from the corner.
func (pc *Painter) BeveledRectangle(x, y, w, h, r float32) {
pc.State.Path.BeveledRectangle(x, y, w, h, r)
}
// Circle adds a circle at given center coordinates of radius r.
func (pc *Painter) Circle(cx, cy, r float32) {
pc.Ellipse(cx, cy, r, r)
}
// Ellipse adds an ellipse at given center coordinates of radii rx and ry.
func (pc *Painter) Ellipse(cx, cy, rx, ry float32) {
pc.State.Path.Ellipse(cx, cy, rx, ry)
}
// CircularArc adds a circular arc centered at given coordinates with radius r
// and theta0 and theta1 as the angles in degrees of the ellipse
// (before rot is applied) between which the arc will run.
// If theta0 < theta1, the arc will run in a CCW direction.
// If the difference between theta0 and theta1 is bigger than 360 degrees,
// one full circle will be drawn and the remaining part of diff % 360,
// e.g. a difference of 810 degrees will draw one full circle and an arc
// over 90 degrees.
func (pc *Painter) CircularArc(x, y, r, theta0, theta1 float32) {
pc.State.Path.EllipticalArc(x, y, r, r, 0, theta0, theta1)
}
// EllipticalArc adds an elliptical arc centered at given coordinates with
// radii rx and ry, with rot the counter clockwise rotation in degrees,
// and theta0 and theta1 the angles in degrees of the ellipse
// (before rot is applied) between which the arc will run.
// If theta0 < theta1, the arc will run in a CCW direction.
// If the difference between theta0 and theta1 is bigger than 360 degrees,
// one full circle will be drawn and the remaining part of diff % 360,
// e.g. a difference of 810 degrees will draw one full circle and an arc
// over 90 degrees.
func (pc *Painter) EllipticalArc(x, y, rx, ry, rot, theta0, theta1 float32) {
pc.State.Path.EllipticalArc(x, y, rx, ry, rot, theta0, theta1)
}
// Triangle adds a triangle of radius r pointing upwards.
func (pc *Painter) Triangle(x, y, r float32) {
pc.State.Path.RegularPolygon(3, r, true).Translate(x, y) // todo: just make these take a position.
}
// RegularPolygon adds a regular polygon with radius r.
// It uses n vertices/edges, so when n approaches infinity
// this will return a path that approximates a circle.
// n must be 3 or more. The up boolean defines whether
// the first point will point upwards or downwards.
func (pc *Painter) RegularPolygon(x, y float32, n int, r float32, up bool) {
pc.State.Path.RegularPolygon(n, r, up).Translate(x, y)
}
// RegularStarPolygon adds a regular star polygon with radius r.
// It uses n vertices of density d. This will result in a
// self-intersection star in counter clockwise direction.
// If n/2 < d the star will be clockwise and if n and d are not coprime
// a regular polygon will be obtained, possible with multiple windings.
// n must be 3 or more and d 2 or more. The up boolean defines whether
// the first point will point upwards or downwards.
func (pc *Painter) RegularStarPolygon(x, y float32, n, d int, r float32, up bool) {
pc.State.Path.RegularStarPolygon(n, d, r, up).Translate(x, y)
}
// StarPolygon returns a star polygon of n points with alternating
// radius R and r. The up boolean defines whether the first point
// will be point upwards or downwards.
func (pc *Painter) StarPolygon(x, y float32, n int, R, r float32, up bool) {
pc.State.Path.StarPolygon(n, R, r, up).Translate(x, y)
}
// Grid returns a stroked grid of width w and height h,
// with grid line thickness r, and the number of cells horizontally
// and vertically as nx and ny respectively.
func (pc *Painter) Grid(x, y, w, h float32, nx, ny int, r float32) {
pc.State.Path.Grid(w, y, nx, ny, r).Translate(x, y)
}
// ClampBorderRadius returns the given border radius clamped to fit based
// on the given width and height of the object.
func ClampBorderRadius(r sides.Floats, w, h float32) sides.Floats {
min := math32.Min(w/2, h/2)
r.Top = math32.Clamp(r.Top, 0, min)
r.Right = math32.Clamp(r.Right, 0, min)
r.Bottom = math32.Clamp(r.Bottom, 0, min)
r.Left = math32.Clamp(r.Left, 0, min)
return r
}
// Border is a higher-level function that draws, strokes, and fills
// an potentially rounded border box with the given position, size, and border styles.
func (pc *Painter) Border(x, y, w, h float32, bs styles.Border) {
origStroke := pc.Stroke
origFill := pc.Fill
defer func() {
pc.Stroke = origStroke
pc.Fill = origFill
}()
r := bs.Radius.Dots()
if sides.AreSame(bs.Style) && sides.AreSame(bs.Color) && sides.AreSame(bs.Width.Dots().Sides) {
// set the color if it is not nil and the stroke style
// is not set to the correct color
if bs.Color.Top != nil && bs.Color.Top != pc.Stroke.Color {
pc.Stroke.Color = bs.Color.Top
}
pc.Stroke.Width = bs.Width.Top
pc.Stroke.ApplyBorderStyle(bs.Style.Top)
if sides.AreZero(r.Sides) {
pc.Rectangle(x, y, w, h)
} else {
pc.RoundedRectangleSides(x, y, w, h, r)
}
pc.Draw()
return
}
// use consistent rounded rectangle for fill, and then draw borders side by side
pc.RoundedRectangleSides(x, y, w, h, r)
pc.Draw()
r = ClampBorderRadius(r, w, h)
// position values
var (
xtl, ytl = x, y // top left
xtli, ytli = x + r.Top, y + r.Top // top left inset
xtr, ytr = x + w, y // top right
xtri, ytri = x + w - r.Right, y + r.Right // top right inset
xbr, ybr = x + w, y + h // bottom right
xbri, ybri = x + w - r.Bottom, y + h - r.Bottom // bottom right inset
xbl, ybl = x, y + h // bottom left
xbli, ybli = x + r.Left, y + h - r.Left // bottom left inset
)
// SidesTODO: need to figure out how to style rounded corners correctly
// (in CSS they are split in the middle between different border side styles)
pc.MoveTo(xtli, ytl)
// set the color if it is not the same as the already set color
if bs.Color.Top != pc.Stroke.Color {
pc.Stroke.Color = bs.Color.Top
}
pc.Stroke.Width = bs.Width.Top
pc.LineTo(xtri, ytr)
if r.Right != 0 {
pc.CircularArc(xtri, ytri, r.Right, math32.DegToRad(270), math32.DegToRad(360))
}
// if the color or width is changing for the next one, we have to stroke now
if bs.Color.Top != bs.Color.Right || bs.Width.Top.Dots != bs.Width.Right.Dots {
pc.Draw()
pc.MoveTo(xtr, ytri)
}
if bs.Color.Right != pc.Stroke.Color {
pc.Stroke.Color = bs.Color.Right
}
pc.Stroke.Width = bs.Width.Right
pc.LineTo(xbr, ybri)
if r.Bottom != 0 {
pc.CircularArc(xbri, ybri, r.Bottom, math32.DegToRad(0), math32.DegToRad(90))
}
if bs.Color.Right != bs.Color.Bottom || bs.Width.Right.Dots != bs.Width.Bottom.Dots {
pc.Draw()
pc.MoveTo(xbri, ybr)
}
if bs.Color.Bottom != pc.Stroke.Color {
pc.Stroke.Color = bs.Color.Bottom
}
pc.Stroke.Width = bs.Width.Bottom
pc.LineTo(xbli, ybl)
if r.Left != 0 {
pc.CircularArc(xbli, ybli, r.Left, math32.DegToRad(90), math32.DegToRad(180))
}
if bs.Color.Bottom != bs.Color.Left || bs.Width.Bottom.Dots != bs.Width.Left.Dots {
pc.Draw()
pc.MoveTo(xbl, ybli)
}
if bs.Color.Left != pc.Stroke.Color {
pc.Stroke.Color = bs.Color.Left
}
pc.Stroke.Width = bs.Width.Left
pc.LineTo(xtl, ytli)
if r.Top != 0 {
pc.CircularArc(xtli, ytli, r.Top, math32.DegToRad(180), math32.DegToRad(270))
}
pc.LineTo(xtli, ytl)
pc.Draw()
}
// RoundedShadowBlur draws a standard rounded rectangle
// with a consistent border and with the given x and y position,
// width and height, and border radius for each corner.
// The blurSigma and radiusFactor args add a blurred shadow with
// an effective Gaussian sigma = blurSigma, and radius = radiusFactor * sigma.
// This shadow is rendered around the given box size up to given radius.
// See EdgeBlurFactors for underlying blur factor code.
// Using radiusFactor = 1 works well for weak shadows, where the fringe beyond
// 1 sigma is essentially invisible. To match the CSS standard, you then
// pass blurSigma = blur / 2, radiusFactor = 1. For darker shadows,
// use blurSigma = blur / 2, radiusFactor = 2, and reserve extra space for the full shadow.
// The effective blurRadius is clamped to be <= w-2 and h-2.
func (pc *Painter) RoundedShadowBlur(blurSigma, radiusFactor, x, y, w, h float32, r sides.Floats) {
if blurSigma <= 0 || radiusFactor <= 0 {
pc.RoundedRectangleSides(x, y, w, h, r)
pc.Draw()
return
}
x = math32.Floor(x)
y = math32.Floor(y)
w = math32.Ceil(w)
h = math32.Ceil(h)
br := math32.Ceil(radiusFactor * blurSigma)
br = math32.Clamp(br, 1, w/2-2)
br = math32.Clamp(br, 1, h/2-2)
// radiusFactor = math32.Ceil(br / blurSigma)
radiusFactor = br / blurSigma
blurs := EdgeBlurFactors(blurSigma, radiusFactor)
origStroke := pc.Stroke
origFill := pc.Fill
origOpacity := pc.Fill.Opacity
pc.Stroke.Color = nil
pc.RoundedRectangleSides(x+br, y+br, w-2*br, h-2*br, r)
pc.Draw()
pc.Stroke.Color = pc.Fill.Color
pc.Fill.Color = nil
pc.Stroke.Width.Dots = 1.5 // 1.5 is the key number: 1 makes lines very transparent overall
for i, b := range blurs {
bo := br - float32(i)
pc.Stroke.Opacity = b * origOpacity
pc.RoundedRectangleSides(x+bo, y+bo, w-2*bo, h-2*bo, r)
pc.Draw()
}
pc.Stroke = origStroke
pc.Fill = origFill
}
//////// Image drawing
// FillBox performs an optimized fill of the given
// rectangular region with the given image. It is equivalent
// to [Painter.DrawBox] with [draw.Over].
func (pc *Painter) FillBox(pos, size math32.Vector2, img image.Image) {
pc.DrawBox(pos, size, img, draw.Over)
}
// BlitBox performs an optimized overwriting fill (blit) of the given
// rectangular region with the given image. It is equivalent
// to [Painter.DrawBox] with [draw.Src].
func (pc *Painter) BlitBox(pos, size math32.Vector2, img image.Image) {
pc.DrawBox(pos, size, img, draw.Src)
}
// DrawBox performs an optimized fill/blit of the given rectangular region
// with the given image, using the given draw operation.
// If the image is nil, a new transparent color is used.
func (pc *Painter) DrawBox(pos, size math32.Vector2, img image.Image, op draw.Op) {
if img == nil {
img = colors.Uniform(color.RGBA{})
}
pos = pc.Cumulative().MulPoint(pos)
size = pc.Cumulative().MulVector(size)
br := math32.RectFromPosSizeMax(pos, size)
cb := pc.Context().Bounds.Rect.ToRect()
b := cb.Intersect(br)
if b.Size() == (image.Point{}) {
return
}
if g, ok := img.(gradient.Gradient); ok {
g.Update(pc.Fill.Opacity, math32.B2FromRect(b), pc.Cumulative())
} else {
img = gradient.ApplyOpacity(img, pc.Fill.Opacity)
}
pc.Render.Add(pimage.NewDraw(b, img, nil, b.Min, op))
}
// BlurBox blurs the given already drawn region with the given blur radius.
// The blur radius passed to this function is the actual Gaussian
// standard deviation (σ). This means that you need to divide a CSS-standard
// blur radius value by two before passing it this function
// (see https://stackoverflow.com/questions/65454183/how-does-blur-radius-value-in-box-shadow-property-affect-the-resulting-blur).
func (pc *Painter) BlurBox(pos, size math32.Vector2, blurRadius float32) {
rect := math32.RectFromPosSizeMax(pos, size)
pc.Render.Add(pimage.NewBlur(rect, blurRadius))
}
// SetMask allows you to directly set the *image.Alpha to be used as a clipping
// mask. It must be the same size as the context, else an error is returned
// and the mask is unchanged.
func (pc *Painter) SetMask(mask *image.Alpha) error {
// if mask.Bounds() != pc.Image.Bounds() {
// return errors.New("mask size must match context size")
// }
pc.Mask = mask
return nil
}
// AsMask returns an *image.Alpha representing the alpha channel of this
// context. This can be useful for advanced clipping operations where you first
// render the mask geometry and then use it as a mask.
// func (pc *Painter) AsMask() *image.Alpha {
// b := pc.Image.Bounds()
// mask := image.NewAlpha(b)
// draw.Draw(mask, b, pc.Image, image.Point{}, draw.Src)
// return mask
// }
// Clear fills the entire image with the current fill color.
func (pc *Painter) Clear() {
src := pc.Fill.Color
pc.Render.Add(pimage.NewClear(src, image.Point{}, draw.Src))
}
// SetPixel sets the color of the specified pixel using the current stroke color.
func (pc *Painter) SetPixel(x, y int) {
pc.Render.Add(pimage.NewSetPixel(image.Point{x, y}, pc.Stroke.Color))
}
// DrawImage draws the given image at the specified starting point,
// using the bounds of the source image in rectangle rect. orig = original
// source image, which is used for high-resolution rendering if higher res.
// Uses the given draw operration: Over = overlay (alpha blend with destination)
// Src = copy source directly, overwriting destination pixels.
func (pc *Painter) DrawImage(src, orig image.Image, rect image.Rectangle, srcStart image.Point, op draw.Op) *pimage.Params {
pim := pimage.NewDraw(rect, src, orig, srcStart, op)
pc.Render.Add(pim)
return pim
}
// DrawImageAnchored draws the specified image at the specified anchor point.
// orig = original source image, which is used for high-resolution rendering.
// The anchor point is x - w * ax, y - h * ay, where w, h is the size of the
// image. Use ax=0.5, ay=0.5 to center the image at the specified point.
func (pc *Painter) DrawImageAnchored(src, orig image.Image, x, y, ax, ay float32) *pimage.Params {
s := src.Bounds().Size()
x -= ax * float32(s.X)
y -= ay * float32(s.Y)
m := math32.Translate2D(x, y)
cm := pc.Cumulative().Mul(m)
var pim *pimage.Params
if pc.Mask == nil {
pim = pimage.NewTransform(m, cm, src.Bounds(), src, orig, draw.Over)
} else {
pim = pimage.NewTransformMask(m, cm, src.Bounds(), src, orig, draw.Over, pc.Mask, image.Point{})
}
pc.Render.Add(pim)
return pim
}
// DrawImageScaled draws the specified image starting at given upper-left point,
// orig = original source image, which is used for high-resolution rendering,
// such that the size of the image is rendered as specified by w, h parameters
// (an additional scaling is applied to the transform matrix used in rendering)
func (pc *Painter) DrawImageScaled(src, orig image.Image, x, y, w, h float32) *pimage.Params {
s := src.Bounds().Size()
isz := math32.FromPoint(s)
isc := math32.Vec2(w, h).Div(isz)
m := math32.Translate2D(x, y).Scale(isc.X, isc.Y)
cm := pc.Cumulative().Mul(m)
var pim *pimage.Params
if pc.Mask == nil {
pim = pimage.NewTransform(m, cm, src.Bounds(), src, orig, draw.Over)
} else {
pim = pimage.NewTransformMask(m, cm, src.Bounds(), src, orig, draw.Over, pc.Mask, image.Point{})
}
pc.Render.Add(pim)
return pim
}
// BoundingBox computes the bounding box for an element in pixel int
// coordinates, applying current transform
func (pc *Painter) BoundingBox(minX, minY, maxX, maxY float32) image.Rectangle {
sw := float32(0.0)
// if pc.Stroke.Color != nil {// todo
// sw = 0.5 * pc.StrokeWidth()
// }
tmin := pc.Cumulative().MulPoint(math32.Vec2(minX, minY))
tmax := pc.Cumulative().MulPoint(math32.Vec2(maxX, maxY))
tp1 := math32.Vec2(tmin.X-sw, tmin.Y-sw).ToPointFloor()
tp2 := math32.Vec2(tmax.X+sw, tmax.Y+sw).ToPointCeil()
return image.Rect(tp1.X, tp1.Y, tp2.X, tp2.Y)
}
// BoundingBoxFromPoints computes the bounding box for a slice of points
func (pc *Painter) BoundingBoxFromPoints(points []math32.Vector2) image.Rectangle {
sz := len(points)
if sz == 0 {
return image.Rectangle{}
}
min := points[0]
max := points[1]
for i := 1; i < sz; i++ {
min.SetMin(points[i])
max.SetMax(points[i])
}
return pc.BoundingBox(min.X, min.Y, max.X, max.Y)
}
/////// DrawText
// DrawText adds given [shaped] text lines to the rendering list,
// at given position. Note that all rendering is subject to the
// current active transform, including the position:
// e.g., use math32.Rotate2DAround to just rotate the text at a given
// absolute position offset.
func (pc *Painter) DrawText(tx *shaped.Lines, pos math32.Vector2) {
pc.Render.Add(render.NewText(tx, pc.Paint, pc.Context(), pos))
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package pdf
import (
"fmt"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
)
// context holds the graphics state context to track the corresponding
// PDF state to optimize setting of styles.
type context struct {
// Style is current style: copied from parent context initially.
Style styles.Paint
// Transform is the current transform that has been set.
// it is not accumulated.
Transform math32.Matrix2
}
func newContext(sty *styles.Paint, ctm math32.Matrix2) *context {
c := &context{}
c.Style = *sty
c.Transform = ctm
return c
}
// PushStack adds a graphics stack push (q), which must
// be paired with a corresponding Pop (Q).
func (w *pdfPage) PushStack() {
ctx := w.stack.Peek()
fmt.Fprintf(w, " q")
w.stack.Push(newContext(&ctx.Style, ctx.Transform))
}
// PopStack adds a graphics stack pop (Q) which must
// be paired with a corresponding Push (q).
func (w *pdfPage) PopStack() {
fmt.Fprintf(w, " Q")
w.stack.Pop()
}
// SetTransform adds a cm to set the current matrix transform (CMT).
func (w *pdfPage) SetTransform(m math32.Matrix2) {
rot := m.ExtractRot()
m2 := m
if rot != 0 {
m2 = m.Mul(math32.Rotate2D(-2 * rot))
}
fmt.Fprintf(w, " %s cm", mat2(m2))
ctx := w.stack.Peek()
ctx.Transform = m2 // not cumulative!
}
// PushTransform adds a graphics stack push (q) and then
// cm to set the current matrix transform (CMT).
func (w *pdfPage) PushTransform(m math32.Matrix2) {
w.PushStack()
w.SetTransform(m)
}
// Cumulative returns the current cumulative transform.
func (w *pdfPage) Cumulative() math32.Matrix2 {
m := math32.Identity2()
for _, s := range w.stack {
m = m.Mul(s.Transform)
}
return m
}
// style() returns the currently active style
func (w *pdfPage) style() *styles.Paint {
ctx := w.stack.Peek()
return &ctx.Style
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This is adapted from https://github.com/tdewolff/canvas
// Copyright (c) 2015 Taco de Wolff, under an MIT License.
package pdf
import (
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/text"
)
func standardFontName(sty *rich.Style) string {
name := "Helvetica"
switch sty.Family {
case rich.SansSerif:
name = "Helvetica"
case rich.Serif:
name = "Times"
case rich.Monospace:
name = "Courier"
case rich.Cursive:
name = "ZapfChancery"
case rich.Math:
name = "Symbol"
case rich.Emoji:
name = "ZapfDingbats"
}
bname := name
if sty.Weight > rich.Medium {
name += "-Bold"
if sty.Slant == rich.Italic {
if bname == "Times" {
name += "Italic"
} else {
name += "Oblique"
}
}
} else {
if sty.Slant == rich.Italic {
if bname == "Times" {
name += "-Italic"
} else {
name += "-Oblique"
}
}
}
if name == "Times" {
name = "Times-Roman" // ugh
}
return name
}
func (w *pdfWriter) getFont(sty *rich.Style, _ *text.Style) pdfRef {
if sty.Family != rich.Custom {
stdFont := standardFontName(sty)
if ref, ok := w.fontsStd[stdFont]; ok {
return ref
}
dict := pdfDict{
"Type": pdfName("Font"),
"Subtype": pdfName("Type1"),
"BaseFont": pdfName(stdFont),
"Encoding": pdfName("WinAnsiEncoding"),
}
ref := w.writeObject(dict)
w.fontsStd[stdFont] = ref
return ref
}
// todo: deal with custom
/*
fonts := w.fontsH
if vertical {
fonts = w.fontsV
}
if ref, ok := fonts[font]; ok {
return ref
}
w.objOffsets = append(w.objOffsets, 0)
ref := pdfRef(len(w.objOffsets))
fonts[font] = ref
w.fontSubset[font] = ppath.NewFontSubsetter()
return ref
*/
return 0
}
/*
func (w *pdfWriter) writeFont(ref pdfRef, font *text.Font, vertical bool) {
// subset the font, we only write the used characters to the PDF CMap object to reduce its
// length. At the end of the function we add a CID to GID mapping to correctly select the
// right glyphID.
sfnt := font.SFNT
glyphIDs := w.fontSubset[font].List() // also when not subsetting, to minimize cmap table
if w.subset {
if sfnt.IsCFF && sfnt.CFF != nil {
sfnt.CFF.SetGlyphNames(nil)
}
sfntSubset, err := sfnt.Subset(glyphIDs, canvasFont.SubsetOptions{Tables: canvasFont.KeepPDFTables})
if err == nil {
sfnt = sfntSubset
} else {
fmt.Println("WARNING: font subsetting failed:", err)
}
}
fontProgram := sfnt.Write()
// calculate the character widths for the W array and shorten it
f := 1000.0 / float64(font.SFNT.Head.UnitsPerEm)
widths := make([]int, len(glyphIDs)+1)
for subsetGlyphID, glyphID := range glyphIDs {
widths[subsetGlyphID] = int(f*float64(font.SFNT.GlyphAdvance(glyphID)) + 0.5)
}
DW := widths[0]
W := pdfArray{}
i, j := 1, 1
for k, width := range widths {
if k != 0 && width != widths[j] {
if 4 < k-j { // at about 5 equal widths, it would be shorter using the other notation format
if i < j {
arr := pdfArray{}
for _, w := range widths[i:j] {
arr = append(arr, w)
}
W = append(W, i, arr)
}
if widths[j] != DW {
W = append(W, j, k-1, widths[j])
}
i = k
}
j = k
}
}
if i < len(widths) {
arr := pdfArray{}
for _, w := range widths[i:] {
arr = append(arr, w)
}
W = append(W, i, arr)
}
// create ToUnicode CMap
var bfRange, bfChar strings.Builder
var bfRangeCount, bfCharCount int
startGlyphID := uint16(0)
startUnicode := uint32('\uFFFD')
length := uint16(1)
for subsetGlyphID, glyphID := range glyphIDs[1:] {
unicode := uint32(font.SFNT.Cmap.ToUnicode(glyphID))
if 0x010000 <= unicode && unicode <= 0x10FFFF {
// UTF-16 surrogates
unicode -= 0x10000
unicode = (0xD800+(unicode>>10)&0x3FF)<<16 + 0xDC00 + unicode&0x3FF
}
if uint16(subsetGlyphID+1) == startGlyphID+length && unicode == startUnicode+uint32(length) {
length++
} else {
if 1 < length {
fmt.Fprintf(&bfRange, "\n<%04X> <%04X> <%04X>", startGlyphID, startGlyphID+length-1, startUnicode)
bfRangeCount++
} else {
fmt.Fprintf(&bfChar, "\n<%04X> <%04X>", startGlyphID, startUnicode)
bfCharCount++
}
startGlyphID = uint16(subsetGlyphID + 1)
startUnicode = unicode
length = 1
}
}
if 1 < length {
fmt.Fprintf(&bfRange, "\n<%04X> <%04X> <%04X>", startGlyphID, startGlyphID+length-1, startUnicode)
bfRangeCount++
} else {
fmt.Fprintf(&bfChar, "\n<%04X> <%04X>", startGlyphID, startUnicode)
bfCharCount++
}
toUnicode := bytes.Buffer{}
fmt.Fprintf(&toUnicode, `/CIDInit /ProcSet findresource begin
12 dict begin
begincmap
/CIDSystemInfo <</Registry(Adobe)/Ordering(UCS)/Supplement 0>> def
/CMapName /Adobe-Identity-UCS def
/CMapType 2 def
1 begincodespacerange
<0000> <FFFF> endcodespacerange`)
if 0 < bfRangeCount {
fmt.Fprintf(&toUnicode, `
%d beginbfrange%s endbfrange`, bfRangeCount, bfRange.String())
}
if 0 < bfCharCount {
fmt.Fprintf(&toUnicode, `
%d beginbfchar%s endbfchar`, bfCharCount, bfChar.String())
}
fmt.Fprintf(&toUnicode, `
endcmap
CMapName currentdict /CMap defineresource pop
end
end`)
toUnicodeStream := pdfStream{
dict: pdfDict{},
stream: toUnicode.Bytes(),
}
if w.compress {
toUnicodeStream.dict["Filter"] = pdfFilterFlate
}
toUnicodeRef := w.writeObject(toUnicodeStream)
// write font program
var cidSubtype string
var fontfileKey pdfName
var fontfileRef pdfRef
if font.SFNT.IsTrueType {
cidSubtype = "CIDFontType2"
fontfileKey = "FontFile2"
fontfileRef = w.writeObject(pdfStream{
dict: pdfDict{
"Filter": pdfFilterFlate,
},
stream: fontProgram,
})
} else if font.SFNT.IsCFF {
cidSubtype = "CIDFontType0"
fontfileKey = "FontFile3"
fontfileRef = w.writeObject(pdfStream{
dict: pdfDict{
"Subtype": pdfName("OpenType"),
"Filter": pdfFilterFlate,
},
stream: fontProgram,
})
}
// get name and CID subtype
name := font.Name()
if records := font.SFNT.Name.Get(canvasFont.NamePostScript); 0 < len(records) {
name = records[0].String()
}
baseFont := strings.ReplaceAll(name, " ", "")
if w.subset {
baseFont = "SUBSET+" + baseFont // TODO: give unique subset name
}
encoding := "Identity-H"
if vertical {
encoding = "Identity-V"
}
// in order to support more than 256 characters, we need to use a CIDFont dictionary which must be inside a Type0 font. Character codes in the stream are glyph IDs, however for subsetted fonts they are the _old_ glyph IDs, which is why we need the CIDToGIDMap
dict := pdfDict{
"Type": pdfName("Font"),
"Subtype": pdfName("Type0"),
"BaseFont": pdfName(baseFont),
"Encoding": pdfName(encoding), // map character codes in the stream to CID with identity encoding, we additionally map CID to GID in the descendant font when subsetting, otherwise that is also identity
"ToUnicode": toUnicodeRef,
"DescendantFonts": pdfArray{pdfDict{
"Type": pdfName("Font"),
"Subtype": pdfName(cidSubtype),
"BaseFont": pdfName(baseFont),
"DW": DW,
"W": W,
//"CIDToGIDMap": pdfName("Identity"),
"CIDSystemInfo": pdfDict{
"Registry": "Adobe",
"Ordering": "Identity",
"Supplement": 0,
},
"FontDescriptor": pdfDict{
"Type": pdfName("FontDescriptor"),
"FontName": pdfName(baseFont),
"Flags": 4, // Symbolic
"FontBBox": pdfArray{
int(f * float64(font.SFNT.Head.XMin)),
int(f * float64(font.SFNT.Head.YMin)),
int(f * float64(font.SFNT.Head.XMax)),
int(f * float64(font.SFNT.Head.YMax)),
},
"ItalicAngle": float64(font.SFNT.Post.ItalicAngle),
"Ascent": int(f * float64(font.SFNT.Hhea.Ascender)),
"Descent": -int(f * float64(font.SFNT.Hhea.Descender)),
"CapHeight": int(f * float64(font.SFNT.OS2.SCapHeight)),
"StemV": 80, // taken from Inkscape, should be calculated somehow, maybe use: 10+220*(usWeightClass-50)/900
fontfileKey: fontfileRef,
},
}},
}
if !w.subset {
cidToGIDMap := make([]byte, 2*len(glyphIDs))
for subsetGlyphID, glyphID := range glyphIDs {
j := int(subsetGlyphID) * 2
cidToGIDMap[j+0] = byte((glyphID & 0xFF00) >> 8)
cidToGIDMap[j+1] = byte(glyphID & 0x00FF)
}
cidToGIDMapStream := pdfStream{
dict: pdfDict{},
stream: cidToGIDMap,
}
if w.compress {
cidToGIDMapStream.dict["Filter"] = pdfFilterFlate
}
cidToGIDMapRef := w.writeObject(cidToGIDMapStream)
dict["DescendantFonts"].(pdfArray)[0].(pdfDict)["CIDToGIDMap"] = cidToGIDMapRef
}
w.objOffsets[ref-1] = w.pos
w.write("%v 0 obj\n", ref)
w.writeVal(dict)
w.write("\nendobj\n")
}
func (w *pdfWriter) writeFonts(fontMap map[*text.Font]pdfRef, vertical bool) {
// sort fonts by ref to make PDF deterministic
refs := make([]pdfRef, 0, len(fontMap))
refMap := make(map[pdfRef]*text.Font, len(fontMap))
for font, ref := range fontMap {
refs = append(refs, ref)
refMap[ref] = font
}
sort.Slice(refs, func(i, j int) bool {
return refs[i] < refs[j]
})
for _, ref := range refs {
w.writeFont(ref, refMap[ref], vertical)
}
}
*/
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This is adapted from codeberg.org/go-pdf/fpdf
// Copyright (c) 2023 The go-pdf Authors and Kurt Jung,
// under an MIT License.
package pdf
import "fmt"
// pdfLayer is one layer
type pdfLayer struct {
name string
visible bool
index int
ref pdfRef
}
// pdfLayers is all the layers
type pdfLayers struct {
list []pdfLayer
currentLayer int
openLayerPane bool
}
func (w *pdfWriter) layerInit() {
w.layers.list = make([]pdfLayer, 0)
w.layers.currentLayer = -1
w.layers.openLayerPane = false // only with OpenLayerPane
}
// AddLayer defines a layer that can be shown or hidden when the document is
// displayed. name specifies the layer name that the document reader will
// display in the layer list. visible specifies whether the layer will be
// initially visible. The return value is unique layer index that must be
// used in subsequent calls to BeginLayer.
func (w *pdfWriter) AddLayer(name string, visible bool) int {
layno := len(w.layers.list)
lay := pdfLayer{name: name, visible: visible, index: layno}
lay.ref = w.writeObject(pdfDict{"Type": pdfName("OCG"), "Name": name})
w.layers.list = append(w.layers.list, lay)
return layno
}
// BeginLayer is called to begin adding content to the specified layer index
// in a given page. Layer must have already been added via AddLayer.
// All content added to the page between a call to BeginLayer and a call to
// EndLayer is added to the layer specified by id.
func (w *pdfPage) BeginLayer(id int) {
w.EndLayer()
if id < 0 || id >= len(w.pdf.layers.list) {
return
}
ocn := fmt.Sprintf("oc%d", id)
fmt.Fprintf(w, " /OC /%s BDC", ocn)
w.pdf.layers.currentLayer = id
if _, ok := w.resources["Properties"]; !ok {
w.resources["Properties"] = pdfDict{}
}
l := &w.pdf.layers.list[id]
w.resources["Properties"].(pdfDict)[pdfName(ocn)] = l.ref
}
// EndLayer is called to stop adding content to the currently active layer.
// See BeginLayer for more details.
func (w *pdfPage) EndLayer() {
if w.pdf.layers.currentLayer < 0 {
return
}
fmt.Fprintf(w, " EMC")
w.pdf.layers.currentLayer = -1
}
// OpenLayerPane advises the document reader to open the layer pane when the
// document is initially displayed.
func (w *pdfWriter) OpenLayerPane() {
w.layers.openLayerPane = true
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package pdf
import (
"cogentcore.org/core/math32"
)
// AddAnchor adds a uniquely-named link anchor location.
// The position is in "default user space" coordinates = standard page coordinates,
// without the current CTM transform.// This function will handle the base page
// transform for scaling and flipping of coordinates to top-left system.
func (w *pdfPage) AddAnchor(name string, pos math32.Vector2) {
ms := math32.Scale2D(w.pdf.globalScale, w.pdf.globalScale)
pos = ms.MulPoint(pos)
if w.pdf.anchors == nil {
w.pdf.anchors = make(pdfMap)
}
// pageNo replaced at end with ref:
w.pdf.anchors[name] = pdfArray{w.pageNo, pdfName("XYZ"), 0, w.height - pos.Y, 0}
// fmt.Println("anchor:", w.pageNo, name, pos)
}
// AddLink adds a link annotation. The rect is in "default user space"
// coordinates = standard page coordinates, without the current CTM transform.
// This function will handle the base page transform for scaling and
// flipping of coordinates to top-left system.
func (w *pdfPage) AddLink(uri string, rect math32.Box2) {
ms := math32.Scale2D(w.pdf.globalScale, w.pdf.globalScale)
rect = rect.MulMatrix2(ms)
bs := pdfDict{
"W": 0,
}
annot := pdfDict{
"Type": pdfName("Annot"),
"Subtype": pdfName("Link"),
"BS": bs,
"C": pdfArray{0.8, 0.8, 1.0},
"Rect": pdfArray{rect.Min.X, w.height - rect.Max.Y, rect.Max.X, w.height - rect.Min.Y},
}
if len(uri) > 0 && uri[0] == '#' { // local anchor actions
annot["Dest"] = uri[1:]
} else {
annot["Contents"] = uri
annot["A"] = pdfDict{
"Type": pdfName("Action"),
"S": pdfName("URI"),
pdfName("URI"): uri,
}
}
w.annots = append(w.annots, annot)
}
//////// outline
// pdfOutline is one outline entry
type pdfOutline struct {
name string
level int
page int
ypos float32 // inverted y position
parent int // index into outline list
count int
prev int
next int
first int
last int
}
// AddOutline adds an outline element. level must be > 0
func (w *pdfPage) AddOutline(name string, level int, ypos float32) {
ol := &pdfOutline{name: name, level: level, page: w.pageNo, ypos: w.height - w.pdf.globalScale*ypos, prev: -1, next: -1, first: -1, last: -1}
if len(w.pdf.outlines) == 0 {
or := &pdfOutline{name: "Contents", level: 0, page: 0, ypos: w.height, prev: -1, next: -1, first: -1, last: -1}
w.pdf.outlines = append(w.pdf.outlines, or)
}
w.pdf.outlines = append(w.pdf.outlines, ol)
}
// writeOutlines outputs all the outline elements, and returns the ref to the first one.
func (w *pdfWriter) writeOutlines() pdfRef {
lastLev := make(map[int]int)
level := 0
n := len(w.outlines)
// note: this logic from fpdf
for i, o := range w.outlines {
if o.level > 0 {
parent := lastLev[o.level-1]
o.parent = parent
w.outlines[parent].last = i
w.outlines[parent].count++
if o.level > level {
w.outlines[parent].first = i
}
} else {
o.parent = n
}
if o.level <= level && i > 0 {
prev := lastLev[o.level]
w.outlines[prev].next = i
o.prev = prev
}
lastLev[o.level] = i
level = o.level
}
firstRef := pdfRef(len(w.objOffsets) + 1)
for i, o := range w.outlines {
od := pdfDict{
"Title": o.name,
"Parent": firstRef + pdfRef(o.parent),
"Dest": pdfArray{w.pages[o.page], pdfName("XYZ"), 0, o.ypos, 0},
"Count": o.count,
}
if o.prev != -1 {
od[pdfName("Prev")] = firstRef + pdfRef(o.prev)
}
if o.next != -1 {
od[pdfName("Next")] = firstRef + pdfRef(o.next)
}
if o.first != -1 {
od[pdfName("First")] = firstRef + pdfRef(o.first)
}
if o.last != -1 {
od[pdfName("Last")] = firstRef + pdfRef(o.last)
}
if i == 0 {
delete(od, "Parent")
}
w.writeObject(od)
}
return firstRef
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This is adapted from https://github.com/tdewolff/canvas
// Copyright (c) 2015 Taco de Wolff, under an MIT License.
package pdf
import (
"bytes"
"fmt"
"image"
"cogentcore.org/core/base/stack"
"cogentcore.org/core/math32"
)
type pdfPage struct {
*bytes.Buffer
pdf *pdfWriter
pageNo int
width, height float32
resources pdfDict
annots pdfArray
graphicsStates map[float32]pdfName
stack stack.Stack[*context]
inTextObject bool
textPosition math32.Vector2
textCharSpace float32
textRenderMode int
// maskSet is whether the soft mask of a transparent gradient is set,
// which is removed after the path is painted (see endMask).
maskSet bool
}
func (w *pdfPage) writePage(parent pdfRef) pdfRef {
b := w.Bytes()
if 0 < len(b) && b[0] == ' ' {
b = b[1:]
}
stream := pdfStream{
dict: pdfDict{},
stream: b,
}
if w.pdf.compress {
stream.dict["Filter"] = pdfFilterFlate
}
contents := w.pdf.writeObject(stream)
page := pdfDict{
"Type": pdfName("Page"),
"Parent": parent,
"MediaBox": pdfArray{0.0, 0.0, w.width, w.height},
"Resources": w.resources,
"Group": pdfDict{
"Type": pdfName("Group"),
"S": pdfName("Transparency"),
"I": true,
"CS": pdfName("DeviceRGB"),
},
"Contents": contents,
}
if 0 < len(w.annots) {
page["Annots"] = w.annots
}
return w.pdf.writeObject(page)
}
// DrawImage embeds and draws an image, as a lossless (PNG)
func (w *pdfPage) DrawImage(img image.Image, m math32.Matrix2) {
size := img.Bounds().Size()
// add clipping path around image for smooth edges when rotating
outerRect := math32.B2(0.0, 0.0, float32(size.X), float32(size.Y)).MulMatrix2(m)
bl := m.MulPoint(math32.Vec2(0, 0))
br := m.MulPoint(math32.Vec2(float32(size.X), 0))
tl := m.MulPoint(math32.Vec2(0, float32(size.Y)))
tr := m.MulPoint(math32.Vec2(float32(size.X), float32(size.Y)))
fmt.Fprintf(w, " q %v %v %v %v re W n", dec(outerRect.Min.X), dec(outerRect.Min.Y), dec(outerRect.Size().X), dec(outerRect.Size().Y))
fmt.Fprintf(w, " %v %v m %v %v l %v %v l %v %v l h W n", dec(bl.X), dec(bl.Y), dec(tl.X), dec(tl.Y), dec(tr.X), dec(tr.Y), dec(br.X), dec(br.Y))
ref := w.embedImage(img)
if _, ok := w.resources["XObject"]; !ok {
w.resources["XObject"] = pdfDict{}
}
name := pdfName(fmt.Sprintf("Im%d", len(w.resources["XObject"].(pdfDict))))
w.resources["XObject"].(pdfDict)[name] = ref
m = m.Scale(float32(size.X), float32(size.Y))
w.SetAlpha(1.0)
fmt.Fprintf(w, " %s cm /%v Do Q", mat2(m), name)
}
// embedImage does a lossless image embedding.
func (w *pdfPage) embedImage(img image.Image) pdfRef {
if ref, ok := w.pdf.images[img]; ok {
return ref
}
var hasMask bool
size := img.Bounds().Size()
filter := pdfFilterFlate
sp := img.Bounds().Min // starting point
stream := make([]byte, size.X*size.Y*3)
streamMask := make([]byte, size.X*size.Y)
for y := size.Y - 1; y >= 0; y-- { // invert
for x := range size.X {
pi := (size.Y-1-y)*size.X + x
i := pi * 3
R, G, B, A := img.At(sp.X+x, sp.Y+y).RGBA()
if A != 0 {
stream[i+0] = byte((R * 65535 / A) >> 8)
stream[i+1] = byte((G * 65535 / A) >> 8)
stream[i+2] = byte((B * 65535 / A) >> 8)
streamMask[pi] = byte(A >> 8)
}
if A>>8 != 255 {
hasMask = true
}
}
}
dict := pdfDict{
"Type": pdfName("XObject"),
"Subtype": pdfName("Image"),
"Width": size.X,
"Height": size.Y,
"ColorSpace": pdfName("DeviceRGB"),
"BitsPerComponent": 8,
"Interpolate": true,
"Filter": filter,
}
if hasMask {
dict["SMask"] = w.pdf.writeObject(pdfStream{
dict: pdfDict{
"Type": pdfName("XObject"),
"Subtype": pdfName("Image"),
"Width": size.X,
"Height": size.Y,
"ColorSpace": pdfName("DeviceGray"),
"BitsPerComponent": 8,
"Interpolate": true,
"Filter": pdfFilterFlate,
},
stream: streamMask,
})
}
ref := w.pdf.writeObject(pdfStream{
dict: dict,
stream: stream,
})
w.pdf.images[img] = ref
return ref
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This is adapted from https://github.com/tdewolff/canvas
// Copyright (c) 2015 Taco de Wolff, under an MIT License.
package pdf
import (
"fmt"
"image"
"image/color"
"log/slog"
"maps"
"reflect"
"cogentcore.org/core/colors"
"cogentcore.org/core/colors/gradient"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint/ppath"
"cogentcore.org/core/styles"
)
// Path renders a path to the canvas using a style and an
// individual matrix (needed for fill)
func (r *PDF) Path(path ppath.Path, style *styles.Paint, tr math32.Matrix2) {
// TODO: PDFs don't support the arcs joiner, miter joiner (not clipped),
// or miter joiner (clipped) with non-bevel fallback, which could be
// drawn by filling the outline of the stroke (see stroke.Stroke).
scale := math32.Sqrt(math32.Abs(tr.Det()))
stk := style.Stroke
stk.Width.Dots *= scale
stk.DashOffset, stk.Dashes = ppath.ScaleDash(scale, stk.DashOffset, stk.Dashes)
// PDFs don't support connecting first and last dashes if path is closed,
// so we move the start of the path if this is the case
// TODO: closing dashes
//if style.DashesClose {
// strokeUnsupported = true
//}
closed := false
trpath := path.Clone().Transform(tr)
data := trpath.ToPDF()
if 1 < len(data) && data[len(data)-1] == 'h' {
data = data[:len(data)-2]
closed = true
}
// the bounds of the path, for a gradient fill or stroke
var bounds math32.Box2
_, fillGrad := style.Fill.Color.(gradient.Gradient)
_, strokeGrad := style.Stroke.Color.(gradient.Gradient)
if (style.HasFill() && fillGrad) || (style.HasStroke() && strokeGrad) {
fbox := trpath.FastBounds()
cum := r.Cumulative()
bounds = fbox.MulMatrix2(cum)
}
if style.HasFill() && !style.HasStroke() {
r.w.SetFill(&style.Fill, bounds, tr)
r.w.Write([]byte(" "))
r.w.Write([]byte(data))
r.w.Write([]byte(" f"))
if style.Fill.Rule == ppath.EvenOdd {
r.w.Write([]byte("*"))
}
r.w.endMask()
} else if !style.HasFill() && style.HasStroke() {
r.w.SetStroke(&stk, bounds, tr)
r.w.Write([]byte(" "))
r.w.Write([]byte(data))
if closed {
r.w.Write([]byte(" s"))
} else {
r.w.Write([]byte(" S"))
}
r.w.endMask()
} else if style.HasFill() && style.HasStroke() {
r.w.SetFill(&style.Fill, bounds, tr)
r.w.Write([]byte(" "))
r.w.Write([]byte(data))
r.w.Write([]byte(" f"))
if style.Fill.Rule == ppath.EvenOdd {
r.w.Write([]byte("*"))
}
r.w.endMask()
r.w.SetStroke(&stk, bounds, tr)
r.w.Write([]byte(" "))
r.w.Write([]byte(data))
if closed {
r.w.Write([]byte(" s"))
} else {
r.w.Write([]byte(" S"))
}
r.w.endMask()
}
}
// SetFill sets the fill style values where different from current.
// The bounds and matrix are required for gradient fills: pass identity
// if not available.
func (w *pdfPage) SetFill(fill *styles.Fill, bounds math32.Box2, m math32.Matrix2) {
csty := w.style()
_, grad := fill.Color.(gradient.Gradient)
// a gradient is set again for the bounds of each path
if grad || csty.Fill.Color != fill.Color || csty.Fill.Opacity != fill.Opacity {
w.SetFillColor(fill, bounds, m)
}
csty.Fill = *fill
}
// SetAlpha sets the transparency value.
func (w *pdfPage) SetAlpha(alpha float32) {
gs := w.getOpacityGS(alpha)
fmt.Fprintf(w, " /%v gs", gs)
}
func alphaNorm(c uint8, a float32) dec {
if a == 0 {
return dec(0)
}
return dec(float32(c) / 255.0 / a)
}
func alphaNormColor(c color.RGBA, a float32) [3]dec {
var v [3]dec
v[0] = alphaNorm(c.R, a)
v[1] = alphaNorm(c.G, a)
v[2] = alphaNorm(c.B, a)
return v
}
// SetFillColor sets the filling color (image).
func (w *pdfPage) SetFillColor(fill *styles.Fill, bounds math32.Box2, m math32.Matrix2) {
switch x := fill.Color.(type) {
// todo: image
case gradient.Gradient:
w.setGradient(x, fill.Opacity, bounds, m, "cs", "scn")
case *image.Uniform:
w.endMask()
var clr color.RGBA
if x != nil {
clr = colors.ApplyOpacity(colors.AsRGBA(x), fill.Opacity)
}
a := float32(clr.A) / 255.0
if a == 0 {
fmt.Fprintf(w, " 0 g")
} else if clr.R == clr.G && clr.R == clr.B {
fmt.Fprintf(w, " %v g", alphaNorm(clr.R, a))
} else {
v := alphaNormColor(clr, a)
fmt.Fprintf(w, " %v %v %v rg", v[0], v[1], v[2])
}
w.SetAlpha(a)
}
}
// SetStroke sets the stroke style values where different from current.
// The bounds and matrix are required for gradient strokes: pass identity
// if not available.
func (w *pdfPage) SetStroke(stroke *styles.Stroke, bounds math32.Box2, m math32.Matrix2) {
csty := w.style()
_, grad := stroke.Color.(gradient.Gradient)
// a gradient is set again for the bounds of each path
if grad || csty.Stroke.Color != stroke.Color || csty.Stroke.Opacity != stroke.Opacity {
w.SetStrokeColor(stroke, bounds, m)
}
if csty.Stroke.Width.Dots != stroke.Width.Dots {
w.SetStrokeWidth(stroke.Width.Dots)
}
if csty.Stroke.Cap != stroke.Cap {
w.SetStrokeCap(stroke.Cap)
}
if csty.Stroke.Join != stroke.Join || (csty.Stroke.Join == ppath.JoinMiter && csty.Stroke.MiterLimit != stroke.MiterLimit) {
w.SetStrokeJoin(stroke.Join, stroke.MiterLimit)
}
if len(stroke.Dashes) > 0 { // always do
w.SetDashes(stroke.DashOffset, stroke.Dashes)
} else {
if len(csty.Stroke.Dashes) > 0 {
w.SetDashes(0, nil)
}
}
csty.Stroke = *stroke
}
// SetStrokeColor sets the stroking color (image). The bounds and matrix
// are required for gradient strokes.
func (w *pdfPage) SetStrokeColor(stroke *styles.Stroke, bounds math32.Box2, m math32.Matrix2) {
switch x := stroke.Color.(type) {
case gradient.Gradient:
w.setGradient(x, stroke.Opacity, bounds, m, "CS", "SCN")
case *image.Uniform:
w.endMask()
clr := colors.ApplyOpacity(colors.AsRGBA(x), stroke.Opacity)
a := float32(clr.A) / 255.0
if clr.R == clr.G && clr.R == clr.B {
fmt.Fprintf(w, " %v G", alphaNorm(clr.R, a))
} else {
v := alphaNormColor(clr, a)
fmt.Fprintf(w, " %v %v %v RG", v[0], v[1], v[2])
}
w.SetAlpha(a)
}
}
// SetStrokeWidth sets the stroke width.
func (w *pdfPage) SetStrokeWidth(lineWidth float32) {
fmt.Fprintf(w, " %v w", dec(lineWidth))
}
// SetStrokeCap sets the stroke cap type.
func (w *pdfPage) SetStrokeCap(capper ppath.Caps) {
var lineCap int
switch capper {
case ppath.CapButt:
lineCap = 0
case ppath.CapRound:
lineCap = 1
case ppath.CapSquare:
lineCap = 2
default:
slog.Error("pdfWriter", "StrokeCap not supported", capper)
}
fmt.Fprintf(w, " %d J", lineCap)
}
// SetStrokeJoin sets the stroke join type.
func (w *pdfPage) SetStrokeJoin(joiner ppath.Joins, miterLimit float32) {
var lineJoin int
switch joiner {
case ppath.JoinBevel:
lineJoin = 2
case ppath.JoinRound:
lineJoin = 1
case ppath.JoinMiter:
lineJoin = 0
default:
slog.Error("pdfWriter", "StrokeJoin not supported", joiner)
}
fmt.Fprintf(w, " %d j", lineJoin)
if lineJoin == 0 {
fmt.Fprintf(w, " %v M", dec(miterLimit))
}
}
// SetDashes sets the dash phase and array.
func (w *pdfPage) SetDashes(dashPhase float32, dashArray []float32) {
if len(dashArray)%2 == 1 {
dashArray = append(dashArray, dashArray...)
}
// PDF can't handle negative dash phases
if dashPhase < 0.0 {
totalLength := float32(0.0)
for _, dash := range dashArray {
totalLength += dash
}
for dashPhase < 0.0 {
dashPhase += totalLength
}
}
dashes := append(dashArray, dashPhase)
if len(dashes) == 1 {
fmt.Fprintf(w, " [] 0 d")
dashes[0] = 0.0
} else {
fmt.Fprintf(w, " [%v", dec(dashes[0]))
for _, dash := range dashes[1 : len(dashes)-1] {
fmt.Fprintf(w, " %v", dec(dash))
}
fmt.Fprintf(w, "] %v d", dec(dashes[len(dashes)-1]))
}
}
func (w *pdfPage) getOpacityGS(a float32) pdfName {
if name, ok := w.graphicsStates[a]; ok {
return name
}
name := pdfName(fmt.Sprintf("A%d", len(w.graphicsStates)))
w.graphicsStates[a] = name
if _, ok := w.resources["ExtGState"]; !ok {
w.resources["ExtGState"] = pdfDict{}
}
w.resources["ExtGState"].(pdfDict)[name] = pdfDict{
"CA": a,
"ca": a,
}
return name
}
// setGradient sets the given gradient as the fill (cs, scn) or stroke
// (CS, SCN) color, with the given opacity. A gradient with transparent
// stops also sets a soft mask of its alphas, which [pdfPage.endMask]
// removes after the path is painted.
func (w *pdfPage) setGradient(gr gradient.Gradient, opacity float32, bounds math32.Box2, m math32.Matrix2, cs, scn string) {
w.endMask()
pat, mask := w.gradientPattern(gr, opacity, bounds, m)
w.SetAlpha(1) // the transparency is in the mask
if mask != "" {
fmt.Fprintf(w, " /%v gs", mask)
w.maskSet = true
}
fmt.Fprintf(w, " /Pattern %s /%v %s", cs, pat, scn)
}
// endMask removes the soft mask of a transparent gradient, if set.
func (w *pdfPage) endMask() {
if !w.maskSet {
return
}
fmt.Fprintf(w, " /%v gs", w.extGState("MN", pdfDict{"SMask": pdfName("None")}))
w.maskSet = false
}
// extGState returns the name of an ExtGState with the given values,
// with names starting with the given prefix.
func (w *pdfPage) extGState(prefix string, gs pdfDict) pdfName {
if _, ok := w.resources["ExtGState"]; !ok {
w.resources["ExtGState"] = pdfDict{}
}
egs := w.resources["ExtGState"].(pdfDict)
for name, g := range egs {
if reflect.DeepEqual(g, gs) {
return name
}
}
name := pdfName(fmt.Sprintf("%s%d", prefix, len(egs)))
egs[name] = gs
return name
}
// gradientPattern returns the name of the pattern of the given gradient,
// and of the ExtGState of its soft mask if any of its stops are
// transparent (with the given opacity), or "".
func (w *pdfPage) gradientPattern(gr gradient.Gradient, opacity float32, bounds math32.Box2, m math32.Matrix2) (pdfName, pdfName) {
cum := w.Cumulative().Mul(m)
gr.Update(opacity, bounds, cum)
base := gr.AsBase()
// the geometry of the shading, the same for its colors and alphas
geom := pdfDict{"Extend": pdfArray{true, true}}
switch g := gr.(type) {
case *gradient.Linear:
s, e := g.TransformedAxis()
geom["ShadingType"] = 2
geom["Coords"] = pdfArray{s.X, s.Y, e.X, e.Y}
case *gradient.Radial:
c, f, rad := g.TransformedCoords()
r := max(math32.Abs(rad.X), math32.Abs(rad.Y))
geom["ShadingType"] = 3
geom["Coords"] = pdfArray{f.X, f.Y, 0, c.X, c.Y, r}
}
shading := pdfDict{"ColorSpace": pdfName("DeviceRGB")}
maps.Copy(shading, geom)
shading["Function"] = patternStopsFunction(base.Stops, stopColor)
pattern := pdfDict{
"Type": pdfName("Pattern"),
"PatternType": 2,
"Shading": shading,
}
if _, ok := w.resources["Pattern"]; !ok {
w.resources["Pattern"] = pdfDict{}
}
pats := w.resources["Pattern"].(pdfDict)
var name pdfName
for pn, pat := range pats {
if reflect.DeepEqual(pat, pattern) {
name = pn
break
}
}
if name == "" {
name = pdfName(fmt.Sprintf("P%d", len(pats)))
pats[name] = pattern
}
opaque := true
for i := range base.Stops {
if stopAlpha(&base.Stops[i], opacity) < 1 {
opaque = false
break
}
}
if opaque {
return name, ""
}
// the mask is a luminosity transparency group of a gray shading of the
// alphas, in the default space of the page, as the pattern is.
alphas := pdfDict{"ColorSpace": pdfName("DeviceGray")}
maps.Copy(alphas, geom)
alphas["Function"] = patternStopsFunction(base.Stops, func(st *gradient.Stop) pdfArray {
return pdfArray{dec(stopAlpha(st, opacity))}
})
inv := w.Cumulative().Inverse()
form := w.pdf.writeObject(pdfStream{
dict: pdfDict{
"Type": pdfName("XObject"),
"Subtype": pdfName("Form"),
"BBox": pdfArray{0, 0, w.width, w.height},
"Matrix": pdfArray{dec(inv.XX), dec(inv.XY), dec(inv.YX), dec(inv.YY), dec(inv.X0), dec(inv.Y0)}, // as mat2
"Group": pdfDict{
"Type": pdfName("Group"),
"S": pdfName("Transparency"),
"CS": pdfName("DeviceGray"),
},
"Resources": pdfDict{"Shading": pdfDict{"Sh0": alphas}},
},
stream: []byte("/Sh0 sh"),
})
mask := w.extGState("M", pdfDict{
"SMask": pdfDict{
"Type": pdfName("Mask"),
"S": pdfName("Luminosity"),
"G": form,
},
})
return name, mask
}
// stopAlpha returns the alpha of the given stop, with the given opacity.
func stopAlpha(st *gradient.Stop, opacity float32) float32 {
return float32(st.Color.A) / 255 * st.Opacity * opacity
}
// stopColor returns the (not premultiplied) RGB color of the given stop.
func stopColor(st *gradient.Stop) pdfArray {
c := alphaNormColor(st.Color, float32(st.Color.A)/255)
return pdfArray{c[0], c[1], c[2]}
}
// patternStopsFunction returns the function of the values of the given
// stops (as their colors or alphas), stitching the functions between
// each pair of stops.
func patternStopsFunction(stops []gradient.Stop, value func(st *gradient.Stop) pdfArray) pdfDict {
n := len(stops)
if n == 0 {
return pdfDict{}
}
if n == 1 {
return patternStopFunction(value(&stops[0]), value(&stops[0]))
}
fs := pdfArray{}
encode := pdfArray{}
bounds := pdfArray{}
if !ppath.Equal(stops[0].Pos, 0.0) {
fs = append(fs, patternStopFunction(value(&stops[0]), value(&stops[0])))
encode = append(encode, 0, 1)
bounds = append(bounds, stops[0].Pos)
}
for i := range n - 1 {
fs = append(fs, patternStopFunction(value(&stops[i]), value(&stops[i+1])))
encode = append(encode, 0, 1)
if i != 0 {
bounds = append(bounds, stops[i].Pos) // the start of this function
}
}
if !ppath.Equal(stops[n-1].Pos, 1.0) {
fs = append(fs, patternStopFunction(value(&stops[n-1]), value(&stops[n-1])))
encode = append(encode, 0, 1)
bounds = append(bounds, stops[n-1].Pos)
}
if len(fs) == 1 {
return fs[0].(pdfDict)
}
return pdfDict{
"FunctionType": 3,
"Domain": pdfArray{0, 1},
"Encode": encode,
"Bounds": bounds,
"Functions": fs,
}
}
// patternStopFunction returns the function interpolating between the
// given values of two stops.
func patternStopFunction(v0, v1 pdfArray) pdfDict {
return pdfDict{
"FunctionType": 2,
"Domain": pdfArray{0, 1},
"N": 1,
"C0": v0,
"C1": v1,
}
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This is adapted from https://github.com/tdewolff/canvas
// Copyright (c) 2015 Taco de Wolff, under an MIT License.
// Package pdf writes PDF documents of painted content: paths, text, images,
// gradients, links, and outlines.
package pdf
import (
"image"
"io"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/rich"
)
// todo:
// * needs to include the basic page xform which we neeed to install on pdf rendering stack.
// if passed bounds are empty, use path bounds.
// - compute cumulative from stack, don't pass -- only pass local
// - add a convenience method with empty bounds and ID transform, for text cases?
// UseStandardFonts sets the [rich.Settings] default fonts to the
// corresponding PDF defaults, so that text layout works correctly
// for the PDF rendering. The current settings are returned,
// and should be passed to [RestorePreviousFonts] when done.
func UseStandardFonts() rich.SettingsData {
prev := rich.Settings
rich.Settings.SansSerif = "Helvetica"
rich.Settings.Serif = "Times"
rich.Settings.Monospace = "Courier"
return prev
}
// RestorePreviousFonts sets the [rich.Settings] default fonts
// to those returned from [UseStandardFonts]
func RestorePreviousFonts(s rich.SettingsData) {
rich.Settings = s
}
// type Options struct {
// Compress bool
// SubsetFonts bool
// canvas.ImageEncoding
// }
//
// var DefaultOptions = Options{
// Compress: true,
// SubsetFonts: true,
// ImageEncoding: canvas.Lossless,
// }
// PDF is a portable document format renderer.
type PDF struct {
w *pdfPage
width, height float32
// opts *Options
}
// New returns a portable document format (PDF) renderer.
// The size is in points.
func New(w io.Writer, width, height float32, un *units.Context) *PDF {
// if opts == nil {
// defaultOptions := DefaultOptions
// opts = &defaultOptions
// }
page := newPDFWriter(w, un).NewPage(width, height)
// page.pdf.SetCompression(opts.Compress)
// page.pdf.SetFontSubsetting(opts.SubsetFonts)
return &PDF{
w: page,
width: width,
height: height,
// opts: opts,
}
}
// SetImageEncoding sets the image encoding to Loss or Lossless.
// func (r *PDF) SetImageEncoding(enc canvas.ImageEncoding) {
// r.opts.ImageEncoding = enc
// }
// SetInfo sets the document's title, subject, keywords, author and creator.
func (r *PDF) SetInfo(title, subject, keywords, author, creator string) {
r.w.pdf.SetTitle(title)
r.w.pdf.SetSubject(subject)
r.w.pdf.SetKeywords(keywords)
r.w.pdf.SetAuthor(author)
r.w.pdf.SetCreator(creator)
}
// SetLang sets the document's language. It must adhere the RFC 3066 specification on Language-Tag, eg. es-CL.
func (r *PDF) SetLang(lang string) {
r.w.pdf.SetLang(lang)
}
// NewPage starts adds a new page where further rendering will be written to.
func (r *PDF) NewPage(width, height float32) {
r.w = r.w.pdf.NewPage(width, height)
}
// AddLink adds a link to the PDF document.
func (r *PDF) AddLink(uri string, rect math32.Box2) {
r.w.AddLink(uri, rect)
}
// Close finished and closes the PDF.
func (r *PDF) Close() error {
return r.w.pdf.Close()
}
// Size returns the size of the canvas in millimeters.
func (r *PDF) Size() (float32, float32) {
return r.width, r.height
}
// AddLayer defines a layer that can be shown or hidden when the document is
// displayed. name specifies the layer name that the document reader will
// display in the layer list. visible specifies whether the layer will be
// initially visible. The return value is an integer ID that is used in a call
// to BeginLayer().
func (r *PDF) AddLayer(name string, visible bool) (layerID int) {
return r.w.pdf.AddLayer(name, visible)
}
// BeginLayer is called to begin adding content to the specified layer.
// All content added to the page between a call to BeginLayer and a call to
// EndLayer is added to the layer specified by id. See AddLayer for more
// details.
func (r *PDF) BeginLayer(id int) {
r.w.BeginLayer(id)
}
// EndLayer is called to stop adding content to the currently active layer.
// See BeginLayer for more details.
func (r *PDF) EndLayer() {
r.w.EndLayer()
}
// PushStack adds a graphics stack push, which must
// be paired with a corresponding Pop.
func (r *PDF) PushStack() {
r.w.PushStack()
}
// PopStack adds a graphics stack pop which must
// be paired with a corresponding Push.
func (r *PDF) PopStack() {
r.w.PopStack()
}
// SetTransform adds a cm to set the current matrix transform (CMT).
func (r *PDF) SetTransform(m math32.Matrix2) {
r.w.SetTransform(m)
}
// PushTransform adds a graphics stack push (q) and then
// cm to set the current matrix transform (CMT).
func (r *PDF) PushTransform(m math32.Matrix2) {
r.PushStack()
r.SetTransform(m)
}
// Cumulative returns the current cumulative transform.
func (r *PDF) Cumulative() math32.Matrix2 {
return r.w.Cumulative()
}
// Image renders an image to the canvas using a transformation matrix.
func (r *PDF) Image(img image.Image, m math32.Matrix2) {
r.w.DrawImage(img, m)
}
// AddAnchor adds a uniquely-named link anchor location,
// which can then be a target for links.
func (r *PDF) AddAnchor(name string, pos math32.Vector2) {
r.w.AddAnchor(name, pos)
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This is adapted from https://github.com/tdewolff/canvas
// Copyright (c) 2015 Taco de Wolff, under an MIT License.
package pdf
import (
"fmt"
"image"
"strconv"
"strings"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/colors"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint/ppath"
"cogentcore.org/core/styles"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/shaped"
"cogentcore.org/core/text/shaped/shapers/shapedgt"
"cogentcore.org/core/text/text"
"cogentcore.org/core/text/textpos"
"golang.org/x/text/encoding/charmap"
)
// Text renders text to the canvas using a transformation matrix,
// (the translation component specifies the starting offset)
func (r *PDF) Text(style *styles.Paint, m math32.Matrix2, pos math32.Vector2, lns *shaped.Lines) {
if lns.Anchor != "" {
anc := lns.Anchor
hidx := strings.Index(anc, ";Header ")
if hidx >= 0 {
if hidx > 0 {
r.w.AddAnchor(anc[:hidx], pos)
anc = anc[hidx:]
}
anc = anc[8:]
level := errors.Log1(strconv.Atoi(anc[0:1]))
anc = anc[2:]
r.w.AddOutline(anc, level, pos.Y)
} else {
r.w.AddAnchor(lns.Anchor, pos)
}
}
mt := m.Mul(math32.Translate2D(pos.X, pos.Y))
r.w.PushTransform(mt)
off := lns.Offset
clr := colors.Uniform(lns.Color)
runes := lns.Source.Join()
for li := range lns.Lines {
ln := &lns.Lines[li]
r.textLine(style, m, li, ln, lns, runes, clr, off)
}
r.links(lns, m, pos)
r.w.PopStack()
}
// TextLine rasterizes the given shaped.Line.
func (r *PDF) textLine(style *styles.Paint, m math32.Matrix2, _ int, ln *shaped.Line, lns *shaped.Lines, runes []rune, clr image.Image, off math32.Vector2) {
start := off.Add(ln.Offset)
off = start
for ri := range ln.Runs {
run := ln.Runs[ri].(*shapedgt.Run)
r.textRunRegions(m, run, ln, lns, off)
if run.Direction.IsVertical() {
off.Y += run.Advance()
} else {
off.X += run.Advance()
}
}
off = start
for ri := range ln.Runs {
run := ln.Runs[ri].(*shapedgt.Run)
r.textRun(style, m, run, ln, lns, runes, clr, off)
if run.Direction.IsVertical() {
off.Y += run.Advance()
} else {
off.X += run.Advance()
}
}
}
// textRegionFill fills given regions within run with given fill color.
func (r *PDF) textRegionFill(_ math32.Matrix2, run *shapedgt.Run, off math32.Vector2, fill image.Image, ranges []textpos.Range) {
if fill == nil {
return
}
idm := math32.Identity2()
for _, sel := range ranges {
rsel := sel.Intersect(run.Runes())
if rsel.Len() == 0 {
continue
}
fi := run.FirstGlyphAt(rsel.Start)
li := run.LastGlyphAt(rsel.End - 1)
if fi >= 0 && li >= fi {
sbb := run.GlyphRegionBounds(fi, li).Canon()
r.FillBox(idm, sbb.Translate(off), fill)
}
}
}
// textRunRegions draws region fills for given run.
func (r *PDF) textRunRegions(m math32.Matrix2, run *shapedgt.Run, ln *shaped.Line, lns *shaped.Lines, off math32.Vector2) {
idm := math32.Identity2()
// dir := run.Direction
rbb := run.MaxBounds.Translate(off)
if run.Background != nil {
r.FillBox(idm, rbb, run.Background)
}
r.textRegionFill(m, run, off, lns.SelectionColor, ln.Selections)
r.textRegionFill(m, run, off, lns.HighlightColor, ln.Highlights)
}
// textRun rasterizes the given text run into the output image using the
// font face set in the shaping.
// The text will be drawn starting at the start pixel position.
func (r *PDF) textRun(style *styles.Paint, _ math32.Matrix2, run *shapedgt.Run, _ *shaped.Line, lns *shaped.Lines, runes []rune, clr image.Image, off math32.Vector2) {
// dir := run.Direction
region := run.Runes()
rbb := run.MaxBounds.Translate(off)
fill := clr
if run.FillColor != nil {
fill = run.FillColor
}
fsz := math32.FromFixed(run.Size)
lineW := max(fsz/16, 1) // 1 at 16, bigger if biggerr
if run.Math.Path != nil {
r.w.PushTransform(math32.Translate2D(off.X, off.Y))
psty := *style
psty.Stroke.Color = run.StrokeColor
psty.Fill.Color = fill
r.Path(run.Math.Path, &psty, math32.Identity2())
r.w.PopStack()
return
}
sty := run.Font.Style(&style.Text)
// https://en.wikipedia.org/wiki/Subscript_and_superscript: latex does -.14 sub, .25 super
// others often use -.33 and .33
switch sty.Special {
case rich.Super:
off.X += 0.05 * fsz // tends to be cramped otherwise
off.Y -= 0.25 * fsz
case rich.Sub:
off.X += 0.05 * fsz // tends to be cramped otherwise
off.Y += 0.14 * fsz
}
idm := math32.Identity2()
if run.Decoration.HasFlag(rich.Underline) || run.Decoration.HasFlag(rich.DottedUnderline) {
dash := []float32{2, 2}
if run.Decoration.HasFlag(rich.Underline) {
dash = nil
}
if run.Direction.IsVertical() {
} else {
dec := off.Y + 3
r.strokeTextLine(idm, math32.Vec2(rbb.Min.X, dec), math32.Vec2(rbb.Max.X, dec), lineW, fill, dash)
}
}
if run.Decoration.HasFlag(rich.Overline) {
if run.Direction.IsVertical() {
} else {
dec := off.Y - 0.7*rbb.Size().Y
r.strokeTextLine(idm, math32.Vec2(rbb.Min.X, dec), math32.Vec2(rbb.Max.X, dec), lineW, fill, nil)
}
}
r.w.StartTextObject(math32.Translate2D(off.X, off.Y))
r.setTextStyle(&run.Font, style, fill, run.StrokeColor, math32.FromFixed(run.Size), lns.LineHeight)
raw := string(runes[region.Start:region.End])
raw = strings.ReplaceAll(raw, "https://", "https.//") // links need to be obfuscated, to prevent PDF auto-link detection!
raw = strings.ReplaceAll(raw, "http://", "http.//") // links need to be obfuscated, to prevent PDF auto-link detection!
raw = strings.ReplaceAll(raw, "www.", "www:")
raw = strings.ReplaceAll(raw, "doi.", "doi:")
r.w.WriteText(raw)
r.w.EndTextObject()
if run.Decoration.HasFlag(rich.LineThrough) {
if run.Direction.IsVertical() {
} else {
dec := off.Y - 0.2*rbb.Size().Y
r.strokeTextLine(idm, math32.Vec2(rbb.Min.X, dec), math32.Vec2(rbb.Max.X, dec), lineW, fill, nil)
}
}
}
// setTextStrokeColor sets the text stroke color. Returns false
// if stroke color is fully transparent and thus should not be rendered.
func (r *PDF) setTextStrokeColor(clr image.Image) bool {
sc := r.w.style().Stroke
if x, ok := clr.(*image.Uniform); ok {
c := colors.ApplyOpacity(colors.AsRGBA(x), sc.Opacity)
if c.A == 0 { // fully transparent
return false
}
}
sc.Color = clr
r.w.SetStroke(&sc, math32.Box2{}, math32.Identity2())
return true
}
func (r *PDF) setTextFillColor(clr image.Image) {
fc := r.w.style().Fill
fc.Color = clr
r.w.SetFill(&fc, math32.Box2{}, math32.Identity2())
}
// setTextStyle applies the given styles.
func (r *PDF) setTextStyle(fnt *text.Font, style *styles.Paint, fill, stroke image.Image, _, _ float32) {
tsty := &style.Text
sty := fnt.Style(tsty)
r.w.SetFont(sty, tsty)
mode := 0
hasStroke := false
if stroke != nil {
hasStroke = r.setTextStrokeColor(stroke)
}
if fill != nil {
r.setTextFillColor(fill)
if hasStroke {
mode = 2
}
} else {
if hasStroke {
mode = 1
}
}
r.w.SetTextRenderMode(mode)
}
// strokeTextLine strokes a line for text decoration.
func (r *PDF) strokeTextLine(m math32.Matrix2, sp, ep math32.Vector2, width float32, clr image.Image, dash []float32) {
sty := styles.NewPaint()
sty.Fill.Color = nil
sty.Stroke.Width.Dots = width
sty.Stroke.Color = clr
sty.Stroke.Dashes = dash
p := ppath.New().Line(sp.X, sp.Y, ep.X, ep.Y)
r.Path(*p, sty, m)
}
// FillBox fills a box in the given color.
func (r *PDF) FillBox(m math32.Matrix2, bb math32.Box2, clr image.Image) {
sty := styles.NewPaint()
sty.Stroke.Color = nil
sty.Fill.Color = clr
sz := bb.Size()
p := ppath.New().Rectangle(bb.Min.X, bb.Min.Y, sz.X, sz.Y)
r.Path(*p, sty, m)
}
func (r *PDF) links(lns *shaped.Lines, m math32.Matrix2, pos math32.Vector2) {
lks := lns.GetLinks()
for _, lk := range lks {
// note: link coordinates are in default user space, not current transform.
srb := lns.RuneBounds(lk.Range.Start)
erb := lns.RuneBounds(lk.Range.End)
rb := srb
if erb.Max.X > srb.Max.X {
rb.Max.X = erb.Max.X
} else {
rb.Max.X = lns.Bounds.Max.X
}
rb = rb.Translate(pos)
rb = rb.MulMatrix2(m)
r.w.AddLink(lk.URL, rb)
}
}
// SetFont sets the font.
func (w *pdfPage) SetFont(sty *rich.Style, tsty *text.Style) error {
if !w.inTextObject {
return errors.Log(errors.New("pdfWriter: must be in text object"))
}
size := tsty.FontHeight(sty) // * w.pdf.globalScale
ref := w.pdf.getFont(sty, tsty)
if _, ok := w.resources["Font"]; !ok {
w.resources["Font"] = pdfDict{}
} else {
for name, fontRef := range w.resources["Font"].(pdfDict) {
if ref == fontRef {
fmt.Fprintf(w, " /%v %v Tf", name, dec(size))
return nil
}
}
}
name := pdfName(fmt.Sprintf("F%d", len(w.resources["Font"].(pdfDict))))
w.resources["Font"].(pdfDict)[name] = ref
fmt.Fprintf(w, " /%v %v Tf", name, dec(size))
return nil
}
// SetTextPosition sets the text offset position.
func (w *pdfPage) SetTextPosition(off math32.Vector2) error {
if !w.inTextObject {
return errors.Log(errors.New("pdfWriter: must be in text object"))
}
do := off.Sub(w.textPosition)
// and finally apply an offset from there, in reverse for Y
fmt.Fprintf(w, " %v %v Td", dec(do.X), dec(-do.Y))
w.textPosition = off
return nil
}
// SetTextRenderMode sets the text rendering mode.
// 0 = fill text, 1 = stroke text, 2 = fill, then stroke.
// higher numbers support clip path.
func (w *pdfPage) SetTextRenderMode(mode int) error {
if !w.inTextObject {
return errors.Log(errors.New("pdfWriter: must be in text object"))
}
fmt.Fprintf(w, " %d Tr", mode)
w.textRenderMode = mode
return nil
}
// SetTextCharSpace sets the text character spacing.
func (w *pdfPage) SetTextCharSpace(space float32) error {
if !w.inTextObject {
return errors.Log(errors.New("pdfWriter: must be in text object"))
}
fmt.Fprintf(w, " %v Tc", dec(space))
w.textCharSpace = space
return nil
}
// StartTextObject starts a text object, adding to the graphics
// CTM transform matrix as given by the arg, and setting an inverting
// text transform, so text is rendered upright.
func (w *pdfPage) StartTextObject(m math32.Matrix2) error {
if w.inTextObject {
return errors.Log(errors.New("pdfWriter: already in text object"))
}
// set the graphics transform to m first
w.PushTransform(m)
fmt.Fprintf(w, " BT")
// then apply an inversion text matrix
tm := math32.Scale2D(1, -1)
fmt.Fprintf(w, " %s Tm", mat2(tm))
w.inTextObject = true
w.textPosition = math32.Vector2{}
return nil
}
// EndTextObject ends a text object.
func (w *pdfPage) EndTextObject() error {
if !w.inTextObject {
return errors.Log(errors.New("pdfWriter: must be in text object"))
}
fmt.Fprintf(w, " ET")
w.PopStack()
w.inTextObject = false
return nil
}
// WriteText writes text using current text style.
func (w *pdfPage) WriteText(tx string) error {
if !w.inTextObject {
return errors.Log(errors.New("pdfWriter: must be in text object"))
}
if len(tx) == 0 {
return nil
}
first := true
write := func(s string) {
if first {
fmt.Fprintf(w, "(")
first = false
} else {
fmt.Fprintf(w, " (")
}
for _, r := range s {
c, ok := charmap.Windows1252.EncodeRune(r)
if !ok {
if '\u2000' <= r && r <= '\u200A' {
c = ' '
}
}
switch c {
case '\n':
w.WriteByte('\\')
w.WriteByte('n')
case '\r':
w.WriteByte('\\')
w.WriteByte('r')
case '\t':
w.WriteByte('\\')
w.WriteByte('t')
case '\b':
w.WriteByte('\\')
w.WriteByte('b')
case '\f':
w.WriteByte('\\')
w.WriteByte('f')
case '\\', '(', ')':
w.WriteByte('\\')
w.WriteByte(c)
default:
w.WriteByte(c)
}
}
fmt.Fprintf(w, ")")
}
fmt.Fprintf(w, "[")
write(tx)
fmt.Fprintf(w, "]TJ")
return nil
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This is adapted from https://github.com/tdewolff/canvas
// Copyright (c) 2015 Taco de Wolff, under an MIT License.
package pdf
import (
"bytes"
"compress/zlib"
"encoding/ascii85"
"fmt"
"image"
"io"
"math"
"slices"
"sort"
"strings"
"time"
"unicode/utf16"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint/ppath"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/units"
"golang.org/x/exp/maps"
)
// TODO: Invalid graphics transparency, Group has a transparency S entry or the S entry is null
// TODO: Invalid Color space, The operator "g" can't be used without Color Profile
type pdfWriter struct {
w io.Writer
err error
unitContext units.Context
globalScale float32 // global unit conversion
pos int
objOffsets []int
pages []pdfRef
page *pdfPage
fontsStd map[string]pdfRef
// todo: for custom fonts:
// fontSubset map[*text.Font]*ppath.FontSubsetter
// fontsH map[*text.Font]pdfRef
// fontsV map[*text.Font]pdfRef
images map[image.Image]pdfRef
layers pdfLayers
anchors pdfMap // things that can be linked to within doc
outlines []*pdfOutline
compress bool
subset bool
title string
subject string
keywords string
author string
creator string
lang string
}
func newPDFWriter(writer io.Writer, un *units.Context) *pdfWriter {
w := &pdfWriter{
w: writer,
unitContext: *un,
objOffsets: []int{0, 0, 0}, // catalog, metadata, page tree
fontsStd: map[string]pdfRef{},
// fontSubset: map[*text.Font]*ppath.FontSubsetter{},
// fontsH: map[*text.Font]pdfRef{},
// fontsV: map[*text.Font]pdfRef{},
images: map[image.Image]pdfRef{},
compress: false,
subset: true,
}
w.layerInit()
w.globalScale = w.unitContext.Convert(1, units.UnitDot, units.UnitPt)
w.write("%%PDF-1.7\n%%Ŧǟċơ\n")
return w
}
// SetCompression enable the compression of the streams.
func (w *pdfWriter) SetCompression(compress bool) {
w.compress = compress
}
// SeFontSubsetting enables the subsetting of embedded fonts.
func (w *pdfWriter) SetFontSubsetting(subset bool) {
w.subset = subset
}
// SetTitle sets the document's title.
func (w *pdfWriter) SetTitle(title string) {
w.title = title
}
// SetSubject sets the document's subject.
func (w *pdfWriter) SetSubject(subject string) {
w.subject = subject
}
// SetKeywords sets the document's keywords.
func (w *pdfWriter) SetKeywords(keywords string) {
w.keywords = keywords
}
// SetAuthor sets the document's author.
func (w *pdfWriter) SetAuthor(author string) {
w.author = author
}
// SetCreator sets the document's creator.
func (w *pdfWriter) SetCreator(creator string) {
w.creator = creator
}
// SetLang sets the document's language.
func (w *pdfWriter) SetLang(lang string) {
w.lang = lang
}
func (w *pdfWriter) writeBytes(b []byte) {
if w.err != nil {
return
}
n, err := w.w.Write(b)
w.pos += n
w.err = err
}
func (w *pdfWriter) write(s string, v ...any) {
if w.err != nil {
return
}
n, err := fmt.Fprintf(w.w, s, v...)
w.pos += n
w.err = err
}
type pdfRef int
type pdfName string
type pdfArray []any
type pdfDict map[pdfName]any
type pdfMap map[string]any
type pdfFilter string
type pdfStream struct {
dict pdfDict
stream []byte
}
const (
pdfFilterASCII85 pdfFilter = "ASCII85Decode"
pdfFilterFlate pdfFilter = "FlateDecode"
pdfFilterDCT pdfFilter = "DCTDecode"
)
func pdfValContinuesName(val any) bool {
switch val.(type) {
case string, pdfName, pdfFilter, pdfArray, pdfDict, pdfStream:
return false
}
return true
}
func (w *pdfWriter) writeVal(i any) {
switch v := i.(type) {
case bool:
if v {
w.write("true")
} else {
w.write("false")
}
case int:
w.write("%d", v)
case dec:
w.write("%v", v)
case float32:
w.write("%v", dec(v))
case float64:
w.write("%v", dec(v))
case string:
w.write("(%v)", escape(v))
case pdfRef:
w.write("%v 0 R", v)
case pdfName, pdfFilter:
w.write("/%v", v)
case pdfArray:
w.write("[")
for j, val := range v {
if j != 0 {
w.write(" ")
}
w.writeVal(val)
}
w.write("]")
case pdfDict:
w.write("<<")
if val, ok := v["Type"]; ok {
w.write("/Type")
if pdfValContinuesName(val) {
w.write(" ")
}
w.writeVal(val)
}
if val, ok := v["Subtype"]; ok {
w.write("/Subtype")
if pdfValContinuesName(val) {
w.write(" ")
}
w.writeVal(val)
}
if val, ok := v["S"]; ok {
w.write("/S")
if pdfValContinuesName(val) {
w.write(" ")
}
w.writeVal(val)
}
keys := []string{}
for key := range v {
if key != "Type" && key != "Subtype" && key != "S" {
keys = append(keys, string(key))
}
}
sort.Strings(keys)
for _, key := range keys {
w.writeVal(pdfName(key))
if pdfValContinuesName(v[pdfName(key)]) {
w.write(" ")
}
w.writeVal(v[pdfName(key)])
}
w.write(">>")
case pdfMap:
w.write("<<")
keys := maps.Keys(v)
sort.Strings(keys)
nk := len(keys)
for i, key := range keys {
w.writeVal(pdfName(key))
w.write(" ")
w.writeVal(v[key])
if i < nk-1 {
w.write(" ")
}
}
w.write(">>")
case pdfStream:
if v.dict == nil {
v.dict = pdfDict{}
}
filters := []pdfFilter{}
if filter, ok := v.dict["Filter"].(pdfFilter); ok {
filters = append(filters, filter)
} else if filterArray, ok := v.dict["Filter"].(pdfArray); ok {
for ri := len(filterArray) - 1; ri >= 0; ri-- {
f := filterArray[ri]
if filter, ok := f.(pdfFilter); ok {
filters = append(filters, filter)
}
}
}
b := v.stream
for _, filter := range filters {
var b2 bytes.Buffer
switch filter {
case pdfFilterASCII85:
w := ascii85.NewEncoder(&b2)
w.Write(b)
w.Close()
fmt.Fprintf(&b2, "~>")
b = b2.Bytes()
case pdfFilterFlate:
w := zlib.NewWriter(&b2)
w.Write(b)
w.Close()
b = b2.Bytes()
default:
// assume already in the right format
}
}
v.dict["Length"] = len(b)
w.writeVal(v.dict)
w.write("stream\n")
w.writeBytes(b)
w.write("\nendstream\n")
default:
// panic(fmt.Sprintf("unknown PDF type %T", i))
}
}
func (w *pdfWriter) writeObject(val any) pdfRef {
// newlines before and after obj and endobj are required by PDF/A
w.objOffsets = append(w.objOffsets, w.pos)
w.write("%v 0 obj\n", len(w.objOffsets))
w.writeVal(val)
w.write("\nendobj\n")
return pdfRef(len(w.objOffsets))
}
// Close finished the document.
func (w *pdfWriter) Close() error {
if w.page != nil {
w.pages = append(w.pages, w.page.writePage(pdfRef(3)))
}
kids := pdfArray{}
for _, page := range w.pages {
kids = append(kids, page)
}
// write fonts
// w.writeFonts(w.fontsH, false)
// w.writeFonts(w.fontsV, false)
// document catalog
catalog := pdfDict{
"Type": pdfName("Catalog"),
"Pages": pdfRef(3),
}
if len(w.anchors) > 0 {
ancrefs := pdfMap{}
var nms []string
for nm, v := range w.anchors {
vary := v.(pdfArray)
vary[0] = w.pages[vary[0].(int)] // replace page no with ref
anc := w.writeObject(pdfDict{"D": vary})
ancrefs[nm] = anc
nms = append(nms, nm)
}
slices.Sort(nms)
var nmary pdfArray
for _, nm := range nms {
nmary = append(nmary, nm, ancrefs[nm])
}
nmref := w.writeObject(pdfDict{"Names": nmary})
catalog[pdfName("Names")] = pdfDict{"Dests": nmref}
}
if len(w.outlines) > 0 {
firstRef := w.writeOutlines()
first := w.outlines[0]
cdict := w.writeObject(pdfDict{
"Type": pdfName("Outlines"),
"First": firstRef,
"Last": firstRef + pdfRef(first.last),
"Count": len(w.outlines),
})
catalog[pdfName("Outlines")] = cdict
}
if len(w.layers.list) > 0 {
var refs, off pdfArray
for _, l := range w.layers.list {
refs = append(refs, l.ref)
if !l.visible {
off = append(off, l.ref)
}
}
catalog[pdfName("OCProperties")] = pdfDict{
"OCGs": refs,
"D": pdfDict{"OFF": off, "Order": refs},
}
if w.layers.openLayerPane {
catalog[pdfName("PageMode")] = pdfName("UseOC")
}
}
// document info
info := pdfDict{
"Producer": "cogentcore/pdf",
"CreationDate": time.Now().Format("D:20060102150405Z0700"),
}
encode := func(s string) string {
// TODO: make clean
ascii := true
for _, r := range s {
if 0x80 <= r {
ascii = false
break
}
}
if ascii {
return s
}
rs := utf16.Encode([]rune(s))
b := make([]byte, 2+2*len(rs))
b[0] = 254
b[1] = 255
for i, r := range rs {
b[2+2*i+0] = byte(r >> 8)
b[2+2*i+1] = byte(r & 0x00FF)
}
return string(b)
}
if w.title != "" {
info["Title"] = encode(w.title)
}
if w.subject != "" {
info["Subject"] = encode(w.subject)
}
if w.keywords != "" {
info["Keywords"] = encode(w.keywords)
}
if w.author != "" {
info["Author"] = encode(w.author)
}
if w.creator != "" {
info["Creator"] = encode(w.creator)
}
if w.lang != "" {
catalog["Lang"] = encode(w.lang)
}
// document catalog
w.objOffsets[0] = w.pos
w.write("%v 0 obj\n", 1)
w.writeVal(catalog)
w.write("\nendobj\n")
// document info
w.objOffsets[1] = w.pos
w.write("%v 0 obj\n", 2)
w.writeVal(info)
w.write("\nendobj\n")
// page tree
w.objOffsets[2] = w.pos
w.write("%v 0 obj\n", 3)
w.writeVal(pdfDict{
"Type": pdfName("Pages"),
"Kids": pdfArray(kids),
"Count": len(kids),
})
w.write("\nendobj\n")
xrefOffset := w.pos
w.write("xref\n0 %d\n0000000000 65535 f \n", len(w.objOffsets)+1)
for _, objOffset := range w.objOffsets {
w.write("%010d 00000 n \n", objOffset)
}
w.write("trailer\n")
w.writeVal(pdfDict{
"Root": pdfRef(1),
"Size": len(w.objOffsets) + 1,
"Info": pdfRef(2),
// TODO: write document ID
})
w.write("\nstartxref\n%v\n%%%%EOF\n", xrefOffset)
return w.err
}
// NewPage starts a new page.
func (w *pdfWriter) NewPage(width, height float32) *pdfPage {
if w.page != nil {
w.pages = append(w.pages, w.page.writePage(pdfRef(3)))
}
// for defaults see https://help.adobe.com/pdfl_sdk/15/PDFL_SDK_HTMLHelp/PDFL_SDK_HTMLHelp/API_References/PDFL_API_Reference/PDFEdit_Layer/General.html#_t_PDEGraphicState
w.page = &pdfPage{
Buffer: &bytes.Buffer{},
pdf: w,
width: width,
height: height,
pageNo: len(w.pages),
resources: pdfDict{},
graphicsStates: map[float32]pdfName{},
inTextObject: false,
textPosition: math32.Vector2{},
textCharSpace: 0.0,
textRenderMode: 0,
}
w.page.stack.Push(newContext(styles.NewPaint(), math32.Identity2()))
w.page.setTopTransform()
// fmt.Println("added page:", w.page.pageNo)
return w.page
}
// setTopTransform sets the current transformation matrix so that
// the top left corner is effectively at 0,0. This is set at the
// start of each page, to align with standard rendering in cogent core.
func (w *pdfPage) setTopTransform() {
sc := w.pdf.globalScale
m := math32.Translate2D(0, w.height).Scale(sc, -sc)
w.SetTransform(m)
}
// dec efficiently prints float values.
type dec float32
func (f dec) String() string {
s := fmt.Sprintf("%.*f", 5, f) // precision
s = string(ppath.MinifyDecimal([]byte(s), ppath.Precision))
if dec(math.MaxInt32) < f || f < dec(math.MinInt32) {
if i := strings.IndexByte(s, '.'); i == -1 {
s += ".0"
}
}
return s
}
// mat2 returns matrix components as a string
func mat2(m math32.Matrix2) string {
return fmt.Sprintf("%v %v %v %v %v %v", dec(m.XX), dec(m.XY), dec(m.YX), dec(m.YY), dec(m.X0), dec(m.Y0))
}
// Escape special characters in strings
func escape(s string) string {
s = strings.ReplaceAll(s, "\\", "\\\\")
s = strings.ReplaceAll(s, "(", "\\(")
s = strings.ReplaceAll(s, ")", "\\)")
s = strings.ReplaceAll(s, "\r", "\\r")
return s
}
// utf8toutf16 converts UTF-8 to UTF-16BE; from http://www.fpdf.org/
func utf8toutf16(s string, withBOM ...bool) string {
bom := true
if len(withBOM) > 0 {
bom = withBOM[0]
}
res := make([]byte, 0, 8)
if bom {
res = append(res, 0xFE, 0xFF)
}
nb := len(s)
i := 0
for i < nb {
c1 := byte(s[i])
i++
switch {
case c1 >= 224:
// 3-byte character
c2 := byte(s[i])
i++
c3 := byte(s[i])
i++
res = append(res, ((c1&0x0F)<<4)+((c2&0x3C)>>2),
((c2&0x03)<<6)+(c3&0x3F))
case c1 >= 192:
// 2-byte character
c2 := byte(s[i])
i++
res = append(res, ((c1 & 0x1C) >> 2),
((c1&0x03)<<6)+(c2&0x3F))
default:
// Single-byte character
res = append(res, 0, c1)
}
}
return string(res)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package pimage
import (
"image"
"math"
"github.com/anthonynsimon/bild/clone"
"github.com/anthonynsimon/bild/convolution"
)
// scipy impl:
// https://github.com/scipy/scipy/blob/4bfc152f6ee1ca48c73c06e27f7ef021d729f496/scipy/ndimage/filters.py#L136
// #L214 has the invocation: radius = Ceil(sigma)
// bild uses:
// math.Exp(-0.5 * (x * x / (2 * radius))
// so sigma = sqrt(radius) / 2
// and radius = sigma * sigma * 2
// GaussianBlurKernel1D returns a 1D Gaussian kernel.
// Sigma is the standard deviation,
// and the radius of the kernel is 4 * sigma.
func GaussianBlurKernel1D(sigma float64) *convolution.Kernel {
sigma2 := sigma * sigma
sfactor := -0.5 / sigma2
radius := math.Ceil(4 * sigma) // truncate = 4 in scipy
length := 2*int(radius) + 1
// Create the 1-d gaussian kernel
k := convolution.NewKernel(length, 1)
for i, x := 0, -radius; i < length; i, x = i+1, x+1 {
k.Matrix[i] = math.Exp(sfactor * (x * x))
}
return k
}
// GaussianBlur returns a smoothly blurred version of the image using
// a Gaussian function. Sigma is the standard deviation of the Gaussian
// function, and a kernel of radius = 4 * Sigma is used.
func GaussianBlur(src image.Image, sigma float64) *image.RGBA {
if sigma <= 0 {
return clone.AsRGBA(src)
}
k := GaussianBlurKernel1D(sigma).Normalized()
// Perform separable convolution
options := convolution.Options{Bias: 0, Wrap: false, KeepAlpha: false}
result := convolution.Convolve(src, k, &options)
result = convolution.Convolve(result, k.Transposed(), &options)
return result
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package pimage provides the render items for drawing images (drawing,
// transforming, and blurring them), and image utilities.
package pimage
//go:generate core generate
import (
"image"
"cogentcore.org/core/base/iox/imagex"
"cogentcore.org/core/math32"
"golang.org/x/image/draw"
"golang.org/x/image/math/f64"
)
// Cmds are possible commands to perform for [Params].
type Cmds int32 //enums:enum
const (
// Draw Source image using draw.Draw equivalent function,
// without any transformation. If Mask is non-nil it is used.
Draw Cmds = iota
// Draw Source image with transform. If Mask is non-nil, it is used.
Transform
// blurs the Rect region with the given blur radius.
// The blur radius passed to this function is the actual Gaussian
// standard deviation (σ).
Blur
// Sets pixel from Source image at Pos
SetPixel
)
// Params for image operations. This is a Render Item.
type Params struct {
// Command to perform.
Cmd Cmds
// Rect is the rectangle to draw into. This is the bounds for Transform source.
// If empty, the entire destination image Bounds() are used.
Rect image.Rectangle
// SourcePos is the position for the source image in Draw,
// and the location for SetPixel.
SourcePos image.Point
// Draw operation: Src or Over
Op draw.Op
// Source to draw.
Source image.Image
// Original is the original source image, which is used for
// high-resolution renderers (e.g., PDF).
Original image.Image
// Mask, used if non-nil.
Mask image.Image
// MaskPos is the position for the mask
MaskPos image.Point
// Transform for image transform, just for the image.
Transform math32.Matrix2
// Cumulative is the cumulative image transform including all prior transforms.
Cumulative math32.Matrix2
// BlurRadius is the Gaussian standard deviation for Blur function
BlurRadius float32
// Anchor provides a named link destination associated with this text item.
// Used for document navigation, e.g., in PDF rendering. Must be a unique name.
// Is set in [core.Text] based on the id property, which is set by [content].
Anchor string
}
func (pr *Params) IsRenderItem() {}
func (pr *Params) String() string {
return "image: " + pr.Cmd.String()
}
// NewClear returns a new Clear that renders entire image with given source image.
func NewClear(src image.Image, sp image.Point, op draw.Op) *Params {
pr := &Params{Cmd: Draw, Rect: image.Rectangle{}, Source: imagex.WrapJS(src), SourcePos: sp, Op: op}
return pr
}
// NewDraw returns a new Draw operation with given parameters.
// Does nothing if rect is empty.
func NewDraw(rect image.Rectangle, src, orig image.Image, sp image.Point, op draw.Op) *Params {
if rect == (image.Rectangle{}) {
return nil
}
pr := &Params{Cmd: Draw, Rect: rect, Source: imagex.WrapJS(src), Original: orig, SourcePos: sp, Op: op}
return pr
}
// NewDrawMask returns a new DrawMask operation with given parameters.
// Does nothing if rect is empty.
func NewDrawMask(rect image.Rectangle, src, orig image.Image, sp image.Point, op draw.Op, mask image.Image, mp image.Point) *Params {
if rect == (image.Rectangle{}) {
return nil
}
pr := &Params{Cmd: Draw, Rect: rect, Source: imagex.WrapJS(src), Original: orig, SourcePos: sp, Op: op, Mask: imagex.WrapJS(mask), MaskPos: mp}
return pr
}
// NewTransform returns a new Transform operation with given parameters,
// where m is the specific Transform for the image, and cm is the Cumulative including it.
// Does nothing if rect is empty.
func NewTransform(m, cm math32.Matrix2, rect image.Rectangle, src, orig image.Image, op draw.Op) *Params {
if rect == (image.Rectangle{}) {
return nil
}
pr := &Params{Cmd: Transform, Transform: m, Cumulative: cm, Rect: rect, Source: imagex.WrapJS(src), Original: orig, Op: op}
return pr
}
// NewTransformMask returns a new Transform Mask operation with given parameters.
// where m is the specific Transform for the image, and cm is the Cumulative including it.
// Does nothing if rect is empty.
func NewTransformMask(m, cm math32.Matrix2, rect image.Rectangle, src, orig image.Image, op draw.Op, mask image.Image, mp image.Point) *Params {
if rect == (image.Rectangle{}) {
return nil
}
pr := &Params{Cmd: Transform, Transform: m, Cumulative: cm, Rect: rect, Source: imagex.WrapJS(src), Original: orig, Op: op, Mask: imagex.WrapJS(mask), MaskPos: mp}
return pr
}
// NewBlur returns a new Blur operation with given parameters.
// Does nothing if rect is empty.
func NewBlur(rect image.Rectangle, blurRadius float32) *Params {
if rect == (image.Rectangle{}) {
return nil
}
pr := &Params{Cmd: Blur, Rect: rect, BlurRadius: blurRadius}
return pr
}
// NewSetPixel returns a new SetPixel operation with given parameters.
func NewSetPixel(at image.Point, clr image.Image) *Params {
pr := &Params{Cmd: SetPixel, SourcePos: at, Source: clr}
return pr
}
// transparent returns whether the given image is a uniform transparent
// color.
func transparent(src image.Image) bool {
u, ok := imagex.Unwrap(src).(*image.Uniform)
if !ok {
return false
}
_, _, _, a := u.RGBA()
return a == 0
}
// Render performs the image operation on given destination image.
// This uses the native Go image package draw function.
func (pr *Params) Render(dest *image.RGBA) {
switch pr.Cmd {
case Draw:
if pr.Op == draw.Over && transparent(pr.Source) {
// (it changes nothing, but draw blends each pixel: the
// transparent backgrounds of web pages, as of nytimes.com,
// took most of the time of rendering them)
return
}
if pr.Rect == (image.Rectangle{}) {
pr.Rect = dest.Bounds()
}
if pr.Mask != nil {
draw.DrawMask(dest, pr.Rect, imagex.Unwrap(pr.Source), pr.SourcePos, imagex.Unwrap(pr.Mask), pr.MaskPos, pr.Op)
} else {
if pr.Source == nil {
return
}
draw.Draw(dest, pr.Rect, imagex.Unwrap(pr.Source), pr.SourcePos, pr.Op)
}
case Transform:
m := pr.Cumulative
s2d := f64.Aff3{float64(m.XX), float64(m.XY), float64(m.X0), float64(m.YX), float64(m.YY), float64(m.Y0)}
tdraw := draw.BiLinear
if pr.Mask != nil {
tdraw.Transform(dest, s2d, imagex.Unwrap(pr.Source), pr.Rect, pr.Op, &draw.Options{
DstMask: imagex.Unwrap(pr.Mask),
DstMaskP: pr.MaskPos,
})
} else {
tdraw.Transform(dest, s2d, imagex.Unwrap(pr.Source), pr.Rect, pr.Op, nil)
}
case Blur:
sub := dest.SubImage(pr.Rect)
sub = GaussianBlur(sub, float64(pr.BlurRadius))
draw.Draw(dest, pr.Rect, sub, pr.Rect.Min, draw.Src)
case SetPixel:
x := pr.SourcePos.X
y := pr.SourcePos.Y
dest.Set(x, y, imagex.Unwrap(pr.Source).At(x, y))
}
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This is adapted from https://github.com/tdewolff/canvas
// Copyright (c) 2015 Taco de Wolff, under an MIT License.
package ppath
import "cogentcore.org/core/math32"
func QuadraticToCubicBezier(p0, p1, p2 math32.Vector2) (math32.Vector2, math32.Vector2) {
c1 := p0.Lerp(p1, 2.0/3.0)
c2 := p2.Lerp(p1, 2.0/3.0)
return c1, c2
}
func QuadraticBezierDeriv(p0, p1, p2 math32.Vector2, t float32) math32.Vector2 {
p0 = p0.MulScalar(-2.0 + 2.0*t)
p1 = p1.MulScalar(2.0 - 4.0*t)
p2 = p2.MulScalar(2.0 * t)
return p0.Add(p1).Add(p2)
}
func CubicBezierDeriv(p0, p1, p2, p3 math32.Vector2, t float32) math32.Vector2 {
p0 = p0.MulScalar(-3.0 + 6.0*t - 3.0*t*t)
p1 = p1.MulScalar(3.0 - 12.0*t + 9.0*t*t)
p2 = p2.MulScalar(6.0*t - 9.0*t*t)
p3 = p3.MulScalar(3.0 * t * t)
return p0.Add(p1).Add(p2).Add(p3)
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This is adapted from https://github.com/tdewolff/canvas
// Copyright (c) 2015 Taco de Wolff, under an MIT License.
package ppath
import "cogentcore.org/core/math32"
// FastBounds returns the maximum bounding box rectangle of the path.
// It is quicker than Bounds but less accurate.
func (p Path) FastBounds() math32.Box2 {
if len(p) < 4 {
return math32.Box2{}
}
// first command is MoveTo
start, end := math32.Vec2(p[1], p[2]), math32.Vector2{}
xmin, xmax := start.X, start.X
ymin, ymax := start.Y, start.Y
for i := 4; i < len(p); {
cmd := p[i]
switch cmd {
case MoveTo, LineTo, Close:
end = math32.Vec2(p[i+1], p[i+2])
xmin = math32.Min(xmin, end.X)
xmax = math32.Max(xmax, end.X)
ymin = math32.Min(ymin, end.Y)
ymax = math32.Max(ymax, end.Y)
case QuadTo:
cp := math32.Vec2(p[i+1], p[i+2])
end = math32.Vec2(p[i+3], p[i+4])
xmin = math32.Min(xmin, math32.Min(cp.X, end.X))
xmax = math32.Max(xmax, math32.Max(cp.X, end.X))
ymin = math32.Min(ymin, math32.Min(cp.Y, end.Y))
ymax = math32.Max(ymax, math32.Max(cp.Y, end.Y))
case CubeTo:
cp1 := math32.Vec2(p[i+1], p[i+2])
cp2 := math32.Vec2(p[i+3], p[i+4])
end = math32.Vec2(p[i+5], p[i+6])
xmin = math32.Min(xmin, math32.Min(cp1.X, math32.Min(cp2.X, end.X)))
xmax = math32.Max(xmax, math32.Max(cp1.X, math32.Max(cp2.X, end.X)))
ymin = math32.Min(ymin, math32.Min(cp1.Y, math32.Min(cp2.Y, end.Y)))
ymax = math32.Max(ymax, math32.Max(cp1.Y, math32.Max(cp2.Y, end.Y)))
case ArcTo:
var rx, ry, phi float32
var large ArcSize
var sweep ArcSweep
rx, ry, phi, large, sweep, end = p.ArcToPoints(i)
cx, cy, _, _ := EllipseToCenter(start.X, start.Y, rx, ry, phi, ArcSize(large), ArcSweep(sweep), end.X, end.Y)
r := math32.Max(rx, ry)
xmin = math32.Min(xmin, cx-r)
xmax = math32.Max(xmax, cx+r)
ymin = math32.Min(ymin, cy-r)
ymax = math32.Max(ymax, cy+r)
}
i += CmdLen(cmd)
start = end
}
return math32.B2(xmin, ymin, xmax, ymax)
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This is adapted from https://github.com/tdewolff/canvas
// Copyright (c) 2015 Taco de Wolff, under an MIT License.
package ppath
import (
"cogentcore.org/core/math32"
)
func EllipseDeriv(rx, ry, phi float32, sweep ArcSweep, theta float32) math32.Vector2 {
sintheta, costheta := math32.Sincos(theta)
sinphi, cosphi := math32.Sincos(phi)
dx := -rx*sintheta*cosphi - ry*costheta*sinphi
dy := -rx*sintheta*sinphi + ry*costheta*cosphi
if !sweep {
return math32.Vec2(-dx, -dy)
}
return math32.Vec2(dx, dy)
}
// EllipsePos adds the position on the ellipse at angle theta.
func EllipsePos(rx, ry, phi, cx, cy, theta float32) math32.Vector2 {
sintheta, costheta := math32.Sincos(theta)
sinphi, cosphi := math32.Sincos(phi)
x := cx + rx*costheta*cosphi - ry*sintheta*sinphi
y := cy + rx*costheta*sinphi + ry*sintheta*cosphi
return math32.Vec2(x, y)
}
// EllipseToCenter converts to the center arc format and returns
// (centerX, centerY, angleFrom, angleTo) with angles in radians.
// When angleFrom with range [0, 2*PI) is bigger than angleTo with range
// (-2*PI, 4*PI), the ellipse runs clockwise.
// The angles are from before the ellipse has been stretched and rotated.
// See https://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes
func EllipseToCenter(x1, y1, rx, ry, phi float32, large ArcSize, sweep ArcSweep, x2, y2 float32) (float32, float32, float32, float32) {
if Equal(x1, x2) && Equal(y1, y2) {
return x1, y1, 0.0, 0.0
} else if Equal(math32.Abs(x2-x1), rx) && Equal(y1, y2) && Equal(phi, 0.0) {
// common case since circles are defined as two arcs from (+dx,0) to (-dx,0) and back
cx, cy := x1+(x2-x1)/2.0, y1
theta := float32(0.0)
if x1 < x2 {
theta = math32.Pi
}
delta := float32(math32.Pi)
if !sweep {
delta = -delta
}
return cx, cy, theta, theta + delta
}
// compute the half distance between start and end point for the unrotated ellipse
sinphi, cosphi := math32.Sincos(phi)
x1p := cosphi*(x1-x2)/2.0 + sinphi*(y1-y2)/2.0
y1p := -sinphi*(x1-x2)/2.0 + cosphi*(y1-y2)/2.0
// check that radii are large enough to reduce rounding errors
radiiCheck := x1p*x1p/rx/rx + y1p*y1p/ry/ry
if 1.0 < radiiCheck {
radiiScale := math32.Sqrt(radiiCheck)
rx *= radiiScale
ry *= radiiScale
}
// calculate the center point (cx,cy)
sq := (rx*rx*ry*ry - rx*rx*y1p*y1p - ry*ry*x1p*x1p) / (rx*rx*y1p*y1p + ry*ry*x1p*x1p)
if sq <= Epsilon {
// Epsilon instead of 0.0 improves numerical stability for coef near zero
// this happens when start and end points are at two opposites of the ellipse and
// the line between them passes through the center, a common case
sq = 0.0
}
coef := math32.Sqrt(sq)
if bool(large) == bool(sweep) {
coef = -coef
}
cxp := coef * rx * y1p / ry
cyp := coef * -ry * x1p / rx
cx := cosphi*cxp - sinphi*cyp + (x1+x2)/2.0
cy := sinphi*cxp + cosphi*cyp + (y1+y2)/2.0
// specify U and V vectors; theta = arccos(U*V / sqrt(U*U + V*V))
ux := (x1p - cxp) / rx
uy := (y1p - cyp) / ry
vx := -(x1p + cxp) / rx
vy := -(y1p + cyp) / ry
// calculate the start angle (theta) and extent angle (delta)
theta := math32.Acos(ux / math32.Sqrt(ux*ux+uy*uy))
if uy < 0.0 {
theta = -theta
}
theta = AngleNorm(theta)
deltaAcos := (ux*vx + uy*vy) / math32.Sqrt((ux*ux+uy*uy)*(vx*vx+vy*vy))
deltaAcos = math32.Min(1.0, math32.Max(-1.0, deltaAcos))
delta := math32.Acos(deltaAcos)
if ux*vy-uy*vx < 0.0 {
delta = -delta
}
if !sweep && 0.0 < delta { // clockwise in Cartesian
delta -= 2.0 * math32.Pi
} else if sweep && delta < 0.0 { // counter clockwise in Cartesian
delta += 2.0 * math32.Pi
}
return cx, cy, theta, theta + delta
}
// EllipseRadiiCorrection returns the scale of the ellipse radii if rx and ry are too small, see https://www.w3.org/TR/SVG/implnote.html#ArcCorrectionOutOfRangeRadii
func EllipseRadiiCorrection(start math32.Vector2, rx, ry, phi float32, end math32.Vector2) float32 {
diff := start.Sub(end)
sinphi, cosphi := math32.Sincos(phi)
x1p := (cosphi*diff.X + sinphi*diff.Y) / 2.0
y1p := (-sinphi*diff.X + cosphi*diff.Y) / 2.0
return math32.Sqrt(x1p*x1p/rx/rx + y1p*y1p/ry/ry)
}
// see Drawing and elliptical arc using polylines, quadratic or cubic Bézier curves (2003), L. Maisonobe, https://spaceroots.org/documents/ellipse/elliptical-arc.pdf
func ellipseToCubicBeziers(start math32.Vector2, rx, ry, phi float32, large ArcSize, sweep ArcSweep, end math32.Vector2) [][4]math32.Vector2 {
cx, cy, theta0, theta1 := EllipseToCenter(start.X, start.Y, rx, ry, phi, large, sweep, end.X, end.Y)
dtheta := float32(math32.Pi / 2.0) // TODO: use error measure to determine dtheta?
n := int(math32.Ceil(math32.Abs(theta1-theta0) / dtheta))
dtheta = math32.Abs(theta1-theta0) / float32(n) // evenly spread the n points, dalpha will get smaller
kappa := math32.Sin(dtheta) * (math32.Sqrt(4.0+3.0*math32.Pow(math32.Tan(dtheta/2.0), 2.0)) - 1.0) / 3.0
if !sweep {
dtheta = -dtheta
}
beziers := [][4]math32.Vector2{}
startDeriv := EllipseDeriv(rx, ry, phi, sweep, theta0)
for i := 1; i < n+1; i++ {
theta := theta0 + float32(i)*dtheta
end := EllipsePos(rx, ry, phi, cx, cy, theta)
endDeriv := EllipseDeriv(rx, ry, phi, sweep, theta)
cp1 := start.Add(startDeriv.MulScalar(kappa))
cp2 := end.Sub(endDeriv.MulScalar(kappa))
beziers = append(beziers, [4]math32.Vector2{start, cp1, cp2, end})
startDeriv = endDeriv
start = end
}
return beziers
}
// see Drawing and elliptical arc using polylines, quadratic or cubic Bézier curves (2003), L. Maisonobe, https://spaceroots.org/documents/ellipse/elliptical-arc.pdf
func ellipseToQuadraticBeziers(start math32.Vector2, rx, ry, phi float32, large ArcSize, sweep ArcSweep, end math32.Vector2) [][3]math32.Vector2 {
cx, cy, theta0, theta1 := EllipseToCenter(start.X, start.Y, rx, ry, phi, large, sweep, end.X, end.Y)
dtheta := float32(math32.Pi / 2.0) // TODO: use error measure to determine dtheta?
n := int(math32.Ceil(math32.Abs(theta1-theta0) / dtheta))
dtheta = math32.Abs(theta1-theta0) / float32(n) // evenly spread the n points, dalpha will get smaller
kappa := math32.Tan(dtheta / 2.0)
if !sweep {
dtheta = -dtheta
}
beziers := [][3]math32.Vector2{}
startDeriv := EllipseDeriv(rx, ry, phi, sweep, theta0)
for i := 1; i < n+1; i++ {
theta := theta0 + float32(i)*dtheta
end := EllipsePos(rx, ry, phi, cx, cy, theta)
endDeriv := EllipseDeriv(rx, ry, phi, sweep, theta)
cp := start.Add(startDeriv.MulScalar(kappa))
beziers = append(beziers, [3]math32.Vector2{start, cp, end})
startDeriv = endDeriv
start = end
}
return beziers
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This is adapted from https://github.com/tdewolff/canvas
// Copyright (c) 2015 Taco de Wolff, under an MIT License.
package intersect
import (
"cogentcore.org/core/math32"
"cogentcore.org/core/paint/ppath"
)
func cubicBezierDeriv2(p0, p1, p2, p3 math32.Vector2, t float32) math32.Vector2 {
p0 = p0.MulScalar(6.0 - 6.0*t)
p1 = p1.MulScalar(18.0*t - 12.0)
p2 = p2.MulScalar(6.0 - 18.0*t)
p3 = p3.MulScalar(6.0 * t)
return p0.Add(p1).Add(p2).Add(p3)
}
func cubicBezierDeriv3(p0, p1, p2, p3 math32.Vector2, _ float32) math32.Vector2 {
p0 = p0.MulScalar(-6.0)
p1 = p1.MulScalar(18.0)
p2 = p2.MulScalar(-18.0)
p3 = p3.MulScalar(6.0)
return p0.Add(p1).Add(p2).Add(p3)
}
func cubicBezierPos(p0, p1, p2, p3 math32.Vector2, t float32) math32.Vector2 {
p0 = p0.MulScalar(1.0 - 3.0*t + 3.0*t*t - t*t*t)
p1 = p1.MulScalar(3.0*t - 6.0*t*t + 3.0*t*t*t)
p2 = p2.MulScalar(3.0*t*t - 3.0*t*t*t)
p3 = p3.MulScalar(t * t * t)
return p0.Add(p1).Add(p2).Add(p3)
}
func quadraticBezierDeriv2(p0, p1, p2 math32.Vector2) math32.Vector2 {
p0 = p0.MulScalar(2.0)
p1 = p1.MulScalar(-4.0)
p2 = p2.MulScalar(2.0)
return p0.Add(p1).Add(p2)
}
func quadraticBezierPos(p0, p1, p2 math32.Vector2, t float32) math32.Vector2 {
p0 = p0.MulScalar(1.0 - 2.0*t + t*t)
p1 = p1.MulScalar(2.0*t - 2.0*t*t)
p2 = p2.MulScalar(t * t)
return p0.Add(p1).Add(p2)
}
// CubicBezierCurvatureRadius returns the curvature radius, negative when curve bends CW while following t.
func CubicBezierCurvatureRadius(p0, p1, p2, p3 math32.Vector2, t float32) float32 {
dp := ppath.CubicBezierDeriv(p0, p1, p2, p3, t)
ddp := cubicBezierDeriv2(p0, p1, p2, p3, t)
a := dp.Cross(ddp) // negative when bending right ie. curve is CW at this point
if ppath.Equal(a, 0.0) {
return math32.NaN()
}
return math32.Pow(dp.X*dp.X+dp.Y*dp.Y, 1.5) / a
}
// negative when curve bends CW while following t
func quadraticBezierCurvatureRadius(p0, p1, p2 math32.Vector2, t float32) float32 {
dp := ppath.QuadraticBezierDeriv(p0, p1, p2, t)
ddp := quadraticBezierDeriv2(p0, p1, p2)
a := dp.Cross(ddp) // negative when bending right ie. curve is CW at this point
if ppath.Equal(a, 0.0) {
return math32.NaN()
}
return math32.Pow(dp.X*dp.X+dp.Y*dp.Y, 1.5) / a
}
// see https://malczak.linuxpl.com/blog/quadratic-bezier-curve-length/
func quadraticBezierLength(p0, p1, p2 math32.Vector2) float32 {
a := p0.Sub(p1.MulScalar(2.0)).Add(p2)
b := p1.MulScalar(2.0).Sub(p0.MulScalar(2.0))
A := 4.0 * a.Dot(a)
B := 4.0 * a.Dot(b)
C := b.Dot(b)
if ppath.Equal(A, 0.0) {
// p1 is in the middle between p0 and p2, so it is a straight line from p0 to p2
return p2.Sub(p0).Length()
}
Sabc := 2.0 * math32.Sqrt(A+B+C)
A2 := math32.Sqrt(A)
A32 := 2.0 * A * A2
C2 := 2.0 * math32.Sqrt(C)
BA := B / A2
return (A32*Sabc + A2*B*(Sabc-C2) + (4.0*C*A-B*B)*math32.Log((2.0*A2+BA+Sabc)/(BA+C2))) / (4.0 * A32)
}
func findInflectionPointCubicBezier(p0, p1, p2, p3 math32.Vector2) (float32, float32) {
// see www.faculty.idc.ac.il/arik/quality/appendixa.html
// we omit multiplying bx,by,cx,cy with 3.0, so there is no need for divisions when calculating a,b,c
ax := -p0.X + 3.0*p1.X - 3.0*p2.X + p3.X
ay := -p0.Y + 3.0*p1.Y - 3.0*p2.Y + p3.Y
bx := p0.X - 2.0*p1.X + p2.X
by := p0.Y - 2.0*p1.Y + p2.Y
cx := -p0.X + p1.X
cy := -p0.Y + p1.Y
a := (ay*bx - ax*by)
b := (ay*cx - ax*cy)
c := (by*cx - bx*cy)
x1, x2 := solveQuadraticFormula(a, b, c)
if x1 < ppath.Epsilon/2.0 || 1.0-ppath.Epsilon/2.0 < x1 {
x1 = math32.NaN()
}
if x2 < ppath.Epsilon/2.0 || 1.0-ppath.Epsilon/2.0 < x2 {
x2 = math32.NaN()
} else if math32.IsNaN(x1) {
x1, x2 = x2, x1
}
return x1, x2
}
func findInflectionPointRangeCubicBezier(p0, p1, p2, p3 math32.Vector2, t, tolerance float32) (float32, float32) {
// find the range around an inflection point that we consider flat within the flatness criterion
if math32.IsNaN(t) {
return math32.Inf(1), math32.Inf(1)
} else if t < 0.0 || t > 1.0 {
panic("t outside 0.0--1.0 range")
}
// we state that s(t) = 3*s2*t^2 + (s3 - 3*s2)*t^3 (see paper on the r-s coordinate system)
// with s(t) aligned perpendicular to the curve at t = 0
// then we impose that s(tf) = flatness and find tf
// at inflection points however, s2 = 0, so that s(t) = s3*t^3
if !ppath.Equal(t, 0.0) {
_, _, _, _, p0, p1, p2, p3 = cubicBezierSplit(p0, p1, p2, p3, t)
}
nr := p1.Sub(p0)
ns := p3.Sub(p0)
if ppath.Equal(nr.X, 0.0) && ppath.Equal(nr.Y, 0.0) {
// if p0=p1, then rn (the velocity at t=0) needs adjustment
// nr = lim[t->0](B'(t)) = 3*(p1-p0) + 6*t*((p1-p0)+(p2-p1)) + second order terms of t
// if (p1-p0)->0, we use (p2-p1)=(p2-p0)
nr = p2.Sub(p0)
}
if ppath.Equal(nr.X, 0.0) && ppath.Equal(nr.Y, 0.0) {
// if rn is still zero, this curve has p0=p1=p2, so it is straight
return math32.Max(0.0, 2.0*t-1.0), 1.0
}
s3 := math32.Abs(ns.X*nr.Y-ns.Y*nr.X) / math32.Hypot(nr.X, nr.Y)
if ppath.Equal(s3, 0.0) {
return math32.Max(0.0, 2.0*t-1.0), 1.0 // can approximate whole curve linearly
}
tf := math32.Cbrt(tolerance / s3)
return t - tf*(1.0-t), t + tf*(1.0-t)
}
// cubicBezierLength calculates the length of the Bézier, taking care of inflection points. It uses Gauss-Legendre (n=5) and has an error of ~1% or less (empirical).
func cubicBezierLength(p0, p1, p2, p3 math32.Vector2) float32 {
t1, t2 := findInflectionPointCubicBezier(p0, p1, p2, p3)
var beziers [][4]math32.Vector2
if t1 > 0.0 && t1 < 1.0 && t2 > 0.0 && t2 < 1.0 {
p0, p1, p2, p3, q0, q1, q2, q3 := cubicBezierSplit(p0, p1, p2, p3, t1)
t2 = (t2 - t1) / (1.0 - t1)
q0, q1, q2, q3, r0, r1, r2, r3 := cubicBezierSplit(q0, q1, q2, q3, t2)
beziers = append(beziers, [4]math32.Vector2{p0, p1, p2, p3})
beziers = append(beziers, [4]math32.Vector2{q0, q1, q2, q3})
beziers = append(beziers, [4]math32.Vector2{r0, r1, r2, r3})
} else if t1 > 0.0 && t1 < 1.0 {
p0, p1, p2, p3, q0, q1, q2, q3 := cubicBezierSplit(p0, p1, p2, p3, t1)
beziers = append(beziers, [4]math32.Vector2{p0, p1, p2, p3})
beziers = append(beziers, [4]math32.Vector2{q0, q1, q2, q3})
} else {
beziers = append(beziers, [4]math32.Vector2{p0, p1, p2, p3})
}
length := float32(0.0)
for _, bezier := range beziers {
speed := func(t float32) float32 {
return ppath.CubicBezierDeriv(bezier[0], bezier[1], bezier[2], bezier[3], t).Length()
}
length += gaussLegendre7(speed, 0.0, 1.0)
}
return length
}
func quadraticBezierSplit(p0, p1, p2 math32.Vector2, t float32) (math32.Vector2, math32.Vector2, math32.Vector2, math32.Vector2, math32.Vector2, math32.Vector2) {
q0 := p0
q1 := p0.Lerp(p1, t)
r2 := p2
r1 := p1.Lerp(p2, t)
r0 := q1.Lerp(r1, t)
q2 := r0
return q0, q1, q2, r0, r1, r2
}
func cubicBezierSplit(p0, p1, p2, p3 math32.Vector2, t float32) (math32.Vector2, math32.Vector2, math32.Vector2, math32.Vector2, math32.Vector2, math32.Vector2, math32.Vector2, math32.Vector2) {
pm := p1.Lerp(p2, t)
q0 := p0
q1 := p0.Lerp(p1, t)
q2 := q1.Lerp(pm, t)
r3 := p3
r2 := p2.Lerp(p3, t)
r1 := pm.Lerp(r2, t)
r0 := q2.Lerp(r1, t)
q3 := r0
return q0, q1, q2, q3, r0, r1, r2, r3
}
func cubicBezierNumInflections(p0, p1, p2, p3 math32.Vector2) int {
t1, t2 := findInflectionPointCubicBezier(p0, p1, p2, p3)
if !math32.IsNaN(t2) {
return 2
} else if !math32.IsNaN(t1) {
return 1
}
return 0
}
func xmonotoneCubicBezier(p0, p1, p2, p3 math32.Vector2) ppath.Path {
a := -p0.X + 3*p1.X - 3*p2.X + p3.X
b := 2*p0.X - 4*p1.X + 2*p2.X
c := -p0.X + p1.X
p := ppath.Path{}
p.MoveTo(p0.X, p0.Y)
split := false
t1, t2 := solveQuadraticFormula(a, b, c)
if !math32.IsNaN(t1) && inIntervalExclusive(t1, 0.0, 1.0) {
_, q1, q2, q3, r0, r1, r2, r3 := cubicBezierSplit(p0, p1, p2, p3, t1)
p.CubeTo(q1.X, q1.Y, q2.X, q2.Y, q3.X, q3.Y)
p0, p1, p2, p3 = r0, r1, r2, r3
split = true
}
if !math32.IsNaN(t2) && inIntervalExclusive(t2, 0.0, 1.0) {
if split {
t2 = (t2 - t1) / (1.0 - t1)
}
_, q1, q2, q3, _, r1, r2, r3 := cubicBezierSplit(p0, p1, p2, p3, t2)
p.CubeTo(q1.X, q1.Y, q2.X, q2.Y, q3.X, q3.Y)
p1, p2, p3 = r1, r2, r3
}
p.CubeTo(p1.X, p1.Y, p2.X, p2.Y, p3.X, p3.Y)
return p
}
func quadraticBezierDistance(p0, p1, p2, q math32.Vector2) float32 {
f := p0.Sub(p1.MulScalar(2.0)).Add(p2)
g := p1.MulScalar(2.0).Sub(p0.MulScalar(2.0))
h := p0.Sub(q)
a := 4.0 * (f.X*f.X + f.Y*f.Y)
b := 6.0 * (f.X*g.X + f.Y*g.Y)
c := 2.0 * (2.0*(f.X*h.X+f.Y*h.Y) + g.X*g.X + g.Y*g.Y)
d := 2.0 * (g.X*h.X + g.Y*h.Y)
dist := math32.Inf(1.0)
t0, t1, t2 := solveCubicFormula(a, b, c, d)
ts := []float32{t0, t1, t2, 0.0, 1.0}
for _, t := range ts {
if !math32.IsNaN(t) {
if t < 0.0 {
t = 0.0
} else if 1.0 < t {
t = 1.0
}
if tmpDist := quadraticBezierPos(p0, p1, p2, t).Sub(q).Length(); tmpDist < dist {
dist = tmpDist
}
}
}
return dist
}
func xmonotoneQuadraticBezier(p0, p1, p2 math32.Vector2) ppath.Path {
p := ppath.Path{}
p.MoveTo(p0.X, p0.Y)
if tdenom := (p0.X - 2*p1.X + p2.X); !ppath.Equal(tdenom, 0.0) {
if t := (p0.X - p1.X) / tdenom; 0.0 < t && t < 1.0 {
_, q1, q2, _, r1, r2 := quadraticBezierSplit(p0, p1, p2, t)
p.QuadTo(q1.X, q1.Y, q2.X, q2.Y)
p1, p2 = r1, r2
}
}
p.QuadTo(p1.X, p1.Y, p2.X, p2.Y)
return p
}
// CubicBezierNormal returns the normal at the right-side of the curve (when increasing t).
func CubicBezierNormal(p0, p1, p2, p3 math32.Vector2, t, d float32) math32.Vector2 {
// TODO: remove and use CubicBezierDeriv + Rot90CW?
switch t {
case 0.0:
n := p1.Sub(p0)
if n.X == 0 && n.Y == 0 {
n = p2.Sub(p0)
}
if n.X == 0 && n.Y == 0 {
n = p3.Sub(p0)
}
if n.X == 0 && n.Y == 0 {
return math32.Vector2{}
}
return n.Rot90CW().Normal().MulScalar(d)
case 1.0:
n := p3.Sub(p2)
if n.X == 0 && n.Y == 0 {
n = p3.Sub(p1)
}
if n.X == 0 && n.Y == 0 {
n = p3.Sub(p0)
}
if n.X == 0 && n.Y == 0 {
return math32.Vector2{}
}
return n.Rot90CW().Normal().MulScalar(d)
}
panic("not implemented") // not needed
}
func addCubicBezierLine(p *ppath.Path, p0, p1, p2, p3 math32.Vector2, t, d float32) {
if ppath.EqualPoint(p0, p3) && (ppath.EqualPoint(p0, p1) || ppath.EqualPoint(p0, p2)) {
// Bézier has p0=p1=p3 or p0=p2=p3 and thus has no surface or length
return
}
pos := math32.Vector2{}
switch t {
case 0.0:
// line to beginning of path
pos = p0
if d != 0.0 {
n := CubicBezierNormal(p0, p1, p2, p3, t, d)
pos = pos.Add(n)
}
case 1.0:
// line to the end of the path
pos = p3
if d != 0.0 {
n := CubicBezierNormal(p0, p1, p2, p3, t, d)
pos = pos.Add(n)
}
default:
panic("not implemented")
}
p.LineTo(pos.X, pos.Y)
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This is adapted from https://github.com/tdewolff/canvas
// Copyright (c) 2015 Taco de Wolff, under an MIT License.
package intersect
import (
"cogentcore.org/core/math32"
"cogentcore.org/core/paint/ppath"
)
func ellipseDeriv2(rx, ry, phi float32, theta float32) math32.Vector2 {
sintheta, costheta := math32.Sincos(theta)
sinphi, cosphi := math32.Sincos(phi)
ddx := -rx*costheta*cosphi + ry*sintheta*sinphi
ddy := -rx*costheta*sinphi - ry*sintheta*cosphi
return math32.Vec2(ddx, ddy)
}
// ellipseLength calculates the length of the elliptical arc
// it uses Gauss-Legendre (n=5) and has an error of ~1% or less (empirical)
func ellipseLength(rx, ry, theta1, theta2 float32) float32 {
if theta2 < theta1 {
theta1, theta2 = theta2, theta1
}
speed := func(theta float32) float32 {
return ppath.EllipseDeriv(rx, ry, 0.0, ppath.Clockwise, theta).Length()
}
return gaussLegendre5(speed, theta1, theta2)
}
func EllipseCurvatureRadius(rx, ry float32, sweep ppath.ArcSweep, theta float32) float32 {
// positive for ccw / sweep
// phi has no influence on the curvature
dp := ppath.EllipseDeriv(rx, ry, 0.0, sweep, theta)
ddp := ellipseDeriv2(rx, ry, 0.0, theta)
a := dp.Cross(ddp)
if ppath.Equal(a, 0.0) {
return math32.NaN()
}
return math32.Pow(dp.X*dp.X+dp.Y*dp.Y, 1.5) / a
}
// ellipseSplit returns the new mid point, the two large parameters and the ok bool, the rest stays the same
func ellipseSplit(rx, ry, phi, cx, cy, theta0, theta1, theta float32) (math32.Vector2, bool, bool, bool) {
if !ppath.IsAngleBetween(theta, theta0, theta1) {
return math32.Vector2{}, false, false, false
}
mid := ppath.EllipsePos(rx, ry, phi, cx, cy, theta)
large0, large1 := false, false
if math32.Abs(theta-theta0) > math32.Pi {
large0 = true
} else if math32.Abs(theta-theta1) > math32.Pi {
large1 = true
}
return mid, large0, large1, true
}
func xmonotoneEllipticArc(start math32.Vector2, rx, ry, phi float32, large ppath.ArcSize, sweep ppath.ArcSweep, end math32.Vector2) ppath.Path {
sign := float32(1.0)
if !sweep {
sign = -1.0
}
cx, cy, theta0, theta1 := ppath.EllipseToCenter(start.X, start.Y, rx, ry, phi, large, sweep, end.X, end.Y)
sinphi, cosphi := math32.Sincos(phi)
thetaRight := math32.Atan2(-ry*sinphi, rx*cosphi)
thetaLeft := thetaRight + math32.Pi
p := ppath.Path{}
p.MoveTo(start.X, start.Y)
left := !ppath.AngleEqual(thetaLeft, theta0) && ppath.AngleNorm(sign*(thetaLeft-theta0)) < ppath.AngleNorm(sign*(thetaRight-theta0))
for t := theta0; !ppath.AngleEqual(t, theta1); {
dt := ppath.AngleNorm(sign * (theta1 - t))
if left {
dt = math32.Min(dt, ppath.AngleNorm(sign*(thetaLeft-t)))
} else {
dt = math32.Min(dt, ppath.AngleNorm(sign*(thetaRight-t)))
}
t += sign * dt
pos := ppath.EllipsePos(rx, ry, phi, cx, cy, t)
p.ArcTo(rx, ry, phi, ppath.SmallArc, sweep, pos.X, pos.Y)
left = !left
}
return p
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This is adapted from https://github.com/tdewolff/canvas
// Copyright (c) 2015 Taco de Wolff, under an MIT License.
package intersect
import (
"cogentcore.org/core/math32"
"cogentcore.org/core/paint/ppath"
)
// Flatten flattens all Bézier and arc curves into linear segments
// and returns a new path. It uses tolerance as the maximum deviation.
func Flatten(p ppath.Path, tolerance float32) ppath.Path {
quad := func(p0, p1, p2 math32.Vector2) ppath.Path {
return FlattenQuadraticBezier(p0, p1, p2, tolerance)
}
cube := func(p0, p1, p2, p3 math32.Vector2) ppath.Path {
return FlattenCubicBezier(p0, p1, p2, p3, 0.0, tolerance)
}
arc := func(start math32.Vector2, rx, ry, phi float32, large ppath.ArcSize, sweep ppath.ArcSweep, end math32.Vector2) ppath.Path {
return FlattenEllipticArc(start, rx, ry, phi, large, sweep, end, tolerance)
}
return p.Replace(nil, quad, cube, arc)
}
func FlattenEllipticArc(start math32.Vector2, rx, ry, phi float32, large ppath.ArcSize, sweep ppath.ArcSweep, end math32.Vector2, tolerance float32) ppath.Path {
if ppath.Equal(rx, ry) {
// circle
r := rx
cx, cy, theta0, theta1 := ppath.EllipseToCenter(start.X, start.Y, rx, ry, phi, large, sweep, end.X, end.Y)
theta0 += phi
theta1 += phi
// draw line segments from arc+tolerance to arc+tolerance, touching arc-tolerance in between
// we start and end at the arc itself
dtheta := math32.Abs(theta1 - theta0)
thetaEnd := math32.Acos((r - tolerance) / r) // half angle of first/last segment
thetaMid := math32.Acos((r - tolerance) / (r + tolerance)) // half angle of middle segments
n := math32.Ceil((dtheta - thetaEnd*2.0) / (thetaMid * 2.0))
// evenly space out points along arc
ratio := dtheta / (thetaEnd*2.0 + thetaMid*2.0*n)
thetaEnd *= ratio
thetaMid *= ratio
// adjust distance from arc to lower total deviation area, add points on the outer circle
// of the tolerance since the middle of the line segment touches the inner circle and thus
// even out. Ratio < 1 is when the line segments are shorter (and thus not touch the inner
// tolerance circle).
r += ratio * tolerance
p := ppath.Path{}
p.MoveTo(start.X, start.Y)
theta := thetaEnd + thetaMid
for i := 0; i < int(n); i++ {
t := theta0 + math32.Copysign(theta, theta1-theta0)
pos := math32.Vector2Polar(t, r).Add(math32.Vec2(cx, cy))
p.LineTo(pos.X, pos.Y)
theta += 2.0 * thetaMid
}
p.LineTo(end.X, end.Y)
return p
}
// TODO: (flatten ellipse) use direct algorithm
return Flatten(ppath.ArcToCube(start, rx, ry, phi, large, sweep, end), tolerance)
}
func FlattenQuadraticBezier(p0, p1, p2 math32.Vector2, tolerance float32) ppath.Path {
// see Flat, precise flattening of cubic Bézier path and offset curves, by T.F. Hain et al., 2005, https://www.sciencedirect.com/science/article/pii/S0097849305001287
t := float32(0.0)
p := ppath.Path{}
p.MoveTo(p0.X, p0.Y)
for t < 1.0 {
D := p1.Sub(p0)
if ppath.EqualPoint(p0, p1) {
// p0 == p1, curve is a straight line from p0 to p2
// should not occur directly from paths as this is prevented in QuadTo, but may appear in other subroutines
break
}
denom := math32.Hypot(D.X, D.Y) // equal to r1
s2nom := D.Cross(p2.Sub(p0))
//effFlatness := tolerance / (1.0 - d*s2nom/(denom*denom*denom)/2.0)
t = 2.0 * math32.Sqrt(tolerance*math32.Abs(denom/s2nom))
if t >= 1.0 {
break
}
_, _, _, p0, p1, p2 = quadraticBezierSplit(p0, p1, p2, t)
p.LineTo(p0.X, p0.Y)
}
p.LineTo(p2.X, p2.Y)
return p
}
// FlattenCubicBezier returns the cubic Bézier curve flattened into lines,
// offset by d (for strokes), within the given tolerance.
// see Flat, precise flattening of cubic Bézier path and offset curves, by T.F. Hain et al., 2005, https://www.sciencedirect.com/science/article/pii/S0097849305001287
// see https://github.com/Manishearth/stylo-flat/blob/master/gfx/2d/Path.cpp for an example implementation
// or https://docs.rs/crate/lyon_bezier/0.4.1/source/src/flatten_cubic.rs
// p0, p1, p2, p3 are the start points, two control points and the end points respectively. With flatness defined as the maximum error from the orinal curve, and d the half width of the curve used for stroking (positive is to the right).
func FlattenCubicBezier(p0, p1, p2, p3 math32.Vector2, d, tolerance float32) ppath.Path {
tolerance = math32.Max(tolerance, ppath.Epsilon) // prevent infinite loop if user sets tolerance to zero
p := ppath.Path{}
start := p0.Add(CubicBezierNormal(p0, p1, p2, p3, 0.0, d))
p.MoveTo(start.X, start.Y)
// 0 <= t1 <= 1 if t1 exists
// 0 <= t1 <= t2 <= 1 if t1 and t2 both exist
t1, t2 := findInflectionPointCubicBezier(p0, p1, p2, p3)
if math32.IsNaN(t1) && math32.IsNaN(t2) {
// There are no inflection points or cusps, approximate linearly by subdivision.
FlattenSmoothCubicBezier(&p, p0, p1, p2, p3, d, tolerance)
return p
}
// t1min <= t1max; with 0 <= t1max and t1min <= 1
// t2min <= t2max; with 0 <= t2max and t2min <= 1
t1min, t1max := findInflectionPointRangeCubicBezier(p0, p1, p2, p3, t1, tolerance)
t2min, t2max := findInflectionPointRangeCubicBezier(p0, p1, p2, p3, t2, tolerance)
if math32.IsNaN(t2) && t1min <= 0.0 && 1.0 <= t1max {
// There is no second inflection point, and the first inflection point can be entirely approximated linearly.
addCubicBezierLine(&p, p0, p1, p2, p3, 1.0, d)
return p
}
if 0.0 < t1min {
// Flatten up to t1min
q0, q1, q2, q3, _, _, _, _ := cubicBezierSplit(p0, p1, p2, p3, t1min)
FlattenSmoothCubicBezier(&p, q0, q1, q2, q3, d, tolerance)
}
if 0.0 < t1max && t1max < 1.0 && t1max < t2min {
// t1 and t2 ranges do not overlap, approximate t1 linearly
_, _, _, _, q0, q1, q2, q3 := cubicBezierSplit(p0, p1, p2, p3, t1max)
addCubicBezierLine(&p, q0, q1, q2, q3, 0.0, d)
if 1.0 <= t2min {
// No t2 present, approximate the rest linearly by subdivision
FlattenSmoothCubicBezier(&p, q0, q1, q2, q3, d, tolerance)
return p
}
} else if 1.0 <= t2min {
// No t2 present and t1max is past the end of the curve, approximate linearly
addCubicBezierLine(&p, p0, p1, p2, p3, 1.0, d)
return p
}
// t1 and t2 exist and ranges might overlap
if 0.0 < t2min {
if t2min < t1max {
// t2 range starts inside t1 range, approximate t1 range linearly
_, _, _, _, q0, q1, q2, q3 := cubicBezierSplit(p0, p1, p2, p3, t1max)
addCubicBezierLine(&p, q0, q1, q2, q3, 0.0, d)
} else {
// no overlap
_, _, _, _, q0, q1, q2, q3 := cubicBezierSplit(p0, p1, p2, p3, t1max)
t2minq := (t2min - t1max) / (1 - t1max)
q0, q1, q2, q3, _, _, _, _ = cubicBezierSplit(q0, q1, q2, q3, t2minq)
FlattenSmoothCubicBezier(&p, q0, q1, q2, q3, d, tolerance)
}
}
// handle (the rest of) t2
if t2max < 1.0 {
_, _, _, _, q0, q1, q2, q3 := cubicBezierSplit(p0, p1, p2, p3, t2max)
addCubicBezierLine(&p, q0, q1, q2, q3, 0.0, d)
FlattenSmoothCubicBezier(&p, q0, q1, q2, q3, d, tolerance)
} else {
// t2max extends beyond 1
addCubicBezierLine(&p, p0, p1, p2, p3, 1.0, d)
}
return p
}
// FlattenSmoothCubicBezier splits the curve and replaces it by lines as long as (maximum deviation <= tolerance) is maintained.
func FlattenSmoothCubicBezier(p *ppath.Path, p0, p1, p2, p3 math32.Vector2, d, tolerance float32) {
t := float32(0.0)
for t < 1.0 {
D := p1.Sub(p0)
if ppath.EqualPoint(p0, p1) {
// p0 == p1, base on p2
D = p2.Sub(p0)
if ppath.EqualPoint(p0, p2) {
// p0 == p1 == p2, curve is a straight line from p0 to p3
p.LineTo(p3.X, p3.Y)
return
}
}
denom := D.Length() // equal to r1
// effective flatness distorts the stroke width as both sides have different cuts
//effFlatness := flatness / (1.0 - d*s2nom/(denom*denom*denom)*2.0/3.0)
s2nom := D.Cross(p2.Sub(p0))
s2inv := denom / s2nom
t2 := 2.0 * math32.Sqrt(tolerance*math32.Abs(s2inv)/3.0)
// if s2 is small, s3 may represent the curvature more accurately
// we cannot calculate the effective flatness here
s3nom := D.Cross(p3.Sub(p0))
s3inv := denom / s3nom
t3 := 2.0 * math32.Cbrt(tolerance*math32.Abs(s3inv))
// choose whichever is most curved, P2-P0 or P3-P0
t = math32.Min(t2, t3)
if 1.0 <= t {
break
}
_, _, _, _, p0, p1, p2, p3 = cubicBezierSplit(p0, p1, p2, p3, t)
addCubicBezierLine(p, p0, p1, p2, p3, 0.0, d)
}
addCubicBezierLine(p, p0, p1, p2, p3, 1.0, d)
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This is adapted from https://github.com/tdewolff/canvas
// Copyright (c) 2015 Taco de Wolff, under an MIT License.
package intersect
import (
"slices"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint/ppath"
)
// curvature returns the curvature of the path at the given index
// into ppath.Path and t in [0.0,1.0]. ppath.Path must not contain subpaths,
// and will return the path's starting curvature when i points
// to a MoveTo, or the path's final curvature when i points to
// a Close of zero-length.
func curvature(p ppath.Path, i int, t float32) float32 {
last := len(p)
if p[last-1] == ppath.Close && ppath.EqualPoint(math32.Vec2(p[last-ppath.CmdLen(ppath.Close)-3], p[last-ppath.CmdLen(ppath.Close)-2]), math32.Vec2(p[last-3], p[last-2])) {
// point-closed
last -= ppath.CmdLen(ppath.Close)
}
if i == 0 {
// get path's starting direction when i points to MoveTo
i = 4
t = 0.0
} else if i < len(p) && i == last {
// get path's final direction when i points to zero-length Close
i -= ppath.CmdLen(p[i-1])
t = 1.0
}
if i < 0 || len(p) <= i || last < i+ppath.CmdLen(p[i]) {
return 0.0
}
cmd := p[i]
var start math32.Vector2
if i == 0 {
start = math32.Vec2(p[last-3], p[last-2])
} else {
start = math32.Vec2(p[i-3], p[i-2])
}
i += ppath.CmdLen(cmd)
end := math32.Vec2(p[i-3], p[i-2])
switch cmd {
case ppath.LineTo, ppath.Close:
return 0.0
case ppath.QuadTo:
cp := math32.Vec2(p[i-5], p[i-4])
return 1.0 / quadraticBezierCurvatureRadius(start, cp, end, t)
case ppath.CubeTo:
cp1 := math32.Vec2(p[i-7], p[i-6])
cp2 := math32.Vec2(p[i-5], p[i-4])
return 1.0 / CubicBezierCurvatureRadius(start, cp1, cp2, end, t)
case ppath.ArcTo:
rx, ry, phi := p[i-7], p[i-6], p[i-5]
large, sweep := ppath.ToArcFlags(p[i-4])
_, _, theta0, theta1 := ppath.EllipseToCenter(start.X, start.Y, rx, ry, phi, large, sweep, end.X, end.Y)
theta := theta0 + t*(theta1-theta0)
return 1.0 / EllipseCurvatureRadius(rx, ry, sweep, theta)
}
return 0.0
}
// Curvature returns the curvature of the path at the given segment
// and t in [0.0,1.0] along that path. It is zero for straight lines
// and for non-existing segments.
func Curvature(p ppath.Path, seg int, t float32) float32 {
if len(p) <= 4 {
return 0.0
}
// segments are the commands, including each ppath.MoveTo, and the curvature
// is found in the subpath that has the segment.
curSeg := 0
iStart, iSeg := 0, -1
for i := 0; i < len(p); {
cmd := p[i]
if cmd == ppath.MoveTo && 0 < i {
if 0 <= iSeg {
return curvature(p[iStart:i], iSeg-iStart, t)
}
iStart = i
}
if seg == curSeg {
iSeg = i
}
curSeg++
i += ppath.CmdLen(cmd)
}
if 0 <= iSeg {
return curvature(p[iStart:], iSeg-iStart, t)
}
return 0.0 // if segment doesn't exist
}
// windings counts intersections of ray with path.
// ppath.Paths that cross downwards are negative and upwards are positive.
// It returns the windings excluding the start position and the
// windings of the start position itself. If the windings of the
// start position is not zero, the start position is on a boundary.
func windings(zs []Intersection) (int, bool) {
// There are four particular situations to be aware of. Whenever the path is horizontal it
// will be parallel to the ray, and usually overlapping. Either we have:
// - a starting point to the left of the overlapping section: ignore the overlapping
// intersections so that it appears as a regular intersection, albeit at the endpoints
// of two segments, which may either cancel out to zero (top or bottom edge) or add up to
// 1 or -1 if the path goes upwards or downwards respectively before/after the overlap.
// - a starting point on the left-hand corner of an overlapping section: ignore if either
// intersection of an endpoint pair (t=0,t=1) is overlapping, but count for nb upon
// leaving the overlap.
// - a starting point in the middle of an overlapping section: same as above
// - a starting point on the right-hand corner of an overlapping section: intersections are
// tangent and thus already ignored for n, but for nb we should ignore the intersection with
// a 0/180 degree direction, and count the other
n := 0
boundary := false
for i := 0; i < len(zs); i++ {
z := zs[i]
if z.T[0] == 0.0 {
boundary = true
continue
}
d := 1
if z.Into() {
d = -1 // downwards
}
if z.T[1] != 0.0 && z.T[1] != 1.0 {
if !z.Same {
n += d
}
} else if i+1 < len(zs) {
same := z.Same || (len(zs) > i+1 && zs[i+1].Same)
if !same && len(zs) > i+1 {
if z.Into() == zs[i+1].Into() {
n += d
}
}
i++
}
}
return n, boundary
}
// Windings returns the number of windings at the given point,
// i.e. the sum of windings for each time a ray from (x,y)
// towards (∞,y) intersects the path. Counter clock-wise
// intersections count as positive, while clock-wise intersections
// count as negative. Additionally, it returns whether the point
// is on a path's boundary (which counts as being on the exterior).
func Windings(p ppath.Path, x, y float32) (int, bool) {
n := 0
boundary := false
for _, pi := range p.Split() {
zs := RayIntersections(pi, x, y)
if ni, boundaryi := windings(zs); boundaryi {
boundary = true
} else {
n += ni
}
}
return n, boundary
}
// Crossings returns the number of crossings with the path from the
// given point outwards, i.e. the number of times a ray from (x,y)
// towards (∞,y) intersects the path. Additionally, it returns whether
// the point is on a path's boundary (which does not count towards
// the number of crossings).
func Crossings(p ppath.Path, x, y float32) (int, bool) {
n := 0
boundary := false
for _, pi := range p.Split() {
// Count intersections of ray with path. Count half an intersection on boundaries.
ni := 0.0
for _, z := range RayIntersections(pi, x, y) {
if z.T[0] == 0.0 {
boundary = true
} else if !z.Same {
if z.T[1] == 0.0 || z.T[1] == 1.0 {
ni += 0.5
} else {
ni += 1.0
}
} else if z.T[1] == 0.0 || z.T[1] == 1.0 {
ni -= 0.5
}
}
n += int(ni)
}
return n, boundary
}
// Contains returns whether the point (x,y) is contained/filled by the path.
// This depends on the ppath.FillRules. It uses a ray from (x,y) toward (∞,y) and
// counts the number of intersections with the path.
// When the point is on the boundary it is considered to be on the path's exterior.
func Contains(p ppath.Path, x, y float32, fillRule ppath.FillRules) bool {
n, boundary := Windings(p, x, y)
if boundary {
return true
}
return fillRule.Fills(n)
}
// CCW returns true when the path is counter clockwise oriented at its
// bottom-right-most coordinate. It is most useful when knowing that
// the path does not self-intersect as it will tell you if the entire
// path is CCW or not. It will only return the result for the first subpath.
// It will return true for an empty path or a straight line.
// It may not return a valid value when the right-most point happens to be a
// (self-)overlapping segment.
func CCW(p ppath.Path) bool {
if len(p) <= 4 || (p[4] == ppath.LineTo || p[4] == ppath.Close) && len(p) <= 4+ppath.CmdLen(p[4]) {
// empty path or single straight segment
return true
}
p = XMonotone(p)
// pick bottom-right-most coordinate of subpath, as we know its left-hand side is filling
k, kMax := 4, len(p)
if p[kMax-1] == ppath.Close {
kMax -= ppath.CmdLen(ppath.Close)
}
for i := 4; i < len(p); {
cmd := p[i]
if cmd == ppath.MoveTo {
// only handle first subpath
kMax = i
break
}
i += ppath.CmdLen(cmd)
if x, y := p[i-3], p[i-2]; p[k-3] < x || ppath.Equal(p[k-3], x) && y < p[k-2] {
k = i
}
}
// get coordinates of previous and next segments
var kPrev int
if k == 4 {
kPrev = kMax
} else {
kPrev = k - ppath.CmdLen(p[k-1])
}
var angleNext float32
anglePrev := ppath.AngleNorm(ppath.Angle(ppath.DirectionIndex(p, kPrev, 1.0)) + math32.Pi)
if k == kMax {
// use implicit close command
angleNext = ppath.Angle(math32.Vec2(p[1], p[2]).Sub(math32.Vec2(p[k-3], p[k-2])))
} else {
angleNext = ppath.Angle(ppath.DirectionIndex(p, k, 0.0))
}
if ppath.Equal(anglePrev, angleNext) {
// segments have the same direction at their right-most point
// one or both are not straight lines, check if curvature is different
var curvNext float32
curvPrev := -curvature(p, kPrev, 1.0)
if k == kMax {
// use implicit close command
curvNext = 0.0
} else {
curvNext = curvature(p, k, 0.0)
}
if !ppath.Equal(curvPrev, curvNext) {
// ccw if curvNext is smaller than curvPrev
return curvNext < curvPrev
}
}
return (angleNext - anglePrev) < 0.0
}
// Filling returns whether each subpath gets filled or not.
// Whether a path is filled depends on the ppath.FillRules and whether it
// negates another path. If a subpath is not closed, it is implicitly
// assumed to be closed.
func Filling(p ppath.Path, fillRule ppath.FillRules) []bool {
ps := p.Split()
filling := make([]bool, len(ps))
for i, pi := range ps {
// get current subpath's winding
n := 0
if CCW(pi) {
n++
} else {
n--
}
// sum windings from other subpaths
pos := math32.Vec2(pi[1], pi[2])
for j, pj := range ps {
if i == j {
continue
}
zs := RayIntersections(pj, pos.X, pos.Y)
// TODO: on the boundary, check if around the interior or exterior of pos
if ni, boundaryi := windings(zs); !boundaryi {
n += ni
}
}
filling[i] = fillRule.Fills(n)
}
return filling
}
// Length returns the length of the path in millimeters.
// The length is approximated for cubic Béziers.
func Length(p ppath.Path) float32 {
d := float32(0.0)
var start, end math32.Vector2
for i := 0; i < len(p); {
cmd := p[i]
switch cmd {
case ppath.MoveTo:
end = math32.Vec2(p[i+1], p[i+2])
case ppath.LineTo, ppath.Close:
end = math32.Vec2(p[i+1], p[i+2])
d += end.Sub(start).Length()
case ppath.QuadTo:
cp := math32.Vec2(p[i+1], p[i+2])
end = math32.Vec2(p[i+3], p[i+4])
d += quadraticBezierLength(start, cp, end)
case ppath.CubeTo:
cp1 := math32.Vec2(p[i+1], p[i+2])
cp2 := math32.Vec2(p[i+3], p[i+4])
end = math32.Vec2(p[i+5], p[i+6])
d += cubicBezierLength(start, cp1, cp2, end)
case ppath.ArcTo:
var rx, ry, phi float32
var large ppath.ArcSize
var sweep ppath.ArcSweep
rx, ry, phi, large, sweep, end = p.ArcToPoints(i)
_, _, theta1, theta2 := ppath.EllipseToCenter(start.X, start.Y, rx, ry, phi, ppath.ArcSize(large), ppath.ArcSweep(sweep), end.X, end.Y)
d += ellipseLength(rx, ry, theta1, theta2)
}
i += ppath.CmdLen(cmd)
start = end
}
return d
}
// IsFlat returns true if the path consists of solely line segments,
// that is only MoveTo, ppath.LineTo and Close commands.
func IsFlat(p ppath.Path) bool {
for i := 0; i < len(p); {
cmd := p[i]
if cmd != ppath.MoveTo && cmd != ppath.LineTo && cmd != ppath.Close {
return false
}
i += ppath.CmdLen(cmd)
}
return true
}
// SplitAt splits the path into separate paths at the specified
// intervals (given in millimeters) along the path.
func SplitAt(p ppath.Path, ts ...float32) []ppath.Path {
if len(ts) == 0 {
return []ppath.Path{p}
}
slices.Sort(ts)
if ts[0] == 0.0 {
ts = ts[1:]
}
j := 0 // index into ts
T := float32(0.0) // current position along curve
qs := []ppath.Path{}
q := ppath.Path{}
push := func() {
qs = append(qs, q)
q = ppath.Path{}
}
if 0 < len(p) && p[0] == ppath.MoveTo {
q.MoveTo(p[1], p[2])
}
for _, ps := range p.Split() {
var start, end math32.Vector2
for i := 0; i < len(ps); {
cmd := ps[i]
switch cmd {
case ppath.MoveTo:
end = math32.Vec2(p[i+1], p[i+2])
case ppath.LineTo, ppath.Close:
end = math32.Vec2(p[i+1], p[i+2])
if j == len(ts) {
q.LineTo(end.X, end.Y)
} else {
dT := end.Sub(start).Length()
Tcurve := T
for j < len(ts) && T < ts[j] && ts[j] <= T+dT {
tpos := (ts[j] - T) / dT
pos := start.Lerp(end, tpos)
Tcurve = ts[j]
q.LineTo(pos.X, pos.Y)
push()
q.MoveTo(pos.X, pos.Y)
j++
}
if Tcurve < T+dT {
q.LineTo(end.X, end.Y)
}
T += dT
}
case ppath.QuadTo:
cp := math32.Vec2(p[i+1], p[i+2])
end = math32.Vec2(p[i+3], p[i+4])
if j == len(ts) {
q.QuadTo(cp.X, cp.Y, end.X, end.Y)
} else {
speed := func(t float32) float32 {
return ppath.QuadraticBezierDeriv(start, cp, end, t).Length()
}
invL, dT := invSpeedPolynomialChebyshevApprox(20, gaussLegendre7, speed, 0.0, 1.0)
t0 := float32(0.0)
r0, r1, r2 := start, cp, end
for j < len(ts) && T < ts[j] && ts[j] <= T+dT {
t := invL(ts[j] - T)
tsub := (t - t0) / (1.0 - t0)
t0 = t
var q1 math32.Vector2
_, q1, _, r0, r1, r2 = quadraticBezierSplit(r0, r1, r2, tsub)
q.QuadTo(q1.X, q1.Y, r0.X, r0.Y)
push()
q.MoveTo(r0.X, r0.Y)
j++
}
if !ppath.Equal(t0, 1.0) {
q.QuadTo(r1.X, r1.Y, r2.X, r2.Y)
}
T += dT
}
case ppath.CubeTo:
cp1 := math32.Vec2(p[i+1], p[i+2])
cp2 := math32.Vec2(p[i+3], p[i+4])
end = math32.Vec2(p[i+5], p[i+6])
if j == len(ts) {
q.CubeTo(cp1.X, cp1.Y, cp2.X, cp2.Y, end.X, end.Y)
} else {
speed := func(t float32) float32 {
// splitting on inflection points does not improve output
return ppath.CubicBezierDeriv(start, cp1, cp2, end, t).Length()
}
N := 20 + 20*cubicBezierNumInflections(start, cp1, cp2, end) // TODO: needs better N
invL, dT := invSpeedPolynomialChebyshevApprox(N, gaussLegendre7, speed, 0.0, 1.0)
t0 := float32(0.0)
r0, r1, r2, r3 := start, cp1, cp2, end
for j < len(ts) && T < ts[j] && ts[j] <= T+dT {
t := invL(ts[j] - T)
tsub := (t - t0) / (1.0 - t0)
t0 = t
var q1, q2 math32.Vector2
_, q1, q2, _, r0, r1, r2, r3 = cubicBezierSplit(r0, r1, r2, r3, tsub)
q.CubeTo(q1.X, q1.Y, q2.X, q2.Y, r0.X, r0.Y)
push()
q.MoveTo(r0.X, r0.Y)
j++
}
if !ppath.Equal(t0, 1.0) {
q.CubeTo(r1.X, r1.Y, r2.X, r2.Y, r3.X, r3.Y)
}
T += dT
}
case ppath.ArcTo:
var rx, ry, phi float32
var large ppath.ArcSize
var sweep ppath.ArcSweep
rx, ry, phi, large, sweep, end = p.ArcToPoints(i)
cx, cy, theta1, theta2 := ppath.EllipseToCenter(start.X, start.Y, rx, ry, phi, ppath.ArcSize(large), ppath.ArcSweep(sweep), end.X, end.Y)
if j == len(ts) {
q.ArcTo(rx, ry, phi, ppath.ArcSize(large), ppath.ArcSweep(sweep), end.X, end.Y)
} else {
speed := func(theta float32) float32 {
return ppath.EllipseDeriv(rx, ry, 0.0, ppath.Clockwise, theta).Length()
}
invL, dT := invSpeedPolynomialChebyshevApprox(10, gaussLegendre7, speed, theta1, theta2)
startTheta := theta1
nextLarge := large
for j < len(ts) && T < ts[j] && ts[j] <= T+dT {
theta := invL(ts[j] - T)
mid, large1, large2, ok := ellipseSplit(rx, ry, phi, cx, cy, startTheta, theta2, theta)
if !ok {
panic("theta not in elliptic arc range for splitting")
}
q.ArcTo(rx, ry, phi, ppath.ArcSize(large1), ppath.ArcSweep(sweep), mid.X, mid.Y)
push()
q.MoveTo(mid.X, mid.Y)
startTheta = theta
nextLarge = ppath.ArcSize(large2)
j++
}
if !ppath.Equal(startTheta, theta2) {
q.ArcTo(rx, ry, phi*180.0/math32.Pi, ppath.ArcSize(nextLarge), ppath.ArcSweep(sweep), end.X, end.Y)
}
T += dT
}
}
i += ppath.CmdLen(cmd)
start = end
}
}
if ppath.CmdLen(ppath.MoveTo) < len(q) {
push()
}
return qs
}
// XMonotone replaces all Bézier and arc segments to be x-monotone
// and returns a new path, that is each path segment is either increasing
// or decreasing with X while moving across the segment.
// This is always true for line segments.
func XMonotone(p ppath.Path) ppath.Path {
quad := func(p0, p1, p2 math32.Vector2) ppath.Path {
return xmonotoneQuadraticBezier(p0, p1, p2)
}
cube := func(p0, p1, p2, p3 math32.Vector2) ppath.Path {
return xmonotoneCubicBezier(p0, p1, p2, p3)
}
arc := func(start math32.Vector2, rx, ry, phi float32, large ppath.ArcSize, sweep ppath.ArcSweep, end math32.Vector2) ppath.Path {
return xmonotoneEllipticArc(start, rx, ry, phi, ppath.ArcSize(large), ppath.ArcSweep(sweep), end)
}
return p.Replace(nil, quad, cube, arc)
}
// Bounds returns the exact bounding box rectangle of the path.
func Bounds(p ppath.Path) math32.Box2 {
if len(p) < 4 {
return math32.Box2{}
}
// first command is MoveTo
start, end := math32.Vec2(p[1], p[2]), math32.Vector2{}
xmin, xmax := start.X, start.X
ymin, ymax := start.Y, start.Y
for i := 4; i < len(p); {
cmd := p[i]
switch cmd {
case ppath.MoveTo, ppath.LineTo, ppath.Close:
end = math32.Vec2(p[i+1], p[i+2])
xmin = math32.Min(xmin, end.X)
xmax = math32.Max(xmax, end.X)
ymin = math32.Min(ymin, end.Y)
ymax = math32.Max(ymax, end.Y)
case ppath.QuadTo:
cp := math32.Vec2(p[i+1], p[i+2])
end = math32.Vec2(p[i+3], p[i+4])
xmin = math32.Min(xmin, end.X)
xmax = math32.Max(xmax, end.X)
if tdenom := (start.X - 2*cp.X + end.X); !ppath.Equal(tdenom, 0.0) {
if t := (start.X - cp.X) / tdenom; inIntervalExclusive(t, 0.0, 1.0) {
x := quadraticBezierPos(start, cp, end, t)
xmin = math32.Min(xmin, x.X)
xmax = math32.Max(xmax, x.X)
}
}
ymin = math32.Min(ymin, end.Y)
ymax = math32.Max(ymax, end.Y)
if tdenom := (start.Y - 2*cp.Y + end.Y); !ppath.Equal(tdenom, 0.0) {
if t := (start.Y - cp.Y) / tdenom; inIntervalExclusive(t, 0.0, 1.0) {
y := quadraticBezierPos(start, cp, end, t)
ymin = math32.Min(ymin, y.Y)
ymax = math32.Max(ymax, y.Y)
}
}
case ppath.CubeTo:
cp1 := math32.Vec2(p[i+1], p[i+2])
cp2 := math32.Vec2(p[i+3], p[i+4])
end = math32.Vec2(p[i+5], p[i+6])
a := -start.X + 3*cp1.X - 3*cp2.X + end.X
b := 2*start.X - 4*cp1.X + 2*cp2.X
c := -start.X + cp1.X
t1, t2 := solveQuadraticFormula(a, b, c)
xmin = math32.Min(xmin, end.X)
xmax = math32.Max(xmax, end.X)
if !math32.IsNaN(t1) && inIntervalExclusive(t1, 0.0, 1.0) {
x1 := cubicBezierPos(start, cp1, cp2, end, t1)
xmin = math32.Min(xmin, x1.X)
xmax = math32.Max(xmax, x1.X)
}
if !math32.IsNaN(t2) && inIntervalExclusive(t2, 0.0, 1.0) {
x2 := cubicBezierPos(start, cp1, cp2, end, t2)
xmin = math32.Min(xmin, x2.X)
xmax = math32.Max(xmax, x2.X)
}
a = -start.Y + 3*cp1.Y - 3*cp2.Y + end.Y
b = 2*start.Y - 4*cp1.Y + 2*cp2.Y
c = -start.Y + cp1.Y
t1, t2 = solveQuadraticFormula(a, b, c)
ymin = math32.Min(ymin, end.Y)
ymax = math32.Max(ymax, end.Y)
if !math32.IsNaN(t1) && inIntervalExclusive(t1, 0.0, 1.0) {
y1 := cubicBezierPos(start, cp1, cp2, end, t1)
ymin = math32.Min(ymin, y1.Y)
ymax = math32.Max(ymax, y1.Y)
}
if !math32.IsNaN(t2) && inIntervalExclusive(t2, 0.0, 1.0) {
y2 := cubicBezierPos(start, cp1, cp2, end, t2)
ymin = math32.Min(ymin, y2.Y)
ymax = math32.Max(ymax, y2.Y)
}
case ppath.ArcTo:
var rx, ry, phi float32
var large ppath.ArcSize
var sweep ppath.ArcSweep
rx, ry, phi, large, sweep, end = p.ArcToPoints(i)
cx, cy, theta0, theta1 := ppath.EllipseToCenter(start.X, start.Y, rx, ry, phi, ppath.ArcSize(large), ppath.ArcSweep(sweep), end.X, end.Y)
// find the four extremes (top, bottom, left, right) and apply those who are between theta1 and theta2
// x(theta) = cx + rx*cos(theta)*cos(phi) - ry*sin(theta)*sin(phi)
// y(theta) = cy + rx*cos(theta)*sin(phi) + ry*sin(theta)*cos(phi)
// be aware that positive rotation appears clockwise in SVGs (non-Cartesian coordinate system)
// we can now find the angles of the extremes
sinphi, cosphi := math32.Sincos(phi)
thetaRight := math32.Atan2(-ry*sinphi, rx*cosphi)
thetaTop := math32.Atan2(rx*cosphi, ry*sinphi)
thetaLeft := thetaRight + math32.Pi
thetaBottom := thetaTop + math32.Pi
dx := math32.Sqrt(rx*rx*cosphi*cosphi + ry*ry*sinphi*sinphi)
dy := math32.Sqrt(rx*rx*sinphi*sinphi + ry*ry*cosphi*cosphi)
if ppath.IsAngleBetween(thetaLeft, theta0, theta1) {
xmin = math32.Min(xmin, cx-dx)
}
if ppath.IsAngleBetween(thetaRight, theta0, theta1) {
xmax = math32.Max(xmax, cx+dx)
}
if ppath.IsAngleBetween(thetaBottom, theta0, theta1) {
ymin = math32.Min(ymin, cy-dy)
}
if ppath.IsAngleBetween(thetaTop, theta0, theta1) {
ymax = math32.Max(ymax, cy+dy)
}
xmin = math32.Min(xmin, end.X)
xmax = math32.Max(xmax, end.X)
ymin = math32.Min(ymin, end.Y)
ymax = math32.Max(ymax, end.Y)
}
i += ppath.CmdLen(cmd)
start = end
}
return math32.B2(xmin, ymin, xmax, ymax)
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This is adapted from https://github.com/tdewolff/canvas
// Copyright (c) 2015 Taco de Wolff, under an MIT License.
// Package intersect provides the intersections of paths, and boolean
// operations on them (and, or, xor, not), settling, and filling tests.
package intersect
import (
"fmt"
"io"
"log"
"slices"
"sort"
"strings"
"sync"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint/ppath"
)
// DebugPathIntersection enables debugging mode for path intersection edge-cases. Please send us the test cases generated as temporary files.
var DebugPathIntersection = false
// BentleyOttmannEpsilon is the snap rounding grid used by the Bentley-Ottmann algorithm.
// This prevents numerical issues. It must be larger than Epsilon since we use that to calculate
// intersections between segments. It is the number of binary digits to keep.
// It is 1e-6 here, instead of the 1e-8 of canvas in float64: float32 only
// has about 7 significant digits, and with a finer grid, nearly coincident
// points (as of shared edges computed in different ways) are not merged,
// which gives wrong results or panics; it is 10 times [ppath.Epsilon] (1e-7),
// as canvas's is 100 times its Epsilon (1e-10).
var BentleyOttmannEpsilon = float32(1e-6)
// RayIntersections returns the intersections of a path with a ray starting at (x,y) to (∞,y).
// An intersection is tangent only when it is at (x,y), i.e. the start of the ray. The parameter T
// along the ray is zero at the start but NaN otherwise. Intersections are sorted along the ray.
// This function runs in O(n) with n the number of path segments.
func RayIntersections(p ppath.Path, x, y float32) []Intersection {
var start, end, cp1, cp2 math32.Vector2
var zs []Intersection
for i := 0; i < len(p); {
cmd := p[i]
switch cmd {
case ppath.MoveTo:
end = p.EndPoint(i)
case ppath.LineTo, ppath.Close:
end = p.EndPoint(i)
ymin := math32.Min(start.Y, end.Y)
ymax := math32.Max(start.Y, end.Y)
xmax := math32.Max(start.X, end.X)
if inInterval(y, ymin, ymax) && x <= xmax+ppath.Epsilon {
zs = intersectionLineLine(zs, math32.Vec2(x, y), math32.Vec2(xmax+1.0, y), start, end)
}
case ppath.QuadTo:
cp1, end = p.QuadToPoints(i)
ymin := math32.Min(math32.Min(start.Y, end.Y), cp1.Y)
ymax := math32.Max(math32.Max(start.Y, end.Y), cp1.Y)
xmax := math32.Max(math32.Max(start.X, end.X), cp1.X)
if inInterval(y, ymin, ymax) && x <= xmax+ppath.Epsilon {
zs = intersectionLineQuad(zs, math32.Vec2(x, y), math32.Vec2(xmax+1.0, y), start, cp1, end)
}
case ppath.CubeTo:
cp1, cp2, end = p.CubeToPoints(i)
ymin := math32.Min(math32.Min(start.Y, end.Y), math32.Min(cp1.Y, cp2.Y))
ymax := math32.Max(math32.Max(start.Y, end.Y), math32.Max(cp1.Y, cp2.Y))
xmax := math32.Max(math32.Max(start.X, end.X), math32.Max(cp1.X, cp2.X))
if inInterval(y, ymin, ymax) && x <= xmax+ppath.Epsilon {
zs = intersectionLineCube(zs, math32.Vec2(x, y), math32.Vec2(xmax+1.0, y), start, cp1, cp2, end)
}
case ppath.ArcTo:
var rx, ry, phi float32
var large ppath.ArcSize
var sweep ppath.ArcSweep
rx, ry, phi, large, sweep, end = p.ArcToPoints(i)
cx, cy, theta0, theta1 := ppath.EllipseToCenter(start.X, start.Y, rx, ry, phi, ppath.ArcSize(large), ppath.ArcSweep(sweep), end.X, end.Y)
if inInterval(y, cy-math32.Max(rx, ry), cy+math32.Max(rx, ry)) && x <= cx+math32.Max(rx, ry)+ppath.Epsilon {
zs = intersectionLineEllipse(zs, math32.Vec2(x, y), math32.Vec2(cx+rx+1.0, y), math32.Vec2(cx, cy), math32.Vec2(rx, ry), phi, theta0, theta1)
}
}
i += ppath.CmdLen(cmd)
start = end
}
for i := range zs {
if zs[i].T[0] != 0.0 {
zs[i].T[0] = math32.NaN()
}
}
sort.SliceStable(zs, func(i, j int) bool {
if ppath.Equal(zs[i].X, zs[j].X) {
return false
}
return zs[i].X < zs[j].X
})
return zs
}
type pathOp int
const (
opSettle pathOp = iota
opAND
opOR
opNOT
opXOR
opDIV
)
func (op pathOp) String() string {
switch op {
case opSettle:
return "Settle"
case opAND:
return "AND"
case opOR:
return "OR"
case opNOT:
return "NOT"
case opXOR:
return "XOR"
case opDIV:
return "DIV"
}
return fmt.Sprintf("pathOp(%d)", op)
}
var boPointPool *sync.Pool
var boNodePool *sync.Pool
var boSquarePool *sync.Pool
var boInitPoolsOnce = sync.OnceFunc(func() {
boPointPool = &sync.Pool{New: func() any { return &SweepPoint{} }}
boNodePool = &sync.Pool{New: func() any { return &SweepNode{} }}
boSquarePool = &sync.Pool{New: func() any { return &toleranceSquare{} }}
})
// Settle returns the "settled"/flattened path, a visually identical version of the original.
// It removes all self-intersections and overlapping areas, orients all filling paths CCW and all
// holes CW, and tries to separate paths as much as possible. Paths are grouped by the
// filling/outer ring followed by the corresponding holes/inner rings; the outer rings are ordered
// from left-to-right and secondly from bottom-to-top. Note that path p is flattened unless q is
// already flat. It runs in O((n + k) log n), with n the number of segments, and k the number of
// intersections.
func Settle(p ppath.Path, fillRule ppath.FillRules) ppath.Path {
return mergePaths(bentleyOttmann(p.Split(), nil, opSettle, fillRule))
}
// SettlePaths is the same as [Settle], but faster if paths are already split.
func SettlePaths(ps ppath.Paths, fillRule ppath.FillRules) ppath.Path {
return mergePaths(bentleyOttmann(ps, nil, opSettle, fillRule))
}
// SettleRings is the same as [SettlePaths], but returns each filling path
// followed by its holes as subpaths, as a separate path.
func SettleRings(ps ppath.Paths, fillRule ppath.FillRules) ppath.Paths {
return bentleyOttmann(ps, nil, opSettle, fillRule)
}
// And returns the boolean path operation of path p AND q, i.e. the intersection of both.
// It removes all self-intersections and overlapping areas, orients all filling paths CCW and all
// holes CW, and tries to separate paths as much as possible (see [Settle]). Note that path p is
// flattened unless q is already flat. Path q is implicitly closed. It runs in O((n + k) log n),
// with n the number of segments, and k the number of intersections.
func And(p ppath.Path, q ppath.Path) ppath.Path {
return mergePaths(bentleyOttmann(p.Split(), q.Split(), opAND, ppath.NonZero))
}
// AndPaths is the same as [And], but faster if paths are already split.
func AndPaths(ps ppath.Paths, qs ppath.Paths) ppath.Path {
return mergePaths(bentleyOttmann(ps, qs, opAND, ppath.NonZero))
}
// Or returns the boolean path operation of path p OR q, i.e. the union of both.
// See [And] for the details.
func Or(p ppath.Path, q ppath.Path) ppath.Path {
return mergePaths(bentleyOttmann(p.Split(), q.Split(), opOR, ppath.NonZero))
}
// OrPaths is the same as [Or], but faster if paths are already split.
func OrPaths(ps ppath.Paths, qs ppath.Paths) ppath.Path {
return mergePaths(bentleyOttmann(ps, qs, opOR, ppath.NonZero))
}
// Xor returns the boolean path operation of path p XOR q, i.e. the symmetric difference of both.
// See [And] for the details.
func Xor(p ppath.Path, q ppath.Path) ppath.Path {
return mergePaths(bentleyOttmann(p.Split(), q.Split(), opXOR, ppath.NonZero))
}
// XorPaths is the same as [Xor], but faster if paths are already split.
func XorPaths(ps ppath.Paths, qs ppath.Paths) ppath.Path {
return mergePaths(bentleyOttmann(ps, qs, opXOR, ppath.NonZero))
}
// Not returns the boolean path operation of path p NOT q, i.e. the difference of both.
// See [And] for the details.
func Not(p ppath.Path, q ppath.Path) ppath.Path {
return mergePaths(bentleyOttmann(p.Split(), q.Split(), opNOT, ppath.NonZero))
}
// NotPaths is the same as [Not], but faster if paths are already split.
func NotPaths(ps ppath.Paths, qs ppath.Paths) ppath.Path {
return mergePaths(bentleyOttmann(ps, qs, opNOT, ppath.NonZero))
}
// DivideBy returns the boolean path operation of path p DIV q, i.e. p divided by q.
// See [And] for the details.
func DivideBy(p ppath.Path, q ppath.Path) ppath.Path {
return mergePaths(bentleyOttmann(p.Split(), q.Split(), opDIV, ppath.NonZero))
}
// DivideByPaths is the same as [DivideBy] but faster if paths are already split.
func DivideByPaths(ps ppath.Paths, qs ppath.Paths) ppath.Path {
return mergePaths(bentleyOttmann(ps, qs, opDIV, ppath.NonZero))
}
// mergePaths returns the paths appended as one path.
func mergePaths(ps ppath.Paths) ppath.Path {
n := 0
for _, pi := range ps {
n += len(pi)
}
p := make(ppath.Path, 0, n)
for _, pi := range ps {
p = p.Append(pi)
}
return p
}
// SweepPoint is of size 88 bytes on 64-bit architectures
type SweepPoint struct {
// initial data
math32.Vector2 // position of this endpoint
other *SweepPoint // pointer to the other endpoint of the segment
segment int // segment index to distinguish self-overlapping segments
// processing the queue
node *SweepNode // used for fast accessing btree node in O(1) (instead of Find in O(log n))
// computing sweep fields
prev *SweepPoint // segment below
windings int16 // windings of the same polygon (excluding this segment)
otherWindings int16 // windings of the other polygon
selfWindings int16 // positive if segment goes left-right (or bottom-top when vertical)
otherSelfWindings int16 // used when merging overlapping segments
// building the polygon
square int // index into tolerance squares
index int // index into resulting paths' array
inResult uint8 // in final result polygon (1 is once, 2 is twice for opDIV)
resultWindings int16 // windings above the segment of the resulting polygon
// bools at the end to optimize memory layout of struct
clipping bool // is clipping path (otherwise is subject path)
open bool // path is not closed
end bool // event is path endpoint (only for open paths)
left bool // point is left-end of segment
vertical bool // segment is vertical
increasing bool // original direction is left-right (or bottom-top)
overlapped bool // segment's overlapping was handled
swept bool // sweep fields have been computed for this left-endpoint
}
func (s *SweepPoint) InterpolateY(x float32) float32 {
t := (x - s.X) / (s.other.X - s.X)
return s.Lerp(s.other.Vector2, t).Y
}
// ToleranceEdgeY returns the y-value of the SweepPoint at the tolerance edges given by xLeft and
// xRight, or at the endpoints of the SweepPoint, whichever comes first.
func (s *SweepPoint) ToleranceEdgeY(xLeft, xRight float32) (float32, float32) {
if !s.left {
s = s.other
}
if s.X == s.other.X {
// Vertical segments have no x-extent: both endpoints lie in this column and the
// y-values at the tolerance edges are simply the endpoints. Interpolating would divide
// by zero and yield NaN whenever floating-point rounding puts the segment's x a ulp
// outside [xLeft, xRight), which then fails every below/above test and leaves the
// segment unbroken across the squares it passes through.
// (from https://github.com/tdewolff/canvas/pull/394)
return s.Y, s.other.Y
}
y0 := s.Y
if s.X < xLeft {
y0 = s.InterpolateY(xLeft)
}
y1 := s.other.Y
if xRight <= s.other.X {
y1 = s.InterpolateY(xRight)
}
return y0, y1
}
func (s *SweepPoint) SplitAt(z math32.Vector2) (*SweepPoint, *SweepPoint) {
// split segment at point
r := boPointPool.Get().(*SweepPoint)
l := boPointPool.Get().(*SweepPoint)
*r, *l = *s.other, *s
r.Vector2, l.Vector2 = z, z
r.end, l.end = false, false
r.swept, l.swept = false, false
// update references
r.other, s.other.other = s, l
l.other, s.other = s.other, r
l.node = nil
return r, l
}
func (s *SweepPoint) Reverse() {
s.left, s.other.left = !s.left, s.left
s.increasing, s.other.increasing = !s.increasing, !s.other.increasing
}
func (s *SweepPoint) String() string {
path := "P"
if s.clipping {
path = "Q"
}
arrow := "→"
if !s.left {
arrow = "←"
}
return fmt.Sprintf("%s-%v(%v%v%v)", path, s.segment, s.Vector2, arrow, s.other.Vector2)
}
// SweepEvents is a heap priority queue of sweep events.
type SweepEvents []*SweepPoint
func (q SweepEvents) Less(i, j int) bool {
return q[i].LessH(q[j])
}
func (q SweepEvents) Swap(i, j int) {
q[i], q[j] = q[j], q[i]
}
// AddPathEndpoints adds all line segments of p to the queue q. The first command is converted to a ppath.MoveTo and any ppath.Close that
// is not at the end is converted to a ppath.LineTo.
func (q *SweepEvents) AddPathEndpoints(p ppath.Path, seg int, clipping bool) int {
if len(p) == 0 {
return seg
}
// TODO: change this if we allow non-flat paths
// allocate all memory at once to prevent multiple allocations/memmoves below
n := len(p) / 4
if cap(*q) < len(*q)+n {
q2 := make(SweepEvents, len(*q), len(*q)+n)
copy(q2, *q)
*q = q2
}
open := !p.Closed()
start := math32.Vec2(p[1], p[2])
if math32.IsNaN(start.X) || math32.IsInf(start.X, 0.0) || math32.IsNaN(start.Y) || math32.IsInf(start.Y, 0.0) {
panic("path has NaN or Inf")
} else if open && p[len(p)-3] == p[1] && p[len(p)-2] == p[2] {
open = false // start and end points coincide, consider path closed
}
for i := 4; i < len(p); {
cmd := p[i]
if cmd != ppath.LineTo && cmd != ppath.Close {
panic("non-flat paths not supported")
}
n := ppath.CmdLen(cmd)
end := math32.Vec2(p[i+n-3], p[i+n-2])
if cmd == ppath.Close {
// a close ends exactly at the start of the subpath, also when its coordinates
// differ from it within ppath.Epsilon (as [ppath.Path.Close] allows); canvas
// panics here as its Close sets them exactly
end = math32.Vec2(p[1], p[2])
}
if math32.IsNaN(end.X) || math32.IsInf(end.X, 0.0) || math32.IsNaN(end.Y) || math32.IsInf(end.Y, 0.0) {
panic("path has NaN or Inf")
}
i += n
seg++
// The sweep decides verticality with an exact comparison, but only snaps coordinates to
// the grid after the intersection phase. A segment whose endpoints share a grid column is
// therefore driven through the sweep as left-to-right, and turns vertical the moment it
// is split; a piece that becomes vertical while pointing downwards has to be reversed to
// keep left-endpoints at the bottom, which is impossible once its left-endpoint is in the
// sweep status. Make it vertical up front, which moves a point no further than the
// snapping that follows the sweep would. (from https://github.com/tdewolff/canvas/pull/394)
if start.X != end.X && snap(start.X, BentleyOttmannEpsilon) == snap(end.X, BentleyOttmannEpsilon) {
end.X = start.X
}
if start == end {
// skip zero-length lineTo or close command
continue
}
vertical := start.X == end.X
increasing := start.X < end.X
if vertical {
increasing = start.Y < end.Y
}
a := boPointPool.Get().(*SweepPoint)
b := boPointPool.Get().(*SweepPoint)
*a = SweepPoint{
Vector2: start,
clipping: clipping,
open: open,
end: open && i == 4+n,
segment: seg,
left: increasing,
increasing: increasing,
vertical: vertical,
}
*b = SweepPoint{
Vector2: end,
clipping: clipping,
open: open,
end: open && i == len(p),
segment: seg,
left: !increasing,
increasing: increasing,
vertical: vertical,
}
a.other = b
b.other = a
*q = append(*q, a, b)
start = end
}
return seg
}
func (q SweepEvents) Init() {
n := len(q)
for i := n/2 - 1; 0 <= i; i-- {
q.down(i, n)
}
}
func (q *SweepEvents) Push(item *SweepPoint) {
*q = append(*q, item)
q.up(len(*q) - 1)
}
func (q *SweepEvents) Top() *SweepPoint {
return (*q)[0]
}
func (q *SweepEvents) Pop() *SweepPoint {
n := len(*q) - 1
q.Swap(0, n)
q.down(0, n)
items := (*q)[n]
*q = (*q)[:n]
return items
}
//func (q *SweepEvents) Fix(i int) {
// if !q.down(i, len(*q)) {
// q.up(i)
// }
//}
// from container/heap
func (q SweepEvents) up(j int) {
for {
i := (j - 1) / 2 // parent
if i == j || !q.Less(j, i) {
break
}
q.Swap(i, j)
j = i
}
}
func (q SweepEvents) down(i0, n int) bool {
i := i0
for {
j1 := 2*i + 1
if n <= j1 || j1 < 0 { // j1 < 0 after int overflow
break
}
j := j1 // left child
if j2 := j1 + 1; j2 < n && q.Less(j2, j1) {
j = j2 // = 2*i + 2 // right child
}
if !q.Less(j, i) {
break
}
q.Swap(i, j)
i = j
}
return i0 < i
}
func (q SweepEvents) Print(w io.Writer) {
q2 := make(SweepEvents, len(q))
copy(q2, q)
q = q2
n := len(q) - 1
for 0 < n {
q.Swap(0, n)
q.down(0, n)
n--
}
width := int(math32.Max(0.0, math32.Log10(float32(len(q)-1)))) + 1
for k := len(q) - 1; 0 <= k; k-- {
fmt.Fprintf(w, "%*d %v\n", width, len(q)-1-k, q[k])
}
}
func (q SweepEvents) String() string {
sb := strings.Builder{}
q.Print(&sb)
str := sb.String()
if 0 < len(str) {
str = str[:len(str)-1]
}
return str
}
type SweepNode struct {
parent, left, right *SweepNode
height int
*SweepPoint
}
func (n *SweepNode) Prev() *SweepNode {
// go left
if n.left != nil {
n = n.left
for n.right != nil {
n = n.right // find the right-most of current subtree
}
return n
}
for n.parent != nil && n.parent.left == n {
n = n.parent // find first parent for which we're right
}
return n.parent // can be nil
}
func (n *SweepNode) Next() *SweepNode {
// go right
if n.right != nil {
n = n.right
for n.left != nil {
n = n.left // find the left-most of current subtree
}
return n
}
for n.parent != nil && n.parent.right == n {
n = n.parent // find first parent for which we're left
}
return n.parent // can be nil
}
//func (a *SweepNode) swap(b *SweepNode) {
// a.SweepPoint, b.SweepPoint = b.SweepPoint, a.SweepPoint
// a.SweepPoint.node, b.SweepPoint.node = a, b
//}
//func (n *SweepNode) fix() (*SweepNode, int) {
// move := 0
// if prev := n.Prev(); prev != nil && 0 < prev.CompareV(n.SweepPoint, false) {
// // move down
// n.swap(prev)
// n, prev = prev, n
// move--
//
// for prev = prev.Prev(); prev != nil; prev = prev.Prev() {
// if prev.CompareV(n.SweepPoint, false) < 0 {
// break
// }
// n.swap(prev)
// n, prev = prev, n
// move--
// }
// } else if next := n.Next(); next != nil && next.CompareV(n.SweepPoint, false) < 0 {
// // move up
// n.swap(next)
// n, next = next, n
// move++
//
// for next = next.Next(); next != nil; next = next.Next() {
// if 0 < next.CompareV(n.SweepPoint, false) {
// break
// }
// n.swap(next)
// n, next = next, n
// move++
// }
// }
// return n, move
//}
func (n *SweepNode) balance() int {
r := 0
if n.left != nil {
r -= n.left.height
}
if n.right != nil {
r += n.right.height
}
return r
}
func (n *SweepNode) updateHeight() {
n.height = 0
if n.left != nil {
n.height = n.left.height
}
if n.right != nil && n.height < n.right.height {
n.height = n.right.height
}
n.height++
}
func (n *SweepNode) swapChild(a, b *SweepNode) {
if n.right == a {
n.right = b
} else {
n.left = b
}
if b != nil {
b.parent = n
}
}
func (n *SweepNode) rotateLeft() *SweepNode {
b := n.right
if n.parent != nil {
n.parent.swapChild(n, b)
} else {
b.parent = nil
}
n.parent = b
if n.right = b.left; n.right != nil {
n.right.parent = n
}
b.left = n
return b
}
func (n *SweepNode) rotateRight() *SweepNode {
b := n.left
if n.parent != nil {
n.parent.swapChild(n, b)
} else {
b.parent = nil
}
n.parent = b
if n.left = b.right; n.left != nil {
n.left.parent = n
}
b.right = n
return b
}
func (n *SweepNode) print(w io.Writer, prefix string, cmp int) {
c := ""
if cmp < 0 {
c = "│ "
} else if 0 < cmp {
c = " "
}
if n.right != nil {
n.right.print(w, prefix+c, 1)
} else if n.left != nil {
fmt.Fprintf(w, "%v%v┌─nil\n", prefix, c)
}
c = ""
if 0 < cmp {
c = "┌─"
} else if cmp < 0 {
c = "└─"
}
fmt.Fprintf(w, "%v%v%v\n", prefix, c, n.SweepPoint)
c = ""
if 0 < cmp {
c = "│ "
} else if cmp < 0 {
c = " "
}
if n.left != nil {
n.left.print(w, prefix+c, -1)
} else if n.right != nil {
fmt.Fprintf(w, "%v%v└─nil\n", prefix, c)
}
}
func (n *SweepNode) Print(w io.Writer) {
n.print(w, "", 0)
}
// SweepStatus is the status of the sweep line: the segments that it
// crosses, from the bottom up, in an AVL tree.
// TODO: test performance versus (2,4)-tree (current LEDA implementation), (2,16)-tree (as proposed by S. Naber/Näher in "Comparison of search-tree data structures in LEDA. Personal communication" apparently), RB-tree (likely a good candidate), and an AA-tree (simpler implementation may be faster). Perhaps an unbalanced (e.g. Treap) works well due to the high number of insertions/deletions.
// In any case, measure the amount of finds and inserts/deletes. If finds >> inserts probably AVL is better, if somewhat similar or inserts > finds then perhaps an RB tree (store color in sign bit of node's height).
type SweepStatus struct {
root *SweepNode
}
func (s *SweepStatus) newNode(item *SweepPoint) *SweepNode {
n := boNodePool.Get().(*SweepNode)
n.parent = nil
n.left = nil
n.right = nil
n.height = 1
n.SweepPoint = item
n.node = n
return n
}
func (s *SweepStatus) returnNode(n *SweepNode) {
n.node = nil
n.SweepPoint = nil // help the GC
boNodePool.Put(n)
}
func (s *SweepStatus) find(item *SweepPoint) (*SweepNode, int) {
n := s.root
for n != nil {
cmp := item.CompareV(n.SweepPoint)
if cmp < 0 {
if n.left == nil {
return n, -1
}
n = n.left
} else if 0 < cmp {
if n.right == nil {
return n, 1
}
n = n.right
} else {
break // should never happen
}
}
return n, 0 // should never happen
}
func (s *SweepStatus) rebalance(n *SweepNode) {
for {
oheight := n.height
if balance := n.balance(); balance == 2 {
// Tree is excessively right-heavy, rotate it to the left.
if n.right != nil && n.right.balance() < 0 {
// Right tree is left-heavy, which would cause the next rotation to result in
// overall left-heaviness. Rotate the right tree to the right to counteract this.
n.right = n.right.rotateRight()
n.right.right.updateHeight()
}
n = n.rotateLeft()
n.left.updateHeight()
} else if balance == -2 {
// Tree is excessively left-heavy, rotate it to the right
if n.left != nil && 0 < n.left.balance() {
// The left tree is right-heavy, which would cause the next rotation to result in
// overall right-heaviness. Rotate the left tree to the left to compensate.
n.left = n.left.rotateLeft()
n.left.left.updateHeight()
}
n = n.rotateRight()
n.right.updateHeight()
} else if balance < -2 || 2 < balance {
panic("Tree too far out of shape!")
}
n.updateHeight()
if n.parent == nil {
s.root = n
return
}
if oheight == n.height {
return
}
n = n.parent
}
}
func (s *SweepStatus) String() string {
if s.root == nil {
return "nil"
}
sb := strings.Builder{}
s.root.Print(&sb)
str := sb.String()
if 0 < len(str) {
str = str[:len(str)-1]
}
return str
}
//func (s *SweepStatus) First() *SweepNode {
// if s.root == nil {
// return nil
// }
// n := s.root
// for n.left != nil {
// n = n.left
// }
// return n
//}
//func (s *SweepStatus) Last() *SweepNode {
// if s.root == nil {
// return nil
// }
// n := s.root
// for n.right != nil {
// n = n.right
// }
// return n
//}
// Find returns the node equal to item. May return nil.
//func (s *SweepStatus) Find(item *SweepPoint) *SweepNode {
// n, cmp := s.find(item)
// if cmp == 0 {
// return n
// }
// return nil
//}
func (s *SweepStatus) FindPrevNext(item *SweepPoint) (*SweepNode, *SweepNode) {
if s.root == nil {
return nil, nil
}
n, cmp := s.find(item)
if cmp < 0 {
return n.Prev(), n
} else if 0 < cmp {
return n, n.Next()
} else {
return n.Prev(), n.Next() // should never happen
}
}
//func (s *SweepStatus) Insert(item *SweepPoint) *SweepNode {
// if s.root == nil {
// s.root = s.newNode(item)
// return s.root
// }
//
// rebalance := false
// n, cmp := s.find(item)
// if cmp < 0 {
// // lower
// n.left = s.newNode(item)
// n.left.parent = n
// rebalance = n.right == nil
// } else if 0 < cmp {
// // higher
// n.right = s.newNode(item)
// n.right.parent = n
// rebalance = n.left == nil
// } else {
// // equal, replace
// n.SweepPoint.node = nil
// n.SweepPoint = item
// n.SweepPoint.node = n
// return n
// }
//
// if rebalance && n.parent != nil {
// n.height++
// s.rebalance(n.parent)
// }
//
// if cmp < 0 {
// return n.left
// } else {
// return n.right
// }
//}
func (s *SweepStatus) InsertAfter(n *SweepNode, item *SweepPoint) *SweepNode {
var cur *SweepNode
rebalance := false
if n == nil {
if s.root == nil {
s.root = s.newNode(item)
return s.root
}
// insert as left-most node in tree
n = s.root
for n.left != nil {
n = n.left
}
n.left = s.newNode(item)
n.left.parent = n
rebalance = n.right == nil
cur = n.left
} else if n.right == nil {
// insert directly to the right of n
n.right = s.newNode(item)
n.right.parent = n
rebalance = n.left == nil
cur = n.right
} else {
// insert next to n at a deeper level
n = n.right
for n.left != nil {
n = n.left
}
n.left = s.newNode(item)
n.left.parent = n
rebalance = n.right == nil
cur = n.left
}
if rebalance && n.parent != nil {
n.height++
s.rebalance(n.parent)
}
return cur
}
func (s *SweepStatus) Remove(n *SweepNode) {
ancestor := n.parent
if n.left == nil || n.right == nil {
// no children or one child
child := n.left
if n.left == nil {
child = n.right
}
if n.parent != nil {
n.parent.swapChild(n, child)
} else {
s.root = child
}
if child != nil {
child.parent = n.parent
}
} else {
// two children
succ := n.right
for succ.left != nil {
succ = succ.left
}
ancestor = succ.parent // rebalance from here
if succ.parent == n {
// succ is child of n
ancestor = succ
}
succ.parent.swapChild(succ, succ.right)
// swap successor with deleted node
succ.parent, succ.left, succ.right = n.parent, n.left, n.right
if n.parent != nil {
n.parent.swapChild(n, succ)
} else {
s.root = succ
}
if n.left != nil {
n.left.parent = succ
}
if n.right != nil {
n.right.parent = succ
}
}
// rebalance all ancestors
for ; ancestor != nil; ancestor = ancestor.parent {
s.rebalance(ancestor)
}
s.returnNode(n)
}
//func (s *SweepStatus) Clear() {
// n := s.First()
// for n != nil {
// cur := n
// n = n.Next()
// s.returnNode(cur)
// }
// s.root = nil
//}
func (s *SweepPoint) LessH(b *SweepPoint) bool {
// used for sweep queue
if s.X != b.X {
return s.X < b.X // sort left to right
} else if s.Y != b.Y {
return s.Y < b.Y // then bottom to top
} else if s.left != b.left {
return b.left // handle right-endpoints before left-endpoints
} else if s.compareTangentsV(b) < 0 {
return true // sort upwards, this ensures CCW orientation order of result
}
return false
}
func (s *SweepPoint) CompareH(b *SweepPoint) int {
// used for nodes in tolerance square so that a.X==b.X and a.Y==b.Y
// sort left-to-right, then bottom-to-top, then right-endpoints before left-endpoints, and then
// sort upwards to ensure a CCW orientation of the result
//if a.X < b.X {
// return -1
//} else if b.X < a.X {
// return 1
//} else if a.Y < b.Y {
// return -1
//} else if b.Y < a.Y {
// return 1
if !s.left && b.left {
return -1
} else if s.left && !b.left {
return 1
}
return s.compareTangentsV(b)
}
func (s *SweepPoint) compareOverlapsV(b *SweepPoint) int {
// compare segments vertically that overlap (ie. are the same)
if s.clipping != b.clipping {
// clipping path is virtually on top (or left if vertical) of subject
if b.clipping {
return -1
} else {
return 1
}
}
// higher segment index is virtually on top
if s.segment != b.segment {
if s.segment < b.segment {
return -1
} else {
return 1
}
}
return 0
}
func (s *SweepPoint) compareTangentsV(b *SweepPoint) int {
// compare segments vertically at a.X, b.X <= a.X, and a and b coincide at (a.X,a.Y)
// note that a.left==b.left, we may be comparing right-endpoints
sign := 1
if !s.left {
sign = -1
}
if s.vertical {
// a is vertical
if b.vertical {
// a and b are vertical, a.X == b.X
// this implies a.Y == b.Y, otherwise we never arrive here
return sign * s.compareOverlapsV(b)
}
return 1
} else if b.vertical {
// b is vertical
return -1
}
if s.other.X == b.other.X && s.other.Y == b.other.Y {
return sign * s.compareOverlapsV(b)
} else if s.left && s.other.X < b.other.X || !s.left && b.other.X < s.other.X {
by := b.InterpolateY(s.other.X) // b's y at a's other
if s.other.Y == by {
return sign * s.compareOverlapsV(b)
} else if s.other.Y < by {
return sign * -1
} else {
return sign * 1
}
} else {
ay := s.InterpolateY(b.other.X) // a's y at b's other
if ay == b.other.Y {
return sign * s.compareOverlapsV(b)
} else if ay < b.other.Y {
return sign * -1
} else {
return sign * 1
}
}
}
func (s *SweepPoint) compareV(b *SweepPoint) int {
// compare segments vertically at a.X and b.X < a.X
// note that by is never very large, +/- infinity, or NaN as a result of both segments being in SweepStatus
by := b.InterpolateY(s.X) // b's y at a's left
if by < s.Y {
return 1
} else if s.Y < by {
return -1
} else {
return s.compareTangentsV(b)
}
}
func (s *SweepPoint) CompareV(b *SweepPoint) int {
// used for sweep status, a is the point to be inserted / found
// note that both points must be in SweepStatus: a.X <= b.other.X and b.X <= a.other.X
if s.X == b.X {
// left-point at same X
if s.Y == b.Y {
// left-point the same
return s.compareTangentsV(b)
} else if s.Y < b.Y {
return -1
} else {
return 1
}
} else if s.X < b.X {
// a starts to the left of b
return -b.compareV(s)
} else {
// a starts to the right of b
return s.compareV(b)
}
}
//type SweepPointPair [2]*SweepPoint
//
//func (pair SweepPointPair) Swapped() SweepPointPair {
// return SweepPointPair{pair[1], pair[0]}
//}
func addIntersections(zs []math32.Vector2, queue *SweepEvents, event, a, b *SweepPoint) bool {
// a and b are always left-endpoints and a is below b
//pair := SweepPointPair{a, b}
//if _, ok := handled[pair]; ok {
// return
//} else if _, ok := handled[pair.Swapped()]; ok {
// return
//}
//handled[pair] = struct{}{}
//var a, b *SweepPoint
//if prev == nil {
// a, b = event, next.SweepPoint
//} else if next == nil {
// a, b = prev.SweepPoint, event
//} else {
// a, b = prev.SweepPoint, next.SweepPoint
//}
// find all intersections between segment pair
// this returns either no intersections, or one or more secant/tangent intersections,
// or exactly two endpoint intersections which occurs when the segments overlap.
zs = intersectionLineLineBentleyOttmann(zs[:0], a.Vector2, a.other.Vector2, b.Vector2, b.other.Vector2)
// no (valid) intersections
if len(zs) == 0 {
return false
}
// Non-vertical but downwards-sloped segments may become vertical upon intersection due to
// floating-point rounding and limited precision. Only the first segment of b can ever become
// vertical, never the first segment of a:
// - a and b may be segments in status when processing a right-endpoint. The left-endpoints of
// both thus must be to the left of this right-endpoint (unless vertical) and can never
// become vertical in their first segment.
// - a is the segment of the currently processed left-endpoint and b is in status and above it.
// a's left-endpoint is to the right of b's left-endpoint and is below b, thus:
// - a and b go upwards: a nor b may become vertical, no reversal
// - a goes downwards and b upwards: no intersection
// - a goes upwards and b downwards: only a may become vertical but no reversal
// - a and b go downwards: b may pass a's left-endpoint to its left (no intersection),
// through it (tangential intersection, no splitting), or to its right so that a never
// becomes vertical and thus no reversal
// - b is the segment of the currently processed left-endpoint and a is in status and below it.
// a's left-endpoint is below or to the left of b's left-endpoint and a is below b, thus:
// - a and b go upwards: only a may become vertical, no reversal
// - a goes downwards and b upwards: no intersection
// - a goes upwards and b downwards: both may become vertical where only b must be reversed
// - a and b go downwards: if b passes through a's left-endpoint, it must become vertical and
// be reversed, or it passed to the right of a's left-endpoint and a nor b become vertical
// Conclusion: either may become vertical, but only b ever needs reversal of direction. And
// note that b is the currently processed left-endpoint and thus isn't in status.
// Note: handle overlapping segments immediately by checking up and down status for segments
// that compare equally with weak ordering (ie. overlapping).
if !event.left {
// intersection may be to the left (or below) the current event due to floating-point
// precision which would interfere with the sequence in queue, this is a problem when
// handling right-endpoints. New intersections must be at, or to the right/above the
// current event.
for i := range zs {
//zold := zs[i]
// NOTE: an intersections _may_ move to the right/above the current segments
z := &zs[i]
if z.X < event.X {
z.X = event.X
} else if z.X == event.X && z.Y < event.Y {
z.Y = event.Y
}
//aMaxY := math32.Max(a.Y, a.other.Y)
//bMaxY := math32.Max(b.Y, b.other.Y)
//if a.other.X < z.X || b.other.X < z.X || aMaxY < z.Y || bMaxY < z.Y {
// // TODO: handle/check this case, apparently a and b are both _below_ the event
// log.Println("WARNING: intersection moved outside of segment:", zold, "=>", z)
//}
}
}
// TODO: if we _did_ combine overlapping segments here, it might save us a lot of work after in finding intersections
// in the tolerance squares.
//// split segments a and b, but first find overlapping segments above and below and split them at the same point
//// this prevents a case that causes alternating intersections between overlapping segments and thus slowdown significantly
//if a.node != nil {
// splitOverlappingAtIntersections(zs, queue, a, true)
//}
aChanged := splitAtIntersections(zs, queue, a, true)
//if b.node != nil {
// splitOverlappingAtIntersections(zs, queue, b, false)
//}
bChanged := splitAtIntersections(zs, queue, b, false)
return aChanged || bChanged
}
//func splitOverlappingAtIntersections(zs []Point, queue *SweepEvents, s *SweepPoint, isA bool) bool {
// changed := false
// for prev := s.node.Prev(); prev != nil; prev = prev.Prev() {
// if prev.Point == s.Point && prev.other.Point == s.other.Point {
// splitAtIntersections(zs, queue, prev.SweepPoint, isA)
// changed = true
// }
// }
// if !changed {
// for next := s.node.Next(); next != nil; next = next.Next() {
// if next.Point == s.Point && next.other.Point == s.other.Point {
// splitAtIntersections(zs, queue, next.SweepPoint, isA)
// changed = true
// }
// }
// }
// return changed
//}
func splitAtIntersections(zs []math32.Vector2, queue *SweepEvents, s *SweepPoint, isA bool) bool {
changed := false
for i := len(zs) - 1; 0 <= i; i-- {
z := zs[i]
if z == s.Vector2 || z == s.other.Vector2 {
// ignore tangent intersections at the endpoints
continue
}
// split segment at intersection
right, left := s.SplitAt(z)
// reverse direction if necessary
if left.X == left.other.X {
// segment after the split is vertical
left.vertical, left.other.vertical = true, true
if left.other.Y < left.Y {
left.Reverse()
}
} else if right.X == right.other.X {
// segment before the split is vertical
right.vertical, right.other.vertical = true, true
if right.Y < right.other.Y {
// reverse first segment
if DebugPathIntersection && isA {
log.Println("WARNING: reversing first segment of A")
}
if right.other.node != nil {
// panic("impossible: first segment became vertical and needs reversal, but was already in the sweep status")
continue
}
right.Reverse()
// Note that we swap the content of the currently processed left-endpoint of b with
// the new left-endpoint vertically below. The queue may not be strictly ordered
// with other vertical segments at the new left-endpoint, but this isn't a problem
// since we sort the events in each square after the Bentley-Ottmann phase.
// update references from handled and queue by swapping their contents
first := right.other
*right, *first = *first, *right
first.other, right.other = right, first
}
}
// add to handled
//handled[SweepPointPair{a, bLeft}] = struct{}{}
//if aPrevLeft != a {
// // there is only one non-tangential intersection
// handled[SweepPointPair{aPrevLeft, bLeft}] = struct{}{}
//}
// add to queue
queue.Push(right)
queue.Push(left)
changed = true
}
return changed
}
//func reorderStatus(queue *SweepEvents, event *SweepPoint, aOld, bOld *SweepNode) {
// var aNew, bNew *SweepNode
// var aMove, bMove int
// if aOld != nil {
// // a == prev is a node in status that needs to be reordered
// aNew, aMove = aOld.fix()
// }
// if bOld != nil {
// // b == next is a node in status that needs to be reordered
// bNew, bMove = bOld.fix()
// }
//
// // find new intersections after snapping and moving around, first between the (new) neighbours
// // of a and b, and then check if any other segment became adjacent due to moving around a or b,
// // while avoiding superfluous checking for intersections (the aMove/bMove conditions)
// if aNew != nil {
// if prev := aNew.Prev(); prev != nil && aMove != bMove+1 {
// // b is not a's previous
// addIntersections(queue, event, prev, aNew)
// }
// if next := aNew.Next(); next != nil && aMove != bMove-1 {
// // b is not a's next
// addIntersections(queue, event, aNew, next)
// }
// }
// if bNew != nil {
// if prev := bNew.Prev(); prev != nil && bMove != aMove+1 {
// // a is not b's previous
// addIntersections(queue, event, prev, bNew)
// }
// if next := bNew.Next(); next != nil && bMove != aMove-1 {
// // a is not b's next
// addIntersections(queue, event, bNew, next)
// }
// }
// if aOld != nil && aMove != 0 && bMove != -1 {
// // a's old position is not aNew or bNew
// if prev := aOld.Prev(); prev != nil && aMove != -1 && bMove != -2 {
// // a nor b are not old a's previous
// addIntersections(queue, event, prev, aOld)
// }
// if next := aOld.Next(); next != nil && aMove != 1 && bMove != 0 {
// // a nor b are not old a's next
// addIntersections(queue, event, aOld, next)
// }
// }
// if bOld != nil && aMove != 1 && bMove != 0 {
// // b's old position is not aNew or bNew
// if aOld == nil {
// if prev := bOld.Prev(); prev != nil && aMove != 0 && bMove != -1 {
// // a nor b are not old b's previous
// addIntersections(queue, event, prev, bOld)
// }
// }
// if next := bOld.Next(); next != nil && aMove != 2 && bMove != 1 {
// // a nor b are not old b's next
// addIntersections(queue, event, bOld, next)
// }
// }
//}
type toleranceSquare struct {
X, Y float32 // snapped value
Events []*SweepPoint // all events in this square
// reference node inside or near the square
// after breaking up segments, this is the previous node (ie. completely below the square)
Node *SweepNode
// lower and upper node crossing this square
Lower, Upper *SweepNode
}
type toleranceSquares []*toleranceSquare
func (squares *toleranceSquares) find(x, y float32) (int, bool) {
// find returns the index of the square at or above (x,y) (or len(squares) if above all)
// the bool indicates if the square exists, otherwise insert a new square at that index
for i := len(*squares) - 1; 0 <= i; i-- {
if (*squares)[i].X < x || (*squares)[i].Y < y {
return i + 1, false
} else if (*squares)[i].Y == y {
return i, true
}
}
return 0, false
}
func (squares *toleranceSquares) Add(x float32, event *SweepPoint, refNode *SweepNode) {
// refNode is always the node itself for left-endpoints, and otherwise the previous node (ie.
// the node below) of a right-endpoint, or the next (ie. above) node if the previous is nil.
// It may be inside or outside the right edge of the square. If outside, it is the first such
// segment going upwards/downwards from the square (and not just any segment).
y := snap(event.Y, BentleyOttmannEpsilon)
if idx, ok := squares.find(x, y); !ok {
// create new tolerance square
square := boSquarePool.Get().(*toleranceSquare)
*square = toleranceSquare{
X: x,
Y: y,
Events: []*SweepPoint{event},
Node: refNode,
}
*squares = append((*squares)[:idx], append(toleranceSquares{square}, (*squares)[idx:]...)...)
} else {
// insert into existing tolerance square
(*squares)[idx].Node = refNode
(*squares)[idx].Events = append((*squares)[idx].Events, event)
}
// (nearly) vertical segments may still be used as the reference segment for squares around
// in that case, replace with the new reference node (above or below that segment)
if !event.left {
orig := event.other.node
for i := len(*squares) - 1; 0 <= i && (*squares)[i].X == x; i-- {
if (*squares)[i].Node == orig {
(*squares)[i].Node = refNode
}
}
}
}
//func (event *SweepPoint) insertIntoSortedH(events *[]*SweepPoint) {
// // O(log n)
// lo, hi := 0, len(*events)
// for lo < hi {
// mid := (lo + hi) / 2
// if (*events)[mid].LessH(event, false) {
// lo = mid + 1
// } else {
// hi = mid
// }
// }
//
// sorted := sort.IsSorted(eventSliceH(*events))
// if !sorted {
// log.Println("WARNING: H not sorted")
// for i, event := range *events {
// fmt.Println(i, event, event.Angle())
// }
// }
// *events = append(*events, nil)
// copy((*events)[lo+1:], (*events)[lo:])
// (*events)[lo] = event
// if sorted && !sort.IsSorted(eventSliceH(*events)) {
// log.Println("ERROR: not sorted after inserting into events:", *events)
// }
//}
func (s *SweepPoint) breakupSegment(events *[]*SweepPoint, index int, x, y float32) *SweepPoint {
// break up a segment in two parts and let the middle point be (x,y)
if snap(s.X, BentleyOttmannEpsilon) == x && snap(s.Y, BentleyOttmannEpsilon) == y || snap(s.other.X, BentleyOttmannEpsilon) == x && snap(s.other.Y, BentleyOttmannEpsilon) == y {
// segment starts or ends in tolerance square, don't break up
return s
}
// original segment should be kept in-place to not alter the queue or status
r, l := s.SplitAt(math32.Vec2(x, y))
r.square, l.square = index, index
// reverse
//if r.other.X == r.X {
// if l.other.Y < r.other.Y {
// r.Reverse()
// }
// r.vertical, r.other.vertical = true, true
//} else if l.other.X == l.X {
// if l.other.Y < r.other.Y {
// l.Reverse()
// }
// l.vertical, l.other.vertical = true, true
//}
// update node reference
if s.node != nil {
l.node, s.node = s.node, nil
l.node.SweepPoint = l
}
*events = append(*events, r, l)
return l
}
func (squares toleranceSquares) breakupCrossingSegments(n int, x float32) {
// find and break up all segments that cross this tolerance square
// note that we must move up to find all upwards-sloped segments and then move down for the
// downwards-sloped segments, since they may need to be broken up in other squares first
x0, x1 := x-BentleyOttmannEpsilon/2.0, x+BentleyOttmannEpsilon/2.0
// scan squares bottom to top
for i := n; i < len(squares); i++ {
square := squares[i] // pointer
// be aware that a tolerance square is inclusive of the left and bottom edge
// and only the bottom-left corner
yTop, yBottom := square.Y+BentleyOttmannEpsilon/2.0, square.Y-BentleyOttmannEpsilon/2.0
// from reference node find the previous/lower/upper segments for this square
// the reference node may be any of the segments that cross the right-edge of the square,
// or a segment below or above the right-edge of the square
if square.Node != nil {
y0, y1 := square.Node.ToleranceEdgeY(x0, x1)
below, above := y0 < yBottom && y1 <= yBottom, yTop <= y0 && yTop <= y1
if !below && !above {
// reference node is inside the square
square.Lower, square.Upper = square.Node, square.Node
}
// reference node is in or below, find upper node
if !above {
for next := square.Node.Next(); next != nil; next = next.Next() {
y0, y1 := next.ToleranceEdgeY(x0, x1)
if yTop <= y0 && yTop <= y1 {
// above
break
} else if y0 < yBottom && y1 <= yBottom {
// below
square.Node = next
continue
}
square.Upper = next
if square.Lower == nil {
// this is set if the reference node is below the square
square.Lower = next
}
}
}
// reference node is in or above, find lower node and set reference node to the node completely below the square
if !below {
prev := square.Node.Prev()
for ; prev != nil; prev = prev.Prev() {
y0, y1 := prev.ToleranceEdgeY(x0, x1)
if y0 < yBottom && y1 <= yBottom { // exclusive for bottom-right corner
// below
break
} else if yTop <= y0 && yTop <= y1 {
// above
square.Node = prev
continue
}
square.Lower = prev
if square.Upper == nil {
if DebugPathIntersection {
log.Println("NOTE: square without a segment above it")
}
square.Upper = prev
}
}
square.Node = prev
}
}
// find all segments that cross the tolerance square
// first find all segments that extend to the right (they are in the sweepline status)
if square.Lower != nil {
for node := square.Lower; ; node = node.Next() {
node.breakupSegment(&squares[i].Events, i, x, square.Y)
if node == square.Upper {
break
}
}
}
// then find which segments that end in this square go through other squares
for _, event := range square.Events {
if !event.left {
y0, _ := event.ToleranceEdgeY(x0, x1)
s := event.other
if y0 < yBottom {
// comes from below, find lowest square and breakup in each square
j0 := i
for j := i - 1; 0 <= j; j-- {
if squares[j].X != x || squares[j].Y+BentleyOttmannEpsilon/2.0 <= y0 {
break
}
j0 = j
}
for j := j0; j < i; j++ {
s = s.breakupSegment(&squares[j].Events, j, x, squares[j].Y)
}
} else if yTop <= y0 {
// comes from above, find highest square and breakup in each square
j0 := i
for j := i + 1; j < len(squares); j++ {
if y0 < squares[j].Y-BentleyOttmannEpsilon/2.0 {
break
}
j0 = j
}
for j := j0; i < j; j-- {
s = s.breakupSegment(&squares[j].Events, j, x, squares[j].Y)
}
}
}
}
}
}
type eventSliceV []*SweepPoint
func (a eventSliceV) Len() int {
return len(a)
}
func (a eventSliceV) Less(i, j int) bool {
return a[i].CompareV(a[j]) < 0
}
func (a eventSliceV) Swap(i, j int) {
a[i].node.SweepPoint, a[j].node.SweepPoint = a[j], a[i]
a[i].node, a[j].node = a[j].node, a[i].node
a[i], a[j] = a[j], a[i]
}
//type eventSliceH []*SweepPoint
//
//func (a eventSliceH) Len() int {
// return len(a)
//}
//
//func (a eventSliceH) Less(i, j int) bool {
// return a[i].LessH(a[j])
//}
//
//func (a eventSliceH) Swap(i, j int) {
// a[i], a[j] = a[j], a[i]
//}
// computeSweepFieldsInOrder computes the sweep fields of a non-vertical left-endpoint from the
// segment below it in the sweep status, computing that segment first when it starts in the same
// point and has not been computed yet. Left-endpoints of a tolerance square are visited in
// CompareH order, but windings propagate bottom-up along the sweep status, and for overlapping
// segments starting in the same point the two orders need not agree: a segment would then read
// the windings of a neighbour that has not been computed yet.
// (from https://github.com/tdewolff/canvas/pull/394)
func (s *SweepPoint) computeSweepFieldsInOrder(op pathOp, fillRule ppath.FillRules) {
if s.swept {
return
}
var prev *SweepPoint
if node := s.node.Prev(); node != nil {
prev = node.SweepPoint
if !prev.swept && prev.node != nil && prev.Vector2 == s.Vector2 {
prev.computeSweepFieldsInOrder(op, fillRule)
}
}
s.computeSweepFields(prev, op, fillRule)
}
func (s *SweepPoint) computeSweepFields(prev *SweepPoint, op pathOp, fillRule ppath.FillRules) {
s.swept = true
// cur is left-endpoint
if !s.open {
s.selfWindings = 1
if !s.increasing {
s.selfWindings = -1
}
}
// skip vertical segments
s.prev = prev
for prev != nil && prev.vertical {
prev = prev.prev
}
// compute windings
if prev != nil {
if s.clipping == prev.clipping {
s.windings = prev.windings + prev.selfWindings
s.otherWindings = prev.otherWindings + prev.otherSelfWindings
} else {
s.windings = prev.otherWindings + prev.otherSelfWindings
s.otherWindings = prev.windings + prev.selfWindings
}
} else {
// may have been copied when intersected / broken up
s.windings, s.otherWindings = 0, 0
}
s.inResult = s.InResult(op, fillRule)
s.other.inResult = s.inResult
}
func (s *SweepPoint) InResult(op pathOp, fillRule ppath.FillRules) uint8 {
lowerWindings, lowerOtherWindings := int(s.windings), int(s.otherWindings)
upperWindings, upperOtherWindings := int(s.windings+s.selfWindings), int(s.otherWindings+s.otherSelfWindings)
if s.clipping {
lowerWindings, lowerOtherWindings = lowerOtherWindings, lowerWindings
upperWindings, upperOtherWindings = upperOtherWindings, upperWindings
}
if s.open {
// handle open paths on the subject
switch op {
case opSettle, opOR, opDIV:
return 1
case opAND:
if fillRule.Fills(lowerOtherWindings) || fillRule.Fills(upperOtherWindings) {
return 1
}
case opNOT, opXOR:
if !fillRule.Fills(lowerOtherWindings) || !fillRule.Fills(upperOtherWindings) {
return 1
}
}
return 0
}
// lower/upper windings refers to subject path, otherWindings to clipping path
var belowFills, aboveFills bool
switch op {
case opSettle:
belowFills = fillRule.Fills(lowerWindings)
aboveFills = fillRule.Fills(upperWindings)
case opAND:
belowFills = fillRule.Fills(lowerWindings) && fillRule.Fills(lowerOtherWindings)
aboveFills = fillRule.Fills(upperWindings) && fillRule.Fills(upperOtherWindings)
case opOR:
belowFills = fillRule.Fills(lowerWindings) || fillRule.Fills(lowerOtherWindings)
aboveFills = fillRule.Fills(upperWindings) || fillRule.Fills(upperOtherWindings)
case opNOT:
belowFills = fillRule.Fills(lowerWindings) && !fillRule.Fills(lowerOtherWindings)
aboveFills = fillRule.Fills(upperWindings) && !fillRule.Fills(upperOtherWindings)
case opXOR:
belowFills = fillRule.Fills(lowerWindings) != fillRule.Fills(lowerOtherWindings)
aboveFills = fillRule.Fills(upperWindings) != fillRule.Fills(upperOtherWindings)
case opDIV:
belowFills = fillRule.Fills(lowerWindings)
aboveFills = fillRule.Fills(upperWindings)
if belowFills && aboveFills {
return 2
} else if belowFills || aboveFills {
return 1
}
return 0
}
// only keep edge if there is a change in filling between both sides
if belowFills != aboveFills {
return 1
}
return 0
}
func (s *SweepPoint) mergeOverlapping(op pathOp, fillRule ppath.FillRules) {
// When merging overlapping segments, the order of the right-endpoints may have changed and
// thus be different from the order used to compute the sweep fields, here we reset the values
// for windings and otherWindings to be taken from the segment below (prev) which was updated
// after snapping the endpoints.
// We use event.overlapped to handle segments once and count windings once, in whichever order
// the events are handled. We also update prev to reflect the segment below the overlapping
// segments.
if s.overlapped {
// already handled
return
}
prev := s.prev
for ; prev != nil; prev = prev.prev {
if prev.overlapped || s.Vector2 != prev.Vector2 || s.other.Vector2 != prev.other.Vector2 {
break
}
// combine selfWindings
if s.clipping == prev.clipping {
s.selfWindings += prev.selfWindings
s.otherSelfWindings += prev.otherSelfWindings
} else {
s.selfWindings += prev.otherSelfWindings
s.otherSelfWindings += prev.selfWindings
}
prev.windings, prev.selfWindings, prev.otherWindings, prev.otherSelfWindings = 0, 0, 0, 0
prev.inResult, prev.other.inResult = 0, 0
prev.overlapped = true
}
if prev == s.prev {
return
}
// compute merged windings
if prev == nil {
s.windings, s.otherWindings = 0, 0
} else if s.clipping == prev.clipping {
s.windings = prev.windings + prev.selfWindings
s.otherWindings = prev.otherWindings + prev.otherSelfWindings
} else {
s.windings = prev.otherWindings + prev.otherSelfWindings
s.otherWindings = prev.windings + prev.selfWindings
}
s.inResult = s.InResult(op, fillRule)
s.other.inResult = s.inResult
s.prev = prev
}
func bentleyOttmann(ps, qs ppath.Paths, op pathOp, fillRule ppath.FillRules) ppath.Paths {
// TODO: add grid spacing argument
// TODO: add Intersects/Touches functions (return bool)
// TODO: add Intersections function (return []Point)
// TODO: support Cut to cut a path in subpaths between intersections (not polygons)
// TODO: support elliptical arcs
// TODO: use a red-black tree for the sweepline status?
// TODO: use a red-black or 2-4 tree for the sweepline queue (LessH is 33% of time spent now),
// perhaps a red-black tree where the nodes are min-queues of the resulting squares
// TODO: optimize path data by removing commands, set number of same command (50% less memory)
// TODO: can we get idempotency (same result after second time) by tracing back each snapped
// right-endpoint for the squares it may now intersect? (Hershberger 2013)
// TODO: if overlapping segments can be detected earlier, we can just process left-events
// and make the code simpler
// Implementation of the Bentley-Ottmann algorithm by reducing the complexity of finding
// intersections to O((n + k) log n), with n the number of segments and k the number of
// intersections. All special cases are handled by use of:
// - M. de Berg, et al., "Computational Geometry", Chapter 2, DOI: 10.1007/978-3-540-77974-2
// - F. Martínez, et al., "A simple algorithm for Boolean operations on polygons", Advances in
// Engineering Software 64, p. 11-19, 2013, DOI: 10.1016/j.advengsoft.2013.04.004
// - J. Hobby, "Practical segment intersection with finite precision output", Computational
// Geometry, 1997
// - J. Hershberger, "Stable snap rounding", Computational Geometry: Theory and Applications,
// 2013, DOI: 10.1016/j.comgeo.2012.02.011
// - https://github.com/verven/contourklip
// Bentley-Ottmann is the most popular algorithm to find path intersections, which is mainly
// due to it's relative simplicity and the fact that it is (much) faster than the naive
// approach. It however does not specify how special cases should be handled (overlapping
// segments, multiple segment endpoints in one point, vertical segments), which is treated in
// later works by other authors (e.g. Martínez from which this implementation draws
// inspiration). I've made some small additions and adjustments to make it work in all cases
// I encountered. Specifically, this implementation has the following properties:
// - Subject and clipping paths may consist of any number of contours / subpaths.
// - Any contour may be oriented clockwise (CW) or counter-clockwise (CCW).
// - Any path or contour may self-intersect any number of times.
// - Any point may be crossed multiple times by any path.
// - Segments may overlap any number of times by any path.
// - Segments may be vertical.
// - The clipping path is implicitly closed, it makes no sense if it is an open path.
// - The subject path is currently implicitly closed, but it is WIP to support open paths.
// - ppath.Paths are currently flattened, but supporting Bézier or elliptical arcs is a WIP.
// An unaddressed problem in those works is that of numerical accuracies. The main problem is
// that calculating the intersections is not precise; the imprecision of the initial endpoints
// of a path can be trivially fixed before the algorithm. Intersections however are calculated
// during the algorithm and must be addressed. There are a few authors that propose a solution,
// and Hobby's work inspired this implementation. The approach taken is somewhat different
// though:
// - Instead of integers (or rational numbers implemented using integers), floating points are
// used for their speed. It isn't even necessary that the grid points can be represented
// exactly in the floating point format, as long as all points in the tolerance square around
// the grid points snap to the same point. Now we can compare using == instead of an equality
// test.
// - As in Martínez, we treat an intersection as a right- and left-endpoint combination and not
// as a third type of event. This avoids rearrangement of events in the sweep status as it is
// removed and reinserted into the right position, but at the cost of more delete/insert
// operations in the sweep status (potential to improve performance).
// - As we run the Bentley-Ottmann algorithm, found endpoints must also be snapped to the grid.
// Since intersections are found in advance (ie. towards the right), we have no idea how the
// sweepline status will be yet, so we cannot snap those intersections to the grid yet. We
// must snap all endpoints/intersections when we reach them (ie. pop them off the queue).
// When we get to an endpoint, snap all endpoints in the tolerance square around the grid
// point to that point, and process all endpoints and intersections. Additionally, we should
// break-up all segments that pass through the square into two, and snap them to the grid
// point as well. These segments pass very close to another endpoint, and by snapping those
// to the grid we avoid the problem where we may or may not find that the segment intersects.
// - Note that most (not all) intersections on the right are calculated with the left-endpoint
// already snapped, which may move the intersection to another grid point. These inaccuracies
// depend on the grid spacing and can be made small relative to the size of the input paths.
//
// The difference with Hobby's steps is that we advance Bentley-Ottmann for the entire column,
// and only then do we calculate crossing segments. I'm not sure what reason Hobby has to do
// this in two phases. Also, Hobby uses a shadow sweep line status structure which contains the
// segments sorted after snapping. Instead of using two sweep status structures (the original
// Bentley-Ottmann and the shadow with snapped segments), we sort the status after each column.
// Additionally, we need to keep the sweep line queue structure ordered as well for the result
// polygon (instead of the queue we gather the events for each square, and sort those), and we
// need to calculate the sweep fields for the result polygon.
//
// It is best to think of processing the tolerance squares, one at a time moving bottom-to-top,
// for each column while moving the sweepline from left to right. Since all intersections
// in this implementation are already converted to two right-endpoints and two left-endpoints,
// we do all the snapping after each column and snapping the endpoints beforehand is not
// necessary. We pop off all events from the queue that belong to the same column and process
// them as we would with Bentley-Ottmann. This ensures that we find all original locations of
// the intersections (except for intersections between segments in the sweep status structure
// that are not yet adjacent, see note above) and may introduce new tolerance squares. For each
// square, we find all segments that pass through and break them up and snap them to the grid.
// Then snap all endpoints in the
// square to the grid. We must sort the sweep line status and all events per square to account
// for the new order after snapping. Some implementation observations:
// - We must breakup segments that cross the square BEFORE we snap the square's endpoints,
// since we depend on the order of in the sweep status (from after processing the column
// using the original Bentley-Ottmann sweep line) for finding crossing segments.
// - We find all original locations of intersections for adjacent segments during and after
// processing the column. However, if intersections become adjacent later on, the
// left-endpoint has already been snapped and the intersection has moved.
// - We must be careful with overlapping segments. Since gridsnapping may introduce new
// overlapping segments (potentially vertical), we must check for that when processing the
// right-endpoints of each square.
//
// We thus proceed as follows:
// - Process all events from left-to-right in a column using the regular Bentley-Ottmann.
// - Identify all "hot" squares (those that contain endpoints / intersections).
// - Find all segments that pass through each hot square, break them up and snap to the grid.
// These may be segments that start left of the column and end right of it, but also segments
// that start or end inside the column, or even start AND end inside the column (eg. vertical
// or almost vertical segments).
// - Snap all endpoints and intersections to the grid.
// - Compute sweep fields / windings for all new left-endpoints.
// - Handle segments that are now overlapping for all right-endpoints.
// Note that we must be careful with vertical segments.
boInitPoolsOnce() // use pools for SweepPoint and SweepNode to amortize repeated calls to BO
// return when one path is empty
if op == opSettle {
qs = nil
} else if qs.Empty() {
if op == opAND {
return []ppath.Path{}
}
return SettleRings(ps, fillRule)
}
if ps.Empty() {
if qs != nil && (op == opOR || op == opXOR) {
return SettleRings(qs, fillRule)
}
return []ppath.Path{}
}
// ensure that X-monotone property holds for Béziers and arcs by breaking them up at their
// extremes along X (ie. their inflection points along X)
// TODO: handle Béziers and arc segments
//p = p.XMonotone()
//q = q.XMonotone()
for i, iMax := 0, len(ps); i < iMax; i++ {
split := ps[i].Split()
if 1 < len(split) {
ps[i] = split[0]
ps = append(ps, split[1:]...)
}
}
for i := range ps {
ps[i] = Flatten(ps[i], ppath.Tolerance)
}
if qs != nil {
for i, iMax := 0, len(qs); i < iMax; i++ {
split := qs[i].Split()
if 1 < len(split) {
qs[i] = split[0]
qs = append(qs, split[1:]...)
}
}
for i := range qs {
qs[i] = Flatten(qs[i], ppath.Tolerance)
}
}
// check for path bounding boxes to overlap
// TODO: cluster paths that overlap and treat non-overlapping clusters separately, this
// makes the algorithm "more linear"
Rs := []ppath.Path{}
//var pOverlaps, qOverlaps []bool
//if qs != nil {
// pBounds := make([]math32.Box2, len(ps))
// qBounds := make([]math32.Box2, len(qs))
// for i := range ps {
// pBounds[i] = ps[i].FastBounds()
// }
// for i := range qs {
// qBounds[i] = qs[i].FastBounds()
// }
// pOverlaps = make([]bool, len(ps))
// qOverlaps = make([]bool, len(qs))
// for i := range ps {
// for j := range qs {
// if pBounds[i].Touches(qBounds[j]) {
// pOverlaps[i] = true
// qOverlaps[j] = true
// }
// }
// if !pOverlaps[i] && (op == opOR || op == opXOR || op == opNOT) {
// // path bounding boxes do not overlap, thus no intersections
// pOverlaps[i] = true
// //Rs = append(Rs, ps[i].Settle(fillRule))
// }
// }
// for j := range qs {
// if !qOverlaps[j] && (op == opOR || op == opXOR) {
// // path bounding boxes do not overlap, thus no intersections
// qOverlaps[j] = true
// //Rs = append(Rs, qs[j].Settle(fillRule))
// }
// }
//}
// construct the priority queue of sweep events
pSeg, qSeg := 0, 0
queue := &SweepEvents{}
for i := range ps {
//if qs == nil || pOverlaps[i] {
pSeg = queue.AddPathEndpoints(ps[i], pSeg, false)
//}
}
for i := range qs {
//if qOverlaps[i] {
qs[i].Close() // implicitly close all subpaths on Q
qSeg = queue.AddPathEndpoints(qs[i], qSeg, true)
//}
}
queue.Init() // sort from left to right
// run sweep line left-to-right
zs := make([]math32.Vector2, 0, 2) // buffer for intersections
centre := &SweepPoint{} // allocate here to reduce allocations
events := []*SweepPoint{} // buffer used for ordering status
status := &SweepStatus{} // contains only left events
squares := toleranceSquares{} // sorted vertically, squares and their events
// TODO: use linked list for toleranceSquares?
for 0 < len(*queue) {
// TODO: skip or stop depending on operation if we're to the left/right of subject/clipping polygon
// We slightly divert from the original Bentley-Ottmann and paper implementation. First
// we find the top element in queue but do not pop it off yet. If it is a right-event, pop
// from queue and proceed as usual, but if it's a left-event we first check (and add) all
// surrounding intersections to the queue. This may change the order from which we should
// pop off the queue, since intersections may create right-events, or new left-events that
// are lower (by compareTangentV). If no intersections are found, pop off the queue and
// proceed as usual.
// Pass 1
// process all events of the current column
n := len(squares)
x := snap(queue.Top().X, BentleyOttmannEpsilon)
//fmt.Println()
//fmt.Println("---")
//fmt.Println("X", x)
//fmt.Println(queue)
//fmt.Println(status)
BentleyOttmannLoop:
for 0 < len(*queue) && snap(queue.Top().X, BentleyOttmannEpsilon) == x {
event := queue.Top()
// TODO: breaking intersections into two right and two left endpoints is not the most
// efficient. We could keep an intersection-type event and simply swap the order of the
// segments in status (note there can be multiple segments crossing in one point). This
// would alleviate a 2*m*log(n) search in status to remove/add the segments (m number
// of intersections in one point, and n number of segments in status), and instead use
// an m/2 number of swap operations. This alleviates pressure on the CompareV method.
if !event.left {
queue.Pop()
n := event.other.node
if n == nil {
// panic("right-endpoint not part of status, probably buggy intersection code")
// don't put back in boPointPool, rare event
continue
} else if n.SweepPoint == nil {
// this may happen if the left-endpoint is to the right of the right-endpoint
// for some reason, usually due to a bug in the segment intersection code
// panic("other endpoint already removed, probably buggy intersection code")
// don't put back in boPointPool, rare event
continue
}
// find intersections between the now adjacent segments
prev := n.Prev()
next := n.Next()
if prev != nil && next != nil {
addIntersections(zs, queue, event, prev.SweepPoint, next.SweepPoint)
}
// add event to tolerance square
if prev != nil {
squares.Add(x, event, prev)
} else {
// next can be nil
squares.Add(x, event, next)
}
// remove event from sweep status
status.Remove(n)
} else {
// add intersections to queue
prev, next := status.FindPrevNext(event)
if prev != nil {
addIntersections(zs, queue, event, prev.SweepPoint, event)
}
if next != nil {
addIntersections(zs, queue, event, event, next.SweepPoint)
}
if queue.Top() != event {
// check if the queue order was changed, this happens if the current event
// is the left-endpoint of a segment that intersects with an existing segment
// that goes below, or when two segments become fully overlapping, which sets
// their order in status differently than when one of them extends further
continue
}
queue.Pop()
// add event to sweep status
n := status.InsertAfter(prev, event)
// add event to tolerance square
squares.Add(x, event, n)
}
}
// Pass 2
// find all crossing segments, break them up and snap to the grid
squares.breakupCrossingSegments(n, x)
// snap events to grid
// note that this may make segments overlapping from the left and towards the right
// we handle the former below, but ignore the latter which may result in overlapping
// segments not being strictly ordered
for j := n; j < len(squares); j++ {
del := 0
square := squares[j] // pointer
for i := 0; i < len(square.Events); i++ {
event := square.Events[i]
event.square = j
event.X, event.Y = x, square.Y
other := Gridsnap(event.other.Vector2, BentleyOttmannEpsilon)
if event.Vector2 == other {
// remove collapsed segments, we aggregate them with `del` to improve performance when we have many
// TODO: prevent creating these segments in the first place
del++
} else {
if 0 < del {
for _, event := range square.Events[i-del : i] {
if !event.left {
boPointPool.Put(event.other)
boPointPool.Put(event)
}
}
square.Events = append(square.Events[:i-del], square.Events[i:]...)
i -= del
del = 0
}
if event.X == other.X {
// correct for segments that have become vertical due to snap/breakup
event.vertical, event.other.vertical = true, true
if !event.left && event.Y < other.Y {
// downward sloped, reverse direction
event.Reverse()
}
}
}
}
if 0 < del {
for _, event := range square.Events[len(square.Events)-del:] {
if !event.left {
boPointPool.Put(event.other)
boPointPool.Put(event)
}
}
square.Events = square.Events[:len(square.Events)-del]
}
}
for _, square := range squares[n:] {
// reorder sweep status and events for result polygon
// note that the number of events/nodes is usually small
// and note that we must first snap all segments in this column before sorting
if square.Lower != nil {
events = events[:0]
for n := square.Lower; ; n = n.Next() {
events = append(events, n.SweepPoint)
if n == square.Upper {
break
}
}
// TODO: test this thoroughly, this below prevents long loops of moving intersections to columns on the right
for n := square.Lower; n != square.Upper; {
next := n.Next()
if 0 < n.CompareV(next.SweepPoint) {
if next.other.X < n.other.X {
r, l := n.SplitAt(next.other.Vector2)
queue.Push(r)
queue.Push(l)
} else if n.other.X < next.other.X {
r, l := next.SplitAt(n.other.Vector2)
queue.Push(r)
queue.Push(l)
}
}
n = next
}
// keep unsorted events in the same slice
n := len(events)
events = append(events, events...)
origEvents := events[n:]
events = events[:n]
sort.Sort(eventSliceV(events))
// find intersections between neighbouring segments due to snapping
// TODO: ugly!
has := false
centre.Vector2 = math32.Vec2(square.X, square.Y)
if prev := square.Lower.Prev(); prev != nil {
has = addIntersections(zs, queue, centre, prev.SweepPoint, square.Lower.SweepPoint)
}
if next := square.Upper.Next(); next != nil {
has = has || addIntersections(zs, queue, centre, square.Upper.SweepPoint, next.SweepPoint)
}
// find intersections between new neighbours in status after sorting
for i, event := range events[:len(events)-1] {
if event != origEvents[i] {
n := event.node
var j int
for origEvents[j] != event {
j++
}
if next := n.Next(); next != nil && (j == 0 || next.SweepPoint != origEvents[j-1]) && (j+1 == len(origEvents) || next.SweepPoint != origEvents[j+1]) {
// segment changed order and the segment above was not its neighbour
has = has || addIntersections(zs, queue, centre, n.SweepPoint, next.SweepPoint)
}
}
}
if 0 < len(*queue) && snap(queue.Top().X, BentleyOttmannEpsilon) == x {
// TODO: find a test to cover this case
if DebugPathIntersection {
log.Println("WARNING: new intersections in this column!")
}
goto BentleyOttmannLoop // TODO: is this correct? seems to work
// TODO: almost parallel combined with overlapping segments may create many intersections considering order of
// of overlapping segments and snapping after each column
} else if has {
// sort overlapping segments again
// this is needed when segments get cut and now become equal to the adjacent
// overlapping segments
// TODO: segments should be sorted by segment ID when overlapping, even if
// one segment extends further than the other, is that due to floating
// point accuracy?
sort.Sort(eventSliceV(events))
}
}
slices.SortFunc(square.Events, (*SweepPoint).CompareH)
// compute sweep fields on left-endpoints
for i, event := range square.Events {
if !event.left {
event.other.mergeOverlapping(op, fillRule)
} else if event.node == nil {
// vertical
if 0 < i && square.Events[i-1].left {
// against last left-endpoint in square
// inside this square there are no crossing segments, they have been broken
// up and have their left-endpoints sorted
event.computeSweepFields(square.Events[i-1], op, fillRule)
} else {
// against first segment below square
// square.Node may be nil
var s *SweepPoint
if square.Node != nil {
s = square.Node.SweepPoint
}
event.computeSweepFields(s, op, fillRule)
}
} else {
event.computeSweepFieldsInOrder(op, fillRule)
}
}
}
}
//status.Clear() // release all nodes (but not SweepPoints) // already cleared!
//for _, square := range squares {
// for _, event := range square.Events {
// if event.left {
// fmt.Println(event, event.prev, event.inResult, "--", event.windings, event.selfWindings)
// }
// }
//}
// build resulting polygons
var Ropen ppath.Path
for _, square := range squares {
for _, cur := range square.Events {
if !cur.left || cur.inResult == 0 {
// skip
continue
}
BuildPath:
windings := int16(0) // windings (outside) of the current polygon
index := len(Rs) + 1 // index into Rs + 1 to group (outer) filling with (inner) holes, 0 means resultWindings is invalid
if op != opDIV {
prev := cur.prev
for prev != nil && prev.index == 0 {
prev = prev.prev
}
if prev != nil {
windings = prev.resultWindings
if windings%2 != 0 {
// current ring is a hole
index = prev.index
}
}
}
first := cur
R := ppath.Path{}
R.MoveTo(cur.X, cur.Y)
cur.index = index
cur.resultWindings = windings
if !first.open {
// TODO: should be += selfWindings? test with open paths
cur.resultWindings++
}
for {
// find segments starting from other endpoint, find the other segment amongst
// them, the next segment should be the next going CCW
i0 := 0
nodes := squares[cur.other.square].Events
for i := range nodes {
if nodes[i] == cur.other {
i0 = i
break
}
}
// find the next segment in CW order, this will make smaller subpaths
// instead one large path when multiple segments end at the same position
var next *SweepPoint
for i := i0 - 1; ; i-- {
if i < 0 {
i += len(nodes)
}
if i == i0 {
break
} else if 0 < nodes[i].inResult && nodes[i].open == first.open {
next = nodes[i]
break
}
}
if next == nil {
// (in the debug mode of canvas, a closed path panics here:
// "next node for result polygon is nil, probably buggy
// intersection code")
if first.open || !DebugPathIntersection {
R.LineTo(cur.other.X, cur.other.Y)
}
break
} else if next == first {
first.open = false // open path encloses area
break // contour is done
}
cur = next
R.LineTo(cur.X, cur.Y)
if cur.left {
// we go to the right/top
cur.inResult--
cur.index = index
cur.resultWindings = windings
if !first.open {
// TODO: should be += selfWindings? test with open paths
cur.resultWindings++
}
} else {
cur.other.inResult--
cur.other.index = index
cur.other.resultWindings = windings
}
}
first.inResult--
if first.open {
// open path, merge separate parts
// TODO: relevant?
if Ropen != nil {
R = R.Reverse()
R = append(R, Ropen[4:]...)
Ropen = nil
} else {
for _, cur2 := range square.Events {
if 0 < cur2.inResult && cur2.open {
cur = cur2
Ropen = R
goto BuildPath
}
}
}
Rs = append(Rs, R)
} else {
R.Close()
if windings%2 != 0 {
// orient holes clockwise and put together with outer filling ring
R = R.Reverse()
Rs[index-1] = Rs[index-1].Append(R)
} else {
// filling ring
Rs = append(Rs, R)
}
}
}
for _, event := range square.Events {
if !event.left {
boPointPool.Put(event.other)
boPointPool.Put(event)
}
}
boSquarePool.Put(square)
}
return Rs
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This is adapted from https://github.com/tdewolff/canvas
// Copyright (c) 2015 Taco de Wolff, under an MIT License.
package intersect
import (
"fmt"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint/ppath"
)
// see https://github.com/signavio/svg-intersections
// see https://github.com/w8r/bezier-intersect
// see https://cs.nyu.edu/exact/doc/subdiv1.pdf
// IntersectionSegment returns the intersections of path segments a and b, starting at a0 and b0.
// Note that all intersection functions return up to two intersections.
func IntersectionSegment(zs Intersections, a0 math32.Vector2, a ppath.Path, b0 math32.Vector2, b ppath.Path) Intersections {
n := len(zs)
swapCurves := false
switch a[0] {
case ppath.LineTo, ppath.Close:
switch b[0] {
case ppath.LineTo, ppath.Close:
zs = intersectionLineLine(zs, a0, math32.Vec2(a[1], a[2]), b0, math32.Vec2(b[1], b[2]))
case ppath.QuadTo:
zs = intersectionLineQuad(zs, a0, math32.Vec2(a[1], a[2]), b0, math32.Vec2(b[1], b[2]), math32.Vec2(b[3], b[4]))
case ppath.CubeTo:
zs = intersectionLineCube(zs, a0, math32.Vec2(a[1], a[2]), b0, math32.Vec2(b[1], b[2]), math32.Vec2(b[3], b[4]), math32.Vec2(b[5], b[6]))
case ppath.ArcTo:
rx := b[1]
ry := b[2]
phi := b[3]
large, sweep := ppath.ToArcFlags(b[4])
cx, cy, theta0, theta1 := ppath.EllipseToCenter(b0.X, b0.Y, rx, ry, phi, large, sweep, b[5], b[6])
zs = intersectionLineEllipse(zs, a0, math32.Vec2(a[1], a[2]), math32.Vec2(cx, cy), math32.Vec2(rx, ry), phi, theta0, theta1)
}
case ppath.QuadTo:
switch b[0] {
case ppath.LineTo, ppath.Close:
zs = intersectionLineQuad(zs, b0, math32.Vec2(b[1], b[2]), a0, math32.Vec2(a[1], a[2]), math32.Vec2(a[3], a[4]))
swapCurves = true
case ppath.QuadTo:
panic("unsupported intersection for quad-quad")
case ppath.CubeTo:
panic("unsupported intersection for quad-cube")
case ppath.ArcTo:
panic("unsupported intersection for quad-arc")
}
case ppath.CubeTo:
switch b[0] {
case ppath.LineTo, ppath.Close:
zs = intersectionLineCube(zs, b0, math32.Vec2(b[1], b[2]), a0, math32.Vec2(a[1], a[2]), math32.Vec2(a[3], a[4]), math32.Vec2(a[5], a[6]))
swapCurves = true
case ppath.QuadTo:
panic("unsupported intersection for cube-quad")
case ppath.CubeTo:
panic("unsupported intersection for cube-cube")
case ppath.ArcTo:
panic("unsupported intersection for cube-arc")
}
case ppath.ArcTo:
rx := a[1]
ry := a[2]
phi := a[3]
large, sweep := ppath.ToArcFlags(a[4])
cx, cy, theta0, theta1 := ppath.EllipseToCenter(a0.X, a0.Y, rx, ry, phi, large, sweep, a[5], a[6])
switch b[0] {
case ppath.LineTo, ppath.Close:
zs = intersectionLineEllipse(zs, b0, math32.Vec2(b[1], b[2]), math32.Vec2(cx, cy), math32.Vec2(rx, ry), phi, theta0, theta1)
swapCurves = true
case ppath.QuadTo:
panic("unsupported intersection for arc-quad")
case ppath.CubeTo:
panic("unsupported intersection for arc-cube")
case ppath.ArcTo:
rx2 := b[1]
ry2 := b[2]
phi2 := b[3]
large2, sweep2 := ppath.ToArcFlags(b[4])
cx2, cy2, theta20, theta21 := ppath.EllipseToCenter(b0.X, b0.Y, rx2, ry2, phi2, large2, sweep2, b[5], b[6])
zs = intersectionEllipseEllipse(zs, math32.Vec2(cx, cy), math32.Vec2(rx, ry), phi, theta0, theta1, math32.Vec2(cx2, cy2), math32.Vec2(rx2, ry2), phi2, theta20, theta21)
}
}
// swap A and B in the intersection found to match segments A and B of this function
if swapCurves {
for i := n; i < len(zs); i++ {
zs[i].T[0], zs[i].T[1] = zs[i].T[1], zs[i].T[0]
zs[i].Dir[0], zs[i].Dir[1] = zs[i].Dir[1], zs[i].Dir[0]
}
}
return zs
}
// Intersection is an intersection between two path segments, e.g. Line x Line. Note that an
// intersection is tangent also when it is at one of the endpoints, in which case it may be tangent
// for this segment but may or may not cross the path depending on the adjacent segment.
// Notabene: for quad/cube/ellipse aligned angles at the endpoint for non-overlapping curves are deviated slightly to correctly calculate the value for Into, and will thus not be aligned
type Intersection struct {
math32.Vector2 // coordinate of intersection
T [2]float32 // position along segment [0,1]
Dir [2]float32 // direction at intersection [0,2*pi)
Tangent bool // intersection is tangent (touches) instead of secant (crosses)
Same bool // intersection is of two overlapping segments (tangent is also true)
}
// Into returns true if first path goes into the left-hand side of the second path,
// i.e. the second path goes to the right-hand side of the first path.
func (z Intersection) Into() bool {
return angleBetweenExclusive(z.Dir[1]-z.Dir[0], math32.Pi, 2.0*math32.Pi)
}
func (z Intersection) Equals(o Intersection) bool {
return ppath.EqualPoint(z.Vector2, o.Vector2) && ppath.Equal(z.T[0], o.T[0]) && ppath.Equal(z.T[1], o.T[1]) && ppath.AngleEqual(z.Dir[0], o.Dir[0]) && ppath.AngleEqual(z.Dir[1], o.Dir[1]) && z.Tangent == o.Tangent && z.Same == o.Same
}
func (z Intersection) String() string {
var extra string
if z.Tangent {
extra = " Tangent"
}
if z.Same {
extra = " Same"
}
return fmt.Sprintf("({%v,%v} t={%v,%v} dir={%v°,%v°}%v)", numEps(z.X), numEps(z.Y), numEps(z.T[0]), numEps(z.T[1]), numEps(math32.RadToDeg(ppath.AngleNorm(z.Dir[0]))), numEps(math32.RadToDeg(ppath.AngleNorm(z.Dir[1]))), extra)
}
type Intersections []Intersection
// Has returns true if there are secant/tangent intersections.
func (zs Intersections) Has() bool {
return 0 < len(zs)
}
// HasSecant returns true when there are secant intersections, i.e. the curves intersect and cross (they cut).
func (zs Intersections) HasSecant() bool {
for _, z := range zs {
if !z.Tangent {
return true
}
}
return false
}
// HasTangent returns true when there are tangent intersections, i.e. the curves intersect but don't cross (they touch).
func (zs Intersections) HasTangent() bool {
for _, z := range zs {
if z.Tangent {
return true
}
}
return false
}
func (zs Intersections) add(pos math32.Vector2, ta, tb, dira, dirb float32, tangent, same bool) Intersections {
// normalise T values between [0,1]
if ta < 0.0 { // || ppath.Equal(ta, 0.0) {
ta = 0.0
} else if 1.0 <= ta { // || ppath.Equal(ta, 1.0) {
ta = 1.0
}
if tb < 0.0 { // || ppath.Equal(tb, 0.0) {
tb = 0.0
} else if 1.0 < tb { // || ppath.Equal(tb, 1.0) {
tb = 1.0
}
return append(zs, Intersection{pos, [2]float32{ta, tb}, [2]float32{dira, dirb}, tangent, same})
}
func correctIntersection(z, aMin, aMax, bMin, bMax math32.Vector2) math32.Vector2 {
if z.X < aMin.X {
//fmt.Println("CORRECT 1:", a0, a1, "--", b0, b1)
z.X = aMin.X
} else if aMax.X < z.X {
//fmt.Println("CORRECT 2:", a0, a1, "--", b0, b1)
z.X = aMax.X
}
if z.X < bMin.X {
//fmt.Println("CORRECT 3:", a0, a1, "--", b0, b1)
z.X = bMin.X
} else if bMax.X < z.X {
//fmt.Println("CORRECT 4:", a0, a1, "--", b0, b1)
z.X = bMax.X
}
if z.Y < aMin.Y {
//fmt.Println("CORRECT 5:", a0, a1, "--", b0, b1)
z.Y = aMin.Y
} else if aMax.Y < z.Y {
//fmt.Println("CORRECT 6:", a0, a1, "--", b0, b1)
z.Y = aMax.Y
}
if z.Y < bMin.Y {
//fmt.Println("CORRECT 7:", a0, a1, "--", b0, b1)
z.Y = bMin.Y
} else if bMax.Y < z.Y {
//fmt.Println("CORRECT 8:", a0, a1, "--", b0, b1)
z.Y = bMax.Y
}
return z
}
// correctIntersectionOrder restores the ordering the Bentley-Ottmann sweep relies on between a
// segment's left-endpoint and an intersection on it: a0 must stay to the left of, or below, z,
// and likewise b0. correctIntersection constrains x and y independently against each segment's
// bounding box, which keeps z inside the box but lets it land in the same column as a
// downwards-sloped segment's left-endpoint and below it. Splitting there makes the piece before
// the split a vertical segment pointing downwards, which has to be reversed to keep
// left-endpoints at the bottom, while that left-endpoint may already be in the sweep status where
// it can no longer be reversed. Collapse z onto the left-endpoint only when the two snap to the
// same tolerance square, which makes it a split the snapping phase would undo anyway.
// (from https://github.com/tdewolff/canvas/pull/394)
func correctIntersectionOrder(z, a0, b0 math32.Vector2) math32.Vector2 {
eps := BentleyOttmannEpsilon
if z.X == a0.X && z.Y < a0.Y && snap(z.Y, eps) == snap(a0.Y, eps) {
z.Y = a0.Y
}
if z.X == b0.X && z.Y < b0.Y && snap(z.Y, eps) == snap(b0.Y, eps) {
z.Y = b0.Y
}
return z
}
// F. Antonio, "Faster Line Segment Intersection", Graphics Gems III, 1992
func intersectionLineLineBentleyOttmann(zs []math32.Vector2, a0, a1, b0, b1 math32.Vector2) []math32.Vector2 {
// fast line-line intersection code, with additional constraints for the BentleyOttmann code:
// - a0 is to the left and/or bottom of a1, same for b0 and b1
// - an intersection z must keep the above property between (a0,z), (z,a1), (b0,z), and (z,b1)
// note that an exception is made for (z,a1) and (z,b1) to allow them to become vertical, this
// is because there isn't always "space" between a0.X and a1.X, eg. when a1.X = nextafter(a0.X)
if a1.X < b0.X || b1.X < a0.X {
return zs
}
aMin, aMax, bMin, bMax := a0, a1, b0, b1
if a1.Y < a0.Y {
aMin.Y, aMax.Y = aMax.Y, aMin.Y
}
if b1.Y < b0.Y {
bMin.Y, bMax.Y = bMax.Y, bMin.Y
}
if aMax.Y < bMin.Y || bMax.Y < aMin.Y {
return zs
} else if (aMax.X == bMin.X || bMax.X == aMin.X) && (aMax.Y == bMin.Y || bMax.Y == aMin.Y) {
return zs
}
// only the position and T values are valid for each intersection
A := a1.Sub(a0)
B := b0.Sub(b1)
C := a0.Sub(b0)
denom := B.Cross(A)
// divide by length^2 since the perpdot between very small segments may be below Epsilon
if denom == 0.0 {
// colinear
if C.Cross(B) == 0.0 {
// overlap, rotate to x-axis
a, b, c, d := a0.X, a1.X, b0.X, b1.X
if math32.Abs(A.X) < math32.Abs(A.Y) {
// mostly vertical
a, b, c, d = a0.Y, a1.Y, b0.Y, b1.Y
}
if c < b && a < d {
if a < c {
zs = append(zs, b0)
} else if c < a {
zs = append(zs, a0)
}
if d < b {
zs = append(zs, b1)
} else if b < d {
zs = append(zs, a1)
}
}
}
return zs
}
// find intersections within +-Epsilon to avoid missing near intersections
ta := C.Cross(B) / denom
if ta < -ppath.Epsilon || 1.0+ppath.Epsilon < ta {
return zs
}
tb := A.Cross(C) / denom
if tb < -ppath.Epsilon || 1.0+ppath.Epsilon < tb {
return zs
}
// ta is snapped to 0.0 or 1.0 if very close
if ta <= ppath.Epsilon {
ta = 0.0
} else if 1.0-ppath.Epsilon <= ta {
ta = 1.0
}
z := a0.Lerp(a1, ta)
z = correctIntersection(z, aMin, aMax, bMin, bMax)
z = correctIntersectionOrder(z, a0, b0)
if z != a0 && z != a1 || z != b0 && z != b1 {
// not at endpoints for both
if a0 != b0 && z != a0 && z != b0 && b0.Sub(z).Cross(z.Sub(a0)) == 0.0 {
a, c, m := a0.X, b0.X, z.X
if math32.Abs(z.Sub(a0).X) < math32.Abs(z.Sub(a0).Y) {
// mostly vertical
a, c, m = a0.Y, b0.Y, z.Y
}
if a != c && (a < m) == (c < m) {
if a < m && a < c || m < a && c < a {
zs = append(zs, b0)
} else {
zs = append(zs, a0)
}
}
zs = append(zs, z)
} else if a1 != b1 && z != a1 && z != b1 && z.Sub(b1).Cross(a1.Sub(z)) == 0.0 {
b, d, m := a1.X, b1.X, z.X
if math32.Abs(z.Sub(a1).X) < math32.Abs(z.Sub(a1).Y) {
// mostly vertical
b, d, m = a1.Y, b1.Y, z.Y
}
if b != d && (b < m) == (d < m) {
if b < m && b < d || m < b && d < b {
zs = append(zs, b1)
} else {
zs = append(zs, a1)
}
}
} else {
zs = append(zs, z)
}
}
return zs
}
func intersectionLineLine(zs Intersections, a0, a1, b0, b1 math32.Vector2) Intersections {
if ppath.EqualPoint(a0, a1) || ppath.EqualPoint(b0, b1) {
return zs // zero-length Close
}
da := a1.Sub(a0)
db := b1.Sub(b0)
anglea := ppath.Angle(da)
angleb := ppath.Angle(db)
div := da.Cross(db)
// divide by length^2 since otherwise the perpdot between very small segments may be
// below Epsilon
if length := da.Length() * db.Length(); ppath.Equal(div/length, 0.0) {
// parallel
if ppath.Equal(b0.Sub(a0).Cross(db), 0.0) {
// overlap, rotate to x-axis
a := a0.Rot(-anglea, math32.Vector2{}).X
b := a1.Rot(-anglea, math32.Vector2{}).X
c := b0.Rot(-anglea, math32.Vector2{}).X
d := b1.Rot(-anglea, math32.Vector2{}).X
if inInterval(a, c, d) && inInterval(b, c, d) {
// a-b in c-d or a-b == c-d
zs = zs.add(a0, 0.0, (a-c)/(d-c), anglea, angleb, true, true)
zs = zs.add(a1, 1.0, (b-c)/(d-c), anglea, angleb, true, true)
} else if inInterval(c, a, b) && inInterval(d, a, b) {
// c-d in a-b
zs = zs.add(b0, (c-a)/(b-a), 0.0, anglea, angleb, true, true)
zs = zs.add(b1, (d-a)/(b-a), 1.0, anglea, angleb, true, true)
} else if inInterval(a, c, d) {
// a in c-d
same := a < d-ppath.Epsilon || a < c-ppath.Epsilon
zs = zs.add(a0, 0.0, (a-c)/(d-c), anglea, angleb, true, same)
if a < d-ppath.Epsilon {
zs = zs.add(b1, (d-a)/(b-a), 1.0, anglea, angleb, true, true)
} else if a < c-ppath.Epsilon {
zs = zs.add(b0, (c-a)/(b-a), 0.0, anglea, angleb, true, true)
}
} else if inInterval(b, c, d) {
// b in c-d
same := c < b-ppath.Epsilon || d < b-ppath.Epsilon
if c < b-ppath.Epsilon {
zs = zs.add(b0, (c-a)/(b-a), 0.0, anglea, angleb, true, true)
} else if d < b-ppath.Epsilon {
zs = zs.add(b1, (d-a)/(b-a), 1.0, anglea, angleb, true, true)
}
zs = zs.add(a1, 1.0, (b-c)/(d-c), anglea, angleb, true, same)
}
}
return zs
} else if ppath.EqualPoint(a1, b0) {
// handle common cases with endpoints to avoid numerical issues
zs = zs.add(a1, 1.0, 0.0, anglea, angleb, true, false)
return zs
} else if ppath.EqualPoint(a0, b1) {
// handle common cases with endpoints to avoid numerical issues
zs = zs.add(a0, 0.0, 1.0, anglea, angleb, true, false)
return zs
}
ta := db.Cross(a0.Sub(b0)) / div
tb := da.Cross(a0.Sub(b0)) / div
if inInterval(ta, 0.0, 1.0) && inInterval(tb, 0.0, 1.0) {
tangent := ppath.Equal(ta, 0.0) || ppath.Equal(ta, 1.0) || ppath.Equal(tb, 0.0) || ppath.Equal(tb, 1.0)
zs = zs.add(a0.Lerp(a1, ta), ta, tb, anglea, angleb, tangent, false)
}
return zs
}
// https://www.particleincell.com/2013/cubic-line-intersection/
func intersectionLineQuad(zs Intersections, l0, l1, p0, p1, p2 math32.Vector2) Intersections {
if ppath.EqualPoint(l0, l1) {
return zs // zero-length Close
}
// write line as A.X = bias
A := math32.Vec2(l1.Y-l0.Y, l0.X-l1.X)
bias := l0.Dot(A)
a := A.Dot(p0.Sub(p1.MulScalar(2.0)).Add(p2))
b := A.Dot(p1.Sub(p0).MulScalar(2.0))
c := A.Dot(p0) - bias
roots := []float32{}
r0, r1 := solveQuadraticFormula(a, b, c)
if !math32.IsNaN(r0) {
roots = append(roots, r0)
if !math32.IsNaN(r1) {
roots = append(roots, r1)
}
}
dira := ppath.Angle(l1.Sub(l0))
horizontal := math32.Abs(l1.Y-l0.Y) <= math32.Abs(l1.X-l0.X)
for _, root := range roots {
if inInterval(root, 0.0, 1.0) {
var s float32
pos := quadraticBezierPos(p0, p1, p2, root)
if horizontal {
s = (pos.X - l0.X) / (l1.X - l0.X)
} else {
s = (pos.Y - l0.Y) / (l1.Y - l0.Y)
}
if inInterval(s, 0.0, 1.0) {
deriv := ppath.QuadraticBezierDeriv(p0, p1, p2, root)
dirb := ppath.Angle(deriv)
endpoint := ppath.Equal(root, 0.0) || ppath.Equal(root, 1.0) || ppath.Equal(s, 0.0) || ppath.Equal(s, 1.0)
if endpoint {
// deviate angle slightly at endpoint when aligned to properly set Into
deriv2 := quadraticBezierDeriv2(p0, p1, p2)
if (0.0 <= deriv.Cross(deriv2)) == (ppath.Equal(root, 0.0) || !ppath.Equal(root, 1.0) && ppath.Equal(s, 0.0)) {
dirb += ppath.Epsilon * 2.0 // t=0 and CCW, or t=1 and CW
} else {
dirb -= ppath.Epsilon * 2.0 // t=0 and CW, or t=1 and CCW
}
dirb = ppath.AngleNorm(dirb)
}
zs = zs.add(pos, s, root, dira, dirb, endpoint || ppath.Equal(A.Dot(deriv), 0.0), false)
}
}
}
return zs
}
// https://www.particleincell.com/2013/cubic-line-intersection/
func intersectionLineCube(zs Intersections, l0, l1, p0, p1, p2, p3 math32.Vector2) Intersections {
if ppath.EqualPoint(l0, l1) {
return zs // zero-length Close
}
// write line as A.X = bias
A := math32.Vec2(l1.Y-l0.Y, l0.X-l1.X)
bias := l0.Dot(A)
a := A.Dot(p3.Sub(p0).Add(p1.MulScalar(3.0)).Sub(p2.MulScalar(3.0)))
b := A.Dot(p0.MulScalar(3.0).Sub(p1.MulScalar(6.0)).Add(p2.MulScalar(3.0)))
c := A.Dot(p1.MulScalar(3.0).Sub(p0.MulScalar(3.0)))
d := A.Dot(p0) - bias
roots := []float32{}
r0, r1, r2 := solveCubicFormula(a, b, c, d)
if !math32.IsNaN(r0) {
roots = append(roots, r0)
if !math32.IsNaN(r1) {
roots = append(roots, r1)
if !math32.IsNaN(r2) {
roots = append(roots, r2)
}
}
}
dira := ppath.Angle(l1.Sub(l0))
horizontal := math32.Abs(l1.Y-l0.Y) <= math32.Abs(l1.X-l0.X)
for _, root := range roots {
if inInterval(root, 0.0, 1.0) {
var s float32
pos := cubicBezierPos(p0, p1, p2, p3, root)
if horizontal {
s = (pos.X - l0.X) / (l1.X - l0.X)
} else {
s = (pos.Y - l0.Y) / (l1.Y - l0.Y)
}
if inInterval(s, 0.0, 1.0) {
deriv := ppath.CubicBezierDeriv(p0, p1, p2, p3, root)
dirb := ppath.Angle(deriv)
tangent := ppath.Equal(A.Dot(deriv), 0.0)
endpoint := ppath.Equal(root, 0.0) || ppath.Equal(root, 1.0) || ppath.Equal(s, 0.0) || ppath.Equal(s, 1.0)
if endpoint {
// deviate angle slightly at endpoint when aligned to properly set Into
deriv2 := cubicBezierDeriv2(p0, p1, p2, p3, root)
if (0.0 <= deriv.Cross(deriv2)) == (ppath.Equal(root, 0.0) || !ppath.Equal(root, 1.0) && ppath.Equal(s, 0.0)) {
dirb += ppath.Epsilon * 2.0 // t=0 and CCW, or t=1 and CW
} else {
dirb -= ppath.Epsilon * 2.0 // t=0 and CW, or t=1 and CCW
}
} else if ppath.AngleEqual(dira, dirb) || ppath.AngleEqual(dira, dirb+math32.Pi) {
// directions are parallel but the paths do cross (inflection point)
// TODO: test better
deriv2 := cubicBezierDeriv2(p0, p1, p2, p3, root)
if ppath.Equal(deriv2.X, 0.0) && ppath.Equal(deriv2.Y, 0.0) {
deriv3 := cubicBezierDeriv3(p0, p1, p2, p3, root)
if 0.0 < deriv.Cross(deriv3) {
dirb += ppath.Epsilon * 2.0
} else {
dirb -= ppath.Epsilon * 2.0
}
dirb = ppath.AngleNorm(dirb)
tangent = false
}
}
zs = zs.add(pos, s, root, dira, dirb, endpoint || tangent, false)
}
}
}
return zs
}
// handle line-arc intersections and their peculiarities regarding angles
func addLineArcIntersection(zs Intersections, pos math32.Vector2, dira, dirb, t, t0, t1, angle, theta0, theta1 float32, tangent bool) Intersections {
if theta0 <= theta1 {
angle = theta0 - ppath.Epsilon + ppath.AngleNorm(angle-theta0+ppath.Epsilon)
} else {
angle = theta1 - ppath.Epsilon + ppath.AngleNorm(angle-theta1+ppath.Epsilon)
}
endpoint := ppath.Equal(t, t0) || ppath.Equal(t, t1) || ppath.Equal(angle, theta0) || ppath.Equal(angle, theta1)
if endpoint {
// deviate angle slightly at endpoint when aligned to properly set Into
if (theta0 <= theta1) == (ppath.Equal(angle, theta0) || !ppath.Equal(angle, theta1) && ppath.Equal(t, t0)) {
dirb += ppath.Epsilon * 2.0 // t=0 and CCW, or t=1 and CW
} else {
dirb -= ppath.Epsilon * 2.0 // t=0 and CW, or t=1 and CCW
}
dirb = ppath.AngleNorm(dirb)
}
// snap segment parameters to 0.0 and 1.0 to avoid numerical issues
var s float32
if ppath.Equal(t, t0) {
t = 0.0
} else if ppath.Equal(t, t1) {
t = 1.0
} else {
t = (t - t0) / (t1 - t0)
}
if ppath.Equal(angle, theta0) {
s = 0.0
} else if ppath.Equal(angle, theta1) {
s = 1.0
} else {
s = (angle - theta0) / (theta1 - theta0)
}
return zs.add(pos, t, s, dira, dirb, endpoint || tangent, false)
}
// https://www.geometrictools.com/GTE/Mathematics/IntrLine2Circle2.h
func intersectionLineCircle(zs Intersections, l0, l1, center math32.Vector2, radius, theta0, theta1 float32) Intersections {
if ppath.EqualPoint(l0, l1) {
return zs // zero-length Close
}
// solve l0 + t*(l1-l0) = P + t*D = X (line equation)
// and |X - center| = |X - C| = R = radius (circle equation)
// by substitution and squaring: |P + t*D - C|^2 = R^2
// giving: D^2 t^2 + 2D(P-C) t + (P-C)^2-R^2 = 0
dir := l1.Sub(l0)
diff := l0.Sub(center) // P-C
length := dir.Length()
D := dir.DivScalar(length)
// we normalise D to be of length 1, so that the roots are in [0,length]
a := float32(1.0)
b := 2.0 * D.Dot(diff)
c := diff.Dot(diff) - radius*radius
// find solutions for t ∈ [0,1], the parameter along the line's path
roots := []float32{}
r0, r1 := solveQuadraticFormula(a, b, c)
if !math32.IsNaN(r0) {
roots = append(roots, r0)
if !math32.IsNaN(r1) && !ppath.Equal(r0, r1) {
roots = append(roots, r1)
}
}
// handle common cases with endpoints to avoid numerical issues
// snap closest root to path's start or end
if 0 < len(roots) {
if pos := l0.Sub(center); ppath.Equal(pos.Length(), radius) {
if len(roots) == 1 || math32.Abs(roots[0]) < math32.Abs(roots[1]) {
roots[0] = 0.0
} else {
roots[1] = 0.0
}
}
if pos := l1.Sub(center); ppath.Equal(pos.Length(), radius) {
if len(roots) == 1 || math32.Abs(roots[0]-length) < math32.Abs(roots[1]-length) {
roots[0] = length
} else {
roots[1] = length
}
}
}
// add intersections
dira := ppath.Angle(dir)
tangent := len(roots) == 1
for _, root := range roots {
pos := diff.Add(dir.MulScalar(root / length))
angle := math32.Atan2(pos.Y*radius, pos.X*radius)
if inInterval(root, 0.0, length) && ppath.IsAngleBetween(angle, theta0, theta1) {
pos = center.Add(pos)
dirb := ppath.Angle(ppath.EllipseDeriv(radius, radius, 0.0, theta0 <= theta1, angle))
zs = addLineArcIntersection(zs, pos, dira, dirb, root, 0.0, length, angle, theta0, theta1, tangent)
}
}
return zs
}
func intersectionLineEllipse(zs Intersections, l0, l1, center, radius math32.Vector2, phi, theta0, theta1 float32) Intersections {
if ppath.Equal(radius.X, radius.Y) {
return intersectionLineCircle(zs, l0, l1, center, radius.X, theta0, theta1)
} else if ppath.EqualPoint(l0, l1) {
return zs // zero-length Close
}
// TODO: needs more testing
// TODO: intersection inconsistency due to numerical stability in finding tangent collisions for subsequent paht segments (line -> ellipse), or due to the endpoint of a line not touching with another arc, but the subsequent segment does touch with its starting point
dira := ppath.Angle(l1.Sub(l0))
// we take the ellipse center as the origin and counter-rotate by phi
l0 = l0.Sub(center).Rot(-phi, ppath.Origin)
l1 = l1.Sub(center).Rot(-phi, ppath.Origin)
// line: cx + dy + e = 0
c := l0.Y - l1.Y
d := l1.X - l0.X
e := l0.Cross(l1)
// follow different code paths when line is mostly horizontal or vertical
horizontal := math32.Abs(c) <= math32.Abs(d)
// ellipse: x^2/a + y^2/b = 1
a := radius.X * radius.X
b := radius.Y * radius.Y
// rewrite as a polynomial by substituting x or y to obtain:
// At^2 + Bt + C = 0, with t either x (horizontal) or y (!horizontal)
var A, B, C float32
A = a*c*c + b*d*d
if horizontal {
B = 2.0 * a * c * e
C = a*e*e - a*b*d*d
} else {
B = 2.0 * b * d * e
C = b*e*e - a*b*c*c
}
// find solutions
roots := []float32{}
r0, r1 := solveQuadraticFormula(A, B, C)
if !math32.IsNaN(r0) {
roots = append(roots, r0)
if !math32.IsNaN(r1) && !ppath.Equal(r0, r1) {
roots = append(roots, r1)
}
}
for _, root := range roots {
// get intersection position with center as origin
var x, y, t0, t1 float32
if horizontal {
x = root
y = -e/d - c*root/d
t0 = l0.X
t1 = l1.X
} else {
x = -e/c - d*root/c
y = root
t0 = l0.Y
t1 = l1.Y
}
tangent := len(roots) == 1 // (a root of 0 is only where it is)
angle := math32.Atan2(y*radius.X, x*radius.Y)
if inInterval(root, t0, t1) && ppath.IsAngleBetween(angle, theta0, theta1) {
pos := math32.Vec2(x, y).Rot(phi, ppath.Origin).Add(center)
dirb := ppath.Angle(ppath.EllipseDeriv(radius.X, radius.Y, phi, theta0 <= theta1, angle))
zs = addLineArcIntersection(zs, pos, dira, dirb, root, t0, t1, angle, theta0, theta1, tangent)
}
}
return zs
}
func intersectionEllipseEllipse(zs Intersections, c0, r0 math32.Vector2, phi0, thetaStart0, thetaEnd0 float32, c1, r1 math32.Vector2, phi1, thetaStart1, thetaEnd1 float32) Intersections {
// TODO: needs more testing
if !ppath.Equal(r0.X, r0.Y) || !ppath.Equal(r1.X, r1.Y) {
panic("not handled") // ellipses
}
arcAngle := func(theta float32, sweep bool) float32 {
theta += math32.Pi / 2.0
if !sweep {
theta -= math32.Pi
}
return ppath.AngleNorm(theta)
}
dtheta0 := thetaEnd0 - thetaStart0
thetaStart0 = ppath.AngleNorm(thetaStart0 + phi0)
thetaEnd0 = thetaStart0 + dtheta0
dtheta1 := thetaEnd1 - thetaStart1
thetaStart1 = ppath.AngleNorm(thetaStart1 + phi1)
thetaEnd1 = thetaStart1 + dtheta1
if ppath.EqualPoint(c0, c1) && ppath.EqualPoint(r0, r1) {
// parallel
tOffset1 := float32(0.0)
dirOffset1 := float32(0.0)
if (0.0 <= dtheta0) != (0.0 <= dtheta1) {
thetaStart1, thetaEnd1 = thetaEnd1, thetaStart1 // keep order on first arc
dirOffset1 = math32.Pi
tOffset1 = 1.0
}
// will add either 1 (when touching) or 2 (when overlapping) intersections
if t := angleTime(thetaStart0, thetaStart1, thetaEnd1); inInterval(t, 0.0, 1.0) {
// ellipse0 starts within/on border of ellipse1
dir := arcAngle(thetaStart0, 0.0 <= dtheta0)
pos := ppath.EllipsePos(r0.X, r0.Y, 0.0, c0.X, c0.Y, thetaStart0)
zs = zs.add(pos, 0.0, math32.Abs(t-tOffset1), dir, ppath.AngleNorm(dir+dirOffset1), true, true)
}
if t := angleTime(thetaStart1, thetaStart0, thetaEnd0); inIntervalExclusive(t, 0.0, 1.0) {
// ellipse1 starts within ellipse0
dir := arcAngle(thetaStart1, 0.0 <= dtheta0)
pos := ppath.EllipsePos(r0.X, r0.Y, 0.0, c0.X, c0.Y, thetaStart1)
zs = zs.add(pos, t, tOffset1, dir, ppath.AngleNorm(dir+dirOffset1), true, true)
}
if t := angleTime(thetaEnd1, thetaStart0, thetaEnd0); inIntervalExclusive(t, 0.0, 1.0) {
// ellipse1 ends within ellipse0
dir := arcAngle(thetaEnd1, 0.0 <= dtheta0)
pos := ppath.EllipsePos(r0.X, r0.Y, 0.0, c0.X, c0.Y, thetaEnd1)
zs = zs.add(pos, t, 1.0-tOffset1, dir, ppath.AngleNorm(dir+dirOffset1), true, true)
}
if t := angleTime(thetaEnd0, thetaStart1, thetaEnd1); inInterval(t, 0.0, 1.0) {
// ellipse0 ends within/on border of ellipse1
dir := arcAngle(thetaEnd0, 0.0 <= dtheta0)
pos := ppath.EllipsePos(r0.X, r0.Y, 0.0, c0.X, c0.Y, thetaEnd0)
zs = zs.add(pos, 1.0, math32.Abs(t-tOffset1), dir, ppath.AngleNorm(dir+dirOffset1), true, true)
}
return zs
}
// https://math32.stackexchange.com/questions/256100/how-can-i-find-the-points-at-which-two-circles-intersect
// https://gist.github.com/jupdike/bfe5eb23d1c395d8a0a1a4ddd94882ac
R := c0.Sub(c1).Length()
if R < math32.Abs(r0.X-r1.X) || r0.X+r1.X < R {
return zs
}
R2 := R * R
k := r0.X*r0.X - r1.X*r1.X
a := float32(0.5)
b := 0.5 * k / R2
c := 0.5 * math32.Sqrt(2.0*(r0.X*r0.X+r1.X*r1.X)/R2-k*k/(R2*R2)-1.0)
mid := c1.Sub(c0).MulScalar(a + b)
dev := math32.Vec2(c1.Y-c0.Y, c0.X-c1.X).MulScalar(c)
tangent := ppath.EqualPoint(dev, math32.Vector2{})
anglea0 := ppath.Angle(mid.Add(dev))
anglea1 := ppath.Angle(c0.Sub(c1).Add(mid).Add(dev))
ta0 := angleTime(anglea0, thetaStart0, thetaEnd0)
ta1 := angleTime(anglea1, thetaStart1, thetaEnd1)
if inInterval(ta0, 0.0, 1.0) && inInterval(ta1, 0.0, 1.0) {
dir0 := arcAngle(anglea0, 0.0 <= dtheta0)
dir1 := arcAngle(anglea1, 0.0 <= dtheta1)
endpoint := ppath.Equal(ta0, 0.0) || ppath.Equal(ta0, 1.0) || ppath.Equal(ta1, 0.0) || ppath.Equal(ta1, 1.0)
zs = zs.add(c0.Add(mid).Add(dev), ta0, ta1, dir0, dir1, tangent || endpoint, false)
}
if !tangent {
angleb0 := ppath.Angle(mid.Sub(dev))
angleb1 := ppath.Angle(c0.Sub(c1).Add(mid).Sub(dev))
tb0 := angleTime(angleb0, thetaStart0, thetaEnd0)
tb1 := angleTime(angleb1, thetaStart1, thetaEnd1)
if inInterval(tb0, 0.0, 1.0) && inInterval(tb1, 0.0, 1.0) {
dir0 := arcAngle(angleb0, 0.0 <= dtheta0)
dir1 := arcAngle(angleb1, 0.0 <= dtheta1)
endpoint := ppath.Equal(tb0, 0.0) || ppath.Equal(tb0, 1.0) || ppath.Equal(tb1, 0.0) || ppath.Equal(tb1, 1.0)
zs = zs.add(c0.Add(mid).Sub(dev), tb0, tb1, dir0, dir1, endpoint, false)
}
}
return zs
}
// TODO: bezier-bezier intersection
// TODO: bezier-ellipse intersection
// For Bézier-Bézier intersections:
// see T.W. Sederberg, "Computer Aided Geometric Design", 2012
// see T.W. Sederberg and T. Nishita, "Curve intersection using Bézier clipping", 1990
// see T.W. Sederberg and S.R. Parry, "Comparison of three curve intersection algorithms", 1986
func IntersectionRayLine(a0, a1, b0, b1 math32.Vector2) (math32.Vector2, bool) {
da := a1.Sub(a0)
db := b1.Sub(b0)
div := da.Cross(db)
if ppath.Equal(div, 0.0) {
// parallel
return math32.Vector2{}, false
}
tb := da.Cross(a0.Sub(b0)) / div
if inInterval(tb, 0.0, 1.0) {
return b0.Lerp(b1, tb), true
}
return math32.Vector2{}, false
}
// IntersectionRayCircle returns the intersections of the ray through l0 and l1
// with the circle of center c and radius r, and whether there are any.
// See https://mathworld.wolfram.com/Circle-LineIntersection.html
func IntersectionRayCircle(l0, l1, c math32.Vector2, r float32) (math32.Vector2, math32.Vector2, bool) {
d := l1.Sub(l0).Normal() // along line direction, anchored in l0, its length is 1
D := l0.Sub(c).Cross(d)
discriminant := r*r - D*D
if discriminant < 0 {
return math32.Vector2{}, math32.Vector2{}, false
}
discriminant = math32.Sqrt(discriminant)
ax := D * d.Y
bx := d.X * discriminant
if d.Y < 0.0 {
bx = -bx
}
ay := -D * d.X
by := math32.Abs(d.Y) * discriminant
return c.Add(math32.Vec2(ax+bx, ay+by)), c.Add(math32.Vec2(ax-bx, ay-by)), true
}
// IntersectionCircleCircle returns the intersections of two circles,
// and whether there are any. See
// https://math32.stackexchange.com/questions/256100/how-can-i-find-the-points-at-which-two-circles-intersect
// https://gist.github.com/jupdike/bfe5eb23d1c395d8a0a1a4ddd94882ac
func IntersectionCircleCircle(c0 math32.Vector2, r0 float32, c1 math32.Vector2, r1 float32) (math32.Vector2, math32.Vector2, bool) {
R := c0.Sub(c1).Length()
if R < math32.Abs(r0-r1) || r0+r1 < R || ppath.EqualPoint(c0, c1) {
return math32.Vector2{}, math32.Vector2{}, false
}
R2 := R * R
k := r0*r0 - r1*r1
a := float32(0.5)
b := 0.5 * k / R2
c := 0.5 * math32.Sqrt(2.0*(r0*r0+r1*r1)/R2-k*k/(R2*R2)-1.0)
i0 := c0.Add(c1).MulScalar(a)
i1 := c1.Sub(c0).MulScalar(b)
i2 := math32.Vec2(c1.Y-c0.Y, c0.X-c1.X).MulScalar(c)
return i0.Add(i1).Add(i2), i0.Add(i1).Sub(i2), true
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This is adapted from https://github.com/tdewolff/canvas
// Copyright (c) 2015 Taco de Wolff, under an MIT License.
package intersect
import (
"fmt"
"strings"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint/ppath"
)
// inInterval returns true if f is in closed interval
// [lower-Epsilon,upper+Epsilon] where lower and upper can be interchanged.
func inInterval(f, lower, upper float32) bool {
if upper < lower {
lower, upper = upper, lower
}
return lower-ppath.Epsilon <= f && f <= upper+ppath.Epsilon
}
// inIntervalExclusive returns true if f is in open interval
// [lower+Epsilon,upper-Epsilon] where lower and upper can be interchanged.
func inIntervalExclusive(f, lower, upper float32) bool {
if upper < lower {
lower, upper = upper, lower
}
return lower+ppath.Epsilon < f && f < upper-ppath.Epsilon
}
// angleBetweenExclusive is true when theta is in range (lower,upper)
// excluding the end points. Angles can be outside the [0,2PI) range.
func angleBetweenExclusive(theta, lower, upper float32) bool {
if upper < lower {
// sweep is false, ie direction is along negative angle (clockwise)
lower, upper = upper, lower
}
theta = ppath.AngleNorm(theta - lower)
upper = ppath.AngleNorm(upper - lower)
if 0.0 < theta && theta < upper {
return true
}
return false
}
// angleTime returns the time [0.0,1.0] of theta between
// [lower,upper]. When outside of [lower,upper], the result will also be outside of [0.0,1.0].
func angleTime(theta, lower, upper float32) float32 {
sweep := true
if upper < lower {
// sweep is false, ie direction is along negative angle (clockwise)
lower, upper = upper, lower
sweep = false
}
theta = ppath.AngleNorm(theta - lower + ppath.Epsilon)
upper = ppath.AngleNorm(upper - lower)
t := (theta - ppath.Epsilon) / upper
if !sweep {
t = 1.0 - t
}
if ppath.Equal(t, 0.0) {
return 0.0
} else if ppath.Equal(t, 1.0) {
return 1.0
}
return t
}
// Numerically stable quadratic formula, lowest root is returned first, see https://math32.stackexchange.com/a/2007723
func solveQuadraticFormula(a, b, c float32) (float32, float32) {
if ppath.Equal(a, 0.0) {
if ppath.Equal(b, 0.0) {
if ppath.Equal(c, 0.0) {
// all terms disappear, all x satisfy the solution
return 0.0, math32.NaN()
}
// linear term disappears, no solutions
return math32.NaN(), math32.NaN()
}
// quadratic term disappears, solve linear equation
return -c / b, math32.NaN()
}
if ppath.Equal(c, 0.0) {
// no constant term, one solution at zero and one from solving linearly
if ppath.Equal(b, 0.0) {
return 0.0, math32.NaN()
}
return 0.0, -b / a
}
discriminant := b*b - 4.0*a*c
if discriminant < 0.0 {
return math32.NaN(), math32.NaN()
} else if ppath.Equal(discriminant, 0.0) {
return -b / (2.0 * a), math32.NaN()
}
// Avoid catastrophic cancellation, which occurs when we subtract two nearly equal numbers and causes a large error. This can be the case when 4*a*c is small so that sqrt(discriminant) -> b, and the sign of b and in front of the radical are the same. Instead, we calculate x where b and the radical have different signs, and then use this result in the analytical equivalent of the formula, called the Citardauq Formula.
q := math32.Sqrt(discriminant)
if b < 0.0 {
// apply sign of b
q = -q
}
x1 := -(b + q) / (2.0 * a)
x2 := c / (a * x1)
if x2 < x1 {
x1, x2 = x2, x1
}
return x1, x2
}
// see https://www.geometrictools.com/Documentation/LowDegreePolynomialRoots.pdf
// see https://github.com/thelonious/kld-polynomial/blob/development/lib/Polynomial.js
func solveCubicFormula(a, b, c, d float32) (float32, float32, float32) {
var x1, x2, x3 float32
x2, x3 = math32.NaN(), math32.NaN() // x1 is always set to a number below
if ppath.Equal(a, 0.0) {
x1, x2 = solveQuadraticFormula(b, c, d)
} else {
// obtain monic polynomial: x^3 + f.x^2 + g.x + h = 0
b /= a
c /= a
d /= a
// obtain depressed polynomial: x^3 + c1.x + c0
bthird := b / 3.0
c0 := d - bthird*(c-2.0*bthird*bthird)
c1 := c - b*bthird
if ppath.Equal(c0, 0.0) {
if c1 < 0.0 {
tmp := math32.Sqrt(-c1)
x1 = -tmp - bthird
x2 = tmp - bthird
x3 = 0.0 - bthird
} else {
x1 = 0.0 - bthird
}
} else if ppath.Equal(c1, 0.0) {
if 0.0 < c0 {
x1 = -math32.Cbrt(c0) - bthird
} else {
x1 = math32.Cbrt(-c0) - bthird
}
} else {
delta := -(4.0*c1*c1*c1 + 27.0*c0*c0)
if ppath.Equal(delta, 0.0) {
delta = 0.0
}
if delta < 0.0 {
betaRe := -c0 / 2.0
betaIm := math32.Sqrt(-delta / 108.0)
tmp := betaRe - betaIm
if 0.0 <= tmp {
x1 = math32.Cbrt(tmp)
} else {
x1 = -math32.Cbrt(-tmp)
}
tmp = betaRe + betaIm
if 0.0 <= tmp {
x1 += math32.Cbrt(tmp)
} else {
x1 -= math32.Cbrt(-tmp)
}
x1 -= bthird
} else if 0.0 < delta {
betaRe := -c0 / 2.0
betaIm := math32.Sqrt(delta / 108.0)
theta := math32.Atan2(betaIm, betaRe) / 3.0
sintheta, costheta := math32.Sincos(theta)
distance := math32.Sqrt(-c1 / 3.0) // same as rhoPowThird
tmp := distance * sintheta * math32.Sqrt(3.0)
x1 = 2.0*distance*costheta - bthird
x2 = -distance*costheta - tmp - bthird
x3 = -distance*costheta + tmp - bthird
} else {
tmp := -3.0 * c0 / (2.0 * c1)
x1 = tmp - bthird
x2 = -2.0*tmp - bthird
}
}
}
// sort
if x3 < x2 || math32.IsNaN(x2) {
x2, x3 = x3, x2
}
if x2 < x1 || math32.IsNaN(x1) {
x1, x2 = x2, x1
}
if x3 < x2 || math32.IsNaN(x2) {
x2, x3 = x3, x2
}
return x1, x2, x3
}
type gaussLegendreFunc func(func(float32) float32, float32, float32) float32
// Gauss-Legendre quadrature integration from a to b with n=5
func gaussLegendre5(f func(float32) float32, a, b float32) float32 {
c := (b - a) / 2.0
d := (a + b) / 2.0
Qd1 := f(-0.90618*c + d)
Qd2 := f(-0.538469*c + d)
Qd3 := f(d)
Qd4 := f(0.538469*c + d)
Qd5 := f(0.90618*c + d)
return c * (0.236927*(Qd1+Qd5) + 0.478629*(Qd2+Qd4) + 0.568889*Qd3)
}
// Gauss-Legendre quadrature integration from a to b with n=7
func gaussLegendre7(f func(float32) float32, a, b float32) float32 {
c := (b - a) / 2.0
d := (a + b) / 2.0
Qd1 := f(-0.949108*c + d)
Qd2 := f(-0.741531*c + d)
Qd3 := f(-0.405845*c + d)
Qd4 := f(d)
Qd5 := f(0.405845*c + d)
Qd6 := f(0.741531*c + d)
Qd7 := f(0.949108*c + d)
return c * (0.129485*(Qd1+Qd7) + 0.279705*(Qd2+Qd6) + 0.381830*(Qd3+Qd5) + 0.417959*Qd4)
}
func invSpeedPolynomialChebyshevApprox(N int, gaussLegendre gaussLegendreFunc, fp func(float32) float32, tmin, tmax float32) (func(float32) float32, float32) {
// TODO: find better way to determine N. For Arc 10 seems fine, for some Quads 10 is too low, for Cube depending on inflection points is maybe not the best indicator
// TODO: track efficiency, how many times is fp called? Does a look-up table make more sense?
fLength := func(t float32) float32 {
return math32.Abs(gaussLegendre(fp, tmin, t))
}
totalLength := fLength(tmax)
t := func(L float32) float32 {
return bisectionMethod(fLength, L, tmin, tmax)
}
return polynomialChebyshevApprox(N, t, 0.0, totalLength, tmin, tmax), totalLength
}
func polynomialChebyshevApprox(N int, f func(float32) float32, xmin, xmax, ymin, ymax float32) func(float32) float32 {
fs := make([]float32, N)
for k := range N {
u := math32.Cos(math32.Pi * (float32(k+1) - 0.5) / float32(N))
fs[k] = f(xmin + (xmax-xmin)*(u+1.0)/2.0)
}
c := make([]float32, N)
for j := range N {
a := float32(0.0)
for k := range N {
a += fs[k] * math32.Cos(float32(j)*math32.Pi*(float32(k+1)-0.5)/float32(N))
}
c[j] = (2.0 / float32(N)) * a
}
if ymax < ymin {
ymin, ymax = ymax, ymin
}
return func(x float32) float32 {
x = math32.Min(xmax, math32.Max(xmin, x))
u := (x-xmin)/(xmax-xmin)*2.0 - 1.0
a := float32(0.0)
for j := range N {
a += c[j] * math32.Cos(float32(j)*math32.Acos(u))
}
y := -0.5*c[0] + a
if !math32.IsNaN(ymin) && !math32.IsNaN(ymax) {
y = math32.Min(ymax, math32.Max(ymin, y))
}
return y
}
}
// find value x for which f(x) = y in the interval x in [xmin, xmax] using the bisection method
func bisectionMethod(f func(float32) float32, y, xmin, xmax float32) float32 {
const MaxIterations = 100
const Tolerance = 0.001 // 0.1%
n := 0
toleranceX := math32.Abs(xmax-xmin) * Tolerance
toleranceY := math32.Abs(f(xmax)-f(xmin)) * Tolerance
var x float32
for {
x = (xmin + xmax) / 2.0
if n >= MaxIterations {
return x
}
dy := f(x) - y
if math32.Abs(dy) < toleranceY || math32.Abs(xmax-xmin)/2.0 < toleranceX {
return x
} else if dy > 0.0 {
xmax = x
} else {
xmin = x
}
n++
}
}
// snap "gridsnaps" the floating point to a grid of the given spacing
func snap(val, spacing float32) float32 {
return math32.Round(val/spacing) * spacing
}
// Gridsnap snaps point to a grid with the given spacing.
func Gridsnap(p math32.Vector2, spacing float32) math32.Vector2 {
return math32.Vec2(snap(p.X, spacing), snap(p.Y, spacing))
}
type numEps float32
func (f numEps) String() string {
s := fmt.Sprintf("%.*g", int(math32.Ceil(-math32.Log10(ppath.Epsilon))), f)
if dot := strings.IndexByte(s, '.'); dot != -1 {
for dot < len(s) && s[len(s)-1] == '0' {
s = s[:len(s)-1]
}
if dot < len(s) && s[len(s)-1] == '.' {
s = s[:len(s)-1]
}
}
return s
}
//func lookupMin(f func(float64) float64, xmin, xmax float64) float64 {
// const MaxIterations = 1000
// min := math32.Inf(1)
// for i := 0; i <= MaxIterations; i++ {
// t := float64(i) / float64(MaxIterations)
// x := xmin + t*(xmax-xmin)
// y := f(x)
// if y < min {
// min = y
// }
// }
// return min
//}
//
//func gradientDescent(f func(float64) float64, xmin, xmax float64) float64 {
// const MaxIterations = 100
// const Delta = 0.0001
// const Rate = 0.01
//
// x := (xmin + xmax) / 2.0
// for i := 0; i < MaxIterations; i++ {
// dydx := (f(x+Delta) - f(x-Delta)) / 2.0 / Delta
// x -= Rate * dydx
// }
// return x
//}
// func cohenSutherlandOutcode(rect math32.Box2, p math32.Vector2, eps float32) int {
// code := 0b0000
// if p.X < rect.Min.X-eps {
// code |= 0b0001 // left
// } else if rect.Max.X+eps < p.X {
// code |= 0b0010 // right
// }
// if p.Y < rect.Min.Y-eps {
// code |= 0b0100 // bottom
// } else if rect.Max.Y+eps < p.Y {
// code |= 0b1000 // top
// }
// return code
// }
//
// // return whether line is inside the rectangle, either entirely or partially.
// func cohenSutherlandLineClip(rect math32.Box2, a, b math32.Vector2, eps float32) (math32.Vector2, math32.Vector2, bool, bool) {
// outcode0 := cohenSutherlandOutcode(rect, a, eps)
// outcode1 := cohenSutherlandOutcode(rect, b, eps)
// if outcode0 == 0 && outcode1 == 0 {
// return a, b, true, false
// }
// for {
// if (outcode0 | outcode1) == 0 {
// // both inside
// return a, b, true, true
// } else if (outcode0 & outcode1) != 0 {
// // both in same region outside
// return a, b, false, false
// }
//
// // pick point outside
// outcodeOut := outcode0
// if outcode0 < outcode1 {
// outcodeOut = outcode1
// }
//
// // intersect with rectangle
// var c math32.Vector2
// if (outcodeOut & 0b1000) != 0 {
// // above
// c.X = a.X + (b.X-a.X)*(rect.Max.Y-a.Y)/(b.Y-a.Y)
// c.Y = rect.Max.Y
// } else if (outcodeOut & 0b0100) != 0 {
// // below
// c.X = a.X + (b.X-a.X)*(rect.Min.Y-a.Y)/(b.Y-a.Y)
// c.Y = rect.Min.Y
// } else if (outcodeOut & 0b0010) != 0 {
// // right
// c.X = rect.Max.X
// c.Y = a.Y + (b.Y-a.Y)*(rect.Max.X-a.X)/(b.X-a.X)
// } else if (outcodeOut & 0b0001) != 0 {
// // left
// c.X = rect.Min.X
// c.Y = a.Y + (b.Y-a.Y)*(rect.Min.X-a.X)/(b.X-a.X)
// }
//
// // prepare next pass
// if outcodeOut == outcode0 {
// outcode0 = cohenSutherlandOutcode(rect, c, eps)
// a = c
// } else {
// outcode1 = cohenSutherlandOutcode(rect, c, eps)
// b = c
// }
// }
// }
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This is adapted from https://github.com/tdewolff/canvas
// Copyright (c) 2015 Taco de Wolff, under an MIT License.
package ppath
import (
"fmt"
"math"
"strings"
"cogentcore.org/core/math32"
"github.com/tdewolff/parse/v2/strconv"
)
type num float32
func (f num) String() string {
s := fmt.Sprintf("%.*g", Precision, f)
if num(math.MaxInt32) < f || f < num(math.MinInt32) {
if i := strings.IndexAny(s, ".eE"); i == -1 {
s += ".0"
}
}
return string(MinifyNumber([]byte(s), Precision))
}
type dec float32
func (f dec) String() string {
s := fmt.Sprintf("%.*f", Precision, f)
s = string(MinifyDecimal([]byte(s), Precision))
if dec(math.MaxInt32) < f || f < dec(math.MinInt32) {
if i := strings.IndexByte(s, '.'); i == -1 {
s += ".0"
}
}
return s
}
func skipCommaWhitespace(path []byte) int {
i := 0
for i < len(path) && (path[i] == ' ' || path[i] == ',' || path[i] == '\n' || path[i] == '\r' || path[i] == '\t') {
i++
}
return i
}
// MustParseSVGPath parses an SVG path data string and panics if it fails.
func MustParseSVGPath(s string) Path {
p, err := ParseSVGPath(s)
if err != nil {
panic(err)
}
return p
}
// ParseSVGPath parses an SVG path data string.
func ParseSVGPath(s string) (Path, error) {
if len(s) == 0 {
return Path{}, nil
}
i := 0
path := []byte(s)
i += skipCommaWhitespace(path[i:])
if path[0] == ',' || path[i] < 'A' {
return nil, fmt.Errorf("bad path: path should start with command")
}
cmdLens := map[byte]int{
'M': 2,
'Z': 0,
'L': 2,
'H': 1,
'V': 1,
'C': 6,
'S': 4,
'Q': 4,
'T': 2,
'A': 7,
}
f := [7]float32{}
p := Path{}
var q, c math32.Vector2
var p0, p1 math32.Vector2
prevCmd := byte('z')
for {
i += skipCommaWhitespace(path[i:])
if len(path) <= i {
break
}
cmd := prevCmd
repeat := true
if cmd == 'z' || cmd == 'Z' || (path[i] < '0' || path[i] > '9') && path[i] != '.' && path[i] != '-' && path[i] != '+' {
cmd = path[i]
repeat = false
i++
i += skipCommaWhitespace(path[i:])
}
CMD := cmd
if 'a' <= cmd && cmd <= 'z' {
CMD -= 'a' - 'A'
}
for j := 0; j < cmdLens[CMD]; j++ {
if CMD == 'A' && (j == 3 || j == 4) {
// parse largeArc and sweep booleans for A command
if i < len(path) && path[i] == '1' {
f[j] = 1.0
} else if i < len(path) && path[i] == '0' {
f[j] = 0.0
} else {
return nil, fmt.Errorf("bad path: largeArc and sweep flags should be 0 or 1 in command '%c' at position %d", cmd, i+1)
}
i++
} else {
num, n := strconv.ParseFloat(path[i:])
if n == 0 {
if repeat && j == 0 && i < len(path) {
return nil, fmt.Errorf("bad path: unknown command '%c' at position %d", path[i], i+1)
} else if 1 < cmdLens[CMD] {
return nil, fmt.Errorf("bad path: sets of %d numbers should follow command '%c' at position %d", cmdLens[CMD], cmd, i+1)
} else {
return nil, fmt.Errorf("bad path: number should follow command '%c' at position %d", cmd, i+1)
}
}
f[j] = float32(num)
i += n
}
i += skipCommaWhitespace(path[i:])
}
switch cmd {
case 'M', 'm':
p1 = math32.Vec2(f[0], f[1])
if cmd == 'm' {
p1 = p1.Add(p0)
cmd = 'l'
} else {
cmd = 'L'
}
p.MoveTo(p1.X, p1.Y)
case 'Z', 'z':
p1 = p.StartPos()
p.Close()
case 'L', 'l':
p1 = math32.Vec2(f[0], f[1])
if cmd == 'l' {
p1 = p1.Add(p0)
}
p.LineTo(p1.X, p1.Y)
case 'H', 'h':
p1.X = f[0]
if cmd == 'h' {
p1.X += p0.X
}
p.LineTo(p1.X, p1.Y)
case 'V', 'v':
p1.Y = f[0]
if cmd == 'v' {
p1.Y += p0.Y
}
p.LineTo(p1.X, p1.Y)
case 'C', 'c':
cp1 := math32.Vec2(f[0], f[1])
cp2 := math32.Vec2(f[2], f[3])
p1 = math32.Vec2(f[4], f[5])
if cmd == 'c' {
cp1 = cp1.Add(p0)
cp2 = cp2.Add(p0)
p1 = p1.Add(p0)
}
p.CubeTo(cp1.X, cp1.Y, cp2.X, cp2.Y, p1.X, p1.Y)
c = cp2
case 'S', 's':
cp1 := p0
cp2 := math32.Vec2(f[0], f[1])
p1 = math32.Vec2(f[2], f[3])
if cmd == 's' {
cp2 = cp2.Add(p0)
p1 = p1.Add(p0)
}
if prevCmd == 'C' || prevCmd == 'c' || prevCmd == 'S' || prevCmd == 's' {
cp1 = p0.MulScalar(2.0).Sub(c)
}
p.CubeTo(cp1.X, cp1.Y, cp2.X, cp2.Y, p1.X, p1.Y)
c = cp2
case 'Q', 'q':
cp := math32.Vec2(f[0], f[1])
p1 = math32.Vec2(f[2], f[3])
if cmd == 'q' {
cp = cp.Add(p0)
p1 = p1.Add(p0)
}
p.QuadTo(cp.X, cp.Y, p1.X, p1.Y)
q = cp
case 'T', 't':
cp := p0
p1 = math32.Vec2(f[0], f[1])
if cmd == 't' {
p1 = p1.Add(p0)
}
if prevCmd == 'Q' || prevCmd == 'q' || prevCmd == 'T' || prevCmd == 't' {
cp = p0.MulScalar(2.0).Sub(q)
}
p.QuadTo(cp.X, cp.Y, p1.X, p1.Y)
q = cp
case 'A', 'a':
rx := f[0]
ry := f[1]
rot := f[2]
large := f[3] == 1.0
sweep := f[4] == 1.0
p1 = math32.Vec2(f[5], f[6])
if cmd == 'a' {
p1 = p1.Add(p0)
}
p.ArcToDeg(rx, ry, rot, ArcSize(large), ArcSweep(sweep), p1.X, p1.Y)
default:
return nil, fmt.Errorf("bad path: unknown command '%c' at position %d", cmd, i+1)
}
prevCmd = cmd
p0 = p1
}
return p, nil
}
// String returns a string that represents the path similar to the SVG
// path data format (but not necessarily valid SVG).
func (p Path) String() string {
sb := strings.Builder{}
for i := 0; i < len(p); {
cmd := p[i]
switch cmd {
case MoveTo:
fmt.Fprintf(&sb, "M%g %g", p[i+1], p[i+2])
case LineTo:
fmt.Fprintf(&sb, "L%g %g", p[i+1], p[i+2])
case QuadTo:
fmt.Fprintf(&sb, "Q%g %g %g %g", p[i+1], p[i+2], p[i+3], p[i+4])
case CubeTo:
fmt.Fprintf(&sb, "C%g %g %g %g %g %g", p[i+1], p[i+2], p[i+3], p[i+4], p[i+5], p[i+6])
case ArcTo:
rot := math32.RadToDeg(p[i+3])
large, sweep := ToArcFlags(p[i+4])
sLarge := "0"
if large {
sLarge = "1"
}
sSweep := "0"
if sweep {
sSweep = "1"
}
fmt.Fprintf(&sb, "A%g %g %g %s %s %g %g", p[i+1], p[i+2], rot, sLarge, sSweep, p[i+5], p[i+6])
case Close:
fmt.Fprintf(&sb, "z")
}
i += CmdLen(cmd)
}
return sb.String()
}
// ToSVG returns a string that represents the path in the SVG path data format with minification.
func (p Path) ToSVG() string {
if p.Empty() {
return ""
}
sb := strings.Builder{}
var x, y float32
for i := 0; i < len(p); {
cmd := p[i]
switch cmd {
case MoveTo:
x, y = p[i+1], p[i+2]
fmt.Fprintf(&sb, "M%v %v", num(x), num(y))
case LineTo:
xStart, yStart := x, y
x, y = p[i+1], p[i+2]
if Equal(x, xStart) && Equal(y, yStart) {
// nothing
} else if Equal(x, xStart) {
fmt.Fprintf(&sb, "V%v", num(y))
} else if Equal(y, yStart) {
fmt.Fprintf(&sb, "H%v", num(x))
} else {
fmt.Fprintf(&sb, "L%v %v", num(x), num(y))
}
case QuadTo:
x, y = p[i+3], p[i+4]
fmt.Fprintf(&sb, "Q%v %v %v %v", num(p[i+1]), num(p[i+2]), num(x), num(y))
case CubeTo:
x, y = p[i+5], p[i+6]
fmt.Fprintf(&sb, "C%v %v %v %v %v %v", num(p[i+1]), num(p[i+2]), num(p[i+3]), num(p[i+4]), num(x), num(y))
case ArcTo:
rx, ry := p[i+1], p[i+2]
rot := math32.RadToDeg(p[i+3])
large, sweep := ToArcFlags(p[i+4])
x, y = p[i+5], p[i+6]
sLarge := "0"
if large {
sLarge = "1"
}
sSweep := "0"
if sweep {
sSweep = "1"
}
if 90.0 <= rot {
rx, ry = ry, rx
rot -= 90.0
}
fmt.Fprintf(&sb, "A%v %v %v %s%s%v %v", num(rx), num(ry), num(rot), sLarge, sSweep, num(p[i+5]), num(p[i+6]))
case Close:
x, y = p[i+1], p[i+2]
fmt.Fprintf(&sb, "z")
}
i += CmdLen(cmd)
}
return sb.String()
}
// ToPS returns a string that represents the path in the PostScript data format.
func (p Path) ToPS() string {
if p.Empty() {
return ""
}
sb := strings.Builder{}
var x, y float32
for i := 0; i < len(p); {
cmd := p[i]
switch cmd {
case MoveTo:
x, y = p[i+1], p[i+2]
fmt.Fprintf(&sb, " %v %v moveto", dec(x), dec(y))
case LineTo:
x, y = p[i+1], p[i+2]
fmt.Fprintf(&sb, " %v %v lineto", dec(x), dec(y))
case QuadTo, CubeTo:
var start, cp1, cp2 math32.Vector2
start = math32.Vec2(x, y)
if cmd == QuadTo {
x, y = p[i+3], p[i+4]
cp1, cp2 = QuadraticToCubicBezier(start, math32.Vec2(p[i+1], p[i+2]), math32.Vec2(x, y))
} else {
cp1 = math32.Vec2(p[i+1], p[i+2])
cp2 = math32.Vec2(p[i+3], p[i+4])
x, y = p[i+5], p[i+6]
}
fmt.Fprintf(&sb, " %v %v %v %v %v %v curveto", dec(cp1.X), dec(cp1.Y), dec(cp2.X), dec(cp2.Y), dec(x), dec(y))
case ArcTo:
x0, y0 := x, y
rx, ry, phi := p[i+1], p[i+2], p[i+3]
large, sweep := ToArcFlags(p[i+4])
x, y = p[i+5], p[i+6]
cx, cy, theta0, theta1 := EllipseToCenter(x0, y0, rx, ry, phi, large, sweep, x, y)
theta0 = math32.RadToDeg(theta0)
theta1 = math32.RadToDeg(theta1)
rot := math32.RadToDeg(phi)
fmt.Fprintf(&sb, " %v %v %v %v %v %v %v ellipse", dec(cx), dec(cy), dec(rx), dec(ry), dec(theta0), dec(theta1), dec(rot))
if !sweep {
fmt.Fprintf(&sb, "n")
}
case Close:
x, y = p[i+1], p[i+2]
fmt.Fprintf(&sb, " closepath")
}
i += CmdLen(cmd)
}
return sb.String()[1:] // remove the first space
}
// ToPDF returns a string that represents the path in the PDF data format.
func (p Path) ToPDF() string {
if p.Empty() {
return ""
}
p = p.ReplaceArcs()
sb := strings.Builder{}
var x, y float32
for i := 0; i < len(p); {
cmd := p[i]
switch cmd {
case MoveTo:
x, y = p[i+1], p[i+2]
fmt.Fprintf(&sb, " %v %v m", dec(x), dec(y))
case LineTo:
x, y = p[i+1], p[i+2]
fmt.Fprintf(&sb, " %v %v l", dec(x), dec(y))
case QuadTo, CubeTo:
var start, cp1, cp2 math32.Vector2
start = math32.Vec2(x, y)
if cmd == QuadTo {
x, y = p[i+3], p[i+4]
cp1, cp2 = QuadraticToCubicBezier(start, math32.Vec2(p[i+1], p[i+2]), math32.Vec2(x, y))
} else {
cp1 = math32.Vec2(p[i+1], p[i+2])
cp2 = math32.Vec2(p[i+3], p[i+4])
x, y = p[i+5], p[i+6]
}
fmt.Fprintf(&sb, " %v %v %v %v %v %v c", dec(cp1.X), dec(cp1.Y), dec(cp2.X), dec(cp2.Y), dec(x), dec(y))
case ArcTo:
panic("arcs should have been replaced")
case Close:
x, y = p[i+1], p[i+2]
fmt.Fprintf(&sb, " h")
}
i += CmdLen(cmd)
}
return sb.String()[1:] // remove the first space
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This is adapted from https://github.com/tdewolff/canvas
// Copyright (c) 2015 Taco de Wolff, under an MIT License.
package ppath
import (
"cogentcore.org/core/math32"
)
var (
// Tolerance is the maximum deviation from the original path in millimeters
// when e.g. flatting. Used for flattening in the renderers, font decorations,
// and path intersections.
Tolerance = float32(0.01)
// PixelTolerance is the maximum deviation of the rasterized path from
// the original for flattening purposed in pixels.
PixelTolerance = float32(0.1)
// In C, FLT_EPSILON = 1.19209e-07
// Epsilon is the smallest number below which we assume the value to be zero.
// This is to avoid numerical floating point issues.
Epsilon = float32(1e-7)
// Precision is the number of significant digits at which floating point
// value will be printed to output formats.
Precision = 7
// Origin is the coordinate system's origin.
Origin = math32.Vec2(0.0, 0.0)
)
// Equal returns true if a and b are equal within an absolute
// tolerance of Epsilon.
func Equal(a, b float32) bool {
// avoid math32.Abs
if a < b {
return b-a <= Epsilon
}
return a-b <= Epsilon
}
func EqualPoint(a, b math32.Vector2) bool {
return Equal(a.X, b.X) && Equal(a.Y, b.Y)
}
// AngleEqual returns true if both angles are equal.
func AngleEqual(a, b float32) bool {
return IsAngleBetween(a, b, b) // IsAngleBetween will add Epsilon to lower and upper
}
// AngleNorm returns the angle theta in the range [0,2PI).
func AngleNorm(theta float32) float32 {
theta = math32.Mod(theta, 2.0*math32.Pi)
if theta < 0.0 {
theta += 2.0 * math32.Pi
}
return theta
}
// IsAngleBetween is true when theta is in range [lower,upper]
// including the end points. Angles can be outside the [0,2PI) range.
func IsAngleBetween(theta, lower, upper float32) bool {
if upper < lower {
// sweep is false, ie direction is along negative angle (clockwise)
lower, upper = upper, lower
}
theta = AngleNorm(theta - lower + Epsilon)
upper = AngleNorm(upper - lower + 2.0*Epsilon)
return theta <= upper
}
// Slope returns the slope between OP, i.e. y/x.
func Slope(p math32.Vector2) float32 {
return p.Y / p.X
}
// Angle returns the angle in radians [0,2PI) between the x-axis and OP.
func Angle(p math32.Vector2) float32 {
return AngleNorm(math32.Atan2(p.Y, p.X))
}
// todo: use this for our AngleTo
// AngleBetween returns the angle between OP and OQ.
func AngleBetween(p, q math32.Vector2) float32 {
return math32.Atan2(p.Cross(q), p.Dot(q))
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This is adapted from https://github.com/tdewolff/minify
// Copyright (c) 2015 Taco de Wolff, under an MIT License.
package ppath
import "github.com/tdewolff/parse/v2/strconv"
// MaxInt is the maximum value of int.
const MaxInt = int(^uint(0) >> 1)
// MinInt is the minimum value of int.
const MinInt = -MaxInt - 1
// MinifyDecimal minifies a given byte slice containing a decimal and removes superfluous characters.
// It differs from Number in that it does not parse exponents.
// It does not parse or output exponents. prec is the number of significant digits.
// When prec is zero it will keep all digits. Only digits after the dot can be removed
// to reach the number of significant digits. Very large number may thus have more significant digits.
func MinifyDecimal(num []byte, prec int) []byte {
if len(num) <= 1 {
return num
}
// omit first + and register mantissa start and end, whether it's negative and the exponent
neg := false
start := 0
dot := -1
end := len(num)
if 0 < end && (num[0] == '+' || num[0] == '-') {
if num[0] == '-' {
neg = true
}
start++
}
for i, c := range num[start:] {
if c == '.' {
dot = start + i
break
}
}
if dot == -1 {
dot = end
}
// trim leading zeros but leave at least one digit
for start < end-1 && num[start] == '0' {
start++
}
// trim trailing zeros
i := end - 1
for ; dot < i; i-- {
if num[i] != '0' {
end = i + 1
break
}
}
if i == dot {
end = dot
if start == end {
num[start] = '0'
return num[start : start+1]
}
} else if start == end-1 && num[start] == '0' {
return num[start:end]
}
// apply precision
if 0 < prec && dot <= start+prec {
precEnd := start + prec + 1 // include dot
if dot == start { // for numbers like .012
digit := start + 1
for digit < end && num[digit] == '0' {
digit++
}
precEnd = digit + prec
}
if precEnd < end {
end = precEnd
// process either an increase from a lesser significant decimal (>= 5)
// or remove trailing zeros after the dot, or both
i := end - 1
inc := '5' <= num[end]
for ; start < i; i-- {
if i == dot {
// no-op
} else if inc && num[i] != '9' {
num[i]++
inc = false
break
} else if inc && i < dot { // end inc for integer
num[i] = '0'
} else if !inc && (i < dot || num[i] != '0') {
break
}
}
if i < dot {
end = dot
} else {
end = i + 1
}
if inc {
if dot == start && end == start+1 {
num[start] = '1'
} else if num[start] == '9' {
num[start] = '1'
num[start+1] = '0'
end++
} else {
num[start]++
}
}
}
}
if neg {
start--
num[start] = '-'
}
return num[start:end]
}
// MinifyNumber minifies a given byte slice containing a number and removes superfluous characters.
func MinifyNumber(num []byte, prec int) []byte {
if len(num) <= 1 {
return num
}
// omit first + and register mantissa start and end, whether it's negative and the exponent
neg := false
start := 0
dot := -1
end := len(num)
origExp := 0
if num[0] == '+' || num[0] == '-' {
if num[0] == '-' {
neg = true
}
start++
}
for i, c := range num[start:] {
if c == '.' {
dot = start + i
} else if c == 'e' || c == 'E' {
end = start + i
i += start + 1
if i < len(num) && num[i] == '+' {
i++
}
if tmpOrigExp, n := strconv.ParseInt(num[i:]); 0 < n && int64(MinInt) <= tmpOrigExp && tmpOrigExp <= int64(MaxInt) {
// range checks for when int is 32 bit
origExp = int(tmpOrigExp)
} else {
return num
}
break
}
}
if dot == -1 {
dot = end
}
// trim leading zeros but leave at least one digit
for start < end-1 && num[start] == '0' {
start++
}
// trim trailing zeros
i := end - 1
for ; dot < i; i-- {
if num[i] != '0' {
end = i + 1
break
}
}
if i == dot {
end = dot
if start == end {
num[start] = '0'
return num[start : start+1]
}
} else if start == end-1 && num[start] == '0' {
return num[start:end]
}
// apply precision
if 0 < prec { //&& (dot <= start+prec || start+prec+1 < dot || 0 < origExp) { // don't minify 9 to 10, but do 999 to 1e3 and 99e1 to 1e3
precEnd := start + prec
if dot == start { // for numbers like .012
digit := start + 1
for digit < end && num[digit] == '0' {
digit++
}
precEnd = digit + prec
} else if dot < precEnd { // for numbers where precision will include the dot
precEnd++
}
if precEnd < end && (dot < end || 1 < dot-precEnd+origExp) { // do not minify 9=>10 or 99=>100 or 9e1=>1e2 (but 90), but 999=>1e3 and 99e1=>1e3
end = precEnd
inc := '5' <= num[end]
if dot == end {
inc = end+1 < len(num) && '5' <= num[end+1]
}
if precEnd < dot {
origExp += dot - precEnd
dot = precEnd
}
// process either an increase from a lesser significant decimal (>= 5)
// and remove trailing zeros
i := end - 1
for ; start < i; i-- {
if i == dot {
// no-op
} else if inc && num[i] != '9' {
num[i]++
inc = false
break
} else if !inc && num[i] != '0' {
break
}
}
end = i + 1
if end < dot {
origExp += dot - end
dot = end
}
if inc { // single digit left
if dot == start {
num[start] = '1'
dot = start + 1
} else if num[start] == '9' {
num[start] = '1'
origExp++
} else {
num[start]++
}
}
}
}
// n is the number of significant digits
// normExp would be the exponent if it were normalised (0.1 <= f < 1)
n := 0
normExp := 0
if dot == start {
for i = dot + 1; i < end; i++ {
if num[i] != '0' {
n = end - i
normExp = dot - i + 1
break
}
}
} else if dot == end {
normExp = end - start
for i = end - 1; start <= i; i-- {
if num[i] != '0' {
n = i + 1 - start
end = i + 1
break
}
}
} else {
n = end - start - 1
normExp = dot - start
}
if origExp < 0 && (normExp < MinInt-origExp || normExp-n < MinInt-origExp) || 0 < origExp && (MaxInt-origExp < normExp || MaxInt-origExp < normExp-n) {
return num // exponent overflow
}
normExp += origExp
// intExp would be the exponent if it were an integer
intExp := normExp - n
lenIntExp := lenDigits(intExp)
lenNormExp := lenDigits(normExp)
// there are three cases to consider when printing the number
// case 1: without decimals and with a positive exponent (large numbers: 5e4)
// case 2: with decimals and with a negative exponent (small numbers with many digits: .123456e-4)
// case 3: with decimals and without an exponent (around zero: 5.6)
// case 4: without decimals and with a negative exponent (small numbers: 123456e-9)
if n <= normExp {
// case 1: print number with positive exponent
if dot < end {
// remove dot, either from the front or copy the smallest part
if dot == start {
start = end - n
} else if dot-start < end-dot-1 {
copy(num[start+1:], num[start:dot])
start++
} else {
copy(num[dot:], num[dot+1:end])
end--
}
}
if n+3 <= normExp {
num[end] = 'e'
end++
for i := end + lenIntExp - 1; end <= i; i-- {
num[i] = byte(intExp%10) + '0'
intExp /= 10
}
end += lenIntExp
} else if n+2 == normExp {
num[end] = '0'
num[end+1] = '0'
end += 2
} else if n+1 == normExp {
num[end] = '0'
end++
}
} else if normExp < -3 && lenNormExp < lenIntExp && dot < end {
// case 2: print normalized number (0.1 <= f < 1)
zeroes := -normExp + origExp
if 0 < zeroes {
copy(num[start+1:], num[start+1+zeroes:end])
end -= zeroes
} else if zeroes < 0 {
copy(num[start+1:], num[start:dot])
num[start] = '.'
}
num[end] = 'e'
num[end+1] = '-'
end += 2
for i := end + lenNormExp - 1; end <= i; i-- {
num[i] = -byte(normExp%10) + '0'
normExp /= 10
}
end += lenNormExp
} else if -lenIntExp-1 <= normExp {
// case 3: print number without exponent
zeroes := -normExp
if 0 < zeroes {
// dot placed at the front and negative exponent, adding zeroes
newDot := end - n - zeroes - 1
if newDot != dot {
d := start - newDot
if 0 < d {
if dot < end {
// copy original digits after the dot towards the end
copy(num[dot+1+d:], num[dot+1:end])
if start < dot {
// copy original digits before the dot towards the end
copy(num[start+d+1:], num[start:dot])
}
} else if start < dot {
// copy original digits before the dot towards the end
copy(num[start+d:], num[start:dot])
}
newDot = start
end += d
} else {
start += -d
}
num[newDot] = '.'
for i := range zeroes {
num[newDot+1+i] = '0'
}
}
} else {
// dot placed in the middle of the number
if dot == start {
// when there are zeroes after the dot
dot = end - n - 1
start = dot
} else if end <= dot {
// when input has no dot in it
dot = end
end++
}
newDot := start + normExp
// move digits between dot and newDot towards the end
if dot < newDot {
copy(num[dot:], num[dot+1:newDot+1])
} else if newDot < dot {
copy(num[newDot+1:], num[newDot:dot])
}
num[newDot] = '.'
}
} else {
// case 4: print number with negative exponent
// find new end, considering moving numbers to the front, removing the dot and increasing the length of the exponent
newEnd := end
if dot == start {
newEnd = start + n
} else {
newEnd--
}
newEnd += 2 + lenIntExp
exp := intExp
lenExp := lenIntExp
if newEnd < len(num) {
// it saves space to convert the decimal to an integer and decrease the exponent
if dot < end {
if dot == start {
copy(num[start:], num[end-n:end])
end = start + n
} else {
copy(num[dot:], num[dot+1:end])
end--
}
}
} else {
// it does not save space and will panic, so we revert to the original representation
exp = origExp
lenExp = 1
if origExp <= -10 || 10 <= origExp {
lenExp = lenDigits(origExp)
}
}
num[end] = 'e'
num[end+1] = '-'
end += 2
for i := end + lenExp - 1; end <= i; i-- {
num[i] = -byte(exp%10) + '0'
exp /= 10
}
end += lenExp
}
if neg {
start--
num[start] = '-'
}
return num[start:end]
}
// lenDigits returns the number of decimal digits of i, not counting
// its sign (which strconv.LenInt counts in some versions).
func lenDigits(i int) int {
if i < 0 {
i = -i
}
n := 1
for ; 10 <= i; i /= 10 {
n++
}
return n
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This is adapted from https://github.com/tdewolff/canvas
// Copyright (c) 2015 Taco de Wolff, under an MIT License.
// Package ppath provides vector paths of lines, Bézier curves, and arcs, with
// their construction, transformation, and parsing and writing as SVG.
package ppath
import (
"slices"
"cogentcore.org/core/math32"
)
// ArcToCubeImmediate causes ArcTo commands to be immediately converted into
// corresponding CubeTo commands, instead of doing this later.
// This is faster than using [Path.ReplaceArcs], but when rendering to SVG
// it might be better to turn this off in order to preserve the logical structure
// of the arcs in the SVG output.
var ArcToCubeImmediate = true
// Path is a collection of MoveTo, LineTo, QuadTo, CubeTo, ArcTo, and Close
// commands, each followed the float32 coordinate data for it.
// To enable support bidirectional processing, the command verb is also added
// to the end of the coordinate data as well.
// The last two coordinate values are the end point position of the pen after
// the action (x,y).
// QuadTo defines one control point (x,y) in between.
// CubeTo defines two control points.
// ArcTo defines (rx,ry,phi,large+sweep) i.e. the radius in x and y,
// its rotation (in radians) and the large and sweep booleans in one float32.
// While ArcTo can be converted to CubeTo, it is useful for the path intersection
// computation.
// Only valid commands are appended, so that LineTo has a non-zero length,
// QuadTo's and CubeTo's control point(s) don't (both) overlap with the start
// and end point.
type Path []float32
func New() *Path {
return &Path{}
}
// Commands
const (
MoveTo float32 = 0
LineTo float32 = 1
QuadTo float32 = 2
CubeTo float32 = 3
ArcTo float32 = 4
Close float32 = 5
)
var cmdLens = [6]int{4, 4, 6, 8, 8, 4}
// CmdLen returns the overall length of the command, including
// the command op itself.
func CmdLen(cmd float32) int {
return cmdLens[int(cmd)]
}
// ArcSize is the large-arc flag of an elliptical arc (see [Path.ArcTo]):
// [LargeArc] for the arc of more than 180 degrees, or [SmallArc].
type ArcSize bool
const (
// LargeArc is the arc of more than 180 degrees.
LargeArc ArcSize = true
// SmallArc is the arc of less than 180 degrees.
SmallArc ArcSize = false
)
// ArcSweep is the sweep flag of an elliptical arc (see [Path.ArcTo]): the
// direction from the start to the end, [Clockwise] (the positive angle
// direction, as the Y axis points down) or [CounterClockwise].
type ArcSweep bool
const (
// Clockwise sweeps in the positive angle direction.
Clockwise ArcSweep = true
// CounterClockwise sweeps in the negative angle direction.
CounterClockwise ArcSweep = false
)
// ToArcFlags converts to the largeArc and sweep boolean flags given its value in the path.
func ToArcFlags(cmd float32) (ArcSize, ArcSweep) {
large := ArcSize(cmd == 1.0 || cmd == 3.0)
sweep := ArcSweep(cmd == 2.0 || cmd == 3.0)
return large, sweep
}
// fromArcFlags converts the largeArc and sweep boolean flags to a value stored in the path.
func fromArcFlags(large ArcSize, sweep ArcSweep) float32 {
f := float32(0.0)
if large {
f += 1.0
}
if sweep {
f += 2.0
}
return f
}
// Paths is a collection of Path elements.
type Paths []Path
// Empty returns true if the set of paths is empty.
func (ps Paths) Empty() bool {
for _, p := range ps {
if !p.Empty() {
return false
}
}
return true
}
// Reset clears the path but retains the same memory.
// This can be used in loops where you append and process
// paths every iteration, and avoid new memory allocations.
func (p *Path) Reset() {
*p = (*p)[:0]
}
// Empty returns true if p is an empty path or consists of only MoveTos and Closes.
func (p Path) Empty() bool {
return len(p) <= CmdLen(MoveTo)
}
// Equals returns true if p and q are equal within tolerance Epsilon.
func (p Path) Equals(q Path) bool {
if len(p) != len(q) {
return false
}
for i := range p {
if !Equal(p[i], q[i]) {
return false
}
}
return true
}
// Sane returns true if the path is sane, ie. it does not have NaN or infinity values.
func (p Path) Sane() bool {
sane := func(x float32) bool {
return !math32.IsNaN(x) && !math32.IsInf(x, 0.0)
}
for i := 0; i < len(p); {
cmd := p[i]
i += CmdLen(cmd)
if !sane(p[i-3]) || !sane(p[i-2]) {
return false
}
switch cmd {
case QuadTo:
if !sane(p[i-5]) || !sane(p[i-4]) {
return false
}
case CubeTo, ArcTo:
if !sane(p[i-7]) || !sane(p[i-6]) || !sane(p[i-5]) || !sane(p[i-4]) {
return false
}
}
}
return true
}
// Same returns true if p and q are equal shapes within tolerance Epsilon.
// Path q may start at an offset into path p or may be in the reverse direction.
func (p Path) Same(q Path) bool {
// TODO: improve, does not handle subpaths or Close vs LineTo
if len(p) != len(q) {
return false
}
qr := q.Reverse() // TODO: can we do without?
for j := 0; j < len(q); {
equal := true
for i := range p {
if !Equal(p[i], q[(j+i)%len(q)]) {
equal = false
break
}
}
if equal {
return true
}
// backwards
equal = true
for i := range p {
if !Equal(p[i], qr[(j+i)%len(qr)]) {
equal = false
break
}
}
if equal {
return true
}
j += CmdLen(q[j])
}
return false
}
// Closed returns true if the last subpath of p is a closed path.
func (p Path) Closed() bool {
return 0 < len(p) && p[len(p)-1] == Close
}
// PointClosed returns true if the last subpath of p is a closed path
// and the close command is a point and not a line.
func (p Path) PointClosed() bool {
return 6 < len(p) && p[len(p)-1] == Close && Equal(p[len(p)-7], p[len(p)-3]) && Equal(p[len(p)-6], p[len(p)-2])
}
// HasSubpaths returns true when path p has subpaths.
// TODO: naming right? A simple path would not self-intersect.
// Add IsXMonotone and IsFlat as well?
func (p Path) HasSubpaths() bool {
for i := 0; i < len(p); {
if p[i] == MoveTo && i != 0 {
return true
}
i += CmdLen(p[i])
}
return false
}
// Clone returns a copy of p.
func (p Path) Clone() Path {
return slices.Clone(p)
}
// CopyTo returns a copy of p, using the memory of path q.
func (p Path) CopyTo(q Path) Path {
if q == nil || len(q) < len(p) {
q = make(Path, len(p))
} else {
q = q[:len(p)]
}
copy(q, p)
return q
}
// Len returns the number of commands in the path.
func (p Path) Len() int {
n := 0
for i := 0; i < len(p); {
i += CmdLen(p[i])
n++
}
return n
}
// Append appends path q to p and returns the extended path p.
func (p Path) Append(qs ...Path) Path {
if p.Empty() {
p = Path{}
}
for _, q := range qs {
if !q.Empty() {
p = append(p, q...)
}
}
return p
}
// Join joins path q to p and returns the extended path p
// (or q if p is empty). It's like executing the commands
// in q to p in sequence, where if the first MoveTo of q
// doesn't coincide with p, or if p ends in Close,
// it will fallback to appending the paths.
func (p Path) Join(q Path) Path {
if q.Empty() {
return p
} else if p.Empty() {
return q
}
if p[len(p)-1] == Close || !Equal(p[len(p)-3], q[1]) || !Equal(p[len(p)-2], q[2]) {
return append(p, q...)
}
d := q[CmdLen(MoveTo):]
// add the first command through the command functions to use the optimization features
// q is not empty, so starts with a MoveTo followed by other commands
cmd := d[0]
switch cmd {
case MoveTo:
p.MoveTo(d[1], d[2])
case LineTo:
p.LineTo(d[1], d[2])
case QuadTo:
p.QuadTo(d[1], d[2], d[3], d[4])
case CubeTo:
p.CubeTo(d[1], d[2], d[3], d[4], d[5], d[6])
case ArcTo:
large, sweep := ToArcFlags(d[4])
p.ArcTo(d[1], d[2], d[3], large, sweep, d[5], d[6])
case Close:
p.Close()
}
i := len(p)
end := p.StartPos()
p = append(p, d[CmdLen(cmd):]...)
// repair close commands
for i < len(p) {
cmd := p[i]
if cmd == MoveTo {
break
} else if cmd == Close {
p[i+1] = end.X
p[i+2] = end.Y
break
}
i += CmdLen(cmd)
}
return p
}
// Pos returns the current position of the path,
// which is the end point of the last command.
func (p Path) Pos() math32.Vector2 {
if 0 < len(p) {
return math32.Vec2(p[len(p)-3], p[len(p)-2])
}
return math32.Vector2{}
}
// StartPos returns the start point of the current subpath,
// i.e. it returns the position of the last MoveTo command.
func (p Path) StartPos() math32.Vector2 {
for i := len(p); 0 < i; {
cmd := p[i-1]
if cmd == MoveTo {
return math32.Vec2(p[i-3], p[i-2])
}
i -= CmdLen(cmd)
}
return math32.Vector2{}
}
// Coords returns all the coordinates of the segment
// start/end points. It omits zero-length Closes.
func (p Path) Coords() []math32.Vector2 {
coords := []math32.Vector2{}
for i := 0; i < len(p); {
cmd := p[i]
i += CmdLen(cmd)
if len(coords) == 0 || cmd != Close || !EqualPoint(coords[len(coords)-1], math32.Vec2(p[i-3], p[i-2])) {
coords = append(coords, math32.Vec2(p[i-3], p[i-2]))
}
}
return coords
}
/////// Accessors
// EndPoint returns the end point for MoveTo, LineTo, and Close commands,
// where the command is at index i.
func (p Path) EndPoint(i int) math32.Vector2 {
return math32.Vec2(p[i+1], p[i+2])
}
// QuadToPoints returns the control point and end for QuadTo command,
// where the command is at index i.
func (p Path) QuadToPoints(i int) (cp, end math32.Vector2) {
return math32.Vec2(p[i+1], p[i+2]), math32.Vec2(p[i+3], p[i+4])
}
// CubeToPoints returns the cp1, cp2, and end for CubeTo command,
// where the command is at index i.
func (p Path) CubeToPoints(i int) (cp1, cp2, end math32.Vector2) {
return math32.Vec2(p[i+1], p[i+2]), math32.Vec2(p[i+3], p[i+4]), math32.Vec2(p[i+5], p[i+6])
}
// ArcToPoints returns the rx, ry, phi, large, sweep values for ArcTo command,
// where the command is at index i.
func (p Path) ArcToPoints(i int) (rx, ry, phi float32, large ArcSize, sweep ArcSweep, end math32.Vector2) {
rx = p[i+1]
ry = p[i+2]
phi = p[i+3]
large, sweep = ToArcFlags(p[i+4])
end = math32.Vec2(p[i+5], p[i+6])
return
}
/////// Constructors
// MoveTo moves the path to (x,y) without connecting the path.
// It starts a new independent subpath. Multiple subpaths can be useful
// when negating parts of a previous path by overlapping it with a path
// in the opposite direction. The behaviour for overlapping paths depends
// on the FillRules.
func (p *Path) MoveTo(x, y float32) {
if 0 < len(*p) && (*p)[len(*p)-1] == MoveTo {
(*p)[len(*p)-3] = x
(*p)[len(*p)-2] = y
return
}
*p = append(*p, MoveTo, x, y, MoveTo)
}
// LineTo adds a linear path to (x,y).
func (p *Path) LineTo(x, y float32) {
start := p.Pos()
end := math32.Vec2(x, y)
if EqualPoint(start, end) {
return
} else if CmdLen(LineTo) <= len(*p) && (*p)[len(*p)-1] == LineTo {
prevStart := math32.Vector2{}
if CmdLen(LineTo) < len(*p) {
prevStart = math32.Vec2((*p)[len(*p)-CmdLen(LineTo)-3], (*p)[len(*p)-CmdLen(LineTo)-2])
}
// divide by length^2 since otherwise the perpdot between very small segments may be
// below Epsilon
da := start.Sub(prevStart)
db := end.Sub(start)
div := da.Cross(db)
if length := da.Length() * db.Length(); Equal(div/length, 0.0) {
// lines are parallel
extends := false
if da.Y < da.X {
extends = math32.Signbit(da.X) == math32.Signbit(db.X)
} else {
extends = math32.Signbit(da.Y) == math32.Signbit(db.Y)
}
if extends {
//if Equal(end.Sub(start).AngleBetween(start.Sub(prevStart)), 0.0) {
(*p)[len(*p)-3] = x
(*p)[len(*p)-2] = y
return
}
}
}
if len(*p) == 0 {
p.MoveTo(0.0, 0.0)
} else if (*p)[len(*p)-1] == Close {
p.MoveTo((*p)[len(*p)-3], (*p)[len(*p)-2])
}
*p = append(*p, LineTo, end.X, end.Y, LineTo)
}
// QuadTo adds a quadratic Bézier path with control point (cpx,cpy) and end point (x,y).
func (p *Path) QuadTo(cpx, cpy, x, y float32) {
start := p.Pos()
cp := math32.Vec2(cpx, cpy)
end := math32.Vec2(x, y)
if EqualPoint(start, end) && EqualPoint(start, cp) {
return
} else if !EqualPoint(start, end) && (EqualPoint(start, cp) || AngleEqual(AngleBetween(end.Sub(start), cp.Sub(start)), 0.0)) && (EqualPoint(end, cp) || AngleEqual(AngleBetween(end.Sub(start), end.Sub(cp)), 0.0)) {
p.LineTo(end.X, end.Y)
return
}
if len(*p) == 0 {
p.MoveTo(0.0, 0.0)
} else if (*p)[len(*p)-1] == Close {
p.MoveTo((*p)[len(*p)-3], (*p)[len(*p)-2])
}
*p = append(*p, QuadTo, cp.X, cp.Y, end.X, end.Y, QuadTo)
}
// CubeTo adds a cubic Bézier path with control points
// (cpx1,cpy1) and (cpx2,cpy2) and end point (x,y).
func (p *Path) CubeTo(cpx1, cpy1, cpx2, cpy2, x, y float32) {
start := p.Pos()
cp1 := math32.Vec2(cpx1, cpy1)
cp2 := math32.Vec2(cpx2, cpy2)
end := math32.Vec2(x, y)
if EqualPoint(start, end) && EqualPoint(start, cp1) && EqualPoint(start, cp2) {
return
} else if !EqualPoint(start, end) && (EqualPoint(start, cp1) || EqualPoint(end, cp1) || AngleEqual(AngleBetween(end.Sub(start), cp1.Sub(start)), 0.0) && AngleEqual(AngleBetween(end.Sub(start), end.Sub(cp1)), 0.0)) && (EqualPoint(start, cp2) || EqualPoint(end, cp2) || AngleEqual(AngleBetween(end.Sub(start), cp2.Sub(start)), 0.0) && AngleEqual(AngleBetween(end.Sub(start), end.Sub(cp2)), 0.0)) {
p.LineTo(end.X, end.Y)
return
}
if len(*p) == 0 {
p.MoveTo(0.0, 0.0)
} else if (*p)[len(*p)-1] == Close {
p.MoveTo((*p)[len(*p)-3], (*p)[len(*p)-2])
}
*p = append(*p, CubeTo, cp1.X, cp1.Y, cp2.X, cp2.Y, end.X, end.Y, CubeTo)
}
// ArcTo adds an arc with radii rx and ry, with rot the counter clockwise
// rotation with respect to the coordinate system in radians, large and sweep booleans
// (see https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths#Arcs),
// and (x,y) the end position of the pen. The start position of the pen was
// given by a previous command's end point.
func (p *Path) ArcTo(rx, ry, rot float32, large ArcSize, sweep ArcSweep, x, y float32) {
start := p.Pos()
end := math32.Vec2(x, y)
if EqualPoint(start, end) {
return
}
if Equal(rx, 0.0) || math32.IsInf(rx, 0) || Equal(ry, 0.0) || math32.IsInf(ry, 0) {
p.LineTo(end.X, end.Y)
return
}
rx = math32.Abs(rx)
ry = math32.Abs(ry)
if Equal(rx, ry) {
rot = 0.0 // circle
} else if rx < ry {
rx, ry = ry, rx
rot += math32.Pi / 2.0
}
phi := AngleNorm(rot)
if math32.Pi <= phi { // phi is canonical within 0 <= phi < 180
phi -= math32.Pi
}
// scale ellipse if rx and ry are too small
lambda := EllipseRadiiCorrection(start, rx, ry, phi, end)
if lambda > 1.0 {
rx *= lambda
ry *= lambda
}
if len(*p) == 0 {
p.MoveTo(0.0, 0.0)
} else if (*p)[len(*p)-1] == Close {
p.MoveTo((*p)[len(*p)-3], (*p)[len(*p)-2])
}
if ArcToCubeImmediate {
for _, bezier := range ellipseToCubicBeziers(start, rx, ry, phi, large, sweep, end) {
p.CubeTo(bezier[1].X, bezier[1].Y, bezier[2].X, bezier[2].Y, bezier[3].X, bezier[3].Y)
}
} else {
*p = append(*p, ArcTo, rx, ry, phi, fromArcFlags(large, sweep), end.X, end.Y, ArcTo)
}
}
// ArcToDeg is a version of [Path.ArcTo] with the angle in degrees instead of radians.
// It adds an arc with radii rx and ry, with rot the counter clockwise
// rotation with respect to the coordinate system in degrees, large and sweep booleans
// (see https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths#Arcs),
// and (x,y) the end position of the pen. The start position of the pen was
// given by a previous command's end point.
func (p *Path) ArcToDeg(rx, ry, rot float32, large ArcSize, sweep ArcSweep, x, y float32) {
p.ArcTo(rx, ry, math32.DegToRad(rot), large, sweep, x, y)
}
// Arc adds an elliptical arc with radii rx and ry, with rot the
// counter clockwise rotation in radians, and theta0 and theta1
// the angles in radians of the ellipse (before rot is applies)
// between which the arc will run. If theta0 < theta1,
// the arc will run in a CCW direction. If the difference between
// theta0 and theta1 is bigger than 360 degrees, one full circle
// will be drawn and the remaining part of diff % 360,
// e.g. a difference of 810 degrees will draw one full circle
// and an arc over 90 degrees.
func (p *Path) Arc(rx, ry, phi, theta0, theta1 float32) {
dtheta := math32.Abs(theta1 - theta0)
sweep := theta0 < theta1
large := math32.Mod(dtheta, 2.0*math32.Pi) > math32.Pi
p0 := EllipsePos(rx, ry, phi, 0.0, 0.0, theta0)
p1 := EllipsePos(rx, ry, phi, 0.0, 0.0, theta1)
start := p.Pos()
center := start.Sub(p0)
if dtheta >= 2.0*math32.Pi {
startOpposite := center.Sub(p0)
p.ArcTo(rx, ry, phi, ArcSize(large), ArcSweep(sweep), startOpposite.X, startOpposite.Y)
p.ArcTo(rx, ry, phi, ArcSize(large), ArcSweep(sweep), start.X, start.Y)
if Equal(math32.Mod(dtheta, 2.0*math32.Pi), 0.0) {
return
}
}
end := center.Add(p1)
p.ArcTo(rx, ry, phi, ArcSize(large), ArcSweep(sweep), end.X, end.Y)
}
// ArcDeg is a version of [Path.Arc] that uses degrees instead of radians,
// to add an elliptical arc with radii rx and ry, with rot the
// counter clockwise rotation in degrees, and theta0 and theta1
// the angles in degrees of the ellipse (before rot is applied)
// between which the arc will run.
func (p *Path) ArcDeg(rx, ry, rot, theta0, theta1 float32) {
p.Arc(rx, ry, math32.DegToRad(rot), math32.DegToRad(theta0), math32.DegToRad(theta1))
}
// Close closes a (sub)path with a LineTo to the start of the path
// (the most recent MoveTo command). It also signals the path closes
// as opposed to being just a LineTo command, which can be significant
// for stroking purposes for example.
func (p *Path) Close() {
if len(*p) == 0 || (*p)[len(*p)-1] == Close {
// already closed or empty
return
} else if (*p)[len(*p)-1] == MoveTo {
// remove MoveTo + Close
*p = (*p)[:len(*p)-CmdLen(MoveTo)]
return
}
end := p.StartPos()
if (*p)[len(*p)-1] == LineTo && Equal((*p)[len(*p)-3], end.X) && Equal((*p)[len(*p)-2], end.Y) {
// replace LineTo by Close if equal (with the coordinates of the start,
// so that they match exactly)
(*p)[len(*p)-CmdLen(LineTo)] = Close
(*p)[len(*p)-3] = end.X
(*p)[len(*p)-2] = end.Y
(*p)[len(*p)-1] = Close
return
} else if (*p)[len(*p)-1] == LineTo {
// replace LineTo by Close if equidirectional extension
start := math32.Vec2((*p)[len(*p)-3], (*p)[len(*p)-2])
prevStart := math32.Vector2{}
if CmdLen(LineTo) < len(*p) {
prevStart = math32.Vec2((*p)[len(*p)-CmdLen(LineTo)-3], (*p)[len(*p)-CmdLen(LineTo)-2])
}
if Equal(AngleBetween(end.Sub(start), start.Sub(prevStart)), 0.0) {
(*p)[len(*p)-CmdLen(LineTo)] = Close
(*p)[len(*p)-3] = end.X
(*p)[len(*p)-2] = end.Y
(*p)[len(*p)-1] = Close
return
}
}
*p = append(*p, Close, end.X, end.Y, Close)
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This is adapted from https://github.com/tdewolff/canvas
// Copyright (c) 2015 Taco de Wolff, under an MIT License.
package ppath
import (
"cogentcore.org/core/math32"
)
// Scanner returns a path scanner.
func (p Path) Scanner() *Scanner {
return &Scanner{p, -1}
}
// ReverseScanner returns a path scanner in reverse order.
func (p Path) ReverseScanner() ReverseScanner {
return ReverseScanner{p, len(p)}
}
// Scanner scans the path.
type Scanner struct {
p Path
i int // i is at the end of the current command
}
// Scan scans a new path segment and should be called before the other methods.
func (s *Scanner) Scan() bool {
if s.i+1 < len(s.p) {
s.i += CmdLen(s.p[s.i+1])
return true
}
return false
}
// Cmd returns the current path segment command.
func (s *Scanner) Cmd() float32 {
return s.p[s.i]
}
// Index returns the index in path of the current command.
func (s *Scanner) Index() int {
return (s.i - CmdLen(s.p[s.i])) + 1
}
// Values returns the current path segment values.
func (s *Scanner) Values() []float32 {
return s.p[s.i-CmdLen(s.p[s.i])+2 : s.i]
}
// Start returns the current path segment start position.
func (s *Scanner) Start() math32.Vector2 {
i := s.i - CmdLen(s.p[s.i])
if i == -1 {
return math32.Vector2{}
}
return math32.Vec2(s.p[i-2], s.p[i-1])
}
// CP1 returns the first control point for quadratic and cubic Béziers.
func (s *Scanner) CP1() math32.Vector2 {
if s.p[s.i] != QuadTo && s.p[s.i] != CubeTo {
panic("must be quadratic or cubic Bézier")
}
i := s.i - CmdLen(s.p[s.i]) + 1
return math32.Vec2(s.p[i+1], s.p[i+2])
}
// CP2 returns the second control point for cubic Béziers.
func (s *Scanner) CP2() math32.Vector2 {
if s.p[s.i] != CubeTo {
panic("must be cubic Bézier")
}
i := s.i - CmdLen(s.p[s.i]) + 1
return math32.Vec2(s.p[i+3], s.p[i+4])
}
// Arc returns the arguments for arcs (rx,ry,rot,large,sweep).
func (s *Scanner) Arc() (float32, float32, float32, ArcSize, ArcSweep) {
if s.p[s.i] != ArcTo {
panic("must be arc")
}
i := s.i - CmdLen(s.p[s.i]) + 1
large, sweep := ToArcFlags(s.p[i+4])
return s.p[i+1], s.p[i+2], s.p[i+3], large, sweep
}
// End returns the current path segment end position.
func (s *Scanner) End() math32.Vector2 {
return math32.Vec2(s.p[s.i-2], s.p[s.i-1])
}
// Path returns the current path segment.
func (s *Scanner) Path() Path {
p := Path{}
p.MoveTo(s.Start().X, s.Start().Y)
switch s.Cmd() {
case LineTo:
p.LineTo(s.End().X, s.End().Y)
case QuadTo:
p.QuadTo(s.CP1().X, s.CP1().Y, s.End().X, s.End().Y)
case CubeTo:
p.CubeTo(s.CP1().X, s.CP1().Y, s.CP2().X, s.CP2().Y, s.End().X, s.End().Y)
case ArcTo:
rx, ry, rot, large, sweep := s.Arc()
p.ArcTo(rx, ry, rot, large, sweep, s.End().X, s.End().Y)
}
return p
}
// ReverseScanner scans the path in reverse order.
type ReverseScanner struct {
p Path
i int
}
// Scan scans a new path segment and should be called before the other methods.
func (s *ReverseScanner) Scan() bool {
if 0 < s.i {
s.i -= CmdLen(s.p[s.i-1])
return true
}
return false
}
// Cmd returns the current path segment command.
func (s *ReverseScanner) Cmd() float32 {
return s.p[s.i]
}
// Values returns the current path segment values.
func (s *ReverseScanner) Values() []float32 {
return s.p[s.i+1 : s.i+CmdLen(s.p[s.i])-1]
}
// Start returns the current path segment start position.
func (s *ReverseScanner) Start() math32.Vector2 {
if s.i == 0 {
return math32.Vector2{}
}
return math32.Vec2(s.p[s.i-3], s.p[s.i-2])
}
// CP1 returns the first control point for quadratic and cubic Béziers.
func (s *ReverseScanner) CP1() math32.Vector2 {
if s.p[s.i] != QuadTo && s.p[s.i] != CubeTo {
panic("must be quadratic or cubic Bézier")
}
return math32.Vec2(s.p[s.i+1], s.p[s.i+2])
}
// CP2 returns the second control point for cubic Béziers.
func (s *ReverseScanner) CP2() math32.Vector2 {
if s.p[s.i] != CubeTo {
panic("must be cubic Bézier")
}
return math32.Vec2(s.p[s.i+3], s.p[s.i+4])
}
// Arc returns the arguments for arcs (rx,ry,rot,large,sweep).
func (s *ReverseScanner) Arc() (float32, float32, float32, ArcSize, ArcSweep) {
if s.p[s.i] != ArcTo {
panic("must be arc")
}
large, sweep := ToArcFlags(s.p[s.i+4])
return s.p[s.i+1], s.p[s.i+2], s.p[s.i+3], large, sweep
}
// End returns the current path segment end position.
func (s *ReverseScanner) End() math32.Vector2 {
i := s.i + CmdLen(s.p[s.i])
return math32.Vec2(s.p[i-3], s.p[i-2])
}
// Path returns the current path segment.
func (s *ReverseScanner) Path() Path {
p := Path{}
p.MoveTo(s.Start().X, s.Start().Y)
switch s.Cmd() {
case LineTo:
p.LineTo(s.End().X, s.End().Y)
case QuadTo:
p.QuadTo(s.CP1().X, s.CP1().Y, s.End().X, s.End().Y)
case CubeTo:
p.CubeTo(s.CP1().X, s.CP1().Y, s.CP2().X, s.CP2().Y, s.End().X, s.End().Y)
case ArcTo:
rx, ry, rot, large, sweep := s.Arc()
p.ArcTo(rx, ry, rot, large, sweep, s.End().X, s.End().Y)
}
return p
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This is adapted from https://github.com/tdewolff/canvas
// Copyright (c) 2015 Taco de Wolff, under an MIT License.
package ppath
import (
"cogentcore.org/core/math32"
"cogentcore.org/core/styles/sides"
)
// Line adds a line segment of from (x1,y1) to (x2,y2).
func (p *Path) Line(x1, y1, x2, y2 float32) *Path {
if Equal(x1, x2) && Equal(y1, y2) {
return p
}
p.MoveTo(x1, y1)
p.LineTo(x2, y2)
return p
}
// Polyline adds multiple connected lines, with no final Close.
func (p *Path) Polyline(points ...math32.Vector2) *Path {
sz := len(points)
if sz < 2 {
return p
}
p.MoveTo(points[0].X, points[0].Y)
for i := 1; i < sz; i++ {
p.LineTo(points[i].X, points[i].Y)
}
return p
}
// Polygon adds multiple connected lines with a final Close.
func (p *Path) Polygon(points ...math32.Vector2) *Path {
p.Polyline(points...)
p.Close()
return p
}
// Rectangle adds a rectangle of width w and height h.
func (p *Path) Rectangle(x, y, w, h float32) *Path {
if Equal(w, 0.0) || Equal(h, 0.0) {
return p
}
p.MoveTo(x, y)
p.LineTo(x+w, y)
p.LineTo(x+w, y+h)
p.LineTo(x, y+h)
p.Close()
return p
}
// RoundedRectangle adds a rectangle of width w and height h
// with rounded corners of radius r. A negative radius will cast
// the corners inwards (i.e. concave).
func (p *Path) RoundedRectangle(x, y, w, h, r float32) *Path {
if Equal(w, 0.0) || Equal(h, 0.0) {
return p
} else if Equal(r, 0.0) {
return p.Rectangle(x, y, w, h)
}
sweep := true
if r < 0.0 {
sweep = false
r = -r
}
r = math32.Min(r, w/2.0)
r = math32.Min(r, h/2.0)
p.MoveTo(x, y+r)
p.ArcTo(r, r, 0.0, SmallArc, ArcSweep(sweep), x+r, y)
p.LineTo(x+w-r, y)
p.ArcTo(r, r, 0.0, SmallArc, ArcSweep(sweep), x+w, y+r)
p.LineTo(x+w, y+h-r)
p.ArcTo(r, r, 0.0, SmallArc, ArcSweep(sweep), x+w-r, y+h)
p.LineTo(x+r, y+h)
p.ArcTo(r, r, 0.0, SmallArc, ArcSweep(sweep), x, y+h-r)
p.Close()
return p
}
// RoundedRectangleSides draws a standard rounded rectangle
// with a consistent border and with the given x and y position,
// width and height, and border radius for each corner.
// This version uses the Arc elliptical arc function.
func (p *Path) RoundedRectangleSides(x, y, w, h float32, r sides.Floats) *Path {
// clamp border radius values
min := math32.Min(w/2, h/2)
r.Top = math32.Clamp(r.Top, 0, min)
r.Right = math32.Clamp(r.Right, 0, min)
r.Bottom = math32.Clamp(r.Bottom, 0, min)
r.Left = math32.Clamp(r.Left, 0, min)
// position values; some variables are missing because they are unused
var (
xtl, ytl = x, y // top left
xtli, ytli = x + r.Top, y + r.Top // top left inset
ytr = y // top right
xtri, ytri = x + w - r.Right, y + r.Right // top right inset
xbr = x + w // bottom right
xbri, ybri = x + w - r.Bottom, y + h - r.Bottom // bottom right inset
ybl = y + h // bottom left
xbli, ybli = x + r.Left, y + h - r.Left // bottom left inset
)
p.MoveTo(xtl, ytli)
if r.Top != 0 {
p.ArcTo(r.Top, r.Top, 0, SmallArc, Clockwise, xtli, ytl)
}
p.LineTo(xtri, ytr)
if r.Right != 0 {
p.ArcTo(r.Right, r.Right, 0, SmallArc, Clockwise, xbr, ytri)
}
p.LineTo(xbr, ybri)
if r.Bottom != 0 {
p.ArcTo(r.Bottom, r.Bottom, 0, SmallArc, Clockwise, xbri, ybl)
}
p.LineTo(xbli, ybl)
if r.Left != 0 {
p.ArcTo(r.Left, r.Left, 0, SmallArc, Clockwise, xtl, ybli)
}
p.Close()
return p
}
// BeveledRectangle adds a rectangle of width w and height h
// with beveled corners at distance r from the corner.
func (p *Path) BeveledRectangle(x, y, w, h, r float32) *Path {
if Equal(w, 0.0) || Equal(h, 0.0) {
return p
} else if Equal(r, 0.0) {
return p.Rectangle(x, y, w, h)
}
r = math32.Abs(r)
r = math32.Min(r, w/2.0)
r = math32.Min(r, h/2.0)
p.MoveTo(x, y+r)
p.LineTo(x+r, y)
p.LineTo(x+w-r, y)
p.LineTo(x+w, y+r)
p.LineTo(x+w, y+h-r)
p.LineTo(x+w-r, y+h)
p.LineTo(x+r, y+h)
p.LineTo(x, y+h-r)
p.Close()
return p
}
// Circle adds a circle at given center coordinates of radius r.
func (p *Path) Circle(cx, cy, r float32) *Path {
return p.Ellipse(cx, cy, r, r)
}
// Ellipse adds an ellipse at given center coordinates of radii rx and ry.
func (p *Path) Ellipse(cx, cy, rx, ry float32) *Path {
if Equal(rx, 0.0) || Equal(ry, 0.0) {
return p
}
p.MoveTo(cx+rx, cy+(ry*0.001))
p.ArcTo(rx, ry, 0.0, SmallArc, Clockwise, cx-rx, cy)
p.ArcTo(rx, ry, 0.0, SmallArc, Clockwise, cx+rx, cy)
p.Close()
return p
}
// CircularArc adds a circular arc centered at given coordinates with radius r
// and theta0 and theta1 as the angles in degrees of the ellipse
// (before rot is applied) between which the arc will run.
// If theta0 < theta1, the arc will run in a CCW direction.
// If the difference between theta0 and theta1 is bigger than 360 degrees,
// one full circle will be drawn and the remaining part of diff % 360,
// e.g. a difference of 810 degrees will draw one full circle and an arc
// over 90 degrees.
func (p *Path) CircularArc(x, y, r, theta0, theta1 float32) *Path {
return p.EllipticalArc(x, y, r, r, 0, theta0, theta1)
}
// EllipticalArc adds an elliptical arc centered at given coordinates with
// radii rx and ry, with rot the counter clockwise rotation in radians,
// and theta0 and theta1 the angles in radians of the ellipse
// (before rot is applied) between which the arc will run.
// If theta0 < theta1, the arc will run in a CCW direction.
// If the difference between theta0 and theta1 is bigger than 360 degrees,
// one full circle will be drawn and the remaining part of diff % 360,
// e.g. a difference of 810 degrees will draw one full circle and an arc
// over 90 degrees.
func (p *Path) EllipticalArc(x, y, rx, ry, rot, theta0, theta1 float32) *Path {
sins, coss := math32.Sincos(theta0)
sx := rx * coss
sy := ry * sins
p.MoveTo(x+sx, y+sy)
p.Arc(rx, ry, rot, theta0, theta1)
return p
}
// Triangle adds a triangle of radius r pointing upwards.
func (p *Path) Triangle(r float32) *Path {
return p.RegularPolygon(3, r, true)
}
// RegularPolygon adds a regular polygon with radius r.
// It uses n vertices/edges, so when n approaches infinity
// this will return a path that approximates a circle.
// n must be 3 or more. The up boolean defines whether
// the first point will point upwards or downwards.
func (p *Path) RegularPolygon(n int, r float32, up bool) *Path {
return p.RegularStarPolygon(n, 1, r, up)
}
// RegularStarPolygon adds a regular star polygon with radius r.
// It uses n vertices of density d. This will result in a
// self-intersection star in counter clockwise direction.
// If n/2 < d the star will be clockwise and if n and d are not coprime
// a regular polygon will be obtained, possible with multiple windings.
// n must be 3 or more and d 2 or more. The up boolean defines whether
// the first point will point upwards or downwards.
func (p *Path) RegularStarPolygon(n, d int, r float32, up bool) *Path {
if n < 3 || d < 1 || n == d*2 || Equal(r, 0.0) {
return p
}
dtheta := 2.0 * math32.Pi / float32(n)
theta0 := float32(0.5 * math32.Pi)
if !up {
theta0 += dtheta / 2.0
}
for i := 0; i == 0 || i%n != 0; i += d {
theta := theta0 + float32(i)*dtheta
sintheta, costheta := math32.Sincos(theta)
if i == 0 {
p.MoveTo(r*costheta, r*sintheta)
} else {
p.LineTo(r*costheta, r*sintheta)
}
}
p.Close()
return p
}
// StarPolygon adds a star polygon of n points with alternating
// radius R and r. The up boolean defines whether the first point
// will be point upwards or downwards.
func (p *Path) StarPolygon(n int, R, r float32, up bool) *Path {
if n < 3 || Equal(R, 0.0) || Equal(r, 0.0) {
return p
}
n *= 2
dtheta := 2.0 * math32.Pi / float32(n)
theta0 := float32(0.5 * math32.Pi)
if !up {
theta0 += dtheta
}
for i := 0; i < n; i++ {
theta := theta0 + float32(i)*dtheta
sintheta, costheta := math32.Sincos(theta)
if i == 0 {
p.MoveTo(R*costheta, R*sintheta)
} else if i%2 == 0 {
p.LineTo(R*costheta, R*sintheta)
} else {
p.LineTo(r*costheta, r*sintheta)
}
}
p.Close()
return p
}
// Grid adds a stroked grid of width w and height h,
// with grid line thickness r, and the number of cells horizontally
// and vertically as nx and ny respectively.
func (p *Path) Grid(w, h float32, nx, ny int, r float32) *Path {
if nx < 1 || ny < 1 || w <= float32(nx+1)*r || h <= float32(ny+1)*r {
return p
}
p.Rectangle(0, 0, w, h)
dx, dy := (w-float32(nx+1)*r)/float32(nx), (h-float32(ny+1)*r)/float32(ny)
cell := New().Rectangle(0, 0, dx, dy).Reverse()
for j := range ny {
for i := range nx {
x := r + float32(i)*(r+dx)
y := r + float32(j)*(r+dy)
*p = p.Append(cell.Clone().Translate(x, y)) // Translate is in place
}
}
return p
}
func ArcToQuad(start math32.Vector2, rx, ry, phi float32, large ArcSize, sweep ArcSweep, end math32.Vector2) Path {
p := Path{}
p.MoveTo(start.X, start.Y)
for _, bezier := range ellipseToQuadraticBeziers(start, rx, ry, phi, large, sweep, end) {
p.QuadTo(bezier[1].X, bezier[1].Y, bezier[2].X, bezier[2].Y)
}
return p
}
func ArcToCube(start math32.Vector2, rx, ry, phi float32, large ArcSize, sweep ArcSweep, end math32.Vector2) Path {
p := Path{}
p.MoveTo(start.X, start.Y)
for _, bezier := range ellipseToCubicBeziers(start, rx, ry, phi, large, sweep, end) {
p.CubeTo(bezier[1].X, bezier[1].Y, bezier[2].X, bezier[2].Y, bezier[3].X, bezier[3].Y)
}
return p
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This is adapted from https://github.com/tdewolff/canvas
// Copyright (c) 2015 Taco de Wolff, under an MIT License.
package ppath
import "cogentcore.org/core/math32"
//go:generate core generate
// FillRules specifies the algorithm for which area is to be filled and which not,
// in particular when multiple subpaths overlap. The NonZero rule is the default
// and will fill any point that is being enclosed by an unequal number of paths
// winding clock-wise and counter clock-wise, otherwise it will not be filled.
// The EvenOdd rule will fill any point that is being enclosed by an uneven number
// of paths, whichever their direction. Positive fills only counter clock-wise
// oriented paths, while Negative fills only clock-wise oriented paths.
type FillRules int32 //enums:enum -transform lower
const (
NonZero FillRules = iota
EvenOdd
Positive
Negative
)
func (fr FillRules) Fills(windings int) bool {
switch fr {
case NonZero:
return windings != 0
case EvenOdd:
return windings%2 != 0
case Positive:
return 0 < windings
case Negative:
return windings < 0
}
return false
}
// todo: these need serious work:
// VectorEffects contains special effects for rendering
type VectorEffects int32 //enums:enum -trim-prefix VectorEffect -transform kebab
const (
VectorEffectNone VectorEffects = iota
// VectorEffectNonScalingStroke means that the stroke width is not affected by
// transform properties
VectorEffectNonScalingStroke
)
// Caps specifies the end-cap of a stroked line: stroke-linecap property in SVG
type Caps int32 //enums:enum -trim-prefix Cap -transform kebab
const (
// CapButt indicates to draw no line caps; it draws a
// line with the length of the specified length.
CapButt Caps = iota
// CapRound indicates to draw a semicircle on each line
// end with a diameter of the stroke width.
CapRound
// CapSquare indicates to draw a rectangle on each line end
// with a height of the stroke width and a width of half of the
// stroke width.
CapSquare
)
// Joins specifies the way stroked lines are joined together:
// stroke-linejoin property in SVG
type Joins int32 //enums:enum -trim-prefix Join -transform kebab
const (
JoinMiter Joins = iota
JoinMiterClip
JoinRound
JoinBevel
JoinArcs
JoinArcsClip
)
// Dash patterns
var (
Solid = []float32{}
Dotted = []float32{1.0, 2.0}
DenselyDotted = []float32{1.0, 1.0}
SparselyDotted = []float32{1.0, 4.0}
Dashed = []float32{3.0, 3.0}
DenselyDashed = []float32{3.0, 1.0}
SparselyDashed = []float32{3.0, 6.0}
Dashdotted = []float32{3.0, 2.0, 1.0, 2.0}
DenselyDashdotted = []float32{3.0, 1.0, 1.0, 1.0}
SparselyDashdotted = []float32{3.0, 4.0, 1.0, 4.0}
)
func ScaleDash(scale float32, offset float32, d []float32) (float32, []float32) {
d2 := make([]float32, len(d))
for i := range d {
d2[i] = d[i] * scale
}
return offset * scale, d2
}
// DirectionIndex returns the direction of the path at the given index
// into Path and t in [0.0,1.0]. Path must not contain subpaths,
// and will return the path's starting direction when i points
// to a MoveTo, or the path's final direction when i points to
// a Close of zero-length.
func DirectionIndex(p Path, i int, t float32) math32.Vector2 {
last := len(p)
if p[last-1] == Close && EqualPoint(math32.Vec2(p[last-CmdLen(Close)-3], p[last-CmdLen(Close)-2]), math32.Vec2(p[last-3], p[last-2])) {
// point-closed
last -= CmdLen(Close)
}
if i == 0 {
// get path's starting direction when i points to MoveTo
i = 4
t = 0.0
} else if i < len(p) && i == last {
// get path's final direction when i points to zero-length Close
i -= CmdLen(p[i-1])
t = 1.0
}
if i < 0 || len(p) <= i || last < i+CmdLen(p[i]) {
return math32.Vector2{}
}
cmd := p[i]
var start math32.Vector2
if i == 0 {
start = math32.Vec2(p[last-3], p[last-2])
} else {
start = math32.Vec2(p[i-3], p[i-2])
}
i += CmdLen(cmd)
end := math32.Vec2(p[i-3], p[i-2])
switch cmd {
case LineTo, Close:
return end.Sub(start).Normal()
case QuadTo:
cp := math32.Vec2(p[i-5], p[i-4])
return QuadraticBezierDeriv(start, cp, end, t).Normal()
case CubeTo:
cp1 := math32.Vec2(p[i-7], p[i-6])
cp2 := math32.Vec2(p[i-5], p[i-4])
return CubicBezierDeriv(start, cp1, cp2, end, t).Normal()
case ArcTo:
rx, ry, phi := p[i-7], p[i-6], p[i-5]
large, sweep := ToArcFlags(p[i-4])
_, _, theta0, theta1 := EllipseToCenter(start.X, start.Y, rx, ry, phi, large, sweep, end.X, end.Y)
theta := theta0 + t*(theta1-theta0)
return EllipseDeriv(rx, ry, phi, sweep, theta).Normal()
}
return math32.Vector2{}
}
// Direction returns the direction of the path at the given
// segment and t in [0.0,1.0] along that path.
// The direction is a vector of unit length.
func (p Path) Direction(seg int, t float32) math32.Vector2 {
if len(p) <= 4 {
return math32.Vector2{}
}
// segments are the commands, including each MoveTo, and the direction
// is found in the subpath that has the segment.
curSeg := 0
iStart, iSeg := 0, -1
for i := 0; i < len(p); {
cmd := p[i]
if cmd == MoveTo && 0 < i {
if 0 <= iSeg {
return DirectionIndex(p[iStart:i], iSeg-iStart, t)
}
iStart = i
}
if seg == curSeg {
iSeg = i
}
curSeg++
i += CmdLen(cmd)
}
if 0 <= iSeg {
return DirectionIndex(p[iStart:], iSeg-iStart, t)
}
return math32.Vector2{} // if segment doesn't exist
}
// CoordDirections returns the direction of the segment start/end points.
// It will return the average direction at the intersection of two
// end points, and for an open path it will simply return the direction
// of the start and end points of the path.
func (p Path) CoordDirections() []math32.Vector2 {
if len(p) <= 4 {
return []math32.Vector2{{}}
}
last := len(p)
if p[last-1] == Close && EqualPoint(math32.Vec2(p[last-CmdLen(Close)-3], p[last-CmdLen(Close)-2]), math32.Vec2(p[last-3], p[last-2])) {
// point-closed
last -= CmdLen(Close)
}
dirs := []math32.Vector2{}
var closed bool
var dirPrev math32.Vector2
for i := 4; i < last; {
cmd := p[i]
dir := DirectionIndex(p, i, 0.0)
if i == 0 {
dirs = append(dirs, dir)
} else {
dirs = append(dirs, dirPrev.Add(dir).Normal())
}
dirPrev = DirectionIndex(p, i, 1.0)
closed = cmd == Close
i += CmdLen(cmd)
}
if closed {
dirs[0] = dirs[0].Add(dirPrev).Normal()
dirs = append(dirs, dirs[0])
} else {
dirs = append(dirs, dirPrev)
}
return dirs
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This is adapted from https://github.com/tdewolff/canvas
// Copyright (c) 2015 Taco de Wolff, under an MIT License.
package stroke
import (
"cogentcore.org/core/paint/ppath"
"cogentcore.org/core/paint/ppath/intersect"
)
// Dash returns a new path that consists of dashes.
// The elements in d specify the width of the dashes and gaps.
// It will alternate between dashes and gaps when picking widths.
// If d is an array of odd length, it is equivalent of passing d
// twice in sequence. The offset specifies the offset used into d
// (or negative offset into the path).
// Dash will be applied to each subpath independently.
func Dash(p ppath.Path, offset float32, d ...float32) ppath.Path {
offset, d = dashCanonical(offset, d)
if len(d) == 0 {
return p
} else if len(d) == 1 && d[0] == 0.0 {
return ppath.Path{}
}
if len(d)%2 == 1 {
// if d is uneven length, dash and space lengths alternate. Duplicate d so that uneven indices are always spaces
d = append(d, d...)
}
i0, pos0 := dashStart(offset, d)
q := ppath.Path{}
for _, ps := range p.Split() {
i := i0
pos := pos0
t := []float32{}
length := intersect.Length(ps)
for pos+d[i]+ppath.Epsilon < length {
pos += d[i]
if 0.0 < pos {
t = append(t, pos)
}
i++
if i == len(d) {
i = 0
}
}
j0 := 0
endsInDash := i%2 == 0
if len(t)%2 == 1 && endsInDash || len(t)%2 == 0 && !endsInDash {
j0 = 1
}
qd := ppath.Path{}
pd := intersect.SplitAt(ps, t...)
for j := j0; j < len(pd)-1; j += 2 {
qd = qd.Append(pd[j])
}
if endsInDash {
if ps.Closed() {
qd = pd[len(pd)-1].Join(qd)
} else {
qd = qd.Append(pd[len(pd)-1])
}
}
q = q.Append(qd)
}
return q
}
func dashStart(offset float32, d []float32) (int, float32) {
i0 := 0 // index in d
for d[i0] <= offset {
offset -= d[i0]
i0++
if i0 == len(d) {
i0 = 0
}
}
pos0 := -offset // negative if offset is halfway into dash
if offset < 0.0 {
dTotal := float32(0.0)
for _, dd := range d {
dTotal += dd
}
pos0 = -(dTotal + offset) // handle negative offsets
}
return i0, pos0
}
// dashCanonical returns an optimized dash array.
func dashCanonical(offset float32, d []float32) (float32, []float32) {
if len(d) == 0 {
return 0.0, []float32{}
}
// remove zeros except first and last
for i := 1; i < len(d)-1; i++ {
if ppath.Equal(d[i], 0.0) {
d[i-1] += d[i+1]
d = append(d[:i], d[i+2:]...)
i--
}
}
// remove first zero, collapse with second and last
if ppath.Equal(d[0], 0.0) {
if len(d) < 3 {
return 0.0, []float32{0.0}
}
offset -= d[1]
d[len(d)-1] += d[1]
d = d[2:]
}
// remove last zero, collapse with fist and second to last
if ppath.Equal(d[len(d)-1], 0.0) {
if len(d) < 3 {
return 0.0, []float32{}
}
offset += d[len(d)-2]
d[0] += d[len(d)-2]
d = d[:len(d)-2]
}
// if there are zeros or negatives, don't draw any dashes
for i := 0; i < len(d); i++ {
if d[i] < 0.0 || ppath.Equal(d[i], 0.0) {
return 0.0, []float32{0.0}
}
}
// remove repeated patterns
REPEAT:
for len(d)%2 == 0 {
mid := len(d) / 2
for i := range mid {
if !ppath.Equal(d[i], d[mid+i]) {
break REPEAT
}
}
d = d[:mid]
}
return offset, d
}
func checkDash(p ppath.Path, offset float32, d []float32) ([]float32, bool) {
offset, d = dashCanonical(offset, d)
if len(d) == 0 {
return d, true // stroke without dashes
} else if len(d) == 1 && d[0] == 0.0 {
return d[:0], false // no dashes, no stroke
}
length := intersect.Length(p)
i, pos := dashStart(offset, d)
if length <= d[i]-pos {
if i%2 == 0 {
return d[:0], true // first dash covers whole path, stroke without dashes
}
return d[:0], false // first space covers whole path, no stroke
}
return d, true
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This is adapted from https://github.com/tdewolff/canvas
// Copyright (c) 2015 Taco de Wolff, under an MIT License.
// Package stroke provides the stroking of paths, with caps and joins, and
// their dashing and offsetting.
package stroke
//go:generate core generate
import (
"cogentcore.org/core/math32"
"cogentcore.org/core/paint/ppath"
"cogentcore.org/core/paint/ppath/intersect"
)
// ellipseNormal returns the normal to the right at angle theta of the ellipse, given rotation phi.
func ellipseNormal(rx, ry, phi float32, sweep ppath.ArcSweep, theta, d float32) math32.Vector2 {
return ppath.EllipseDeriv(rx, ry, phi, sweep, theta).Rot90CW().Normal().MulScalar(d)
}
// FastStroke skips "settling" the resulting paths of [Offset] and [Stroke],
// which ensures a well-formed path without overlaps or holes. Settling fixes
// overlapping strokes and the inner bends of corners. Inner bends are already
// fixed for two line segments, but otherwise leave a hole. Overlapping
// strokes may not be a problem when they are drawn with the NonZero fill
// rule. Strokes that are much wider than the path itself may be drawn wrong
// with this, but it can be much faster for most (simple) paths.
var FastStroke = false
// NOTE: implementation inspired from github.com/golang/freetype/raster/stroke.go
// Stroke converts a path into a stroke of width w and returns a new path.
// It uses cr to cap the start and end of the path, and jr to join all path elements.
// If the path closes itself, it will use a join between the start and end instead
// of capping them. The tolerance is the maximum deviation from the original path
// when flattening Béziers and optimizing the stroke.
func Stroke(p ppath.Path, w float32, cr Capper, jr Joiner, tolerance float32) ppath.Path {
if cr == nil {
cr = ButtCap
}
if jr == nil {
jr = MiterJoin
}
q := ppath.Path{}
halfWidth := math32.Abs(w) / 2.0
for _, pi := range p.Split() {
rhs, lhs := offset(pi, halfWidth, cr, jr, true, tolerance)
if rhs != nil {
q = q.Append(rhs).Append(lhs.Reverse())
}
}
if !FastStroke {
// fix overlapping and spilled parts
q = intersect.Settle(q, ppath.Positive)
}
return q
}
func CapFromStyle(st ppath.Caps) Capper {
switch st {
case ppath.CapButt:
return ButtCap
case ppath.CapRound:
return RoundCap
case ppath.CapSquare:
return SquareCap
}
return ButtCap
}
func JoinFromStyle(st ppath.Joins) Joiner {
switch st {
case ppath.JoinMiter:
return MiterJoin
case ppath.JoinMiterClip:
return MiterClipJoin
case ppath.JoinRound:
return RoundJoin
case ppath.JoinBevel:
return BevelJoin
case ppath.JoinArcs:
return ArcsJoin
case ppath.JoinArcsClip:
return ArcsClipJoin
}
return MiterJoin
}
// Capper implements Cap, with rhs the path to append to,
// halfWidth the half width of the stroke, pivot the pivot point around
// which to construct a cap, and n0 the normal at the start of the path.
// The length of n0 is equal to the halfWidth.
type Capper interface {
Cap(*ppath.Path, float32, math32.Vector2, math32.Vector2)
}
// RoundCap caps the start or end of a path by a round cap.
var RoundCap Capper = RoundCapper{}
// RoundCapper is a round capper.
type RoundCapper struct{}
// Cap adds a cap to path p of width 2*halfWidth,
// at a pivot point and initial normal direction of n0.
func (RoundCapper) Cap(p *ppath.Path, halfWidth float32, pivot, n0 math32.Vector2) {
end := pivot.Sub(n0)
p.ArcTo(halfWidth, halfWidth, 0, ppath.SmallArc, ppath.Clockwise, end.X, end.Y)
}
func (RoundCapper) String() string {
return "Round"
}
// ButtCap caps the start or end of a path by a butt cap.
var ButtCap Capper = ButtCapper{}
// ButtCapper is a butt capper.
type ButtCapper struct{}
// Cap adds a cap to path p of width 2*halfWidth,
// at a pivot point and initial normal direction of n0.
func (ButtCapper) Cap(p *ppath.Path, halfWidth float32, pivot, n0 math32.Vector2) {
end := pivot.Sub(n0)
p.LineTo(end.X, end.Y)
}
func (ButtCapper) String() string {
return "Butt"
}
// SquareCap caps the start or end of a path by a square cap.
var SquareCap Capper = SquareCapper{}
// SquareCapper is a square capper.
type SquareCapper struct{}
// Cap adds a cap to path p of width 2*halfWidth,
// at a pivot point and initial normal direction of n0.
func (SquareCapper) Cap(p *ppath.Path, halfWidth float32, pivot, n0 math32.Vector2) {
e := n0.Rot90CCW()
corner1 := pivot.Add(e).Add(n0)
corner2 := pivot.Add(e).Sub(n0)
end := pivot.Sub(n0)
p.LineTo(corner1.X, corner1.Y)
p.LineTo(corner2.X, corner2.Y)
p.LineTo(end.X, end.Y)
}
func (SquareCapper) String() string {
return "Square"
}
////////
// Joiner implements Join, with rhs the right path and lhs the left path
// to append to, pivot the intersection of both path elements, n0 and n1
// the normals at the start and end of the path respectively.
// The length of n0 and n1 are equal to the halfWidth.
type Joiner interface {
Join(*ppath.Path, *ppath.Path, float32, math32.Vector2, math32.Vector2, math32.Vector2, float32, float32)
}
// BevelJoin connects two path elements by a linear join.
var BevelJoin Joiner = BevelJoiner{}
// BevelJoiner is a bevel joiner.
type BevelJoiner struct{}
// Join adds a join to a right-hand-side and left-hand-side path,
// of width 2*halfWidth, around a pivot point with starting and
// ending normals of n0 and n1, and radius of curvatures of the
// previous and next segments.
func (BevelJoiner) Join(rhs, lhs *ppath.Path, halfWidth float32, pivot, n0, n1 math32.Vector2, r0, r1 float32) {
rEnd := pivot.Add(n1)
lEnd := pivot.Sub(n1)
rhs.LineTo(rEnd.X, rEnd.Y)
lhs.LineTo(lEnd.X, lEnd.Y)
}
func (BevelJoiner) String() string {
return "Bevel"
}
// RoundJoin connects two path elements by a round join.
var RoundJoin Joiner = RoundJoiner{}
// RoundJoiner is a round joiner.
type RoundJoiner struct{}
func (RoundJoiner) Join(rhs, lhs *ppath.Path, halfWidth float32, pivot, n0, n1 math32.Vector2, r0, r1 float32) {
rEnd := pivot.Add(n1)
lEnd := pivot.Sub(n1)
cw := 0.0 <= n0.Rot90CW().Dot(n1)
if cw { // bend to the right, ie. CW (or 180 degree turn)
rhs.LineTo(rEnd.X, rEnd.Y)
lhs.ArcTo(halfWidth, halfWidth, 0.0, ppath.SmallArc, ppath.CounterClockwise, lEnd.X, lEnd.Y)
} else { // bend to the left, ie. CCW
rhs.ArcTo(halfWidth, halfWidth, 0.0, ppath.SmallArc, ppath.Clockwise, rEnd.X, rEnd.Y)
lhs.LineTo(lEnd.X, lEnd.Y)
}
}
func (RoundJoiner) String() string {
return "Round"
}
// MiterJoin connects two path elements by extending the ends
// of the paths as lines until they meet.
// If this point is further than the limit, this will result in a bevel
// join (MiterJoin) or they will meet at the limit (MiterClipJoin).
var MiterJoin Joiner = MiterJoiner{BevelJoin, 4.0}
var MiterClipJoin Joiner = MiterJoiner{nil, 4.0} // TODO: should extend limit*halfwidth before bevel
// MiterJoiner is a miter joiner.
type MiterJoiner struct {
GapJoiner Joiner
Limit float32
}
func (j MiterJoiner) Join(rhs, lhs *ppath.Path, halfWidth float32, pivot, n0, n1 math32.Vector2, r0, r1 float32) {
if ppath.EqualPoint(n0, n1.Negate()) {
BevelJoin.Join(rhs, lhs, halfWidth, pivot, n0, n1, r0, r1)
return
}
cw := 0.0 <= n0.Rot90CW().Dot(n1)
hw := halfWidth
if cw {
hw = -hw // used to calculate |R|, when running CW then n0 and n1 point the other way, so the sign of r0 and r1 is negated
}
// note that cos(theta) below refers to sin(theta/2) in the documentation of stroke-miterlimit
// in https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-miterlimit
theta := ppath.AngleBetween(n0, n1) / 2.0 // half the angle between normals
d := hw / math32.Cos(theta) // half the miter length
limit := math32.Max(j.Limit, 1.001) // otherwise nearly linear joins will also get clipped
clip := !math32.IsNaN(limit) && limit*halfWidth < math32.Abs(d)
if clip && j.GapJoiner != nil {
j.GapJoiner.Join(rhs, lhs, halfWidth, pivot, n0, n1, r0, r1)
return
}
rEnd := pivot.Add(n1)
lEnd := pivot.Sub(n1)
mid := pivot.Add(n0.Add(n1).Normal().MulScalar(d))
if clip {
// miter-clip
t := math32.Abs(limit * halfWidth / d)
if cw { // bend to the right, ie. CW
mid0 := lhs.Pos().Lerp(mid, t)
mid1 := lEnd.Lerp(mid, t)
lhs.LineTo(mid0.X, mid0.Y)
lhs.LineTo(mid1.X, mid1.Y)
} else {
mid0 := rhs.Pos().Lerp(mid, t)
mid1 := rEnd.Lerp(mid, t)
rhs.LineTo(mid0.X, mid0.Y)
rhs.LineTo(mid1.X, mid1.Y)
}
} else {
if cw { // bend to the right, ie. CW
lhs.LineTo(mid.X, mid.Y)
} else {
rhs.LineTo(mid.X, mid.Y)
}
}
rhs.LineTo(rEnd.X, rEnd.Y)
lhs.LineTo(lEnd.X, lEnd.Y)
}
func (j MiterJoiner) String() string {
if j.GapJoiner == nil {
return "MiterClip"
}
return "Miter"
}
// ArcsJoin connects two path elements by extending the ends
// of the paths as circle arcs until they meet.
// If this point is further than the limit, this will result
// in a bevel join (ArcsJoin) or they will meet at the limit (ArcsClipJoin).
var ArcsJoin Joiner = ArcsJoiner{BevelJoin, 4.0}
var ArcsClipJoin Joiner = ArcsJoiner{nil, 4.0}
// ArcsJoiner is an arcs joiner.
type ArcsJoiner struct {
GapJoiner Joiner
Limit float32
}
func closestArcIntersection(c math32.Vector2, cw bool, pivot, i0, i1 math32.Vector2) math32.Vector2 {
thetaPivot := ppath.Angle(pivot.Sub(c))
dtheta0 := ppath.Angle(i0.Sub(c)) - thetaPivot
dtheta1 := ppath.Angle(i1.Sub(c)) - thetaPivot
if cw { // arc runs clockwise, so look the other way around
dtheta0 = -dtheta0
dtheta1 = -dtheta1
}
if ppath.AngleNorm(dtheta1) < ppath.AngleNorm(dtheta0) {
return i1
}
return i0
}
func (j ArcsJoiner) Join(rhs, lhs *ppath.Path, halfWidth float32, pivot, n0, n1 math32.Vector2, r0, r1 float32) {
if ppath.EqualPoint(n0, n1.Negate()) {
BevelJoin.Join(rhs, lhs, halfWidth, pivot, n0, n1, r0, r1)
return
} else if math32.IsNaN(r0) && math32.IsNaN(r1) {
MiterJoiner(j).Join(rhs, lhs, halfWidth, pivot, n0, n1, r0, r1)
return
}
limit := math32.Max(j.Limit, 1.001) // 1.001 so that nearly linear joins will not get clipped
cw := 0.0 <= n0.Rot90CW().Dot(n1)
hw := halfWidth
if cw {
hw = -hw // used to calculate |R|, when running CW then n0 and n1 point the other way, so the sign of r0 and r1 is negated
}
// r is the radius of the original curve, R the radius of the stroke curve, c are the centers of the circles
c0 := pivot.Add(n0.Normal().MulScalar(-r0))
c1 := pivot.Add(n1.Normal().MulScalar(-r1))
R0, R1 := math32.Abs(r0+hw), math32.Abs(r1+hw)
// TODO: can simplify if intersection returns angles too?
var i0, i1 math32.Vector2
var ok bool
if math32.IsNaN(r0) {
line := pivot.Add(n0)
if cw {
line = pivot.Sub(n0)
}
i0, i1, ok = intersect.IntersectionRayCircle(line, line.Add(n0.Rot90CCW()), c1, R1)
} else if math32.IsNaN(r1) {
line := pivot.Add(n1)
if cw {
line = pivot.Sub(n1)
}
i0, i1, ok = intersect.IntersectionRayCircle(line, line.Add(n1.Rot90CCW()), c0, R0)
} else {
i0, i1, ok = intersect.IntersectionCircleCircle(c0, R0, c1, R1)
}
if !ok {
// no intersection
BevelJoin.Join(rhs, lhs, halfWidth, pivot, n0, n1, r0, r1)
return
}
// find the closest intersection when following the arc (using either arc r0 or r1 with center c0 or c1 respectively)
var mid math32.Vector2
if !math32.IsNaN(r0) {
mid = closestArcIntersection(c0, r0 < 0.0, pivot, i0, i1)
} else {
mid = closestArcIntersection(c1, 0.0 <= r1, pivot, i0, i1)
}
// check arc limit
d := mid.Sub(pivot).Length()
clip := !math32.IsNaN(limit) && limit*halfWidth < d
if clip && j.GapJoiner != nil {
j.GapJoiner.Join(rhs, lhs, halfWidth, pivot, n0, n1, r0, r1)
return
}
mid2 := mid
if clip {
// arcs-clip
start, end := pivot.Add(n0), pivot.Add(n1)
if cw {
start, end = pivot.Sub(n0), pivot.Sub(n1)
}
var clipMid, clipNormal math32.Vector2
if !math32.IsNaN(r0) && !math32.IsNaN(r1) && (0.0 < r0) == (0.0 < r1) {
// circle have opposite direction/sweep
// NOTE: this may cause the bevel to be imperfectly oriented
clipMid = mid.Sub(pivot).Normal().MulScalar(limit * halfWidth)
clipNormal = clipMid.Rot90CCW()
} else {
// circle in between both stroke edges
rMid := (r0 - r1) / 2.0
if math32.IsNaN(r0) {
rMid = -(r1 + hw) * 2.0
} else if math32.IsNaN(r1) {
rMid = (r0 + hw) * 2.0
}
sweep := 0.0 < rMid
RMid := math32.Abs(rMid)
cx, cy, a0, _ := ppath.EllipseToCenter(pivot.X, pivot.Y, RMid, RMid, 0.0, ppath.SmallArc, ppath.ArcSweep(sweep), mid.X, mid.Y)
cMid := math32.Vec2(cx, cy)
dtheta := limit * halfWidth / rMid
clipMid = ppath.EllipsePos(RMid, RMid, 0.0, cMid.X, cMid.Y, a0+dtheta)
clipNormal = ellipseNormal(RMid, RMid, 0.0, ppath.ArcSweep(sweep), a0+dtheta, 1.0)
}
if math32.IsNaN(r1) {
i0, ok = intersect.IntersectionRayLine(clipMid, clipMid.Add(clipNormal), mid, end)
if !ok {
// not sure when this occurs
BevelJoin.Join(rhs, lhs, halfWidth, pivot, n0, n1, r0, r1)
return
}
mid2 = i0
} else {
i0, i1, ok = intersect.IntersectionRayCircle(clipMid, clipMid.Add(clipNormal), c1, R1)
if !ok {
// not sure when this occurs
BevelJoin.Join(rhs, lhs, halfWidth, pivot, n0, n1, r0, r1)
return
}
mid2 = closestArcIntersection(c1, 0.0 <= r1, pivot, i0, i1)
}
if math32.IsNaN(r0) {
i0, ok = intersect.IntersectionRayLine(clipMid, clipMid.Add(clipNormal), start, mid)
if !ok {
// not sure when this occurs
BevelJoin.Join(rhs, lhs, halfWidth, pivot, n0, n1, r0, r1)
return
}
mid = i0
} else {
i0, i1, ok = intersect.IntersectionRayCircle(clipMid, clipMid.Add(clipNormal), c0, R0)
if !ok {
// not sure when this occurs
BevelJoin.Join(rhs, lhs, halfWidth, pivot, n0, n1, r0, r1)
return
}
mid = closestArcIntersection(c0, r0 < 0.0, pivot, i0, i1)
}
}
rEnd := pivot.Add(n1)
lEnd := pivot.Sub(n1)
if cw { // bend to the right, ie. CW
rhs.LineTo(rEnd.X, rEnd.Y)
if math32.IsNaN(r0) {
lhs.LineTo(mid.X, mid.Y)
} else {
lhs.ArcTo(R0, R0, 0.0, ppath.SmallArc, 0.0 < r0, mid.X, mid.Y)
}
if clip {
lhs.LineTo(mid2.X, mid2.Y)
}
if math32.IsNaN(r1) {
lhs.LineTo(lEnd.X, lEnd.Y)
} else {
lhs.ArcTo(R1, R1, 0.0, ppath.SmallArc, 0.0 < r1, lEnd.X, lEnd.Y)
}
} else { // bend to the left, ie. CCW
if math32.IsNaN(r0) {
rhs.LineTo(mid.X, mid.Y)
} else {
rhs.ArcTo(R0, R0, 0.0, ppath.SmallArc, 0.0 < r0, mid.X, mid.Y)
}
if clip {
rhs.LineTo(mid2.X, mid2.Y)
}
if math32.IsNaN(r1) {
rhs.LineTo(rEnd.X, rEnd.Y)
} else {
rhs.ArcTo(R1, R1, 0.0, ppath.SmallArc, 0.0 < r1, rEnd.X, rEnd.Y)
}
lhs.LineTo(lEnd.X, lEnd.Y)
}
}
func (j ArcsJoiner) String() string {
if j.GapJoiner == nil {
return "ArcsClip"
}
return "Arcs"
}
// optimizeClose removes a superfluous first line segment in-place
// of a subpath. If both the first and last segment are line segments
// and are colinear, move the start of the path forward one segment
func optimizeClose(p *ppath.Path) {
if len(*p) == 0 || (*p)[len(*p)-1] != ppath.Close {
return
}
// find last MoveTo
end := math32.Vector2{}
iMoveTo := len(*p)
for 0 < iMoveTo {
cmd := (*p)[iMoveTo-1]
iMoveTo -= ppath.CmdLen(cmd)
if cmd == ppath.MoveTo {
end = math32.Vec2((*p)[iMoveTo+1], (*p)[iMoveTo+2])
break
}
}
if (*p)[iMoveTo] == ppath.MoveTo && (*p)[iMoveTo+ppath.CmdLen(ppath.MoveTo)] == ppath.LineTo && iMoveTo+ppath.CmdLen(ppath.MoveTo)+ppath.CmdLen(ppath.LineTo) < len(*p)-ppath.CmdLen(ppath.Close) {
// replace Close + MoveTo + LineTo by Close + MoveTo if equidirectional
// move Close and MoveTo forward along the path
start := math32.Vec2((*p)[len(*p)-ppath.CmdLen(ppath.Close)-3], (*p)[len(*p)-ppath.CmdLen(ppath.Close)-2])
nextEnd := math32.Vec2((*p)[iMoveTo+ppath.CmdLen(ppath.MoveTo)+ppath.CmdLen(ppath.LineTo)-3], (*p)[iMoveTo+ppath.CmdLen(ppath.MoveTo)+ppath.CmdLen(ppath.LineTo)-2])
if ppath.Equal(ppath.AngleBetween(end.Sub(start), nextEnd.Sub(end)), 0.0) {
// update Close
(*p)[len(*p)-3] = nextEnd.X
(*p)[len(*p)-2] = nextEnd.Y
// update MoveTo
(*p)[iMoveTo+1] = nextEnd.X
(*p)[iMoveTo+2] = nextEnd.Y
// remove LineTo
*p = append((*p)[:iMoveTo+ppath.CmdLen(ppath.MoveTo)], (*p)[iMoveTo+ppath.CmdLen(ppath.MoveTo)+ppath.CmdLen(ppath.LineTo):]...)
}
}
}
// optimizeInnerBend removes the join segment at index i of the inner bend
// of a path (connecting both edges), when the edges intersect, by moving
// the end of the previous segment to the intersection, and returns the
// resulting path.
func optimizeInnerBend(p ppath.Path, i int) ppath.Path {
// i is the index of the line segment in the inner bend connecting both edges
ai := i - ppath.CmdLen(p[i-1])
if ai == 0 {
return p
}
if i >= len(p) {
return p
}
bi := i + ppath.CmdLen(p[i])
a0 := math32.Vec2(p[ai-3], p[ai-2])
b0 := math32.Vec2(p[bi-3], p[bi-2])
if bi == len(p) {
// inner bend is at the path's start
bi = 4
}
// TODO: implement other segment combinations
zs_ := [2]intersect.Intersection{}
zs := zs_[:]
if (p[ai] == ppath.LineTo || p[ai] == ppath.Close) && (p[bi] == ppath.LineTo || p[bi] == ppath.Close) {
zs = intersect.IntersectionSegment(zs[:0], a0, p[ai:ai+4], b0, p[bi:bi+4])
// TODO: check conditions for pathological cases
if len(zs) == 1 && zs[0].T[0] != 0.0 && zs[0].T[0] != 1.0 && zs[0].T[1] != 0.0 && zs[0].T[1] != 1.0 {
p[ai+1] = zs[0].X
p[ai+2] = zs[0].Y
if bi == 4 {
// inner bend is at the path's start
if p[i] == ppath.Close {
if p[ai] == ppath.LineTo {
p[ai] = ppath.Close
p[ai+3] = ppath.Close
} else {
p = append(p, ppath.Close, zs[0].X, zs[0].Y, ppath.Close)
}
}
p = p[:i]
p[1] = zs[0].X
p[2] = zs[0].Y
} else {
p = append(p[:i], p[bi:]...)
}
}
}
return p
}
type pathStrokeState struct {
cmd float32
p0, p1 math32.Vector2 // position of start and end
n0, n1 math32.Vector2 // normal of start and end (points right when walking the path)
r0, r1 float32 // radius of start and end
cp1, cp2 math32.Vector2 // Béziers
rx, ry, rot, theta0, theta1 float32 // arcs
large ppath.ArcSize // arcs
sweep ppath.ArcSweep
}
// offset returns the rhs and lhs paths from offsetting a path
// (must not have subpaths). It closes rhs and lhs when p is closed as well.
func offset(p ppath.Path, halfWidth float32, cr Capper, jr Joiner, strokeOpen bool, tolerance float32) (ppath.Path, ppath.Path) {
// only non-empty paths are evaluated
closed := false
states := []pathStrokeState{}
var start, end math32.Vector2
for i := 0; i < len(p); {
cmd := p[i]
switch cmd {
case ppath.MoveTo:
end = math32.Vec2(p[i+1], p[i+2])
case ppath.LineTo:
end = math32.Vec2(p[i+1], p[i+2])
n := end.Sub(start).Rot90CW().Normal().MulScalar(halfWidth)
states = append(states, pathStrokeState{
cmd: ppath.LineTo,
p0: start,
p1: end,
n0: n,
n1: n,
r0: math32.NaN(),
r1: math32.NaN(),
})
case ppath.QuadTo, ppath.CubeTo:
var cp1, cp2 math32.Vector2
if cmd == ppath.QuadTo {
cp := math32.Vec2(p[i+1], p[i+2])
end = math32.Vec2(p[i+3], p[i+4])
cp1, cp2 = ppath.QuadraticToCubicBezier(start, cp, end)
} else {
cp1 = math32.Vec2(p[i+1], p[i+2])
cp2 = math32.Vec2(p[i+3], p[i+4])
end = math32.Vec2(p[i+5], p[i+6])
}
n0 := intersect.CubicBezierNormal(start, cp1, cp2, end, 0.0, halfWidth)
n1 := intersect.CubicBezierNormal(start, cp1, cp2, end, 1.0, halfWidth)
r0 := intersect.CubicBezierCurvatureRadius(start, cp1, cp2, end, 0.0)
r1 := intersect.CubicBezierCurvatureRadius(start, cp1, cp2, end, 1.0)
states = append(states, pathStrokeState{
cmd: ppath.CubeTo,
p0: start,
p1: end,
n0: n0,
n1: n1,
r0: r0,
r1: r1,
cp1: cp1,
cp2: cp2,
})
case ppath.ArcTo:
rx, ry, phi := p[i+1], p[i+2], p[i+3]
large, sweep := ppath.ToArcFlags(p[i+4])
end = math32.Vec2(p[i+5], p[i+6])
_, _, theta0, theta1 := ppath.EllipseToCenter(start.X, start.Y, rx, ry, phi, large, sweep, end.X, end.Y)
n0 := ellipseNormal(rx, ry, phi, sweep, theta0, halfWidth)
n1 := ellipseNormal(rx, ry, phi, sweep, theta1, halfWidth)
r0 := intersect.EllipseCurvatureRadius(rx, ry, sweep, theta0)
r1 := intersect.EllipseCurvatureRadius(rx, ry, sweep, theta1)
states = append(states, pathStrokeState{
cmd: ppath.ArcTo,
p0: start,
p1: end,
n0: n0,
n1: n1,
r0: r0,
r1: r1,
rx: rx,
ry: ry,
rot: phi * 180.0 / math32.Pi,
theta0: theta0,
theta1: theta1,
large: large,
sweep: sweep,
})
case ppath.Close:
end = math32.Vec2(p[i+1], p[i+2])
if !ppath.Equal(start.X, end.X) || !ppath.Equal(start.Y, end.Y) {
n := end.Sub(start).Rot90CW().Normal().MulScalar(halfWidth)
states = append(states, pathStrokeState{
cmd: ppath.LineTo,
p0: start,
p1: end,
n0: n,
n1: n,
r0: math32.NaN(),
r1: math32.NaN(),
})
}
closed = true
}
start = end
i += ppath.CmdLen(cmd)
}
if len(states) == 0 {
return nil, nil
}
rhs, lhs := ppath.Path{}, ppath.Path{}
rStart := states[0].p0.Add(states[0].n0)
lStart := states[0].p0.Sub(states[0].n0)
rhs.MoveTo(rStart.X, rStart.Y)
lhs.MoveTo(lStart.X, lStart.Y)
rhsJoinIndex, lhsJoinIndex := -1, -1
for i, cur := range states {
switch cur.cmd {
case ppath.LineTo:
rEnd := cur.p1.Add(cur.n1)
lEnd := cur.p1.Sub(cur.n1)
rhs.LineTo(rEnd.X, rEnd.Y)
lhs.LineTo(lEnd.X, lEnd.Y)
case ppath.CubeTo:
rhs = rhs.Join(intersect.FlattenCubicBezier(cur.p0, cur.cp1, cur.cp2, cur.p1, halfWidth, tolerance))
lhs = lhs.Join(intersect.FlattenCubicBezier(cur.p0, cur.cp1, cur.cp2, cur.p1, -halfWidth, tolerance))
case ppath.ArcTo:
rStart := cur.p0.Add(cur.n0)
lStart := cur.p0.Sub(cur.n0)
rEnd := cur.p1.Add(cur.n1)
lEnd := cur.p1.Sub(cur.n1)
dr := halfWidth
if !cur.sweep { // bend to the right, ie. CW
dr = -dr
}
rLambda := ppath.EllipseRadiiCorrection(rStart, cur.rx+dr, cur.ry+dr, cur.rot*math32.Pi/180.0, rEnd)
lLambda := ppath.EllipseRadiiCorrection(lStart, cur.rx-dr, cur.ry-dr, cur.rot*math32.Pi/180.0, lEnd)
if rLambda <= 1.0 && lLambda <= 1.0 {
rLambda, lLambda = 1.0, 1.0
}
rhs.ArcTo(rLambda*(cur.rx+dr), rLambda*(cur.ry+dr), cur.rot, ppath.ArcSize(cur.large), ppath.ArcSweep(cur.sweep), rEnd.X, rEnd.Y)
lhs.ArcTo(lLambda*(cur.rx-dr), lLambda*(cur.ry-dr), cur.rot, ppath.ArcSize(cur.large), ppath.ArcSweep(cur.sweep), lEnd.X, lEnd.Y)
}
// optimize inner bend
if 0 < i {
prev := states[i-1]
cw := 0.0 <= prev.n1.Rot90CW().Dot(cur.n0)
if cw && rhsJoinIndex != -1 {
rhs = optimizeInnerBend(rhs, rhsJoinIndex)
} else if !cw && lhsJoinIndex != -1 {
lhs = optimizeInnerBend(lhs, lhsJoinIndex)
}
}
rhsJoinIndex = -1
lhsJoinIndex = -1
// join the cur and next path segments
if i+1 < len(states) || closed {
next := states[0]
if i+1 < len(states) {
next = states[i+1]
}
if !ppath.EqualPoint(cur.n1, next.n0) {
rhsJoinIndex = len(rhs)
lhsJoinIndex = len(lhs)
jr.Join(&rhs, &lhs, halfWidth, cur.p1, cur.n1, next.n0, cur.r1, next.r0)
}
}
}
if closed {
rhs.Close()
lhs.Close()
// optimize inner bend
if 1 < len(states) {
cw := 0.0 <= states[len(states)-1].n1.Rot90CW().Dot(states[0].n0)
if cw && rhsJoinIndex != -1 {
rhs = optimizeInnerBend(rhs, rhsJoinIndex)
} else if !cw && lhsJoinIndex != -1 {
lhs = optimizeInnerBend(lhs, lhsJoinIndex)
}
}
optimizeClose(&rhs)
optimizeClose(&lhs)
} else if strokeOpen {
lhs = lhs.Reverse()
cr.Cap(&rhs, halfWidth, states[len(states)-1].p1, states[len(states)-1].n1)
rhs = rhs.Join(lhs)
cr.Cap(&rhs, halfWidth, states[0].p0, states[0].n0.Negate())
lhs = nil
rhs.Close()
optimizeClose(&rhs)
}
return rhs, lhs
}
// Offset offsets the path by w and returns a new path.
// A positive w will offset the path to the right-hand side, that is,
// it expands CCW oriented contours and contracts CW oriented contours.
// If you don't know the orientation you can use `Path.CCW` to find out,
// but if there may be self-intersection you should use `Path.Settle`
// to remove them and orient all filling contours CCW.
// The tolerance is the maximum deviation from the actual offset when
// flattening Béziers and optimizing the path.
func Offset(p ppath.Path, w float32, tolerance float32) ppath.Path {
if ppath.Equal(w, 0.0) {
return p
}
q := ppath.Path{}
if !FastStroke {
// make sure all filling paths are CCW
p = intersect.Settle(p, ppath.NonZero)
}
for _, pi := range p.Split() {
rhs, _ := offset(pi, w, ButtCap, RoundJoin, false, tolerance)
if rhs != nil {
q = q.Append(rhs)
}
}
if !FastStroke {
// fix overlapping and spilled parts
q = intersect.Settle(q, ppath.Positive)
}
return q
}
// Markers returns an array of start, mid and end marker paths along
// the path at the coordinates between commands.
// Align will align the markers with the path direction so that
// the markers orient towards the path's left.
func Markers(p ppath.Path, first, mid, last ppath.Path, align bool) []ppath.Path {
markers := []ppath.Path{}
coordPos := p.Coords()
coordDir := p.CoordDirections()
for i := range coordPos {
q := mid
if i == 0 {
q = first
} else if i == len(coordPos)-1 {
q = last
}
if q != nil {
pos, dir := coordPos[i], coordDir[i]
m := math32.Identity2().Translate(pos.X, pos.Y)
if align {
m = m.Rotate(ppath.Angle(dir))
}
markers = append(markers, q.Clone().Transform(m))
}
}
return markers
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This is adapted from https://github.com/tdewolff/canvas
// Copyright (c) 2015 Taco de Wolff, under an MIT License.
package ppath
import (
"fmt"
"cogentcore.org/core/math32"
)
// Transform transforms the path by the given transformation matrix
// and returns a new path. It modifies the path in-place.
func (p Path) Transform(m math32.Matrix2) Path {
xscale, yscale := m.ExtractScale()
for i := 0; i < len(p); {
cmd := p[i]
switch cmd {
case MoveTo, LineTo, Close:
if i+2 >= len(p) {
fmt.Println("path length error:", len(p), i, p)
return p
}
end := m.MulPoint(math32.Vec2(p[i+1], p[i+2]))
p[i+1] = end.X
p[i+2] = end.Y
case QuadTo:
cp := m.MulPoint(math32.Vec2(p[i+1], p[i+2]))
end := m.MulPoint(math32.Vec2(p[i+3], p[i+4]))
p[i+1] = cp.X
p[i+2] = cp.Y
p[i+3] = end.X
p[i+4] = end.Y
case CubeTo:
cp1 := m.MulPoint(math32.Vec2(p[i+1], p[i+2]))
cp2 := m.MulPoint(math32.Vec2(p[i+3], p[i+4]))
end := m.MulPoint(math32.Vec2(p[i+5], p[i+6]))
p[i+1] = cp1.X
p[i+2] = cp1.Y
p[i+3] = cp2.X
p[i+4] = cp2.Y
p[i+5] = end.X
p[i+6] = end.Y
case ArcTo:
rx, ry, phi, large, sweep, end := p.ArcToPoints(i)
// For ellipses written as the conic section equation in matrix form, we have:
// [x, y] E [x; y] = 0, with E = [1/rx^2, 0; 0, 1/ry^2]
// For our transformed ellipse we have [x', y'] = T [x, y], with T the affine
// transformation matrix so that
// (T^-1 [x'; y'])^T E (T^-1 [x'; y'] = 0 => [x', y'] T^(-T) E T^(-1) [x'; y'] = 0
// We define Q = T^(-1,T) E T^(-1) the new ellipse equation which is typically rotated
// from the x-axis. That's why we find the eigenvalues and eigenvectors (the new
// direction and length of the major and minor axes).
T := m.Rotate(phi)
invT := T.Inverse()
Q := math32.Identity2().Scale(1.0/rx/rx, 1.0/ry/ry)
Q = invT.Transpose().Mul(Q).Mul(invT)
lambda1, lambda2, v1, v2 := Q.Eigen()
rx = 1 / math32.Sqrt(lambda1)
ry = 1 / math32.Sqrt(lambda2)
phi = Angle(v1)
if rx < ry {
rx, ry = ry, rx
phi = Angle(v2)
}
phi = AngleNorm(phi)
if math32.Pi <= phi { // phi is canonical within 0 <= phi < 180
phi -= math32.Pi
}
if xscale*yscale < 0.0 { // flip x or y axis needs flipping of the sweep
sweep = !sweep
}
end = m.MulPoint(end)
p[i+1] = rx
p[i+2] = ry
p[i+3] = phi
p[i+4] = fromArcFlags(ArcSize(large), ArcSweep(sweep))
p[i+5] = end.X
p[i+6] = end.Y
}
i += CmdLen(cmd)
}
return p
}
// Translate translates the path by (x,y) in place and returns it.
func (p Path) Translate(x, y float32) Path {
return p.Transform(math32.Identity2().Translate(x, y))
}
// Scale scales the path by (x,y) in place and returns it.
func (p Path) Scale(x, y float32) Path {
return p.Transform(math32.Identity2().Scale(x, y))
}
// ReplaceArcs replaces ArcTo commands by CubeTo commands and returns a new path.
func (p *Path) ReplaceArcs() Path {
return p.Replace(nil, nil, nil, ArcToCube)
}
// Replace replaces path segments by their respective functions,
// each returning the path that will replace the segment or nil
// if no replacement is to be performed. The line function will
// take the start and end points. The bezier function will take
// the start point, control point 1 and 2, and the end point
// (i.e. a cubic Bézier, quadratic Béziers will be implicitly
// converted to cubic ones). The arc function will take a start point,
// the major and minor radii, the radial rotaton counter clockwise,
// the large and sweep booleans, and the end point.
// The replacing path will replace the path segment without any checks,
// you need to make sure the be moved so that its start point connects
// with the last end point of the base path before the replacement.
// If the end point of the replacing path is different that the end point
// of what is replaced, the path that follows will be displaced.
func (p Path) Replace(
line func(math32.Vector2, math32.Vector2) Path,
quad func(math32.Vector2, math32.Vector2, math32.Vector2) Path,
cube func(math32.Vector2, math32.Vector2, math32.Vector2, math32.Vector2) Path,
arc func(math32.Vector2, float32, float32, float32, ArcSize, ArcSweep, math32.Vector2) Path,
) Path {
copied := false
var start, end, cp1, cp2 math32.Vector2
for i := 0; i < len(p); {
var q Path
cmd := p[i]
switch cmd {
case LineTo, Close:
if line != nil {
end = p.EndPoint(i)
q = line(start, end)
if cmd == Close {
q.Close()
}
}
case QuadTo:
if quad != nil {
cp1, end = p.QuadToPoints(i)
q = quad(start, cp1, end)
}
case CubeTo:
if cube != nil {
cp1, cp2, end = p.CubeToPoints(i)
q = cube(start, cp1, cp2, end)
}
case ArcTo:
if arc != nil {
var rx, ry, phi float32
var large ArcSize
var sweep ArcSweep
rx, ry, phi, large, sweep, end = p.ArcToPoints(i)
q = arc(start, rx, ry, phi, large, sweep, end)
}
}
if q != nil {
if !copied {
p = p.Clone()
copied = true
}
r := append(Path{MoveTo, end.X, end.Y, MoveTo}, p[i+CmdLen(cmd):]...)
p = p[: i : i+CmdLen(cmd)] // make sure not to overwrite the rest of the path
p = p.Join(q)
if cmd != Close {
p.LineTo(end.X, end.Y)
}
i = len(p)
p = p.Join(r) // join the rest of the base path
} else {
i += CmdLen(cmd)
}
start = math32.Vec2(p[i-3], p[i-2])
}
return p
}
// Split splits the path into its independent subpaths.
// The path is split before each MoveTo command.
func (p Path) Split() []Path {
if p == nil {
return nil
}
var i, j int
ps := []Path{}
for j < len(p) {
cmd := p[j]
if i < j && cmd == MoveTo {
ps = append(ps, p[i:j:j])
i = j
}
j += CmdLen(cmd)
}
if i+CmdLen(MoveTo) < j {
ps = append(ps, p[i:j:j])
}
return ps
}
// Reverse returns a new path that is the same path as p but in the reverse direction.
func (p Path) Reverse() Path {
if len(p) == 0 {
return p
}
end := math32.Vec2(p[len(p)-3], p[len(p)-2])
q := make(Path, 0, len(p))
q = append(q, MoveTo, end.X, end.Y, MoveTo)
closed := false
first, start := end, end
for i := len(p); 0 < i; {
cmd := p[i-1]
i -= CmdLen(cmd)
end = math32.Vector2{}
if 0 < i {
end = math32.Vec2(p[i-3], p[i-2])
}
switch cmd {
case MoveTo:
if closed {
q = append(q, Close, first.X, first.Y, Close)
closed = false
}
if i != 0 {
q = append(q, MoveTo, end.X, end.Y, MoveTo)
first = end
}
case Close:
if !EqualPoint(start, end) {
q = append(q, LineTo, end.X, end.Y, LineTo)
}
closed = true
case LineTo:
if closed && (i == 0 || p[i-1] == MoveTo) {
q = append(q, Close, first.X, first.Y, Close)
closed = false
} else {
q = append(q, LineTo, end.X, end.Y, LineTo)
}
case QuadTo:
cx, cy := p[i+1], p[i+2]
q = append(q, QuadTo, cx, cy, end.X, end.Y, QuadTo)
case CubeTo:
cx1, cy1 := p[i+1], p[i+2]
cx2, cy2 := p[i+3], p[i+4]
q = append(q, CubeTo, cx2, cy2, cx1, cy1, end.X, end.Y, CubeTo)
case ArcTo:
rx, ry, phi, large, sweep, _ := p.ArcToPoints(i)
q = append(q, ArcTo, rx, ry, phi, fromArcFlags(ArcSize(large), ArcSweep(!sweep)), end.X, end.Y, ArcTo)
}
start = end
}
if closed {
q = append(q, Close, first.X, first.Y, Close)
}
return q
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package render
import (
"image"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint/ppath"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/sides"
)
// Bounds represents an optimized rounded rectangle form of clipping,
// which is critical for GUI rendering.
type Bounds struct {
// Rect is a rectangular bounding box.
Rect math32.Box2
// Radius is the border radius for rounded rectangles, can be per corner
// or one value for all.
Radius sides.Floats
// Path is the computed clipping path for the Rect and Radius.
Path ppath.Path
}
func NewBounds(x, y, w, h float32, radius sides.Floats) *Bounds {
return &Bounds{Rect: math32.B2(x, y, x+w, y+h), Radius: radius}
}
func NewBoundsRect(rect image.Rectangle, radius sides.Floats) *Bounds {
sz := rect.Size()
return NewBounds(float32(rect.Min.X), float32(rect.Min.Y), float32(sz.X), float32(sz.Y), radius)
}
// Context contains all of the rendering constraints / filters / masks
// that are applied to elements being rendered.
// For SVG compliant rendering, we need a stack of these Context elements
// that apply to all elements in the group.
// Each level always represents the compounded effects of any parent groups,
// with the compounding being performed when a new Context is pushed on the stack.
// https://www.w3.org/TR/SVG2/render.html#Grouping
type Context struct {
// Style has the accumulated style values.
// Individual elements inherit from this style.
Style styles.Paint
// Transform is the transformation matrix for this stack level.
Transform math32.Matrix2
// Cumulative is the accumulated transformation matrix.
Cumulative math32.Matrix2
// Bounds is the rounded rectangle clip boundary.
// This is applied to the effective Path prior to adding to Render.
Bounds Bounds
// ClipPath is the current shape-based clipping path,
// in addition to the Bounds, which is applied to the effective Path
// prior to adding to Render.
ClipPath ppath.Path
// ClipMask, if not empty, clips the rendering within this context
// (the items between its [ContextPush] and [ContextPop]) to where
// these items render: by the alpha of their rendering. It is set
// for this context only (not inherited, as the rendering within
// this context is clipped as a whole), as for an SVG clipPath,
// whose shapes render as opaque fills. Its items are in the same
// (device) coordinates as the other items.
ClipMask Render
// Mask, if not empty, masks the rendering within this context by
// the rendering of these items: by its luminance times its alpha,
// as for an SVG mask. It is set for this context only, as is the
// [Context.ClipMask].
Mask Render
// Opacity, if > 0 and < 1, is the opacity of the rendering within
// this context as a whole (group opacity), which is not the same
// as that of each of its items when they overlap. It is set for
// this context only, as is the [Context.ClipMask].
Opacity float32
// Filter // todo add filtering effects here
}
// NewContext returns a new Context using given paint style, bounds, and
// parent Context. See [Context.Init] for details.
func NewContext(sty *styles.Paint, bounds *Bounds, parent *Context) *Context {
ctx := &Context{}
ctx.Init(sty, bounds, parent)
if sty == nil && parent != nil {
ctx.Style.UnitContext = parent.Style.UnitContext
}
return ctx
}
// Init initializes context based on given style, bounds and parent Context.
// If parent is present, then bounds can be nil, in which
// case it gets the bounds from the parent.
// All the values from the style are used to update the Context,
// accumulating anything from the parent.
func (ctx *Context) Init(sty *styles.Paint, bounds *Bounds, parent *Context) {
if sty != nil {
ctx.Style = *sty
} else {
ctx.Style.Defaults()
}
if parent == nil {
ctx.Transform = sty.Transform
ctx.Cumulative = sty.Transform
ctx.SetBounds(bounds)
ctx.ClipPath = sty.ClipPath
return
}
ctx.Transform = ctx.Style.Transform
ctx.Cumulative = parent.Cumulative.Mul(ctx.Style.Transform)
ctx.Style.InheritFields(&parent.Style)
if bounds == nil {
bounds = &parent.Bounds
}
ctx.SetBounds(bounds)
// todo: not clear if following are needed:
// ctx.Bounds.Path = ctx.Bounds.Path.And(parent.Bounds.Path) // intersect
// ctx.ClipPath = ctx.Style.ClipPath.And(parent.ClipPath)
}
// IsLayer returns whether the rendering within this context is
// composited as a whole (as a layer): if it has a [Context.ClipMask],
// a [Context.Mask], or an [Context.Opacity] < 1.
func (ctx *Context) IsLayer() bool {
return len(ctx.ClipMask) > 0 || len(ctx.Mask) > 0 || (ctx.Opacity > 0 && ctx.Opacity < 1)
}
// SetBounds sets the context bounds, and updates the Bounds.Path
func (ctx *Context) SetBounds(bounds *Bounds) {
ctx.Bounds = *bounds
// bsz := bounds.Rect.Size()
// ctx.Bounds.Path = *ppath.New().RoundedRectangleSides(bounds.Rect.Min.X, bounds.Rect.Min.Y, bsz.X, bsz.Y, bounds.Radius)
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package render
import "fmt"
// Item is a union interface for render items:
// [Path], [Text], [Image], and [ContextPush].
type Item interface {
fmt.Stringer
IsRenderItem()
}
// ContextPush is a [Context] push render item, which can be used by renderers
// that track group structure (e.g., SVG).
type ContextPush struct {
Context Context
}
// IsRenderItem marks this as a render item (interface assertion).
func (p *ContextPush) IsRenderItem() {
}
func (p *ContextPush) String() string {
return "ctx-push: " + p.Context.Cumulative.String()
}
// ContextPop is a [Context] pop render item, which can be used by renderers
// that track group structure (e.g., SVG).
type ContextPop struct {
}
func (p *ContextPop) String() string {
return "ctx-pop"
}
// IsRenderItem marks this as a render item (interface assertion).
func (p *ContextPop) IsRenderItem() {
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package render
import (
"cogentcore.org/core/paint/ppath"
"cogentcore.org/core/styles"
)
// Path is a path drawing render [Item]: responsible for all vector graphics
// drawing functionality.
type Path struct {
// Path specifies the shape(s) to be drawn, using commands:
// MoveTo, LineTo, QuadTo, CubeTo, ArcTo, and Close.
// Each command has the applicable coordinates appended after it,
// like the SVG path element. The coordinates are in the original
// units as specified in the Paint drawing commands, without any
// transforms applied. See [Path.Transform].
Path ppath.Path
// Context has the full accumulated style, transform, etc parameters
// for rendering the path, combining the current state context (e.g.,
// from any higher-level groups) with the current element's style parameters.
Context Context
}
func NewPath(pt ppath.Path, sty *styles.Paint, ctx *Context) *Path {
pe := &Path{Path: pt}
pe.Context.Init(sty, nil, ctx)
return pe
}
// IsRenderItem marks this as a render item (interface assertion).
func (p *Path) IsRenderItem() {}
func (p *Path) String() string {
return "path: " + p.Path.String()
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package render provides the render items that painters record (paths,
// text, images, and contexts), and the Renderer interface that draws them.
package render
import (
"reflect"
"slices"
"strings"
"cogentcore.org/core/base/reflectx"
)
// Render is the sequence of painting [Item]s recorded
// from a [paint.Painter]
type Render []Item
// Clone returns a copy of this Render,
// with shallow clones of the Items and Renderers lists.
func (pr *Render) Clone() Render {
return slices.Clone(*pr)
}
// Add adds item(s) to render. Filters any nil items.
func (pr *Render) Add(item ...Item) *Render {
for _, it := range item {
if reflectx.IsNil(reflect.ValueOf(it)) {
continue
}
n := len(*pr)
if n > 0 {
// eliminate empty push-pop sequences, which occur due to invisible elements
if _, ok := it.(*ContextPop); ok {
if _, ok := (*pr)[n-1].(*ContextPush); ok {
*pr = (*pr)[:n-1]
continue
}
}
}
*pr = append(*pr, it)
}
return pr
}
// Reset resets back to an empty Render state.
// It preserves the existing slice memory for re-use.
func (pr *Render) Reset() {
*pr = (*pr)[:0]
}
func (pr *Render) String() string {
var b strings.Builder
for _, it := range *pr {
b.WriteString(it.String())
b.WriteByte('\n')
}
return b.String()
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package render
import (
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/text/shaped"
)
// Text is a text rendering render item.
type Text struct {
// Text contains shaped Lines of text to be rendered, as produced by a
// [shaped.Shaper]. Typically this text is configured so that the
// Postion is at the upper left corner of the resulting text rendering.
Text *shaped.Lines
// Position to render, which typically specifies the upper left corner of
// the Text. This is added directly to the offsets and is transformed by the
// active transform matrix. See also PositionAbs
Position math32.Vector2
// Context has the full accumulated style, transform, etc parameters
// for rendering, combining the current state context (e.g.,
// from any higher-level groups) with the current element's style parameters.
Context Context
}
func NewText(txt *shaped.Lines, sty *styles.Paint, ctx *Context, pos math32.Vector2) *Text {
nt := &Text{Text: txt, Position: pos}
nt.Context.Init(sty, nil, ctx)
return nt
}
// IsRenderItem marks this as a render item (interface assertion).
func (tx *Text) IsRenderItem() {}
func (tx *Text) String() string {
return "text: " + tx.Text.String()
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package pdfrender renders to PDF documents (with the pdf package).
package pdfrender
import (
"bytes"
"image"
"io"
"reflect"
"cogentcore.org/core/base/iox/imagex"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/base/stack"
"cogentcore.org/core/colors/gradient"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint/pdf"
"cogentcore.org/core/paint/pimage"
"cogentcore.org/core/paint/render"
"cogentcore.org/core/styles/units"
)
// Renderer is the PDF renderer.
type Renderer struct {
size math32.Vector2
sizeUnits units.Units
unitContext units.Context
PDF *pdf.PDF
buff *bytes.Buffer
// gStack is a stack of graphic state context in the PDF
gStack stack.Stack[int]
}
func New(size math32.Vector2, un *units.Context) render.Renderer {
rs := &Renderer{unitContext: *un}
rs.SetSize(units.UnitDot, size)
return rs
}
func (rs *Renderer) Image() image.Image {
return nil // can't generate an image
}
func (rs *Renderer) Source() []byte {
if rs.buff == nil {
return nil
}
return rs.buff.Bytes()
}
func (rs *Renderer) Size() (units.Units, math32.Vector2) {
return rs.sizeUnits, rs.size
}
func (rs *Renderer) SetSize(un units.Units, size math32.Vector2) {
if rs.sizeUnits == un && rs.size == size {
return
}
rs.sizeUnits = un
rs.size = size
}
// Render is the main rendering function.
func (rs *Renderer) Render(r render.Render) render.Renderer {
rs.buff = &bytes.Buffer{}
rs.StartRender(rs.buff)
rs.RenderPage(r)
rs.EndRender()
return rs
}
// StartRender creates the renderer.
func (rs *Renderer) StartRender(w io.Writer) {
sx := rs.unitContext.Convert(float32(rs.size.X), rs.sizeUnits, units.UnitPt)
sy := rs.unitContext.Convert(float32(rs.size.Y), rs.sizeUnits, units.UnitPt)
rs.PDF = pdf.New(w, sx, sy, &rs.unitContext)
rs.gStack = nil
}
// EndRender finishes the render
func (rs *Renderer) EndRender() {
rs.PDF.Close()
}
// AddPage adds a new page of the same size.
func (rs *Renderer) AddPage() {
sx := rs.unitContext.Convert(float32(rs.size.X), rs.sizeUnits, units.UnitPt)
sy := rs.unitContext.Convert(float32(rs.size.Y), rs.sizeUnits, units.UnitPt)
rs.PDF.NewPage(sx, sy)
}
// RenderPage renders the content to current PDF page
func (rs *Renderer) RenderPage(r render.Render) {
for _, ri := range r {
switch x := ri.(type) {
case *render.Path:
rs.RenderPath(x)
case *pimage.Params:
rs.RenderImage(x)
case *render.Text:
rs.RenderText(x)
case *render.ContextPush:
rs.PushContext(x)
case *render.ContextPop:
rs.PopContext(x)
}
}
}
func (rs *Renderer) PushTransform(m math32.Matrix2) int {
cg := rs.gStack.Peek()
g := cg + 1
rs.PDF.PushTransform(m)
rs.gStack.Push(g)
return g
}
func (rs *Renderer) PopStack() int {
cg := rs.gStack.Pop()
rs.PDF.PopStack()
return cg
}
func (rs *Renderer) RenderPath(pt *render.Path) {
p := pt.Path
pc := &pt.Context
rs.PDF.Path(p, &pc.Style, pc.Transform)
}
func (rs *Renderer) PushContext(pt *render.ContextPush) {
rs.PushTransform(pt.Context.Transform)
}
func (rs *Renderer) PopContext(pt *render.ContextPop) {
rs.PopStack()
}
func (rs *Renderer) RenderText(pt *render.Text) {
pc := &pt.Context
rs.PDF.Text(&pc.Style, pc.Transform, pt.Position, pt.Text)
}
func (rs *Renderer) RenderImage(pr *pimage.Params) {
usrc := imagex.Unwrap(pr.Source)
umask := imagex.Unwrap(pr.Mask)
nilSrc := usrc == nil
if r, ok := usrc.(*image.RGBA); ok && r == nil {
nilSrc = true
}
if pr.Rect == (image.Rectangle{}) {
pr.Rect = image.Rectangle{Max: rs.size.ToPoint()}
}
if pr.Anchor != "" {
rs.PDF.AddAnchor(pr.Anchor, math32.FromPoint(pr.Rect.Min))
}
// todo: handle masks!
// Fast path for [image.Uniform]
if u, ok := usrc.(*image.Uniform); nilSrc || ok && umask == nil {
rs.PDF.FillBox(math32.Identity2(), math32.B2FromRect(pr.Rect), u)
return
}
// a gradient fills the rectangle, as a pattern
if gr, ok := usrc.(gradient.Gradient); ok {
rs.PDF.FillBox(math32.Identity2(), math32.B2FromRect(pr.Rect), gr)
return
}
m := math32.Translate2D(float32(pr.Rect.Min.X+pr.SourcePos.X), float32(pr.Rect.Min.Y+pr.SourcePos.Y))
if pr.Cmd == pimage.Transform {
m = pr.Transform.Mul(m)
}
rimg := usrc
if pr.Original != nil {
uorig := imagex.Unwrap(pr.Original)
if !reflectx.IsNil(reflect.ValueOf(uorig)) {
sc := float32(uorig.Bounds().Size().X) / float32(usrc.Bounds().Size().X)
if sc > 1.2 {
rimg = uorig
m = m.Scale(1.0/sc, float32(usrc.Bounds().Size().Y)/float32(uorig.Bounds().Size().Y))
}
}
}
rs.PDF.Image(rimg, m)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on https://github.com/srwiley/rasterx:
// Copyright 2018 by the rasterx Authors. All rights reserved.
// Created 2018 by S.R.Wiley
package rasterx
import (
"golang.org/x/image/math/fixed"
)
// Dasher struct extends the Stroker and can draw
// dashed lines with end capping
type Dasher struct {
Stroker
Dashes []fixed.Int26_6
DashPlace int
FirstDashIsGap bool
DashIsGap bool
DeltaDash fixed.Int26_6
DashOffset fixed.Int26_6
// Sgm allows us to switch between dashing
// and non-dashing rasterizers in the SetStroke function.
Sgm Raster
}
// NewDasher returns a Dasher ptr with default values.
// A Dasher has all of the capabilities of a Stroker, Filler, and Scanner, plus the ability
// to stroke curves with solid lines. Use SetStroke to configure with non-default
// values.
func NewDasher(width, height int, scanner Scanner) *Dasher {
r := new(Dasher)
r.Scanner = scanner
r.SetBounds(width, height)
r.SetWinding(true)
r.SetStroke(1*64, 4*64, ButtCap, nil, FlatGap, MiterClip, nil, 0)
r.Sgm = &r.Stroker
return r
}
// JoinF overides stroker JoinF during dashed stroking, because we need to slightly modify
// the the call as below to handle the case of the join being in a dash gap.
func (r *Dasher) JoinF() {
if len(r.Dashes) == 0 || !r.InStroke || !r.DashIsGap {
r.Stroker.JoinF()
}
}
// Start starts a dashed line
func (r *Dasher) Start(a fixed.Point26_6) {
// Advance dashPlace to the dashOffset start point and set deltaDash
if len(r.Dashes) > 0 {
r.DeltaDash = r.DashOffset
r.DashIsGap = false
r.DashPlace = 0
for r.DeltaDash > r.Dashes[r.DashPlace] {
r.DeltaDash -= r.Dashes[r.DashPlace]
r.DashIsGap = !r.DashIsGap
r.DashPlace++
if r.DashPlace == len(r.Dashes) {
r.DashPlace = 0
}
}
r.FirstDashIsGap = r.DashIsGap
}
r.Stroker.Start(a)
}
// LineF overides stroker LineF to modify the the call as below
// while performing the join in a dashed stroke.
func (r *Dasher) LineF(b fixed.Point26_6) {
var bnorm fixed.Point26_6
a := r.A // Copy local a since r.a is going to change during stroke operation
ba := b.Sub(a)
segLen := Length(ba)
var nlt fixed.Int26_6
if b == r.LeadPoint.P { // End of segment
bnorm = r.LeadPoint.TNorm // Use more accurate leadPoint tangent
} else {
bnorm = TurnPort90(ToLength(b.Sub(a), r.U)) // Intra segment normal
}
for segLen+r.DeltaDash > r.Dashes[r.DashPlace] {
nl := r.Dashes[r.DashPlace] - r.DeltaDash
nlt += nl
r.DashLineStrokeBit(a.Add(ToLength(ba, nlt)), bnorm, false)
r.DashIsGap = !r.DashIsGap
segLen -= nl
r.DeltaDash = 0
r.DashPlace++
if r.DashPlace == len(r.Dashes) {
r.DashPlace = 0
}
}
r.DeltaDash += segLen
r.DashLineStrokeBit(b, bnorm, true)
}
// SetStroke set the parameters for stroking a line. width is the width of the line, miterlimit is the miter cutoff
// value for miter, arc, miterclip and arcClip joinModes. CapL and CapT are the capping functions for leading and trailing
// line ends. If one is nil, the other function is used at both ends. gp is the gap function that determines how a
// gap on the convex side of two lines joining is filled. jm is the JoinMode for curve segments. Dashes is the values for
// the dash pattern. Pass in nil or an empty slice for no dashes. dashoffset is the starting offset into the dash array.
func (r *Dasher) SetStroke(width, miterLimit fixed.Int26_6, capL, capT CapFunc, gp GapFunc, jm JoinMode, dashes []float32, dashOffset float32) {
r.Stroker.SetStroke(width, miterLimit, capL, capT, gp, jm)
r.Dashes = r.Dashes[:0] // clear the dash array
if len(dashes) == 0 {
r.Sgm = &r.Stroker // This is just plain stroking
return
}
// Dashed Stroke
// Convert the float dash array and offset to fixed point and attach to the Filler
oneIsPos := false // Check to see if at least one dash is > 0
for _, v := range dashes {
fv := fixed.Int26_6(v * 64)
if fv <= 0 { // Negatives are considered 0s.
fv = 0
} else {
oneIsPos = true
}
r.Dashes = append(r.Dashes, fv)
}
if !oneIsPos {
r.Dashes = r.Dashes[:0]
r.Sgm = &r.Stroker // This is just plain stroking
return
}
r.DashOffset = fixed.Int26_6(dashOffset * 64)
r.Sgm = r // Use the full dasher
}
// Stop terminates a dashed line
func (r *Dasher) Stop(isClosed bool) {
if len(r.Dashes) == 0 {
r.Stroker.Stop(isClosed)
return
}
if !r.InStroke {
return
}
if isClosed && r.A != r.FirstP.P {
r.LineSeg(r.Sgm, r.FirstP.P)
}
ra := &r.Filler
if isClosed && !r.FirstDashIsGap && !r.DashIsGap { // closed connect w/o caps
a := r.A
r.FirstP.TNorm = r.LeadPoint.TNorm
r.FirstP.RT = r.LeadPoint.RT
r.FirstP.TTan = r.LeadPoint.TTan
ra.Start(r.FirstP.P.Sub(r.FirstP.TNorm))
ra.Line(a.Sub(r.Ln))
ra.Start(a.Add(r.Ln))
ra.Line(r.FirstP.P.Add(r.FirstP.TNorm))
r.Joiner(r.FirstP)
r.FirstP.BlackWidowMark(ra)
} else { // Cap open ends
if !r.DashIsGap {
r.CapL(ra, r.LeadPoint.P, r.LeadPoint.TNorm)
}
if !r.FirstDashIsGap {
r.CapT(ra, r.FirstP.P, Invert(r.FirstP.LNorm))
}
}
r.InStroke = false
}
// DashLineStrokeBit is a helper function that reduces code redundancy in the
// LineF function.
func (r *Dasher) DashLineStrokeBit(b, bnorm fixed.Point26_6, dontClose bool) {
if !r.DashIsGap { // Moving from dash to gap
a := r.A
ra := &r.Filler
ra.Start(b.Sub(bnorm))
ra.Line(a.Sub(r.Ln))
ra.Start(a.Add(r.Ln))
ra.Line(b.Add(bnorm))
if !dontClose {
r.CapL(ra, b, bnorm)
}
} else { // Moving from gap to dash
if !dontClose {
ra := &r.Filler
r.CapT(ra, b, Invert(bnorm))
}
}
r.A = b
r.Ln = bnorm
}
// Line for Dasher is here to pass the dasher sgm to LineP
func (r *Dasher) Line(b fixed.Point26_6) {
r.LineSeg(r.Sgm, b)
}
// QuadBezier for dashing
func (r *Dasher) QuadBezier(b, c fixed.Point26_6) {
r.QuadBezierf(r.Sgm, b, c)
}
// CubeBezier starts a stroked cubic bezier.
// It is a low level function exposed for the purposes of callbacks
// and debugging.
func (r *Dasher) CubeBezier(b, c, d fixed.Point26_6) {
r.CubeBezierf(r.Sgm, b, c, d)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on https://github.com/srwiley/rasterx:
// Copyright 2018 by the rasterx Authors. All rights reserved.
// Created 2018 by S.R.Wiley
package rasterx
import (
"cogentcore.org/core/math32"
"golang.org/x/image/math/fixed"
)
// Filler is a filler that implements [Raster].
type Filler struct {
Scanner
A fixed.Point26_6
First fixed.Point26_6
}
// NewFiller returns a Filler ptr with default values.
// A Filler in addition to rasterizing lines like a Scann,
// can also rasterize quadratic and cubic bezier curves.
// If Scanner is nil default scanner ScannerGV is used
func NewFiller(width, height int, scanner Scanner) *Filler {
r := new(Filler)
r.Scanner = scanner
r.SetBounds(width, height)
r.SetWinding(true)
return r
}
// Start starts a new path at the given point.
func (r *Filler) Start(a fixed.Point26_6) {
r.A = a
r.First = a
r.Scanner.Start(a)
}
// Stop sends a path at the given point.
func (r *Filler) Stop(isClosed bool) {
if r.First != r.A {
r.Line(r.First)
}
}
// QuadBezier adds a quadratic segment to the current curve.
func (r *Filler) QuadBezier(b, c fixed.Point26_6) {
r.QuadBezierF(r, b, c)
}
// QuadTo flattens the quadratic Bezier curve into lines through the LineTo func
// This functions is adapted from the version found in
// golang.org/x/image/vector
func QuadTo(ax, ay, bx, by, cx, cy float32, LineTo func(dx, dy float32)) {
devsq := DevSquared(ax, ay, bx, by, cx, cy)
if devsq >= 0.333 {
const tol = 3
n := 1 + int(math32.Sqrt(math32.Sqrt(tol*float32(devsq))))
t, nInv := float32(0), 1/float32(n)
for i := 0; i < n-1; i++ {
t += nInv
mt := 1 - t
t1 := mt * mt
t2 := mt * t * 2
t3 := t * t
LineTo(
ax*t1+bx*t2+cx*t3,
ay*t1+by*t2+cy*t3)
}
}
LineTo(cx, cy)
}
// CubeTo flattens the cubic Bezier curve into lines through the LineTo func
// This functions is adapted from the version found in
// golang.org/x/image/vector
func CubeTo(ax, ay, bx, by, cx, cy, dx, dy float32, LineTo func(ex, ey float32)) {
devsq := DevSquared(ax, ay, bx, by, dx, dy)
if devsqAlt := DevSquared(ax, ay, cx, cy, dx, dy); devsq < devsqAlt {
devsq = devsqAlt
}
if devsq >= 0.333 {
const tol = 3
n := 1 + int(math32.Sqrt(math32.Sqrt(tol*float32(devsq))))
t, nInv := float32(0), 1/float32(n)
for i := 0; i < n-1; i++ {
t += nInv
tsq := t * t
mt := 1 - t
mtsq := mt * mt
t1 := mtsq * mt
t2 := mtsq * t * 3
t3 := mt * tsq * 3
t4 := tsq * t
LineTo(
ax*t1+bx*t2+cx*t3+dx*t4,
ay*t1+by*t2+cy*t3+dy*t4)
}
}
LineTo(dx, dy)
}
// DevSquared returns a measure of how curvy the sequence (ax, ay) to (bx, by)
// to (cx, cy) is. It determines how many line segments will approximate a
// Bézier curve segment. This functions is copied from the version found in
// golang.org/x/image/vector as are the below comments.
//
// http://lists.nongnu.org/archive/html/freetype-devel/2016-08/msg00080.html
// gives the rationale for this evenly spaced heuristic instead of a recursive
// de Casteljau approach:
//
// The reason for the subdivision by n is that I expect the "flatness"
// computation to be semi-expensive (it's done once rather than on each
// potential subdivision) and also because you'll often get fewer subdivisions.
// Taking a circular arc as a simplifying assumption (ie a spherical cow),
// where I get n, a recursive approach would get 2^⌈lg n⌉, which, if I haven't
// made any horrible mistakes, is expected to be 33% more in the limit.
func DevSquared(ax, ay, bx, by, cx, cy float32) float32 {
devx := ax - 2*bx + cx
devy := ay - 2*by + cy
return devx*devx + devy*devy
}
// QuadBezierF adds a quadratic segment to the sgm Rasterizer.
func (r *Filler) QuadBezierF(sgm Raster, b, c fixed.Point26_6) {
// check for degenerate bezier
if r.A == b || b == c {
sgm.Line(c)
return
}
sgm.JoinF()
QuadTo(float32(r.A.X), float32(r.A.Y), // Pts are x64, but does not matter.
float32(b.X), float32(b.Y),
float32(c.X), float32(c.Y),
func(dx, dy float32) {
sgm.LineF(fixed.Point26_6{X: fixed.Int26_6(dx), Y: fixed.Int26_6(dy)})
})
}
// CubeBezier adds a cubic bezier to the curve
func (r *Filler) CubeBezier(b, c, d fixed.Point26_6) {
r.CubeBezierF(r, b, c, d)
}
// JoinF is a no-op for a filling rasterizer. This is used in stroking and dashed
// stroking
func (r *Filler) JoinF() {
}
// Line for a filling rasterizer is just the line call in scan
func (r *Filler) Line(b fixed.Point26_6) {
r.LineF(b)
}
// LineF for a filling rasterizer is just the line call in scan
func (r *Filler) LineF(b fixed.Point26_6) {
r.Scanner.Line(b)
r.A = b
}
// CubeBezierF adds a cubic bezier to the curve. sending the line calls the the
// sgm Rasterizer
func (r *Filler) CubeBezierF(sgm Raster, b, c, d fixed.Point26_6) {
if (r.A == b && c == d) || (r.A == b && b == c) || (c == b && d == c) {
sgm.Line(d)
return
}
sgm.JoinF()
CubeTo(float32(r.A.X), float32(r.A.Y),
float32(b.X), float32(b.Y),
float32(c.X), float32(c.Y),
float32(d.X), float32(d.Y),
func(ex, ey float32) {
sgm.LineF(fixed.Point26_6{X: fixed.Int26_6(ex), Y: fixed.Int26_6(ey)})
})
}
// Clear resets the filler
func (r *Filler) Clear() {
r.A = fixed.Point26_6{}
r.First = r.A
r.Scanner.Clear()
}
// SetBounds sets the maximum width and height of the rasterized image and
// calls Clear. The width and height are in pixels, not fixed.Int26_6 units.
func (r *Filler) SetBounds(width, height int) {
if width < 0 {
width = 0
}
if height < 0 {
height = 0
}
r.Scanner.SetBounds(width, height)
r.Clear()
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on https://github.com/srwiley/rasterx:
// Copyright 2018 by the rasterx Authors. All rights reserved.
// Created 2018 by S.R.Wiley
package rasterx
import (
"fmt"
"strings"
"cogentcore.org/core/math32"
"golang.org/x/image/math/fixed"
)
// Invert returns the point inverted around the origin
func Invert(v fixed.Point26_6) fixed.Point26_6 {
return fixed.Point26_6{X: -v.X, Y: -v.Y}
}
// TurnStarboard90 returns the vector 90 degrees starboard (right in direction heading)
func TurnStarboard90(v fixed.Point26_6) fixed.Point26_6 {
return fixed.Point26_6{X: -v.Y, Y: v.X}
}
// TurnPort90 returns the vector 90 degrees port (left in direction heading)
func TurnPort90(v fixed.Point26_6) fixed.Point26_6 {
return fixed.Point26_6{X: v.Y, Y: -v.X}
}
// DotProd returns the inner product of p and q
func DotProd(p fixed.Point26_6, q fixed.Point26_6) fixed.Int52_12 {
return fixed.Int52_12(int64(p.X)*int64(q.X) + int64(p.Y)*int64(q.Y))
}
// Length is the distance from the origin of the point
func Length(v fixed.Point26_6) fixed.Int26_6 {
vx, vy := float32(v.X), float32(v.Y)
return fixed.Int26_6(math32.Sqrt(vx*vx + vy*vy))
}
// PathCommand is the type for the path command token
type PathCommand fixed.Int26_6 //enums:enum -no-extend
// Human readable path command constants
const (
PathMoveTo PathCommand = iota
PathLineTo
PathQuadTo
PathCubicTo
PathClose
)
// A Path starts with a PathCommand value followed by zero to three fixed
// int points.
type Path []fixed.Int26_6
// ToSVGPath returns a string representation of the path
func (p Path) ToSVGPath() string {
var s strings.Builder
for i := 0; i < len(p); {
if i != 0 {
s.WriteString(" ")
}
switch PathCommand(p[i]) {
case PathMoveTo:
fmt.Fprintf(&s, "M%4.3f,%4.3f", float32(p[i+1])/64, float32(p[i+2])/64)
i += 3
case PathLineTo:
fmt.Fprintf(&s, "L%4.3f,%4.3f", float32(p[i+1])/64, float32(p[i+2])/64)
i += 3
case PathQuadTo:
fmt.Fprintf(&s, "Q%4.3f,%4.3f,%4.3f,%4.3f", float32(p[i+1])/64, float32(p[i+2])/64,
float32(p[i+3])/64, float32(p[i+4])/64)
i += 5
case PathCubicTo:
fmt.Fprintf(&s, "C%4.3f,%4.3f,%4.3f,%4.3f,%4.3f,%4.3f", float32(p[i+1])/64, float32(p[i+2])/64,
float32(p[i+3])/64, float32(p[i+4])/64, float32(p[i+5])/64, float32(p[i+6])/64)
i += 7
case PathClose:
s.WriteString("Z")
i++
default:
panic("freetype/rasterx: bad pather")
}
}
return s.String()
}
// String returns a readable representation of a Path.
func (p Path) String() string {
return p.ToSVGPath()
}
// Clear zeros the path slice
func (p *Path) Clear() {
*p = (*p)[:0]
}
// Start starts a new curve at the given point.
func (p *Path) Start(a fixed.Point26_6) {
*p = append(*p, fixed.Int26_6(PathMoveTo), a.X, a.Y)
}
// Line adds a linear segment to the current curve.
func (p *Path) Line(b fixed.Point26_6) {
*p = append(*p, fixed.Int26_6(PathLineTo), b.X, b.Y)
}
// QuadBezier adds a quadratic segment to the current curve.
func (p *Path) QuadBezier(b, c fixed.Point26_6) {
*p = append(*p, fixed.Int26_6(PathQuadTo), b.X, b.Y, c.X, c.Y)
}
// CubeBezier adds a cubic segment to the current curve.
func (p *Path) CubeBezier(b, c, d fixed.Point26_6) {
*p = append(*p, fixed.Int26_6(PathCubicTo), b.X, b.Y, c.X, c.Y, d.X, d.Y)
}
// Stop joins the ends of the path
func (p *Path) Stop(closeLoop bool) {
if closeLoop {
*p = append(*p, fixed.Int26_6(PathClose))
}
}
// AddTo adds the Path p to q.
func (p Path) AddTo(q Adder) {
for i := 0; i < len(p); {
switch PathCommand(p[i]) {
case PathMoveTo:
q.Stop(false) // Fixes issues #1 by described by Djadala; implicit close if currently in path.
q.Start(fixed.Point26_6{X: p[i+1], Y: p[i+2]})
i += 3
case PathLineTo:
q.Line(fixed.Point26_6{X: p[i+1], Y: p[i+2]})
i += 3
case PathQuadTo:
q.QuadBezier(fixed.Point26_6{X: p[i+1], Y: p[i+2]}, fixed.Point26_6{X: p[i+3], Y: p[i+4]})
i += 5
case PathCubicTo:
q.CubeBezier(fixed.Point26_6{X: p[i+1], Y: p[i+2]},
fixed.Point26_6{X: p[i+3], Y: p[i+4]}, fixed.Point26_6{X: p[i+5], Y: p[i+6]})
i += 7
case PathClose:
q.Stop(true)
i++
default:
panic("AddTo: bad path")
}
}
q.Stop(false)
}
// ToLength scales the point to the length indicated by ln
func ToLength(p fixed.Point26_6, ln fixed.Int26_6) (q fixed.Point26_6) {
if ln == 0 || (p.X == 0 && p.Y == 0) {
return
}
pX, pY := float32(p.X), float32(p.Y)
lnF := float32(ln)
pLen := math32.Sqrt(pX*pX + pY*pY)
qX, qY := pX*lnF/pLen, pY*lnF/pLen
q.X, q.Y = fixed.Int26_6(qX), fixed.Int26_6(qY)
return
}
// ClosestPortside returns the closest of p1 or p2 on the port side of the
// line from the bow to the stern. (port means left side of the direction you are heading)
// isIntersecting is just convienice to reduce code, and if false returns false, because p1 and p2 are not valid
func ClosestPortside(bow, stern, p1, p2 fixed.Point26_6, isIntersecting bool) (xt fixed.Point26_6, intersects bool) {
if !isIntersecting {
return
}
dir := bow.Sub(stern)
dp1 := p1.Sub(stern)
dp2 := p2.Sub(stern)
cp1 := dir.X*dp1.Y - dp1.X*dir.Y
cp2 := dir.X*dp2.Y - dp2.X*dir.Y
switch {
case cp1 < 0 && cp2 < 0:
return
case cp1 < 0 && cp2 >= 0:
return p2, true
case cp1 >= 0 && cp2 < 0:
return p1, true
default: // both points on port side
dirdot := DotProd(dir, dir)
// calculate vector rejections of dp1 and dp2 onto dir
h1 := dp1.Sub(dir.Mul(fixed.Int26_6((DotProd(dp1, dir) << 6) / dirdot)))
h2 := dp2.Sub(dir.Mul(fixed.Int26_6((DotProd(dp2, dir) << 6) / dirdot)))
// return point with smallest vector rejection; i.e. closest to dir line
if (h1.X*h1.X + h1.Y*h1.Y) > (h2.X*h2.X + h2.Y*h2.Y) {
return p2, true
}
return p1, true
}
}
// RadCurvature returns the curvature of a Bezier curve end point,
// given an end point, the two adjacent control points and the degree.
// The sign of the value indicates if the center of the osculating circle
// is left or right (port or starboard) of the curve in the forward direction.
func RadCurvature(p0, p1, p2 fixed.Point26_6, dm fixed.Int52_12) fixed.Int26_6 {
a, b := p2.Sub(p1), p1.Sub(p0)
abdot, bbdot := DotProd(a, b), DotProd(b, b)
h := a.Sub(b.Mul(fixed.Int26_6((abdot << 6) / bbdot))) // h is the vector rejection of a onto b
if h.X == 0 && h.Y == 0 { // points are co-linear
return 0
}
radCurve := fixed.Int26_6((fixed.Int52_12(a.X*a.X+a.Y*a.Y) * dm / fixed.Int52_12(Length(h)<<6)) >> 6)
if a.X*b.Y > b.X*a.Y { // xprod sign
return radCurve
}
return -radCurve
}
// CircleCircleIntersection calculates the points of intersection of
// two circles or returns with intersects == false if no such points exist.
func CircleCircleIntersection(ct, cl fixed.Point26_6, rt, rl fixed.Int26_6) (xt1, xt2 fixed.Point26_6, intersects bool) {
dc := cl.Sub(ct)
d := Length(dc)
// Check for solvability.
if d > (rt + rl) {
return // No solution. Circles do not intersect.
}
// check if d < abs(rt-rl)
if da := rt - rl; (da > 0 && d < da) || (da < 0 && d < -da) {
return // No solution. One circle is contained by the other.
}
rlf, rtf, df := float32(rl), float32(rt), float32(d)
af := (rtf*rtf - rlf*rlf + df*df) / df / 2.0
hfd := math32.Sqrt(rtf*rtf-af*af) / df
afd := af / df
rOffx, rOffy := float32(-dc.Y)*hfd, float32(dc.X)*hfd
p2x := float32(ct.X) + float32(dc.X)*afd
p2y := float32(ct.Y) + float32(dc.Y)*afd
xt1x, xt1y := p2x+rOffx, p2y+rOffy
xt2x, xt2y := p2x-rOffx, p2y-rOffy
return fixed.Point26_6{X: fixed.Int26_6(xt1x), Y: fixed.Int26_6(xt1y)},
fixed.Point26_6{X: fixed.Int26_6(xt2x), Y: fixed.Int26_6(xt2y)}, true
}
// CalcIntersect calculates the points of intersection of two fixed point lines
// and panics if the determinate is zero. You have been warned.
func CalcIntersect(a1, a2, b1, b2 fixed.Point26_6) (x fixed.Point26_6) {
da, db, ds := a2.Sub(a1), b2.Sub(b1), a1.Sub(b1)
det := float32(da.X*db.Y - db.X*da.Y) // Determinate
t := float32(ds.Y*db.X-ds.X*db.Y) / det
x = a1.Add(fixed.Point26_6{X: fixed.Int26_6(float32(da.X) * t), Y: fixed.Int26_6(float32(da.Y) * t)})
return
}
// RayCircleIntersection calculates the points of intersection of
// a ray starting at s2 passing through s1 and a circle in fixed point.
// Returns intersects == false if no solution is possible. If two
// solutions are possible, the point closest to s2 is returned
func RayCircleIntersection(s1, s2, c fixed.Point26_6, r fixed.Int26_6) (x fixed.Point26_6, intersects bool) {
fx, fy, intersects := RayCircleIntersectionF(float32(s1.X), float32(s1.Y),
float32(s2.X), float32(s2.Y), float32(c.X), float32(c.Y), float32(r))
return fixed.Point26_6{X: fixed.Int26_6(fx),
Y: fixed.Int26_6(fy)}, intersects
}
// RayCircleIntersectionF calculates in floating point the points of intersection of
// a ray starting at s2 passing through s1 and a circle in fixed point.
// Returns intersects == false if no solution is possible. If two
// solutions are possible, the point closest to s2 is returned
func RayCircleIntersectionF(s1X, s1Y, s2X, s2Y, cX, cY, r float32) (x, y float32, intersects bool) {
n := s2X - cX // Calculating using 64* rather than divide
m := s2Y - cY
e := s2X - s1X
d := s2Y - s1Y
// Quadratic normal form coefficients
A, B, C := e*e+d*d, -2*(e*n+m*d), n*n+m*m-r*r
D := B*B - 4*A*C
if D <= 0 {
return // No intersection or is tangent
}
D = math32.Sqrt(D)
t1, t2 := (-B+D)/(2*A), (-B-D)/(2*A)
p1OnSide := t1 > 0
p2OnSide := t2 > 0
switch {
case p1OnSide && p2OnSide:
if t2 < t1 { // both on ray, use closest to s2
t1 = t2
}
case p2OnSide: // Only p2 on ray
t1 = t2
case p1OnSide: // only p1 on ray
default: // Neither solution is on the ray
return
}
return (n - e*t1) + cX, (m - d*t1) + cY, true
}
// MatrixAdder is an adder that applies matrix M to all points
type MatrixAdder struct {
Adder
M math32.Matrix2
}
// Reset sets the matrix M to identity
func (t *MatrixAdder) Reset() {
t.M = math32.Identity2()
}
// Start starts a new path
func (t *MatrixAdder) Start(a fixed.Point26_6) {
t.Adder.Start(t.M.MulFixedPoint(a))
}
// Line adds a linear segment to the current curve.
func (t *MatrixAdder) Line(b fixed.Point26_6) {
t.Adder.Line(t.M.MulFixedPoint(b))
}
// QuadBezier adds a quadratic segment to the current curve.
func (t *MatrixAdder) QuadBezier(b, c fixed.Point26_6) {
t.Adder.QuadBezier(t.M.MulFixedPoint(b), t.M.MulFixedPoint(c))
}
// CubeBezier adds a cubic segment to the current curve.
func (t *MatrixAdder) CubeBezier(b, c, d fixed.Point26_6) {
t.Adder.CubeBezier(t.M.MulFixedPoint(b), t.M.MulFixedPoint(c), t.M.MulFixedPoint(d))
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package rasterx
import (
"image"
"image/color"
"image/draw"
"sync"
"cogentcore.org/core/colors"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint/renderers/rasterx/scan"
"github.com/cogentcore/typesetting/font"
"github.com/cogentcore/typesetting/font/opentype"
"github.com/cogentcore/typesetting/shaping"
)
var (
// TheGlyphCache is the shared font glyph bitmap render cache.
theGlyphCache glyphCache
// UseGlyphCache determines if the glyph cache is used.
UseGlyphCache = true
)
const (
// glyphMinSize is the min size in height to use the cached values.
// small glyphs end up with bad aliasing artifacts when rendered
// from the cache.
glyphMinSize = 12
// glyphMaxSize is the max size in either dim for the render mask.
glyphMaxSize = 128
// glyphMaskBorder is the extra amount on each side to include around the glyph bounds.
glyphMaskBorder = 2
// glyphMaskOffsets is the number of different subpixel offsets to render, in each axis.
// The memory usage goes as the square of this number, and 4 produces very good results,
// while 2 is acceptable, and is significantly better than 1. 8 is overkill.
glyphMaskOffsetsX = 4
glyphMaskOffsetsY = 4
)
func init() {
theGlyphCache.init()
}
// GlyphCache holds cached rendered font glyphs.
type glyphCache struct {
glyphs map[*font.Face]map[glyphKey]*image.Alpha
maxSize image.Point
image *image.RGBA
scanner *scan.Scanner
imgSpanner *scan.ImgSpanner
filler *Filler
sync.Mutex
}
// glyphKey is the key for encoding a mask render.
type glyphKey struct {
gid font.GID // uint32
sx uint8 // size
sy uint8
ox uint8 // offset
oy uint8
}
func (gc *glyphCache) init() {
gc.glyphs = make(map[*font.Face]map[glyphKey]*image.Alpha)
gc.maxSize = image.Point{glyphMaxSize, glyphMaxSize}
sz := gc.maxSize
gc.image = image.NewRGBA(image.Rectangle{Max: sz})
gc.imgSpanner = scan.NewImgSpanner(gc.image)
gc.scanner = scan.NewScanner(gc.imgSpanner, sz.X, sz.Y)
gc.filler = NewFiller(sz.X, sz.Y, gc.scanner)
gc.filler.SetWinding(true)
gc.filler.SetColor(colors.Uniform(color.Black))
gc.scanner.SetClip(gc.image.Bounds())
}
// Glyph returns an existing cached glyph or a newly rendered one,
// and the top-left rendering position to use, based on pos arg.
// fractional offsets are supported to improve quality.
func (gc *glyphCache) Glyph(face *font.Face, g *shaping.Glyph, outline font.GlyphOutline, scale float32, pos math32.Vector2) (*image.Alpha, image.Point) {
gc.Lock()
defer gc.Unlock()
fsize := image.Point{X: int(g.Width.Round()), Y: -int(g.Height.Round())}
size := fsize.Add(image.Point{2 * glyphMaskBorder, 2 * glyphMaskBorder})
if size.X <= 0 || size.X > glyphMaxSize || size.Y <= 0 || size.Y > glyphMaxSize || size.Y < glyphMinSize {
return nil, image.Point{}
}
// fmt.Println(face.Describe().Family, g.GlyphID, "wd, ht:", math32.FromFixed(g.Width), -math32.FromFixed(g.Height), "size:", size)
// fmt.Printf("g: %#v\n", g)
pf := pos.Floor()
pi := pf.ToPoint().Sub(image.Point{glyphMaskBorder, glyphMaskBorder})
pi.X += g.XBearing.Round()
pi.Y -= g.YBearing.Round()
off := pos.Sub(pf)
oi := off.Mul(math32.Vec2(glyphMaskOffsetsX, glyphMaskOffsetsY)).Round().ToPoint()
// fmt.Println("pos:", pos, "oi:", oi, "pi:", pi)
key := glyphKey{gid: g.GlyphID, sx: uint8(fsize.X), sy: uint8(fsize.Y), ox: uint8(oi.X), oy: uint8(oi.Y)}
fc, hasfc := gc.glyphs[face]
if hasfc {
mask := fc[key]
if mask != nil {
return mask, pi
}
} else {
fc = make(map[glyphKey]*image.Alpha)
}
mask := gc.renderGlyph(face, g.GlyphID, g, outline, size, scale, oi.X, oi.Y)
fc[key] = mask
gc.glyphs[face] = fc
// fmt.Println(gc.CacheSize())
return mask, pi
}
// renderGlyph renders the given glyph and caches the result.
func (gc *glyphCache) renderGlyph(_ *font.Face, _ font.GID, g *shaping.Glyph, outline font.GlyphOutline, size image.Point, scale float32, xo, yo int) *image.Alpha {
// clear target:
draw.Draw(gc.image, gc.image.Bounds(), colors.Uniform(color.Transparent), image.Point{0, 0}, draw.Src)
od := math32.Vec2(1, 1).Div(math32.Vec2(glyphMaskOffsetsX, glyphMaskOffsetsY))
x := -float32(g.XBearing.Round()) + float32(xo)*od.X + glyphMaskBorder
y := float32(g.YBearing.Round()) + float32(yo)*od.Y + glyphMaskBorder
rs := gc.filler
rs.Clear()
for _, s := range outline.Segments {
p0 := math32.Vec2(s.Args[0].X*scale+x, -s.Args[0].Y*scale+y)
switch s.Op {
case opentype.SegmentOpMoveTo:
rs.Start(p0.ToFixed())
case opentype.SegmentOpLineTo:
rs.Line(p0.ToFixed())
case opentype.SegmentOpQuadTo:
p1 := math32.Vec2(s.Args[1].X*scale+x, -s.Args[1].Y*scale+y)
rs.QuadBezier(p0.ToFixed(), p1.ToFixed())
case opentype.SegmentOpCubeTo:
p1 := math32.Vec2(s.Args[1].X*scale+x, -s.Args[1].Y*scale+y)
p2 := math32.Vec2(s.Args[2].X*scale+x, -s.Args[2].Y*scale+y)
rs.CubeBezier(p0.ToFixed(), p1.ToFixed(), p2.ToFixed())
}
}
rs.Stop(true)
rs.Draw()
rs.Clear()
bb := image.Rectangle{Max: size}
mask := image.NewAlpha(bb)
draw.Draw(mask, bb, gc.image, image.Point{}, draw.Src)
// fmt.Println("size:", size, *mask)
// fmt.Println("render:", gid, size)
return mask
}
// CacheSize reports the total number of bytes used for image masks.
// For example, the cogent core docs took about 3.5mb using 4
func (gc *glyphCache) CacheSize() int {
gc.Lock()
defer gc.Unlock()
total := 0
for _, fc := range gc.glyphs {
for _, mask := range fc {
sz := mask.Bounds().Size()
total += sz.X * sz.Y
}
}
return total
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package rasterx
import (
"image"
"image/color"
"image/draw"
"cogentcore.org/core/paint/render"
)
// layer is a context that is pushed: if it is composited as a whole (see
// [render.Context.IsLayer]), the rendering within it is to its own image
// (the layer), which is composited onto the image under it, through its
// mask, when it is popped.
type layer struct {
// under is the image under the layer, nil if the context is not a layer.
under *image.RGBA
// image is the image of the layer.
image *image.RGBA
// region is the region of the images that the layer composites onto.
region image.Rectangle
// mask is the mask of the layer (its clip mask, mask, and opacity), nil
// for none.
mask *image.Alpha
// opacity is the opacity of the layer, if it has no mask.
opacity float32
}
// pushContext pushes the given context: if it is a layer, the rendering
// is to a new layer until it is popped.
func (rs *Renderer) pushContext(ctx *render.Context) {
if !ctx.IsLayer() {
rs.layers = append(rs.layers, layer{})
return
}
region := ctx.Bounds.Rect.ToRect().Intersect(rs.image.Bounds())
if ctx.Bounds.Rect.Size().X <= 0 || ctx.Bounds.Rect.Size().Y <= 0 {
region = rs.image.Bounds()
}
ly := layer{under: rs.image, opacity: 1}
if ctx.Opacity > 0 && ctx.Opacity < 1 {
ly.opacity = ctx.Opacity
}
if len(ctx.ClipMask) > 0 || len(ctx.Mask) > 0 {
ly.mask = image.NewAlpha(region)
for i := range ly.mask.Pix {
ly.mask.Pix[i] = uint8(255 * ly.opacity)
}
if len(ctx.ClipMask) > 0 {
rs.applyMask(ly.mask, ctx.ClipMask, false)
}
if len(ctx.Mask) > 0 {
rs.applyMask(ly.mask, ctx.Mask, true)
}
region = alphaBounds(ly.mask)
ly.mask = ly.mask.SubImage(region).(*image.Alpha)
}
ly.region = region
ly.image = rs.newLayerImage(region)
rs.layers = append(rs.layers, ly)
rs.setImage(ly.image)
}
// popContext pops the context that was last pushed: if it is a layer,
// it is composited onto the image under it, through its mask.
func (rs *Renderer) popContext() {
n := len(rs.layers)
if n == 0 {
return
}
ly := rs.layers[n-1]
rs.layers = rs.layers[:n-1]
if ly.under == nil {
return
}
rs.setImage(ly.under)
if !ly.region.Empty() {
var mask image.Image = ly.mask
if ly.mask == nil {
mask = image.NewUniform(color.Alpha{A: uint8(255*ly.opacity + 0.5)})
}
draw.DrawMask(ly.under, ly.region, ly.image, ly.region.Min, mask, ly.region.Min, draw.Over)
}
rs.freeLayers = append(rs.freeLayers, ly.image)
}
// setImage sets the image that is rendered to.
func (rs *Renderer) setImage(img *image.RGBA) {
rs.image = img
rs.ImgSpanner.SetImage(img)
}
// newLayerImage returns an image for a layer, of the size of the
// renderer, which is transparent in the given region (the rest of it is
// not used).
func (rs *Renderer) newLayerImage(region image.Rectangle) *image.RGBA {
var img *image.RGBA
if n := len(rs.freeLayers); n > 0 {
img = rs.freeLayers[n-1]
rs.freeLayers = rs.freeLayers[:n-1]
} else {
img = image.NewRGBA(rs.image.Bounds())
}
if region.Empty() {
return img
}
for y := region.Min.Y; y < region.Max.Y; y++ {
i := img.PixOffset(region.Min.X, y)
clear(img.Pix[i : i+4*region.Dx()])
}
return img
}
// applyMask multiplies the given mask by the rendering of the given
// items: by its alpha, or, if luminance, by its luminance times its alpha
// (as for SVG masks, with the coefficients of browsers).
func (rs *Renderer) applyMask(mask *image.Alpha, items render.Render, luminance bool) {
region := mask.Rect
img := rs.newLayerImage(region)
under := rs.image
rs.setImage(img)
depth := len(rs.layers)
rs.renderItems(items)
for len(rs.layers) > depth { // contexts of the items that are not popped
rs.popContext()
}
rs.setImage(under)
for y := region.Min.Y; y < region.Max.Y; y++ {
mi := mask.PixOffset(region.Min.X, y)
pi := img.PixOffset(region.Min.X, y)
for x := 0; x < region.Dx(); x, mi, pi = x+1, mi+1, pi+4 {
var a uint32
if luminance { // the colors are premultiplied by alpha
p := img.Pix[pi : pi+3]
a = (2125*uint32(p[0]) + 7154*uint32(p[1]) + 721*uint32(p[2]) + 5000) / 10000
} else {
a = uint32(img.Pix[pi+3])
}
mask.Pix[mi] = uint8((uint32(mask.Pix[mi])*a + 127) / 255)
}
}
rs.freeLayers = append(rs.freeLayers, img)
}
// alphaBounds returns the bounds of the pixels of the given mask that are
// not transparent (empty if none are).
func alphaBounds(m *image.Alpha) image.Rectangle {
var b image.Rectangle
r := m.Rect
for y := r.Min.Y; y < r.Max.Y; y++ {
i := m.PixOffset(r.Min.X, y)
row := m.Pix[i : i+r.Dx()]
x0 := -1
for x, a := range row {
if a != 0 {
x0 = x
break
}
}
if x0 < 0 {
continue
}
x1 := x0
for x := len(row) - 1; x > x0; x-- {
if row[x] != 0 {
x1 = x
break
}
}
b = b.Union(image.Rect(r.Min.X+x0, y, r.Min.X+x1+1, y+1))
}
return b
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package rasterx renders to images by rasterizing paths and text.
package rasterx
import (
"image"
"slices"
"cogentcore.org/core/colors/gradient"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint/pimage"
"cogentcore.org/core/paint/ppath"
"cogentcore.org/core/paint/render"
"cogentcore.org/core/paint/renderers/rasterx/scan"
"cogentcore.org/core/styles/units"
)
// Renderer is the rasterx renderer.
type Renderer struct {
size math32.Vector2
image *image.RGBA
// Path is the current path.
Path Path
// rasterizer -- stroke / fill rendering engine from raster
Raster *Dasher
// scan scanner
Scanner *scan.Scanner
// scan spanner
ImgSpanner *scan.ImgSpanner
// layers are the layers of the contexts that are pushed (see layer.go).
layers []layer
// freeLayers are the images of layers that can be used again.
freeLayers []*image.RGBA
}
func New(size math32.Vector2) render.Renderer {
rs := &Renderer{}
rs.SetSize(units.UnitDot, size)
return rs
}
func (rs *Renderer) Image() image.Image { return rs.image }
func (rs *Renderer) Source() []byte { return nil }
func (rs *Renderer) Size() (units.Units, math32.Vector2) {
return units.UnitDot, rs.size
}
func (rs *Renderer) SetSize(un units.Units, size math32.Vector2) {
if rs.size == size {
return
}
rs.size = size
psz := size.ToPointCeil()
rs.image = image.NewRGBA(image.Rectangle{Max: psz})
rs.ImgSpanner = scan.NewImgSpanner(rs.image)
rs.Scanner = scan.NewScanner(rs.ImgSpanner, psz.X, psz.Y)
rs.Raster = NewDasher(psz.X, psz.Y, rs.Scanner)
rs.layers = nil
rs.freeLayers = nil
}
// Render is the main rendering function.
func (rs *Renderer) Render(r render.Render) render.Renderer {
rs.renderItems(r)
for len(rs.layers) > 0 { // contexts that are not popped
rs.popContext()
}
return rs
}
// renderItems renders the given items.
func (rs *Renderer) renderItems(r render.Render) {
for _, ri := range r {
switch x := ri.(type) {
case *render.Path:
rs.RenderPath(x)
case *pimage.Params:
x.Render(rs.image)
case *render.Text:
rs.RenderText(x)
case *render.ContextPush:
rs.pushContext(&x.Context)
case *render.ContextPop:
rs.popContext()
}
}
}
func (rs *Renderer) RenderPath(pt *render.Path) {
p := pt.Path
if !ppath.ArcToCubeImmediate {
p = p.ReplaceArcs()
}
pc := &pt.Context
clip := pc.Bounds.Rect.ToRect()
if clip.Empty() { // all clipped (the scanner does not clip with an empty clip)
return
}
rs.Scanner.SetClip(clip)
PathToRasterx(&rs.Path, p, pt.Context.Cumulative, math32.Vector2{})
rs.Fill(pt)
rs.Stroke(pt)
rs.Path.Clear()
rs.Raster.Clear()
}
func PathToRasterx(rs Adder, p ppath.Path, m math32.Matrix2, off math32.Vector2) {
for s := p.Scanner(); s.Scan(); {
cmd := s.Cmd()
end := m.MulPoint(s.End()).Add(off)
switch cmd {
case ppath.MoveTo:
rs.Start(end.ToFixed())
case ppath.LineTo:
rs.Line(end.ToFixed())
case ppath.QuadTo:
cp1 := m.MulPoint(s.CP1()).Add(off)
rs.QuadBezier(cp1.ToFixed(), end.ToFixed())
case ppath.CubeTo:
cp1 := m.MulPoint(s.CP1()).Add(off)
cp2 := m.MulPoint(s.CP2()).Add(off)
rs.CubeBezier(cp1.ToFixed(), cp2.ToFixed(), end.ToFixed())
case ppath.Close:
rs.Stop(true)
}
}
}
func (rs *Renderer) Stroke(pt *render.Path) {
pc := &pt.Context
sty := &pc.Style
if !sty.HasStroke() {
return
}
dash := slices.Clone(sty.Stroke.Dashes)
if dash != nil {
scx, scy := pc.Cumulative.ExtractScale()
sc := 0.5 * (math32.Abs(scx) + math32.Abs(scy))
for i := range dash {
dash[i] *= sc
}
}
sw := rs.StrokeWidth(pt)
rs.Raster.SetStroke(
math32.ToFixed(sw),
math32.ToFixed(sty.Stroke.MiterLimit),
capfunc(sty.Stroke.Cap), nil, nil, joinmode(sty.Stroke.Join),
dash, 0)
rs.Path.AddTo(rs.Raster)
rs.SetColor(rs.Raster, pc, sty.Stroke.Color, sty.Stroke.Opacity)
rs.Raster.Draw()
}
func (rs *Renderer) SetColor(sc Scanner, pc *render.Context, clr image.Image, opacity float32) {
if g, ok := clr.(gradient.Gradient); ok {
fbox := sc.GetPathExtent()
lastRenderBBox := image.Rectangle{Min: image.Point{fbox.Min.X.Floor(), fbox.Min.Y.Floor()},
Max: image.Point{fbox.Max.X.Ceil(), fbox.Max.Y.Ceil()}}
g.Update(opacity, math32.B2FromRect(lastRenderBBox), pc.Cumulative)
sc.SetColor(clr)
} else {
if opacity < 1 {
sc.SetColor(gradient.ApplyOpacity(clr, opacity))
} else {
sc.SetColor(clr)
}
}
}
// Fill fills the current path with the current color. Open subpaths
// are implicitly closed. The path is preserved after this operation.
func (rs *Renderer) Fill(pt *render.Path) {
pc := &pt.Context
sty := &pc.Style
if !sty.HasFill() {
return
}
rf := &rs.Raster.Filler
rf.SetWinding(sty.Fill.Rule == ppath.NonZero)
rs.Path.AddTo(rf)
rs.SetColor(rf, pc, sty.Fill.Color, sty.Fill.Opacity)
rf.Draw()
rf.Clear()
}
func MeanScale(m math32.Matrix2) float32 {
scx, scy := m.ExtractScale()
return 0.5 * (math32.Abs(scx) + math32.Abs(scy))
}
// StrokeWidth obtains the current stoke width subject to transform (or not
// depending on VecEffNonScalingStroke)
func (rs *Renderer) StrokeWidth(pt *render.Path) float32 {
pc := &pt.Context
sty := &pc.Style
dw := sty.Stroke.Width.Dots
if dw == 0 {
return dw
}
if sty.VectorEffect == ppath.VectorEffectNonScalingStroke {
return dw
}
sc := MeanScale(pt.Context.Cumulative)
return sc * dw
}
func capfunc(st ppath.Caps) CapFunc {
switch st {
case ppath.CapButt:
return ButtCap
case ppath.CapRound:
return RoundCap
case ppath.CapSquare:
return SquareCap
}
return nil
}
func joinmode(st ppath.Joins) JoinMode {
switch st {
case ppath.JoinMiter:
return Miter
case ppath.JoinMiterClip:
return MiterClip
case ppath.JoinRound:
return Round
case ppath.JoinBevel:
return Bevel
case ppath.JoinArcs:
return Arc
case ppath.JoinArcsClip:
return ArcClip
}
return Arc
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on https://github.com/srwiley/scanx:
// Copyright 2018 by the scanx Authors. All rights reserved.
// Created 2018 by S.R.Wiley
// This is the anti-aliasing algorithm from the golang
// translation of FreeType. It has been adapted for use by the scan package
// which replaces the painter interface with the spanner interface.
// Copyright 2010 The Freetype-Go Authors. All rights reserved.
// Use of this source code is governed by your choice of either the
// FreeType License or the GNU General Public License version 2 (or
// any later version), both of which can be found in the LICENSE file.
// Package scan provides an anti-aliasing 2-D rasterizer, which is
// based on the larger Freetype suite of font-related packages, but the
// raster package is not specific to font rasterization, and can be used
// standalone without any other Freetype package.
// Rasterization is done by the same area/coverage accumulation algorithm as
// the Freetype "smooth" module, and the Anti-Grain Geometry library. A
// description of the area/coverage algorithm is at
// http://projects.tuxee.net/cl-vectors/section-the-cl-aa-algorithm
package scan
import (
"image"
"math"
"golang.org/x/image/math/fixed"
)
// Scanner is a refactored version of the freetype scanner
type Scanner struct {
// If false, the behavior is to use the even-odd winding fill
// rule during Rasterize.
UseNonZeroWinding bool
// The Width of the Rasterizer. The height is implicit in len(cellIndex).
Width int
// The current pen position.
A fixed.Point26_6
// The current cell and its area/coverage being accumulated.
Xi, Yi int
Area int
Cover int
// The clip bounds of the scanner
Clip image.Rectangle
// The saved cells.
Cell []Cell
// Linked list of cells, one per row.
CellIndex []int
// The spanner that we use.
Spanner Spanner
// The bounds.
MinX, MinY, MaxX, MaxY fixed.Int26_6
}
// SpanFunc is the type of a span function
type SpanFunc func(yi, xi0, xi1 int, alpha uint32)
// A Spanner consumes spans as they are created by the Scanner Draw function
type Spanner interface {
// SetColor sets the color used for rendering.
SetColor(color image.Image)
// This returns a function that is efficient given the Spanner parameters.
GetSpanFunc() SpanFunc
}
// Cell is part of a linked list (for a given yi co-ordinate) of accumulated
// area/coverage for the pixel at (xi, yi).
type Cell struct {
Xi int
Area int
Cover int
Next int
}
func (s *Scanner) Set(a fixed.Point26_6) {
if s.MaxX < a.X {
s.MaxX = a.X
}
if s.MaxY < a.Y {
s.MaxY = a.Y
}
if s.MinX > a.X {
s.MinX = a.X
}
if s.MinY > a.Y {
s.MinY = a.Y
}
}
// SetWinding set the winding rule for the polygons
func (s *Scanner) SetWinding(useNonZeroWinding bool) {
s.UseNonZeroWinding = useNonZeroWinding
}
// SetColor sets the color used for rendering.
func (s *Scanner) SetColor(clr image.Image) {
s.Spanner.SetColor(clr)
}
// FindCell returns the index in [Scanner.Cell] for the cell corresponding to
// (r.xi, r.yi). The cell is created if necessary.
func (s *Scanner) FindCell() int {
yi := s.Yi
if yi < 0 || yi >= len(s.CellIndex) {
return -1
}
xi := s.Xi
if xi < 0 {
xi = -1
} else if xi > s.Width {
xi = s.Width
}
i, prev := s.CellIndex[yi], -1
for i != -1 && s.Cell[i].Xi <= xi {
if s.Cell[i].Xi == xi {
return i
}
i, prev = s.Cell[i].Next, i
}
c := len(s.Cell)
s.Cell = append(s.Cell, Cell{xi, 0, 0, i})
if prev == -1 {
s.CellIndex[yi] = c
} else {
s.Cell[prev].Next = c
}
return c
}
// SaveCell saves any accumulated [Scanner.Area] or [Scanner.Cover] for ([Scanner.Xi], [Scanner.Yi]).
func (s *Scanner) SaveCell() {
if s.Area != 0 || s.Cover != 0 {
i := s.FindCell()
if i != -1 {
s.Cell[i].Area += s.Area
s.Cell[i].Cover += s.Cover
}
s.Area = 0
s.Cover = 0
}
}
// SetCell sets the (xi, yi) cell that r is accumulating area/coverage for.
func (s *Scanner) SetCell(xi, yi int) {
if s.Xi != xi || s.Yi != yi {
s.SaveCell()
s.Xi, s.Yi = xi, yi
}
}
// Scan accumulates area/coverage for the yi'th scanline, going from
// x0 to x1 in the horizontal direction (in 26.6 fixed point co-ordinates)
// and from y0f to y1f fractional vertical units within that scanline.
func (s *Scanner) Scan(yi int, x0, y0f, x1, y1f fixed.Int26_6) {
// Break the 26.6 fixed point X co-ordinates into integral and fractional parts.
x0i := int(x0) / 64
x0f := x0 - fixed.Int26_6(64*x0i)
x1i := int(x1) / 64
x1f := x1 - fixed.Int26_6(64*x1i)
// A perfectly horizontal scan.
if y0f == y1f {
s.SetCell(x1i, yi)
return
}
dx, dy := x1-x0, y1f-y0f
// A single cell scan.
if x0i == x1i {
s.Area += int((x0f + x1f) * dy)
s.Cover += int(dy)
return
}
// There are at least two cells. Apart from the first and last cells,
// all intermediate cells go through the full width of the cell,
// or 64 units in 26.6 fixed point format.
var (
p, q, edge0, edge1 fixed.Int26_6
xiDelta int
)
if dx > 0 {
p, q = (64-x0f)*dy, dx
edge0, edge1, xiDelta = 0, 64, 1
} else {
p, q = x0f*dy, -dx
edge0, edge1, xiDelta = 64, 0, -1
}
yDelta, yRem := p/q, p%q
if yRem < 0 {
yDelta--
yRem += q
}
// Do the first cell.
xi, y := x0i, y0f
s.Area += int((x0f + edge1) * yDelta)
s.Cover += int(yDelta)
xi, y = xi+xiDelta, y+yDelta
s.SetCell(xi, yi)
if xi != x1i {
// Do all the intermediate cells.
p = 64 * (y1f - y + yDelta)
fullDelta, fullRem := p/q, p%q
if fullRem < 0 {
fullDelta--
fullRem += q
}
yRem -= q
if (xiDelta > 0 && xi < x1i) || (xiDelta < 0 && xi > x1i) {
for xi != x1i {
yDelta = fullDelta
yRem += fullRem
if yRem >= 0 {
yDelta++
yRem -= q
}
s.Area += int(64 * yDelta)
s.Cover += int(yDelta)
xi, y = xi+xiDelta, y+yDelta
s.SetCell(xi, yi)
}
}
}
// Do the last cell.
yDelta = y1f - y
s.Area += int((edge0 + x1f) * yDelta)
s.Cover += int(yDelta)
}
// Start starts a new path at the given point.
func (s *Scanner) Start(a fixed.Point26_6) {
s.Set(a)
s.SetCell(int(a.X/64), int(a.Y/64))
s.A = a
}
// Line adds a linear segment to the current curve.
func (s *Scanner) Line(b fixed.Point26_6) {
s.Set(b)
x0, y0 := s.A.X, s.A.Y
x1, y1 := b.X, b.Y
dx, dy := x1-x0, y1-y0
// Break the 26.6 fixed point Y co-ordinates into integral and fractional
// parts.
y0i := int(y0) / 64
y0f := y0 - fixed.Int26_6(64*y0i)
y1i := int(y1) / 64
y1f := y1 - fixed.Int26_6(64*y1i)
if y0i == y1i {
// There is only one scanline.
s.Scan(y0i, x0, y0f, x1, y1f)
} else if dx == 0 {
// This is a vertical line segment. We avoid calling r.scan and instead
// manipulate r.area and r.cover directly.
var (
edge0, edge1 fixed.Int26_6
yiDelta int
)
if dy > 0 {
edge0, edge1, yiDelta = 0, 64, 1
} else {
edge0, edge1, yiDelta = 64, 0, -1
}
x0i, yi := int(x0)/64, y0i
x0fTimes2 := (int(x0) - (64 * x0i)) * 2
// Do the first pixel.
dcover := int(edge1 - y0f)
darea := int(x0fTimes2 * dcover)
s.Area += darea
s.Cover += dcover
yi += yiDelta
s.SetCell(x0i, yi)
// Do all the intermediate pixels.
dcover = int(edge1 - edge0)
darea = int(x0fTimes2 * dcover)
if (yiDelta > 0 && yi < y1i) || (yiDelta < 0 && yi > y1i) {
for yi != y1i {
s.Area += darea
s.Cover += dcover
yi += yiDelta
s.SetCell(x0i, yi)
}
}
// Do the last pixel.
dcover = int(y1f - edge0)
darea = int(x0fTimes2 * dcover)
s.Area += darea
s.Cover += dcover
} else {
// There are at least two scanlines. Apart from the first and last
// scanlines, all intermediate scanlines go through the full height of
// the row, or 64 units in 26.6 fixed point format.
var (
p, q, edge0, edge1 fixed.Int26_6
yiDelta int
)
if dy > 0 {
p, q = (64-y0f)*dx, dy
edge0, edge1, yiDelta = 0, 64, 1
} else {
p, q = y0f*dx, -dy
edge0, edge1, yiDelta = 64, 0, -1
}
xDelta, xRem := p/q, p%q
if xRem < 0 {
xDelta--
xRem += q
}
// Do the first scanline.
x, yi := x0, y0i
s.Scan(yi, x, y0f, x+xDelta, edge1)
x, yi = x+xDelta, yi+yiDelta
s.SetCell(int(x)/64, yi)
if yi != y1i {
// Do all the intermediate scanlines.
p = 64 * dx
fullDelta, fullRem := p/q, p%q
if fullRem < 0 {
fullDelta--
fullRem += q
}
xRem -= q
if (yiDelta > 0 && yi < y1i) || (yiDelta < 0 && yi > y1i) {
for yi != y1i {
xDelta = fullDelta
xRem += fullRem
if xRem >= 0 {
xDelta++
xRem -= q
}
s.Scan(yi, x, edge0, x+xDelta, edge1)
x, yi = x+xDelta, yi+yiDelta
s.SetCell(int(x)/64, yi)
}
}
}
// Do the last scanline.
s.Scan(yi, x, edge0, x1, y1f)
}
// The next lineTo starts from b.
s.A = b
}
// AreaToAlpha converts an area value to a uint32 alpha value. A completely
// filled pixel corresponds to an area of 64*64*2, and an alpha of 0xffff. The
// conversion of area values greater than this depends on the winding rule:
// even-odd or non-zero.
func (s *Scanner) AreaToAlpha(area int) uint32 {
// The C Freetype implementation (version 2.3.12) does "alpha := area>>1"
// without the +1. Round-to-nearest gives a more symmetric result than
// round-down. The C implementation also returns 8-bit alpha, not 16-bit
// alpha.
a := (area + 1) >> 1
if a < 0 {
a = -a
}
alpha := uint32(a)
if s.UseNonZeroWinding {
if alpha > 0x0fff {
alpha = 0x0fff
}
} else {
alpha &= 0x1fff
if alpha > 0x1000 {
alpha = 0x2000 - alpha
} else if alpha == 0x1000 {
alpha = 0x0fff
}
}
// alpha is now in the range [0x0000, 0x0fff]. Convert that 12-bit alpha to
// 16-bit alpha.
return alpha<<4 | alpha>>8
}
// Draw converts r's accumulated curves into Spans for p. The Spans passed
// to the spanner are non-overlapping, and sorted by Y and then X. They all have non-zero
// width (and 0 <= X0 < X1 <= r.width) and non-zero A, except for the final
// Span, which has Y, X0, X1 and A all equal to zero.
func (s *Scanner) Draw() {
b := image.Rect(0, 0, s.Width, len(s.CellIndex))
if s.Clip.Dx() != 0 && s.Clip.Dy() != 0 {
b = b.Intersect(s.Clip)
}
s.SaveCell()
span := s.Spanner.GetSpanFunc()
for yi := b.Min.Y; yi < b.Max.Y; yi++ {
xi, cover := 0, 0
for c := s.CellIndex[yi]; c != -1; c = s.Cell[c].Next {
if cover != 0 && s.Cell[c].Xi > xi {
alpha := s.AreaToAlpha(cover * 64 * 2)
if alpha != 0 {
xi0, xi1 := xi, s.Cell[c].Xi
if xi0 < b.Min.X {
xi0 = b.Min.X
}
if xi1 > b.Max.X {
xi1 = b.Max.X
}
if xi0 < xi1 {
span(yi, xi0, xi1, alpha)
}
}
}
cover += s.Cell[c].Cover
alpha := s.AreaToAlpha(cover*64*2 - s.Cell[c].Area)
xi = s.Cell[c].Xi + 1
if alpha != 0 {
xi0, xi1 := s.Cell[c].Xi, xi
if xi0 < b.Min.X {
xi0 = b.Min.X
}
if xi1 > b.Max.X {
xi1 = b.Max.X
}
if xi0 < xi1 {
span(yi, xi0, xi1, alpha)
}
}
}
}
}
// GetPathExtent returns the bounds of the accumulated path extent
func (s *Scanner) GetPathExtent() fixed.Rectangle26_6 {
return fixed.Rectangle26_6{
Min: fixed.Point26_6{X: s.MinX, Y: s.MinY},
Max: fixed.Point26_6{X: s.MaxX, Y: s.MaxY}}
}
// Clear cancels any previous accumulated scans
func (s *Scanner) Clear() {
s.A = fixed.Point26_6{}
s.Xi = 0
s.Yi = 0
s.Area = 0
s.Cover = 0
s.Cell = s.Cell[:0]
for i := 0; i < len(s.CellIndex); i++ {
s.CellIndex[i] = -1
}
const mxfi = fixed.Int26_6(math.MaxInt32)
s.MinX, s.MinY, s.MaxX, s.MaxY = mxfi, mxfi, -mxfi, -mxfi
}
// SetBounds sets the maximum width and height of the rasterized image and
// calls Clear. The width and height are in pixels, not fixed.Int26_6 units.
func (s *Scanner) SetBounds(width, height int) {
if width < 0 {
width = 0
}
if height < 0 {
height = 0
}
s.Width = width
s.Cell = s.Cell[:0]
if height > cap(s.CellIndex) {
s.CellIndex = make([]int, height)
}
// Make sure length of cellIndex = height
s.CellIndex = s.CellIndex[0:height]
s.Width = width
s.Clear()
}
// NewScanner creates a new Scanner with the given bounds.
func NewScanner(xs Spanner, width, height int) (sc *Scanner) {
sc = &Scanner{Spanner: xs, UseNonZeroWinding: true}
sc.SetBounds(width, height)
return
}
// SetClip will not affect accumulation of scans, but it will
// clip drawing of the spans int the Draw func by the clip rectangle.
func (s *Scanner) SetClip(r image.Rectangle) {
s.Clip = r
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on https://github.com/srwiley/scanx:
// Copyright 2018 by the scanx Authors. All rights reserved.
// Created 2018 by S.R.Wiley
package scan
import (
"image"
"image/color"
"image/draw"
"cogentcore.org/core/colors"
)
const (
m = 1<<16 - 1
mp = 0x100 * m
pa uint32 = 0x101
q uint32 = 0xFF00
)
// ImgSpanner is a Spanner that draws Spans onto an [*image.RGBA] image.
// It uses either a color function as a the color source, or a fgColor
// if colFunc is nil.
type ImgSpanner struct {
BaseSpanner
Pix []uint8
Stride int
ColorImage image.Image
}
// LinkListSpanner is a Spanner that draws Spans onto a draw.Image
// interface satisfying struct but it is optimized for [*image.RGBA].
// It uses a solid Color only for fg and bg and does not support a color function
// used by gradients. Spans are accumulated into a set of linked lists, one for
// every horizontal line in the image. After the spans for the image are accumulated,
// use the DrawToImage function to write the spans to an image.
type LinkListSpanner struct {
BaseSpanner
Spans []SpanCell
BgColor color.RGBA
LastY int
LastP int
}
// SpanCell represents a span cell.
type SpanCell struct {
X0 int
X1 int
Next int
Clr color.RGBA
}
// BaseSpanner contains base spanner information extended by [ImgSpanner] and [LinkListSpanner].
type BaseSpanner struct {
// drawing is done with Bounds.Min as the origin
Bounds image.Rectangle
// Op is how pixels are overlayed
Op draw.Op
FgColor color.RGBA
}
// Clear clears the current spans
func (x *LinkListSpanner) Clear() {
x.LastY, x.LastP = 0, 0
x.Spans = x.Spans[0:0]
width := x.Bounds.Dy()
for range width {
// The first cells are indexed according to the y values
// to create y separate linked lists corresponding to the
// image y length. Since index 0 is used by the first of these sentinel cells
// 0 can and is used for the end of list value by the spanner linked list.
x.Spans = append(x.Spans, SpanCell{})
}
}
func (x *LinkListSpanner) SpansToImage(img draw.Image) {
for y := 0; y < x.Bounds.Dy(); y++ {
p := x.Spans[y].Next
for p != 0 {
spCell := x.Spans[p]
clr := spCell.Clr
x0, x1 := spCell.X0, spCell.X1
for x := x0; x < x1; x++ {
img.Set(y, x, clr)
}
p = spCell.Next
}
}
}
func (x *LinkListSpanner) SpansToPix(pix []uint8, stride int) {
for y := 0; y < x.Bounds.Dy(); y++ {
yo := y * stride
p := x.Spans[y].Next
for p != 0 {
spCell := x.Spans[p]
i0 := yo + spCell.X0*4
i1 := i0 + (spCell.X1-spCell.X0)*4
r, g, b, a := spCell.Clr.R, spCell.Clr.G, spCell.Clr.B, spCell.Clr.A
for i := i0; i < i1; i += 4 {
pix[i+0] = r
pix[i+1] = g
pix[i+2] = b
pix[i+3] = a
}
p = spCell.Next
}
}
}
// DrawToImage draws the accumulated y spans onto the img
func (x *LinkListSpanner) DrawToImage(img image.Image) {
switch img := img.(type) {
case *image.RGBA:
x.SpansToPix(img.Pix, img.Stride)
case draw.Image:
x.SpansToImage(img)
}
}
// SetBounds sets the spanner boundaries
func (x *LinkListSpanner) SetBounds(bounds image.Rectangle) {
x.Bounds = bounds
x.Clear()
}
func (x *LinkListSpanner) BlendColor(under color.RGBA, ma uint32) color.RGBA {
if ma == 0 {
return under
}
rma := uint32(x.FgColor.R) * ma
gma := uint32(x.FgColor.G) * ma
bma := uint32(x.FgColor.B) * ma
ama := uint32(x.FgColor.A) * ma
if x.Op != draw.Over || under.A == 0 || ama == m*0xFF {
return color.RGBA{
uint8(rma / q),
uint8(gma / q),
uint8(bma / q),
uint8(ama / q)}
}
a := m - (ama / (m >> 8))
cc := color.RGBA{
uint8((uint32(under.R)*a + rma) / q),
uint8((uint32(under.G)*a + gma) / q),
uint8((uint32(under.B)*a + bma) / q),
uint8((uint32(under.A)*a + ama) / q)}
return cc
}
func (x *LinkListSpanner) AddLink(x0, x1, next, pp int, underColor color.RGBA, alpha uint32) (p int) {
clr := x.BlendColor(underColor, alpha)
if pp >= x.Bounds.Dy() && x.Spans[pp].X1 >= x0 && ((clr.A == 0 && x.Spans[pp].Clr.A == 0) || clr == x.Spans[pp].Clr) {
// Just extend the prev span; a new one is not required
x.Spans[pp].X1 = x1
return pp
}
x.Spans = append(x.Spans, SpanCell{X0: x0, X1: x1, Next: next, Clr: clr})
p = len(x.Spans) - 1
x.Spans[pp].Next = p
return
}
// GetSpanFunc returns the function that consumes a span described by the parameters.
func (x *LinkListSpanner) GetSpanFunc() SpanFunc {
x.LastY = -1 // x within a y list may no longer be ordered, so this ensures a reset.
return x.SpanOver
}
// SpanOver adds the span into an array of linked lists of spans using the fgColor and Porter-Duff composition
// ma is the accumulated alpha coverage. This function also assumes usage sorted x inputs for each y and so if
// inputs for x in y are not monotonically increasing, then lastY should be set to -1.
func (x *LinkListSpanner) SpanOver(yi, xi0, xi1 int, ma uint32) {
if yi != x.LastY { // If the y place has changed, start at the list beginning
x.LastP = yi
x.LastY = yi
}
// since spans are sorted, we can start from x.lastP
pp := x.LastP
p := x.Spans[pp].Next
for p != 0 && xi0 < xi1 {
sp := x.Spans[p]
if sp.X1 <= xi0 { //sp is before new span
pp = p
p = sp.Next
continue
}
if sp.X0 >= xi1 { //new span is before sp
x.LastP = x.AddLink(xi0, xi1, p, pp, x.BgColor, ma)
return
}
// left span
if xi0 < sp.X0 {
pp = x.AddLink(xi0, sp.X0, p, pp, x.BgColor, ma)
xi0 = sp.X0
} else if xi0 > sp.X0 {
pp = x.AddLink(sp.X0, xi0, p, pp, sp.Clr, 0)
}
clr := x.BlendColor(sp.Clr, ma)
sameClrs := pp >= x.Bounds.Dy() && ((clr.A == 0 && x.Spans[pp].Clr.A == 0) || clr == x.Spans[pp].Clr)
if xi1 < sp.X1 { // span does not go beyond sp
// merge with left span
if x.Spans[pp].X1 >= xi0 && sameClrs {
x.Spans[pp].X1 = xi1
x.Spans[pp].Next = sp.Next
// Suffices not to advance lastP ?!? Testing says NO!
x.LastP = yi // We need to go back, so let's just go to start of the list next time
p = pp
} else {
// middle span; replaces sp
x.Spans[p] = SpanCell{X0: xi0, X1: xi1, Next: sp.Next, Clr: clr}
x.LastP = pp
}
x.AddLink(xi1, sp.X1, sp.Next, p, sp.Clr, 0)
return
}
if x.Spans[pp].X1 >= xi0 && sameClrs { // Extend and merge with previous
x.Spans[pp].X1 = sp.X1
x.Spans[pp].Next = sp.Next
p = sp.Next // clip out the current span from the list
xi0 = sp.X1 // set remaining to start for next loop
continue
}
// Set current span to start of new span and combined color
x.Spans[p] = SpanCell{X0: xi0, X1: sp.X1, Next: sp.Next, Clr: clr}
xi0 = sp.X1 // any remaining span starts at sp.x1
pp = p
p = sp.Next
}
x.LastP = pp
if xi0 < xi1 { // add any remaining span to the end of the chain
x.AddLink(xi0, xi1, 0, pp, x.BgColor, ma)
}
}
// SetBgColor sets the background color for blending to the first pixel of the given color
func (x *LinkListSpanner) SetBgColor(c image.Image) {
x.BgColor = colors.AsRGBA(colors.ToUniform(c))
}
// SetColor sets the color of x to the first pixel of the given color
func (x *LinkListSpanner) SetColor(c image.Image) {
x.FgColor = colors.AsRGBA(colors.ToUniform(c))
}
// NewImgSpanner returns an ImgSpanner set to draw to the given [*image.RGBA].
func NewImgSpanner(img *image.RGBA) (x *ImgSpanner) {
x = &ImgSpanner{}
x.SetImage(img)
return
}
// SetImage set the [*image.RGBA] that the ImgSpanner will draw onto.
func (x *ImgSpanner) SetImage(img *image.RGBA) {
x.Pix = img.Pix
x.Stride = img.Stride
x.Bounds = img.Bounds()
}
// SetColor sets the color of x to the given color image
func (x *ImgSpanner) SetColor(c image.Image) {
if u, ok := c.(*image.Uniform); ok {
x.FgColor = colors.AsRGBA(u.C)
x.ColorImage = nil
return
}
x.FgColor = color.RGBA{}
x.ColorImage = c
}
// GetSpanFunc returns the function that consumes a span described by the parameters.
// The next four func declarations are all slightly different
// but in order to reduce code redundancy, this method is used
// to dispatch the function in the draw method.
func (x *ImgSpanner) GetSpanFunc() SpanFunc {
var (
useColorFunc = x.ColorImage != nil
drawOver = x.Op == draw.Over
)
switch {
case useColorFunc && drawOver:
return x.SpanColorFunc
case useColorFunc && !drawOver:
return x.SpanColorFuncR
case !useColorFunc && !drawOver:
return x.SpanFgColorR
default:
return x.SpanFgColor
}
}
// SpanColorFuncR draw the span using a colorFunc and replaces the previous values.
func (x *ImgSpanner) SpanColorFuncR(yi, xi0, xi1 int, ma uint32) {
i0 := (yi)*x.Stride + (xi0)*4
i1 := i0 + (xi1-xi0)*4
cx := xi0
for i := i0; i < i1; i += 4 {
rcr, rcg, rcb, rca := x.ColorImage.At(cx, yi).RGBA()
cx++
x.Pix[i+0] = uint8(rcr * ma / mp)
x.Pix[i+1] = uint8(rcg * ma / mp)
x.Pix[i+2] = uint8(rcb * ma / mp)
x.Pix[i+3] = uint8(rca * ma / mp)
}
}
// SpanFgColorR draws the span with the fore ground color and replaces the previous values.
func (x *ImgSpanner) SpanFgColorR(yi, xi0, xi1 int, ma uint32) {
i0 := (yi)*x.Stride + (xi0)*4
i1 := i0 + (xi1-xi0)*4
cr, cg, cb, ca := x.FgColor.RGBA()
rma := uint8(cr * ma / mp)
gma := uint8(cg * ma / mp)
bma := uint8(cb * ma / mp)
ama := uint8(ca * ma / mp)
for i := i0; i < i1; i += 4 {
x.Pix[i+0] = rma
x.Pix[i+1] = gma
x.Pix[i+2] = bma
x.Pix[i+3] = ama
}
}
// SpanColorFunc draws the span using a colorFunc and the Porter-Duff composition operator.
func (x *ImgSpanner) SpanColorFunc(yi, xi0, xi1 int, ma uint32) {
i0 := (yi)*x.Stride + (xi0)*4
i1 := i0 + (xi1-xi0)*4
cx := xi0
for i := i0; i < i1; i += 4 {
// uses the Porter-Duff composition operator.
rcr, rcg, rcb, rca := x.ColorImage.At(cx, yi).RGBA()
cx++
a := (m - (rca * ma / m)) * pa
dr := uint32(x.Pix[i+0])
dg := uint32(x.Pix[i+1])
db := uint32(x.Pix[i+2])
da := uint32(x.Pix[i+3])
x.Pix[i+0] = uint8((dr*a + rcr*ma) / mp)
x.Pix[i+1] = uint8((dg*a + rcg*ma) / mp)
x.Pix[i+2] = uint8((db*a + rcb*ma) / mp)
x.Pix[i+3] = uint8((da*a + rca*ma) / mp)
}
}
// SpanFgColor draw the span using the fore ground color and the Porter-Duff composition operator.
func (x *ImgSpanner) SpanFgColor(yi, xi0, xi1 int, ma uint32) {
i0 := (yi)*x.Stride + (xi0)*4
i1 := i0 + (xi1-xi0)*4
// uses the Porter-Duff composition operator.
cr, cg, cb, ca := x.FgColor.RGBA()
ama := ca * ma
if ama == 0xFFFF*0xFFFF { // undercolor is ignored
rmb := uint8(cr * ma / mp)
gmb := uint8(cg * ma / mp)
bmb := uint8(cb * ma / mp)
amb := uint8(ama / mp)
for i := i0; i < i1; i += 4 {
x.Pix[i+0] = rmb
x.Pix[i+1] = gmb
x.Pix[i+2] = bmb
x.Pix[i+3] = amb
}
return
}
rma := cr * ma
gma := cg * ma
bma := cb * ma
a := (m - (ama / m)) * pa
for i := i0; i < i1; i += 4 {
x.Pix[i+0] = uint8((uint32(x.Pix[i+0])*a + rma) / mp)
x.Pix[i+1] = uint8((uint32(x.Pix[i+1])*a + gma) / mp)
x.Pix[i+2] = uint8((uint32(x.Pix[i+2])*a + bma) / mp)
x.Pix[i+3] = uint8((uint32(x.Pix[i+3])*a + ama) / mp)
}
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on https://github.com/srwiley/rasterx:
// Copyright 2018 by the rasterx Authors. All rights reserved.
// Created 2018 by S.R.Wiley
package rasterx
import (
"cogentcore.org/core/math32"
"cogentcore.org/core/paint/ppath"
"golang.org/x/image/math/fixed"
)
// MaxDx is the Maximum radians a cubic splice is allowed to span
// in ellipse parametric when approximating an off-axis ellipse.
const MaxDx float32 = math32.Pi / 8
// ToFixedP converts two floats to a fixed point.
func ToFixedP(x, y float32) (p fixed.Point26_6) {
p.X = fixed.Int26_6(x * 64)
p.Y = fixed.Int26_6(y * 64)
return
}
// AddCircle adds a circle to the Adder p
func AddCircle(cx, cy, r float32, p Adder) {
AddEllipse(cx, cy, r, r, 0, p)
}
// AddEllipse adds an elipse with center at cx,cy, with the indicated
// x and y radius, (rx, ry), rotated around the center by rot degrees.
func AddEllipse(cx, cy, rx, ry, rot float32, p Adder) {
rotRads := rot * math32.Pi / 180
pt := math32.Identity2().Translate(cx, cy).Rotate(rotRads).Translate(-cx, -cy).MulPoint(math32.Vec2(cx+rx, cy))
points := []float32{rx, ry, rot, 1.0, 0.0, pt.X, pt.Y}
p.Start(pt.ToFixed())
AddArc(points, cx, cy, pt.X, pt.Y, p)
p.Stop(true)
}
// AddRect adds a rectangle of the indicated size, rotated
// around the center by rot degrees.
func AddRect(minX, minY, maxX, maxY, rot float32, p Adder) {
rot *= math32.Pi / 180
cx, cy := (minX+maxX)/2, (minY+maxY)/2
m := math32.Identity2().Translate(cx, cy).Rotate(rot).Translate(-cx, -cy)
q := &MatrixAdder{M: m, Adder: p}
q.Start(ToFixedP(minX, minY))
q.Line(ToFixedP(maxX, minY))
q.Line(ToFixedP(maxX, maxY))
q.Line(ToFixedP(minX, maxY))
q.Stop(true)
}
// AddRoundRect adds a rectangle of the indicated size, rotated
// around the center by rot degrees with rounded corners of radius
// rx in the x axis and ry in the y axis. gf specifes the shape of the
// filleting function. Valid values are RoundGap, QuadraticGap, CubicGap,
// FlatGap, or nil which defaults to a flat gap.
func AddRoundRect(minX, minY, maxX, maxY, rx, ry, rot float32, gf GapFunc, p Adder) {
if rx <= 0 || ry <= 0 {
AddRect(minX, minY, maxX, maxY, rot, p)
return
}
rot *= math32.Pi / 180
if gf == nil {
gf = FlatGap
}
w := maxX - minX
if w < rx*2 {
rx = w / 2
}
h := maxY - minY
if h < ry*2 {
ry = h / 2
}
stretch := rx / ry
midY := minY + h/2
m := math32.Identity2().Translate(minX+w/2, midY).Rotate(rot).Scale(1, 1/stretch).Translate(-minX-w/2, -minY-h/2)
maxY = midY + h/2*stretch
minY = midY - h/2*stretch
q := &MatrixAdder{M: m, Adder: p}
q.Start(ToFixedP(minX+rx, minY))
q.Line(ToFixedP(maxX-rx, minY))
gf(q, ToFixedP(maxX-rx, minY+rx), ToFixedP(0, -rx), ToFixedP(rx, 0))
q.Line(ToFixedP(maxX, maxY-rx))
gf(q, ToFixedP(maxX-rx, maxY-rx), ToFixedP(rx, 0), ToFixedP(0, rx))
q.Line(ToFixedP(minX+rx, maxY))
gf(q, ToFixedP(minX+rx, maxY-rx), ToFixedP(0, rx), ToFixedP(-rx, 0))
q.Line(ToFixedP(minX, minY+rx))
gf(q, ToFixedP(minX+rx, minY+rx), ToFixedP(-rx, 0), ToFixedP(0, -rx))
q.Stop(true)
}
// AddArc adds an arc to the adder p
func AddArc(points []float32, cx, cy, px, py float32, p Adder) (lx, ly float32) {
rotX := points[2] * math32.Pi / 180 // Convert degress to radians
largeArc := points[3] != 0
sweep := points[4] != 0
startAngle := math32.Atan2(py-cy, px-cx) - rotX
endAngle := math32.Atan2(points[6]-cy, points[5]-cx) - rotX
deltaTheta := endAngle - startAngle
arcBig := math32.Abs(deltaTheta) > math32.Pi
// Approximate ellipse using cubic bezeir splines
etaStart := math32.Atan2(math32.Sin(startAngle)/points[1], math32.Cos(startAngle)/points[0])
etaEnd := math32.Atan2(math32.Sin(endAngle)/points[1], math32.Cos(endAngle)/points[0])
deltaEta := etaEnd - etaStart
if (arcBig && !largeArc) || (!arcBig && largeArc) { // Go has no boolean XOR
if deltaEta < 0 {
deltaEta += math32.Pi * 2
} else {
deltaEta -= math32.Pi * 2
}
}
// This check might be needed if the center point of the ellipse is
// at the midpoint of the start and end lines.
if deltaEta < 0 && sweep {
deltaEta += math32.Pi * 2
} else if deltaEta >= 0 && !sweep {
deltaEta -= math32.Pi * 2
}
// Round up to determine number of cubic splines to approximate bezier curve
segs := int(math32.Abs(deltaEta)/MaxDx) + 1
dEta := deltaEta / float32(segs) // span of each segment
// Approximate the ellipse using a set of cubic bezier curves by the method of
// L. Maisonobe, "Drawing an elliptical arc using polylines, quadratic
// or cubic Bezier curves", 2003
// https://www.spaceroots.org/documents/elllipse/elliptical-arc.pdf
tde := math32.Tan(dEta / 2)
alpha := math32.Sin(dEta) * (math32.Sqrt(4+3*tde*tde) - 1) / 3 // math32 is fun!
lx, ly = px, py
sinTheta, cosTheta := math32.Sin(rotX), math32.Cos(rotX)
ldx, ldy := EllipsePrime(points[0], points[1], sinTheta, cosTheta, etaStart, cx, cy)
for i := 1; i <= segs; i++ {
eta := etaStart + dEta*float32(i)
var px, py float32
if i == segs {
px, py = points[5], points[6] // Just makes the end point exact; no roundoff error
} else {
px, py = EllipsePointAt(points[0], points[1], sinTheta, cosTheta, eta, cx, cy)
}
dx, dy := EllipsePrime(points[0], points[1], sinTheta, cosTheta, eta, cx, cy)
p.CubeBezier(ToFixedP(lx+alpha*ldx, ly+alpha*ldy),
ToFixedP(px-alpha*dx, py-alpha*dy), ToFixedP(px, py))
lx, ly, ldx, ldy = px, py, dx, dy
}
return lx, ly
}
// EllipsePrime gives tangent vectors for parameterized ellipse; a, b, radii, eta parameter, center cx, cy
func EllipsePrime(a, b, sinTheta, cosTheta, eta, cx, cy float32) (px, py float32) {
bCosEta := b * math32.Cos(eta)
aSinEta := a * math32.Sin(eta)
px = -aSinEta*cosTheta - bCosEta*sinTheta
py = -aSinEta*sinTheta + bCosEta*cosTheta
return
}
// EllipsePointAt gives points for parameterized ellipse; a, b, radii, eta parameter, center cx, cy
func EllipsePointAt(a, b, sinTheta, cosTheta, eta, cx, cy float32) (px, py float32) {
aCosEta := a * math32.Cos(eta)
bSinEta := b * math32.Sin(eta)
px = cx + aCosEta*cosTheta - bSinEta*sinTheta
py = cy + aCosEta*sinTheta + bSinEta*cosTheta
return
}
// FindEllipseCenter locates the center of the Ellipse if it exists. If it does not exist,
// the radius values will be increased minimally for a solution to be possible
// while preserving the ra to rb ratio. ra and rb arguments are pointers that can be
// checked after the call to see if the values changed. This method uses coordinate transformations
// to reduce the problem to finding the center of a circle that includes the origin
// and an arbitrary point. The center of the circle is then transformed
// back to the original coordinates and returned.
func FindEllipseCenter(ra, rb *float32, rotX, startX, startY, endX, endY float32, sweep ppath.ArcSweep, large ppath.ArcSize) (cx, cy float32) {
cos, sin := math32.Cos(rotX), math32.Sin(rotX)
// Move origin to start point
nx, ny := endX-startX, endY-startY
// Rotate ellipse x-axis to coordinate x-axis
nx, ny = nx*cos+ny*sin, -nx*sin+ny*cos
// Scale X dimension so that ra = rb
nx *= *rb / *ra // Now the ellipse is a circle radius rb; therefore foci and center coincide
midX, midY := nx/2, ny/2
midlenSq := midX*midX + midY*midY
var hr float32
if *rb**rb < midlenSq {
// Requested ellipse does not exist; scale ra, rb to fit. Length of
// span is greater than max width of ellipse, must scale *ra, *rb
nrb := math32.Sqrt(midlenSq)
if *ra == *rb {
*ra = nrb // prevents roundoff
} else {
*ra = *ra * nrb / *rb
}
*rb = nrb
} else {
hr = math32.Sqrt(*rb**rb-midlenSq) / math32.Sqrt(midlenSq)
}
// Notice that if hr is zero, both answers are the same.
if (sweep == ppath.Clockwise) == (large == ppath.SmallArc) {
cx = midX + midY*hr
cy = midY - midX*hr
} else {
cx = midX - midY*hr
cy = midY + midX*hr
}
// reverse scale
cx *= *ra / *rb
//Reverse rotate and translate back to original coordinates
return cx*cos - cy*sin + startX, cx*sin + cy*cos + startY
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on https://github.com/srwiley/rasterx:
// Copyright 2018 by the rasterx Authors. All rights reserved.
// Created 2018 by S.R.Wiley
package rasterx
import (
"cogentcore.org/core/math32"
"golang.org/x/image/math/fixed"
)
// Stroker does everything a [Filler] does, but
// also allows for stroking and dashed stroking in addition to
// filling
type Stroker struct {
Filler
// Trailing cap function
CapT CapFunc
// Leading cpa function
CapL CapFunc
// When gap appears between segments, this function is called
JoinGap GapFunc
// Tracks progress of the stroke
FirstP C2Point
// Tracks progress of the stroke
TrailPoint C2Point
// Tracks progress of the stroke
LeadPoint C2Point
// last normal of intra-seg connection.
Ln fixed.Point26_6
// U is the half-width of the stroke.
U fixed.Int26_6
MLimit fixed.Int26_6
JoinMode JoinMode
InStroke bool
}
// NewStroker returns a ptr to a Stroker with default values.
// A Stroker has all of the capabilities of a Filler and Scanner, plus the ability
// to stroke curves with solid lines. Use SetStroke to configure with non-default
// values.
func NewStroker(width, height int, scanner Scanner) *Stroker {
r := new(Stroker)
r.Scanner = scanner
r.SetBounds(width, height)
//Defaults for stroking
r.SetWinding(true)
r.U = 2 << 6
r.MLimit = 4 << 6
r.JoinMode = MiterClip
r.JoinGap = RoundGap
r.CapL = RoundCap
r.CapT = RoundCap
r.SetStroke(1<<6, 4<<6, ButtCap, nil, FlatGap, MiterClip)
return r
}
// CapFunc defines a function that draws caps on the ends of lines
type CapFunc func(p Adder, a, eNorm fixed.Point26_6)
// GapFunc defines a function to bridge gaps when the miter limit is
// exceeded
type GapFunc func(p Adder, a, tNorm, lNorm fixed.Point26_6)
// C2Point represents a point that connects two stroke segments
// and holds the tangent, normal and radius of curvature
// of the trailing and leading segments in fixed point values.
type C2Point struct {
P, TTan, LTan, TNorm, LNorm fixed.Point26_6
RT, RL fixed.Int26_6
}
// JoinMode type to specify how segments join.
type JoinMode int32 //enums:enum
// JoinMode constants determine how stroke segments bridge the gap at a join
// ArcClip mode is like MiterClip applied to arcs, and is not part of the SVG2.0
// standard.
const (
Arc JoinMode = iota
ArcClip
Miter
MiterClip
Bevel
Round
)
const (
// Number of cubic beziers to approx half a circle
CubicsPerHalfCircle = 8
// 1/4 in fixed point
EpsilonFixed = fixed.Int26_6(16)
// fixed point t parameterization shift factor;
// (2^this)/64 is the max length of t for fixed.Int26_6
TStrokeShift = 14
)
// SetStroke set the parameters for stroking a line. width is the width of the line, miterlimit is the miter cutoff
// value for miter, arc, miterclip and arcClip joinModes. CapL and CapT are the capping functions for leading and trailing
// line ends. If one is nil, the other function is used at both ends. If both are nil, both ends are ButtCapped.
// gp is the gap function that determines how a gap on the convex side of two joining lines is filled. jm is the JoinMode
// for curve segments.
func (r *Stroker) SetStroke(width, miterLimit fixed.Int26_6, capL, capT CapFunc, gp GapFunc, jm JoinMode) {
r.U = width / 2
r.CapL = capL
r.CapT = capT
r.JoinMode = jm
r.JoinGap = gp
r.MLimit = (r.U * miterLimit) >> 6
if r.CapT == nil {
if r.CapL == nil {
r.CapT = ButtCap
} else {
r.CapT = r.CapL
}
}
if r.CapL == nil {
r.CapL = r.CapT
}
if gp == nil {
if r.JoinMode == Round {
r.JoinGap = RoundGap
} else {
r.JoinGap = FlatGap
}
}
}
// GapToCap is a utility that converts a CapFunc to GapFunc
func GapToCap(p Adder, a, eNorm fixed.Point26_6, gf GapFunc) {
p.Start(a.Add(eNorm))
gf(p, a, eNorm, Invert(eNorm))
p.Line(a.Sub(eNorm))
}
var (
// ButtCap caps lines with a straight line
ButtCap CapFunc = func(p Adder, a, eNorm fixed.Point26_6) {
p.Start(a.Add(eNorm))
p.Line(a.Sub(eNorm))
}
// SquareCap caps lines with a square which is slightly longer than ButtCap
SquareCap CapFunc = func(p Adder, a, eNorm fixed.Point26_6) {
tpt := a.Add(TurnStarboard90(eNorm))
p.Start(a.Add(eNorm))
p.Line(tpt.Add(eNorm))
p.Line(tpt.Sub(eNorm))
p.Line(a.Sub(eNorm))
}
// RoundCap caps lines with a half-circle
RoundCap CapFunc = func(p Adder, a, eNorm fixed.Point26_6) {
GapToCap(p, a, eNorm, RoundGap)
}
// CubicCap caps lines with a cubic bezier
CubicCap CapFunc = func(p Adder, a, eNorm fixed.Point26_6) {
GapToCap(p, a, eNorm, CubicGap)
}
// QuadraticCap caps lines with a quadratic bezier
QuadraticCap CapFunc = func(p Adder, a, eNorm fixed.Point26_6) {
GapToCap(p, a, eNorm, QuadraticGap)
}
// Gap functions
// FlatGap bridges miter-limit gaps with a straight line
FlatGap GapFunc = func(p Adder, a, tNorm, lNorm fixed.Point26_6) {
p.Line(a.Add(lNorm))
}
// RoundGap bridges miter-limit gaps with a circular arc
RoundGap GapFunc = func(p Adder, a, tNorm, lNorm fixed.Point26_6) {
StrokeArc(p, a, a.Add(tNorm), a.Add(lNorm), true, 0, 0, p.Line)
p.Line(a.Add(lNorm)) // just to be sure line joins cleanly,
// last pt in stoke arc may not be precisely s2
}
// CubicGap bridges miter-limit gaps with a cubic bezier
CubicGap GapFunc = func(p Adder, a, tNorm, lNorm fixed.Point26_6) {
p.CubeBezier(a.Add(tNorm).Add(TurnStarboard90(tNorm)), a.Add(lNorm).Add(TurnPort90(lNorm)), a.Add(lNorm))
}
// QuadraticGap bridges miter-limit gaps with a quadratic bezier
QuadraticGap GapFunc = func(p Adder, a, tNorm, lNorm fixed.Point26_6) {
c1, c2 := a.Add(tNorm).Add(TurnStarboard90(tNorm)), a.Add(lNorm).Add(TurnPort90(lNorm))
cm := c1.Add(c2).Mul(fixed.Int26_6(1 << 5))
p.QuadBezier(cm, a.Add(lNorm))
}
)
// StrokeArc strokes a circular arc by approximation with bezier curves
func StrokeArc(p Adder, a, s1, s2 fixed.Point26_6, clockwise bool, trimStart,
trimEnd fixed.Int26_6, firstPoint func(p fixed.Point26_6)) (ps1, ds1, ps2, ds2 fixed.Point26_6) {
// Approximate the circular arc using a set of cubic bezier curves by the method of
// L. Maisonobe, "Drawing an elliptical arc using polylines, quadratic
// or cubic Bezier curves", 2003
// https://www.spaceroots.org/documents/elllipse/elliptical-arc.pdf
// The method was simplified for circles.
theta1 := math32.Atan2(float32(s1.Y-a.Y), float32(s1.X-a.X))
theta2 := math32.Atan2(float32(s2.Y-a.Y), float32(s2.X-a.X))
if !clockwise {
for theta1 < theta2 {
theta1 += math32.Pi * 2
}
} else {
for theta2 < theta1 {
theta2 += math32.Pi * 2
}
}
deltaTheta := theta2 - theta1
if trimStart > 0 {
ds := (deltaTheta * float32(trimStart)) / float32(1<<TStrokeShift)
deltaTheta -= ds
theta1 += ds
}
if trimEnd > 0 {
ds := (deltaTheta * float32(trimEnd)) / float32(1<<TStrokeShift)
deltaTheta -= ds
}
segs := int(math32.Abs(deltaTheta)/(math32.Pi/CubicsPerHalfCircle)) + 1
dTheta := deltaTheta / float32(segs)
tde := math32.Tan(dTheta / 2)
alpha := fixed.Int26_6(math32.Sin(dTheta) * (math32.Sqrt(4+3*tde*tde) - 1) * (64.0 / 3.0)) // math32 is fun!
r := float32(Length(s1.Sub(a))) // Note r is *64
ldp := fixed.Point26_6{X: -fixed.Int26_6(r * math32.Sin(theta1)), Y: fixed.Int26_6(r * math32.Cos(theta1))}
ds1 = ldp
ps1 = fixed.Point26_6{X: a.X + ldp.Y, Y: a.Y - ldp.X}
firstPoint(ps1)
s1 = ps1
for i := 1; i <= segs; i++ {
eta := theta1 + dTheta*float32(i)
ds2 = fixed.Point26_6{X: -fixed.Int26_6(r * math32.Sin(eta)), Y: fixed.Int26_6(r * math32.Cos(eta))}
ps2 = fixed.Point26_6{X: a.X + ds2.Y, Y: a.Y - ds2.X} // Using deriviative to calc new pt, because circle
p1 := s1.Add(ldp.Mul(alpha))
p2 := ps2.Sub(ds2.Mul(alpha))
p.CubeBezier(p1, p2, ps2)
s1, ldp = ps2, ds2
}
return
}
// Joiner is called when two segments of a stroke are joined. it is exposed
// so that if can be wrapped to generate callbacks for the join points.
func (r *Stroker) Joiner(p C2Point) {
if p.P.X < 0 || p.P.Y < 0 {
return
}
crossProd := p.LNorm.X*p.TNorm.Y - p.TNorm.X*p.LNorm.Y
// stroke bottom edge, with the reverse of p
r.StrokeEdge(C2Point{P: p.P, TNorm: Invert(p.LNorm), LNorm: Invert(p.TNorm),
TTan: Invert(p.LTan), LTan: Invert(p.TTan), RT: -p.RL, RL: -p.RT}, -crossProd)
// stroke top edge
r.StrokeEdge(p, crossProd)
}
// StrokeEdge reduces code redundancy in the Joiner function by 2x since it handles
// the top and bottom edges. This function encodes most of the logic of how to
// handle joins between the given C2Point point p, and the end of the line.
func (r *Stroker) StrokeEdge(p C2Point, crossProd fixed.Int26_6) {
ra := &r.Filler
s1, s2 := p.P.Add(p.TNorm), p.P.Add(p.LNorm) // Bevel points for top leading and trailing
ra.Start(s1)
if crossProd > -EpsilonFixed*EpsilonFixed { // Almost co-linear or convex
ra.Line(s2)
return // No need to fill any gaps
}
var ct, cl fixed.Point26_6 // Center of curvature trailing, leading
var rt, rl fixed.Int26_6 // Radius of curvature trailing, leading
// Adjust radiuses for stroke width
if r.JoinMode == Arc || r.JoinMode == ArcClip {
// Find centers of radius of curvature and adjust the radius to be drawn
// by half the stroke width.
if p.RT != 0 {
if p.RT > 0 {
ct = p.P.Add(ToLength(TurnPort90(p.TTan), p.RT))
rt = p.RT - r.U
} else {
ct = p.P.Sub(ToLength(TurnPort90(p.TTan), -p.RT))
rt = -p.RT + r.U
}
if rt < 0 {
rt = 0
}
}
if p.RL != 0 {
if p.RL > 0 {
cl = p.P.Add(ToLength(TurnPort90(p.LTan), p.RL))
rl = p.RL - r.U
} else {
cl = p.P.Sub(ToLength(TurnPort90(p.LTan), -p.RL))
rl = -p.RL + r.U
}
if rl < 0 {
rl = 0
}
}
}
if r.JoinMode == MiterClip || r.JoinMode == Miter ||
// Arc or ArcClip with 0 tRadCurve and 0 lRadCurve is treated the same as a
// Miter or MiterClip join, resp.
((r.JoinMode == Arc || r.JoinMode == ArcClip) && (rt == 0 && rl == 0)) {
xt := CalcIntersect(s1.Sub(p.TTan), s1, s2, s2.Sub(p.LTan))
xa := xt.Sub(p.P)
if Length(xa) < r.MLimit { // within miter limit
ra.Line(xt)
ra.Line(s2)
return
}
if r.JoinMode == MiterClip || (r.JoinMode == ArcClip) {
//Projection of tNorm onto xa
tProjP := xa.Mul(fixed.Int26_6((DotProd(xa, p.TNorm) << 6) / DotProd(xa, xa)))
projLen := Length(tProjP)
if r.MLimit > projLen { // the miter limit line is past the bevel point
// t is the fraction shifted by tStrokeShift to scale the vectors from the bevel point
// to the line intersection, so that they abbut the miter limit line.
tiLength := Length(xa)
sx1, sx2 := xt.Sub(s1), xt.Sub(s2)
t := (r.MLimit - projLen) << TStrokeShift / (tiLength - projLen)
tx := ToLength(sx1, t*Length(sx1)>>TStrokeShift)
lx := ToLength(sx2, t*Length(sx2)>>TStrokeShift)
vx := ToLength(xa, t*Length(xa)>>TStrokeShift)
s1p, _, ap := s1.Add(tx), s2.Add(lx), p.P.Add(vx)
gLen := Length(ap.Sub(s1p))
ra.Line(s1p)
r.JoinGap(ra, ap, ToLength(TurnPort90(p.TTan), gLen), ToLength(TurnPort90(p.LTan), gLen))
ra.Line(s2)
return
}
} // Fallthrough
} else if r.JoinMode == Arc || r.JoinMode == ArcClip {
// Test for cases of a bezier meeting line, an line meeting a bezier,
// or a bezier meeting a bezier. (Line meeting line is handled above.)
switch {
case rt == 0: // rl != 0, because one must be non-zero as checked above
xt, intersect := RayCircleIntersection(s1.Add(p.TTan), s1, cl, rl)
if intersect {
ray1, ray2 := xt.Sub(cl), s2.Sub(cl)
clockwise := (ray1.X*ray2.Y > ray1.Y*ray2.X) // Sign of xprod
if Length(p.P.Sub(xt)) < r.MLimit { // within miter limit
StrokeArc(ra, cl, xt, s2, clockwise, 0, 0, ra.Line)
ra.Line(s2)
return
}
// Not within miter limit line
if r.JoinMode == ArcClip { // Scale bevel points towards xt, and call gap func
xa := xt.Sub(p.P)
//Projection of tNorm onto xa
tProjP := xa.Mul(fixed.Int26_6((DotProd(xa, p.TNorm) << 6) / DotProd(xa, xa)))
projLen := Length(tProjP)
if r.MLimit > projLen { // the miter limit line is past the bevel point
// t is the fraction shifted by tStrokeShift to scale the line or arc from the bevel point
// to the line intersection, so that they abbut the miter limit line.
sx1 := xt.Sub(s1) //, xt.Sub(s2)
t := fixed.Int26_6(1<<TStrokeShift) - ((r.MLimit - projLen) << TStrokeShift / (Length(xa) - projLen))
tx := ToLength(sx1, t*Length(sx1)>>TStrokeShift)
s1p := xt.Sub(tx)
ra.Line(s1p)
sp1, ds1, ps2, _ := StrokeArc(ra, cl, xt, s2, clockwise, t, 0, ra.Start)
ra.Start(s1p)
// calc gap center as pt where -tnorm and line perp to midcoord
midP := sp1.Add(s1p).Mul(fixed.Int26_6(1 << 5)) // midpoint
midLine := TurnPort90(midP.Sub(sp1))
if midLine.X*midLine.X+midLine.Y*midLine.Y > EpsilonFixed { // if midline is zero, CalcIntersect is invalid
ap := CalcIntersect(s1p, s1p.Sub(p.TNorm), midLine.Add(midP), midP)
gLen := Length(ap.Sub(s1p))
if clockwise {
ds1 = Invert(ds1)
}
r.JoinGap(ra, ap, ToLength(TurnPort90(p.TTan), gLen), ToLength(TurnStarboard90(ds1), gLen))
}
ra.Line(sp1)
ra.Start(ps2)
ra.Line(s2)
return
}
//Bevel points not past miter limit: fallthrough
}
}
case rl == 0: // rt != 0, because one must be non-zero as checked above
xt, intersect := RayCircleIntersection(s2.Sub(p.LTan), s2, ct, rt)
if intersect {
ray1, ray2 := s1.Sub(ct), xt.Sub(ct)
clockwise := ray1.X*ray2.Y > ray1.Y*ray2.X
if Length(p.P.Sub(xt)) < r.MLimit { // within miter limit
StrokeArc(ra, ct, s1, xt, clockwise, 0, 0, ra.Line)
ra.Line(s2)
return
}
// Not within miter limit line
if r.JoinMode == ArcClip { // Scale bevel points towards xt, and call gap func
xa := xt.Sub(p.P)
//Projection of lNorm onto xa
lProjP := xa.Mul(fixed.Int26_6((DotProd(xa, p.LNorm) << 6) / DotProd(xa, xa)))
projLen := Length(lProjP)
if r.MLimit > projLen { // The miter limit line is past the bevel point,
// t is the fraction to scale the line or arc from the bevel point
// to the line intersection, so that they abbut the miter limit line.
sx2 := xt.Sub(s2)
t := fixed.Int26_6(1<<TStrokeShift) - ((r.MLimit - projLen) << TStrokeShift / (Length(xa) - projLen))
lx := ToLength(sx2, t*Length(sx2)>>TStrokeShift)
s2p := xt.Sub(lx)
_, _, ps2, ds2 := StrokeArc(ra, ct, s1, xt, clockwise, 0, t, ra.Line)
// calc gap center as pt where -lnorm and line perp to midcoord
midP := s2p.Add(ps2).Mul(fixed.Int26_6(1 << 5)) // midpoint
midLine := TurnStarboard90(midP.Sub(ps2))
if midLine.X*midLine.X+midLine.Y*midLine.Y > EpsilonFixed { // if midline is zero, CalcIntersect is invalid
ap := CalcIntersect(midP, midLine.Add(midP), s2p, s2p.Sub(p.LNorm))
gLen := Length(ap.Sub(ps2))
if clockwise {
ds2 = Invert(ds2)
}
r.JoinGap(ra, ap, ToLength(TurnStarboard90(ds2), gLen), ToLength(TurnPort90(p.LTan), gLen))
}
ra.Line(s2)
return
}
//Bevel points not past miter limit: fallthrough
}
}
default: // Both rl != 0 and rt != 0 as checked above
xt1, xt2, gIntersect := CircleCircleIntersection(ct, cl, rt, rl)
xt, intersect := ClosestPortside(s1, s2, xt1, xt2, gIntersect)
if intersect {
ray1, ray2 := s1.Sub(ct), xt.Sub(ct)
clockwiseT := (ray1.X*ray2.Y > ray1.Y*ray2.X)
ray1, ray2 = xt.Sub(cl), s2.Sub(cl)
clockwiseL := ray1.X*ray2.Y > ray1.Y*ray2.X
if Length(p.P.Sub(xt)) < r.MLimit { // within miter limit
StrokeArc(ra, ct, s1, xt, clockwiseT, 0, 0, ra.Line)
StrokeArc(ra, cl, xt, s2, clockwiseL, 0, 0, ra.Line)
ra.Line(s2)
return
}
if r.JoinMode == ArcClip { // Scale bevel points towards xt, and call gap func
xa := xt.Sub(p.P)
//Projection of lNorm onto xa
lProjP := xa.Mul(fixed.Int26_6((DotProd(xa, p.LNorm) << 6) / DotProd(xa, xa)))
projLen := Length(lProjP)
if r.MLimit > projLen { // The miter limit line is past the bevel point,
// t is the fraction to scale the line or arc from the bevel point
// to the line intersection, so that they abbut the miter limit line.
t := fixed.Int26_6(1<<TStrokeShift) - ((r.MLimit - projLen) << TStrokeShift / (Length(xa) - projLen))
_, _, ps1, ds1 := StrokeArc(ra, ct, s1, xt, clockwiseT, 0, t, r.Filler.Line)
ps2, ds2, fs2, _ := StrokeArc(ra, cl, xt, s2, clockwiseL, t, 0, ra.Start)
midP := ps1.Add(ps2).Mul(fixed.Int26_6(1 << 5)) // midpoint
midLine := TurnStarboard90(midP.Sub(ps1))
ra.Start(ps1)
if midLine.X*midLine.X+midLine.Y*midLine.Y > EpsilonFixed { // if midline is zero, CalcIntersect is invalid
if clockwiseT {
ds1 = Invert(ds1)
}
if clockwiseL {
ds2 = Invert(ds2)
}
ap := CalcIntersect(midP, midLine.Add(midP), ps2, ps2.Sub(TurnStarboard90(ds2)))
gLen := Length(ap.Sub(ps2))
r.JoinGap(ra, ap, ToLength(TurnStarboard90(ds1), gLen), ToLength(TurnStarboard90(ds2), gLen))
}
ra.Line(ps2)
ra.Start(fs2)
ra.Line(s2)
return
}
}
}
// fallthrough to final JoinGap
}
}
r.JoinGap(ra, p.P, p.TNorm, p.LNorm)
ra.Line(s2)
}
// Stop a stroked line. The line will close
// is isClosed is true. Otherwise end caps will
// be drawn at both ends.
func (r *Stroker) Stop(isClosed bool) {
if !r.InStroke {
return
}
rf := &r.Filler
if isClosed {
if r.FirstP.P != rf.A {
r.Line(r.FirstP.P)
}
a := rf.A
r.FirstP.TNorm = r.LeadPoint.TNorm
r.FirstP.RT = r.LeadPoint.RT
r.FirstP.TTan = r.LeadPoint.TTan
rf.Start(r.FirstP.P.Sub(r.FirstP.TNorm))
rf.Line(a.Sub(r.Ln))
rf.Start(a.Add(r.Ln))
rf.Line(r.FirstP.P.Add(r.FirstP.TNorm))
r.Joiner(r.FirstP)
r.FirstP.BlackWidowMark(rf)
} else {
a := rf.A
rf.Start(r.LeadPoint.P.Sub(r.LeadPoint.TNorm))
rf.Line(a.Sub(r.Ln))
rf.Start(a.Add(r.Ln))
rf.Line(r.LeadPoint.P.Add(r.LeadPoint.TNorm))
r.CapL(rf, r.LeadPoint.P, r.LeadPoint.TNorm)
r.CapT(rf, r.FirstP.P, Invert(r.FirstP.LNorm))
}
r.InStroke = false
}
// QuadBezier starts a stroked quadratic bezier.
func (r *Stroker) QuadBezier(b, c fixed.Point26_6) {
r.QuadBezierf(r, b, c)
}
// CubeBezier starts a stroked quadratic bezier.
func (r *Stroker) CubeBezier(b, c, d fixed.Point26_6) {
r.CubeBezierf(r, b, c, d)
}
// QuadBezierf calcs end curvature of beziers
func (r *Stroker) QuadBezierf(s Raster, b, c fixed.Point26_6) {
r.TrailPoint = r.LeadPoint
r.CalcEndCurvature(r.A, b, c, c, b, r.A, fixed.Int52_12(2<<12), DoCalcCurvature(s))
r.QuadBezierF(s, b, c)
r.A = c
}
// DoCalcCurvature determines if calculation of the end curvature is required
// depending on the raster type and JoinMode
func DoCalcCurvature(r Raster) bool {
switch q := r.(type) {
case *Filler:
return false // never for filler
case *Stroker:
return (q.JoinMode == Arc || q.JoinMode == ArcClip)
case *Dasher:
return (q.JoinMode == Arc || q.JoinMode == ArcClip)
default:
return true // Better safe than sorry if another raster type is used
}
}
func (r *Stroker) CubeBezierf(sgm Raster, b, c, d fixed.Point26_6) {
if (r.A == b && c == d) || (r.A == b && b == c) || (c == b && d == c) {
sgm.Line(d)
return
}
r.TrailPoint = r.LeadPoint
// Only calculate curvature if stroking or and using arc or arc-clip
doCalcCurve := DoCalcCurvature(sgm)
const dm = fixed.Int52_12((3 << 12) / 2)
switch {
// b != c, and c != d see above
case r.A == b:
r.CalcEndCurvature(b, c, d, d, c, b, dm, doCalcCurve)
// b != a, and b != c, see above
case c == d:
r.CalcEndCurvature(r.A, b, c, c, b, r.A, dm, doCalcCurve)
default:
r.CalcEndCurvature(r.A, b, c, d, c, b, dm, doCalcCurve)
}
r.CubeBezierF(sgm, b, c, d)
r.A = d
}
// Line adds a line segment to the rasterizer
func (r *Stroker) Line(b fixed.Point26_6) {
r.LineSeg(r, b)
}
// LineSeg is called by both the Stroker and Dasher
func (r *Stroker) LineSeg(sgm Raster, b fixed.Point26_6) {
r.TrailPoint = r.LeadPoint
ba := b.Sub(r.A)
if ba.X == 0 && ba.Y == 0 { // a == b, line is degenerate
if r.TrailPoint.TTan.X != 0 || r.TrailPoint.TTan.Y != 0 {
ba = r.TrailPoint.TTan // Use last tangent for seg tangent
} else { // Must be on top of last moveto; set ba to X axis unit vector
ba = fixed.Point26_6{X: 1 << 6, Y: 0}
}
}
bnorm := TurnPort90(ToLength(ba, r.U))
r.TrailPoint.LTan = ba
r.LeadPoint.TTan = ba
r.TrailPoint.LNorm = bnorm
r.LeadPoint.TNorm = bnorm
r.TrailPoint.RL = 0.0
r.LeadPoint.RT = 0.0
r.TrailPoint.P = r.A
r.LeadPoint.P = b
sgm.JoinF()
sgm.LineF(b)
r.A = b
}
// LineF is for intra-curve lines. It is required for the Rasterizer interface
// so that if the line is being stroked or dash stroked, different actions can be
// taken.
func (r *Stroker) LineF(b fixed.Point26_6) {
// b is either an intra-segment value, or
// the end of the segment.
var bnorm fixed.Point26_6
a := r.A // Hold a since r.a is going to change during stroke operation
if b == r.LeadPoint.P { // End of segment
bnorm = r.LeadPoint.TNorm // Use more accurate leadPoint tangent
} else {
bnorm = TurnPort90(ToLength(b.Sub(a), r.U)) // Intra segment normal
}
ra := &r.Filler
ra.Start(b.Sub(bnorm))
ra.Line(a.Sub(r.Ln))
ra.Start(a.Add(r.Ln))
ra.Line(b.Add(bnorm))
r.A = b
r.Ln = bnorm
}
// Start iniitates a stroked path
func (r *Stroker) Start(a fixed.Point26_6) {
r.InStroke = false
r.Filler.Start(a)
}
// CalcEndCurvature calculates the radius of curvature given the control points
// of a bezier curve.
// It is a low level function exposed for the purposes of callbacks
// and debugging.
func (r *Stroker) CalcEndCurvature(p0, p1, p2, q0, q1, q2 fixed.Point26_6,
dm fixed.Int52_12, calcRadCuve bool) {
r.TrailPoint.P = p0
r.LeadPoint.P = q0
r.TrailPoint.LTan = p1.Sub(p0)
r.LeadPoint.TTan = q0.Sub(q1)
r.TrailPoint.LNorm = TurnPort90(ToLength(r.TrailPoint.LTan, r.U))
r.LeadPoint.TNorm = TurnPort90(ToLength(r.LeadPoint.TTan, r.U))
if calcRadCuve {
r.TrailPoint.RL = RadCurvature(p0, p1, p2, dm)
r.LeadPoint.RT = -RadCurvature(q0, q1, q2, dm)
} else {
r.TrailPoint.RL = 0
r.LeadPoint.RT = 0
}
}
func (r *Stroker) JoinF() {
if !r.InStroke {
r.InStroke = true
r.FirstP = r.TrailPoint
} else {
ra := &r.Filler
tl := r.TrailPoint.P.Sub(r.TrailPoint.TNorm)
th := r.TrailPoint.P.Add(r.TrailPoint.TNorm)
if r.A != r.TrailPoint.P || r.Ln != r.TrailPoint.TNorm {
a := r.A
ra.Start(tl)
ra.Line(a.Sub(r.Ln))
ra.Start(a.Add(r.Ln))
ra.Line(th)
}
r.Joiner(r.TrailPoint)
r.TrailPoint.BlackWidowMark(ra)
}
r.Ln = r.TrailPoint.LNorm
r.A = r.TrailPoint.P
}
// BlackWidowMark handles a gap in a stroke that can occur when a line end is too close
// to a segment to segment join point. Although it is only required in those cases,
// at this point, no code has been written to properly detect when it is needed,
// so for now it just draws by default.
func (jp *C2Point) BlackWidowMark(ra Adder) {
xprod := jp.TNorm.X*jp.LNorm.Y - jp.TNorm.Y*jp.LNorm.X
if xprod > EpsilonFixed*EpsilonFixed {
tl := jp.P.Sub(jp.TNorm)
ll := jp.P.Sub(jp.LNorm)
ra.Start(jp.P)
ra.Line(tl)
ra.Line(ll)
ra.Line(jp.P)
} else if xprod < -EpsilonFixed*EpsilonFixed {
th := jp.P.Add(jp.TNorm)
lh := jp.P.Add(jp.LNorm)
ra.Start(jp.P)
ra.Line(lh)
ra.Line(th)
ra.Line(jp.P)
}
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package rasterx
import (
"fmt"
"image"
"image/color"
"image/draw"
_ "image/jpeg" // load image formats for users of the API
_ "image/png"
"cogentcore.org/core/colors"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint/render"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/shaped"
"cogentcore.org/core/text/shaped/shapers/shapedgt"
"cogentcore.org/core/text/textpos"
"github.com/cogentcore/typesetting/font"
"github.com/cogentcore/typesetting/font/opentype"
"github.com/cogentcore/typesetting/shaping"
_ "golang.org/x/image/tiff" // load image formats for users of the API
)
// RenderText rasterizes the given Text
func (rs *Renderer) RenderText(txt *render.Text) {
// pr := profile.Start("RenderText")
rs.TextLines(&txt.Context, txt.Text, txt.Position)
// pr.End()
}
// TextLines rasterizes the given shaped.Lines.
// The text will be drawn starting at the start pixel position, which specifies the
// left baseline location of the first text item..
func (rs *Renderer) TextLines(ctx *render.Context, lns *shaped.Lines, pos math32.Vector2) {
m := ctx.Cumulative
identity := m == math32.Identity2()
off := pos.Add(lns.Offset)
clip := ctx.Bounds.Rect.ToRect()
if clip.Empty() { // all clipped (the scanner does not clip with an empty clip)
return
}
rs.Scanner.SetClip(clip)
// tbb := lns.Bounds.Translate(off)
// rs.StrokeBounds(ctx, tbb, colors.Red)
clr := colors.Uniform(lns.Color)
for li := range lns.Lines {
ln := &lns.Lines[li]
rs.TextLine(ctx, ln, lns, clr, off, identity)
}
}
// TextLine rasterizes the given shaped.Line.
func (rs *Renderer) TextLine(ctx *render.Context, ln *shaped.Line, lns *shaped.Lines, clr image.Image, off math32.Vector2, identity bool) {
start := off.Add(ln.Offset)
off = start
// tbb := ln.Bounds.Translate(off)
// rs.StrokeBounds(ctx, tbb, colors.Blue)
for ri := range ln.Runs {
run := ln.Runs[ri].(*shapedgt.Run)
rs.TextRunRegions(ctx, run, ln, lns, off)
if run.Direction.IsVertical() {
off.Y += run.Advance()
} else {
off.X += run.Advance()
}
}
off = start
for ri := range ln.Runs {
run := ln.Runs[ri].(*shapedgt.Run)
rs.TextRun(ctx, run, ln, lns, clr, off, identity)
if run.Direction.IsVertical() {
off.Y += run.Advance()
} else {
off.X += run.Advance()
}
}
}
// TextRegionFill fills given regions within run with given fill color.
func (rs *Renderer) TextRegionFill(ctx *render.Context, run *shapedgt.Run, off math32.Vector2, fill image.Image, ranges []textpos.Range) {
if fill == nil {
return
}
for _, sel := range ranges {
rsel := sel.Intersect(run.Runes())
if rsel.Len() == 0 {
continue
}
fi := run.FirstGlyphAt(rsel.Start)
li := run.LastGlyphAt(rsel.End - 1)
if fi >= 0 && li >= fi {
sbb := run.GlyphRegionBounds(fi, li).Canon()
rs.FillBounds(ctx, sbb.Translate(off), fill)
}
}
}
// TextRunRegions draws region fills for given run.
func (rs *Renderer) TextRunRegions(ctx *render.Context, run *shapedgt.Run, ln *shaped.Line, lns *shaped.Lines, off math32.Vector2) {
// dir := run.Direction
rbb := run.MaxBounds.Translate(off)
if run.Background != nil {
rs.FillBounds(ctx, rbb, run.Background)
}
rs.TextRegionFill(ctx, run, off, lns.HighlightColor, ln.Highlights)
rs.TextRegionFill(ctx, run, off, lns.SelectionColor, ln.Selections)
}
// TextRun rasterizes the given text run into the output image using the
// font face set in the shaping.
// The text will be drawn starting at the start pixel position.
func (rs *Renderer) TextRun(ctx *render.Context, run *shapedgt.Run, ln *shaped.Line, lns *shaped.Lines, clr image.Image, off math32.Vector2, identity bool) {
// dir := run.Direction
rbb := run.MaxBounds.Translate(off)
fill := clr
if run.FillColor != nil {
fill = run.FillColor
}
stroke := run.StrokeColor
fsz := math32.FromFixed(run.Size)
lineW := max(fsz/16, 1) // 1 at 16, bigger if biggerr
if run.Math.Path != nil {
rs.Path.Clear()
PathToRasterx(&rs.Path, run.Math.Path, ctx.Cumulative, off)
rf := &rs.Raster.Filler
rf.SetWinding(true)
rf.SetColor(fill)
rs.Path.AddTo(rf)
rf.Draw()
rf.Clear()
return
}
sty := run.Font.Style(&ctx.Style.Text)
// https://en.wikipedia.org/wiki/Subscript_and_superscript: latex does -.14 sub, .25 super
// others often use -.33 and .33
switch sty.Special {
case rich.Super:
off.Y -= 0.25 * fsz
case rich.Sub:
off.Y += 0.14 * fsz
}
if run.Decoration.HasFlag(rich.Underline) || run.Decoration.HasFlag(rich.DottedUnderline) {
dash := []float32{2, 2}
if run.Decoration.HasFlag(rich.Underline) {
dash = nil
}
if run.Direction.IsVertical() {
} else {
dec := off.Y + 3
rs.StrokeTextLine(ctx, math32.Vec2(rbb.Min.X, dec), math32.Vec2(rbb.Max.X, dec), lineW, fill, dash)
}
}
if run.Decoration.HasFlag(rich.Overline) {
if run.Direction.IsVertical() {
} else {
dec := off.Y - 0.7*rbb.Size().Y
rs.StrokeTextLine(ctx, math32.Vec2(rbb.Min.X, dec), math32.Vec2(rbb.Max.X, dec), lineW, fill, nil)
}
}
for gi := range run.Glyphs {
g := &run.Glyphs[gi]
pos := off.Add(math32.Vec2(math32.FromFixed(g.XOffset), -math32.FromFixed(g.YOffset)))
bb := run.GlyphBoundsBox(g).Translate(off)
// rs.StrokeBounds(ctx, bb, colors.Yellow)
if data, ok := run.Face.GlyphDataSVG(g.GlyphID); ok {
rs.GlyphSVG(ctx, run, g, data.Source, bb, pos, identity)
} else if data, ok := run.Face.GlyphDataBitmap(g.GlyphID); ok {
rs.GlyphBitmap(ctx, run, g, data, fill, stroke, bb, pos, identity)
} else if data, ok := run.Face.GlyphDataOutline(g.GlyphID); ok {
rs.GlyphOutline(ctx, run, g, data, fill, stroke, bb, pos, identity)
} else {
fmt.Printf("unrecognized glyph data for glyphID: %v, face: %v\n", g.GlyphID, run.Face.Describe().Family)
}
if run.Direction.IsVertical() {
off.Y -= math32.FromFixed(g.Advance)
} else {
off.X += math32.FromFixed(g.Advance)
}
}
if run.Decoration.HasFlag(rich.LineThrough) {
if run.Direction.IsVertical() {
} else {
dec := off.Y - 0.2*rbb.Size().Y
rs.StrokeTextLine(ctx, math32.Vec2(rbb.Min.X, dec), math32.Vec2(rbb.Max.X, dec), lineW, fill, nil)
}
}
}
func (rs *Renderer) GlyphOutline(ctx *render.Context, run *shapedgt.Run, g *shaping.Glyph, outline font.GlyphOutline, fill, stroke image.Image, bb math32.Box2, pos math32.Vector2, identity bool) {
scale := math32.FromFixed(run.Size) / float32(run.Face.Upem())
x := pos.X // note: has offsets already added
y := pos.Y
if len(outline.Segments) == 0 {
// fmt.Println("nil path:", g.GlyphID)
return
}
wd := math32.FromFixed(g.Width)
// todo: should be conditional on run.Direction
xadv := math32.Abs(math32.FromFixed(g.Advance))
if wd > xadv {
if run.Font.Style(&ctx.Style.Text).Family == rich.Monospace {
scale *= 0.95 * xadv / wd
}
}
if UseGlyphCache && identity && stroke == nil {
mask, pi := theGlyphCache.Glyph(run.Face, g, outline, scale, pos)
if mask != nil {
rs.GlyphMask(ctx, run, g, fill, stroke, bb, pi, mask)
return
}
}
rs.Path.Clear()
m := ctx.Cumulative
for _, s := range outline.Segments {
p0 := m.MulPoint(math32.Vec2(s.Args[0].X*scale+x, -s.Args[0].Y*scale+y))
switch s.Op {
case opentype.SegmentOpMoveTo:
rs.Path.Start(p0.ToFixed())
case opentype.SegmentOpLineTo:
rs.Path.Line(p0.ToFixed())
case opentype.SegmentOpQuadTo:
p1 := m.MulPoint(math32.Vec2(s.Args[1].X*scale+x, -s.Args[1].Y*scale+y))
rs.Path.QuadBezier(p0.ToFixed(), p1.ToFixed())
case opentype.SegmentOpCubeTo:
p1 := m.MulPoint(math32.Vec2(s.Args[1].X*scale+x, -s.Args[1].Y*scale+y))
p2 := m.MulPoint(math32.Vec2(s.Args[2].X*scale+x, -s.Args[2].Y*scale+y))
rs.Path.CubeBezier(p0.ToFixed(), p1.ToFixed(), p2.ToFixed())
}
}
rs.Path.Stop(true)
if fill != nil {
rf := &rs.Raster.Filler
rf.SetWinding(true)
rf.SetColor(fill)
rs.Path.AddTo(rf)
rf.Draw()
rf.Clear()
}
if stroke != nil {
sw := math32.FromFixed(run.Size) / 32.0 // scale with font size
rs.Raster.SetStroke(
math32.ToFixed(sw),
math32.ToFixed(10),
ButtCap, nil, nil, Miter, nil, 0)
rs.Path.AddTo(rs.Raster)
rs.Raster.SetColor(stroke)
rs.Raster.Draw()
rs.Raster.Clear()
}
rs.Path.Clear()
}
func (rs *Renderer) GlyphMask(ctx *render.Context, run *shapedgt.Run, g *shaping.Glyph, fill, stroke image.Image, bb math32.Box2, pos image.Point, mask *image.Alpha) error {
mbb := mask.Bounds()
dbb := mbb.Add(pos)
ibb := dbb.Intersect(ctx.Bounds.Rect.ToRect())
if ibb == (image.Rectangle{}) {
return nil
}
mp := ibb.Min.Sub(dbb.Min)
draw.DrawMask(rs.image, ibb, fill, image.Point{}, mask, mp, draw.Over)
return nil
}
// StrokeBounds strokes a bounding box in the given color. Useful for debugging.
func (rs *Renderer) StrokeBounds(ctx *render.Context, bb math32.Box2, clr color.Color) {
rs.Raster.SetStroke(
math32.ToFixed(1),
math32.ToFixed(10),
ButtCap, nil, nil, Miter,
nil, 0)
rs.Raster.SetColor(colors.Uniform(clr))
m := ctx.Cumulative
rs.Raster.Start(m.MulPoint(math32.Vec2(bb.Min.X, bb.Min.Y)).ToFixed())
rs.Raster.Line(m.MulPoint(math32.Vec2(bb.Max.X, bb.Min.Y)).ToFixed())
rs.Raster.Line(m.MulPoint(math32.Vec2(bb.Max.X, bb.Max.Y)).ToFixed())
rs.Raster.Line(m.MulPoint(math32.Vec2(bb.Min.X, bb.Max.Y)).ToFixed())
rs.Raster.Stop(true)
rs.Raster.Draw()
rs.Raster.Clear()
}
// StrokeTextLine strokes a line for text decoration.
func (rs *Renderer) StrokeTextLine(ctx *render.Context, sp, ep math32.Vector2, width float32, clr image.Image, dash []float32) {
m := ctx.Cumulative
sp = m.MulPoint(sp)
ep = m.MulPoint(ep)
width *= MeanScale(m)
rs.Raster.SetStroke(
math32.ToFixed(width),
math32.ToFixed(10),
ButtCap, nil, nil, Miter,
dash, 0)
rs.Raster.SetColor(clr)
rs.Raster.Start(sp.ToFixed())
rs.Raster.Line(ep.ToFixed())
rs.Raster.Stop(false)
rs.Raster.Draw()
rs.Raster.Clear()
}
// FillBounds fills a bounding box in the given color.
func (rs *Renderer) FillBounds(ctx *render.Context, bb math32.Box2, clr image.Image) {
rf := &rs.Raster.Filler
rf.SetColor(clr)
m := ctx.Cumulative
rf.Start(m.MulPoint(math32.Vec2(bb.Min.X, bb.Min.Y)).ToFixed())
rf.Line(m.MulPoint(math32.Vec2(bb.Max.X, bb.Min.Y)).ToFixed())
rf.Line(m.MulPoint(math32.Vec2(bb.Max.X, bb.Max.Y)).ToFixed())
rf.Line(m.MulPoint(math32.Vec2(bb.Min.X, bb.Max.Y)).ToFixed())
rf.Stop(true)
rf.Draw()
rf.Clear()
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package rasterx
import (
"bytes"
"image"
"image/color"
"image/draw"
"cogentcore.org/core/colors"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint/render"
"cogentcore.org/core/text/shaped/shapers/shapedgt"
"github.com/cogentcore/typesetting/font"
"github.com/cogentcore/typesetting/shaping"
scale "golang.org/x/image/draw"
)
var bitmapGlyphCache map[glyphKey]*image.RGBA
func (rs *Renderer) GlyphBitmap(ctx *render.Context, run *shapedgt.Run, g *shaping.Glyph, bitmap font.GlyphBitmap, fill, stroke image.Image, bb math32.Box2, pos math32.Vector2, identity bool) error {
if bitmapGlyphCache == nil {
bitmapGlyphCache = make(map[glyphKey]*image.RGBA)
}
// todo: this needs serious work to function with transforms
x := pos.X
y := pos.Y
top := y - math32.FromFixed(g.YBearing)
bottom := top - math32.FromFixed(g.Height)
right := x + math32.FromFixed(g.Width)
dbb := image.Rect(int(x), int(top), int(right), int(bottom))
ibb := dbb.Intersect(ctx.Bounds.Rect.ToRect())
if ibb == (image.Rectangle{}) {
return nil
}
fam := run.Font.Style(&ctx.Style.Text).Family
size := dbb.Size()
gk := glyphKey{gid: g.GlyphID, sx: uint8(size.Y / 256), sy: uint8(size.Y % 256), ox: uint8(fam)}
img, ok := bitmapGlyphCache[gk]
if !ok {
img = image.NewRGBA(image.Rectangle{Max: size})
switch bitmap.Format {
case font.BlackAndWhite:
rec := image.Rect(0, 0, bitmap.Width, bitmap.Height)
sub := image.NewPaletted(rec, color.Palette{color.Transparent, colors.ToUniform(fill)})
for i := range sub.Pix {
sub.Pix[i] = bitAt(bitmap.Data, i)
}
// note: NearestNeighbor is better than bilinear
scale.NearestNeighbor.Scale(img, img.Bounds(), sub, sub.Bounds(), draw.Src, nil)
case font.JPG, font.PNG, font.TIFF:
pix, _, err := image.Decode(bytes.NewReader(bitmap.Data))
if err != nil {
return err
}
scale.NearestNeighbor.Scale(img, img.Bounds(), pix, pix.Bounds(), draw.Src, nil)
}
bitmapGlyphCache[gk] = img
}
sp := ibb.Min.Sub(dbb.Min)
draw.Draw(rs.image, ibb, img, sp, draw.Over)
if bitmap.Outline != nil {
rs.GlyphOutline(ctx, run, g, *bitmap.Outline, fill, stroke, bb, pos, identity)
}
return nil
}
// bitAt returns the bit at the given index in the byte slice.
func bitAt(b []byte, i int) byte {
return (b[i/8] >> (7 - i%8)) & 1
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package rasterx
import (
"bytes"
"fmt"
"image"
"image/draw"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint/render"
"cogentcore.org/core/svg"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/shaped/shapers/shapedgt"
"github.com/cogentcore/typesetting/shaping"
)
var svgGlyphCache map[glyphKey]image.Image
func (rs *Renderer) GlyphSVG(ctx *render.Context, run *shapedgt.Run, g *shaping.Glyph, svgCmds []byte, bb math32.Box2, pos math32.Vector2, identity bool) {
if svgGlyphCache == nil {
svgGlyphCache = make(map[glyphKey]image.Image)
}
size := float32(run.Size.Floor())
fam := run.Font.Style(&ctx.Style.Text).Family
desc := run.Output.LineBounds.Descent
fsize := math32.Vec2(size, size)
gk := glyphKey{gid: g.GlyphID, sx: uint8(int(size) / 256), sy: uint8(int(size) % 256), ox: uint8(fam)}
img, ok := svgGlyphCache[gk]
if !ok {
hadv := run.Face.HorizontalAdvance(g.GlyphID)
scale := size / hadv
if fam == rich.Monospace {
scale *= 0.8
}
sv := svg.NewSVG(fsize)
sv.GroupFilter = fmt.Sprintf("glyph%d", g.GlyphID) // critical: for filtering items with many glyphs
b := bytes.NewBuffer(svgCmds)
err := sv.ReadXML(b)
errors.Log(err)
sv.Translate.Y = size + math32.FromFixed(desc)
sv.Scale = scale
sv.Root.ViewBox.Size.SetScalar(size)
img = sv.RenderImage()
svgGlyphCache[gk] = img
}
left := int(math32.Round(pos.X + math32.FromFixed(g.XBearing)))
top := int(math32.Round(pos.Y - math32.FromFixed(g.YBearing+desc) - fsize.Y))
dbb := img.Bounds().Add(image.Point{left, top})
ibb := dbb.Intersect(ctx.Bounds.Rect.ToRect())
if ibb == (image.Rectangle{}) {
return
}
sp := ibb.Min.Sub(dbb.Min)
draw.Draw(rs.image, ibb, img, sp, draw.Over)
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package renderers sets the standard renderers of the platform for the
// paint package: images, SVG, and PDF (importing it is enough).
package renderers
import (
"cogentcore.org/core/paint"
"cogentcore.org/core/paint/renderers/pdfrender"
"cogentcore.org/core/paint/renderers/svgrender"
_ "cogentcore.org/core/text/shaped/shapers"
)
func init() {
paint.NewSVGRenderer = svgrender.New
paint.NewPDFRenderer = pdfrender.New
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !js
package renderers
import (
"cogentcore.org/core/paint"
"cogentcore.org/core/paint/renderers/rasterx"
_ "cogentcore.org/core/text/shaped/shapers"
)
func init() {
paint.NewSourceRenderer = rasterx.New
paint.NewImageRenderer = rasterx.New
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package svgrender renders to SVG documents.
package svgrender
import (
"bytes"
"image"
"maps"
"reflect"
"cogentcore.org/core/base/iox/imagex"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/base/stack"
"cogentcore.org/core/colors"
"cogentcore.org/core/colors/gradient"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint"
"cogentcore.org/core/paint/pimage"
"cogentcore.org/core/paint/render"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/svg"
"cogentcore.org/core/text/shaped/shapers/shapedgt"
)
// Renderer is the SVG renderer.
type Renderer struct {
size math32.Vector2
SVG *svg.SVG
// gpStack is a stack of groups used while building the svg
gpStack stack.Stack[*svg.Group]
}
func New(size math32.Vector2) render.Renderer {
rs := &Renderer{}
rs.SetSize(units.UnitDot, size)
return rs
}
func (rs *Renderer) Image() image.Image {
if rs.SVG == nil {
return nil
}
pc := rs.SVG.Render(nil)
ir := paint.NewImageRenderer(rs.size)
ir.Render(pc.RenderDone())
return ir.Image()
}
func (rs *Renderer) Source() []byte {
if rs.SVG == nil {
return nil
}
var b bytes.Buffer
rs.SVG.WriteXML(&b, svg.IndentXML)
return b.Bytes()
}
func (rs *Renderer) Size() (units.Units, math32.Vector2) {
return units.UnitDot, rs.size
}
func (rs *Renderer) SetSize(un units.Units, size math32.Vector2) {
if rs.size == size {
return
}
rs.size = size
}
// Render is the main rendering function.
func (rs *Renderer) Render(r render.Render) render.Renderer {
rs.SVG = svg.NewSVG(rs.size)
rs.SVG.Root.ViewBox.Size = rs.size // so that the document is in dots
rs.gpStack = nil
bg := svg.NewGroup(rs.SVG.Root)
rs.gpStack.Push(bg)
for _, ri := range r {
switch x := ri.(type) {
case *render.Path:
rs.RenderPath(x)
case *pimage.Params:
rs.RenderImage(x)
case *render.Text:
rs.RenderText(x)
case *render.ContextPush:
rs.PushContext(x)
case *render.ContextPop:
rs.PopContext(x)
}
}
// pc := paint.NewPainter(rs.size)
// rs.SVG.Render(pc)
// rs.rend = pc.RenderDone()
return rs
}
func (rs *Renderer) PushGroup() *svg.Group {
cg := rs.gpStack.Peek()
g := svg.NewGroup(cg)
rs.gpStack.Push(g)
return g
}
func (rs *Renderer) RenderPath(pt *render.Path) {
p := pt.Path
pc := &pt.Context
cg := rs.gpStack.Peek()
sp := svg.NewPath(cg)
sp.Data = p.Clone()
props := map[string]any{}
pt.Context.Style.GetProperties(props)
if !pc.Transform.IsIdentity() {
props["transform"] = pc.Transform.String()
}
sp.Properties = props
// rs.Scanner.SetClip(pc.Bounds.Rect.ToRect())
}
func (rs *Renderer) PushContext(pt *render.ContextPush) {
pc := &pt.Context
g := rs.PushGroup()
g.Paint.Transform = pc.Transform
}
func (rs *Renderer) PopContext(pt *render.ContextPop) {
rs.gpStack.Pop()
}
func (rs *Renderer) RenderText(pt *render.Text) {
pc := &pt.Context
cg := rs.gpStack.Peek()
tg := svg.NewGroup(cg)
props := map[string]any{}
pt.Context.Style.GetProperties(props)
if !pc.Transform.IsIdentity() {
props["transform"] = pc.Transform.String()
}
pos := pt.Position
tx := pt.Text.Source
txt := tx.Join()
for li := range pt.Text.Lines {
ln := &pt.Text.Lines[li]
lpos := pos.Add(ln.Offset)
rpos := lpos
for ri := range ln.Runs {
run := ln.Runs[ri].(*shapedgt.Run)
rs := run.Runes().Start
re := run.Runes().End
si, _, _ := tx.Index(rs)
sty, _ := tx.Span(si)
rtxt := txt[rs:re]
st := svg.NewText(tg)
st.Text = string(rtxt)
rprops := maps.Clone(props)
if pc.Style.UnitContext.DPI != 160 {
sty.Size *= pc.Style.UnitContext.DPI / 160
}
pt.Context.Style.Text.ToProperties(sty, rprops)
rprops["x"] = reflectx.ToString(rpos.X)
rprops["y"] = reflectx.ToString(rpos.Y)
st.Pos = rpos
st.Properties = rprops
rpos.X += run.Advance()
}
}
}
func (rs *Renderer) RenderImage(pr *pimage.Params) {
usrc := imagex.Unwrap(pr.Source)
umask := imagex.Unwrap(pr.Mask)
cg := rs.gpStack.Peek()
nilSrc := usrc == nil
if r, ok := usrc.(*image.RGBA); ok && r == nil {
nilSrc = true
}
if pr.Rect == (image.Rectangle{}) {
pr.Rect = image.Rectangle{Max: rs.size.ToPoint()}
}
// todo: handle masks!
// Fast path for [image.Uniform]
if u, ok := usrc.(*image.Uniform); nilSrc || ok && umask == nil {
r := svg.NewRect(cg)
r.Pos = math32.FromPoint(pr.Rect.Min)
r.Size = math32.FromPoint(pr.Rect.Size())
if ok {
r.SetProperty("fill", colors.AsHex(u.C))
} else {
r.SetProperty("fill", colors.Transparent)
}
return
}
if gr, ok := usrc.(gradient.Gradient); ok {
_ = gr
// todo: handle:
return
}
sz := pr.Rect.Size()
rimg := usrc
if pr.Original != nil {
uorig := imagex.Unwrap(pr.Original)
if !reflectx.IsNil(reflect.ValueOf(uorig)) {
sc := float32(uorig.Bounds().Size().X) / float32(usrc.Bounds().Size().X)
if sc > 1.2 {
rimg = uorig
}
}
}
simg := svg.NewImage(cg)
simg.SetImage(rimg, 0, 0)
simg.Size.Set(float32(sz.X), float32(sz.Y))
simg.Pos = math32.FromPoint(pr.Rect.Min.Add(pr.SourcePos))
if pr.Cmd == pimage.Transform {
simg.Paint.Transform = pr.Transform
simg.SetTransformProperty()
}
// todo: ViewBox?
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package paint
import (
"image"
"log/slog"
"cogentcore.org/core/base/iox/imagex"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint/ppath"
"cogentcore.org/core/paint/render"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/sides"
"cogentcore.org/core/styles/units"
)
var (
// NewSourceRenderer returns the [composer.Source] renderer
// for [Painter] rendering, for the current platform.
NewSourceRenderer func(size math32.Vector2) render.Renderer
// NewImageRenderer returns a painter renderer for generating
// images locally in Go regardless of platform.
NewImageRenderer func(size math32.Vector2) render.Renderer
// NewSVGRenderer returns a structured SVG renderer that can
// generate an SVG vector graphics document from painter content.
NewSVGRenderer func(size math32.Vector2) render.Renderer
// NewPDFRenderer returns a PDF renderer that can
// generate a PDF document from painter content.
NewPDFRenderer func(size math32.Vector2, un *units.Context) render.Renderer
)
// RenderToImage is a convenience function that renders the current
// accumulated painter actions to an image using a [NewImageRenderer],
// and returns the Image() call from that renderer.
// The image is wrapped by [imagex.WrapJS] so that it is ready to be
// used efficiently for subsequent rendering actions on the JS (web) platform.
func RenderToImage(pc *Painter) image.Image {
rd := NewImageRenderer(pc.Size)
return imagex.WrapJS(rd.Render(pc.RenderDone()).Image())
}
// RenderToSVG is a convenience function that renders the current
// accumulated painter actions to an SVG document using a [NewSVGRenderer]
func RenderToSVG(pc *Painter) []byte {
rd := NewSVGRenderer(pc.Size)
return rd.Render(pc.RenderDone()).Source()
}
// RenderToPDF is a convenience function that renders the current
// accumulated painter actions to a PDF document using a [NewPDFRenderer]
func RenderToPDF(pc *Painter) []byte {
p := pc.RenderDone()
rd := NewPDFRenderer(pc.Size, &pc.Context().Style.UnitContext)
return rd.Render(p).Source()
}
// The State holds all the current rendering state information used
// while painting. The [Paint] embeds a pointer to this.
type State struct {
// Size in dots (true pixels) as specified during Init.
Size math32.Vector2
// Stack provides the SVG "stacking context" as a stack of [Context]s.
// There is always an initial base-level Context element for the overall
// rendering context.
Stack []*render.Context
// Render holds the current [render.PaintRender] state that we are building.
// and has the list of [render.Renderer]s that we render to.
Render render.Render
// Path is the current path state we are adding to.
Path ppath.Path
// pushes are the indexes in Render of the [render.ContextPush] items
// of the contexts of the Stack after the base one.
pushes []int
}
// Init initializes the rendering state, creating a new Stack
// with an initial baseline context using given size and styles.
// Size is used to set the bounds for clipping rendering, assuming
// units are image dots (true pixels), which is typical.
// This should be called whenever the size changes.
func (rs *State) Init(sty *styles.Paint, size math32.Vector2) {
rs.Size = size
bounds := render.NewBounds(0, 0, size.X, size.Y, sides.Floats{})
rs.Stack = []*render.Context{render.NewContext(sty, bounds, nil)}
rs.Render = nil
rs.Path = nil
rs.pushes = nil
}
// RenderDone should be called when the full set of rendering
// for this painter is done. It returns a self-contained
// [render.Render] representing the entire rendering state,
// suitable for rendering by passing to a [render.Renderer].
// It resets the current painter state so that it is ready for
// new rendering.
func (rs *State) RenderDone() render.Render {
npr := rs.Render.Clone()
rs.Render.Reset()
rs.Path.Reset()
if len(rs.Stack) > 1 { // ensure back to baseline stack
rs.Stack = rs.Stack[:1]
}
rs.pushes = rs.pushes[:0]
return npr
}
// Context returns the currently active [render.Context] state (top of Stack).
func (rs *State) Context() *render.Context {
return rs.Stack[len(rs.Stack)-1]
}
// PushContext pushes a new [render.Context] onto the stack using given styles and bounds.
// The transform from the style will be applied to all elements rendered
// within this group, along with the other group properties.
// This adds the Context to the current Render state as well, so renderers
// that track grouping will track this.
// Must protect within render mutex lock (see Lock version).
func (rs *State) PushContext(sty *styles.Paint, bounds *render.Bounds) *render.Context {
parent := rs.Context()
g := render.NewContext(sty, bounds, parent)
rs.Stack = append(rs.Stack, g)
rs.pushes = append(rs.pushes, len(rs.Render))
rs.Render.Add(&render.ContextPush{Context: *g})
return g
}
// PushStack pushes the contexts of the stack of the given other state above
// its base context (their clipping and transforms) onto this one, so that the
// rendering on this one continues within them, as for the rendering of a
// part of a scene into another image (in which the widgets that it is in
// pop them). See [State.PopStack].
func (rs *State) PushStack(other *State) {
for _, g := range other.Stack[1:] {
rs.Stack = append(rs.Stack, g)
rs.pushes = append(rs.pushes, len(rs.Render))
rs.Render.Add(&render.ContextPush{Context: *g})
}
}
// PopStack pops all of the contexts of the stack above its base context.
func (rs *State) PopStack() {
for len(rs.Stack) > 1 {
rs.PopContext()
}
}
// SetLayer sets the [render.Context.ClipMask], [render.Context.Mask], and
// [render.Context.Opacity] of the context at the top of the stack (pushed
// with [State.PushContext]), with which its rendering is composited as a
// whole (as a layer). The masks are typically rendered with
// [State.RenderSeparately] after the context is pushed, so that they
// have its transform.
func (rs *State) SetLayer(clipMask, mask render.Render, opacity float32) {
n := len(rs.pushes)
if n == 0 {
return
}
g := rs.Stack[len(rs.Stack)-1]
g.ClipMask, g.Mask, g.Opacity = clipMask, mask, opacity
if i := rs.pushes[n-1]; i < len(rs.Render) {
if cp, ok := rs.Render[i].(*render.ContextPush); ok {
cp.Context.ClipMask, cp.Context.Mask, cp.Context.Opacity = clipMask, mask, opacity
}
}
}
// RenderSeparately calls the given function, which renders with this
// state, and returns what it renders, which is not added to the current
// rendering (as for the items of a mask, see [State.SetLayer]).
func (rs *State) RenderSeparately(f func()) render.Render {
saved, savedPushes := rs.Render, rs.pushes
rs.Render, rs.pushes = nil, nil
f()
r := rs.Render
rs.Render, rs.pushes = saved, savedPushes
return r
}
// PopContext pops the current Context off of the Stack.
func (rs *State) PopContext() {
n := len(rs.Stack)
if n == 1 {
slog.Error("programmer error: paint.State.PopContext: stack is at base starting point")
return
}
rs.Stack = rs.Stack[:n-1]
if m := len(rs.pushes); m > 0 {
rs.pushes = rs.pushes[:m-1]
}
rs.Render.Add(&render.ContextPop{})
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package abilities provides the abilities of widgets: what they can do,
// as be pressed, focused, or scrolled.
package abilities
//go:generate core generate
import "cogentcore.org/core/enums"
// Abilities represent abilities of GUI elements to take on different States,
// and are aligned with the States flags. All elements can be disabled.
// These correspond to some of the global attributes in CSS:
// https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes
type Abilities int32 //enums:bitflag
const (
// Selectable means it can be Selected
Selectable Abilities = iota
// Activatable means it can be made Active by pressing down on it,
// which gives it a visible state layer color change.
// This also implies Clickable, receiving Click events when
// the user executes a mouse down and up event on the same element.
Activatable
// Clickable means it can be Clicked, receiving Click events when
// the user executes a mouse down and up event on the same element,
// but otherwise does not change its rendering when pressed
// (as Activatable does). Use this for items that are more passively
// clickable, such as frames or tables, whereas e.g., a Button is
// Activatable.
Clickable
// DoubleClickable indicates that an element does something different
// when it is clicked on twice in a row.
DoubleClickable
// TripleClickable indicates that an element does something different
// when it is clicked on three times in a row.
TripleClickable
// RepeatClickable indicates that an element should receive repeated
// click events when the pointer is held down on it.
RepeatClickable
// LongPressable indicates that an element can be LongPressed.
LongPressable
// Draggable means it can be Dragged
Draggable
// Droppable means it can receive DragEnter, DragLeave, and Drop events
// (not specific to current Drag item, just generally).
Droppable
// Slideable means it has a slider element that can be dragged
// to change value. Cannot be both Draggable and Slideable.
Slideable
// Checkable means it can be Checked.
Checkable
// Scrollable means it can be Scrolled.
Scrollable
// Focusable means it can be Focused: capable of receiving and
// processing key events directly and typically changing the
// style when focused to indicate this property to the user.
Focusable
// Hoverable means it can be Hovered.
Hoverable
// LongHoverable means it can be LongHovered.
LongHoverable
// ScrollableUnattended means it can be Scrolled and Slided without
// Focused or Attended state. This is true by default only for Frames.
ScrollableUnattended
// SlidePriority means that sliding it has priority over other actions
// of the mouse, such as the dragging of the widgets around it, however
// long the mouse is pressed before it moves. It is for controls for
// sliding, such as [core.Handle] and [core.Slider], unlike other
// sliding, such as the selection of text, which gives way to dragging,
// except in a widget that has the focus, as a text field being edited.
SlidePriority
// NoPointerEvents means that it does not get the events of the mouse,
// which go to the widgets under it, as for pointer-events: none in CSS
// (as the transparent overlays of the search box of Google, over its
// buttons). The widgets in it still get them, unless they have it too.
NoPointerEvents
// SkipTab means that it and the widgets in it are skipped when moving
// the focus with Tab and Shift+Tab, but can still be focused by
// clicking them (or by code), as for the less used fields of a form
// (see the tab:"-" tag of [core.Form]).
SkipTab
)
var (
// Pressable is the list of abilities that makes something Pressable
Pressable = []Abilities{Selectable, Activatable, DoubleClickable, TripleClickable, Draggable, Slideable, Checkable, Clickable}
// pressableMask has the bits of all of the Pressable abilities set.
pressableMask = func() Abilities {
var m Abilities
for _, ab := range Pressable {
m |= 1 << ab
}
return m
}()
)
// Is is a shortcut for HasFlag for Abilities
func (ab *Abilities) Is(flag enums.BitFlag) bool {
return ab.HasFlag(flag)
}
// IsPressable returns true when an element is Selectable, Activatable,
// DoubleClickable, Draggable, Slideable, or Checkable
func (ab *Abilities) IsPressable() bool {
return *ab&pressableMask != 0
}
// IsHoverable is true for both Hoverable and LongHoverable
func (ab *Abilities) IsHoverable() bool {
return ab.HasFlag(Hoverable) || ab.HasFlag(LongHoverable)
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package styles
import (
"image"
"cogentcore.org/core/colors"
"cogentcore.org/core/colors/gradient"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles/sides"
"cogentcore.org/core/styles/units"
)
// note: background-color is in FontStyle as it is needed to make that the
// only style needed for text render styling
// // Background has style parameters for backgrounds
// type Background struct {
// // todo: all the properties not yet implemented -- mostly about images
// // Image is like a PaintServer -- includes gradients etc
// // Attachment -- how the image moves
// // Clip -- how to clip the image
// // Origin
// // Position
// // Repeat
// // Size
// }
// func (b *Background) Defaults() {
// b.Color.SetColor(White)
// }
// BorderStyles determines how to draw the border
type BorderStyles int32 //enums:enum -trim-prefix Border -transform kebab
const (
// BorderSolid indicates to render a solid border.
BorderSolid BorderStyles = iota
// BorderDotted indicates to render a dotted border.
BorderDotted
// BorderDashed indicates to render a dashed border.
BorderDashed
// TODO(kai): maybe implement these at some point if there
// is ever an actual use case for them
// BorderDouble is not currently supported.
BorderDouble
// BorderGroove is not currently supported.
BorderGroove
// BorderRidge is not currently supported.
BorderRidge
// BorderInset is not currently supported.
BorderInset
// BorderOutset is not currently supported.
BorderOutset
// BorderNone indicates to render no border.
BorderNone
)
// IMPORTANT: any changes here must be updated in style_properties.go StyleBorderFuncs
// Border contains style parameters for borders
type Border struct { //types:add
// Style specifies how to draw the border
Style sides.Sides[BorderStyles]
// Width specifies the width of the border
Width sides.Values `display:"inline"`
// Radius specifies the radius (rounding) of the corners
Radius sides.Values `display:"inline"`
// Offset specifies how much, if any, the border is offset
// from its element. It is only applicable in the standard
// box model, which is used by [paint.Painter.DrawStdBox] and
// all standard GUI elements.
Offset sides.Values `display:"inline"`
// Color specifies the color of the border
Color sides.Sides[image.Image] `display:"inline"`
}
// ToDots runs ToDots on unit values, to compile down to raw pixels
func (bs *Border) ToDots(uc *units.Context) {
bs.Width.ToDots(uc)
bs.Radius.ToDots(uc)
bs.Offset.ToDots(uc)
}
// Pre-configured border radius values, based on
// https://m3.material.io/styles/shape/shape-scale-tokens
var (
// BorderRadiusExtraSmall indicates to use extra small
// 4dp rounded corners
BorderRadiusExtraSmall = sides.NewValues(units.Dp(4))
// BorderRadiusExtraSmallTop indicates to use extra small
// 4dp rounded corners on the top of the element and no
// border radius on the bottom of the element
BorderRadiusExtraSmallTop = sides.NewValues(units.Dp(4), units.Dp(4), units.Zero(), units.Zero())
// BorderRadiusSmall indicates to use small
// 8dp rounded corners
BorderRadiusSmall = sides.NewValues(units.Dp(8))
// BorderRadiusMedium indicates to use medium
// 12dp rounded corners
BorderRadiusMedium = sides.NewValues(units.Dp(12))
// BorderRadiusLarge indicates to use large
// 16dp rounded corners
BorderRadiusLarge = sides.NewValues(units.Dp(16))
// BorderRadiusLargeEnd indicates to use large
// 16dp rounded corners on the end (right side)
// of the element and no border radius elsewhere
BorderRadiusLargeEnd = sides.NewValues(units.Zero(), units.Dp(16), units.Dp(16), units.Zero())
// BorderRadiusLargeTop indicates to use large
// 16dp rounded corners on the top of the element
// and no border radius on the bottom of the element
BorderRadiusLargeTop = sides.NewValues(units.Dp(16), units.Dp(16), units.Zero(), units.Zero())
// BorderRadiusExtraLarge indicates to use extra large
// 28dp rounded corners
BorderRadiusExtraLarge = sides.NewValues(units.Dp(28))
// BorderRadiusExtraLargeTop indicates to use extra large
// 28dp rounded corners on the top of the element
// and no border radius on the bottom of the element
BorderRadiusExtraLargeTop = sides.NewValues(units.Dp(28), units.Dp(28), units.Zero(), units.Zero())
// BorderRadiusFull indicates to use a full border radius,
// which creates a circular/pill-shaped object.
// It is defined to be a value that the width/height of an object
// will never exceed.
BorderRadiusFull = sides.NewValues(units.Dp(1_000_000_000))
)
// IMPORTANT: any changes here must be updated in style_properties.go StyleShadowFuncs
// Shadow contains the style parameters for shadows.
type Shadow struct { //types:add
// OffsetX is th horizontal offset of the shadow.
// Positive moves it right, negative moves it left.
OffsetX units.Value
// OffsetY is the vertical offset of the shadow.
// Positive moves it down, negative moves it up.
OffsetY units.Value
// Blur specifies the blur radius of the shadow.
// Higher numbers make it more blurry.
Blur units.Value
// Spread specifies the spread radius of the shadow.
// Positive numbers increase the size of the shadow,
// and negative numbers decrease the size.
Spread units.Value
// Color specifies the color of the shadow.
Color image.Image
// Inset specifies whether the shadow is inset within the
// box instead of outset outside of the box.
// TODO: implement.
Inset bool
}
func (s *Shadow) HasShadow() bool {
return s.OffsetX.Dots != 0 || s.OffsetY.Dots != 0 || s.Blur.Dots != 0 || s.Spread.Dots != 0
}
// ToDots runs ToDots on unit values, to compile down to raw pixels
func (s *Shadow) ToDots(uc *units.Context) {
s.OffsetX.ToDots(uc)
s.OffsetY.ToDots(uc)
s.Blur.ToDots(uc)
s.Spread.ToDots(uc)
}
// BasePos returns the position at which the base box shadow
// (the actual solid, unblurred box part) should be rendered
// if the shadow is on an element with the given starting position.
func (s *Shadow) BasePos(startPos math32.Vector2) math32.Vector2 {
// Offset directly affects position.
// We need to subtract spread
// to compensate for size changes and stay centered.
return startPos.Add(math32.Vec2(s.OffsetX.Dots, s.OffsetY.Dots)).SubScalar(s.Spread.Dots)
}
// BaseSize returns the total size the base box shadow
// (the actual solid, unblurred part) should be if
// the shadow is on an element with the given starting size.
func (s *Shadow) BaseSize(startSize math32.Vector2) math32.Vector2 {
// Spread goes on all sides, so need to count twice per dimension.
return startSize.AddScalar(2 * s.Spread.Dots)
}
// Pos returns the position at which the blurred box shadow
// should start if the shadow is on an element
// with the given starting position.
func (s *Shadow) Pos(startPos math32.Vector2) math32.Vector2 {
// We need to subtract half of blur
// to compensate for size changes and stay centered.
return s.BasePos(startPos).SubScalar(s.Blur.Dots / 2)
}
// Size returns the total size occupied by the blurred box shadow
// if the shadow is on an element with the given starting size.
func (s *Shadow) Size(startSize math32.Vector2) math32.Vector2 {
// Blur goes on all sides, but it is rendered as half of actual
// because CSS does the same, so we only count it once.
return s.BaseSize(startSize).AddScalar(s.Blur.Dots)
}
// Margin returns the effective margin created by the
// shadow on each side in terms of raw display dots.
// It should be added to margin for sizing considerations.
func (s *Shadow) Margin() sides.Floats {
// Spread benefits every side.
// Offset goes either way, depending on side.
// Every side must be positive.
// note: we are using EdgeBlurFactors with radiusFactor = 1
// (sigma == radius), so we divide Blur / 2 relative to the
// CSS standard of sigma = blur / 2 (i.e., our sigma = blur,
// so we divide Blur / 2 to achieve the same effect).
// This works fine for low-opacity blur factors (the edges are
// so transparent that you can't really see beyond 1 sigma if
// you used radiusFactor = 2).
// If a higher-contrast shadow is used, it would look better
// with radiusFactor = 2, and you'd have to remove this /2 factor.
sdots := float32(0)
if s.Blur.Dots > 0 {
sdots = math32.Ceil(0.5 * s.Blur.Dots)
if sdots < 2 { // for tight dp = 1 case, the render antialiasing requires a min width..
sdots = 2
}
}
return sides.NewFloats(
math32.Max(s.Spread.Dots-s.OffsetY.Dots+sdots, 0),
math32.Max(s.Spread.Dots+s.OffsetX.Dots+sdots, 0),
math32.Max(s.Spread.Dots+s.OffsetY.Dots+sdots, 0),
math32.Max(s.Spread.Dots-s.OffsetX.Dots+sdots, 0),
)
}
// AddBoxShadow adds the given box shadows to the style
func (s *Style) AddBoxShadow(shadow ...Shadow) {
if s.BoxShadow == nil {
s.BoxShadow = []Shadow{}
}
s.BoxShadow = append(s.BoxShadow, shadow...)
}
// BoxShadowMargin returns the effective box
// shadow margin of the style, calculated through [Shadow.Margin]
func (s *Style) BoxShadowMargin() sides.Floats {
return BoxShadowMargin(s.BoxShadow)
}
// MaxBoxShadowMargin returns the maximum effective box
// shadow margin of the style, calculated through [Shadow.Margin]
func (s *Style) MaxBoxShadowMargin() sides.Floats {
return BoxShadowMargin(s.MaxBoxShadow)
}
// BoxShadowMargin returns the maximum effective box shadow margin
// of the given box shadows, calculated through [Shadow.Margin].
func BoxShadowMargin(shadows []Shadow) sides.Floats {
max := sides.Floats{}
for _, sh := range shadows {
max = max.Max(sh.Margin())
}
return max
}
// BoxShadowToDots runs ToDots on all box shadow
// unit values to compile down to raw pixels
func (s *Style) BoxShadowToDots(uc *units.Context) {
for i := range s.BoxShadow {
s.BoxShadow[i].ToDots(uc)
}
for i := range s.MaxBoxShadow {
s.MaxBoxShadow[i].ToDots(uc)
}
}
// HasBoxShadow returns whether the style has
// any box shadows
func (s *Style) HasBoxShadow() bool {
for _, sh := range s.BoxShadow {
if sh.HasShadow() {
return true
}
}
return false
}
// Pre-configured box shadow values, based on
// those in Material 3.
// BoxShadow0 returns the shadows
// to be used on Elevation 0 elements.
// There are no shadows part of BoxShadow0,
// so applying it is purely semantic.
func BoxShadow0() []Shadow {
return []Shadow{}
}
// BoxShadow1 contains the shadows
// to be used on Elevation 1 elements.
func BoxShadow1() []Shadow {
return []Shadow{
{
OffsetX: units.Zero(),
OffsetY: units.Dp(3),
Blur: units.Dp(1),
Spread: units.Dp(-2),
Color: gradient.ApplyOpacity(colors.Scheme.Shadow, 0.2),
},
{
OffsetX: units.Zero(),
OffsetY: units.Dp(2),
Blur: units.Dp(2),
Spread: units.Zero(),
Color: gradient.ApplyOpacity(colors.Scheme.Shadow, 0.14),
},
{
OffsetX: units.Zero(),
OffsetY: units.Dp(1),
Blur: units.Dp(5),
Spread: units.Zero(),
Color: gradient.ApplyOpacity(colors.Scheme.Shadow, 0.12),
},
}
}
// BoxShadow2 returns the shadows
// to be used on Elevation 2 elements.
func BoxShadow2() []Shadow {
return []Shadow{
{
OffsetX: units.Zero(),
OffsetY: units.Dp(2),
Blur: units.Dp(4),
Spread: units.Dp(-1),
Color: gradient.ApplyOpacity(colors.Scheme.Shadow, 0.2),
},
{
OffsetX: units.Zero(),
OffsetY: units.Dp(4),
Blur: units.Dp(5),
Spread: units.Zero(),
Color: gradient.ApplyOpacity(colors.Scheme.Shadow, 0.14),
},
{
OffsetX: units.Zero(),
OffsetY: units.Dp(1),
Blur: units.Dp(10),
Spread: units.Zero(),
Color: gradient.ApplyOpacity(colors.Scheme.Shadow, 0.12),
},
}
}
// TODO: figure out why 3 and 4 are the same
// BoxShadow3 returns the shadows
// to be used on Elevation 3 elements.
func BoxShadow3() []Shadow {
return []Shadow{
{
OffsetX: units.Zero(),
OffsetY: units.Dp(5),
Blur: units.Dp(5),
Spread: units.Dp(-3),
Color: gradient.ApplyOpacity(colors.Scheme.Shadow, 0.2),
},
{
OffsetX: units.Zero(),
OffsetY: units.Dp(8),
Blur: units.Dp(10),
Spread: units.Dp(1),
Color: gradient.ApplyOpacity(colors.Scheme.Shadow, 0.14),
},
{
OffsetX: units.Zero(),
OffsetY: units.Dp(3),
Blur: units.Dp(14),
Spread: units.Dp(2),
Color: gradient.ApplyOpacity(colors.Scheme.Shadow, 0.12),
},
}
}
// BoxShadow4 returns the shadows
// to be used on Elevation 4 elements.
func BoxShadow4() []Shadow {
return []Shadow{
{
OffsetX: units.Zero(),
OffsetY: units.Dp(5),
Blur: units.Dp(5),
Spread: units.Dp(-3),
Color: gradient.ApplyOpacity(colors.Scheme.Shadow, 0.2),
},
{
OffsetX: units.Zero(),
OffsetY: units.Dp(8),
Blur: units.Dp(10),
Spread: units.Dp(1),
Color: gradient.ApplyOpacity(colors.Scheme.Shadow, 0.14),
},
{
OffsetX: units.Zero(),
OffsetY: units.Dp(3),
Blur: units.Dp(14),
Spread: units.Dp(2),
Color: gradient.ApplyOpacity(colors.Scheme.Shadow, 0.12),
},
}
}
// BoxShadow5 returns the shadows
// to be used on Elevation 5 elements.
func BoxShadow5() []Shadow {
return []Shadow{
{
OffsetX: units.Zero(),
OffsetY: units.Dp(8),
Blur: units.Dp(10),
Spread: units.Dp(-6),
Color: gradient.ApplyOpacity(colors.Scheme.Shadow, 0.2),
},
{
OffsetX: units.Zero(),
OffsetY: units.Dp(16),
Blur: units.Dp(24),
Spread: units.Dp(2),
Color: gradient.ApplyOpacity(colors.Scheme.Shadow, 0.14),
},
{
OffsetX: units.Zero(),
OffsetY: units.Dp(6),
Blur: units.Dp(30),
Spread: units.Dp(5),
Color: gradient.ApplyOpacity(colors.Scheme.Shadow, 0.12),
},
}
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package styles
import "cogentcore.org/core/math32"
// ClampMax returns given value, not greater than given max _only if_ max > 0
func ClampMax(v, mx float32) float32 {
if mx <= 0 {
return v
}
return min(v, mx)
}
// ClampMin returns given value, not less than given min _only if_ min > 0
func ClampMin(v, mn float32) float32 {
if mn <= 0 {
return v
}
return max(v, mn)
}
// SetClampMax ensures the given value is not greater than given max _only if_ max > 0
func SetClampMax(v *float32, mx float32) {
if mx <= 0 {
return
}
*v = min(*v, mx)
}
// SetClampMin ensures the given value is not less than given min _only if_ min > 0
func SetClampMin(v *float32, mn float32) {
if mn <= 0 {
return
}
*v = max(*v, mn)
}
// ClampMaxVector returns given Vector2 values, not greater than given max _only if_ max > 0
func ClampMaxVector(v, mx math32.Vector2) math32.Vector2 {
var nv math32.Vector2
nv.X = ClampMax(v.X, mx.X)
nv.Y = ClampMax(v.Y, mx.Y)
return nv
}
// ClampMinVector returns given Vector2 values, not less than given min _only if_ min > 0
func ClampMinVector(v, mn math32.Vector2) math32.Vector2 {
var nv math32.Vector2
nv.X = ClampMin(v.X, mn.X)
nv.Y = ClampMin(v.Y, mn.Y)
return nv
}
// SetClampMaxVector ensures the given Vector2 values are not greater than given max _only if_ max > 0
func SetClampMaxVector(v *math32.Vector2, mx math32.Vector2) {
SetClampMax(&v.X, mx.X)
SetClampMax(&v.Y, mx.Y)
}
// SetClampMinVector ensures the given Vector2 values are not less than given min _only if_ min > 0
func SetClampMinVector(v *math32.Vector2, mn math32.Vector2) {
SetClampMin(&v.X, mn.X)
SetClampMin(&v.Y, mn.Y)
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package styles
import (
"fmt"
"image"
"strconv"
"strings"
"cogentcore.org/core/colors"
"cogentcore.org/core/colors/gradient"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/text"
)
// ToCSS converts the given [Style] object to a semicolon-separated CSS string.
// It is not guaranteed to be fully complete or accurate. It also takes the kebab-case
// ID name of the associated widget and the resultant html element name for context.
func ToCSS(s *Style, idName, htmlName string) string {
parts := []string{}
add := func(key, value string) {
if value == "" || value == "0" || value == "0px" || value == "0dot" {
return
}
parts = append(parts, key+":"+value)
}
length := func(v units.Value) string { return ToCSSLength(s, v) }
// addAlign adds an alignment that is not the default (auto or start).
addAlign := func(key string, a Aligns) {
if a != Auto && a != Start {
add(key, a.String())
}
}
add("color", colorToCSS(s.Color))
add("background", colorToCSS(s.Background))
if htmlName == "svg" {
add("stroke", colorToCSS(s.Color))
add("fill", colorToCSS(s.Color))
}
if idName != "text" { // text does not have these layout properties
if s.Is(states.Invisible) {
add("display", "none")
} else {
add("display", s.Display.String())
}
add("flex-direction", s.Direction.String())
add("flex-grow", fmt.Sprintf("%g", s.Grow.Y))
add("justify-content", s.Justify.Content.String())
add("align-items", s.Align.Items.String())
if s.Display == Grid && s.Columns > 0 {
add("grid-template-columns", fmt.Sprintf("repeat(%d,auto)", s.Columns))
}
add("row-gap", length(s.Gap.Y))
add("column-gap", length(s.Gap.X))
if s.Wrap {
add("flex-wrap", "wrap")
}
if s.Shrink.X > 0 && s.Shrink.X != 1 { // 0 is a factor of 1, as in CSS
add("flex-shrink", fmt.Sprintf("%g", s.Shrink.X))
}
if s.FlexBasis.Value > 0 {
add("flex-basis", length(s.FlexBasis))
}
addAlign("align-content", s.Align.Content)
addAlign("justify-items", s.Justify.Items)
addAlign("justify-self", s.Justify.Self)
if s.Overflow.X != OverflowVisible {
add("overflow-x", s.Overflow.X.String())
}
if s.Overflow.Y != OverflowVisible {
add("overflow-y", s.Overflow.Y.String())
}
}
add("box-sizing", s.BoxSizing.String())
if s.AspectRatio > 0 {
add("aspect-ratio", fmt.Sprintf("%g", s.AspectRatio))
}
if s.ColSpan > 1 {
add("grid-column", fmt.Sprintf("span %d", s.ColSpan))
}
if s.RowSpan > 1 {
add("grid-row", fmt.Sprintf("span %d", s.RowSpan))
}
// The position of the widget, out of the layout or moved in it.
if s.Position != PositionStatic {
add("position", s.Position.String())
set, inset := s.InsetSet, s.Inset
for i, v := range []units.Value{inset.Top, inset.Right, inset.Bottom, inset.Left} {
if []bool{set.Top, set.Right, set.Bottom, set.Left}[i] {
add(cssSides[i], length(v))
}
}
if s.ZIndex != 0 {
add("z-index", strconv.Itoa(s.ZIndex))
}
}
if s.Float != FloatNone {
add("float", s.Float.String())
}
if s.Clear != ClearNone {
add("clear", s.Clear.String())
}
var transform []string
if s.Translate.X.Value != 0 || s.Translate.Y.Value != 0 {
transform = append(transform, "translate("+length(s.Translate.X)+","+length(s.Translate.Y)+")")
}
if s.Rotate != 0 {
transform = append(transform, fmt.Sprintf("rotate(%gdeg)", s.Rotate))
}
add("transform", strings.Join(transform, " "))
add("min-width", length(s.Min.X))
add("min-height", length(s.Min.Y))
add("max-width", length(s.Max.X))
add("max-height", length(s.Max.Y))
if s.Grow == (math32.Vector2{}) {
add("width", length(s.Min.X))
add("height", length(s.Min.Y))
}
add("padding-top", length(s.Padding.Top))
add("padding-right", length(s.Padding.Right))
add("padding-bottom", length(s.Padding.Bottom))
add("padding-left", length(s.Padding.Left))
add("margin-top", length(s.Margin.Top))
add("margin-right", length(s.Margin.Right))
add("margin-bottom", length(s.Margin.Bottom))
add("margin-left", length(s.Margin.Left))
if s.Font.Size.Value != 16 || s.Font.Size.Unit != units.UnitDp {
add("font-size", length(s.Font.Size))
}
// The font family of the page is the default sans-serif one.
switch {
case s.Font.Family == rich.Custom && s.Font.CustomFont != "":
add("font-family", strconv.Quote(string(s.Font.CustomFont)))
case s.Font.Family != rich.SansSerif && s.Font.Family != rich.Custom:
add("font-family", s.Font.Family.String())
}
// A font of zero values (thin and ultra condensed) is not set, as for
// widgets that only have the font of their rich text. The weight is
// written even when it is normal, as for a heading, which is bold in
// CSS; a stretch of zero is not set.
if s.Font.Weight != rich.Thin || s.Font.Stretch != rich.UltraCondensed {
add("font-weight", strconv.Itoa((int(s.Font.Weight)+1)*100)) // thin is 100
}
if s.Font.Stretch != rich.StretchNormal && s.Font.Stretch != rich.UltraCondensed {
add("font-stretch", s.Font.Stretch.String())
}
if s.Font.Slant == rich.Italic {
add("font-style", "italic")
}
add("text-decoration", decorationToCSS(s.Font.Decoration))
add("line-height", fmt.Sprintf("%g", s.Text.LineHeight))
add("text-align", s.Text.Align.String())
switch s.Text.WhiteSpace {
case text.WrapNever:
add("white-space", "nowrap")
case text.WhiteSpacePre:
add("white-space", "pre")
case text.WhiteSpacePreWrap:
add("white-space", "pre-wrap")
}
add("text-indent", length(s.Text.Indent))
if s.Text.TabSize > 0 && s.Text.TabSize != 4 {
add("tab-size", strconv.Itoa(s.Text.TabSize))
}
if htmlName == "td" || htmlName == "th" { // as the valign of a cell
switch s.Text.AlignV {
case text.Center:
add("vertical-align", "middle")
case text.End:
add("vertical-align", "bottom")
}
}
// The border, shadows, and opacity of the box.
bd := &s.Border
widths := []units.Value{bd.Width.Top, bd.Width.Right, bd.Width.Bottom, bd.Width.Left}
bstyles := []BorderStyles{bd.Style.Top, bd.Style.Right, bd.Style.Bottom, bd.Style.Left}
bcolors := []image.Image{bd.Color.Top, bd.Color.Right, bd.Color.Bottom, bd.Color.Left}
for i, w := range widths {
if w.Value > 0 {
add("border-"+cssSides[i], length(w)+" "+bstyles[i].String()+" "+colorToCSSOr(bcolors[i], "currentColor"))
}
}
// The radii are of the corners: top-left, top-right, bottom-right, bottom-left.
r := []string{length(bd.Radius.Top), length(bd.Radius.Right), length(bd.Radius.Bottom), length(bd.Radius.Left)}
if r[0] == r[1] && r[0] == r[2] && r[0] == r[3] {
add("border-radius", r[0])
} else {
add("border-radius", strings.Join(r, " "))
}
var shadows []string
for _, sh := range s.BoxShadow {
if !sh.HasShadow() {
continue
}
css := length(sh.OffsetX) + " " + length(sh.OffsetY) + " " + length(sh.Blur) + " " + length(sh.Spread) + " " + colorToCSSOr(sh.Color, "currentColor")
if sh.Inset {
css = "inset " + css
}
shadows = append(shadows, css)
}
add("box-shadow", strings.Join(shadows, ","))
if s.Opacity > 0 && s.Opacity < 1 {
add("opacity", fmt.Sprintf("%g", s.Opacity))
}
return strings.Join(parts, ";")
}
// ToCSSLength returns the CSS of the given length of the given [Style], as
// in [ToCSS]: in px for a length in dots, which CSS does not have (as
// htmlcore sets), using the unit context of the style, or as
// [units.Value.StringCSSDp] otherwise.
func ToCSSLength(s *Style, v units.Value) string {
if v.Unit == units.UnitDot {
px := math32.Round(s.UnitContext.FromDots(v.Value, units.UnitDp)*100) / 100
return strconv.FormatFloat(float64(px), 'g', -1, 32) + "px"
}
return v.StringCSSDp()
}
// cssSides are the names of the sides in CSS, in the order of [sides.Sides].
var cssSides = []string{"top", "right", "bottom", "left"}
// decorationToCSS returns the text-decoration of the given decorations.
func decorationToCSS(d rich.Decorations) string {
var parts []string
for _, f := range []rich.Decorations{rich.Underline, rich.Overline, rich.LineThrough} {
if d.HasFlag(f) {
parts = append(parts, f.BitIndexString())
}
}
if d.HasFlag(rich.DottedUnderline) {
parts = append(parts, "underline dotted")
}
return strings.Join(parts, " ")
}
// colorToCSSOr returns the CSS of the given color, or def if it is
// already the default (as for the color of a border, which is the text
// color in CSS).
func colorToCSSOr(c image.Image, def string) string {
if css := colorToCSS(c); css != "" {
return css
}
if c == nil {
return def
}
return colors.AsHex(colors.ToUniform(c))
}
// linearToCSS returns the CSS linear-gradient of a linear gradient whose
// coordinates are relative to the box of the element.
func linearToCSS(g *gradient.Linear) string {
d := g.End.Sub(g.Start)
// The angle of CSS is clockwise from the top (to top is 0deg).
angle := math32.RadToDeg(math32.Atan2(d.X, -d.Y))
stops := []string{fmt.Sprintf("%gdeg", math32.Round(angle))}
for _, st := range g.Stops {
c := st.Color
if st.Opacity < 1 {
c = colors.ApplyOpacity(c, st.Opacity)
}
stops = append(stops, fmt.Sprintf("%s %g%%", colors.AsHex(c), math32.Round(st.Pos*1000)/10))
}
return "linear-gradient(" + strings.Join(stops, ",") + ")"
}
func colorToCSS(c image.Image) string {
switch c {
case nil:
return ""
case colors.Scheme.Primary.Base:
return "var(--primary-color)"
case colors.Scheme.Primary.On:
return "var(--primary-on-color)"
case colors.Scheme.Secondary.Container:
return "var(--secondary-container-color)"
case colors.Scheme.Secondary.OnContainer:
return "var(--secondary-on-container-color)"
case colors.Scheme.Surface, colors.Scheme.OnSurface:
return "" // already default
case colors.Scheme.SurfaceContainer, colors.Scheme.SurfaceContainerLowest, colors.Scheme.SurfaceContainerLow, colors.Scheme.SurfaceContainerHigh, colors.Scheme.SurfaceContainerHighest:
return "var(--surface-container-color)" // all of them are close enough for this
default:
if g, ok := c.(*gradient.Linear); ok && g.Units == gradient.ObjectBoundingBox && len(g.Stops) > 1 {
return linearToCSS(g)
}
return colors.AsHex(colors.ToUniform(c))
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package styles
import (
"image"
"log/slog"
"cogentcore.org/core/colors"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/text"
)
// IMPORTANT: any changes here must be updated in style_properties.go StyleFontFuncs
// Font contains all font styling information.
// Most of font information is inherited.
type Font struct { //types:add
// Size of font to render (inherited).
// Converted to points when getting font to use.
Size units.Value `step:"1"`
// Family indicates the generic family of typeface to use, where the
// specific named values to use for each are provided in the [Settings],
// or [CustomFont] for [Custom].
Family rich.Family
// CustomFont specifies the Custom font name for Family = Custom.
CustomFont rich.FontName
// Slant allows italic or oblique faces to be selected.
Slant rich.Slants
// Weights are the degree of blackness or stroke thickness of a font.
// This value ranges from 100.0 to 900.0, with 400.0 as normal.
Weight rich.Weights
// Stretch is the width of a font as an approximate fraction of the normal width.
// Widths range from 0.5 to 2.0 inclusive, with 1.0 as the normal width.
Stretch rich.Stretch
// Decorations are underline, line-through, etc, as bit flags
// that must be set using [Decorations.SetFlag].
Decoration rich.Decorations
}
func (fs *Font) Defaults() {
fs.Size.Dp(16)
fs.Weight = rich.Normal
fs.Stretch = rich.StretchNormal
}
// InheritFields from parent
func (fs *Font) InheritFields(parent *Font) {
if parent.Size.Value != 0 {
fs.Size = parent.Size
}
fs.Family = parent.Family
fs.CustomFont = parent.CustomFont
fs.Slant = parent.Slant
fs.Weight = parent.Weight
fs.Stretch = parent.Stretch
fs.Decoration = parent.Decoration
}
// ToDots runs ToDots on unit values, to compile down to raw pixels
func (fs *Font) ToDots(uc *units.Context) {
if fs.Size.Unit == units.UnitEm || fs.Size.Unit == units.UnitEx || fs.Size.Unit == units.UnitCh {
slog.Error("girl/styles.Font.Size was set to Em, Ex, or Ch; that is recursive and unstable!", "unit", fs.Size.Unit)
fs.Size.Dp(16)
}
fs.Size.ToDots(uc)
}
// SetUnitContext sets the font-specific information in the given
// units.Context, based on the given styles. Just uses standardized
// fractions of the font size for the other less common units such as ex, ch.
func (fs *Font) SetUnitContext(uc *units.Context) {
fsz := math32.Round(fs.Size.Dots)
if fsz == 0 {
fsz = 16
}
uc.SetFont(fsz)
}
// SetDecoration sets text decoration (underline, etc),
// which uses bitflags to allow multiple combinations.
func (fs *Font) SetDecoration(deco ...rich.Decorations) *Font {
for _, d := range deco {
fs.Decoration.SetFlag(true, d)
}
return fs
}
// FontHeight returns the font height in dots (actual pixels).
// Only valid after ToDots has been called, as final step of styling.
func (fs *Font) FontHeight() float32 {
return math32.Round(fs.Size.Dots)
}
// SetRich sets the rich.Style from font style.
func (fs *Font) SetRich(sty *rich.Style) {
sty.Family = fs.Family
sty.Slant = fs.Slant
sty.Weight = fs.Weight
sty.Stretch = fs.Stretch
sty.Decoration = fs.Decoration
}
// SetFromRich sets from the rich.Style
func (fs *Font) SetFromRich(sty *rich.Style) {
fs.Family = sty.Family
fs.Slant = sty.Slant
fs.Weight = sty.Weight
fs.Stretch = sty.Stretch
fs.Decoration = sty.Decoration
}
// SetRichText sets the rich.Style and text.Style properties from style
// [Font] and [Text] styles
func SetRichText(sty *rich.Style, tsty *text.Style, font *Font, txt *Text, clr image.Image, opacity float32) {
font.SetRich(sty)
txt.SetText(tsty)
tsty.FontSize = font.Size
tsty.CustomFont = font.CustomFont
if clr != nil {
tsty.Color = colors.ApplyOpacity(colors.ToUniform(clr), opacity)
}
// note: no default background color here
}
// SetFromRichText sets the style [Font] and [Text] styles from rich.Style and text.Style.
func SetFromRichText(sty *rich.Style, tsty *text.Style, font *Font, txt *Text) {
font.SetFromRich(sty)
txt.SetFromText(tsty)
font.Size = tsty.FontSize
font.CustomFont = tsty.CustomFont
}
// SetRichText sets the rich.Style and text.Style properties from the style props.
func (s *Style) SetRichText(sty *rich.Style, tsty *text.Style) {
SetRichText(sty, tsty, &s.Font, &s.Text, s.Color, s.Opacity)
}
// NewRichText sets the rich.Style and text.Style properties from the style props.
func (s *Style) NewRichText() (sty *rich.Style, tsty *text.Style) {
sty = rich.NewStyle()
tsty = text.NewStyle()
s.SetRichText(sty, tsty)
return
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package styles
import (
"cogentcore.org/core/math32"
"cogentcore.org/core/styles/units"
)
// todo: for style
// Resize: user-resizability
// z-index
// CSS vs. Layout alignment
//
// CSS has align-self, align-items (for a container, provides a default for
// items) and align-content which only applies to lines in a flex layout (akin
// to a flow layout) -- there is a presumed horizontal aspect to these, except
// align-content, so they are subsumed in the AlignH parameter in this style.
// Vertical-align works as expected, and Text.Align uses left/center/right
// IMPORTANT: any changes here must be updated in style_properties.go StyleLayoutFuncs
// DefaultScrollbarWidth is the default [Style.ScrollbarWidth].
var DefaultScrollbarWidth = units.Dp(10)
func (s *Style) LayoutDefaults() {
s.Justify.Defaults()
s.Align.Defaults()
s.Gap.Set(units.Em(0.5))
s.ScrollbarWidth = DefaultScrollbarWidth
}
// LayoutToDots runs ToDots on unit values, to compile down to raw pixels
func (s *Style) LayoutToDots(uc *units.Context) {
s.Pos.ToDots(uc)
s.Min.ToDots(uc)
s.Max.ToDots(uc)
s.Padding.ToDots(uc)
s.Margin.ToDots(uc)
s.Gap.ToDots(uc)
s.ScrollbarWidth.ToDots(uc)
s.Inset.ToDots(uc)
s.FlexBasis.ToDots(uc)
// max must be at least as much as min
if s.Max.X.Dots > 0 {
s.Max.X.Dots = max(s.Max.X.Dots, s.Min.X.Dots)
}
if s.Max.Y.Dots > 0 {
s.Max.Y.Dots = max(s.Max.Y.Dots, s.Min.Y.Dots)
}
}
// AlignPos returns the position offset based on Align.X,Y settings
// for given inner-sized box within given outer-sized container box.
func AlignPos(align Aligns, inner, outer float32) float32 {
extra := outer - inner
var pos float32
if extra > 0 {
pos += AlignFactor(align) * extra
}
return math32.Floor(pos)
}
/////////////////////////////////////////////////////////////////
// Directions specify the way in which elements are laid out, or
// the dimension on which an element is longer / travels in.
type Directions int32 //enums:enum -transform kebab
const (
// Row indicates that elements are laid out in a row
// or that an element is longer / travels in the x dimension.
Row Directions = iota
// Column indicates that elements are laid out in a column
// or that an element is longer / travels in the y dimension.
Column
)
// Dim returns the corresponding dimension for the direction.
func (d Directions) Dim() math32.Dims {
return math32.Dims(d)
}
// Other returns the opposite (other) direction.
func (d Directions) Other() Directions {
if d == Row {
return Column
}
return Row
}
// Displays determines how items are displayed.
type Displays int32 //enums:enum -trim-prefix Display -transform kebab
const (
// Flex is the default layout model, based on a simplified version of the
// CSS flex layout: uses MainAxis to specify the direction, Wrap for
// wrapping of elements, and Min, Max, and Grow values on elements to
// determine sizing.
Flex Displays = iota
// Stacked is a stack of elements, with one on top that is visible
Stacked
// Grid is the X, Y grid layout, with Columns specifying the number
// of elements in the X axis.
Grid
// Custom means that no automatic layout will be applied to elements,
// which can then be managed via custom code by setting the [Style.Pos] position.
Custom
// None means the item is not displayed: sets the Invisible state
DisplayNone
)
// Aligns has all different types of alignment and justification.
type Aligns int32 //enums:enum -transform kebab
const (
// Auto means the item uses the container's AlignItems value
Auto Aligns = iota
// Align items to the start (top, left) of layout
Start
// Align items to the end (bottom, right) of layout
End
// Align items centered
Center
// Align to text baselines
Baseline
// First and last are flush, equal space between remaining items
SpaceBetween
// First and last have 1/2 space at edges, full space between remaining items
SpaceAround
// Equal space at start, end, and between all items
SpaceEvenly
)
func AlignFactor(al Aligns) float32 {
switch al {
case Start:
return 0
case End:
return 1
case Center:
return 0.5
}
return 0
}
// AlignSet specifies the 3 levels of Justify or Align: Content, Items, and Self
type AlignSet struct { //types:add
// Content specifies the distribution of the entire collection of items within
// any larger amount of space allocated to the container. By contrast, Items
// and Self specify distribution within the individual element's allocated space.
Content Aligns
// Items specifies the distribution within the individual element's allocated space,
// as a default for all items within a collection.
Items Aligns
// Self specifies the distribution within the individual element's allocated space,
// for this specific item. Auto defaults to containers Items setting.
Self Aligns
}
func (as *AlignSet) Defaults() {
as.Content = Start
as.Items = Start
as.Self = Auto
}
// ItemAlign returns the effective Aligns value between parent Items and Self
func ItemAlign(parItems, self Aligns) Aligns {
if self == Auto {
return parItems
}
return self
}
// Overflows are the overflow types, which determine what happens when there is too much stuff in a layout.
type Overflows int32 //enums:enum -trim-prefix Overflow -transform kebab
const (
// OverflowVisible makes the overflow visible, meaning that the size
// of the container is always at least the Min size of its contents.
// No scrollbars are shown.
OverflowVisible Overflows = iota
// OverflowHidden hides the overflow and doesn't present scrollbars.
OverflowHidden
// OverflowAuto automatically determines if scrollbars should be added to show
// the overflow. Scrollbars are added only if the actual content size is greater
// than the currently available size.
OverflowAuto
// OverflowScroll means that scrollbars are always visible,
// and is otherwise identical to Auto. However, only during Viewport PrefSize call,
// the actual content size is used -- otherwise it behaves just like Auto.
OverflowScroll
)
// Positions are the ways that widgets can be positioned, as with the
// position property of CSS (see [Style.Position]).
type Positions int32 //enums:enum -trim-prefix Position -transform kebab
const (
// PositionStatic is the default: the widget is in the layout of its parent.
PositionStatic Positions = iota
// PositionRelative is in the layout of its parent, and then offset
// from its position in the layout by [Style.Inset], without changing
// the layout. It is also the containing block of the widgets in it
// that are [PositionAbsolute].
PositionRelative
// PositionAbsolute is not in the layout of its parent: it is positioned
// by [Style.Inset] relative to its containing block, which is the nearest
// widget that it is in that is not [PositionStatic], or the scene.
// Its size is that of its content, unless both of the opposite sides
// of an inset are set, in which case it fills the space between them.
PositionAbsolute
// PositionFixed is like [PositionAbsolute], but positioned relative
// to the scene, so that it does not scroll.
PositionFixed
// PositionSticky is in the layout of its parent, like [PositionStatic],
// but when its parent frame that scrolls is scrolled past it, it stays
// at the [Style.Inset] (top, bottom, left, right) from the edges of the
// visible part of that frame, within its parent, as the sticky
// position of CSS (as a table of contents beside a long page).
PositionSticky
)
// Floats are the ways that widgets can float (see [Style.Float]).
type Floats int32 //enums:enum -trim-prefix Float -transform kebab
const (
// FloatNone is the default: the widget does not float.
FloatNone Floats = iota
// FloatLeft floats the widget to the left of its parent.
FloatLeft
// FloatRight floats the widget to the right of its parent.
FloatRight
)
// Clears are the sides of the floats that a widget is below (see [Style.Clear]).
type Clears int32 //enums:enum -trim-prefix Clear -transform kebab
const (
// ClearNone is the default: the widget is not moved below floats.
ClearNone Clears = iota
// ClearLeft moves the widget below the floats on the left.
ClearLeft
// ClearRight moves the widget below the floats on the right.
ClearRight
// ClearBoth moves the widget below all of the floats.
ClearBoth
)
// Containments are the dimensions in which the size of an element does
// not depend on its content, as the size containment of CSS (which a
// container for container queries has).
type Containments int32 //enums:enum -trim-prefix Contain -transform kebab
const (
// ContainNone is the default: the size of the element depends on its content.
ContainNone Containments = iota
// ContainInlineSize is for an element whose width does not depend on its
// content (as if it were empty), which overflows it instead.
ContainInlineSize
// ContainSize is for an element whose width and height do not depend on
// its content (as if it were empty), which overflows it instead.
ContainSize
)
// BoxSizings are the boxes that the Min and Max sizes are of,
// as the box-sizing property of CSS.
type BoxSizings int32 //enums:enum -trim-prefix Box -transform kebab
const (
// BoxContentBox is the default: the sizes are of the content,
// without the padding and border.
BoxContentBox BoxSizings = iota
// BoxBorderBox is for sizes that include the padding and border.
BoxBorderBox
)
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package styles
import (
"image"
"image/draw"
"cogentcore.org/core/base/iox/imagex"
"cogentcore.org/core/math32"
"github.com/anthonynsimon/bild/transform"
)
// ObjectFits are the different ways in which a replaced element
// (image, video, etc) can be fit into its containing box.
type ObjectFits int32 //enums:enum -trim-prefix Fit -transform kebab
const (
// FitFill indicates that the replaced object will fill
// the element's entire content box, stretching if necessary.
FitFill ObjectFits = iota
// FitContain indicates that the replaced object will resize
// as large as possible while fully fitting within the element's
// content box and maintaining its aspect ratio. Therefore,
// it may not fill the entire element.
FitContain
// FitCover indicates that the replaced object will fill
// the element's entire content box, clipping if necessary.
FitCover
// FitNone indicates that the replaced object will not resize.
FitNone
// FitScaleDown indicates that the replaced object will size
// as if [FitNone] or [FitContain] was specified, using
// whichever will result in a smaller final size.
FitScaleDown
)
// ObjectSizeFromFit returns the target object size based on the given
// ObjectFits setting, original object size, and target box size
// for the object to fit into.
func ObjectSizeFromFit(fit ObjectFits, obj, box math32.Vector2) math32.Vector2 {
oar := obj.X / obj.Y
bar := box.X / box.Y
var sz math32.Vector2
switch fit {
case FitFill:
return box
case FitContain, FitScaleDown:
if oar >= bar {
// if we have a higher x:y than them, x is our limiting size
sz.X = box.X
// and we make our y in proportion to that
sz.Y = obj.Y * (box.X / obj.X)
} else {
// if we have a lower x:y than them, y is our limiting size
sz.Y = box.Y
// and we make our x in proportion to that
sz.X = obj.X * (box.Y / obj.Y)
}
case FitCover:
if oar < bar {
// if we have a lower x:y than them, x is our limiting size
sz.X = box.X
// and we make our y in proportion to that
sz.Y = obj.Y * (box.X / obj.X)
} else {
// if we have a lower x:y than them, y is our limiting size
sz.Y = box.Y
// and we make our x in proportion to that
sz.X = obj.X * (box.Y / obj.Y)
}
}
return sz
}
// ResizeImage resizes the given image according to [Style.ObjectFit]
// in an object of the given box size. It returns an [imagex.WrapJS] image
// that is a pointer to an html image object on web, and resizing is done
// efficiently for that platform.
func (s *Style) ResizeImage(img image.Image, box math32.Vector2) image.Image {
obj := math32.FromPoint(img.Bounds().Size())
sz := ObjectSizeFromFit(s.ObjectFit, obj, box)
if s.ObjectFit == FitScaleDown && sz.X >= obj.X {
return img
}
szi := sz.ToPointFloor()
rimg := imagex.Resize(img, szi)
if s.ObjectFit != FitCover || (box.X >= sz.X && box.Y >= sz.Y) {
return rimg
}
// need to crop the destination size to the size of the containing object
drect := image.Rect(0, 0, int(min(sz.X, box.X)), int(min(sz.Y, box.Y)))
return imagex.Crop(rimg, drect)
}
// ResizeImageLocal resizes the given image according to [Style.ObjectFit]
// in an object of the given box size. This version uses local Go image
// resizing regardless of what platform, for use with local Image rendering.
func (s *Style) ResizeImageLocal(img image.Image, box math32.Vector2) image.Image {
obj := math32.FromPoint(img.Bounds().Size())
sz := ObjectSizeFromFit(s.ObjectFit, obj, box)
if s.ObjectFit == FitScaleDown && sz.X >= obj.X {
return img
}
szi := sz.ToPointFloor()
rimg := transform.Resize(img, szi.X, szi.Y, transform.Linear)
if s.ObjectFit != FitCover || (box.X >= sz.X && box.Y >= sz.Y) {
return rimg
}
// need to crop the destination size to the size of the containing object
drect := image.Rect(0, 0, int(min(sz.X, box.X)), int(min(sz.Y, box.Y)))
dst := image.NewRGBA(drect)
draw.Draw(dst, drect, rimg, image.Point{}, draw.Src)
return dst
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package styles
import (
"image"
"cogentcore.org/core/colors"
"cogentcore.org/core/paint/ppath"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/text"
)
// Paint provides the styling parameters for SVG-style rendering,
// including the Path stroke and fill properties, and font and text
// properties.
type Paint struct { //types:add
Path
// Font selects font properties.
Font rich.Style
// Text has the text styling settings.
Text text.Style
// ClipPath is a clipping path for this item.
ClipPath ppath.Path
// Mask is a rendered image of the mask for this item.
Mask image.Image
}
func NewPaint() *Paint {
pc := &Paint{}
pc.Defaults()
return pc
}
// NewPaintWithContext returns a new Paint style with [units.Context]
// initialized from given. Pass the Styles context for example.
func NewPaintWithContext(uc *units.Context) *Paint {
pc := NewPaint()
pc.UnitContext = *uc
return pc
}
func (pc *Paint) Defaults() {
pc.Path.Defaults()
pc.Font.Defaults()
pc.Text.Defaults()
}
// CopyStyleFrom copies styles from another paint
func (pc *Paint) CopyStyleFrom(cp *Paint) {
pc.Path.CopyStyleFrom(&cp.Path)
pc.Font = cp.Font
pc.Text = cp.Text
}
// InheritFields from parent
func (pc *Paint) InheritFields(parent *Paint) {
pc.Font.InheritFields(&parent.Font)
pc.Text.InheritFields(&parent.Text)
}
// SetProperties sets paint values based on given property map (name: value
// pairs), inheriting elements as appropriate from parent, and also having a
// default style for the "initial" setting
func (pc *Paint) SetProperties(parent *Paint, properties map[string]any, ctxt colors.Context) {
if !pc.StyleSet && parent != nil { // first time
pc.InheritFields(parent)
}
pc.fromProperties(parent, properties, ctxt)
pc.PropertiesNil = (len(properties) == 0)
pc.StyleSet = true
}
// GetProperties gets properties values from current style settings,
// for any non-default settings, setting name-value pairs in given map,
// which must be non-nil.
func (pc *Paint) GetProperties(properties map[string]any) {
pc.toProperties(properties)
}
func (pc *Paint) FromStyle(st *Style) {
pc.UnitContext = st.UnitContext
st.SetRichText(&pc.Font, &pc.Text)
}
// ToDotsImpl runs ToDots on unit values, to compile down to raw pixels
func (pc *Paint) ToDotsImpl(uc *units.Context) {
pc.Path.ToDotsImpl(uc)
// pc.Font.ToDots(uc)
pc.Text.ToDots(uc)
}
// SetUnitContextExt sets the unit context for external usage of paint
// outside of Core Scene context, based on overall size of painting canvas.
// caches everything out in terms of raw pixel dots for rendering
// call at start of render.
func (pc *Paint) SetUnitContextExt(size image.Point) {
if pc.UnitContext.DPI == 0 {
pc.UnitContext.Defaults()
}
// TODO: maybe should have different values for these sizes?
pc.UnitContext.SetSizes(float32(size.X), float32(size.Y), float32(size.X), float32(size.Y), float32(size.X), float32(size.Y))
// todo: need a shaper here to get SetUnitContext call
// pc.Font.SetUnitContext(&pc.UnitContext)
pc.ToDotsImpl(&pc.UnitContext)
pc.dotsSet = true
}
// ToDots runs ToDots on unit values, to compile down to raw pixels
func (pc *Paint) ToDots() {
if !pc.dotsSet || pc.UnitContext != pc.lastUnCtxt || !pc.PropertiesNil {
pc.ToDotsImpl(&pc.UnitContext)
pc.dotsSet = true
pc.lastUnCtxt = pc.UnitContext
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package styles
import (
"log"
"strconv"
"strings"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/colors"
"cogentcore.org/core/colors/gradient"
"cogentcore.org/core/enums"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint/ppath"
"cogentcore.org/core/styles/styleprops"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/text"
)
/////// see style_props.go for master version
// fromProperties sets style field values based on map[string]any properties
func (pc *Path) fromProperties(parent *Path, properties map[string]any, cc colors.Context) {
for key, val := range properties {
if len(key) == 0 {
continue
}
if key[0] == '#' || key[0] == '.' || key[0] == ':' || key[0] == '_' {
continue
}
if key == "display" {
if inh, init := styleprops.InhInit(val, parent); inh || init {
if inh {
pc.Display = parent.Display
} else if init {
pc.Display = true
}
continue
}
sval := reflectx.ToString(val)
switch sval {
case "none":
pc.Display = false
case "inline":
pc.Display = true
default:
pc.Display = true
}
continue
}
if sfunc, ok := styleStrokeFuncs[key]; ok {
if parent != nil {
sfunc(&pc.Stroke, key, val, &parent.Stroke, cc)
} else {
sfunc(&pc.Stroke, key, val, nil, cc)
}
continue
}
if sfunc, ok := styleFillFuncs[key]; ok {
if parent != nil {
sfunc(&pc.Fill, key, val, &parent.Fill, cc)
} else {
sfunc(&pc.Fill, key, val, nil, cc)
}
continue
}
if sfunc, ok := stylePathFuncs[key]; ok {
sfunc(pc, key, val, parent, cc)
continue
}
}
}
// fromProperties sets style field values based on map[string]any properties
func (pc *Paint) fromProperties(parent *Paint, properties map[string]any, cc colors.Context) {
var ppath *Path
var pfont *rich.Style
var ptext *text.Style
if parent != nil {
ppath = &parent.Path
pfont = &parent.Font
ptext = &parent.Text
}
pc.Path.fromProperties(ppath, properties, cc)
pc.Font.FromProperties(pfont, properties, cc)
pc.Text.FromProperties(ptext, properties, cc)
for key, val := range properties {
_ = val
if len(key) == 0 {
continue
}
if key[0] == '#' || key[0] == '.' || key[0] == ':' || key[0] == '_' {
continue
}
// todo: add others here
}
}
//////// Stroke
// styleStrokeFuncs are functions for styling the Stroke object
var styleStrokeFuncs = map[string]styleprops.Func{
"stroke": func(obj any, key string, val any, parent any, cc colors.Context) {
fs := obj.(*Stroke)
if inh, init := styleprops.InhInit(val, parent); inh || init {
if inh {
fs.Color = parent.(*Stroke).Color
} else if init {
fs.Color = colors.Uniform(colors.Black)
}
return
}
// an invalid color is ignored, as in CSS (it keeps the inherited or initial one)
if c, err := gradient.FromAny(val, cc); err == nil {
fs.Color = c
} else {
errors.Log(err)
}
},
"stroke-opacity": styleprops.Float(float32(1),
func(obj *Stroke) *float32 { return &(obj.Opacity) }),
"stroke-width": styleprops.Units(units.Dp(1),
func(obj *Stroke) *units.Value { return &(obj.Width) }),
"stroke-dasharray": func(obj any, key string, val any, parent any, cc colors.Context) {
fs := obj.(*Stroke)
if inh, init := styleprops.InhInit(val, parent); inh || init {
if inh {
fs.Dashes = parent.(*Stroke).Dashes
} else if init {
fs.Dashes = nil
}
return
}
switch vt := val.(type) {
case string:
fs.Dashes = parseDashesString(vt)
case []float32:
math32.CopyFloat32s(&fs.Dashes, vt)
case *[]float32:
math32.CopyFloat32s(&fs.Dashes, *vt)
}
},
"stroke-linecap": styleprops.Enum(ppath.CapButt,
func(obj *Stroke) enums.EnumSetter { return &(obj.Cap) }),
"stroke-linejoin": styleprops.Enum(ppath.JoinMiter,
func(obj *Stroke) enums.EnumSetter { return &(obj.Join) }),
"stroke-miterlimit": styleprops.Float(float32(1),
func(obj *Stroke) *float32 { return &(obj.MiterLimit) }),
}
//////// Fill
// styleFillFuncs are functions for styling the Fill object
var styleFillFuncs = map[string]styleprops.Func{
"fill": func(obj any, key string, val any, parent any, cc colors.Context) {
fs := obj.(*Fill)
if inh, init := styleprops.InhInit(val, parent); inh || init {
if inh {
fs.Color = parent.(*Fill).Color
} else if init {
fs.Color = colors.Uniform(colors.Black)
}
return
}
// an invalid color is ignored, as in CSS (it keeps the inherited or initial one)
if c, err := gradient.FromAny(val, cc); err == nil {
fs.Color = c
} else {
errors.Log(err)
}
},
"fill-opacity": styleprops.Float(float32(1),
func(obj *Fill) *float32 { return &(obj.Opacity) }),
"fill-rule": styleprops.Enum(ppath.NonZero,
func(obj *Fill) enums.EnumSetter { return &(obj.Rule) }),
}
//////// Paint
// stylePathFuncs are functions for styling the Stroke object
var stylePathFuncs = map[string]styleprops.Func{
"vector-effect": styleprops.Enum(ppath.VectorEffectNone,
func(obj *Path) enums.EnumSetter { return &(obj.VectorEffect) }),
"opacity": styleprops.Float(float32(1),
func(obj *Path) *float32 { return &(obj.Opacity) }),
"transform": func(obj any, key string, val any, parent any, cc colors.Context) {
pc := obj.(*Path)
if inh, init := styleprops.InhInit(val, parent); inh || init {
if inh {
pc.Transform = parent.(*Path).Transform
} else if init {
pc.Transform = math32.Identity2()
}
return
}
switch vt := val.(type) {
case string:
pc.Transform.SetString(vt)
case *math32.Matrix2:
pc.Transform = *vt
case math32.Matrix2:
pc.Transform = vt
}
},
}
// parseDashesString gets a dash slice from given string
func parseDashesString(str string) []float32 {
if len(str) == 0 || str == "none" {
return nil
}
// separated by commas and/or spaces, with optional px units
ds := strings.Fields(strings.ReplaceAll(str, ",", " "))
dl := make([]float32, len(ds))
for i, dstr := range ds {
d, err := strconv.ParseFloat(strings.TrimSuffix(dstr, "px"), 32)
if err != nil {
log.Printf("core.ParseDashesString parsing error: %v\n", err)
return nil
}
dl[i] = float32(d)
}
if len(dl)%2 == 1 { // an odd list is repeated, as in SVG
dl = append(dl, dl...)
}
return dl
}
//////// ToProperties
// toProperties sets map[string]any properties based on non-default style values.
// properties map must be non-nil.
func (pc *Path) toProperties(p map[string]any) {
if !pc.Display {
p["display"] = "none"
return
}
pc.Stroke.toProperties(p)
pc.Fill.toProperties(p)
}
// toProperties sets map[string]any properties based on non-default style values.
// properties map must be non-nil.
func (pc *Paint) toProperties(p map[string]any) {
pc.Path.toProperties(p)
if !pc.Display {
return
}
}
// toProperties sets map[string]any properties based on non-default style values.
// properties map must be non-nil.
func (ss *Stroke) toProperties(p map[string]any) {
if ss.Color == nil {
p["stroke"] = "none"
return
}
// todo: gradients!
p["stroke"] = colors.AsHex(colors.ToUniform(ss.Color))
if ss.Opacity != 1 {
p["stroke-opacity"] = reflectx.ToString(ss.Opacity)
}
if ss.Width.Unit != units.UnitDp || ss.Width.Value != 1 {
p["stroke-width"] = ss.Width.StringCSS()
}
// todo: dashes
if ss.Cap != ppath.CapButt {
p["stroke-linecap"] = ss.Cap.String()
}
if ss.Join != ppath.JoinMiter {
p["stroke-linejoin"] = ss.Join.String()
}
}
// toProperties sets map[string]any properties based on non-default style values.
// properties map must be non-nil.
func (fs *Fill) toProperties(p map[string]any) {
if fs.Color == nil {
p["fill"] = "none"
return
}
p["fill"] = colors.AsHex(colors.ToUniform(fs.Color))
if fs.Opacity != 1 {
p["fill-opacity"] = reflectx.ToString(fs.Opacity)
}
if fs.Rule != ppath.NonZero {
p["fill-rule"] = fs.Rule.String()
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package styles
import (
"image"
"image/color"
"cogentcore.org/core/colors"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint/ppath"
"cogentcore.org/core/styles/units"
)
// Path provides the styling parameters for path-level rendering:
// Stroke and Fill.
type Path struct { //types:add
// Off indicates that node and everything below it are off, non-rendering.
// This is auto-updated based on other settings.
Off bool
// Display is the user-settable flag that determines if this item
// should be displayed.
Display bool
// Stroke (line drawing) parameters.
Stroke Stroke `display:"add-fields"`
// Fill (region filling) parameters.
Fill Fill
// Opacity is a global transparency alpha factor that applies to stroke and fill.
Opacity float32
// Transform has our additions to the transform stack.
Transform math32.Matrix2 `display:"inline"`
// VectorEffect has various rendering special effects settings.
VectorEffect ppath.VectorEffects
// UnitContext has parameters necessary for determining unit sizes.
UnitContext units.Context `display:"-"`
// StyleSet indicates if the styles already been set.
StyleSet bool `display:"-"`
PropertiesNil bool `display:"-"`
dotsSet bool
lastUnCtxt units.Context
}
func (pc *Path) Defaults() {
pc.Off = false
pc.Display = true
pc.Stroke.Defaults()
pc.Fill.Defaults()
pc.Opacity = 1
pc.Transform = math32.Identity2()
pc.StyleSet = false
}
// CopyStyleFrom copies styles from another paint
func (pc *Path) CopyStyleFrom(cp *Path) {
pc.Off = cp.Off
pc.UnitContext = cp.UnitContext
pc.Stroke = cp.Stroke
pc.Fill = cp.Fill
pc.VectorEffect = cp.VectorEffect
}
// SetProperties sets path values based on given property map (name: value
// pairs), inheriting elements as appropriate from parent, and also having a
// default style for the "initial" setting
func (pc *Path) SetProperties(parent *Path, properties map[string]any, ctxt colors.Context) {
pc.fromProperties(parent, properties, ctxt)
pc.PropertiesNil = (len(properties) == 0)
pc.StyleSet = true
}
// GetProperties gets properties values from current style settings,
// for any non-default settings, setting name-value pairs in given map,
// which must be non-nil.
func (pc *Path) GetProperties(properties map[string]any) {
pc.toProperties(properties)
}
func (pc *Path) FromStyle(st *Style) {
pc.UnitContext = st.UnitContext
}
// ToDotsImpl runs ToDots on unit values, to compile down to raw pixels
func (pc *Path) ToDotsImpl(uc *units.Context) {
pc.Stroke.ToDots(uc)
pc.Fill.ToDots(uc)
}
func (pc *Path) HasFill() bool {
return !pc.Off && pc.Fill.Color != nil && pc.Fill.Opacity > 0
}
func (pc *Path) HasStroke() bool {
return !pc.Off && pc.Stroke.Color != nil && pc.Stroke.Width.Dots > 0 && pc.Stroke.Opacity > 0
}
//////// Stroke and Fill Styles
// IMPORTANT: any changes here must be updated in StyleFillFuncs
// Fill contains all the properties for filling a region.
type Fill struct {
// Color to use in filling; filling is off if nil.
Color image.Image
// Fill alpha opacity / transparency factor between 0 and 1.
// This applies in addition to any alpha specified in the Color.
Opacity float32
// Rule for how to fill more complex shapes with crossing lines.
Rule ppath.FillRules
}
// Defaults initializes default values for paint fill
func (fs *Fill) Defaults() {
fs.Color = colors.Uniform(color.Black)
fs.Rule = ppath.NonZero
fs.Opacity = 1.0
}
// ToDots runs ToDots on unit values, to compile down to raw pixels
func (fs *Fill) ToDots(uc *units.Context) {
}
//////// Stroke
// IMPORTANT: any changes here must be updated below in StyleStrokeFuncs
// Stroke contains all the properties for painting a line.
type Stroke struct {
// stroke color image specification; stroking is off if nil
Color image.Image
// global alpha opacity / transparency factor between 0 and 1
Opacity float32
// line width
Width units.Value
// Dashes are the dashes of the stroke. Each pair of values specifies
// the amount to paint and then the amount to skip.
Dashes []float32
// DashOffset is the starting offset for the dashes.
DashOffset float32
// Cap specifies how to draw the end cap of stroked lines.
Cap ppath.Caps
// Join specifies how to join line segments.
Join ppath.Joins
// MiterLimit is the limit of how far to miter: must be 1 or larger.
MiterLimit float32 `min:"1"`
}
// Defaults initializes default values for paint stroke
func (ss *Stroke) Defaults() {
// stroking is off by default in svg
ss.Color = nil
ss.Width.Dp(1)
ss.Cap = ppath.CapButt
ss.Join = ppath.JoinMiter
ss.MiterLimit = 10.0
ss.Opacity = 1.0
}
// ToDots runs ToDots on unit values, to compile down to raw pixels
func (ss *Stroke) ToDots(uc *units.Context) {
ss.Width.ToDots(uc)
}
// ApplyBorderStyle applies the given border style to the stroke style.
func (ss *Stroke) ApplyBorderStyle(bs BorderStyles) {
switch bs {
case BorderNone:
ss.Color = nil
case BorderDotted:
ss.Dashes = []float32{0, 12}
ss.Cap = ppath.CapRound
case BorderDashed:
ss.Dashes = []float32{8, 6}
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package sides provides flexible representation of box sides
// or corners, with either a single value for all, or different values
// for subsets.
package sides
//go:generate core generate
import (
"fmt"
"image/color"
"strings"
"log/slog"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/colors"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles/units"
)
// Indexes provides names for the Sides in order defined
type Indexes int32 //enums:enum
const (
Top Indexes = iota
Right
Bottom
Left
)
// Sides contains values for each side or corner of a box.
// If Sides contains sides, the struct field names correspond
// directly to the side values (ie: Top = top side value).
// If Sides contains corners, the struct field names correspond
// to the corners as follows: Top = top left, Right = top right,
// Bottom = bottom right, Left = bottom left.
type Sides[T any] struct { //types:add
// top/top-left value
Top T
// right/top-right value
Right T
// bottom/bottom-right value
Bottom T
// left/bottom-left value
Left T
}
// NewSides is a helper that creates new sides/corners of the given type
// and calls Set on them with the given values.
func NewSides[T any](vals ...T) *Sides[T] {
return (&Sides[T]{}).Set(vals...)
}
// Set sets the values of the sides/corners from the given list of 0 to 4 values.
// If 0 values are provided, all sides/corners are set to the zero value of the type.
// If 1 value is provided, all sides/corners are set to that value.
// If 2 values are provided, the top/top-left and bottom/bottom-right are set to the first value
// and the right/top-right and left/bottom-left are set to the second value.
// If 3 values are provided, the top/top-left is set to the first value,
// the right/top-right and left/bottom-left are set to the second value,
// and the bottom/bottom-right is set to the third value.
// If 4 values are provided, the top/top-left is set to the first value,
// the right/top-right is set to the second value, the bottom/bottom-right is set
// to the third value, and the left/bottom-left is set to the fourth value.
// If more than 4 values are provided, the behavior is the same
// as with 4 values, but Set also logs a programmer error.
// This behavior is based on the CSS multi-side/corner setting syntax,
// like that with padding and border-radius (see https://www.w3schools.com/css/css_padding.asp
// and https://www.w3schools.com/cssref/css3_pr_border-radius.php)
func (s *Sides[T]) Set(vals ...T) *Sides[T] {
switch len(vals) {
case 0:
var zval T
s.SetAll(zval)
case 1:
s.SetAll(vals[0])
case 2:
s.SetVertical(vals[0])
s.SetHorizontal(vals[1])
case 3:
s.Top = vals[0]
s.SetHorizontal(vals[1])
s.Bottom = vals[2]
case 4:
s.Top = vals[0]
s.Right = vals[1]
s.Bottom = vals[2]
s.Left = vals[3]
default:
s.Top = vals[0]
s.Right = vals[1]
s.Bottom = vals[2]
s.Left = vals[3]
slog.Error("programmer error: sides.Set: expected 0 to 4 values, but got", "numValues", len(vals))
}
return s
}
// Zero sets the values of all of the sides to zero.
func (s *Sides[T]) Zero() *Sides[T] {
s.Set()
return s
}
// SetVertical sets the values for the sides/corners in the
// vertical/diagonally descending direction
// (top/top-left and bottom/bottom-right) to the given value
func (s *Sides[T]) SetVertical(val T) *Sides[T] {
s.Top = val
s.Bottom = val
return s
}
// SetHorizontal sets the values for the sides/corners in the
// horizontal/diagonally ascending direction
// (right/top-right and left/bottom-left) to the given value
func (s *Sides[T]) SetHorizontal(val T) *Sides[T] {
s.Right = val
s.Left = val
return s
}
// SetAll sets the values for all of the sides/corners
// to the given value
func (s *Sides[T]) SetAll(val T) *Sides[T] {
s.Top = val
s.Right = val
s.Bottom = val
s.Left = val
return s
}
// SetTop sets the top side to the given value
func (s *Sides[T]) SetTop(top T) *Sides[T] {
s.Top = top
return s
}
// SetRight sets the right side to the given value
func (s *Sides[T]) SetRight(right T) *Sides[T] {
s.Right = right
return s
}
// SetBottom sets the bottom side to the given value
func (s *Sides[T]) SetBottom(bottom T) *Sides[T] {
s.Bottom = bottom
return s
}
// SetLeft sets the left side to the given value
func (s *Sides[T]) SetLeft(left T) *Sides[T] {
s.Left = left
return s
}
// SetAny sets the sides/corners from the given value of any type
func (s *Sides[T]) SetAny(a any) error {
switch val := a.(type) {
case Sides[T]:
*s = val
case *Sides[T]:
*s = *val
case T:
s.SetAll(val)
case *T:
s.SetAll(*val)
case []T:
s.Set(val...)
case *[]T:
s.Set(*val...)
case string:
return s.SetString(val)
default:
return s.SetString(fmt.Sprint(val))
}
return nil
}
// SetString sets the sides/corners from the given string value
func (s *Sides[T]) SetString(str string) error {
fields := strings.Fields(str)
vals := make([]T, len(fields))
for i, field := range fields {
ss, ok := any(&vals[i]).(reflectx.SetStringer)
if !ok {
err := fmt.Errorf("(Sides).SetString('%s'): to set from a string, the sides type (%T) must implement reflectx.SetStringer (needs SetString(str string) error function)", str, s)
slog.Error(err.Error())
return err
}
err := ss.SetString(field)
if err != nil {
nerr := fmt.Errorf("(Sides).SetString('%s'): error setting sides of type %T from string: %w", str, s, err)
slog.Error(nerr.Error())
return nerr
}
}
s.Set(vals...)
return nil
}
// AreSame returns whether all of the sides/corners are the same
func AreSame[T comparable](s Sides[T]) bool {
return s.Right == s.Top && s.Bottom == s.Top && s.Left == s.Top
}
// AreZero returns whether all of the sides/corners are equal to zero
func AreZero[T comparable](s Sides[T]) bool {
var zv T
return s.Top == zv && s.Right == zv && s.Bottom == zv && s.Left == zv
}
// Values contains units.Value values for each side/corner of a box
type Values struct { //types:add
Sides[units.Value]
}
// NewValues is a helper that creates new side/corner values
// and calls Set on them with the given values.
func NewValues(vals ...units.Value) Values {
sides := Sides[units.Value]{}
sides.Set(vals...)
return Values{sides}
}
// newValues returns side/corner values with the given value for each
// side/corner, without the slice and the switch of [NewValues].
func newValues(top, right, bottom, left units.Value) Values {
return Values{Sides[units.Value]{Top: top, Right: right, Bottom: bottom, Left: left}}
}
// ToDots converts the values for each of the sides/corners
// to raw display pixels (dots) and sets the Dots field for each
// of the values. It returns the dot values as a Floats.
func (sv *Values) ToDots(uc *units.Context) Floats {
return newFloats(
sv.Top.ToDots(uc),
sv.Right.ToDots(uc),
sv.Bottom.ToDots(uc),
sv.Left.ToDots(uc),
)
}
// Dots returns the dot values of the sides/corners as a Floats.
// It does not compute them; see ToDots for that.
func (sv Values) Dots() Floats {
return newFloats(
sv.Top.Dots,
sv.Right.Dots,
sv.Bottom.Dots,
sv.Left.Dots,
)
}
// Floats contains float32 values for each side/corner of a box
type Floats struct { //types:add
Sides[float32]
}
// NewFloats is a helper that creates new side/corner floats
// and calls Set on them with the given values.
func NewFloats(vals ...float32) Floats {
sides := Sides[float32]{}
sides.Set(vals...)
return Floats{sides}
}
// newFloats returns side/corner floats with the given value for each
// side/corner, without the slice and the switch of [NewFloats].
func newFloats(top, right, bottom, left float32) Floats {
return Floats{Sides[float32]{Top: top, Right: right, Bottom: bottom, Left: left}}
}
// Add adds the side floats to the
// other side floats and returns the result
func (sf Floats) Add(other Floats) Floats {
return newFloats(
sf.Top+other.Top,
sf.Right+other.Right,
sf.Bottom+other.Bottom,
sf.Left+other.Left,
)
}
// Sub subtracts the other side floats from
// the side floats and returns the result
func (sf Floats) Sub(other Floats) Floats {
return newFloats(
sf.Top-other.Top,
sf.Right-other.Right,
sf.Bottom-other.Bottom,
sf.Left-other.Left,
)
}
// MulScalar multiplies each side by the given scalar value
// and returns the result.
func (sf Floats) MulScalar(s float32) Floats {
return newFloats(
sf.Top*s,
sf.Right*s,
sf.Bottom*s,
sf.Left*s,
)
}
// Min returns a new side floats containing the
// minimum values of the two side floats
func (sf Floats) Min(other Floats) Floats {
return newFloats(
math32.Min(sf.Top, other.Top),
math32.Min(sf.Right, other.Right),
math32.Min(sf.Bottom, other.Bottom),
math32.Min(sf.Left, other.Left),
)
}
// Max returns a new side floats containing the
// maximum values of the two side floats
func (sf Floats) Max(other Floats) Floats {
return newFloats(
math32.Max(sf.Top, other.Top),
math32.Max(sf.Right, other.Right),
math32.Max(sf.Bottom, other.Bottom),
math32.Max(sf.Left, other.Left),
)
}
// Round returns a new side floats with each side value
// rounded to the nearest whole number.
func (sf Floats) Round() Floats {
return newFloats(
math32.Round(sf.Top),
math32.Round(sf.Right),
math32.Round(sf.Bottom),
math32.Round(sf.Left),
)
}
// Pos returns the position offset casued by the side/corner values (Left, Top)
func (sf Floats) Pos() math32.Vector2 {
return math32.Vec2(sf.Left, sf.Top)
}
// Size returns the toal size the side/corner values take up (Left + Right, Top + Bottom)
func (sf Floats) Size() math32.Vector2 {
return math32.Vec2(sf.Left+sf.Right, sf.Top+sf.Bottom)
}
// ToValues returns the side floats a
// Values composed of [units.UnitDot] values
func (sf Floats) ToValues() Values {
return newValues(
units.Dot(sf.Top),
units.Dot(sf.Right),
units.Dot(sf.Bottom),
units.Dot(sf.Left),
)
}
// Colors contains color values for each side/corner of a box
type Colors struct { //types:add
Sides[color.RGBA]
}
// NewColors is a helper that creates new side/corner colors
// and calls Set on them with the given values.
// It does not return any error values and just logs them.
func NewColors(vals ...color.RGBA) Colors {
sides := Sides[color.RGBA]{}
sides.Set(vals...)
return Colors{sides}
}
// SetAny sets the sides/corners from the given value of any type
func (s *Colors) SetAny(a any, base color.Color) error {
switch val := a.(type) {
case Sides[color.RGBA]:
s.Sides = val
case *Sides[color.RGBA]:
s.Sides = *val
case color.RGBA:
s.SetAll(val)
case *color.RGBA:
s.SetAll(*val)
case []color.RGBA:
s.Set(val...)
case *[]color.RGBA:
s.Set(*val...)
case string:
return s.SetString(val, base)
default:
return s.SetString(fmt.Sprint(val), base)
}
return nil
}
// SetString sets the sides/corners from the given string value
func (s *Colors) SetString(str string, base color.Color) error {
fields := strings.Fields(str)
vals := make([]color.RGBA, len(fields))
for i, field := range fields {
clr, err := colors.FromString(field, base)
if err != nil {
nerr := fmt.Errorf("(Colors).SetString('%s'): error setting sides of type %T from string: %w", str, s, err)
slog.Error(nerr.Error())
return nerr
}
vals[i] = clr
}
s.Set(vals...)
return nil
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package states provides the states of widgets, as hovered, focused, or
// active, which are used in styling them.
package states
//go:generate core generate
import "cogentcore.org/core/enums"
// States are GUI states of elements that are relevant for styling based on
// CSS pseudo-classes (https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes).
type States int32 //enums:bitflag
const (
// Invisible elements are not displayable, and thus do not present
// a target for GUI events. It is identical to CSS display:none.
// It is often used for elements such as tabs to hide elements in
// tabs that are not open. Elements can be made visible by toggling
// this flag and thus in general should be constructed and styled,
// but a new layout step must generally be taken after visibility
// status has changed. See also [cogentcore.org/core/core.WidgetBase.IsDisplayable].
Invisible States = iota
// Disabled elements cannot be interacted with or selected,
// but do display.
Disabled
// ReadOnly elements cannot be changed, but can be selected.
// A text input must not be ReadOnly for entering text.
// A button can be pressed while ReadOnly -- if not ReadOnly then
// the label on the button can be edited, for example.
ReadOnly
// Selected elements have been marked for clipboard or other such actions.
Selected
// Active elements are currently being interacted with,
// usually involving a mouse button being pressed in the element.
// A text field will be active while being clicked on, and this
// can also result in a [Focused] state.
// If further movement happens, an element can also end up being
// Dragged or Sliding.
Active
// Dragging means this element is currently being dragged
// by the mouse (i.e., a MouseDown event followed by MouseMove),
// as part of a drag-n-drop sequence.
Dragging
// Sliding means this element is currently being manipulated
// via mouse to change the slider state, which will continue
// until the mouse is released, even if it goes off the element.
// It should also still be [Active].
Sliding
// The current Focused element receives keyboard input.
// Only one element can be Focused at a time.
Focused
// Attended is the last Pressable element to be clicked on.
// Only one element can be Attended at a time.
// The main effect of Attended is on scrolling events:
// see [abilities.ScrollableUnattended]
Attended
// Checked is for check boxes or radio buttons or other similar state.
Checked
// Indeterminate indicates that the true state of an item is unknown.
// For example, [Checked] state items may be in an uncertain state
// if they represent other checked items, some of which are checked
// and some of which are not.
Indeterminate
// Hovered indicates that a mouse pointer has entered the space over
// an element, but it is not [Active] (nor [DragHovered]).
Hovered
// LongHovered indicates a Hover event that persists without significant
// movement for a minimum period of time (e.g., 500 msec),
// which typically triggers a tooltip popup.
LongHovered
// LongPressed indicates a MouseDown event that persists without significant
// movement for a minimum period of time (e.g., 500 msec),
// which typically triggers a tooltip and/or context menu popup.
LongPressed
// DragHovered indicates that a mouse pointer has entered the space over
// an element during a drag-n-drop sequence. This makes it a candidate
// for a potential drop target.
DragHovered
)
// Is is a shortcut for HasFlag for States
func (st States) Is(flag enums.BitFlag) bool {
return st.HasFlag(flag)
}
// StateLayer returns the state layer opacity for the state, appropriate for use
// as the value of [cogentcore.org/core/styles.Style.StateLayer]
func (st States) StateLayer() float32 {
switch {
case st.Is(Disabled):
return 0
case st.Is(Dragging), st.Is(LongPressed):
return 0.12
case st.Is(Active), st.Is(Focused):
return 0.10
case st.Is(Hovered), st.Is(DragHovered):
return 0.08
default:
return 0
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package styles provides style objects containing style properties
// used for GUI widgets and other rendering contexts.
package styles
//go:generate core generate
import (
"image"
"image/color"
"log/slog"
"cogentcore.org/core/colors"
"cogentcore.org/core/colors/gradient"
"cogentcore.org/core/cursors"
"cogentcore.org/core/enums"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/sides"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/text"
)
// IMPORTANT: any changes here must be updated in style_properties.go StyleStyleFuncs
// and likewise for all sub-styles as fields here.
// Style contains all of the style properties used for GUI widgets.
type Style struct { //types:add
// State holds style-relevant state flags, for convenient styling access,
// given that styles typically depend on element states.
State states.States
// Abilities specifies the abilities of this element, which determine
// which kinds of states the element can express.
// This is used by the system/events system. Putting this info next
// to the State info makes it easy to configure and manage.
Abilities abilities.Abilities
// the cursor to switch to upon hovering over the element (inherited)
Cursor cursors.Cursor
// Padding is the transparent space around central content of box,
// which is _included_ in the size of the standard box rendering.
Padding sides.Values `display:"inline"`
// Margin is the outer-most transparent space around box element,
// which is _excluded_ from standard box rendering.
Margin sides.Values `display:"inline"`
// Display controls how items are displayed, in terms of layout
Display Displays
// Direction specifies the way in which elements are laid out, or
// the dimension on which an element is longer / travels in.
Direction Directions
// Wrap causes elements to wrap around in the CrossAxis dimension
// to fit within sizing constraints.
Wrap bool
// Justify specifies the distribution of elements along the main axis,
// i.e., the same as Direction, for Flex Display. For Grid, the main axis is
// given by the writing direction (e.g., Row-wise for latin based languages).
Justify AlignSet `display:"inline"`
// Align specifies the cross-axis alignment of elements, orthogonal to the
// main Direction axis. For Grid, the cross-axis is orthogonal to the
// writing direction (e.g., Column-wise for latin based languages).
Align AlignSet `display:"inline"`
// Min is the minimum size of the actual content, exclusive of additional space
// from padding, border, margin; 0 = default is sum of Min for all content
// (which _includes_ space for all sub-elements).
// This is equivalent to the Basis for the CSS flex styling model.
Min units.XY `display:"inline"`
// Max is the maximum size of the actual content, exclusive of additional space
// from padding, border, margin; 0 = default provides no Max size constraint
Max units.XY `display:"inline"`
// Grow is the proportional amount that the element can grow (stretch)
// if there is more space available. 0 = default = no growth.
// Extra available space is allocated as: Grow / sum (all Grow).
// Important: grow elements absorb available space and thus are not
// subject to alignment (Center, End).
Grow math32.Vector2
// GrowWrap is a special case for Text elements where it grows initially
// in the horizontal axis, so that its text is wrapped and aligned within
// all of the available space, but then it does not grow thereafter, so
// that alignment operations still work (Grow elements do not align because
// they absorb all available space). Text that is aligned at the start does
// not need this, as it starts out at its preferred width (its width on one
// line), so it is only set for text with other alignments (such as
// centered). Do NOT set this for non-Text elements.
GrowWrap bool
// Shrink is the proportional amount that the element shrinks in width,
// from its preferred width toward its min-content width, if there is less
// space available, as in the CSS flex-shrink property. Every element that
// can be narrower than its preferred width (such as wrapping text) shrinks:
// 0 = default = a factor of 1. In a row or a grid, the columns are narrowed
// in proportion to Shrink and their width, to fit within the frame, and an
// element in a column is at most as wide as the column. Elements that
// wrap their content (such as text) then wrap it within their width.
// Only the X (width) dimension is currently supported.
Shrink math32.Vector2
// RenderBox determines whether to render the standard box model for the element.
// This is typically necessary for most elements and helps prevent text, border,
// and box shadow from rendering over themselves. Therefore, it should be kept at
// its default value of true in most circumstances, but it can be set to false
// when the element is fully managed by something that is guaranteed to render the
// appropriate background color and/or border for the element.
//
// If you want to overlay widgets on top of each other, you might want
// to use RenderBox so that the widget(s) on top do not fully obscure
// the widgets below. (To place widgets on top of each other,
// set [Style.Display] = [Custom] on the parent widget).
RenderBox bool
// FillMargin determines is whether to fill the margin with
// the surrounding background color before rendering the element itself.
// This is typically necessary to prevent text, border, and box shadow from
// rendering over themselves. Therefore, it should be kept at its default value
// of true in most circumstances, but it can be set to false when the element
// is fully managed by something that is guaranteed to render the
// appropriate background color for the element. It is irrelevant if RenderBox
// is false.
FillMargin bool
// Overflow determines how to handle overflowing content in a layout.
// Default is OverflowVisible. Set to OverflowAuto to enable scrollbars.
Overflow XY[Overflows]
// For layouts, extra space added between elements in the layout.
Gap units.XY `display:"inline"`
// For grid layouts, the number of columns to use.
// If > 0, number of rows is computed as N elements / Columns.
// Used as a constraint in layout if individual elements
// do not specify their row, column positions
Columns int
// If this object is a replaced object (image, video, etc)
// or has a background image, ObjectFit specifies the way
// in which the replaced object should be fit into the element.
ObjectFit ObjectFits
// If this object is a replaced object (image, video, etc)
// or has a background image, ObjectPosition specifies the
// X,Y position of the object within the space allocated for
// the object (see ObjectFit).
ObjectPosition units.XY
// Border is a rendered border around the element.
Border Border
// MaxBorder is the largest border that will ever be rendered
// around the element, the size of which is used for computing
// the effective margin to allocate for the element.
MaxBorder Border
// BoxShadow is the box shadows to render around box (can have multiple)
BoxShadow []Shadow
// MaxBoxShadow contains the largest shadows that will ever be rendered
// around the element, the size of which are used for computing the
// effective margin to allocate for the element.
MaxBoxShadow []Shadow
// ContentMinWidth is whether the width of the element is at least the
// min-content width of its content, even over its Max width, as for the
// width of a table in CSS (with an automatic layout), which is as wide
// as its cells need to be when they are wider than it.
ContentMinWidth bool
// MaxContentWidth is whether the width of the element is the width of
// its content without wrapping (its preferred width), whatever the width
// that it is given, which it then overflows, as for a width of
// max-content in CSS (as a ticker of items in a row that scrolls).
MaxContentWidth bool
// FixedSpacing is whether the spacing of the element (its margin,
// padding and gap) is fixed: not scaled by the Spacing setting of the app
// (see core.AppearanceSettingsData.Spacing), as for the elements of
// web pages, whose spacing is that of their CSS. (The FontSize
// setting still applies.)
FixedSpacing bool
// FlexBasis, if positive, is the width that the widget starts from in a
// row that wraps, which its line needs room for (down to its min-content
// width), instead of its preferred width, as the flex-basis of CSS (as
// the hypothetical main size of a flex item). It grows and shrinks from
// there by Grow and Shrink, as usual.
FlexBasis units.Value
// AspectRatio, if positive, is the ratio of the width to the height of
// the element, from which its height follows its width when its height
// is not set (by its Min), as the aspect-ratio property of CSS (its
// content can still make it higher). It is of the content box, or of
// the border box for [BoxBorderBox].
AspectRatio float32
// Contain is the dimensions in which the size of the element does not
// depend on its content, as the size containment of CSS (for container
// queries, which are of the size of the container, so its content
// cannot change it).
Contain Containments
// BoxShadowOutside is whether the box shadows are outside of the
// layout of the element, as in CSS: no space is allocated for them
// around it (they are not in its effective margin), and they are
// rendered around its box, outside of its bounds.
BoxShadowOutside bool
// Color specifies the text / content color, and it is inherited.
Color image.Image
// Background specifies the background of the element. It is not inherited,
// and it is nil (transparent) by default.
Background image.Image
// alpha value between 0 and 1 to apply to the foreground and background
// of this element and all of its children.
Opacity float32
// Zoom, if positive, is a factor that all of the absolute sizes of the
// widget (as dp, px, and pt, and its font sizes) are multiplied by,
// as the DPI of its [units.Context] is. It is inherited, as for zooming
// the content of a frame (as a page in a web browser). Zero is 1.
Zoom float32
// StateLayer, if above zero, indicates to create a state layer over
// the element with this much opacity (on a scale of 0-1) and the
// color Color (or StateColor if it defined). It is automatically
// set based on State, but can be overridden in stylers.
StateLayer float32
// StateColor, if not nil, is the color to use for the StateLayer
// instead of Color. If you want to disable state layers
// for an element, do not use this; instead, set StateLayer to 0.
StateColor image.Image
// ActualBackground is the computed actual background rendered for the element,
// taking into account its Background, Opacity, StateLayer, and parent
// ActualBackground. It is automatically computed and should not be set manually.
ActualBackground image.Image
// VirtualKeyboard is the virtual keyboard to display, if any,
// on mobile platforms when this element is focused. It is not
// used if the element is read only.
VirtualKeyboard VirtualKeyboards
// Pos is used for the position of the widget if the parent frame
// has [Style.Display] = [Custom].
Pos units.XY `display:"inline"`
// Position is the way that the widget is positioned, as with the
// position property of CSS. The default, [PositionStatic], is in the
// layout of its parent. See [Positions] for the others, which are
// positioned by [Style.Inset].
Position Positions
// Inset has the offsets (top, right, bottom, left) of the edges of
// a widget that is not [PositionStatic] from those of its containing
// block ([PositionAbsolute], [PositionFixed]), or from its position in
// the layout ([PositionRelative]), for the sides in [Style.InsetSet].
Inset sides.Values `display:"inline"`
// InsetSet has the sides of [Style.Inset] that are set, as opposed to
// auto (the default), for which the size or the position in the layout
// of the widget determine its position.
InsetSet sides.Sides[bool] `display:"inline"`
// InsetCenter is, for each dimension (X, Y), whether a widget that is
// not [PositionStatic] and has both of its insets set in it (as left
// and right) keeps its own size in it, centered between them, instead
// of being stretched to them, as for auto margins of an element with a
// definite size in CSS (as a modal dialog, centered in the window).
InsetCenter [2]bool
// Translate moves the widget from its position by this offset when it
// is rendered, without changing the layout, as the translate of the
// transform property of CSS. Percentages of the element width and
// height ([units.UnitEw], [units.UnitEh]) are of its own size.
Translate units.XY `display:"inline"`
// Rotate rotates the rendering of the widget by this angle in degrees
// (clockwise) around its center, without changing the layout, as the
// rotate of the transform property of CSS.
Rotate float32
// Float makes the widget float to the left or right of its parent,
// as the float property of CSS: it is out of the flow of the layout of
// its parent (a column), and the widgets after it that start beside it
// are narrowed to be beside it.
Float Floats
// Clear moves the widget down below the widgets before it that float
// on the given sides, as the clear property of CSS.
Clear Clears
// NoClip is whether the children of the widget are not clipped to its
// content box, as for content that overflows it in CSS with visible
// overflow: they are clipped by the nearest widget that it is in that
// does clip (or scrolls) instead.
NoClip bool
// BoxSizing is whether the Min and Max sizes are of the content
// (the default), or also include the padding and border, as the
// box-sizing property of CSS.
BoxSizing BoxSizings
// ZIndex orders the rendering of widgets that are not [PositionStatic],
// or that are and have a ZIndex other than 0 (as the flex and grid items
// of CSS with a z-index), as the z-index property of CSS: they are
// rendered after the other children of their parent (on top of them),
// in increasing order of ZIndex, except that those with a negative
// ZIndex are rendered first.
ZIndex int
// specifies the number of sequential columns that this element should occupy
// within a grid layout
ColSpan int
// RowSpan is the number of sequential rows that this element occupies
// within a grid layout. The cells after it in the rows below it are
// placed in the columns after it.
RowSpan int
// ScrollbarWidth is the width of layout scrollbars. It defaults
// to [DefaultScrollbarWidth], and it is inherited.
ScrollbarWidth units.Value
// IconSize specifies the size of icons in this widget, if it has icons.
// The default icon size is 1em for X and Y. This is inherited.
IconSize units.XY `display:"inline"`
// Font styling parameters applicable to individual spans of text.
Font Font
// Text styling parameters applicable to a paragraph of text.
Text Text
// unit context: parameters necessary for anchoring relative units
UnitContext units.Context
}
func (s *Style) Defaults() {
// mostly all the defaults are 0 initial values, except these..
s.UnitContext.Defaults()
s.LayoutDefaults()
s.Color = colors.Scheme.OnSurface
s.Border.Color.Set(colors.Scheme.Outline)
s.Opacity = 1
s.RenderBox = true
s.FillMargin = true
s.IconSize.Set(units.Em(1))
s.Font.Defaults()
s.Text.Defaults()
}
// ZeroSpace sets all the spacing elements to zero: Padding, Border, Margin, Gap
func (s *Style) ZeroSpace() {
s.Padding.Zero()
s.Margin.Zero()
s.MaxBorder.Width.Zero()
s.Border.Width.Zero()
s.Gap.Zero()
s.BoxShadow = nil
s.MaxBoxShadow = nil
}
// VirtualKeyboards are all of the supported virtual keyboard types
// to display on mobile platforms.
type VirtualKeyboards int32 //enums:enum -trim-prefix Keyboard -transform kebab
const (
// KeyboardNone indicates to display no virtual keyboard.
KeyboardNone VirtualKeyboards = iota
// KeyboardSingleLine indicates to display a virtual keyboard
// with a default input style and a "Done" return key.
KeyboardSingleLine
// KeyboardMultiLine indicates to display a virtual keyboard
// with a default input style and a "Return" return key.
KeyboardMultiLine
// KeyboardNumber indicates to display a virtual keyboard
// for inputting a number.
KeyboardNumber
// KeyboardPassword indicates to display a virtual keyboard
// for inputting a password.
KeyboardPassword
// KeyboardEmail indicates to display a virtual keyboard
// for inputting an email address.
KeyboardEmail
// KeyboardPhone indicates to display a virtual keyboard
// for inputting a phone number.
KeyboardPhone
// KeyboardURL indicates to display a virtual keyboard for
// inputting a URL / URI / web address.
KeyboardURL
)
// todo: Animation
// Clear -- no floating elements
// Clip -- clip images
// column- settings -- lots of those
// List-style for lists
// Object-fit for videos
// visibility -- support more than just hidden
// transition -- animation of hover, etc
// NewStyle returns a new [Style] object with default values.
func NewStyle() *Style {
s := &Style{}
s.Defaults()
return s
}
// Is returns whether the given [states.States] flag is set
func (s *Style) Is(st states.States) bool {
return s.State.HasFlag(st)
}
// AbilityIs returns whether the given [abilities.Abilities] flag is set
func (s *Style) AbilityIs(able abilities.Abilities) bool {
return s.Abilities.HasFlag(able)
}
// SetState sets the given [states.States] flags to the given value
func (s *Style) SetState(on bool, state ...states.States) *Style {
bfs := make([]enums.BitFlag, len(state))
for i, st := range state {
bfs[i] = st
}
s.State.SetFlag(on, bfs...)
return s
}
// SetEnabled sets the Disabled State flag according to given bool
func (s *Style) SetEnabled(on bool) *Style {
s.State.SetFlag(!on, states.Disabled)
return s
}
// IsReadOnly returns whether this style object is flagged as either [states.ReadOnly] or [states.Disabled].
func (s *Style) IsReadOnly() bool {
return s.Is(states.ReadOnly) || s.Is(states.Disabled)
}
// SetAbilities sets the given [states.State] flags to the given value
func (s *Style) SetAbilities(on bool, able ...abilities.Abilities) {
bfs := make([]enums.BitFlag, len(able))
for i, st := range able {
bfs[i] = st
}
s.Abilities.SetFlag(on, bfs...)
}
// InheritFields from parent
func (s *Style) InheritFields(parent *Style) {
s.Color = parent.Color
s.Opacity = parent.Opacity
s.ScrollbarWidth = parent.ScrollbarWidth
s.Zoom = parent.Zoom
s.IconSize = parent.IconSize
s.Font.InheritFields(&parent.Font)
s.Text.InheritFields(&parent.Text)
}
// ToDotsImpl runs ToDots on unit values, to compile down to raw pixels
func (s *Style) ToDotsImpl(uc *units.Context) {
s.LayoutToDots(uc)
s.Font.ToDots(uc)
s.Text.ToDots(uc)
s.Border.ToDots(uc)
s.MaxBorder.ToDots(uc)
s.BoxShadowToDots(uc)
}
// ToDots caches all style elements in terms of raw pixel
// dots for rendering.
func (s *Style) ToDots() {
if s.Min.X.Unit == units.UnitEw || s.Min.X.Unit == units.UnitEh ||
s.Min.Y.Unit == units.UnitEw || s.Min.Y.Unit == units.UnitEh ||
s.Max.X.Unit == units.UnitEw || s.Max.X.Unit == units.UnitEh ||
s.Max.Y.Unit == units.UnitEw || s.Max.Y.Unit == units.UnitEh {
slog.Error("styling error: cannot use Ew or Eh for Min size -- that is self-referential!")
}
s.ToDotsImpl(&s.UnitContext)
}
// BoxSpace returns the extra space around the central content in the box model in dots.
// It rounds all of the sides first.
func (s *Style) BoxSpace() sides.Floats {
return s.TotalMargin().Add(s.Padding.Dots()).Round()
}
// TotalMargin returns the total effective margin of the element
// holding the style, using the sum of the actual margin, the max
// border width, and the max box shadow effective margin. If the
// values for the max border width / box shadow are unset, the
// current values are used instead, which allows for the omission
// of the max properties when the values do not change.
func (s *Style) TotalMargin() sides.Floats {
mbw := s.MaxBorder.Width.Dots()
if sides.AreZero(mbw.Sides) {
mbw = s.Border.Width.Dots()
}
mbo := s.MaxBorder.Offset.Dots()
if sides.AreZero(mbo.Sides) {
mbo = s.Border.Offset.Dots()
}
mbw = mbw.Add(mbo)
if s.Border.Style.Top == BorderNone {
mbw.Top = 0
}
if s.Border.Style.Right == BorderNone {
mbw.Right = 0
}
if s.Border.Style.Bottom == BorderNone {
mbw.Bottom = 0
}
if s.Border.Style.Left == BorderNone {
mbw.Left = 0
}
if s.BoxShadowOutside {
return s.Margin.Dots().Add(mbw)
}
mbsm := s.MaxBoxShadowMargin()
if sides.AreZero(mbsm.Sides) {
mbsm = s.BoxShadowMargin()
}
return s.Margin.Dots().Add(mbw).Add(mbsm)
}
// SubProperties returns a sub-property map from given prop map for a given styling
// selector (property name) -- e.g., :normal :active :hover etc -- returns
// false if not found
func SubProperties(prp map[string]any, selector string) (map[string]any, bool) {
sp, ok := prp[selector]
if !ok {
return nil, false
}
spm, ok := sp.(map[string]any)
if ok {
return spm, true
}
return nil, false
}
// StyleDefault is default style can be used when property specifies "default"
var StyleDefault Style
// ComputeActualBackground sets [Style.ActualBackground] based on the
// given parent actual background and the properties of the style object.
func (s *Style) ComputeActualBackground(pabg image.Image) {
s.ActualBackground = s.ComputeActualBackgroundFor(s.Background, pabg)
}
// ComputeActualBackgroundFor returns the actual background for
// the given background based on the given parent actual background
// and the properties of the style object.
func (s *Style) ComputeActualBackgroundFor(bg, pabg image.Image) image.Image {
if bg == nil {
bg = pabg
} else if u, ok := bg.(*image.Uniform); ok && colors.IsNil(u.C) {
bg = pabg
} else if ok && pabg != nil {
// A translucent background is what it looks like over the
// background of the parent, so that the widgets in it (which
// render the background of their parent) do not blend it again.
if c := colors.AsRGBA(u.C); c.A < 255 {
if pu, ok := pabg.(*image.Uniform); ok {
bg = colors.Uniform(colors.AlphaBlend(pu.C, c))
}
}
}
if s.Opacity >= 1 && s.StateLayer <= 0 {
// we have no transformations to apply
return bg
}
// TODO(kai): maybe improve this function to handle all
// use cases correctly (image parents, image state colors, etc)
upabg := colors.ToUniform(pabg)
if s.Opacity < 1 {
bg = gradient.Apply(bg, func(c color.Color) color.Color {
// we take our opacity-applied background color and then overlay it onto our surrounding color
obg := colors.ApplyOpacity(c, s.Opacity)
return colors.AlphaBlend(upabg, obg)
})
}
if s.StateLayer > 0 {
sc := s.Color
if s.StateColor != nil {
sc = s.StateColor
}
// we take our state-layer-applied state color and then overlay it onto our background color
sclr := colors.WithAF32(colors.ToUniform(sc), s.StateLayer)
bg = gradient.Apply(bg, func(c color.Color) color.Color {
return colors.AlphaBlend(c, sclr)
})
}
return bg
}
// IsFlexWrap returns whether the style is both [Style.Wrap] and [Flex].
func (s *Style) IsFlexWrap() bool {
return s.Wrap && s.Display == Flex
}
// SetReadOnly sets the [states.ReadOnly] flag to the given value.
func (s *Style) SetReadOnly(ro bool) {
s.SetState(ro, states.ReadOnly)
}
// CenterAll sets all of the alignment properties to [Center]
// such that all children are fully centered.
func (s *Style) CenterAll() {
s.Justify.Content = Center
s.Justify.Items = Center
s.Align.Content = Center
s.Align.Items = Center
s.Text.Align = text.Center
s.Text.AlignV = text.Center
}
// SetTextWrap sets the Text.WhiteSpace and GrowWrap properties in
// a coordinated manner. If wrap == true, then WhiteSpaceNormal
// and GrowWrap = true; else WhiteSpaceNowrap and GrowWrap = false, which
// are typically the two desired stylings.
func (s *Style) SetTextWrap(wrap bool) {
if wrap {
s.Text.WhiteSpace = text.WrapAsNeeded
s.GrowWrap = true
} else {
s.Text.WhiteSpace = text.WrapNever
s.GrowWrap = false
}
}
// SetNonSelectable turns off the Selectable and DoubleClickable
// abilities and sets the Cursor to None.
func (s *Style) SetNonSelectable() {
s.SetAbilities(false, abilities.Selectable, abilities.DoubleClickable, abilities.TripleClickable, abilities.Slideable)
s.Cursor = cursors.None
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package styles
import (
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/colors"
"cogentcore.org/core/colors/gradient"
"cogentcore.org/core/enums"
"cogentcore.org/core/styles/styleprops"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/text"
)
// These functions set styles from map[string]any which are used for styling
// FromProperty sets style field values based on the given property key and value
func (s *Style) FromProperty(parent *Style, key string, val any, cc colors.Context) {
var pfont *Font
var ptext *Text
if parent != nil {
pfont = &parent.Font
ptext = &parent.Text
}
s.Font.FromProperty(pfont, key, val, cc)
s.Text.FromProperty(ptext, key, val, cc)
if sfunc, ok := styleLayoutFuncs[key]; ok {
if parent != nil {
sfunc(s, key, val, parent, cc)
} else {
sfunc(s, key, val, nil, cc)
}
return
}
if sfunc, ok := styleBorderFuncs[key]; ok {
if parent != nil {
sfunc(&s.Border, key, val, &parent.Border, cc)
} else {
sfunc(&s.Border, key, val, nil, cc)
}
return
}
if sfunc, ok := styleStyleFuncs[key]; ok {
sfunc(s, key, val, parent, cc)
return
}
// doesn't work with multiple shadows
// if sfunc, ok := StyleShadowFuncs[key]; ok {
// if parent != nil {
// sfunc(&s.BoxShadow, key, val, &par.BoxShadow, cc)
// } else {
// sfunc(&s.BoxShadow, key, val, nil, cc)
// }
// return
// }
}
//////// Style
// styleStyleFuncs are functions for styling the Style object itself
var styleStyleFuncs = map[string]styleprops.Func{
"color": func(obj any, key string, val any, parent any, cc colors.Context) {
fs := obj.(*Style)
if inh, init := styleprops.InhInit(val, parent); inh || init {
if inh {
fs.Color = parent.(*Style).Color
} else if init {
fs.Color = colors.Scheme.OnSurface
}
return
}
fs.Color = errors.Log1(gradient.FromAny(val, cc))
},
"background-color": func(obj any, key string, val any, parent any, cc colors.Context) {
fs := obj.(*Style)
if inh, init := styleprops.InhInit(val, parent); inh || init {
if inh {
fs.Background = parent.(*Style).Background
} else if init {
fs.Background = nil
}
return
}
fs.Background = errors.Log1(gradient.FromAny(val, cc))
},
"opacity": styleprops.Float(float32(1),
func(obj *Style) *float32 { return &obj.Opacity }),
}
//////// Layout
// styleLayoutFuncs are functions for styling the layout
// style properties; they are still stored on the main style object,
// but they are done separately to improve clarity
var styleLayoutFuncs = map[string]styleprops.Func{
"display": styleprops.Enum(Flex,
func(obj *Style) enums.EnumSetter { return &obj.Display }),
"flex-direction": func(obj any, key string, val, parent any, cc colors.Context) {
s := obj.(*Style)
if inh, init := styleprops.InhInit(val, parent); inh || init {
if inh {
s.Direction = parent.(*Style).Direction
} else if init {
s.Direction = Row
}
return
}
str := reflectx.ToString(val)
if str == "row" || str == "row-reverse" {
s.Direction = Row
} else {
s.Direction = Column
}
},
// TODO(kai/styproperties): multi-dim flex-grow
"flex-grow": styleprops.Float(0, func(obj *Style) *float32 { return &obj.Grow.Y }),
"wrap": styleprops.Bool(false,
func(obj *Style) *bool { return &obj.Wrap }),
"justify-content": styleprops.Enum(Start,
func(obj *Style) enums.EnumSetter { return &obj.Justify.Content }),
"justify-items": styleprops.Enum(Start,
func(obj *Style) enums.EnumSetter { return &obj.Justify.Items }),
"justify-self": styleprops.Enum(Auto,
func(obj *Style) enums.EnumSetter { return &obj.Justify.Self }),
"align-content": styleprops.Enum(Start,
func(obj *Style) enums.EnumSetter { return &obj.Align.Content }),
"align-items": styleprops.Enum(Start,
func(obj *Style) enums.EnumSetter { return &obj.Align.Items }),
"align-self": styleprops.Enum(Auto,
func(obj *Style) enums.EnumSetter { return &obj.Align.Self }),
"x": styleprops.Units(units.Value{},
func(obj *Style) *units.Value { return &obj.Pos.X }),
"y": styleprops.Units(units.Value{},
func(obj *Style) *units.Value { return &obj.Pos.Y }),
"width": styleprops.Units(units.Value{},
func(obj *Style) *units.Value { return &obj.Min.X }),
"height": styleprops.Units(units.Value{},
func(obj *Style) *units.Value { return &obj.Min.Y }),
"max-width": styleprops.Units(units.Value{},
func(obj *Style) *units.Value { return &obj.Max.X }),
"max-height": styleprops.Units(units.Value{},
func(obj *Style) *units.Value { return &obj.Max.Y }),
"min-width": styleprops.Units(units.Dp(2),
func(obj *Style) *units.Value { return &obj.Min.X }),
"min-height": styleprops.Units(units.Dp(2),
func(obj *Style) *units.Value { return &obj.Min.Y }),
"margin": func(obj any, key string, val any, parent any, cc colors.Context) {
s := obj.(*Style)
if inh, init := styleprops.InhInit(val, parent); inh || init {
if inh {
s.Margin = parent.(*Style).Margin
} else if init {
s.Margin.Zero()
}
return
}
s.Margin.SetAny(val)
},
"padding": func(obj any, key string, val any, parent any, cc colors.Context) {
s := obj.(*Style)
if inh, init := styleprops.InhInit(val, parent); inh || init {
if inh {
s.Padding = parent.(*Style).Padding
} else if init {
s.Padding.Zero()
}
return
}
s.Padding.SetAny(val)
},
// TODO(kai/styproperties): multi-dim overflow
"overflow": styleprops.Enum(OverflowAuto,
func(obj *Style) enums.EnumSetter { return &obj.Overflow.Y }),
"columns": styleprops.Int(int(0),
func(obj *Style) *int { return &obj.Columns }),
// TODO:
// "row": styleprops.Int(int(0),
// func(obj *Style) *int { return &obj.Row }),
// "col": styleprops.Int(int(0),
// func(obj *Style) *int { return &obj.Col }),
// "row-span": styleprops.Int(int(0),
// func(obj *Style) *int { return &obj.RowSpan }),
"col-span": styleprops.Int(int(0),
func(obj *Style) *int { return &obj.ColSpan }),
// "z-index": styleprops.Int(int(0),
// func(obj *Style) *int { return &obj.ZIndex }),
"scrollbar-width": styleprops.Units(units.Value{},
func(obj *Style) *units.Value { return &obj.ScrollbarWidth }),
}
//////// Border
// styleBorderFuncs are functions for styling the Border object
var styleBorderFuncs = map[string]styleprops.Func{
// SidesTODO: need to figure out how to get key and context information for side SetAny calls
// with padding, margin, border, etc
"border-style": func(obj any, key string, val any, parent any, cc colors.Context) {
bs := obj.(*Border)
if inh, init := styleprops.InhInit(val, parent); inh || init {
if inh {
bs.Style = parent.(*Border).Style
} else if init {
bs.Style.Set(BorderSolid)
}
return
}
switch vt := val.(type) {
case string:
bs.Style.SetString(vt)
case BorderStyles:
bs.Style.Set(vt)
case []BorderStyles:
bs.Style.Set(vt...)
default:
iv, err := reflectx.ToInt(val)
if err == nil {
bs.Style.Set(BorderStyles(iv))
} else {
styleprops.SetError(key, val, err)
}
}
},
"border-width": func(obj any, key string, val any, parent any, cc colors.Context) {
bs := obj.(*Border)
if inh, init := styleprops.InhInit(val, parent); inh || init {
if inh {
bs.Width = parent.(*Border).Width
} else if init {
bs.Width.Zero()
}
return
}
bs.Width.SetAny(val)
},
"border-radius": func(obj any, key string, val any, parent any, cc colors.Context) {
bs := obj.(*Border)
if inh, init := styleprops.InhInit(val, parent); inh || init {
if inh {
bs.Radius = parent.(*Border).Radius
} else if init {
bs.Radius.Zero()
}
return
}
bs.Radius.SetAny(val)
},
"border-color": func(obj any, key string, val any, parent any, cc colors.Context) {
bs := obj.(*Border)
if inh, init := styleprops.InhInit(val, parent); inh || init {
if inh {
bs.Color = parent.(*Border).Color
} else if init {
bs.Color.Set(colors.Scheme.Outline)
}
return
}
// TODO(kai): support side-specific border colors
bs.Color.Set(errors.Log1(gradient.FromAny(val, cc)))
},
}
//////// Outline
// styleOutlineFuncs are functions for styling the OutlineStyle object
var styleOutlineFuncs = map[string]styleprops.Func{
"outline-style": func(obj any, key string, val any, parent any, cc colors.Context) {
bs := obj.(*Border)
if inh, init := styleprops.InhInit(val, parent); inh || init {
if inh {
bs.Style = parent.(*Border).Style
} else if init {
bs.Style.Set(BorderSolid)
}
return
}
switch vt := val.(type) {
case string:
bs.Style.SetString(vt)
case BorderStyles:
bs.Style.Set(vt)
case []BorderStyles:
bs.Style.Set(vt...)
default:
iv, err := reflectx.ToInt(val)
if err == nil {
bs.Style.Set(BorderStyles(iv))
} else {
styleprops.SetError(key, val, err)
}
}
},
"outline-width": func(obj any, key string, val any, parent any, cc colors.Context) {
bs := obj.(*Border)
if inh, init := styleprops.InhInit(val, parent); inh || init {
if inh {
bs.Width = parent.(*Border).Width
} else if init {
bs.Width.Zero()
}
return
}
bs.Width.SetAny(val)
},
"outline-radius": func(obj any, key string, val any, parent any, cc colors.Context) {
bs := obj.(*Border)
if inh, init := styleprops.InhInit(val, parent); inh || init {
if inh {
bs.Radius = parent.(*Border).Radius
} else if init {
bs.Radius.Zero()
}
return
}
bs.Radius.SetAny(val)
},
"outline-color": func(obj any, key string, val any, parent any, cc colors.Context) {
bs := obj.(*Border)
if inh, init := styleprops.InhInit(val, parent); inh || init {
if inh {
bs.Color = parent.(*Border).Color
} else if init {
bs.Color.Set(colors.Scheme.Outline)
}
return
}
// TODO(kai): support side-specific border colors
bs.Color.Set(errors.Log1(gradient.FromAny(val, cc)))
},
}
//////// Shadow
// styleShadowFuncs are functions for styling the Shadow object
var styleShadowFuncs = map[string]styleprops.Func{
"box-shadow.offset-x": styleprops.Units(units.Value{},
func(obj *Shadow) *units.Value { return &obj.OffsetX }),
"box-shadow.offset-y": styleprops.Units(units.Value{},
func(obj *Shadow) *units.Value { return &obj.OffsetY }),
"box-shadow.blur": styleprops.Units(units.Value{},
func(obj *Shadow) *units.Value { return &obj.Blur }),
"box-shadow.spread": styleprops.Units(units.Value{},
func(obj *Shadow) *units.Value { return &obj.Spread }),
"box-shadow.color": func(obj any, key string, val any, parent any, cc colors.Context) {
ss := obj.(*Shadow)
if inh, init := styleprops.InhInit(val, parent); inh || init {
if inh {
ss.Color = parent.(*Shadow).Color
} else if init {
ss.Color = colors.Scheme.Shadow
}
return
}
ss.Color = errors.Log1(gradient.FromAny(val, cc))
},
"box-shadow.inset": styleprops.Bool(false,
func(obj *Shadow) *bool { return &obj.Inset }),
}
//////// Font
// FromProperties sets style field values based on the given property list.
func (fs *Font) FromProperties(parent *Font, properties map[string]any, ctxt colors.Context) {
for key, val := range properties {
if len(key) == 0 {
continue
}
if key[0] == '#' || key[0] == '.' || key[0] == ':' || key[0] == '_' {
continue
}
fs.FromProperty(parent, key, val, ctxt)
}
}
// FromProperty sets style field values based on the given property key and value.
func (fs *Font) FromProperty(parent *Font, key string, val any, cc colors.Context) {
if sfunc, ok := styleFontFuncs[key]; ok {
if parent != nil {
sfunc(fs, key, val, parent, cc)
} else {
sfunc(fs, key, val, nil, cc)
}
return
}
}
// FontSizePoints maps standard font names to standard point sizes -- we use
// dpi zoom scaling instead of rescaling "medium" font size, so generally use
// these values as-is. smaller and larger relative scaling can move in 2pt increments
var FontSizePoints = map[string]float32{
"xx-small": 7,
"x-small": 7.5,
"small": 10, // small is also "smaller"
"smallf": 10, // smallf = small font size..
"medium": 12,
"large": 14,
"x-large": 18,
"xx-large": 24,
}
// styleFontFuncs are functions for styling the Font object.
var styleFontFuncs = map[string]styleprops.Func{
// note: text.Style handles the standard units-based font-size settings
"font-size": func(obj any, key string, val any, parent any, cc colors.Context) {
fs := obj.(*Font)
if inh, init := styleprops.InhInit(val, parent); inh || init {
if inh {
fs.Size = parent.(*Font).Size
} else if init {
fs.Size.Set(16, units.UnitDp)
}
return
}
switch vt := val.(type) {
case string:
if psz, ok := FontSizePoints[vt]; ok {
fs.Size = units.Pt(psz)
} else {
fs.Size.SetAny(val, key) // also processes string
}
}
},
"font-family": func(obj any, key string, val any, parent any, cc colors.Context) {
fs := obj.(*Font)
if inh, init := styleprops.InhInit(val, parent); inh || init {
if inh {
fs.Family = parent.(*Font).Family
fs.CustomFont = parent.(*Font).CustomFont
} else if init {
fs.Family = rich.SansSerif // font has defaults
}
return
}
switch vt := val.(type) {
case string:
fs.CustomFont = rich.FontName(vt)
fs.Family = rich.Custom
default:
// todo: process enum
}
},
"font-style": styleprops.Enum(rich.SlantNormal,
func(obj *Font) enums.EnumSetter { return &obj.Slant }),
"font-weight": styleprops.Enum(rich.Normal,
func(obj *Font) enums.EnumSetter { return &obj.Weight }),
"font-stretch": styleprops.Enum(rich.StretchNormal,
func(obj *Font) enums.EnumSetter { return &obj.Stretch }),
"text-decoration": func(obj any, key string, val any, parent any, cc colors.Context) {
fs := obj.(*Font)
if inh, init := styleprops.InhInit(val, parent); inh || init {
if inh {
fs.Decoration = parent.(*Font).Decoration
} else if init {
fs.Decoration = 0
}
return
}
switch vt := val.(type) {
case string:
if vt == "none" {
fs.Decoration = 0
} else {
fs.Decoration.SetString(vt)
}
case rich.Decorations:
fs.Decoration.SetFlag(true, vt)
default:
iv, err := reflectx.ToInt(val)
if err == nil {
fs.Decoration.SetFlag(true, rich.Decorations(iv))
} else {
styleprops.SetError(key, val, err)
}
}
},
}
// FromProperties sets style field values based on the given property list.
func (ts *Text) FromProperties(parent *Text, properties map[string]any, ctxt colors.Context) {
for key, val := range properties {
if len(key) == 0 {
continue
}
if key[0] == '#' || key[0] == '.' || key[0] == ':' || key[0] == '_' {
continue
}
ts.FromProperty(parent, key, val, ctxt)
}
}
// FromProperty sets style field values based on the given property key and value.
func (ts *Text) FromProperty(parent *Text, key string, val any, cc colors.Context) {
if sfunc, ok := styleFuncs[key]; ok {
if parent != nil {
sfunc(ts, key, val, parent, cc)
} else {
sfunc(ts, key, val, nil, cc)
}
return
}
}
// styleFuncs are functions for styling the Text object.
var styleFuncs = map[string]styleprops.Func{
// text.Start, not the Start of the layout, whose value is that of End
"text-align": text.AlignProperty(func(obj *Text) enums.EnumSetter { return &obj.Align }),
"text-vertical-align": styleprops.Enum(text.Start,
func(obj *Text) enums.EnumSetter { return &obj.AlignV }),
"line-height": styleprops.FloatProportion(float32(1.2),
func(obj *Text) *float32 { return &obj.LineHeight }),
"line-spacing": styleprops.FloatProportion(float32(1.2),
func(obj *Text) *float32 { return &obj.LineHeight }),
"white-space": styleprops.Enum(text.WrapAsNeeded,
func(obj *Text) enums.EnumSetter { return &obj.WhiteSpace }),
"direction": styleprops.Enum(rich.LTR,
func(obj *Text) enums.EnumSetter { return &obj.Direction }),
"text-indent": styleprops.Units(units.Value{},
func(obj *Text) *units.Value { return &obj.Indent }),
"text-hanging": styleprops.Units(units.Value{},
func(obj *Text) *units.Value { return &obj.Hanging }),
"tab-size": styleprops.Int(int(4),
func(obj *Text) *int { return &obj.TabSize }),
"select-color": func(obj any, key string, val any, parent any, cc colors.Context) {
fs := obj.(*Text)
if inh, init := styleprops.InhInit(val, parent); inh || init {
if inh {
fs.SelectColor = parent.(*Text).SelectColor
} else if init {
fs.SelectColor = colors.Scheme.Select.Container
}
return
}
fs.SelectColor = errors.Log1(gradient.FromAny(val, cc))
},
"highlight-color": func(obj any, key string, val any, parent any, cc colors.Context) {
fs := obj.(*Text)
if inh, init := styleprops.InhInit(val, parent); inh || init {
if inh {
fs.HighlightColor = parent.(*Text).HighlightColor
} else if init {
fs.HighlightColor = colors.Scheme.Warn.Container
}
return
}
fs.HighlightColor = errors.Log1(gradient.FromAny(val, cc))
},
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package styleprops provides infrastructure for property-list-based setting
// of style values, where a property list is a map[string]any collection of
// key, value pairs.
package styleprops
import (
"log/slog"
"reflect"
"strings"
"cogentcore.org/core/base/num"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/colors"
"cogentcore.org/core/enums"
"cogentcore.org/core/styles/units"
)
// Func is the signature for styleprops functions
type Func func(obj any, key string, val any, parent any, cc colors.Context)
// InhInit detects the style values of "inherit" and "initial",
// setting the corresponding bool return values
func InhInit(val, parent any) (inh, init bool) {
if str, ok := val.(string); ok {
switch str {
case "inherit":
return !reflectx.IsNil(reflect.ValueOf(parent)), false
case "initial":
return false, true
default:
return false, false
}
}
return false, false
}
// Int returns a style function for any numerical value
func Int[T any, F num.Integer](initVal F, getField func(obj *T) *F) Func {
return func(obj any, key string, val any, parent any, cc colors.Context) {
fp := getField(obj.(*T))
if inh, init := InhInit(val, parent); inh || init {
if inh {
*fp = *getField(parent.(*T))
} else if init {
*fp = initVal
}
return
}
fv, err := reflectx.ToInt(val)
if err == nil {
*fp = F(fv)
}
}
}
// Float returns a style function for any numerical value.
// Automatically removes a trailing % -- see FloatProportion.
func Float[T any, F num.Float](initVal F, getField func(obj *T) *F) Func {
return func(obj any, key string, val any, parent any, cc colors.Context) {
fp := getField(obj.(*T))
if inh, init := InhInit(val, parent); inh || init {
if inh {
*fp = *getField(parent.(*T))
} else if init {
*fp = initVal
}
return
}
if vstr, ok := val.(string); ok {
val = strings.TrimSuffix(vstr, "%")
}
fv, err := reflectx.ToFloat(val)
if err == nil {
*fp = F(fv)
}
}
}
// FloatProportion returns a style function for a proportion that can be
// represented as a percentage (divides value by 100).
func FloatProportion[T any, F num.Float](initVal F, getField func(obj *T) *F) Func {
return func(obj any, key string, val any, parent any, cc colors.Context) {
fp := getField(obj.(*T))
if inh, init := InhInit(val, parent); inh || init {
if inh {
*fp = *getField(parent.(*T))
} else if init {
*fp = initVal
}
return
}
isPct := false
if vstr, ok := val.(string); ok && strings.HasSuffix(vstr, "%") {
val = strings.TrimSuffix(vstr, "%")
isPct = true
}
fv, err := reflectx.ToFloat(val)
if isPct {
fv /= 100
}
if err == nil {
*fp = F(fv)
}
}
}
// Bool returns a style function for a bool value
func Bool[T any](initVal bool, getField func(obj *T) *bool) Func {
return func(obj any, key string, val any, parent any, cc colors.Context) {
fp := getField(obj.(*T))
if inh, init := InhInit(val, parent); inh || init {
if inh {
*fp = *getField(parent.(*T))
} else if init {
*fp = initVal
}
return
}
fv, err := reflectx.ToBool(val)
if err == nil {
*fp = fv
}
}
}
// Units returns a style function for units.Value
func Units[T any](initVal units.Value, getField func(obj *T) *units.Value) Func {
return func(obj any, key string, val any, parent any, cc colors.Context) {
fp := getField(obj.(*T))
if inh, init := InhInit(val, parent); inh || init {
if inh {
*fp = *getField(parent.(*T))
} else if init {
*fp = initVal
}
return
}
fp.SetAny(val, key)
}
}
// Enum returns a style function for any enum value
func Enum[T any](initVal enums.Enum, getField func(obj *T) enums.EnumSetter) Func {
return func(obj any, key string, val any, parent any, cc colors.Context) {
fp := getField(obj.(*T))
if inh, init := InhInit(val, parent); inh || init {
if inh {
fp.SetInt64(getField(parent.(*T)).Int64())
} else if init {
fp.SetInt64(initVal.Int64())
}
return
}
if st, ok := val.(string); ok {
fp.SetString(st)
return
}
if en, ok := val.(enums.Enum); ok {
fp.SetInt64(en.Int64())
return
}
iv, err := reflectx.ToInt(val)
if err == nil {
fp.SetInt64(int64(iv))
}
}
}
// SetError reports that cannot set property of given key with given value due to given error
func SetError(key string, val any, err error) {
slog.Error("styleprops: error setting value", "key", key, "value", val, "err", err)
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package styleprops
import (
"fmt"
"strings"
"cogentcore.org/core/base/reflectx"
)
// FromXMLString sets style properties from XML style string, which contains ';'
// separated name: value pairs
func FromXMLString(style string, properties map[string]any) {
st := strings.SplitSeq(style, ";")
for s := range st {
kv := strings.Split(s, ":")
n := len(kv)
if n >= 2 {
k := strings.TrimSpace(strings.ToLower(kv[n-2]))
if n == 3 { // prefixed name
k = strings.TrimSpace(strings.ToLower(kv[0])) + ":" + k
}
v := strings.TrimSpace(kv[n-1])
properties[k] = v
}
}
}
// ToXMLString returns an XML style string from given style properties map
// using ';' separated name: value pairs.
func ToXMLString(properties map[string]any) string {
var sb strings.Builder
for k, v := range properties {
if k == "transform" {
continue
}
fmt.Fprintf(&sb, "%s:%s;", k, reflectx.ToString(v))
}
return sb.String()
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package styles
import (
"image"
"cogentcore.org/core/colors"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/text"
)
// Text has styles for text layout styling.
// Most of these are inherited
type Text struct { //types:add
// Align specifies how to align text along the default direction (inherited).
// This *only* applies to the text within its containing element,
// and is relevant only for multi-line text.
Align text.Aligns
// AlignV specifies "vertical" (orthogonal to default direction)
// alignment of text (inherited).
// This *only* applies to the text within its containing element:
// if that element does not have a specified size
// that is different from the text size, then this has *no effect*.
AlignV text.Aligns
// LineHeight is a multiplier on the default font size for spacing between lines.
// If there are larger font elements within a line, they will be accommodated, with
// the same amount of total spacing added above that maximum size as if it was all
// the same height. The default of 1.3 represents standard "single spaced" text.
LineHeight float32 `default:"1.3"`
// WhiteSpace (not inherited) specifies how white space is processed,
// and how lines are wrapped. If set to WhiteSpaceNormal (default) lines are wrapped.
// See info about interactions with Grow.X setting for this and the NoWrap case.
WhiteSpace text.WhiteSpaces
// LineClamp (not inherited), if positive, is the most lines that the
// text has: the text after them is cut, and the last line ends with an
// ellipsis (…), as the -webkit-line-clamp property of CSS.
LineClamp int
// Ellipsis (not inherited) is whether text that does not wrap and is
// wider than its box is cut to fit in it, ending with an ellipsis (…),
// as text-overflow: ellipsis in CSS.
Ellipsis bool
// Direction specifies the default text direction, which can be overridden if the
// unicode text is typically written in a different direction.
Direction rich.Directions
// Indent specifies how much to indent the first line in a paragraph (inherited).
Indent units.Value
// Hanging specifies how much to indent all but the first line
// in a paragraph (inherited).
Hanging units.Value
// TabSize specifies the tab size, in number of characters (inherited).
TabSize int
// SelectColor is the color to use for the background region of selected text (inherited).
SelectColor image.Image
// HighlightColor is the color to use for the background region of highlighted text (inherited).
HighlightColor image.Image
}
func (ts *Text) Defaults() {
ts.Align = text.Start
ts.AlignV = text.Start
ts.LineHeight = 1.3
ts.Direction = rich.LTR
ts.TabSize = 4
ts.SelectColor = colors.Scheme.Select.Container
ts.HighlightColor = colors.Scheme.Warn.Container
}
// ToDots runs ToDots on unit values, to compile down to raw pixels
func (ts *Text) ToDots(uc *units.Context) {
ts.Indent.ToDots(uc)
ts.Hanging.ToDots(uc)
}
// InheritFields from parent
func (ts *Text) InheritFields(parent *Text) {
ts.Align = parent.Align
ts.AlignV = parent.AlignV
ts.LineHeight = parent.LineHeight
// ts.WhiteSpace = par.WhiteSpace // note: we can't inherit this b/c label base default then gets overwritten
ts.Direction = parent.Direction
ts.Indent = parent.Indent
ts.Hanging = parent.Hanging
ts.TabSize = parent.TabSize
ts.SelectColor = parent.SelectColor
ts.HighlightColor = parent.HighlightColor
}
// SetText sets the text.Style from this style.
func (ts *Text) SetText(tsty *text.Style) {
tsty.Align = ts.Align
tsty.AlignV = ts.AlignV
tsty.LineHeight = ts.LineHeight
tsty.WhiteSpace = ts.WhiteSpace
tsty.LineClamp = ts.LineClamp
tsty.Ellipsis = ts.Ellipsis
tsty.Direction = ts.Direction
tsty.Indent = ts.Indent
tsty.Hanging = ts.Hanging
tsty.TabSize = ts.TabSize
tsty.SelectColor = ts.SelectColor
tsty.HighlightColor = ts.HighlightColor
}
// SetFromText sets from the given [text.Style].
func (ts *Text) SetFromText(tsty *text.Style) {
ts.Align = tsty.Align
ts.AlignV = tsty.AlignV
ts.LineHeight = tsty.LineHeight
ts.WhiteSpace = tsty.WhiteSpace
ts.LineClamp = tsty.LineClamp
ts.Ellipsis = tsty.Ellipsis
ts.Direction = tsty.Direction
ts.Indent = tsty.Indent
ts.Hanging = tsty.Hanging
ts.TabSize = tsty.TabSize
ts.SelectColor = tsty.SelectColor
ts.HighlightColor = tsty.HighlightColor
}
// LineHeightDots returns the effective line height in dots (actual pixels)
// as FontHeight * LineHeight
func (s *Style) LineHeightDots() float32 {
return math32.Ceil(s.Font.FontHeight() * s.Text.LineHeight)
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package units
import (
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/math32"
)
// Context specifies everything about the current context necessary
// for converting the number into specific display-dependent pixels.
type Context struct {
// DPI is dots-per-inch of the display
DPI float32
// FontEm is the size of the font of the element in raw dots (not points)
FontEm float32
// FontEx is the height x-height of font in points (size of 'x' glyph)
FontEx float32
// FontCh is the ch-size character size of font in points (width of '0' glyph)
FontCh float32
// FontRem is the size of the font of the root element in raw dots (not points)
FontRem float32
// Vpw is viewport width in dots
Vpw float32
// Vph is viewport height in dots
Vph float32
// Elw is width of element in dots
Elw float32
// Elh is height of element in dots
Elh float32
// Paw is width of parent in dots
Paw float32
// Pah is height of parent in dots
Pah float32
}
func NewContext() *Context {
uc := &Context{}
uc.Defaults()
return uc
}
// Defaults are generic defaults
func (uc *Context) Defaults() {
uc.DPI = DpPerInch
uc.FontEm = 16
uc.FontEx = 8
uc.FontCh = 8
uc.FontRem = 16
uc.Vpw = 800
uc.Vph = 600
uc.Elw = uc.Vpw
uc.Elh = uc.Vph
uc.Paw = uc.Vpw
uc.Pah = uc.Vph
}
func (uc *Context) String() string {
return reflectx.StringJSON(uc)
}
// SetSizes sets the context values for the non-font sizes
// to the given values; the values are ignored if they are zero.
// returns true if any are different.
func (uc *Context) SetSizes(vw, vh, ew, eh, pw, ph float32) bool {
diff := false
if vw != 0 {
if uc.Vpw != vw {
diff = true
}
uc.Vpw = vw
}
if vh != 0 {
if uc.Vph != vh {
diff = true
}
uc.Vph = vh
}
if ew != 0 {
if uc.Elw != ew {
diff = true
}
uc.Elw = ew
}
if eh != 0 {
if uc.Elh != eh {
diff = true
}
uc.Elh = eh
}
if pw != 0 {
if uc.Paw != pw {
diff = true
}
uc.Paw = pw
}
if ph != 0 {
if uc.Pah != ph {
diff = true
}
uc.Pah = ph
}
return diff
}
// SetFont sets the context values for font based on the em size,
// which is the nominal font height, in DPI dots.
// This uses standard conversion factors from em. It is too unreliable
// and complicated to get these values from the actual font itself.
func (uc *Context) SetFont(em float32) {
if em == 0 {
em = 16
}
uc.FontEm = em
uc.FontEx = math32.Round(0.53 * em)
uc.FontCh = math32.Round(0.45 * em)
uc.FontRem = math32.Round(uc.Dp(16))
}
// Dots returns factor needed to convert given unit into raw pixels (dots in DPI)
func (uc *Context) Dots(un Units) float32 {
if uc.DPI == 0 {
// log.Printf("gi/units Context was not initialized -- falling back on defaults\n")
uc.Defaults()
}
switch un {
case UnitEw:
return 0.01 * uc.Elw
case UnitEh:
return 0.01 * uc.Elh
case UnitPw:
return 0.01 * uc.Paw
case UnitPh:
return 0.01 * uc.Pah
case UnitEm:
return uc.FontEm
case UnitEx:
return uc.FontEx
case UnitCh:
return uc.FontCh
case UnitRem:
return uc.FontRem
case UnitVw:
return 0.01 * uc.Vpw
case UnitVh:
return 0.01 * uc.Vph
case UnitVmin:
return 0.01 * min(uc.Vpw, uc.Vph)
case UnitVmax:
return 0.01 * max(uc.Vpw, uc.Vph)
case UnitCm:
return uc.DPI / CmPerInch
case UnitMm:
return uc.DPI / MmPerInch
case UnitQ:
return uc.DPI / (4.0 * MmPerInch)
case UnitIn:
return uc.DPI
case UnitPc:
return uc.DPI / PcPerInch
case UnitPt:
return uc.DPI / PtPerInch
case UnitPx:
return uc.DPI / PxPerInch
case UnitDp:
return uc.DPI / DpPerInch
case UnitDot:
return 1.0
}
return uc.DPI
}
// ToDots converts value in given units into raw display pixels (dots in DPI).
func (uc *Context) ToDots(val float32, un Units) float32 {
return val * uc.Dots(un)
}
// FromDots converts value in dots to value in given units.
func (uc *Context) FromDots(val float32, un Units) float32 {
return val / uc.Dots(un)
}
// Convert converts value in given from units to value in given to units.
func (uc *Context) Convert(val float32, from, to Units) float32 {
return val * (uc.Dots(from) / uc.Dots(to))
}
// PxToDots just converts a value from pixels to dots
func (uc *Context) PxToDots(val float32) float32 {
return val * uc.Dots(UnitPx)
}
// DotsToPx just converts a value from dots to pixels
func (uc *Context) DotsToPx(val float32) float32 {
return val / uc.Dots(UnitPx)
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package units
import (
"fmt"
"strings"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/reflectx"
"golang.org/x/image/math/fixed"
)
// NOTE: we have empty labels for value fields, because there is a natural
// flow of the unit values without it. "{{Value}} {{Unit}}" without labels
// makes sense and provides a nicer end-user experience.
// Value and units, and converted value into raw pixels (dots in DPI)
type Value struct { //types:add
// Value is the value in terms of the specified unit
Value float32 `label:""`
// Unit is the unit used for the value
Unit Units `label:""`
// Dots is the computed value in raw pixels (dots in DPI)
Dots float32 `display:"-"`
// Custom is a custom function that returns the dots of the value.
// If it is non-nil, it overrides all other fields.
// Otherwise, the standard ToDots with the other fields is used.
Custom func(uc *Context) float32 `display:"-" json:"-" xml:"-" toml:"-" save:"-"`
}
// New creates a new value with the given unit type
func New(val float32, un Units) Value {
return Value{Value: val, Unit: un}
}
// Set sets the value and units of an existing value
func (v *Value) Set(val float32, un Units) {
v.Value = val
v.Unit = un
}
// Zero returns a new zero (0) value.
func Zero() Value {
return Value{Unit: UnitDot}
}
// Zero sets the value to zero (0).
func (v *Value) Zero() {
v.Value = 0
v.Unit = UnitDot
v.Dots = 0
v.Custom = nil
}
// Dot returns a new dots value.
// Dots are actual real display pixels, which are generally only used internally.
func Dot(val float32) Value {
return Value{Value: val, Unit: UnitDot, Dots: val}
}
// Dot sets the value directly in terms of dots.
// Dots are actual real display pixels, which are generally only used internally.
func (v *Value) Dot(val float32) {
v.Value = val
v.Unit = UnitDot
v.Dots = val
v.Custom = nil
}
// Custom returns a new custom value that has the dots
// of the value returned by the given function.
func Custom(fun func(uc *Context) float32) Value {
return Value{Custom: fun}
}
// SetCustom sets the value to be a custom value that has
// the dots of the value returned by the given function.
func (v *Value) SetCustom(fun func(uc *Context) float32) {
v.Custom = fun
}
// ToDots converts value to raw display pixels (dots as in DPI), setting also
// the Dots field
func (v *Value) ToDots(uc *Context) float32 {
if v.Custom != nil {
v.Dots = v.Custom(uc)
} else {
v.Dots = uc.ToDots(v.Value, v.Unit)
}
return v.Dots
}
// ToDotsFixed converts value to raw display pixels (dots in DPI) in
// fixed-point 26.6 format for rendering
func (v *Value) ToDotsFixed(uc *Context) fixed.Int26_6 {
return fixed.Int26_6(v.ToDots(uc))
}
// Convert converts value to the given units, given unit context
func (v *Value) Convert(to Units, uc *Context) Value {
dots := v.ToDots(uc)
return Value{Value: dots / uc.Dots(to), Unit: to, Dots: dots}
}
// String implements the [fmt.Stringer] interface.
func (v *Value) String() string {
return fmt.Sprintf("%g%s", v.Value, v.Unit.String())
}
// StringCSS returns the value as a string suitable for CSS
// by changing dp to px and using % if applicable.
func (v Value) StringCSS() string {
if v.Unit == UnitDp {
v.Unit = UnitPx // non-pointer so can change directly
}
s := v.String()
if v.Unit == UnitPw || v.Unit == UnitPh || v.Unit == UnitEw || v.Unit == UnitEh {
s = s[:len(s)-2] + "%"
}
return s
}
// StringCSSDp returns the value as a CSS string for HTML that is rendered in a
// web browser, where 1dp corresponds to 1 CSS px (as in the web driver).
// Unlike [Value.StringCSS], absolute units (px, in, cm, etc) are converted to
// CSS px based on [DpPerInch], so that they have the same size as they do
// in a Cogent Core app.
func (v Value) StringCSSDp() string {
perInch := float32(0)
switch v.Unit {
case UnitPx:
perInch = PxPerInch
case UnitIn:
perInch = 1
case UnitCm:
perInch = CmPerInch
case UnitMm:
perInch = MmPerInch
case UnitQ:
perInch = 4 * MmPerInch
case UnitPc:
perInch = PcPerInch
case UnitPt:
perInch = PtPerInch
}
if perInch != 0 {
v.Value *= DpPerInch / perInch
v.Unit = UnitDp
}
return v.StringCSS()
}
// SetString sets value from a string
func (v *Value) SetString(str string) error {
trstr := strings.TrimSpace(strings.ReplaceAll(str, "%", "pct"))
sz := len(trstr)
if sz < 2 {
vc, err := reflectx.ToFloat(str)
if err != nil {
return fmt.Errorf("(units.Value).SetString: unable to convert string value %q into a number: %w", trstr, err)
}
v.Value = float32(vc)
v.Unit = UnitPx
return nil
}
var ends [4]string
ends[0] = strings.ToLower(trstr[sz-1:])
ends[1] = strings.ToLower(trstr[sz-2:])
if sz > 3 {
ends[2] = strings.ToLower(trstr[sz-3:])
}
if sz > 4 {
ends[3] = strings.ToLower(trstr[sz-4:])
}
var numstr string
un := UnitPx // default to pixels
for _, u := range UnitsValues() {
nm := u.String()
unsz := len(nm)
if ends[unsz-1] == nm {
numstr = trstr[:sz-unsz]
un = u
break
}
}
if len(numstr) == 0 { // no units
numstr = trstr
}
var val float32
trspc := strings.TrimSpace(numstr)
n, err := fmt.Sscanf(trspc, "%g", &val)
if err != nil {
return fmt.Errorf("(units.Value).SetString: error scanning string '%s': %w", trspc, err)
}
if n == 0 {
return fmt.Errorf("(units.Value).SetString: no arguments parsed from string '%s'", trspc)
}
v.Set(val, un)
return nil
}
// StringToValue converts a string to a value representation.
func StringToValue(str string) Value {
var v Value
v.SetString(str)
return v
}
// SetAny sets value from an interface value representation as from map[string]any
// key is optional property key for error message -- always logs the error
func (v *Value) SetAny(iface any, key string) error {
switch val := iface.(type) {
case string:
v.SetString(val)
case Value:
*v = val
case *Value:
*v = *val
default: // assume Dp as an implicit default
valflt, err := reflectx.ToFloat(iface)
if err == nil {
v.Dp(float32(valflt))
} else {
err := fmt.Errorf("units.Value: could not set property %q from value: %v of type: %T: %w", key, val, val, err)
return errors.Log(err)
}
}
return nil
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package units
import (
"cogentcore.org/core/math32"
)
// XY represents unit Value for X and Y dimensions
type XY struct { //types:add
// X is the horizontal axis value
X Value
// Y is the vertical axis value
Y Value
}
// ToDots converts value to raw display pixels (dots as in DPI),
// setting also the Dots field
func (xy *XY) ToDots(uc *Context) {
xy.X.ToDots(uc)
xy.Y.ToDots(uc)
}
// String implements the fmt.Stringer interface.
func (xy *XY) String() string {
return "(" + xy.X.String() + ", " + xy.Y.String() + ")"
}
// Zero sets values to 0
func (xy *XY) Zero() {
xy.X.Zero()
xy.Y.Zero()
}
// Set sets the x and y values according to the given values.
// No values: set both to 0.
// One value: set both to that value.
// Two values: set x to the first value and y to the second value.
func (xy *XY) Set(v ...Value) {
switch len(v) {
case 0:
var zv Value
xy.X = zv
xy.Y = zv
case 1:
xy.X = v[0]
xy.Y = v[0]
default:
xy.X = v[0]
xy.Y = v[1]
}
}
// Dim returns the value for given dimension
func (xy *XY) Dim(d math32.Dims) Value {
switch d {
case math32.X:
return xy.X
case math32.Y:
return xy.Y
default:
panic("units.XY dimension invalid")
}
}
// SetDim sets the value for given dimension
func (xy *XY) SetDim(d math32.Dims, val Value) {
switch d {
case math32.X:
xy.X = val
case math32.Y:
xy.Y = val
default:
panic("units.XY dimension invalid")
}
}
// Dots returns the dots values as a math32.Vector2 vector
func (xy *XY) Dots() math32.Vector2 {
return math32.Vec2(xy.X.Dots, xy.Y.Dots)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package styles
import (
"fmt"
"cogentcore.org/core/math32"
)
// XY represents X,Y values
type XY[T any] struct { //types:add
// X is the horizontal axis value
X T
// Y is the vertical axis value
Y T
}
// String implements the fmt.Stringer interface.
func (xy *XY[T]) String() string {
return fmt.Sprintf("(%v, %v)", xy.X, xy.Y)
}
// Set sets the X, Y values according to the given values.
// no values: set to 0.
// 1 value: set both to that value.
// 2 values, set X, Y to the two values respectively.
func (xy *XY[T]) Set(v ...T) {
switch len(v) {
case 0:
var zv T
xy.X = zv
xy.Y = zv
case 1:
xy.X = v[0]
xy.Y = v[0]
default:
xy.X = v[0]
xy.Y = v[1]
}
}
// Dim returns the value for given dimension.
func (xy *XY[T]) Dim(d math32.Dims) T {
switch d {
case math32.X:
return xy.X
case math32.Y:
return xy.Y
default:
panic("styles.XY dimension invalid")
}
}
// SetDim sets the value for given dimension.
func (xy *XY[T]) SetDim(d math32.Dims, val T) {
switch d {
case math32.X:
xy.X = val
case math32.Y:
xy.Y = val
default:
panic("styles.XY dimension invalid")
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package svg
import (
"cogentcore.org/core/math32"
)
// Circle is a SVG circle
type Circle struct {
NodeBase
// position of the center of the circle
Pos math32.Vector2 `svg:"cx,cy"`
// radius of the circle
Radius float32 `xml:"r"`
}
func (g *Circle) SVGName() string { return "circle" }
func (g *Circle) Init() {
g.NodeBase.Init()
g.Radius = 1
}
// SetNodePos sets the upper left of the circle, whose Pos is its center.
func (g *Circle) SetNodePos(pos math32.Vector2) {
g.Pos = pos.AddScalar(g.Radius)
}
// SetNodeSize sets the diameter of the circle to the average of the size,
// keeping its upper left in place.
func (g *Circle) SetNodeSize(sz math32.Vector2) {
ul := g.Pos.SubScalar(g.Radius)
g.Radius = 0.25 * (sz.X + sz.Y)
g.Pos = ul.AddScalar(g.Radius)
}
func (g *Circle) LocalBBox(sv *SVG) math32.Box2 {
bb := math32.Box2{}
hlw := 0.5 * g.LocalLineWidth()
bb.Min = g.Pos.SubScalar(g.Radius + hlw)
bb.Max = g.Pos.AddScalar(g.Radius + hlw)
return bb
}
func (g *Circle) Render(sv *SVG) {
if !g.IsVisible(sv) {
return
}
pc := g.Painter(sv)
if g.pushLayer(sv) {
defer pc.PopContext()
}
pc.Circle(g.Pos.X, g.Pos.Y, g.Radius)
pc.Draw()
g.RenderChildren(sv)
}
// ApplyTransform applies the given 2D transform to the geometry of this node
// each node must define this for itself
func (g *Circle) ApplyTransform(sv *SVG, xf math32.Matrix2) {
rot := xf.ExtractRot()
if rot != 0 {
g.Paint.Transform.SetMul(xf)
g.SetTransformProperty()
} else {
g.Pos = xf.MulPoint(g.Pos)
scx, scy := xf.ExtractScale()
g.Radius *= 0.5 * (scx + scy)
g.GradientApplyTransform(sv, xf)
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package svg
// todo: needs to be impl
// ClipPath is used for holding a path that renders as a clip path
type ClipPath struct {
NodeBase
}
func (g *ClipPath) SVGName() string { return "clippath" }
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
//go:generate core generate -add-types -add-funcs
import (
"path/filepath"
"strings"
"cogentcore.org/core/cli"
"cogentcore.org/core/colors/gradient"
"cogentcore.org/core/math32"
"cogentcore.org/core/svg"
)
func main() { //types:skip
opts := cli.DefaultOptions("svg", "Command line tools for rendering and creating svg files")
cli.Run(opts, &Config{}, Render, EmbedImage)
}
type Config struct {
// Input is the filename of the input file
Input string `posarg:"0"`
// Output is the filename of the output file.
// Defaults to input with the extension changed to the output format.
Output string `flag:"o,output"`
// Fill, if specified, indicates to fill the background of
// the svg with the specified color in CSS format.
Fill string
Render RenderConfig `cmd:"render"`
}
type RenderConfig struct {
// Width is the width of the rendered image
Width int `posarg:"1"`
// Height is the height of the rendered image.
// Defaults to width.
Height int `posarg:"2" required:"-"`
}
// Render renders the input svg file to the output image file.
//
//cli:cmd -root
func Render(c *Config) error {
if c.Render.Height == 0 {
c.Render.Height = c.Render.Width
}
sv := svg.NewSVG(math32.Vec2(float32(c.Render.Width), float32(c.Render.Height)))
err := ApplyFill(c, sv)
if err != nil {
return err
}
err = sv.OpenXML(c.Input)
if err != nil {
return err
}
if c.Output == "" {
c.Output = strings.TrimSuffix(c.Input, filepath.Ext(c.Input)) + ".png"
}
return sv.SaveImage(c.Output)
}
// EmbedImage embeds the input image file into the output svg file.
func EmbedImage(c *Config) error {
sv := svg.NewSVG(math32.Vec2(0, 0))
err := ApplyFill(c, sv)
if err != nil {
return err
}
img := svg.NewImage(sv.Root)
err = img.OpenImage(c.Input, 0, 0)
if err != nil {
return err
}
sz := img.Pixels.Image.Bounds().Size()
sv.Root.ViewBox.Size.SetPoint(sz)
if c.Output == "" {
c.Output = strings.TrimSuffix(c.Input, filepath.Ext(c.Input)) + ".svg"
}
return sv.SaveXML(c.Output)
}
// ApplyFill applies [Config.Fill] to the given [svg.SVG].
func ApplyFill(c *Config, sv *svg.SVG) error { //types:skip
if c.Fill == "" {
return nil
}
bg, err := gradient.FromString(c.Fill)
if err != nil {
return err
}
sv.Background = bg
return nil
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package svg
import (
"log"
"github.com/aymerick/douceur/css"
"github.com/aymerick/douceur/parser"
)
// StyleSheet is a node that contains a stylesheet -- property values
// contained in this sheet can be transformed into tree.Properties and set in CSS
// field of appropriate node.
type StyleSheet struct {
NodeBase
Sheet *css.Stylesheet `copier:"-"`
}
func (ss *StyleSheet) SVGName() string {
return "css"
}
// ParseString parses the string into a StyleSheet of rules, which can then be
// used for extracting properties
func (ss *StyleSheet) ParseString(str string) error {
pss, err := parser.Parse(str)
if err != nil {
log.Printf("styles.StyleSheet ParseString parser error: %v\n", err)
return err
}
ss.Sheet = pss
return nil
}
// CSSProperties returns the properties for each of the rules in this style sheet,
// suitable for setting the CSS value of a node -- returns nil if empty sheet
func (ss *StyleSheet) CSSProperties() map[string]any {
if ss.Sheet == nil {
return nil
}
sz := len(ss.Sheet.Rules)
if sz == 0 {
return nil
}
pr := map[string]any{}
for _, r := range ss.Sheet.Rules {
if r.Kind == css.AtRule {
continue // not supported
}
nd := len(r.Declarations)
if nd == 0 {
continue
}
for _, sel := range r.Selectors {
sp := map[string]any{}
for _, de := range r.Declarations {
sp[de.Property] = de.Value
}
pr[sel] = sp
}
}
return pr
}
//////// MetaData
// MetaData is used for holding meta data info
type MetaData struct {
NodeBase
MetaData string
}
func (g *MetaData) SVGName() string {
return "metadata"
}
// Render does nothing: the children of metadata (and of elements that
// are not supported) are not rendered.
func (g *MetaData) Render(sv *SVG) {}
func (g *MetaData) EnforceSVGName() bool {
return false
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package svg
import (
"cogentcore.org/core/math32"
)
// Ellipse is a SVG ellipse
type Ellipse struct {
NodeBase
// position of the center of the ellipse
Pos math32.Vector2 `svg:"cx,cy"`
// radii of the ellipse in the horizontal, vertical axes
Radii math32.Vector2 `svg:"rx,ry"`
}
func (g *Ellipse) SVGName() string { return "ellipse" }
func (g *Ellipse) Init() {
g.NodeBase.Init()
g.Radii.Set(1, 1)
}
// SetNodePos sets the upper left of the ellipse, whose Pos is its center.
func (g *Ellipse) SetNodePos(pos math32.Vector2) {
g.Pos = pos.Add(g.Radii)
}
// SetNodeSize sets the size of the ellipse, keeping its upper left in place.
func (g *Ellipse) SetNodeSize(sz math32.Vector2) {
ul := g.Pos.Sub(g.Radii)
g.Radii = sz.MulScalar(0.5)
g.Pos = ul.Add(g.Radii)
}
func (g *Ellipse) LocalBBox(sv *SVG) math32.Box2 {
bb := math32.Box2{}
hlw := 0.5 * g.LocalLineWidth()
bb.Min = g.Pos.Sub(g.Radii.AddScalar(hlw))
bb.Max = g.Pos.Add(g.Radii.AddScalar(hlw))
return bb
}
func (g *Ellipse) Render(sv *SVG) {
if !g.IsVisible(sv) {
return
}
pc := g.Painter(sv)
if g.pushLayer(sv) {
defer pc.PopContext()
}
pc.Ellipse(g.Pos.X, g.Pos.Y, g.Radii.X, g.Radii.Y)
pc.Draw()
}
// ApplyTransform applies the given 2D transform to the geometry of this node
// each node must define this for itself
func (g *Ellipse) ApplyTransform(sv *SVG, xf math32.Matrix2) {
rot := xf.ExtractRot()
if rot != 0 || !g.Paint.Transform.IsIdentity() {
g.Paint.Transform.SetMul(xf)
g.SetTransformProperty()
} else {
// todo: this is not the correct transform:
g.Pos = xf.MulPoint(g.Pos)
g.Radii = xf.MulVector(g.Radii)
g.GradientApplyTransform(sv, xf)
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package svg
// Filter represents SVG filter* elements
type Filter struct {
NodeBase
FilterType string
}
func (g *Filter) SVGName() string { return "filter" }
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package svg
// Flow represents SVG flow* elements
type Flow struct {
NodeBase
FlowType string
}
func (g *Flow) SVGName() string { return "flow" }
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package svg
import (
"fmt"
"log"
"strings"
"cogentcore.org/core/colors/gradient"
"cogentcore.org/core/math32"
)
// note: this code provides convenience methods for updating gradient data
// when dynamically updating svg nodes, as in an animation, svg drawing app, etc.
// It is an awkward design that the gradient needs to be updated for each node
// for most sensible use-cases, because the ObjectBoundingBox is too limited,
// so a unique UserSpaceOnUse gradient is typically needed for each node.
// Gradient is used for holding a specified color gradient.
// The name is the id for lookup in url
type Gradient struct {
NodeBase
// the color gradient
Grad gradient.Gradient `json:"-"` // note: cannot do drag-n-drop
// name of another gradient to get stops from
StopsName string
}
// IsRadial returns true if given gradient is a raidal type.
func (gr *Gradient) IsRadial() bool {
_, ok := gr.Grad.(*gradient.Radial)
return ok
}
// GradientTypeName returns the SVG-style type name of gradient:
// linearGradient or radialGradient
func (gr *Gradient) GradientTypeName() string {
if gr.IsRadial() {
return "radialGradient"
}
return "linearGradient"
}
// fromGeom sets gradient geom for UserSpaceOnUse gradient units
// from given geom.
func (gr *Gradient) fromGeom(xf math32.Matrix2) { // gg *GradientGeom) {
gb := gr.Grad.AsBase()
if gb.Units != gradient.UserSpaceOnUse {
return
}
gb.Transform = xf
}
// toGeom copies gradient points to given geom
// for UserSpaceOnUse gradient units.
func (gr *Gradient) toGeom(xf *math32.Matrix2) {
gb := gr.Grad.AsBase()
if gb.Units != gradient.UserSpaceOnUse {
return
}
*xf = gb.Transform
}
//////// SVG gradient management
// GradientByName returns the gradient of given name, stored on SVG node
func (sv *SVG) GradientByName(n Node, grnm string) *Gradient {
gri := sv.NodeFindURL(n, grnm)
if gri == nil {
return nil
}
gr, ok := gri.(*Gradient)
if !ok {
log.Printf("SVG Found element named: %v but isn't a Gradient type, instead is: %T", grnm, gri)
return nil
}
return gr
}
// GradientApplyTransform applies given transform to node's gradient geometry.
// This should ONLY be called when the node's transform is _not_ being updated,
// and instead its geometry values (pos etc) are being transformed directly by
// this transform, because the node's transform will be applied to the gradient
// when it is being rendered.
func (g *NodeBase) GradientApplyTransform(sv *SVG, xf math32.Matrix2) {
g.GradientFill = xf.Mul(g.GradientFill)
g.GradientStroke = xf.Mul(g.GradientStroke)
g.GradientUpdateGeom(sv)
}
// GradientGeomDefault sets the initial default gradient geometry from node.
func (g *NodeBase) GradientGeomDefault(sv *SVG, gr gradient.Gradient) {
gi := g.This.(Node)
if rg, ok := gr.(*gradient.Radial); ok {
lbb := gi.LocalBBox(sv)
ctr := lbb.Center()
sz := lbb.Size()
rad := 0.5 * max(sz.X, sz.Y)
rg.Center = ctr
rg.Focal = ctr
rg.Radius.Set(rad, rad)
return
}
lg := gr.(*gradient.Linear)
lbb := gi.LocalBBox(sv)
lg.Start = lbb.Min
lg.End = math32.Vec2(lbb.Max.X, lbb.Min.Y) // L-R
}
// GradientUpdateGeom updates the geometry of UserSpaceOnUse gradients
// in use by this node for "fill" and "stroke" by copying its current
// GradientGeom points to those gradients.
func (g *NodeBase) GradientUpdateGeom(sv *SVG) {
gi := g.This.(Node)
gnm := NodePropURL(gi, "fill")
if gnm != "" {
gr := sv.GradientByName(gi, gnm)
if gr != nil {
gr.fromGeom(g.GradientFill)
// fmt.Println("set fill:", g.GradientFill)
}
}
gnm = NodePropURL(gi, "stroke")
if gnm != "" {
gr := sv.GradientByName(gi, gnm)
if gr != nil {
gr.fromGeom(g.GradientStroke)
}
}
}
// GradientFromGradients updates the geometry of UserSpaceOnUse gradients
// in use by this node for "fill" and "stroke" by copying its current
// GradientGeom points to those gradients.
func (g *NodeBase) GradientFromGradients(sv *SVG) {
gi := g.This.(Node)
gnm := NodePropURL(gi, "fill")
if gnm != "" {
gr := sv.GradientByName(gi, gnm)
if gr != nil {
gr.toGeom(&g.GradientFill)
}
}
gnm = NodePropURL(gi, "stroke")
if gnm != "" {
gr := sv.GradientByName(gi, gnm)
if gr != nil {
gr.toGeom(&g.GradientStroke)
}
}
}
// GradientFromGradients updates the geometry of UserSpaceOnUse gradients
// for all nodes, for "fill" and "stroke" properties, by copying the current
// GradientGeom points to those gradients. This can be done after loading
// for cases where node transforms will be updated dynamically.
func (sv *SVG) GradientFromGradients() {
for n := range sv.Root.All() {
nb := n.(Node).AsNodeBase()
nb.GradientFromGradients(sv)
}
}
//////// Gradient management utilities for creating element-specific grads
// GradientUpdateStops copies stops from StopsName gradient if it is set
func (sv *SVG) GradientUpdateStops(gr *Gradient) {
if gr.StopsName == "" {
return
}
sgr := sv.GradientByName(gr, gr.StopsName)
if sgr != nil {
gr.Grad.AsBase().CopyStopsFrom(sgr.Grad.AsBase())
}
}
// GradientDeleteForNode deletes the node-specific gradient on given node
// of given name, which can be a full url(# name or just the bare name.
// Returns true if deleted.
func (sv *SVG) GradientDeleteForNode(n Node, grnm string) bool {
gr := sv.GradientByName(n, grnm)
if gr == nil || gr.StopsName == "" {
return false
}
unm := NameFromURL(grnm)
if unm == "" { // a bare name
unm = grnm
}
sv.Defs.DeleteChildByName(unm)
return true
}
// GradientNewForNode adds a new gradient specific to given node
// that points to given stops name. Returns the new gradient
// and the url that points to it (nil if parent svg cannot be found).
// Initializes gradient to use current GradientFill or Stroke with UserSpaceOnUse.
func (sv *SVG) GradientNewForNode(n Node, prop string, radial bool, stops string) (*Gradient, string) {
gr, url := sv.GradientNew(radial)
gr.StopsName = stops
gr.Grad.AsBase().Units = gradient.UserSpaceOnUse
nb := n.AsNodeBase()
nb.GradientGeomDefault(sv, gr.Grad)
if prop == "fill" {
nb.GradientFill = math32.Identity2()
} else {
nb.GradientStroke = math32.Identity2()
}
sv.GradientUpdateStops(gr)
return gr, url
}
// GradientNew adds a new gradient, either linear or radial,
// with a new unique id
func (sv *SVG) GradientNew(radial bool) (*Gradient, string) {
gnm := ""
if radial {
gnm = "radialGradient"
} else {
gnm = "linearGradient"
}
gr := NewGradient(sv.Defs)
id := sv.NewUniqueID()
gnm = NameID(gnm, id)
gr.SetName(gnm)
url := NameToURL(gnm)
if radial {
gr.Grad = gradient.NewRadial()
} else {
gr.Grad = gradient.NewLinear()
}
return gr, url
}
// GradientUpdateNodeProp ensures that node has a gradient property of given type.
func (sv *SVG) GradientUpdateNodeProp(n Node, prop string, radial bool, stops string) (*Gradient, string) {
nb := n.AsNodeBase()
ps := nb.Property(prop)
if ps == nil {
gr, url := sv.GradientNewForNode(n, prop, radial, stops)
nb.SetProperty(prop, url)
nb.SetProperty(prop+"-opacity", "1")
return gr, url
}
pstr, ok := ps.(string)
if !ok {
pstr = *ps.(*string)
}
trgst := ""
if radial {
trgst = "radialGradient"
} else {
trgst = "linearGradient"
}
url := "url(#" + trgst
if strings.HasPrefix(pstr, url) {
gr := sv.GradientByName(n, pstr)
if gr != nil {
gr.StopsName = stops
sv.GradientUpdateStops(gr)
return gr, NameToURL(gr.Name)
} else {
fmt.Println("not found:", pstr, url)
}
}
if strings.HasPrefix(pstr, "url(#") { // wrong kind
sv.GradientDeleteForNode(n, pstr)
}
gr, url := sv.GradientNewForNode(n, prop, radial, stops)
nb.SetProperty(prop, url)
return gr, url
}
// GradientUpdateAllStops removes any items from Defs that are not actually referred to
// by anything in the current SVG tree. Returns true if items were removed.
// Does not remove gradients with StopsName = "" with extant stops -- these
// should be removed manually, as they are not automatically generated.
func (sv *SVG) GradientUpdateAllStops() {
for _, k := range sv.Defs.Children {
gr, ok := k.(*Gradient)
if ok {
sv.GradientUpdateStops(gr)
}
}
}
// GradientDuplicateNode duplicates any existing gradients
// for the given node, in fill or stroke.
// Must be called when duplicating a node.
func (sv *SVG) GradientDuplicateNode(n Node) {
nb := n.AsNodeBase()
setGr := func(prop string) {
v, ok := nb.Properties[prop]
if !ok {
return
}
s, ok := v.(string)
if !ok {
return
}
nm := NameFromURL(s)
if nm == "" {
return
}
gri := sv.FindDefByName(nm)
if gri == nil {
return
}
gr := gri.(*Gradient)
_, ngu := sv.GradientNewForNode(n, prop, gr.IsRadial(), gr.StopsName)
nb.Properties[prop] = ngu
}
setGr("fill")
setGr("stroke")
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package svg
import (
"cogentcore.org/core/math32"
)
// Group groups together SVG elements.
// Provides a common transform for all group elements
// and shared style properties.
type Group struct {
NodeBase
}
func (g *Group) SVGName() string { return "g" }
func (g *Group) EnforceSVGName() bool { return false }
func (g *Group) BBoxes(sv *SVG, parTransform math32.Matrix2) {
g.BBoxesFromChildren(sv, parTransform)
}
func (g *Group) IsVisible(sv *SVG) bool {
if g == nil || g.This == nil || !g.Paint.Display { // does not check g.Paint.Off!
return false
}
nvis := g.VisBBox == math32.Box2{}
if nvis && !g.isDef {
return false
}
return true
}
func (g *Group) Render(sv *SVG) {
if !g.IsVisible(sv) {
return
}
pc := g.Painter(sv)
pc.PushContext(&g.Paint, nil)
g.setLayer(sv, math32.Identity2())
g.RenderChildren(sv)
pc.PopContext()
}
// ApplyTransform applies the given 2D transform to the geometry of this node
// each node must define this for itself
func (g *Group) ApplyTransform(sv *SVG, xf math32.Matrix2) {
g.Paint.Transform.SetMul(xf)
g.SetTransformProperty()
}
// Copyright (c) 2021, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package svg
import (
"errors"
"image"
"log"
"cogentcore.org/core/base/iox/imagex"
"cogentcore.org/core/math32"
"golang.org/x/image/draw"
"golang.org/x/image/math/f64"
)
// Image is an SVG image (bitmap)
type Image struct {
NodeBase
// position of the top-left of the image
Pos math32.Vector2 `svg:"x,y"`
// rendered size of the image (imposes a scaling on image when it is rendered)
Size math32.Vector2 `svg:"width,height"`
// file name of image loaded -- set by OpenImage
Filename string
// how to scale and align the image
ViewBox ViewBox `xml:"viewbox"`
// Pixels are the image pixels, which has imagex.WrapJS already applied,
// and has JSON marshal / unmarshal abilities for copy / paste of element.
Pixels *imagex.JSON `xml:"-" display:"-" set:"-"`
}
func (g *Image) SVGName() string { return "image" }
func (g *Image) SetNodePos(pos math32.Vector2) {
g.Pos = pos
}
func (g *Image) SetNodeSize(sz math32.Vector2) {
g.Size = sz
}
// pixelsOfSize returns the Pixels as an imagex.Image of given size.
// makes a new one if not already the correct size.
func (g *Image) pixelsOfSize(nwsz image.Point) image.Image {
if nwsz.X == 0 || nwsz.Y == 0 {
return nil
}
if g.Pixels != nil && g.Pixels.Image != nil && g.Pixels.Image.Bounds().Size() == nwsz {
return g.Pixels.Image
}
g.Pixels = imagex.NewJSON(imagex.WrapJS(image.NewRGBA(image.Rectangle{Max: nwsz})))
return g.Pixels.Image
}
// SetImage sets an image for the bitmap, and resizes to the size of the image
// or the specified size. Pass 0 for width and/or height to use the actual image size
// for that dimension. Copies from given image into internal image for this bitmap.
func (g *Image) SetImage(img image.Image, width, height float32) {
if img == nil {
return
}
img = imagex.Unwrap(img)
sz := img.Bounds().Size()
if width <= 0 && height <= 0 {
cp := imagex.CloneAsRGBA(img)
g.Pixels = imagex.NewJSON(imagex.WrapJS(cp))
if g.Size.X == 0 && g.Size.Y == 0 {
g.Size = math32.FromPoint(sz)
}
} else {
tsz := sz
transformer := draw.BiLinear
scx := float32(1)
scy := float32(1)
if width > 0 {
scx = width / float32(sz.X)
tsz.X = int(width)
}
if height > 0 {
scy = height / float32(sz.Y)
tsz.Y = int(height)
}
pxi := g.pixelsOfSize(tsz)
px := imagex.Unwrap(pxi).(*image.RGBA)
m := math32.Scale2D(scx, scy)
s2d := f64.Aff3{float64(m.XX), float64(m.XY), float64(m.X0), float64(m.YX), float64(m.YY), float64(m.Y0)}
transformer.Transform(px, s2d, img, img.Bounds(), draw.Over, nil)
if g.Size.X == 0 && g.Size.Y == 0 {
g.Size = math32.FromPoint(tsz)
}
}
}
func (g *Image) DrawImage(sv *SVG) {
if g.Pixels == nil || g.Pixels.Image == nil {
return
}
pc := g.Painter(sv)
pc.DrawImageScaled(g.Pixels.Image, nil, g.Pos.X, g.Pos.Y, g.Size.X, g.Size.Y)
}
func (g *Image) LocalBBox(sv *SVG) math32.Box2 {
bb := math32.Box2{}
bb.Min = g.Pos
bb.Max = g.Pos.Add(g.Size)
return bb.Canon()
}
func (g *Image) Render(sv *SVG) {
vis := g.IsVisible(sv)
if !vis {
return
}
if g.pushLayer(sv) {
defer g.Painter(sv).PopContext()
}
g.DrawImage(sv)
g.RenderChildren(sv)
}
// ApplyTransform applies the given 2D transform to the geometry of this node
// each node must define this for itself
func (g *Image) ApplyTransform(sv *SVG, xf math32.Matrix2) {
rot := xf.ExtractRot()
if rot != 0 {
g.Paint.Transform.SetMul(xf)
g.SetTransformProperty()
} else {
g.Pos = xf.MulPoint(g.Pos)
g.Size = xf.MulVector(g.Size)
g.GradientApplyTransform(sv, xf)
}
}
// OpenImage opens an image for the bitmap, and resizes to the size of the image
// or the specified size -- pass 0 for width and/or height to use the actual image size
// for that dimension
func (g *Image) OpenImage(filename string, width, height float32) error {
img, _, err := imagex.Open(filename)
if err != nil {
log.Printf("svg.OpenImage -- could not open file: %v, err: %v\n", filename, err)
return err
}
g.Filename = filename
g.SetImage(img, width, height)
return nil
}
// SaveImage saves current image to a file
func (g *Image) SaveImage(filename string) error {
if g.Pixels == nil || g.Pixels.Image == nil {
return errors.New("svg.SaveImage Pixels is nil")
}
return imagex.Save(g.Pixels.Image, filename)
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// svg parsing is adapted from github.com/srwiley/oksvg:
// Copyright 2017 The oksvg Authors. All rights reserved.
// created: 2/12/2017 by S.R.Wiley
package svg
import (
"bufio"
"bytes"
"encoding/xml"
"errors"
"fmt"
"io"
"io/fs"
"log"
"log/slog"
"os"
"slices"
"strings"
"cogentcore.org/core/base/iox/imagex"
"cogentcore.org/core/base/iox/xmlx"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/base/stack"
"cogentcore.org/core/colors"
"cogentcore.org/core/colors/gradient"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles/styleprops"
"cogentcore.org/core/tree"
)
// this file contains all the IO-related parsing etc routines
// see https://cogentcore.org/core/ki/wiki/Naming for IO naming conventions
// using standard XML marshal / unmarshal
var errParamMismatch = errors.New("SVG Parse: Param mismatch")
// OpenXML Opens XML-formatted SVG input from given file
func (sv *SVG) OpenXML(fname string) error {
filename := fname
fi, err := os.Stat(filename)
if err != nil {
log.Println(err)
return err
}
if fi.IsDir() {
err := fmt.Errorf("svg.OpenXML: file is a directory: %v", filename)
log.Println(err)
return err
}
fp, err := os.Open(filename)
if err != nil {
log.Println(err)
return err
}
defer fp.Close()
return sv.ReadXML(bufio.NewReader(fp))
}
// OpenFS Opens XML-formatted SVG input from given file, filesystem FS
func (sv *SVG) OpenFS(fsys fs.FS, fname string) error {
fp, err := fsys.Open(fname)
if err != nil {
return err
}
defer fp.Close()
return sv.ReadXML(bufio.NewReader(fp))
}
// ReadXML reads XML-formatted SVG input from io.Reader, and uses
// xml.Decoder to create the SVG scenegraph for corresponding SVG drawing.
// Removes any existing content in SVG first. To process a byte slice, pass:
// bytes.NewReader([]byte(str)) -- all errors are logged and also returned.
func (sv *SVG) ReadXML(reader io.Reader) error {
decoder := xml.NewDecoder(reader)
decoder.Strict = false
decoder.AutoClose = xml.HTMLAutoClose
decoder.Entity = xml.HTMLEntity
decoder.CharsetReader = xmlx.CharsetReader
var err error
outer:
for {
var t xml.Token
t, err = decoder.Token()
if err != nil {
if err == io.EOF {
break
}
log.Printf("SVG parsing error: %v\n", err)
break
}
switch se := t.(type) {
case xml.StartElement:
err = sv.UnmarshalXML(decoder, se)
break outer
// todo: ignore rest?
}
}
if err == io.EOF {
return nil
}
return err
}
// UnmarshalXML unmarshals the svg using xml.Decoder
func (sv *SVG) UnmarshalXML(decoder *xml.Decoder, se xml.StartElement) error {
start := &se
sv.DeleteAll()
curPar := sv.Root.This.(Node) // current parent node into which elements are created
curSvg := sv.Root
inTitle := false
inDesc := false
inDef := false
inCSS := false
var curCSS *StyleSheet
inTxt := false
var curTxt *Text
inTspn := false
var curTspn *Text
var defPrevPar Node // previous parent before a def encountered
var groupStack stack.Stack[string]
var uses []pendingUse
defer func() { sv.resolveUses(uses) }()
sawRoot := false // whether the root svg element has started
var nested []Node // the inner groups of nested svg elements
for {
var t xml.Token
var err error
if start != nil {
t = *start
start = nil
} else {
t, err = decoder.Token()
}
if err != nil {
if err == io.EOF {
break
}
log.Printf("SVG parsing error: %v\n", err)
return err
}
switch se := t.(type) {
case xml.StartElement:
nm := se.Name.Local
if nm == "g" {
name := ""
if sv.GroupFilter != "" {
for _, attr := range se.Attr {
if attr.Name.Local != "id" {
continue
}
name = attr.Value
if name != sv.GroupFilter {
sv.groupFilterSkip = true
sv.groupFilterSkipName = name
// fmt.Println("skipping:", attr.Value, sv.GroupFilter)
break
// } else {
// fmt.Println("including:", attr.Value, sv.GroupFilter)
}
}
}
if name == "" {
name = fmt.Sprintf("tmp%d", len(groupStack)+1)
}
groupStack.Push(name)
if sv.groupFilterSkip {
break
}
curPar = NewGroup(curPar)
for _, attr := range se.Attr {
if SetStandardXMLAttr(curPar.AsNodeBase(), attr.Name.Local, attr.Value) {
continue
}
switch attr.Name.Local {
default:
curPar.AsTree().SetProperty(attr.Name.Local, attr.Value)
}
}
break
}
if sv.groupFilterSkip {
break
}
switch {
case nm == "svg" && sawRoot:
curPar = sv.nestedSVG(curPar, curSvg, se.Attr, len(nested))
nested = append(nested, curPar)
case nm == "svg":
sawRoot = true
// if curPar != sv.This {
// curPar = curPar.NewChild(TypeSVG, "svg").(Node)
// }
for _, attr := range se.Attr {
// if SetStdXMLAttr(curSvg, attr.Name.Local, attr.Value) {
// continue
// }
switch attr.Name.Local {
case "viewBox":
pts := math32.ReadPoints(attr.Value)
if len(pts) != 4 {
return errParamMismatch
}
curSvg.ViewBox.Min.X = pts[0]
curSvg.ViewBox.Min.Y = pts[1]
curSvg.ViewBox.Size.X = pts[2]
curSvg.ViewBox.Size.Y = pts[3]
case "width":
sv.PhysicalWidth.SetString(attr.Value)
sv.PhysicalWidth.ToDots(&curSvg.Paint.UnitContext)
case "height":
sv.PhysicalHeight.SetString(attr.Value)
sv.PhysicalHeight.ToDots(&curSvg.Paint.UnitContext)
case "preserveAspectRatio":
curSvg.ViewBox.PreserveAspectRatio.SetString(attr.Value)
default:
curPar.AsTree().SetProperty(attr.Name.Local, attr.Value)
}
}
case nm == "desc":
inDesc = true
case nm == "title":
inTitle = true
case nm == "defs":
inDef = true
defPrevPar = curPar
curPar = sv.Defs
case nm == "rect":
rect := NewRect(curPar)
var x, y, w, h, rx, ry float32
for _, attr := range se.Attr {
if SetStandardXMLAttr(rect, attr.Name.Local, attr.Value) {
continue
}
switch attr.Name.Local {
case "x":
x, err = sv.parseLength(curSvg, attr.Value, 'x')
case "y":
y, err = sv.parseLength(curSvg, attr.Value, 'y')
case "width":
w, err = sv.parseLength(curSvg, attr.Value, 'x')
case "height":
h, err = sv.parseLength(curSvg, attr.Value, 'y')
case "rx":
rx, err = sv.parseLength(curSvg, attr.Value, 'x')
case "ry":
ry, err = sv.parseLength(curSvg, attr.Value, 'y')
default:
rect.SetProperty(attr.Name.Local, attr.Value)
}
if err != nil {
return err
}
}
rect.Pos.Set(x, y)
rect.Size.Set(w, h)
rect.Radius.Set(rx, ry)
case nm == "circle":
circle := NewCircle(curPar)
var cx, cy, r float32
for _, attr := range se.Attr {
if SetStandardXMLAttr(circle, attr.Name.Local, attr.Value) {
continue
}
switch attr.Name.Local {
case "cx":
cx, err = sv.parseLength(curSvg, attr.Value, 'x')
case "cy":
cy, err = sv.parseLength(curSvg, attr.Value, 'y')
case "r":
r, err = sv.parseLength(curSvg, attr.Value, 'r')
default:
circle.SetProperty(attr.Name.Local, attr.Value)
}
if err != nil {
return err
}
}
circle.Pos.Set(cx, cy)
circle.Radius = r
case nm == "ellipse":
ellipse := NewEllipse(curPar)
var cx, cy, rx, ry float32
for _, attr := range se.Attr {
if SetStandardXMLAttr(ellipse, attr.Name.Local, attr.Value) {
continue
}
switch attr.Name.Local {
case "cx":
cx, err = sv.parseLength(curSvg, attr.Value, 'x')
case "cy":
cy, err = sv.parseLength(curSvg, attr.Value, 'y')
case "rx":
rx, err = sv.parseLength(curSvg, attr.Value, 'x')
case "ry":
ry, err = sv.parseLength(curSvg, attr.Value, 'y')
default:
ellipse.SetProperty(attr.Name.Local, attr.Value)
}
if err != nil {
return err
}
}
ellipse.Pos.Set(cx, cy)
ellipse.Radii.Set(rx, ry)
case nm == "line":
line := NewLine(curPar)
var x1, x2, y1, y2 float32
for _, attr := range se.Attr {
if SetStandardXMLAttr(line, attr.Name.Local, attr.Value) {
continue
}
switch attr.Name.Local {
case "x1":
x1, err = sv.parseLength(curSvg, attr.Value, 'x')
case "y1":
y1, err = sv.parseLength(curSvg, attr.Value, 'y')
case "x2":
x2, err = sv.parseLength(curSvg, attr.Value, 'x')
case "y2":
y2, err = sv.parseLength(curSvg, attr.Value, 'y')
default:
line.SetProperty(attr.Name.Local, attr.Value)
}
if err != nil {
return err
}
}
line.Start.Set(x1, y1)
line.End.Set(x2, y2)
case nm == "polygon":
polygon := NewPolygon(curPar)
for _, attr := range se.Attr {
if SetStandardXMLAttr(polygon, attr.Name.Local, attr.Value) {
continue
}
switch attr.Name.Local {
case "points":
pts := math32.ReadPoints(attr.Value)
if pts != nil {
sz := len(pts)
if sz%2 != 0 {
err = fmt.Errorf("SVG polygon has an odd number of points: %v str: %v", sz, attr.Value)
log.Println(err)
return err
}
pvec := make([]math32.Vector2, sz/2)
for ci := 0; ci < sz/2; ci++ {
pvec[ci].Set(pts[ci*2], pts[ci*2+1])
}
polygon.Points = pvec
}
default:
polygon.SetProperty(attr.Name.Local, attr.Value)
}
}
case nm == "polyline":
polyline := NewPolyline(curPar)
for _, attr := range se.Attr {
if SetStandardXMLAttr(polyline, attr.Name.Local, attr.Value) {
continue
}
switch attr.Name.Local {
case "points":
pts := math32.ReadPoints(attr.Value)
if pts != nil {
sz := len(pts)
if sz%2 != 0 {
err = fmt.Errorf("SVG polyline has an odd number of points: %v str: %v", sz, attr.Value)
log.Println(err)
return err
}
pvec := make([]math32.Vector2, sz/2)
for ci := 0; ci < sz/2; ci++ {
pvec[ci].Set(pts[ci*2], pts[ci*2+1])
}
polyline.Points = pvec
}
default:
polyline.SetProperty(attr.Name.Local, attr.Value)
}
}
case nm == "path":
path := NewPath(curPar)
for _, attr := range se.Attr {
if attr.Name.Local == "original-d" {
continue
}
if SetStandardXMLAttr(path, attr.Name.Local, attr.Value) {
continue
}
switch attr.Name.Local {
case "d":
if sv.GroupFilter != "" && inDef { // font optimization
path.DataStr = attr.Value
} else {
path.SetData(attr.Value)
}
default:
path.SetProperty(attr.Name.Local, attr.Value)
}
}
case nm == "image":
img := NewImage(curPar)
var x, y, w, h float32
for _, attr := range se.Attr {
if SetStandardXMLAttr(img, attr.Name.Local, attr.Value) {
continue
}
switch attr.Name.Local {
case "x":
x, err = sv.parseLength(curSvg, attr.Value, 'x')
case "y":
y, err = sv.parseLength(curSvg, attr.Value, 'y')
case "width":
w, err = sv.parseLength(curSvg, attr.Value, 'x')
case "height":
h, err = sv.parseLength(curSvg, attr.Value, 'y')
case "preserveAspectRatio":
img.ViewBox.PreserveAspectRatio.SetString(attr.Value)
case "href":
if len(attr.Value) > 11 && attr.Value[:11] == "data:image/" {
es := attr.Value[11:]
fmti := strings.Index(es, ";")
// fm := es[:fmti]
bs64 := es[fmti+1 : fmti+8]
if bs64 != "base64," {
log.Printf("image base64 encoding string not properly formatted: %s\n", bs64)
}
eb := []byte(es[fmti+8:])
im, _, err := imagex.FromBase64(eb)
if err != nil {
log.Println(err)
} else {
img.SetImage(im, 0, 0)
}
} else { // a url, which is kept to be written
img.Filename = attr.Value
}
default:
img.SetProperty(attr.Name.Local, attr.Value)
}
if err != nil {
return err
}
}
img.Pos.Set(x, y)
img.Size.Set(w, h)
case nm == "tspan":
fallthrough
case nm == "text":
var txt *Text
if se.Name.Local == "text" {
txt = NewText(curPar)
inTxt = true
curTxt = txt
} else {
if (inTxt && curTxt != nil) || curPar == nil {
// the text of the text element before it is a span
// of its own, as are all of its runs of text
if curTxt.Text != "" {
anon := NewText(curTxt)
tree.SetUniqueName(anon)
anon.Text, curTxt.Text = curTxt.Text, ""
}
txt = NewText(curTxt)
tree.SetUniqueName(txt)
} else if curTxt != nil {
txt = NewText(curPar)
tree.SetUniqueName(txt)
}
inTspn = true
curTspn = txt
}
if txt == nil {
break
}
for _, attr := range se.Attr {
if SetStandardXMLAttr(txt, attr.Name.Local, attr.Value) {
continue
}
switch attr.Name.Local {
case "x":
pts := math32.ReadPoints(attr.Value)
if len(pts) > 1 {
txt.CharPosX = pts
}
if len(pts) > 0 {
txt.Pos.X, txt.absPos.X, txt.hasX = pts[0], pts[0], true
}
case "y":
pts := math32.ReadPoints(attr.Value)
if len(pts) > 1 {
txt.CharPosY = pts
}
if len(pts) > 0 {
txt.Pos.Y, txt.absPos.Y, txt.hasY = pts[0], pts[0], true
}
case "dx":
pts := math32.ReadPoints(attr.Value)
if len(pts) > 0 {
txt.CharPosDX = pts
}
case "dy":
pts := math32.ReadPoints(attr.Value)
if len(pts) > 0 {
txt.CharPosDY = pts
}
case "rotate":
pts := math32.ReadPoints(attr.Value)
if len(pts) > 0 {
txt.CharRots = pts
}
case "textLength":
if tl, err := math32.ParseFloat32(attr.Value); err == nil {
txt.TextLength = tl
}
case "lengthAdjust":
if attr.Value == "spacingAndGlyphs" {
txt.AdjustGlyphs = true
} else {
txt.AdjustGlyphs = false
}
default:
txt.SetProperty(attr.Name.Local, attr.Value)
}
}
case nm == "linearGradient":
grad := NewGradient(curPar)
for _, attr := range se.Attr {
if SetStandardXMLAttr(grad, attr.Name.Local, attr.Value) {
continue
}
switch attr.Name.Local {
case "href":
nm := attr.Value
nm = strings.TrimPrefix(nm, "#")
hr := curPar.AsTree().ChildByName(nm, 0)
if hr != nil {
if hrg, ok := hr.(*Gradient); ok {
grad.StopsName = nm
grad.Grad = gradient.CopyOf(hrg.Grad)
if _, ok := grad.Grad.(*gradient.Linear); !ok {
cp := grad.Grad
grad.Grad = gradient.NewLinear()
*grad.Grad.AsBase() = *cp.AsBase()
}
}
}
}
}
err = gradient.UnmarshalXML(&grad.Grad, decoder, se)
if err != nil {
return err
}
case nm == "radialGradient":
grad := NewGradient(curPar)
for _, attr := range se.Attr {
if SetStandardXMLAttr(grad, attr.Name.Local, attr.Value) {
continue
}
switch attr.Name.Local {
case "href":
nm := attr.Value
nm = strings.TrimPrefix(nm, "#")
hr := curPar.AsTree().ChildByName(nm, 0)
if hr != nil {
if hrg, ok := hr.(*Gradient); ok {
grad.StopsName = nm
grad.Grad = gradient.CopyOf(hrg.Grad)
if _, ok := grad.Grad.(*gradient.Radial); !ok {
cp := grad.Grad
grad.Grad = gradient.NewRadial()
*grad.Grad.AsBase() = *cp.AsBase()
}
}
}
}
}
err = gradient.UnmarshalXML(&grad.Grad, decoder, se)
if err != nil {
return err
}
case nm == "style":
sty := NewStyleSheet(curPar)
for _, attr := range se.Attr {
if SetStandardXMLAttr(sty, attr.Name.Local, attr.Value) {
continue
}
}
inCSS = true
curCSS = sty
// style code shows up in CharData below
case nm == "clipPath":
curPar = NewClipPath(curPar)
cp := curPar.(*ClipPath)
for _, attr := range se.Attr {
if SetStandardXMLAttr(cp, attr.Name.Local, attr.Value) {
continue
}
switch attr.Name.Local {
default:
cp.SetProperty(attr.Name.Local, attr.Value)
}
}
case nm == "mask":
curPar = NewMask(curPar)
mk := curPar.(*Mask)
for _, attr := range se.Attr {
if SetStandardXMLAttr(mk, attr.Name.Local, attr.Value) {
continue
}
mk.SetProperty(attr.Name.Local, attr.Value)
}
case nm == "a" || nm == "switch":
curPar = NewGroup(curPar)
for _, attr := range se.Attr {
if SetStandardXMLAttr(curPar.AsNodeBase(), attr.Name.Local, attr.Value) {
continue
}
if attr.Name.Local != "href" {
curPar.AsTree().SetProperty(attr.Name.Local, attr.Value)
}
}
case nm == "marker":
curPar = NewMarker(curPar)
mrk := curPar.(*Marker)
var rx, ry float32
szx := float32(3)
szy := float32(3)
for _, attr := range se.Attr {
if SetStandardXMLAttr(mrk, attr.Name.Local, attr.Value) {
continue
}
switch attr.Name.Local {
case "refX":
rx, err = math32.ParseFloat32(attr.Value)
case "refY":
ry, err = math32.ParseFloat32(attr.Value)
case "markerWidth":
szx, err = math32.ParseFloat32(attr.Value)
case "markerHeight":
szy, err = math32.ParseFloat32(attr.Value)
case "markerUnits", "matrixUnits": // (the latter was read before)
if attr.Value == "strokeWidth" {
mrk.Units = StrokeWidth
} else {
mrk.Units = UserSpaceOnUse
}
case "viewBox":
pts := math32.ReadPoints(attr.Value)
if len(pts) != 4 {
return errParamMismatch
}
mrk.ViewBox.Min.X = pts[0]
mrk.ViewBox.Min.Y = pts[1]
mrk.ViewBox.Size.X = pts[2]
mrk.ViewBox.Size.Y = pts[3]
case "orient":
mrk.Orient = attr.Value
default:
mrk.SetProperty(attr.Name.Local, attr.Value)
}
if err != nil {
return err
}
}
mrk.RefPos.Set(rx, ry)
mrk.Size.Set(szx, szy)
case nm == "use":
// a group with the transform and properties of the use,
// with a copy of the element that it refers to, which is
// resolved after the parsing (it can be after the use)
ug := NewGroup(curPar)
pu := pendingUse{group: ug}
var tr string
for _, attr := range se.Attr {
if SetStandardXMLAttr(ug, attr.Name.Local, attr.Value) {
continue
}
switch attr.Name.Local {
case "href":
pu.link = strings.TrimPrefix(strings.TrimSpace(attr.Value), "#")
case "x":
pu.x, _ = sv.parseLength(curSvg, attr.Value, 'x')
case "y":
pu.y, _ = sv.parseLength(curSvg, attr.Value, 'y')
case "width":
pu.width, _ = sv.parseLength(curSvg, attr.Value, 'x')
case "height":
pu.height, _ = sv.parseLength(curSvg, attr.Value, 'y')
case "transform":
tr = attr.Value
default:
ug.SetProperty(attr.Name.Local, attr.Value)
}
}
if pu.x != 0 || pu.y != 0 {
tr += fmt.Sprintf(" translate(%g %g)", pu.x, pu.y)
}
if tr = strings.TrimSpace(tr); tr != "" {
ug.SetProperty("transform", tr)
}
uses = append(uses, pu)
case nm == "pattern":
curPar = NewPattern(curPar)
pat := curPar.(*Pattern)
for _, attr := range se.Attr {
if SetStandardXMLAttr(pat, attr.Name.Local, attr.Value) {
continue
}
switch attr.Name.Local {
case "viewBox":
pts := math32.ReadPoints(attr.Value)
if len(pts) == 4 {
pat.ViewBox.Min.Set(pts[0], pts[1])
pat.ViewBox.Size.Set(pts[2], pts[3])
}
case "preserveAspectRatio":
pat.ViewBox.PreserveAspectRatio.SetString(attr.Value)
default:
pat.SetProperty(attr.Name.Local, attr.Value)
}
}
case nm == "symbol":
curPar = NewSymbol(curPar)
sym := curPar.(*Symbol)
for _, attr := range se.Attr {
if SetStandardXMLAttr(sym, attr.Name.Local, attr.Value) {
continue
}
switch attr.Name.Local {
case "viewBox":
pts := math32.ReadPoints(attr.Value)
if len(pts) == 4 {
sym.ViewBox.Min.Set(pts[0], pts[1])
sym.ViewBox.Size.Set(pts[2], pts[3])
}
case "preserveAspectRatio":
sym.ViewBox.PreserveAspectRatio.SetString(attr.Value)
default:
sym.SetProperty(attr.Name.Local, attr.Value)
}
}
case nm == "Work":
fallthrough
case nm == "RDF":
fallthrough
case nm == "format":
fallthrough
case nm == "type":
fallthrough
case nm == "namedview":
fallthrough
case nm == "perspective":
fallthrough
case nm == "grid":
fallthrough
case nm == "guide":
fallthrough
case nm == "metadata":
curPar = NewMetaData(curPar)
md := curPar.(*MetaData)
md.Class = nm
for _, attr := range se.Attr {
if SetStandardXMLAttr(md, attr.Name.Local, attr.Value) {
continue
}
switch attr.Name.Local {
default:
curPar.AsTree().SetProperty(attr.Name.Local, attr.Value)
}
}
case strings.HasPrefix(nm, "flow"):
curPar = NewFlow(curPar)
md := curPar.(*Flow)
md.Class = nm
md.FlowType = nm
for _, attr := range se.Attr {
if SetStandardXMLAttr(md, attr.Name.Local, attr.Value) {
continue
}
switch attr.Name.Local {
default:
curPar.AsTree().SetProperty(attr.Name.Local, attr.Value)
}
}
case strings.HasPrefix(nm, "fe"):
fallthrough
case strings.HasPrefix(nm, "path-effect"):
fallthrough
case strings.HasPrefix(nm, "filter"):
curPar = NewFilter(curPar)
md := curPar.(*Filter)
md.Class = nm
md.FilterType = nm
for _, attr := range se.Attr {
if SetStandardXMLAttr(md, attr.Name.Local, attr.Value) {
continue
}
switch attr.Name.Local {
default:
curPar.AsTree().SetProperty(attr.Name.Local, attr.Value)
}
}
default:
// an element that is not supported, which is not rendered
// (nor are its children), and keeps the nesting of the
// elements after it (its end pops it)
slog.Debug("svg: element not supported", "element", se.Name.Local)
curPar = NewMetaData(curPar)
curPar.AsNodeBase().Class = nm
}
case xml.EndElement:
nm := se.Name.Local
if nm == "g" {
cg := groupStack.Pop()
if sv.groupFilterSkip {
if sv.groupFilterSkipName == cg {
// fmt.Println("unskip:", cg)
sv.groupFilterSkip = false
}
break
}
if curPar == sv.Root.This {
break
}
if curPar.AsTree().Parent == nil {
break
}
curPar = curPar.AsTree().Parent.(Node)
if curPar == sv.Root.This {
break
}
r := tree.ParentByType[*Root](curPar)
if r != nil {
curSvg = r
}
break
}
if sv.groupFilterSkip {
break
}
if nm == "svg" && len(nested) > 0 && curPar == nested[len(nested)-1] {
// the end of a nested svg: its inner and outer groups
nested = nested[:len(nested)-1]
curPar = curPar.AsTree().Parent.AsTree().Parent.(Node)
break
}
switch nm {
case "title":
inTitle = false
case "desc":
inDesc = false
case "style":
inCSS = false
curCSS = nil
case "text":
if curTxt != nil {
curTxt.trimSpans()
}
inTxt = false
curTxt = nil
case "tspan":
inTspn = false
curTspn = nil
case "defs":
if inDef {
inDef = false
curPar = defPrevPar
}
case "rect":
case "circle":
case "ellipse":
case "line":
case "polygon":
case "polyline":
case "path":
case "use":
case "linearGradient":
case "radialGradient":
default:
if curPar == sv.Root.This {
break
}
if curPar.AsTree().Parent == nil {
break
}
curPar = curPar.AsTree().Parent.(Node)
if curPar == sv.Root.This {
break
}
r := tree.ParentByType[*Root](curPar)
if r != nil {
curSvg = r
}
}
case xml.CharData:
// (ok, md := curPar.(*MetaData); ok)
trspc := strings.TrimSpace(string(se))
switch {
// case :
// md.MetaData = string(se)
case inTitle:
sv.Title += trspc
case inDesc:
sv.Desc += trspc
case inTspn && curTspn != nil:
curTspn.Text += collapseSpace(string(se))
case inTxt && curTxt != nil:
if t := collapseSpace(string(se)); curTxt.NumChildren() > 0 {
if strings.TrimSpace(t) != "" || t == " " { // the text after a span is a span of its own
anon := NewText(curTxt)
tree.SetUniqueName(anon)
anon.Text = t
}
} else {
curTxt.Text += t
}
case inCSS && curCSS != nil:
curCSS.ParseString(trspc)
cp := curCSS.CSSProperties()
if cp != nil {
if inDef && defPrevPar != nil {
defPrevPar.AsNodeBase().CSS = cp
} else {
curPar.AsNodeBase().CSS = cp
}
}
}
}
}
return nil
}
//////// Writing
// XMLString returns the svg to a XML-encoded file, using WriteXML
func (sv *SVG) XMLString() string {
var b bytes.Buffer
sv.WriteXML(&b, NoIndentXML)
return b.String()
}
// SaveXML saves the svg to a XML-encoded file, using WriteXML
func (sv *SVG) SaveXML(fname string) error {
filename := string(fname)
fp, err := os.Create(filename)
if err != nil {
log.Println(err)
return err
}
defer fp.Close()
bw := bufio.NewWriter(fp)
err = sv.WriteXML(bw, IndentXML)
if err != nil {
log.Println(err)
return err
}
err = bw.Flush()
if err != nil {
log.Println(err)
}
return err
}
// XMLIndent specifies whether the written XML is indented: [IndentXML] or
// [NoIndentXML].
type XMLIndent bool
const (
// IndentXML indents the XML.
IndentXML XMLIndent = true
// NoIndentXML does not indent the XML.
NoIndentXML XMLIndent = false
)
// WriteXML writes XML-formatted SVG output to io.Writer, and uses
// XMLEncoder
func (sv *SVG) WriteXML(wr io.Writer, indent XMLIndent) error {
enc := NewXMLEncoder(wr)
if indent {
enc.Indent("", " ")
}
sv.MarshalXMLx(enc, xml.StartElement{})
enc.Flush()
return nil
}
func XMLAddAttr(attr *[]xml.Attr, name, val string) {
at := xml.Attr{}
at.Name.Local = name
at.Value = val
*attr = append(*attr, at)
}
// InkscapeProperties are property keys that should be prefixed with "inkscape:"
var InkscapeProperties = map[string]bool{
"isstock": true,
"stockid": true,
}
// MarshalXML encodes just the given node under SVG to XML.
// It returns the name of node, for end tag; if empty, then children will not be
// output.
func MarshalXML(n tree.Node, enc *XMLEncoder, setName string) string {
if n == nil || n.AsTree().This == nil {
return ""
}
se := xml.StartElement{}
properties := n.AsTree().Properties
if n.AsTree().Name != "" {
XMLAddAttr(&se.Attr, "id", n.AsTree().Name)
}
if sn, ok := n.(Node); ok && sn.AsNodeBase().Class != "" {
XMLAddAttr(&se.Attr, "class", sn.AsNodeBase().Class)
}
text := "" // if non-empty, contains text to render
_, issvg := n.(Node)
// _, isgp := n.(*Group)
_, ismark := n.(*Marker)
if issvg && !ismark {
sp := styleprops.ToXMLString(properties)
if sp != "" {
XMLAddAttr(&se.Attr, "style", sp)
}
if txp, has := properties["transform"]; has {
XMLAddAttr(&se.Attr, "transform", reflectx.ToString(txp))
}
} else {
for k, v := range properties {
sv := reflectx.ToString(v)
if _, has := InkscapeProperties[k]; has {
k = "inkscape:" + k
} else if k == "overflow" {
k = "style"
sv = "overflow:" + sv
}
XMLAddAttr(&se.Attr, k, sv)
}
}
var sb strings.Builder
nm := ""
switch nd := n.(type) {
case *Path:
nm = "path"
nd.DataStr = nd.Data.ToSVG()
XMLAddAttr(&se.Attr, "d", nd.DataStr)
case *Group:
nm = "g"
// if strings.HasPrefix(strings.ToLower(n.AsTree().Name), "layer") {
// }
for k, v := range properties {
sv := reflectx.ToString(v)
switch k {
case "opacity":
XMLAddAttr(&se.Attr, k, sv)
case "transform":
if slices.IndexFunc(se.Attr, func(a xml.Attr) bool { return a.Name.Local == k }) < 0 {
XMLAddAttr(&se.Attr, k, sv)
}
case "groupmode":
XMLAddAttr(&se.Attr, "inkscape:groupmode", sv)
if st, has := properties["style"]; has {
XMLAddAttr(&se.Attr, "style", reflectx.ToString(st))
} else {
XMLAddAttr(&se.Attr, "style", "display:inline")
}
case "insensitive":
if sv == "true" {
XMLAddAttr(&se.Attr, "sodipodi:"+k, sv)
}
}
}
case *Rect:
nm = "rect"
XMLAddAttr(&se.Attr, "x", fmt.Sprintf("%g", nd.Pos.X))
XMLAddAttr(&se.Attr, "y", fmt.Sprintf("%g", nd.Pos.Y))
XMLAddAttr(&se.Attr, "width", fmt.Sprintf("%g", nd.Size.X))
XMLAddAttr(&se.Attr, "height", fmt.Sprintf("%g", nd.Size.Y))
XMLAddAttr(&se.Attr, "rx", fmt.Sprintf("%g", nd.Radius.X))
XMLAddAttr(&se.Attr, "ry", fmt.Sprintf("%g", nd.Radius.Y))
case *Circle:
nm = "circle"
XMLAddAttr(&se.Attr, "cx", fmt.Sprintf("%g", nd.Pos.X))
XMLAddAttr(&se.Attr, "cy", fmt.Sprintf("%g", nd.Pos.Y))
XMLAddAttr(&se.Attr, "r", fmt.Sprintf("%g", nd.Radius))
case *Ellipse:
nm = "ellipse"
XMLAddAttr(&se.Attr, "cx", fmt.Sprintf("%g", nd.Pos.X))
XMLAddAttr(&se.Attr, "cy", fmt.Sprintf("%g", nd.Pos.Y))
XMLAddAttr(&se.Attr, "rx", fmt.Sprintf("%g", nd.Radii.X))
XMLAddAttr(&se.Attr, "ry", fmt.Sprintf("%g", nd.Radii.Y))
case *Line:
nm = "line"
XMLAddAttr(&se.Attr, "x1", fmt.Sprintf("%g", nd.Start.X))
XMLAddAttr(&se.Attr, "y1", fmt.Sprintf("%g", nd.Start.Y))
XMLAddAttr(&se.Attr, "x2", fmt.Sprintf("%g", nd.End.X))
XMLAddAttr(&se.Attr, "y2", fmt.Sprintf("%g", nd.End.Y))
case *Polygon:
nm = "polygon"
for _, p := range nd.Points {
fmt.Fprintf(&sb, "%g,%g ", p.X, p.Y)
}
XMLAddAttr(&se.Attr, "points", sb.String())
case *Polyline:
nm = "polyline"
for _, p := range nd.Points {
fmt.Fprintf(&sb, "%g,%g ", p.X, p.Y)
}
XMLAddAttr(&se.Attr, "points", sb.String())
case *Text:
_, parIsTxt := nd.Parent.(*Text)
if nd.HasChildren() || !parIsTxt {
nm = "text"
} else {
nm = "tspan"
}
XMLAddAttr(&se.Attr, "x", fmt.Sprintf("%g", nd.Pos.X))
XMLAddAttr(&se.Attr, "y", fmt.Sprintf("%g", nd.Pos.Y))
text = nd.Text
case *Image:
hasPixels := nd.Pixels != nil && nd.Pixels.Image != nil
if !hasPixels && nd.Filename == "" {
return ""
}
nm = "image"
XMLAddAttr(&se.Attr, "x", fmt.Sprintf("%g", nd.Pos.X))
XMLAddAttr(&se.Attr, "y", fmt.Sprintf("%g", nd.Pos.Y))
XMLAddAttr(&se.Attr, "width", fmt.Sprintf("%g", nd.Size.X))
XMLAddAttr(&se.Attr, "height", fmt.Sprintf("%g", nd.Size.Y))
XMLAddAttr(&se.Attr, "preserveAspectRatio", nd.ViewBox.PreserveAspectRatio.String())
if !hasPixels { // a link to an image that is not loaded
XMLAddAttr(&se.Attr, "href", nd.Filename)
break
}
ib, fmt := imagex.ToBase64(nd.Pixels.Image, imagex.PNG)
XMLAddAttr(&se.Attr, "href", "data:"+fmt+";base64,"+string(imagex.Base64SplitLines(ib)))
case *MetaData:
if strings.HasPrefix(nd.Name, "namedview") {
nm = "sodipodi:namedview"
} else if strings.HasPrefix(nd.Name, "grid") {
nm = "inkscape:grid"
}
case *Gradient:
MarshalXMLGradient(nd, nd.Name, enc)
return "" // exclude -- already written
case *Marker:
nm = "marker"
XMLAddAttr(&se.Attr, "refX", fmt.Sprintf("%g", nd.RefPos.X))
XMLAddAttr(&se.Attr, "refY", fmt.Sprintf("%g", nd.RefPos.Y))
XMLAddAttr(&se.Attr, "orient", nd.Orient)
XMLAddAttr(&se.Attr, "markerWidth", fmt.Sprintf("%g", nd.Size.X))
XMLAddAttr(&se.Attr, "markerHeight", fmt.Sprintf("%g", nd.Size.Y))
if nd.Units == UserSpaceOnUse { // (strokeWidth is the default)
XMLAddAttr(&se.Attr, "markerUnits", "userSpaceOnUse")
}
addXMLViewBox(&se.Attr, &nd.ViewBox)
case *Symbol:
nm = "symbol"
addXMLViewBox(&se.Attr, &nd.ViewBox)
case *Filter:
return "" // not yet supported
case *StyleSheet:
nm = "style"
if nd.Sheet != nil {
text = nd.Sheet.String()
}
default:
// the element name of an svg node, which is not its Go type name
if sn, ok := n.(Node); ok {
nm = sn.SVGName()
} else {
nm = n.AsTree().NodeType().Name
}
}
se.Name.Local = nm
if setName != "" {
se.Name.Local = setName
}
enc.EncodeToken(se)
if text != "" {
cd := xml.CharData([]byte(text))
enc.EncodeToken(cd)
}
return se.Name.Local
}
// addXMLViewBox adds the viewBox attribute of the given view box,
// if it has a size.
func addXMLViewBox(attr *[]xml.Attr, vb *ViewBox) {
if vb.Size == (math32.Vector2{}) {
return
}
XMLAddAttr(attr, "viewBox", fmt.Sprintf("%g %g %g %g", vb.Min.X, vb.Min.Y, vb.Size.X, vb.Size.Y))
}
// MarshalXMLGradient adds the XML for the given gradient to the given encoder.
// This is not in [cogentcore.org/core/colors/gradient] because it uses a lot of SVG
// and XML infrastructure defined here.
func MarshalXMLGradient(n *Gradient, name string, enc *XMLEncoder) {
gr := n.Grad
if gr == nil {
return
}
gb := gr.AsBase()
me := xml.StartElement{}
XMLAddAttr(&me.Attr, "id", name)
linear := true
if _, ok := gr.(*gradient.Radial); ok {
linear = false
me.Name.Local = "radialGradient"
} else {
me.Name.Local = "linearGradient"
}
if linear {
l := gr.(*gradient.Linear)
XMLAddAttr(&me.Attr, "x1", fmt.Sprintf("%g", l.Start.X))
XMLAddAttr(&me.Attr, "y1", fmt.Sprintf("%g", l.Start.Y))
XMLAddAttr(&me.Attr, "x2", fmt.Sprintf("%g", l.End.X))
XMLAddAttr(&me.Attr, "y2", fmt.Sprintf("%g", l.End.Y))
} else {
r := gr.(*gradient.Radial)
// must be non-zero to add
if r.Center != (math32.Vector2{}) {
XMLAddAttr(&me.Attr, "cx", fmt.Sprintf("%g", r.Center.X))
XMLAddAttr(&me.Attr, "cy", fmt.Sprintf("%g", r.Center.Y))
}
if r.Focal != (math32.Vector2{}) {
XMLAddAttr(&me.Attr, "fx", fmt.Sprintf("%g", r.Focal.X))
XMLAddAttr(&me.Attr, "fy", fmt.Sprintf("%g", r.Focal.Y))
}
if r.Radius != (math32.Vector2{}) {
XMLAddAttr(&me.Attr, "r", fmt.Sprintf("%g", max(r.Radius.X, r.Radius.Y)))
}
}
XMLAddAttr(&me.Attr, "gradientUnits", gb.Units.String())
// pad is default
if gb.Spread != gradient.Pad {
XMLAddAttr(&me.Attr, "spreadMethod", gb.Spread.String())
}
if gb.Transform != math32.Identity2() {
XMLAddAttr(&me.Attr, "gradientTransform", fmt.Sprintf("matrix(%g,%g,%g,%g,%g,%g)", gb.Transform.XX, gb.Transform.YX, gb.Transform.XY, gb.Transform.YY, gb.Transform.X0, gb.Transform.Y0))
}
if n.StopsName != "" {
XMLAddAttr(&me.Attr, "xlink:href", "#"+n.StopsName)
}
enc.EncodeToken(me)
if n.StopsName == "" {
for _, gs := range gb.Stops {
se := xml.StartElement{}
se.Name.Local = "stop"
clr := gs.Color
hs := colors.AsHex(clr)[:7] // get rid of transparency
op := gs.Opacity * float32(colors.AsRGBA(clr).A) / 255 // with any alpha of the color
XMLAddAttr(&se.Attr, "style", fmt.Sprintf("stop-color:%s;stop-opacity:%g;", hs, op))
XMLAddAttr(&se.Attr, "offset", fmt.Sprintf("%g", gs.Pos))
enc.EncodeToken(se)
enc.WriteEnd(se.Name.Local)
}
}
enc.WriteEnd(me.Name.Local)
}
// MarshalXMLTree encodes the given node and any children to XML.
// It returns any error, and name of element that enc.WriteEnd() should be
// called with; allows for extra elements to be added at end of list.
func MarshalXMLTree(n Node, enc *XMLEncoder, setName string) (string, error) {
name := MarshalXML(n, enc, setName)
if name == "" {
return "", nil
}
for _, k := range n.AsTree().Children {
kn := k.(Node)
if setName == "defs" {
if _, ok := kn.(*Path); ok { // skip paths in defs b/c just for use and copied
continue
}
}
knm, err := MarshalXMLTree(kn, enc, "")
if knm != "" {
enc.WriteEnd(knm)
}
if err != nil {
return name, err
}
}
return name, nil
}
// MarshalXMLx marshals the svg using XMLEncoder
func (sv *SVG) MarshalXMLx(enc *XMLEncoder, se xml.StartElement) error {
me := xml.StartElement{}
me.Name.Local = "svg"
hasNamedView := false
if sv.Root.NumChildren() > 0 {
kd := sv.Root.Children[0]
if md, ismd := kd.(*MetaData); ismd {
if strings.HasPrefix(md.Name, "namedview") {
hasNamedView = true
}
}
}
// PhysicalWidth and PhysicalHeight define the viewport in SVG terminology:
// https://www.w3.org/TR/SVG/coords.html
// these are defined in "abstract" units.
if sv.PhysicalWidth.Dots > 0 {
XMLAddAttr(&me.Attr, "width", fmt.Sprintf("%g", sv.PhysicalWidth.Dots))
}
if sv.PhysicalHeight.Dots > 0 {
XMLAddAttr(&me.Attr, "height", fmt.Sprintf("%g", sv.PhysicalHeight.Dots))
}
XMLAddAttr(&me.Attr, "viewBox", fmt.Sprintf("%g %g %g %g", sv.Root.ViewBox.Min.X, sv.Root.ViewBox.Min.Y, sv.Root.ViewBox.Size.X, sv.Root.ViewBox.Size.Y))
if hasNamedView {
XMLAddAttr(&me.Attr, "xmlns:inkscape", "http://www.inkscape.org/namespaces/inkscape")
XMLAddAttr(&me.Attr, "xmlns:sodipodi", "http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd")
}
XMLAddAttr(&me.Attr, "xmlns:xlink", "http://www.w3.org/1999/xlink")
XMLAddAttr(&me.Attr, "xmlns", "http://www.w3.org/2000/svg")
enc.EncodeToken(me)
var errs []error
if sv.Defs.HasChildren() {
dnm, err := MarshalXMLTree(sv.Defs, enc, "defs")
if err != nil {
errs = append(errs, err)
} else {
enc.WriteEnd(dnm)
}
}
for _, k := range sv.Root.Children {
knm, err := MarshalXMLTree(k.(Node), enc, "")
if err != nil {
errs = append(errs, err)
break
}
if knm != "" {
enc.WriteEnd(knm)
}
}
ed := xml.EndElement{}
ed.Name = me.Name
enc.EncodeToken(ed)
return errors.Join(errs...)
}
// SetStandardXMLAttr sets standard attributes of node given XML-style name /
// attribute values (e.g., from parsing XML / SVG files); returns true if handled.
func SetStandardXMLAttr(ni Node, name, val string) bool {
nb := ni.AsNodeBase()
switch name {
case "id":
nb.Name = val
return true
case "class":
nb.Class = val
return true
case "style":
if nb.Properties == nil {
nb.Properties = make(map[string]any)
}
styleprops.FromXMLString(val, nb.Properties)
return true
}
return false
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package svg
import (
"fmt"
"image/color"
"strings"
"cogentcore.org/core/colors"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint/ppath"
"cogentcore.org/core/paint/render"
"cogentcore.org/core/styles"
"cogentcore.org/core/tree"
)
// Mask is an SVG mask element: the luminance (times the alpha) of the
// rendering of its children masks the elements that refer to it with
// the mask property. It is not rendered itself.
type Mask struct {
NodeBase
}
func (g *Mask) SVGName() string { return "mask" }
func (g *Mask) EnforceSVGName() bool { return false }
func (g *Mask) Render(sv *SVG) {} // only for the elements that refer to it
func (g *ClipPath) Render(sv *SVG) {} // only for the elements that refer to it
func (g *ClipPath) EnforceSVGName() bool { return false }
// urlName returns the name (id) of the element that the given url()
// value refers to (url(#name), with or without quotes), or "" if it is
// not one (as none).
func urlName(v any) string {
s, ok := v.(string)
if !ok {
return ""
}
s = strings.TrimSpace(s)
rest, ok := strings.CutPrefix(s, "url(")
if !ok {
return ""
}
rest = strings.TrimSpace(strings.TrimSuffix(rest, ")"))
rest = strings.Trim(rest, `"'`)
_, name, ok := strings.Cut(rest, "#")
if !ok {
return ""
}
return name
}
// findByName returns the element with the given name (id), in the defs
// or the tree of the SVG, or nil if there is none.
func (sv *SVG) findByName(name string) Node {
if name == "" {
return nil
}
var found Node
find := func(n tree.Node) bool {
if found != nil {
return tree.Break
}
if n.AsTree().Name == name {
found = n.(Node)
return tree.Break
}
return tree.Continue
}
sv.Defs.WalkDown(find)
if found == nil {
sv.Root.WalkDown(find)
}
return found
}
// setLayerRefs sets the clip-path and mask references of the node from
// the given properties (as of its attributes or the rules of its style
// sheet that apply to it), if they have them.
func (g *NodeBase) setLayerRefs(properties map[string]any) {
if v, ok := properties["clip-path"]; ok {
g.clipRef = urlName(v)
}
if v, ok := properties["mask"]; ok {
g.maskRef = urlName(v)
}
}
// isGroupOpacity returns whether the opacity of the node applies to its
// rendering as a whole (as for the opacity of groups), rather than to
// its fill and stroke.
func (g *NodeBase) isGroupOpacity() bool {
_, ok := g.This.(*Group)
return ok
}
// pushLayer pushes a context for the clip-path and mask of a shape (which
// renders with its transform without pushing a context), if it has them,
// returning whether it did, in which case the shape pops it after it
// renders. The context has no transform of its own, but its clip mask and
// mask are in the user space of the shape (with its transform).
func (g *NodeBase) pushLayer(sv *SVG) bool {
g.preparePatterns(sv, g.Paint.Transform)
if g.clipRef == "" && g.maskRef == "" {
return false
}
sv.pushTransform(math32.Identity2())
g.setLayer(sv, g.Paint.Transform)
return true
}
// setLayer sets the clip mask, mask, and opacity of the context of the
// node, which it has just pushed, if it has a clip-path or mask that
// refers to an element, or the opacity of a group (see
// [paint.State.SetLayer]). The clip mask and mask are rendered with the
// given transform, from the user space of the context.
func (g *NodeBase) setLayer(sv *SVG, xf math32.Matrix2) {
var opacity float32
if g.isGroupOpacity() && g.Paint.Opacity < 1 {
opacity = g.Paint.Opacity
}
var cp *ClipPath
var mk *Mask
if g.clipRef != "" {
cp, _ = sv.findByName(g.clipRef).(*ClipPath)
}
if g.maskRef != "" {
mk, _ = sv.findByName(g.maskRef).(*Mask)
}
if cp == nil && mk == nil && opacity == 0 {
return
}
pc := g.Painter(sv)
var clip, mask render.Render
if cp != nil {
clip = pc.RenderSeparately(func() {
sv.pushTransform(xf)
cp.renderClip(sv, g)
sv.painter.PopContext()
})
if len(clip) == 0 { // nothing is in the clip path: nothing is rendered
clip = render.Render{&render.ContextPush{}, &render.ContextPop{}}
}
}
if mk != nil {
mask = pc.RenderSeparately(func() {
sv.pushTransform(xf)
mk.renderMask(sv, g)
sv.painter.PopContext()
})
if len(mask) == 0 {
mask = render.Render{&render.ContextPush{}, &render.ContextPop{}}
}
}
pc.SetLayer(clip, mask, opacity)
}
// userBBox returns the bounding box of the given node in its user space,
// for the objectBoundingBox units of clip paths, masks, and patterns.
func (sv *SVG) userBBox(g *NodeBase) math32.Box2 {
if bb := g.This.(Node).LocalBBox(sv); bb.Size() != (math32.Vector2{}) {
return bb
}
// groups: their box (in the coordinates of the SVG) in their user space
inv := sv.painter.Context().Cumulative.Inverse()
return g.BBox.MulMatrix2(inv)
}
// unitsTransform returns the transform from the objectBoundingBox units
// of the given property of the given node (as clipPathUnits) to the
// user space of the given target node, or the identity for
// userSpaceOnUse units (or the given default).
func (sv *SVG) unitsTransform(n *NodeBase, prop string, def bool, target *NodeBase) math32.Matrix2 {
obb := def
if v, ok := n.Properties[prop]; ok {
obb = fmt.Sprint(v) == "objectBoundingBox"
}
if !obb {
return math32.Identity2()
}
bb := sv.userBBox(target)
sz := bb.Size()
return math32.Translate2D(bb.Min.X, bb.Min.Y).Scale(sz.X, sz.Y)
}
// pushTransform pushes a context with the given transform, from the user
// space of the current one.
func (sv *SVG) pushTransform(xf math32.Matrix2) {
sty := styles.NewPaint()
sty.UnitContext = sv.painter.Context().Style.UnitContext
sty.Transform = xf
sv.painter.PushContext(sty, nil)
}
// renderClip renders the shapes of the clip path, for the clip mask of
// the given target node (in its user space, as its context is pushed):
// as opaque fills (with their clip-rule), whatever their fill and stroke.
func (g *ClipPath) renderClip(sv *SVG, target *NodeBase) {
xf := sv.unitsTransform(&g.NodeBase, "clipPathUnits", false, target).Mul(g.Paint.Transform)
sv.pushTransform(xf)
defer sv.painter.PopContext()
type saved struct {
nb *NodeBase
paint styles.Paint
isDef bool
}
var restore []saved
white := colors.Uniform(color.RGBA{255, 255, 255, 255})
rule := clipRule(g.Properties, ppath.NonZero)
var setRules func(n tree.Node, rule ppath.FillRules)
setRules = func(n tree.Node, rule ppath.FillRules) {
nb := n.(Node).AsNodeBase()
rule = clipRule(nb.Properties, rule)
restore = append(restore, saved{nb, nb.Paint, nb.isDef})
pc := &nb.Paint
pc.Fill.Color, pc.Fill.Opacity, pc.Fill.Rule = white, 1, rule
pc.Stroke.Color = nil
pc.Opacity = 1
pc.Off = false
nb.isDef = true // rendered whatever their visible box
for _, k := range nb.Children {
setRules(k, rule)
}
}
for _, k := range g.Children {
setRules(k, rule)
}
defer func() {
for _, s := range restore {
s.nb.Paint, s.nb.isDef = s.paint, s.isDef
}
}()
for _, k := range g.Children {
k.(Node).Render(sv)
}
}
// clipRule returns the fill rule of the clip-rule in the given
// properties, or the given one (inherited) if they have none.
func clipRule(properties map[string]any, rule ppath.FillRules) ppath.FillRules {
switch fmt.Sprint(properties["clip-rule"]) {
case "evenodd":
return ppath.EvenOdd
case "nonzero":
return ppath.NonZero
}
return rule
}
// renderMask renders the children of the mask, for the mask of the given
// target node (in its user space, as its context is pushed), clipped to
// the region of the mask (by default 10% larger than the bounding box of
// the target on each side).
func (g *Mask) renderMask(sv *SVG, target *NodeBase) {
// the region of the mask, in maskUnits (objectBoundingBox by default)
region := math32.B2(-0.1, -0.1, 1.1, 1.1)
pos := func(prop string, def float32) float32 {
v, ok := g.Properties[prop]
if !ok {
return def
}
s := strings.TrimSpace(fmt.Sprint(v))
if pct, ok := strings.CutSuffix(s, "%"); ok {
f, _ := math32.ParseFloat32(pct)
return f / 100
}
f, _ := math32.ParseFloat32(s)
return f
}
x, y := pos("x", region.Min.X), pos("y", region.Min.Y)
w, h := pos("width", region.Size().X), pos("height", region.Size().Y)
unitsXf := sv.unitsTransform(&g.NodeBase, "maskUnits", true, target)
regionPath := ppath.New().Rectangle(x, y, w, h)
// the children, clipped to the region
pc := g.Painter(sv)
sv.pushTransform(math32.Identity2())
regionClip := pc.RenderSeparately(func() {
sv.pushTransform(unitsXf)
sty := styles.NewPaint()
sty.Fill.Color = colors.Uniform(color.RGBA{255, 255, 255, 255})
sty.Stroke.Color = nil
rp := &render.Path{Path: *regionPath, Context: *render.NewContext(sty, nil, sv.painter.Context())}
sv.painter.Render.Add(rp)
sv.painter.PopContext()
})
pc.SetLayer(regionClip, nil, 0)
sv.pushTransform(sv.unitsTransform(&g.NodeBase, "maskContentUnits", false, target))
for _, k := range g.Children {
nb := k.(Node).AsNodeBase()
def := nb.isDef
nb.isDef = true // rendered whatever their visible box
k.(Node).Render(sv)
nb.isDef = def
}
sv.painter.PopContext()
sv.painter.PopContext()
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package svg
import (
"cogentcore.org/core/math32"
)
// Line is a SVG line
type Line struct {
NodeBase
// position of the start of the line
Start math32.Vector2 `svg:"x1,y1"`
// position of the end of the line
End math32.Vector2 `svg:"x2,y2"`
}
func (g *Line) SVGName() string { return "line" }
func (g *Line) Init() {
g.NodeBase.Init()
g.End.Set(1, 1)
}
func (g *Line) SetPos(pos math32.Vector2) {
g.Start = pos
}
func (g *Line) SetSize(sz math32.Vector2) {
g.End = g.Start.Add(sz)
}
func (g *Line) LocalBBox(sv *SVG) math32.Box2 {
bb := math32.B2Empty()
bb.ExpandByPoint(g.Start)
bb.ExpandByPoint(g.End)
hlw := 0.5 * g.LocalLineWidth()
bb.Min.SetSubScalar(hlw)
bb.Max.SetAddScalar(hlw)
return bb
}
func (g *Line) Render(sv *SVG) {
if !g.IsVisible(sv) {
return
}
pc := g.Painter(sv)
if g.pushLayer(sv) {
defer pc.PopContext()
}
pc.Line(g.Start.X, g.Start.Y, g.End.X, g.End.Y)
pc.Draw()
g.PushContext(sv)
if mrk := sv.MarkerByName(g, "marker-start"); mrk != nil {
ang := math32.Atan2(g.End.Y-g.Start.Y, g.End.X-g.Start.X)
mrk.RenderMarkerStart(sv, g.Start, ang, g.Paint.Stroke.Width.Dots)
}
if mrk := sv.MarkerByName(g, "marker-end"); mrk != nil {
ang := math32.Atan2(g.End.Y-g.Start.Y, g.End.X-g.Start.X)
mrk.RenderMarker(sv, g.End, ang, g.Paint.Stroke.Width.Dots)
}
pc.PopContext()
}
// ApplyTransform applies the given 2D transform to the geometry of this node
// each node must define this for itself
func (g *Line) ApplyTransform(sv *SVG, xf math32.Matrix2) {
rot := xf.ExtractRot()
if rot != 0 {
g.Paint.Transform.SetMul(xf)
g.SetTransformProperty()
} else {
g.Start = xf.MulPoint(g.Start)
g.End = xf.MulPoint(g.End)
g.GradientApplyTransform(sv, xf)
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package svg
import (
"log"
"strings"
"cogentcore.org/core/math32"
)
// Marker represents marker elements that can be drawn along paths (arrow heads, etc)
type Marker struct {
NodeBase
// reference position to align the vertex position with, specified in ViewBox coordinates
RefPos math32.Vector2 `svg:"refX,refY"`
// size of marker to render, in Units units
Size math32.Vector2 `svg:"markerWidth,markerHeight"`
// units to use
Units MarkerUnits `xml:"markerUnits"`
// viewbox defines the internal coordinate system for the drawing elements within the marker
ViewBox ViewBox
// orientation of the marker -- either 'auto' or an angle
Orient string `xml:"orient"`
// start is whether the marker is rendered as a marker-start.
start bool
// current vertex position
VertexPos math32.Vector2
// current vertex angle in radians
VertexAngle float32
// current stroke width
StrokeWidth float32
// net transform computed from settings and current values -- applied prior to rendering
Transform math32.Matrix2
// effective size for actual rendering
EffSize math32.Vector2
}
func (g *Marker) SVGName() string { return "marker" }
func (g *Marker) EnforceSVGName() bool { return false }
// MarkerUnits specifies units to use for svg marker elements
type MarkerUnits int32 //enum: enum
const (
StrokeWidth MarkerUnits = iota
UserSpaceOnUse
MarkerUnitsN
)
// RenderMarkerStart renders the marker as a marker-start, with the given
// vertex position, angle (in radians), and stroke width: as
// [Marker.RenderMarker], reversed for an orient of auto-start-reverse.
func (g *Marker) RenderMarkerStart(sv *SVG, vertexPos math32.Vector2, vertexAng, strokeWidth float32) {
g.start = true
g.RenderMarker(sv, vertexPos, vertexAng, strokeWidth)
g.start = false
}
// RenderMarker renders the marker using given vertex position, angle (in
// radians), and stroke width
func (g *Marker) RenderMarker(sv *SVG, vertexPos math32.Vector2, vertexAng, strokeWidth float32) {
g.VertexPos = vertexPos
g.VertexAngle = vertexAng
g.StrokeWidth = strokeWidth
if g.Units == StrokeWidth {
g.EffSize = g.Size.MulScalar(strokeWidth)
} else {
g.EffSize = g.Size
}
ang := vertexAng
switch strings.TrimSpace(g.Orient) {
case "auto":
case "auto-start-reverse": // the start marker points backward
if g.start {
ang += math32.Pi
}
default:
ang, _ = math32.ParseAngle32(g.Orient)
}
if g.ViewBox.Size == (math32.Vector2{}) {
g.ViewBox.Size = math32.Vec2(3, 3)
}
g.Transform = math32.Rotate2D(ang).Scale(g.EffSize.X/g.ViewBox.Size.X, g.EffSize.Y/g.ViewBox.Size.Y).Translate(-g.RefPos.X, -g.RefPos.Y)
g.Transform.X0 += vertexPos.X
g.Transform.Y0 += vertexPos.Y
g.Paint.Transform = g.Transform
// fmt.Println("render marker:", mrk.Name, strokeWidth, mrk.EffSize, mrk.Transform)
g.Render(sv)
}
func (g *Marker) BBoxes(sv *SVG, parTransform math32.Matrix2) {
g.BBoxesFromChildren(sv, parTransform)
}
func (g *Marker) Render(sv *SVG) {
pc := g.Painter(sv)
pc.PushContext(&g.Paint, nil)
g.RenderChildren(sv)
pc.PopContext()
}
//////// SVG marker management
// MarkerByName finds marker property of given name, or generic "marker"
// type, and if set, attempts to find that marker and return it
func (sv *SVG) MarkerByName(n Node, marker string) *Marker {
url := NodePropURL(n, marker)
if url == "" {
url = NodePropURL(n, "marker")
}
if url == "" {
return nil
}
mrkn := sv.NodeFindURL(n, url)
if mrkn == nil {
return nil
}
mrk, ok := mrkn.(*Marker)
if !ok {
log.Printf("SVG Found element named: %v but isn't a Marker type, instead is: %T", url, mrkn)
return nil
}
return mrk
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package svg
import (
"fmt"
"image/color"
"maps"
"reflect"
"slices"
"strings"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/colors"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint"
"cogentcore.org/core/styles"
"cogentcore.org/core/text/text"
"cogentcore.org/core/tree"
)
// Node is the interface for all SVG nodes.
type Node interface {
tree.Node
// AsNodeBase returns the [NodeBase] for our node, which gives
// access to all the base-level data structures and methods
// without requiring interface methods.
AsNodeBase() *NodeBase
// BBoxes computes BBox and VisBBox, prior to render.
BBoxes(sv *SVG, parTransform math32.Matrix2)
// Render draws the node to the svg image.
Render(sv *SVG)
// LocalBBox returns the bounding box of node in local dimensions.
LocalBBox(sv *SVG) math32.Box2
// SetNodePos sets the upper left effective position of this element, in local dimensions.
SetNodePos(pos math32.Vector2)
// SetNodeSize sets the overall effective size of this element, in local dimensions.
SetNodeSize(sz math32.Vector2)
// ApplyTransform applies the given 2D transform to the geometry of this node
// this just does a direct transform multiplication on coordinates.
ApplyTransform(sv *SVG, xf math32.Matrix2)
// SVGName returns the SVG element name (e.g., "rect", "path" etc).
SVGName() string
// EnforceSVGName returns true if in general this element should
// be named with its SVGName plus a unique id.
// Groups and Markers are false.
EnforceSVGName() bool
}
// NodeBase is the base type for all elements within an SVG tree.
// It implements the [Node] interface and contains the core functionality.
type NodeBase struct {
tree.NodeBase
// Class contains user-defined class name(s) used primarily for attaching
// CSS styles to different display elements.
// Multiple class names can be used to combine properties;
// use spaces to separate per css standard.
Class string
// CSS is the cascading style sheet at this level.
// These styles apply here and to everything below, until superceded.
// Use .class and #name Properties elements to apply entire styles
// to given elements, and type for element type.
CSS map[string]any `xml:"css" set:"-"`
// CSSAgg is the aggregated css properties from all higher nodes down to this node.
CSSAgg map[string]any `copier:"-" json:"-" xml:"-" set:"-" display:"no-inline"`
// vars are the custom properties of CSS (--name) of the node, as they
// apply to it (see vars.go).
vars map[string]string
// BBox is the bounding box for the node within the SVG Pixels image.
// This one can be outside the visible range of the SVG image.
// VisBBox is intersected and only shows visible portion.
BBox math32.Box2 `copier:"-" json:"-" xml:"-" set:"-"`
// VisBBox is the visible bounding box for the node intersected with the SVG image geometry.
VisBBox math32.Box2 `copier:"-" json:"-" xml:"-" set:"-"`
// Paint is the paint style information for this node.
Paint styles.Paint `json:"-" xml:"-" set:"-"`
// GradientFill contains the fill gradient geometry to use for linear and radial
// gradients of UserSpaceOnUse type applied to this node.
// These values are updated and copied to gradients of the appropriate type to keep
// the gradients sync'd with updates to the node as it is transformed.
GradientFill math32.Matrix2 `json:"-" xml:"-" set:"-" display:"-"`
// GradientStroke contains the stroke gradient geometry to use for linear and radial
// gradients of UserSpaceOnUse type applied to this node.
// These values are updated and copied to gradients of the appropriate type to keep
// the gradients sync'd with updates to the node as it is transformed.
GradientStroke math32.Matrix2 `json:"-" xml:"-" set:"-" display:"-"`
// isDef is whether this is in [SVG.Defs].
isDef bool
// clipRef is the name of the clipPath that the clip-path property
// refers to, if any.
clipRef string
// maskRef is the name of the mask that the mask property refers to,
// if any.
maskRef string
// color is the current color of the node (currentColor), from its
// color property or that of its parent.
color color.RGBA
// anchor is the text-anchor of the node (set on it or inherited).
anchor string
// fillCurrent and strokeCurrent are whether the fill and stroke of
// the node are currentColor (set on it or inherited), which is that
// of the node, not of the node that it is inherited from.
fillCurrent, strokeCurrent bool
}
// nodeContext is the [colors.Context] of the properties of a node: that of
// its SVG, with its current color as the base color (currentColor).
type nodeContext struct {
*SVG
color color.RGBA
}
func (nc *nodeContext) Base() color.RGBA { return nc.color }
// setColor sets the current color of the node, from its color property
// (in its properties or the rules of the style sheets that apply to it),
// or that of its parent (or of the SVG, for the root).
func (g *NodeBase) setColor(sv *SVG) {
if g.Parent != nil {
if pn, ok := g.Parent.(Node); ok {
g.color = pn.AsNodeBase().color
}
} else {
g.color = colors.AsRGBA(colors.ToUniform(sv.Color))
if sv.Color == nil {
g.color = color.RGBA{0, 0, 0, 255}
}
}
if v, ok := g.ownProperty("color"); ok {
if c, err := colors.FromString(v, g.color); err == nil {
g.color = colors.AsRGBA(c)
}
}
g.fillCurrent, g.strokeCurrent, g.anchor = false, false, ""
if pn, ok := g.Parent.(Node); ok {
pb := pn.AsNodeBase()
g.fillCurrent, g.strokeCurrent, g.anchor = pb.fillCurrent, pb.strokeCurrent, pb.anchor
}
if v, ok := g.ownProperty("text-anchor"); ok {
g.anchor = v
}
if v, ok := g.ownProperty("fill"); ok {
g.fillCurrent = strings.EqualFold(v, "currentcolor")
}
if v, ok := g.ownProperty("stroke"); ok {
g.strokeCurrent = strings.EqualFold(v, "currentcolor")
}
}
// ownProperty returns the value of the given property that is set on the
// node, in its properties or the rules of the style sheets that apply to
// it (the last that applies), and whether it is set.
func (g *NodeBase) ownProperty(name string) (string, bool) {
vals := []any{g.Properties[name]}
if g.CSSAgg != nil {
for _, sel := range []string{strings.ToLower(g.NodeType().Name), "." + strings.ToLower(g.Class), "#" + strings.ToLower(g.Name)} {
if pm, ok := g.CSSAgg[sel].(map[string]any); ok {
vals = append(vals, pm[name])
}
}
}
val, has := "", false
for _, v := range vals {
if s, ok := v.(string); ok && strings.TrimSpace(s) != "" {
val, has = strings.TrimSpace(s), true
}
}
return val, has
}
func (g *NodeBase) AsNodeBase() *NodeBase { return g }
func (g *NodeBase) SVGName() string { return "base" }
func (g *NodeBase) EnforceSVGName() bool { return true }
func (g *NodeBase) SetPos(pos math32.Vector2) {}
func (g *NodeBase) SetSize(sz math32.Vector2) {}
func (g *NodeBase) PaintStyle() *styles.Paint { return &g.Paint }
func (g *NodeBase) LocalBBox(sv *SVG) math32.Box2 { return math32.Box2{} }
func (g *NodeBase) BaseInterface() reflect.Type { return reflect.TypeFor[NodeBase]() }
func (g *NodeBase) SetTransformProperty() { g.SetProperty("transform", g.Paint.Transform.String()) }
func (g *NodeBase) Init() {
g.Paint.Defaults()
g.GradientFill = math32.Identity2()
g.GradientStroke = math32.Identity2()
g.Paint.Stroke.Width.Px(1) // dp is not understood by svg..
}
// SetColorProperties sets color property from a string representation.
// It breaks color alpha out as opacity. prop is either "stroke" or "fill"
func (g *NodeBase) SetColorProperties(prop, value string) {
if NameFromURL(value) != "" {
return
}
if value == "none" || value == "" {
g.SetProperty(prop, "none")
g.DeleteProperty(prop + "-opacity")
if prop == "stroke" {
g.DeleteProperty("stroke-width")
}
return
}
clr, _ := colors.FromString(value)
g.SetProperty(prop+"-opacity", fmt.Sprintf("%g", float32(clr.A)/255))
// we have consumed the A via opacity, so we reset it to 255, after
// un-premultiplying the color by it
nclr := color.NRGBAModel.Convert(clr).(color.NRGBA)
nclr.A = 255
g.SetProperty(prop, colors.AsHex(nclr))
}
// ParentTransform returns the full compounded 2D transform matrix for all
// of the parents of this node. If self is true, then include our
// own transform too.
func (g *NodeBase) ParentTransform(self bool) math32.Matrix2 {
pars := []Node{}
xf := math32.Identity2()
n := g.This.(Node)
for n.AsTree().Parent != nil {
n = n.AsTree().Parent.(Node)
pars = append(pars, n)
}
np := len(pars)
if np > 0 {
xf = pars[np-1].AsNodeBase().PaintStyle().Transform
}
for i := np - 2; i >= 0; i-- {
n := pars[i]
xf.SetMul(n.AsNodeBase().PaintStyle().Transform)
}
if self {
xf.SetMul(g.Paint.Transform)
}
return xf
}
// ApplyTransform applies the given 2D transform to the geometry of this node.
func (g *NodeBase) ApplyTransform(sv *SVG, xf math32.Matrix2) {
}
// DeltaTransform computes the net transform matrix for given delta transform parameters,
// operating around given reference point which serves as the effective origin for rotation.
func (g *NodeBase) DeltaTransform(trans math32.Vector2, scale math32.Vector2, rot float32, pt math32.Vector2) math32.Matrix2 {
mxi := g.ParentTransform(true).Inverse()
lpt := mxi.MulPoint(pt)
ltr := mxi.MulVector(trans)
xf := math32.Translate2D(lpt.X, lpt.Y).Scale(scale.X, scale.Y).Rotate(rot).Translate(ltr.X, ltr.Y).Translate(-lpt.X, -lpt.Y)
return xf
}
// SVGWalkDown does [tree.NodeBase.WalkDown] on given node using given walk function
// with SVG Node parameters.
func SVGWalkDown(n Node, fun func(sn Node, snb *NodeBase) bool) {
n.AsTree().WalkDown(func(n tree.Node) bool {
sn := n.(Node)
return fun(sn, sn.AsNodeBase())
})
}
// SVGWalkDownNoDefs does [tree.Node.WalkDown] on given node using given walk function
// with SVG Node parameters. Automatically filters Defs nodes (IsDef) and MetaData,
// i.e., it only processes concrete graphical nodes.
func SVGWalkDownNoDefs(n Node, fun func(sn Node, snb *NodeBase) bool) {
n.AsTree().WalkDown(func(cn tree.Node) bool {
sn := cn.(Node)
snb := sn.AsNodeBase()
_, md := sn.(*MetaData)
if snb.isDef || md {
return tree.Break
}
return fun(sn, snb)
})
}
// FirstNonGroupNode returns the first item that is not a group
// recursing into groups until a non-group item is found.
func FirstNonGroupNode(n Node) Node {
var ngn Node
SVGWalkDownNoDefs(n, func(sn Node, snb *NodeBase) bool {
if _, isgp := sn.(*Group); isgp {
return tree.Continue
}
ngn = sn
return tree.Break
})
return ngn
}
//////// Standard Node infrastructure
// Style styles the Paint values directly from node properties
func (g *NodeBase) Style(sv *SVG) {
pc := &g.Paint
pc.Defaults()
pc.StyleSet = false // this is always first call, restart
var parCSSAgg map[string]any
if g.Parent != nil { // && g.Par != sv.Root.This
parCSSAgg = g.Parent.(Node).AsNodeBase().CSSAgg
}
if parCSSAgg != nil {
AggCSS(&g.CSSAgg, parCSSAgg)
} else {
g.CSSAgg = nil
}
AggCSS(&g.CSSAgg, g.CSS)
var parVars map[string]string
if pn, ok := g.Parent.(Node); ok && pn != nil {
parVars = pn.AsNodeBase().vars
}
g.vars = g.customVars(parVars)
props := resolveVarsIn(g.Properties, g.vars)
g.setColor(sv)
ctxt := colors.Context(&nodeContext{sv, g.color})
if g.Parent != nil { // && g.Par != sv.Root.This
pn := g.Parent.(Node)
pp := pn.AsNodeBase().PaintStyle()
pc.CopyStyleFrom(pp)
pc.SetProperties(pp, props, ctxt)
} else {
pc.SetProperties(nil, props, ctxt)
}
pc.ToDotsImpl(&pc.UnitContext) // we always inherit parent's unit context -- SVG sets it once-and-for-all
g.clipRef, g.maskRef = "", ""
g.setLayerRefs(g.Properties)
g.StyleCSS(sv, g.CSSAgg)
switch g.anchor { // text-anchor, as the text alignment
case "middle":
pc.Text.Align = text.Center
case "end":
pc.Text.Align = text.End
case "start":
pc.Text.Align = text.Start
}
if g.fillCurrent && pc.Fill.Color != nil { // the current color of this node
pc.Fill.Color = colors.Uniform(g.color)
}
if g.strokeCurrent && pc.Stroke.Color != nil {
pc.Stroke.Color = colors.Uniform(g.color)
}
if !g.isGroupOpacity() { // groups are rendered with their opacity as a whole
pc.Stroke.Opacity *= pc.Opacity // applies to all
pc.Fill.Opacity *= pc.Opacity
}
pc.Off = (pc.Stroke.Color == nil && pc.Fill.Color == nil)
}
// AggCSS aggregates css properties
func AggCSS(agg *map[string]any, css map[string]any) {
if *agg == nil {
*agg = make(map[string]any)
}
maps.Copy(*agg, css)
}
// ApplyCSS applies css styles to given node,
// using key to select sub-properties from overall properties list
func (g *NodeBase) ApplyCSS(sv *SVG, key string, css map[string]any) bool {
pp, got := css[key]
if !got {
return false
}
pmap, ok := pp.(map[string]any) // must be a properties map
if !ok {
return false
}
pmap = resolveVarsIn(pmap, g.vars)
pc := &g.Paint
ctxt := colors.Context(&nodeContext{sv, g.color})
if g.Parent != sv.Root.This {
pp := g.Parent.(Node).AsNodeBase().PaintStyle()
pc.SetProperties(pp, pmap, ctxt)
} else {
pc.SetProperties(nil, pmap, ctxt)
}
g.setLayerRefs(pmap)
return true
}
// StyleCSS applies css style properties to given SVG node
// parsing out type, .class, and #name selectors
func (g *NodeBase) StyleCSS(sv *SVG, css map[string]any) {
tyn := strings.ToLower(g.NodeType().Name) // type is most general, first
g.ApplyCSS(sv, tyn, css)
cln := "." + strings.ToLower(g.Class) // then class
g.ApplyCSS(sv, cln, css)
idnm := "#" + strings.ToLower(g.Name) // then name
g.ApplyCSS(sv, idnm, css)
}
func (g *NodeBase) SetNodePos(pos math32.Vector2) {
// no-op by default
}
func (g *NodeBase) SetNodeSize(sz math32.Vector2) {
// no-op by default
}
// LocalLineWidth returns the line width in local coordinates
func (g *NodeBase) LocalLineWidth() float32 {
pc := &g.Paint
if pc.Stroke.Color == nil {
return 0
}
return pc.Stroke.Width.Dots
}
func (g *NodeBase) BBoxes(sv *SVG, parTransform math32.Matrix2) {
xf := parTransform.Mul(g.Paint.Transform)
ni := g.This.(Node)
lbb := ni.LocalBBox(sv)
g.BBox = lbb.MulMatrix2(xf)
g.VisBBox = sv.Geom.Box2().Intersect(g.BBox)
}
// IsVisible checks our bounding box and visibility, returning false if
// out of bounds. Must be called as first step in Render.
func (g *NodeBase) IsVisible(sv *SVG) bool {
if g == nil || g.This == nil || g.Paint.Off || !g.Paint.Display {
return false
}
nvis := g.VisBBox == (math32.Box2{})
if nvis && !g.isDef {
// fmt.Println("invisible:", g.Name, "bb:", g.BBox, "vbb:", g.VisBBox, "svg:", sv.Geom.Bounds())
return false
}
return true
}
// Painter returns a new Painter using my styles.
func (g *NodeBase) Painter(sv *SVG) *paint.Painter {
return &paint.Painter{State: sv.painter.State, Paint: &g.Paint}
}
// PushContext checks our bounding box and visibility, returning false if
// out of bounds. If visible, pushes us as Context.
// Must be called as first step in Render.
func (g *NodeBase) PushContext(sv *SVG) bool {
if !g.IsVisible(sv) {
return false
}
pc := g.Painter(sv)
pc.PushContext(&g.Paint, nil)
return true
}
func (g *NodeBase) BBoxesFromChildren(sv *SVG, parTransform math32.Matrix2) {
xf := parTransform.Mul(g.Paint.Transform)
var bb math32.Box2
for i, kid := range g.Children {
ni := kid.(Node)
ni.BBoxes(sv, xf)
nb := ni.AsNodeBase()
if i == 0 {
bb = nb.BBox
} else {
bb = bb.Union(nb.BBox)
}
}
g.BBox = bb
g.VisBBox = sv.Geom.Box2().Intersect(g.BBox)
}
func (g *NodeBase) RenderChildren(sv *SVG) {
for _, kid := range g.Children {
ni := kid.(Node)
ni.Render(sv)
}
}
func (g *NodeBase) Render(sv *SVG) {
if !g.IsVisible(sv) {
return
}
g.RenderChildren(sv)
}
// BitCloneNode returns a bit-wise copy of just the single svg Node itself
// without any of the children, props or other state being copied, etc.
// Useful for saving and restoring state during animations or other
// manipulations. See also [CopyFrom].
func BitCloneNode(n Node) Node {
cp := n.AsTree().NewInstance().(Node)
BitCopyFrom(cp, n)
return cp
}
// BitCopyFrom copies only the direct field bits and other key shape data
// (e.g., [Path.Data]) between nodes. Useful for saving and restoring
// state during animations or other manipulations.
func BitCopyFrom(to, fm any) {
reflectx.Underlying(reflect.ValueOf(to)).Set(reflectx.Underlying(reflect.ValueOf(fm)))
switch x := to.(type) {
case *Path:
x.Data = fm.(*Path).Data.Clone()
case *Polyline: // (the copy of the fields shares the points)
x.Points = slices.Clone(fm.(*Polyline).Points)
case *Polygon:
x.Points = slices.Clone(fm.(*Polygon).Points)
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package svg
import (
"cogentcore.org/core/base/errors"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint/ppath"
)
// Path renders SVG data sequences that can render just about anything
type Path struct {
NodeBase
// Path data using paint/ppath representation.
Data ppath.Path `xml:"-" set:"-"`
// string version of the path data
DataStr string `xml:"d"`
}
func (g *Path) SVGName() string { return "path" }
func (g *Path) SetPos(pos math32.Vector2) {
// todo: set first point
}
func (g *Path) SetSize(sz math32.Vector2) {
bb := g.Data.FastBounds()
csz := bb.Size()
if csz.X == 0 || csz.Y == 0 {
return
}
sc := sz.Div(csz)
g.Data.Transform(math32.Scale2D(sc.X, sc.Y))
}
// SetData sets the path data to given string, parsing it into an optimized
// form used for rendering
func (g *Path) SetData(data string) error {
d, err := ppath.ParseSVGPath(data)
if errors.Log(err) != nil {
return err
}
g.DataStr = data
g.Data = d
return err
}
func (g *Path) LocalBBox(sv *SVG) math32.Box2 {
bb := g.Data.FastBounds()
hlw := 0.5 * g.LocalLineWidth()
bb.Min.SetSubScalar(hlw)
bb.Max.SetAddScalar(hlw)
return bb
}
func (g *Path) Render(sv *SVG) {
sz := len(g.Data)
if sz < 2 || !g.IsVisible(sv) {
return
}
pc := g.Painter(sv)
if g.pushLayer(sv) {
defer pc.PopContext()
}
pc.State.Path = g.Data.Clone() // note: yes this Clone() is absolutely necessary.
pc.Draw()
g.PushContext(sv)
mrkStart := sv.MarkerByName(g, "marker-start")
mrkEnd := sv.MarkerByName(g, "marker-end")
mrkMid := sv.MarkerByName(g, "marker-mid")
if mrkStart != nil || mrkEnd != nil || mrkMid != nil {
pos := g.Data.Coords()
dir := g.Data.CoordDirections()
np := len(pos)
if mrkStart != nil && np > 1 {
dir0 := pos[1].Sub(pos[0])
ang := ppath.Angle(dir0) // dir[0]: has average but last 2 works better
mrkStart.RenderMarkerStart(sv, pos[0], ang, g.Paint.Stroke.Width.Dots)
}
if mrkEnd != nil && np > 1 {
dirn := pos[np-1].Sub(pos[np-2])
ang := ppath.Angle(dirn) // dir[np-1]: see above
mrkEnd.RenderMarker(sv, pos[np-1], ang, g.Paint.Stroke.Width.Dots)
}
if mrkMid != nil && np > 2 {
for i := 1; i < np-2; i++ {
ang := ppath.Angle(dir[i])
mrkMid.RenderMarker(sv, pos[i], ang, g.Paint.Stroke.Width.Dots)
}
}
}
pc.PopContext()
}
// UpdatePathString sets the path string from the Data
func (g *Path) UpdatePathString() {
g.DataStr = g.Data.ToSVG()
}
// ApplyTransform applies the given 2D transform to the geometry of this node
// each node must define this for itself
func (g *Path) ApplyTransform(sv *SVG, xf math32.Matrix2) {
g.Data.Transform(xf)
g.GradientApplyTransform(sv, xf)
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package svg
import (
"fmt"
"image"
"image/color"
"strings"
"sync"
"cogentcore.org/core/colors/gradient"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint"
"cogentcore.org/core/paint/render"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/sides"
)
// Pattern is an SVG pattern element: the fill or stroke of the elements
// that refer to it (as fill="url(#name)") is its children, rendered in a
// tile that repeats. It is not rendered itself.
type Pattern struct {
NodeBase
// ViewBox is the view box of the pattern, if any.
ViewBox ViewBox
}
func (g *Pattern) SVGName() string { return "pattern" }
func (g *Pattern) EnforceSVGName() bool { return false }
func (g *Pattern) Render(sv *SVG) {} // only for the elements that refer to it
// maxPatternTile is the maximum width and height of the image of the tile
// of a pattern, in pixels.
const maxPatternTile = 2048
// attr returns the value of the given attribute (property) of the pattern
// or of the patterns that it refers to (with href), and whether it has it.
func (g *Pattern) attr(sv *SVG, name string) (string, bool) {
// (p is declared on its own, as goscript gives it the type of g in
// the loop, which is narrowed to a non-nil pattern in TypeScript)
p := g
for n := 0; p != nil && n < 10; n++ {
if v, ok := p.Properties[name]; ok {
return strings.TrimSpace(fmt.Sprint(v)), true
}
p = p.ref(sv)
}
return "", false
}
// ref returns the pattern that the pattern refers to with href, if any.
func (g *Pattern) ref(sv *SVG) *Pattern {
href, ok := g.Properties["href"]
if !ok {
return nil
}
name := strings.TrimPrefix(strings.TrimSpace(fmt.Sprint(href)), "#")
p, _ := sv.findByName(name).(*Pattern)
if p == g {
return nil
}
return p
}
// content returns the pattern with the children of the pattern (its own
// or of the patterns that it refers to), and the one with its view box.
func (g *Pattern) content(sv *SVG) (*Pattern, *Pattern) {
// (not in the init of the loop: see attr)
var kids, vb *Pattern
p := g
for n := 0; p != nil && n < 10; n++ {
if kids == nil && len(p.Children) > 0 {
kids = p
}
if vb == nil && p.ViewBox.Size.X > 0 && p.ViewBox.Size.Y > 0 {
vb = p
}
p = p.ref(sv)
}
return kids, vb
}
// length returns the value of the given attribute of the pattern as a
// length: in the units of the given size for objectBoundingBox units (a
// fraction or percent), or in user units (or percent of the given size).
func (g *Pattern) length(sv *SVG, name string, size float32) float32 {
v, ok := g.attr(sv, name)
if !ok {
return 0
}
if pct, ok := strings.CutSuffix(v, "%"); ok {
f, _ := math32.ParseFloat32(pct)
return f / 100 * size
}
f, _ := math32.ParseFloat32(strings.TrimSuffix(v, "px"))
return f
}
// preparePatterns makes the pattern fill and stroke of the node, if any,
// ready to render, for the node, with the given transform from the user
// space of the current context to that of the node.
func (g *NodeBase) preparePatterns(sv *SVG, xf math32.Matrix2) {
for _, clr := range []*image.Image{&g.Paint.Fill.Color, &g.Paint.Stroke.Color} {
pf, ok := (*clr).(*patternFill)
if !ok {
continue
}
npf := &patternFill{pattern: pf.pattern}
npf.prepare(sv, g, xf)
*clr = npf // for the node only
}
}
// patternFill is the fill (or stroke) of an element with a [Pattern]: the
// image of its tile, repeated. It is a [gradient.Gradient] so that the
// renderers update it (with [patternFill.Update]) before they render it.
type patternFill struct {
base gradient.Base
pattern *Pattern
// items render the tile, in the pixels of its image.
items render.Render
// size is the size of the image of the tile, in pixels.
size image.Point
// toTile transforms the pixels where the pattern is rendered to the
// pixels of the image of the tile (before they wrap around).
toTile math32.Matrix2
once sync.Once
tile *image.RGBA
opacity float32
}
// prepare renders the items of the tile of the pattern for the given
// node, with the given transform from the user space of the current
// context to that of the node.
func (pf *patternFill) prepare(sv *SVG, target *NodeBase, xf math32.Matrix2) {
g := pf.pattern
pf.opacity = 1
bb := sv.userBBox(target)
bsz := bb.Size()
obb := true // patternUnits
if u, ok := g.attr(sv, "patternUnits"); ok {
obb = u != "userSpaceOnUse"
}
var tile math32.Box2
if obb {
tile.Min.Set(bb.Min.X+g.length(sv, "x", 1)*bsz.X, bb.Min.Y+g.length(sv, "y", 1)*bsz.Y)
tile.Max = tile.Min.Add(math32.Vec2(g.length(sv, "width", 1)*bsz.X, g.length(sv, "height", 1)*bsz.Y))
} else {
vp := sv.Root.ViewBox.Size
tile.Min.Set(g.length(sv, "x", vp.X), g.length(sv, "y", vp.Y))
tile.Max = tile.Min.Add(math32.Vec2(g.length(sv, "width", vp.X), g.length(sv, "height", vp.Y)))
}
tsz := tile.Size()
if tsz.X <= 0 || tsz.Y <= 0 {
return // nothing is rendered
}
ptf := math32.Identity2()
if v, ok := g.attr(sv, "patternTransform"); ok {
ptf.SetString(v)
}
// from pattern space to the pixels where the node renders
toPixels := sv.painter.Context().Cumulative.Mul(xf).Mul(ptf)
sx := math32.Vec2(toPixels.XX, toPixels.YX).Length()
sy := math32.Vec2(toPixels.XY, toPixels.YY).Length()
pf.size = image.Pt(int(math32.Ceil(tsz.X*sx)), int(math32.Ceil(tsz.Y*sy)))
pf.size.X = min(max(pf.size.X, 1), maxPatternTile)
pf.size.Y = min(max(pf.size.Y, 1), maxPatternTile)
scale := math32.Vec2(float32(pf.size.X)/tsz.X, float32(pf.size.Y)/tsz.Y)
// tile pixels from pattern space
tileXf := math32.Scale2D(scale.X, scale.Y).Translate(-tile.Min.X, -tile.Min.Y)
pf.toTile = tileXf.Mul(toPixels.Inverse())
// the content, from its units (or view box) to the tile
contentXf := math32.Translate2D(tile.Min.X, tile.Min.Y)
kids, vbp := g.content(sv)
if vbp != nil {
vb := vbp.ViewBox
_, trans, vscale := vb.Transform(tsz)
trans.SetSub(vb.Min)
contentXf = contentXf.Mul(math32.Scale2D(vscale.X, vscale.Y).Translate(trans.X, trans.Y))
} else if u, _ := g.attr(sv, "patternContentUnits"); u == "objectBoundingBox" {
contentXf = math32.Translate2D(tile.Min.X, tile.Min.Y).Scale(bsz.X, bsz.Y)
}
if kids == nil {
return
}
pc := sv.painter
cur := pc.Context().Cumulative
pf.items = pc.RenderSeparately(func() {
sty := styles.NewPaint()
sty.UnitContext = pc.Context().Style.UnitContext
sty.Transform = cur.Inverse().Mul(tileXf.Mul(contentXf))
pc.PushContext(sty, render.NewBounds(0, 0, float32(pf.size.X), float32(pf.size.Y), sides.Floats{}))
for _, k := range kids.Children {
nb := k.(Node).AsNodeBase()
def := nb.isDef
nb.isDef = true // rendered whatever their visible box
k.(Node).Render(sv)
nb.isDef = def
}
pc.PopContext()
})
}
func (pf *patternFill) AsBase() *gradient.Base { return &pf.base }
// CopyGradient returns a copy of the pattern fill, which shares its tile.
func (pf *patternFill) CopyGradient() gradient.Gradient {
pf.once.Do(func() { pf.renderTile() })
cp := &patternFill{pattern: pf.pattern, items: pf.items, size: pf.size, toTile: pf.toTile, tile: pf.tile, opacity: pf.opacity}
cp.once.Do(func() {}) // the tile is shared
cp.base.ApplyFuncs = pf.base.ApplyFuncs.Clone()
return cp
}
// Update sets the opacity of the pattern, before it is rendered.
func (pf *patternFill) Update(opacity float32, box math32.Box2, objTransform math32.Matrix2) {
pf.opacity = opacity
}
func (pf *patternFill) ColorModel() color.Model { return color.RGBAModel }
func (pf *patternFill) Bounds() image.Rectangle {
return image.Rect(-1e9, -1e9, 1e9, 1e9)
}
// At returns the color of the pattern at the given pixel: of the pixel
// of the tile that it is at.
func (pf *patternFill) At(x, y int) color.Color {
pf.once.Do(func() { pf.renderTile() })
if pf.tile == nil {
return color.RGBA{}
}
p := pf.toTile.MulPoint(math32.Vec2(float32(x)+0.5, float32(y)+0.5))
tx := int(math32.Floor(p.X)) % pf.size.X
ty := int(math32.Floor(p.Y)) % pf.size.Y
if tx < 0 {
tx += pf.size.X
}
if ty < 0 {
ty += pf.size.Y
}
c := pf.tile.RGBAAt(tx, ty)
if pf.opacity < 1 {
o := pf.opacity
c = color.RGBA{uint8(float32(c.R) * o), uint8(float32(c.G) * o), uint8(float32(c.B) * o), uint8(float32(c.A) * o)}
}
if len(pf.base.ApplyFuncs) > 0 {
return pf.base.ApplyFuncs.Apply(c)
}
return c
}
// renderTile renders the image of the tile of the pattern.
func (pf *patternFill) renderTile() {
if len(pf.items) == 0 || paint.NewImageRenderer == nil {
return
}
img := paint.NewImageRenderer(math32.FromPoint(pf.size)).Render(pf.items).Image()
pf.tile, _ = img.(*image.RGBA)
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package svg
import (
"cogentcore.org/core/math32"
)
// Polygon is a SVG polygon
type Polygon struct {
Polyline
}
func (g *Polygon) SVGName() string { return "polygon" }
func (g *Polygon) Render(sv *SVG) {
sz := len(g.Points)
if sz < 2 || !g.IsVisible(sv) {
return
}
pc := g.Painter(sv)
if g.pushLayer(sv) {
defer pc.PopContext()
}
pc.Polygon(g.Points...)
pc.Draw()
g.PushContext(sv)
if mrk := sv.MarkerByName(g, "marker-start"); mrk != nil {
pt := g.Points[0]
ptn := g.Points[1]
ang := math32.Atan2(ptn.Y-pt.Y, ptn.X-pt.X)
mrk.RenderMarkerStart(sv, pt, ang, g.Paint.Stroke.Width.Dots)
}
if mrk := sv.MarkerByName(g, "marker-end"); mrk != nil {
pt := g.Points[sz-1]
ptp := g.Points[sz-2]
ang := math32.Atan2(pt.Y-ptp.Y, pt.X-ptp.X)
mrk.RenderMarker(sv, pt, ang, g.Paint.Stroke.Width.Dots)
}
if mrk := sv.MarkerByName(g, "marker-mid"); mrk != nil {
for i := 1; i < sz-1; i++ {
pt := g.Points[i]
ptp := g.Points[i-1]
ptn := g.Points[i+1]
ang := 0.5 * (math32.Atan2(pt.Y-ptp.Y, pt.X-ptp.X) + math32.Atan2(ptn.Y-pt.Y, ptn.X-pt.X))
mrk.RenderMarker(sv, pt, ang, g.Paint.Stroke.Width.Dots)
}
}
pc.PopContext()
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package svg
import (
"cogentcore.org/core/math32"
)
// Polyline is a SVG multi-line shape
type Polyline struct {
NodeBase
// the coordinates to draw -- does a moveto on the first, then lineto for all the rest
Points []math32.Vector2 `xml:"points"`
}
func (g *Polyline) SVGName() string { return "polyline" }
func (g *Polyline) SetPos(pos math32.Vector2) {
// todo: set offset relative to bbox
}
func (g *Polyline) SetSize(sz math32.Vector2) {
// todo: scale bbox
}
func (g *Polyline) LocalBBox(sv *SVG) math32.Box2 {
bb := math32.B2Empty()
for _, pt := range g.Points {
bb.ExpandByPoint(pt)
}
hlw := 0.5 * g.LocalLineWidth()
bb.Min.SetSubScalar(hlw)
bb.Max.SetAddScalar(hlw)
return bb
}
func (g *Polyline) Render(sv *SVG) {
sz := len(g.Points)
if sz < 2 || !g.IsVisible(sv) {
return
}
pc := g.Painter(sv)
if g.pushLayer(sv) {
defer pc.PopContext()
}
pc.Polyline(g.Points...)
pc.Draw()
g.PushContext(sv)
if mrk := sv.MarkerByName(g, "marker-start"); mrk != nil {
pt := g.Points[0]
ptn := g.Points[1]
ang := math32.Atan2(ptn.Y-pt.Y, ptn.X-pt.X)
mrk.RenderMarkerStart(sv, pt, ang, g.Paint.Stroke.Width.Dots)
}
if mrk := sv.MarkerByName(g, "marker-end"); mrk != nil {
pt := g.Points[sz-1]
ptp := g.Points[sz-2]
ang := math32.Atan2(pt.Y-ptp.Y, pt.X-ptp.X)
mrk.RenderMarker(sv, pt, ang, g.Paint.Stroke.Width.Dots)
}
if mrk := sv.MarkerByName(g, "marker-mid"); mrk != nil {
for i := 1; i < sz-1; i++ {
pt := g.Points[i]
ptp := g.Points[i-1]
ptn := g.Points[i+1]
ang := 0.5 * (math32.Atan2(pt.Y-ptp.Y, pt.X-ptp.X) + math32.Atan2(ptn.Y-pt.Y, ptn.X-pt.X))
mrk.RenderMarker(sv, pt, ang, g.Paint.Stroke.Width.Dots)
}
}
pc.PopContext()
}
// ApplyTransform applies the given 2D transform to the geometry of this node
// each node must define this for itself
func (g *Polyline) ApplyTransform(sv *SVG, xf math32.Matrix2) {
rot := xf.ExtractRot()
if rot != 0 {
g.Paint.Transform.SetMul(xf)
g.SetTransformProperty()
} else {
for i, p := range g.Points {
p = xf.MulPoint(p)
g.Points[i] = p
}
g.GradientApplyTransform(sv, xf)
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package svg
import (
"cogentcore.org/core/math32"
"cogentcore.org/core/styles/sides"
)
// Rect is a SVG rectangle, optionally with rounded corners
type Rect struct {
NodeBase
// position of the top-left of the rectangle
Pos math32.Vector2 `svg:"x,y"`
// size of the rectangle
Size math32.Vector2 `svg:"width,height"`
// radii for curved corners. only rx is used for now.
Radius math32.Vector2 `svg:"rx,ry"`
}
func (g *Rect) SVGName() string { return "rect" }
func (g *Rect) Init() {
g.NodeBase.Init()
g.Size.Set(1, 1)
}
func (g *Rect) SetNodePos(pos math32.Vector2) {
g.Pos = pos
}
func (g *Rect) SetNodeSize(sz math32.Vector2) {
g.Size = sz
}
func (g *Rect) LocalBBox(sv *SVG) math32.Box2 {
bb := math32.Box2{}
hlw := 0.5 * g.LocalLineWidth()
bb.Min = g.Pos.SubScalar(hlw)
bb.Max = g.Pos.Add(g.Size).AddScalar(hlw)
return bb
}
func (g *Rect) Render(sv *SVG) {
if !g.IsVisible(sv) {
return
}
pc := g.Painter(sv)
if g.pushLayer(sv) {
defer pc.PopContext()
}
if g.Radius.X == 0 && g.Radius.Y == 0 {
pc.Rectangle(g.Pos.X, g.Pos.Y, g.Size.X, g.Size.Y)
} else {
// todo: only supports 1 radius right now -- easy to add another
// the Painter also support different radii for each corner but not rx, ry at this point,
// although that would be easy to add TODO:
pc.RoundedRectangleSides(g.Pos.X, g.Pos.Y, g.Size.X, g.Size.Y, sides.NewFloats(g.Radius.X))
}
pc.Draw()
}
// ApplyTransform applies the given 2D transform to the geometry of this node
// each node must define this for itself
func (g *Rect) ApplyTransform(sv *SVG, xf math32.Matrix2) {
rot := xf.ExtractRot()
if rot != 0 {
g.Paint.Transform.SetMul(xf)
g.SetTransformProperty()
} else {
g.Pos = xf.MulPoint(g.Pos)
g.Size = xf.MulVector(g.Size)
g.GradientApplyTransform(sv, xf)
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package svg
//go:generate core generate
import (
"bytes"
"image"
"image/color"
"os"
"strings"
"sync"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/iox/imagex"
"cogentcore.org/core/colors"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint"
"cogentcore.org/core/paint/render"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/sides"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/shaped"
)
var (
// svgShaper is a shared text shaper.
svgShaper shaped.Shaper
// mutex for initializing the svgShaper.
shaperMu sync.Mutex
)
// SVGToImage generates an image from given svg source,
// with given width and height size.
func SVGToImage(svg []byte, size math32.Vector2) (image.Image, error) {
sv := NewSVG(size)
err := sv.ReadXML(bytes.NewBuffer(svg))
return sv.RenderImage(), err
}
// SVG represents a structured SVG vector graphics drawing,
// with nodes allocated for each element.
// It renders to a [paint.Painter] via the Render method.
// Any supported representation can then be rendered from that.
type SVG struct {
// Name is the name of the SVG -- e.g., the filename if loaded
Name string
// the title of the svg
Title string `xml:"title"`
// the description of the svg
Desc string `xml:"desc"`
// Background is the image/color to fill the background with,
// if any.
Background image.Image
// DefaultFill can be set to provide a default Fill color for the root node.
DefaultFill image.Image
// Color is the current color (currentColor) of the root of the SVG,
// which its elements inherit, unless they set it with the color
// property: as the CSS color of the element of a page that it is in.
// It is black if nil.
Color image.Image
// Size is size of image, Pos is offset within any parent viewport.
// The bounding boxes within the scene _include_ the Pos offset already.
Geom math32.Geom2DInt
// physical width of the drawing, e.g., when printed.
// Does not affect rendering, metadata.
PhysicalWidth units.Value
// physical height of the drawing, e.g., when printed.
// Does not affect rendering, metadata.
PhysicalHeight units.Value
// InvertY, when applying the ViewBox transform, also flip the Y axis so that
// the smallest Y value is at the bottom of the SVG box,
// instead of being at the top as it is by default.
InvertY bool
// Translate specifies a translation to apply beyond what is specified in the SVG,
// and its ViewBox transform, in top-level rendering units (dots, pixels).
Translate math32.Vector2
// Scale specifies a zoom scale factor to apply beyond what is specified in the SVG,
// and its ViewBox transform. See [SVG.ZoomAt] for convenient zooming method.
Scale float32
// painter is the current painter being used, which is only valid during rendering.
painter *paint.Painter
// TextShaper for shaping text. Can set to a shared external one,
// or else the shared svgShaper is used.
TextShaper shaped.Shaper
// all defs defined elements go here (gradients, symbols, etc)
Defs *Group
// Root is the root of the svg tree, which has the top-level viewbox and styles.
Root *Root
// GroupFilter is used to filter group names, skipping any that don't contain
// this string, if non-empty. This is needed e.g., for reading SVG font files
// which pack many elements into the same file.
GroupFilter string
// groupFilterSkip is whether to skip the current group based on GroupFilter.
groupFilterSkip bool
// groupFilterSkipName is name of group currently skipping.
groupFilterSkipName string
// map of def names to index. uses starting index to find element.
// always updated after each search.
DefIndexes map[string]int `display:"-" json:"-" xml:"-"`
// map of unique numeric ids for all elements.
// Used for allocating new unique id numbers, appended to end of elements.
// See NewUniqueID, GatherIDs
UniqueIDs map[int]struct{} `display:"-" json:"-" xml:"-"`
// mutex for protecting rendering
sync.Mutex
}
// NewSVG creates a SVG with the given viewport size,
// which is typically in pixel dots.
func NewSVG(size math32.Vector2) *SVG {
sv := &SVG{}
sv.Init(size)
return sv
}
// Init initializes the SVG with given viewport size,
// which is typically in pixel dots.
func (sv *SVG) Init(size math32.Vector2) {
sv.Geom.Size = size.ToPointCeil()
sv.Scale = 1
sv.Root = NewRoot()
sv.Root.SetName("svg")
sv.Defs = NewGroup()
sv.Defs.SetName("defs")
sv.SetUnitContext(&sv.Root.Paint)
}
// SetSize updates the viewport size.
func (sv *SVG) SetSize(size math32.Vector2) {
sv.Geom.Size = size.ToPointCeil()
sv.SetUnitContext(&sv.Root.Paint)
}
// DeleteAll deletes any existing elements in this svg
func (sv *SVG) DeleteAll() {
if sv.Root == nil || sv.Root.This == nil {
return
}
sv.Root.Paint.Defaults()
sv.Root.DeleteChildren()
sv.Defs.DeleteChildren()
}
// Base returns the current Color activated in the context.
// Color has support for special color names that are relative to
// this current color.
func (sv *SVG) Base() color.RGBA {
return colors.AsRGBA(colors.ToUniform(sv.Background))
}
// ImageByURL finds a Node by an element name (URL-like path), and
// attempts to convert it to an [image.Image].
// Used for color styling based on url() value.
func (sv *SVG) ImageByURL(url string) image.Image {
// TODO(kai): support taking snapshot of element as image in SVG.ImageByURL
if sv == nil {
return nil
}
val := url[4:]
val = strings.TrimPrefix(strings.TrimSuffix(val, ")"), "#")
def := sv.FindDefByName(val)
if def != nil {
if grad, ok := def.(*Gradient); ok {
return grad.Grad
}
}
ne := sv.findByName(val)
switch x := ne.(type) {
case *Gradient:
return x.Grad
case *Pattern:
return &patternFill{pattern: x}
}
return nil
}
func (sv *SVG) Style() {
// set isDef
for n := range sv.Defs.All() {
sn := n.(Node)
sn.AsNodeBase().isDef = true
sn.AsNodeBase().Style(sv)
}
sv.Root.Paint.Defaults()
if sv.DefaultFill != nil {
// TODO(kai): consider handling non-uniform colors here
sv.Root.SetColorProperties("fill", colors.AsHex(colors.ToUniform(sv.DefaultFill)))
}
sv.SetUnitContext(&sv.Root.Paint)
for k := range sv.Root.All() {
sn := k.(Node)
sn.AsNodeBase().Style(sv)
}
}
// useSharedShaper sets the TextShaper to the shared svgShaper, returning
// a function that sets it back to nil.
func (sv *SVG) useSharedShaper() func() {
shaperMu.Lock()
if svgShaper == nil {
svgShaper = shaped.NewShaper()
}
sv.TextShaper = svgShaper
shaperMu.Unlock()
return func() {
sv.TextShaper = nil
}
}
// Render renders the SVG to given Painter, which can be nil
// to have a new one created. Returns the painter used.
// Set the TextShaper prior to calling to use an existing one,
// otherwise it will use shared svgShaper.
func (sv *SVG) Render(pc *paint.Painter) *paint.Painter {
sv.Lock()
defer sv.Unlock()
if pc != nil {
sv.painter = pc
} else {
sv.UpdateSize()
sv.painter = paint.NewPainter(math32.FromPoint(sv.Geom.Size))
pc = sv.painter
}
if sv.TextShaper == nil {
defer sv.useSharedShaper()()
}
sv.Style()
sv.UpdateBBoxes()
if sv.Background != nil {
sv.FillViewport()
}
sv.Root.Render(sv)
sv.painter = nil
return pc
}
// RenderImage renders the SVG to an image and returns it.
func (sv *SVG) RenderImage() image.Image {
return paint.RenderToImage(sv.Render(nil))
}
// SaveImage renders the SVG to an image and saves it to given filename,
// using the filename extension to determine the file type.
func (sv *SVG) SaveImage(fname string) error {
pos := sv.Geom.Pos
sv.Geom.Pos = image.Point{}
err := imagex.Save(sv.RenderImage(), fname)
sv.Geom.Pos = pos
return err
}
// SaveImageSize renders the SVG to an image and saves it to given filename,
// using the filename extension to determine the file type.
// Specify either width or height of resulting image, or nothing for
// current physical size as set.
func (sv *SVG) SaveImageSize(fname string, width, height float32) error {
sz := sv.Geom
sv.Geom.Pos = image.Point{}
sv.Geom.Size.X = int(width)
sv.Geom.Size.Y = int(height)
err := imagex.Save(sv.RenderImage(), fname)
sv.Geom = sz
return err
}
// SavePDF renders the SVG to a PDF and saves it to given filename.
func (sv *SVG) SavePDF(fname string) error {
pos := sv.Geom.Pos
sv.Geom.Pos = image.Point{}
rend := sv.Render(nil).RenderDone()
ctx := units.NewContext()
vsz := math32.FromPoint(sv.Geom.Size)
pd := paint.NewPDFRenderer(vsz, ctx)
pd.Render(rend)
err := os.WriteFile(fname, pd.Source(), 0666)
sv.Geom.Pos = pos
return err
}
// CloneSVG returns a copy of this SVG, with given size,
// by writing and reading the XML source.
func (sv *SVG) CloneSVG(size math32.Vector2) *SVG {
var b bytes.Buffer
errors.Log(sv.WriteXML(&b, NoIndentXML))
nsv := NewSVG(size)
errors.Log(nsv.ReadXML(&b))
return nsv
}
func (sv *SVG) FillViewport() {
sty := styles.NewPaint() // has no transform
pc := &paint.Painter{State: sv.painter.State, Paint: sty}
pc.FillBox(math32.Vector2{}, math32.FromPoint(sv.Geom.Size), sv.Background)
}
// UpdateBBoxes updates the bounding boxes for all nodes
// using current transform settings.
func (sv *SVG) UpdateBBoxes() {
if sv.TextShaper == nil { // text needs a shaper for its bounding box
defer sv.useSharedShaper()()
}
sv.setRootTransform()
sv.Root.BBoxes(sv, math32.Identity2())
}
//////// Root
// Root represents the root of an SVG tree.
type Root struct {
Group
// ViewBox defines the coordinate system for the drawing.
// These units are mapped into the screen space allocated
// for the SVG during rendering.
ViewBox ViewBox
}
func (g *Root) SVGName() string { return "svg" }
func (g *Root) EnforceSVGName() bool { return false }
// SetUnitContext sets the unit context based on size of viewport, element,
// and parent element (from bbox) and then caches everything out in terms of raw pixel
// dots for rendering -- call at start of render
func (sv *SVG) SetUnitContext(pc *styles.Paint) {
pc.UnitContext.Defaults()
pc.UnitContext.DPI = 96 // paint (SVG) context is always 96 = 1to1
wd := float32(sv.Geom.Size.X)
ht := float32(sv.Geom.Size.Y)
pc.UnitContext.SetSizes(wd, ht, wd, ht, wd, ht) // self, element, parent -- all same
pc.ToDots()
sv.ToDots(&pc.UnitContext)
}
func (sv *SVG) ToDots(uc *units.Context) {
sv.PhysicalWidth.ToDots(uc)
sv.PhysicalHeight.ToDots(uc)
}
func (g *Root) Render(sv *SVG) {
pc := g.Painter(sv)
pc.PushContext(&g.Paint, render.NewBoundsRect(sv.Geom.Bounds(), sides.NewFloats()))
g.RenderChildren(sv)
pc.PopContext()
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package svg
import (
"strings"
"unicode"
"cogentcore.org/core/colors"
"cogentcore.org/core/math32"
"cogentcore.org/core/text/htmltext"
"cogentcore.org/core/text/shaped"
"cogentcore.org/core/text/text"
)
// todo: needs some work to get up to spec:
// https://developer.mozilla.org/en-US/docs/Web/SVG/Reference/Element/tspan
// dx, dy need to be specifiable as relative offsets from parent text, not just glyph
// relative offsets. Also, the literal parsing of example in link of an inline <tspan>
// element within a broader text shows that a different kind of parsing
// structure is required.
// Text renders SVG text, handling both text and tspan elements.
// tspan is nested under a parent text, where text has empty Text string.
// There is no line wrapping on SVG Text: every span is a separate line.
type Text struct {
NodeBase
// position of the left, baseline of the text
Pos math32.Vector2 `svg:"x,y"`
// text string to render
Text string `xml:"text"`
// render version of text
TextShaped *shaped.Lines `xml:"-" json:"-" copier:"-"`
// character positions along X axis, if specified
CharPosX []float32
// character positions along Y axis, if specified
CharPosY []float32
// character delta-positions along X axis, if specified
CharPosDX []float32
// character delta-positions along Y axis, if specified
CharPosDY []float32
// character rotations, if specified
CharRots []float32
// author's computed text length, if specified -- we attempt to match
TextLength float32
// in attempting to match TextLength, should we adjust glyphs in addition to spacing?
AdjustGlyphs bool
// hasX and hasY are whether the x and y of the text are specified,
// which for a span (tspan) is an absolute position (absPos), which
// otherwise follows the span before it.
hasX, hasY bool
// absPos is the absolute position of a span, for hasX and hasY.
absPos math32.Vector2
// laidOut is whether the span is laid out by its parent text
// (which aligns its spans by its text-anchor).
laidOut bool
}
// collapseSpace returns the given text with its runs of white space
// collapsed to a single space, as SVG text is by default.
func collapseSpace(s string) string {
var sb strings.Builder
space := false
for _, r := range s {
if unicode.IsSpace(r) {
space = true
continue
}
if space {
sb.WriteByte(' ')
space = false
}
sb.WriteRune(r)
}
if space {
sb.WriteByte(' ')
}
return sb.String()
}
// trimSpans trims the space at the start and end of the text (of the
// first and last of its spans, if it has them), as SVG text does.
func (g *Text) trimSpans() {
if g.NumChildren() == 0 {
g.Text = strings.TrimSpace(g.Text)
return
}
if first, ok := g.Child(0).(*Text); ok {
first.Text = strings.TrimLeft(first.Text, " ")
}
if last, ok := g.Child(g.NumChildren() - 1).(*Text); ok {
last.Text = strings.TrimRight(last.Text, " ")
}
}
// layoutSpans positions the spans of a parent text: each after the one
// before it (from the position of the text), unless it has an absolute
// position, with its dx and dy offsets, and the spans of each chunk (from
// an absolute position) aligned as a whole by the text-anchor of the span
// that starts it.
func (g *Text) layoutSpans(sv *SVG) {
pen := g.Pos
var chunk []*Text
chunkStart := pen.X
flush := func() {
if len(chunk) == 0 {
return
}
w := pen.X - chunkStart
shift := float32(0)
switch chunk[0].Paint.Text.Align { // that of the span that starts the chunk
case text.Center:
shift = -w / 2
case text.End:
shift = -w
}
for _, kt := range chunk {
kt.Pos.X += shift
}
chunk = chunk[:0]
}
for _, k := range g.Children {
kt, ok := k.(*Text)
if !ok {
continue
}
if kt.hasX {
flush()
pen.X = kt.absPos.X
chunkStart = pen.X
}
if kt.hasY {
pen.Y = kt.absPos.Y
}
if len(kt.CharPosDX) > 0 {
pen.X += kt.CharPosDX[0]
}
if len(kt.CharPosDY) > 0 {
pen.Y += kt.CharPosDY[0]
}
kt.Pos = pen
kt.laidOut = true
kt.LocalBBox(sv)
if kt.TextShaped != nil {
pen.X += kt.TextShaped.Bounds.Size().X
}
chunk = append(chunk, kt)
}
flush()
}
func (g *Text) SVGName() string {
if len(g.Text) == 0 {
return "text"
}
return "tspan"
}
// IsParText returns true if this element serves as a parent text element
// to tspan elements within it. This is true if NumChildren() > 0 and
// Text == ""
func (g *Text) IsParText() bool {
return g.NumChildren() > 0 && g.Text == ""
}
func (g *Text) SetNodePos(pos math32.Vector2) {
g.Pos = pos
for _, kii := range g.Children {
kt := kii.(*Text)
kt.Pos = g.Paint.Transform.MulPoint(pos)
}
}
// LocalBBox does full text layout, but no transforms. The box of a text
// with nothing to show (empty, or only white space, as between spans) is
// empty, at its position, not at the origin.
func (g *Text) LocalBBox(sv *SVG) math32.Box2 {
if g.Text == "" {
return math32.Box2{Min: g.Pos, Max: g.Pos}
}
pc := &g.Paint
fs := pc.Font
if pc.Fill.Color != nil {
fs.SetFillColor(colors.ApplyOpacity(colors.ToUniform(pc.Fill.Color), pc.Fill.Opacity))
}
tx, _ := htmltext.HTMLToRich([]byte(g.Text), &fs, nil)
// fmt.Println(tx)
sz := math32.Vec2(10000, 10000) // no wrapping!!
g.TextShaped = sv.TextShaper.WrapLines(tx, &fs, &pc.Text, sz)
if len(g.TextShaped.Lines) > 0 {
baseOff := g.TextShaped.Lines[0].Offset
g.TextShaped.StartAtBaseline() // remove top-left offset
return g.TextShaped.Bounds.Translate(g.Pos.Sub(baseOff))
}
return math32.Box2{Min: g.Pos, Max: g.Pos}
// fmt.Println("baseoff:", baseOff)
// fmt.Println(pc.Text.FontSize, pc.Text.FontSize.Dots)
// todo: align styling only affects multi-line text and is about how tspan is arranged within
// the overall text block.
/*
if len(g.CharPosX) > 0 {
mx := min(len(g.CharPosX), len(sr.Render))
for i := 0; i < mx; i++ {
sr.Render[i].RelPos.X = g.CharPosX[i]
}
}
if len(g.CharPosY) > 0 {
mx := min(len(g.CharPosY), len(sr.Render))
for i := 0; i < mx; i++ {
sr.Render[i].RelPos.Y = g.CharPosY[i]
}
}
if len(g.CharPosDX) > 0 {
mx := min(len(g.CharPosDX), len(sr.Render))
for i := 0; i < mx; i++ {
if i > 0 {
sr.Render[i].RelPos.X = sr.Render[i-1].RelPos.X + g.CharPosDX[i]
} else {
sr.Render[i].RelPos.X = g.CharPosDX[i] // todo: not sure this is right
}
}
}
if len(g.CharPosDY) > 0 {
mx := min(len(g.CharPosDY), len(sr.Render))
for i := 0; i < mx; i++ {
if i > 0 {
sr.Render[i].RelPos.Y = sr.Render[i-1].RelPos.Y + g.CharPosDY[i]
} else {
sr.Render[i].RelPos.Y = g.CharPosDY[i] // todo: not sure this is right
}
}
}
*/
// todo: TextLength, AdjustGlyphs -- also svg2 at least supports word wrapping!
// g.TextShaped.UpdateBBox()
}
func (g *Text) BBoxes(sv *SVG, parTransform math32.Matrix2) {
if g.IsParText() {
g.layoutSpans(sv)
g.spanBBoxes(sv, parTransform)
return
}
xf := parTransform.Mul(g.Paint.Transform)
ni := g.This.(Node)
lbb := ni.LocalBBox(sv)
g.BBox = lbb.MulMatrix2(xf)
g.VisBBox = sv.Geom.Box2().Intersect(g.BBox)
}
// spanBBoxes sets the boxes of the spans of a parent text, and its box
// from those of the spans that have text: a span without text (as the
// white space between spans, trimmed) has an empty box at the origin,
// which is not part of the text.
func (g *Text) spanBBoxes(sv *SVG, parTransform math32.Matrix2) {
xf := parTransform.Mul(g.Paint.Transform)
var bb math32.Box2
has := false
for _, kid := range g.Children {
ni := kid.(Node)
ni.BBoxes(sv, xf)
if kt, ok := kid.(*Text); ok && kt.Text == "" && !kt.HasChildren() {
continue
}
nb := ni.AsNodeBase()
if !has {
bb, has = nb.BBox, true
} else {
bb = bb.Union(nb.BBox)
}
}
g.BBox = bb
g.VisBBox = sv.Geom.Box2().Intersect(g.BBox)
}
func (g *Text) Render(sv *SVG) {
if g.IsParText() {
if !g.PushContext(sv) {
return
}
g.setLayer(sv, math32.Identity2())
g.preparePatterns(sv, math32.Identity2())
pc := g.Painter(sv)
g.RenderChildren(sv)
pc.PopContext()
return
}
if !g.IsVisible(sv) {
return
}
if len(g.Text) > 0 {
g.RenderText(sv)
}
}
func (g *Text) RenderText(sv *SVG) {
// note: transform is managed entirely in the render side function!
pc := g.Painter(sv)
pos := g.Pos
bsz := g.TextShaped.Bounds.Size()
if g.laidOut { // aligned by the parent text
} else if pc.Text.Align == text.Center {
pos.X -= bsz.X * .5
} else if pc.Text.Align == text.End {
pos.X -= bsz.X
}
pc.DrawText(g.TextShaped, pos)
}
// ApplyTransform applies the given 2D transform to the geometry of this node
// each node must define this for itself
func (g *Text) ApplyTransform(sv *SVG, xf math32.Matrix2) {
rot := xf.ExtractRot()
scx, scy := xf.ExtractScale()
if rot != 0 || scx != 1 || scy != 1 || g.IsParText() {
// note: par text requires transform b/c not saving children pos
g.Paint.Transform.SetMul(xf)
g.SetTransformProperty()
} else {
g.Pos = xf.MulPoint(g.Pos)
g.GradientApplyTransform(sv, xf)
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package svg
import (
"fmt"
"log"
"math/rand"
"slices"
"strconv"
"strings"
"unicode"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/base/slicesx"
"cogentcore.org/core/tree"
)
//////// Naming elements with unique id's
// SplitNameIDDig splits name into numerical end part and preceding name,
// based on string of digits from end of name.
// If Id == 0 then it was not specified or didn't parse.
// SVG object names are element names + numerical id
func SplitNameIDDig(nm string) (string, int) {
sz := len(nm)
for i := sz - 1; i >= 0; i-- {
c := rune(nm[i])
if !unicode.IsDigit(c) {
if i == sz-1 {
return nm, 0
}
n := nm[:i+1]
id, _ := strconv.Atoi(nm[i+1:])
return n, id
}
}
return nm, 0
}
// SplitNameID splits name after the element name (e.g., 'rect')
// returning true if it starts with element name,
// and numerical id part after that element.
// if numerical id part is 0, then it didn't parse.
// SVG object names are element names + numerical id
func SplitNameID(elnm, nm string) (bool, int) {
if !strings.HasPrefix(nm, elnm) {
// fmt.Printf("not elnm: %s %s\n", nm, elnm)
return false, 0
}
idstr := nm[len(elnm):]
id, _ := strconv.Atoi(idstr)
return true, id
}
// NameID returns the name with given unique id.
// returns plain name if id == 0
func NameID(nm string, id int) string {
if id == 0 {
return nm
}
return fmt.Sprintf("%s%d", nm, id)
}
// GatherIDs gathers all the numeric id suffixes currently in use.
// It automatically renames any that are not unique or empty.
// The ids in use are all registered before any new one is made,
// so that a new id never takes that of a node later in the tree
// (which would then be renamed in turn).
func (sv *SVG) GatherIDs() {
sv.UniqueIDs = make(map[int]struct{})
var renew []Node
for n := range sv.Root.All() {
if nd := n.(Node); !sv.registerID(nd) {
renew = append(renew, nd)
}
}
for _, n := range renew {
sv.newNodeID(n)
}
}
// NodeEnsureUniqueID ensures that the given node has a unique ID.
// Call this on any newly created nodes.
func (sv *SVG) NodeEnsureUniqueID(n Node) {
if !sv.registerID(n) {
sv.newNodeID(n)
}
}
// registerID registers the numeric id of the name of the given node as in
// use, renaming it to its element name and that id as needed, and returns
// false if it needs a new id, because it has none or that of another node.
func (sv *SVG) registerID(n Node) bool {
elnm := n.SVGName()
if elnm == "" {
return true
}
nb := n.AsNodeBase()
elpfx, id := SplitNameID(elnm, nb.Name)
if !elpfx {
if !n.EnforceSVGName() { // if we end in a number, just register it anyway
_, id = SplitNameIDDig(nb.Name)
if id > 0 {
sv.UniqueIDs[id] = struct{}{}
}
return true
}
_, id = SplitNameIDDig(nb.Name)
if id > 0 {
nb.SetName(NameID(elnm, id))
}
}
if _, exists := sv.UniqueIDs[id]; id <= 0 || exists {
return false
}
sv.UniqueIDs[id] = struct{}{}
return true
}
// newNodeID names the given node with its element name and a new unique id.
func (sv *SVG) newNodeID(n Node) {
n.AsNodeBase().SetName(NameID(n.SVGName(), sv.NewUniqueID()))
}
// NewUniqueID returns a new unique numerical id number, for naming an object.
// It is never 0, which is the id of a name without a number. It is random,
// below 1000 for a drawing with less than 100 ids, and otherwise in a range
// that is at least 10 times the number of ids, so most of it is free.
func (sv *SVG) NewUniqueID() int {
if sv.UniqueIDs == nil {
sv.GatherIDs()
}
n := max(999, 10*len(sv.UniqueIDs))
for {
nid := 1 + rand.Intn(n)
if _, has := sv.UniqueIDs[nid]; !has {
sv.UniqueIDs[nid] = struct{}{}
return nid
}
}
}
// FindDefByName finds Defs item by name, using cached indexes for speed.
func (sv *SVG) FindDefByName(defnm string) Node {
if sv.DefIndexes == nil {
sv.DefIndexes = make(map[string]int)
}
idx, has := sv.DefIndexes[defnm]
if !has {
idx = len(sv.Defs.Children) / 2
}
dn := sv.Defs.ChildByName(defnm, idx)
if dn != nil {
sv.DefIndexes[defnm] = dn.AsTree().IndexInParent()
return dn.(Node)
}
delete(sv.DefIndexes, defnm) // not found, so delete from map
return nil
}
func (sv *SVG) FindNamedElement(name string) Node {
name = strings.TrimPrefix(name, "#")
def := sv.FindDefByName(name)
if def != nil {
return def
}
for n := range sv.Root.All() {
if n.AsTree().Name == name {
def = n.(Node)
break
}
}
if def != nil {
return def
}
log.Printf("SVG FindNamedElement: could not find name: %v\n", name)
return nil
}
// NameFromURL returns just the name referred to in a url(#name)
// if it is not a url(#) format then returns empty string.
func NameFromURL(url string) string {
if len(url) < 7 {
return ""
}
if url[:5] != "url(#" {
return ""
}
ref := url[5:]
sz := len(ref)
if ref[sz-1] == ')' {
ref = ref[:sz-1]
}
return ref
}
// NameToURL returns url as: url(#name)
func NameToURL(nm string) string {
return "url(#" + nm + ")"
}
// NodeFindURL finds a url element in the parent SVG of given node.
// Returns nil if not found.
// Works with full 'url(#Name)' string or plain name or "none"
func (sv *SVG) NodeFindURL(n Node, url string) Node {
if url == "none" {
return nil
}
ref := NameFromURL(url)
if ref == "" {
ref = url
}
if ref == "" {
return nil
}
rv := sv.FindNamedElement(ref)
if rv == nil {
log.Printf("svg.NodeFindURL could not find element named: %s for element: %s\n", url, n.AsTree().Path())
}
return rv
}
// NodePropURL returns a url(#name) url from given prop name on node,
// or empty string if none. Returned value is just the 'name' part
// of the url, not the full string.
func NodePropURL(n Node, prop string) string {
fp := n.AsTree().Property(prop)
fs, iss := fp.(string)
if !iss {
return ""
}
return NameFromURL(fs)
}
const SVGRefCountKey = "SVGRefCount"
func IncRefCount(k tree.Node) {
rc := k.AsTree().Property(SVGRefCountKey).(int)
rc++
k.AsTree().SetProperty(SVGRefCountKey, rc)
}
// RemoveOrphanedDefs removes any items from Defs that are not actually referred to
// by anything in the current SVG tree. Returns true if items were removed.
// Does not remove gradients with StopsName = "" with extant stops -- these
// should be removed manually, as they are not automatically generated.
// Also ensures that referenced gradients are before their referencers,
// so that they work correctly on loading.
func (sv *SVG) RemoveOrphanedDefs() bool {
refkey := SVGRefCountKey
for _, k := range sv.Defs.Children {
k.AsTree().SetProperty(refkey, 0)
}
for n := range sv.Root.All() {
nb := n.(Node).AsNodeBase()
pr := nb.Properties
for _, v := range pr {
nm := NameFromURL(reflectx.ToString(v))
if nm == "" {
continue
}
el := sv.FindDefByName(nm)
if el != nil {
IncRefCount(el)
}
}
}
refGr := map[Node]bool{} // ref'd gradients -- move to top!
for n := range sv.Defs.All() {
gr, isgr := n.(*Gradient)
if !isgr {
continue
}
if gr.StopsName != "" {
el := sv.FindDefByName(gr.StopsName)
if el != nil {
IncRefCount(el)
refGr[el] = true
} else {
fmt.Println("stopsname not found:", gr.StopsName)
}
} else {
if gr.Grad != nil && len(gr.Grad.AsBase().Stops) > 0 {
IncRefCount(n) // keep us around
}
}
}
ng := len(refGr)
for gn := range refGr {
idx := gn.AsNodeBase().IndexInParent()
if idx >= ng { // not in first elements
sv.Defs.Children = slicesx.Move(sv.Defs.Children, idx, 0) // move to top
}
}
sz := len(sv.Defs.Children)
del := false
for i := sz - 1; i >= 0; i-- {
n := sv.Defs.Children[i]
rc := n.AsTree().Property(refkey).(int)
if rc == 0 {
// fmt.Printf("Deleting unused item: %s\n", n.AsTree().Name)
sv.Defs.Children = slices.Delete(sv.Defs.Children, i, i+1)
del = true
} else {
n.AsTree().DeleteProperty(refkey)
}
}
return del
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package svg
import (
"log/slog"
"cogentcore.org/core/math32"
"cogentcore.org/core/tree"
)
// Symbol is an SVG symbol element, which is only rendered by the use
// elements that refer to it, scaled from its ViewBox to their size.
type Symbol struct {
Group
// ViewBox is the view box of the symbol, if any.
ViewBox ViewBox
}
func (g *Symbol) SVGName() string { return "symbol" }
func (g *Symbol) EnforceSVGName() bool { return false }
func (g *Symbol) Render(sv *SVG) {} // only through use elements
// pendingUse is a use element, as a group, whose element is resolved
// after the parsing.
type pendingUse struct {
group *Group
link string
x, y, width, height float32
}
// resolveUses adds a copy of the element that each of the given use
// elements refers to, to its group. A symbol is added as a group, with
// the transform from its view box to the size of the use (or its view
// box size, if the use has none).
func (sv *SVG) resolveUses(uses []pendingUse) {
for _, pu := range uses {
itm := sv.findByName(pu.link)
if itm == nil {
slog.Debug("svg: use refers to an element that does not exist", "href", pu.link)
continue
}
if isAncestor(itm, pu.group) { // a use of its own ancestor
continue
}
cln := itm.AsTree().Clone().(Node)
if sym, ok := cln.(*Symbol); ok {
g := NewGroup(pu.group)
g.Properties = sym.Properties
delete(g.Properties, "transform")
if vb := sym.ViewBox; vb.Size.X > 0 && vb.Size.Y > 0 {
size := math32.Vec2(pu.width, pu.height)
if size.X <= 0 {
size.X = vb.Size.X
}
if size.Y <= 0 {
size.Y = vb.Size.Y
}
_, trans, scale := vb.Transform(size)
trans.SetSub(vb.Min)
xf := math32.Scale2D(scale.X, scale.Y).Translate(trans.X, trans.Y)
g.SetProperty("transform", xf.String())
}
for _, k := range sym.Children {
g.AddChild(k)
}
sym.Children = nil
cln = g
} else {
pu.group.AddChild(cln)
}
for n := range cln.AsTree().All() {
if p, ok := n.(*Path); ok {
p.SetData(p.DataStr) // defs don't apply paths
}
}
}
}
// isAncestor returns whether the given node is the given other node or
// one of its ancestors.
func isAncestor(n Node, of tree.Node) bool {
for p := of; p != nil; p = p.AsTree().Parent {
if p == n {
return true
}
}
return false
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package svg
import (
"fmt"
"maps"
"strings"
)
// This file has the custom properties of CSS (--name) of SVG nodes, and
// their uses by var(--name, fallback) in the values of the properties of
// nodes and of CSS rules (as the icons of bicycling.com, of
// style="fill:var(--primary, #000)", with --primary set for :root in a
// style element of some, which failed to parse as colors).
// customVars returns the custom properties of the node: those of its
// parent, with those that it sets (for :root, in a CSS rule of its type,
// class or name, or in its properties) over them.
func (g *NodeBase) customVars(parent map[string]string) map[string]string {
type custom struct{ name, value string }
var own []custom
add := func(props map[string]any) {
for k, v := range props {
if strings.HasPrefix(k, "--") {
own = append(own, custom{k, fmt.Sprint(v)})
}
}
}
for _, key := range []string{":root", strings.ToLower(g.NodeType().Name), "." + strings.ToLower(g.Class), "#" + strings.ToLower(g.Name)} {
if pm, ok := g.CSSAgg[key].(map[string]any); ok {
add(pm)
}
}
add(g.Properties)
if len(own) == 0 {
return parent
}
vars := maps.Clone(parent)
if vars == nil {
vars = map[string]string{}
}
for _, c := range own {
vars[c.name] = strings.TrimSpace(resolveVars(c.value, vars))
}
return vars
}
// resolveVarsIn returns the given properties with the uses of custom
// properties in their string values (var(--name, fallback)) replaced by
// their values in the given custom properties, or their fallbacks; it is
// the given map if none has any.
func resolveVarsIn(props map[string]any, vars map[string]string) map[string]any {
var out map[string]any
for k, v := range props {
s, ok := v.(string)
if !ok || !strings.Contains(s, "var(") {
continue
}
if out == nil {
out = maps.Clone(props)
}
out[k] = resolveVars(s, vars)
}
if out == nil {
return props
}
return out
}
// resolveVars returns the given value with its uses of custom properties
// (var(--name, fallback)) replaced by their values in the given custom
// properties, or their fallbacks (or nothing), as in CSS.
func resolveVars(s string, vars map[string]string) string {
for range 16 { // (for the uses in values and fallbacks)
i := strings.Index(s, "var(")
if i < 0 {
return s
}
depth, end, comma := 0, -1, -1
for j := i + 3; j < len(s); j++ {
switch s[j] {
case '(':
depth++
case ')':
depth--
case ',':
if depth == 1 && comma < 0 {
comma = j
}
}
if depth == 0 {
end = j
break
}
}
if end < 0 {
return s
}
name, fallback := s[i+4:end], ""
if comma > 0 {
name, fallback = s[i+4:comma], s[comma+1:end]
}
v, ok := vars[strings.TrimSpace(name)]
if !ok {
v = strings.TrimSpace(fallback)
}
s = s[:i] + v + s[end+1:]
}
return s
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package svg
import (
"encoding/xml"
"errors"
"fmt"
"strings"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
)
////////////////////////////////////////////////////////////////////////////////////////
//////// ViewBox defines the SVG viewbox
// ViewBox is used in SVG to define the coordinate system
type ViewBox struct {
// offset or starting point in parent Viewport2D
Min math32.Vector2
// size of viewbox within parent Viewport2D
Size math32.Vector2
// how to scale the view box within parent
PreserveAspectRatio ViewBoxPreserveAspectRatio
}
// Defaults returns viewbox to defaults
func (vb *ViewBox) Defaults() {
vb.Min = math32.Vector2{}
vb.Size = math32.Vec2(100, 100)
vb.PreserveAspectRatio.Align.Set(AlignMid)
vb.PreserveAspectRatio.MeetOrSlice = Meet
}
func (vb *ViewBox) Max() math32.Vector2 {
return vb.Min.Add(vb.Size)
}
// BoxString returns the string representation of just the viewbox:
// "min.X min.Y size.X size.Y"
func (vb *ViewBox) BoxString() string {
return fmt.Sprintf(`viewbox="%g %g %g %g"`, vb.Min.X, vb.Min.Y, vb.Size.X, vb.Size.Y)
}
func (vb *ViewBox) String() string {
return vb.BoxString() + ` preserveAspectRatio="` + vb.PreserveAspectRatio.String() + `"`
}
// Transform returns the transform based on viewbox size relative to given box
// (viewport) size that it will be rendered into
func (vb *ViewBox) Transform(box math32.Vector2) (size, trans, scale math32.Vector2) {
of := styles.FitFill
switch {
case vb.PreserveAspectRatio.Align.X == AlignNone:
of = styles.FitFill
case vb.PreserveAspectRatio.MeetOrSlice == Meet:
of = styles.FitContain
case vb.PreserveAspectRatio.MeetOrSlice == Slice:
of = styles.FitCover
}
if vb.Size.X == 0 || vb.Size.Y == 0 {
vb.Size = math32.Vec2(100, 100)
}
size = styles.ObjectSizeFromFit(of, vb.Size, box)
scale = size.Div(vb.Size)
extra := box.Sub(size)
if extra.X > 0 {
trans.X = extra.X * vb.PreserveAspectRatio.Align.X.AlignFactor()
}
if extra.Y > 0 {
trans.Y = extra.Y * vb.PreserveAspectRatio.Align.Y.AlignFactor()
}
trans.SetDiv(scale)
return
}
// ViewBoxAligns defines values for the PreserveAspectRatio alignment factor
type ViewBoxAligns int32 //enums:enum -trim-prefix Align -transform lower
const (
// align ViewBox.Min with midpoint of Viewport (default)
AlignMid ViewBoxAligns = iota
// do not preserve uniform scaling (if either X or Y is None, both are treated as such).
// In this case, the Meet / Slice value is ignored.
// This is the same as FitFill from styles.ObjectFits
AlignNone
// align ViewBox.Min with top / left of Viewport
AlignMin
// align ViewBox.Min+Size with bottom / right of Viewport
AlignMax
)
// Aligns returns the styles.Aligns version of ViewBoxAligns
func (va ViewBoxAligns) Aligns() styles.Aligns {
switch va {
case AlignNone:
return styles.Start
case AlignMin:
return styles.Start
case AlignMax:
return styles.End
default:
return styles.Center
}
}
// SetFromAligns sets alignment from the styles.Aligns version of ViewBoxAligns
func (va *ViewBoxAligns) SetFromAligns(a styles.Aligns) {
switch a {
case styles.Start:
*va = AlignMin
case styles.End:
*va = AlignMax
case styles.Center:
*va = AlignMid
}
}
// AlignFactor returns the alignment factor for proportion offset
func (va ViewBoxAligns) AlignFactor() float32 {
return styles.AlignFactor(va.Aligns())
}
// ViewBoxMeetOrSlice defines values for the PreserveAspectRatio meet or slice factor
type ViewBoxMeetOrSlice int32 //enums:enum -transform lower
const (
// Meet only applies if Align != None (i.e., only for uniform scaling),
// and means the entire ViewBox is visible within Viewport,
// and it is scaled up as much as possible to meet the align constraints.
// This is the same as FitContain from styles.ObjectFits
Meet ViewBoxMeetOrSlice = iota
// Slice only applies if Align != None (i.e., only for uniform scaling),
// and means the entire ViewBox is covered by the ViewBox, and the
// ViewBox is scaled down as much as possible, while still meeting the
// align constraints.
// This is the same as FitCover from styles.ObjectFits
Slice
)
// ViewBoxPreserveAspectRatio determines how to scale the view box within parent Viewport2D
type ViewBoxPreserveAspectRatio struct {
// how to align X, Y coordinates within viewbox
Align styles.XY[ViewBoxAligns] `xml:"align"`
// how to scale the view box relative to the viewport
MeetOrSlice ViewBoxMeetOrSlice `xml:"meetOrSlice"`
}
func (pa *ViewBoxPreserveAspectRatio) String() string {
if pa.Align.X == AlignNone {
return "none"
}
xs := "xM" + pa.Align.X.String()[1:]
ys := "YM" + pa.Align.Y.String()[1:]
s := xs + ys
if pa.MeetOrSlice != Meet {
s += " slice"
}
return s
}
// SetString sets from a standard svg-formatted string,
// consisting of:
// none | x[Min, Mid, Max]Y[Min, Mid, Max] [ meet | slice]
// e.g., "xMidYMid meet" (default)
// It does not make sense to specify "meet | slice" for "none"
// as they do not apply in that case.
func (pa *ViewBoxPreserveAspectRatio) SetString(s string) error {
s = strings.TrimSpace(s)
if len(s) == 0 {
pa.Align.Set(AlignMid, AlignMid)
pa.MeetOrSlice = Meet
return nil
}
sl := strings.ToLower(s)
f := strings.Fields(sl)
if strings.HasPrefix(f[0], "none") {
pa.Align.Set(AlignNone)
pa.MeetOrSlice = Meet
return nil
}
var errs []error
if len(f) > 1 {
switch f[1] {
case "slice":
pa.MeetOrSlice = Slice
case "meet":
pa.MeetOrSlice = Meet
default:
errs = append(errs, fmt.Errorf("ViewBoxPreserveAspectRatio: 2nd value must be meet or slice, not %q", f[1]))
}
}
yi := strings.Index(f[0], "y")
if yi < 0 {
return fmt.Errorf("ViewBoxPreserveAspectRatio: string %q must contain a 'y'", s)
}
xs := f[0][1:yi]
ys := f[0][yi+1:]
err := pa.Align.X.SetString(xs)
if err != nil {
errs = append(errs, fmt.Errorf("ViewBoxPreserveAspectRatio: X align be min, mid, or max, not %q", xs))
}
err = pa.Align.Y.SetString(ys)
if err != nil {
errs = append(errs, fmt.Errorf("ViewBoxPreserveAspectRatio: Y align be min, mid, or max, not %q", ys))
}
if len(errs) == 0 {
return nil
}
return errors.Join(errs...)
}
// SetFromStyle sets from ObjectFit and Justify (X) and Align (Y) Content
// in given style.
func (pa *ViewBoxPreserveAspectRatio) SetFromStyle(s *styles.Style) {
pa.Align.X.SetFromAligns(s.Justify.Content)
pa.Align.Y.SetFromAligns(s.Align.Content)
// todo: could override with ObjectPosition but maybe not worth it?
switch s.ObjectFit {
case styles.FitFill:
pa.Align.Set(AlignNone)
case styles.FitContain:
pa.MeetOrSlice = Meet
case styles.FitCover, styles.FitScaleDown: // note: FitScaleDown not handled
pa.MeetOrSlice = Slice
}
}
// parseLength parses the given SVG length attribute (as x or width) of an
// element in the given root: a number of user units, with an optional
// unit (px, or absolute units, or em for 16px), or a percentage of the
// size of the view box of the root (its width for the x axis, its height
// for y, and their normalized diagonal for r, as for a circle radius).
func (sv *SVG) parseLength(root *Root, v string, axis byte) (float32, error) {
v = strings.TrimSpace(v)
if pct, ok := strings.CutSuffix(v, "%"); ok {
f, err := math32.ParseFloat32(strings.TrimSpace(pct))
if err != nil {
return 0, err
}
size := root.ViewBox.Size
if size.X <= 0 || size.Y <= 0 {
size = math32.FromPoint(sv.Geom.Size)
}
switch axis {
case 'x':
return f / 100 * size.X, nil
case 'y':
return f / 100 * size.Y, nil
default:
return f / 100 * math32.Sqrt((size.X*size.X+size.Y*size.Y)/2), nil
}
}
scale := float32(1)
for _, u := range []struct {
suffix string
scale float32
}{{"px", 1}, {"pt", 4.0 / 3}, {"pc", 16}, {"mm", 96 / 25.4}, {"cm", 96 / 2.54}, {"in", 96}, {"em", 16}} {
if rest, ok := strings.CutSuffix(v, u.suffix); ok {
v, scale = strings.TrimSpace(rest), u.scale
break
}
}
f, err := math32.ParseFloat32(v)
return f * scale, err
}
// nestedSVG adds the groups of a nested svg element with the given
// attributes (in the given root) to the given parent: an outer group
// clipped to its viewport (x, y, width, height, 100% by default), as
// browsers clip nested svg elements, and an inner group with the transform
// of its view box to its viewport, which it returns, for its children.
func (sv *SVG) nestedSVG(parent Node, root *Root, attrs []xml.Attr, n int) Node {
outer := NewGroup(parent)
inner := NewGroup(outer)
var x, y float32
w, _ := sv.parseLength(root, "100%", 'x')
h, _ := sv.parseLength(root, "100%", 'y')
var vb ViewBox
for _, attr := range attrs {
if SetStandardXMLAttr(inner, attr.Name.Local, attr.Value) {
continue
}
switch attr.Name.Local {
case "x":
x, _ = sv.parseLength(root, attr.Value, 'x')
case "y":
y, _ = sv.parseLength(root, attr.Value, 'y')
case "width":
w, _ = sv.parseLength(root, attr.Value, 'x')
case "height":
h, _ = sv.parseLength(root, attr.Value, 'y')
case "viewBox":
if pts := math32.ReadPoints(attr.Value); len(pts) == 4 {
vb.Min.Set(pts[0], pts[1])
vb.Size.Set(pts[2], pts[3])
}
case "preserveAspectRatio":
vb.PreserveAspectRatio.SetString(attr.Value)
case "xmlns", "version", "overflow":
default:
inner.SetProperty(attr.Name.Local, attr.Value)
}
}
xf := math32.Translate2D(x, y)
if vb.Size.X > 0 && vb.Size.Y > 0 {
_, trans, scale := vb.Transform(math32.Vec2(w, h))
trans.SetSub(vb.Min)
xf = xf.Mul(math32.Scale2D(scale.X, scale.Y).Translate(trans.X, trans.Y))
}
inner.SetProperty("transform", xf.String())
cp := NewClipPath(sv.Defs)
cp.SetName(fmt.Sprintf("nested-svg-clip-%d-%p", n, outer))
rect := NewRect(cp)
rect.Pos.Set(x, y)
rect.Size.Set(w, h)
outer.SetProperty("clip-path", "url(#"+cp.Name+")")
return inner
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package svg
import (
"bufio"
"bytes"
"encoding/xml"
"errors"
"io"
"unicode/utf8"
)
// XMLEncoder is a minimal XML encoder that formats output with Attr
// each on a new line, using same API as xml.Encoder
type XMLEncoder struct {
Writer io.Writer
DoIndent bool
IndBytes []byte
PreBytes []byte
CurIndent int
CurStart string
NoEndIndent bool
// textDepth is the number of open elements that are text elements or
// in them, where whitespace is text, so nothing is indented.
textDepth int
}
func NewXMLEncoder(wr io.Writer) *XMLEncoder {
return &XMLEncoder{Writer: wr}
}
func (xe *XMLEncoder) Indent(prefix, indent string) {
if len(indent) > 0 {
xe.DoIndent = true
}
xe.IndBytes = []byte(indent)
xe.PreBytes = []byte(prefix)
}
func (xe *XMLEncoder) EncodeToken(t xml.Token) error {
switch t := t.(type) {
case xml.StartElement:
if err := xe.WriteStart(&t); err != nil {
return err
}
case xml.EndElement:
if err := xe.WriteEnd(t.Name.Local); err != nil {
return err
}
case xml.CharData:
if xe.CurStart != "" {
xe.WriteString(">")
xe.CurStart = ""
xe.NoEndIndent = true // don't indent the end now
}
EscapeText(xe.Writer, t, false)
}
return nil
}
func (xe *XMLEncoder) WriteString(str string) {
xe.Writer.Write([]byte(str))
}
func (xe *XMLEncoder) WriteIndent() {
xe.Writer.Write(xe.PreBytes)
xe.Writer.Write(bytes.Repeat(xe.IndBytes, xe.CurIndent))
}
func (xe *XMLEncoder) WriteEOL() {
xe.Writer.Write([]byte("\n"))
}
// Decide whether the given rune is in the XML Character Range, per
// the Char production of https://www.xml.com/axml/testaxml.htm,
// Section 2.2 Characters.
func isInCharacterRange(r rune) (inrange bool) {
return r == 0x09 ||
r == 0x0A ||
r == 0x0D ||
r >= 0x20 && r <= 0xD7FF ||
r >= 0xE000 && r <= 0xFFFD ||
r >= 0x10000 && r <= 0x10FFFF
}
var (
escQuot = []byte(""") // shorter than """
escApos = []byte("'") // shorter than "'"
escAmp = []byte("&")
escLT = []byte("<")
escGT = []byte(">")
escTab = []byte("	")
escNL = []byte("
")
escCR = []byte("
")
escFFFD = []byte("\uFFFD") // Unicode replacement character
)
// EscapeText writes to w the properly escaped XML equivalent
// of the plain text data s. If escapeNewline is true, newline
// XMLcharacters will be escaped.
func EscapeText(w io.Writer, s []byte, escapeNewline bool) error {
var esc []byte
last := 0
for i := 0; i < len(s); {
r, width := utf8.DecodeRune(s[i:])
i += width
switch r {
case '"':
esc = escQuot
case '\'':
esc = escApos
case '&':
esc = escAmp
case '<':
esc = escLT
case '>':
esc = escGT
case '\t':
esc = escTab
case '\n':
if !escapeNewline {
continue
}
esc = escNL
case '\r':
esc = escCR
default:
if !isInCharacterRange(r) || (r == 0xFFFD && width == 1) {
esc = escFFFD
break
}
continue
}
if _, err := w.Write(s[last : i-width]); err != nil {
return err
}
if _, err := w.Write(esc); err != nil {
return err
}
last = i
}
_, err := w.Write(s[last:])
return err
}
// EscapeString writes to p the properly escaped XML equivalent
// of the plain text data s.
func (xe *XMLEncoder) EscapeString(s string, escapeNewline bool) {
var esc []byte
last := 0
for i := 0; i < len(s); {
r, width := utf8.DecodeRuneInString(s[i:])
i += width
switch r {
case '"':
esc = escQuot
case '\'':
esc = escApos
case '&':
esc = escAmp
case '<':
esc = escLT
case '>':
esc = escGT
case '\t':
esc = escTab
case '\n':
if !escapeNewline {
continue
}
esc = escNL
case '\r':
esc = escCR
default:
if !isInCharacterRange(r) || (r == 0xFFFD && width == 1) {
esc = escFFFD
break
}
continue
}
xe.WriteString(s[last : i-width])
xe.Writer.Write(esc)
last = i
}
xe.WriteString(s[last:])
}
func (xe *XMLEncoder) WriteStart(start *xml.StartElement) error {
if start.Name.Local == "" {
return errors.New("xml: start tag with no name")
}
inText := xe.textDepth > 0
if xe.CurStart != "" {
xe.WriteString(">")
if !inText {
xe.WriteEOL()
}
}
if !inText {
xe.WriteIndent()
}
if inText || start.Name.Local == "text" {
xe.textDepth++
}
xe.WriteString("<")
xe.WriteString(start.Name.Local)
xe.CurIndent++
xe.CurStart = start.Name.Local
// Attributes
for _, attr := range start.Attr {
name := attr.Name
if name.Local == "" {
continue
}
xe.WriteEOL()
xe.WriteIndent()
xe.WriteString(name.Local)
xe.WriteString(`="`)
xe.EscapeString(attr.Value, false)
xe.WriteString(`"`)
}
return nil
}
func (xe *XMLEncoder) WriteEnd(name string) error {
xe.CurIndent--
if name == "" {
return errors.New("xml: end tag with no name")
}
wasText := xe.textDepth > 0
if wasText {
xe.textDepth--
}
inText := xe.textDepth > 0 // whether the parent is in text
if xe.CurStart == name {
xe.WriteString(" />")
if !inText {
xe.WriteEOL()
}
} else {
if !xe.NoEndIndent && !wasText {
xe.WriteIndent()
}
xe.NoEndIndent = false
xe.WriteString("</")
xe.WriteString(name)
xe.WriteString(">")
if !inText {
xe.WriteEOL()
}
}
xe.CurStart = ""
xe.Flush()
return nil
}
func (xe *XMLEncoder) Flush() {
if bw, isb := xe.Writer.(*bufio.Writer); isb {
bw.Flush()
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package svg
import (
"image"
"cogentcore.org/core/math32"
)
// ContentBounds returns the bounding box of the contents
// in its natural units, without any Viewbox transformations, etc.
// Can set the Viewbox to this to have the contents fully occupy the space.
func (sv *SVG) ContentBounds() math32.Box2 {
tr := sv.Root.Paint.Transform
sv.Root.Paint.Transform = math32.Identity2()
sv.Root.BBoxes(sv, math32.Identity2())
sv.Root.Paint.Transform = tr
return sv.Root.BBox
}
// UpdateSize ensures that the size is valid, using existing ViewBox values
// to set proportions if size is not valid.
func (sv *SVG) UpdateSize() {
vb := &sv.Root.ViewBox
if vb.Size.X == 0 {
if sv.PhysicalWidth.Dots > 0 {
vb.Size.X = sv.PhysicalWidth.Dots
} else {
vb.Size.X = 640
}
}
if vb.Size.Y == 0 {
if sv.PhysicalHeight.Dots > 0 {
vb.Size.Y = sv.PhysicalHeight.Dots
} else {
vb.Size.Y = 480
}
}
if sv.Geom.Size.X > 0 && sv.Geom.Size.Y == 0 {
sv.Geom.Size.Y = int(float32(sv.Geom.Size.X) * (float32(vb.Size.Y) / float32(vb.Size.X)))
} else if sv.Geom.Size.Y > 0 && sv.Geom.Size.X == 0 {
sv.Geom.Size.X = int(float32(sv.Geom.Size.Y) * (float32(vb.Size.X) / float32(vb.Size.Y)))
}
}
// setRootTransform sets the Root node transform based on ViewBox, Translate, Scale
// parameters set on the SVG object.
func (sv *SVG) setRootTransform() {
sv.UpdateSize()
vb := &sv.Root.ViewBox
box := math32.FromPoint(sv.Geom.Size)
tr := math32.Translate2D(float32(sv.Geom.Pos.X)+sv.Translate.X, float32(sv.Geom.Pos.Y)+sv.Translate.Y)
_, trans, scale := vb.Transform(box)
if sv.InvertY {
scale.Y *= -1
}
trans.SetSub(vb.Min)
scale.SetMulScalar(sv.Scale)
rt := math32.Scale2D(scale.X, scale.Y).Translate(trans.X, trans.Y)
if sv.InvertY {
rt.Y0 = -rt.Y0
}
sv.Root.Paint.Transform = tr.Mul(rt)
}
// SetDPITransform sets a scaling transform to compensate for
// a given LogicalDPI factor.
// svg rendering is done within a 96 DPI context.
func (sv *SVG) SetDPITransform(logicalDPI float32) {
pc := &sv.Root.Paint
dpisc := logicalDPI / 96.0
pc.Transform = math32.Scale2D(dpisc, dpisc)
}
// ZoomAtScroll calls ZoomAt using the Delta.Y and Pos() parameters
// from an [events.MouseScroll] event, to produce well-behaved zooming behavior,
// for elements of any size.
func (sv *SVG) ZoomAtScroll(deltaY float32, pos image.Point) {
del := 0.01 * deltaY * max(sv.Root.ViewBox.Size.X/1280, 0.1)
del /= max(1, sv.Scale)
del = math32.Clamp(del, -0.1, 0.1)
sv.ZoomAt(pos, del)
}
// ZoomAt updates the global Scale by given delta value,
// by multiplying the current Scale by 1+delta
// (+ means zoom in; - means zoom out).
// Delta should be < 1 in magnitude, and resulting scale is clamped
// in range 0.01..100.
// The global Translate is updated so that the given render
// coordinate point (dots) corresponds to the same
// underlying svg viewbox coordinate point.
func (sv *SVG) ZoomAt(pt image.Point, delta float32) {
sc := float32(1)
if delta > 1 {
sc += delta
} else {
sc *= (1 - math32.Min(-delta, .5))
}
nsc := math32.Clamp(sv.Scale*sc, 0.01, 100)
sv.ScaleAt(pt, nsc)
}
// ScaleAt sets the global Scale parameter and updates the
// global Translate parameter so that the given render coordinate
// point (dots) corresponds to the same underlying svg viewbox
// coordinate point.
func (sv *SVG) ScaleAt(pt image.Point, sc float32) {
sv.setRootTransform()
rxf := sv.Root.Paint.Transform.Inverse()
mpt := math32.FromPoint(pt)
xpt := rxf.MulPoint(mpt)
sv.Scale = sc
sv.setRootTransform()
rxf = sv.Root.Paint.Transform
npt := rxf.MulPoint(xpt) // original point back to screen
dpt := mpt.Sub(npt)
sv.Translate.SetAdd(dpt)
}
func (sv *SVG) ZoomReset() {
sv.Translate.Set(0, 0)
sv.Scale = 1
}
// ZoomToContents sets the scale to fit the current contents
// into a display of given size.
func (sv *SVG) ZoomToContents(size math32.Vector2) {
sv.ZoomReset()
bb := sv.ContentBounds()
bsz := bb.Size().Max(math32.Vec2(1, 1))
if bsz == (math32.Vector2{}) {
return
}
sc := size.Div(bsz)
sv.Translate = bb.Min.Negate()
sv.Scale = math32.Min(sc.X, sc.Y)
}
// ResizeToContents resizes the drawing to just fit the current contents,
// including moving everything to start at upper-left corner.
// The given grid spacing parameter ensures sizes are in units of the grid
// spacing: pass a 1 to just use actual sizes.
func (sv *SVG) ResizeToContents(grid float32) {
sv.ZoomReset()
bb := sv.ContentBounds()
bsz := bb.Size()
if bsz.X <= 0 || bsz.Y <= 0 {
return
}
trans := bb.Min
treff := trans
if grid > 1 {
incr := grid * sv.Scale
treff.X = math32.Floor(trans.X/incr) * incr
treff.Y = math32.Floor(trans.Y/incr) * incr
bsz.SetAdd(trans.Sub(treff))
bsz.X = math32.Ceil(bsz.X/incr) * incr
bsz.Y = math32.Ceil(bsz.Y/incr) * incr
}
root := sv.Root
root.ViewBox.Min = treff
root.ViewBox.Size = bsz
// sv.PhysicalWidth.Value = bsz.X
// sv.PhysicalHeight.Value = bsz.Y
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// based on golang.org/x/exp/shiny:
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package system provides a Go operating system interface framework
// to support events, window management, and other OS-specific
// functionality needed for full GUI support.
package system
import (
"fmt"
"os"
"runtime/debug"
"cogentcore.org/core/styles"
)
//go:generate core generate
var (
// TheApp is the current [App]; only one is ever in effect.
TheApp App
// AppVersion is the version of the current app.
// It is set by a linker flag in the core command line tool,
// with a backup based on [debug.ReadBuildInfo].
AppVersion = "dev"
// CoreVersion is the version of Cogent Core that the current app is using.
// It is set by a linker flag in the core command line tool,
// with a backup based on [debug.ReadBuildInfo].
CoreVersion = "dev"
// AppID is the ID of the current app, such as com.org.app, which is its
// package name on Android. It is set by a linker flag in the core command
// line tool, and is empty otherwise.
AppID = ""
// ReservedWebShortcuts is a list of shortcuts that are reserved on the web
// platform, meaning that they are handled by the browser instead of Cogent Core.
// By default, this list contains important web shortcuts like Command+r and Command+(1-9).
// All instances of "Command" are automatically converted to "Control" on non-macOS system
// platforms, meaning that shortcuts should typically be expressed using "Command" for
// cross-platform support. Modifiers should be specified in the order of [key.Modifiers]:
// Shift, Control, Alt, Command. Shortcuts can be removed from this list by an app whose use of
// them is more important than the default web action for that shortcut.
ReservedWebShortcuts = []string{"Command+r", "Command+Shift+r", "Command+w", "Command+t", "Command+Shift+t", "Command+q", "Command+n", "Command+m", "Command+l", "Command+h", "Command+Shift+j", "Command+Alt+j", "Command+Alt+∆", "Command+1", "Command+2", "Command+3", "Command+4", "Command+5", "Command+6", "Command+7", "Command+8", "Command+9"}
)
// App represents the overall OS GUI hardware, and creates Images, Textures
// and Windows, appropriate for that hardware / OS, and maintains data about
// the physical screen(s)
type App interface {
// Platform returns the platform type, which can be used
// for conditionalizing behavior.
Platform() Platforms
// SystemPlatform returns the platform type of the underlying
// system, which can be used for conditionalizing behavior. On platforms
// other than [Web], this is the same as [App.Platform]. On [Web], it
// returns the platform of the underlying operating system.
SystemPlatform() Platforms
// SystemLocale returns the https://www.rfc-editor.org/rfc/bcp/bcp47.txt standard
// language tag, consisting of language and region, e.g., "en-US", "fr-FR", "ja-JP".
SystemLocale() Locale
// SystemInfo returns any additional information about the underlying system
// that is not otherwise given. It is used in crash logs.
SystemInfo() string
// Name is the overall name of the application. Used for specifying an
// application-specific preferences directory, etc.
Name() string
// SetName sets the application name. Defaults to Cogent Core if not otherwise set.
SetName(name string)
// GetScreens gets the current list of screens.
GetScreens()
// NScreens returns the number of different logical and/or physical
// screens managed under this overall screen hardware.
NScreens() int
// Screen returns the screen for the given screen number, or the first
// screen if the number is out of range.
Screen(n int) *Screen
// ScreenByName returns screen for given screen name, or nil if not a
// valid screen name.
ScreenByName(name string) *Screen
// NWindows returns the number of windows open for this app.
NWindows() int
// Window returns given window in list of windows opened under this screen
// -- list is not in any guaranteed order, but typically in order of
// creation (see also WindowByName) -- returns nil for invalid index.
Window(win int) Window
// WindowByName returns given window in list of windows opened under this
// screen, by name -- nil if not found.
WindowByName(name string) Window
// WindowInFocus returns the window currently in focus (receiving keyboard
// input) -- could be nil if none are.
WindowInFocus() Window
// ContextWindow returns the window passed as context for clipboard, cursor, etc calls.
ContextWindow() Window
// NewWindow returns a new Window for this screen. A nil opts is valid and
// means to use the default option values.
NewWindow(opts *NewWindowOptions) (Window, error)
// RemoveWindow removes the given Window from the app's list of windows.
// It does not actually close it; see [Window.Close] for that.
RemoveWindow(win Window)
// Clipboard returns the [Clipboard] handler for the system,
// in context of given window, which is optional (can be nil)
// but can provide useful context on some systems.
Clipboard(win Window) Clipboard
// Cursor returns the [Cursor] handler for the system, in the context
// of the given window.
Cursor(win Window) Cursor
// Notifier returns the [Notifier] for showing notifications with the
// notification system of the operating system.
Notifier() Notifier
// DataDir returns the OS-specific data directory: Mac: ~/Library,
// Linux: ~/.config, Windows: ~/AppData/Roaming
DataDir() string
// AppDataDir returns the application-specific data directory: [App.DataDir] +
// [App.Name]. It ensures that the directory exists first.
AppDataDir() string
// CogentCoreDataDir returns the Cogent Core data directory: [App.DataDir] +
// "Cogent Core". It ensures that the directory exists first.
CogentCoreDataDir() string
// OpenURL opens the given URL in the user's default browser. On Linux
// this requires that xdg-utils package has been installed, since it uses
// the xdg-open command.
OpenURL(url string)
// SetBadge sets the badge shown on the icon of the app, as the number
// of unread messages, or removes it if it is empty: on the icon in the
// dock on macOS; on Linux, as a count (numbers only) on the icon in the
// docks and task managers that support the launcher entry API of Unity
// (Ubuntu Dock, Dash to Dock, KDE Plasma); and on the web, in parentheses
// before the title of the page, and on the icon of an installed app
// where the browser supports it. Elsewhere it does nothing.
SetBadge(label string)
// OpenFiles returns file names that have been set to be open at startup.
OpenFiles() []string
// SetQuitReqFunc sets the function that is called whenever there is a
// request to quit the app (via a OS or a call to QuitReq() method). That
// function can then adjudicate whether and when to actually call Quit.
SetQuitReqFunc(fun func())
// AddQuitCleanFunc adds the given function to a list that is called whenever
// app is actually about to quit (irrevocably). Can do any necessary
// last-minute cleanup here.
AddQuitCleanFunc(fun func())
// QuitReq is a quit request, triggered either by OS or user call (e.g.,
// via Quit menu action) -- calls function previously registered by
// SetQuitReqFunc, which is then solely responsible for actually calling
// Quit.
QuitReq()
// IsQuitting returns true when the app is actually quitting -- it is set
// to true just before the QuitClean function is called, and before all
// the windows are closed.
IsQuitting() bool
// QuitClean calls the function setup in SetQuitCleanFunc and does other
// app cleanup -- called on way to quitting. If it returns false, then
// the app should not quit.
QuitClean() bool
// Quit closes all windows and exits the program.
Quit()
// MainLoop runs the main loop of the app.
MainLoop()
// RunOnMain runs given function on main thread (where [App.MainLoop] is running).
// Some functions (GUI-specific etc) must run on this initial main thread for the
// overall app. If [App.MainLoop] has not been called yet, RunOnMain assumes that
// it is being called from the main thread and thus just calls the given function
// directly.
RunOnMain(f func())
// SendEmptyEvent sends an empty, blank event to global event processing
// system, which has the effect of pushing the system along during cases when
// the event loop needs to be "pinged" to get things moving along.
// See also similar method on Window.
SendEmptyEvent()
// ShowVirtualKeyboard shows a virtual keyboard of the given type.
// ShowVirtualKeyboard only has an effect on mobile platforms (iOS, Android, and Web).
// It should not be called with [styles.NoKeyboard].
ShowVirtualKeyboard(typ styles.VirtualKeyboards)
// HideVirtualKeyboard hides the virtual keyboard.
// HideVirtualKeyboard only has an effect on mobile platforms (iOS, Android, and Web).
HideVirtualKeyboard()
// BeginBackgroundTask asks the operating system to keep the app running
// for a while if it goes into the background (as when the user goes
// to the home screen or locks the phone), until the returned function
// is called, for finishing work such as saving or syncing data. It only
// has an effect on iOS, where the app has about 30 seconds; elsewhere,
// apps keep running in the background, or are not suspended anyway.
// The returned function must be called once the work is done.
BeginBackgroundTask(name string) (end func())
// IsDark returns whether the system color theme is dark (as oppposed to light).
IsDark() bool
}
// OnSystemWindowCreated is a channel used to communicate that the underlying
// system window has been created on iOS and Android. If it is nil, it indicates
// that the current platform does not have an underlying system window that is
// created asynchronously, or that system window has already been created and
// thus this is no longer applicable. If it is non-nil, no actions with the window
// should be taken until a signal is sent.
var OnSystemWindowCreated chan struct{}
// HandleBack is, if set, a function that is called by the drivers for the back button or
// gesture of the system (on Android), and returns whether it went back
// within the app; otherwise the system handles it (leaving the app).
// It is set by the core package (see core.handleBack).
var HandleBack func() bool
// Platforms are all the supported platforms for system
type Platforms int32 //enums:enum
const (
// MacOS is a macOS computer (aka Darwin). It is a multi-window desktop platform.
MacOS Platforms = iota
// Linux is a Linux computer. It is a multi-window desktop platform.
Linux
// Windows is a Microsoft Windows computer. It is a multi-window desktop platform.
Windows
// IOS is an Apple iOS or iPadOS mobile phone or iPad. It is a single-window mobile platform.
IOS
// Android is an Android mobile phone or tablet. It is a single-window mobile platform.
Android
// Web is a web browser running the app through WASM. It is a single-window "mobile" platform.
Web
// Offscreen is an offscreen driver typically used for testing,
// specified using the "offscreen" build tag. It is automatically
// enabled when testing. It is a multi-window but single-screen platform.
Offscreen
)
// IsMobile returns whether the platform is a "mobile" platform
// ([IOS], [Android], or [Web]). [Web] is considered a mobile platform
// because it only supports one window. You can use [App.SystemPlatform]
// to determine the underlying system platform on [Web] (IsMobile on SystemPlatform
// will only return true if the underlying system is actually iOS or Android).
func (p Platforms) IsMobile() bool {
return p == IOS || p == Android || p == Web
}
func init() {
// We only need this backup [debug.ReadBuildInfo] logic if the versions
// weren't already set by the linker flags in the core tool.
if AppVersion != "dev" || CoreVersion != "dev" {
return
}
bi, ok := debug.ReadBuildInfo()
if !ok {
return
}
revision, time := "dev", "unknown"
for _, set := range bi.Settings {
if set.Key == "vcs.revision" {
revision = set.Value
}
if set.Key == "vcs.time" {
time = set.Value
}
}
AppVersion = fmt.Sprintf("%s (%s)", revision, time)
if bi.Main.Path == "cogentcore.org/core" {
CoreVersion = AppVersion
} else {
for _, dep := range bi.Deps {
if dep.Path == "cogentcore.org/core" {
CoreVersion = dep.Version
break
}
}
}
}
// GenerateHTMLArg returns true if the first [os.Args] is -generatehtml.
// Apps that process args should test this first and skip arg processing
// if true.
func GenerateHTMLArg() bool {
if len(os.Args) < 2 {
return false
}
return os.Args[1] == "-generatehtml"
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package system
import (
"cogentcore.org/core/base/fileinfo/mimedata"
)
// Clipboard defines the methods for reading and writing data to
// the system clipboard, which use mimedata to represent the data.
// Due to limitations of Windows (and Linux to a lesser extent),
// a multipart MIME formatted string is used if there are multiple
// elements in the mimedata, with any binary data text-encoded using base64.
type Clipboard interface {
// IsEmpty returns true if there is nothing on the clipboard to read.
// Can be used for disabling a Paste menu.
IsEmpty() bool
// Read attempts to read data of the given MIME type(s), in preference
// order, from the clipboard, returning mimedata.Mimes which can
// potentially have multiple types / multiple items, etc. If the first type
// listed is a text type, then text-based retrieval is assumed; always
// put the most specific desired type first; anything else present will
// be returned
Read(types []string) mimedata.Mimes
// Write writes given mimedata to the clipboard; in general having a
// text/plain representation of the data in addition to a more specific
// format is a good idea for anything more complex than plain text; if
// data has > 1 element, it is all encoded as a multipart MIME text string
Write(data mimedata.Mimes) error
// Clear clears the clipboard.
Clear()
}
// ClipboardBase is a basic implementation of [Clipboard] that does nothing.
type ClipboardBase struct{}
var _ Clipboard = &ClipboardBase{}
func (bb *ClipboardBase) IsEmpty() bool { return false }
func (bb *ClipboardBase) Read(types []string) mimedata.Mimes { return nil }
func (bb *ClipboardBase) Write(data mimedata.Mimes) error { return nil }
func (bb *ClipboardBase) Clear() {}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package composer
// ComposerDrawer implements [Composer] using a [Drawer].
type ComposerDrawer struct {
// Drawer is the [Drawer] used for composition.
Drawer Drawer
// Sources are the composition [Source]s.
Sources []Source
}
func (cd *ComposerDrawer) Start() {
cd.Sources = cd.Sources[:0]
}
func (cd *ComposerDrawer) Add(s Source, ctx any) {
if s == nil { // TODO: necessary?
return
}
cd.Sources = append(cd.Sources, s)
}
func (cd *ComposerDrawer) Compose() {
cd.Drawer.Start()
for _, s := range cd.Sources {
s.Draw(cd)
}
cd.Drawer.End()
}
// Occluded returns whether the drawer did not draw the last composition, as
// its window was occluded (hidden), if it can tell (as the GPU drawer can).
func (cd *ComposerDrawer) Occluded() bool {
od, ok := cd.Drawer.(interface{ Occluded() bool })
return ok && od.Occluded()
}
func (cd *ComposerDrawer) Redraw() {
cd.Drawer.Redraw()
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package composer
import (
"image"
"image/draw"
"cogentcore.org/core/math32"
)
const (
// Unchanged should be used for the unchanged argument in drawer calls,
// when the caller knows that the image is unchanged.
Unchanged = true
// Changed should be used for the unchanged argument to drawer calls,
// when the image has changed since last time or its status is unknown.
Changed = false
)
// Drawer is an interface for image/draw style image compositing
// functionality, which is implemented for the GPU in
// [*cogentcore.org/core/gpu/gpudraw.Drawer] and in offscreen drivers.
// This is used for compositing the stack of images that together comprise
// the content of a window. It is used in [ComposerDrawer].
type Drawer interface {
// Start starts recording a sequence of draw / fill actions,
// which will be performed on the GPU at End().
// This must be called prior to any Drawer operations.
Start()
// End ends image drawing rendering process on render target.
End()
// Redraw re-renders the last draw
Redraw()
// Copy copies the given Go source image to the render target, with the
// same semantics as golang.org/x/image/draw.Copy, with the destination
// implicit in the Drawer target.
// - Must have called Start first!
// - dp is the destination point.
// - src is the source image. If an image.Uniform, fast Fill is done.
// - sr is the source region, if zero full src is used; must have for Uniform.
// - op is the drawing operation: Src = copy source directly (blit),
// Over = alpha blend with existing.
// - unchanged should be true if caller knows that this image is unchanged
// from the last time it was used -- saves re-uploading to gpu.
Copy(dp image.Point, src image.Image, sr image.Rectangle, op draw.Op, unchanged bool)
// Scale copies the given Go source image to the render target,
// scaling the region defined by src and sr to the destination
// such that sr in src-space is mapped to dr in dst-space,
// and applying an optional rotation of the source image.
// Has the same general semantics as golang.org/x/image/draw.Scale, with the
// destination implicit in the Drawer target.
// If src image is an
// - Must have called Start first!
// - dr is the destination rectangle; if zero uses full dest image.
// - src is the source image. Uniform does not work (or make sense) here.
// - sr is the source region, if zero full src is used; must have for Uniform.
// - rotateDeg = rotation degrees to apply in the mapping:
// 90 = left, -90 = right, 180 = invert.
// - op is the drawing operation: Src = copy source directly (blit),
// Over = alpha blend with existing.
// - unchanged should be true if caller knows that this image is unchanged
// from the last time it was used -- saves re-uploading to gpu.
Scale(dr image.Rectangle, src image.Image, sr image.Rectangle, rotateDeg float32, op draw.Op, unchanged bool)
// Transform copies the given Go source image to the render target,
// with the same semantics as golang.org/x/image/draw.Transform, with the
// destination implicit in the Drawer target.
// - xform is the transform mapping source to destination coordinates.
// - src is the source image. Uniform does not work (or make sense) here.
// - sr is the source region, if zero full src is used; must have for Uniform.
// - op is the drawing operation: Src = copy source directly (blit),
// Over = alpha blend with existing.
// - unchanged should be true if caller knows that this image is unchanged
// from the last time it was used -- saves re-uploading to gpu.
Transform(xform math32.Matrix3, src image.Image, sr image.Rectangle, op draw.Op, unchanged bool)
// Renderer is the gpu device being drawn to.
// Could be nil on unsupported devices (such as offscreen).
Renderer() any
}
// DrawerBase is a base implementation of [Drawer] with basic no-ops
// for most methods. Embedders need to implement DestBounds and End.
type DrawerBase struct {
// Image is the target render image
Image *image.RGBA
}
// Copy copies the given Go source image to the render target, with the
// same semantics as golang.org/x/image/draw.Copy, with the destination
// implicit in the Drawer target.
// - Must have called Start first!
// - dp is the destination point.
// - src is the source image. If an image.Uniform, fast Fill is done.
// - sr is the source region, if zero full src is used; must have for Uniform.
// - op is the drawing operation: Src = copy source directly (blit),
// Over = alpha blend with existing.
// - unchanged should be true if caller knows that this image is unchanged
// from the last time it was used -- saves re-uploading to gpu.
func (dw *DrawerBase) Copy(dp image.Point, src image.Image, sr image.Rectangle, op draw.Op, unchanged bool) {
// the source region (all of src if zero) is drawn at dp, as on the GPU,
// which is also the region filled with a Uniform (which has no bounds)
if sr == (image.Rectangle{}) {
sr = src.Bounds()
}
draw.Draw(dw.Image, image.Rectangle{dp, dp.Add(sr.Size())}, src, sr.Min, op)
}
// Scale copies the given Go source image to the render target,
// scaling the region defined by src and sr to the destination
// such that sr in src-space is mapped to dr in dst-space,
// and applying an optional rotation of the source image.
// Has the same general semantics as golang.org/x/image/draw.Scale, with the
// destination implicit in the Drawer target.
// If src image is an
// - Must have called Start first!
// - dr is the destination rectangle; if zero uses full dest image.
// - src is the source image. Uniform does not work (or make sense) here.
// - sr is the source region, if zero full src is used; must have for Uniform.
// - rotateDeg = rotation degrees to apply in the mapping:
// 90 = left, -90 = right, 180 = invert.
// - op is the drawing operation: Src = copy source directly (blit),
// Over = alpha blend with existing.
// - unchanged should be true if caller knows that this image is unchanged
// from the last time it was used -- saves re-uploading to gpu.
func (dw *DrawerBase) Scale(dr image.Rectangle, src image.Image, sr image.Rectangle, rotateDeg float32, op draw.Op, unchanged bool) {
// todo: use drawmatrix and x/image to implement scale.
draw.Draw(dw.Image, dr, src, sr.Min, op)
}
// Transform copies the given Go source image to the render target,
// with the same semantics as golang.org/x/image/draw.Transform, with the
// destination implicit in the Drawer target.
// - xform is the transform mapping source to destination coordinates.
// - src is the source image. Uniform does not work (or make sense) here.
// - sr is the source region, if zero full src is used; must have for Uniform.
// - op is the drawing operation: Src = copy source directly (blit),
// Over = alpha blend with existing.
// - unchanged should be true if caller knows that this image is unchanged
// from the last time it was used -- saves re-uploading to gpu.
func (dw *DrawerBase) Transform(xform math32.Matrix3, src image.Image, sr image.Rectangle, op draw.Op, unchanged bool) {
// todo: use drawmatrix and x/image to implement transform
draw.Draw(dw.Image, sr, src, sr.Min, op)
}
// Start starts recording a sequence of draw / fill actions,
// which will be performed on the GPU at End().
// This must be called prior to any Drawer operations.
func (dw *DrawerBase) Start() {
// no-op
}
func (dw *DrawerBase) Renderer() any {
// no-op
return nil
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package system
import (
"cogentcore.org/core/enums"
"cogentcore.org/core/styles/units"
)
// Cursor manages the mouse cursor / pointer appearance.
type Cursor interface {
// Current returns the current cursor as an enum, which is a
// [cogentcore.org/core/cursors.Cursor]
// by default, but could be something else if you are extending
// the default cursor set.
Current() enums.Enum
// Set sets the active cursor to the given cursor as an enum, which is typically
// a [cursors.Cursor], unless you are extending the default cursor set, in
// which case it should be a type you defined. The string version of the
// enum value must correspond to a filename of the form "name.svg" in
// [cogentcore.org/core/cursors.Cursors]; this will be satisfied automatically by all
// [cursor.Cursor] values.
Set(cursor enums.Enum) error
// IsVisible returns whether cursor is currently visible (according to [Cursor.Hide] and [Cursor.Show] actions)
IsVisible() bool
// Hide hides the cursor if it is not already hidden.
Hide()
// Show shows the cursor after a hide if it is hidden.
Show()
// SetSize sets the size that cursors are rendered at.
// The standard size is [units.Dp](32).
SetSize(size units.Value)
}
// CursorBase provides the common infrastructure for the [Cursor] interface,
// to be extended on desktop platforms. It can also be used as an empty
// implementation of the [Cursor] interface on mobile platforms, as they
// do not have cursors.
type CursorBase struct {
// Cur is the current cursor, which is maintained by the standard methods.
Cur enums.Enum
// Vis is whether the cursor is visible; be sure to initialize to true!
Vis bool
// Size is the size that cursors are rendered at.
// The standard size is [units.Dp](32).
Size units.Value
}
// CursorBase should be a valid cursor so that it can be used directly in mobile
var _ Cursor = (*CursorBase)(nil)
func (c *CursorBase) Current() enums.Enum {
return c.Cur
}
func (c *CursorBase) Set(cursor enums.Enum) error {
c.Cur = cursor
return nil
}
func (c *CursorBase) IsVisible() bool {
return c.Vis
}
func (c *CursorBase) Hide() {
c.Vis = false
}
func (c *CursorBase) Show() {
c.Vis = true
}
func (c *CursorBase) SetSize(size units.Value) {
c.Size = size
}
// Copyright 2023 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on golang.org/x/exp/shiny:
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package base provides base driver types that platform-specific drivers can extend
// to implement interfaces defined in package system.
package base
import (
"os"
"path/filepath"
"sync"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/events/key"
"cogentcore.org/core/styles"
"cogentcore.org/core/system"
"github.com/jeandeaual/go-locale"
)
// App contains the data and logic common to all implementations of [system.App].
type App struct {
// This is the App as a [system.App] interface, which preserves the actual identity
// of the app when calling interface methods in the base App.
This system.App `display:"-"`
// Mu is the main mutex protecting access to app operations, including [App.RunOnMain] functions.
Mu sync.Mutex `display:"-"`
// MainQueue is the queue of functions to call on the main loop.
// To add to it, use [App.RunOnMain].
MainQueue chan FuncRun `display:"-"`
// MainDone is a channel on which is a signal is sent when the main
// loop of the app should be terminated.
MainDone chan struct{} `display:"-"`
// mainDoneOnce makes MainDone once (see [App.InitMainDone]).
mainDoneOnce sync.Once
// Nm is the name of the app.
Nm string `label:"Name"`
// OpenFls are files that have been set by the operating system to open at startup.
OpenFls []string `label:"Open files"`
// Quitting is whether the app is quitting and thus closing all of the windows
Quitting bool
// QuitReqFunc is a function to call when a quit is requested
QuitReqFunc func()
// QuitCleanFuncs are functions to call when the app is about to quit
QuitCleanFuncs []func()
// Dark is whether the system color theme is dark (as opposed to light)
Dark bool
}
// Init does basic initialization steps of the given App. It should be called by
// platform-specific implementations of Init with their platform-specific app
// instance and its base App field. Other platform-specific initial configuration
// steps can be called before this. Platform-specific implementations of Init are
// always called by a lowercase init function in system/driver/driver_{platform}.go.
func Init(a system.App, ab *App) {
ab.This = a
system.TheApp = a
key.SystemPlatform = a.SystemPlatform().String()
// sl := a.SystemLocale()
// fmt.Println("locale:", sl, sl.Language(), sl.Region())
}
// InitMainDone makes [App.MainDone] if it has not been made yet. Both the
// main loop and [App.StopMain] call it, as StopMain can be called before
// the main loop starts (from another goroutine), when a send on a nil
// channel would block forever.
func (a *App) InitMainDone() {
a.mainDoneOnce.Do(func() {
a.MainDone = make(chan struct{})
})
}
func (a *App) MainLoop() {
a.MainQueue = make(chan FuncRun)
a.InitMainDone()
for {
select {
case <-a.MainDone:
return
case f := <-a.MainQueue:
f.F()
if f.Done != nil {
f.Done <- struct{}{}
}
}
}
}
// RunOnMain runs the given function on the main thread
func (a *App) RunOnMain(f func()) {
if a.MainQueue == nil {
f()
return
}
a.This.SendEmptyEvent()
done := make(chan struct{})
a.MainQueue <- FuncRun{F: f, Done: done}
<-done
a.This.SendEmptyEvent()
}
// SendEmptyEvent sends an empty, blank event to global event processing
// system, which has the effect of pushing the system along during cases when
// the event loop needs to be "pinged" to get things moving along..
func (a *App) SendEmptyEvent() {
// no-op by default
}
// StopMain stops the main loop and thus terminates the app
func (a *App) StopMain() {
a.InitMainDone()
a.MainDone <- struct{}{}
}
func (a *App) SystemPlatform() system.Platforms {
// same as Platform by default
return a.This.Platform()
}
func (a *App) SystemInfo() string {
return "" // no-op by default
}
func (a *App) SystemLocale() system.Locale {
return system.Locale(errors.Log1(locale.GetLocale()))
}
func (a *App) Name() string {
return a.Nm
}
func (a *App) SetName(name string) {
a.Nm = name
}
func (a *App) OpenFiles() []string {
return a.OpenFls
}
func (a *App) AppDataDir() string {
pdir := filepath.Join(system.TheApp.DataDir(), a.Name())
errors.Log(os.MkdirAll(pdir, 0755))
return pdir
}
func (a *App) CogentCoreDataDir() string {
pdir := filepath.Join(a.This.DataDir(), "Cogent Core")
errors.Log(os.MkdirAll(pdir, 0755))
return pdir
}
func (a *App) SetQuitReqFunc(fun func()) {
a.QuitReqFunc = fun
}
func (a *App) AddQuitCleanFunc(fun func()) {
a.QuitCleanFuncs = append(a.QuitCleanFuncs, fun)
}
func (a *App) QuitReq() {
if a.Quitting {
return
}
if a.QuitReqFunc != nil {
a.QuitReqFunc()
} else {
a.Quit()
}
}
func (a *App) IsQuitting() bool {
return a.Quitting
}
func (a *App) Quit() {
if a.Quitting {
return
}
a.Quitting = true
if a.This.QuitClean() {
a.StopMain()
} else {
a.Quitting = false
}
}
func (a *App) IsDark() bool {
return a.Dark
}
func (a *App) GetScreens() {
// no-op by default
}
func (a *App) SetBadge(label string) {
// no-op by default
}
func (a *App) OpenURL(url string) {
// no-op by default
}
func (a *App) Clipboard(win system.Window) system.Clipboard {
// no-op by default
return &system.ClipboardBase{}
}
func (a *App) Cursor(win system.Window) system.Cursor {
// no-op by default
return &system.CursorBase{}
}
func (a *App) Notifier() system.Notifier {
// not supported by default
return &system.NotifierBase{}
}
func (a *App) ShowVirtualKeyboard(typ styles.VirtualKeyboards) {
// no-op by default
}
func (a *App) BeginBackgroundTask(name string) (end func()) {
return func() {} // (not needed)
}
func (a *App) HideVirtualKeyboard() {
// no-op by default
}
// Copyright 2023 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on golang.org/x/exp/shiny:
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package base
import (
"slices"
"cogentcore.org/core/system"
)
// AppMulti contains the data and logic common to all implementations of [system.App]
// on multi-window platforms (desktop and offscreen), as opposed to single-window
// platforms (mobile and web), for which you should use [AppSingle]. An AppMulti is associated
// with a corresponding type of [system.Window]. The [system.Window]
// type should embed [WindowMulti].
type AppMulti[W system.Window] struct {
App
// Windows are the windows associated with the app
Windows []W
// Screens are the screens associated with the app
Screens []*system.Screen
// AllScreens is a unique list of all screens ever seen, from which
// information can be got if something is missing in [AppMulti.Screens]
AllScreens []*system.Screen
// CtxWindow is a dynamically set context window used for some operations
CtxWindow W `label:"Context window"`
}
// NewAppMulti makes a new [AppMulti].
func NewAppMulti[W system.Window]() AppMulti[W] {
return AppMulti[W]{}
}
func (a *AppMulti[W]) NScreens() int {
return len(a.Screens)
}
func (a *AppMulti[W]) Screen(n int) *system.Screen {
if n >= 0 && n < len(a.Screens) {
return a.Screens[n]
}
return a.Screens[0]
}
func (a *AppMulti[W]) ScreenByName(name string) *system.Screen {
for _, sc := range a.Screens {
if sc.Name == name {
return sc
}
}
return nil
}
func (a *AppMulti[W]) NWindows() int {
a.Mu.Lock()
defer a.Mu.Unlock()
return len(a.Windows)
}
func (a *AppMulti[W]) Window(win int) system.Window {
a.Mu.Lock()
defer a.Mu.Unlock()
if win >= 0 && win < len(a.Windows) {
return a.Windows[win]
}
return nil
}
func (a *AppMulti[W]) WindowByName(name string) system.Window {
a.Mu.Lock()
defer a.Mu.Unlock()
for _, win := range a.Windows {
if win.Name() == name {
return win
}
}
return nil
}
func (a *AppMulti[W]) WindowInFocus() system.Window {
a.Mu.Lock()
defer a.Mu.Unlock()
for _, win := range a.Windows {
if win.Is(system.Focused) {
return win
}
}
return nil
}
func (a *AppMulti[W]) ContextWindow() system.Window {
a.Mu.Lock()
defer a.Mu.Unlock()
return a.CtxWindow
}
// RemoveWindow removes the given Window from the app's list of windows.
// It does not actually close it; see [Window.Close] for that.
func (a *AppMulti[W]) RemoveWindow(w system.Window) {
a.Mu.Lock()
defer a.Mu.Unlock()
a.Windows = slices.DeleteFunc(a.Windows, func(ew W) bool {
return system.Window(ew) == w
})
}
func (a *AppMulti[W]) QuitClean() bool {
a.Mu.Lock()
defer a.Mu.Unlock()
for _, qf := range a.QuitCleanFuncs {
qf()
}
nwin := len(a.Windows)
for i := nwin - 1; i >= 0; i-- {
win := a.Windows[i]
// CloseReq calls RemoveWindow, which also Locks, so we must Unlock
a.Mu.Unlock()
win.CloseReq()
a.Mu.Lock()
}
return len(a.Windows) == 0
}
// Copyright 2023 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on golang.org/x/exp/shiny:
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package base
import (
"image"
"cogentcore.org/core/events"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles/sides"
"cogentcore.org/core/system"
"cogentcore.org/core/system/composer"
)
// AppSingle contains the data and logic common to all implementations of [system.App]
// on single-window platforms (mobile and web), as opposed to multi-window
// platforms (desktop and offscreen), for which you should use [AppMulti]. An AppSingle is associated
// with a corresponding type of [composer.Composer] and [system.Window]. The [system.Window]
// type should embed [WindowSingle].
type AppSingle[C composer.Composer, W system.Window] struct {
App
// Event is the event manager for the app.
Event events.Source `label:"Events"`
// Compose is the single [composer.Composer] used for the app.
Compose C `label:"Composer"`
// Win is the single [system.Window] associated with the app.
Win W `label:"Window"`
// Scrn is the single [system.Screen] associated with the app.
Scrn *system.Screen `label:"Screen"`
// Insets are the size of any insets on the sides of the screen.
Insets sides.Sides[int]
}
// AppSingler describes the common functionality implemented by [AppSingle]
// apps that [WindowSingle] windows need to access.
type AppSingler interface {
system.App
// Events returns the single [events.Source] associated with this app.
Events() *events.Source
// Composer returns the single [composer.Composer] associated with this app.
Composer() composer.Composer
// RenderGeom returns the actual effective geometry of the window used
// for rendering content, which may be different from {0, [system.Screen.PixelSize]}
// due to insets caused by things like status bars and button overlays.
RenderGeom() math32.Geom2DInt
}
// NewAppSingle makes a new [AppSingle].
func NewAppSingle[C composer.Composer, W system.Window]() AppSingle[C, W] {
return AppSingle[C, W]{
Scrn: &system.Screen{Name: "main"},
}
}
func (a *AppSingle[C, W]) Events() *events.Source {
return &a.Event
}
func (a *AppSingle[C, W]) Composer() composer.Composer {
return a.Compose
}
func (a *AppSingle[C, W]) RenderGeom() math32.Geom2DInt {
pos := image.Pt(a.Insets.Left, a.Insets.Top)
return math32.Geom2DInt{
Pos: pos,
Size: a.Scrn.PixelSize.Sub(pos).Sub(image.Pt(a.Insets.Right, a.Insets.Bottom)),
}
}
func (a *AppSingle[C, W]) NScreens() int {
if a.Scrn != nil {
return 1
}
return 0
}
func (a *AppSingle[C, W]) Screen(n int) *system.Screen {
return a.Scrn
}
func (a *AppSingle[C, W]) ScreenByName(name string) *system.Screen {
if a.Scrn.Name == name {
return a.Scrn
}
return nil
}
// hasWindow returns whether the app has its window, which is a nil
// pointer (not a nil [system.Window]) before it is made.
func (a *AppSingle[C, W]) hasWindow() bool {
var none W
return any(a.Win) != any(none)
}
func (a *AppSingle[C, W]) NWindows() int {
a.Mu.Lock()
defer a.Mu.Unlock()
if a.hasWindow() {
return 1
}
return 0
}
func (a *AppSingle[C, W]) Window(win int) system.Window {
a.Mu.Lock()
defer a.Mu.Unlock()
if win == 0 && a.hasWindow() {
return a.Win
}
return nil
}
func (a *AppSingle[C, W]) WindowByName(name string) system.Window {
a.Mu.Lock()
defer a.Mu.Unlock()
if a.hasWindow() && a.Win.Name() == name {
return a.Win
}
return nil
}
func (a *AppSingle[C, W]) WindowInFocus() system.Window {
a.Mu.Lock()
defer a.Mu.Unlock()
if a.hasWindow() && a.Win.Is(system.Focused) {
return a.Win
}
return nil
}
func (a *AppSingle[C, W]) ContextWindow() system.Window {
a.Mu.Lock()
defer a.Mu.Unlock()
if !a.hasWindow() {
return nil
}
return a.Win
}
func (a *AppSingle[C, W]) RemoveWindow(w system.Window) {
// no-op
}
func (a *AppSingle[C, W]) QuitClean() bool {
a.Quitting = true
for _, qf := range a.QuitCleanFuncs {
qf()
}
a.Mu.Lock()
defer a.Mu.Unlock()
a.Win.Close()
return a.Win.IsClosed()
}
// Copyright 2023 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on golang.org/x/exp/shiny:
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package base
import "cogentcore.org/core/events"
// FuncRun is a simple helper type that contains a function to call and a channel
// to send a signal on when the function is finished running.
type FuncRun struct {
F func()
Done chan struct{}
}
// PendingKeys returns whether the given queue of events has key events
// that have not been handled yet, as for a virtual keyboard whose text is
// set (see [system.TextInput.Before]) only once the keys that it sent
// have been handled, as they change it.
func PendingKeys(q *events.Deque) bool {
q.LockAndInit()
defer q.Mu.Unlock()
for _, evs := range [][]events.Event{q.Front, q.Back} {
for _, e := range evs {
if _, ok := e.(*events.Key); ok {
return true
}
}
}
return false
}
// Copyright 2023 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on golang.org/x/exp/shiny:
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package base
import (
"fmt"
"image"
"sync"
"sync/atomic"
"time"
"cogentcore.org/core/base/fileinfo/mimedata"
"cogentcore.org/core/events"
"cogentcore.org/core/math32"
"cogentcore.org/core/system"
)
// Window contains the data and logic common to all implementations of [system.Window].
// A Window is associated with a corresponding [system.App] type.
type Window[A system.App] struct {
// This is the Window as a [system.Window] interface, which preserves the actual identity
// of the window when calling interface methods in the base Window.
This system.Window `display:"-"`
// App is the [system.App] associated with the window.
App A
// Mu is the main mutex protecting access to window operations, including [Window.RunOnWin] functions.
Mu sync.Mutex `display:"-"`
// WinClose is a channel on which a single is sent to indicate that the
// window should close.
WinClose chan struct{} `display:"-"`
// closing is set when the window starts closing (see [Window.MarkClosing]).
closing atomic.Bool
// closed is set when the window is closed (see [Window.MarkClosed]),
// for platforms whose [system.Window.IsClosed] uses it.
closed atomic.Bool
// CloseReqFunc is the function to call on a close request
CloseReqFunc func(win system.Window)
// CloseCleanFunc is the function to call to close the window
CloseCleanFunc func(win system.Window)
// Nm is the name of the window
Nm string `label:"Name"`
// Titl is the title of the window
Titl string `label:"Title"`
// titleMu protects [Window.Titl], which is set by the event loops
// of the stages of windows (see [Window.SetTitle]).
titleMu sync.Mutex
// Flgs contains the flags associated with the window
Flgs system.WindowFlags `label:"Flags" table:"-"`
// DestroyGPUFunc should be set to a function that will destroy GPU resources
// in the main thread prior to destroying the drawer
// and the surface; otherwise it is difficult to
// ensure that the proper ordering of destruction applies.
DestroyGPUFunc func()
// CursorEnabled is whether the cursor is currently enabled
CursorEnabled bool
// Paint is the state of the paint events of the window: whether
// they are paused while it is idle (see [system.Window.PaintIdle]).
Paint *PaintState `display:"-"`
}
// PaintState is the state of the paint events of a window, which are
// paused while it is idle (see [system.Window.PaintIdle]), until it is
// woken (see [system.Window.PaintWake]).
type PaintState struct {
// idle is whether the paint events are paused.
idle atomic.Bool
// wake receives a value when the window is woken while idle.
wake chan struct{}
}
// NewPaintState returns a new [PaintState].
func NewPaintState() *PaintState {
return &PaintState{wake: make(chan struct{}, 1)}
}
// SetIdle pauses the paint events.
func (ps *PaintState) SetIdle() {
ps.idle.Store(true)
}
// Wake resumes the paint events, if paused. It can be called from any
// goroutine, and does not block.
func (ps *PaintState) Wake() {
if ps.idle.Swap(false) {
select {
case ps.wake <- struct{}{}:
default:
}
}
}
// IsIdle returns whether the paint events are paused.
func (ps *PaintState) IsIdle() bool {
return ps.idle.Load()
}
// Woken returns the channel that receives a value when the window is
// woken while idle.
func (ps *PaintState) Woken() <-chan struct{} {
return ps.wake
}
// NewWindow makes a new [Window] for the given app with the given options.
func NewWindow[A system.App](a A, opts *system.NewWindowOptions) Window[A] {
return Window[A]{
WinClose: make(chan struct{}),
App: a,
Titl: opts.GetTitle(),
Flgs: opts.Flags,
CursorEnabled: true,
Paint: NewPaintState(),
}
}
// WinLoop runs the window's own locked processing loop, which sends it
// paint events at the refresh rate of its screen, except while it is idle
// (see [system.Window.PaintIdle]).
func (w *Window[A]) WinLoop() {
defer func() { system.HandleRecover(recover()) }()
fps := w.This.Screen().RefreshRate
if fps <= 0 {
fps = 60
}
dur := time.Second / time.Duration(fps)
winPaint := time.NewTicker(dur)
defer winPaint.Stop()
for {
// While idle, the ticker is stopped, so that an idle app does not
// use the CPU (as on mobile, in the background), until woken.
if w.Paint.IsIdle() {
winPaint.Stop()
select {
case <-w.WinClose:
return
case <-w.Paint.Woken():
}
winPaint.Reset(dur)
w.This.SendPaintEvent() // right away
continue
}
select {
case <-w.WinClose:
return
case <-w.Paint.Woken(): // (woken before it was idle)
case <-winPaint.C:
if w.This.IsClosed() {
fmt.Println("win IsClosed in paint:", w.Name())
return
}
w.This.SendPaintEvent()
}
}
}
// PaintIdle pauses the paint events of the window until [Window.PaintWake].
func (w *Window[A]) PaintIdle() {
w.Paint.SetIdle()
}
// PaintWake resumes the paint events of the window, if paused.
func (w *Window[A]) PaintWake() {
w.Paint.Wake()
}
// PaintIsIdle returns whether the paint events of the window are paused
// (see [Window.PaintIdle]).
func (w *Window[A]) PaintIsIdle() bool {
return w.Paint.IsIdle()
}
func (w *Window[A]) SendPaintEvent() {
w.This.Events().WindowPaint()
}
func (w *Window[A]) Lock() bool {
if w.This.IsClosed() {
return false
}
w.Mu.Lock()
return true
}
func (w *Window[A]) Unlock() {
w.Mu.Unlock()
}
func (w *Window[A]) Name() string {
return w.Nm
}
func (w *Window[A]) SetName(name string) {
w.Nm = name
}
func (w *Window[A]) Title() string {
w.titleMu.Lock()
defer w.titleMu.Unlock()
return w.Titl
}
func (w *Window[A]) SetTitle(title string) {
if w.This.IsClosed() {
return
}
w.titleMu.Lock()
w.Titl = title
w.titleMu.Unlock()
}
func (w *Window[A]) SetIcon(images []image.Image) {
// no-op by default
}
func (w *Window[A]) Raise() {
// no-op by default
}
func (w *Window[A]) Minimize() {
// no-op by default
}
func (w *Window[A]) Hide() {
// no-op by default
}
func (w *Window[A]) Flags() system.WindowFlags {
return w.Flgs
}
func (w *Window[A]) Is(flag system.WindowFlags) bool {
return w.Flgs.HasFlag(flag)
}
func (w *Window[A]) IsClosed() bool {
return w == nil || w.This == nil || w.This.Composer() == nil
}
func (w *Window[A]) IsVisible() bool {
return !w.This.IsClosed() && !w.Is(system.Minimized)
}
func (w *Window[A]) SetDestroyGPUResourcesFunc(f func()) {
w.DestroyGPUFunc = f
}
func (w *Window[A]) RenderGeom() math32.Geom2DInt {
// {0, Size} by default
return math32.Geom2DInt{Size: w.This.Size()}
}
func (w *Window[A]) SetCloseReqFunc(fun func(win system.Window)) {
w.Mu.Lock()
defer w.Mu.Unlock()
w.CloseReqFunc = fun
}
func (w *Window[A]) SetCloseCleanFunc(fun func(win system.Window)) {
w.Mu.Lock()
defer w.Mu.Unlock()
w.CloseCleanFunc = fun
}
func (w *Window[A]) CloseReq() {
if w.CloseReqFunc != nil {
w.CloseReqFunc(w.This)
} else {
w.This.Close()
}
}
func (w *Window[A]) CloseClean() {
if w.CloseCleanFunc != nil {
w.CloseCleanFunc(w.This)
}
}
// Close closes the window, once: it does nothing if the window is already
// closing, as it can be asked to close again then (as by
// [Window.CloseReq] from another goroutine).
func (w *Window[A]) Close() {
if !w.MarkClosing() {
return
}
w.CloseBase()
}
// MarkClosing marks the window as closing, returning false if it was
// already closing, so that a Close method of a platform does its closing
// only once, and then calls [Window.CloseBase].
func (w *Window[A]) MarkClosing() bool {
return w.closing.CompareAndSwap(false, true)
}
// MarkClosed marks the window as closed, for platforms whose
// [system.Window.IsClosed] uses [Window.IsMarkedClosed], which, unlike
// [Window.IsClosed] (based on the composer), can be called from any
// goroutine while the window is being closed, without holding [Window.Mu].
func (w *Window[A]) MarkClosed() {
w.closed.Store(true)
}
// IsMarkedClosed returns whether the window has been marked as closed
// by [Window.MarkClosed].
func (w *Window[A]) IsMarkedClosed() bool {
return w.closed.Load()
}
// CloseBase does the closing of the window by the base implementation,
// for [Window.Close] after [Window.MarkClosing].
func (w *Window[A]) CloseBase() {
// base implementation doesn't actually close any system windows,
// but platform-specific implementations can.
// The window is removed from the app before its WinClose event is sent:
// the event stops the event loop of the window (in core), and the app
// quits once the loops of all of its windows stop, which fails while a
// closing window is still in the app (see [AppMulti.QuitClean]).
w.Mu.Lock()
w.CloseClean()
w.App.RemoveWindow(w.This)
w.Mu.Unlock()
w.This.Events().Window(events.WinClose)
w.WinClose <- struct{}{}
}
func (w *Window[A]) SetCursorEnabled(enabled, raw bool) {
w.CursorEnabled = enabled
}
func (w *Window[A]) IsCursorEnabled() bool {
return w.CursorEnabled
}
func (w *Window[A]) SetMousePos(x, y float64) {
// no-op by default
}
func (w *Window[A]) SetTitleBarIsDark(isDark bool) {
// no-op by default
}
func (w *Window[A]) StartDrag(data mimedata.Mimes, files []string, img image.Image) bool {
return false // not supported by default
}
func (w *Window[A]) DragAccepted() bool {
return true // not known by default
}
func (w *Window[A]) SetTextInput(ti *system.TextInput) {
// no-op by default
}
// Copyright 2023 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on golang.org/x/exp/shiny:
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package base
import (
"image"
"sync"
"cogentcore.org/core/events"
"cogentcore.org/core/styles/sides"
"cogentcore.org/core/system"
"cogentcore.org/core/system/composer"
)
// WindowMulti contains the data and logic common to all implementations of [system.Window]
// on multi-window platforms (desktop and offscreen), as opposed to single-window
// platforms (mobile and web), for which you should use [WindowSingle].
// A WindowMulti is associated with a corresponding [system.App] type.
// The [system.App] type should embed [AppMulti].
type WindowMulti[A system.App, C composer.Composer] struct {
Window[A]
// Event is the event manager for the window
Event events.Source `label:"Event manger"`
// Compose is the [composer.Composer] for this window.
Compose C `label:"Composer"`
// GeomMu protects the geometry fields of the window ([WindowMulti.Pos],
// [WindowMulti.WnSize], and [WindowMulti.PixelSize]), which goroutines
// such as the event loop and the content sizing of scenes read and set
// concurrently. It is separate from [Window.Mu], which is held during
// rendering and resizing, when they are also read (as by
// [Window.RenderGeom]), so it is only held for each read or write of
// them, without acquiring any other lock.
// [WindowMulti.LogDPI] and [WindowMulti.DevicePixelRatio] are written
// holding both [Window.Mu] and GeomMu, so that they can be read holding
// either one (GeomMu where Mu could already be held, as by event handling).
GeomMu sync.Mutex `display:"-"`
// Pos is the position of the window
Pos image.Point `label:"Position"`
// WnSize is the size of the window in window manager coordinates
WnSize image.Point `label:"Window manager size"`
// PixelSize is the pixel size of the window in raw display dots
PixelSize image.Point `label:"Pixel size"`
// FrameSize of the window frame: Min = left, top; Max = right, bottom.
FrameSize sides.Sides[int]
// DevicePixelRatio is a factor that scales the screen's
// "natural" pixel coordinates into actual device pixels.
// On OS-X, it is backingScaleFactor = 2.0 on "retina"
DevicePixelRatio float32
// PhysicalDPI is the physical dots per inch of the screen,
// for generating true-to-physical-size output.
// It is computed as 25.4 * (PixelSize.X / PhysicalSize.X)
// where 25.4 is the number of mm per inch.
PhysDPI float32 `label:"Physical DPI"`
// LogicalDPI is the logical dots per inch of the screen,
// which is used for all rendering.
// It is: transient zoom factor * screen-specific multiplier * PhysicalDPI
LogDPI float32 `label:"Logical DPI"`
}
// NewWindowMulti makes a new [WindowMulti] for the given app with the given options.
func NewWindowMulti[A system.App, C composer.Composer](a A, opts *system.NewWindowOptions) WindowMulti[A, C] {
return WindowMulti[A, C]{
Window: NewWindow(a, opts),
}
}
func (w *WindowMulti[A, D]) Composer() composer.Composer {
// a nil composer pointer, set when the window is closed, is a nil
// Composer, so that the window is closed (see [Window.IsClosed])
var none D
if any(w.Compose) == any(none) {
return nil
}
return w.Compose
}
func (w *WindowMulti[A, D]) Events() *events.Source {
return &w.Event
}
// Size returns the pixel size of the window. It uses [WindowMulti.GeomMu],
// not [Window.Mu], which its callers can hold (such as rendering).
func (w *WindowMulti[A, D]) Size() image.Point {
w.GeomMu.Lock()
defer w.GeomMu.Unlock()
return w.PixelSize
}
func (w *WindowMulti[A, D]) WinSize() image.Point {
w.GeomMu.Lock()
defer w.GeomMu.Unlock()
return w.WnSize
}
func (w *WindowMulti[A, D]) Position(screen *system.Screen) image.Point {
w.GeomMu.Lock()
defer w.GeomMu.Unlock()
return w.Pos
}
func (w *WindowMulti[A, D]) PhysicalDPI() float32 {
w.Mu.Lock()
defer w.Mu.Unlock()
return w.PhysDPI
}
func (w *WindowMulti[A, D]) LogicalDPI() float32 {
w.Mu.Lock()
defer w.Mu.Unlock()
return w.LogDPI
}
func (w *WindowMulti[A, D]) SetLogicalDPI(dpi float32) {
w.Mu.Lock()
defer w.Mu.Unlock()
w.GeomMu.Lock()
w.LogDPI = dpi
w.GeomMu.Unlock()
}
// ScaleDPI returns the [WindowMulti.LogDPI] and
// [WindowMulti.DevicePixelRatio] of the window, using
// [WindowMulti.GeomMu], so it can be called while [Window.Mu] is held.
func (w *WindowMulti[A, D]) ScaleDPI() (logicalDPI, devicePixelRatio float32) {
w.GeomMu.Lock()
defer w.GeomMu.Unlock()
return w.LogDPI, w.DevicePixelRatio
}
func (w *WindowMulti[A, D]) SetWinSize(sz image.Point) {
if w.This.IsClosed() {
return
}
w.GeomMu.Lock()
w.WnSize = sz
w.GeomMu.Unlock()
}
func (w *WindowMulti[A, D]) SetSize(sz image.Point) {
if w.This.IsClosed() {
return
}
sc := w.This.Screen()
sz = sc.WindowSizeFromPixels(sz)
w.SetWinSize(sz)
}
func (w *WindowMulti[A, D]) SetPos(pos image.Point, screen *system.Screen) {
if w.This.IsClosed() {
return
}
w.GeomMu.Lock()
w.Pos = pos
w.GeomMu.Unlock()
}
func (w *WindowMulti[A, D]) SetGeometry(fullscreen bool, pos image.Point, size image.Point, screen *system.Screen) {
if w.This.IsClosed() {
return
}
sc := w.This.Screen()
size = sc.WindowSizeFromPixels(size)
w.SetWinSize(size)
w.GeomMu.Lock()
w.Pos = pos
w.GeomMu.Unlock()
}
func (w *WindowMulti[A, D]) ConstrainFrame(topOnly bool) sides.Sides[int] {
// no-op
return sides.Sides[int]{}
}
func (w *WindowMulti[A, D]) IsVisible() bool {
return w.Window.IsVisible() && w.App.NScreens() != 0
}
// Copyright 2023 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on golang.org/x/exp/shiny:
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package base
import (
"image"
"cogentcore.org/core/events"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles/sides"
"cogentcore.org/core/system"
"cogentcore.org/core/system/composer"
)
// WindowSingle contains the data and logic common to all implementations of [system.Window]
// on single-window platforms (mobile and web), as opposed to multi-window
// platforms (desktop and offscreen), for which you should use [WindowSingle].
// A WindowSingle is associated with a corresponding [AppSingler] type.
type WindowSingle[A AppSingler] struct {
Window[A]
}
// NewWindowSingle makes a new [WindowSingle] for the given app with the given options.
func NewWindowSingle[A AppSingler](a A, opts *system.NewWindowOptions) WindowSingle[A] {
return WindowSingle[A]{
NewWindow(a, opts),
}
}
func (w *WindowSingle[A]) Events() *events.Source {
return w.App.Events()
}
func (w *WindowSingle[A]) Composer() composer.Composer {
return w.App.Composer()
}
func (w *WindowSingle[A]) Screen() *system.Screen {
return w.App.Screen(0)
}
func (w *WindowSingle[A]) Size() image.Point {
// w.Mu.Lock() // this prevents race conditions but also locks up
// defer w.Mu.Unlock()
return w.Screen().PixelSize
}
func (w *WindowSingle[A]) WinSize() image.Point {
// w.Mu.Lock() // this prevents race conditions but also locks up
// defer w.Mu.Unlock()
return w.Screen().PixelSize
}
func (w *WindowSingle[A]) Position(screen *system.Screen) image.Point {
// w.Mu.Lock()
// defer w.Mu.Unlock()
return image.Point{}
}
func (w *WindowSingle[A]) PhysicalDPI() float32 {
w.Mu.Lock()
defer w.Mu.Unlock()
return w.Screen().PhysicalDPI
}
func (w *WindowSingle[A]) LogicalDPI() float32 {
w.Mu.Lock()
defer w.Mu.Unlock()
return w.Screen().LogicalDPI
}
func (w *WindowSingle[A]) SetLogicalDPI(dpi float32) {
w.Mu.Lock()
defer w.Mu.Unlock()
w.Screen().LogicalDPI = dpi
}
func (w *WindowSingle[A]) SetWinSize(sz image.Point) {
if w.This.IsClosed() {
return
}
w.Screen().PixelSize = sz
}
func (w *WindowSingle[A]) SetSize(sz image.Point) {
if w.This.IsClosed() || w.App.Platform().IsMobile() {
return
}
w.Screen().PixelSize = sz
}
func (w *WindowSingle[A]) SetPos(pos image.Point, screen *system.Screen) {
// no-op
}
func (w *WindowSingle[A]) SetGeometry(fullscreen bool, pos image.Point, size image.Point, screen *system.Screen) {
// mostly no-op
w.Flgs.SetFlag(fullscreen, system.Fullscreen)
}
func (w *WindowSingle[A]) ConstrainFrame(topOnly bool) sides.Sides[int] {
// no-op
return sides.Sides[int]{}
}
func (w *WindowSingle[A]) RenderGeom() math32.Geom2DInt {
return w.App.RenderGeom()
}
// Copyright 2019 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// based on golang.org/x/exp/shiny:
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package desktop
import (
"errors"
"image"
"log"
"runtime"
"slices"
"sync"
"sync/atomic"
"cogentcore.org/core/gpu"
"cogentcore.org/core/gpu/gpudraw"
"cogentcore.org/core/gpu/wgpuglfw"
"cogentcore.org/core/system"
"cogentcore.org/core/system/composer"
"cogentcore.org/core/system/driver/base"
"github.com/cogentcore/glfw4/v3.4/glfw"
)
// Init sets up the desktop app. The windowing system is initialized
// when it is first needed (see [App.initGUI]).
func Init() {
// some operating systems require us to be on the main thread
runtime.LockOSThread()
setMainThread()
base.Init(TheApp, &TheApp.App)
}
// hideNewWindows is whether new windows are not shown, which the tests set,
// so that they do not pop up on the screen of the user running them.
var hideNewWindows bool
// TheApp is the single [system.App] for the desktop platform
var TheApp = &App{AppMulti: base.NewAppMulti[*Window]()}
// App is the [system.App] implementation for the desktop platform
type App struct {
base.AppMulti[*Window]
// GPU is the system GPU used for the app
GPU *gpu.GPU
// Monitors are pointers to the glfw monitors corresponding to Screens.
Monitors []*glfw.Monitor
// dark is whether the system color theme is dark; see [App.IsDark].
dark atomic.Bool
// guiOnce initializes the windowing system once (see [App.initGUI]).
guiOnce sync.Once
// guiDone is whether the windowing system has been initialized.
guiDone atomic.Bool
// guiInitializing is whether the windowing system is being initialized,
// during which the calls of [App.initGUI] on the main thread, as for the
// screens when they are updated, return at once.
guiInitializing atomic.Bool
}
// initGUI initializes the windowing system (glfw), the screens, and the
// theme watcher the first time that they are needed, as for the first
// window or the information about the screens, instead of when the
// program starts, so that a program that does not use the GUI, such as
// a server, does not initialize it, which gives it a dock icon on macOS.
// Like glfw, it runs on the main thread: in [App.MainLoop], which calls
// it first, so that it is done once the main loop runs, and before that,
// on the main goroutine, which [Init] locks to the main thread.
func (a *App) initGUI() {
if a.guiDone.Load() || (a.guiInitializing.Load() && onMainThread()) {
return
}
a.guiOnce.Do(func() {
if !onMainThread() {
panic("system/driver/desktop: the GUI must first be used on the main goroutine, as for the first window or screen information, before the main loop runs")
}
a.guiInitializing.Store(true)
defer a.guiInitializing.Store(false)
a.InitGPU()
a.watchTheme()
a.guiDone.Store(true)
})
}
// NScreens returns the number of screens, initializing the windowing system
// if needed (see [App.initGUI]).
func (a *App) NScreens() int {
a.initGUI()
return a.AppMulti.NScreens()
}
// Screen returns the given screen, initializing the windowing system
// if needed (see [App.initGUI]).
func (a *App) Screen(n int) *system.Screen {
a.initGUI()
return a.AppMulti.Screen(n)
}
// ScreenByName returns the screen with the given name, initializing the
// windowing system if needed (see [App.initGUI]).
func (a *App) ScreenByName(name string) *system.Screen {
a.initGUI()
return a.AppMulti.ScreenByName(name)
}
// SendEmptyEvent sends an empty, blank event to global event processing
// system, which has the effect of pushing the system along during cases when
// the event loop needs to be "pinged" to get things moving along..
func (a *App) SendEmptyEvent() {
if !a.guiDone.Load() {
return // no event loop yet
}
glfw.PostEmptyEvent()
}
// MainLoop starts running event loop on main thread (must be called
// from the main thread).
func (a *App) MainLoop() {
a.initGUI()
a.MainQueue = make(chan base.FuncRun)
a.InitMainDone()
for {
select {
case <-a.MainDone:
glfw.Terminate()
return
case f := <-a.MainQueue:
f.F()
if f.Done != nil {
f.Done <- struct{}{}
}
default:
glfw.WaitEventsTimeout(0.1) // timeout is essential on linux
// (here, not with the paint events of the windows, which are
// paused while they are idle; and glfw is used on the main thread)
a.PollScreenChanges()
}
}
}
// InitGPU initializes glfw, gpu, and the screens.
func (a *App) InitGPU() {
restore := imeInitApp()
if err := glfw.Init(); err != nil {
log.Fatalln("system/driver/desktop failed to initialize glfw:", err)
}
restore()
glfw.SetMonitorCallback(a.MonitorChange)
a.GetScreens()
}
func (a *App) NewWindow(opts *system.NewWindowOptions) (system.Window, error) {
a.initGUI()
if len(a.Windows) == 0 && system.UpdateLogicalDPIScaleFunc != nil {
if ScreenDebug {
log.Println("app first new window calling UpdateLogicalDPIScaleFunc")
}
system.UpdateLogicalDPIScaleFunc()
}
// glfw can find no monitors, as with an X display without RandR outputs
if len(a.Screens) == 0 {
return nil, errors.New("system/driver/desktop: no screens to open a window on")
}
sc := a.Screens[0]
if opts == nil {
opts = &system.NewWindowOptions{}
}
opts.Fixup()
// can also apply further tuning here..
if opts.Screen > 0 && opts.Screen < len(a.Screens) {
sc = a.Screens[opts.Screen]
}
w := &Window{
WindowMulti: base.NewWindowMulti[*App, *composer.ComposerDrawer](a, opts),
ScreenWindow: sc.Name,
}
w.This = w
var err error
a.RunOnMain(func() {
err = w.newGlfwWindow(opts, sc)
})
if err != nil {
return nil, err
}
a.RunOnMain(func() {
surf := gpu.Instance().CreateSurface(wgpuglfw.GetSurfaceDescriptor(w.Glw))
var fbsz image.Point
fbsz.X, fbsz.Y = w.Glw.GetFramebufferSize()
if fbsz == (image.Point{}) {
fbsz = opts.Size
}
if a.GPU == nil {
a.GPU = gpu.NewGPU(surf)
}
// no multisample and no depth
sf := gpu.NewSurface(a.GPU, surf, fbsz, 1, gpu.UndefinedType)
w.Draw = gpudraw.NewDrawer(a.GPU, sf)
w.Compose = &composer.ComposerDrawer{Drawer: w.Draw}
})
// w.Flgs.SetFlag(true, system.Focused) // starts out focused
a.Mu.Lock()
a.Windows = append(a.Windows, w)
a.Mu.Unlock()
w.Glw.SetPosCallback(w.Moved)
w.Glw.SetSizeCallback(w.WinResized)
w.Glw.SetFramebufferSizeCallback(w.FbResized)
w.Glw.SetCloseCallback(w.OnCloseReq)
// w.Glw.SetRefreshCallback(w.refresh)
w.Glw.SetFocusCallback(w.Focused)
w.Glw.SetIconifyCallback(w.Iconify)
w.Glw.SetKeyCallback(w.KeyEvent)
w.Glw.SetCharModsCallback(w.CharEvent)
w.Glw.SetMouseButtonCallback(w.MouseButtonEvent)
w.Glw.SetScrollCallback(w.ScrollEvent)
w.Glw.SetCursorPosCallback(w.CursorPosEvent)
w.Glw.SetCursorEnterCallback(w.CursorEnterEvent)
w.Glw.SetDropCallback(w.DropEvent)
w.Glw.SetInputMode(glfw.LockKeyMods, glfw.True)
if !hideNewWindows {
w.Show()
}
a.RunOnMain(func() {
w.updateGeometry()
w.ConstrainFrame(false) // constrain full frame on open
})
go w.WinLoop() // start window's own dedicated publish update loop
return w, nil
}
func (a *App) Clipboard(win system.Window) system.Clipboard {
a.setContext(win)
return TheClipboard
}
func (a *App) Cursor(win system.Window) system.Cursor {
a.setContext(win)
return TheCursor
}
// setContext sets [App.CtxWindow] to the given window, if it is one,
// or else keeps the last one, as for the clipboard of a widget whose
// window has closed, such as a snackbar (which was a panic while
// holding [App.Mu], which hung the app in the crash dialog).
func (a *App) setContext(win system.Window) {
w, ok := win.(*Window)
if !ok || w == nil {
return
}
a.Mu.Lock()
a.CtxWindow = w
a.Mu.Unlock()
}
// ShowHidden shows the windows hidden by [Window.Hide] again, as when the
// app's dock icon is clicked on macOS.
func (a *App) ShowHidden() {
a.Mu.Lock()
wins := slices.Clone(a.Windows)
a.Mu.Unlock()
var hidden []*Window
a.RunOnMain(func() {
for _, w := range wins {
if w.hidden {
hidden = append(hidden, w)
}
}
})
for _, w := range hidden {
w.Raise()
}
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !darwin
package desktop
import "image"
// setAppIcon does nothing: the windows have the icons (see [Window.SetIcon]),
// which are only set as the app icon on macOS.
func setAppIcon(images []image.Image) {}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build linux && !android
package desktop
import (
"os"
"path/filepath"
"strconv"
"strings"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/strcase"
"github.com/godbus/dbus/v5"
)
// The D-Bus names of the launcher entry API of Unity, which the docks and
// task managers of several desktops implement for the badges of the icons
// of apps (Ubuntu Dock, Dash to Dock, KDE Plasma, and others).
const (
launcherEntryPath = "/org/cogentcore/LauncherEntry"
launcherEntryUpdate = "com.canonical.Unity.LauncherEntry.Update"
)
// SetBadge sets the badge of the app's icon in the dock or task manager,
// as a count, with the launcher entry API of Unity, which only supports
// numbers: a label that is not a number removes the badge, as an empty one
// does. The app is identified by its desktop file (see [desktopFileID]).
func (a *App) SetBadge(label string) {
conn, err := dbus.SessionBus()
if errors.Log(err) != nil {
return
}
uri, props := launcherEntry(desktopFileID(a.Name()), label)
errors.Log(conn.Emit(launcherEntryPath, launcherEntryUpdate, uri, props))
}
// launcherEntry returns the app URI and the properties of the update
// signal of the launcher entry API for the given desktop file ID and badge.
func launcherEntry(id, label string) (string, map[string]dbus.Variant) {
n, err := strconv.ParseInt(label, 10, 64)
visible := err == nil
if !visible {
n = 0
}
return "application://" + id, map[string]dbus.Variant{
"count": dbus.MakeVariant(n),
"count-visible": dbus.MakeVariant(visible),
}
}
// desktopFileID returns the ID of the desktop file of the app with the
// given name: that of the desktop file it was launched from, if the
// launcher says (GIO_LAUNCHED_DESKTOP_FILE, BAMF_DESKTOP_FILE_HINT), and
// otherwise the name in kebab case, as "cogent-mail.desktop", the name of
// the desktop file that core pack makes.
func desktopFileID(name string) string {
for _, env := range []string{"GIO_LAUNCHED_DESKTOP_FILE", "BAMF_DESKTOP_FILE_HINT"} {
if f := os.Getenv(env); strings.HasSuffix(f, ".desktop") {
return filepath.Base(f)
}
}
return strcase.ToKebab(name) + ".desktop"
}
// Copyright 2023 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package desktop
import (
"sync"
"cogentcore.org/core/cursors/cursorimg"
"cogentcore.org/core/enums"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/system"
"github.com/cogentcore/glfw4/v3.4/glfw"
)
// TheCursor is the single [system.Cursor] for the desktop platform
var TheCursor = &Cursor{Vis: true, Size: units.Dp(32), cursors: map[enums.Enum]map[int]*glfw.Cursor{}}
// Cursor is the [cursor.Cursor] implementation for the desktop platform
type Cursor struct {
system.CursorBase
// cursors are the cached glfw cursors
cursors map[enums.Enum]map[int]*glfw.Cursor
// mu is a mutex protecting access to the cursors
mu sync.Mutex
// prevSize is the cached previous size
prevSize int
// unitContext is the unit context used for converting the cursor size to dots.
unitContext *units.Context
}
func (cu *Cursor) Set(cursor enums.Enum) error {
cu.mu.Lock()
defer cu.mu.Unlock()
if cu.unitContext == nil {
cu.unitContext = &units.Context{}
cu.unitContext.Defaults()
}
dpi, dpr := TheApp.CtxWindow.ScaleDPI()
cu.unitContext.DPI = dpi
if TheApp.Platform() == system.MacOS {
// The DPR is automatically applied to cursors on macOS already, so we cannot apply it here.
cu.unitContext.DPI /= dpr
}
// If the cursorimg cache got cleared (probably due to a theme change),
// we have to clear our cache as well.
if cursorimg.NumCached() == 0 {
clear(cu.cursors)
cu.prevSize = 0
}
sizef := cu.Size.ToDots(cu.unitContext)
// Multiples of 2 are less blurry on macOS Retina displays
// (TODO: make cursors less blurry on macOS Retina displays:
// https://github.com/cogentcore/core/issues/1373).
size := int(math32.Round(sizef/2) * 2)
if cursor == cu.Cur && size == cu.prevSize { // we already have, so we don't need to set again
return nil
}
sm := cu.cursors[cursor]
if sm == nil {
sm = map[int]*glfw.Cursor{}
cu.cursors[cursor] = sm
}
if cur, ok := sm[size]; ok {
TheApp.CtxWindow.Glw.SetCursor(cur)
cu.prevSize = size
cu.Cur = cursor
return nil
}
ci, err := cursorimg.Get(cursor, size)
if err != nil {
return err
}
h := ci.Hotspot
gc := glfw.CreateCursor(ci.Image, h.X, h.Y)
sm[size] = gc
TheApp.CtxWindow.Glw.SetCursor(gc)
cu.prevSize = size
cu.Cur = cursor
return nil
}
// Copyright 2018 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build (linux && !android) || dragonfly || openbsd
package desktop
import (
"log"
"os/exec"
"os/user"
"path/filepath"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/fileinfo/mimedata"
"cogentcore.org/core/system"
"github.com/cogentcore/glfw4/v3.4/glfw"
)
// Notes on intermixing glfw and xgb: bottom line, can't do:
//
// can include Xlib-xcb.h to get XGetXCBConnection method, which can get the
// xcb_connection from the Display: https://xcb.freedesktop.org/MixingCalls/
// which glfw can return, in GetX11Display().
// BUT, BurntSushi/xgb does NOT seem to directly use the xcb_connection
// and instead is a complete ground-up rewrite using net.Conn connection protocol
// not sure if we can have 2 separate connections..
// and really, maybe we don't need it after all!? just use the
// text-based clipboard mechanisms to write mime-encoded content, and
// cursor impl has full support for creating new cursors, so..
/////////////////////////////////////////////////////////////////
// OS-specific methods
func (a *App) Platform() system.Platforms {
return system.Linux
}
func (a *App) OpenURL(url string) {
cmd := exec.Command("xdg-open", url)
errors.Log(cmd.Run())
}
func (a *App) DataDir() string {
usr, err := user.Current()
if err != nil {
log.Print(err)
return "/tmp"
}
return filepath.Join(usr.HomeDir, ".config")
}
/////////////////////////////////////////////////////////////////
// Clipboard
// TheClipboard is the single [system.Clipboard] for Linux
var TheClipboard = &Clipboard{}
// Clipboard is the [system.Clipboard] implementation for Linux
type Clipboard struct{}
func (cl *Clipboard) IsEmpty() bool {
return false // todo: GetClipboardString hangs with some
// non-zero probability and this call spams the thing
// so we just bail here with a permissive not-empty.
return len(glfw.GetClipboardString()) == 0
}
// The clipboard is used on the main thread, as glfw requires.
func (cl *Clipboard) Read(types []string) mimedata.Mimes {
var str string
TheApp.RunOnMain(func() {
str = glfw.GetClipboardString()
})
if len(str) == 0 {
return nil
}
wantText := mimedata.IsText(types[0])
if wantText {
bstr := []byte(str)
isMulti, mediaType, boundary, body := mimedata.IsMultipart(bstr)
if isMulti {
return mimedata.FromMultipart(body, boundary)
}
if mediaType != "" { // found a mime type encoding
return mimedata.NewMime(mediaType, bstr)
}
// we can't really figure out type, so just assume..
return mimedata.NewMime(types[0], bstr)
} else {
// todo: deal with image formats etc
}
return nil
}
func (cl *Clipboard) Write(data mimedata.Mimes) error {
if len(data) == 0 {
return nil
}
var str string
if len(data) > 1 { // multipart
str = string(data.ToMultipart())
} else if d := data[0]; mimedata.IsText(d.Type) {
str = string(d.Data)
} else {
return nil
}
TheApp.RunOnMain(func() {
glfw.SetClipboardString(str)
})
return nil
}
func (cl *Clipboard) Clear() {
// nop
}
// Copyright 2026 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package desktop
import (
"bytes"
"image"
"image/png"
"sync"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/fileinfo/mimedata"
"cogentcore.org/core/events"
"cogentcore.org/core/events/key"
)
// Drag-and-drop with other windows and apps: the platform code starts
// drags from a window with [Window.StartDrag] (with the data from
// [dragData]), and sends drags over the windows of the app with
// [Window.dragMove] and [Window.dragDrop], for the window found with
// [dragWindow] from its native handle.
// dragWindows maps the native handle of each window (NSWindow,
// HWND or X11 Window) to the window, for the drag-and-drop callbacks.
var dragWindows = struct {
sync.Mutex
m map[uintptr]*Window
}{m: map[uintptr]*Window{}}
// addDragWindow adds the window with the given native handle.
func addDragWindow(id uintptr, w *Window) {
dragWindows.Lock()
dragWindows.m[id] = w
dragWindows.Unlock()
}
// deleteDragWindow deletes the window with the given native handle.
func deleteDragWindow(id uintptr) {
dragWindows.Lock()
delete(dragWindows.m, id)
dragWindows.Unlock()
}
// dragWindow returns the window with the given native handle, or nil.
func dragWindow(id uintptr) *Window {
dragWindows.Lock()
defer dragWindows.Unlock()
return dragWindows.m[id]
}
// dragData returns the data provided to other apps for a drag of
// the given data: unless there are files, the mime data as multipart
// MIME (for other Cogent Core apps), and its first text item as text.
func dragData(data mimedata.Mimes, files []string) (mime, text []byte) {
if len(files) > 0 {
return
}
mime = data.ToMultipart()
for _, d := range data {
if mimedata.IsText(d.Type) {
text = d.Data
break
}
}
return
}
// dragImagePNG returns the given drag image as PNG data.
func dragImagePNG(img image.Image) []byte {
if img == nil {
return nil
}
var b bytes.Buffer
if errors.Log(png.Encode(&b, img)) != nil {
return nil
}
return b.Bytes()
}
// dragMove sends a drag over the window to the window, at the given
// position in window (pixel) coordinates, or leaving the window.
func (w *Window) dragMove(leave bool, where image.Point, mods key.Modifiers, fromApp bool) {
typ := events.DragMove
if leave {
typ = events.DragLeave
}
w.Event.DragExternal(typ, where, mods, nil, fromApp)
}
// dragDrop sends a drop on the window to the window, with either
// files, or multipart mime data from [dragData].
func (w *Window) dragDrop(where image.Point, mods key.Modifiers, fromApp bool, files []string, mime []byte) {
var md mimedata.Mimes
if len(files) > 0 {
for _, f := range files {
md = append(md, mimedata.NewTextData(f))
}
} else if len(mime) > 0 {
if isMulti, _, boundary, body := mimedata.IsMultipart(mime); isMulti {
md = mimedata.FromMultipart(body, boundary)
}
}
if len(md) == 0 {
return
}
w.Event.DragExternal(events.Drop, where, mods, md, fromApp)
}
// Copyright 2026 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build linux && (x11 || !wayland)
package desktop
/*
#cgo LDFLAGS: -lX11 -lpthread
#include <X11/Xlib.h>
#include <stdbool.h>
#include <stdlib.h>
void registerDrag(Window win);
void unregisterDrag(Window win);
void ungrabGLFW(Display* gd);
bool startDrag(Window win, void* uris, int urislen, void* mime, int mimelen, void* text, int textlen);
bool dragAccepted(void);
*/
import "C"
import (
"image"
"net/url"
"strings"
"unsafe"
"cogentcore.org/core/base/fileinfo/mimedata"
"cogentcore.org/core/events/key"
"github.com/cogentcore/glfw4/v3.4/glfw"
)
// isX11 returns whether GLFW is using X11, which drag-and-drop
// requires, rather than Wayland, where only GLFW file drops work.
func isX11() bool {
return glfw.GetPlatform() == glfw.PlatformX11
}
// xwindow returns the X11 Window of the window.
func (w *Window) xwindow() C.Window {
return C.Window(w.Glw.GetX11Window())
}
// initDrag sets up drag-and-drop for the window.
// It must be called on the main thread.
func (w *Window) initDrag() {
if !isX11() {
return
}
xw := w.xwindow()
addDragWindow(uintptr(xw), w)
C.registerDrag(xw)
}
// closeDrag removes the window from drag-and-drop.
// It must be called on the main thread.
func (w *Window) closeDrag() {
if !isX11() {
return
}
xw := w.xwindow()
C.unregisterDrag(xw)
deleteDragWindow(uintptr(xw))
}
func (w *Window) DragAccepted() bool {
return bool(C.dragAccepted())
}
func (w *Window) StartDrag(data mimedata.Mimes, files []string, img image.Image) bool {
if w.Glw == nil || !isX11() {
return false
}
mime, text := dragData(data, files)
uris := fileURIs(files)
var xw C.Window
w.App.RunOnMain(func() {
if w.Glw == nil {
return
}
xw = w.xwindow()
C.ungrabGLFW((*C.Display)(unsafe.Pointer(glfw.GetX11Display())))
})
if xw == 0 {
return false
}
curis, curislen := cBytes(uris)
defer C.free(curis)
cmime, cmimelen := cBytes(mime)
defer C.free(cmime)
ctext, ctextlen := cBytes(text)
defer C.free(ctext)
return bool(C.startDrag(xw, curis, curislen, cmime, cmimelen, ctext, ctextlen))
}
// fileURIs returns the given files as a text/uri-list.
func fileURIs(files []string) []byte {
var b strings.Builder
for _, f := range files {
u := url.URL{Scheme: "file", Path: f}
b.WriteString(u.String() + "\r\n")
}
return []byte(b.String())
}
// filesFromURIs returns the local files in the given text/uri-list.
func filesFromURIs(uris string) []string {
var files []string
for _, line := range strings.Split(uris, "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
u, err := url.Parse(line)
if err != nil || u.Scheme != "file" || u.Path == "" {
continue
}
files = append(files, u.Path)
}
return files
}
// cBytes returns a C copy of the given bytes, which must be freed.
func cBytes(b []byte) (unsafe.Pointer, C.int) {
if len(b) == 0 {
return nil, 0
}
return C.CBytes(b), C.int(len(b))
}
// x11Mods converts the modifier bits from the C code to [key.Modifiers].
func x11Mods(mods C.int) key.Modifiers {
var m key.Modifiers
m.SetFlag(mods&1 != 0, key.Shift)
m.SetFlag(mods&2 != 0, key.Control)
m.SetFlag(mods&4 != 0, key.Alt)
m.SetFlag(mods&8 != 0, key.Meta)
return m
}
// x11DragMove is called for a drag over the window: leave is true when
// the drag leaves the window. x, y are in window pixels.
//
//export x11DragMove
func x11DragMove(win C.Window, leave C.bool, x, y C.int, mods C.int, fromApp C.bool) {
if w := dragWindow(uintptr(win)); w != nil {
w.dragMove(bool(leave), image.Pt(int(x), int(y)), x11Mods(mods), bool(fromApp))
}
}
// x11DragDrop is called for a drop on the window, with either a
// text/uri-list of files, or mime data from [dragData].
//
//export x11DragDrop
func x11DragDrop(win C.Window, x, y C.int, mods C.int, fromApp C.bool, uris *C.char, urislen C.int, mime *C.char, mimelen C.int) {
w := dragWindow(uintptr(win))
if w == nil {
return
}
var files []string
if urislen > 0 {
files = filesFromURIs(C.GoStringN(uris, urislen))
}
var mb []byte
if mimelen > 0 {
mb = C.GoBytes(unsafe.Pointer(mime), mimelen)
}
w.dragDrop(image.Pt(int(x), int(y)), x11Mods(mods), bool(fromApp), files, mb)
}
// Copyright 2019 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package desktop
import (
"image"
"cogentcore.org/core/base/fileinfo/mimedata"
"cogentcore.org/core/events"
"cogentcore.org/core/events/key"
"cogentcore.org/core/math32"
"cogentcore.org/core/system"
"github.com/cogentcore/glfw4/v3.4/glfw"
)
func GlfwMods(mod glfw.ModifierKey) key.Modifiers {
var m key.Modifiers
if mod&glfw.ModShift != 0 {
m.SetFlag(true, key.Shift)
}
if mod&glfw.ModControl != 0 {
m.SetFlag(true, key.Control)
}
if mod&glfw.ModAlt != 0 {
m.SetFlag(true, key.Alt)
}
if mod&glfw.ModSuper != 0 {
m.SetFlag(true, key.Meta)
}
if mod&glfw.ModCapsLock != 0 {
m.SetFlag(true, key.CapsLock)
}
if mod&glfw.ModNumLock != 0 {
m.SetFlag(true, key.NumLock)
}
return m
}
func (w *Window) FocusWindow() *Window {
fw := TheApp.WindowInFocus()
if w != fw {
if fw == nil {
fw = w
}
}
return fw.(*Window)
}
// physical key
func (w *Window) KeyEvent(gw *glfw.Window, ky glfw.Key, scancode int, action glfw.Action, mod glfw.ModifierKey) {
if w.imeKey(ky, scancode, action, mod) {
return
}
mods := GlfwMods(mod)
if TheApp.Platform() == system.MacOS {
mods.SetFlag(true, key.NumLock) // mac always acts like numlock is on
}
ec := GlfwKeyCode(ky)
rn := key.CodeRuneMap[ec]
typ := events.KeyDown
if action == glfw.Release {
typ = events.KeyUp
} else if action == glfw.Repeat {
typ = events.KeyDown
}
fw := w.FocusWindow()
fw.Event.Key(typ, rn, ec, mods)
glfw.PostEmptyEvent() // todo: why??
}
// char input
func (w *Window) CharEvent(gw *glfw.Window, char rune, mod glfw.ModifierKey) {
if w.imeChar() {
return
}
mods := GlfwMods(mod)
fw := w.FocusWindow()
fw.Event.KeyChord(char, key.CodeUnknown, mods)
glfw.PostEmptyEvent() // todo: why?
}
func (w *Window) CurMousePosPoint(gw *glfw.Window) image.Point {
xp, yp := gw.GetCursorPos()
return w.MousePosToPoint(xp, yp)
}
func (w *Window) MousePosToPoint(x, y float64) image.Point {
var where image.Point
if TheApp.Platform() == system.MacOS {
dpr := w.pixelRatio()
where = image.Pt(int(dpr*float32(x)), int(dpr*float32(y)))
} else {
where = image.Pt(int(x), int(y))
}
return where
}
func (w *Window) MouseButtonEvent(gw *glfw.Window, button glfw.MouseButton, action glfw.Action, mod glfw.ModifierKey) {
mods := GlfwMods(mod)
but := events.Left
switch button {
case glfw.MouseButtonMiddle:
but = events.Middle
case glfw.MouseButtonRight:
but = events.Right
}
typ := events.MouseDown
if action == glfw.Release {
typ = events.MouseUp
}
if mod&glfw.ModControl != 0 { // special case: control always = RMB can undo this downstream..
but = events.Right
}
where := w.CurMousePosPoint(gw)
w.Event.MouseButton(typ, but, where, mods)
glfw.PostEmptyEvent() // why?
}
func (w *Window) ScrollEvent(gw *glfw.Window, xoff, yoff float64) {
delta := math32.Vec2(float32(xoff), float32(yoff)).MulScalar(-10)
if TheApp.Platform() == system.MacOS {
delta.SetMulScalar(w.pixelRatio())
} else {
delta.SetMulScalar(4) // other platforms need a bigger multiplier in general
}
where := w.CurMousePosPoint(gw)
w.Event.Scroll(where, delta)
glfw.PostEmptyEvent()
}
func (w *Window) CursorPosEvent(gw *glfw.Window, x, y float64) {
if w.Event.ResettingPos {
return
}
where := w.MousePosToPoint(x, y)
if !w.CursorEnabled {
w.Event.ResettingPos = true
if TheApp.Platform() == system.MacOS {
dpr := float64(w.pixelRatio())
w.Glw.SetCursorPos(float64(w.Event.Last.MousePos.X)/dpr, float64(w.Event.Last.MousePos.Y)/dpr)
} else {
w.Glw.SetCursorPos(float64(w.Event.Last.MousePos.X), float64(w.Event.Last.MousePos.Y))
}
w.Event.ResettingPos = false
}
w.Event.MouseMove(where)
glfw.PostEmptyEvent()
}
func (w *Window) CursorEnterEvent(gw *glfw.Window, entered bool) {
}
func (w *Window) DropEvent(gw *glfw.Window, names []string) {
ln := len(names)
if ln == 0 {
return
}
md := mimedata.NewMimes(ln, ln)
for i, s := range names {
md[i] = mimedata.NewTextData(s)
}
where := w.CurMousePosPoint(gw)
w.Event.DropExternal(where, md)
}
// TODO: should this be a map?
func GlfwKeyCode(kcode glfw.Key) key.Codes {
switch kcode {
case glfw.KeyA:
return key.CodeA
case glfw.KeyB:
return key.CodeB
case glfw.KeyC:
return key.CodeC
case glfw.KeyD:
return key.CodeD
case glfw.KeyE:
return key.CodeE
case glfw.KeyF:
return key.CodeF
case glfw.KeyG:
return key.CodeG
case glfw.KeyH:
return key.CodeH
case glfw.KeyI:
return key.CodeI
case glfw.KeyJ:
return key.CodeJ
case glfw.KeyK:
return key.CodeK
case glfw.KeyL:
return key.CodeL
case glfw.KeyM:
return key.CodeM
case glfw.KeyN:
return key.CodeN
case glfw.KeyO:
return key.CodeO
case glfw.KeyP:
return key.CodeP
case glfw.KeyQ:
return key.CodeQ
case glfw.KeyR:
return key.CodeR
case glfw.KeyS:
return key.CodeS
case glfw.KeyT:
return key.CodeT
case glfw.KeyU:
return key.CodeU
case glfw.KeyV:
return key.CodeV
case glfw.KeyW:
return key.CodeW
case glfw.KeyX:
return key.CodeX
case glfw.KeyY:
return key.CodeY
case glfw.KeyZ:
return key.CodeZ
case glfw.Key1:
return key.Code1
case glfw.Key2:
return key.Code2
case glfw.Key3:
return key.Code3
case glfw.Key4:
return key.Code4
case glfw.Key5:
return key.Code5
case glfw.Key6:
return key.Code6
case glfw.Key7:
return key.Code7
case glfw.Key8:
return key.Code8
case glfw.Key9:
return key.Code9
case glfw.Key0:
return key.Code0
case glfw.KeyEnter:
return key.CodeReturnEnter
case glfw.KeyEscape:
return key.CodeEscape
case glfw.KeyBackspace:
return key.CodeBackspace
case glfw.KeyTab:
return key.CodeTab
case glfw.KeySpace:
return key.CodeSpacebar
case glfw.KeyMinus:
return key.CodeHyphenMinus
case glfw.KeyEqual:
return key.CodeEqualSign
case glfw.KeyLeftBracket:
return key.CodeLeftSquareBracket
case glfw.KeyRightBracket:
return key.CodeRightSquareBracket
case glfw.KeyBackslash:
return key.CodeBackslash
case glfw.KeySemicolon:
return key.CodeSemicolon
case glfw.KeyApostrophe:
return key.CodeApostrophe
case glfw.KeyGraveAccent:
return key.CodeGraveAccent
case glfw.KeyComma:
return key.CodeComma
case glfw.KeyPeriod:
return key.CodeFullStop
case glfw.KeySlash:
return key.CodeSlash
case glfw.KeyCapsLock:
return key.CodeCapsLock
case glfw.KeyF1:
return key.CodeF1
case glfw.KeyF2:
return key.CodeF2
case glfw.KeyF3:
return key.CodeF3
case glfw.KeyF4:
return key.CodeF4
case glfw.KeyF5:
return key.CodeF5
case glfw.KeyF6:
return key.CodeF6
case glfw.KeyF7:
return key.CodeF7
case glfw.KeyF8:
return key.CodeF8
case glfw.KeyF9:
return key.CodeF9
case glfw.KeyF10:
return key.CodeF10
case glfw.KeyF11:
return key.CodeF11
case glfw.KeyF12:
return key.CodeF12
// 70: PrintScreen
// 71: Scroll Lock
// 72: Pause
// 73: Insert
case glfw.KeyHome:
return key.CodeHome
case glfw.KeyPageUp:
return key.CodePageUp
case glfw.KeyDelete:
return key.CodeDelete
case glfw.KeyEnd:
return key.CodeEnd
case glfw.KeyPageDown:
return key.CodePageDown
case glfw.KeyRight:
return key.CodeRightArrow
case glfw.KeyLeft:
return key.CodeLeftArrow
case glfw.KeyDown:
return key.CodeDownArrow
case glfw.KeyUp:
return key.CodeUpArrow
case glfw.KeyNumLock:
return key.CodeKeypadNumLock
case glfw.KeyKPDivide:
return key.CodeKeypadSlash
case glfw.KeyKPMultiply:
return key.CodeKeypadAsterisk
case glfw.KeyKPSubtract:
return key.CodeKeypadHyphenMinus
case glfw.KeyKPAdd:
return key.CodeKeypadPlusSign
case glfw.KeyKPEnter:
return key.CodeKeypadEnter
case glfw.KeyKP1:
return key.CodeKeypad1
case glfw.KeyKP2:
return key.CodeKeypad2
case glfw.KeyKP3:
return key.CodeKeypad3
case glfw.KeyKP4:
return key.CodeKeypad4
case glfw.KeyKP5:
return key.CodeKeypad5
case glfw.KeyKP6:
return key.CodeKeypad6
case glfw.KeyKP7:
return key.CodeKeypad7
case glfw.KeyKP8:
return key.CodeKeypad8
case glfw.KeyKP9:
return key.CodeKeypad9
case glfw.KeyKP0:
return key.CodeKeypad0
case glfw.KeyKPDecimal:
return key.CodeKeypadFullStop
case glfw.KeyKPEqual:
return key.CodeKeypadEqualSign
case glfw.KeyF13:
return key.CodeF13
case glfw.KeyF14:
return key.CodeF14
case glfw.KeyF15:
return key.CodeF15
case glfw.KeyF16:
return key.CodeF16
case glfw.KeyF17:
return key.CodeF17
case glfw.KeyF18:
return key.CodeF18
case glfw.KeyF19:
return key.CodeF19
case glfw.KeyF20:
return key.CodeF20
// 116: Keyboard Execute
// case glfw.KeyHelp:
// return key.CodeHelp
// 118: Keyboard Menu
case glfw.KeyMenu: // the Menu key of Windows keyboards: 101, Keyboard Application
return key.CodeContextMenu
// 119: Keyboard Select
// 120: Keyboard Stop
// 121: Keyboard Again
// 122: Keyboard Undo
// 123: Keyboard Cut
// 124: Keyboard Copy
// 125: Keyboard Paste
// 126: Keyboard Find
// case glfw.KeyMute:
// return key.CodeMute
// case glfw.KeyVolumeUp:
// return key.CodeVolumeUp
// case glfw.KeyVolumeDown:
// return key.CodeVolumeDown
// 130: Keyboard Locking Caps Lock
// 131: Keyboard Locking Num Lock
// 132: Keyboard Locking Scroll Lock
// 133: Keyboard Comma
// 134: Keyboard Equal Sign
case glfw.KeyLeftControl:
return key.CodeLeftControl
case glfw.KeyLeftShift:
return key.CodeLeftShift
case glfw.KeyLeftAlt:
return key.CodeLeftAlt
case glfw.KeyLeftSuper:
return key.CodeLeftMeta
case glfw.KeyRightControl:
return key.CodeRightControl
case glfw.KeyRightShift:
return key.CodeRightShift
case glfw.KeyRightAlt:
return key.CodeRightAlt
case glfw.KeyRightSuper:
return key.CodeRightMeta
default:
return key.CodeUnknown
}
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build linux && !android
package desktop
import (
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"unicode"
"cogentcore.org/core/events/key"
"cogentcore.org/core/system"
"github.com/cogentcore/glfw4/v3.4/glfw"
"github.com/godbus/dbus/v5"
)
// Input method (IME) support on Linux, with IBus or Fcitx5 over D-Bus,
// through the IBus portal on the session bus, which both provide (as used
// by sandboxed apps), or else the IBus bus. While a text widget is focused,
// keys are sent to the input method first, and those that it handles are
// not sent as key events; its preedit (composition) and committed text are
// sent as events. GLFW's own XIM input method support is turned off when
// this is used, as it would also handle the keys.
const ibusInputContext = "org.freedesktop.IBus.InputContext"
// theIME is the input method connection, or nil if there is none.
var theIME *ibusIME
// ibusIME is a connection to an input method with the IBus D-Bus protocol.
type ibusIME struct {
conn *dbus.Conn
ic dbus.BusObject // the input context
// mu protects the fields below, which are used by
// the signal handler goroutine.
mu sync.Mutex
// win is the window with the text input, or nil if there is none.
win *Window
// composing is whether a composition has been sent.
composing bool
}
// suppressChar is whether the next char callback is for a key that the
// input method handled, so it is not sent. It is only used on the main thread.
var suppressChar bool
// imeInitApp connects to the input method if there is one, before GLFW is
// initialized, so that GLFW does not also use it through XIM, which Xlib
// sets up from XMODIFIERS when GLFW is initialized. The returned function
// restores XMODIFIERS after that, for any processes that the app starts.
func imeInitApp() (restore func()) {
restore = func() {}
if os.Getenv("COGENT_IME") == "none" {
return
}
ime, err := connectIME()
if err != nil { // no input method: GLFW still gets committed text through XIM
return
}
theIME = ime
old, had := os.LookupEnv("XMODIFIERS")
os.Setenv("XMODIFIERS", "@im=none")
return func() {
if had {
os.Setenv("XMODIFIERS", old)
} else {
os.Unsetenv("XMODIFIERS")
}
}
}
// connectIME connects to the input method through the IBus portal on the
// session bus, or else the IBus bus, and creates an input context.
func connectIME() (*ibusIME, error) {
ime := &ibusIME{}
conn, err := dbus.ConnectSessionBus(dbus.WithSignalHandler(ime))
if err == nil {
var path dbus.ObjectPath
err = conn.Object("org.freedesktop.portal.IBus", "/org/freedesktop/IBus").
Call("org.freedesktop.IBus.Portal.CreateInputContext", 0, "cogentcore").Store(&path)
if err == nil {
return ime.init(conn, "org.freedesktop.portal.IBus", path)
}
conn.Close()
}
addr, err := ibusAddress()
if err != nil {
return nil, err
}
conn, err = dbus.Connect(addr, dbus.WithSignalHandler(ime))
if err != nil {
return nil, err
}
var path dbus.ObjectPath
err = conn.Object("org.freedesktop.IBus", "/org/freedesktop/IBus").
Call("org.freedesktop.IBus.CreateInputContext", 0, "cogentcore").Store(&path)
if err != nil {
conn.Close()
return nil, err
}
return ime.init(conn, "org.freedesktop.IBus", path)
}
// init sets up the input context with the given bus name and path.
func (ime *ibusIME) init(conn *dbus.Conn, name string, path dbus.ObjectPath) (*ibusIME, error) {
const (
capPreeditText = 1 << 0
capFocus = 1 << 3
)
ime.conn = conn
ime.ic = conn.Object(name, path)
if err := ime.ic.Call(ibusInputContext+".SetCapabilities", 0, uint32(capPreeditText|capFocus)).Err; err != nil {
conn.Close()
return nil, err
}
if err := conn.AddMatchSignal(dbus.WithMatchObjectPath(path), dbus.WithMatchInterface(ibusInputContext)); err != nil {
conn.Close()
return nil, err
}
return ime, nil
}
// ibusAddress returns the address of the IBus bus, from IBUS_ADDRESS
// or the file that IBus writes for the display.
func ibusAddress() (string, error) {
if addr := os.Getenv("IBUS_ADDRESS"); addr != "" {
return addr, nil
}
mid, err := os.ReadFile("/etc/machine-id")
if err != nil {
return "", err
}
host, disp, ok := strings.Cut(os.Getenv("DISPLAY"), ":")
if !ok || host != "" {
return "", fmt.Errorf("ibus: no local X display")
}
disp, _, _ = strings.Cut(disp, ".")
conf := os.Getenv("XDG_CONFIG_HOME")
if conf == "" {
conf = filepath.Join(os.Getenv("HOME"), ".config")
}
b, err := os.ReadFile(filepath.Join(conf, "ibus", "bus", fmt.Sprintf("%s-unix-%s", strings.TrimSpace(string(mid)), disp)))
if err != nil {
return "", err
}
for _, line := range strings.Split(string(b), "\n") {
if addr, ok := strings.CutPrefix(line, "IBUS_ADDRESS="); ok {
return addr, nil
}
}
return "", fmt.Errorf("ibus: no address")
}
// initIME sets up input methods (IME) for the window, which uses
// the connection of the app.
func (w *Window) initIME() {}
func (w *Window) SetTextInput(ti *system.TextInput) {
ime := theIME
if ime == nil {
return
}
ime.mu.Lock()
if ti == nil {
if ime.win == w {
ime.win = nil
ime.endComposition()
ime.mu.Unlock()
ime.ic.Go(ibusInputContext+".Reset", 0, nil)
ime.ic.Go(ibusInputContext+".FocusOut", 0, nil)
return
}
ime.mu.Unlock()
return
}
focusIn := ime.win != w
ime.win = w
ime.mu.Unlock()
if focusIn {
ime.ic.Go(ibusInputContext+".FocusIn", 0, nil)
}
// The cursor location is in screen pixels, from the window position,
// which is not known on Wayland, where it is relative to the window.
r := ti.Caret
x, y := r.Min.X, r.Min.Y
if glfw.GetPlatform() == glfw.PlatformX11 {
x, y = x+w.Pos.X, y+w.Pos.Y
}
ime.ic.Go(ibusInputContext+".SetCursorLocation", 0, nil, int32(x), int32(y), int32(r.Dx()), int32(r.Dy()))
}
// imeFocus is called when the window gets or loses the focus.
func (w *Window) imeFocus(focused bool) {
ime := theIME
if ime == nil {
return
}
ime.mu.Lock()
has := ime.win == w
ime.mu.Unlock()
if !has {
return
}
if focused {
ime.ic.Go(ibusInputContext+".FocusIn", 0, nil)
} else {
ime.ic.Go(ibusInputContext+".FocusOut", 0, nil)
}
}
// imeKey sends the key event to the input method while text input is
// active, returning true if it handled the key, which is then not sent as
// a key event, nor its char. It is called on the main thread.
func (w *Window) imeKey(ky glfw.Key, scancode int, action glfw.Action, mods glfw.ModifierKey) bool {
suppressChar = false
ime := theIME
if ime == nil {
return false
}
ime.mu.Lock()
active := ime.win == w
ime.mu.Unlock()
if !active {
return false
}
sym := keysym(ky, scancode, mods)
if sym == 0 {
return false
}
state := ibusState(mods)
if action == glfw.Release {
state |= 1 << 30 // IBUS_RELEASE_MASK
}
var handled bool
if err := ime.ic.Call(ibusInputContext+".ProcessKeyEvent", 0, sym, uint32(max(scancode-8, 0)), state).Store(&handled); err != nil {
return false
}
if handled && action != glfw.Release {
suppressChar = true
}
return handled
}
// imeChar returns whether the char callback is for a key that
// the input method handled, so it is not sent.
func (w *Window) imeChar() bool {
s := suppressChar
suppressChar = false
return s
}
// ibusState returns the X11 modifier state for the given modifiers.
func ibusState(mods glfw.ModifierKey) uint32 {
var st uint32
if mods&glfw.ModShift != 0 {
st |= 1 // ShiftMask
}
if mods&glfw.ModCapsLock != 0 {
st |= 2 // LockMask
}
if mods&glfw.ModControl != 0 {
st |= 4 // ControlMask
}
if mods&glfw.ModAlt != 0 {
st |= 8 // Mod1Mask
}
if mods&glfw.ModNumLock != 0 {
st |= 16 // Mod2Mask
}
if mods&glfw.ModSuper != 0 {
st |= 64 // Mod4Mask
}
return st
}
// keysym returns the X11 keysym of the given key, which is the char of a
// printable key in the keyboard layout, or 0 if it is not known.
func keysym(ky glfw.Key, scancode int, mods glfw.ModifierKey) uint32 {
if sym, ok := specialKeysyms[ky]; ok {
return sym
}
name := glfw.GetKeyName(ky, scancode)
rs := []rune(name)
if len(rs) != 1 {
return 0
}
r := rs[0]
if mods&glfw.ModShift != 0 != (mods&glfw.ModCapsLock != 0) {
r = unicode.ToUpper(r)
}
if r < 0x100 { // Latin-1 keysyms are the same as the code points
return uint32(r)
}
return 0x01000000 | uint32(r)
}
// specialKeysyms are the X11 keysyms of the keys that are not printable.
var specialKeysyms = map[glfw.Key]uint32{
glfw.KeySpace: 0x0020,
glfw.KeyBackspace: 0xff08,
glfw.KeyTab: 0xff09,
glfw.KeyEnter: 0xff0d,
glfw.KeyPause: 0xff13,
glfw.KeyScrollLock: 0xff14,
glfw.KeyEscape: 0xff1b,
glfw.KeyHome: 0xff50,
glfw.KeyLeft: 0xff51,
glfw.KeyUp: 0xff52,
glfw.KeyRight: 0xff53,
glfw.KeyDown: 0xff54,
glfw.KeyPageUp: 0xff55,
glfw.KeyPageDown: 0xff56,
glfw.KeyEnd: 0xff57,
glfw.KeyInsert: 0xff63,
glfw.KeyMenu: 0xff67,
glfw.KeyNumLock: 0xff7f,
glfw.KeyKPEnter: 0xff8d,
glfw.KeyDelete: 0xffff,
glfw.KeyLeftShift: 0xffe1,
glfw.KeyRightShift: 0xffe2,
glfw.KeyLeftControl: 0xffe3,
glfw.KeyRightControl: 0xffe4,
glfw.KeyCapsLock: 0xffe5,
glfw.KeyLeftAlt: 0xffe9,
glfw.KeyRightAlt: 0xffea,
glfw.KeyLeftSuper: 0xffeb,
glfw.KeyRightSuper: 0xffec,
glfw.KeyF1: 0xffbe,
glfw.KeyF2: 0xffbf,
glfw.KeyF3: 0xffc0,
glfw.KeyF4: 0xffc1,
glfw.KeyF5: 0xffc2,
glfw.KeyF6: 0xffc3,
glfw.KeyF7: 0xffc4,
glfw.KeyF8: 0xffc5,
glfw.KeyF9: 0xffc6,
glfw.KeyF10: 0xffc7,
glfw.KeyF11: 0xffc8,
glfw.KeyF12: 0xffc9,
}
// endComposition sends the end of the composition, if one was sent.
// It must be called with mu locked.
func (ime *ibusIME) endComposition() {
if ime.composing && ime.win != nil {
ime.composing = false
ime.win.Event.Composition("", 0, 0)
glfw.PostEmptyEvent()
}
ime.composing = false
}
// DeliverSignal handles the signals of the input context, on the
// goroutine of the D-Bus connection.
func (ime *ibusIME) DeliverSignal(iface, name string, signal *dbus.Signal) {
if iface != ibusInputContext {
return
}
ime.mu.Lock()
defer ime.mu.Unlock()
w := ime.win
if w == nil {
return
}
switch name {
case "CommitText":
txt, _, _ := ibusText(signal.Body, 0)
ime.endComposition()
for _, r := range txt {
w.Event.KeyChord(r, key.CodeUnknown, 0)
}
glfw.PostEmptyEvent()
case "UpdatePreeditText", "UpdatePreeditTextWithMode":
txt, start, end := ibusText(signal.Body, 0)
visible := len(signal.Body) > 2 && signal.Body[2] == true
if !visible || txt == "" {
ime.endComposition()
return
}
if start < 0 { // the cursor
cur, _ := signal.Body[1].(uint32)
start, end = int(cur), int(cur)
}
ime.composing = true
w.Event.Composition(txt, start, end)
glfw.PostEmptyEvent()
case "HidePreeditText":
ime.endComposition()
}
}
// ibusText returns the text of the IBusText at the given index of the
// signal body, and the range of its double underlined attribute, which is
// the clause being converted, or -1 if there is none.
func ibusText(body []any, i int) (txt string, start, end int) {
start, end = -1, -1
if len(body) <= i {
return
}
v, ok := body[i].(dbus.Variant)
if !ok {
return
}
// IBusText: (s a{sv} s v), with the attribute list v: (s a{sv} av)
fields, ok := v.Value().([]any)
if !ok || len(fields) < 3 {
return
}
txt, _ = fields[2].(string)
if len(fields) < 4 {
return
}
al, ok := fields[3].(dbus.Variant)
if !ok {
return
}
alf, ok := al.Value().([]any)
if !ok || len(alf) < 3 {
return
}
attrs, ok := alf[2].([]dbus.Variant)
if !ok {
return
}
for _, a := range attrs {
// IBusAttribute: (s a{sv} u u u u): type, value, start, end
af, ok := a.Value().([]any)
if !ok || len(af) < 6 {
continue
}
typ, _ := af[2].(uint32)
val, _ := af[3].(uint32)
st, _ := af[4].(uint32)
ed, _ := af[5].(uint32)
const (
attrUnderline = 1
underlineDouble = 2
)
if typ == attrUnderline && val == underlineDouble {
return txt, int(st), int(ed)
}
}
return
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package desktop
import "golang.org/x/sys/unix"
// currentThreadID returns the id of the current thread.
func currentThreadID() int { return unix.Gettid() }
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build linux || windows
package desktop
import "sync/atomic"
// mainThreadID is the id of the thread that [Init] locks the main goroutine
// to, on which the main loop runs, or 0 before Init.
var mainThreadID atomic.Int64
// setMainThread records the current thread as the main thread; it is
// called by [Init] after locking the main goroutine to it.
func setMainThread() {
mainThreadID.Store(int64(currentThreadID()))
}
// onMainThread returns whether the calling goroutine runs on the main
// thread (see [setMainThread]), or true before [Init] (when it is not known).
// Other goroutines must not be taken to be on the main thread, as the
// initialization of the windowing system returns at once for calls on the
// main thread while it is in progress (see [App.initGUI]).
func onMainThread() bool {
id := mainThreadID.Load()
return id == 0 || int64(currentThreadID()) == id
}
// Copyright 2026 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build linux && !android
package desktop
import (
"sync"
"cogentcore.org/core/system"
"github.com/godbus/dbus/v5"
)
// The D-Bus names of the notification service of freedesktop.org, which
// the notification daemons of the desktops implement.
const (
notifyService = "org.freedesktop.Notifications"
notifyPath = "/org/freedesktop/Notifications"
)
// linuxNotifier shows notifications with the notification service of
// freedesktop.org, over D-Bus. It cannot schedule them, so they are
// shown with timers while the app is running (see [system.NotifierTimers]).
type linuxNotifier struct {
system.NotifierTimers
mu sync.Mutex
conn *dbus.Conn
// ids are the IDs of the notifications by the IDs of the service,
// for the clicks.
ids map[uint32]string
}
var (
// theNotifier is the notifier of the app, made by [App.Notifier].
theNotifier *linuxNotifier
notifierOnce sync.Once
)
// Notifier returns the notifier of Linux, which only shows notifications
// while the app is running, as the notification service cannot schedule
// them.
func (a *App) Notifier() system.Notifier {
notifierOnce.Do(func() {
ln := &linuxNotifier{ids: map[uint32]string{}}
ln.ShowFunc = ln.show
theNotifier = ln
})
return theNotifier
}
// connect connects to the session bus, once, and listens for clicks.
// It must be called with the mutex locked.
func (ln *linuxNotifier) connect() error {
if ln.conn != nil {
return nil
}
conn, err := dbus.ConnectSessionBus()
if err != nil {
return err
}
err = conn.AddMatchSignal(dbus.WithMatchObjectPath(notifyPath), dbus.WithMatchInterface(notifyService))
if err != nil {
conn.Close()
return err
}
signals := make(chan *dbus.Signal, 10)
conn.Signal(signals)
go ln.signals(signals)
ln.conn = conn
return nil
}
// signals handles the signals of the notification service: the click of
// a notification (its default action), and its closing.
func (ln *linuxNotifier) signals(signals chan *dbus.Signal) {
for sig := range signals {
if len(sig.Body) < 2 {
continue
}
nid, ok := sig.Body[0].(uint32)
if !ok {
continue
}
ln.mu.Lock()
id, has := ln.ids[nid]
ln.mu.Unlock()
if !has {
continue
}
switch sig.Name {
case notifyService + ".ActionInvoked":
if action, _ := sig.Body[1].(string); action == "default" {
ln.Clicked(id)
}
case notifyService + ".NotificationClosed":
ln.mu.Lock()
delete(ln.ids, nid)
ln.mu.Unlock()
}
}
}
// show shows the given notification now.
func (ln *linuxNotifier) show(n *system.Notification) error {
ln.mu.Lock()
defer ln.mu.Unlock()
if err := ln.connect(); err != nil {
return err
}
// the default action is the click of the notification
actions := []string{"default", "Open"}
obj := ln.conn.Object(notifyService, notifyPath)
var nid uint32
err := obj.Call(notifyService+".Notify", 0, system.TheApp.Name(), uint32(0), "",
n.Title, n.Body, actions, map[string]dbus.Variant{}, int32(-1)).Store(&nid)
if err != nil {
return err
}
ln.ids[nid] = n.ID
return nil
}
// Copyright 2019 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package desktop
import (
"image"
"log"
"slices"
"time"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/events"
"cogentcore.org/core/math32"
"cogentcore.org/core/system"
"github.com/cogentcore/glfw4/v3.4/glfw"
)
var (
// ScreenDebug turns on various debugging statements about monitor changes
// and updates from glfw.
ScreenDebug = false
// ScreenPollInterval is the time between checking if screens have changed.
// This is primarily for detecting changes after sleep, in which case
// the interval has likely been much longer than a few seconds.
ScreenPollInterval = time.Second
// Note: MacOS monitor situation is significantly buggy. we try to work around this.
// https://github.com/glfw/glfw/issues/2160
MacOsBuiltinMonitor = "Built-in Retina Display"
)
// MonitorChange is called when a monitor is connected to or
// disconnected from the system.
func (a *App) MonitorChange(monitor *glfw.Monitor, event glfw.PeripheralEvent) {
if ScreenDebug {
enm := "Unknown"
if event == glfw.Connected {
enm = "Connected"
} else {
enm = "Disconnected"
}
name := ""
if monitor != nil {
name = monitor.GetName()
}
log.Printf("ScreenDebug: monitorChange: %v event: %v\n", name, enm)
}
// glfw is used on the main thread, where this callback runs
a.GetScreens()
// the windows are updated on another goroutine, as they lock App.Mu
go func() {
a.Mu.Lock()
wins := slices.Clone(a.Windows) // (windows can close meanwhile)
a.Mu.Unlock()
if len(wins) == 0 {
if ScreenDebug {
log.Println("ScreenDebug: monitorChange: no windows, NOT sending screen update")
}
return
}
if ScreenDebug {
log.Println("ScreenDebug: monitorChange: sending screen update")
}
for _, w := range wins {
sc := w.Screen()
if sc != nil {
w.SetLogicalDPI(sc.LogicalDPI)
}
}
wins[0].Event.Window(events.ScreenUpdate)
}()
}
var lastScreenPoll time.Time
func (a *App) PollScreenChanges() {
now := time.Now()
if now.Sub(lastScreenPoll) < ScreenPollInterval {
return
}
lastScreenPoll = now
mons := glfw.GetMonitors()
ns := len(mons)
if ns == 0 {
return
}
csc := make([]*system.Screen, ns)
if len(mons) != len(a.Screens) {
goto doUpdate
}
for i, sc := range a.Screens {
ssc := &system.Screen{}
*ssc = *sc
csc[i] = ssc
}
a.GetScreens()
for i, sc := range a.Screens {
if i >= len(csc) { // number could have changed
goto doUpdate
}
ssc := csc[i]
if *ssc != *sc {
goto doUpdate
}
}
return // no change
doUpdate:
if len(a.Windows) > 0 {
fw := a.Windows[0]
if ScreenDebug {
log.Println("ScreenDebug: PollScreenChanges: sending screen update")
}
fw.Event.Window(events.ScreenUpdate)
}
}
func (a *App) GetScreens() {
a.Mu.Lock()
defer a.Mu.Unlock()
mons := glfw.GetMonitors()
a.Monitors = mons
sz := len(mons)
if sz == 0 {
a.Screens = []*system.Screen{}
if ScreenDebug {
log.Printf("ScreenDebug: getScreens: no screens found!\n")
}
return
}
if ScreenDebug {
pm := glfw.GetPrimaryMonitor()
log.Printf("ScreenDebug: Primary monitor: %s first monitor: %s\n", pm.GetName(), mons[0].GetName())
}
a.Screens = make([]*system.Screen, 0, sz)
scNo := 0
for i := range sz {
mon := mons[i]
if ScreenDebug {
log.Printf("ScreenDebug: getScreens: mon number: %v name: %v\n", i, mon.GetName())
}
for len(a.Screens) <= scNo {
a.Screens = append(a.Screens, &system.Screen{})
}
sc := a.Screens[scNo]
vm := mon.GetVideoMode()
if vm == nil || vm.Width == 0 || vm.Height == 0 {
if ScreenDebug {
log.Printf("ScreenDebug: getScreens: screen %v has no size!\n", sc.Name)
}
if a.Platform() == system.MacOS {
si, has := a.FindScreenInfo(MacOsBuiltinMonitor)
if has {
*sc = *si
sc.ScreenNumber = scNo
sc.UpdateLogicalDPI()
if ScreenDebug {
log.Printf("ScreenDebug: getScreens: MacOS recovered screen info from %v\n", sc.Name)
}
scNo++
continue
}
// use plausible defaults.. sheesh
sc.ScreenNumber = scNo
sc.Name = MacOsBuiltinMonitor
sc.Geometry.Max = image.Point{2056, 1329}
sc.DevicePixelRatio = 2
sc.PixelSize = sc.Geometry.Max.Mul(2)
sc.PhysicalSize = image.Point{344, 222}
sc.Depth = 24
sc.RefreshRate = 60
sc.UpdatePhysicalDPI()
sc.UpdateLogicalDPI()
if ScreenDebug {
log.Printf("ScreenDebug: getScreens: MacOS unknown display set to Built-in Retina Display %d:\n%s\n", i, reflectx.StringJSON(sc))
}
scNo++
continue
}
a.Screens = slices.Delete(a.Screens, scNo, scNo+1)
a.Monitors = slices.Delete(a.Monitors, scNo, scNo+1)
continue
}
pw, ph := mon.GetPhysicalSize()
if pw == 0 {
if ScreenDebug {
log.Printf("ScreenDebug: physical size %s returned 0 -- bailing\n", mon.GetName())
}
a.Screens = slices.Delete(a.Screens, scNo, scNo+1)
a.Monitors = slices.Delete(a.Monitors, scNo, scNo+1)
continue
}
x, y := mon.GetPos()
cscx, _ := mon.GetContentScale() // note: requires glfw 3.3
if math32.IsNaN(cscx) {
if ScreenDebug {
log.Printf("ScreenDebug: GetContentScale on %s returned NaN -- trying saved info..\n", mon.GetName())
}
si, has := a.FindScreenInfo(mon.GetName())
if has {
cscx = si.DevicePixelRatio
if ScreenDebug {
log.Printf("ScreenDebug: recovered value of: %g for screen: %s\n", cscx, si.Name)
}
} else {
cscx = 1
if ScreenDebug {
log.Printf("ScreenDebug: using default of 1 -- may not be correct!\n")
}
}
}
if cscx < 1 {
cscx = 1
}
sc.Name = mon.GetName()
sc.ScreenNumber = scNo
sc.Geometry = image.Rectangle{Min: image.Point{x, y}, Max: image.Point{x + vm.Width, y + vm.Height}}
sc.DevicePixelRatio = cscx
sc.PixelSize = sc.WindowSizeToPixels(image.Point{vm.Width, vm.Height})
depth := vm.RedBits + vm.GreenBits + vm.BlueBits
sc.Depth = depth
sc.PhysicalSize = image.Point{pw, ph}
sc.UpdatePhysicalDPI()
sc.UpdateLogicalDPI()
sc.RefreshRate = float32(vm.RefreshRate)
if ScreenDebug {
log.Printf("ScreenDebug: screen %d:\n%s\n", scNo, reflectx.StringJSON(sc))
}
a.SaveScreenInfo(sc)
scNo++
}
// if originally a non-builtin monitor was primary, and now builtin is primary,
// then switch builtin and non-builtin. see https://github.com/glfw/glfw/issues/2160
if sz > 1 && a.Platform() == system.MacOS && a.Screens[0].Name == MacOsBuiltinMonitor {
fss := a.AllScreens[0]
if fss.Name != MacOsBuiltinMonitor {
if ScreenDebug {
log.Printf("ScreenDebug: getScreens: MacOs, builtin is currently primary, but was not originally -- restoring primary monitor as: %s\n", a.Screens[1].Name)
}
// assume 2nd one is good..
a.Screens[0], a.Screens[1] = a.Screens[1], a.Screens[0] // swap
a.Screens[0].ScreenNumber = 0
a.Screens[1].ScreenNumber = 1
}
}
if system.UpdateLogicalDPIScaleFunc != nil {
system.UpdateLogicalDPIScaleFunc()
}
}
// SaveScreenInfo saves a copy of given screen info to screensAll list if unique
// based on name. Returns true if added a new screen.
func (a *App) SaveScreenInfo(sc *system.Screen) bool {
_, has := a.FindScreenInfo(sc.Name)
if has {
return false
}
nsc := &system.Screen{}
*nsc = *sc
a.AllScreens = append(a.AllScreens, nsc)
return true
}
// FindScreenInfo finds saved screen info based on name
func (a *App) FindScreenInfo(name string) (*system.Screen, bool) {
for _, sc := range a.AllScreens {
if sc.Name == name {
return sc, true
}
}
return nil, false
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package desktop
import (
"cogentcore.org/core/events"
)
// IsDark returns whether the system color theme is dark (as opposed to light).
// It is kept up to date by the platform-specific theme watcher started by
// [App.watchTheme], when the windowing system is initialized (see [App.initGUI]).
func (a *App) IsDark() bool {
a.initGUI()
return a.dark.Load()
}
// setDark sets whether the system color theme is dark. If it changed, it sends
// an [events.ScreenUpdate] event to the first window, which updates the color
// scheme when the Auto theme is used. It can be called on any thread.
func (a *App) setDark(dark bool) {
if a.dark.Swap(dark) == dark {
return
}
// not on this thread, which may be the main thread, as Window locks App.Mu
go func() {
if w := a.Window(0); w != nil {
w.Events().Window(events.ScreenUpdate)
}
}()
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build linux
package desktop
import (
"log/slog"
"os"
"os/exec"
"strings"
"github.com/godbus/dbus/v5"
)
// TODO(kai): implement SetTitleBarIsDark on linux
const (
portalDest = "org.freedesktop.portal.Desktop"
portalPath = "/org/freedesktop/portal/desktop"
portalSettings = "org.freedesktop.portal.Settings"
appearanceNS = "org.freedesktop.appearance"
colorSchemeName = "color-scheme"
)
// watchTheme sets the initial system color theme and starts watching it for
// changes, using the color-scheme setting of the XDG desktop portal, which
// is supported by GNOME, KDE, and other desktops. If the portal does not
// have a preference, it falls back on whether the GTK theme name has "dark"
// in it, without watching for changes.
func (a *App) watchTheme() {
conn, err := dbus.ConnectSessionBus()
if err != nil {
slog.Debug("system color theme: no session bus: " + err.Error())
a.dark.Store(isDarkGTK())
return
}
obj := conn.Object(portalDest, portalPath)
scheme, err := readColorScheme(obj)
if err != nil {
slog.Debug("system color theme: no desktop portal color-scheme: " + err.Error())
conn.Close()
a.dark.Store(isDarkGTK())
return
}
a.dark.Store(isDarkScheme(scheme))
err = conn.AddMatchSignal(
dbus.WithMatchObjectPath(portalPath),
dbus.WithMatchInterface(portalSettings),
dbus.WithMatchMember("SettingChanged"),
dbus.WithMatchArg(0, appearanceNS),
dbus.WithMatchArg(1, colorSchemeName),
)
if err != nil {
slog.Error("error watching system color theme: " + err.Error())
conn.Close()
return
}
signals := make(chan *dbus.Signal, 10)
conn.Signal(signals)
go func() {
for sig := range signals {
if len(sig.Body) < 3 {
continue
}
ns, _ := sig.Body[0].(string)
key, _ := sig.Body[1].(string)
if ns != appearanceNS || key != colorSchemeName {
continue
}
if v, ok := sig.Body[2].(dbus.Variant); ok {
if scheme, ok := variantUint32(v); ok {
a.setDark(isDarkScheme(scheme))
}
}
}
}()
}
// readColorScheme returns the color-scheme setting of the desktop portal:
// 0 for no preference, 1 for dark, and 2 for light.
func readColorScheme(obj dbus.BusObject) (uint32, error) {
var v dbus.Variant
err := obj.Call(portalSettings+".ReadOne", 0, appearanceNS, colorSchemeName).Store(&v)
if err != nil {
// ReadOne is only in version 2 of the portal; Read wraps
// the value in another variant.
err = obj.Call(portalSettings+".Read", 0, appearanceNS, colorSchemeName).Store(&v)
if err != nil {
return 0, err
}
}
scheme, _ := variantUint32(v)
return scheme, nil
}
// variantUint32 returns the uint32 value of the given variant,
// unwrapping any variants nested in it.
func variantUint32(v dbus.Variant) (uint32, bool) {
for {
switch x := v.Value().(type) {
case dbus.Variant:
v = x
case uint32:
return x, true
default:
return 0, false
}
}
}
// isDarkScheme returns whether the given desktop portal color-scheme
// value is dark, falling back on [isDarkGTK] when there is no preference.
func isDarkScheme(scheme uint32) bool {
switch scheme {
case 1:
return true
case 2:
return false
}
return isDarkGTK()
}
// isDarkGTK returns whether the GTK theme is dark, based on whether its name
// has "dark" in it, from the GTK_THEME environment variable or the GNOME
// gtk-theme setting.
func isDarkGTK() bool {
theme := os.Getenv("GTK_THEME")
if theme == "" {
out, err := exec.Command("gsettings", "get", "org.gnome.desktop.interface", "gtk-theme").Output()
if err != nil {
return false
}
theme = string(out)
}
return strings.Contains(strings.ToLower(theme), "dark")
}
// Copyright 2019 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// originally based on golang.org/x/exp/shiny:
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package desktop
import (
"image"
"log"
"cogentcore.org/core/events"
"cogentcore.org/core/gpu"
"cogentcore.org/core/gpu/gpudraw"
"cogentcore.org/core/styles/sides"
"cogentcore.org/core/system"
"cogentcore.org/core/system/composer"
"cogentcore.org/core/system/driver/base"
"github.com/cogentcore/glfw4/v3.4/glfw"
)
// Window is the implementation of [system.Window] for the desktop platform.
type Window struct {
base.WindowMulti[*App, *composer.ComposerDrawer]
// Glw is the glfw window associated with this window
Glw *glfw.Window
// Draw is the [gpudraw.Drawer] used for the Composer.
Draw *gpudraw.Drawer // TODO: really need this separately?
// ScreenName is the name of the last known screen this window was on
ScreenWindow string
// hidden is whether the window is hidden by [Window.Hide], until
// [Window.Raise] shows it again. It is only used on the main thread.
hidden bool
}
func (w *Window) IsVisible() bool {
return w.WindowMulti.IsVisible() && w.Glw != nil
}
func (w *Window) SendPaintEvent() {
w.This.Events().WindowPaint()
}
// newGlfwWindow makes a new glfw window for this window.
// It must be run on main.
func (w *Window) newGlfwWindow(opts *system.NewWindowOptions, sc *system.Screen) error {
// glfw.DefaultWindowHints()
if opts.Flags.HasFlag(system.FixedSize) {
glfw.WindowHint(glfw.Resizable, glfw.False)
} else {
glfw.WindowHint(glfw.Resizable, glfw.True)
}
glfw.WindowHint(glfw.Visible, glfw.False) // needed to position
glfw.WindowHint(glfw.Focused, glfw.True)
// glfw.WindowHint(glfw.ScaleToMonitor, glfw.True)
glfw.WindowHint(glfw.ClientAPI, glfw.NoAPI)
// glfw.WindowHint(glfw.Samples, 0) // don't do multisampling for main window -- only in sub-render
if opts.Flags.HasFlag(system.Maximized) {
glfw.WindowHint(glfw.Maximized, glfw.True)
}
if opts.Flags.HasFlag(system.Tool) {
glfw.WindowHint(glfw.Decorated, glfw.False)
} else {
glfw.WindowHint(glfw.Decorated, glfw.True)
}
glfw.WindowHint(glfw.CocoaRetinaFramebuffer, glfw.True)
// glfw.WindowHint(glfw.TransparentFramebuffer, glfw.True)
// todo: glfw.Floating for always-on-top -- could set for modal
sz := opts.Size
if TheApp.Platform() == system.MacOS {
// on macOS, the size we pass to glfw must be in window manager units
sz = sc.WindowSizeFromPixels(opts.Size)
}
fullscreen := opts.Flags.HasFlag(system.Fullscreen)
var mon *glfw.Monitor
if fullscreen && sc.ScreenNumber < len(TheApp.Monitors) {
mon = TheApp.Monitors[sc.ScreenNumber]
sz = sc.PixelSize // use screen size for fullscreen video mode resolution
}
glw, err := glfw.CreateWindow(sz.X, sz.Y, opts.GetTitle(), mon, nil)
if err != nil {
return err
}
if !fullscreen {
pos := opts.Pos.Add(sc.Geometry.Min) // screen relative
glw.SetPos(pos.X, pos.Y)
w.GeomMu.Lock()
w.Pos = pos
w.GeomMu.Unlock()
}
if opts.Icon != nil {
glw.SetIcon(opts.Icon)
setAppIcon(opts.Icon)
}
w.Glw = glw
w.initDrag()
w.initIME()
return nil
}
// Screen gets the screen of the window, computing various window parameters.
func (w *Window) Screen() *system.Screen {
if w == nil || w.Glw == nil {
return TheApp.Screens[0]
}
var sc *system.Screen
mon := w.Glw.GetMonitor() // this returns nil for windowed windows -- i.e., most windows
// that is super useless it seems. only works for fullscreen
if mon != nil {
if ScreenDebug {
log.Printf("ScreenDebug: desktop.Window.Screen: %v: got screen: %v\n", w.Nm, mon.GetName())
}
sc = TheApp.ScreenByName(mon.GetName())
if sc == nil {
log.Printf("ScreenDebug: desktop.Window.Screen: could not find screen of name: %v\n", mon.GetName())
sc = TheApp.Screens[0]
}
goto setScreen
}
sc = w.GetScreenOverlap()
if sc == nil {
return nil
}
// if monitorDebug {
// log.Printf("ScreenDebug: desktop.Window.GetScreenOverlap: %v: got screen: %v\n", w.Nm, sc.Name)
// }
setScreen:
w.Mu.Lock()
defer w.Mu.Unlock()
w.ScreenWindow = sc.Name
w.PhysDPI = sc.PhysicalDPI
w.GeomMu.Lock() // see [base.WindowMulti.GeomMu]
w.DevicePixelRatio = sc.DevicePixelRatio
if w.LogDPI == 0 {
w.LogDPI = sc.LogicalDPI
}
w.GeomMu.Unlock()
return sc
}
// GetScreenOverlap gets the monitor for given window
// based on overlap of geometry, using limited glfw 3.3 api,
// which does not provide this functionality.
// See: https://github.com/glfw/glfw/issues/1699
// This is adapted from slawrence2302's code posted there.
func (w *Window) GetScreenOverlap() *system.Screen {
w.App.Mu.Lock()
defer w.App.Mu.Unlock()
var wgeom image.Rectangle
wgeom.Min.X, wgeom.Min.Y = w.Glw.GetPos()
var sz image.Point
sz.X, sz.Y = w.Glw.GetSize()
wgeom.Max = wgeom.Min.Add(sz)
var csc *system.Screen
var ovlp int
for _, sc := range TheApp.Screens {
isect := sc.Geometry.Intersect(wgeom).Size()
ov := isect.X * isect.Y
if ov > ovlp || ovlp == 0 {
csc = sc
ovlp = ov
}
}
return csc
}
// Position returns the position of the window, as set by [Window.Moved],
// relative to the given screen if it is not nil. It does not wait on
// [Window.Mu], which is held while the window renders, and opening a new
// window gets the position of the last one.
func (w *Window) Position(screen *system.Screen) image.Point {
w.GeomMu.Lock()
ps := w.Pos
w.GeomMu.Unlock()
if screen != nil {
ps = ps.Sub(screen.Geometry.Min)
}
return ps
}
func (w *Window) SetTitle(title string) {
if w.IsClosed() {
return
}
w.WindowMulti.SetTitle(title)
w.App.RunOnMain(func() {
if w.Glw == nil { // by time we got to main, could be diff
return
}
w.Glw.SetTitle(title)
})
}
func (w *Window) SetIcon(images []image.Image) {
if w.IsClosed() {
return
}
w.App.RunOnMain(func() {
if w.Glw == nil { // by time we got to main, could be diff
return
}
w.Glw.SetIcon(images)
setAppIcon(images)
})
}
func (w *Window) SetWinSize(sz image.Point) {
if w.IsClosed() || w.Is(system.Fullscreen) {
return
}
// note: anything run on main only doesn't need lock -- implicit lock
w.App.RunOnMain(func() {
if w.Glw == nil { // by time we got to main, could be diff
return
}
w.Glw.SetSize(sz.X, sz.Y)
})
}
func (w *Window) SetSize(sz image.Point) {
sc := w.Screen()
sz = sc.WindowSizeFromPixels(sz)
w.SetWinSize(sz)
}
func (w *Window) SetPos(pos image.Point, screen *system.Screen) {
if w.IsClosed() || w.Is(system.Fullscreen) {
return
}
if screen != nil {
pos = pos.Add(screen.Geometry.Min)
}
// note: anything run on main only doesn't need lock -- implicit lock
w.App.RunOnMain(func() {
if w.Glw == nil { // by time we got to main, could be diff
return
}
w.Glw.SetPos(pos.X, pos.Y)
})
}
func (w *Window) SetGeometry(fullscreen bool, pos, size image.Point, screen *system.Screen) {
if w.IsClosed() {
return
}
if pos == (image.Point{}) {
pos = w.Pos
}
if size == (image.Point{}) {
size = w.Size()
}
if screen != nil {
pos = pos.Add(screen.Geometry.Min)
}
sc := w.Screen()
if screen != nil {
sc = screen // critical to use this b/c w.Screen() can be wrong on new screen sequence
}
size = sc.WindowSizeFromPixels(size)
// note: anything run on main only doesn't need lock -- implicit lock
w.App.RunOnMain(func() {
if w.Glw == nil { // by time we got to main, could be diff
return
}
switch {
case w.Is(system.Fullscreen) && !fullscreen:
w.Flgs.SetFlag(false, system.Fullscreen)
w.Glw.SetMonitor(nil, pos.X, pos.Y, size.X, size.Y, glfw.DontCare)
case fullscreen:
w.Flgs.SetFlag(true, system.Fullscreen)
if screen != nil {
sc = screen
}
mon := w.App.Monitors[sc.ScreenNumber]
w.Glw.SetMonitor(mon, 0, 0, sc.PixelSize.X, sc.PixelSize.Y, glfw.DontCare)
default:
w.Glw.SetSize(size.X, size.Y)
w.Glw.SetPos(pos.X, pos.Y)
}
})
}
func (w *Window) ConstrainFrame(topOnly bool) sides.Sides[int] {
if w.IsClosed() || w.Is(system.Fullscreen) || w.Is(system.Maximized) {
return w.FrameSize
}
if TheApp.Platform() == system.Windows && w.Pos.X == -32000 || w.Pos.Y == -32000 {
return w.FrameSize
}
l, t, r, b := w.Glw.GetFrameSize()
w.FrameSize.Set(t, r, b, l)
sc := w.Screen()
if sc == nil {
return w.FrameSize
}
scSize := sc.Geometry.Size()
// fmt.Println("\tconstrainframe screen:", sc.Name, scSize, w.FrameSize, "geom:", w.Pos, w.WnSize)
frSize := image.Pt(w.FrameSize.Left+w.FrameSize.Right, w.FrameSize.Top+w.FrameSize.Bottom)
frOff := image.Pt(w.FrameSize.Left, w.FrameSize.Top)
sz := w.WinSize().Add(frSize)
scpos := w.Pos.Sub(sc.Geometry.Min)
pos := scpos.Sub(frOff)
cpos, csz := system.ConstrainWindowGeometry(pos, sz, scSize)
cpos = cpos.Add(frOff)
csz = csz.Sub(frSize)
// fmt.Println("\tconstrainframe pos:", scpos, "cpos:", cpos, "size:", w.WnSize, "csz:", csz)
change := false
pos = scpos
if !topOnly && cpos.X > pos.X {
change = true
pos.X = cpos.X
}
if cpos.Y > pos.Y {
change = true
pos.Y = cpos.Y
}
sz = w.WinSize()
if !topOnly && csz.X < sz.X {
change = true
sz.X = csz.X
}
if !topOnly && csz.Y < sz.Y {
change = true
sz.Y = csz.Y
}
if change {
// fmt.Println("\tconstrainframe changed:", pos, sz)
w.SetGeometry(false, pos, sz, sc)
}
return w.FrameSize
}
func (w *Window) Show() {
if w.IsClosed() {
return
}
// note: anything run on main only doesn't need lock -- implicit lock
w.App.RunOnMain(func() {
if w.Glw == nil { // by time we got to main, could be diff
return
}
w.Glw.Show()
})
}
func (w *Window) Raise() {
if w.IsClosed() {
return
}
// note: anything run on main only doesn't need lock -- implicit lock
w.App.RunOnMain(func() {
if w.Glw == nil { // by time we got to main, could be diff
return
}
switch {
case w.hidden:
w.hidden = false
w.Glw.Show()
w.Flgs.SetFlag(false, system.Minimized)
w.Glw.Focus()
w.Event.Window(events.WinShow)
case w.Is(system.Minimized):
w.Glw.Restore()
default:
w.Glw.Focus()
}
})
}
func (w *Window) Hide() {
if w.IsClosed() {
return
}
w.App.RunOnMain(func() {
if w.Glw == nil || w.hidden {
return
}
w.hidden = true
w.Glw.Hide()
w.Flgs.SetFlag(true, system.Minimized)
w.Event.Window(events.WinMinimize)
})
}
func (w *Window) Minimize() {
if w.IsClosed() {
return
}
// note: anything run on main only doesn't need lock -- implicit lock
w.App.RunOnMain(func() {
if w.Glw == nil { // by time we got to main, could be diff
return
}
w.Glw.Iconify()
})
}
func (w *Window) Close() {
if w == nil || !w.MarkClosing() {
return
}
w.Window.CloseBase()
w.Mu.Lock()
defer w.Mu.Unlock()
w.App.RunOnMain(func() {
w.Draw.System.WaitDone()
if w.DestroyGPUFunc != nil {
w.DestroyGPUFunc()
}
var surf *gpu.Surface
if sf, ok := w.Draw.Renderer().(*gpu.Surface); ok {
surf = sf
}
w.Draw.Release()
if surf != nil { // note: release surface after draw
surf.Release()
}
w.closeDrag()
w.Glw.Destroy()
w.Glw = nil // marks as closed for all other calls
w.Draw = nil
w.Compose = nil
})
}
func (w *Window) SetMousePos(x, y float64) {
if !w.IsVisible() {
return
}
w.Mu.Lock()
defer w.Mu.Unlock()
if TheApp.Platform() == system.MacOS {
dpr := float64(w.pixelRatio())
w.Glw.SetCursorPos(x/dpr, y/dpr)
} else {
w.Glw.SetCursorPos(x, y)
}
}
func (w *Window) SetCursorEnabled(enabled, raw bool) {
w.CursorEnabled = enabled
if enabled {
w.Glw.SetInputMode(glfw.CursorMode, glfw.CursorNormal)
} else {
w.Glw.SetInputMode(glfw.CursorMode, glfw.CursorDisabled)
if raw && glfw.RawMouseMotionSupported() {
w.Glw.SetInputMode(glfw.RawMouseMotion, glfw.True)
}
}
}
//////// Window Callbacks
func (w *Window) Moved(gw *glfw.Window, x, y int) {
go func() {
w.GeomMu.Lock() // see [Window.Position]
w.Pos = image.Pt(x, y)
w.GeomMu.Unlock()
// w.app.GetScreens() // this can crash here on win disconnect..
w.updateGeometry() // critical to update size etc here.
w.Event.Window(events.WinMove)
}()
}
func (w *Window) WinResized(gw *glfw.Window, width, height int) {
go func() {
// w.app.GetScreens() // this can crash here on win disconnect..
if ScreenDebug {
log.Printf("desktop.Window.WinResized: %v: %v (was: %v)\n", w.Nm, image.Pt(width, height), w.Size())
}
w.updateMaximized()
w.updateGeometry()
}()
}
func (w *Window) updateMaximized() {
w.Flgs.SetFlag(w.Glw.GetAttrib(glfw.Maximized) == glfw.True, system.Maximized)
}
func (w *Window) updateGeometry() {
w.Mu.Lock()
cursc := w.ScreenWindow
w.Mu.Unlock()
sc := w.Screen() // gets parameters
w.Mu.Lock()
w.updateMaximized()
var wsz image.Point
wsz.X, wsz.Y = w.Glw.GetSize()
var fbsz image.Point
fbsz.X, fbsz.Y = w.Glw.GetFramebufferSize()
w.GeomMu.Lock()
w.WnSize = wsz
w.PixelSize = fbsz
w.LogDPI = sc.LogicalDPI
w.GeomMu.Unlock()
w.PhysDPI = sc.PhysicalDPI
newsc := w.ScreenWindow // read under Mu: Screen sets it on other goroutines
w.Mu.Unlock()
w.Draw.System.Renderer.SetSize(fbsz)
if cursc != newsc {
if ScreenDebug {
log.Printf("desktop.Window.updateGeometry: %v: got new screen: %v (was: %v)\n", w.Nm, newsc, cursc)
}
}
w.Event.WindowResize()
}
func (w *Window) FbResized(gw *glfw.Window, width, height int) {
go func() {
if w.Is(system.Fullscreen) {
sc := w.Screen()
width = sc.PixelSize.X
height = sc.PixelSize.Y
}
fbsz := image.Point{width, height}
if cur := w.Size(); cur != fbsz {
if ScreenDebug {
log.Printf("desktop.Window.FbResized: %v: %v (was: %v)\n", w.Nm, fbsz, cur)
}
w.updateGeometry()
}
}()
}
func (w *Window) OnCloseReq(gw *glfw.Window) {
go w.CloseReq()
}
func (w *Window) Focused(gw *glfw.Window, focused bool) {
w.imeFocus(focused)
// w.Flgs.SetFlag(focused, system.Focused)
if focused {
w.Event.Window(events.WinFocus)
} else {
w.Event.Last.MousePos = image.Point{-1, -1} // key for preventing random click to same location
w.Event.Window(events.WinFocusLost)
}
}
func (w *Window) Iconify(gw *glfw.Window, iconified bool) {
w.Flgs.SetFlag(iconified, system.Minimized)
if iconified {
w.Event.Window(events.WinMinimize)
} else {
w.Screen() // gets parameters
w.Event.Window(events.WinMinimize)
}
}
// pixelRatio returns the DevicePixelRatio of the window, which is set
// on other goroutines (see [base.WindowMulti.GeomMu]).
func (w *Window) pixelRatio() float32 {
_, dpr := w.ScaleDPI()
return dpr
}
// Copyright 2018 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// based on golang.org/x/exp/shiny:
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !(android || ios || js)
package driver
import (
"os"
"slices"
"testing"
"cogentcore.org/core/system/driver/desktop"
"cogentcore.org/core/system/driver/offscreen"
)
func init() {
// TODO(kai/binsize): consider figuring out how to do this without
// increasing binary sizes; also supporting running tests on mobile and web
if testing.Testing() || slices.Contains(os.Args, "-nogui") {
offscreen.Init()
return
}
desktop.Init()
}
// Copyright 2023 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package offscreen provides placeholder implementations of system interfaces
// to allow for offscreen testing and capturing of apps.
package offscreen
import (
"image"
"os"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/events"
"cogentcore.org/core/system"
"cogentcore.org/core/system/composer"
"cogentcore.org/core/system/driver/base"
)
func Init() {
TheApp.GetScreens()
TheApp.TempDataDir = errors.Log1(os.MkdirTemp("", "cogent-core-offscreen-data-dir-"))
base.Init(TheApp, &TheApp.App)
}
// TheApp is the single [system.App] for the offscreen platform
var TheApp = &App{AppMulti: base.NewAppMulti[*Window]()}
// App is the [system.App] implementation for the offscreen platform.
// It is multi-window but only has one screen.
type App struct {
base.AppMulti[*Window]
// TempDataDir is the path of the app data directory, used as the
// return value of [App.DataDir]. It is set to a temporary directory,
// as offscreen tests should not be dependent on user preferences and
// other data.
TempDataDir string
}
// NewWindow creates a new window with the given options.
// It waits for the underlying system window to be created first.
// Also, it hides all other windows and shows the new one.
func (a *App) NewWindow(opts *system.NewWindowOptions) (system.Window, error) {
defer func() { system.HandleRecover(recover()) }()
w := &Window{base.NewWindowMulti[*App, *composer.ComposerDrawer](a, opts)}
w.This = w
w.Compose = &composer.ComposerDrawer{Drawer: &Drawer{Window: w}}
w.PixelSize = opts.Size
a.Mu.Lock()
a.Windows = append(a.Windows, w)
a.Mu.Unlock()
w.Event.WindowResize()
w.Event.Window(events.WinShow)
w.Event.Window(events.ScreenUpdate)
w.Event.Window(events.WinFocus)
go w.WinLoop()
return w, nil
}
func (a *App) GetScreens() {
if len(a.Screens) != 1 {
a.Screens = []*system.Screen{{}}
}
sc := a.Screen(0)
if sc.PixelSize.X == 0 {
sc.PixelSize.X = 800
}
if sc.PixelSize.Y == 0 {
sc.PixelSize.Y = 600
}
sc.DevicePixelRatio = 1
sc.Geometry.Max = sc.PixelSize
dpi := float32(160)
sc.PhysicalDPI = dpi
sc.LogicalDPI = dpi
if system.UpdateLogicalDPIScaleFunc != nil {
system.UpdateLogicalDPIScaleFunc()
}
physX := 25.4 * float32(sc.PixelSize.X) / dpi
physY := 25.4 * float32(sc.PixelSize.Y) / dpi
sc.PhysicalSize = image.Pt(int(physX), int(physY))
}
func (a *App) QuitClean() bool {
if a.TempDataDir != "" {
errors.Log(os.RemoveAll(a.TempDataDir))
}
return a.AppMulti.QuitClean()
}
func (a *App) DataDir() string {
return a.TempDataDir
}
func (a *App) Platform() system.Platforms {
return system.Offscreen
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package offscreen
import (
"sync"
"cogentcore.org/core/base/fileinfo/mimedata"
"cogentcore.org/core/system"
)
// Clipboard is an in-memory [system.Clipboard] shared by all of the
// windows of the offscreen app, so that copy and paste can be tested.
// Like the desktop clipboards, it holds only text: multiple items are
// encoded as a multipart MIME string, and only text types are read back.
type Clipboard struct {
mu sync.Mutex
// text is the text on the clipboard, nil if it is empty.
text []byte
}
var _ system.Clipboard = &Clipboard{}
// TheClipboard is the single [Clipboard] of the offscreen app.
var TheClipboard = &Clipboard{}
func (a *App) Clipboard(win system.Window) system.Clipboard {
return TheClipboard
}
func (cl *Clipboard) IsEmpty() bool {
cl.mu.Lock()
defer cl.mu.Unlock()
return cl.text == nil
}
func (cl *Clipboard) Read(types []string) mimedata.Mimes {
cl.mu.Lock()
defer cl.mu.Unlock()
if len(types) == 0 || cl.text == nil || !mimedata.IsText(types[0]) {
return nil
}
isMulti, mediaType, boundary, body := mimedata.IsMultipart(cl.text)
if isMulti {
return mimedata.FromMultipart(body, boundary)
}
if mediaType != "" {
return mimedata.NewMime(mediaType, cl.text)
}
return mimedata.NewMime(types[0], cl.text)
}
func (cl *Clipboard) Write(data mimedata.Mimes) error {
cl.mu.Lock()
defer cl.mu.Unlock()
cl.text = nil
if len(data) > 1 {
cl.text = data.ToMultipart()
} else if len(data) == 1 && mimedata.IsText(data[0].Type) {
cl.text = append([]byte{}, data[0].Data...)
}
return nil
}
func (cl *Clipboard) Clear() {
cl.mu.Lock()
defer cl.mu.Unlock()
cl.text = nil
}
// Copyright 2023 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package offscreen
import (
"image"
"cogentcore.org/core/system/composer"
)
// Drawer is the implementation of [system.Drawer] for the offscreen platform
type Drawer struct {
composer.DrawerBase
Window *Window
}
func (dw *Drawer) Start() {
rect := image.Rectangle{Max: dw.Window.Size()}
if dw.Image == nil || dw.Image.Rect != rect {
dw.Image = image.NewRGBA(rect)
}
dw.DrawerBase.Start()
}
func (dw *Drawer) End() {} // no-op
func (dw *Drawer) Redraw() {} // no-op
// GetImage returns the rendered image. It is called through an interface
// in core.AssertRender.
func (dw *Drawer) GetImage() *image.RGBA {
return dw.Image
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package offscreen
import (
"slices"
"sync"
"cogentcore.org/core/system"
)
// Notifier is the [system.Notifier] of the offscreen app, which records
// the notifications that are shown, so that they can be tested.
// The notifications of [system.Notifier.Sync] are shown with timers.
type Notifier struct {
system.NotifierTimers
mu sync.Mutex
shown []system.Notification
}
// TheNotifier is the single [Notifier] of the offscreen app.
var TheNotifier = newNotifier()
func newNotifier() *Notifier {
nt := &Notifier{}
nt.ShowFunc = func(n *system.Notification) error {
nt.mu.Lock()
nt.shown = append(nt.shown, *n)
nt.mu.Unlock()
return nil
}
return nt
}
func (a *App) Notifier() system.Notifier {
return TheNotifier
}
// Shown returns the notifications that have been shown, in order.
func (nt *Notifier) Shown() []system.Notification {
nt.mu.Lock()
defer nt.mu.Unlock()
return slices.Clone(nt.shown)
}
// ClearShown clears the list of the notifications that have been shown.
func (nt *Notifier) ClearShown() {
nt.mu.Lock()
nt.shown = nil
nt.mu.Unlock()
}
// Copyright 2023 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package offscreen
import (
"cogentcore.org/core/events"
"cogentcore.org/core/system"
"cogentcore.org/core/system/composer"
"cogentcore.org/core/system/driver/base"
)
// Window is the implementation of [system.Window] for the offscreen platform.
type Window struct {
base.WindowMulti[*App, *composer.ComposerDrawer]
}
func (w *Window) Screen() *system.Screen {
return TheApp.Screen(0)
}
// Close closes the window, once, as on desktop platforms: it is closed
// (see [base.Window.IsClosed]) right after the close event is sent, so
// that an event loop that closes its own window gets the close event
// once the window is closed, and can no longer lock it.
func (w *Window) Close() {
if !w.MarkClosing() {
return
}
w.CloseBase()
w.MarkClosed()
w.Mu.Lock()
w.Compose = nil
w.Mu.Unlock()
}
// IsClosed returns whether the window is closed, using an atomic flag
// set by [Window.Close] instead of reading the composer, which Close sets
// to nil under [base.Window.Mu], as IsClosed is called without that lock
// (as by [base.Window.Lock], before acquiring it).
func (w *Window) IsClosed() bool {
return w == nil || w.IsMarkedClosed()
}
// Hide hides the window, as on desktop platforms, which only makes it
// [system.Minimized], as there is nothing to show, for testing.
func (w *Window) Hide() {
w.Flgs.SetFlag(true, system.Minimized)
w.Events().Window(events.WinMinimize)
}
// Minimize minimizes the window, as [Window.Hide].
func (w *Window) Minimize() {
w.Hide()
}
// Raise shows the window again, after [Window.Hide] or [Window.Minimize].
func (w *Window) Raise() {
w.Flgs.SetFlag(false, system.Minimized)
w.Events().Window(events.WinShow) // (wakes it, to render what is pending)
}
// Copyright 2023 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"image"
"cogentcore.org/core/system"
_ "cogentcore.org/core/system/driver"
)
func main() {
fmt.Println("Hello, world!")
opts := &system.NewWindowOptions{
Size: image.Pt(1024, 768),
StdPixels: true,
Title: "System Test Window",
}
w, err := system.TheApp.NewWindow(opts)
if err != nil {
panic(err)
}
fmt.Println("got new window", w)
system.TheApp.MainLoop()
}
// Copyright 2023 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
_ "embed"
"fmt"
"image"
"image/color"
"time"
"unsafe"
"cogentcore.org/core/events"
"cogentcore.org/core/gpu"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/system"
"cogentcore.org/core/system/composer"
_ "cogentcore.org/core/system/driver"
"github.com/oliverbestmann/webgpu/wgpu"
)
//go:embed indexed.wgsl
var indexed string
type CamView struct {
Model math32.Matrix4
View math32.Matrix4
Projection math32.Matrix4
}
func main() {
opts := &system.NewWindowOptions{
Size: image.Pt(1024, 768),
StdPixels: true,
Title: "System Draw Triangle Indexed",
}
w, err := system.TheApp.NewWindow(opts)
if err != nil {
panic(err)
}
var sf *gpu.Surface
var sy *gpu.GraphicsSystem
var pl *gpu.GraphicsPipeline
var cam *gpu.Value
var camo CamView
make := func() {
dc, ok := w.Composer().(*composer.ComposerDrawer)
if ok {
sf = dc.Drawer.Renderer().(*gpu.Surface)
}
// todo: web version
sy = gpu.NewGraphicsSystem(sf.GPU, "drawidx", sf)
destroy := func() {
sy.Release()
}
w.SetDestroyGPUResourcesFunc(destroy)
pl = sy.AddGraphicsPipeline("drawidx")
pl.SetCullMode(wgpu.CullModeNone)
sy.SetClearColor(color.RGBA{50, 50, 50, 255})
sh := pl.AddShader("indexed")
sh.OpenCode(indexed)
pl.AddEntry(sh, gpu.VertexShader, "vs_main")
pl.AddEntry(sh, gpu.FragmentShader, "fs_main")
vgp := sy.Vars().AddVertexGroup()
ugp := sy.Vars().AddGroup(gpu.Uniform)
// vertex are dynamically sized in general, so using 0 here
posv := vgp.Add("Pos", gpu.Float32Vector3, 0, gpu.VertexShader)
clrv := vgp.Add("Color", gpu.Float32Vector3, 0, gpu.VertexShader)
// note: index goes last usually
idxv := vgp.Add("Index", gpu.Uint16, 0, gpu.VertexShader)
idxv.Role = gpu.Index
camv := ugp.AddStruct("Camera", int(unsafe.Sizeof(CamView{})), 1, gpu.VertexShader)
vgp.SetNValues(1)
ugp.SetNValues(1)
sy.Config()
triPos := posv.Values.Values[0]
gpu.SetValueFrom(triPos, []float32{
-0.5, 0.5, 0.0,
0.5, 0.5, 0.0,
0.0, -0.5, 0.0}) // negative point is UP in native Vulkan
triClr := clrv.Values.Values[0]
gpu.SetValueFrom(triClr, []float32{
1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0})
triIndex := idxv.Values.Values[0]
gpu.SetValueFrom(triIndex, []uint16{0, 1, 2})
// note: the only way to set indexes is at start..
// This is the standard camera view projection computation
cam = camv.Values.Values[0]
campos := math32.Vec3(0, 0, 2)
target := math32.Vec3(0, 0, 0)
var lookq math32.Quat
lookq.SetFromRotationMatrix(math32.NewLookAt(campos, target, math32.Vec3(0, 1, 0)))
scale := math32.Vec3(1, 1, 1)
var cview math32.Matrix4
cview.SetTransform(campos, lookq, scale)
view, _ := cview.Inverse()
camo.Model.SetIdentity()
camo.View.CopyFrom(view)
aspect := float32(sf.Format.Size.X) / float32(sf.Format.Size.Y)
fmt.Printf("aspect: %g\n", aspect)
camo.Projection.SetPerspective(45, aspect, 0.01, 100)
gpu.SetValueFrom(cam, []CamView{camo}) // note: always use slice to copy
fmt.Println("made and configured pipelines")
}
frameCount := 0
stTime := time.Now()
renderFrame := func() {
if sf == nil {
make()
}
// fmt.Printf("frame: %d\n", frameCount)
// rt := time.Now()
camo.Model.SetRotationY(.1 * float32(frameCount))
gpu.SetValueFrom(cam, []CamView{camo})
rp, err := sy.BeginRenderPass()
if err != nil {
return
}
pl.BindPipeline(rp)
pl.BindDrawIndexed(rp)
rp.End()
sy.EndRenderPass(rp)
frameCount++
eTime := time.Now()
dur := float64(eTime.Sub(stTime)) / float64(time.Second)
if dur > 10 {
fps := float64(frameCount) / dur
fmt.Printf("fps: %.0f\n", fps)
frameCount = 0
stTime = eTime
}
}
haveKeyboard := false
go func() {
for {
evi := w.Events().Deque.NextEvent()
et := evi.Type()
if et != events.WindowPaint && et != events.MouseMove {
fmt.Println("got event", evi)
}
switch et {
case events.Window:
ev := evi.(*events.WindowEvent)
fmt.Println("got window event", ev)
switch ev.Action {
case events.WinShow:
make()
case events.WinClose:
fmt.Println("got events.Close; quitting")
system.TheApp.Quit()
}
case events.WindowPaint:
if w.IsVisible() {
renderFrame()
} else {
fmt.Println("skipping paint event")
}
case events.MouseDown:
if haveKeyboard {
system.TheApp.HideVirtualKeyboard()
} else {
system.TheApp.ShowVirtualKeyboard(styles.KeyboardMultiLine)
}
haveKeyboard = !haveKeyboard
}
}
}()
system.TheApp.MainLoop()
}
// Copyright 2023 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
_ "embed"
"fmt"
"image"
"time"
"cogentcore.org/core/cursors"
"cogentcore.org/core/events"
"cogentcore.org/core/gpu"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/system"
"cogentcore.org/core/system/composer"
_ "cogentcore.org/core/system/driver"
"github.com/oliverbestmann/webgpu/wgpu"
)
//go:embed trianglelit.wgsl
var trianglelit string
func main() {
opts := &system.NewWindowOptions{
Size: image.Pt(1024, 768),
StdPixels: true,
Title: "System Draw Triangle",
}
w, err := system.TheApp.NewWindow(opts)
if err != nil {
panic(err)
}
system.TheApp.Cursor(w).SetSize(units.Dp(32))
var sf *gpu.Surface
var sy *gpu.GraphicsSystem
var pl *gpu.GraphicsPipeline
make := func() {
dc, ok := w.Composer().(*composer.ComposerDrawer)
if ok {
sf = dc.Drawer.Renderer().(*gpu.Surface)
}
// todo: web version
sy = gpu.NewGraphicsSystem(sf.GPU, "drawtri", sf)
destroy := func() {
sy.Release()
}
w.SetDestroyGPUResourcesFunc(destroy)
pl = sy.AddGraphicsPipeline("drawtri")
pl.SetFrontFace(wgpu.FrontFaceCW)
sh := pl.AddShader("trianglelit")
sh.OpenCode(trianglelit)
pl.AddEntry(sh, gpu.VertexShader, "vs_main")
pl.AddEntry(sh, gpu.FragmentShader, "fs_main")
sy.Config()
fmt.Println("made and configured pipelines")
}
frameCount := 0
cur := cursors.Arrow
stTime := time.Now()
renderFrame := func() {
if sf == nil {
make()
}
// fmt.Printf("frame: %d\n", frameCount)
// rt := time.Now()
rp, err := sy.BeginRenderPass()
if err != nil {
return
}
pl.BindPipeline(rp)
rp.Draw(3, 1, 0, 0)
rp.End()
sy.EndRenderPass(rp)
frameCount++
eTime := time.Now()
dur := float64(eTime.Sub(stTime)) / float64(time.Second)
if dur > 10 {
fps := float64(frameCount) / dur
fmt.Printf("fps: %.0f\n", fps)
frameCount = 0
stTime = eTime
}
if frameCount%60 == 0 {
cur++
if cur >= cursors.CursorN {
cur = cursors.Arrow
}
err := system.TheApp.Cursor(w).Set(cur)
if err != nil {
fmt.Println("error setting cursor:", err)
}
}
}
go func() {
for {
evi := w.Events().Deque.NextEvent()
et := evi.Type()
if et != events.WindowPaint && et != events.MouseMove {
fmt.Println("got event", evi)
}
switch et {
case events.Window:
ev := evi.(*events.WindowEvent)
fmt.Println("got window event", ev)
switch ev.Action {
case events.WinShow:
make()
case events.WinClose:
fmt.Println("got events.Close; quitting")
system.TheApp.Quit()
}
case events.WindowPaint:
// fmt.Println("paint")
renderFrame()
}
}
}()
system.TheApp.MainLoop()
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package system
import "strings"
// Locale represents a https://www.rfc-editor.org/rfc/bcp/bcp47.txt standard
// language tag, consisting of language and region, e.g., "en-US", "fr-FR", "ja-JP".
type Locale string
// Language returns the language portion of the locale tag (e.g., en, fr, ja)
func (l Locale) Language() string {
lang, _, _ := strings.Cut(string(l), "-")
return lang
}
// Region returns the region portion of the locale tag (e.g., US, FR, JA)
func (l Locale) Region() string {
_, region, _ := strings.Cut(string(l), "-")
return region
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package system
import (
"errors"
"slices"
"sync"
"time"
)
// Notification is a notification shown by the operating system, as for
// a reminder of something that is due.
type Notification struct {
// ID identifies the notification, which is passed to the function of
// [Notifier.OnClick] when it is clicked. The app's notifications
// should have different IDs.
ID string
// Title is the title of the notification, in bold.
Title string
// Body is the text of the notification, below the title.
Body string
// Time is when the notification is shown, for [Notifier.Sync].
Time time.Time
}
// MaxScheduled is the maximum number of notifications that
// [Notifier.Sync] schedules, the soonest ones, as iOS only keeps
// that many for an app.
const MaxScheduled = 64
// Notifier shows notifications with the notification system of the
// operating system (see [App.Notifier]). The methods return
// [errors.ErrUnsupported] where notifications are not supported,
// as on macOS for an app that is not in an app bundle.
type Notifier interface {
// RequestPermission asks the user for permission to show
// notifications, if they have not already answered, and then calls
// the given function with whether they are allowed. It returns
// without waiting for the answer, and the function is called on
// another goroutine. On the web, it must be called in the event
// handler of a click, as for a button that turns notifications on.
RequestPermission(fun func(allowed bool))
// Show shows the given notification now (its time is not used).
Show(n *Notification) error
// Sync schedules the given notifications to be shown at their times,
// replacing all of the notifications scheduled before, so it is
// called again with all of them when any of them changes, and with
// none to cancel them. Those whose time is past are not shown, and
// only the [MaxScheduled] soonest are scheduled. On macOS, iOS,
// Windows, and Android, the operating system shows them even when the
// app is not running; elsewhere, they are only shown while it runs.
Sync(ns []*Notification) error
// OnClick sets the function that is called with the ID of a
// notification when the user clicks it, which brings the app to the
// front. A click that starts the app (on iOS and Android) is passed
// to the function once it is set. Clicks are not reported on Windows
// yet. It is called on another goroutine, so it must lock the app as
// needed.
OnClick(fun func(id string))
}
// ScheduleOrder returns the notifications of the given list whose time is
// after now, sorted by time, and at most [MaxScheduled] of them, which are
// the notifications that [Notifier.Sync] schedules.
func ScheduleOrder(ns []*Notification, now time.Time) []*Notification {
var sched []*Notification
for _, n := range ns {
if n != nil && n.Time.After(now) {
sched = append(sched, n)
}
}
slices.SortStableFunc(sched, func(a, b *Notification) int {
return a.Time.Compare(b.Time)
})
if len(sched) > MaxScheduled {
sched = sched[:MaxScheduled]
}
return sched
}
// NotifierClicks has the click function of a [Notifier], for implementing
// [Notifier.OnClick].
type NotifierClicks struct {
mu sync.Mutex
click func(id string)
// pending is the ID of a notification clicked before the click
// function was set, as when the click started the app.
pending string
}
func (nc *NotifierClicks) OnClick(fun func(id string)) {
nc.mu.Lock()
nc.click = fun
pending := nc.pending
nc.pending = ""
nc.mu.Unlock()
if fun != nil && pending != "" {
go fun(pending)
}
}
// Clicked calls the click function for the notification with the given
// ID, which the user clicked. If it is not set yet, as when the click
// started the app, it is called with the ID once it is set.
func (nc *NotifierClicks) Clicked(id string) {
nc.mu.Lock()
fun := nc.click
if fun == nil {
nc.pending = id
}
nc.mu.Unlock()
if fun != nil {
fun(id)
}
}
// NotifierBase is a [Notifier] for where notifications are not supported,
// whose methods return [errors.ErrUnsupported].
type NotifierBase struct{}
var _ Notifier = &NotifierBase{}
func (nb *NotifierBase) RequestPermission(fun func(allowed bool)) { go fun(false) }
func (nb *NotifierBase) Show(n *Notification) error { return errors.ErrUnsupported }
func (nb *NotifierBase) Sync(ns []*Notification) error { return errors.ErrUnsupported }
func (nb *NotifierBase) OnClick(fun func(id string)) {}
// NotifierTimers is a [Notifier] that shows the notifications of
// [Notifier.Sync] with timers, for where the operating system cannot
// schedule them, so they are only shown while the app is running.
type NotifierTimers struct {
NotifierClicks
// ShowFunc shows the given notification now.
ShowFunc func(n *Notification) error
// PermissionFunc, if set, asks for permission
// (see [Notifier.RequestPermission]); otherwise it is allowed.
PermissionFunc func(fun func(allowed bool))
mu sync.Mutex
timers []*time.Timer
}
var _ Notifier = &NotifierTimers{}
func (nt *NotifierTimers) RequestPermission(fun func(allowed bool)) {
if nt.PermissionFunc == nil {
go fun(true)
return
}
nt.PermissionFunc(fun)
}
func (nt *NotifierTimers) Show(n *Notification) error {
return nt.ShowFunc(n)
}
func (nt *NotifierTimers) Sync(ns []*Notification) error {
nt.mu.Lock()
defer nt.mu.Unlock()
for _, t := range nt.timers {
t.Stop()
}
nt.timers = nil
now := time.Now()
for _, n := range ScheduleOrder(ns, now) {
nc := *n // a copy, as the caller can change it
nt.timers = append(nt.timers, time.AfterFunc(n.Time.Sub(now), func() {
nt.ShowFunc(&nc)
}))
}
return nil
}
// Copyright 2023 Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package system
import (
"fmt"
"log"
"os"
"path/filepath"
"runtime/debug"
"strings"
"time"
"cogentcore.org/core/base/errors"
)
// HandleRecover takes the given value of recover, and, if it is not nil,
// handles it. The behavior of HandleRecover can be customized by changing
// it to a custom function, but by default it calls [HandleRecoverBase] and
// [HandleRecoverPanic], which safely prints a stack trace, saves a crash log,
// and panics on non-mobile platforms. It is set in core to a function that does
// the aforementioned things in addition to creating a GUI error dialog.
// HandleRecover should be called at the start of every
// goroutine whenever possible. The correct usage of HandleRecover is:
//
// func myFunc() {
// defer func() { system.HandleRecover(recover()) }()
// ...
// }
var HandleRecover = func(r any) {
HandleRecoverBase(r)
HandleRecoverPanic(r)
}
// HandleRecoverBase is the default base value of [HandleRecover].
// It can be extended to form a different value of [HandleRecover].
// It prints a panic message and a stack trace, using a string-based log
// method that guarantees that the stack trace will be printed before
// the program exits. This is needed because, without this, the program
// may exit before it can print the stack trace on some systems like Android,
// which makes debugging nearly impossible. It also saves a crash log to
// [App.AppDataDir].
func HandleRecoverBase(r any) {
if r == nil {
return
}
stack := string(debug.Stack())
log.Println("panic:", r)
log.Println("")
log.Println("----- START OF STACK TRACE: -----")
log.Println(stack)
log.Println("----- END OF STACK TRACE -----")
dnm := filepath.Join(TheApp.AppDataDir(), "crash-logs")
err := os.MkdirAll(dnm, 0755)
if errors.Log(err) != nil {
return
}
cfnm := filepath.Join(dnm, "crash_"+time.Now().Format("2006-01-02_15-04-05"))
err = os.WriteFile(cfnm, []byte(CrashLogText(r, stack)), 0666)
if errors.Log(err) != nil {
return
}
cfnm = strings.ReplaceAll(cfnm, " ", `\ `) // escape spaces
log.Println("SAVED CRASH LOG TO", cfnm)
}
// HandleRecoverPanic panics on r if r is non-nil and [TheApp.Platform] is not mobile.
// This is because panicking screws up logging on mobile, but is necessary for debugging
// on desktop.
func HandleRecoverPanic(r any) {
if r == nil {
return
}
if !TheApp.Platform().IsMobile() || TheApp.Platform() == Web {
panic(r)
}
}
// CrashLogText returns an appropriate crash log string for the given recover value and stack trace.
func CrashLogText(r any, stack string) string {
info := TheApp.SystemInfo()
if info != "" {
info += "\n"
}
return fmt.Sprintf("Platform: %v\nSystem platform: %v\nApp version: %s\nCore version: %s\nTime: %s\n%s\npanic: %v\n\n%s", TheApp.Platform(), TheApp.SystemPlatform(), AppVersion, CoreVersion, time.Now().Format(time.DateTime), info, r, stack)
}
// crashOutputPrefix is the prefix of the files of the output of the Go
// runtime for crashes (see [SaveCrashOutput]).
const crashOutputPrefix = "runtime_"
// SaveCrashOutput makes the Go runtime write the output of a crash that
// [HandleRecover] does not handle, a panic in another goroutine or a fatal
// error (as a concurrent map read and write), with the stacks of all of the
// goroutines, to a file in the crash-logs of [App.AppDataDir], named for
// the time the app started. Otherwise that output goes to the standard
// error, which is lost for an app that is not run from a terminal, as an
// app bundle on macOS, which just exits. The files of earlier runs that
// did not crash, which are empty, are removed. It does nothing on mobile,
// on the web, and offscreen (as in tests).
func SaveCrashOutput() {
p := TheApp.Platform()
if p.IsMobile() || p == Web || p == Offscreen {
return
}
dnm := filepath.Join(TheApp.AppDataDir(), "crash-logs")
if errors.Log(os.MkdirAll(dnm, 0755)) != nil {
return
}
if old, err := filepath.Glob(filepath.Join(dnm, crashOutputPrefix+"*")); err == nil {
for _, f := range old {
if fi, err := os.Stat(f); err == nil && fi.Size() == 0 {
os.Remove(f)
}
}
}
fnm := filepath.Join(dnm, crashOutputPrefix+time.Now().Format("2006-01-02_15-04-05")+"_"+fmt.Sprint(os.Getpid()))
f, err := os.Create(fnm)
if errors.Log(err) != nil {
return
}
// with the stacks of all of the goroutines, as for a concurrent map
// write, whose other goroutine is the one to find
debug.SetTraceback("all")
errors.Log(debug.SetCrashOutput(f, debug.CrashOptions{}))
f.Close() // SetCrashOutput has its own copy
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// based on golang.org/x/exp/shiny:
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package system
import (
"image"
"cogentcore.org/core/math32"
)
var (
// LogicalDPIScale is the default scaling factor for Logical DPI
// as a multiplier on Physical DPI.
// Smaller numbers produce smaller font sizes etc.
LogicalDPIScale = float32(1)
// LogicalDPIScales are per-screen name versions of LogicalDPIScale
// these can be set from preferences (as in gi/prefs) on a per-screen
// basis.
LogicalDPIScales map[string]float32
// UpdateLogicalDPIScaleFunc is a function that updates the system
// LogicalDPIScale and the per-screen LogicalDPIScales map
UpdateLogicalDPIScaleFunc func()
)
// note: fields obtained from QScreen in Qt
// Screen contains data about each physical and/or logical screen.
type Screen struct {
// ScreenNumber is the index of this screen in the list of screens
// maintained under Screen.
ScreenNumber int
// Name is the name of the screen.
Name string
// Geometry contains the geometry of the screen in window manager
// size units, which may not be same as raw pixels (dots)
Geometry image.Rectangle
// DevicePixelRatio is a factor that scales the screen's
// "natural" pixel coordinates into actual device pixels.
// On OS-X, it is backingScaleFactor = 2.0 on "retina"
DevicePixelRatio float32
// PixelSize is the number of actual pixels in the screen
// (raw display dots), computed as Size * DevicePixelRatio
PixelSize image.Point
// PhysicalSize is the actual physical size of the screen, in mm.
PhysicalSize image.Point
// LogicalDPI is the logical dots per inch of the screen,
// which is used for all rendering.
// It is 160 * DevicePixelRatio * zoom factor, rounded to the nearest 6
// for optimal font rendering.
LogicalDPI float32
// PhysicalDPI is the physical dots per inch of the screen,
// for generating true-to-physical-size output.
// It is computed as 25.4 * (PixelSize.X / PhysicalSize.X)
// where 25.4 is the number of mm per inch.
PhysicalDPI float32
// Color depth of the screen, in bits.
Depth int
// Refresh rate in Hz
RefreshRate float32
// todo: not using these yet
// AvailableGeometry image.Rectangle
// VirtualGeometry image.Rectangle
// AvailableVirtualGeometry image.Rectangle
Orientation ScreenOrientation `table:"-"`
NativeOrientation ScreenOrientation `table:"-"`
PrimaryOrientation ScreenOrientation `table:"-"`
Manufacturer string `table:"-"`
Model string `table:"-"`
SerialNumber string `table:"-"`
}
// ScreenOrientation is the orientation of the device screen.
type ScreenOrientation int32 //enums:enum
const (
// OrientationUnknown means device orientation cannot be determined.
//
// Equivalent on Android to Configuration.ORIENTATION_UNKNOWN
// and on iOS to:
// UIDeviceOrientationUnknown
// UIDeviceOrientationFaceUp
// UIDeviceOrientationFaceDown
OrientationUnknown ScreenOrientation = iota
// Portrait is a device oriented so it is tall and thin.
//
// Equivalent on Android to Configuration.ORIENTATION_PORTRAIT
// and on iOS to:
// UIDeviceOrientationPortrait
// UIDeviceOrientationPortraitUpsideDown
Portrait
// Landscape is a device oriented so it is short and wide.
//
// Equivalent on Android to Configuration.ORIENTATION_LANDSCAPE
// and on iOS to:
// UIDeviceOrientationLandscapeLeft
// UIDeviceOrientationLandscapeRight
Landscape
)
// computeLogicalDPI computes the logical DPI used in actual screen scaling
// based on the given device pixel ratio and scaling factor. It also makes it a
// multiple of 6 to make normal font sizes look best. DPI is 160 * dpr * scale.
func computeLogicalDPI(dpr, scale float32) float32 {
dpi := 160 * dpr * scale
return 6 * math32.Round(dpi/6)
}
// SetLogicalDPIScale sets the LogicalDPIScale factor for given screen name
func SetLogicalDPIScale(scrnName string, dpiScale float32) {
if s, ok := LogicalDPIScales[scrnName]; ok && s == dpiScale {
return // (unchanged, as it is read in other goroutines)
}
if LogicalDPIScales == nil {
LogicalDPIScales = make(map[string]float32)
}
LogicalDPIScales[scrnName] = dpiScale
}
// UpdateLogicalDPI updates the logical DPI of the screen
// based on ZoomFactor and LogicalDPIScale (per screen if exists)
func (sc *Screen) UpdateLogicalDPI() {
scale := LogicalDPIScale
if LogicalDPIScales != nil {
if dsc, has := LogicalDPIScales[sc.Name]; has {
scale = dsc
}
}
if dpi := computeLogicalDPI(sc.DevicePixelRatio, scale); sc.LogicalDPI != dpi {
sc.LogicalDPI = dpi // (only when changed, as it is read in other goroutines)
}
}
// UpdatePhysicalDPI updates the value of [Screen.PhysicalDPI] based on
// [Screen.PixelSize] and [Screen.PhysicalSize]
func (sc *Screen) UpdatePhysicalDPI() {
sc.PhysicalDPI = 25.4 * (float32(sc.PixelSize.X) / float32(sc.PhysicalSize.X))
}
// WindowSizeToPixels returns window manager size units
// (where DevicePixelRatio is ignored) converted to pixel units --
// i.e., multiply by DevicePixelRatio
func (sc *Screen) WindowSizeToPixels(sz image.Point) image.Point {
var psz image.Point
psz.X = int(float32(sz.X) * sc.DevicePixelRatio)
psz.Y = int(float32(sz.Y) * sc.DevicePixelRatio)
return psz
}
// WindowSizeFromPixels returns window manager size units
// (where DevicePixelRatio is ignored) converted from pixel units --
// i.e., divide by DevicePixelRatio
func (sc *Screen) WindowSizeFromPixels(sz image.Point) image.Point {
var wsz image.Point
wsz.X = int(float32(sz.X) / sc.DevicePixelRatio)
wsz.Y = int(float32(sz.Y) / sc.DevicePixelRatio)
return wsz
}
// ConstrainWindowGeometry constrains window geometry to fit in the screen.
// Size is in pixel units.
func (sc *Screen) ConstrainWindowGeometry(pos, sz image.Point) (cpos, csz image.Point) {
scSize := sc.Geometry.Size() // in window coords size
if TheApp.Platform() == Windows {
// these are windows-specific special numbers for minimized windows
// can be sent here for WinGeom saved geom.
if pos.X == -32000 {
pos.X = 0
}
if pos.Y == -32000 {
pos.Y = 50
}
}
cpos, csz = ConstrainWindowGeometry(pos, sc.WindowSizeFromPixels(sz), scSize)
csz = sc.WindowSizeToPixels(csz)
return
}
// ConstrainWindowGeometry constrains the size and position of a window within
// given screen size, preserving the size to the extent possible.
// size is in window manager coordinates.
func ConstrainWindowGeometry(pos, sz, scSize image.Point) (cpos, csz image.Point) {
csz = sz
cpos = pos
if csz.X > scSize.X {
csz.X = scSize.X
}
if csz.Y > scSize.Y {
csz.Y = scSize.Y
}
// don't go off the edge
if cpos.X+csz.X > scSize.X {
cpos.X = scSize.X - csz.X
}
if cpos.Y+csz.Y > scSize.Y {
cpos.Y = scSize.Y - csz.Y
}
if cpos.X < 0 {
cpos.X = 0
}
if cpos.Y < 0 {
cpos.Y = 0
}
return
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package system
import "image"
// TextInput is the state of text input in a window, which the input
// method (IME) of the operating system uses, such as for composing
// Chinese, Japanese and Korean text (see [Window.SetTextInput]).
type TextInput struct {
// Caret is the rectangle of the text cursor, or of the cursor of
// the input method within the composition, in window coordinates
// (the same as those of events). The input method shows its
// candidate window next to it, typically below it.
Caret image.Rectangle
// Before is the text before the cursor, on its line, up to
// [TextInputBeforeMax] runes, or before the text being composed, which
// a virtual keyboard uses for its predictions and corrections (on iOS).
// It is empty for the text of a password.
Before string
}
// TextInputBeforeMax is the most runes of the text before the cursor in
// [TextInput.Before].
const TextInputBeforeMax = 200
// TextInputBefore returns the [TextInput.Before] text of the given text of
// the line of the cursor, up to the cursor: at most [TextInputBeforeMax]
// runes, after any newline.
func TextInputBefore(line []rune) string {
for i := len(line) - 1; i >= 0; i-- {
if line[i] == '\n' {
line = line[i+1:]
break
}
}
if n := len(line); n > TextInputBeforeMax {
line = line[n-TextInputBeforeMax:]
}
return string(line)
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// based on golang.org/x/exp/shiny:
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package system
import (
"image"
"unicode/utf8"
"cogentcore.org/core/base/fileinfo/mimedata"
"cogentcore.org/core/events"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles/sides"
"cogentcore.org/core/system/composer"
)
// Window is a double-buffered OS-specific hardware window.
//
// It provides basic GPU support functions, and is currently implemented
// via WebGPU. It uses glfw on desktop and native APIs on mobile and web.
//
// The Window maintains its own [Drawer] drawing system for rendering
// bitmap images and filled regions onto the window surface.
//
// The base full-window image should be drawn with a Scale call first,
// followed by any overlay images such as sprites or direct upload
// images already on the GPU (e.g., from 3D render frames)
type Window interface {
// Name returns the name of the window -- name is used strictly for
// internal tracking and finding of windows -- see Title for the displayed
// title of the window.
Name() string
// SetName sets the name of the window.
SetName(name string)
// Title returns the current title of the window, which is displayed in the GUI.
Title() string
// SetTitle sets the current title of the window, which is displayed in the GUI.
SetTitle(title string)
// SetIcon sets the icon of the window, which is displayed in the title bar
// and taskbar on Windows. It takes a list of candidate images and uses the
// one closest to the required size. Good sizes are 16x16, 32x32, and 48x48.
SetIcon(images []image.Image)
// Size returns the current size of the window, in raw underlying dots / pixels.
// This includes any high DPI factors that may not be used in OS window sizing
// (see WinSize for that size).
Size() image.Point
// WinSize returns the current size of the window, in OS-specific window manager
// units that may not include any high DPI factors.
WinSize() image.Point
// Position returns the current left-top position of the window,
// in OS-specific window manager coordinates.
// If the optional screen is non-nil, then coordinates are relative
// to that screen (e.g., pass window.Screen() for window's own screen).
Position(screen *Screen) image.Point
// RenderGeom returns the actual effective geometry of the window used
// for rendering content, which may be different from {0, [Window.Size]}
// due to insets caused by things like status bars and button overlays.
RenderGeom() math32.Geom2DInt
// SetWinSize sets the size of the window, in OS-specific window manager
// units that may not include any high DPI factors (DevicePixelRatio)
// (i.e., the same units as returned in WinSize())
SetWinSize(sz image.Point)
// SetSize sets the size of the window, in actual pixel units
// (i.e., the same units as returned by Size())
// Divides by DevicePixelRatio before calling SetWinSize.
// This method works on desktop and offscreen platforms.
SetSize(sz image.Point)
// SetPos sets the position of the window, in OS window manager
// coordinates, which may be different from Size() coordinates
// that reflect high DPI. If the optional screen argument is non-nil,
// then the position is relative to the given screen, so the window
// should move to be on the given screen assuming the coordinates are within
// its bounds. Otherwise, positions are in global coordinates interpreted
// relative to overall screen layouts in multi-monitor configurations.
SetPos(pos image.Point, screen *Screen)
// SetGeometry sets the full window geometry in one call, including full screen,
// position, and size. If fullscreen is true, then the position and size are
// ignored, but screen can be used to move to a different screen. For
// non-fullscreen, this method is preferred over separate [Window.SetPos]
// and [Window.SetSize]. Size is in actual pixel units (i.e., same units as
// returned by [Window.Size]), and pos is in OS-specific window manager units
// (i.e., as returned in [Window.Position]). If pos and/or size is not specified,
// it defaults to the current value. See [Window.SetPos] for information
// on the optional screen argument. This method only fully works on desktop
// platforms, with only fullscreen supported on web.
SetGeometry(fullscreen bool, pos image.Point, size image.Point, screen *Screen)
// ConstrainFrame ensures that the window frame is entirely within the
// window's screen, returning the size of each side of the frame.
// This will result in move and / or size events as needed.
// If topOnly is true, then only the top vertical axis is constrained, so that
// the window title bar does not go offscreen.
ConstrainFrame(topOnly bool) sides.Sides[int]
// Raise requests that the window be at the top of the stack of windows,
// and receive focus. If it is iconified, it will be de-iconified. This
// is the only supported mechanism for de-iconifying.
Raise()
// Minimize requests that the window be iconified, making it no longer
// visible or active -- rendering should not occur for minimized windows.
Minimize()
// Hide requests that the window be hidden, without an icon, as on macOS
// for a window whose app stays open when it is closed, until [Window.Raise]
// shows it again, as when the app's dock icon is clicked. A hidden window
// is [Minimized], so that it is not rendered. It is only supported on
// desktop platforms; elsewhere it does nothing.
Hide()
// PhysicalDPI is the physical dots per inch of the window, for generating
// true-to-physical-size output, for example -- see the gi/units package for
// translating into various other units.
PhysicalDPI() float32
// LogicalDPI returns the current logical dots-per-inch resolution of the
// window, which should be used for most conversion of standard units --
// physical DPI can be found in the Screen.
LogicalDPI() float32
// SetLogicalDPI sets the current logical dots-per-inch resolution of the
// window, which should be used for most conversion of standard units --
// physical DPI can be found in the Screen.
SetLogicalDPI(dpi float32)
// Screen returns the screen for this window, with all the relevant
// information about its properties.
Screen() *Screen
// Flags returns the bit flags for this window's properties set according
// to WindowFlags bits.
Flags() WindowFlags
// Is returns whether the window has the given flag.
Is(flag WindowFlags) bool
// IsClosed returns true if this window has been closed (but some threads
// may have not received the news yet)
IsClosed() bool
// IsVisible returns true if this window is not closed or minimized and
// there are active screens
IsVisible() bool
// SetCloseReqFunc sets the function that is called whenever there is a
// request to close the window (via a OS or a call to CloseReq() method). That
// function can then adjudicate whether and when to actually call Close.
SetCloseReqFunc(fun func(win Window))
// SetCloseCleanFunc sets the function that is called whenever window is
// actually about to close (irrevocably) -- can do any necessary
// last-minute cleanup here.
SetCloseCleanFunc(fun func(win Window))
// CloseReq is a close request, triggered either by OS or user call (e.g.,
// via Close menu action) -- calls function previously registered by
// SetCloseReqFunc, which is then solely responsible for actually calling
// Close.
CloseReq()
// CloseClean calls the function setup in SetCloseCleanFunc and does other
// window cleanup -- called on way to closing.
CloseClean()
// Close requests that the window be closed. The behavior of the Window
// after this, whether calling its methods or passing it as an argument,
// is undefined. See App.Quit methods to quit overall app.
Close()
// Sets the mouse position to given values
SetMousePos(x, y float64)
// Sets the mouse cursor to be enabled (true by default) or disabled (false).
// If disabled, setting raw to true will enable raw mouse movement
// which can provide better control in a game environment (not avail on Mac).
SetCursorEnabled(enabled, raw bool)
// IsCursorEnabled returns true or false if cursor is enabled
IsCursorEnabled() bool
// Composer returns the [composer.Composer] for rendering to this
// window surface.
Composer() composer.Composer
// Lock attempts to grab the overall window Mutex lock
// and returns true if the window is still open and ready for business.
// Otherwise, it might have been closed and any further use should be
// abandoned. Do this before any use of window resources
// (eg. rendering to the Drawer).
Lock() bool
// Unlock unlocks the Mutex. Must be called after Lock() is done.
Unlock()
// SetDestroyGPUResourcesFunc sets the given function
// that will be called on the main thread just prior
// to destroying the drawer and surface.
SetDestroyGPUResourcesFunc(f func())
// SetTitleBarIsDark sets whether the color theme of the window
// title bar is dark (as opposed to light).
SetTitleBarIsDark(isDark bool)
// Events returns the [events.Source] for this window,
// which manages all of the event sending.
Events() *events.Source
// SendPaintEvent sends the WindowPaint event.
// Other updates / polling may be done at this point too.
SendPaintEvent()
// PaintIdle pauses the paint events of the window, which are otherwise
// sent at the refresh rate of its screen, until [Window.PaintWake], as
// there is nothing to update in it, so that an idle app does not use
// the CPU.
PaintIdle()
// PaintWake resumes the paint events of the window, if paused by
// [Window.PaintIdle], as something in it needs to be updated. It can
// be called from any goroutine, and does not block.
PaintWake()
// StartDrag starts an operating system drag-and-drop of the given data
// from this window, so that it can be dropped in other windows and apps.
// It is used when a drag within the window leaves the window, while the
// mouse button is still down. files are absolute paths of files being
// dragged, which are provided to other apps as files; otherwise data is
// provided, for other Cogent Core apps and as text. img is the image
// shown under the mouse during the drag, with its top-left corner at the
// mouse. Drags over the windows of this app, including this window, are
// then sent as external drag events (see [events.Source.DragExternal]).
// It returns false if not supported on this platform.
StartDrag(data mimedata.Mimes, files []string, img image.Image) bool
// DragAccepted returns whether the last drag that the window started
// with [Window.StartDrag] was accepted by a drop target (as a window of
// any app that takes its data), once it has ended, with the release of
// the mouse button. It is false for a drag that was dropped where
// nothing accepted it (as onto the desktop), and it is true where that
// is not known, or the drag was canceled, where that is known.
DragAccepted() bool
// SetTextInput sets the state of text input in this window for the
// input method (IME) of the operating system, which sends the text
// being composed as [events.Composition] events. The focused text
// widget sets it when it gets the focus and when its cursor moves,
// and sets it to nil when it loses the focus, which also ends any
// composition. It does nothing on platforms without support.
SetTextInput(ti *TextInput)
}
////////////////////////////////////////////////////////////////////////////
// WindowOptions
// Qt options: http://doc.qt.io/qt-5/qt.html#WindowType-enum
// WindowFlags contains all the binary properties of a window -- by default
// with no other relevant flags a window is a main top-level window.
type WindowFlags int32 //enums:bitflag -atomic
const (
// Dialog indicates that this is a temporary, pop-up window.
Dialog WindowFlags = iota
// Modal indicates that this dialog window blocks events going to other
// windows until it is closed.
Modal
// Tool indicates that this is a floating tool window that has minimized
// window decoration.
Tool
// Maximized indicates a window that occupies the entire screen, but
// still has window decorations.
Maximized
// Fullscreen indicates a fullscreen window attached to a monitor.
// This results in no window decorations.
Fullscreen
// FixedSize indicates a window that cannot be resized.
FixedSize
// Minimized indicates a window reduced to an icon, or otherwise no longer
// visible or active. Otherwise, the window should be assumed to be
// visible.
Minimized
// Focused indicates that the window has the focus.
Focused
)
// NewWindowOptions are optional arguments to NewWindow.
type NewWindowOptions struct {
// Size specifies the dimensions of the new window, either in raw pixels
// or std 96 dpi pixels depending on StdPixels. If Width or Height are
// zero, a driver-dependent default will be used for each zero value
// dimension
Size image.Point
// StdPixels means use standardized "pixel" units for the window size (96
// per inch), not the actual underlying raw display dot pixels
StdPixels bool
// Pos specifies the position of the window, if non-zero -- always in
// device-specific raw pixels, and relative to the specified screen.
Pos image.Point
// Title specifies the window title.
Title string
// Screen is the screen number to open on. 0 default = primary monitor.
Screen int
// Icon specifies the window icon (see [Window.SetIcon] for more info).
// On macOS, where windows have no icons, the largest image, if it is
// at least 256x256, is the app icon in the Dock.
Icon []image.Image
// Flags can be set using WindowFlags to request different types of windows
Flags WindowFlags
}
// GetTitle returns a sanitized form of o.Title. In particular, its length will
// not exceed 4096, and it may be further truncated so that it is valid UTF-8
// and will not contain the NUL byte.
// o may be nil, in which case "" is returned.
func (o *NewWindowOptions) GetTitle() string {
if o == nil {
return ""
}
return sanitizeUTF8(o.Title, 4096)
}
func sanitizeUTF8(s string, n int) string {
if n < len(s) {
s = s[:n]
}
i := 0
for i < len(s) {
r, n := utf8.DecodeRuneInString(s[i:])
if r == 0 || (r == utf8.RuneError && n == 1) {
break
}
i += n
}
return s[:i]
}
// Fixup fills in defaults and updates everything based on current screen and
// window context. Specific hardware can fine-tune this as well, in driver code.
func (o *NewWindowOptions) Fixup() {
sc := TheApp.Screen(o.Screen)
scsz := sc.Geometry.Size() // window coords size
if o.Flags.HasFlag(Fullscreen) {
o.Size = sc.PixelSize
o.Pos = image.Point{}
return
}
if o.Size.X <= 0 {
o.StdPixels = false
o.Size.X = int(0.8 * float32(scsz.X) * sc.DevicePixelRatio)
}
if o.Size.Y <= 0 {
o.StdPixels = false
o.Size.Y = int(0.8 * float32(scsz.Y) * sc.DevicePixelRatio)
}
o.Pos, o.Size = sc.ConstrainWindowGeometry(o.Pos, o.Size)
if o.Pos.X == 0 && o.Pos.Y == 0 {
wsz := sc.WindowSizeFromPixels(o.Size)
dialog := o.Flags.HasFlag(Dialog)
modal := o.Flags.HasFlag(Modal)
nw := TheApp.NWindows()
if nw > 0 {
lastw := TheApp.Window(nw - 1)
lsz := lastw.WinSize()
lp := lastw.Position(nil)
nwbig := wsz.X > lsz.X || wsz.Y > lsz.Y
if modal || dialog || !nwbig { // place centered on top of current
ctrx := lp.X + (lsz.X / 2)
ctry := lp.Y + (lsz.Y / 2)
o.Pos.X = ctrx - wsz.X/2
o.Pos.Y = ctry - wsz.Y/2
} else { // cascade to right
o.Pos.X = lp.X + lsz.X // tile to right -- could depend on orientation
o.Pos.Y = lp.Y + 72 // and move down a bit
}
} else { // center in screen
o.Pos.X = scsz.X/2 - wsz.X/2
o.Pos.Y = scsz.Y/2 - wsz.Y/2
}
o.Pos, o.Size = sc.ConstrainWindowGeometry(o.Pos, o.Size) // make sure ok
}
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package csl
import (
"unicode"
"cogentcore.org/core/text/rich"
)
// definitive reference:
// https://apastyle.apa.org/style-grammar-guidelines/references/examples
// CiteAPA generates a APA-style citation, as Last[ & Last|et al.] Year
// with a , before Year in Parenthetical style, and Parens around the Year
// in Narrative style.
func CiteAPA(cs CiteStyles, it *Item) string {
c := ""
if len(it.Author) > 0 {
c = NamesCiteEtAl(it.Author)
} else {
c = NamesCiteEtAl(it.Editor)
}
switch cs {
case Parenthetical:
c += ", " + it.Issued.Year()
case Narrative:
c += " (" + it.Issued.Year() + ")"
}
return c
}
// RefAPA generates an APA-style reference entry from the given item,
// with rich.Text formatting of italics around the source, volume,
// and spans for each separate chunk.
// Use Join method to get full raw text.
func RefAPA(it *Item) rich.Text {
switch it.Type {
case Book, Collection:
return RefAPABook(it)
case Chapter, PaperConference:
return RefAPAChapter(it)
case Thesis:
return RefAPAThesis(it)
case Article, ArticleJournal, ArticleMagazine, ArticleNewspaper:
return RefAPAArticle(it)
default:
return RefAPAMisc(it)
}
}
// RefsAPA generates a list of APA-style reference entries
// and correspondingly ordered items for given keylist.
// APA uses alpha sort order.
func RefsAPA(kl *KeyList) ([]rich.Text, []*Item) {
refs := make([]rich.Text, kl.Len())
items := make([]*Item, kl.Len())
ks := kl.AlphaKeys()
for i, k := range ks {
it := kl.At(k)
refs[i] = RefAPA(it)
items[i] = it
}
return refs, items
}
func RefLinks(it *Item, tx *rich.Text) {
link := rich.NewStyle().SetLinkStyle()
if it.URL != "" {
tx.AddLink(link, it.URL, it.URL)
}
if it.DOI != "" {
url := "http://doi.org/" + it.DOI
tx.AddLink(link, url, " "+url)
}
}
// EnsurePeriod returns a string that ends with a . if it doesn't
// already end in some form of punctuation.
func EnsurePeriod(s string) string {
if !unicode.IsPunct(rune(s[len(s)-1])) {
s += "."
}
return s
}
func RefAPABook(it *Item) rich.Text {
sty := rich.NewStyle()
ital := sty.Clone().SetSlant(rich.Italic)
auths := ""
if len(it.Author) > 0 {
auths = NamesLastFirstInitialCommaAmpersand(it.Author)
} else if len(it.Editor) > 0 {
auths = NamesLastFirstInitialCommaAmpersand(it.Editor) + " (Ed"
if len(it.Editor) == 1 {
auths += ".)"
} else {
auths += "s.)"
}
}
tx := rich.NewText(sty, []rune(auths+" "))
tx.AddSpanString(sty, "("+it.Issued.Year()+"). ")
if it.Title != "" {
ttl := it.Title
end := rune(ttl[len(ttl)-1])
if it.Edition != "" {
if unicode.IsPunct(end) {
ttl = ttl[:len(ttl)-1]
} else {
end = '.'
}
tx.AddSpanString(ital, ttl)
tx.AddSpanString(sty, " ("+it.Edition+" ed)"+string(end)+" ")
} else {
tx.AddSpanString(ital, EnsurePeriod(ttl)+" ")
}
}
if it.Publisher != "" {
tx.AddSpanString(sty, " "+EnsurePeriod(it.Publisher)+" ")
}
RefLinks(it, &tx)
return tx
}
func RefAPAChapter(it *Item) rich.Text {
sty := rich.NewStyle()
ital := sty.Clone().SetSlant(rich.Italic)
tx := rich.NewText(sty, []rune(NamesLastFirstInitialCommaAmpersand(it.Author)+" "))
tx.AddSpanString(sty, "("+it.Issued.Year()+"). ")
contStyle := ital
if it.Title != "" {
if len(it.Editor) == 0 || it.ContainerTitle == "" {
contStyle = sty
tx.AddSpanString(ital, EnsurePeriod(it.Title)+" ")
} else {
tx.AddSpanString(sty, EnsurePeriod(it.Title)+" ")
}
}
if len(it.Editor) > 0 {
eds := "In " + NamesFirstInitialLastCommaAmpersand(it.Editor)
if len(it.Editor) == 1 {
eds += " (Ed.), "
} else {
eds += " (Eds.), "
}
tx.AddSpanString(sty, eds)
} else {
tx.AddSpanString(sty, "In ")
}
if it.ContainerTitle != "" {
ttl := it.ContainerTitle
end := rune(ttl[len(ttl)-1])
pp := ""
if it.Edition != "" {
pp = "(" + it.Edition + " ed."
}
if it.Page != "" {
if pp != "" {
pp += ", "
} else {
pp = "("
}
pp += "pp. " + it.Page
}
if pp != "" {
pp = " " + pp + ")"
if unicode.IsPunct(end) {
ttl = ttl[:len(ttl)-1]
pp += string(end)
} else {
pp += "."
}
tx.AddSpanString(contStyle, ttl)
tx.AddSpanString(sty, pp+" ")
} else {
tx.AddSpanString(contStyle, EnsurePeriod(it.ContainerTitle)+" ")
}
}
if it.Publisher != "" {
tx.AddSpanString(sty, EnsurePeriod(it.Publisher)+" ")
}
RefLinks(it, &tx)
return tx
}
func RefAPAArticle(it *Item) rich.Text {
sty := rich.NewStyle()
ital := sty.Clone().SetSlant(rich.Italic)
tx := rich.NewText(sty, []rune(NamesLastFirstInitialCommaAmpersand(it.Author)+" "))
tx.AddSpanString(sty, "("+it.Issued.Year()+"). ")
if it.Title != "" {
tx.AddSpanString(sty, EnsurePeriod(it.Title)+" ")
}
jt := ""
if it.ContainerTitle != "" {
jt = it.ContainerTitle + ", "
}
if it.Volume != "" {
jt += it.Volume
}
if jt != "" {
tx.AddSpanString(ital, jt)
}
if it.Volume != "" {
if it.Number != "" {
tx.AddSpanString(sty, "("+it.Number+"), ")
} else {
tx.AddSpanString(sty, ", ")
}
}
if it.Page != "" {
tx.AddSpanString(sty, it.Page+". ")
}
RefLinks(it, &tx)
return tx
}
func RefAPAThesis(it *Item) rich.Text {
sty := rich.NewStyle()
ital := sty.Clone().SetSlant(rich.Italic)
tx := rich.NewText(sty, []rune(NamesLastFirstInitialCommaAmpersand(it.Author)+" "))
tx.AddSpanString(sty, "("+it.Issued.Year()+"). ")
if it.Title != "" {
tx.AddSpanString(ital, EnsurePeriod(it.Title)+" ")
}
tt := "["
if it.Source == "" {
tt += "unpublished "
}
if it.Genre == "" {
tt += "thesis"
} else {
tt += it.Genre
}
if it.Publisher != "" {
tt += ", " + it.Publisher
}
tt += "]. "
tx.AddSpanString(sty, tt)
if it.Source != "" {
tx.AddSpanString(sty, EnsurePeriod(it.Source)+" ")
}
RefLinks(it, &tx)
return tx
}
func RefAPAMisc(it *Item) rich.Text {
sty := rich.NewStyle()
ital := sty.Clone().SetSlant(rich.Italic)
tx := rich.NewText(sty, []rune(NamesLastFirstInitialCommaAmpersand(it.Author)+" "))
tx.AddSpanString(sty, "("+it.Issued.Year()+"). ")
if it.Title != "" {
tx.AddSpanString(ital, EnsurePeriod(it.Title)+" ")
}
jt := ""
if it.ContainerTitle != "" {
jt = it.ContainerTitle + ", "
}
if it.Volume != "" {
jt += it.Volume
}
if jt != "" {
tx.AddSpanString(sty, jt)
}
if it.Volume != "" {
if it.Number != "" {
tx.AddSpanString(sty, "("+it.Number+"), ")
} else {
tx.AddSpanString(sty, ", ")
}
}
if it.Page != "" {
tx.AddSpanString(sty, it.Page+". ")
}
if it.Genre != "" {
tx.AddSpanString(sty, EnsurePeriod(it.Genre)+" ")
} else {
tx.AddSpanString(sty, it.Type.String()+". ")
}
if it.Source != "" {
tx.AddSpanString(sty, EnsurePeriod(it.Source)+" ")
}
if it.Publisher != "" {
tx.AddSpanString(sty, EnsurePeriod(it.Publisher)+" ")
}
RefLinks(it, &tx)
return tx
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package csl
import "strings"
// Date is a date of the CSL input model, which supports two different
// date representations:
// an EDTF string (preferred), and a more structured alternative.
type Date struct {
DateParts [][]any `json:"date-parts,omitempty"`
Season any `json:"season,omitempty"`
Circa string `json:"circa,omitempty"`
Literal string `json:"literal,omitempty"`
Raw string `json:"raw,omitempty"`
}
func (dt *Date) Year() string {
if len(dt.DateParts) > 0 {
if len(dt.DateParts[0]) > 0 {
return dt.DateParts[0][0].(string) // this is normally it
}
}
str := dt.Literal
if str == "" {
str = dt.Raw
}
if str == "" {
str = dt.Circa
}
if str == "" {
return "undated"
}
fs := strings.FieldsSeq(str)
for s := range fs {
if len(s) == 4 {
return s
}
}
return str
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package csl
import (
"io/fs"
"os"
"time"
"cogentcore.org/core/base/iox/jsonx"
"cogentcore.org/core/text/parse/languages/bibtex"
)
// Open opens CSL data items from a .json formatted CSL file.
func Open(filename string) ([]Item, error) {
var its []Item
err := jsonx.Open(&its, filename)
return its, err
}
// OpenFS opens CSL data items from a .json formatted CSL file from given
// filesystem.
func OpenFS(fsys fs.FS, filename string) ([]Item, error) {
var its []Item
err := jsonx.OpenFS(&its, fsys, filename)
return its, err
}
// SaveItems saves items to given filename.
func SaveItems(items []Item, filename string) error {
return jsonx.Save(items, filename)
}
// SaveKeyList saves items to given filename.
func SaveKeyList(kl *KeyList, filename string) error {
return jsonx.Save(kl.Values, filename)
}
//////// File
// File maintains a record for a CSL file.
type File struct {
// File name, full path.
File string
// Items from the file, as a KeyList for easy citation lookup.
Items *KeyList
// mod time for loaded file, to detect updates.
Mod time.Time
}
// Open [re]opens the given filename, looking on standard BIBINPUTS or TEXINPUTS
// env var paths if not found locally. If Mod >= mod timestamp on the file,
// and is already loaded, then nothing happens (already have it), but
// otherwise it parses the file and puts contents in Items.
func (fl *File) Open(fname string) error {
path := fname
var err error
if fl.File == "" {
path, err = bibtex.FullPath(fname)
if err != nil {
return err
}
fl.File = path
fl.Items = nil
fl.Mod = time.Time{}
// fmt.Printf("first open file: %s path: %s\n", fname, fl.File)
}
st, err := os.Stat(fl.File)
if err != nil {
return err
}
if fl.Items != nil && !fl.Mod.Before(st.ModTime()) {
// fmt.Printf("existing file: %v is fine: file mod: %v last mod: %v\n", fl.File, st.ModTime(), fl.Mod)
return nil
}
its, err := Open(fl.File)
if err != nil {
return err
}
fl.Items = NewKeyList(its)
fl.Mod = st.ModTime()
// fmt.Printf("(re)loaded bibtex bibliography: %s\n", fl.File)
return nil
}
//////// Files
// Files is a map of CSL items keyed by file name.
type Files map[string]*File
// Open [re]opens the given filename, looking on standard BIBINPUTS or TEXINPUTS
// env var paths if not found locally. If Mod >= mod timestamp on the file,
// and Items is already loaded, then nothing happens (already have it), but
// otherwise it parses the file and puts contents in Items field.
func (fl *Files) Open(fname string) (*File, error) {
if *fl == nil {
*fl = make(Files)
}
fr, has := (*fl)[fname]
if has {
err := fr.Open(fname)
return fr, err
}
fr = &File{}
err := fr.Open(fname)
if err != nil {
return nil, err
}
(*fl)[fname] = fr
return fr, nil
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package csl
import (
"fmt"
"slices"
"strings"
"cogentcore.org/core/base/keylist"
)
// KeyList is an ordered list of citation [Item]s,
// which should be used to collect items by unique citation keys.
type KeyList struct {
keylist.List[string, *Item]
}
// NewKeyList returns a KeyList from given list of [Item]s.
func NewKeyList(items []Item) *KeyList {
kl := &KeyList{}
for i := range items {
it := &items[i]
kl.Add(it.CitationKey, it)
}
return kl
}
// AddItems adds items to this KeyList, replacing any duplicates with new items.
func (kl *KeyList) AddItems(items []Item) {
for i := range items {
it := &items[i]
kl.Set(it.CitationKey, it)
}
}
// AlphaKeys returns an alphabetically sorted list of keys (case insensitive).
func (kl *KeyList) AlphaKeys() []string {
ks := slices.Clone(kl.Keys)
slices.SortFunc(ks, func(a, b string) int {
return strings.Compare(strings.ToLower(a), strings.ToLower(b))
})
return ks
}
// PrettyString pretty prints the items using default style.
func (kl *KeyList) PrettyString() string {
var w strings.Builder
for _, it := range kl.Values {
fmt.Fprintf(&w, "%s [%s]:\n", it.CitationKey, it.Type)
w.WriteString(string(Ref(DefaultStyle, it).Join()))
w.WriteString("\n\n")
}
return w.String()
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package csl
import (
"bufio"
"io"
"io/fs"
"regexp"
"strings"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/text/htmltext"
)
// GenerateMarkdown extracts markdown citations in the format [@Ref; @Ref]
// from given mds markdown files in given filesystem (use os.DirFS for filesys),
// looking up in given source [KeyList], and writing the results in given style to writer.
// Heading is written first: must include the appropriate markdown heading level
// (## typically). Returns the [KeyList] of references that were cited.
func GenerateMarkdown(w io.Writer, fsys fs.FS, heading string, kl *KeyList, sty Styles, mds ...string) (*KeyList, error) {
cited := &KeyList{}
var errs []error
err := ExtractMarkdownCites(fsys, mds, kl, cited)
if err != nil {
errs = append(errs, err)
}
if heading != "" {
w.Write([]byte(heading + "\n\n"))
}
err = WriteRefsMarkdown(w, cited, sty)
if err != nil {
errs = append(errs, err)
}
return cited, errors.Join(errs...)
}
// ExtractMarkdownCites extracts markdown citations in the format [@Ref; @Ref]
// from given list of .md files in given FS,
// looking up in given source [KeyList], adding to cited.
func ExtractMarkdownCites(fsys fs.FS, files []string, src, cited *KeyList) error {
exp := regexp.MustCompile(`\[(@\^?([[:alnum:]]+-?)+(;[[:blank:]]+)?)+\]`)
var errs []error
for _, fn := range files {
f, err := fsys.Open(fn)
if err != nil {
errs = append(errs, err)
continue
}
scan := bufio.NewScanner(f)
for scan.Scan() {
cs := exp.FindAllString(string(scan.Bytes()), -1)
for _, c := range cs {
tc := c[1 : len(c)-1]
sp := strings.SplitSeq(tc, "@")
for ac := range sp {
a := strings.TrimSpace(ac)
a = strings.TrimSuffix(a, ";")
if a == "" {
continue
}
if a[0] == '^' {
a = a[1:]
}
it, has := src.AtTry(a)
if !has {
err = errors.New("citation not found: " + a)
errs = append(errs, err)
continue
}
cited.Add(a, it)
}
}
}
if err := scan.Err(); err != nil {
errs = append(errs, err)
}
f.Close()
}
return errors.Join(errs...)
}
// WriteRefsMarkdown writes references from given [KeyList] to a
// markdown file.
func WriteRefsMarkdown(w io.Writer, kl *KeyList, sty Styles) error {
refs, items := Refs(sty, kl)
for i, ref := range refs {
it := items[i]
_, err := w.Write([]byte(`<p id="` + it.CitationKey + `">`))
if err != nil {
return err
}
str := htmltext.RichToHTML(ref)
_, err = w.Write([]byte(str + "</p>\n\n")) // todo: ref to markdown!!
if err != nil {
return err
}
}
return nil
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"os"
"path/filepath"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/fsx"
"cogentcore.org/core/cli"
"cogentcore.org/core/text/csl"
)
//go:generate core generate -add-types -add-funcs
type Config struct {
// CSL JSON formatted file(s) (comma-separated list) with the library
// of references to lookup citations in.
Refs []string `flag:"r,refs" posarg:"0"`
// Directory with markdown files to extract citations from.
// Defaults to current directory if empty.
Dir string `flag:"d,dir"`
// File name to write the formatted references to.
// Defaults to references.md if empty.
Output string `flag:"o,output"`
// File name to write the subset of cited reference data to.
// Defaults to citedrefs.json if empty.
CitedData string `flag:"c,cited"`
// heading to add to the top of the references file.
// Include markdown heading syntax, e.g., ##
// Defaults to ## References if empty.
Heading string `flag:"h,heading"`
// style is the citation style to generate.
// Defaults to APA if empty.
Style csl.Styles `flag:"s,style"`
}
// Generate extracts citations and generates resulting references file.
func Generate(c *Config) error {
var kl *csl.KeyList
for _, rf := range c.Refs {
refs, err := csl.Open(rf)
if err != nil {
return err
}
if kl == nil {
kl = csl.NewKeyList(refs)
} else {
kl.AddItems(refs)
}
}
if c.Dir == "" {
c.Dir = "." + string(filepath.Separator)
}
mds := fsx.Filenames(c.Dir, ".md")
if len(mds) == 0 {
return errors.New("No .md files found in: " + c.Dir)
}
if c.Output == "" {
c.Output = filepath.Join(c.Dir, "references.md")
}
of, err := os.Create(c.Output)
if errors.Log(err) != nil {
return err
}
defer of.Close()
cited, err := csl.GenerateMarkdown(of, os.DirFS(c.Dir), c.Heading, kl, c.Style, mds...)
cf := c.CitedData
if cf == "" {
cf = "citedrefs.json"
}
csl.SaveKeyList(cited, cf)
return err
}
func main() { //types:skip
opts := cli.DefaultOptions("mdcite", "mdcites extracts markdown citations from .md files in a directory, and writes a references file with the resulting citations, using the default APA style or the specified one.")
cli.Run(opts, &Config{}, Generate)
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package csl
import (
"fmt"
"strings"
)
// Name represents a persons name.
type Name struct {
Family string `json:"family,omitempty"`
Given string `json:"given,omitempty"`
DroppingParticle string `json:"dropping-particle,omitempty"`
NonDroppingParticle string `json:"non-dropping-particle,omitempty"`
Suffix string `json:"suffix,omitempty"`
CommaSuffix any `json:"comma-suffix,omitempty"`
StaticOrdering any `json:"static-ordering,omitempty"`
Literal string `json:"literal,omitempty"`
ParseNames any `json:"parse-names,omitempty"`
}
// NameFamilyGiven returns the family and given names from given name record,
// parsing what is available if not already parsed.
// todo: add suffix stuff!
func NameFamilyGiven(nm *Name) (family, given string) {
if nm.Family != "" && nm.Given != "" {
return nm.Family, nm.Given
}
pnm := ""
switch {
case nm.Family != "":
pnm = nm.Family
case nm.Given != "":
pnm = nm.Given
case nm.Literal != "":
pnm = nm.Literal
}
if pnm == "" {
fmt.Printf("csl.NameFamilyGiven name format error: no valid name: %#v\n", nm)
return
}
ci := strings.Index(pnm, ",")
if ci > 0 {
return pnm[:ci], strings.TrimSpace(pnm[ci+1:])
}
fs := strings.Fields(pnm)
nfs := len(fs)
if nfs > 1 {
return fs[nfs-1], strings.Join(fs[:nfs-1], " ")
}
return pnm, ""
}
// NamesLastFirstInitialCommaAmpersand returns a list of names
// formatted as a string, in the format: Last, F., Last, F., & Last., F.
func NamesLastFirstInitialCommaAmpersand(nms []Name) string {
var w strings.Builder
n := len(nms)
for i := range nms {
nm := &nms[i]
fam, giv := NameFamilyGiven(nm)
w.WriteString(fam)
if giv != "" {
w.WriteString(", ")
nf := strings.FieldsSeq(giv)
for fn := range nf {
w.WriteString(fn[0:1])
w.WriteString(".")
}
}
if i == n-1 {
break
}
if i == n-2 {
w.WriteString(", & ")
} else {
w.WriteString(", ")
}
}
return w.String()
}
// NamesFirstInitialLastCommaAmpersand returns a list of names
// formatted as a string, in the format: A.B. Last, C.D., Last & L.M. Last
func NamesFirstInitialLastCommaAmpersand(nms []Name) string {
var w strings.Builder
n := len(nms)
for i := range nms {
nm := &nms[i]
fam, giv := NameFamilyGiven(nm)
if giv != "" {
nf := strings.FieldsSeq(giv)
for fn := range nf {
w.WriteString(fn[0:1])
w.WriteString(".")
}
w.WriteString(" ")
}
w.WriteString(fam)
if i == n-1 {
break
}
if i == n-2 {
w.WriteString(", & ")
} else {
w.WriteString(", ")
}
}
return w.String()
}
// NamesCiteEtAl returns a list of names formatted for a
// citation within a document, as Last [et al..] or
// Last & Last if exactly two authors.
func NamesCiteEtAl(nms []Name) string {
var w strings.Builder
n := len(nms)
switch n {
case 0:
return "(None)"
case 1:
fam, _ := NameFamilyGiven(&nms[0])
w.WriteString(fam)
case 2:
fam, _ := NameFamilyGiven(&nms[0])
w.WriteString(fam)
w.WriteString(" & ")
fam, _ = NameFamilyGiven(&nms[1])
w.WriteString(fam)
default:
fam, _ := NameFamilyGiven(&nms[0])
w.WriteString(fam)
w.WriteString(" et al.")
}
return w.String()
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package csl
import "cogentcore.org/core/text/rich"
// DefaultStyle is the default citation and reference formatting style.
var DefaultStyle = APA
// Styles are CSL citation and reference formatting styles.
type Styles int32 //enums:enum
const (
APA Styles = iota
)
// CiteStyles are different types of citation styles that are supported by
// some formatting [Styles].
type CiteStyles int32 //enums:enum
const (
// Parenthetical means that the citation is placed within parentheses.
// This is default for most styles. In the APA style for example, it
// adds a comma before the year, e.g., "(Smith, 1989)".
// Note that the parentheses or other outer bracket syntax are NOT
// generated directly, because often multiple are included together
// in the same group.
Parenthetical CiteStyles = iota
// Narrative is an active, "inline" form of citation where the cited
// content is used as the subject of a sentence. In the APA style this
// puts the year in parentheses, e.g., "Smith (1989) invented the..."
// In this case the parentheses are generated.
Narrative
)
// Ref generates the reference text for given item,
// according to the given style.
func Ref(s Styles, it *Item) rich.Text {
switch s {
case APA:
return RefAPA(it)
}
return nil
}
// Refs returns a list of references and matching items
// according to the given [Styles] style.
func Refs(s Styles, kl *KeyList) ([]rich.Text, []*Item) {
switch s {
case APA:
return RefsAPA(kl)
}
return nil, nil
}
// RefsDefault returns a list of references and matching items
// according to the [DefaultStyle].
func RefsDefault(kl *KeyList) ([]rich.Text, []*Item) {
return Refs(DefaultStyle, kl)
}
// Cite generates the citation text for given item,
// according to the given overall style an citation style.
func Cite(s Styles, cs CiteStyles, it *Item) string {
switch s {
case APA:
return CiteAPA(cs, it)
}
return ""
}
// CiteDefault generates the citation text for given item,
// according to the [DefaultStyle] overall style, and given [CiteStyles].
func CiteDefault(cs CiteStyles, it *Item) string {
return Cite(DefaultStyle, cs, it)
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package diffbrowser
//go:generate core generate
import (
"cogentcore.org/core/base/fsx"
"cogentcore.org/core/base/stringsx"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/styles"
"cogentcore.org/core/text/textcore"
"cogentcore.org/core/tree"
)
// Browser is a diff browser, for browsing a set of paired files
// for viewing differences between them, organized into a tree
// structure, e.g., reflecting their source in a filesystem.
type Browser struct {
core.Frame
// starting paths for the files being compared
PathA, PathB string
}
func (br *Browser) Init() {
br.Frame.Init()
br.Styler(func(s *styles.Style) {
s.Grow.Set(1, 1)
})
br.OnShow(func(e events.Event) {
br.OpenFiles()
})
tree.AddChildAt(br, "splits", func(w *core.Splits) {
w.SetSplits(.15, .85)
tree.AddChildAt(w, "treeframe", func(w *core.Frame) {
w.Styler(func(s *styles.Style) {
s.Direction = styles.Column
s.Overflow.Set(styles.OverflowAuto)
s.Grow.Set(1, 1)
})
tree.AddChildAt(w, "tree", func(w *Node) {})
})
tree.AddChildAt(w, "tabs", func(w *core.Tabs) {
w.Type = core.FunctionalTabs
})
})
}
// NewBrowserWindow opens a new diff Browser in a new window
func NewBrowserWindow() (*Browser, *core.Body) {
b := core.NewBody("Diff browser")
br := NewBrowser(b)
br.UpdateTree() // must have tree
b.AddTopBar(func(bar *core.Frame) {
core.NewToolbar(bar).Maker(br.MakeToolbar)
})
return br, b
}
func (br *Browser) Splits() *core.Splits {
return br.FindPath("splits").(*core.Splits)
}
func (br *Browser) Tree() *Node {
sp := br.Splits()
return sp.Child(0).AsTree().Child(0).(*Node)
}
func (br *Browser) Tabs() *core.Tabs {
return br.FindPath("splits/tabs").(*core.Tabs)
}
// OpenFiles Updates the tree based on files
func (br *Browser) OpenFiles() { //types:add
tv := br.Tree()
if tv == nil {
return
}
tv.Open()
}
func (br *Browser) MakeToolbar(p *tree.Plan) {
// tree.Add(p, func(w *core.FuncButton) {
// w.SetFunc(br.OpenFiles).SetText("").SetIcon(icons.Refresh).SetShortcut("Command+U")
// })
}
// ViewDiff views diff for given file Node, returning a textcore.DiffEditor
func (br *Browser) ViewDiff(fn *Node) *textcore.DiffEditor {
df := fsx.DirAndFile(fn.FileA)
tabs := br.Tabs()
tab := tabs.RecycleTab(df)
if tab.HasChildren() {
dv := tab.Child(1).(*textcore.DiffEditor)
return dv
}
tb := core.NewToolbar(tab)
de := textcore.NewDiffEditor(tab)
tb.Maker(de.MakeToolbar)
de.SetFileA(fn.FileA).SetFileB(fn.FileB).SetRevisionA(fn.RevA).SetRevisionB(fn.RevB)
de.DiffStrings(stringsx.SplitLines(fn.TextA), stringsx.SplitLines(fn.TextB))
br.Update()
return de
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package diffbrowser
import (
"image"
"log/slog"
"os"
"path/filepath"
"slices"
"cogentcore.org/core/base/fileinfo"
"cogentcore.org/core/base/fsx"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/tree"
)
// Node is an element in the diff tree
type Node struct {
core.Tree
// file names (full path) being compared. Name of node is just the filename.
// Typically A is the older, base version and B is the newer one being compared.
FileA, FileB string
// VCS revisions for files if applicable
RevA, RevB string
// Status of the change from A to B: A=Added, D=Deleted, M=Modified, R=Renamed
Status string
// Text content of the files
TextA, TextB string
// Info about the B file, for getting icons etc
Info fileinfo.FileInfo
}
func (tn *Node) Init() {
tn.Tree.Init()
tn.IconOpen = icons.FolderOpen
tn.IconClosed = icons.Folder
tn.ContextMenus = nil
tn.AddContextMenu(tn.ContextMenu)
tn.Styler(func(s *styles.Style) {
s.IconSize.Set(units.Em(1))
})
tn.Parts.AsWidget().OnDoubleClick(func(e events.Event) {
if tn.HasChildren() {
return
}
br := tn.Browser()
if br == nil {
return
}
sels := tn.GetSelectedNodes()
if sels != nil {
br.ViewDiff(tn)
}
})
tn.Parts.Styler(func(s *styles.Style) {
s.Gap.X.Em(0.4)
})
}
// Browser returns the parent browser
func (tn *Node) Browser() *Browser {
return tree.ParentByType[*Browser](tn)
}
func (tn *Node) ContextMenu(m *core.Scene, pos image.Point) {
vd := core.NewButton(m).SetText("View Diffs").SetIcon(icons.Add)
vd.Styler(func(s *styles.Style) {
s.SetState(!tn.HasSelection(), states.Disabled)
})
vd.OnClick(func(e events.Event) {
br := tn.Browser()
if br == nil {
return
}
sels := tn.GetSelectedNodes()
sn := sels[len(sels)-1].(*Node)
br.ViewDiff(sn)
})
}
// DiffDirs creates a tree of files within the two paths,
// where the files have the same names, yet differ in content.
// The excludeFile function, if non-nil, will exclude files or
// directories from consideration if it returns true.
func (br *Browser) DiffDirs(pathA, pathB string, excludeFile func(fname string) bool) {
br.PathA = pathA
br.PathB = pathB
tv := br.Tree()
tv.SetText(fsx.DirAndFile(pathA))
br.diffDirsAt(pathA, pathB, tv, excludeFile)
}
// diffDirsAt creates a tree of files with the same names
// that differ within two dirs.
func (br *Browser) diffDirsAt(pathA, pathB string, node *Node, excludeFile func(fname string) bool) {
da := fsx.Dirs(pathA)
db := fsx.Dirs(pathB)
node.SetFileA(pathA).SetFileB(pathB)
for _, pa := range da {
if excludeFile != nil && excludeFile(pa) {
continue
}
for _, pb := range db {
if pa == pb {
nn := NewNode(node)
nn.SetText(pa)
br.diffDirsAt(filepath.Join(pathA, pa), filepath.Join(pathB, pb), nn, excludeFile)
}
}
}
fsa := fsx.Filenames(pathA)
fsb := fsx.Filenames(pathB)
for _, fa := range fsa {
isDir := slices.Contains(da, fa)
if isDir {
continue
}
if excludeFile != nil && excludeFile(fa) {
continue
}
for _, fb := range fsb {
if fa != fb {
continue
}
pfa := filepath.Join(pathA, fa)
pfb := filepath.Join(pathB, fb)
ca, err := os.ReadFile(pfa)
if err != nil {
slog.Error(err.Error())
continue
}
cb, err := os.ReadFile(pfb)
if err != nil {
slog.Error(err.Error())
continue
}
sa := string(ca)
sb := string(cb)
if sa == sb {
continue
}
nn := NewNode(node)
nn.SetText(fa)
nn.SetFileA(pfa).SetFileB(pfb).SetTextA(sa).SetTextB(sb)
nn.Info.InitFile(pfb)
nn.IconLeaf = nn.Info.Ic
}
}
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package diffbrowser
import (
"log/slog"
"maps"
"path/filepath"
"slices"
"strings"
"cogentcore.org/core/base/fsx"
"cogentcore.org/core/base/stringsx"
"cogentcore.org/core/base/vcs"
)
// NewDiffBrowserVCS returns a new diff browser for files that differ
// between two given revisions in the repository.
func NewDiffBrowserVCS(repo vcs.Repo, revA, revB string) {
brow, b := NewBrowserWindow()
brow.DiffVCS(repo, revA, revB)
b.RunWindow()
}
// DiffVCS creates a tree of the files changed between the given revisions
// (see [vcs.Repo.FilesChanged]), with a node for each directory, which has
// its subdirectories and then its files, each sorted by name, as in a file
// tree.
func (br *Browser) DiffVCS(repo vcs.Repo, revA, revB string) {
cinfo, err := repo.FilesChanged(revA, revB, false)
if err != nil {
slog.Error(err.Error())
return
}
br.PathA = repo.LocalPath()
br.PathB = br.PathA
root := br.Tree()
root.SetText(fsx.DirAndFile(br.PathA))
top := parseChanges(stringsx.SplitLines(string(cinfo)))
br.makeChangeNodes(root, top, "", repo, revA, revB)
}
// fileChange is a file changed between two revisions.
type fileChange struct {
// status is the status of the change: A, D, M, or R (renamed).
status string
// pathA and pathB are the paths of the file in the two revisions,
// relative to the repository, which differ if it was renamed.
pathA, pathB string
}
// changeDir is a directory of the changed files, with its subdirectories.
type changeDir struct {
dirs map[string]*changeDir
files []fileChange
}
// parseChanges returns the top directory of the changed files of the
// given lines of git diff --name-status (or the equivalent of another
// VCS): a status, then the path, and the new path of a renamed file,
// separated by tabs (paths can have spaces), or else by spaces. Files
// are in the directories of their paths in revision B.
func parseChanges(lines []string) *changeDir {
top := &changeDir{}
for _, ln := range lines {
fd := strings.Split(ln, "\t")
if len(fd) < 2 {
fd = strings.Fields(ln)
}
if len(fd) < 2 || fd[0] == "" {
continue
}
fc := fileChange{status: fd[0][:1], pathA: fd[1], pathB: fd[1]}
if len(fd) >= 3 {
fc.pathB = fd[2]
}
d := top
parts := strings.Split(filepath.ToSlash(fc.pathB), "/")
for _, p := range parts[:len(parts)-1] {
if d.dirs == nil {
d.dirs = map[string]*changeDir{}
}
sub := d.dirs[p]
if sub == nil {
sub = &changeDir{}
d.dirs[p] = sub
}
d = sub
}
d.files = append(d.files, fc)
}
return top
}
// makeChangeNodes makes the nodes of the given directory of changed files,
// at the given path relative to the repository, in the given parent node:
// those of its subdirectories, and then those of its files, each sorted
// by name, with the contents of the files at the revisions.
func (br *Browser) makeChangeNodes(parent *Node, d *changeDir, path string, repo vcs.Repo, revA, revB string) {
for _, name := range slices.Sorted(maps.Keys(d.dirs)) {
dp := filepath.Join(br.PathA, path, name)
nn := NewNode(parent)
nn.SetFileA(dp).SetFileB(dp)
nn.SetText(name)
br.makeChangeNodes(nn, d.dirs[name], filepath.Join(path, name), repo, revA, revB)
}
slices.SortFunc(d.files, func(a, b fileChange) int {
return strings.Compare(filepath.Base(a.pathB), filepath.Base(b.pathB))
})
for _, fc := range d.files {
dpa := filepath.Join(br.PathA, fc.pathA)
dpb := filepath.Join(br.PathA, fc.pathB)
nn := NewNode(parent)
nn.SetFileA(dpa).SetFileB(dpb).SetRevA(revA).SetRevB(revB).SetStatus(fc.status)
nn.SetText(filepath.Base(fc.pathB) + " [" + fc.status + "]")
if fc.status != "D" {
fbB, err := repo.FileContents(dpb, revB)
if err != nil {
slog.Error(err.Error())
}
nn.SetTextB(string(fbB))
nn.Info.InitFile(dpb)
nn.IconLeaf = nn.Info.Ic
}
if fc.status != "A" {
fbA, err := repo.FileContents(dpa, revA)
if err != nil {
slog.Error(err.Error())
}
nn.SetTextA(string(fbA))
if fc.status == "D" {
nn.Info.InitFile(dpa)
nn.IconLeaf = nn.Info.Ic
}
}
}
}
// Package bytes is a partial port of Python difflib module for bytes.
//
// It provides tools to compare sequences of bytes and generate textual diffs.
//
// The following class and functions have been ported:
//
// - SequenceMatcher
//
// - unified_diff
//
// - context_diff
//
// Getting unified diffs was the main goal of the port. Keep in mind this code
// is mostly suitable to output text differences in a human friendly way, there
// are no guarantees generated diffs are consumable by patch(1).
package bytes
import (
"bufio"
"bytes"
"errors"
"fmt"
"hash/adler32"
"io"
"strings"
"unicode"
)
func calculateRatio(matches, length int) float64 {
if length > 0 {
return 2.0 * float64(matches) / float64(length)
}
return 1.0
}
func listifyString(str []byte) (lst [][]byte) {
lst = make([][]byte, len(str))
for i := range str {
lst[i] = str[i : i+1]
}
return lst
}
type Match struct {
A int
B int
Size int
}
type OpCode struct {
Tag byte
I1 int
I2 int
J1 int
J2 int
}
type lineHash uint32
func _hash(line []byte) lineHash {
return lineHash(adler32.Checksum(line))
}
// B2J is essentially a map from lines to line numbers, so that later it can
// be made a bit cleverer than the standard map in that it will not need to
// store copies of the lines.
// It needs to hold a reference to the underlying slice of lines.
type B2J struct {
store map[lineHash][][]int
b [][]byte
}
type lineType int8
const (
lineNONE lineType = 0
lineNORMAL lineType = 1
lineJUNK lineType = -1
linePOPULAR lineType = -2
)
func (b2j *B2J) _find(line *[]byte) (h lineHash, slotIndex int,
slot []int, lt lineType) {
h = _hash(*line)
for slotIndex, slot = range b2j.store[h] {
// Thanks to the qualities of sha1, the probability of having more than
// one line content with the same hash is very low. Nevertheless, store
// each of them in a different slot, that we can differentiate by
// looking at the line contents in the b slice.
// In place of all the line numbers where the line appears, a slot can
// also contain [lineno, -1] if b[lineno] is junk.
if bytes.Equal(*line, b2j.b[slot[0]]) {
// The content already has a slot in its hash bucket.
if len(slot) == 2 && slot[1] < 0 {
lt = lineType(slot[1])
} else {
lt = lineNORMAL
}
return // every return variable has the correct value
}
}
// The line content still has no slot.
slotIndex = -1
slot = nil
lt = lineNONE
return
}
func newB2J(b [][]byte, isJunk func([]byte) bool, autoJunk bool) *B2J {
b2j := B2J{store: map[lineHash][][]int{}, b: b}
ntest := len(b)
if autoJunk && ntest >= 200 {
ntest = ntest/100 + 1
}
for lineno, line := range b {
h, slotIndex, slot, lt := b2j._find(&line)
switch lt {
case lineNORMAL:
if len(slot) >= ntest {
b2j.store[h][slotIndex] = []int{slot[0], int(linePOPULAR)}
} else {
b2j.store[h][slotIndex] = append(slot, lineno)
}
case lineNONE:
if isJunk != nil && isJunk(line) {
b2j.store[h] = append(b2j.store[h], []int{lineno, int(lineJUNK)})
} else {
b2j.store[h] = append(b2j.store[h], []int{lineno})
}
default:
}
}
return &b2j
}
func (b2j *B2J) get(line []byte) []int {
_, _, slot, lt := b2j._find(&line)
if lt == lineNORMAL {
return slot
}
return []int{}
}
func (b2j *B2J) isBJunk(line []byte) bool {
_, _, _, lt := b2j._find(&line)
return lt == lineJUNK
}
// SequenceMatcher compares sequence of strings. The basic
// algorithm predates, and is a little fancier than, an algorithm
// published in the late 1980's by Ratcliff and Obershelp under the
// hyperbolic name "gestalt pattern matching". The basic idea is to find
// the longest contiguous matching subsequence that contains no "junk"
// elements (R-O doesn't address junk). The same idea is then applied
// recursively to the pieces of the sequences to the left and to the right
// of the matching subsequence. This does not yield minimal edit
// sequences, but does tend to yield matches that "look right" to people.
//
// SequenceMatcher tries to compute a "human-friendly diff" between two
// sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the
// longest *contiguous* & junk-free matching subsequence. That's what
// catches peoples' eyes. The Windows(tm) windiff has another interesting
// notion, pairing up elements that appear uniquely in each sequence.
// That, and the method here, appear to yield more intuitive difference
// reports than does diff. This method appears to be the least vulnerable
// to synching up on blocks of "junk lines", though (like blank lines in
// ordinary text files, or maybe "<P>" lines in HTML files). That may be
// because this is the only method of the 3 that has a *concept* of
// "junk" <wink>.
//
// Timing: Basic R-O is cubic time worst case and quadratic time expected
// case. SequenceMatcher is quadratic time for the worst case and has
// expected-case behavior dependent in a complicated way on how many
// elements the sequences have in common; best case time is linear.
type SequenceMatcher struct {
a [][]byte
b [][]byte
b2j B2J
IsJunk func([]byte) bool
autoJunk bool
matchingBlocks []Match
fullBCount map[lineHash]int
opCodes []OpCode
}
func NewMatcher(a, b [][]byte) *SequenceMatcher {
m := SequenceMatcher{autoJunk: true}
m.SetSeqs(a, b)
return &m
}
func NewMatcherWithJunk(a, b [][]byte, autoJunk bool,
isJunk func([]byte) bool) *SequenceMatcher {
m := SequenceMatcher{IsJunk: isJunk, autoJunk: autoJunk}
m.SetSeqs(a, b)
return &m
}
// SetSeqs sets two sequences to be compared.
func (m *SequenceMatcher) SetSeqs(a, b [][]byte) {
m.SetSeq1(a)
m.SetSeq2(b)
}
// SetSeq1 sets the first sequence to be compared. The second sequence to be compared is
// not changed.
//
// SequenceMatcher computes and caches detailed information about the second
// sequence, so if you want to compare one sequence S against many sequences,
// use .SetSeq2(s) once and call .SetSeq1(x) repeatedly for each of the other
// sequences.
//
// See also SetSeqs() and SetSeq2().
func (m *SequenceMatcher) SetSeq1(a [][]byte) {
if &a == &m.a {
return
}
m.a = a
m.matchingBlocks = nil
m.opCodes = nil
}
// SetSeq2 sets the second sequence to be compared. The first sequence to be compared is
// not changed.
func (m *SequenceMatcher) SetSeq2(b [][]byte) {
if &b == &m.b {
return
}
m.b = b
m.matchingBlocks = nil
m.opCodes = nil
m.fullBCount = nil
m.chainB()
}
func (m *SequenceMatcher) chainB() {
// Populate line -> index mapping
b2j := *newB2J(m.b, m.IsJunk, m.autoJunk)
m.b2j = b2j
}
// Find longest matching block in a[alo:ahi] and b[blo:bhi].
//
// If IsJunk is not defined:
//
// Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where
//
// alo <= i <= i+k <= ahi
// blo <= j <= j+k <= bhi
//
// and for all (i',j',k') meeting those conditions,
//
// k >= k'
// i <= i'
// and if i == i', j <= j'
//
// In other words, of all maximal matching blocks, return one that
// starts earliest in a, and of all those maximal matching blocks that
// start earliest in a, return the one that starts earliest in b.
//
// If IsJunk is defined, first the longest matching block is
// determined as above, but with the additional restriction that no
// junk element appears in the block. Then that block is extended as
// far as possible by matching (only) junk elements on both sides. So
// the resulting block never matches on junk except as identical junk
// happens to be adjacent to an "interesting" match.
//
// If no blocks match, return (alo, blo, 0).
func (m *SequenceMatcher) findLongestMatch(alo, ahi, blo, bhi int) Match {
// CAUTION: stripping common prefix or suffix would be incorrect.
// E.g.,
// ab
// acab
// Longest matching block is "ab", but if common prefix is
// stripped, it's "a" (tied with "b"). UNIX(tm) diff does so
// strip, so ends up claiming that ab is changed to acab by
// inserting "ca" in the middle. That's minimal but unintuitive:
// "it's obvious" that someone inserted "ac" at the front.
// Windiff ends up at the same place as diff, but by pairing up
// the unique 'b's and then matching the first two 'a's.
besti, bestj, bestsize := alo, blo, 0
// find longest junk-free match
// during an iteration of the loop, j2len[j] = length of longest
// junk-free match ending with a[i-1] and b[j]
N := bhi - blo
j2len := make([]int, N)
newj2len := make([]int, N)
var indices []int
for i := alo; i != ahi; i++ {
// look at all instances of a[i] in b; note that because
// b2j has no junk keys, the loop is skipped if a[i] is junk
newindices := m.b2j.get(m.a[i])
for _, j := range newindices {
// a[i] matches b[j]
if j < blo {
continue
}
if j >= bhi {
break
}
k := 1
if j > blo {
k = j2len[j-1-blo] + 1
}
newj2len[j-blo] = k
if k > bestsize {
besti, bestj, bestsize = i-k+1, j-k+1, k
}
}
// j2len = newj2len, clear and reuse j2len as newj2len
for _, j := range indices {
if j < blo {
continue
}
if j >= bhi {
break
}
j2len[j-blo] = 0
}
indices = newindices
j2len, newj2len = newj2len, j2len
}
// Extend the best by non-junk elements on each end. In particular,
// "popular" non-junk elements aren't in b2j, which greatly speeds
// the inner loop above, but also means "the best" match so far
// doesn't contain any junk *or* popular non-junk elements.
for besti > alo && bestj > blo && !m.b2j.isBJunk(m.b[bestj-1]) &&
bytes.Equal(m.a[besti-1], m.b[bestj-1]) {
besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
}
for besti+bestsize < ahi && bestj+bestsize < bhi &&
!m.b2j.isBJunk(m.b[bestj+bestsize]) &&
bytes.Equal(m.a[besti+bestsize], m.b[bestj+bestsize]) {
bestsize += 1
}
// Now that we have a wholly interesting match (albeit possibly
// empty!), we may as well suck up the matching junk on each
// side of it too. Can't think of a good reason not to, and it
// saves post-processing the (possibly considerable) expense of
// figuring out what to do with it. In the case of an empty
// interesting match, this is clearly the right thing to do,
// because no other kind of match is possible in the regions.
for besti > alo && bestj > blo && m.b2j.isBJunk(m.b[bestj-1]) &&
bytes.Equal(m.a[besti-1], m.b[bestj-1]) {
besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
}
for besti+bestsize < ahi && bestj+bestsize < bhi &&
m.b2j.isBJunk(m.b[bestj+bestsize]) &&
bytes.Equal(m.a[besti+bestsize], m.b[bestj+bestsize]) {
bestsize += 1
}
return Match{A: besti, B: bestj, Size: bestsize}
}
// GetMatchingBlocks returns a list of triples describing matching subsequences.
//
// Each triple is of the form (i, j, n), and means that
// a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in
// i and in j. It's also guaranteed that if (i, j, n) and (i', j', n') are
// adjacent triples in the list, and the second is not the last triple in the
// list, then i+n != i' or j+n != j'. IOW, adjacent triples never describe
// adjacent equal blocks.
//
// The last triple is a dummy, (len(a), len(b), 0), and is the only
// triple with n==0.
func (m *SequenceMatcher) GetMatchingBlocks() []Match {
if m.matchingBlocks != nil {
return m.matchingBlocks
}
var matchBlocks func(alo, ahi, blo, bhi int, matched []Match) []Match
matchBlocks = func(alo, ahi, blo, bhi int, matched []Match) []Match {
match := m.findLongestMatch(alo, ahi, blo, bhi)
i, j, k := match.A, match.B, match.Size
if match.Size > 0 {
if alo < i && blo < j {
matched = matchBlocks(alo, i, blo, j, matched)
}
matched = append(matched, match)
if i+k < ahi && j+k < bhi {
matched = matchBlocks(i+k, ahi, j+k, bhi, matched)
}
}
return matched
}
matched := matchBlocks(0, len(m.a), 0, len(m.b), nil)
// It's possible that we have adjacent equal blocks in the
// matching_blocks list now.
var nonAdjacent []Match
i1, j1, k1 := 0, 0, 0
for _, b := range matched {
// Is this block adjacent to i1, j1, k1?
i2, j2, k2 := b.A, b.B, b.Size
if i1+k1 == i2 && j1+k1 == j2 {
// Yes, so collapse them -- this just increases the length of
// the first block by the length of the second, and the first
// block so lengthened remains the block to compare against.
k1 += k2
} else {
// Not adjacent. Remember the first block (k1==0 means it's
// the dummy we started with), and make the second block the
// new block to compare against.
if k1 > 0 {
nonAdjacent = append(nonAdjacent, Match{i1, j1, k1})
}
i1, j1, k1 = i2, j2, k2
}
}
if k1 > 0 {
nonAdjacent = append(nonAdjacent, Match{i1, j1, k1})
}
nonAdjacent = append(nonAdjacent, Match{len(m.a), len(m.b), 0})
m.matchingBlocks = nonAdjacent
return m.matchingBlocks
}
// GetOpCodes returns a list of 5-tuples describing how to turn a into b.
//
// Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple
// has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the
// tuple preceding it, and likewise for j1 == the previous j2.
//
// The tags are characters, with these meanings:
//
// 'r' (replace): a[i1:i2] should be replaced by b[j1:j2]
//
// 'd' (delete): a[i1:i2] should be deleted, j1==j2 in this case.
//
// 'i' (insert): b[j1:j2] should be inserted at a[i1:i1], i1==i2 in this case.
//
// 'e' (equal): a[i1:i2] == b[j1:j2]
func (m *SequenceMatcher) GetOpCodes() []OpCode {
if m.opCodes != nil {
return m.opCodes
}
i, j := 0, 0
matching := m.GetMatchingBlocks()
opCodes := make([]OpCode, 0, len(matching))
for _, m := range matching {
// invariant: we've pumped out correct diffs to change
// a[:i] into b[:j], and the next matching block is
// a[ai:ai+size] == b[bj:bj+size]. So we need to pump
// out a diff to change a[i:ai] into b[j:bj], pump out
// the matching block, and move (i,j) beyond the match
ai, bj, size := m.A, m.B, m.Size
tag := byte(0)
if i < ai && j < bj {
tag = 'r'
} else if i < ai {
tag = 'd'
} else if j < bj {
tag = 'i'
}
if tag > 0 {
opCodes = append(opCodes, OpCode{tag, i, ai, j, bj})
}
i, j = ai+size, bj+size
// the list of matching blocks is terminated by a
// sentinel with size 0
if size > 0 {
opCodes = append(opCodes, OpCode{'e', ai, i, bj, j})
}
}
m.opCodes = opCodes
return m.opCodes
}
// GetGroupedOpCodes isolates change clusters by eliminating ranges with no changes.
//
// Return a generator of groups with up to n lines of context.
// Each group is in the same format as returned by GetOpCodes().
func (m *SequenceMatcher) GetGroupedOpCodes(n int) [][]OpCode {
if n < 0 {
n = 3
}
codes := m.GetOpCodes()
if len(codes) == 0 {
codes = []OpCode{{'e', 0, 1, 0, 1}}
}
// Fixup leading and trailing groups if they show no changes.
if codes[0].Tag == 'e' {
c := codes[0]
i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
codes[0] = OpCode{c.Tag, max(i1, i2-n), i2, max(j1, j2-n), j2}
}
if codes[len(codes)-1].Tag == 'e' {
c := codes[len(codes)-1]
i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
codes[len(codes)-1] = OpCode{c.Tag, i1, min(i2, i1+n), j1, min(j2, j1+n)}
}
nn := n + n
var groups [][]OpCode
var group []OpCode
for _, c := range codes {
i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
// End the current group and start a new one whenever
// there is a large range with no changes.
if c.Tag == 'e' && i2-i1 > nn {
group = append(group, OpCode{c.Tag, i1, min(i2, i1+n),
j1, min(j2, j1+n)})
groups = append(groups, group)
group = []OpCode{}
i1, j1 = max(i1, i2-n), max(j1, j2-n)
}
group = append(group, OpCode{c.Tag, i1, i2, j1, j2})
}
if len(group) > 0 && (len(group) != 1 || group[0].Tag != 'e') {
groups = append(groups, group)
}
return groups
}
// Ratio returns a measure of the sequences' similarity (float in [0,1]).
//
// Where T is the total number of elements in both sequences, and
// M is the number of matches, this is 2.0*M / T.
// Note that this is 1 if the sequences are identical, and 0 if
// they have nothing in common.
//
// .Ratio() is expensive to compute if you haven't already computed
// .GetMatchingBlocks() or .GetOpCodes(), in which case you may
// want to try .QuickRatio() or .RealQuickRation() first to get an
// upper bound.
func (m *SequenceMatcher) Ratio() float64 {
matches := 0
for _, m := range m.GetMatchingBlocks() {
matches += m.Size
}
return calculateRatio(matches, len(m.a)+len(m.b))
}
// QuickRatio returns an upper bound on ratio() relatively quickly.
//
// This isn't defined beyond that it is an upper bound on .Ratio(), and
// is faster to compute.
func (m *SequenceMatcher) QuickRatio() float64 {
// viewing a and b as multisets, set matches to the cardinality
// of their intersection; this counts the number of matches
// without regard to order, so is clearly an upper bound. We do
// so on hashes of the lines themselves, so this might even be
// greater due hash collisions incurring false positives, but
// we don't care because we want an upper bound anyway.
if m.fullBCount == nil {
m.fullBCount = map[lineHash]int{}
for _, s := range m.b {
h := _hash(s)
m.fullBCount[h] = m.fullBCount[h] + 1
}
}
// avail[x] is the number of times x appears in 'b' less the
// number of times we've seen it in 'a' so far ... kinda
avail := map[lineHash]int{}
matches := 0
for _, s := range m.a {
h := _hash(s)
n, ok := avail[h]
if !ok {
n = m.fullBCount[h]
}
avail[h] = n - 1
if n > 0 {
matches += 1
}
}
return calculateRatio(matches, len(m.a)+len(m.b))
}
// RealQuickRatio returns an upper bound on ratio() very quickly.
//
// This isn't defined beyond that it is an upper bound on .Ratio(), and
// is faster to compute than either .Ratio() or .QuickRatio().
func (m *SequenceMatcher) RealQuickRatio() float64 {
la, lb := len(m.a), len(m.b)
return calculateRatio(min(la, lb), la+lb)
}
func countLeading(line []byte, ch byte) (count int) {
// Return number of `ch` characters at the start of `line`.
count = 0
n := len(line)
for (count < n) && (line[count] == ch) {
count++
}
return count
}
type DiffLine struct {
Tag byte
Line []byte
}
func NewDiffLine(tag byte, line []byte) (l DiffLine) {
l = DiffLine{}
l.Tag = tag
l.Line = line
return l
}
type Differ struct {
Linejunk func([]byte) bool
Charjunk func([]byte) bool
}
func NewDiffer() *Differ {
return &Differ{}
}
var MINUS = []byte("-")
var SPACE = []byte(" ")
var PLUS = []byte("+")
var CARET = []byte("^")
func (d *Differ) Compare(a [][]byte, b [][]byte) (diffs [][]byte, err error) {
// Compare two sequences of lines; generate the resulting delta.
// Each sequence must contain individual single-line strings ending with
// newlines. Such sequences can be obtained from the `readlines()` method
// of file-like objects. The delta generated also consists of newline-
// terminated strings, ready to be printed as-is via the writeline()
// method of a file-like object.
diffs = [][]byte{}
cruncher := NewMatcherWithJunk(a, b, true, d.Linejunk)
opcodes := cruncher.GetOpCodes()
for _, current := range opcodes {
alo := current.I1
ahi := current.I2
blo := current.J1
bhi := current.J2
var g [][]byte
switch current.Tag {
case 'r':
g, _ = d.FancyReplace(a, alo, ahi, b, blo, bhi)
case 'd':
g = d.Dump(MINUS, a, alo, ahi)
case 'i':
g = d.Dump(PLUS, b, blo, bhi)
case 'e':
g = d.Dump(SPACE, a, alo, ahi)
default:
return nil, fmt.Errorf("unknown tag %q", current.Tag)
}
diffs = append(diffs, g...)
}
return diffs, nil
}
func (d *Differ) StructuredDump(tag byte, x [][]byte, low int, high int) (out []DiffLine) {
size := high - low
out = make([]DiffLine, size)
for i := range size {
out[i] = NewDiffLine(tag, x[i+low])
}
return out
}
func (d *Differ) Dump(tag []byte, x [][]byte, low int, high int) (out [][]byte) {
// Generate comparison results for a same-tagged range.
sout := d.StructuredDump(tag[0], x, low, high)
out = make([][]byte, len(sout))
var bld bytes.Buffer
bld.Grow(1024)
for i, line := range sout {
bld.Reset()
bld.WriteByte(line.Tag)
bld.Write(SPACE)
bld.Write(line.Line)
out[i] = append(out[i], bld.Bytes()...)
}
return out
}
func (d *Differ) PlainReplace(a [][]byte, alo int, ahi int, b [][]byte, blo int, bhi int) (out [][]byte, err error) {
if (alo >= ahi) || (blo >= bhi) { // assertion
return nil, errors.New("low greater than or equal to high")
}
// dump the shorter block first -- reduces the burden on short-term
// memory if the blocks are of very different sizes
if bhi-blo < ahi-alo {
out = d.Dump(PLUS, b, blo, bhi)
out = append(out, d.Dump(MINUS, a, alo, ahi)...)
} else {
out = d.Dump(MINUS, a, alo, ahi)
out = append(out, d.Dump(PLUS, b, blo, bhi)...)
}
return out, nil
}
func (d *Differ) FancyReplace(a [][]byte, alo int, ahi int, b [][]byte, blo int, bhi int) (out [][]byte, err error) {
// When replacing one block of lines with another, search the blocks
// for *similar* lines; the best-matching pair (if any) is used as a
// synch point, and intraline difference marking is done on the
// similar pair. Lots of work, but often worth it.
// don't synch up unless the lines have a similarity score of at
// least cutoff; bestRatio tracks the best score seen so far
bestRatio := 0.74
cutoff := 0.75
cruncher := NewMatcherWithJunk(a, b, true, d.Charjunk)
eqi := -1 // 1st indices of equal lines (if any)
eqj := -1
out = [][]byte{}
// search for the pair that matches best without being identical
// (identical lines must be junk lines, & we don't want to synch up
// on junk -- unless we have to)
var bestI, bestJ int
for j := blo; j < bhi; j++ {
bj := b[j]
cruncher.SetSeq2(listifyString(bj))
for i := alo; i < ahi; i++ {
ai := a[i]
if bytes.Equal(ai, bj) {
if eqi == -1 {
eqi = i
eqj = j
}
continue
}
cruncher.SetSeq1(listifyString(ai))
// computing similarity is expensive, so use the quick
// upper bounds first -- have seen this speed up messy
// compares by a factor of 3.
// note that ratio() is only expensive to compute the first
// time it's called on a sequence pair; the expensive part
// of the computation is cached by cruncher
if cruncher.RealQuickRatio() > bestRatio &&
cruncher.QuickRatio() > bestRatio &&
cruncher.Ratio() > bestRatio {
bestRatio = cruncher.Ratio()
bestI = i
bestJ = j
}
}
}
if bestRatio < cutoff {
// no non-identical "pretty close" pair
if eqi == -1 {
// no identical pair either -- treat it as a straight replace
out, _ = d.PlainReplace(a, alo, ahi, b, blo, bhi)
return out, nil
}
// no close pair, but an identical pair -- synch up on that
bestI = eqi
bestJ = eqj
bestRatio = 1.0
} else {
// there's a close pair, so forget the identical pair (if any)
eqi = -1
}
// a[bestI] very similar to b[bestJ]; eqi is None iff they're not
// identical
// pump out diffs from before the synch point
out = append(out, d.fancyHelper(a, alo, bestI, b, blo, bestJ)...)
// do intraline marking on the synch pair
aelt, belt := a[bestI], b[bestJ]
if eqi == -1 {
// pump out a '-', '?', '+', '?' quad for the synched lines
var atags, btags []byte
cruncher.SetSeqs(listifyString(aelt), listifyString(belt))
opcodes := cruncher.GetOpCodes()
for _, current := range opcodes {
ai1 := current.I1
ai2 := current.I2
bj1 := current.J1
bj2 := current.J2
la, lb := ai2-ai1, bj2-bj1
switch current.Tag {
case 'r':
atags = append(atags, bytes.Repeat(CARET, la)...)
btags = append(btags, bytes.Repeat(CARET, lb)...)
case 'd':
atags = append(atags, bytes.Repeat(MINUS, la)...)
case 'i':
btags = append(btags, bytes.Repeat(PLUS, lb)...)
case 'e':
atags = append(atags, bytes.Repeat(SPACE, la)...)
btags = append(btags, bytes.Repeat(SPACE, lb)...)
default:
return nil, fmt.Errorf("unknown tag %q",
current.Tag)
}
}
out = append(out, d.QFormat(aelt, belt, atags, btags)...)
} else {
// the synch pair is identical
out = append(out, append([]byte{' ', ' '}, aelt...))
}
// pump out diffs from after the synch point
out = append(out, d.fancyHelper(a, bestI+1, ahi, b, bestJ+1, bhi)...)
return out, nil
}
func (d *Differ) fancyHelper(a [][]byte, alo int, ahi int, b [][]byte, blo int, bhi int) (out [][]byte) {
if alo < ahi {
if blo < bhi {
out, _ = d.FancyReplace(a, alo, ahi, b, blo, bhi)
} else {
out = d.Dump(MINUS, a, alo, ahi)
}
} else if blo < bhi {
out = d.Dump(PLUS, b, blo, bhi)
} else {
out = [][]byte{}
}
return out
}
func (d *Differ) QFormat(aline []byte, bline []byte, atags []byte, btags []byte) (out [][]byte) {
// Format "?" output and deal with leading tabs.
// Can hurt, but will probably help most of the time.
common := min(countLeading(aline, '\t'), countLeading(bline, '\t'))
common = min(common, countLeading(atags[:common], ' '))
common = min(common, countLeading(btags[:common], ' '))
atags = bytes.TrimRightFunc(atags[common:], unicode.IsSpace)
btags = bytes.TrimRightFunc(btags[common:], unicode.IsSpace)
out = [][]byte{append([]byte("- "), aline...)}
if len(atags) > 0 {
t := make([]byte, 0, len(atags)+common+3)
t = append(t, []byte("? ")...)
for i := 0; i < common; i++ {
t = append(t, byte('\t'))
}
t = append(t, atags...)
t = append(t, byte('\n'))
out = append(out, t)
}
out = append(out, append([]byte("+ "), bline...))
if len(btags) > 0 {
t := make([]byte, 0, len(btags)+common+3)
t = append(t, []byte("? ")...)
for i := 0; i < common; i++ {
t = append(t, byte('\t'))
}
t = append(t, btags...)
t = append(t, byte('\n'))
out = append(out, t)
}
return out
}
// Convert range to the "ed" format
func formatRangeUnified(start, stop int) []byte {
// Per the diff spec at http://www.unix.org/single_unix_specification/
beginning := start + 1 // lines start numbering with one
length := stop - start
if length == 1 {
return fmt.Appendf(nil, "%d", beginning)
}
if length == 0 {
beginning -= 1 // empty ranges begin at line just before the range
}
return fmt.Appendf(nil, "%d,%d", beginning, length)
}
// UnifiedDiff contains unified diff parameters
type UnifiedDiff struct {
A [][]byte // First sequence lines
FromFile string // First file name
FromDate string // First file time
B [][]byte // Second sequence lines
ToFile string // Second file name
ToDate string // Second file time
Eol []byte // Headers end of line, defaults to LF
Context int // Number of context lines
}
// WriteUnifiedDiff compares two sequences of lines and generates the delta as a unified diff.
//
// Unified diffs are a compact way of showing line changes and a few
// lines of context. The number of context lines is set by 'n' which
// defaults to three.
//
// By default, the diff control lines (those with ---, +++, or @@) are
// created with a trailing newline. This is helpful so that inputs
// created from file.readlines() result in diffs that are suitable for
// file.writelines() since both the inputs and outputs have trailing
// newlines.
//
// For inputs that do not have trailing newlines, set the lineterm
// argument to "" so that the output will be uniformly newline free.
//
// The unidiff format normally has a header for filenames and modification
// times. Any or all of these may be specified using strings for
// 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
// The modification times are normally expressed in the ISO 8601 format.
func WriteUnifiedDiff(writer io.Writer, diff UnifiedDiff) error {
//buf := bufio.NewWriter(writer)
//defer buf.Flush()
var bld strings.Builder
bld.Reset()
wf := func(format string, args ...any) error {
_, err := fmt.Fprintf(&bld, format, args...)
return err
}
ws := func(s []byte) error {
_, err := bld.Write(s)
return err
}
if len(diff.Eol) == 0 {
diff.Eol = []byte("\n")
}
started := false
m := NewMatcher(diff.A, diff.B)
for _, g := range m.GetGroupedOpCodes(diff.Context) {
if !started {
started = true
fromDate := ""
if len(diff.FromDate) > 0 {
fromDate = "\t" + diff.FromDate
}
toDate := ""
if len(diff.ToDate) > 0 {
toDate = "\t" + diff.ToDate
}
if diff.FromFile != "" || diff.ToFile != "" {
err := wf("--- %s%s%s", diff.FromFile, fromDate, diff.Eol)
if err != nil {
return err
}
err = wf("+++ %s%s%s", diff.ToFile, toDate, diff.Eol)
if err != nil {
return err
}
}
}
first, last := g[0], g[len(g)-1]
range1 := formatRangeUnified(first.I1, last.I2)
range2 := formatRangeUnified(first.J1, last.J2)
if err := wf("@@ -%s +%s @@%s", range1, range2, diff.Eol); err != nil {
return err
}
for _, c := range g {
i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
if c.Tag == 'e' {
for _, line := range diff.A[i1:i2] {
if err := ws(SPACE); err != nil {
return err
}
if err := ws(line); err != nil {
return err
}
}
continue
}
if c.Tag == 'r' || c.Tag == 'd' {
for _, line := range diff.A[i1:i2] {
if err := ws(MINUS); err != nil {
return err
}
if err := ws(line); err != nil {
return err
}
}
}
if c.Tag == 'r' || c.Tag == 'i' {
for _, line := range diff.B[j1:j2] {
if err := ws(PLUS); err != nil {
return err
}
if err := ws(line); err != nil {
return err
}
}
}
}
}
buf := bufio.NewWriter(writer)
buf.WriteString(bld.String())
buf.Flush()
return nil
}
// GetUnifiedDiffString is like WriteUnifiedDiff but returns the diff a []byte.
func GetUnifiedDiffString(diff UnifiedDiff) ([]byte, error) {
w := &bytes.Buffer{}
err := WriteUnifiedDiff(w, diff)
return w.Bytes(), err
}
// Convert range to the "ed" format.
func formatRangeContext(start, stop int) []byte {
// Per the diff spec at http://www.unix.org/single_unix_specification/
beginning := start + 1 // lines start numbering with one
length := stop - start
if length == 0 {
beginning -= 1 // empty ranges begin at line just before the range
}
if length <= 1 {
return fmt.Appendf(nil, "%d", beginning)
}
return fmt.Appendf(nil, "%d,%d", beginning, beginning+length-1)
}
type ContextDiff UnifiedDiff
// WriteContextDiff compare two sequences of lines and generates the delta as a context diff.
//
// Context diffs are a compact way of showing line changes and a few
// lines of context. The number of context lines is set by diff.Context
// which defaults to three.
//
// By default, the diff control lines (those with *** or ---) are
// created with a trailing newline.
//
// For inputs that do not have trailing newlines, set the diff.Eol
// argument to "" so that the output will be uniformly newline free.
//
// The context diff format normally has a header for filenames and
// modification times. Any or all of these may be specified using
// strings for diff.FromFile, diff.ToFile, diff.FromDate, diff.ToDate.
// The modification times are normally expressed in the ISO 8601 format.
// If not specified, the strings default to blanks.
func WriteContextDiff(writer io.Writer, diff ContextDiff) error {
buf := bufio.NewWriter(writer)
defer buf.Flush()
var diffErr error
wf := func(format string, args ...any) {
_, err := fmt.Fprintf(buf, format, args...)
if diffErr == nil && err != nil {
diffErr = err
}
}
ws := func(s []byte) {
_, err := buf.Write(s)
if diffErr == nil && err != nil {
diffErr = err
}
}
if len(diff.Eol) == 0 {
diff.Eol = []byte("\n")
}
prefix := map[byte][]byte{
'i': []byte("+ "),
'd': []byte("- "),
'r': []byte("! "),
'e': []byte(" "),
}
started := false
m := NewMatcher(diff.A, diff.B)
for _, g := range m.GetGroupedOpCodes(diff.Context) {
if !started {
started = true
fromDate := ""
if len(diff.FromDate) > 0 {
fromDate = "\t" + diff.FromDate
}
toDate := ""
if len(diff.ToDate) > 0 {
toDate = "\t" + diff.ToDate
}
if diff.FromFile != "" || diff.ToFile != "" {
wf("*** %s%s%s", diff.FromFile, fromDate, diff.Eol)
wf("--- %s%s%s", diff.ToFile, toDate, diff.Eol)
}
}
first, last := g[0], g[len(g)-1]
ws([]byte("***************"))
ws(diff.Eol)
range1 := formatRangeContext(first.I1, last.I2)
wf("*** %s ****%s", range1, diff.Eol)
for _, c := range g {
if c.Tag == 'r' || c.Tag == 'd' {
for _, cc := range g {
if cc.Tag == 'i' {
continue
}
for _, line := range diff.A[cc.I1:cc.I2] {
ws(prefix[cc.Tag])
ws(line)
}
}
break
}
}
range2 := formatRangeContext(first.J1, last.J2)
wf("--- %s ----%s", range2, diff.Eol)
for _, c := range g {
if c.Tag == 'r' || c.Tag == 'i' {
for _, cc := range g {
if cc.Tag == 'd' {
continue
}
for _, line := range diff.B[cc.J1:cc.J2] {
ws(prefix[cc.Tag])
ws(line)
}
}
break
}
}
}
return diffErr
}
// GetContextDiffString Like WriteContextDiff but returns the diff a []byte.
func GetContextDiffString(diff ContextDiff) ([]byte, error) {
w := &bytes.Buffer{}
err := WriteContextDiff(w, diff)
return w.Bytes(), err
}
// SplitLines splits a []byte on "\n" while preserving them. The output can be used
// as input for UnifiedDiff and ContextDiff structures.
func SplitLines(s []byte) [][]byte {
lines := bytes.SplitAfter(s, []byte("\n"))
lines[len(lines)-1] = append(lines[len(lines)-1], '\n')
return lines
}
// Package difflib is a partial port of Python difflib module.
//
// It provides tools to compare sequences of strings and generate textual diffs.
//
// The following class and functions have been ported:
//
// - SequenceMatcher
//
// - unified_diff
//
// - context_diff
//
// Getting unified diffs was the main goal of the port. Keep in mind this code
// is mostly suitable to output text differences in a human friendly way, there
// are no guarantees generated diffs are consumable by patch(1).
package difflib
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"strings"
"unicode"
)
func calculateRatio(matches, length int) float64 {
if length > 0 {
return 2.0 * float64(matches) / float64(length)
}
return 1.0
}
func listifyString(str string) (lst []string) {
lst = make([]string, len(str))
for i, c := range str {
lst[i] = string(c)
}
return lst
}
type Match struct {
A int
B int
Size int
}
type OpCode struct {
Tag byte
I1 int
I2 int
J1 int
J2 int
}
// SequenceMatcher compares sequence of strings. The basic
// algorithm predates, and is a little fancier than, an algorithm
// published in the late 1980's by Ratcliff and Obershelp under the
// hyperbolic name "gestalt pattern matching". The basic idea is to find
// the longest contiguous matching subsequence that contains no "junk"
// elements (R-O doesn't address junk). The same idea is then applied
// recursively to the pieces of the sequences to the left and to the right
// of the matching subsequence. This does not yield minimal edit
// sequences, but does tend to yield matches that "look right" to people.
//
// SequenceMatcher tries to compute a "human-friendly diff" between two
// sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the
// longest *contiguous* & junk-free matching subsequence. That's what
// catches peoples' eyes. The Windows(tm) windiff has another interesting
// notion, pairing up elements that appear uniquely in each sequence.
// That, and the method here, appear to yield more intuitive difference
// reports than does diff. This method appears to be the least vulnerable
// to synching up on blocks of "junk lines", though (like blank lines in
// ordinary text files, or maybe "<P>" lines in HTML files). That may be
// because this is the only method of the 3 that has a *concept* of
// "junk" <wink>.
//
// Timing: Basic R-O is cubic time worst case and quadratic time expected
// case. SequenceMatcher is quadratic time for the worst case and has
// expected-case behavior dependent in a complicated way on how many
// elements the sequences have in common; best case time is linear.
type SequenceMatcher struct {
a []string
b []string
b2j map[string][]int
IsJunk func(string) bool
autoJunk bool
bJunk map[string]bool
matchingBlocks []Match
fullBCount map[string]int
bPopular map[string]bool
opCodes []OpCode
}
func NewMatcher(a, b []string) *SequenceMatcher {
m := SequenceMatcher{autoJunk: true}
m.SetSeqs(a, b)
return &m
}
func NewMatcherWithJunk(a, b []string, autoJunk bool,
isJunk func(string) bool) *SequenceMatcher {
m := SequenceMatcher{IsJunk: isJunk, autoJunk: autoJunk}
m.SetSeqs(a, b)
return &m
}
// SetSeqs sets two sequences to be compared.
func (m *SequenceMatcher) SetSeqs(a, b []string) {
m.SetSeq1(a)
m.SetSeq2(b)
}
// SetSeq1 sets the first sequence to be compared. The second sequence to be compared is
// not changed.
//
// SequenceMatcher computes and caches detailed information about the second
// sequence, so if you want to compare one sequence S against many sequences,
// use .SetSeq2(s) once and call .SetSeq1(x) repeatedly for each of the other
// sequences.
//
// See also SetSeqs() and SetSeq2().
func (m *SequenceMatcher) SetSeq1(a []string) {
if &a == &m.a {
return
}
m.a = a
m.matchingBlocks = nil
m.opCodes = nil
}
// SetSeq2 sets the second sequence to be compared. The first sequence to be compared is
// not changed.
func (m *SequenceMatcher) SetSeq2(b []string) {
if &b == &m.b {
return
}
m.b = b
m.matchingBlocks = nil
m.opCodes = nil
m.fullBCount = nil
m.chainB()
}
func (m *SequenceMatcher) chainB() {
// Populate line -> index mapping
b2j := map[string][]int{}
junk := map[string]bool{}
popular := map[string]bool{}
ntest := len(m.b)
if m.autoJunk && ntest >= 200 {
ntest = ntest/100 + 1
}
for i, s := range m.b {
if !junk[s] {
if m.IsJunk != nil && m.IsJunk(s) {
junk[s] = true
} else if !popular[s] {
ids := append(b2j[s], i)
if len(ids) <= ntest {
b2j[s] = ids
} else {
delete(b2j, s)
popular[s] = true
}
}
}
}
m.b2j = b2j
m.bJunk = junk
m.bPopular = popular
}
func (m *SequenceMatcher) isBJunk(s string) bool {
_, ok := m.bJunk[s]
return ok
}
// Find longest matching block in a[alo:ahi] and b[blo:bhi].
//
// If IsJunk is not defined:
//
// Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where
//
// alo <= i <= i+k <= ahi
// blo <= j <= j+k <= bhi
//
// and for all (i',j',k') meeting those conditions,
//
// k >= k'
// i <= i'
// and if i == i', j <= j'
//
// In other words, of all maximal matching blocks, return one that
// starts earliest in a, and of all those maximal matching blocks that
// start earliest in a, return the one that starts earliest in b.
//
// If IsJunk is defined, first the longest matching block is
// determined as above, but with the additional restriction that no
// junk element appears in the block. Then that block is extended as
// far as possible by matching (only) junk elements on both sides. So
// the resulting block never matches on junk except as identical junk
// happens to be adjacent to an "interesting" match.
//
// If no blocks match, return (alo, blo, 0).
func (m *SequenceMatcher) findLongestMatch(alo, ahi, blo, bhi int) Match {
// CAUTION: stripping common prefix or suffix would be incorrect.
// E.g.,
// ab
// acab
// Longest matching block is "ab", but if common prefix is
// stripped, it's "a" (tied with "b"). UNIX(tm) diff does so
// strip, so ends up claiming that ab is changed to acab by
// inserting "ca" in the middle. That's minimal but unintuitive:
// "it's obvious" that someone inserted "ac" at the front.
// Windiff ends up at the same place as diff, but by pairing up
// the unique 'b's and then matching the first two 'a's.
besti, bestj, bestsize := alo, blo, 0
// find longest junk-free match
// during an iteration of the loop, j2len[j] = length of longest
// junk-free match ending with a[i-1] and b[j]
N := bhi - blo
j2len := make([]int, N)
newj2len := make([]int, N)
var indices []int
for i := alo; i != ahi; i++ {
// look at all instances of a[i] in b; note that because
// b2j has no junk keys, the loop is skipped if a[i] is junk
newindices := m.b2j[m.a[i]]
for _, j := range newindices {
// a[i] matches b[j]
if j < blo {
continue
}
if j >= bhi {
break
}
k := 1
if j > blo {
k = j2len[j-1-blo] + 1
}
newj2len[j-blo] = k
if k > bestsize {
besti, bestj, bestsize = i-k+1, j-k+1, k
}
}
// j2len = newj2len, clear and reuse j2len as newj2len
for _, j := range indices {
if j < blo {
continue
}
if j >= bhi {
break
}
j2len[j-blo] = 0
}
indices = newindices
j2len, newj2len = newj2len, j2len
}
// Extend the best by non-junk elements on each end. In particular,
// "popular" non-junk elements aren't in b2j, which greatly speeds
// the inner loop above, but also means "the best" match so far
// doesn't contain any junk *or* popular non-junk elements.
for besti > alo && bestj > blo && !m.isBJunk(m.b[bestj-1]) &&
m.a[besti-1] == m.b[bestj-1] {
besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
}
for besti+bestsize < ahi && bestj+bestsize < bhi &&
!m.isBJunk(m.b[bestj+bestsize]) &&
m.a[besti+bestsize] == m.b[bestj+bestsize] {
bestsize += 1
}
// Now that we have a wholly interesting match (albeit possibly
// empty!), we may as well suck up the matching junk on each
// side of it too. Can't think of a good reason not to, and it
// saves post-processing the (possibly considerable) expense of
// figuring out what to do with it. In the case of an empty
// interesting match, this is clearly the right thing to do,
// because no other kind of match is possible in the regions.
for besti > alo && bestj > blo && m.isBJunk(m.b[bestj-1]) &&
m.a[besti-1] == m.b[bestj-1] {
besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
}
for besti+bestsize < ahi && bestj+bestsize < bhi &&
m.isBJunk(m.b[bestj+bestsize]) &&
m.a[besti+bestsize] == m.b[bestj+bestsize] {
bestsize += 1
}
return Match{A: besti, B: bestj, Size: bestsize}
}
// GetMatchingBlocks returns a list of triples describing matching subsequences.
//
// Each triple is of the form (i, j, n), and means that
// a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in
// i and in j. It's also guaranteed that if (i, j, n) and (i', j', n') are
// adjacent triples in the list, and the second is not the last triple in the
// list, then i+n != i' or j+n != j'. IOW, adjacent triples never describe
// adjacent equal blocks.
//
// The last triple is a dummy, (len(a), len(b), 0), and is the only
// triple with n==0.
func (m *SequenceMatcher) GetMatchingBlocks() []Match {
if m.matchingBlocks != nil {
return m.matchingBlocks
}
var matchBlocks func(alo, ahi, blo, bhi int, matched []Match) []Match
matchBlocks = func(alo, ahi, blo, bhi int, matched []Match) []Match {
match := m.findLongestMatch(alo, ahi, blo, bhi)
i, j, k := match.A, match.B, match.Size
if match.Size > 0 {
if alo < i && blo < j {
matched = matchBlocks(alo, i, blo, j, matched)
}
matched = append(matched, match)
if i+k < ahi && j+k < bhi {
matched = matchBlocks(i+k, ahi, j+k, bhi, matched)
}
}
return matched
}
matched := matchBlocks(0, len(m.a), 0, len(m.b), nil)
// It's possible that we have adjacent equal blocks in the
// matching_blocks list now.
var nonAdjacent []Match
i1, j1, k1 := 0, 0, 0
for _, b := range matched {
// Is this block adjacent to i1, j1, k1?
i2, j2, k2 := b.A, b.B, b.Size
if i1+k1 == i2 && j1+k1 == j2 {
// Yes, so collapse them -- this just increases the length of
// the first block by the length of the second, and the first
// block so lengthened remains the block to compare against.
k1 += k2
} else {
// Not adjacent. Remember the first block (k1==0 means it's
// the dummy we started with), and make the second block the
// new block to compare against.
if k1 > 0 {
nonAdjacent = append(nonAdjacent, Match{i1, j1, k1})
}
i1, j1, k1 = i2, j2, k2
}
}
if k1 > 0 {
nonAdjacent = append(nonAdjacent, Match{i1, j1, k1})
}
nonAdjacent = append(nonAdjacent, Match{len(m.a), len(m.b), 0})
m.matchingBlocks = nonAdjacent
return m.matchingBlocks
}
// GetOpCodes returns a list of 5-tuples describing how to turn a into b.
//
// Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple
// has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the
// tuple preceding it, and likewise for j1 == the previous j2.
//
// The tags are characters, with these meanings:
//
// 'r' (replace): a[i1:i2] should be replaced by b[j1:j2]
//
// 'd' (delete): a[i1:i2] should be deleted, j1==j2 in this case.
//
// 'i' (insert): b[j1:j2] should be inserted at a[i1:i1], i1==i2 in this case.
//
// 'e' (equal): a[i1:i2] == b[j1:j2]
func (m *SequenceMatcher) GetOpCodes() []OpCode {
if m.opCodes != nil {
return m.opCodes
}
i, j := 0, 0
matching := m.GetMatchingBlocks()
opCodes := make([]OpCode, 0, len(matching))
for _, m := range matching {
// invariant: we've pumped out correct diffs to change
// a[:i] into b[:j], and the next matching block is
// a[ai:ai+size] == b[bj:bj+size]. So we need to pump
// out a diff to change a[i:ai] into b[j:bj], pump out
// the matching block, and move (i,j) beyond the match
ai, bj, size := m.A, m.B, m.Size
tag := byte(0)
if i < ai && j < bj {
tag = 'r'
} else if i < ai {
tag = 'd'
} else if j < bj {
tag = 'i'
}
if tag > 0 {
opCodes = append(opCodes, OpCode{tag, i, ai, j, bj})
}
i, j = ai+size, bj+size
// the list of matching blocks is terminated by a
// sentinel with size 0
if size > 0 {
opCodes = append(opCodes, OpCode{'e', ai, i, bj, j})
}
}
m.opCodes = opCodes
return m.opCodes
}
// GetGroupedOpCodes isolates change clusters by eliminating ranges with no changes.
//
// Return a generator of groups with up to n lines of context.
// Each group is in the same format as returned by GetOpCodes().
func (m *SequenceMatcher) GetGroupedOpCodes(n int) [][]OpCode {
if n < 0 {
n = 3
}
codes := m.GetOpCodes()
if len(codes) == 0 {
codes = []OpCode{{'e', 0, 1, 0, 1}}
}
// Fixup leading and trailing groups if they show no changes.
if codes[0].Tag == 'e' {
c := codes[0]
i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
codes[0] = OpCode{c.Tag, max(i1, i2-n), i2, max(j1, j2-n), j2}
}
if codes[len(codes)-1].Tag == 'e' {
c := codes[len(codes)-1]
i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
codes[len(codes)-1] = OpCode{c.Tag, i1, min(i2, i1+n), j1, min(j2, j1+n)}
}
nn := n + n
var (
groups [][]OpCode
group []OpCode
)
for _, c := range codes {
i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
// End the current group and start a new one whenever
// there is a large range with no changes.
if c.Tag == 'e' && i2-i1 > nn {
group = append(group, OpCode{c.Tag, i1, min(i2, i1+n),
j1, min(j2, j1+n)})
groups = append(groups, group)
group = []OpCode{}
i1, j1 = max(i1, i2-n), max(j1, j2-n)
}
group = append(group, OpCode{c.Tag, i1, i2, j1, j2})
}
if len(group) > 0 && (len(group) != 1 || group[0].Tag != 'e') {
groups = append(groups, group)
}
return groups
}
// Ratio returns a measure of the sequences' similarity (float in [0,1]).
//
// Where T is the total number of elements in both sequences, and
// M is the number of matches, this is 2.0*M / T.
// Note that this is 1 if the sequences are identical, and 0 if
// they have nothing in common.
//
// .Ratio() is expensive to compute if you haven't already computed
// .GetMatchingBlocks() or .GetOpCodes(), in which case you may
// want to try .QuickRatio() or .RealQuickRation() first to get an
// upper bound.
func (m *SequenceMatcher) Ratio() float64 {
matches := 0
for _, m := range m.GetMatchingBlocks() {
matches += m.Size
}
return calculateRatio(matches, len(m.a)+len(m.b))
}
// QuickRatio returns an upper bound on ratio() relatively quickly.
//
// This isn't defined beyond that it is an upper bound on .Ratio(), and
// is faster to compute.
func (m *SequenceMatcher) QuickRatio() float64 {
// viewing a and b as multisets, set matches to the cardinality
// of their intersection; this counts the number of matches
// without regard to order, so is clearly an upper bound
if m.fullBCount == nil {
m.fullBCount = map[string]int{}
for _, s := range m.b {
m.fullBCount[s] = m.fullBCount[s] + 1
}
}
// avail[x] is the number of times x appears in 'b' less the
// number of times we've seen it in 'a' so far ... kinda
avail := map[string]int{}
matches := 0
for _, s := range m.a {
n, ok := avail[s]
if !ok {
n = m.fullBCount[s]
}
avail[s] = n - 1
if n > 0 {
matches += 1
}
}
return calculateRatio(matches, len(m.a)+len(m.b))
}
// RealQuickRatio returns an upper bound on ratio() very quickly.
//
// This isn't defined beyond that it is an upper bound on .Ratio(), and
// is faster to compute than either .Ratio() or .QuickRatio().
func (m *SequenceMatcher) RealQuickRatio() float64 {
la, lb := len(m.a), len(m.b)
return calculateRatio(min(la, lb), la+lb)
}
func countLeading(line string, ch byte) (count int) {
// Return number of `ch` characters at the start of `line`.
count = 0
n := len(line)
for (count < n) && (line[count] == ch) {
count++
}
return count
}
type DiffLine struct {
Tag byte
Line string
}
func NewDiffLine(tag byte, line string) (l DiffLine) {
l = DiffLine{}
l.Tag = tag
l.Line = line
return l
}
type Differ struct {
Linejunk func(string) bool
Charjunk func(string) bool
}
func NewDiffer() *Differ {
return &Differ{}
}
func (d *Differ) Compare(a []string, b []string) (diffs []string, err error) {
// Compare two sequences of lines; generate the resulting delta.
// Each sequence must contain individual single-line strings ending with
// newlines. Such sequences can be obtained from the `readlines()` method
// of file-like objects. The delta generated also consists of newline-
// terminated strings, ready to be printed as-is via the writeline()
// method of a file-like object.
diffs = []string{}
cruncher := NewMatcherWithJunk(a, b, true, d.Linejunk)
opcodes := cruncher.GetOpCodes()
for _, current := range opcodes {
alo := current.I1
ahi := current.I2
blo := current.J1
bhi := current.J2
var g []string
switch current.Tag {
case 'r':
g, _ = d.FancyReplace(a, alo, ahi, b, blo, bhi)
case 'd':
g = d.Dump("-", a, alo, ahi)
case 'i':
g = d.Dump("+", b, blo, bhi)
case 'e':
g = d.Dump(" ", a, alo, ahi)
default:
return nil, fmt.Errorf("unknown tag %q", current.Tag)
}
diffs = append(diffs, g...)
}
return diffs, nil
}
func (d *Differ) StructuredDump(tag byte, x []string, low int, high int) (out []DiffLine) {
size := high - low
out = make([]DiffLine, size)
for i := range size {
out[i] = NewDiffLine(tag, x[i+low])
}
return out
}
func (d *Differ) Dump(tag string, x []string, low int, high int) (out []string) {
// Generate comparison results for a same-tagged range.
sout := d.StructuredDump(tag[0], x, low, high)
out = make([]string, len(sout))
var bld strings.Builder
bld.Grow(1024)
for i, line := range sout {
bld.Reset()
bld.WriteByte(line.Tag)
bld.WriteString(" ")
bld.WriteString(line.Line)
out[i] = bld.String()
}
return out
}
func (d *Differ) PlainReplace(a []string, alo int, ahi int, b []string, blo int, bhi int) (out []string, err error) {
if (alo >= ahi) || (blo >= bhi) { // assertion
return nil, errors.New("low greater than or equal to high")
}
// dump the shorter block first -- reduces the burden on short-term
// memory if the blocks are of very different sizes
if bhi-blo < ahi-alo {
out = d.Dump("+", b, blo, bhi)
out = append(out, d.Dump("-", a, alo, ahi)...)
} else {
out = d.Dump("-", a, alo, ahi)
out = append(out, d.Dump("+", b, blo, bhi)...)
}
return out, nil
}
func (d *Differ) FancyReplace(a []string, alo int, ahi int, b []string, blo int, bhi int) (out []string, err error) {
// When replacing one block of lines with another, search the blocks
// for *similar* lines; the best-matching pair (if any) is used as a
// synch point, and intraline difference marking is done on the
// similar pair. Lots of work, but often worth it.
// don't synch up unless the lines have a similarity score of at
// least cutoff; bestRatio tracks the best score seen so far
bestRatio := 0.74
cutoff := 0.75
cruncher := NewMatcherWithJunk(a, b, true, d.Charjunk)
eqi := -1 // 1st indices of equal lines (if any)
eqj := -1
out = []string{}
// search for the pair that matches best without being identical
// (identical lines must be junk lines, & we don't want to synch up
// on junk -- unless we have to)
var bestI, bestJ int
for j := blo; j < bhi; j++ {
bj := b[j]
cruncher.SetSeq2(listifyString(bj))
for i := alo; i < ahi; i++ {
ai := a[i]
if ai == bj {
if eqi == -1 {
eqi = i
eqj = j
}
continue
}
cruncher.SetSeq1(listifyString(ai))
// computing similarity is expensive, so use the quick
// upper bounds first -- have seen this speed up messy
// compares by a factor of 3.
// note that ratio() is only expensive to compute the first
// time it's called on a sequence pair; the expensive part
// of the computation is cached by cruncher
if cruncher.RealQuickRatio() > bestRatio &&
cruncher.QuickRatio() > bestRatio &&
cruncher.Ratio() > bestRatio {
bestRatio = cruncher.Ratio()
bestI = i
bestJ = j
}
}
}
if bestRatio < cutoff {
// no non-identical "pretty close" pair
if eqi == -1 {
// no identical pair either -- treat it as a straight replace
out, _ = d.PlainReplace(a, alo, ahi, b, blo, bhi)
return out, nil
}
// no close pair, but an identical pair -- synch up on that
bestI = eqi
bestJ = eqj
bestRatio = 1.0
} else {
// there's a close pair, so forget the identical pair (if any)
eqi = -1
}
// a[bestI] very similar to b[bestJ]; eqi is None iff they're not
// identical
// pump out diffs from before the synch point
out = append(out, d.fancyHelper(a, alo, bestI, b, blo, bestJ)...)
// do intraline marking on the synch pair
aelt, belt := a[bestI], b[bestJ]
if eqi == -1 {
// pump out a '-', '?', '+', '?' quad for the synched lines
var atags, btags string
cruncher.SetSeqs(listifyString(aelt), listifyString(belt))
opcodes := cruncher.GetOpCodes()
for _, current := range opcodes {
ai1 := current.I1
ai2 := current.I2
bj1 := current.J1
bj2 := current.J2
la, lb := ai2-ai1, bj2-bj1
switch current.Tag {
case 'r':
atags += strings.Repeat("^", la)
btags += strings.Repeat("^", lb)
case 'd':
atags += strings.Repeat("-", la)
case 'i':
btags += strings.Repeat("+", lb)
case 'e':
atags += strings.Repeat(" ", la)
btags += strings.Repeat(" ", lb)
default:
return nil, fmt.Errorf("unknown tag %q",
current.Tag)
}
}
out = append(out, d.QFormat(aelt, belt, atags, btags)...)
} else {
// the synch pair is identical
out = append(out, " "+aelt)
}
// pump out diffs from after the synch point
out = append(out, d.fancyHelper(a, bestI+1, ahi, b, bestJ+1, bhi)...)
return out, nil
}
func (d *Differ) fancyHelper(a []string, alo int, ahi int, b []string, blo int, bhi int) (out []string) {
if alo < ahi {
if blo < bhi {
out, _ = d.FancyReplace(a, alo, ahi, b, blo, bhi)
} else {
out = d.Dump("-", a, alo, ahi)
}
} else if blo < bhi {
out = d.Dump("+", b, blo, bhi)
} else {
out = []string{}
}
return out
}
func (d *Differ) QFormat(aline string, bline string, atags string, btags string) (out []string) {
// Format "?" output and deal with leading tabs.
// Can hurt, but will probably help most of the time.
common := min(countLeading(aline, '\t'), countLeading(bline, '\t'))
common = min(common, countLeading(atags[:common], ' '))
common = min(common, countLeading(btags[:common], ' '))
atags = strings.TrimRightFunc(atags[common:], unicode.IsSpace)
btags = strings.TrimRightFunc(btags[common:], unicode.IsSpace)
out = []string{"- " + aline}
if len(atags) > 0 {
out = append(out, fmt.Sprintf("? %s%s\n",
strings.Repeat("\t", common), atags))
}
out = append(out, "+ "+bline)
if len(btags) > 0 {
out = append(out, fmt.Sprintf("? %s%s\n",
strings.Repeat("\t", common), btags))
}
return out
}
// Convert range to the "ed" format
func formatRangeUnified(start, stop int) string {
// Per the diff spec at http://www.unix.org/single_unix_specification/
beginning := start + 1 // lines start numbering with one
length := stop - start
if length == 1 {
return fmt.Sprintf("%d", beginning)
}
if length == 0 {
beginning -= 1 // empty ranges begin at line just before the range
}
return fmt.Sprintf("%d,%d", beginning, length)
}
// LineDiffParams contains unified diff parameters
type LineDiffParams struct {
A []string // First sequence lines
FromFile string // First file name
FromDate string // First file time
B []string // Second sequence lines
ToFile string // Second file name
ToDate string // Second file time
Eol string // Headers end of line, defaults to LF
Context int // Number of context lines
AutoJunk bool // If true, use autojunking
IsJunkLine func(string) bool // How to spot junk lines
}
// WriteUnifiedDiff compares two sequences of lines and generates the delta as a unified diff.
//
// Unified diffs are a compact way of showing line changes and a few
// lines of context. The number of context lines is set by 'n' which
// defaults to three.
//
// By default, the diff control lines (those with ---, +++, or @@) are
// created with a trailing newline. This is helpful so that inputs
// created from file.readlines() result in diffs that are suitable for
// file.writelines() since both the inputs and outputs have trailing
// newlines.
//
// For inputs that do not have trailing newlines, set the lineterm
// argument to "" so that the output will be uniformly newline free.
//
// The unidiff format normally has a header for filenames and modification
// times. Any or all of these may be specified using strings for
// 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
// The modification times are normally expressed in the ISO 8601 format.
func WriteUnifiedDiff(writer io.Writer, diff LineDiffParams) error {
//buf := bufio.NewWriter(writer)
//defer buf.Flush()
var bld strings.Builder
bld.Reset()
wf := func(format string, args ...any) error {
_, err := fmt.Fprintf(&bld, format, args...)
return err
}
ws := func(s string) error {
_, err := bld.WriteString(s)
return err
}
if len(diff.Eol) == 0 {
diff.Eol = "\n"
}
started := false
m := NewMatcher(diff.A, diff.B)
if diff.AutoJunk || diff.IsJunkLine != nil {
m = NewMatcherWithJunk(diff.A, diff.B, diff.AutoJunk, diff.IsJunkLine)
}
for _, g := range m.GetGroupedOpCodes(diff.Context) {
if !started {
started = true
fromDate := ""
if len(diff.FromDate) > 0 {
fromDate = "\t" + diff.FromDate
}
toDate := ""
if len(diff.ToDate) > 0 {
toDate = "\t" + diff.ToDate
}
if diff.FromFile != "" || diff.ToFile != "" {
err := wf("--- %s%s%s", diff.FromFile, fromDate, diff.Eol)
if err != nil {
return err
}
err = wf("+++ %s%s%s", diff.ToFile, toDate, diff.Eol)
if err != nil {
return err
}
}
}
first, last := g[0], g[len(g)-1]
range1 := formatRangeUnified(first.I1, last.I2)
range2 := formatRangeUnified(first.J1, last.J2)
if err := wf("@@ -%s +%s @@%s", range1, range2, diff.Eol); err != nil {
return err
}
for _, c := range g {
i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
if c.Tag == 'e' {
for _, line := range diff.A[i1:i2] {
if err := ws(" " + line); err != nil {
return err
}
}
continue
}
if c.Tag == 'r' || c.Tag == 'd' {
for _, line := range diff.A[i1:i2] {
if err := ws("-" + line); err != nil {
return err
}
}
}
if c.Tag == 'r' || c.Tag == 'i' {
for _, line := range diff.B[j1:j2] {
if err := ws("+" + line); err != nil {
return err
}
}
}
}
}
buf := bufio.NewWriter(writer)
buf.WriteString(bld.String())
buf.Flush()
return nil
}
// GetUnifiedDiffString is like WriteUnifiedDiff but returns the diff a string.
func GetUnifiedDiffString(diff LineDiffParams) (string, error) {
w := &bytes.Buffer{}
err := WriteUnifiedDiff(w, diff)
return w.String(), err
}
// Convert range to the "ed" format.
func formatRangeContext(start, stop int) string {
// Per the diff spec at http://www.unix.org/single_unix_specification/
beginning := start + 1 // lines start numbering with one
length := stop - start
if length == 0 {
beginning -= 1 // empty ranges begin at line just before the range
}
if length <= 1 {
return fmt.Sprintf("%d", beginning)
}
return fmt.Sprintf("%d,%d", beginning, beginning+length-1)
}
// ContextDiff is for backward compatibility. Ugh.
type ContextDiff = LineDiffParams
type UnifiedDiff = LineDiffParams
// WriteContextDiff compares two sequences of lines and generates the delta as a context diff.
//
// Context diffs are a compact way of showing line changes and a few
// lines of context. The number of context lines is set by diff.Context
// which defaults to three.
//
// By default, the diff control lines (those with *** or ---) are
// created with a trailing newline.
//
// For inputs that do not have trailing newlines, set the diff.Eol
// argument to "" so that the output will be uniformly newline free.
//
// The context diff format normally has a header for filenames and
// modification times. Any or all of these may be specified using
// strings for diff.FromFile, diff.ToFile, diff.FromDate, diff.ToDate.
// The modification times are normally expressed in the ISO 8601 format.
// If not specified, the strings default to blanks.
func WriteContextDiff(writer io.Writer, diff LineDiffParams) error {
buf := bufio.NewWriter(writer)
defer buf.Flush()
var diffErr error
wf := func(format string, args ...any) {
_, err := fmt.Fprintf(buf, format, args...)
if diffErr == nil && err != nil {
diffErr = err
}
}
ws := func(s string) {
_, err := buf.WriteString(s)
if diffErr == nil && err != nil {
diffErr = err
}
}
if len(diff.Eol) == 0 {
diff.Eol = "\n"
}
prefix := map[byte]string{
'i': "+ ",
'd': "- ",
'r': "! ",
'e': " ",
}
started := false
m := NewMatcher(diff.A, diff.B)
if diff.AutoJunk || diff.IsJunkLine != nil {
m = NewMatcherWithJunk(diff.A, diff.B, diff.AutoJunk, diff.IsJunkLine)
}
for _, g := range m.GetGroupedOpCodes(diff.Context) {
if !started {
started = true
fromDate := ""
if len(diff.FromDate) > 0 {
fromDate = "\t" + diff.FromDate
}
toDate := ""
if len(diff.ToDate) > 0 {
toDate = "\t" + diff.ToDate
}
if diff.FromFile != "" || diff.ToFile != "" {
wf("*** %s%s%s", diff.FromFile, fromDate, diff.Eol)
wf("--- %s%s%s", diff.ToFile, toDate, diff.Eol)
}
}
first, last := g[0], g[len(g)-1]
ws("***************" + diff.Eol)
range1 := formatRangeContext(first.I1, last.I2)
wf("*** %s ****%s", range1, diff.Eol)
for _, c := range g {
if c.Tag == 'r' || c.Tag == 'd' {
for _, cc := range g {
if cc.Tag == 'i' {
continue
}
for _, line := range diff.A[cc.I1:cc.I2] {
ws(prefix[cc.Tag] + line)
}
}
break
}
}
range2 := formatRangeContext(first.J1, last.J2)
wf("--- %s ----%s", range2, diff.Eol)
for _, c := range g {
if c.Tag == 'r' || c.Tag == 'i' {
for _, cc := range g {
if cc.Tag == 'd' {
continue
}
for _, line := range diff.B[cc.J1:cc.J2] {
ws(prefix[cc.Tag] + line)
}
}
break
}
}
}
return diffErr
}
// GetContextDiffString is like WriteContextDiff but returns the diff as a string.
func GetContextDiffString(diff LineDiffParams) (string, error) {
w := &bytes.Buffer{}
err := WriteContextDiff(w, diff)
return w.String(), err
}
// SplitLines splits a string on "\n" while preserving them. The output can be used
// as input for LineDiffParams.
func SplitLines(s string) []string {
lines := strings.SplitAfter(s, "\n")
lines[len(lines)-1] += "\n"
return lines
}
// Package tester provides random strings for the tests and benchmarks of
// difflib.
package tester
import (
"math/rand"
"time"
)
func prepareStrings(seed int64) (A, B []string) {
if seed == -1 {
seed = time.Now().UnixNano()
}
rng := rand.New(rand.NewSource(seed))
// Generate 4000 random lines
lines := [4000]string{}
for i := range lines {
l := rng.Intn(100)
p := make([]byte, l)
rng.Read(p)
lines[i] = string(p)
}
// Generate two 4000 lines documents by picking some lines at random
A = make([]string, 4000)
B = make([]string, len(A))
for i := range A {
// make the first 50 lines more likely to appear
if rng.Intn(100) < 40 {
A[i] = lines[rng.Intn(50)]
} else {
A[i] = lines[rng.Intn(len(lines))]
}
if rng.Intn(100) < 40 {
B[i] = lines[rng.Intn(50)]
} else {
B[i] = lines[rng.Intn(len(lines))]
}
}
// Do some copies from A to B
maxcopy := rng.Intn(len(A)-1) + 1
for copied, tocopy := 0, rng.Intn(2*len(A)/3); copied < tocopy; {
l := rng.Intn(rng.Intn(maxcopy-1) + 1)
for a, b, n := rng.Intn(len(A)), rng.Intn(len(B)), 0; a < len(A) && b < len(B) && n < l; a, b, n = a+1, b+1, n+1 {
B[b] = A[a]
copied++
}
}
// And some from B to A
for copied, tocopy := 0, rng.Intn(2*len(A)/3); copied < tocopy; {
l := rng.Intn(rng.Intn(maxcopy-1) + 1)
for a, b, n := rng.Intn(len(A)), rng.Intn(len(B)), 0; a < len(A) && b < len(B) && n < l; a, b, n = a+1, b+1, n+1 {
A[a] = B[b]
copied++
}
}
return
}
func PrepareStringsToDiff(count, seed int) (As, Bs [][]string) {
As = make([][]string, count)
Bs = make([][]string, count)
for i := range As {
As[i], Bs[i] = prepareStrings(int64(i + seed))
}
return
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
//go:generate core generate -add-types
import (
"bytes"
"fmt"
"math"
"os"
"strconv"
"strings"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/keylist"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/keymap"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/text/fonts"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/tree"
"github.com/cogentcore/typesetting/font"
"github.com/cogentcore/typesetting/font/opentype"
)
// Browser is a font browser.
type Browser struct {
core.Frame
Filename core.Filename
IsEmoji bool // true if an emoji font
Font *font.Face
RuneMap *keylist.List[rune, font.GID]
}
// OpenFile opens a font file.
func (fb *Browser) OpenFile(fname core.Filename) error { //types:add
return fb.OpenFileIndex(fname, 0)
}
// OpenFileIndex opens a font file.
func (fb *Browser) OpenFileIndex(fname core.Filename, index int) error { //types:add
b, err := os.ReadFile(string(fname))
if errors.Log(err) != nil {
return err
}
fb.Filename = fname
fb.IsEmoji = strings.Contains(strings.ToLower(string(fb.Filename)), "emoji")
if fb.IsEmoji {
core.MessageSnackbar(fb, "Opening emoji font: "+string(fb.Filename)+" will take a while to render..")
}
return fb.OpenFontData(b, index)
}
// SelectFont selects a font from among a loaded list.
func (fb *Browser) SelectFont() { //types:add
d := core.NewBody("Select Font")
d.SetTitle("Select a font family")
si := 0
fl := fb.Scene.TextShaper().FontList()
fi := fonts.Families(fl)
tb := core.NewTable(d)
tb.SetSlice(&fi).SetSelectedField("Family").
SetSelectedValue(fb.Font.Describe().Family).BindSelect(&si)
tb.SetTableStyler(func(w core.Widget, s *styles.Style, row, col int) {
if col != 1 {
return
}
s.Font.CustomFont = rich.FontName(fi[row].Family)
s.Font.Family = rich.Custom
s.Font.Size.Dp(24)
})
d.AddBottomBar(func(bar *core.Frame) {
d.AddOK(bar).OnClick(func(e events.Event) {
fam := fi[si].Family
idx := 0
for i := range fl {
if fl[i].Family == fam && (fl[i].Weight == rich.Medium || fl[i].Weight == rich.Normal) {
idx = i
break
}
}
loc := fl[idx].Font.Location
finfo := fmt.Sprintf("loading font: %s from: %s idx: %d, sel: %d", fam, loc.File, loc.Index, si)
fmt.Println(finfo)
core.MessageSnackbar(fb, finfo)
fb.OpenFileIndex(core.Filename(loc.File), int(loc.Index))
})
})
d.RunWindowDialog(fb)
}
// OpenFontData opens given font data.
func (fb *Browser) OpenFontData(b []byte, index int) error {
faces, err := font.ParseTTC(bytes.NewReader(b))
if errors.Log(err) != nil {
return err
}
// fmt.Println("number of faces:", len(faces), "index:", index)
fb.Font = faces[index]
for i, fnt := range faces {
d := fnt.Describe()
fmt.Println("index:", i, "family:", d.Family, "Aspect:", d.Aspect)
}
fb.UpdateRuneMap()
fb.Update()
return nil
}
func (fb *Browser) UpdateRuneMap() {
fb.DeleteChildren()
fb.RuneMap = keylist.New[rune, font.GID]()
if fb.Font == nil {
return
}
// for _, pr := range unicode.PrintRanges {
// for _, rv := range pr.R16 {
// for r := rv.Lo; r <= rv.Hi; r += rv.Stride {
// gid, has := fb.Font.NominalGlyph(rune(r))
// if !has {
// continue
// }
// fb.RuneMap.Add(rune(r), gid)
// }
// }
// }
if fb.IsEmoji {
// for r := rune(0); r < math.MaxInt16; r++ {
for r := range rune(math.MaxInt32) { // takes a LONG time..
gid, has := fb.Font.NominalGlyph(r)
if !has {
continue
}
fb.RuneMap.Add(r, gid)
}
} else {
for r := range rune(math.MaxInt16) {
gid, has := fb.Font.NominalGlyph(r)
if !has {
continue
}
fb.RuneMap.Add(r, gid)
}
}
}
// SelectRune selects a rune in current font (first char) of string.
func (fb *Browser) SelectRune(r string) { //types:add
rs := []rune(r)
if len(rs) == 0 {
core.MessageSnackbar(fb, "no runes!")
return
}
ix := fb.RuneMap.IndexByKey(rs[0])
if ix < 0 {
core.MessageSnackbar(fb, "rune not found!")
return
}
gi := fb.Child(ix).(core.Widget).AsWidget()
gi.Styles.State.SetFlag(true, states.Selected, states.Active)
gi.SetFocus()
core.MessageSnackbar(fb, fmt.Sprintf("rune %s at index: %d GID: %d", r, ix, fb.RuneMap.Values[ix]))
}
// SelectRuneInt selects a rune in current font by number
func (fb *Browser) SelectRuneInt(r int) { //types:add
ix := fb.RuneMap.IndexByKey(rune(r))
if ix < 0 {
core.MessageSnackbar(fb, "rune not found!")
return
}
gi := fb.Child(ix).(core.Widget).AsWidget()
gi.Styles.State.SetFlag(true, states.Selected, states.Active)
gi.SetFocus()
core.MessageSnackbar(fb, fmt.Sprintf("rune %s at index: %d GID: %d", string(rune(r)), ix, fb.RuneMap.Values[ix]))
}
// SelectGlyphID selects glyphID in current font.
func (fb *Browser) SelectGlyphID(gid opentype.GID) { //types:add
ix := -1
for i, g := range fb.RuneMap.Values {
if gid == g {
ix = i
break
}
}
if ix < 0 {
core.MessageSnackbar(fb, "glyph id not found!")
return
}
r := string(rune(fb.RuneMap.Keys[ix]))
gi := fb.Child(ix).(core.Widget).AsWidget()
gi.Styles.State.SetFlag(true, states.Selected, states.Active)
gi.SetFocus()
core.MessageSnackbar(fb, fmt.Sprintf("rune %s at index: %d GID: %d", r, ix, fb.RuneMap.Values[ix]))
}
// SaveUnicodes saves all the unicodes in hex format to a file called unicodes.md
func (fb *Browser) SaveUnicodes() { //types:add
var b strings.Builder
for _, r := range fb.RuneMap.Keys {
b.WriteString(fmt.Sprintf("%X\n", r))
}
os.WriteFile("unicodes.md", []byte(b.String()), 0666)
}
func (fb *Browser) Init() {
fb.Frame.Init()
fb.Styler(func(s *styles.Style) {
// s.Display = styles.Flex
// s.Wrap = true
// s.Direction = styles.Row
s.Display = styles.Grid
s.Columns = 32
})
fb.Maker(func(p *tree.Plan) {
if fb.Font == nil {
return
}
for i, gid := range fb.RuneMap.Values {
r := fb.RuneMap.Keys[i]
nm := string(r) + "_" + strconv.Itoa(int(r))
tree.AddAt(p, nm, func(w *Glyph) {
w.SetBrowser(fb).SetRune(r).SetGID(gid)
})
}
})
}
func (fb *Browser) MakeToolbar(p *tree.Plan) {
tree.Add(p, func(w *core.FuncButton) {
w.SetFunc(fb.OpenFile).SetIcon(icons.Open).SetKey(keymap.Open)
w.Args[0].SetValue(fb.Filename).SetTag(`extension:".ttf"`)
})
tree.Add(p, func(w *core.FuncButton) {
w.SetFunc(fb.SelectFont).SetIcon(icons.Open)
})
tree.Add(p, func(w *core.FuncButton) {
w.SetFunc(fb.SelectEmbedded).SetIcon(icons.Open)
})
tree.Add(p, func(w *core.FuncButton) {
w.SetFunc(fb.SelectRune).SetIcon(icons.Select)
})
tree.Add(p, func(w *core.FuncButton) {
w.SetFunc(fb.SelectRuneInt).SetIcon(icons.Select)
})
tree.Add(p, func(w *core.FuncButton) {
w.SetFunc(fb.SelectGlyphID).SetIcon(icons.Select)
})
tree.Add(p, func(w *core.FuncButton) {
w.SetFunc(fb.SaveUnicodes).SetIcon(icons.Save)
})
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"cogentcore.org/core/base/slicesx"
"cogentcore.org/core/colors"
"cogentcore.org/core/core"
"cogentcore.org/core/cursors"
"cogentcore.org/core/events"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint"
"cogentcore.org/core/paint/ppath"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/fonts"
"cogentcore.org/core/text/rich"
"github.com/cogentcore/typesetting/font"
"github.com/cogentcore/typesetting/font/opentype"
)
// GlyphInfo returns info about a glyph.
type GlyphInfo struct {
// Rune is the unicode rune as a string
Rune string
// RuneInt is the unicode code point, int number.
RuneInt rune
// RuneHex is the unicode code point, hexidecimal number.
RuneHex rune `format:"%0X"`
// GID is the glyph ID, specific to each Font.
GID font.GID
// HAdvance is the horizontal advance.
HAdvance float32
// Extents give the size of the glyph.
Extents opentype.GlyphExtents
// Extents are the horizontal font size parameters.
HExtents font.FontExtents
// Outline has the end points of each segment of the outline.
Outline []math32.Vector2
}
func NewGlyphInfo(face *font.Face, r rune, gid font.GID) *GlyphInfo {
gi := &GlyphInfo{}
gi.Set(face, r, gid)
return gi
}
// Set sets the info from given [font.Face] and gid.
func (gi *GlyphInfo) Set(face *font.Face, r rune, gid font.GID) {
gi.Rune = string(r)
gi.RuneInt = r
gi.RuneHex = r
gi.GID = gid
gi.HAdvance = face.HorizontalAdvance(gid)
gi.HExtents, _ = face.FontHExtents()
gi.Extents, _ = face.GlyphExtents(gid)
}
// Glyph displays an individual glyph in the browser
type Glyph struct {
core.Canvas
// Rune is the rune to render.
Rune rune
// GID is the glyph ID of the Rune
GID font.GID
// Outline is the set of control points (end points only).
Outline []math32.Vector2 `set:"-"`
// Stroke only renders the outline of the glyph, not the standard fill.
Stroke bool
// Points plots the control points.
Points bool
Browser *Browser
}
func (gi *Glyph) Init() {
gi.Canvas.Init()
gi.Styler(func(s *styles.Style) {
s.Min.Set(units.Em(3))
s.SetTextWrap(false)
s.Cursor = cursors.Pointer
if gi.Browser == nil {
return
}
s.SetAbilities(true, abilities.Clickable, abilities.Focusable, abilities.Activatable, abilities.Selectable)
sty, tsty := s.NewRichText()
fonts.Style(gi.Browser.Font, sty, tsty)
})
gi.OnClick(func(e events.Event) {
if gi.Stroke || gi.Browser == nil || gi.Browser.Font == nil {
return
}
gli := NewGlyphInfo(gi.Browser.Font, gi.Rune, gi.GID)
gli.Outline = gi.Outline
d := core.NewBody("Glyph Info")
bg := NewGlyph(d).SetBrowser(gi.Browser).SetRune(gi.Rune).SetGID(gi.GID).
SetStroke(true).SetPoints(true)
bg.Styler(func(s *styles.Style) {
s.Min.Set(units.Em(40))
})
core.NewForm(d).SetStruct(gli).StartFocus()
d.AddBottomBar(func(bar *core.Frame) {
d.AddOK(bar)
})
d.RunWindowDialog(gi.Browser)
})
gi.SetDraw(gi.draw)
}
func (gi *Glyph) drawShaped(pc *paint.Painter) {
sty, tsty := gi.Styles.NewRichText()
fonts.Style(gi.Browser.Font, sty, tsty)
sz := gi.Geom.Size.Actual.Content
msz := min(sz.X, sz.Y)
sty.Size = float32(msz) / tsty.FontSize.Dots
sty.Size *= 0.85
tx := rich.NewText(sty, []rune{gi.Rune})
lns := gi.Scene.TextShaper().WrapLines(tx, sty, tsty, sz)
off := math32.Vec2(0, 0)
if msz > 200 {
o := 0.2 * float32(msz)
if !gi.Browser.IsEmoji { // for bitmap fonts, kinda random
off = math32.Vec2(o, o)
}
}
pc.DrawText(lns, gi.Geom.Pos.Content.Add(off))
}
func (gi *Glyph) draw(pc *paint.Painter) {
if gi.Browser == nil || gi.Browser.Font == nil {
return
}
face := gi.Browser.Font
data := face.GlyphData(gi.GID)
gd, ok := data.(font.GlyphOutline)
if !ok {
gi.drawShaped(pc)
return
}
scale := 0.7 / float32(face.Upem())
x := float32(0.1)
y := float32(0.8)
gi.Outline = slicesx.SetLength(gi.Outline, len(gd.Segments))
pc.Fill.Color = colors.Scheme.Surface
if gi.StateIs(states.Active) || gi.StateIs(states.Focused) || gi.StateIs(states.Selected) {
pc.Fill.Color = colors.Scheme.Select.Container
}
pc.Stroke.Color = colors.Scheme.OnSurface
pc.Rectangle(0, 0, 1, 1)
pc.Draw()
pc.Fill.Color = nil
pc.Line(0, y, 1, y)
pc.Draw()
if gi.Stroke {
pc.Stroke.Width.Dp(2)
pc.Stroke.Color = colors.Scheme.OnSurface
pc.Fill.Color = nil
} else {
pc.Stroke.Color = nil
pc.Fill.Color = colors.Scheme.OnSurface
}
ext, _ := face.GlyphExtents(gi.GID)
if ext.XBearing < 0 {
x -= scale * ext.XBearing
}
var gp ppath.Path
for i, s := range gd.Segments {
px := s.Args[0].X*scale + x
py := -s.Args[0].Y*scale + y
switch s.Op {
case opentype.SegmentOpMoveTo:
gp.MoveTo(px, py)
gi.Outline[i] = math32.Vec2(px, py)
case opentype.SegmentOpLineTo:
gp.LineTo(px, py)
gi.Outline[i] = math32.Vec2(px, py)
case opentype.SegmentOpQuadTo:
p1x := s.Args[1].X*scale + x
p1y := -s.Args[1].Y*scale + y
gp.QuadTo(px, py, p1x, p1y)
gi.Outline[i] = math32.Vec2(p1x, p1y)
case opentype.SegmentOpCubeTo:
p1x := s.Args[1].X*scale + x
p1y := -s.Args[1].Y*scale + y
p2x := s.Args[2].X*scale + x
p2y := -s.Args[2].Y*scale + y
gp.CubeTo(px, py, p1x, p1y, p2x, p2y)
gi.Outline[i] = math32.Vec2(p2x, p2y)
}
}
bb := gp.FastBounds()
sx := float32(1)
sy := float32(1)
if bb.Max.X >= 0.98 {
sx = 0.9 / bb.Max.X
}
if bb.Min.Y < 0 {
sy = 0.9 * (1 + bb.Min.Y) / 1.0
gp = gp.Translate(0, -bb.Min.Y/sy)
y -= bb.Min.Y / sy
}
if bb.Max.Y > 1 {
sy *= 0.9 / bb.Max.Y
}
if sx != 1 || sy != 1 {
gp = gp.Scale(sx, sy)
}
pc.State.Path = gp
pc.Draw()
// Points
if !gi.Points {
return
}
pc.Stroke.Color = nil
pc.Fill.Color = colors.Scheme.Primary.Base
radius := float32(0.01)
for _, s := range gd.Segments {
px := sx * (s.Args[0].X*scale + x)
py := sy * (-s.Args[0].Y*scale + y)
switch s.Op {
case opentype.SegmentOpMoveTo, opentype.SegmentOpLineTo:
pc.Circle(px, py, radius)
case opentype.SegmentOpQuadTo:
p1x := sx * (s.Args[1].X*scale + x)
p1y := sy * (-s.Args[1].Y*scale + y)
pc.Circle(p1x, p1y, radius)
case opentype.SegmentOpCubeTo:
p2x := sx * (s.Args[2].X*scale + x)
p2y := sy * (-s.Args[2].Y*scale + y)
pc.Circle(p2x, p2y, radius)
}
}
pc.Draw()
radius *= 0.8
pc.Stroke.Color = nil
pc.Fill.Color = colors.Scheme.Error.Base
for _, s := range gd.Segments {
px := sx * (s.Args[0].X*scale + x)
py := sy * (-s.Args[0].Y*scale + y)
switch s.Op {
case opentype.SegmentOpQuadTo:
pc.Circle(px, py, radius)
case opentype.SegmentOpCubeTo:
p1x := sx * (s.Args[1].X*scale + x)
p1y := sy * (-s.Args[1].Y*scale + y)
pc.Circle(px, py, radius)
pc.Circle(p1x, p1y, radius)
}
}
pc.Draw()
pc.Stroke.Color = colors.Scheme.Error.Base
pc.Fill.Color = nil
for _, s := range gd.Segments {
px := sx * (s.Args[0].X*scale + x)
py := sy * (-s.Args[0].Y*scale + y)
switch s.Op {
case opentype.SegmentOpQuadTo:
p1x := sx * (s.Args[1].X*scale + x)
p1y := sy * (-s.Args[1].Y*scale + y)
pc.Line(p1x, p1y, px, py)
case opentype.SegmentOpCubeTo:
p1x := sx * (s.Args[1].X*scale + x)
p1y := sy * (-s.Args[1].Y*scale + y)
p2x := sx * (s.Args[2].X*scale + x)
p2y := sy * (-s.Args[2].Y*scale + y)
pc.Line(px, py, p2x, p2y)
pc.Line(p1x, p1y, p2x, p2y)
}
}
pc.Draw()
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import "cogentcore.org/core/core"
func main() {
b := core.NewBody()
makeBody(b)
b.RunMainWindow()
}
// makeBody makes the font browser in the given body, and returns it.
func makeBody(b *core.Body) *Browser {
fb := NewBrowser(b)
fb.OpenFile("../noto/NotoSans-Regular.ttf")
b.AddTopBar(func(bar *core.Frame) {
core.NewToolbar(bar).Maker(fb.MakeToolbar)
})
return fb
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/text/tex"
)
func init() {
tex.LMFontsLoad()
}
// SelectEmbedded selects an embedded font from a list.
func (fb *Browser) SelectEmbedded() { //types:add
d := core.NewBody("Select Font")
d.SetTitle("Select an embedded font")
si := 0
fl := tex.LMFonts
names := make([]string, len(fl))
for i := range fl {
names[i] = fl[i].Family
}
tb := core.NewList(d)
tb.SetSlice(&names).BindSelect(&si)
d.AddBottomBar(func(bar *core.Frame) {
d.AddOK(bar).OnClick(func(e events.Event) {
fb.Font = fl[si].Fonts[0]
fb.UpdateRuneMap()
fb.Update()
})
})
d.RunWindowDialog(fb)
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package fonts
import (
"bytes"
"cmp"
"slices"
"cogentcore.org/core/text/rich"
"github.com/cogentcore/typesetting/font"
"github.com/cogentcore/typesetting/fontscan"
)
// Info contains basic font information for aviailable fonts.
// This is used for a chooser for example.
type Info struct {
// Family name.
Family string
// Weight: normal, bold, etc
Weight rich.Weights
// Slant: normal or italic
Slant rich.Slants
// Stretch: normal, expanded, condensed, etc
Stretch rich.Stretch
// Font contains info about the location, family, etc of the font file.
Font fontscan.Footprint `display:"-"`
}
// Family is used for selecting a font family in a font chooser.
type Family struct {
// Family name.
Family string
// example text, styled according to font family in chooser.
Example string
}
// InfoExample is example text to demonstrate fonts.
var InfoExample = "AaBbCcIiPpQq12369$€¢?.:/()àáâãäåæç日本中国⇧⌘"
// Label satisfies the Labeler interface
func (fi Info) Label() string {
return fi.Family
}
// Label satisfies the Labeler interface
func (fi Family) Label() string {
return fi.Family
}
// Families returns a list of [Family] with one representative per family.
func Families(fi []Info) []Family {
slices.SortFunc(fi, func(a, b Info) int {
return cmp.Compare(a.Family, b.Family)
})
n := len(fi)
ff := make([]Family, 0, n)
for i := 0; i < n; i++ {
cur := fi[i].Family
ff = append(ff, Family{Family: cur, Example: InfoExample})
for i < n-1 {
if fi[i+1].Family != cur {
break
}
i++
}
}
return ff
}
// Data contains font information for embedded font data.
type Data struct {
// Family name.
Family string
// Weight: normal, bold, etc.
Weight rich.Weights
// Slant: normal or italic.
Slant rich.Slants
// Stretch: normal, expanded, condensed, etc.
Stretch rich.Stretch
// Data contains the font data.
Data []byte `display:"-"`
// Font contains the loaded font face(s).
Fonts []*font.Face
}
// Load loads the data, setting the Font.
func (fd *Data) Load() error {
faces, err := font.ParseTTC(bytes.NewReader(fd.Data))
if err != nil {
return err
}
fd.Fonts = faces
return nil
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package fonts provides the fonts that are embedded in apps (Noto Sans and
// Roboto Mono by default), the fonts added at run time, and their information.
package fonts
import (
"fmt"
"io/fs"
"cogentcore.org/core/base/errors"
"github.com/cogentcore/typesetting/font/opentype"
"github.com/cogentcore/typesetting/fontscan"
)
// Embedded are embedded filesystems to get fonts from. By default,
// this includes a set of Noto Sans and Roboto Mono fonts. System fonts are
// automatically supported separate from this. Use [AddEmbedded] to add
// to this. This must be called before the text shaper is created to have an effect.
//
// On web, Embedded is only used for font metrics, as the actual font
// rendering happens through web fonts. See https://cogentcore.org/core/font for
// more information.
var Embedded = []fs.FS{Default}
// AddEmbedded adds to [Embedded] for font loading.
func AddEmbedded(fsys ...fs.FS) {
Embedded = append(Embedded, fsys...)
}
// UseEmbeddedInMap adds the fonts from the current [Embedded] list to the given map.
func UseEmbeddedInMap(fontMap *fontscan.FontMap) error {
return UseInMap(fontMap, Embedded)
}
// UseInMap adds the fonts from given file systems to the given map.
func UseInMap(fontMap *fontscan.FontMap, fss []fs.FS) error {
var errs []error
for _, fsys := range fss {
err := fs.WalkDir(fsys, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
errs = append(errs, err)
return err
}
if d.IsDir() {
return nil
}
f, err := fsys.Open(path)
if err != nil {
errs = append(errs, err)
return err
}
defer f.Close()
resource, ok := f.(opentype.Resource)
if !ok {
err = fmt.Errorf("file %q cannot be used as an opentype.Resource", path)
errs = append(errs, err)
return err
}
err = fontMap.AddFont(resource, path, "")
if err != nil {
errs = append(errs, err)
return err
}
return nil
})
if err != nil {
errs = append(errs, err)
}
}
return errors.Join(errs...)
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Command metricsonly extracts font metrics from font files,
// discarding all the glyph outlines and other data.
package main
import (
"fmt"
"os"
"path/filepath"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/cli"
"github.com/cogentcore/typesetting/font/opentype"
)
//go:generate core generate -add-types -add-funcs
func ExtractMetrics(fname, outfile string, debug bool) error {
if debug {
fmt.Println(fname, "->", outfile)
}
f, err := os.Open(fname)
if err != nil {
return err
}
font, err := opentype.NewLoader(f)
if err != nil {
return err
}
// full list from roboto:
// GSUB OS/2 STAT cmap gasp glyf head hhea hmtx loca maxp name post prep
// minimal effective list: you have to exclude both loca and glyf -- if
// you have loca it needs glyf, but otherwise fine to exclude.
// include := []string{"head", "hhea", "htmx", "maxp", "name", "cmap"}
include := []string{"head", "hhea", "htmx", "maxp", "name", "cmap"}
tags := font.Tables()
tables := make([]opentype.Table, len(tags))
var taglist []string
for i, tag := range tags {
if debug {
taglist = append(taglist, tag.String())
}
skip := true
for _, in := range include {
if tag.String() == in {
skip = false
break
}
}
if skip {
continue
}
tables[i].Tag = tag
tables[i].Content, err = font.RawTable(tag)
if err != nil {
return err
}
if tag.String() == "name" {
fmt.Println("name:", string(tables[i].Content))
}
}
if debug {
fmt.Println("\t", taglist)
}
content := opentype.WriteOpentype(tables, opentype.TrueType)
return os.WriteFile(outfile, content, 0666)
}
type Config struct {
// Files to extract metrics from.
Files []string `flag:"f,files" posarg:"all"`
// directory to output the metrics only files.
Output string `flag:"output,o"`
// emit debug info while processing. todo: use verbose for this!
Debug bool `flag:"d,debug"`
}
// Extract reads fonts and extracts metrics, saving to given output directory.
func Extract(c *Config) error {
if c.Output != "" {
err := os.MkdirAll(c.Output, 0777)
if err != nil {
return err
}
}
var errs []error
for _, fn := range c.Files {
_, fname := filepath.Split(fn)
outfile := filepath.Join(c.Output, fname)
err := ExtractMetrics(fn, outfile, c.Debug)
if err != nil {
errs = append(errs, err)
}
}
return errors.Join(errs...)
}
func main() { //types:skip
opts := cli.DefaultOptions("metricsonly", "metricsonly extracts font metrics from font files, discarding all the glyph outlines and other data.")
cli.Run(opts, &Config{}, Extract)
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package fonts
import (
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/text"
"github.com/cogentcore/typesetting/font"
)
// Style sets the [rich.Style] and [text.Style] for the given [font.Face].
func Style(face *font.Face, sty *rich.Style, tsty *text.Style) {
if face == nil {
return
}
d := face.Describe()
tsty.CustomFont = rich.FontName(d.Family)
sty.Family = rich.Custom
as := d.Aspect
sty.Weight = rich.WeightFromFloat32(float32(as.Weight))
sty.Slant = rich.Slants(as.Style - 1)
// fi[i].Stretch = rich.Stretch() // not avail
// fi[i].Stretch = rich.StretchNormal
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package fonts
import (
"bytes"
"strings"
"sync"
"github.com/cogentcore/typesetting/font/opentype"
)
// WebFont is a font that is added at run time, with the family name that
// it is used with (as the web fonts of the @font-face rules of HTML pages).
type WebFont struct {
// Family is the family name that the font is used with.
Family string
// Data is the data of the font, as TrueType, OpenType or WOFF.
Data []byte
}
// webFonts are the fonts that are added with [AddWebFont].
var webFonts struct {
sync.Mutex
fonts []WebFont
families map[string]bool
}
// AddWebFont adds the given font data (TrueType, OpenType, or WOFF; see
// also [WebFont]) with the given family name, which is used for the given
// family by the text shapers (which add it when they next shape text),
// for all of the faces of the data. It returns an error if the data is
// not a font.
func AddWebFont(family string, data []byte) error {
if _, err := opentype.NewLoaders(bytes.NewReader(data)); err != nil {
return err
}
webFonts.Lock()
defer webFonts.Unlock()
if webFonts.families == nil {
webFonts.families = map[string]bool{}
}
webFonts.families[strings.ToLower(family)] = true
webFonts.fonts = append(webFonts.fonts, WebFont{Family: family, Data: data})
return nil
}
// HasWebFont returns whether a font has been added for the given family
// with [AddWebFont] (ignoring case).
func HasWebFont(family string) bool {
webFonts.Lock()
defer webFonts.Unlock()
return webFonts.families[strings.ToLower(family)]
}
// WebFonts returns the fonts added with [AddWebFont] after the first n, and
// the number of fonts added in all, with which a shaper adds the fonts that
// it does not have yet.
func WebFonts(n int) ([]WebFont, int) {
webFonts.Lock()
defer webFonts.Unlock()
if n >= len(webFonts.fonts) {
return nil, len(webFonts.fonts)
}
return webFonts.fonts[n:], len(webFonts.fonts)
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package alllexers makes syntax highlighting use all of the chroma lexers
// on all platforms, when imported:
//
// import _ "cogentcore.org/core/text/highlighting/alllexers"
//
// An editor of code in any language needs this. Otherwise, the default is
// [highlighting.NewGoLexers], which highlights only Go and leaves out the
// definitions of the hundreds of other languages that chroma supports,
// saving several megabytes in the size of the app, and
// [highlighting.AddLexers] adds the lexers of particular languages.
package alllexers
import (
"cogentcore.org/core/text/highlighting"
"github.com/alecthomas/chroma/v3/lexers"
)
func init() {
highlighting.SetLexers(lexers.GlobalLexerRegistry)
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package highlighting
import (
"fmt"
"iter"
"log/slog"
"slices"
"strings"
"cogentcore.org/core/base/fileinfo"
"cogentcore.org/core/text/parse"
"cogentcore.org/core/text/parse/lexer"
"cogentcore.org/core/text/token"
"github.com/alecthomas/chroma/v3"
"github.com/alecthomas/chroma/v3/formatters/html"
)
// UseParse is whether syntax highlighting, completion, lookup and
// indentation use the [parse] lexer and parser for the languages that it
// supports, instead of chroma. It is off by default, which keeps the parse
// languages out of programs that only need highlighting, making them smaller
// and faster to start. Programs that want the parse languages, such as code
// editors, set it to true and import
// cogentcore.org/core/text/parse/supportedlanguages to register them.
var UseParse = false
// ParseFilter, if set, further restricts [UseParse] to the languages for
// which it returns true, so that a program can use [parse] for some
// languages and other means (such as a language server) for the rest.
// It can be called from any goroutine. Buffers pick up a change the next
// time their file info is set (lines.Lines.SetFileInfo).
var ParseFilter func(known fileinfo.Known) bool
// ParseLanguage returns the [parse] language properties for the given
// known file type if [UseParse] is on, [ParseFilter] allows it, and the
// language is registered, and nil otherwise.
func ParseLanguage(known fileinfo.Known) *parse.LanguageProperties {
if !UseParse || known == fileinfo.Unknown {
return nil
}
if ParseFilter != nil && !ParseFilter(known) {
return nil
}
lp, err := parse.LanguageSupport.Properties(known)
if err != nil || lp.Lang == nil {
return nil
}
return lp
}
// Highlighter performs syntax highlighting, using [parse] if [UseParse]
// is on and the language is supported, and otherwise chroma.
type Highlighter struct {
// syntax highlighting style to use
StyleName HighlightingName
// chroma-based language name for syntax highlighting the code
language string
// Has is whether there are highlighting parameters set
// (only valid after [Highlighter.init] has been called).
Has bool
// tab size, in chars
TabSize int
// Commpiled CSS properties for given highlighting style
CSSProperties map[string]any
// parser state info
parseState *parse.FileStates
// if supported, this is the [parse.Language] support for parsing
parseLanguage parse.Language
// Style is the current highlighting style.
Style *Style
// external toggle to turn off automatic highlighting
off bool
lastLanguage string
lastStyle HighlightingName
lexer chroma.Lexer
formatter *html.Formatter
}
// UsingParse returns true if markup is using parse lexer / parser, which affects
// use of results
func (hi *Highlighter) UsingParse() bool {
return hi.parseLanguage != nil
}
// Init initializes the syntax highlighting for current params
func (hi *Highlighter) Init(info *fileinfo.FileInfo, pist *parse.FileStates) {
if hi.Style == nil {
hi.SetStyle(DefaultStyle)
}
hi.parseState = pist
if lp := ParseLanguage(info.Known); lp != nil {
hi.lexer = nil
hi.parseLanguage = lp.Lang
} else {
hi.parseLanguage = nil
}
if hi.parseLanguage == nil {
lexer := Lexers().MatchMimeType(info.Mime)
if lexer == nil {
lexer = Lexers().Match(info.Name)
}
if lexer == nil && info.Cat == fileinfo.Code {
// code without a lexer of its own, as SPIR-V assembly, is
// highlighted as Go, whose lexer is always in the Lexers
lexer = Lexers().Get("go")
}
if lexer != nil {
hi.language = lexer.Config().Name
hi.lexer = lexer
}
}
if hi.StyleName == "" || (hi.parseLanguage == nil && hi.lexer == nil) {
hi.Has = false
return
}
hi.Has = true
if hi.StyleName != hi.lastStyle {
hi.Style = AvailableStyle(hi.StyleName)
hi.CSSProperties = hi.Style.ToProperties()
hi.lastStyle = hi.StyleName
}
if hi.lexer != nil {
// always coalesce the newly matched lexer, which can also follow
// a switch from parse back to chroma for the same language
hi.lexer = chroma.Coalesce(GetLexer(hi.language))
if hi.language != hi.lastLanguage || hi.formatter == nil {
hi.formatter = html.New(html.WithClasses(true), html.TabWidth(hi.TabSize))
hi.lastLanguage = hi.language
}
}
}
// SetStyle sets the highlighting style and updates corresponding settings
func (hi *Highlighter) SetStyle(style HighlightingName) {
if style == "" {
return
}
st := AvailableStyle(style)
if st == nil {
slog.Error("Highlighter Style not found:", "style", style)
return
}
hi.StyleName = style
hi.Style = st
hi.CSSProperties = hi.Style.ToProperties()
hi.lastStyle = hi.StyleName
}
// MarkupTagsAll returns all the markup tags according to current
// syntax highlighting settings
func (hi *Highlighter) MarkupTagsAll(txt []byte) ([]lexer.Line, error) {
if hi.off {
return nil, nil
}
if hi.parseLanguage != nil {
hi.parseLanguage.ParseFile(hi.parseState, txt) // processes in Proc(), does Switch()
lex := hi.parseState.Done().Src.Lexs
return lex, nil // Done() is results of above
} else if hi.lexer != nil {
return hi.chromaTagsAll(txt)
}
return nil, nil
}
// MarkupTagsLine returns tags for one line according to current
// syntax highlighting settings
func (hi *Highlighter) MarkupTagsLine(ln int, txt []rune) (lexer.Line, error) {
if hi.off {
return nil, nil
}
if hi.parseLanguage != nil {
ll := hi.parseLanguage.HighlightLine(hi.parseState, ln, txt)
return ll, nil
} else if hi.lexer != nil {
return hi.chromaTagsLine(txt)
}
return nil, nil
}
// chromaTagsForLine generates the chroma tags for one line of chroma tokens
func chromaTagsForLine(tags *lexer.Line, toks []chroma.Token) {
cp := 0
for _, tok := range toks {
str := []rune(strings.TrimSuffix(tok.Value, "\n"))
slen := len(str)
if slen == 0 {
continue
}
if tok.Type == chroma.None { // always a parsing err AFAIK
// fmt.Printf("type: %v st: %v ed: %v txt: %v\n", tok.Type, cp, ep, str)
continue
}
ep := cp + slen
// chroma marks the characters that a lexer does not know as errors,
// such as the # and $ of Goal, which is highlighted as Go: they are
// plain text, not the Error tags of diagnostics.
if tok.Type < chroma.Text && tok.Type != chroma.Error {
ht := TokenFromChroma(tok.Type)
tags.AddLex(token.KeyToken{Token: ht}, cp, ep)
}
cp = ep
}
}
// chromaTagsAll returns all the markup tags according to current
// syntax highlighting settings
func (hi *Highlighter) chromaTagsAll(txt []byte) ([]lexer.Line, error) {
txtstr := string(txt) // expensive!
iterator, err := hi.lexer.Tokenise(nil, txtstr)
if err != nil {
slog.Error(err.Error())
return nil, err
}
toks, err := collectTokens(iterator)
if err != nil {
slog.Error(err.Error())
return nil, err
}
lines := chroma.SplitTokensIntoLines(toks)
sz := len(lines)
tags := make([]lexer.Line, sz)
for li, lt := range lines {
chromaTagsForLine(&tags[li], lt)
}
return tags, nil
}
// chromaTagsLine returns tags for one line according to current
// syntax highlighting settings
func (hi *Highlighter) chromaTagsLine(txt []rune) (lexer.Line, error) {
return ChromaTagsLine(hi.lexer, string(txt))
}
// ChromaTagsLine returns tags for one line according to given chroma lexer
func ChromaTagsLine(clex chroma.Lexer, txt string) (lexer.Line, error) {
n := len(txt)
if n == 0 {
return nil, nil
}
if txt[n-1] != '\n' {
txt += "\n"
}
iterator, err := clex.Tokenise(nil, txt)
if err != nil {
slog.Error(err.Error())
return nil, err
}
var tags lexer.Line
toks, err := collectTokens(iterator)
if err != nil {
slog.Error(err.Error())
return nil, err
}
chromaTagsForLine(&tags, toks)
return tags, nil
}
// collectTokens collects the tokens of a chroma lexer's iterator. The
// iterator cannot return an error, so chroma panics when lexing fails,
// for example when a rule's regular expression exceeds its match timeout,
// and leaves it to the caller to recover; this returns that as an error.
func collectTokens(iterator iter.Seq[chroma.Token]) (toks []chroma.Token, err error) {
defer func() {
if r := recover(); r != nil {
toks = nil
if e, ok := r.(error); ok {
err = fmt.Errorf("highlighting: lexing failed: %w", e)
} else {
err = fmt.Errorf("highlighting: lexing failed: %v", r)
}
}
}()
return slices.Collect(iterator), nil
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package highlighting
import (
"html"
"cogentcore.org/core/text/parse/lexer"
)
// maxLineLen prevents overflow in allocating line length
const (
maxLineLen = 64 * 1024
maxNumTags = 1024
)
// HTMLEscape specifies whether [MarkupLineHTML] escapes the HTML special
// characters of the text: [EscapeHTML] or [NoEscapeHTML].
type HTMLEscape bool
const (
// EscapeHTML escapes the HTML special characters of the text.
EscapeHTML HTMLEscape = true
// NoEscapeHTML does not escape the HTML special characters of the text.
NoEscapeHTML HTMLEscape = false
)
// MarkupLineHTML returns the line with html class tags added for each tag
// takes both the hi tags and extra tags. Only fully nested tags are supported,
// with any dangling ends truncated.
func MarkupLineHTML(txt []rune, hitags, tags lexer.Line, escapeHTML HTMLEscape) []byte {
if len(txt) > maxLineLen { // avoid overflow
return nil
}
sz := len(txt)
if sz == 0 {
return nil
}
var escf func([]rune) []byte
if escapeHTML {
escf = HTMLEscapeRunes
} else {
escf = func(r []rune) []byte {
return []byte(string(r))
}
}
ttags := lexer.MergeLines(hitags, tags) // ensures that inner-tags are *after* outer tags
nt := len(ttags)
if nt == 0 || nt > maxNumTags {
return escf(txt)
}
sps := []byte(`<span class="`)
sps2 := []byte(`">`)
spe := []byte(`</span>`)
taglen := len(sps) + len(sps2) + len(spe) + 2
musz := sz + nt*taglen
mu := make([]byte, 0, musz)
cp := 0
var tstack []int // stack of tags indexes that remain to be completed, sorted soonest at end
for i, tr := range ttags {
if cp >= sz {
break
}
for si := len(tstack) - 1; si >= 0; si-- {
t := tstack[si]
ts := ttags[t]
if ts.End <= tr.Start {
ep := min(sz, ts.End)
if cp < ep {
mu = append(mu, escf(txt[cp:ep])...)
cp = ep
}
mu = append(mu, spe...)
tstack = append(tstack[:si], tstack[si+1:]...)
}
}
if cp >= sz || tr.Start >= sz {
break
}
if tr.Start > cp {
mu = append(mu, escf(txt[cp:tr.Start])...)
}
mu = append(mu, sps...)
clsnm := tr.Token.Token.StyleName()
mu = append(mu, []byte(clsnm)...)
mu = append(mu, sps2...)
ep := tr.End
addEnd := true
if i < nt-1 {
if ttags[i+1].Start < tr.End { // next one starts before we end, add to stack
addEnd = false
ep = ttags[i+1].Start
if len(tstack) == 0 {
tstack = append(tstack, i)
} else {
for si := len(tstack) - 1; si >= 0; si-- {
t := tstack[si]
ts := ttags[t]
if tr.End <= ts.End {
ni := si // + 1 // new index in stack -- right *before* current
tstack = append(tstack, i)
copy(tstack[ni+1:], tstack[ni:])
tstack[ni] = i
}
}
}
}
}
ep = min(len(txt), ep)
if tr.Start < ep {
mu = append(mu, escf(txt[tr.Start:ep])...)
}
if addEnd {
mu = append(mu, spe...)
}
cp = ep
}
if sz > cp {
mu = append(mu, escf(txt[cp:sz])...)
}
// pop any left on stack..
for si := len(tstack) - 1; si >= 0; si-- {
mu = append(mu, spe...)
}
return mu
}
// HTMLEscapeBytes escapes special characters like "<" to become "<". It
// escapes only five such characters: <, >, &, ' and ".
// It operates on a *copy* of the byte string and does not modify the input!
// otherwise it causes major problems..
func HTMLEscapeBytes(b []byte) []byte {
return []byte(html.EscapeString(string(b)))
}
// HTMLEscapeRunes escapes special characters like "<" to become "<". It
// escapes only five such characters: <, >, &, ' and ".
// It operates on a *copy* of the byte string and does not modify the input!
// otherwise it causes major problems..
func HTMLEscapeRunes(r []rune) []byte {
return []byte(html.EscapeString(string(r)))
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package highlighting
import (
"cogentcore.org/core/text/highlighting/lexers"
"github.com/alecthomas/chroma/v3"
)
// lexerRegistry is the registry returned by [Lexers].
var lexerRegistry *chroma.LexerRegistry
// Lexers returns the registry of chroma lexers used for syntax highlighting.
// It is made by [NewGoLexers] by default, which keeps the definitions of the
// hundreds of other languages that chroma supports out of the app.
// [AddLexers] adds the lexers for other languages, and importing
// cogentcore.org/core/text/highlighting/alllexers switches it to all of the
// chroma lexers, as an editor of any language needs. Code in languages
// without a lexer is not highlighted.
func Lexers() *chroma.LexerRegistry {
if lexerRegistry == nil {
lexerRegistry = NewGoLexers()
}
return lexerRegistry
}
// SetLexers sets the registry of chroma lexers returned by [Lexers].
// It must be called before any highlighting, typically in an init function.
func SetLexers(reg *chroma.LexerRegistry) {
lexerRegistry = reg
}
// AddLexers adds lexers to [Lexers] with the given functions of the
// cogentcore.org/core/text/highlighting/lexers package, such as:
//
// highlighting.AddLexers(lexers.Bash, lexers.TOML)
//
// Only the definitions of the given languages are linked into the app.
// It must be called before any highlighting, typically in an init function
// or at the start of main.
func AddLexers(lexers ...func(reg *chroma.LexerRegistry)) {
reg := Lexers()
for _, add := range lexers {
add(reg)
}
}
// GetLexer returns the chroma lexer in [Lexers] for the given language name,
// alias or file extension, or nil if there is none.
func GetLexer(name string) chroma.Lexer {
return Lexers().Get(name)
}
// NewGoLexers returns a new registry with the chroma lexers for Go and Go
// text templates, which highlight the raw strings of Go code. It is the
// default for [Lexers].
func NewGoLexers() *chroma.LexerRegistry {
reg := chroma.NewLexerRegistry()
lexers.Go(reg)
return reg
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lexers
// This file contains a copy of the Go lexer of
// github.com/alecthomas/chroma/v3/lexers, which is defined in Go code
// rather than XML.
// Copyright (C) 2017 Alec Thomas, under an MIT License (see COPYING).
import (
_ "embed"
"strings"
"github.com/alecthomas/chroma/v3"
)
//go:embed go_template.xml
var xmlGoTemplate string
// Go adds the chroma lexers for Go (go, golang) and Go text templates
// (go-text-template), which highlight the raw strings of Go code,
// to the registry.
func Go(reg *chroma.LexerRegistry) {
goTextTemplate := reg.Register(chroma.MustNewXMLLexer(xmlFS{"go_template.xml", xmlGoTemplate}, "go_template.xml").SetConfig(&chroma.Config{
Name: "Go Text Template",
Aliases: []string{"go-text-template"},
}))
reg.Register(newGoLexer(goTextTemplate))
}
// newGoLexer returns the Go lexer, using the given Go text template
// lexer for raw strings.
func newGoLexer(goTextTemplate chroma.Lexer) chroma.Lexer {
return chroma.MustNewLexer(
&chroma.Config{
Name: "Go",
Aliases: []string{"go", "golang"},
Filenames: []string{"*.go"},
MimeTypes: []string{"text/x-gosrc"},
},
func() chroma.Rules { return goRules(goTextTemplate) },
).SetAnalyser(func(text string) float32 {
if strings.Contains(text, "fmt.") && strings.Contains(text, "package ") {
return 0.5
}
if strings.Contains(text, "package ") {
return 0.1
}
return 0.0
})
}
func goRules(goTextTemplate chroma.Lexer) chroma.Rules {
return chroma.Rules{
"root": {
{Pattern: `\n`, Type: chroma.TextWhitespace, Mutator: nil},
{Pattern: `\s+`, Type: chroma.TextWhitespace, Mutator: nil},
{Pattern: `//[^\s\n\r][^\n\r]*`, Type: chroma.CommentPreproc, Mutator: nil},
{Pattern: `//[^\n\r]*`, Type: chroma.CommentSingle, Mutator: nil},
{Pattern: `/(\\\n)?[*](.|\n)*?[*](\\\n)?/`, Type: chroma.CommentMultiline, Mutator: nil},
{Pattern: `(import|package)\b`, Type: chroma.KeywordNamespace, Mutator: nil},
{Pattern: `(var|func|struct|map|chan|type|interface|const)\b`, Type: chroma.KeywordDeclaration, Mutator: nil},
{Pattern: chroma.Words(``, `\b`, `break`, `default`, `select`, `case`, `defer`, `go`, `else`, `goto`, `switch`, `fallthrough`, `if`, `range`, `continue`, `for`, `return`), Type: chroma.Keyword, Mutator: nil},
{Pattern: `(true|false|iota|nil)\b`, Type: chroma.KeywordConstant, Mutator: nil},
{Pattern: chroma.Words(``, `\b(\()`, `uint`, `uint8`, `uint16`, `uint32`, `uint64`, `int`, `int8`, `int16`, `int32`, `int64`, `float`, `float32`, `float64`, `complex64`, `complex128`, `byte`, `rune`, `string`, `bool`, `error`, `uintptr`, `print`, `println`, `panic`, `recover`, `close`, `complex`, `real`, `imag`, `len`, `cap`, `append`, `copy`, `delete`, `new`, `make`, `clear`, `min`, `max`), Type: chroma.ByGroups(chroma.NameBuiltin, chroma.Punctuation), Mutator: nil},
{Pattern: chroma.Words(``, `\b`, `uint`, `uint8`, `uint16`, `uint32`, `uint64`, `int`, `int8`, `int16`, `int32`, `int64`, `float`, `float32`, `float64`, `complex64`, `complex128`, `byte`, `rune`, `string`, `bool`, `error`, `uintptr`, `any`), Type: chroma.KeywordType, Mutator: nil},
{Pattern: `\d[\d_]*i`, Type: chroma.LiteralNumber, Mutator: nil},
{Pattern: `\d[\d_]*\.[\d_]*([Ee][-+]?\d[\d_]*)?i`, Type: chroma.LiteralNumber, Mutator: nil},
{Pattern: `\.\d[\d_]*([Ee][-+]?\d[\d_]*)?i`, Type: chroma.LiteralNumber, Mutator: nil},
{Pattern: `\d[\d_]*[Ee][-+]?\d[\d_]*i`, Type: chroma.LiteralNumber, Mutator: nil},
{Pattern: `\d[\d_]*(\.[\d_]*([eE][+\-]?\d[\d_]*)?|[eE][+\-]?\d[\d_]*)`, Type: chroma.LiteralNumberFloat, Mutator: nil},
{Pattern: `\.\d[\d_]*([eE][+\-]?\d[\d_]*)?`, Type: chroma.LiteralNumberFloat, Mutator: nil},
{Pattern: `0[xX][0-9a-fA-F_]*\.?[0-9a-fA-F_]*[pP][+\-]?[0-9_]+`, Type: chroma.LiteralNumberFloat, Mutator: nil},
{Pattern: `0[oO]?[0-7_]+`, Type: chroma.LiteralNumberOct, Mutator: nil},
{Pattern: `0[xX][0-9a-fA-F_]+`, Type: chroma.LiteralNumberHex, Mutator: nil},
{Pattern: `0[bB][01_]+`, Type: chroma.LiteralNumberBin, Mutator: nil},
{Pattern: `(0|[1-9][0-9_]*)`, Type: chroma.LiteralNumberInteger, Mutator: nil},
{Pattern: `'(\\['"\\abfnrtv]|\\x[0-9a-fA-F]{2}|\\[0-7]{1,3}|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}|[^\\])'`, Type: chroma.LiteralStringChar, Mutator: nil},
{Pattern: "(`)([^`]*)(`)", Type: chroma.ByGroups(chroma.LiteralString, chroma.UsingLexer(chroma.TypeRemappingLexer(goTextTemplate, chroma.TypeMapping{{chroma.Other, chroma.LiteralString, nil}})), chroma.LiteralString), Mutator: nil},
{Pattern: `"(\\\\|\\"|[^"])*"`, Type: chroma.LiteralString, Mutator: nil},
{Pattern: `(<<=|>>=|<<|>>|<=|>=|&\^=|&\^|\+=|-=|\*=|/=|%=|&=|\|=|&&|\|\||<-|\+\+|--|==|!=|:=|\.\.\.|[+\-*/%&])`, Type: chroma.Operator, Mutator: nil},
{Pattern: `([a-zA-Z_]\w*)(\s*)(\()`, Type: chroma.ByGroups(chroma.NameFunction, chroma.UsingSelf("root"), chroma.Punctuation), Mutator: nil},
{Pattern: `[|^<>=!()\[\]{}.,;:~]`, Type: chroma.Punctuation, Mutator: nil},
{Pattern: `[^\W\d]\w*`, Type: chroma.NameOther, Mutator: nil},
},
}
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package lexers provides the chroma lexers for syntax highlighting one
// language at a time, so that an app links only the definitions of the
// languages that it highlights, instead of those of all of the hundreds of
// languages in github.com/alecthomas/chroma/v3/lexers. Each function adds
// the lexer for a language to a registry, as in:
//
// highlighting.AddLexers(lexers.Bash, lexers.TOML)
//
// The lexers are copies of the chroma lexers, for only the few languages
// that Cogent Core apps use, until chroma provides individual lexers itself
// (https://github.com/alecthomas/chroma/issues/1414). A language is added
// by adding its XML file to the included list of gen.go. Each function also
// adds the lexers that its lexer uses. Importing
// cogentcore.org/core/text/highlighting/alllexers uses all of the chroma
// lexers instead.
// Copyright (C) 2017 Alec Thomas, under an MIT License (see COPYING).
package lexers
//go:generate go run gen.go
import (
"io/fs"
"strings"
"time"
"github.com/alecthomas/chroma/v3"
)
// register adds the lexer defined by the XML file with the given name and
// contents to the registry. Its rules are loaded when it is first used.
func register(reg *chroma.LexerRegistry, file, xml string) {
reg.Register(chroma.MustNewXMLLexer(xmlFS{file, xml}, file))
}
// xmlFS is a file system with the XML definition of a lexer as its only file.
// The definitions are embedded as strings rather than embed.FS variables,
// because the bundler of the web leaves out unused strings, but not unused
// embed.FS variables.
type xmlFS struct {
name, data string
}
func (x xmlFS) Open(name string) (fs.File, error) {
if name != x.name {
return nil, &fs.PathError{Op: "open", Path: name, Err: fs.ErrNotExist}
}
return &xmlFile{Reader: strings.NewReader(x.data), name: name}, nil
}
// xmlFile is an open file of an [xmlFS], which is also its [fs.FileInfo].
type xmlFile struct {
*strings.Reader
name string
}
func (f *xmlFile) Stat() (fs.FileInfo, error) { return f, nil }
func (f *xmlFile) Close() error { return nil }
func (f *xmlFile) Name() string { return f.name }
func (f *xmlFile) Mode() fs.FileMode { return 0444 }
func (f *xmlFile) ModTime() time.Time { return time.Time{} }
func (f *xmlFile) IsDir() bool { return false }
func (f *xmlFile) Sys() any { return nil }
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package highlighting
import (
"fmt"
"cogentcore.org/core/text/parse/lexer"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/runes"
"cogentcore.org/core/text/textpos"
)
// MarkupLineRich returns the [rich.Text] styled line for each tag.
// Takes both the hi highlighting tags and extra tags.
// The style provides the starting default style properties.
func MarkupLineRich(hs *Style, sty *rich.Style, txt []rune, hitags, tags lexer.Line) rich.Text {
if len(txt) > maxLineLen { // avoid overflow
return rich.NewText(sty, txt[:maxLineLen])
}
if hs == nil {
return rich.NewText(sty, txt)
}
sz := len(txt)
if sz == 0 {
return nil
}
// The markup is often done in a background goroutine (see
// lines.Lines), while the theme colors can be updated.
themeMu.RLock()
defer themeMu.RUnlock()
ttags := lexer.MergeLines(hitags, tags) // ensures that inner-tags are *after* outer tags
// fmt.Println(ttags)
nt := len(ttags)
if nt == 0 || nt > maxNumTags {
return rich.NewText(sty, txt)
}
// first ensure text has spans for each tag region.
ln := len(txt)
var tx rich.Text
cp := 0
for _, tr := range ttags {
st := min(tr.Start, ln)
if st > cp {
tx.AddSpan(sty, txt[cp:st])
cp = st
} else if st < cp {
tx.SplitSpan(st)
}
ed := min(tr.End, ln)
if ed > cp {
tx.AddSpan(sty, txt[cp:ed])
cp = ed
} else {
tx.SplitSpan(ed)
}
}
if cp < ln {
tx.AddSpan(sty, txt[cp:])
}
// next, accumulate styles for each span
for si := range tx {
s, e := tx.Range(si)
srng := textpos.Range{Start: s, End: e}
cst := *sty
for _, tr := range ttags {
trng := textpos.Range{Start: tr.Start, End: tr.End}
if srng.Intersect(trng).Len() <= 0 {
continue
}
entry := hs.Tag(tr.Token.Token)
if !entry.IsZero() {
entry.ToRichStyle(&cst)
}
if tp, ok := Properties[tr.Token.Token]; ok {
applyPropertyDecorations(&cst, tp)
}
}
tx.SetSpanStyle(si, &cst)
}
return tx
}
// MarkupPathsAsLinks adds hyperlink span styles to given markup of given text,
// for any strings that look like file paths / urls.
// maxFields is the maximum number of fieldsto look for file paths in:
// 2 is a reasonable default, to avoid getting other false-alarm info later.
func MarkupPathsAsLinks(txt []rune, mu rich.Text, maxFields int) rich.Text {
fl := runes.Fields(txt)
mx := min(len(fl), maxFields)
for i := range mx {
ff := fl[i]
if !runes.HasPrefix(ff, []rune("./")) && !runes.HasPrefix(ff, []rune("/")) && !runes.HasPrefix(ff, []rune("../")) {
// todo: use regex instead of this.
if !runes.Contains(ff, []rune("/")) && !runes.Contains(ff, []rune(":")) {
continue
}
}
fi := runes.Index(txt, ff)
fnflds := runes.Split(ff, []rune(":"))
fn := string(fnflds[0])
pos := ""
col := ""
if len(fnflds) > 1 {
pos = string(fnflds[1])
col = ""
if len(fnflds) > 2 {
col = string(fnflds[2])
}
}
url := ""
if col != "" {
url = fmt.Sprintf(`file:///%v#L%vC%v`, fn, pos, col)
} else if pos != "" {
url = fmt.Sprintf(`file:///%v#L%v`, fn, pos)
} else {
url = fmt.Sprintf(`file:///%v`, fn)
}
si := mu.SplitSpan(fi)
efi := fi + len(ff)
esi := mu.SplitSpan(efi)
sty, _ := mu.Span(si)
sty.SetLink(url)
mu.SetSpanStyle(si, sty)
if esi > 0 {
mu.InsertEndSpecial(esi)
} else {
mu.EndSpecial()
}
}
// if string(mu.Join()) != string(txt) {
// panic("markup is not the same: " + string(txt) + " mu: " + string(mu.Join()))
// }
return mu
}
// applyPropertyDecorations applies the text-decoration flags from the
// custom tag fallback [Properties] (for tags without explicit style
// entries, such as TextSpellErr and Error) to the given rich style.
func applyPropertyDecorations(cst *rich.Style, pr map[string]any) {
var bits uint32
switch dec := pr["text-decoration"].(type) {
case uint32:
bits = dec
case int:
bits = uint32(dec)
default:
return
}
for d := rich.Underline; d <= rich.ParagraphStart; d++ {
if bits&(1<<uint32(d)) != 0 {
cst.SetDecoration(d)
}
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package highlighting provides syntax highlighting styles; it is based on
// github.com/alecthomas/chroma, which in turn was based on the python
// pygments package. Note that this package depends on core and parse
// and cannot be imported there; is imported in texteditor.
package highlighting
//go:generate core generate -add-types
import (
"encoding/json"
"image/color"
"log/slog"
"maps"
"os"
"strings"
"cogentcore.org/core/base/fsx"
"cogentcore.org/core/colors"
"cogentcore.org/core/colors/cam/hct"
"cogentcore.org/core/colors/matcolor"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/token"
)
type HighlightingName string
// Trilean value for StyleEntry value inheritance.
type Trilean int32 //enums:enum
const (
Pass Trilean = iota
Yes
No
)
func (t Trilean) Prefix(s string) string {
if t == Yes {
return s
} else if t == No {
return "no" + s
}
return ""
}
// TODO(go1.24): use omitzero instead of omitempty in [StyleEntry]
// once we update to go1.24
// StyleEntry is one value in the map of highlight style values
type StyleEntry struct {
// Color is the text color.
Color color.RGBA
// Background color.
// In general it is not good to use this because it obscures highlighting.
Background color.RGBA
// Border color? not sure what this is -- not really used.
Border color.RGBA `display:"-"`
// Bold font.
Bold Trilean `json:",omitempty"`
// Italic font.
Italic Trilean `json:",omitempty"`
// Underline.
Underline Trilean `json:",omitempty"`
// DottedUnderline
DottedUnderline Trilean `json:",omitempty"`
// NoInherit indicates to not inherit these settings from sub-category or category levels.
// Otherwise everything with a Pass is inherited.
NoInherit bool `json:",omitempty"`
// themeColor is the theme-adjusted text color.
themeColor color.RGBA
// themeBackground is the theme-adjusted background color.
themeBackground color.RGBA
}
// // FromChroma copies styles from chroma
//
// func (he *StyleEntry) FromChroma(ce chroma.StyleEntry) {
// if ce.Colour.IsSet() {
// he.Color.SetString(ce.Colour.String(), nil)
// } else {
// he.Color.SetToNil()
// }
// if ce.Background.IsSet() {
// he.Background.SetString(ce.Background.String(), nil)
// } else {
// he.Background.SetToNil()
// }
// if ce.Border.IsSet() {
// he.Border.SetString(ce.Border.String(), nil)
// } else {
// he.Border.SetToNil()
// }
// he.Bold = Trilean(ce.Bold)
// he.Italic = Trilean(ce.Italic)
// he.Underline = Trilean(ce.Underline)
// he.NoInherit = ce.NoInherit
// }
//
// // StyleEntryFromChroma returns a new style entry from corresponding chroma version
//
// func StyleEntryFromChroma(ce chroma.StyleEntry) StyleEntry {
// he := StyleEntry{}
// he.FromChroma(ce)
// return he
// }
// UpdateFromTheme normalizes the colors of the style entry such that they have consistent
// chromas and tones that guarantee sufficient text contrast in accordance with the color theme.
// An entry without a color (such as Error, which only has a border in most
// styles) has no theme color, so that its text keeps the default color.
func (se *StyleEntry) UpdateFromTheme() {
se.themeColor = color.RGBA{}
if !colors.IsNil(se.Color) {
hc := hct.FromColor(se.Color)
ctone := float32(40)
if matcolor.SchemeIsDark {
ctone = 80
}
se.themeColor = hc.WithChroma(max(hc.Chroma, 48)).WithTone(ctone).AsRGBA()
}
if !colors.IsNil(se.Background) {
hb := hct.FromColor(se.Background)
btone := max(hb.Tone, 94)
if matcolor.SchemeIsDark {
btone = min(hb.Tone, 17)
}
se.themeBackground = hb.WithChroma(max(hb.Chroma, 6)).WithTone(btone).AsRGBA()
}
}
func (se StyleEntry) String() string {
out := []string{}
if se.Bold != Pass {
out = append(out, se.Bold.Prefix("bold"))
}
if se.Italic != Pass {
out = append(out, se.Italic.Prefix("italic"))
}
if se.Underline != Pass {
out = append(out, se.Underline.Prefix("underline"))
}
if se.DottedUnderline != Pass {
out = append(out, se.DottedUnderline.Prefix("dotted-underline"))
}
if se.NoInherit {
out = append(out, "noinherit")
}
if !colors.IsNil(se.themeColor) {
out = append(out, colors.AsString(se.themeColor))
}
if !colors.IsNil(se.themeBackground) {
out = append(out, "bg:"+colors.AsString(se.themeBackground))
}
if !colors.IsNil(se.Border) {
out = append(out, "border:"+colors.AsString(se.Border))
}
return strings.Join(out, " ")
}
// ToCSS converts StyleEntry to CSS attributes.
func (se StyleEntry) ToCSS() string {
styles := []string{}
if !colors.IsNil(se.themeColor) {
styles = append(styles, "color: "+colors.AsString(se.themeColor))
}
if !colors.IsNil(se.themeBackground) {
styles = append(styles, "background-color: "+colors.AsString(se.themeBackground))
}
if se.Bold == Yes {
styles = append(styles, "font-weight: bold")
}
if se.Italic == Yes {
styles = append(styles, "font-style: italic")
}
if se.Underline == Yes {
styles = append(styles, "text-decoration: underline")
} else if se.DottedUnderline == Yes {
styles = append(styles, "text-decoration: dotted-underline")
}
return strings.Join(styles, "; ")
}
// ToProperties converts the StyleEntry to key-value properties.
func (se StyleEntry) ToProperties() map[string]any {
pr := map[string]any{}
if !colors.IsNil(se.themeColor) {
pr["color"] = se.themeColor
}
if !colors.IsNil(se.themeBackground) {
pr["background-color"] = se.themeBackground
}
if se.Bold == Yes {
pr["font-weight"] = rich.Bold
}
if se.Italic == Yes {
pr["font-style"] = rich.Italic
}
if se.Underline == Yes {
pr["text-decoration"] = 1 << uint32(rich.Underline)
} else if se.DottedUnderline == Yes {
pr["text-decoration"] = 1 << uint32(rich.DottedUnderline)
}
return pr
}
// ToRichStyle sets the StyleEntry to given [rich.Style].
func (se StyleEntry) ToRichStyle(sty *rich.Style) {
if !colors.IsNil(se.themeColor) {
sty.SetFillColor(se.themeColor)
}
if !colors.IsNil(se.themeBackground) {
sty.SetBackground(se.themeBackground)
}
if se.Bold == Yes {
sty.Weight = rich.Bold
}
if se.Italic == Yes {
sty.Slant = rich.Italic
}
if se.Underline == Yes {
sty.Decoration.SetFlag(true, rich.Underline)
} else if se.DottedUnderline == Yes {
sty.Decoration.SetFlag(true, rich.DottedUnderline)
}
}
// Sub subtracts two style entries, returning an entry with only the differences set
func (se StyleEntry) Sub(e StyleEntry) StyleEntry {
out := StyleEntry{}
if e.Color != se.Color {
out.Color = se.Color
out.themeColor = se.themeColor
}
if e.Background != se.Background {
out.Background = se.Background
out.themeBackground = se.themeBackground
}
if e.Border != se.Border {
out.Border = se.Border
}
if e.Bold != se.Bold {
out.Bold = se.Bold
}
if e.Italic != se.Italic {
out.Italic = se.Italic
}
if e.Underline != se.Underline {
out.Underline = se.Underline
}
if e.DottedUnderline != se.DottedUnderline {
out.DottedUnderline = se.DottedUnderline
}
return out
}
// Inherit styles from ancestors.
//
// Ancestors should be provided from oldest, furthest away to newest, closest.
func (se StyleEntry) Inherit(ancestors ...StyleEntry) StyleEntry {
out := se
for ri := len(ancestors) - 1; ri >= 0; ri-- {
ancestor := ancestors[ri]
if out.NoInherit {
return out
}
if colors.IsNil(out.themeColor) {
out.Color = ancestor.Color
out.themeColor = ancestor.themeColor
}
if colors.IsNil(out.themeBackground) {
out.Background = ancestor.Background
out.themeBackground = ancestor.themeBackground
}
if colors.IsNil(out.Border) {
out.Border = ancestor.Border
}
if out.Bold == Pass {
out.Bold = ancestor.Bold
}
if out.Italic == Pass {
out.Italic = ancestor.Italic
}
if out.Underline == Pass {
out.Underline = ancestor.Underline
}
if out.DottedUnderline == Pass {
out.DottedUnderline = ancestor.DottedUnderline
}
}
return out
}
func (se StyleEntry) IsZero() bool {
return colors.IsNil(se.Color) && colors.IsNil(se.Background) && colors.IsNil(se.Border) && se.Bold == Pass && se.Italic == Pass && se.Underline == Pass && se.DottedUnderline == Pass && !se.NoInherit
}
///////////////////////////////////////////////////////////////////////////////////
// Style
// Style is a full style map of styles for different token.Tokens tag values
type Style map[token.Tokens]*StyleEntry
// CopyFrom copies a style from source style
func (hs *Style) CopyFrom(ss *Style) {
if ss == nil {
return
}
*hs = make(Style, len(*ss))
maps.Copy((*hs), *ss)
}
// TagRaw returns a StyleEntry for given tag without any inheritance of anything
// will be IsZero if not defined for this style
func (hs Style) TagRaw(tag token.Tokens) StyleEntry {
if len(hs) == 0 {
return StyleEntry{}
}
if se, has := hs[tag]; has {
return *se
}
return StyleEntry{}
}
// Tag returns a StyleEntry for given Tag.
// Will try sub-category or category if an exact match is not found.
// does NOT add the background properties -- those are always kept separate.
func (hs Style) Tag(tag token.Tokens) StyleEntry {
se := hs.TagRaw(tag).Inherit(
hs.TagRaw(token.Text),
hs.TagRaw(tag.Cat()),
hs.TagRaw(tag.SubCat()))
return se
}
// ToCSS generates a CSS style sheet for this style, by token.Tokens tag
func (hs Style) ToCSS() map[token.Tokens]string {
themeMu.RLock() // (the theme colors can be updated in another window)
defer themeMu.RUnlock()
css := map[token.Tokens]string{}
for ht := range token.Names {
entry := hs.Tag(ht)
if entry.IsZero() {
continue
}
css[ht] = entry.ToCSS()
}
return css
}
// ToProperties generates a list of key-value properties for this style.
func (hs Style) ToProperties() map[string]any {
themeMu.RLock() // (the theme colors can be updated in another window)
defer themeMu.RUnlock()
pr := map[string]any{}
for ht, nm := range token.Names {
entry := hs.Tag(ht)
if entry.IsZero() {
if tp, ok := Properties[ht]; ok {
pr["."+nm] = tp
}
continue
}
pr["."+nm] = entry.ToProperties()
}
return pr
}
// Open hi style from a JSON-formatted file.
func (hs *Style) OpenJSON(filename fsx.Filename) error {
b, err := os.ReadFile(string(filename))
if err != nil {
// PromptDialog(nil, "File Not Found", err.Error(), true, false, nil, nil, nil)
slog.Error(err.Error())
return err
}
return json.Unmarshal(b, hs)
}
// Save hi style to a JSON-formatted file.
func (hs Style) SaveJSON(filename fsx.Filename) error {
b, err := json.MarshalIndent(hs, "", " ")
if err != nil {
slog.Error(err.Error()) // unlikely
return err
}
err = os.WriteFile(string(filename), b, 0644)
if err != nil {
// PromptDialog(nil, "Could not Save to File", err.Error(), true, false, nil, nil, nil)
slog.Error(err.Error())
}
return err
}
// Properties are default properties for custom tags (tokens); if set in style then used
// there but otherwise we use these as a fallback; typically not overridden.
// text-decoration flags here are applied to tagged spans even when the style
// also defines other properties for the tag, so that diagnostic tags like
// Error are always visibly decorated.
var Properties = map[token.Tokens]map[string]any{
token.TextSpellErr: {
"text-decoration": uint32(1) << uint32(rich.DottedUnderline), // bitflag!
},
token.Error: {
"text-decoration": uint32(1) << uint32(rich.DottedUnderline), // bitflag!
},
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package highlighting
import (
_ "embed"
"encoding/json"
"fmt"
"log/slog"
"maps"
"os"
"path/filepath"
"slices"
"sync"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/fsx"
"cogentcore.org/core/system"
)
// DefaultStyle is the initial default style.
var DefaultStyle = HighlightingName("emacs")
// Styles is a collection of styles
type Styles map[string]*Style
var (
//go:embed defaults.highlighting
defaults []byte
// StandardStyles are the styles from chroma package
StandardStyles Styles
// CustomStyles are user's special styles
CustomStyles = Styles{}
// AvailableStyles are all highlighting styles
AvailableStyles Styles
// StyleDefault is the default highlighting style name
StyleDefault = HighlightingName("emacs")
// StyleNames are all the names of all the available highlighting styles
StyleNames []string
// SettingsStylesFilename is the name of the preferences file in App data
// directory for saving / loading the custom styles
SettingsStylesFilename = "highlighting.json"
// StylesChanged is used for gui updating while editing
StylesChanged = false
)
// themeMu guards usedStyles and the theme colors of the style entries,
// which [UpdateFromTheme] sets while the syntax highlighting markup of
// [MarkupLineRich] can read them in another goroutine.
var themeMu sync.RWMutex
// usedStyles holds the names of the styles that [AvailableStyle] has
// returned. [UpdateFromTheme] updates only these styles, and AvailableStyle
// updates a style when it first returns it, as updating the colors of all
// of the styles takes time.
var usedStyles = map[string]bool{}
// UpdateFromTheme normalizes the colors of all style entry such that they have consistent
// chromas and tones that guarantee sufficient text contrast in accordance with the color theme.
// Styles that have not been used yet are updated when they are first used.
func UpdateFromTheme() {
themeMu.Lock()
defer themeMu.Unlock()
for nm := range usedStyles {
updateStyleFromTheme(AvailableStyles[nm])
}
}
// updateStyleFromTheme updates the colors of all entries of the style
// from the color theme.
func updateStyleFromTheme(s *Style) {
if s == nil {
return
}
for _, se := range *s {
se.UpdateFromTheme()
}
}
// AvailableStyle returns a style by name from the AvailStyles list -- if not found
// default is used as a fallback
func AvailableStyle(nm HighlightingName) *Style {
if AvailableStyles == nil {
Init()
}
name := string(nm)
st, ok := AvailableStyles[name]
if !ok {
name = string(StyleDefault)
st = AvailableStyles[name]
}
// A style used for the first time gets the colors of the theme.
themeMu.Lock()
defer themeMu.Unlock()
if !usedStyles[name] {
usedStyles[name] = true
updateStyleFromTheme(st)
}
return st
}
// Add adds a new style to the list
func (hs *Styles) Add() *Style {
hse := &Style{}
nm := fmt.Sprintf("NewStyle_%v", len(*hs))
(*hs)[nm] = hse
return hse
}
// CopyFrom copies styles from another collection
func (hs *Styles) CopyFrom(os Styles) {
if *hs == nil {
*hs = make(Styles, len(os))
}
maps.Copy((*hs), os)
}
// MergeAvailStyles updates AvailStyles as combination of std and custom styles
func MergeAvailStyles() {
AvailableStyles = make(Styles, len(CustomStyles)+len(StandardStyles))
AvailableStyles.CopyFrom(StandardStyles)
AvailableStyles.CopyFrom(CustomStyles)
StyleNames = AvailableStyles.Names()
}
// Open hi styles from a JSON-formatted file. You can save and open
// styles to / from files to share, experiment, transfer, etc.
func (hs *Styles) OpenJSON(filename fsx.Filename) error { //types:add
b, err := os.ReadFile(string(filename))
if err != nil {
// PromptDialog(nil, "File Not Found", err.Error(), true, false, nil, nil, nil)
// slog.Error(err.Error())
return err
}
return json.Unmarshal(b, hs)
}
// Save hi styles to a JSON-formatted file. You can save and open
// styles to / from files to share, experiment, transfer, etc.
func (hs *Styles) SaveJSON(filename fsx.Filename) error { //types:add
b, err := json.MarshalIndent(hs, "", " ")
if err != nil {
slog.Error(err.Error()) // unlikely
return err
}
err = os.WriteFile(string(filename), b, 0644)
if err != nil {
// PromptDialog(nil, "Could not Save to File", err.Error(), true, false, nil, nil, nil)
slog.Error(err.Error())
}
return err
}
// OpenSettings opens Styles from Cogent Core standard prefs directory, using SettingsStylesFilename
func (hs *Styles) OpenSettings() error {
pdir := system.TheApp.CogentCoreDataDir()
pnm := filepath.Join(pdir, SettingsStylesFilename)
StylesChanged = false
return hs.OpenJSON(fsx.Filename(pnm))
}
// SaveSettings saves Styles to Cogent Core standard prefs directory, using SettingsStylesFilename
func (hs *Styles) SaveSettings() error {
pdir := system.TheApp.CogentCoreDataDir()
pnm := filepath.Join(pdir, SettingsStylesFilename)
StylesChanged = false
MergeAvailStyles()
return hs.SaveJSON(fsx.Filename(pnm))
}
// SaveAll saves all styles individually to chosen directory
func (hs *Styles) SaveAll(dir fsx.Filename) {
for nm, st := range *hs {
fnm := filepath.Join(string(dir), nm+".highlighting")
st.SaveJSON(fsx.Filename(fnm))
}
}
// OpenDefaults opens the default highlighting styles (from chroma originally)
// These are encoded as an embed from defaults.highlighting
func (hs *Styles) OpenDefaults() error {
err := json.Unmarshal(defaults, hs)
if err != nil {
return errors.Log(err)
}
return err
}
// Names outputs names of styles in collection
func (hs *Styles) Names() []string {
nms := make([]string, len(*hs))
idx := 0
for nm := range *hs {
nms[idx] = nm
idx++
}
slices.Sort(nms)
return nms
}
// Init must be called to initialize the hi styles -- post startup
// so chroma stuff is all in place, and loads custom styles.
// The parsers of the languages open when they are first used.
func Init() {
StandardStyles.OpenDefaults()
CustomStyles.OpenSettings()
if len(CustomStyles) == 0 {
cs := &Style{}
cs.CopyFrom(StandardStyles[string(StyleDefault)])
CustomStyles["custom-sample"] = cs
}
MergeAvailStyles()
UpdateFromTheme()
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package highlighting
import (
"sync"
"cogentcore.org/core/text/token"
"github.com/alecthomas/chroma/v3"
)
// FromChroma converts a chroma.TokenType to a parse token.Tokens
func TokenFromChroma(ct chroma.TokenType) token.Tokens {
chromaToTokensMu.Lock()
defer chromaToTokensMu.Unlock()
if chromaToTokensMap == nil {
chromaToTokensMap = make(map[chroma.TokenType]token.Tokens, len(TokensToChromaMap))
for k, v := range TokensToChromaMap {
chromaToTokensMap[v] = k
}
}
tok := chromaToTokensMap[ct]
return tok
}
// TokenToChroma converts to a chroma.TokenType
func TokenToChroma(tok token.Tokens) chroma.TokenType {
return TokensToChromaMap[tok]
}
var (
// chromaToTokensMap maps from chroma.TokenType to Tokens -- built from opposite map
chromaToTokensMap map[chroma.TokenType]token.Tokens
chromaToTokensMu sync.Mutex
)
// TokensToChromaMap maps from Tokens to chroma.TokenType
var TokensToChromaMap = map[token.Tokens]chroma.TokenType{
token.EOF: chroma.TokenType(0), // chroma v3 has no EOFType, which was 0 in v2
token.Background: chroma.Background,
token.Error: chroma.Error,
token.None: chroma.None,
token.Keyword: chroma.Keyword,
token.KeywordConstant: chroma.KeywordConstant,
token.KeywordDeclaration: chroma.KeywordDeclaration,
token.KeywordNamespace: chroma.KeywordNamespace,
token.KeywordPseudo: chroma.KeywordPseudo,
token.KeywordReserved: chroma.KeywordReserved,
token.KeywordType: chroma.KeywordType,
token.Name: chroma.Name,
token.NameAttribute: chroma.NameAttribute,
token.NameBuiltin: chroma.NameBuiltin,
token.NameBuiltinPseudo: chroma.NameBuiltinPseudo,
token.NameClass: chroma.NameClass,
token.NameConstant: chroma.NameConstant,
token.NameDecorator: chroma.NameDecorator,
token.NameEntity: chroma.NameEntity,
token.NameException: chroma.NameException,
token.NameFunction: chroma.NameFunction,
token.NameFunctionMagic: chroma.NameFunctionMagic,
token.NameLabel: chroma.NameLabel,
token.NameNamespace: chroma.NameNamespace,
token.NameOperator: chroma.NameOperator,
token.NameOther: chroma.NameOther,
token.NamePseudo: chroma.NamePseudo,
token.NameProperty: chroma.NameProperty,
token.NameTag: chroma.NameTag,
token.NameVar: chroma.NameVariable,
token.NameVarAnonymous: chroma.NameVariableAnonymous,
token.NameVarClass: chroma.NameVariableClass,
token.NameVarGlobal: chroma.NameVariableGlobal,
token.NameVarInstance: chroma.NameVariableInstance,
token.NameVarMagic: chroma.NameVariableMagic,
token.Literal: chroma.Literal,
token.LiteralDate: chroma.LiteralDate,
token.LiteralOther: chroma.LiteralOther,
token.LitStr: chroma.LiteralString,
token.LitStrAffix: chroma.LiteralStringAffix,
token.LitStrAtom: chroma.LiteralStringAtom,
token.LitStrBacktick: chroma.LiteralStringBacktick,
token.LitStrBoolean: chroma.LiteralStringBoolean,
token.LitStrChar: chroma.LiteralStringChar,
token.LitStrDelimiter: chroma.LiteralStringDelimiter,
token.LitStrDoc: chroma.LiteralStringDoc,
token.LitStrDouble: chroma.LiteralStringDouble,
token.LitStrEscape: chroma.LiteralStringEscape,
token.LitStrHeredoc: chroma.LiteralStringHeredoc,
token.LitStrInterpol: chroma.LiteralStringInterpol,
token.LitStrName: chroma.LiteralStringName,
token.LitStrOther: chroma.LiteralStringOther,
token.LitStrRegex: chroma.LiteralStringRegex,
token.LitStrSingle: chroma.LiteralStringSingle,
token.LitStrSymbol: chroma.LiteralStringSymbol,
token.LitNum: chroma.LiteralNumber,
token.LitNumBin: chroma.LiteralNumberBin,
token.LitNumFloat: chroma.LiteralNumberFloat,
token.LitNumHex: chroma.LiteralNumberHex,
token.LitNumInteger: chroma.LiteralNumberInteger,
token.LitNumIntegerLong: chroma.LiteralNumberIntegerLong,
token.LitNumOct: chroma.LiteralNumberOct,
token.Operator: chroma.Operator,
token.OperatorWord: chroma.OperatorWord,
token.Punctuation: chroma.Punctuation,
token.Comment: chroma.Comment,
token.CommentHashbang: chroma.CommentHashbang,
token.CommentMultiline: chroma.CommentMultiline,
token.CommentSingle: chroma.CommentSingle,
token.CommentSpecial: chroma.CommentSpecial,
token.CommentPreproc: chroma.CommentPreproc,
token.CommentPreprocFile: chroma.CommentPreprocFile,
token.Text: chroma.Text,
token.TextWhitespace: chroma.TextWhitespace,
token.TextSymbol: chroma.TextSymbol,
token.TextPunctuation: chroma.TextPunctuation,
token.TextStyle: chroma.Generic,
token.TextStyleDeleted: chroma.GenericDeleted,
token.TextStyleEmph: chroma.GenericEmph,
token.TextStyleError: chroma.GenericError,
token.TextStyleHeading: chroma.GenericHeading,
token.TextStyleInserted: chroma.GenericInserted,
token.TextStyleOutput: chroma.GenericOutput,
token.TextStylePrompt: chroma.GenericPrompt,
token.TextStyleStrong: chroma.GenericStrong,
token.TextStyleSubheading: chroma.GenericSubheading,
token.TextStyleTraceback: chroma.GenericTraceback,
token.TextStyleUnderline: chroma.GenericUnderline,
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package htmltext converts HTML and preformatted text with HTML markup to
// rich text, and rich text to HTML.
package htmltext
import (
"bytes"
"encoding/xml"
"fmt"
"html"
"io"
"strings"
"unicode"
"unicode/utf8"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/iox/xmlx"
"cogentcore.org/core/base/stack"
"cogentcore.org/core/styles/styleprops"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/runes"
)
// HTMLToRich translates HTML-formatted rich text into a [rich.Text],
// using given initial text styling parameters and css properties.
// This uses the golang XML decoder system, which strips all whitespace
// and therefore does not capture any preformatted text. See HTMLPre.
// cssProps are a list of css key-value pairs that are used to set styling
// properties for the text, and can include class names with a value of
// another property map that is applied to elements of that class,
// including standard elements like a for links, etc.
func HTMLToRich(str []byte, sty *rich.Style, cssProps map[string]any) (rich.Text, error) {
sz := len(str)
if sz == 0 {
return nil, nil
}
spcstr := bytes.Join(bytes.Fields(str), []byte(" "))
// Plain text without markup is one span of the text, as the decoder gives.
if isPlainText(spcstr) {
return rich.Join(rich.NewText(sty, []rune(string(spcstr)))), nil
}
return htmlToRich(spcstr, sty, cssProps)
}
// isPlainText returns whether the text has no markup, entities or anything
// else that the XML decoder would change or report as an error, in which case
// it is one character data token of the text itself.
func isPlainText(b []byte) bool {
if bytes.Contains(b, []byte("]]>")) {
return false
}
for len(b) > 0 {
r, n := utf8.DecodeRune(b)
switch {
case r == '<' || r == '&':
return false
case r < 0x20 || r == utf8.RuneError || r == 0xFEFF || r == 0xFFFE || r == 0xFFFF:
return false
}
b = b[n:]
}
return true
}
// htmlToRich is [HTMLToRich] for the given text with its whitespace collapsed.
func htmlToRich(spcstr []byte, sty *rich.Style, cssProps map[string]any) (rich.Text, error) {
var errs []error
reader := bytes.NewReader(spcstr)
decoder := xml.NewDecoder(reader)
decoder.Strict = false
decoder.AutoClose = xml.HTMLAutoClose
decoder.Entity = xml.HTMLEntity
decoder.CharsetReader = xmlx.CharsetReader
// set when a </p> is encountered
nextIsParaStart := false
// stack of font styles
fstack := make(stack.Stack[*rich.Style], 0)
fstack.Push(sty)
// stack of rich text spans that are later joined for final result
spstack := make(stack.Stack[rich.Text], 0)
curSp := rich.NewText(sty, nil)
spstack.Push(curSp)
for {
t, err := decoder.Token()
if err != nil {
if err == io.EOF {
break
}
errs = append(errs, err)
break
}
switch se := t.(type) {
case xml.StartElement:
fs := fstack.Peek().Clone() // new style for new element
atStart := curSp.Len() == 0
if nextIsParaStart && atStart {
fs.Decoration.SetFlag(true, rich.ParagraphStart)
}
nextIsParaStart = false
nm := strings.ToLower(se.Name.Local)
insertText := []rune{}
special := rich.Nothing
linkURL := ""
if !fs.SetFromHTMLTag(nm) {
switch nm {
case "a":
special = rich.Link
fs.SetLinkStyle()
for _, attr := range se.Attr {
if attr.Name.Local == "href" {
linkURL = attr.Value
}
}
case "span": // todo: , "pre"
// just uses properties
case "q":
special = rich.Quote
case "math":
special = rich.MathInline
case "sup":
special = rich.Super
fs.Size = 0.8
case "sub":
special = rich.Sub
fs.Size = 0.8
case "dfn":
// no default styling
case "bdo":
// todo: bidirectional override..
case "p":
// todo: detect <p> at end of paragraph only
fs.Decoration.SetFlag(true, rich.ParagraphStart)
case "br":
// handled in end: standalone <br> is in both start and end
case "err":
// custom; used to mark errors
default:
err := fmt.Errorf("%q tag not recognized", nm)
errs = append(errs, err)
}
}
if len(se.Attr) > 0 {
sprop := make(map[string]any, len(se.Attr))
for _, attr := range se.Attr {
switch attr.Name.Local {
case "style":
styleprops.FromXMLString(attr.Value, sprop)
case "class":
if attr.Value == "math inline" {
special = rich.MathInline
}
if attr.Value == "math display" {
special = rich.MathDisplay
}
if cssProps != nil {
clnm := "." + attr.Value
if aggp, ok := SubProperties(clnm, cssProps); ok {
fs.FromProperties(nil, aggp, nil)
}
}
default:
sprop[attr.Name.Local] = attr.Value
}
}
fs.FromProperties(nil, sprop, nil)
}
if cssProps != nil {
FontStyleCSS(fs, nm, cssProps)
}
fstack.Push(fs)
if curSp.Len() == 0 && len(spstack) > 0 && !startsSpecial(curSp) { // we started something but added nothing to it.
// (except a special, as a link, whose text is in elements in
// it, as <a href="..."><span>text</span></a>, which was not
// a link)
spstack.Pop()
}
if special != rich.Nothing {
ss := fs.Clone() // key about specials: make a new one-off style so special doesn't repeat
ss.Special = special
if special == rich.Link {
ss.URL = linkURL
}
curSp = rich.NewText(ss, insertText)
} else {
curSp = rich.NewText(fs, insertText)
}
spstack.Push(curSp)
case xml.EndElement:
switch se.Name.Local {
case "p":
curSp.AddRunes([]rune{'\n'})
nextIsParaStart = true
case "br":
curSp.AddRunes([]rune{'\n'})
nextIsParaStart = false
case "a", "q", "math", "sub", "sup": // important: any special must be ended!
nsp := rich.Text{}
nsp.EndSpecial()
spstack.Push(nsp)
case "span":
sty, stx := curSp.Span(0)
if sty.Special != rich.Nothing {
if sty.IsMath() {
stx = runes.TrimPrefix(stx, []rune("\\("))
stx = runes.TrimSuffix(stx, []rune("\\)"))
stx = runes.TrimPrefix(stx, []rune("\\["))
stx = runes.TrimSuffix(stx, []rune("\\]"))
// fmt.Println("math:", string(stx))
curSp.SetSpanRunes(0, stx)
}
nsp := rich.Text{}
nsp.EndSpecial()
spstack.Push(nsp)
}
}
if len(fstack) > 0 {
fstack.Pop()
fs := fstack.Peek()
curSp = rich.NewText(fs, nil)
spstack.Push(curSp) // start a new span with previous style
} else {
err := fmt.Errorf("imbalanced start / end tags: %q", se.Name.Local)
errs = append(errs, err)
}
case xml.CharData:
atStart := curSp.Len() == 0
sstr := html.UnescapeString(string(se))
if nextIsParaStart && atStart {
sstr = strings.TrimLeftFunc(sstr, func(r rune) bool {
return unicode.IsSpace(r)
})
}
curSp.AddRunes([]rune(sstr))
}
}
return rich.Join(spstack...), errors.Join(errs...)
}
// SubProperties returns a properties map[string]any from given key tag
// of given properties map, if the key exists and the value is a sub props map.
// Otherwise returns nil, false
func SubProperties(tag string, cssProps map[string]any) (map[string]any, bool) {
tp, ok := cssProps[tag]
if !ok {
return nil, false
}
pmap, ok := tp.(map[string]any)
if !ok {
return nil, false
}
return pmap, true
}
// FontStyleCSS looks for "tag" name properties in cssProps properties, and applies those to
// style if found, and returns true -- false if no such tag found
func FontStyleCSS(fs *rich.Style, tag string, cssProps map[string]any) bool {
if cssProps == nil {
return false
}
pmap, ok := SubProperties(tag, cssProps)
if !ok {
return false
}
fs.FromProperties(nil, pmap, nil)
return true
}
// startsSpecial returns whether the given span starts a special (as a link),
// with no text of its own yet.
func startsSpecial(sp rich.Text) bool {
if len(sp) == 0 || len(sp[0]) == 0 {
return false
}
s := rich.RuneToSpecial(sp[0][0])
return s != rich.Nothing && s != rich.End
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmltext
import (
"bytes"
"errors"
"fmt"
"html"
"regexp"
"strings"
"cogentcore.org/core/base/stack"
"cogentcore.org/core/styles/styleprops"
"cogentcore.org/core/text/rich"
)
// HTMLPreToRich translates preformatted HTML-styled text into a [rich.Text]
// using given initial text styling parameters and css properties.
// This uses a custom decoder that preserves all whitespace characters,
// and decodes all standard inline HTML text style formatting tags in the string.
// Only basic styling tags, including <span> elements with style parameters
// (including class names) are decoded. Whitespace is decoded as-is,
// including LF \n etc, except in WhiteSpacePreLine case which only preserves LF's.
func HTMLPreToRich(str []byte, sty *rich.Style, cssProps map[string]any) (rich.Text, error) {
sz := len(str)
if sz == 0 {
return nil, nil
}
var errs []error
// set when a </p> is encountered
nextIsParaStart := false
// stack of font styles
fstack := make(stack.Stack[*rich.Style], 0)
fstack.Push(sty)
// stack of rich text spans that are later joined for final result
spstack := make(stack.Stack[rich.Text], 0)
curSp := rich.NewText(sty, nil)
spstack.Push(curSp)
tagstack := make(stack.Stack[string], 0)
tmpbuf := make([]byte, 0, 1020)
bidx := 0
curTag := ""
for bidx < sz {
cb := str[bidx]
ftag := ""
if cb == '<' && sz > bidx+1 {
eidx := bytes.Index(str[bidx+1:], []byte(">"))
if eidx > 0 {
ftag = string(str[bidx+1 : bidx+1+eidx])
bidx += eidx + 2
} else { // get past <
curSp.AddRunes([]rune(string(str[bidx : bidx+1])))
bidx++
}
}
if ftag != "" {
if ftag[0] == '/' { // EndElement
etag := strings.ToLower(ftag[1:])
// fmt.Printf("%v etag: %v\n", bidx, etag)
if etag == "pre" {
continue // ignore
}
if etag != curTag {
err := fmt.Errorf("end tag: %q doesn't match current tag: %q", etag, curTag)
errs = append(errs, err)
}
switch etag {
case "p":
curSp.AddRunes([]rune{'\n'})
nextIsParaStart = true
case "br":
curSp.AddRunes([]rune{'\n'})
nextIsParaStart = false
case "a", "q", "math", "sub", "sup": // important: any special must be ended!
curSp.EndSpecial()
}
if len(fstack) > 1 { // (the first is the base style, not of a tag)
fstack.Pop()
fs := fstack.Peek()
curSp = rich.NewText(fs, nil)
spstack.Push(curSp) // start a new span with previous style
} else {
err := fmt.Errorf("imbalanced start / end tags: %q", etag)
errs = append(errs, err)
}
tslen := len(tagstack)
if tslen > 1 {
tagstack.Pop()
curTag = tagstack.Peek()
} else if tslen == 1 {
tagstack.Pop()
curTag = ""
} else {
err := fmt.Errorf("imbalanced start / end tags: %q", curTag)
errs = append(errs, err)
}
} else { // StartElement
parts := strings.Split(ftag, " ")
stag := strings.ToLower(strings.TrimSpace(parts[0]))
// fmt.Printf("%v stag: %v\n", bidx, stag)
attrs := parseAttrs(strings.Join(parts[1:], " "))
nattr := len(attrs)
fs := fstack.Peek().Clone() // new style for new element
atStart := curSp.Len() == 0
if nextIsParaStart && atStart {
fs.Decoration.SetFlag(true, rich.ParagraphStart)
}
nextIsParaStart = false
insertText := []rune{}
special := rich.Nothing
linkURL := ""
if !fs.SetFromHTMLTag(stag) {
switch stag {
case "a":
special = rich.Link
fs.SetLinkStyle()
if nattr > 0 {
sprop := make(map[string]any, nattr)
for _, at := range attrs {
nm, vl := at[0], at[1]
if nm == "href" {
linkURL = vl
}
sprop[nm] = vl
}
}
case "span":
// just uses properties
case "q":
special = rich.Quote
case "math":
special = rich.MathInline
case "sup":
special = rich.Super
fs.Size = 0.8
case "sub":
special = rich.Sub
fs.Size = 0.8
case "dfn":
// no default styling
case "bdo":
// todo: bidirectional override..
case "pre": // nop
case "p":
fs.Decoration.SetFlag(true, rich.ParagraphStart)
case "br":
curSp = rich.NewText(fs, []rune{'\n'}) // br is standalone: do it!
spstack.Push(curSp)
nextIsParaStart = false
default:
err := fmt.Errorf("%q tag not recognized", stag)
errs = append(errs, err)
}
}
if nattr > 0 { // attr
sprop := make(map[string]any, nattr)
for _, at := range attrs {
nm, vl := at[0], at[1]
// fmt.Printf("nm: %v val: %v\n", nm, vl)
switch nm {
case "style":
styleprops.FromXMLString(vl, sprop)
case "class":
if vl == "math inline" {
special = rich.MathInline
}
if vl == "math display" {
special = rich.MathDisplay
}
if cssProps != nil {
clnm := "." + vl
if aggp, ok := SubProperties(clnm, cssProps); ok {
fs.FromProperties(nil, aggp, nil)
}
}
default:
sprop[nm] = vl
}
}
fs.FromProperties(nil, sprop, nil)
}
if cssProps != nil {
FontStyleCSS(fs, stag, cssProps)
}
fstack.Push(fs)
curTag = stag
tagstack.Push(curTag)
if curSp.Len() == 0 && len(spstack) > 0 { // we started something but added nothing to it.
spstack.Pop()
}
if special != rich.Nothing {
ss := fs.Clone() // key about specials: make a new one-off style so special doesn't repeat
ss.Special = special
if special == rich.Link {
ss.URL = linkURL
}
curSp = rich.NewText(ss, insertText)
} else {
curSp = rich.NewText(fs, insertText)
}
spstack.Push(curSp)
}
} else { // raw chars
// todo: deal with WhiteSpacePreLine -- trim out non-LF ws
tmpbuf := tmpbuf[0:0]
didNl := false
aggloop:
for ; bidx < sz; bidx++ {
nb := str[bidx] // re-gets cb so it can be processed here..
switch nb {
case '<':
if (bidx > 0 && str[bidx-1] == '<') || sz == bidx+1 {
tmpbuf = append(tmpbuf, nb)
didNl = false
} else {
didNl = false
break aggloop
}
case '\n': // todo absorb other line endings
unestr := html.UnescapeString(string(tmpbuf))
curSp.AddRunes([]rune(unestr + "\n"))
curSp = rich.NewText(fstack.Peek(), nil)
spstack.Push(curSp) // start a new span with previous style
tmpbuf = tmpbuf[0:0]
didNl = true
default:
didNl = false
tmpbuf = append(tmpbuf, nb)
}
}
if !didNl {
unestr := html.UnescapeString(string(tmpbuf))
// fmt.Printf("%v added: %v\n", bidx, unestr)
curSp.AddRunes([]rune(unestr))
}
}
}
return rich.Join(spstack...), errors.Join(errs...)
}
// attrRegexp matches an attribute of a start tag, with a quoted or bare value.
var attrRegexp = regexp.MustCompile(`([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))`)
// parseAttrs returns the names and values of the attributes of a start tag
// (the text after its name), whose values can contain spaces and equal signs.
func parseAttrs(s string) [][2]string {
var attrs [][2]string
for _, m := range attrRegexp.FindAllStringSubmatch(s, -1) {
attrs = append(attrs, [2]string{m[1], m[2] + m[3] + m[4]})
}
return attrs
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package htmltext
import (
"html"
"slices"
"strings"
"cogentcore.org/core/text/rich"
)
// RichToHTML returns an HTML encoded representation of the rich.Text,
// with <b>, <i>, and <u> tags for bold, italic, and underlined text,
// <a> tags for links, and the text escaped.
func RichToHTML(tx rich.Text) string {
var b strings.Builder
var open []string // the tags that are open, innermost last
closeTo := func(n int) { // closes the tags after the first n
for len(open) > n {
b.WriteString("</")
b.WriteString(open[len(open)-1])
b.WriteString(">")
open = open[:len(open)-1]
}
}
for si := range tx.NumSpans() {
sty, rs := tx.Span(si)
if sty.Special == rich.Link {
closeTo(0)
b.WriteString(`<a href="`)
b.WriteString(html.EscapeString(sty.URL))
b.WriteString(`">`)
b.WriteString(html.EscapeString(string(rs)))
b.WriteString(`</a>`)
continue
}
var want []string // the tags of this span, in the order they are opened
if tag := sty.Weight.HTMLTag(); tag != "" {
want = append(want, tag)
}
if sty.Slant != rich.SlantNormal {
want = append(want, "i")
}
if sty.Decoration.HasFlag(rich.Underline) {
want = append(want, "u")
}
// the open tags that are wanted stay open, up to the first one that
// is not, which is closed with the ones in it
keep := 0
for keep < len(open) && slices.Contains(want, open[keep]) {
keep++
}
closeTo(keep)
for _, tag := range want {
if !slices.Contains(open, tag) {
b.WriteString("<")
b.WriteString(tag)
b.WriteString(">")
open = append(open, tag)
}
}
b.WriteString(html.EscapeString(string(rs)))
}
closeTo(0)
return b.String()
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lines
import (
"image"
"regexp"
"slices"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/fileinfo"
"cogentcore.org/core/text/highlighting"
"cogentcore.org/core/text/parse/lexer"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/search"
"cogentcore.org/core/text/textpos"
"cogentcore.org/core/text/token"
)
// this file contains the exported API for Lines
// NewLines returns a new empty Lines, with no views.
func NewLines() *Lines {
ls := &Lines{}
ls.Defaults()
ls.setText([]byte(""))
return ls
}
// NewLinesFromBytes returns a new Lines representation of given bytes of text,
// using given filename to determine the type of content that is represented
// in the bytes, based on the filename extension, and given initial display width.
// A width-specific view is created, with the unique view id returned: this id
// must be used for all subsequent view-specific calls.
// This uses all default styling settings.
func NewLinesFromBytes(filename string, width int, src []byte) (*Lines, int) {
ls := &Lines{}
ls.Defaults()
fi, _ := fileinfo.NewFileInfo(filename)
ls.setFileInfo(fi)
_, vid := ls.newView(width)
ls.setText(src)
return ls, vid
}
func (ls *Lines) Defaults() {
ls.Settings.Defaults()
ls.fontStyle = rich.NewStyle().SetFamily(rich.Monospace)
ls.links = make(map[int][]rich.Hyperlink)
}
// NewView makes a new view with given initial width,
// with a layout of the existing text at this width.
// The return value is a unique int handle that must be
// used for all subsequent calls that depend on the view.
func (ls *Lines) NewView(width int) int {
ls.Lock()
defer ls.Unlock()
_, vid := ls.newView(width)
return vid
}
// DeleteView deletes view for given unique view id.
// It is important to delete unused views to maintain efficient updating of
// existing views.
func (ls *Lines) DeleteView(vid int) {
ls.Lock()
defer ls.Unlock()
ls.deleteView(vid)
}
// SetWidth sets the width for line wrapping, for given view id.
// If the width is different than current, the layout is updated,
// and a true is returned, else false.
func (ls *Lines) SetWidth(vid int, wd int) bool {
ls.Lock()
defer ls.Unlock()
vw := ls.view(vid)
if vw != nil {
if vw.width == wd || wd == 0 {
return false
}
vw.width = wd
ls.layoutViewLines(vw)
// fmt.Println("set width:", vw.width, "lines:", vw.viewLines, "mu:", len(vw.markup), len(vw.vlineStarts))
return true
}
return false
}
// Width returns the width for line wrapping for given view id.
func (ls *Lines) Width(vid int) int {
ls.Lock()
defer ls.Unlock()
vw := ls.view(vid)
if vw != nil {
return vw.width
}
return 0
}
// ViewLines returns the total number of line-wrapped view lines, for given view id.
func (ls *Lines) ViewLines(vid int) int {
ls.Lock()
defer ls.Unlock()
vw := ls.view(vid)
if vw != nil {
return vw.viewLines
}
return 0
}
// SetFontStyle sets the font style to use in styling and rendering text.
// The Family of the font MUST be set to Monospace.
func (ls *Lines) SetFontStyle(fs *rich.Style) *Lines {
ls.Lock()
defer ls.Unlock()
if fs.Family != rich.Monospace {
errors.Log(errors.New("lines.Lines font style MUST be Monospace. Setting that but should fix upstream"))
fs.Family = rich.Monospace
}
ls.fontStyle = fs
return ls
}
// FontStyle returns the font style used for this lines.
func (ls *Lines) FontStyle() *rich.Style {
ls.Lock()
defer ls.Unlock()
return ls.fontStyle
}
// SetText sets the text to the given bytes, and does
// full markup update and sends a Change event.
// Pass nil to initialize an empty lines.
func (ls *Lines) SetText(text []byte) *Lines {
ls.Lock()
ls.setText(text)
ls.Unlock()
ls.sendChange()
return ls
}
// SetString sets the text to the given string.
func (ls *Lines) SetString(txt string) *Lines {
return ls.SetText([]byte(txt))
}
// SetTextLines sets the source lines from given lines of bytes.
func (ls *Lines) SetTextLines(lns [][]byte) {
ls.Lock()
ls.setLineBytes(lns)
ls.Unlock()
ls.sendChange()
}
// Text returns the current text lines as a slice of bytes,
// with an additional line feed at the end, per POSIX standards.
// It does NOT call EditDone or send a Change event: that should
// happen prior or separately from this call.
func (ls *Lines) Text() []byte {
ls.Lock()
defer ls.Unlock()
return ls.bytes(0)
}
// String returns the current text as a string.
// It does NOT call EditDone or send a Change event: that should
// happen prior or separately from this call.
func (ls *Lines) String() string {
return string(ls.Text())
}
// SetHighlighting sets the highlighting style.
func (ls *Lines) SetHighlighting(style highlighting.HighlightingName) {
ls.Lock()
defer ls.Unlock()
ls.Highlighter.SetStyle(style)
}
// Close should be called when done using the Lines.
// It first sends Close events to all views.
// An Editor widget will likely want to check IsNotSaved()
// and prompt the user to save or cancel first.
func (ls *Lines) Close() {
ls.sendClose()
ls.Lock()
ls.stopDelayedReMarkup()
ls.views = make(map[int]*view)
ls.lines = nil
ls.tags = nil
ls.hiTags = nil
ls.virtual = nil
ls.markup = nil
// ls.parseState.Reset() // todo
ls.undos.Reset()
ls.markupEdits = nil
ls.posHistory = nil
ls.filename = ""
ls.notSaved = false
ls.Unlock()
}
// IsChanged reports whether any edits have been applied to text
func (ls *Lines) IsChanged() bool {
ls.Lock()
defer ls.Unlock()
return ls.changed
}
// SetChanged sets the changed flag to given value (e.g., when file saved)
func (ls *Lines) SetChanged(changed bool) {
ls.Lock()
defer ls.Unlock()
ls.changed = changed
}
// SendChange sends an [event.Change] to the views of this lines,
// causing them to update.
func (ls *Lines) SendChange() {
ls.Lock()
defer ls.Unlock()
ls.sendChange()
}
// SendInput sends an [event.Input] to the views of this lines,
// causing them to update.
func (ls *Lines) SendInput() {
ls.Lock()
defer ls.Unlock()
ls.sendInput()
}
// NumLines returns the number of lines.
func (ls *Lines) NumLines() int {
ls.Lock()
defer ls.Unlock()
return ls.numLines()
}
// IsValidLine returns true if given line number is in range.
func (ls *Lines) IsValidLine(ln int) bool {
if ln < 0 {
return false
}
ls.Lock()
defer ls.Unlock()
return ls.isValidLine(ln)
}
// ValidPos returns a position based on given pos that is valid.
func (ls *Lines) ValidPos(pos textpos.Pos) textpos.Pos {
ls.Lock()
defer ls.Unlock()
n := ls.numLines()
if n == 0 {
return textpos.Pos{}
}
if pos.Line < 0 {
pos.Line = 0
}
if pos.Line >= n {
pos.Line = n - 1
}
llen := len(ls.lines[pos.Line])
if pos.Char < 0 {
pos.Char = 0
}
if pos.Char > llen {
pos.Char = llen // end of line is valid
}
return pos
}
// Line returns a (copy of) specific line of runes.
func (ls *Lines) Line(ln int) []rune {
ls.Lock()
defer ls.Unlock()
if !ls.isValidLine(ln) {
return nil
}
return slices.Clone(ls.lines[ln])
}
// strings returns the current text as []string array.
// If addNewLine is true, each string line has a \n appended at end.
func (ls *Lines) Strings(addNewLine bool) []string {
ls.Lock()
defer ls.Unlock()
return ls.strings(addNewLine)
}
// LineLen returns the length of the given source line, in runes.
func (ls *Lines) LineLen(ln int) int {
ls.Lock()
defer ls.Unlock()
if !ls.isValidLine(ln) {
return 0
}
return len(ls.lines[ln])
}
// LineChar returns rune at given line and character position.
// returns a 0 if character position is not valid
func (ls *Lines) LineChar(ln, ch int) rune {
ls.Lock()
defer ls.Unlock()
if !ls.isValidLine(ln) {
return 0
}
if len(ls.lines[ln]) <= ch {
return 0
}
return ls.lines[ln][ch]
}
// HiTags returns the highlighting tags for given line, nil if invalid
func (ls *Lines) HiTags(ln int) lexer.Line {
ls.Lock()
defer ls.Unlock()
if !ls.isValidLine(ln) {
return nil
}
return ls.hiTags[ln]
}
// LineLexDepth returns the starting lexical depth in terms of brackets, parens, etc
func (ls *Lines) LineLexDepth(ln int) int {
ls.Lock()
defer ls.Unlock()
n := len(ls.hiTags)
if ln >= n || len(ls.hiTags[ln]) == 0 {
return 0
}
return ls.hiTags[ln][0].Token.Depth
}
// EndPos returns the ending position at end of lines.
func (ls *Lines) EndPos() textpos.Pos {
ls.Lock()
defer ls.Unlock()
return ls.endPos()
}
// IsValidPos returns an true if the position is valid.
func (ls *Lines) IsValidPos(pos textpos.Pos) bool {
ls.Lock()
defer ls.Unlock()
return ls.isValidPos(pos)
}
// PosToView returns the view position in terms of ViewLines and Char
// offset into that view line for given source line, char position.
func (ls *Lines) PosToView(vid int, pos textpos.Pos) textpos.Pos {
ls.Lock()
defer ls.Unlock()
vw := ls.view(vid)
if vw == nil {
return textpos.Pos{}
}
return ls.posToView(vw, pos)
}
// PosFromView returns the original source position from given
// view position in terms of ViewLines and Char offset into that view line.
// If the Char position is beyond the end of the line, it returns the
// end of the given line.
func (ls *Lines) PosFromView(vid int, pos textpos.Pos) textpos.Pos {
ls.Lock()
defer ls.Unlock()
vw := ls.view(vid)
if vw == nil {
return textpos.Pos{}
}
return ls.posFromView(vw, pos)
}
// ViewLineLen returns the length in chars (runes) of the given view line.
func (ls *Lines) ViewLineLen(vid int, vln int) int {
ls.Lock()
defer ls.Unlock()
vw := ls.view(vid)
if vw == nil {
return 0
}
return ls.viewLineLen(vw, vln)
}
// ViewCell returns the cell column of the given view position,
// where wide characters take two cells, and tabs go to tab stops
// (see [LineCells]).
func (ls *Lines) ViewCell(vid int, vpos textpos.Pos) int {
ls.Lock()
defer ls.Unlock()
vw := ls.view(vid)
if vw == nil {
return 0
}
return ls.viewCell(vw, vpos)
}
// ViewLineRegion returns the region in view coordinates of the given view line.
func (ls *Lines) ViewLineRegion(vid int, vln int) textpos.Region {
ls.Lock()
defer ls.Unlock()
vw := ls.view(vid)
if vw == nil {
return textpos.Region{}
}
return ls.viewLineRegion(vw, vln)
}
// ViewLineRegionNoLock returns the region in view coordinates of the given view line,
// for case where Lines is already locked.
func (ls *Lines) ViewLineRegionNoLock(vid int, vln int) textpos.Region {
vw := ls.view(vid)
if vw == nil {
return textpos.Region{}
}
return ls.viewLineRegion(vw, vln)
}
// RegionToView converts the given region in source coordinates into view coordinates.
func (ls *Lines) RegionToView(vid int, reg textpos.Region) textpos.Region {
ls.Lock()
defer ls.Unlock()
vw := ls.view(vid)
if vw == nil {
return textpos.Region{}
}
return ls.regionToView(vw, reg)
}
// RegionFromView converts the given region in view coordinates into source coordinates.
func (ls *Lines) RegionFromView(vid int, reg textpos.Region) textpos.Region {
ls.Lock()
defer ls.Unlock()
vw := ls.view(vid)
if vw == nil {
return textpos.Region{}
}
return ls.regionFromView(vw, reg)
}
// Region returns a Edit representation of text between start and end positions.
// returns nil if not a valid region. sets the timestamp on the Edit to now.
func (ls *Lines) Region(st, ed textpos.Pos) *textpos.Edit {
ls.Lock()
defer ls.Unlock()
return ls.region(st, ed)
}
// RegionRect returns a Edit representation of text between
// start and end positions as a rectangle,
// returns nil if not a valid region. sets the timestamp on the Edit to now.
func (ls *Lines) RegionRect(st, ed textpos.Pos) *textpos.Edit {
ls.Lock()
defer ls.Unlock()
return ls.regionRect(st, ed)
}
// AdjustRegion adjusts given text region for any edits that
// have taken place since time stamp on region (using the Undo stack).
// If region was wholly within a deleted region, then RegionNil will be
// returned, otherwise it is clipped appropriately as function of deletes.
func (ls *Lines) AdjustRegion(reg textpos.Region) textpos.Region {
ls.Lock()
defer ls.Unlock()
return ls.undos.AdjustRegion(reg)
}
//////// Edits
// DeleteText is the primary method for deleting text from the lines.
// It deletes region of text between start and end positions.
// Sets the timestamp on resulting Edit to now.
// An Undo record is automatically saved depending on Undo.Off setting.
// Calls sendInput to send an Input event to views, so they update.
func (ls *Lines) DeleteText(st, ed textpos.Pos) *textpos.Edit {
ls.Lock()
ls.fileModCheck()
// positions can be off based on lock acquisition dynamics
st, _ = ls.validCharPos(st)
ed, _ = ls.validCharPos(ed)
tbe := ls.deleteText(st, ed)
if tbe != nil && ls.Autosave {
ls.autoSaves.Go(func() { ls.autoSave() })
}
ls.Unlock()
ls.sendInput()
return tbe
}
// DeleteTextRect deletes rectangular region of text between start, end
// defining the upper-left and lower-right corners of a rectangle.
// Fails if st.Char >= ed.Char. Sets the timestamp on resulting Edit to now.
// An Undo record is automatically saved depending on Undo.Off setting.
// Calls sendInput to send an Input event to views, so they update.
func (ls *Lines) DeleteTextRect(st, ed textpos.Pos) *textpos.Edit {
ls.Lock()
ls.fileModCheck()
// positions can be off based on lock acquisition dynamics
st, _ = ls.validCharPos(st)
ed, _ = ls.validCharPos(ed)
tbe := ls.deleteTextRect(st, ed)
if tbe != nil && ls.Autosave {
ls.autoSaves.Go(func() { ls.autoSave() })
}
ls.Unlock()
ls.sendInput()
return tbe
}
// InsertTextBytes is the primary method for inserting text,
// at given starting position. Sets the timestamp on resulting Edit to now.
// An Undo record is automatically saved depending on Undo.Off setting.
// Calls sendInput to send an Input event to views, so they update.
func (ls *Lines) InsertTextBytes(st textpos.Pos, text []byte) *textpos.Edit {
ls.Lock()
ls.fileModCheck()
// positions can be off based on lock acquisition dynamics
st, _ = ls.validCharPos(st)
tbe := ls.insertText(st, []rune(string(text)))
if tbe != nil && ls.Autosave {
ls.autoSaves.Go(func() { ls.autoSave() })
}
ls.Unlock()
ls.sendInput()
return tbe
}
// InsertText is the primary method for inserting text,
// at given starting position. Sets the timestamp on resulting Edit to now.
// An Undo record is automatically saved depending on Undo.Off setting.
// Calls sendInput to send an Input event to views, so they update.
func (ls *Lines) InsertText(st textpos.Pos, text []rune) *textpos.Edit {
ls.Lock()
ls.fileModCheck()
// positions can be off based on lock acquisition dynamics
st, _ = ls.validCharPos(st)
tbe := ls.insertText(st, text)
if tbe != nil && ls.Autosave {
ls.autoSaves.Go(func() { ls.autoSave() })
}
ls.Unlock()
ls.sendInput()
return tbe
}
// InsertTextLines is the primary method for inserting text,
// at given starting position. Sets the timestamp on resulting Edit to now.
// An Undo record is automatically saved depending on Undo.Off setting.
// Calls sendInput to send an Input event to views, so they update.
func (ls *Lines) InsertTextLines(st textpos.Pos, text [][]rune) *textpos.Edit {
ls.Lock()
ls.fileModCheck()
// positions can be off based on lock acquisition dynamics
st, _ = ls.validCharPos(st)
tbe := ls.insertTextLines(st, text)
if tbe != nil && ls.Autosave {
ls.autoSaves.Go(func() { ls.autoSave() })
}
ls.Unlock()
ls.sendInput()
return tbe
}
// InsertTextRect inserts a rectangle of text defined in given Edit record,
// (e.g., from RegionRect or DeleteRect).
// Returns a copy of the Edit record with an updated timestamp.
// An Undo record is automatically saved depending on Undo.Off setting.
// Calls sendInput to send an Input event to views, so they update.
func (ls *Lines) InsertTextRect(tbe *textpos.Edit) *textpos.Edit {
ls.Lock()
ls.fileModCheck()
tbe = ls.insertTextRect(tbe)
if tbe != nil && ls.Autosave {
ls.autoSaves.Go(func() { ls.autoSave() })
}
ls.Unlock()
ls.sendInput()
return tbe
}
// ReplaceText does DeleteText for given region, and then InsertText at given position
// (typically same as delSt but not necessarily).
// if matchCase is true, then the lexer.MatchCase function is called to match the
// case (upper / lower) of the new inserted text to that of the text being replaced.
// returns the Edit for the inserted text.
// An Undo record is automatically saved depending on Undo.Off setting.
// Calls sendInput to send an Input event to views, so they update.
func (ls *Lines) ReplaceText(delSt, delEd, insPos textpos.Pos, insTxt string, matchCase MatchCase) *textpos.Edit {
ls.Lock()
ls.fileModCheck()
tbe := ls.replaceText(delSt, delEd, insPos, insTxt, matchCase)
if tbe != nil && ls.Autosave {
ls.autoSaves.Go(func() { ls.autoSave() })
}
ls.Unlock()
ls.sendInput()
return tbe
}
// Replacement is a replacement of the text in Region by Text,
// for [Lines.ReplaceTexts].
type Replacement struct {
Region textpos.Region
Text string
}
// ReplaceTexts does [Lines.ReplaceText] for each of the given
// replacements, in order, as one batch update: they are one undo group,
// with one autosave and one Input event at the end. Each replacement
// applies to the text as changed by the prior ones, so multiple edits
// computed for the same text, e.g., from a language server, are given
// in reverse position order. Returns the number of replacements that
// changed the text.
func (ls *Lines) ReplaceTexts(reps []Replacement, matchCase MatchCase) int {
ls.Lock()
ls.fileModCheck()
autoSave := ls.batchUpdateStart()
n := 0
for _, r := range reps {
if ls.replaceText(r.Region.Start, r.Region.End, r.Region.Start, r.Text, matchCase) != nil {
n++
}
}
ls.batchUpdateEnd(autoSave)
if n > 0 && ls.Autosave {
ls.autoSaves.Go(func() { ls.autoSave() })
}
ls.Unlock()
ls.sendInput()
return n
}
// ReplaceLinesMarkup replaces the lines from start up to end (exclusive)
// with the given lines of text and their markup, for preformatted text
// that is updated in place, such as a terminal. An end < 0 replaces
// through the last line. It does not record undo, does not affect the
// changed state, and does not send any events: the caller updates its
// views as needed. The view layout is only redone from the start line,
// so replacing the final lines of a long text is fast. The text and
// markup slices are used directly, not copied. The markup must not be
// changed by syntax highlighting, so the Lines should not have a language.
func (ls *Lines) ReplaceLinesMarkup(start, end int, text [][]rune, markup []rich.Text) {
ls.Lock()
defer ls.Unlock()
ls.replaceLinesMarkup(start, end, text, markup)
}
// AppendTextMarkup appends new text to end of lines, using insert, returns
// edit, and uses supplied markup to render it, for preformatted output.
// Calls sendInput to send an Input event to views, so they update.
func (ls *Lines) AppendTextMarkup(text [][]rune, markup []rich.Text) *textpos.Edit {
tbe := ls.appendTextMarkupLocked(text, markup)
ls.sendInput()
return tbe
}
// AppendTextMarkupAsync is [Lines.AppendTextMarkup] for a background
// goroutine, such as that of [textcore.OutputBuffer]: the Input event is
// sent to the listeners of each view with its [Lines.SetAsyncRunner]
// function, which gets the lock that they need. It must not be called
// with that lock held.
func (ls *Lines) AppendTextMarkupAsync(text [][]rune, markup []rich.Text) *textpos.Edit {
tbe := ls.appendTextMarkupLocked(text, markup)
ls.sendInputAsync()
return tbe
}
// appendTextMarkupLocked does [Lines.AppendTextMarkup] under the mutex lock,
// without sending the Input event.
func (ls *Lines) appendTextMarkupLocked(text [][]rune, markup []rich.Text) *textpos.Edit {
ls.Lock()
defer ls.Unlock()
ls.fileModCheck()
tbe := ls.appendTextMarkup(text, markup)
if tbe != nil && ls.Autosave {
ls.autoSaves.Go(func() { ls.autoSave() })
}
ls.collectLinks()
ls.layoutViews()
return tbe
}
// ReMarkup starts a background task of redoing the markup
func (ls *Lines) ReMarkup() {
ls.Lock()
defer ls.Unlock()
ls.reMarkup()
}
// SetUndoOn turns on or off the recording of undo records for every edit.
func (ls *Lines) SetUndoOn(on bool) {
ls.Lock()
defer ls.Unlock()
ls.undos.Off = !on
}
// NewUndoGroup increments the undo group counter for batchiung
// the subsequent actions.
func (ls *Lines) NewUndoGroup() {
ls.Lock()
defer ls.Unlock()
ls.undos.NewGroup()
}
// UndoReset resets all current undo records.
func (ls *Lines) UndoReset() {
ls.Lock()
defer ls.Unlock()
ls.undos.Reset()
}
// Undo undoes next group of items on the undo stack,
// and returns all the edits performed.
// Calls sendInput to send an Input event to views, so they update.
func (ls *Lines) Undo() []*textpos.Edit {
ls.Lock()
autoSave := ls.batchUpdateStart()
tbe := ls.undo()
ls.updateSaved()
ls.batchUpdateEnd(autoSave)
ls.Unlock()
ls.sendInput()
return tbe
}
// Redo redoes next group of items on the undo stack,
// and returns all the edits performed.
// Calls sendInput to send an Input event to views, so they update.
func (ls *Lines) Redo() []*textpos.Edit {
ls.Lock()
autoSave := ls.batchUpdateStart()
tbe := ls.redo()
ls.updateSaved()
ls.batchUpdateEnd(autoSave)
ls.Unlock()
ls.sendInput()
return tbe
}
// EmacsUndoSave is called by an editor at end of latest set of undo commands.
// If EmacsUndo mode is active, saves the current UndoStack to the regular Undo stack
// at the end, and moves undo to the very end; undo is a constant stream.
func (ls *Lines) EmacsUndoSave() {
ls.Lock()
defer ls.Unlock()
if !ls.Settings.EmacsUndo {
return
}
ls.undos.UndoStackSave()
}
///////// Moving
// MoveForward moves given source position forward given number of rune steps.
func (ls *Lines) MoveForward(pos textpos.Pos, steps int) textpos.Pos {
ls.Lock()
defer ls.Unlock()
return ls.moveForward(pos, steps)
}
// MoveBackward moves given source position backward given number of rune steps.
func (ls *Lines) MoveBackward(pos textpos.Pos, steps int) textpos.Pos {
ls.Lock()
defer ls.Unlock()
return ls.moveBackward(pos, steps)
}
// MoveForwardWord moves given source position forward given number of word steps.
func (ls *Lines) MoveForwardWord(pos textpos.Pos, steps int) textpos.Pos {
ls.Lock()
defer ls.Unlock()
return ls.moveForwardWord(pos, steps)
}
// MoveBackwardWord moves given source position backward given number of word steps.
func (ls *Lines) MoveBackwardWord(pos textpos.Pos, steps int) textpos.Pos {
ls.Lock()
defer ls.Unlock()
return ls.moveBackwardWord(pos, steps)
}
// MoveDown moves given source position down given number of display line steps,
// always attempting to use the given column position if the line is long enough.
// The column is in cells (see [Lines.ViewCell]).
func (ls *Lines) MoveDown(vid int, pos textpos.Pos, steps, col int) textpos.Pos {
ls.Lock()
defer ls.Unlock()
vw := ls.view(vid)
if vw == nil {
return textpos.Pos{}
}
return ls.moveDown(vw, pos, steps, col)
}
// MoveUp moves given source position up given number of display line steps,
// always attempting to use the given column position if the line is long enough.
// The column is in cells (see [Lines.ViewCell]).
func (ls *Lines) MoveUp(vid int, pos textpos.Pos, steps, col int) textpos.Pos {
ls.Lock()
defer ls.Unlock()
vw := ls.view(vid)
if vw == nil {
return textpos.Pos{}
}
return ls.moveUp(vw, pos, steps, col)
}
// MoveLineStart moves given source position to start of view line.
func (ls *Lines) MoveLineStart(vid int, pos textpos.Pos) textpos.Pos {
ls.Lock()
defer ls.Unlock()
vw := ls.view(vid)
if vw == nil {
return textpos.Pos{}
}
return ls.moveLineStart(vw, pos)
}
// MoveLineEnd moves given source position to end of view line.
func (ls *Lines) MoveLineEnd(vid int, pos textpos.Pos) textpos.Pos {
ls.Lock()
defer ls.Unlock()
vw := ls.view(vid)
if vw == nil {
return textpos.Pos{}
}
return ls.moveLineEnd(vw, pos)
}
// TransposeChar swaps the character at the cursor with the one before it.
func (ls *Lines) TransposeChar(vid int, pos textpos.Pos) bool {
ls.Lock()
defer ls.Unlock()
vw := ls.view(vid)
if vw == nil {
return false
}
return ls.transposeChar(vw, pos)
}
// TransposeWord swaps the word at or before the given position with the
// next word on its line, or with the word before it if it is the last
// word of the line, as in "one tw|o three" to "one three two|". It returns
// the position after the moved words, and false if there are not two
// words to swap.
func (ls *Lines) TransposeWord(pos textpos.Pos) (textpos.Pos, bool) {
ls.Lock()
defer ls.Unlock()
return ls.transposeWord(pos)
}
//////// Words
// IsWordEnd returns true if the cursor is just past the last letter of a word.
func (ls *Lines) IsWordEnd(pos textpos.Pos) bool {
ls.Lock()
defer ls.Unlock()
if !ls.isValidPos(pos) {
return false
}
txt := ls.lines[pos.Line]
sz := len(txt)
if sz == 0 {
return false
}
if pos.Char >= len(txt) { // end of line: after its last letter
r := txt[len(txt)-1]
return !textpos.IsWordBreak(r, -1)
}
if pos.Char == 0 { // start of line: not after any letter
return false
}
r1 := txt[pos.Char-1]
r2 := txt[pos.Char]
return !textpos.IsWordBreak(r1, rune(-1)) && textpos.IsWordBreak(r2, rune(-1))
}
// IsWordMiddle returns true if the cursor is anywhere inside a word,
// i.e. the character before the cursor and the one after the cursor
// are not classified as word break characters
func (ls *Lines) IsWordMiddle(pos textpos.Pos) bool {
ls.Lock()
defer ls.Unlock()
if !ls.isValidPos(pos) {
return false
}
txt := ls.lines[pos.Line]
sz := len(txt)
if sz < 2 {
return false
}
if pos.Char >= len(txt) { // end of line
return false
}
if pos.Char == 0 { // start of line
return false
}
r1 := txt[pos.Char-1]
r2 := txt[pos.Char]
return !textpos.IsWordBreak(r1, rune(-1)) && !textpos.IsWordBreak(r2, rune(-1))
}
// WordAt returns a Region for a word starting at given position.
// If the current position is a word break then go to next
// break after the first non-break.
func (ls *Lines) WordAt(pos textpos.Pos) textpos.Region {
ls.Lock()
defer ls.Unlock()
if !ls.isValidPos(pos) {
return textpos.Region{}
}
txt := ls.lines[pos.Line]
rng := textpos.WordAt(txt, pos.Char)
st := pos
st.Char = rng.Start
ed := pos
ed.Char = rng.End
return textpos.NewRegionPos(st, ed)
}
// WordBefore returns the word before the given source position.
// uses IsWordBreak to determine the bounds of the word
func (ls *Lines) WordBefore(pos textpos.Pos) *textpos.Edit {
ls.Lock()
defer ls.Unlock()
if !ls.isValidPos(pos) {
return &textpos.Edit{}
}
txt := ls.lines[pos.Line]
ch := pos.Char
ch = min(ch, len(txt))
st := ch
for i := ch - 1; i >= 0; i-- {
if i == 0 { // start of line
st = 0
break
}
r1 := txt[i]
r2 := txt[i-1]
if textpos.IsWordBreak(r1, r2) {
st = i + 1
break
}
}
if st != ch {
return ls.region(textpos.Pos{Line: pos.Line, Char: st}, pos)
}
return nil
}
//////// PosHistory
// PosHistorySave saves the cursor position in history stack of cursor positions.
// Tracks across views. Returns false if position was on same line as last one saved.
func (ls *Lines) PosHistorySave(pos textpos.Pos) bool {
ls.Lock()
defer ls.Unlock()
if ls.posHistory == nil {
ls.posHistory = make([]textpos.Pos, 0, 1000)
}
sz := len(ls.posHistory)
if sz > 0 {
if ls.posHistory[sz-1].Line == pos.Line {
return false
}
}
ls.posHistory = append(ls.posHistory, pos)
// fmt.Printf("saved pos hist: %v\n", pos)
return true
}
// PosHistoryLen returns the length of the position history stack.
func (ls *Lines) PosHistoryLen() int {
ls.Lock()
defer ls.Unlock()
return len(ls.posHistory)
}
// PosHistoryAt returns the position history at given index.
// returns false if not a valid index.
func (ls *Lines) PosHistoryAt(idx int) (textpos.Pos, bool) {
ls.Lock()
defer ls.Unlock()
if idx < 0 || idx >= len(ls.posHistory) {
return textpos.Pos{}, false
}
return ls.posHistory[idx], true
}
///////// Edit helpers
// InComment returns true if the given text position is within
// a commented region.
func (ls *Lines) InComment(pos textpos.Pos) bool {
ls.Lock()
defer ls.Unlock()
return ls.inComment(pos)
}
// HiTagAtPos returns the highlighting (markup) lexical tag at given position
// using current Markup tags, and index, -- could be nil if none or out of range.
func (ls *Lines) HiTagAtPos(pos textpos.Pos) (*lexer.Lex, int) {
ls.Lock()
defer ls.Unlock()
return ls.hiTagAtPos(pos)
}
// InTokenSubCat returns true if the given text position is marked with lexical
// type in given SubCat sub-category.
func (ls *Lines) InTokenSubCat(pos textpos.Pos, subCat token.Tokens) bool {
ls.Lock()
defer ls.Unlock()
return ls.inTokenSubCat(pos, subCat)
}
// InLitString returns true if position is in a string literal.
func (ls *Lines) InLitString(pos textpos.Pos) bool {
ls.Lock()
defer ls.Unlock()
return ls.inLitString(pos)
}
// InTokenCode returns true if position is in a Keyword,
// Name, Operator, or Punctuation.
// This is useful for turning off spell checking in docs
func (ls *Lines) InTokenCode(pos textpos.Pos) bool {
ls.Lock()
defer ls.Unlock()
return ls.inTokenCode(pos)
}
// LexObjPathString returns the string at given lex, and including prior
// lex-tagged regions that include sequences of PunctSepPeriod and NameTag
// which are used for object paths -- used for e.g., debugger to pull out
// variable expressions that can be evaluated.
func (ls *Lines) LexObjPathString(ln int, lx *lexer.Lex) string {
ls.Lock()
defer ls.Unlock()
return ls.lexObjPathString(ln, lx)
}
//////// Tags
// AddTag adds a new custom tag for given line, at given position.
func (ls *Lines) AddTag(ln, st, ed int, tag token.Tokens) {
ls.Lock()
defer ls.Unlock()
if !ls.isValidLine(ln) {
return
}
tr := lexer.NewLex(token.KeyToken{Token: tag}, st, ed)
tr.Time.Now()
if len(ls.tags[ln]) == 0 {
ls.tags[ln] = append(ls.tags[ln], tr)
} else {
ls.tags[ln] = ls.adjustedTags(ln) // must re-adjust before adding new ones!
ls.tags[ln].AddSort(tr)
}
ls.markupLines(ln, ln)
}
// AddTagEdit adds a new custom tag for given line, using Edit for location.
func (ls *Lines) AddTagEdit(tbe *textpos.Edit, tag token.Tokens) {
ls.AddTag(tbe.Region.Start.Line, tbe.Region.Start.Char, tbe.Region.End.Char, tag)
}
// RemoveTag removes tag (optionally only given tag if non-zero)
// at given position if it exists. returns tag.
func (ls *Lines) RemoveTag(pos textpos.Pos, tag token.Tokens) (reg lexer.Lex, ok bool) {
ls.Lock()
defer ls.Unlock()
if !ls.isValidLine(pos.Line) {
return
}
ls.tags[pos.Line] = ls.adjustedTags(pos.Line) // re-adjust for current info
for i, t := range ls.tags[pos.Line] {
if t.ContainsPos(pos.Char) {
if tag > 0 && t.Token.Token != tag {
continue
}
ls.tags[pos.Line].DeleteIndex(i)
reg = t
ok = true
break
}
}
if ok {
ls.markupLines(pos.Line, pos.Line)
}
return
}
// SetTags tags for given line.
func (ls *Lines) SetTags(ln int, tags lexer.Line) {
ls.Lock()
defer ls.Unlock()
if !ls.isValidLine(ln) {
return
}
ls.tags[ln] = tags
}
// AdjustedTags updates tag positions for edits, for given line
// and returns the new tags
func (ls *Lines) AdjustedTags(ln int) lexer.Line {
ls.Lock()
defer ls.Unlock()
return ls.adjustedTags(ln)
}
// AdjustedTagsLine updates tag positions for edits, for given list of tags,
// associated with given line of text.
func (ls *Lines) AdjustedTagsLine(tags lexer.Line, ln int) lexer.Line {
ls.Lock()
defer ls.Unlock()
return ls.adjustedTagsLine(tags, ln)
}
// MarkupLines generates markup of given range of lines.
// end is *inclusive* line. Called after edits, under Lock().
// returns true if all lines were marked up successfully.
func (ls *Lines) MarkupLines(st, ed int) bool {
ls.Lock()
defer ls.Unlock()
return ls.markupLines(st, ed)
}
// StartDelayedReMarkup starts a timer for doing markup after an interval.
func (ls *Lines) StartDelayedReMarkup() {
ls.Lock()
defer ls.Unlock()
ls.startDelayedReMarkup()
}
// StopDelayedReMarkup stops the timer for doing markup after an interval.
func (ls *Lines) StopDelayedReMarkup() {
ls.Lock()
defer ls.Unlock()
ls.stopDelayedReMarkup()
}
//////// Misc edit functions
// IndentLine indents line by given number of tab stops, using tabs or spaces,
// for given tab size (if using spaces). Either inserts or deletes to reach target.
// Returns edit record for any change.
// Calls sendInput to send an Input event to views, so they update.
func (ls *Lines) IndentLine(ln, ind int) *textpos.Edit {
ls.Lock()
autoSave := ls.batchUpdateStart()
tbe := ls.indentLine(ln, ind)
ls.batchUpdateEnd(autoSave)
ls.Unlock()
ls.sendInput()
return tbe
}
// AutoIndent indents given line to the level of the prior line, adjusted
// appropriately if the current line starts with one of the given un-indent
// strings, or the prior line ends with one of the given indent strings.
// Returns any edit that took place (could be nil), along with the auto-indented
// level and character position for the indent of the current line.
// Calls sendInput to send an Input event to views, so they update.
func (ls *Lines) AutoIndent(ln int) (tbe *textpos.Edit, indLev, chPos int) {
ls.Lock()
autoSave := ls.batchUpdateStart()
tbe, indLev, chPos = ls.autoIndent(ln)
ls.batchUpdateEnd(autoSave)
ls.Unlock()
ls.sendInput()
return
}
// AutoIndentRegion does auto-indent over given region; end is *exclusive*.
// Calls sendInput to send an Input event to views, so they update.
func (ls *Lines) AutoIndentRegion(start, end int) {
ls.Lock()
autoSave := ls.batchUpdateStart()
ls.autoIndentRegion(start, end)
ls.batchUpdateEnd(autoSave)
ls.Unlock()
ls.sendInput()
}
// CommentRegion inserts comment marker on given lines; end is *exclusive*.
// Calls sendInput to send an Input event to views, so they update.
func (ls *Lines) CommentRegion(start, end int) {
ls.Lock()
autoSave := ls.batchUpdateStart()
ls.commentRegion(start, end)
ls.batchUpdateEnd(autoSave)
ls.Unlock()
ls.sendInput()
}
// JoinParaLines merges sequences of lines with hard returns forming paragraphs,
// separated by blank lines, into a single line per paragraph,
// within the given line regions; endLine is *inclusive*.
// Calls sendInput to send an Input event to views, so they update.
func (ls *Lines) JoinParaLines(startLine, endLine int) {
ls.Lock()
autoSave := ls.batchUpdateStart()
ls.joinParaLines(startLine, endLine)
ls.batchUpdateEnd(autoSave)
ls.Unlock()
ls.sendInput()
}
// TabsToSpaces replaces tabs with spaces over given region; end is *exclusive*.
// Calls sendInput to send an Input event to views, so they update.
func (ls *Lines) TabsToSpaces(start, end int) {
ls.Lock()
autoSave := ls.batchUpdateStart()
ls.tabsToSpaces(start, end)
ls.batchUpdateEnd(autoSave)
ls.Unlock()
ls.sendInput()
}
// SpacesToTabs replaces tabs with spaces over given region; end is *exclusive*
// Calls sendInput to send an Input event to views, so they update.
func (ls *Lines) SpacesToTabs(start, end int) {
ls.Lock()
autoSave := ls.batchUpdateStart()
ls.spacesToTabs(start, end)
ls.batchUpdateEnd(autoSave)
ls.Unlock()
ls.sendInput()
}
// CountWordsLinesRegion returns the count of words and lines in given region.
func (ls *Lines) CountWordsLinesRegion(reg textpos.Region) (words, lines int) {
ls.Lock()
defer ls.Unlock()
words, lines = CountWordsLinesRegion(ls.lines, reg)
return
}
// Diffs computes the diff between this lines and the other lines,
// reporting a sequence of operations that would convert this lines (a) into
// the other lines (b). Each operation is either an 'r' (replace), 'd'
// (delete), 'i' (insert) or 'e' (equal). Everything is line-based (0, offset).
func (ls *Lines) Diffs(ob *Lines) Diffs {
ls.Lock()
defer ls.Unlock()
return ls.diffs(ob)
}
// PatchFrom patches (edits) using content from other,
// according to diff operations (e.g., as generated from Diffs).
func (ls *Lines) PatchFrom(ob *Lines, diffs Diffs) bool {
ls.Lock()
defer ls.Unlock()
return ls.patchFrom(ob, diffs)
}
// DiffsUnified computes the diff between this lines and the other lines,
// returning a unified diff with given amount of context (default of 3 will be
// used if -1)
func (ls *Lines) DiffsUnified(ob *Lines, context int) []byte {
astr := ls.Strings(true) // needs newlines for some reason
bstr := ob.Strings(true)
return DiffLinesUnified(astr, bstr, context, ls.Filename(), ls.FileInfo().ModTime.String(),
ob.Filename(), ob.FileInfo().ModTime.String())
}
//////// Search etc
// Search looks for a string (no regexp) within buffer,
// with given case-sensitivity, returning number of occurrences
// and specific match position list. Column positions are in runes.
func (ls *Lines) Search(find []byte, useCase textpos.CaseSensitive, lexItems textpos.MatchScope) (int, []textpos.Match) {
ls.Lock()
defer ls.Unlock()
if lexItems {
return search.LexItems(ls.lines, ls.hiTags, find, useCase)
}
return search.RuneLines(ls.lines, find, useCase)
}
// SearchRegexp looks for a string (regexp) within buffer,
// returning number of occurrences and specific match position list.
// Column positions are in runes.
func (ls *Lines) SearchRegexp(re *regexp.Regexp) (int, []textpos.Match) {
ls.Lock()
defer ls.Unlock()
return search.RuneLinesRegexp(ls.lines, re)
}
// BraceMatch finds the brace, bracket, or parens that is the partner
// of the one at the given position, if there is one of those at this position.
func (ls *Lines) BraceMatch(pos textpos.Pos) (textpos.Pos, bool) {
ls.Lock()
defer ls.Unlock()
return ls.braceMatch(pos)
}
// BraceMatchRune finds the brace, bracket, or parens that is the partner
// of the given rune, starting at given position.
func (ls *Lines) BraceMatchRune(r rune, pos textpos.Pos) (textpos.Pos, bool) {
ls.Lock()
defer ls.Unlock()
return lexer.BraceMatch(ls.lines, ls.hiTags, r, pos, maxScopeLines)
}
// LinkAt returns a hyperlink at given source position, if one exists,
// nil otherwise. this is fast so no problem to call frequently.
func (ls *Lines) LinkAt(pos textpos.Pos) *rich.Hyperlink {
ls.Lock()
defer ls.Unlock()
return ls.linkAt(pos)
}
// NextLink returns the next hyperlink after given source position,
// if one exists, and the line it is on. nil, -1 otherwise.
func (ls *Lines) NextLink(pos textpos.Pos) (*rich.Hyperlink, int) {
ls.Lock()
defer ls.Unlock()
return ls.nextLink(pos)
}
// PrevLink returns the previous hyperlink before given source position,
// if one exists, and the line it is on. nil, -1 otherwise.
func (ls *Lines) PrevLink(pos textpos.Pos) (*rich.Hyperlink, int) {
ls.Lock()
defer ls.Unlock()
return ls.prevLink(pos)
}
// Links returns the full list of hyperlinks
func (ls *Lines) Links() map[int][]rich.Hyperlink {
ls.Lock()
defer ls.Unlock()
return ls.links
}
//////// LineColors
// SetLineColor sets the color to use for rendering a circle next to the line
// number at the given line.
func (ls *Lines) SetLineColor(ln int, color image.Image) {
ls.Lock()
defer ls.Unlock()
if ls.lineColors == nil {
ls.lineColors = make(map[int]image.Image)
}
ls.lineColors[ln] = color
}
// LineColor returns the line color for given line, and bool indicating if set.
func (ls *Lines) LineColor(ln int) (image.Image, bool) {
ls.Lock()
defer ls.Unlock()
if ln < 0 {
return nil, false
}
if ls.lineColors == nil {
return nil, false
}
clr, has := ls.lineColors[ln]
return clr, has
}
// DeleteLineColor deletes the line color at the given line.
// Passing a -1 clears all current line colors.
func (ls *Lines) DeleteLineColor(ln int) {
ls.Lock()
defer ls.Unlock()
if ln < 0 {
ls.lineColors = nil
return
}
if ls.lineColors == nil {
return
}
delete(ls.lineColors, ln)
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lines
import (
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/textpos"
"github.com/clipperhouse/displaywidth"
)
// Lines are displayed in a grid of monospaced cells, where most
// characters take one cell, and wide characters, such as CJK
// characters, take two cells, as in a terminal. A view line is
// wrapped at its width in cells, and the cursor column used in
// moving up and down is in cells, so that it stays in the same
// visual column across lines with wide characters. Positions in the
// text are still in characters (runes): cells only affect the display.
// RuneWidth returns the number of cells used to display the given rune:
// 2 for wide characters (East Asian Wide and Fullwidth characters, and
// emoji), and 1 otherwise, including zero width characters. Tabs are
// handled separately, by [LineCells].
func RuneWidth(r rune) int {
if r < 0x1100 { // no wide characters before the Hangul Jamo
return 1
}
if displaywidth.Rune(r) == 2 {
return 2
}
return 1
}
// textCells returns the total width in cells of the given text,
// which has no tabs.
func textCells(txt []rune) int {
n := 0
for _, r := range txt {
n += RuneWidth(r)
}
return n
}
// LineCells returns the cell column at the start of each character
// in the given view line markup, as returned by [Lines.ViewMarkupLine],
// followed by the column at its end. The tabs at the start of the line,
// each of which is in its own span, take tabSize cells, other tabs
// go to the next multiple of 8 cells, and wide characters take 2 cells
// (see [RuneWidth]).
func LineCells(tx rich.Text, tabSize int) []int {
cells := make([]int, 0, tx.Len()+1)
cc := 0
start := true
for si := range tx {
sn, rn := rich.SpanLen(tx[si])
if rn == 0 {
continue
}
rs := tx[si][sn:]
if start && rn == 1 && rs[0] == '\t' {
cells = append(cells, cc)
cc += tabSize
continue
}
start = false
for _, r := range rs {
cells = append(cells, cc)
if r == '\t' {
cc = ((cc / 8) + 1) * 8
} else {
cc += RuneWidth(r)
}
}
}
return append(cells, cc)
}
// cellChar returns the character index in the line with the given
// cells (see [LineCells]) that is closest to the given cell column:
// a column in the second half of a wide character is after it.
func cellChar(cells []int, col int) int {
n := len(cells) - 1
for i := range n {
if 2*col < cells[i]+cells[i+1] {
return i
}
}
return n
}
// viewLineCells returns the [LineCells] of the given view line.
func (ls *Lines) viewLineCells(vw *view, vl int) []int {
if vl < 0 || vl >= len(vw.markup) {
return []int{0}
}
return LineCells(vw.markup[vl], ls.Settings.TabSize)
}
// viewCell returns the cell column of the given view position.
// Positions beyond the end of the line are one cell per character.
func (ls *Lines) viewCell(vw *view, vpos textpos.Pos) int {
cells := ls.viewLineCells(vw, vpos.Line)
n := len(cells) - 1
if vpos.Char <= n {
return cells[max(vpos.Char, 0)]
}
return cells[n] + vpos.Char - n
}
// Copyright (c) 2020, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lines
import (
"bytes"
"fmt"
"strings"
"cogentcore.org/core/text/difflib"
"cogentcore.org/core/text/textpos"
)
// note: original difflib is: "github.com/pmezard/go-difflib/difflib"
// Diffs are raw differences between text, in terms of lines, reporting a
// sequence of operations that would convert one buffer (a) into the other
// buffer (b). Each operation is either an 'r' (replace), 'd' (delete), 'i'
// (insert) or 'e' (equal).
type Diffs []difflib.OpCode
// DiffForLine returns the diff record applying to given line, and its index in slice
func (di Diffs) DiffForLine(line int) (int, difflib.OpCode) {
for i, df := range di {
if line >= df.I1 && (line < df.I2 || line < df.J2) {
return i, df
}
}
return -1, difflib.OpCode{}
}
func DiffOpReverse(op difflib.OpCode) difflib.OpCode {
op.J1, op.I1 = op.I1, op.J1 // swap
op.J2, op.I2 = op.I2, op.J2 // swap
t := op.Tag
switch t {
case 'd':
op.Tag = 'i'
case 'i':
op.Tag = 'd'
}
return op
}
// Reverse returns the reverse-direction diffs, switching a vs. b
func (di Diffs) Reverse() Diffs {
rd := make(Diffs, len(di))
for i := range di {
rd[i] = DiffOpReverse(di[i])
}
return rd
}
func DiffOpString(op difflib.OpCode) string {
switch op.Tag {
case 'r':
return fmt.Sprintf("delete lines: %v - %v, insert lines: %v - %v", op.I1, op.I2, op.J1, op.J2)
case 'd':
return fmt.Sprintf("delete lines: %v - %v", op.I1, op.I2)
case 'i':
return fmt.Sprintf("insert lines at %v: %v - %v", op.I1, op.J1, op.J2)
case 'e':
return fmt.Sprintf("same lines %v - %v == %v - %v", op.I1, op.I2, op.J1, op.J2)
}
return "<bad tag>"
}
// String satisfies the Stringer interface
func (di Diffs) String() string {
var b strings.Builder
for _, df := range di {
b.WriteString(DiffOpString(df) + "\n")
}
return b.String()
}
// DiffLines computes the diff between two string arrays (one string per line),
// reporting a sequence of operations that would convert buffer a into buffer b.
// Each operation is either an 'r' (replace), 'd' (delete), 'i' (insert)
// or 'e' (equal). Everything is line-based (0, offset).
func DiffLines(astr, bstr []string) Diffs {
m := difflib.NewMatcherWithJunk(astr, bstr, false, nil) // no junk
return m.GetOpCodes()
}
// DiffLinesUnified computes the diff between two string arrays (one string per line),
// returning a unified diff with given amount of context (default of 3 will be
// used if -1), with given file names and modification dates.
func DiffLinesUnified(astr, bstr []string, context int, afile, adate, bfile, bdate string) []byte {
ud := difflib.UnifiedDiff{A: astr, FromFile: afile, FromDate: adate,
B: bstr, ToFile: bfile, ToDate: bdate, Context: context}
var buf bytes.Buffer
difflib.WriteUnifiedDiff(&buf, ud)
return buf.Bytes()
}
// PatchRec is a self-contained record of a DiffLines result that contains
// the source lines of the b buffer needed to patch a into b
type PatchRec struct {
// diff operation: 'r', 'd', 'i', 'e'
Op difflib.OpCode
// lines from B buffer needed for 'r' and 'i' operations
Blines []string
}
// Patch is a collection of patch records needed to turn original a buffer into b
type Patch []*PatchRec
// NumBlines returns the total number of Blines source code in the patch
func (pt Patch) NumBlines() int {
nl := 0
for _, pr := range pt {
nl += len(pr.Blines)
}
return nl
}
// ToPatch creates a Patch list from given Diffs output from DiffLines and the
// b strings from which the needed lines of source are copied.
// ApplyPatch with this on the a strings will result in the b strings.
// The resulting Patch is independent of bstr slice.
func (dif Diffs) ToPatch(bstr []string) Patch {
pt := make(Patch, len(dif))
for pi, op := range dif {
pr := &PatchRec{Op: op}
if op.Tag == 'r' || op.Tag == 'i' {
nl := (op.J2 - op.J1)
pr.Blines = make([]string, nl)
for i := range nl {
pr.Blines[i] = bstr[op.J1+i]
}
}
pt[pi] = pr
}
return pt
}
// Apply applies given Patch to given file as list of strings
// this does no checking except range checking so it won't crash
// so if input string is not appropriate for given Patch, results
// may be nonsensical.
func (pt Patch) Apply(astr []string) []string {
np := len(pt)
if np == 0 {
return astr
}
sz := len(astr)
lr := pt[np-1]
bstr := make([]string, lr.Op.J2)
for _, pr := range pt {
switch pr.Op.Tag {
case 'e':
nl := (pr.Op.J2 - pr.Op.J1)
for i := range nl {
if pr.Op.I1+i < sz {
bstr[pr.Op.J1+i] = astr[pr.Op.I1+i]
}
}
case 'r', 'i':
nl := (pr.Op.J2 - pr.Op.J1)
for i := range nl {
bstr[pr.Op.J1+i] = pr.Blines[i]
}
}
}
return bstr
}
//////// Lines api
// diffs computes the diff between this lines and the other lines,
// reporting a sequence of operations that would convert this lines (a) into
// the other lines (b). Each operation is either an 'r' (replace), 'd'
// (delete), 'i' (insert) or 'e' (equal). Everything is line-based (0, offset).
func (ls *Lines) diffs(ob *Lines) Diffs {
astr := ls.strings(false)
bstr := ob.strings(false)
return DiffLines(astr, bstr)
}
// patchFrom patches (edits) using content from other,
// according to diff operations (e.g., as generated from DiffBufs).
func (ls *Lines) patchFrom(ob *Lines, diffs Diffs) bool {
ls.undos.NewGroup()
blines := ob.strings(false)
sz := len(diffs)
mods := false
for i := sz - 1; i >= 0; i-- { // go in reverse so changes are valid!
df := diffs[i]
if df.Tag == 'e' {
continue
}
var nl [][]rune // the new lines, for a replace or insert
if df.Tag != 'd' {
for _, s := range blines[df.J1:df.J2] {
nl = append(nl, []rune(s))
}
}
n := ls.numLines()
switch {
case df.I2 < n:
// the lines and their newlines are replaced by the new lines,
// each with a newline.
if df.I2 > df.I1 {
ls.deleteText(textpos.Pos{Line: df.I1}, textpos.Pos{Line: df.I2})
}
if len(nl) > 0 {
ls.insertTextLines(textpos.Pos{Line: df.I1}, append(nl, []rune{}))
}
case df.I1 > 0:
// through the end, which has no newline: the newline before
// the lines goes with them, and comes before each new line.
prev := textpos.Pos{Line: df.I1 - 1, Char: len(ls.lines[df.I1-1])}
if df.I2 > df.I1 {
ls.deleteText(prev, ls.endPos())
}
if len(nl) > 0 {
ls.insertTextLines(ls.endPos(), append([][]rune{{}}, nl...))
}
default: // all of the text
ls.deleteText(textpos.Pos{}, ls.endPos())
if len(nl) > 0 {
ls.insertTextLines(textpos.Pos{}, nl)
}
}
mods = true
}
if mods {
ls.undos.NewGroup()
}
return mods
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lines
import (
"slices"
"cogentcore.org/core/text/difflib"
)
// DiffSelectData contains data for one set of text
type DiffSelectData struct {
// original text
Orig []string
// edits applied
Edit []string
// mapping of original line numbers (index) to edited line numbers,
// accounting for the edits applied so far
LineMap []int
// todo: in principle one should be able to reverse the edits to undo
// but the orig is different -- figure it out later..
// Undos: stack of diffs applied
Undos Diffs
// undo records
EditUndo [][]string
// undo records for ALineMap
LineMapUndo [][]int
}
// SetStringLines sets the data from given lines of strings
// The Orig is set directly and Edit is cloned
// if the input will be modified during the processing,
// call slices.Clone first
func (ds *DiffSelectData) SetStringLines(s []string) {
ds.Orig = s
ds.Edit = slices.Clone(s)
nl := len(s)
ds.LineMap = make([]int, nl)
for i := range ds.LineMap {
ds.LineMap[i] = i
}
}
func (ds *DiffSelectData) SaveUndo(op difflib.OpCode) {
ds.Undos = append(ds.Undos, op)
ds.EditUndo = append(ds.EditUndo, slices.Clone(ds.Edit))
ds.LineMapUndo = append(ds.LineMapUndo, slices.Clone(ds.LineMap))
}
func (ds *DiffSelectData) Undo() bool {
n := len(ds.LineMapUndo)
if n == 0 {
return false
}
ds.Undos = ds.Undos[:n-1]
ds.LineMap = ds.LineMapUndo[n-1]
ds.LineMapUndo = ds.LineMapUndo[:n-1]
ds.Edit = ds.EditUndo[n-1]
ds.EditUndo = ds.EditUndo[:n-1]
return true
}
// ApplyOneDiff applies given diff operator to given "B" lines
// using original "A" lines and given b line map
func ApplyOneDiff(op difflib.OpCode, bedit *[]string, aorig []string, blmap []int) {
// fmt.Println("applying:", DiffOpString(op))
switch op.Tag {
case 'r':
na := op.J2 - op.J1
nb := op.I2 - op.I1
b1 := blmap[op.I1]
nc := min(na, nb)
for i := range nc {
(*bedit)[b1+i] = aorig[op.J1+i]
}
db := na - nb
if db > 0 {
*bedit = slices.Insert(*bedit, b1+nb, aorig[op.J1+nb:op.J2]...)
} else {
*bedit = slices.Delete(*bedit, b1+na, b1+nb)
}
for i := op.I2; i < len(blmap); i++ {
blmap[i] = blmap[i] + db
}
case 'd':
nb := op.I2 - op.I1
b1 := blmap[op.I1]
*bedit = slices.Delete(*bedit, b1, b1+nb)
for i := op.I2; i < len(blmap); i++ {
blmap[i] = blmap[i] - nb
}
case 'i':
na := op.J2 - op.J1
b1 := op.I1
if op.I1 < len(blmap) {
b1 = blmap[op.I1]
} else {
b1 = len(*bedit)
}
*bedit = slices.Insert(*bedit, b1, aorig[op.J1:op.J2]...)
for i := op.I2; i < len(blmap); i++ {
blmap[i] = blmap[i] + na
}
}
}
// DiffSelected supports the incremental application of selected diffs
// between two files (either A -> B or B <- A), with Undo
type DiffSelected struct {
A DiffSelectData
B DiffSelectData
// Diffs are the diffs between A and B
Diffs Diffs
}
func NewDiffSelected(astr, bstr []string) *DiffSelected {
ds := &DiffSelected{}
ds.SetStringLines(astr, bstr)
return ds
}
// SetStringLines sets the data from given lines of strings
func (ds *DiffSelected) SetStringLines(astr, bstr []string) {
ds.A.SetStringLines(astr)
ds.B.SetStringLines(bstr)
ds.Diffs = DiffLines(astr, bstr)
}
// AtoB applies given diff index from A to B
func (ds *DiffSelected) AtoB(idx int) {
op := DiffOpReverse(ds.Diffs[idx])
ds.B.SaveUndo(op)
ApplyOneDiff(op, &ds.B.Edit, ds.A.Orig, ds.B.LineMap)
}
// BtoA applies given diff index from B to A
func (ds *DiffSelected) BtoA(idx int) {
op := ds.Diffs[idx]
ds.A.SaveUndo(op)
ApplyOneDiff(op, &ds.A.Edit, ds.B.Orig, ds.A.LineMap)
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lines
import (
"maps"
"cogentcore.org/core/events"
)
// OnChange adds an event listener function to the view with given
// unique id, for the [events.Change] event.
// This is used for large-scale changes in the text, such as opening a
// new file or setting new text, or EditDone or Save.
func (ls *Lines) OnChange(vid int, fun func(e events.Event)) {
ls.Lock()
defer ls.Unlock()
vw := ls.view(vid)
if vw != nil {
vw.listeners.Add(events.Change, fun)
}
}
// OnInput adds an event listener function to the view with given
// unique id, for the [events.Input] event.
// This is sent after every fine-grained change in the text,
// and is used by text widgets to drive updates. It is blocked
// during batchUpdating.
func (ls *Lines) OnInput(vid int, fun func(e events.Event)) {
ls.Lock()
defer ls.Unlock()
vw := ls.view(vid)
if vw != nil {
vw.listeners.Add(events.Input, fun)
}
}
// SetAsyncRunner sets the function that runs the listeners of the view
// with the given unique id for an event that is sent from a background
// goroutine, as when the syntax highlighting markup has been updated.
// It must call the given function with whatever lock the listeners need,
// such as the AsyncLock of a widget, which already holds that lock for
// events sent while it handles its own events.
func (ls *Lines) SetAsyncRunner(vid int, run func(f func())) {
ls.Lock()
defer ls.Unlock()
vw := ls.view(vid)
if vw != nil {
vw.runAsync = run
}
}
// OnClose adds an event listener function to the view with given
// unique id, for the [events.Close] event.
// This event is sent in the Close function.
func (ls *Lines) OnClose(vid int, fun func(e events.Event)) {
ls.Lock()
defer ls.Unlock()
vw := ls.view(vid)
if vw != nil {
vw.listeners.Add(events.Close, fun)
}
}
//////// unexported api
// sendChange sends a new [events.Change] event to all views listeners.
// Must never be called with the mutex lock in place!
// This is used to signal that the text has changed, for large-scale changes,
// such as opening a new file or setting new text, or EditoDone or Save.
func (ls *Lines) sendChange() {
e := &events.Base{Typ: events.Change}
e.Init()
for _, vw := range ls.views {
vw.listeners.Call(e)
}
}
// sendInput sends a new [events.Input] event to all views listeners.
// Must never be called with the mutex lock in place!
// This is used to signal fine-grained changes in the text,
// and is used by text widgets to drive updates. It is blocked
// during batchUpdating.
func (ls *Lines) sendInput() {
if ls.batchUpdating {
return
}
e := &events.Base{Typ: events.Input}
e.Init()
for _, vw := range ls.views {
vw.listeners.Call(e)
}
}
// sendInputAsync is [Lines.sendInput] for a background goroutine:
// the listeners of each view are run by its [Lines.SetAsyncRunner]
// function, if it has one.
func (ls *Lines) sendInputAsync() {
if ls.batchUpdating {
return
}
e := &events.Base{Typ: events.Input}
e.Init()
// The views can be changed by the goroutines of their widgets meanwhile,
// so a view that has been deleted since is skipped: its widget can be
// gone. That is checked under the lock of the runner, which the widget
// holds when it deletes its view.
ls.Lock()
views := maps.Clone(ls.views)
ls.Unlock()
for vid, vw := range views {
if vw.runAsync == nil {
if ls.hasView(vid, vw) {
vw.listeners.Call(e)
}
continue
}
vw.runAsync(func() {
if ls.hasView(vid, vw) {
vw.listeners.Call(e)
}
})
}
}
// hasView returns whether the given view is still the view with the
// given id, so that it has not been deleted.
func (ls *Lines) hasView(vid int, vw *view) bool {
ls.Lock()
defer ls.Unlock()
return ls.views[vid] == vw
}
// sendClose sends a new [events.Close] event to all views listeners.
// Must never be called with the mutex lock in place!
// Only sent in the Close function.
func (ls *Lines) sendClose() {
e := &events.Base{Typ: events.Close}
e.Init()
for _, vw := range ls.views {
vw.listeners.Call(e)
}
}
// batchUpdateStart call this when starting a batch of updates.
// It calls AutoSaveOff and returns the prior state of that flag
// which must be restored using batchUpdateEnd.
func (ls *Lines) batchUpdateStart() (autoSave bool) {
ls.batchUpdating = true
ls.undos.NewGroup()
autoSave = ls.autoSaveOff()
return
}
// batchUpdateEnd call to complete BatchUpdateStart
func (ls *Lines) batchUpdateEnd(autoSave bool) {
ls.autoSaveRestore(autoSave)
ls.batchUpdating = false
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lines
import (
"io/fs"
"log"
"log/slog"
"os"
"path/filepath"
"strings"
"time"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/fileinfo"
"cogentcore.org/core/text/highlighting"
"cogentcore.org/core/text/parse"
)
//////// exported file api
// todo: cleanup and simplify the logic about language support!
// Filename returns the current filename
func (ls *Lines) Filename() string {
ls.Lock()
defer ls.Unlock()
return ls.filename
}
// FileInfo returns the current fileinfo
func (ls *Lines) FileInfo() *fileinfo.FileInfo {
ls.Lock()
defer ls.Unlock()
return &ls.fileInfo
}
// ParseState returns the current language properties and ParseState
// if it is a parse-supported known language, nil otherwise.
// Note: this API will change when LSP is implemented, and current
// use is likely to create race conditions / conflicts with markup.
func (ls *Lines) ParseState() (*parse.LanguageProperties, *parse.FileStates) {
ls.Lock()
defer ls.Unlock()
if lp := highlighting.ParseLanguage(ls.parseState.Known); lp != nil {
return lp, &ls.parseState
}
return nil, nil
}
// ParseFileState returns the parsed file state if this is a
// parse-supported known language, nil otherwise.
// Note: this API will change when LSP is implemented, and current
// use is likely to create race conditions / conflicts with markup.
func (ls *Lines) ParseFileState() *parse.FileState {
ls.Lock()
defer ls.Unlock()
if highlighting.ParseLanguage(ls.parseState.Known) != nil {
return ls.parseState.Done()
}
return nil
}
// SetFilename sets the filename associated with the buffer and updates
// the code highlighting information accordingly.
func (ls *Lines) SetFilename(fn string) *Lines {
ls.Lock()
defer ls.Unlock()
return ls.setFilename(fn)
}
// Stat gets info about the file, including the highlighting language.
func (ls *Lines) Stat() error {
ls.Lock()
defer ls.Unlock()
return ls.stat()
}
// ConfigKnown configures options based on the supported language info in parse.
// Returns true if supported.
func (ls *Lines) ConfigKnown() bool {
ls.Lock()
defer ls.Unlock()
return ls.configKnown()
}
// SetFileInfo sets the syntax highlighting and other parameters
// based on the type of file specified by given [fileinfo.FileInfo].
func (ls *Lines) SetFileInfo(info *fileinfo.FileInfo) *Lines {
ls.Lock()
defer ls.Unlock()
ls.setFileInfo(info)
return ls
}
// SetFileType sets the syntax highlighting and other parameters
// based on the given fileinfo.Known file type
func (ls *Lines) SetLanguage(ftyp fileinfo.Known) *Lines {
return ls.SetFileInfo(fileinfo.NewFileInfoType(ftyp))
}
// SetFileExt sets syntax highlighting and other parameters
// based on the given file extension (without the . prefix),
// for cases where an actual file with [fileinfo.FileInfo] is not
// available.
func (ls *Lines) SetFileExt(ext string) *Lines {
if len(ext) == 0 {
return ls
}
if ext[0] == '.' {
ext = ext[1:]
}
fn := "_fake." + strings.ToLower(ext)
fi, _ := fileinfo.NewFileInfo(fn)
return ls.SetFileInfo(fi)
}
// Open loads the given file into the buffer.
func (ls *Lines) Open(filename string) error { //types:add
ls.Lock()
err := ls.openFile(filename)
ls.Unlock()
ls.sendChange()
return err
}
// OpenFS loads the given file in the given filesystem into the buffer.
func (ls *Lines) OpenFS(fsys fs.FS, filename string) error {
ls.Lock()
err := ls.openFileFS(fsys, filename)
ls.Unlock()
ls.sendChange()
return err
}
// SaveFile writes current buffer to file, with no prompting, etc
func (ls *Lines) SaveFile(filename string) error {
ls.Lock()
err := ls.saveFile(filename)
if err == nil {
ls.autosaveDelete()
}
ls.Unlock()
return err
}
// Revert re-opens text from the current file,
// if the filename is set; returns false if not.
// It uses an optimized diff-based update to preserve
// existing formatting, making it very fast if not very different.
func (ls *Lines) Revert() bool { //types:add
ls.Lock()
did := ls.revert()
ls.Unlock()
ls.sendChange()
return did
}
// IsNotSaved returns true if buffer was changed (edited) since last Save.
func (ls *Lines) IsNotSaved() bool {
ls.Lock()
defer ls.Unlock()
return ls.notSaved
}
// ClearNotSaved sets Changed and NotSaved to false.
func (ls *Lines) ClearNotSaved() {
ls.Lock()
defer ls.Unlock()
ls.clearNotSaved()
}
// SetFileModOK sets the flag indicating that it is OK to edit even though
// the underlying file on disk has been edited.
func (ls *Lines) SetFileModOK(ok bool) {
ls.Lock()
defer ls.Unlock()
ls.fileModOK = ok
}
// EditDone is called externally (e.g., by Editor widget) when the user
// has indicated that editing is done, and the results are to be consumed.
func (ls *Lines) EditDone() {
ls.Lock()
ls.changed = false
ls.Unlock()
ls.sendChange()
}
// SetReadOnly sets whether the buffer is read-only.
func (ls *Lines) SetReadOnly(readonly bool) *Lines {
ls.Lock()
defer ls.Unlock()
return ls.setReadOnly(readonly)
}
// AutosaveFilename returns the autosave filename.
func (ls *Lines) AutosaveFilename() string {
ls.Lock()
defer ls.Unlock()
return ls.autosaveFilename()
}
// AutosaveDelete deletes any existing autosave file.
func (ls *Lines) AutosaveDelete() {
ls.Lock()
defer ls.Unlock()
ls.autosaveDelete()
}
// AutosaveCheck checks if an autosave file exists; logic for dealing with
// it is left to larger app; call this before opening a file.
func (ls *Lines) AutosaveCheck() bool {
ls.Lock()
defer ls.Unlock()
return ls.autosaveCheck()
}
// FileModCheck checks if the underlying file has been modified since last
// Stat (open, save); if haven't yet prompted, user is prompted to ensure
// that this is OK. It returns true if the file was modified.
func (ls *Lines) FileModCheck() bool {
ls.Lock()
defer ls.Unlock()
return ls.fileModCheck()
}
//////// Unexported implementation
// setChanged sets the changed and notSaved flags
func (ls *Lines) setChanged() {
ls.changed = true
ls.notSaved = true
}
// clearNotSaved sets Changed and NotSaved to false,
// as when the text is saved, recording its state as saved.
func (ls *Lines) clearNotSaved() {
ls.changed = false
ls.notSaved = false
ls.savedState = ls.undos.CurrentState()
}
// updateSaved makes the text not changed if it is in the state in which
// it was last saved, after undoing or redoing edits, as back to it, while
// the undo history before that is kept, so that edits before the save
// can still be undone. This works in both undo modes: in the emacs mode,
// undoing the undos past the save reaches the saved state again
// (see [Undo.State]).
func (ls *Lines) updateSaved() {
if ls.undos.CurrentState() != ls.savedState {
return
}
ls.changed = false
ls.notSaved = false
ls.autosaveDelete()
}
// setReadOnly sets whether the buffer is read-only.
// read-only buffers also do not record undo events.
func (ls *Lines) setReadOnly(readonly bool) *Lines {
ls.readOnly = readonly
ls.undos.Off = readonly
return ls
}
// setFilename sets the filename associated with the buffer and updates
// the code highlighting information accordingly.
func (ls *Lines) setFilename(fn string) *Lines {
ls.filename = fn
ls.stat()
ls.setFileInfo(&ls.fileInfo)
return ls
}
// stat gets info about the file, including the highlighting language.
func (ls *Lines) stat() error {
ls.fileModOK = false
err := ls.fileInfo.InitFile(string(ls.filename))
ls.diskModTime = time.Time{}
if info, serr := os.Stat(ls.fileInfo.Path); serr == nil {
ls.diskModTime = info.ModTime()
}
ls.configKnown() // may have gotten file type info even if not existing
return err
}
// configKnown configures options based on the supported language info in parse.
// Returns true if supported.
func (ls *Lines) configKnown() bool {
if ls.fileInfo.Known != fileinfo.Unknown {
return ls.Settings.ConfigKnown(ls.fileInfo.Known)
}
return false
}
// openFile just loads the given file into the buffer, without doing
// any markup or signaling. It is typically used in other functions or
// for temporary buffers.
func (ls *Lines) openFile(filename string) error {
txt, err := os.ReadFile(string(filename))
if err != nil {
return err
}
ls.setFilename(filename)
ls.setText(txt)
return nil
}
// openFileOnly just loads the given file into the buffer, without doing
// any markup or signaling. It is typically used in other functions or
// for temporary buffers.
func (ls *Lines) openFileOnly(filename string) error {
txt, err := os.ReadFile(string(filename))
if err != nil {
return err
}
ls.setFilename(filename)
ls.bytesToLines(txt) // not setText!
return nil
}
// openFileFS loads the given file in the given filesystem into the buffer.
func (ls *Lines) openFileFS(fsys fs.FS, filename string) error {
txt, err := fs.ReadFile(fsys, filename)
if err != nil {
return err
}
ls.setFilename(filename)
ls.setText(txt)
return nil
}
// revert re-opens text from the current file,
// if the filename is set; returns false if not.
// It uses an optimized diff-based update to preserve
// existing formatting, making it very fast if not very different.
func (ls *Lines) revert() bool {
if ls.filename == "" {
return false
}
ls.stopDelayedReMarkup()
ls.autosaveDelete() // justin case
didDiff := false
if ls.numLines() < diffRevertLines {
ob := NewLines()
err := ob.openFileOnly(ls.filename)
if errors.Log(err) != nil {
// sc := tb.sceneFromEditor() // todo:
// if sc != nil { // only if viewing
// core.ErrorSnackbar(sc, err, "Error reopening file")
// }
return false
}
ls.stat() // "own" the new file..
if ob.NumLines() < diffRevertLines {
diffs := ls.diffs(ob)
if len(diffs) < diffRevertDiffs {
ls.patchFrom(ob, diffs)
didDiff = true
}
}
}
if !didDiff {
ls.openFile(ls.filename)
}
ls.clearNotSaved()
ls.autosaveDelete()
return true
}
// saveFile writes current buffer to file, with no prompting, etc
func (ls *Lines) saveFile(filename string) error {
err := os.WriteFile(string(filename), ls.bytes(0), 0644)
if err != nil {
// core.ErrorSnackbar(tb.sceneFromEditor(), err) // todo:
slog.Error(err.Error())
} else {
ls.clearNotSaved()
ls.filename = filename
ls.stat()
}
return err
}
// ChangedOnDisk returns whether the file has been modified on disk
// since it was last opened or saved.
func (ls *Lines) ChangedOnDisk() bool {
ls.Lock()
defer ls.Unlock()
return ls.changedOnDisk()
}
func (ls *Lines) changedOnDisk() bool {
if ls.filename == "" {
return false
}
info, err := os.Stat(string(ls.filename))
return err == nil && !info.ModTime().Equal(ls.diskModTime)
}
// fileModCheck checks if the underlying file has been modified since last
// Stat (open, save); if haven't yet prompted, user is prompted to ensure
// that this is OK. It returns true if the file was modified.
func (ls *Lines) fileModCheck() bool {
if ls.filename == "" || ls.fileModOK {
return false
}
if ls.changedOnDisk() {
if !ls.notSaved { // we haven't edited: just revert
ls.revert()
return true
}
if ls.FileModPromptFunc != nil {
ls.Unlock() // note: we assume anything getting here will be under lock
ls.FileModPromptFunc()
ls.Lock()
}
return true
}
return false
}
//////// Autosave
// autoSaveOff turns off autosave and returns the
// prior state of Autosave flag.
// Call AutosaveRestore with rval when done.
// See BatchUpdate methods for auto-use of this.
func (ls *Lines) autoSaveOff() bool {
asv := ls.Autosave
ls.Autosave = false
return asv
}
// autoSaveRestore restores prior Autosave setting,
// from AutosaveOff
func (ls *Lines) autoSaveRestore(asv bool) {
ls.Autosave = asv
}
// autosaveFilename returns the autosave filename.
func (ls *Lines) autosaveFilename() string {
path, fn := filepath.Split(ls.filename)
if fn == "" {
fn = "new_file"
}
asfn := filepath.Join(path, "#"+fn+"#")
return asfn
}
// autoSave does the autosave. It is called in a separate goroutine
// after edits, which hold the lock, so it gets the lock to read the
// text, which further edits could otherwise change while it is read.
func (ls *Lines) autoSave() error {
ls.Lock()
if ls.autoSaving {
ls.Unlock()
return nil
}
ls.autoSaving = true
asfn := ls.autosaveFilename()
b := ls.bytes(0)
ls.Unlock()
err := os.WriteFile(asfn, b, 0644)
if err != nil {
log.Printf("Lines: Could not Autosave file: %v, error: %v\n", asfn, err)
}
ls.Lock()
ls.autoSaving = false
ls.Unlock()
return err
}
// autosaveDelete deletes any existing autosave file
func (ls *Lines) autosaveDelete() {
asfn := ls.autosaveFilename()
err := os.Remove(asfn)
// the file may not exist, which is fine
if err != nil && !errors.Is(err, fs.ErrNotExist) {
errors.Log(err)
}
}
// autosaveCheck checks if an autosave file exists; logic for dealing with
// it is left to larger app; call this before opening a file.
func (ls *Lines) autosaveCheck() bool {
asfn := ls.autosaveFilename()
if _, err := os.Stat(asfn); os.IsNotExist(err) {
return false // does not exist
}
return true
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lines
import (
"fmt"
"unicode"
"cogentcore.org/core/base/slicesx"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/textpos"
)
// layoutViewLines performs view-specific layout of all lines of current lines markup.
// This manages its own memory allocation, so it can be called on a new view.
// It must be called after any update to the source text or view layout parameters.
func (ls *Lines) layoutViewLines(vw *view) {
n := len(ls.markup)
if n == 0 {
return
}
vw.markup = vw.markup[:0]
vw.vlineStarts = vw.vlineStarts[:0]
vw.lineToVline = slicesx.SetLength(vw.lineToVline, n)
nln := 0
for ln, mu := range ls.markup {
muls, vst := ls.layoutViewLine(vw, ln, ls.lines[ln], mu)
vw.lineToVline[ln] = len(vw.vlineStarts)
vw.markup = append(vw.markup, muls...)
vw.vlineStarts = append(vw.vlineStarts, vst...)
nln += len(vst)
}
vw.viewLines = nln
}
// layoutViewLinesFrom updates the layout of the view lines from the
// given source line onward, keeping the layout of the lines before it,
// which must not have changed.
func (ls *Lines) layoutViewLinesFrom(vw *view, start int) {
n := len(ls.markup)
if start <= 0 || n == 0 || start > len(vw.lineToVline) {
ls.layoutViewLines(vw)
return
}
vst := len(vw.vlineStarts)
if start < len(vw.lineToVline) {
vst = vw.lineToVline[start]
}
vw.markup = vw.markup[:vst]
vw.vlineStarts = vw.vlineStarts[:vst]
vw.lineToVline = slicesx.SetLength(vw.lineToVline, n)
for ln := start; ln < n; ln++ {
muls, vst := ls.layoutViewLine(vw, ln, ls.lines[ln], ls.markup[ln])
vw.lineToVline[ln] = len(vw.vlineStarts)
vw.markup = append(vw.markup, muls...)
vw.vlineStarts = append(vw.vlineStarts, vst...)
}
vw.viewLines = len(vw.vlineStarts)
}
// layoutViewLinesRange updates the layout of the given range of source
// lines (inclusive) in the given view, after their markup changed, keeping
// the layout of the other lines, unless the number of view lines of the
// range changed, in which case the lines after it are laid out again too.
// This makes the markup of single lines, such as for tags, fast.
func (ls *Lines) layoutViewLinesRange(vw *view, st, ed int) {
n := len(ls.markup)
if st < 0 || st > ed || ed >= n || len(vw.lineToVline) != n || len(vw.vlineStarts) != vw.viewLines || len(vw.markup) != vw.viewLines {
ls.layoutViewLinesFrom(vw, max(st, 0))
return
}
vst := vw.lineToVline[st]
ved := vw.viewLines // view lines of the range: [vst, ved)
if ed+1 < n {
ved = vw.lineToVline[ed+1]
}
var muls []rich.Text
var starts []textpos.Pos
vls := make([]int, 0, ed-st+1) // the first view line of each line
for ln := st; ln <= ed; ln++ {
mu, vs := ls.layoutViewLine(vw, ln, ls.lines[ln], ls.markup[ln])
vls = append(vls, vst+len(starts))
muls = append(muls, mu...)
starts = append(starts, vs...)
}
if len(starts) != ved-vst {
ls.layoutViewLinesFrom(vw, st)
return
}
copy(vw.markup[vst:ved], muls)
copy(vw.vlineStarts[vst:ved], starts)
copy(vw.lineToVline[st:ed+1], vls)
}
// layoutViewLine performs layout and line wrapping on the given text,
// for given view text, with the given markup rich.Text.
// The layout is implemented in the markup that is returned.
// This clones and then modifies the given markup rich text.
// Any [VirtualText] for the view is included, so the returned
// view line starts are in display chars (see [Lines.srcToDisplay]).
func (ls *Lines) layoutViewLine(vw *view, ln int, txt []rune, mu rich.Text) ([]rich.Text, []textpos.Pos) {
width := vw.width
txt, mu, forced := ls.displayLine(vw, ln, txt, mu)
lt := mu.Clone()
n := len(txt)
sp := textpos.Pos{Line: ln, Char: 0} // source startinng position
vst := []textpos.Pos{sp} // start with this line
breaks := []int{} // line break indexes into lt spans
clen := 0 // current line length so far
start := true
prevWasTab := false
i := 0
for i < n {
if len(forced) > 0 && i >= forced[0] { // next line of multi-line virtual text
forced = forced[1:]
clen = 0
start = false
prevWasTab = false
if i > sp.Char || len(vst) == 0 {
sp.Char = i
vst = append(vst, sp)
if si := lt.SplitSpan(i); si >= 0 {
breaks = append(breaks, si)
}
}
continue
}
r := txt[i]
si, sn, ri := lt.Index(i)
startOfSpan := sn == ri
// fmt.Printf("\n####\n%d\tclen:%d\tsi:%dsn:%d\tri:%d\t%v %v, sisrc: %q txt: %q\n", i, clen, si, sn, ri, startOfSpan, prevWasTab, string(lt[si][ri:]), string(txt[i:min(i+5, n)]))
switch {
case start && r == '\t':
clen += ls.Settings.TabSize
if !startOfSpan {
lt.SplitSpan(i) // each tab gets its own
}
prevWasTab = true
i++
case r == '\t':
tp := (clen / 8) + 1
tp *= 8
clen = tp
if !startOfSpan {
lt.SplitSpan(i)
}
prevWasTab = true
i++
case unicode.IsSpace(r):
start = false
clen++
if prevWasTab && !startOfSpan {
lt.SplitSpan(i)
}
prevWasTab = false
i++
default:
start = false
didSplit := false
if prevWasTab && !startOfSpan {
lt.SplitSpan(i)
didSplit = true
si++
}
prevWasTab = false
ns := NextSpace(txt, i)
if len(forced) > 0 && forced[0] < ns {
ns = forced[0]
}
wlen := textCells(txt[i:ns]) // width of word, in cells
// fmt.Println("word at:", i, "ns:", ns, string(txt[i:ns]))
if clen+wlen > width && clen > 0 { // need to wrap
clen = 0
sp.Char = i
vst = append(vst, sp)
if !startOfSpan && !didSplit {
lt.SplitSpan(i)
si++
}
if si < 0 {
fmt.Println("lines.layout si < 0")
} else {
breaks = append(breaks, si)
}
}
if clen+wlen > width { // break the word, where it fills a line
for bp := i; bp < ns; bp++ {
w := RuneWidth(txt[bp])
if clen+w > width && clen > 0 {
si, sn, ri := lt.Index(bp)
if sn != ri { // not start of span already
lt.SplitSpan(bp)
si++
}
if si < 0 {
fmt.Println("lines.layout si < 0")
} else {
breaks = append(breaks, si)
}
sp.Char = bp
vst = append(vst, sp)
clen = 0
}
clen += w
}
} else {
clen += wlen
}
i = ns
}
}
nb := len(breaks)
if nb == 0 {
return []rich.Text{lt}, vst
}
muls := make([]rich.Text, 0, nb+1)
last := 0
ltn := len(lt)
for _, si := range breaks {
if si < last || si > ltn {
continue
}
muls = append(muls, lt[last:si])
last = si
}
muls = append(muls, lt[last:])
return muls, vst
}
func NextSpace(txt []rune, pos int) int {
n := len(txt)
for i := pos; i < n; i++ {
r := txt[i]
if unicode.IsSpace(r) {
return i
}
}
return n
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lines
//go:generate core generate -add-types
import (
"bytes"
"fmt"
"image"
"log"
"slices"
"sync"
"time"
"cogentcore.org/core/base/fileinfo"
"cogentcore.org/core/base/metadata"
"cogentcore.org/core/base/slicesx"
"cogentcore.org/core/text/highlighting"
"cogentcore.org/core/text/parse"
"cogentcore.org/core/text/parse/lexer"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/runes"
"cogentcore.org/core/text/textpos"
)
// MatchCase specifies whether [Lines.ReplaceText] matches the case of the
// replaced text: [ReplaceMatchCase] or [ReplaceNoMatchCase].
type MatchCase bool
const (
// ReplaceMatchCase is used for MatchCase arg in ReplaceText method
ReplaceMatchCase MatchCase = true
// ReplaceNoMatchCase is used for MatchCase arg in ReplaceText method
ReplaceNoMatchCase MatchCase = false
)
var (
// maximum number of lines to look for matching scope syntax (parens, brackets)
maxScopeLines = 100 // `default:"100" min:"10" step:"10"`
// maximum number of lines to apply syntax highlighting markup on
maxMarkupLines = 10000 // `default:"10000" min:"1000" step:"1000"`
// amount of time to wait before starting a new background markup process,
// after text changes within a single line (always does after line insertion / deletion)
markupDelay = 500 * time.Millisecond // `default:"500" min:"100" step:"100"`
// text buffer max lines to use diff-based revert to more quickly update
// e.g., after file has been reformatted
diffRevertLines = 10000 // `default:"10000" min:"0" step:"1000"`
// text buffer max diffs to use diff-based revert to more quickly update
// e.g., after file has been reformatted -- if too many differences, just revert.
diffRevertDiffs = 20 // `default:"20" min:"0" step:"1"`
)
// Lines manages multi-line monospaced text with a given line width in runes,
// so that all text wrapping, editing, and navigation logic can be managed
// purely in text space, allowing rendering and GUI layout to be relatively fast.
// This is suitable for text editing and terminal applications, among others.
// The text encoded as runes along with a corresponding [rich.Text] markup
// representation with syntax highlighting etc.
// The markup is updated in a separate goroutine for efficiency.
// Everything is protected by an overall sync.Mutex and is safe to concurrent access,
// and thus nothing is exported and all access is through protected accessor functions.
// In general, all unexported methods do NOT lock, and all exported methods do.
type Lines struct {
// Settings are the options for how text editing and viewing works.
Settings Settings
// Highlighter does the syntax highlighting markup, and contains the
// parameters thereof, such as the language and style.
Highlighter highlighting.Highlighter
// Autosave specifies whether an autosave copy of the file should
// be automatically saved after changes are made.
Autosave bool
// FileModPromptFunc is called when a file has been modified in the filesystem
// and it is about to be modified through an edit, in the fileModCheck function.
// The prompt should determine whether the user wants to revert, overwrite, or
// save current version as a different file. It must block until the user responds.
FileModPromptFunc func()
// Meta can be used to maintain misc metadata associated with the Lines text,
// which allows the Lines object to be the primary data type for applications
// dealing with text data, if there are just a few additional data elements needed.
// Use standard Go camel-case key names, standards in [metadata].
Meta metadata.Data
// fontStyle is the default font styling to use for markup.
// Is set to use the monospace font.
fontStyle *rich.Style
// undos is the undo manager.
undos Undo
// filename is the filename of the file that was last loaded or saved.
// If this is empty then no file-related functionality is engaged.
filename string
// readOnly marks the contents as not editable. This is for the outer GUI
// elements to consult, and is not enforced within Lines itself.
readOnly bool
// fileInfo is the full information about the current file, if one is set.
fileInfo fileinfo.FileInfo
// diskModTime is the modification time of the file on disk when it was
// last opened or saved, for detecting changes on disk. This is not
// fileInfo.ModTime, which is a fixed time when testing.
diskModTime time.Time
// parseState is the parsing state information for the file.
parseState parse.FileStates
// changed indicates whether any changes have been made.
// Use [IsChanged] method to access.
changed bool
// lines are the live lines of text being edited, with the latest modifications.
// They are encoded as runes per line, which is necessary for one-to-one rune/glyph
// rendering correspondence. All textpos positions are in rune indexes.
lines [][]rune
// tags are the extra custom tagged regions for each line.
tags []lexer.Line
// hiTags are the syntax highlighting tags, which are auto-generated.
hiTags []lexer.Line
// virtual is the display-only virtual text for each line,
// in order of position (see [Lines.SetVirtualText]).
virtual [][]virtualText
// markup is the [rich.Text] encoded marked-up version of the text lines,
// with the results of syntax highlighting. It just has the raw markup without
// additional layout for a specific line width, which goes in a [view].
markup []rich.Text
// views are the distinct views of the lines, accessed via a unique view handle,
// which is the key in the map. Each view can have its own width, and thus its own
// markup and layout.
views map[int]*view
// lineColors associate a color with a given line number (key of map),
// e.g., for a breakpoint or other such function.
lineColors map[int]image.Image
// markupEdits are the edits that were made during the time it takes to generate
// the new markup tags. this is rare but it does happen.
markupEdits []*textpos.Edit
// markupDelayTimer is the markup delay timer.
markupDelayTimer *time.Timer
// markupDelayMu is the mutex for updating the markup delay timer.
markupDelayMu sync.Mutex
// markupDeferred is whether the syntax highlighting markup is deferred
// until the text is first shown in a view (see [Lines.StartDeferredMarkup]),
// which is done when running in JavaScript (see goscript), where it can
// take a significant amount of time.
markupDeferred bool
// posHistory is the history of cursor positions.
// It can be used to move back through them.
posHistory []textpos.Pos
// links is the collection of all hyperlinks within the markup source,
// indexed by the markup source line.
// only updated at the full markup sweep.
links map[int][]rich.Hyperlink
// batchUpdating indicates that a batch update is under way,
// so Input signals are not sent until the end.
batchUpdating bool
// autoSaving is used in atomically safe way to protect autosaving
autoSaving bool
// autoSaves are the running autosave goroutines.
autoSaves sync.WaitGroup
// notSaved indicates if the text has been changed (edited) relative to the
// original, since last Save. This can be true even when changed flag is
// false, because changed is cleared on EditDone, e.g., when texteditor
// is being monitored for OnChange and user does Control+Enter.
// Use IsNotSaved() method to query state.
notSaved bool
// savedState is the state of the undo stack ([Undo.State]) when the text
// was last saved, or set, as when it was opened, so that undoing or
// redoing edits back to that state makes it not changed
// (see [Lines.updateSaved]).
savedState int
// fileModOK have already asked about fact that file has changed since being
// opened, user is ok
fileModOK bool
// use Lock(), Unlock() directly for overall mutex on any content updates
sync.Mutex
}
func (ls *Lines) Metadata() *metadata.Data { return &ls.Meta }
// numLines returns number of lines
func (ls *Lines) numLines() int {
return len(ls.lines)
}
// isValidLine returns true if given line number is in range.
func (ls *Lines) isValidLine(ln int) bool {
if ln < 0 {
return false
}
return ln < ls.numLines()
}
// setText sets the rune lines from source text,
// and triggers initial markup and delayed full markup.
func (ls *Lines) setText(txt []byte) {
ls.bytesToLines(txt)
ls.initialMarkup()
ls.startDelayedReMarkup()
}
// bytesToLines sets the rune lines from source text.
// it does not trigger any markup but does allocate everything.
func (ls *Lines) bytesToLines(txt []byte) {
if txt == nil {
txt = []byte("")
}
ls.setLineBytes(bytes.Split(txt, []byte("\n")))
}
// setLineBytes sets the lines from source [][]byte.
func (ls *Lines) setLineBytes(lns [][]byte) {
n := len(lns)
if n > 1 && len(lns[n-1]) == 0 { // lines have lf at end typically
lns = lns[:n-1]
n--
}
if ls.fontStyle == nil {
ls.Defaults()
}
ls.lines = slicesx.SetLength(ls.lines, n)
ls.tags = slicesx.SetLength(ls.tags, n)
ls.hiTags = slicesx.SetLength(ls.hiTags, n)
ls.markup = slicesx.SetLength(ls.markup, n)
ls.virtual = make([][]virtualText, n) // positions are not valid for new text
for ln, txt := range lns {
ls.lines[ln] = runes.SetFromBytes(ls.lines[ln], txt)
ls.markup[ln] = rich.NewText(ls.fontStyle, ls.lines[ln]) // start with raw
}
ls.savedState = ls.undos.CurrentState()
}
// bytes returns the current text lines as a slice of bytes, up to
// given number of lines if maxLines > 0. Every line ends with a line
// feed, including the last, per POSIX standards:
// https://stackoverflow.com/questions/729692/why-should-text-files-end-with-a-newline
func (ls *Lines) bytes(maxLines int) []byte {
nl := ls.numLines()
if maxLines > 0 {
nl = min(nl, maxLines)
}
b := make([]byte, 0, 80*nl)
for ln := range nl {
b = append(b, string(ls.lines[ln])...)
b = append(b, '\n')
}
return b
}
// strings returns the current text as []string array.
// If addNewLine is true, each string line has a \n appended at end.
func (ls *Lines) strings(addNewLine bool) []string {
str := make([]string, ls.numLines())
for i, l := range ls.lines {
str[i] = string(l)
if addNewLine {
str[i] += "\n"
}
}
return str
}
//////// Appending Lines
// endPos returns the ending position at end of lines
func (ls *Lines) endPos() textpos.Pos {
n := ls.numLines()
if n == 0 {
return textpos.Pos{}
}
return textpos.Pos{Line: n - 1, Char: len(ls.lines[n-1])}
}
// appendTextMarkup appends new lines of text to end of lines,
// using insert, returns edit, and uses supplied markup to render it.
func (ls *Lines) appendTextMarkup(text [][]rune, markup []rich.Text) *textpos.Edit {
if len(text) == 0 {
return &textpos.Edit{}
}
text = append(text, []rune{})
ed := ls.endPos()
tbe := ls.insertTextLines(ed, text)
if tbe == nil {
fmt.Println("nil insert", ed, text)
return nil
}
st := tbe.Region.Start.Line
el := tbe.Region.End.Line
for ln := st; ln < el; ln++ {
ls.markup[ln] = markup[ln-st]
}
return tbe
}
// replaceLinesMarkup does [Lines.ReplaceLinesMarkup] without locking.
func (ls *Lines) replaceLinesMarkup(start, end int, text [][]rune, markup []rich.Text) {
if ls.fontStyle == nil {
ls.Defaults()
}
n := ls.numLines()
start = max(0, min(start, n))
if end < 0 || end > n {
end = n
}
end = max(end, start)
nt := len(text)
if len(markup) != nt {
mu := make([]rich.Text, nt)
for i := range nt {
if i < len(markup) {
mu[i] = markup[i]
} else {
mu[i] = rich.NewText(ls.fontStyle, text[i])
}
}
markup = mu
}
ls.lines = slices.Replace(ls.lines, start, end, text...)
ls.markup = slices.Replace(ls.markup, start, end, markup...)
ls.tags = slices.Replace(ls.tags, start, end, make([]lexer.Line, nt)...)
ls.hiTags = slices.Replace(ls.hiTags, start, end, make([]lexer.Line, nt)...)
ls.virtual = slices.Replace(ls.virtualLinesFor(n), start, end, make([][]virtualText, nt)...)
if ls.numLines() == 0 { // there is always at least one line
ls.lines = [][]rune{{}}
ls.markup = []rich.Text{rich.NewText(ls.fontStyle, nil)}
ls.tags = make([]lexer.Line, 1)
ls.hiTags = make([]lexer.Line, 1)
ls.virtual = make([][]virtualText, 1)
}
if end == n { // only the tail changed, so other lines keep their indexes
for ln := range ls.links {
if ln >= start {
delete(ls.links, ln)
}
}
if ls.links == nil {
ls.links = make(map[int][]rich.Hyperlink)
}
for ln := start; ln < ls.numLines(); ln++ {
if lks := ls.markup[ln].GetLinks(); len(lks) > 0 {
ls.links[ln] = lks
}
}
} else {
ls.collectLinks()
}
for _, vw := range ls.views {
ls.layoutViewLinesFrom(vw, start)
}
}
//////// Edits
// validCharPos returns the position with a valid Char position,
// if it is not valid. if the line is invalid, it returns false.
func (ls *Lines) validCharPos(pos textpos.Pos) (textpos.Pos, bool) {
n := ls.numLines()
if n == 0 {
if pos.Line != 0 {
return pos, false
}
pos.Char = 0
return pos, true
}
if pos.Line < 0 || pos.Line >= n {
return pos, false
}
llen := len(ls.lines[pos.Line])
if pos.Char < 0 {
pos.Char = 0
return pos, true
}
if pos.Char > llen {
pos.Char = llen
return pos, true
}
return pos, true
}
// isValidPos returns true if position is valid. Note that the end
// of the line (at length) is valid. This version does not panic or emit
// an error message, and should be used for cases where a position can
// legitimately be invalid, and is managed.
func (ls *Lines) isValidPos(pos textpos.Pos) bool {
n := ls.numLines()
if n == 0 {
if pos.Line != 0 || pos.Char != 0 {
return false
}
}
if pos.Line < 0 || pos.Line >= n {
return false
}
llen := len(ls.lines[pos.Line])
if pos.Char < 0 || pos.Char > llen {
return false
}
return true
}
// mustValidPos panics if the position is invalid. Note that the end
// of the line (at length) is valid.
func (ls *Lines) mustValidPos(pos textpos.Pos) {
n := ls.numLines()
if n == 0 {
if pos.Line != 0 || pos.Char != 0 {
panic("invalid position for empty text: " + pos.String())
}
}
if pos.Line < 0 || pos.Line >= n {
panic(fmt.Sprintf("invalid line number for n lines %d: pos: %s", n, pos))
}
llen := len(ls.lines[pos.Line])
if pos.Char < 0 || pos.Char > llen {
panic(fmt.Sprintf("invalid character position for pos, len: %d: pos: %s", llen, pos))
}
}
// region returns a Edit representation of text between start and end positions
// returns nil and logs an error if not a valid region.
// sets the timestamp on the Edit to now
func (ls *Lines) region(st, ed textpos.Pos) *textpos.Edit {
n := ls.numLines()
ls.mustValidPos(st)
if ed.Line == n && ed.Char == 0 { // end line: goes to endpos
ed.Line = n - 1
ed.Char = len(ls.lines[ed.Line])
}
ls.mustValidPos(ed)
if st == ed {
return nil
}
if !st.IsLess(ed) {
log.Printf("lines.region: starting position must be less than ending!: st: %v, ed: %v\n", st, ed)
return nil
}
tbe := &textpos.Edit{Region: textpos.NewRegionPos(st, ed)}
if ed.Line == st.Line {
sz := ed.Char - st.Char
tbe.Text = make([][]rune, 1)
tbe.Text[0] = make([]rune, sz)
copy(tbe.Text[0][:sz], ls.lines[st.Line][st.Char:ed.Char])
} else {
nln := tbe.Region.NumLines()
tbe.Text = make([][]rune, nln)
stln := st.Line
if st.Char > 0 {
ec := len(ls.lines[st.Line])
sz := ec - st.Char
if sz > 0 {
tbe.Text[0] = make([]rune, sz)
copy(tbe.Text[0], ls.lines[st.Line][st.Char:])
}
stln++
}
edln := ed.Line
if ed.Char < len(ls.lines[ed.Line]) {
tbe.Text[ed.Line-st.Line] = make([]rune, ed.Char)
copy(tbe.Text[ed.Line-st.Line], ls.lines[ed.Line][:ed.Char])
edln--
}
for ln := stln; ln <= edln; ln++ {
ti := ln - st.Line
sz := len(ls.lines[ln])
tbe.Text[ti] = make([]rune, sz)
copy(tbe.Text[ti], ls.lines[ln])
}
}
return tbe
}
// regionRect returns a Edit representation of text between start and end
// positions as a rectangle.
// returns nil and logs an error if not a valid region.
// sets the timestamp on the Edit to now
func (ls *Lines) regionRect(st, ed textpos.Pos) *textpos.Edit {
ls.mustValidPos(st)
ls.mustValidPos(ed)
if st == ed {
return nil
}
if !st.IsLess(ed) || st.Char >= ed.Char {
log.Printf("core.Buf.RegionRect: starting position must be less than ending!: st: %v, ed: %v\n", st, ed)
return nil
}
tbe := &textpos.Edit{Region: textpos.NewRegionPos(st, ed)}
tbe.Rect = true
nln := tbe.Region.NumLines()
nch := (ed.Char - st.Char)
tbe.Text = make([][]rune, nln)
for i := range nln {
ln := st.Line + i
lr := ls.lines[ln]
ll := len(lr)
var txt []rune
if ll > st.Char {
sz := min(ll-st.Char, nch)
txt = make([]rune, sz, nch)
edl := min(ed.Char, ll)
copy(txt, lr[st.Char:edl])
}
if len(txt) < nch { // rect
txt = append(txt, runes.Repeat([]rune(" "), nch-len(txt))...)
}
tbe.Text[i] = txt
}
return tbe
}
// deleteText is the primary method for deleting text,
// between start and end positions.
// An Undo record is automatically saved depending on Undo.Off setting.
func (ls *Lines) deleteText(st, ed textpos.Pos) *textpos.Edit {
tbe := ls.deleteTextImpl(st, ed)
ls.saveUndo(tbe)
return tbe
}
func (ls *Lines) deleteTextImpl(st, ed textpos.Pos) *textpos.Edit {
tbe := ls.region(st, ed)
if tbe == nil {
return nil
}
tbe.Delete = true
nl := ls.numLines()
if ed.Line == st.Line {
if st.Line < nl {
ec := min(ed.Char, len(ls.lines[st.Line])) // somehow region can still not be valid.
ls.lines[st.Line] = append(ls.lines[st.Line][:st.Char], ls.lines[st.Line][ec:]...)
ls.virtualDeleted(st, textpos.Pos{Line: st.Line, Char: ec})
ls.linesEdited(tbe)
}
} else {
// first get chars on start and end
stln := st.Line + 1
cpln := st.Line
ls.lines[st.Line] = ls.lines[st.Line][:st.Char]
eoedl := 0
if ed.Line >= nl {
ed.Line = nl - 1
}
if ed.Char < len(ls.lines[ed.Line]) {
eoedl = len(ls.lines[ed.Line][ed.Char:])
}
var eoed []rune
if eoedl > 0 { // save it
eoed = make([]rune, eoedl)
copy(eoed, ls.lines[ed.Line][ed.Char:])
}
ls.lines = append(ls.lines[:stln], ls.lines[ed.Line+1:]...)
if eoed != nil {
ls.lines[cpln] = append(ls.lines[cpln], eoed...)
}
ls.virtualDeleted(st, ed)
ls.linesDeleted(tbe)
}
ls.setChanged()
return tbe
}
// deleteTextRect deletes rectangular region of text between start, end
// defining the upper-left and lower-right corners of a rectangle.
// Fails if st.Char >= ed.Char. Sets the timestamp on resulting Edit to now.
// An Undo record is automatically saved depending on Undo.Off setting.
func (ls *Lines) deleteTextRect(st, ed textpos.Pos) *textpos.Edit {
tbe := ls.deleteTextRectImpl(st, ed)
ls.saveUndo(tbe)
return tbe
}
func (ls *Lines) deleteTextRectImpl(st, ed textpos.Pos) *textpos.Edit {
tbe := ls.regionRect(st, ed)
if tbe == nil {
return nil
}
// fmt.Println("del:", tbe.Region)
tbe.Delete = true
for ln := st.Line; ln <= ed.Line; ln++ {
l := ls.lines[ln]
// fmt.Println(ln, string(l))
if len(l) > st.Char {
if ed.Char <= len(l)-1 {
ls.lines[ln] = slices.Delete(l, st.Char, ed.Char)
// fmt.Println(ln, "del:", st.Char, ed.Char, string(ls.lines[ln]))
} else {
ls.lines[ln] = l[:st.Char]
// fmt.Println(ln, "trunc", st.Char, ed.Char, string(ls.lines[ln]))
}
}
}
ls.linesEdited(tbe)
ls.setChanged()
return tbe
}
// insertText is the primary method for inserting text,
// at given starting position. Sets the timestamp on resulting Edit to now.
// An Undo record is automatically saved depending on Undo.Off setting.
func (ls *Lines) insertText(st textpos.Pos, txt []rune) *textpos.Edit {
tbe := ls.insertTextImpl(st, runes.Split(txt, []rune("\n")))
ls.saveUndo(tbe)
return tbe
}
// insertTextLines is the primary method for inserting text,
// at given starting position, for text source that is already split
// into lines. Do NOT use Impl unless you really don't want to save
// the undo: in general very bad not to!
// Sets the timestamp on resulting Edit to now.
// An Undo record is automatically saved depending on Undo.Off setting.
func (ls *Lines) insertTextLines(st textpos.Pos, txt [][]rune) *textpos.Edit {
tbe := ls.insertTextImpl(st, txt)
ls.saveUndo(tbe)
return tbe
}
// appendLines appends given number of lines at the end.
func (ls *Lines) appendLines(n int) {
ls.lines = append(ls.lines, make([][]rune, n)...)
ls.markup = append(ls.markup, make([]rich.Text, n)...)
ls.tags = append(ls.tags, make([]lexer.Line, n)...)
ls.hiTags = append(ls.hiTags, make([]lexer.Line, n)...)
ls.virtual = append(ls.virtualLinesFor(len(ls.tags)-n), make([][]virtualText, n)...)
for _, vw := range ls.views {
// the appended lines start at the end of the view lines, so that
// they are laid out there (not at view line 0, over the first line)
for range n {
vw.lineToVline = append(vw.lineToVline, vw.viewLines)
}
}
}
// insertTextImpl inserts the Text at given starting position.
func (ls *Lines) insertTextImpl(st textpos.Pos, txt [][]rune) *textpos.Edit {
if st.Line == ls.numLines() && st.Char == 0 { // adding new line
ls.appendLines(1)
}
ls.mustValidPos(st)
nl := len(txt)
var tbe *textpos.Edit
ed := st
if nl == 1 {
ls.lines[st.Line] = slices.Insert(ls.lines[st.Line], st.Char, txt[0]...)
ed.Char += len(txt[0])
tbe = ls.region(st, ed)
ls.virtualInserted(st, ed)
ls.linesEdited(tbe)
} else {
if ls.lines[st.Line] == nil {
ls.lines[st.Line] = []rune{}
}
eostl := len(ls.lines[st.Line][st.Char:]) // end of starting line
var eost []rune
if eostl > 0 { // save it
eost = make([]rune, eostl)
copy(eost, ls.lines[st.Line][st.Char:])
}
ls.lines[st.Line] = append(ls.lines[st.Line][:st.Char], txt[0]...)
nsz := nl - 1
stln := st.Line + 1
ls.lines = slices.Insert(ls.lines, stln, txt[1:]...)
ed.Line += nsz
ed.Char = len(ls.lines[ed.Line])
if eost != nil {
ls.lines[ed.Line] = append(ls.lines[ed.Line], eost...)
}
tbe = ls.region(st, ed)
ls.insertLineSlices(tbe)
ls.virtualInserted(st, ed)
ls.linesEdited(tbe)
}
ls.setChanged()
return tbe
}
// insertTextRect inserts a rectangle of text defined in given Edit record,
// (e.g., from RegionRect or DeleteRect).
// Returns a copy of the Edit record with an updated timestamp.
// An Undo record is automatically saved depending on Undo.Off setting.
func (ls *Lines) insertTextRect(tbe *textpos.Edit) *textpos.Edit {
re := ls.insertTextRectImpl(tbe)
ls.saveUndo(re)
return tbe
}
func (ls *Lines) insertTextRectImpl(tbe *textpos.Edit) *textpos.Edit {
st := tbe.Region.Start
ed := tbe.Region.End
nlns := (ed.Line - st.Line) + 1
if nlns <= 0 {
return nil
}
ls.setChanged()
// make sure there are enough lines -- add as needed
cln := ls.numLines()
if cln <= ed.Line {
nln := (1 + ed.Line) - cln
tmp := make([][]rune, nln)
ls.lines = append(ls.lines, tmp...)
ie := &textpos.Edit{}
ie.Region.Start.Line = cln - 1
ie.Region.End.Line = ed.Line
ls.linesInserted(ie)
}
nch := (ed.Char - st.Char)
for i := range nlns {
ln := st.Line + i
lr := ls.lines[ln]
ir := tbe.Text[i]
if len(ir) != nch {
panic(fmt.Sprintf("insertTextRectImpl: length of rect line: %d, %d != expected from region: %d", i, len(ir), nch))
}
if len(lr) < st.Char {
lr = append(lr, runes.Repeat([]rune{' '}, st.Char-len(lr))...)
}
nt := slices.Insert(lr, st.Char, ir...)
ls.lines[ln] = nt
}
re := tbe.Clone()
re.Rect = true
re.Delete = false
re.Region.TimeNow()
ls.linesEdited(re)
return re
}
// ReplaceText does DeleteText for given region, and then InsertText at given position
// (typically same as delSt but not necessarily).
// if matchCase is true, then the lexer.MatchCase function is called to match the
// case (upper / lower) of the new inserted text to that of the text being replaced.
// returns the Edit for the inserted text.
// An Undo record is automatically saved depending on Undo.Off setting.
func (ls *Lines) replaceText(delSt, delEd, insPos textpos.Pos, insTxt string, matchCase MatchCase) *textpos.Edit {
if matchCase {
red := ls.region(delSt, delEd)
cur := string(red.ToBytes())
insTxt = lexer.MatchCase(cur, insTxt)
}
if len(insTxt) > 0 {
ls.deleteText(delSt, delEd)
return ls.insertText(insPos, []rune(insTxt))
}
return ls.deleteText(delSt, delEd)
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lines
import (
"slices"
"time"
"cogentcore.org/core/base/fileinfo"
"cogentcore.org/core/base/goscript"
"cogentcore.org/core/text/highlighting"
"cogentcore.org/core/text/parse/lexer"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/textpos"
"cogentcore.org/core/text/token"
"golang.org/x/exp/maps"
)
// setFileInfo sets the syntax highlighting and other parameters
// based on the type of file specified by given [fileinfo.FileInfo].
func (ls *Lines) setFileInfo(info *fileinfo.FileInfo) {
// the file info is kept, for its language: all of it without a file,
// and only the type of content with one, keeping that of the file.
if info != &ls.fileInfo {
if ls.filename == "" {
ls.fileInfo = *info
} else {
ls.fileInfo.Known = info.Known
ls.fileInfo.Cat = info.Cat
ls.fileInfo.Mime = info.Mime
}
}
ls.parseState.SetSrc(string(info.Path), "", info.Known)
ls.Highlighter.Init(info, &ls.parseState)
ls.Settings.ConfigKnown(info.Known)
if ls.numLines() > 0 {
ls.initialMarkup()
ls.startDelayedReMarkup()
}
}
// initialMarkup does the first-pass markup on the file
func (ls *Lines) initialMarkup() {
if !ls.Highlighter.Has || ls.numLines() == 0 {
ls.collectLinks()
ls.layoutViews()
return
}
if goscript.Enabled {
ls.markupDeferred = true
ls.collectLinks()
ls.layoutViews()
return
}
txt := ls.bytes(100)
if ls.Highlighter.UsingParse() {
fs := ls.parseState.Done() // initialize
fs.Src.SetBytes(txt)
}
tags, err := ls.markupTags(txt)
if err == nil {
ls.markupApplyTags(tags)
}
}
// startDelayedReMarkup starts a timer for doing markup after an interval.
func (ls *Lines) startDelayedReMarkup() {
ls.markupDelayMu.Lock()
defer ls.markupDelayMu.Unlock()
if !ls.Highlighter.Has || ls.numLines() == 0 || ls.numLines() > maxMarkupLines {
ls.collectLinks()
ls.layoutViews()
return
}
if ls.markupDeferred {
return
}
if ls.markupDelayTimer != nil {
ls.markupDelayTimer.Stop()
ls.markupDelayTimer = nil
}
ls.markupDelayTimer = time.AfterFunc(markupDelay, func() {
ls.markupDelayMu.Lock()
ls.markupDelayTimer = nil
ls.markupDelayMu.Unlock()
ls.asyncMarkup() // already in a goroutine
})
}
// StartDeferredMarkup starts the syntax highlighting markup in the background
// if it was deferred until the text is first shown, which is done when running
// in JavaScript (see goscript), where it can take a significant amount of time.
// Views call it when they render the text.
func (ls *Lines) StartDeferredMarkup() {
ls.Lock()
if !ls.markupDeferred {
ls.Unlock()
return
}
ls.markupDeferred = false
ls.Unlock()
ls.reMarkup()
}
// stopDelayedReMarkup stops timer for doing markup after an interval
func (ls *Lines) stopDelayedReMarkup() {
ls.markupDelayMu.Lock()
defer ls.markupDelayMu.Unlock()
if ls.markupDelayTimer != nil {
ls.markupDelayTimer.Stop()
ls.markupDelayTimer = nil
}
}
// reMarkup runs re-markup on text in background
func (ls *Lines) reMarkup() {
if !ls.Highlighter.Has || ls.numLines() == 0 || ls.numLines() > maxMarkupLines {
return
}
ls.stopDelayedReMarkup()
go ls.asyncMarkup()
}
// asyncMarkup does the markupTags from a separate goroutine.
// Does not start or end with lock, but acquires at end to apply.
func (ls *Lines) asyncMarkup() {
ls.Lock()
txt := ls.bytes(0)
ls.markupEdits = nil // only accumulate after this point; very rare
ls.Unlock()
tags, err := ls.markupTags(txt)
if err != nil {
return
}
ls.Lock()
ls.markupApplyTags(tags)
ls.Unlock()
ls.sendInputAsync()
}
// markupTags generates the new markup tags from the highligher.
// this is a time consuming step, done via asyncMarkup typically.
// does not require any locking.
func (ls *Lines) markupTags(txt []byte) ([]lexer.Line, error) {
return ls.Highlighter.MarkupTagsAll(txt)
}
// markupApplyEdits applies any edits in markupEdits to the
// tags prior to applying the tags. returns the updated tags.
// For parse-based updates, this is critical for getting full tags
// even if there aren't any markupEdits.
func (ls *Lines) markupApplyEdits(tags []lexer.Line) []lexer.Line {
edits := ls.markupEdits
ls.markupEdits = nil
if ls.Highlighter.UsingParse() {
pfs := ls.parseState.Done()
// The types of the symbols of the file can be resolved from its
// source in another goroutine, under the lock of its symbols.
pfs.SymsMu.Lock()
for _, tbe := range edits {
if tbe.Delete {
stln := tbe.Region.Start.Line
edln := tbe.Region.End.Line
pfs.Src.LinesDeleted(stln, edln)
} else {
stln := tbe.Region.Start.Line + 1
nlns := (tbe.Region.End.Line - tbe.Region.Start.Line)
pfs.Src.LinesInserted(stln, nlns)
}
}
for ln := range tags { // todo: something weird about this -- not working in test
tags[ln] = pfs.LexLine(ln) // does clone, combines comments too
}
pfs.SymsMu.Unlock()
} else {
for _, tbe := range edits {
if tbe.Delete {
stln := tbe.Region.Start.Line
edln := tbe.Region.End.Line
tags = append(tags[:stln], tags[edln:]...)
} else {
stln := tbe.Region.Start.Line + 1
nlns := (tbe.Region.End.Line - tbe.Region.Start.Line)
stln = min(stln, len(tags))
tags = slices.Insert(tags, stln, make([]lexer.Line, nlns)...)
}
}
}
return tags
}
// markupApplyTags applies given tags to current text
// and sets the markup lines. Must be called under Lock.
func (ls *Lines) markupApplyTags(tags []lexer.Line) {
tags = ls.markupApplyEdits(tags)
maxln := min(len(tags), ls.numLines())
for ln := range maxln {
ls.hiTags[ln] = tags[ln]
ls.tags[ln] = ls.adjustedTags(ln)
mu := highlighting.MarkupLineRich(ls.Highlighter.Style, ls.fontStyle, ls.lines[ln], tags[ln], ls.tags[ln])
ls.markup[ln] = mu
}
ls.collectLinks()
ls.layoutViews()
}
// collectLinks finds all the links in markup into links.
func (ls *Lines) collectLinks() {
ls.links = make(map[int][]rich.Hyperlink)
for ln, mu := range ls.markup {
lks := mu.GetLinks()
if len(lks) > 0 {
ls.links[ln] = lks
}
}
}
// layoutViews updates layout of all view lines.
func (ls *Lines) layoutViews() {
for _, vw := range ls.views {
ls.layoutViewLines(vw)
}
}
// markupLines generates markup of given range of lines.
// end is *inclusive* line. Called after edits, under Lock().
// returns true if all lines were marked up successfully.
func (ls *Lines) markupLines(st, ed int) bool {
n := ls.numLines()
if !ls.Highlighter.Has || n == 0 {
return false
}
if ed >= n {
ed = n - 1
}
allgood := true
for ln := st; ln <= ed; ln++ {
ltxt := ls.lines[ln]
mt, err := ls.Highlighter.MarkupTagsLine(ln, ltxt)
var mu rich.Text
if err == nil {
ls.hiTags[ln] = mt
mu = highlighting.MarkupLineRich(ls.Highlighter.Style, ls.fontStyle, ltxt, mt, ls.adjustedTags(ln))
lks := mu.GetLinks()
if len(lks) > 0 {
ls.links[ln] = lks
}
} else {
mu = rich.NewText(ls.fontStyle, ltxt)
allgood = false
}
ls.markup[ln] = mu
}
for _, vw := range ls.views {
ls.layoutViewLinesRange(vw, st, ed)
}
// Now we trigger a background reparse of everything in a separate parse.FilesState
// that gets switched into the current.
return allgood
}
//////// Lines and tags
// linesEdited re-marks-up lines in edit (typically only 1).
func (ls *Lines) linesEdited(tbe *textpos.Edit) {
if tbe == nil {
return
}
st, ed := tbe.Region.Start.Line, tbe.Region.End.Line
for ln := st; ln <= ed; ln++ {
ls.markup[ln] = rich.NewText(ls.fontStyle, ls.lines[ln])
}
ls.markupLines(st, ed)
ls.startDelayedReMarkup()
}
// linesInserted inserts new lines for all other line-based slices
// corresponding to lines inserted in the lines slice.
func (ls *Lines) linesInserted(tbe *textpos.Edit) {
ls.insertLineSlices(tbe)
ls.linesEdited(tbe)
}
// insertLineSlices inserts the per-line data for the lines inserted
// in the given edit, after its start line.
func (ls *Lines) insertLineSlices(tbe *textpos.Edit) {
stln := tbe.Region.Start.Line + 1
nsz := (tbe.Region.End.Line - tbe.Region.Start.Line)
ls.markupEdits = append(ls.markupEdits, tbe)
if nsz > 0 {
tags := ls.splitTags(tbe)
ls.markup = slices.Insert(ls.markup, stln, make([]rich.Text, nsz)...)
ls.tags = slices.Insert(ls.tags, stln, make([]lexer.Line, nsz)...)
ls.tags[stln-1], ls.tags[stln+nsz-1] = tags[0], tags[1]
ls.hiTags = slices.Insert(ls.hiTags, stln, make([]lexer.Line, nsz)...)
ls.virtual = slices.Insert(ls.virtualLinesFor(len(ls.tags)-nsz), stln, make([][]virtualText, nsz)...)
for _, vw := range ls.views {
vw.lineToVline = slices.Insert(vw.lineToVline, stln, make([]int, nsz)...)
}
if ls.Highlighter.UsingParse() {
pfs := ls.parseState.Done()
pfs.SymsMu.Lock() // (see markupApplyEdits)
pfs.Src.LinesInserted(stln, nsz)
pfs.SymsMu.Unlock()
}
}
}
// linesDeleted deletes lines in Markup corresponding to lines
// deleted in Lines text.
func (ls *Lines) linesDeleted(tbe *textpos.Edit) {
ls.markupEdits = append(ls.markupEdits, tbe)
stln := tbe.Region.Start.Line
edln := tbe.Region.End.Line
if edln > stln {
tags := ls.joinTags(tbe)
ls.markup = append(ls.markup[:stln], ls.markup[edln:]...)
ls.tags = append(ls.tags[:stln], ls.tags[edln:]...)
ls.tags[stln] = tags
ls.hiTags = append(ls.hiTags[:stln], ls.hiTags[edln:]...)
if len(ls.virtual) > edln {
ls.virtual = append(ls.virtual[:stln], ls.virtual[edln:]...)
}
if ls.Highlighter.UsingParse() {
pfs := ls.parseState.Done()
pfs.SymsMu.Lock() // (see markupApplyEdits)
pfs.Src.LinesDeleted(stln, edln)
pfs.SymsMu.Unlock()
}
}
// remarkup of start line:
st := tbe.Region.Start.Line
ls.markupLines(st, st)
ls.startDelayedReMarkup()
}
// splitTags returns the tags of the start line of the given edit that
// inserts lines, before it is applied to them, for that line and for the
// last line of the inserted text: the tags after the start of the insert
// go with the rest of the start line, to the end of the inserted text.
// The tags of the other lines stay with their lines, but a split line kept
// all of its tags at their positions, with the text after them moved to
// another line, until they were set again (as the semantic tokens of a
// language server are, after a delay).
func (ls *Lines) splitTags(tbe *textpos.Edit) [2]lexer.Line {
var res [2]lexer.Line
st, ed := tbe.Region.Start, tbe.Region.End
for _, tg := range ls.adjustedTagsLine(ls.tags[st.Line], st.Line) {
var ntr *lexer.Lex
switch {
case tg.End <= st.Char:
ntr = res[0].AddLex(tg.Token, tg.Start, tg.End)
case tg.Start >= st.Char:
ntr = res[1].AddLex(tg.Token, ed.Char+tg.Start-st.Char, ed.Char+tg.End-st.Char)
default: // the part on the start line
ntr = res[0].AddLex(tg.Token, tg.Start, st.Char)
}
ntr.Time.Now() // (after the edit)
}
return res
}
// joinTags returns the tags of the start line of the given edit that
// deletes lines, before it is applied to them, with those of the rest of
// its end line, which joins the start line (see [Lines.splitTags]).
func (ls *Lines) joinTags(tbe *textpos.Edit) lexer.Line {
var res lexer.Line
st, ed := tbe.Region.Start, tbe.Region.End
for _, tg := range ls.adjustedTagsLine(ls.tags[st.Line], st.Line) {
if s := min(tg.Start, st.Char); s < min(tg.End, st.Char) {
res.AddLex(tg.Token, s, min(tg.End, st.Char)).Time.Now()
}
}
for _, tg := range ls.adjustedTagsLine(ls.tags[ed.Line], ed.Line) {
if s := max(tg.Start, ed.Char); s < max(tg.End, ed.Char) {
res.AddLex(tg.Token, st.Char+s-ed.Char, st.Char+max(tg.End, ed.Char)-ed.Char).Time.Now()
}
}
return res
}
// adjustedTags updates tag positions for edits, for given list of tags
func (ls *Lines) adjustedTags(ln int) lexer.Line {
if !ls.isValidLine(ln) {
return nil
}
return ls.adjustedTagsLine(ls.tags[ln], ln)
}
// adjustedTagsLine updates tag positions for edits, for given list of tags
func (ls *Lines) adjustedTagsLine(tags lexer.Line, ln int) lexer.Line {
sz := len(tags)
if sz == 0 {
return nil
}
ntags := make(lexer.Line, 0, sz)
for _, tg := range tags {
reg := textpos.Region{Start: textpos.Pos{Line: ln, Char: tg.Start}, End: textpos.Pos{Line: ln, Char: tg.End}}
reg.Time = tg.Time
reg = ls.undos.AdjustRegion(reg)
if !reg.IsNil() {
ntr := ntags.AddLex(tg.Token, reg.Start.Char, reg.End.Char)
ntr.Time.Now()
}
}
return ntags
}
// lexObjPathString returns the string at given lex, and including prior
// lex-tagged regions that include sequences of PunctSepPeriod and NameTag
// which are used for object paths -- used for e.g., debugger to pull out
// variable expressions that can be evaluated.
func (ls *Lines) lexObjPathString(ln int, lx *lexer.Lex) string {
if !ls.isValidLine(ln) {
return ""
}
lln := len(ls.lines[ln])
if lx.End > lln {
return ""
}
stlx := lexer.ObjPathAt(ls.hiTags[ln], lx)
if stlx.Start >= lx.End {
return ""
}
return string(ls.lines[ln][stlx.Start:lx.End])
}
// hiTagAtPos returns the highlighting (markup) lexical tag at given position
// using current Markup tags, and index, -- could be nil if none or out of range
func (ls *Lines) hiTagAtPos(pos textpos.Pos) (*lexer.Lex, int) {
if !ls.isValidLine(pos.Line) {
return nil, -1
}
return ls.hiTags[pos.Line].AtPos(pos.Char)
}
// inTokenSubCat returns true if the given text position is marked with lexical
// type in given SubCat sub-category.
func (ls *Lines) inTokenSubCat(pos textpos.Pos, subCat token.Tokens) bool {
lx, _ := ls.hiTagAtPos(pos)
return lx != nil && lx.Token.Token.InSubCat(subCat)
}
// inLitString returns true if position is in a string literal
func (ls *Lines) inLitString(pos textpos.Pos) bool {
return ls.inTokenSubCat(pos, token.LitStr)
}
// inTokenCode returns true if position is in a Keyword,
// Name, Operator, or Punctuation.
// This is useful for turning off spell checking in docs
func (ls *Lines) inTokenCode(pos textpos.Pos) bool {
lx, _ := ls.hiTagAtPos(pos)
if lx == nil {
return false
}
return lx.Token.Token.IsCode()
}
func (ls *Lines) braceMatch(pos textpos.Pos) (textpos.Pos, bool) {
if !ls.isValidPos(pos) {
return textpos.Pos{}, false
}
txt := ls.lines[pos.Line]
ch := pos.Char
if ch >= len(txt) {
return textpos.Pos{}, false
}
r := txt[ch]
if r == '{' || r == '}' || r == '(' || r == ')' || r == '[' || r == ']' {
return lexer.BraceMatch(ls.lines, ls.hiTags, r, pos, maxScopeLines)
}
return textpos.Pos{}, false
}
// linkAt returns a hyperlink at given source position, if one exists,
// nil otherwise. this is fast so no problem to call frequently.
func (ls *Lines) linkAt(pos textpos.Pos) *rich.Hyperlink {
ll := ls.links[pos.Line]
if len(ll) == 0 {
return nil
}
for _, l := range ll {
if l.Range.Contains(pos.Char) {
return &l
}
}
return nil
}
// nextLink returns the next hyperlink after given source position,
// if one exists, and the line it is on. nil, -1 otherwise.
func (ls *Lines) nextLink(pos textpos.Pos) (*rich.Hyperlink, int) {
cl := ls.linkAt(pos)
if cl != nil {
pos.Char = cl.Range.End
}
// the first link starting at or after pos on its line, which is past
// the current link if pos is in one.
ll := ls.links[pos.Line]
for _, l := range ll {
if l.Range.Start >= pos.Char {
return &l, pos.Line
}
}
// find next line
lns := maps.Keys(ls.links)
slices.Sort(lns)
for _, ln := range lns {
if ln <= pos.Line {
continue
}
l := &ls.links[ln][0]
return l, ln
}
return nil, -1
}
// prevLink returns the previous hyperlink before given source position,
// if one exists, and the line it is on. nil, -1 otherwise.
func (ls *Lines) prevLink(pos textpos.Pos) (*rich.Hyperlink, int) {
cl := ls.linkAt(pos)
if cl != nil {
if cl.Range.Start == 0 {
pos = ls.moveBackward(pos, 1)
} else {
pos.Char = cl.Range.Start - 1
}
}
// the last link ending at or before pos on its line
ll := ls.links[pos.Line]
for ri := len(ll) - 1; ri >= 0; ri-- {
l := ll[ri]
if l.Range.End <= pos.Char {
return &l, pos.Line
}
}
// find prev line
lns := maps.Keys(ls.links)
slices.Sort(lns)
nl := len(lns)
for i := nl - 1; i >= 0; i-- {
ln := lns[i]
if ln >= pos.Line {
continue
}
ll := ls.links[ln]
return &ll[len(ll)-1], ln
}
return nil, -1
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lines
import (
"fmt"
"cogentcore.org/core/text/textpos"
)
// moveForward moves given source position forward given number of rune steps.
func (ls *Lines) moveForward(pos textpos.Pos, steps int) textpos.Pos {
if !ls.isValidPos(pos) {
return pos
}
for range steps {
pos.Char++
llen := len(ls.lines[pos.Line])
if pos.Char > llen {
if pos.Line < len(ls.lines)-1 {
pos.Char = 0
pos.Line++
} else {
pos.Char = llen
break
}
}
}
return pos
}
// moveBackward moves given source position backward given number of rune steps.
func (ls *Lines) moveBackward(pos textpos.Pos, steps int) textpos.Pos {
if !ls.isValidPos(pos) {
return pos
}
for range steps {
pos.Char--
if pos.Char < 0 {
if pos.Line > 0 {
pos.Line--
pos.Char = len(ls.lines[pos.Line])
} else {
pos.Char = 0
break
}
}
}
return pos
}
// moveForwardWord moves given source position forward given number of word steps.
func (ls *Lines) moveForwardWord(pos textpos.Pos, steps int) textpos.Pos {
if !ls.isValidPos(pos) {
return pos
}
nstep := 0
for nstep < steps {
op := pos.Char
np, ns := textpos.ForwardWord(ls.lines[pos.Line], op, steps)
nstep += ns
pos.Char = np
if np == op || pos.Line >= len(ls.lines)-1 {
break
}
if nstep < steps {
pos.Line++
pos.Char = 0
}
}
return pos
}
// moveBackwardWord moves given source position backward given number of word steps.
func (ls *Lines) moveBackwardWord(pos textpos.Pos, steps int) textpos.Pos {
if !ls.isValidPos(pos) {
return pos
}
nstep := 0
for nstep < steps {
op := pos.Char
np, ns := textpos.BackwardWord(ls.lines[pos.Line], op, steps)
nstep += ns
pos.Char = np
if pos.Line == 0 {
break
}
if nstep < steps {
pos.Line--
pos.Char = len(ls.lines[pos.Line])
}
}
return pos
}
// moveDown moves given source position down given number of display line steps,
// always attempting to use the given column position if the line is long enough.
func (ls *Lines) moveDown(vw *view, pos textpos.Pos, steps, col int) textpos.Pos {
if !ls.isValidPos(pos) {
return pos
}
vp := ls.posToView(vw, pos)
nvp := vp
nvp.Line = ls.viewLinesMoved(vw, vp.Line, steps)
nvp.Char = cellChar(ls.viewLineCells(vw, nvp.Line), col)
dp := ls.posFromView(vw, nvp)
return dp
}
// moveUp moves given source position up given number of display line steps,
// always attempting to use the given column position if the line is long enough.
func (ls *Lines) moveUp(vw *view, pos textpos.Pos, steps, col int) textpos.Pos {
if !ls.isValidPos(pos) {
return pos
}
vp := ls.posToView(vw, pos)
nvp := vp
nvp.Line = ls.viewLinesMoved(vw, vp.Line, -steps)
nvp.Char = cellChar(ls.viewLineCells(vw, nvp.Line), col)
dp := ls.posFromView(vw, nvp)
return dp
}
// viewLinesMoved returns the view line that is the given number of
// steps (negative for up) from the given view line, within range,
// skipping view lines that only contain virtual text.
func (ls *Lines) viewLinesMoved(vw *view, vl, steps int) int {
dir := 1
if steps < 0 {
dir, steps = -1, -steps
}
nl := vl
for steps > 0 {
next := nl + dir
for next >= 0 && next < vw.viewLines && ls.isVirtualViewLine(vw, next) {
next += dir
}
if next < 0 || next >= vw.viewLines {
break
}
nl = next
steps--
}
return nl
}
// moveLineStart moves given source position to start of view line.
func (ls *Lines) moveLineStart(vw *view, pos textpos.Pos) textpos.Pos {
if !ls.isValidPos(pos) {
return pos
}
vp := ls.posToView(vw, pos)
vp.Char = 0
return ls.posFromView(vw, vp)
}
// moveLineEnd moves given source position to end of view line.
func (ls *Lines) moveLineEnd(vw *view, pos textpos.Pos) textpos.Pos {
if !ls.isValidPos(pos) {
return pos
}
vp := ls.posToView(vw, pos)
vp.Char = ls.viewLineLen(vw, vp.Line)
return ls.posFromView(vw, vp)
}
// transposeChar swaps the character at the cursor with the one before it.
func (ls *Lines) transposeChar(vw *view, pos textpos.Pos) bool {
if !ls.isValidPos(pos) {
return false
}
vp := ls.posToView(vw, pos)
pvp := vp
pvp.Char--
if pvp.Char < 0 {
return false
}
ppos := ls.posFromView(vw, pvp)
if pos.Line >= len(ls.lines) || pos.Char >= len(ls.lines[pos.Line]) {
fmt.Println("transpose err:", pos, "lines:", len(ls.lines))
return false
}
chr := ls.lines[pos.Line][pos.Char]
pchr := ls.lines[ppos.Line][ppos.Char]
repl := string([]rune{chr, pchr})
pos.Char++
ls.replaceText(ppos, pos, ppos, repl, ReplaceMatchCase)
return true
}
// wordsOfLine returns the ranges of the words of the given line.
func wordsOfLine(txt []rune) []textpos.Range {
var wds []textpos.Range
st := -1
for i, r := range txt {
brk := textpos.RuneIsWordBreak(r)
switch {
case !brk && st < 0:
st = i
case brk && st >= 0:
wds = append(wds, textpos.Range{Start: st, End: i})
st = -1
}
}
if st >= 0 {
wds = append(wds, textpos.Range{Start: st, End: len(txt)})
}
return wds
}
// transposeWord swaps the word at or before the given position with the
// next word on its line, or with the word before it if it is the last
// word of the line, as in "one tw|o three" to "one three two|". It returns
// the position after the moved words, and false if there are not two
// words to swap.
func (ls *Lines) transposeWord(pos textpos.Pos) (textpos.Pos, bool) {
if !ls.isValidPos(pos) {
return pos, false
}
txt := ls.lines[pos.Line]
wds := wordsOfLine(txt)
if len(wds) < 2 {
return pos, false
}
wi := 0 // the word at or before pos
for i, w := range wds {
if w.Start <= pos.Char {
wi = i
}
}
if wi == len(wds)-1 {
wi--
}
w1, w2 := wds[wi], wds[wi+1]
repl := string(txt[w2.Start:w2.End]) + string(txt[w1.End:w2.Start]) + string(txt[w1.Start:w1.End])
st := textpos.Pos{Line: pos.Line, Char: w1.Start}
ed := textpos.Pos{Line: pos.Line, Char: w2.End}
ls.replaceText(st, ed, st, repl, ReplaceNoMatchCase)
return ed, true
}
// Copyright (c) 2020, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lines
import (
"cogentcore.org/core/base/fileinfo"
"cogentcore.org/core/base/indent"
"cogentcore.org/core/text/parse"
"cogentcore.org/core/text/text"
)
// Settings contains settings for editing text lines.
type Settings struct {
text.EditorSettings
// CommentLine are character(s) that start a single-line comment;
// if empty then multi-line comment syntax will be used.
CommentLine string
// CommentStart are character(s) that start a multi-line comment
// or one that requires both start and end.
CommentStart string
// Commentend are character(s) that end a multi-line comment
// or one that requires both start and end.
CommentEnd string
}
// CommentStrings returns the comment start and end strings,
// using line-based CommentLn first if set and falling back
// on multi-line / general purpose start / end syntax.
func (tb *Settings) CommentStrings() (comst, comed string) {
comst = tb.CommentLine
if comst == "" {
comst = tb.CommentStart
comed = tb.CommentEnd
}
return
}
// IndentChar returns the indent character based on SpaceIndent option
func (tb *Settings) IndentChar() indent.Character {
if tb.SpaceIndent {
return indent.Space
}
return indent.Tab
}
// ConfigKnown configures options based on the supported language info in parse.
// Returns true if supported.
func (tb *Settings) ConfigKnown(sup fileinfo.Known) bool {
if sup == fileinfo.Unknown {
return false
}
lp, ok := parse.StandardLanguageProperties[sup]
if !ok {
return false
}
tb.CommentLine = lp.CommentLn
tb.CommentStart = lp.CommentSt
tb.CommentEnd = lp.CommentEd
for _, flg := range lp.Flags {
switch flg {
case parse.IndentSpace:
tb.SpaceIndent = true
case parse.IndentTab:
tb.SpaceIndent = false
}
}
return true
}
// KnownComments returns the comment strings for supported file types,
// and returns the standard C-style comments otherwise.
func KnownComments(fpath string) (comLn, comSt, comEd string) {
comLn = "//"
comSt = "/*"
comEd = "*/"
mtyp, _, err := fileinfo.MimeFromFile(fpath)
if err != nil {
return
}
sup := fileinfo.MimeKnown(mtyp)
if sup == fileinfo.Unknown {
return
}
lp, ok := parse.StandardLanguageProperties[sup]
if !ok {
return
}
comLn = lp.CommentLn
comSt = lp.CommentSt
comEd = lp.CommentEd
return
}
// Copyright (c) 2020, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lines
import (
"fmt"
"runtime/debug"
"sync"
"time"
"cogentcore.org/core/text/textpos"
)
// UndoTrace; set to true to get a report of undo actions
var UndoTrace = false
// UndoGroupDelay is the amount of time above which a new group
// is started, for grouping undo events
var UndoGroupDelay = 250 * time.Millisecond
// Undo is the textview.Buf undo manager
type Undo struct {
// if true, saving and using undos is turned off (e.g., inactive buffers)
Off bool
// undo stack of edits
Stack []*textpos.Edit
// undo stack of *undo* edits -- added to whenever an Undo is done -- for emacs-style undo
UndoStack []*textpos.Edit
// undo position in stack
Pos int
// group counter
Group int
// State is the current state of the text, as a number that is the same
// for the same text in the history of the undo stack: each new edit
// makes a new state, and undoing and redoing return to the states before
// and after edits, also in the emacs mode, in which undoing the undos
// returns to the states before them. It is 0 at the start of the stack.
State int
// States are the states of the text after the edits in Stack.
States []int
// UndoStates are the states of the text after the edits in UndoStack.
UndoStates []int
// lastState is the number of the last new state.
lastState int
// mutex protecting all updates
Mu sync.Mutex `json:"-" xml:"-"`
}
// NewGroup increments the Group counter so subsequent undos will be grouped separately
func (un *Undo) NewGroup() {
un.Mu.Lock()
un.Group++
un.Mu.Unlock()
}
// Reset clears all undo records
func (un *Undo) Reset() {
un.Pos = 0
un.Group = 0
un.Stack = nil
un.UndoStack = nil
un.State = 0
un.States = nil
un.UndoStates = nil
un.lastState = 0
}
// CurrentState returns the current [Undo.State] of the text.
func (un *Undo) CurrentState() int {
un.Mu.Lock()
defer un.Mu.Unlock()
return un.State
}
// stateAt returns the state of the text at the given position in the stack,
// which is that after the edit before it, or 0 at the start.
func (un *Undo) stateAt(pos int) int {
if pos == 0 {
return 0
}
return un.States[pos-1]
}
// Save saves given edit to undo stack, with current group marker unless timer interval
// exceeds UndoGroupDelay since last item.
func (un *Undo) Save(tbe *textpos.Edit) {
if un.Off {
return
}
un.Mu.Lock()
defer un.Mu.Unlock()
if un.Pos < len(un.Stack) {
if UndoTrace {
fmt.Printf("Undo: resetting to pos: %v len was: %v\n", un.Pos, len(un.Stack))
}
un.Stack = un.Stack[:un.Pos]
un.States = un.States[:un.Pos]
}
if len(un.Stack) > 0 {
since := tbe.Region.Since(&un.Stack[len(un.Stack)-1].Region)
if since > UndoGroupDelay {
un.Group++
if UndoTrace {
fmt.Printf("Undo: incrementing group to: %v since: %v\n", un.Group, since)
}
}
}
tbe.Group = un.Group
if UndoTrace {
fmt.Printf("Undo: save to pos: %v: group: %v\n->\t%v\n", un.Pos, un.Group, string(tbe.ToBytes()))
}
un.Stack = append(un.Stack, tbe)
un.lastState++
un.State = un.lastState
un.States = append(un.States, un.State)
un.Pos = len(un.Stack)
}
// UndoPop pops the top item off of the stack for use in Undo. returns nil if none.
func (un *Undo) UndoPop() *textpos.Edit {
if un.Off {
return nil
}
un.Mu.Lock()
defer un.Mu.Unlock()
if un.Pos == 0 {
return nil
}
un.Pos--
un.State = un.stateAt(un.Pos)
tbe := un.Stack[un.Pos]
if UndoTrace {
fmt.Printf("Undo: UndoPop of Gp: %v pos: %v delete? %v at: %v text: %v\n", un.Group, un.Pos, tbe.Delete, tbe.Region, string(tbe.ToBytes()))
}
return tbe
}
// UndoPopIfGroup pops the top item off of the stack if it is the same as given group
func (un *Undo) UndoPopIfGroup(gp int) *textpos.Edit {
if un.Off {
return nil
}
un.Mu.Lock()
defer un.Mu.Unlock()
if un.Pos == 0 {
return nil
}
tbe := un.Stack[un.Pos-1]
if tbe.Group != gp {
return nil
}
un.Pos--
un.State = un.stateAt(un.Pos)
if UndoTrace {
fmt.Printf("Undo: UndoPopIfGroup of Gp: %v pos: %v delete? %v at: %v text: %v\n", un.Group, un.Pos, tbe.Delete, tbe.Region, string(tbe.ToBytes()))
}
return tbe
}
// SaveUndo saves given edit to UndoStack (stack of undoes that have have undone..)
// for emacs mode, with the state that it returns to, which is the current one.
func (un *Undo) SaveUndo(tbe *textpos.Edit) {
un.UndoStack = append(un.UndoStack, tbe)
un.UndoStates = append(un.UndoStates, un.State)
}
// UndoStackSave if EmacsUndo mode is active, saves the UndoStack
// to the regular Undo stack, at the end, and moves undo to the very end.
// Undo is a constant stream..
func (un *Undo) UndoStackSave() {
if un.Off {
return
}
un.Mu.Lock()
defer un.Mu.Unlock()
if len(un.UndoStack) == 0 {
return
}
un.Stack = append(un.Stack, un.UndoStack...)
un.States = append(un.States, un.UndoStates...)
un.Pos = len(un.Stack)
un.UndoStack = nil
un.UndoStates = nil
if UndoTrace {
fmt.Printf("Undo: undo stack saved to main stack, new pos: %v\n", un.Pos)
}
}
// RedoNext returns the current item on Stack for Redo, and increments the position
// returns nil if at end of stack.
func (un *Undo) RedoNext() *textpos.Edit {
if un.Off {
return nil
}
un.Mu.Lock()
defer un.Mu.Unlock()
if un.Pos >= len(un.Stack) {
return nil
}
tbe := un.Stack[un.Pos]
if UndoTrace {
fmt.Printf("Undo: RedoNext of Gp: %v at pos: %v delete? %v at: %v text: %v\n", un.Group, un.Pos, tbe.Delete, tbe.Region, string(tbe.ToBytes()))
}
un.State = un.States[un.Pos]
un.Pos++
return tbe
}
// RedoNextIfGroup returns the current item on Stack for Redo if it is same group
// and increments the position. returns nil if at end of stack.
func (un *Undo) RedoNextIfGroup(gp int) *textpos.Edit {
if un.Off {
return nil
}
un.Mu.Lock()
defer un.Mu.Unlock()
if un.Pos >= len(un.Stack) {
return nil
}
tbe := un.Stack[un.Pos]
if tbe.Group != gp {
return nil
}
if UndoTrace {
fmt.Printf("Undo: RedoNextIfGroup of Gp: %v at pos: %v delete? %v at: %v text: %v\n", un.Group, un.Pos, tbe.Delete, tbe.Region, string(tbe.ToBytes()))
}
un.State = un.States[un.Pos]
un.Pos++
return tbe
}
// AdjustRegion adjusts given text region for any edits that
// have taken place since time stamp on region (using the Undo stack).
// If region was wholly within a deleted region, then RegionNil will be
// returned -- otherwise it is clipped appropriately as function of deletes.
func (un *Undo) AdjustRegion(reg textpos.Region) textpos.Region {
if un.Off {
return reg
}
un.Mu.Lock()
defer un.Mu.Unlock()
for _, utbe := range un.Stack {
reg = utbe.AdjustRegion(reg)
if reg == (textpos.Region{}) {
return reg
}
}
return reg
}
//////// Lines api
// saveUndo saves given edit to undo stack.
func (ls *Lines) saveUndo(tbe *textpos.Edit) {
if tbe == nil {
return
}
ls.undos.Save(tbe)
}
// undo undoes next group of items on the undo stack
func (ls *Lines) undo() []*textpos.Edit {
tbe := ls.undos.UndoPop()
if tbe == nil {
// note: could clear the changed flag on tbe == nil in parent
return nil
}
stgp := tbe.Group
var eds []*textpos.Edit
for {
if tbe.Rect {
if tbe.Delete {
utbe := ls.insertTextRectImpl(tbe)
utbe.Group = stgp + tbe.Group
if ls.Settings.EmacsUndo {
ls.undos.SaveUndo(utbe)
}
eds = append(eds, utbe)
} else {
utbe := ls.deleteTextRectImpl(tbe.Region.Start, tbe.Region.End)
utbe.Group = stgp + tbe.Group
if ls.Settings.EmacsUndo {
ls.undos.SaveUndo(utbe)
}
eds = append(eds, utbe)
}
} else {
if tbe.Delete {
utbe := ls.insertTextImpl(tbe.Region.Start, tbe.Text)
utbe.Group = stgp + tbe.Group
if ls.Settings.EmacsUndo {
ls.undos.SaveUndo(utbe)
}
eds = append(eds, utbe)
} else {
if !ls.isValidPos(tbe.Region.End) {
fmt.Println("lines.undo: invalid end region for undo. stack:", len(ls.undos.Stack), "tbe:", tbe)
debug.PrintStack()
break
}
utbe := ls.deleteTextImpl(tbe.Region.Start, tbe.Region.End)
utbe.Group = stgp + tbe.Group
if ls.Settings.EmacsUndo {
ls.undos.SaveUndo(utbe)
}
eds = append(eds, utbe)
}
}
tbe = ls.undos.UndoPopIfGroup(stgp)
if tbe == nil {
break
}
}
return eds
}
// redo redoes next group of items on the undo stack,
// and returns the last record, nil if no more
func (ls *Lines) redo() []*textpos.Edit {
tbe := ls.undos.RedoNext()
if tbe == nil {
return nil
}
var eds []*textpos.Edit
stgp := tbe.Group
for {
if tbe.Rect {
if tbe.Delete {
ls.deleteTextRectImpl(tbe.Region.Start, tbe.Region.End)
} else {
ls.insertTextRectImpl(tbe)
}
} else {
if tbe.Delete {
ls.deleteTextImpl(tbe.Region.Start, tbe.Region.End)
} else {
ls.insertTextImpl(tbe.Region.Start, tbe.Text)
}
}
eds = append(eds, tbe)
tbe = ls.undos.RedoNextIfGroup(stgp)
if tbe == nil {
break
}
}
return eds
}
// Copyright (c) 2020, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lines
import (
"bufio"
"bytes"
"io"
"log/slog"
"os"
"strings"
"cogentcore.org/core/base/indent"
"cogentcore.org/core/text/highlighting"
"cogentcore.org/core/text/parse/lexer"
"cogentcore.org/core/text/runes"
"cogentcore.org/core/text/textpos"
"cogentcore.org/core/text/token"
)
// BytesToLineStrings returns []string lines from []byte input.
// If addNewLn is true, each string line has a \n appended at end.
func BytesToLineStrings(txt []byte, addNewLn bool) []string {
lns := bytes.Split(txt, []byte("\n"))
nl := len(lns)
if nl == 0 {
return nil
}
str := make([]string, nl)
for i, l := range lns {
str[i] = string(l)
if addNewLn {
str[i] += "\n"
}
}
return str
}
// StringLinesToByteLines returns [][]byte lines from []string lines
func StringLinesToByteLines(str []string) [][]byte {
nl := len(str)
bl := make([][]byte, nl)
for i, s := range str {
bl[i] = []byte(s)
}
return bl
}
// FileBytes returns the bytes of given file.
func FileBytes(fpath string) ([]byte, error) {
fp, err := os.Open(fpath)
if err != nil {
slog.Error(err.Error())
return nil, err
}
txt, err := io.ReadAll(fp)
fp.Close()
if err != nil {
slog.Error(err.Error())
return nil, err
}
return txt, nil
}
// FileRegionBytes returns the bytes of given file within given
// start / end lines, either of which might be 0 (in which case full file
// is returned).
// If preComments is true, it also automatically includes any comments
// that might exist just prior to the start line if stLn is > 0, going back
// a maximum of lnBack lines.
func FileRegionBytes(fpath string, stLn, edLn int, preComments bool, lnBack int) []byte {
txt, err := FileBytes(fpath)
if err != nil {
return nil
}
if stLn == 0 && edLn == 0 {
return txt
}
lns := bytes.Split(txt, []byte("\n"))
nln := len(lns)
if edLn > 0 && edLn > stLn && edLn < nln {
el := min(edLn+1, nln-1)
lns = lns[:el]
}
if preComments && stLn > 0 && stLn < nln {
comLn, comSt, comEd := KnownComments(fpath)
stLn = PreCommentStart(lns, stLn, comLn, comSt, comEd, lnBack)
}
if stLn > 0 && stLn < len(lns) {
lns = lns[stLn:]
}
txt = bytes.Join(lns, []byte("\n"))
txt = append(txt, '\n')
return txt
}
// PreCommentStart returns the starting line for comment line(s) that just
// precede the given stLn line number within the given lines of bytes,
// using the given line-level and block start / end comment chars.
// returns stLn if nothing found. Only looks back a total of lnBack lines.
func PreCommentStart(lns [][]byte, stLn int, comLn, comSt, comEd string, lnBack int) int {
comLnb := []byte(strings.TrimSpace(comLn))
comStb := []byte(strings.TrimSpace(comSt))
comEdb := []byte(strings.TrimSpace(comEd))
nback := 0
gotEd := false
for i := stLn - 1; i >= 0; i-- {
l := lns[i]
fl := bytes.Fields(l)
if len(fl) == 0 {
return i + 1
}
if !gotEd {
for _, ff := range fl {
if bytes.Equal(ff, comEdb) {
gotEd = true
break
}
}
if gotEd {
continue
}
}
if bytes.Equal(fl[0], comStb) {
return i
}
if !bytes.Equal(fl[0], comLnb) && !gotEd {
return i + 1
}
nback++
if nback > lnBack {
return i
}
}
// the comment lines go back to the first line
return 0
}
// CountWordsLinesRegion counts the number of words (aka Fields, space-separated strings)
// and lines in given region of source (lines = 1 + End.Line - Start.Line)
func CountWordsLinesRegion(src [][]rune, reg textpos.Region) (words, lines int) {
lns := len(src)
mx := min(lns-1, reg.End.Line)
for ln := reg.Start.Line; ln <= mx; ln++ {
sln := src[ln]
if ln == reg.Start.Line {
sln = sln[reg.Start.Char:]
} else if ln == reg.End.Line {
sln = sln[:min(reg.End.Char, len(sln))]
}
flds := strings.Fields(string(sln))
words += len(flds)
}
lines = 1 + (reg.End.Line - reg.Start.Line)
return
}
// CountWordsLines counts the number of words (aka Fields, space-separated strings)
// and lines given io.Reader input
func CountWordsLines(reader io.Reader) (words, lines int) {
scan := bufio.NewScanner(reader)
for scan.Scan() {
flds := bytes.Fields(scan.Bytes())
words += len(flds)
lines++
}
return
}
//////// Indenting
// see parse/lexer/indent.go for support functions
// indentLine indents line by given number of tab stops, using tabs or spaces,
// for given tab size (if using spaces) -- either inserts or deletes to reach target.
// Returns edit record for any change.
func (ls *Lines) indentLine(ln, ind int) *textpos.Edit {
tabSz := ls.Settings.TabSize
ichr := indent.Tab
if ls.Settings.SpaceIndent {
ichr = indent.Space
}
curind, _ := lexer.LineIndent(ls.lines[ln], tabSz)
if ind > curind {
txt := runes.SetFromBytes([]rune{}, indent.Bytes(ichr, ind-curind, tabSz))
return ls.insertText(textpos.Pos{Line: ln}, txt)
} else if ind < curind {
spos := indent.Len(ichr, ind, tabSz)
cpos := indent.Len(ichr, curind, tabSz)
return ls.deleteText(textpos.Pos{Line: ln, Char: spos}, textpos.Pos{Line: ln, Char: cpos})
}
return nil
}
// autoIndent indents given line to the level of the prior line, adjusted
// appropriately if the current line starts with one of the given un-indent
// strings, or the prior line ends with one of the given indent strings.
// Returns any edit that took place (could be nil), along with the auto-indented
// level and character position for the indent of the current line.
func (ls *Lines) autoIndent(ln int) (tbe *textpos.Edit, indLev, chPos int) {
tabSz := ls.Settings.TabSize
lp := highlighting.ParseLanguage(ls.parseState.Known)
var pInd, delInd int
if lp != nil {
pInd, delInd, _, _ = lp.Lang.IndentLine(&ls.parseState, ls.lines, ls.hiTags, ln, tabSz)
} else {
pInd, delInd, _, _ = lexer.BracketIndentLine(ls.lines, ls.hiTags, ln, tabSz)
}
ichr := ls.Settings.IndentChar()
indLev = max(pInd+delInd, 0)
chPos = indent.Len(ichr, indLev, tabSz)
tbe = ls.indentLine(ln, indLev)
return
}
// autoIndentRegion does auto-indent over given region; end is *exclusive*
func (ls *Lines) autoIndentRegion(start, end int) {
end = min(ls.numLines(), end)
for ln := start; ln < end; ln++ {
ls.autoIndent(ln)
}
}
// commentStart returns the char index where the comment
// starts on given line, -1 if no comment.
func (ls *Lines) commentStart(ln int) int {
if !ls.isValidLine(ln) {
return -1
}
comst, _ := ls.Settings.CommentStrings()
if comst == "" {
return -1
}
return runes.Index(ls.lines[ln], []rune(comst))
}
// inComment returns true if the given text position is within
// a commented region.
func (ls *Lines) inComment(pos textpos.Pos) bool {
if ls.inTokenSubCat(pos, token.Comment) {
return true
}
cs := ls.commentStart(pos.Line)
if cs < 0 {
return false
}
return pos.Char > cs
}
// lineCommented returns true if the given line is a full-comment
// line (i.e., starts with a comment).
func (ls *Lines) lineCommented(ln int) bool {
if !ls.isValidLine(ln) {
return false
}
tags := ls.hiTags[ln]
if len(tags) == 0 {
return false
}
return tags[0].Token.Token.InCat(token.Comment)
}
// commentRegion inserts comment marker on given lines; end is *exclusive*.
func (ls *Lines) commentRegion(start, end int) {
tabSz := ls.Settings.TabSize
ch := 0
ind, _ := lexer.LineIndent(ls.lines[start], tabSz)
if ind > 0 {
if ls.Settings.SpaceIndent {
ch = ls.Settings.TabSize * ind
} else {
ch = ind
}
}
comst, comed := ls.Settings.CommentStrings()
if comst == "" {
// log.Printf("text.Lines: attempt to comment region without any comment syntax defined")
comst = "// "
return
}
eln := min(ls.numLines(), end)
ncom := 0
nln := eln - start
for ln := start; ln < eln; ln++ {
if ls.lineCommented(ln) {
ncom++
}
}
trgln := max(nln-2, 1)
doCom := true
if ncom >= trgln {
doCom = false
}
rcomst := []rune(comst)
rcomed := []rune(comed)
for ln := start; ln < eln; ln++ {
if doCom {
ipos, ok := ls.validCharPos(textpos.Pos{Line: ln, Char: ch})
if ok {
ls.insertText(ipos, rcomst)
if comed != "" {
lln := len(ls.lines[ln]) // automatically ok
ls.insertText(textpos.Pos{Line: ln, Char: lln}, rcomed)
}
}
} else {
idx := ls.commentStart(ln)
if idx >= 0 {
ls.deleteText(textpos.Pos{Line: ln, Char: idx}, textpos.Pos{Line: ln, Char: idx + len(comst)})
}
if comed != "" {
idx := runes.IndexFold(ls.lines[ln], []rune(comed))
if idx >= 0 {
ls.deleteText(textpos.Pos{Line: ln, Char: idx}, textpos.Pos{Line: ln, Char: idx + len(comed)})
}
}
}
}
}
// joinParaLines merges sequences of lines with hard returns forming paragraphs,
// separated by blank lines, into a single line per paragraph,
// within the given line regions; endLine is *inclusive*.
func (ls *Lines) joinParaLines(startLine, endLine int) {
// current end of region being joined == last blank line
curEd := endLine
for ln := endLine; ln >= startLine; ln-- { // reverse order
lr := ls.lines[ln]
lrt := runes.TrimSpace(lr)
if len(lrt) == 0 || ln == startLine {
if ln < curEd-1 {
stp := textpos.Pos{Line: ln + 1}
if ln == startLine {
stp.Line--
}
ep := textpos.Pos{Line: curEd - 1}
if curEd == endLine {
ep.Line = curEd
}
eln := ls.lines[ep.Line]
ep.Char = len(eln)
trt := runes.Join(ls.lines[stp.Line:ep.Line+1], []rune(" "))
ls.replaceText(stp, ep, stp, string(trt), ReplaceNoMatchCase)
}
curEd = ln
}
}
}
// tabsToSpacesLine replaces tabs with spaces in the given line.
func (ls *Lines) tabsToSpacesLine(ln int) {
tabSz := ls.Settings.TabSize
lr := ls.lines[ln]
st := textpos.Pos{Line: ln}
ed := textpos.Pos{Line: ln}
i := 0
for {
if i >= len(lr) {
break
}
r := lr[i]
if r == '\t' {
po := i % tabSz
nspc := tabSz - po
st.Char = i
ed.Char = i + 1
ls.replaceText(st, ed, st, indent.Spaces(1, nspc), ReplaceNoMatchCase)
i += nspc
lr = ls.lines[ln]
} else {
i++
}
}
}
// tabsToSpaces replaces tabs with spaces over given region; end is *exclusive*.
func (ls *Lines) tabsToSpaces(start, end int) {
end = min(ls.numLines(), end)
for ln := start; ln < end; ln++ {
ls.tabsToSpacesLine(ln)
}
}
// spacesToTabsLine replaces spaces with tabs in the given line.
func (ls *Lines) spacesToTabsLine(ln int) {
tabSz := ls.Settings.TabSize
lr := ls.lines[ln]
st := textpos.Pos{Line: ln}
ed := textpos.Pos{Line: ln}
i := 0
nspc := 0
for {
if i >= len(lr) {
break
}
r := lr[i]
if r == ' ' {
nspc++
if nspc == tabSz {
st.Char = i - (tabSz - 1)
ed.Char = i + 1
ls.replaceText(st, ed, st, "\t", ReplaceNoMatchCase)
i -= tabSz - 1
lr = ls.lines[ln]
nspc = 0
} else {
i++
}
} else {
nspc = 0
i++
}
}
}
// spacesToTabs replaces tabs with spaces over given region; end is *exclusive*
func (ls *Lines) spacesToTabs(start, end int) {
end = min(ls.numLines(), end)
for ln := start; ln < end; ln++ {
ls.spacesToTabsLine(ln)
}
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lines
import (
"cogentcore.org/core/events"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/textpos"
)
// view provides a view onto a shared [Lines] text buffer,
// with a representation of view lines that are the wrapped versions of
// the original [Lines.lines] source lines, with wrapping according to
// the view width. Views are managed by the Lines.
type view struct {
// id is the unique id of the view in its [Lines].
id int
// width is the current line width in rune characters, used for line wrapping.
width int
// viewLines is the total number of line-wrapped lines.
viewLines int
// vlineStarts are the positions of the start of each view line, as the
// source line and the display char position in that line, which includes
// any [VirtualText] (see [Lines.srcToDisplay]). This slice is viewLines in length.
vlineStarts []textpos.Pos
// markup is the view-specific version of the [Lines.markup] markup for
// each view line (len = viewLines).
markup []rich.Text
// lineToVline maps the source [Lines.lines] indexes to the wrapped
// viewLines. Each slice value contains the index into the viewLines space,
// such that vlineStarts of that index is the start of the original source line.
// Any subsequent vlineStarts with the same Line and Char > 0 following this
// starting line represent additional wrapped content from the same source line.
lineToVline []int
// listeners is used for sending Change, Input, and Close events to views.
listeners events.Listeners
// runAsync, if set, runs the listeners for an event that is sent from
// a background goroutine (see [Lines.SetAsyncRunner]).
runAsync func(f func())
}
// viewLineLen returns the length in chars (runes) of the given view line.
func (ls *Lines) viewLineLen(vw *view, vl int) int {
n := len(vw.vlineStarts)
if n == 0 {
return 0
}
if vl < 0 {
vl = 0
}
if vl >= n {
vl = n - 1
}
vs := vw.vlineStarts[vl]
sl := ls.displayLineLen(vw, vs.Line)
if vl == vw.viewLines-1 {
return sl + 1 - vs.Char
}
np := vw.vlineStarts[vl+1]
if np.Line == vs.Line {
return np.Char - vs.Char
}
return sl + 1 - vs.Char
}
// viewLinesRange returns the start and end view lines for given
// source line number, using only lineToVline. ed is inclusive.
func (ls *Lines) viewLinesRange(vw *view, ln int) (st, ed int) {
n := len(vw.lineToVline)
st = vw.lineToVline[ln]
if ln+1 < n {
ed = vw.lineToVline[ln+1] - 1
} else {
ed = vw.viewLines - 1
}
return
}
// validViewLine returns a view line that is in range based on given
// source line.
func (ls *Lines) validViewLine(vw *view, ln int) int {
if ln < 0 {
return 0
} else if ln >= len(vw.lineToVline) {
return vw.viewLines - 1
}
return vw.lineToVline[ln]
}
// posToView returns the view position in terms of viewLines and Char
// offset into that view line for given source line, char position.
// Is robust to out-of-range positions.
func (ls *Lines) posToView(vw *view, pos textpos.Pos) textpos.Pos {
if pos.Line < 0 || pos.Line >= len(ls.lines) {
return ls.displayToView(vw, pos)
}
pos.Char = ls.srcToDisplay(vw, pos.Line, pos.Char)
vp := ls.displayToView(vw, pos)
// A position at the start of a view line that starts with virtual
// text is shown at the end of the previous view line, as the cursor
// is shown before virtual text.
if vp.Char == 0 && vp.Line > 0 && vp.Line < len(vw.vlineStarts) {
prev := vw.vlineStarts[vp.Line-1]
if prev.Line == pos.Line && ls.isVirtualDisplay(vw, pos.Line, pos.Char) {
return textpos.Pos{Line: vp.Line - 1, Char: pos.Char - prev.Char}
}
}
return vp
}
// displayToView returns the view position for the given position
// in terms of the source line and display char in that line.
func (ls *Lines) displayToView(vw *view, pos textpos.Pos) textpos.Pos {
vp := pos
vl := ls.validViewLine(vw, pos.Line)
vp.Line = vl
vlen := ls.viewLineLen(vw, vl)
if pos.Char < vlen {
return vp
}
nl := vl + 1
if nl == vw.viewLines {
vp.Char = pos.Char
return vp
}
for nl < vw.viewLines && vw.vlineStarts[nl].Line == pos.Line {
np := vw.vlineStarts[nl]
vlen := ls.viewLineLen(vw, nl)
if pos.Char >= np.Char && pos.Char < np.Char+vlen {
np.Line = nl
np.Char = pos.Char - np.Char
return np
}
nl++
}
return vp
}
// posFromView returns the original source position from given
// view position in terms of viewLines and Char offset into that view line.
// If the Char position is beyond the end of the line, it returns the
// end of the given line.
func (ls *Lines) posFromView(vw *view, vp textpos.Pos) textpos.Pos {
n := len(vw.vlineStarts)
if n == 0 {
return textpos.Pos{}
}
vl := vp.Line
if vl < 0 {
vl = 0
} else if vl >= n {
vl = n - 1
}
vlen := ls.viewLineLen(vw, vl)
if vlen == 0 {
vlen = 1
}
sp := vw.vlineStarts[vl]
if vl+1 < n && vw.vlineStarts[vl+1].Line == sp.Line && ls.isVirtualDisplay(vw, sp.Line, vw.vlineStarts[vl+1].Char) {
vlen++ // the end of the view line is before the virtual text that starts the next one
}
vp.Char = min(vp.Char, vlen-1)
pos := vp
pos.Line = sp.Line
pos.Char = ls.displayToSrc(vw, sp.Line, sp.Char+vp.Char)
return pos
}
// regionToView converts the given region in source coordinates into view coordinates.
// The text of a region starts after any virtual text at its start, which
// is not in it, as the cursor is shown before it.
func (ls *Lines) regionToView(vw *view, reg textpos.Region) textpos.Region {
st := ls.posToView(vw, reg.Start)
ed := ls.posToView(vw, reg.End)
if n := ls.virtualLenAt(vw, reg.Start); n > 0 && reg.Start.IsLess(reg.End) {
d := ls.srcToDisplay(vw, reg.Start.Line, reg.Start.Char) + n
st = ls.displayToView(vw, textpos.Pos{Line: reg.Start.Line, Char: d})
}
return textpos.Region{Start: st, End: ed}
}
// regionFromView converts the given region in view coordinates into source coordinates.
func (ls *Lines) regionFromView(vw *view, reg textpos.Region) textpos.Region {
return textpos.Region{Start: ls.posFromView(vw, reg.Start), End: ls.posFromView(vw, reg.End)}
}
// viewLineRegion returns the region in view coordinates of the given view line.
func (ls *Lines) viewLineRegion(vw *view, vln int) textpos.Region {
llen := ls.viewLineLen(vw, vln)
return textpos.Region{Start: textpos.Pos{Line: vln}, End: textpos.Pos{Line: vln, Char: llen}}
}
// initViews ensures that the views map is constructed.
func (ls *Lines) initViews() {
if ls.views == nil {
ls.views = make(map[int]*view)
}
}
// view returns view for given unique view id. nil if not found.
func (ls *Lines) view(vid int) *view {
ls.initViews()
return ls.views[vid]
}
// newView makes a new view with next available id, using given initial width.
func (ls *Lines) newView(width int) (*view, int) {
ls.initViews()
mxi := 0
for i := range ls.views {
mxi = max(i, mxi)
}
id := mxi + 1
vw := &view{id: id, width: width}
ls.views[id] = vw
ls.layoutViewLines(vw)
return vw, id
}
// deleteView deletes view with given view id.
func (ls *Lines) deleteView(vid int) {
delete(ls.views, vid)
}
// ViewMarkupLine returns the markup [rich.Text] line for given view and
// view line number. This must be called under the mutex Lock! It is the
// api for rendering the lines.
func (ls *Lines) ViewMarkupLine(vid, line int) rich.Text {
vw := ls.view(vid)
if line >= 0 && len(vw.markup) > line {
return vw.markup[line]
}
return rich.Text{}
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lines
import (
"slices"
"cogentcore.org/core/events"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/runes"
"cogentcore.org/core/text/textpos"
)
// VirtualText is display-only text that is shown in the views of [Lines]
// at a source position, such as the composition of an input method,
// language server inlay hints, or suggested completions. It is not part
// of the text: it is not saved, edited, undone, searched, or sent to
// language servers, and the cursor cannot be positioned within it.
//
// Text typed at the position goes before the virtual text, which stays
// attached to the source text after it, and the cursor at the position
// is shown before it.
type VirtualText struct {
// Pos is the source position that the text is shown at.
Pos textpos.Pos
// Text is the styled text, which can contain newlines, in which case
// the following lines are shown as separate lines in the view,
// with the source text after Pos following the last line.
// It can have multiple spans with different styles, such as the
// clauses of a composition, or the parts of an inlay hint.
Text rich.Text
}
// virtualText is a [VirtualText] as stored for its source line.
type virtualText struct {
// char is the source char position in the line.
char int
// lines are the lines of the text, split at newlines.
lines []rich.Text
// layer is the layer of the text (see [Lines.SetVirtualText]).
layer string
// view is the view that the text is shown in, or -1 for all views.
view int
}
// len returns the number of display chars of the text,
// which does not include newlines.
func (vt *virtualText) len() int {
n := 0
for _, l := range vt.lines {
n += l.Len()
}
return n
}
// shownIn returns whether the text is shown in the given view.
func (vt *virtualText) shownIn(vw *view) bool {
return vt.view < 0 || vt.view == vw.id
}
// SetVirtualText replaces all of the virtual text in the given layer for
// the given view (or all views if vid < 0) with the given texts, such as
// "ime", "inlay" or "suggestion". Texts at the same position are shown
// in order. The views are laid out again and sent a virtual text event
// (see [Lines.OnVirtualText]), but not a Change or Input event, as the
// text has not changed.
func (ls *Lines) SetVirtualText(layer string, vid int, vts ...VirtualText) {
ls.Lock()
ls.setVirtualText(layer, vid, vts...)
ls.Unlock()
ls.sendVirtualText()
}
// ClearVirtualText removes all of the virtual text in the given
// layer for the given view (or all views if vid < 0).
func (ls *Lines) ClearVirtualText(layer string, vid int) {
ls.SetVirtualText(layer, vid)
}
// VirtualText returns the virtual text in the given layer for the
// given view (or all views if vid < 0), with positions updated for any
// edits since it was set, in order.
func (ls *Lines) VirtualText(layer string, vid int) []VirtualText {
ls.Lock()
defer ls.Unlock()
var vts []VirtualText
for ln, lvt := range ls.virtual {
for i := range lvt {
vt := &lvt[i]
if vt.layer != layer || vt.view != vid {
continue
}
vts = append(vts, VirtualText{Pos: textpos.Pos{Line: ln, Char: vt.char}, Text: joinLines(vt.lines)})
}
}
return vts
}
// VirtualTextView returns the view position, in view lines and display
// chars, of the char at the given offset within the virtual text in the
// given layer at the given source position, as shown in the given view.
// Newlines in the text are not counted in the offset. For example, an
// input method uses the position of its composition cursor to place its
// candidate window. It returns false if there is no such virtual text.
func (ls *Lines) VirtualTextView(vid int, layer string, pos textpos.Pos, offset int) (textpos.Pos, bool) {
ls.Lock()
defer ls.Unlock()
vw := ls.view(vid)
if vw == nil {
return textpos.Pos{}, false
}
d := ls.srcToDisplay(vw, pos.Line, pos.Char)
for i := range ls.virtualAt(pos.Line) {
vt := &ls.virtual[pos.Line][i]
if vt.char < pos.Char || !vt.shownIn(vw) {
continue
}
if vt.char > pos.Char {
break
}
if vt.layer == layer {
offset = max(0, min(offset, vt.len()))
return ls.displayToView(vw, textpos.Pos{Line: pos.Line, Char: d + offset}), true
}
d += vt.len()
}
return textpos.Pos{}, false
}
// OnVirtualText adds a listener for when the virtual text shown in
// the given view changes. It is an [events.Custom] event.
func (ls *Lines) OnVirtualText(vid int, fun func(e events.Event)) {
ls.Lock()
defer ls.Unlock()
vw := ls.view(vid)
if vw != nil {
vw.listeners.Add(events.Custom, fun)
}
}
func (ls *Lines) sendVirtualText() {
e := &events.Base{Typ: events.Custom}
e.Init()
for _, vw := range ls.views {
vw.listeners.Call(e)
}
}
// setVirtualText does [Lines.SetVirtualText] without locking or sending events.
func (ls *Lines) setVirtualText(layer string, vid int, vts ...VirtualText) {
vid = max(vid, -1)
ls.virtual = ls.virtualLines()
changed := false
for ln := range ls.virtual {
n := len(ls.virtual[ln])
ls.virtual[ln] = slices.DeleteFunc(ls.virtual[ln], func(vt virtualText) bool {
return vt.layer == layer && vt.view == vid
})
changed = changed || len(ls.virtual[ln]) != n
}
for _, vt := range vts {
pos, ok := ls.validCharPos(vt.Pos)
if !ok || vt.Text.Len() == 0 {
continue
}
lvt := ls.virtual[pos.Line]
i := len(lvt)
for i > 0 && lvt[i-1].char > pos.Char {
i--
}
ls.virtual[pos.Line] = slices.Insert(lvt, i, virtualText{char: pos.Char, lines: splitLines(vt.Text), layer: layer, view: vid})
changed = true
}
if changed {
ls.layoutViews()
}
}
// virtualLines returns ls.virtual with one entry per line.
func (ls *Lines) virtualLines() [][]virtualText {
return ls.virtualLinesFor(ls.numLines())
}
// virtualLinesFor returns ls.virtual with n entries.
func (ls *Lines) virtualLinesFor(n int) [][]virtualText {
if len(ls.virtual) == n {
return ls.virtual
}
if len(ls.virtual) > n {
return ls.virtual[:n]
}
return append(ls.virtual, make([][]virtualText, n-len(ls.virtual))...)
}
// virtualAt returns the virtual text for the given source line.
func (ls *Lines) virtualAt(ln int) []virtualText {
if ln < 0 || ln >= len(ls.virtual) {
return nil
}
return ls.virtual[ln]
}
// hasVirtual returns whether any virtual text is shown in the
// given view on the given source line.
func (ls *Lines) hasVirtual(vw *view, ln int) bool {
for i := range ls.virtualAt(ln) {
if ls.virtual[ln][i].shownIn(vw) {
return true
}
}
return false
}
// displayLineLen returns the number of display chars
// of the given source line in the given view.
func (ls *Lines) displayLineLen(vw *view, ln int) int {
n := len(ls.lines[ln])
for i := range ls.virtualAt(ln) {
vt := &ls.virtual[ln][i]
if vt.shownIn(vw) {
n += vt.len()
}
}
return n
}
// virtualLenAt returns the length of the virtual text at the given
// source position that is shown in the given view.
func (ls *Lines) virtualLenAt(vw *view, pos textpos.Pos) int {
n := 0
for i := range ls.virtualAt(pos.Line) {
vt := &ls.virtual[pos.Line][i]
if vt.char == pos.Char && vt.shownIn(vw) {
n += vt.len()
}
}
return n
}
// srcToDisplay returns the display char position in the given view
// for the given source char position in the given source line.
// The cursor is shown before any virtual text at its position.
func (ls *Lines) srcToDisplay(vw *view, ln, ch int) int {
d := ch
for i := range ls.virtualAt(ln) {
vt := &ls.virtual[ln][i]
if vt.char >= ch {
break
}
if vt.shownIn(vw) {
d += vt.len()
}
}
return d
}
// displayToSrc returns the source char position in the given source line
// for the given display char position in the given view. Display positions
// within virtual text return its source position.
func (ls *Lines) displayToSrc(vw *view, ln, d int) int {
src, disp := 0, 0
for i := range ls.virtualAt(ln) {
vt := &ls.virtual[ln][i]
if !vt.shownIn(vw) {
continue
}
vst := disp + vt.char - src // display start of the virtual text
if d < vst {
return src + d - disp
}
if d < vst+vt.len() {
return vt.char
}
src, disp = vt.char, vst+vt.len()
}
return src + d - disp
}
// isVirtualDisplay returns whether the given display char position
// in the given source line is within virtual text in the given view.
func (ls *Lines) isVirtualDisplay(vw *view, ln, d int) bool {
src, disp := 0, 0
for i := range ls.virtualAt(ln) {
vt := &ls.virtual[ln][i]
if !vt.shownIn(vw) {
continue
}
vst := disp + vt.char - src
if d < vst {
return false
}
if d < vst+vt.len() {
return true
}
src, disp = vt.char, vst+vt.len()
}
return false
}
// isVirtualViewLine returns whether the given view line
// only contains virtual text, so the cursor skips it.
func (ls *Lines) isVirtualViewLine(vw *view, vl int) bool {
if vl < 0 || vl >= len(vw.vlineStarts) {
return false
}
vs := vw.vlineStarts[vl]
if !ls.hasVirtual(vw, vs.Line) {
return false
}
n := ls.viewLineLen(vw, vl)
if vl+1 >= len(vw.vlineStarts) || vw.vlineStarts[vl+1].Line != vs.Line {
n-- // the end of the source line, which is not virtual
}
if n <= 0 {
return false
}
for d := vs.Char; d < vs.Char+n; d++ {
if !ls.isVirtualDisplay(vw, vs.Line, d) {
return false
}
}
return true
}
// displayLine returns the display text and markup for the given source
// line in the given view, with any virtual text spliced into the source
// text and markup, and the display positions where the following lines
// of multi-line virtual text start, which must start new view lines.
// If there is no virtual text, the source text and markup are returned.
func (ls *Lines) displayLine(vw *view, ln int, txt []rune, mu rich.Text) ([]rune, rich.Text, []int) {
if !ls.hasVirtual(vw, ln) {
return txt, mu, nil
}
dtxt := make([]rune, 0, ls.displayLineLen(vw, ln))
dmu := mu.Clone()
var breaks []int
src := 0
for i := range ls.virtual[ln] {
vt := &ls.virtual[ln][i]
if !vt.shownIn(vw) {
continue
}
dtxt = append(dtxt, txt[src:vt.char]...)
src = vt.char
for li, l := range vt.lines {
if li > 0 {
breaks = append(breaks, len(dtxt))
}
insertSpans(&dmu, len(dtxt), l)
dtxt = append(dtxt, l.Join()...)
}
}
dtxt = append(dtxt, txt[src:]...)
return dtxt, dmu, breaks
}
// insertSpans inserts copies of the spans of the given text into the
// markup at the given char position, which can be its end.
func insertSpans(mu *rich.Text, ch int, tx rich.Text) {
si := len(*mu)
if ch < mu.Len() {
if si = mu.SplitSpan(ch); si < 0 {
si = len(*mu)
}
}
spans := make([][]rune, 0, len(tx))
for _, sp := range tx {
if _, rn := rich.SpanLen(sp); rn > 0 {
spans = append(spans, slices.Clone(sp))
}
}
*mu = slices.Insert(*mu, si, spans...)
}
// splitLines splits the text into lines at newlines, keeping the
// styles of the spans, which can contain multiple lines.
func splitLines(tx rich.Text) []rich.Text {
lines := []rich.Text{{}}
for _, sp := range tx {
sn, _ := rich.SpanLen(sp)
for i, part := range runes.Split(sp[sn:], []rune("\n")) {
if i > 0 {
lines = append(lines, rich.Text{})
}
if len(part) > 0 {
ln := &lines[len(lines)-1]
*ln = append(*ln, append(slices.Clone(sp[:sn]), part...))
}
}
}
return lines
}
// joinLines joins lines of text with newlines,
// which is the inverse of [splitLines].
func joinLines(lines []rich.Text) rich.Text {
var tx rich.Text
for li, l := range lines {
if li > 0 {
if len(tx) == 0 {
tx.AddSpan(rich.NewStyle(), nil)
}
tx.AddRunes([]rune("\n"))
}
for _, sp := range l {
tx = append(tx, slices.Clone(sp))
}
}
return tx
}
// virtualInserted updates the virtual text for text inserted from st to ed,
// which must be called after the lines are inserted.
func (ls *Lines) virtualInserted(st, ed textpos.Pos) {
if st.Line >= len(ls.virtual) {
return
}
lvt := ls.virtual[st.Line]
i := 0
for i < len(lvt) && lvt[i].char < st.Char {
i++
}
moved := lvt[i:]
for j := range moved {
moved[j].char += ed.Char - st.Char
}
if ed.Line == st.Line {
return
}
ls.virtual[st.Line] = lvt[:i:i]
if ed.Line < len(ls.virtual) {
ls.virtual[ed.Line] = append(ls.virtual[ed.Line], moved...)
}
}
// virtualDeleted updates the virtual text for text deleted from st to ed,
// which must be called before the lines are deleted. Virtual text within
// the deleted text is removed, and that after it is moved to st.
func (ls *Lines) virtualDeleted(st, ed textpos.Pos) {
if st.Line >= len(ls.virtual) {
return
}
var kept []virtualText
for _, vt := range ls.virtual[st.Line] {
if vt.char <= st.Char {
kept = append(kept, vt)
} else if st.Line == ed.Line && vt.char >= ed.Char {
vt.char -= ed.Char - st.Char
kept = append(kept, vt)
}
}
if ed.Line > st.Line && ed.Line < len(ls.virtual) {
for _, vt := range ls.virtual[ed.Line] {
if vt.char >= ed.Char {
vt.char += st.Char - ed.Char
kept = append(kept, vt)
}
}
// The deleted lines are removed by linesDeleted, which keeps
// the slot of the end line for the joined line.
ls.virtual[ed.Line] = kept
return
}
ls.virtual[st.Line] = kept
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package paginate
import (
"strings"
"cogentcore.org/core/base/stack"
"cogentcore.org/core/core"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/tree"
)
// item is one layout item
type item struct {
w core.Widget
gap math32.Vector2 // gap to add before this element
left float32 // left-side margin from parent frame
}
func (it *item) String() string {
return core.AsWidget(it.w).String()
}
// extract returns the widget chunks to actually paginate.
func (p *pager) extract() []*item {
widg := core.AsWidget
ii := 0
type posn struct {
w core.Widget
i int
}
pars := stack.Stack[*posn]{} // stack of parents that we are iterating
pars.Push(&posn{p.ins[ii], 0})
atEnd := false
next := func() {
start:
cp := pars.Peek()
cp.i++
if cp.i >= cp.w.AsWidget().NumChildren() {
pars.Pop()
if len(pars) == 0 {
ii++
if ii >= len(p.ins) {
atEnd = true
return
}
pars.Push(&posn{p.ins[ii], 0})
return
} else {
goto start
}
}
}
// The blocks are spaced by at least the gap of the first input
// (as the page of content), as frames of the browser style of
// htmlcore have no gap, and their CSS margins are dropped for this
// (see below).
blockGap := widg(p.ins[0]).Styles.Gap.Dots().Floor().Y
var its []*item
for {
cp := pars.Peek()
cpw := cp.w.AsWidget()
if cp.i >= cpw.NumChildren() {
next()
if atEnd {
break
}
continue
}
gap := cpw.Styles.Gap.Dots().Floor()
left := cpw.Styles.Padding.Left.Dots
if cp.i == 0 {
gap.Y = 0
}
gap.Y = max(gap.Y, blockGap)
cw := widg(cpw.Child(cp.i))
if fr, ok := cw.This.(*core.Frame); ok {
if fr.Styles.Direction == styles.Column && hasBlocks(fr) {
if fr.Property("paginate-block") == nil {
pars.Push(&posn{fr.This.(core.Widget), 0})
continue
}
}
// a block kept whole is spaced by the gap
fr.Styler(func(s *styles.Style) {
s.Margin.Top.Zero()
s.Margin.Bottom.Zero()
})
}
its = append(its, &item{w: cw.This.(core.Widget), gap: gap, left: left})
next()
if atEnd {
break
}
}
// fmt.Println("its:", its)
return its
}
// hasBlocks returns whether the frame has other frames in it, other than
// the inline containers of its text, into which it is divided for the
// pages. A frame with just text in it, as of a paragraph or heading in
// the browser style of htmlcore, is kept whole, with its margins (the
// spacing of the blocks), and the styles that its text inherits from it.
func hasBlocks(fr *core.Frame) bool {
blocks := false
fr.ForWidgetChildren(func(i int, cw core.Widget, cwb *core.WidgetBase) bool {
if _, ok := cw.(*core.Frame); ok && !strings.HasPrefix(cwb.Name, "inline-container") {
blocks = true
return tree.Break
}
return tree.Continue
})
return blocks
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package paginate
import (
"cogentcore.org/core/core"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/tree"
)
// pagify organizes widget list into page-sized chunks.
func (p *pager) pagify(its []*item) [][]*item {
widg := core.AsWidget
size := func(it *item) float32 {
wb := widg(it.w)
ih := wb.Geom.Size.Actual.Total.Y // todo: something wrong with size!
return ih + it.gap.Y
}
maxY := p.opts.BodyDots.Y
var pgs [][]*item
var cpg []*item
ht := float32(0)
n := len(its)
for i, ci := range its {
cw := widg(ci.w)
// fmt.Println(cw)
brk := cw.Property("paginate-break") != nil
nobrk := cw.Property("paginate-no-break-after") != nil
sz := size(ci)
over := ht+sz > maxY
if !over && nobrk {
if i < n-1 {
nsz := size(its[i+1]) // extra space to be sure
if ht+sz+nsz > maxY {
over = true // break now
// } else {
// fmt.Println("not !over, nobrk:", ht, sz, nsz, maxY, ht+sz+nsz, cw, its[i+1])
}
}
}
if brk || over {
ht = 0
if !brk && len(cpg) == 0 { // no blank pages!
cpg = append(cpg, ci)
pgs = append(pgs, cpg)
cpg = nil
continue
}
pgs = append(pgs, cpg)
cpg = nil
}
ht += sz
cpg = append(cpg, ci)
}
if len(cpg) > 0 {
pgs = append(pgs, cpg)
}
return pgs
}
func (p *pager) outputPages(pgs [][]*item, newPage func(gap math32.Vector2, pageNo int) (page, body *core.Frame)) []*core.Frame {
var outs []*core.Frame
for pn, pg := range pgs {
lastGap := math32.Vector2{}
lastLeft := float32(0)
if len(pg) > 0 {
lastGap = pg[0].gap
}
page, body := newPage(lastGap, pn+1)
cpar := body
for _, it := range pg {
gap := it.gap
left := it.left
if gap != lastGap || left != lastLeft {
cpar = p.newOutFrame(body, gap, left)
lastGap = gap
lastLeft = left
}
tree.MoveToParent(it.w, cpar)
}
outs = append(outs, page)
}
return outs
}
func (p *pager) newOutFrame(par *core.Frame, gap math32.Vector2, left float32) *core.Frame {
var fr *core.Frame
if par != nil {
fr = core.NewFrame(par)
} else {
fr = core.NewFrame()
}
fr.Styler(func(s *styles.Style) {
s.Direction = styles.Column
s.ZeroSpace()
s.Min.X.Dot(p.opts.BodyDots.X)
s.Max.X.Dot(p.opts.BodyDots.X)
s.Gap.X.Dot(gap.X)
s.Gap.Y.Dot(gap.Y)
s.Padding.Left.Dot(core.ConstantSpacing(left))
})
return fr
}
// pre-render everything in the offscreen scene that will be used for final
// to get accurate element sizes.
func (p *pager) preRender(its []*item) {
pg := [][]*item{its}
op := p.outputPages(pg, func(gap math32.Vector2, pageNo int) (page, body *core.Frame) {
fr := p.newOutFrame(nil, gap, 0)
page, body = fr, fr
return
})
sc := p.offScene()
tree.MoveToParent(op[0], sc)
op[0].SetScene(sc)
sc.StyleTree()
sc.LayoutScene()
}
// layout reorders items within the pages and generates final output.
func (p *pager) layout(its []*item) {
p.preRender(its)
pgs := p.pagify(its)
// note: could rearrange elements to put text at bottom and non-text at top?
// but this is probably not necessary?
p.outs = p.outputPages(pgs, p.newPage)
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:generate core generate -add-types
package paginate
import (
"cogentcore.org/core/core"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles/sides"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/printer"
)
// Options has the parameters for pagination.
type Options struct {
// FontScale is an additional font scaling factor to apply.
// This is used in content to reverse the DocsFontSize factor, for example.
FontScale float32
// TextStyler is an optional text styling function to apply to text elements.
// Can be used to adjust the sizes and formatting of headers, for example.
TextStyler func(tx *core.Text)
// Title generates the title contents for the first page,
// into the given page body frame.
Title func(frame *core.Frame, opts *Options)
// Header generates the header contents for the page, into the given
// frame that represents the entire top margin.
// See examples in runners.go
Header func(frame *core.Frame, opts *Options, pageNo int)
// Footer generates the footer contents for the page, into the given
// frame that represents the entire top margin.
// See examples in runners.go
Footer func(frame *core.Frame, opts *Options, pageNo int)
// SizeDots is the total size in dots. Set automatically, but needs to be readable
// so is exported.
SizeDots math32.Vector2 `edit:"-"`
// BodyDots (content) size in dots.
BodyDots math32.Vector2 `edit:"-"`
// MargDots is the margin sizes in dots.
MargDots sides.Floats `edit:"-"`
}
func NewOptions() Options {
o := Options{}
o.Defaults()
return o
}
func (o *Options) Defaults() {
o.FontScale = 1
o.Footer = CenteredPageNumber
}
func (o *Options) ToDots(un *units.Context) {
o.SizeDots, o.BodyDots, o.MargDots = printer.Settings.ToDots(un)
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package paginate
import (
"fmt"
"cogentcore.org/core/core"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
)
func styMinMax(s *styles.Style, x, y float32) {
s.ZeroSpace()
s.Min.X.Dot(x)
s.Min.Y.Dot(y)
s.Max.X.Dot(x)
s.Max.Y.Dot(y)
}
func (p *pager) newPage(gap math32.Vector2, pageNo int) (page, body *core.Frame) {
pn := fmt.Sprintf("page-%d", pageNo)
page = core.NewFrame()
page.SetName(pn)
page.Styler(func(s *styles.Style) {
s.Direction = styles.Row
styMinMax(s, p.opts.SizeDots.X, p.opts.SizeDots.Y)
})
lmar := core.NewFrame(page)
lmar.SetName("left-margin")
lmar.Styler(func(s *styles.Style) {
s.Direction = styles.Column
styMinMax(s, p.opts.MargDots.Left, p.opts.SizeDots.Y)
})
bfr := core.NewFrame(page)
bfr.SetName("body-frame")
bfr.Styler(func(s *styles.Style) {
s.Direction = styles.Column
styMinMax(s, p.opts.BodyDots.X, p.opts.SizeDots.Y)
})
hdr := core.NewFrame(bfr)
hdr.SetName("header")
hdr.Styler(func(s *styles.Style) {
s.Direction = styles.Column
styMinMax(s, p.opts.BodyDots.X, p.opts.MargDots.Top)
})
if p.opts.Header != nil {
p.opts.Header(hdr, p.opts, pageNo)
}
body = core.NewFrame(bfr)
body.SetName("body")
body.Styler(func(s *styles.Style) {
s.Direction = styles.Column
styMinMax(s, p.opts.BodyDots.X, p.opts.BodyDots.Y)
s.Gap.X.Dot(gap.X)
s.Gap.Y.Dot(gap.Y)
})
ftr := core.NewFrame(bfr)
ftr.SetName("footer")
ftr.Styler(func(s *styles.Style) {
s.Direction = styles.Column
styMinMax(s, p.opts.BodyDots.X, p.opts.MargDots.Bottom)
})
if p.opts.Footer != nil {
p.opts.Footer(ftr, p.opts, pageNo)
}
return
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package paginate
import (
"cogentcore.org/core/core"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint"
"cogentcore.org/core/styles/units"
)
// Paginate organizes the given input widget content into frames
// that each fit within the page size specified in the options.
// See PDF for function that generates paginated PDFs suitable
// for printing: it ensures that the content layout matches
// the page sizes, for example, which is not done in this version.
func Paginate(opts Options, ins ...core.Widget) []*core.Frame {
if len(ins) == 0 {
return nil
}
p := pager{opts: &opts, ins: ins}
p.optsUpdate()
p.paginate()
return p.outs
}
// pager implements the pagination.
type pager struct {
opts *Options
ins []core.Widget
outs []*core.Frame
ctx units.Context
sc *core.Scene
}
// optsUpdate updates the option sizes based on unit context in first input.
func (p *pager) optsUpdate() {
in0 := p.ins[0].AsWidget()
p.ctx = in0.Styles.UnitContext
p.opts.ToDots(&p.ctx)
}
func (p *pager) paginate() {
its := p.extract()
p.layout(its)
}
// offScene returns a scene suitable for offline rendering,
// sized to the full page size.
func (p *pager) offScene() *core.Scene {
if p.sc != nil {
p.sc.DeleteChildren()
return p.sc
}
sz := p.opts.SizeDots
sc := core.NewScene()
// critical to be image not htmlcanvas, and not to be the correct size yet..
sc.Renderer = paint.NewImageRenderer(sz.SubScalar(1))
scsz := math32.Geom2DInt{}
scsz.Size = sz.ToPointCeil()
sc.Resize(scsz)
sc.MakeTextShaper()
p.sc = sc
return sc
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package paginate
import (
"io"
"cogentcore.org/core/colors"
"cogentcore.org/core/colors/matcolor"
"cogentcore.org/core/core"
"cogentcore.org/core/paint"
"cogentcore.org/core/paint/pdf"
"cogentcore.org/core/paint/renderers/pdfrender"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/printer"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/tree"
)
// PDF generates PDF pages from given input content using given options,
// writing to the given writer. It re-renders the input widgets with
// the default PDF fonts in place (Helvetica, Times, Courier),
// and the size set to the target size as configured in the options.
// This will produce accurate PDF layout.
func PDF(w io.Writer, opts Options, ins ...core.Widget) {
if len(ins) == 0 {
return
}
cmode := matcolor.SchemeIsDark
colors.SetScheme(false)
cset := pdf.UseStandardFonts()
// The inputs are sized for the pages by final stylers, which are
// removed afterward, so that they are as they were on the screen.
nfinal := make([]int, len(ins))
for i, in := range ins {
nfinal[i] = len(in.AsWidget().Stylers.Final)
}
defer func() {
for i, in := range ins {
iw := in.AsWidget()
iw.Stylers.Final = iw.Stylers.Final[:nfinal[i]]
iw.Style()
iw.NeedsLayout()
}
}()
p := pager{opts: &opts, ins: ins}
p.ctx = *units.NewContext() // generic, invariant of actual context
p.opts.ToDots(&p.ctx)
p.assemble()
p.paginate()
sc := p.offScene()
pdr := paint.NewPDFRenderer(opts.SizeDots, &p.ctx).(*pdfrender.Renderer)
pdr.StartRender(w)
np := len(p.outs)
for i, p := range p.outs {
tree.MoveToParent(p, sc)
p.SetScene(sc)
sc.StyleTree()
sc.LayoutScene()
for _, cwb := range sc.AllWidgets() {
if tx, ok := cwb.This.(*core.Text); ok {
lns := tx.PaintText()
if len(lns.Lines) > 0 {
ln := &lns.Lines[0]
ln.Offset.Y += 3 // todo: seriously, this fixes an otherwise inexplicable offset
}
}
}
p.RenderWidget()
rend := sc.Painter.RenderDone()
pdr.RenderPage(rend)
if i < np-1 {
pdr.AddPage()
}
sc.DeleteChildren()
}
pdr.EndRender()
colors.SetScheme(cmode)
pdf.RestorePreviousFonts(cset)
}
// assemble collects everything to be rendered into one big list,
// and sets the font family and size for text elements.
// only for full format rendering (e.g., PDF)
func (p *pager) assemble() {
sc := core.AsWidget(p.ins[0]).Scene
if p.opts.Title != nil {
tf := core.NewFrame()
tf.Scene = sc
tf.FinalStyler(func(s *styles.Style) {
s.Min.X.Dot(p.opts.BodyDots.X)
s.Min.Y.Dot(p.opts.BodyDots.Y)
})
p.opts.Title(tf, p.opts)
p.ins = append([]core.Widget{tf.This.(core.Widget)}, p.ins...)
tf.StyleTree()
}
fsc := printer.Settings.FontScale() * p.opts.FontScale
for ii, in := range p.ins {
iw := core.AsWidget(in)
iw.FinalStyler(func(s *styles.Style) {
s.Min.X.Dot(p.opts.BodyDots.X)
s.Min.Y.Dot(p.opts.BodyDots.Y)
})
if p.opts.Title != nil && ii == 0 { // don't restyle the title
continue
}
for _, cwb := range iw.AllWidgets() {
if tx, ok := cwb.This.(*core.Text); ok {
if _, ok := cwb.Parent.(*core.Frame); ok { // not inside buttons etc
cwb.Styler(func(s *styles.Style) {
if tx.Styles.Font.Family == rich.SansSerif {
s.Font.Family = printer.Settings.FontFamily
}
if tx.Type == core.TextBodyLarge {
s.Text.LineHeight = printer.Settings.LineHeight
}
s.Font.Size.Value *= fsc
s.Color = colors.Uniform(colors.Black) // in case dark mode
if p.opts.TextStyler != nil {
p.opts.TextStyler(tx)
}
})
}
}
}
}
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package paginate
import (
"strconv"
"cogentcore.org/core/colors"
"cogentcore.org/core/core"
"cogentcore.org/core/styles"
"cogentcore.org/core/text/printer"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/text"
)
// TextStyler does standard text styling for printout:
// FontFamily and Black Color (e.g., in case user is in Dark mode).
func TextStyler(s *styles.Style) {
s.Font.Family = printer.Settings.FontFamily
s.Color = colors.Uniform(colors.Black)
}
// CenteredPageNumber generates a page number centered in the frame
// with a 1.5em space above it.
func CenteredPageNumber(frame *core.Frame, opts *Options, pageNo int) {
core.NewSpace(frame).Styler(func(s *styles.Style) { // space before
s.Min.Y.Em(1.5)
s.Grow.Set(1, 0)
})
fr := core.NewFrame(frame)
fr.Styler(func(s *styles.Style) {
s.Direction = styles.Row
s.Grow.Set(1, 0)
s.Justify.Content = styles.Center
})
core.NewText(fr).SetText(strconv.Itoa(pageNo)).Styler(func(s *styles.Style) {
TextStyler(s)
})
}
// NoFirst excludes the first page for any runner
func NoFirst(fun func(frame *core.Frame, opts *Options, pageNo int)) func(frame *core.Frame, opts *Options, pageNo int) {
return func(frame *core.Frame, opts *Options, pageNo int) {
if pageNo == 1 {
return
}
fun(frame, opts, pageNo)
}
}
// HeaderLeftPageNumber adds a running header with page number on the right.
func HeaderLeftPageNumber(header string) func(frame *core.Frame, opts *Options, pageNo int) {
return func(frame *core.Frame, opts *Options, pageNo int) {
core.NewStretch(frame)
fr := core.NewFrame(frame)
fr.Styler(func(s *styles.Style) {
s.Direction = styles.Row
s.Grow.Set(1, 0)
})
core.NewText(fr).SetText(header).Styler(func(s *styles.Style) {
TextStyler(s)
s.SetTextWrap(false)
s.Font.Slant = rich.Italic
s.Font.Size = printer.Settings.FontSize
})
core.NewStretch(fr)
core.NewText(fr).SetText(strconv.Itoa(pageNo)).Styler(func(s *styles.Style) {
TextStyler(s)
s.SetTextWrap(false)
s.Font.Size = printer.Settings.FontSize
})
core.NewSpace(frame).Styler(func(s *styles.Style) { // space after
s.Min.Y.Em(3)
s.Grow.Set(1, 0)
})
}
}
// CenteredTitle inserts centered text elements for each element if non-empty.
func CenteredTitle(title, authors, affiliations, url, date, version, reference, abstract string) func(frame *core.Frame, opts *Options) {
return func(frame *core.Frame, opts *Options) {
fr := core.NewFrame(frame)
fr.Styler(func(s *styles.Style) {
s.Direction = styles.Column
s.Grow.Set(1, 0)
s.Align.Items = styles.Center
})
fr.SetProperty("paginate-block", true)
core.NewStretch(fr).Styler(func(s *styles.Style) { // need this to take up the full width
s.Grow.Set(1, 0)
s.Min.X.Dot(opts.BodyDots.X)
s.Min.Y.Em(.1)
})
core.NewText(fr).SetText(title).Styler(func(s *styles.Style) {
TextStyler(s)
s.Font.Size = printer.Settings.FontSize
s.Font.Size.Value *= 16.0 / 11
s.Text.Align = text.Center
})
if authors != "" {
core.NewText(fr).SetText(authors).Styler(func(s *styles.Style) {
TextStyler(s)
s.Font.Size = printer.Settings.FontSize
s.Font.Size.Value *= 12.0 / 11
s.Text.Align = text.Center
})
}
if affiliations != "" {
core.NewText(fr).SetText(affiliations).Styler(func(s *styles.Style) {
TextStyler(s)
s.Font.Size = printer.Settings.FontSize
s.Text.Align = text.Center
s.Text.LineHeight = 1.1
})
}
core.NewSpace(fr).Styler(func(s *styles.Style) { s.Min.Y.Em(1) })
if date != "" {
txt := date
if version != "" {
txt += ", Version: " + version
}
core.NewText(fr).SetText(txt).Styler(func(s *styles.Style) {
TextStyler(s)
s.Font.Size = printer.Settings.FontSize
s.Text.Align = text.Center
})
} else if version != "" {
core.NewText(fr).SetText("Version: " + version).Styler(func(s *styles.Style) {
TextStyler(s)
s.Font.Size = printer.Settings.FontSize
s.Text.Align = text.Center
})
}
if url != "" {
core.NewText(fr).SetText(url).Styler(func(s *styles.Style) {
TextStyler(s)
s.Font.Size = printer.Settings.FontSize
s.Text.Align = text.Center
})
}
if reference != "" {
core.NewText(fr).SetText(reference).Styler(func(s *styles.Style) {
TextStyler(s)
s.Font.Size = printer.Settings.FontSize
s.Text.Align = text.Center
})
}
if abstract != "" {
core.NewText(fr).SetText("Abstract:").Styler(func(s *styles.Style) {
TextStyler(s)
s.Font.Size = printer.Settings.FontSize
s.Font.Size.Value *= 12.0 / 11
s.Font.Weight = rich.Bold
s.Align.Self = styles.Start
})
core.NewText(fr).SetText(abstract).Styler(func(s *styles.Style) {
TextStyler(s)
s.Font.Size = printer.Settings.FontSize
s.Text.LineHeight = printer.Settings.LineHeight
s.Align.Self = styles.Start
})
}
core.NewSpace(fr).Styler(func(s *styles.Style) { s.Min.Y.Em(1) })
}
}
// APAHeaders is a TextStyler function that sets APA-style headers based
// on the tag property. The default material design header sizes used onscreen are
// generally too large for print. This is designed for content, where the
// second level header ## is used for most top-level headers within a page.
func APAHeaders(tx *core.Text) {
headerLevel := 0
if tag, ok := tx.Properties["tag"].(string); ok && len(tag) > 1 && tag[0] == 'h' {
headerLevel, _ = strconv.Atoi(tag[1:])
}
s := &tx.Styles
base := printer.Settings.FontSize
// the line heights are of the types of text of the headings
// (as h2 is [core.TextHeadlineMedium])
switch headerLevel {
case 1: // e.g., chapter level
s.Text.LineHeight = 44.0 / 36
s.Font.Size = base
s.Font.Size.Value *= 16.0 / 11.0
s.Font.Weight = rich.Bold
case 2:
s.Text.LineHeight = 36.0 / 28
s.Font.Size = base
s.Font.Size.Value *= 14.0 / 11.0
s.Font.Weight = rich.Bold
case 3:
s.Text.LineHeight = 28.0 / 22
s.Font.Size = base
s.Font.Size.Value *= 12.0 / 11.0
s.Font.Weight = rich.Bold
case 4:
s.Text.LineHeight = 24.0 / 16
s.Font.Size = base
s.Font.Weight = rich.Bold
s.Font.Slant = rich.Italic
case 5: // as [core.TextTitleSmall], from the 0.83em of the CSS of h5
s.Text.LineHeight = 20.0 / 14
s.Font.Size.Value *= (14.0 / 16) / 0.83
s.Font.Weight = rich.Medium
case 6: // as [core.TextLabelSmall], from the 0.67em of the CSS of h6
s.Text.LineHeight = 16.0 / 11
s.Font.Size.Value *= (11.0 / 16) / 0.67
s.Font.Weight = rich.Medium
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"cogentcore.org/core/base/fileinfo"
"cogentcore.org/core/base/fsx"
"cogentcore.org/core/text/parse"
_ "cogentcore.org/core/text/parse/languages"
"cogentcore.org/core/text/parse/syms"
)
var Excludes []string
func main() {
var path string
var recurse bool
var excl string
parse.LanguageSupport.OpenStandard()
flag.Usage = func() {
fmt.Fprintf(flag.CommandLine.Output(), "Usage of %s:\n", os.Args[0])
flag.PrintDefaults()
fmt.Fprintf(flag.CommandLine.Output(), "\ne.g., on mac, to run all of the std go files except cmd which is large and slow:\npi -r -ex cmd /usr/local/Cellar/go/1.11.3/libexec/src\n\n")
}
// process command args
flag.StringVar(&path, "path", "", "path to open; can be to a directory or a filename within the directory; or just last arg without a flag")
flag.BoolVar(&recurse, "r", false, "recursive; apply to subdirectories")
flag.StringVar(&excl, "ex", "", "comma-separated list of directory names to exclude, for recursive case")
flag.Parse()
if path == "" {
if flag.NArg() > 0 {
path = flag.Arg(0)
} else {
path = "."
}
}
Excludes = strings.Split(excl, ",")
// todo: assuming go for now
if recurse {
DoGoRecursive(path)
} else {
DoGoPath(path)
}
}
func DoGoPath(path string) {
fmt.Printf("Processing path: %v\n", path)
lp, _ := parse.LanguageSupport.Properties(fileinfo.Go)
pr := lp.Lang.Parser()
pr.ReportErrs = true
fs := parse.NewFileState()
pkgsym := lp.Lang.ParseDir(fs, path, parse.LanguageDirOptions{Rebuild: true})
if pkgsym != nil {
syms.SaveSymDoc(pkgsym, fileinfo.Go, path)
}
}
func DoGoRecursive(path string) {
DoGoPath(path)
drs := fsx.Dirs(path)
outer:
for _, dr := range drs {
if dr == "testdata" {
continue
}
for _, ex := range Excludes {
if dr == ex {
continue outer
}
}
sp := filepath.Join(path, dr)
DoGoRecursive(sp)
}
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Command update updates all of the .parse files within
// or beneath the current directory by opening and saving them.
package main
import (
"io/fs"
"path/filepath"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/text/parse"
)
func main() {
errors.Log(filepath.Walk(".", func(path string, info fs.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
if filepath.Ext(path) != ".parse" {
return nil
}
p := parse.NewParser()
err = p.OpenJSON(path)
if err != nil {
return err
}
return p.SaveJSON(path)
}))
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package complete provides the matching of completions to the text being
// completed (the seed), and the edits that insert them.
package complete
import (
"cmp"
"path/filepath"
"slices"
"strings"
"unicode"
"unicode/utf8"
"cogentcore.org/core/base/strcase"
"cogentcore.org/core/icons"
)
// Completion holds one potential completion
type Completion struct {
// Text is the completion text: what will actually be inserted if selected.
Text string
// Label is the label text to show the user. It is only used if
// non-empty; otherwise Text is used.
Label string
// Icon is the icon to render in core for the completion item.
Icon icons.Icon
// Desc is extra description information used in tooltips in core.
Desc string
}
// Completions is a full list (slice) of completion options
type Completions []Completion
// Matches is used for passing completions around.
// contains seed in addition to completions
type Matches struct {
// the matches based on seed
Matches Completions
// seed is the prefix we use to find possible completions
Seed string
}
// Lookup is used for returning lookup results
type Lookup struct {
// if non-empty, the result is to view this file (full path)
Filename string
// starting line number within file to display
StLine int
// ending line number within file
EdLine int
// if filename is empty, this is raw text to display for lookup result
Text []byte
}
// SetFile sets file info
func (lk *Lookup) SetFile(fname string, st, ed int) {
lk.Filename = fname
lk.StLine = st
lk.EdLine = ed
}
// Edit is returned from completion edit function
// to incorporate the selected completion
type Edit struct {
// completion text after special edits
NewText string
// number of runes, past the cursor, to delete, if any
ForwardDelete int
// cursor adjustment if cursor should be placed in a location other than at end of newText
CursorAdjust int
}
// MatchFunc is the function called to get the list of possible completions
// and also determines the correct seed based on the text
// passed as a parameter of CompletionFunc
type MatchFunc func(data any, text string, posLine, posChar int) Matches
// LookupFunc is the function called to get the lookup results for given
// input test and position.
type LookupFunc func(data any, text string, posLine, posChar int) Lookup
// EditFunc is passed the current text and the selected completion for text editing.
// Allows for other editing, e.g. adding "()" or adding "/", etc.
type EditFunc func(data any, text string, cursorPos int, comp Completion, seed string) Edit
// MatchSeedString returns a list of matches given a list of string
// possibilities and a seed. It checks whether different
// transformations of each possible completion contain a lowercase
// version of the seed. It returns nil if there are no matches.
func MatchSeedString(completions []string, seed string) []string {
if len(seed) == 0 {
// everything matches
return completions
}
var matches []string
lseed := strings.ToLower(seed)
for _, c := range completions {
if IsSeedMatching(lseed, c) {
matches = append(matches, c)
}
}
slices.SortStableFunc(matches, func(a, b string) int {
return cmp.Compare(MatchPrecedence(lseed, a), MatchPrecedence(lseed, b))
})
return matches
}
// MatchSeedCompletion returns a list of matches given a list of
// [Completion] possibilities and a seed. It checks whether different
// transformations of each possible completion contain a lowercase
// version of the seed. It returns nil if there are no matches.
func MatchSeedCompletion(completions []Completion, seed string) []Completion {
if len(seed) == 0 {
// everything matches
return completions
}
var matches []Completion
lseed := strings.ToLower(seed)
for _, c := range completions {
if IsSeedMatching(lseed, c.Text) {
matches = append(matches, c)
}
}
slices.SortStableFunc(matches, func(a, b Completion) int {
return cmp.Compare(MatchPrecedence(lseed, a.Text), MatchPrecedence(lseed, b.Text))
})
return matches
}
// IsSeedMatching returns whether the given lowercase seed matches
// the given completion string. It checks whether different
// transformations of the completion contain the lowercase
// version of the seed.
func IsSeedMatching(lseed string, completion string) bool {
lc := strings.ToLower(completion)
if strings.Contains(lc, lseed) {
return true
}
// stripped version of completion
// (space delimeted with no punctuation and symbols)
cs := strings.Map(func(r rune) rune {
if unicode.IsPunct(r) || unicode.IsSymbol(r) {
return -1
}
return r
}, completion)
cs = strcase.ToWordCase(cs, strcase.WordLowerCase, ' ')
if strings.Contains(cs, lseed) {
return true
}
// the initials (first letters) of every field
var ci strings.Builder
csdf := strings.FieldsSeq(cs)
for f := range csdf {
ci.WriteString(string(f[0]))
}
return strings.Contains(ci.String(), lseed)
}
// MatchPrecedence returns the sorting precedence of the given
// completion relative to the given lowercase seed. The completion
// is assumed to already match the seed by [IsSeedMatching]. A
// lower return value indicates a higher precedence.
func MatchPrecedence(lseed string, completion string) int {
lc := strings.ToLower(completion)
if strings.HasPrefix(lc, lseed) {
return 0
}
if len(lseed) > 0 && strings.HasPrefix(lc, lseed[:1]) {
return 1
}
return 2
}
// SeedSpace returns the text after the last whitespace,
// which is typically used for creating a completion seed string.
func SeedSpace(text string) string {
return SeedAfter(text, func(r rune) bool {
return unicode.IsSpace(r)
})
}
// SeedPath returns the text after the last whitespace and path/filepath
// separator, which is typically used for creating a completion seed string.
func SeedPath(text string) string {
return SeedAfter(text, func(r rune) bool {
return unicode.IsSpace(r) || r == '/' || r == filepath.Separator
})
}
// SeedAfter returns the text after the last rune for which the given
// function returns true, which is typically used for creating a completion
// seed string.
func SeedAfter(text string, f func(r rune) bool) string {
seedStart := 0
runes := []rune(text)
for i := len(runes) - 1; i >= 0; i-- {
r := runes[i]
if f(r) {
seedStart = i + 1
break
}
}
return string(runes[seedStart:])
}
// EditWord replaces the completion seed and any text up to the next whitespace with completion.
// The cursorPos is a rune position, and the ForwardDelete runes include the seed.
func EditWord(text string, cursorPos int, completion string, seed string) (ed Edit) {
rn := []rune(text)
s2 := rn[min(cursorPos, len(rn)):]
fd := 0 // number of runes past seed in word to be deleted (forward delete)
for fd < len(s2) && !unicode.IsSpace(s2[fd]) {
fd++
}
ed.NewText = completion
ed.ForwardDelete = fd + utf8.RuneCountInString(seed)
ed.CursorAdjust = 0
return ed
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package parse
import (
"fmt"
"sync"
"cogentcore.org/core/base/fileinfo"
"cogentcore.org/core/text/parse/lexer"
"cogentcore.org/core/text/parse/parser"
"cogentcore.org/core/text/parse/syms"
)
// FileState contains the full lexing and parsing state information for a given file.
// It is the master state record for everything that happens in parse. One of these
// should be maintained for each file; [lines.Lines] has one as parseState field.
//
// Separate State structs are maintained for each stage (Lexing, PassTwo, Parsing) and
// the final output of Parsing goes into the AST and Syms fields.
//
// The Src lexer.File field maintains all the info about the source file, and the basic
// tokenized version of the source produced initially by lexing and updated by the
// remaining passes. It has everything that is maintained at a line-by-line level.
type FileState struct {
// the source to be parsed -- also holds the full lexed tokens
Src lexer.File `json:"-" xml:"-"`
// state for lexing
LexState lexer.State `json:"_" xml:"-"`
// state for second pass nesting depth and EOS matching
TwoState lexer.TwoState `json:"-" xml:"-"`
// state for parsing
ParseState parser.State `json:"-" xml:"-"`
// ast output tree from parsing
AST *parser.AST `json:"-" xml:"-"`
// symbols contained within this file -- initialized at start of parsing and created by AddSymbol or PushNewScope actions. These are then processed after parsing by the language-specific code, via Lang interface.
Syms syms.SymMap `json:"-" xml:"-"`
// External symbols that are entirely maintained in a language-specific way by the Lang interface code. These are only here as a convenience and are not accessed in any way by the language-general parse code.
ExtSyms syms.SymMap `json:"-" xml:"-"`
// mutex protecting updates / reading of Syms symbols
SymsMu sync.RWMutex `display:"-" json:"-" xml:"-"`
// waitgroup for coordinating processing of other items
WaitGp sync.WaitGroup `display:"-" json:"-" xml:"-"`
// anonymous counter -- counts up
AnonCtr int `display:"-" json:"-" xml:"-"`
// path mapping cache -- for other files referred to by this file, this stores the full path associated with a logical path (e.g., in go, the logical import path -> local path with actual files) -- protected for access from any thread
PathMap sync.Map `display:"-" json:"-" xml:"-"`
}
// Init initializes the file state
func (fs *FileState) Init() {
// fmt.Println("fs init:", fs.Src.Filename)
fs.AST = parser.NewAST()
fs.LexState.Init()
fs.TwoState.Init()
fs.ParseState.Init(&fs.Src, fs.AST)
fs.SymsMu.Lock()
fs.Syms = make(syms.SymMap)
fs.SymsMu.Unlock()
fs.AnonCtr = 0
}
// NewFileState returns a new initialized file state
func NewFileState() *FileState {
fs := &FileState{}
fs.Init()
return fs
}
func (fs *FileState) ClearAST() {
fs.Syms.ClearAST()
fs.ExtSyms.ClearAST()
}
func (fs *FileState) Destroy() {
fs.ClearAST()
fs.Syms = nil
fs.ExtSyms = nil
fs.AST.Destroy()
fs.LexState.Init()
fs.TwoState.Init()
fs.ParseState.Destroy()
}
// SetSrc sets source to be parsed, and filename it came from, and also the
// base path for project for reporting filenames relative to
// (if empty, path to filename is used)
func (fs *FileState) SetSrc(src [][]rune, fname, basepath string, sup fileinfo.Known) {
fs.Init()
fs.Src.SetSrc(src, fname, basepath, sup)
fs.LexState.Filename = fname
}
// LexAtEnd returns true if lexing state is now at end of source
func (fs *FileState) LexAtEnd() bool {
return fs.LexState.Line >= fs.Src.NLines()
}
// LexLine returns the lexing output for given line, combining comments and all other tokens
// and allocating new memory using clone
func (fs *FileState) LexLine(ln int) lexer.Line {
return fs.Src.LexLine(ln)
}
// LexLineString returns a string rep of the current lexing output for the current line
func (fs *FileState) LexLineString() string {
return fs.LexState.LineString()
}
// LexNextSrcLine returns the next line of source that the lexer is currently at
func (fs *FileState) LexNextSrcLine() string {
return fs.LexState.NextSrcLine()
}
// LexHasErrs returns true if there were errors from lexing
func (fs *FileState) LexHasErrs() bool {
return len(fs.LexState.Errs) > 0
}
// LexErrReport returns a report of all the lexing errors -- these should only
// occur during development of lexer so we use a detailed report format
func (fs *FileState) LexErrReport() string {
return fs.LexState.Errs.Report(0, fs.Src.BasePath, lexer.ShowSrc, lexer.ShowRule)
}
// PassTwoHasErrs returns true if there were errors from pass two processing
func (fs *FileState) PassTwoHasErrs() bool {
return len(fs.TwoState.Errs) > 0
}
// PassTwoErrReport returns all the pass two errors as a string -- these should
// only occur during development so we use a detailed report format
func (fs *FileState) PassTwoErrReport() string {
return fs.TwoState.Errs.Report(0, fs.Src.BasePath, lexer.ShowSrc, lexer.ShowRule)
}
// ParseAtEnd returns true if parsing state is now at end of source
func (fs *FileState) ParseAtEnd() bool {
return fs.ParseState.AtEofNext()
}
// ParseNextSrcLine returns the next line of source that the parser is currently at
func (fs *FileState) ParseNextSrcLine() string {
return fs.ParseState.NextSrcLine()
}
// ParseHasErrs returns true if there were errors from parsing
func (fs *FileState) ParseHasErrs() bool {
return len(fs.ParseState.Errs) > 0
}
// ParseErrReport returns at most 10 parsing errors in end-user format, sorted
func (fs *FileState) ParseErrReport() string {
fs.ParseState.Errs.Sort()
return fs.ParseState.Errs.Report(10, fs.Src.BasePath, lexer.ShowSrc, lexer.NoRule)
}
// ParseErrReportAll returns all parsing errors in end-user format, sorted
func (fs *FileState) ParseErrReportAll() string {
fs.ParseState.Errs.Sort()
return fs.ParseState.Errs.Report(0, fs.Src.BasePath, lexer.ShowSrc, lexer.NoRule)
}
// ParseErrReportDetailed returns at most 10 parsing errors in detailed format, sorted
func (fs *FileState) ParseErrReportDetailed() string {
fs.ParseState.Errs.Sort()
return fs.ParseState.Errs.Report(10, fs.Src.BasePath, lexer.ShowSrc, lexer.ShowRule)
}
// ParseRuleString returns the rule info for entire source -- if full
// then it includes the full stack at each point -- otherwise just the top
// of stack
func (fs *FileState) ParseRuleString(full bool) string {
return fs.ParseState.RuleString(full)
}
////////////////////////////////////////////////////////////////////////
// Syms symbol processing support
// FindNameScoped looks for given symbol name within given map first
// (if non nil) and then in fs.Syms and ExtSyms maps,
// and any children on those global maps that are of subcategory
// token.NameScope (i.e., namespace, module, package, library)
func (fs *FileState) FindNameScoped(nm string, scope syms.SymMap) (*syms.Symbol, bool) {
var sy *syms.Symbol
has := false
if scope != nil {
sy, has = scope.FindName(nm)
if has {
return sy, true
}
}
sy, has = fs.Syms.FindNameScoped(nm)
if has {
return sy, true
}
sy, has = fs.ExtSyms.FindNameScoped(nm)
if has {
return sy, true
}
return nil, false
}
// FindChildren fills out map with direct children of given symbol
// If seed is non-empty it is used as a prefix for filtering children names.
// Returns false if no children were found.
func (fs *FileState) FindChildren(sym *syms.Symbol, seed string, scope syms.SymMap, kids *syms.SymMap) bool {
if len(sym.Children) == 0 {
if sym.Type != "" {
typ, got := fs.FindNameScoped(sym.NonPtrTypeName(), scope)
if got {
sym = typ
} else {
return false
}
}
}
if seed != "" {
sym.Children.FindNamePrefix(seed, kids)
} else {
kids.CopyFrom(sym.Children, true) // src is newer
}
return len(*kids) > 0
}
// FindAnyChildren fills out map with either direct children of given symbol
// or those of the type of this symbol -- useful for completion.
// If seed is non-empty it is used as a prefix for filtering children names.
// Returns false if no children were found.
func (fs *FileState) FindAnyChildren(sym *syms.Symbol, seed string, scope syms.SymMap, kids *syms.SymMap) bool {
if len(sym.Children) == 0 {
if sym.Type != "" {
typ, got := fs.FindNameScoped(sym.NonPtrTypeName(), scope)
if got {
sym = typ
} else {
return false
}
}
}
if seed != "" {
sym.Children.FindNamePrefixRecursive(seed, kids)
} else {
kids.CopyFrom(sym.Children, true) // src is newer
}
return len(*kids) > 0
}
// FindNamePrefixScoped looks for given symbol name prefix within given map first
// (if non nil) and then in fs.Syms and ExtSyms maps,
// and any children on those global maps that are of subcategory
// token.NameScope (i.e., namespace, module, package, library)
// adds to given matches map (which can be nil), for more efficient recursive use
func (fs *FileState) FindNamePrefixScoped(seed string, scope syms.SymMap, matches *syms.SymMap) {
lm := len(*matches)
if scope != nil {
scope.FindNamePrefixRecursive(seed, matches)
}
if len(*matches) != lm {
return
}
fs.Syms.FindNamePrefixScoped(seed, matches)
if len(*matches) != lm {
return
}
fs.ExtSyms.FindNamePrefixScoped(seed, matches)
}
// NextAnonName returns the next anonymous name for this file, using counter here
// and given context name (e.g., package name)
func (fs *FileState) NextAnonName(ctxt string) string {
fs.AnonCtr++
return fmt.Sprintf("anon_%s_%d", ctxt, fs.AnonCtr)
}
// PathMapLoad does a mutex-protected load of PathMap for given string,
// returning value and true if found
func (fs *FileState) PathMapLoad(path string) (string, bool) {
fabs, ok := fs.PathMap.Load(path)
fs.PathMap.Load(path)
if ok {
return fabs.(string), ok
}
return "", ok
}
// PathMapStore does a mutex-protected store of abs path for given path key
func (fs *FileState) PathMapStore(path, abs string) {
fs.PathMap.Store(path, abs)
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package parse
import (
"sync"
"cogentcore.org/core/base/fileinfo"
)
// FileStates contains two FileState's: one is being processed while the
// other is being used externally. The FileStates maintains
// a common set of file information set in each of the FileState items when
// they are used.
type FileStates struct {
// the filename
Filename string
// the known file type, if known (typically only known files are processed)
Known fileinfo.Known
// base path for reporting file names -- this must be set externally e.g., by gide for the project root path
BasePath string
// index of the state that is done
DoneIndex int
// one filestate
FsA FileState
// one filestate
FsB FileState
// mutex locking the switching of Done vs. Proc states
SwitchMu sync.Mutex
// mutex locking the parsing of Proc state -- reading states can happen fine with this locked, but no switching
ProcMu sync.Mutex
// extra meta data associated with this FileStates
Meta map[string]string
}
// NewFileStates returns a new FileStates for given filename, basepath,
// and known file type.
func NewFileStates(fname, basepath string, sup fileinfo.Known) *FileStates {
fs := &FileStates{}
fs.SetSrc(fname, basepath, sup)
return fs
}
// SetSrc sets the source that is processed by this FileStates
// if basepath is empty then it is set to the path for the filename.
func (fs *FileStates) SetSrc(fname, basepath string, sup fileinfo.Known) {
fs.ProcMu.Lock() // make sure processing is done
defer fs.ProcMu.Unlock()
fs.SwitchMu.Lock()
defer fs.SwitchMu.Unlock()
fs.Filename = fname
fs.BasePath = basepath
fs.Known = sup
fs.FsA.SetSrc(nil, fname, basepath, sup)
fs.FsB.SetSrc(nil, fname, basepath, sup)
}
// Done returns the filestate that is done being updated, and is ready for
// use by external clients etc. Proc is the other one which is currently
// being processed by the parser and is not ready to be used externally.
// The state is accessed under a lock, and as long as any use of state is
// fast enough, it should be usable over next two switches (typically true).
func (fs *FileStates) Done() *FileState {
fs.SwitchMu.Lock()
defer fs.SwitchMu.Unlock()
return fs.DoneNoLock()
}
// DoneNoLock returns the filestate that is done being updated, and is ready for
// use by external clients etc. Proc is the other one which is currently
// being processed by the parser and is not ready to be used externally.
// The state is accessed under a lock, and as long as any use of state is
// fast enough, it should be usable over next two switches (typically true).
func (fs *FileStates) DoneNoLock() *FileState {
switch fs.DoneIndex {
case 0:
return &fs.FsA
case 1:
return &fs.FsB
}
return &fs.FsA
}
// Proc returns the filestate that is currently being processed by
// the parser etc and is not ready for external use.
// Access is protected by a lock so it will wait if currently switching.
// The state is accessed under a lock, and as long as any use of state is
// fast enough, it should be usable over next two switches (typically true).
func (fs *FileStates) Proc() *FileState {
fs.SwitchMu.Lock()
defer fs.SwitchMu.Unlock()
return fs.ProcNoLock()
}
// ProcNoLock returns the filestate that is currently being processed by
// the parser etc and is not ready for external use.
// Access is protected by a lock so it will wait if currently switching.
// The state is accessed under a lock, and as long as any use of state is
// fast enough, it should be usable over next two switches (typically true).
func (fs *FileStates) ProcNoLock() *FileState {
switch fs.DoneIndex {
case 0:
return &fs.FsB
case 1:
return &fs.FsA
}
return &fs.FsB
}
// StartProc should be called when starting to process the file, and returns the
// FileState to use for processing. It locks the Proc state, sets the current
// source code, and returns the filestate for subsequent processing.
func (fs *FileStates) StartProc(txt []byte) *FileState {
fs.ProcMu.Lock()
pfs := fs.ProcNoLock()
pfs.Src.BasePath = fs.BasePath
pfs.Src.SetBytes(txt)
return pfs
}
// EndProc is called when primary processing (parsing) has been completed --
// there still may be ongoing updating of symbols after this point but parse
// is done. This calls Switch to move Proc over to done, under cover of ProcMu Lock
func (fs *FileStates) EndProc() {
fs.Switch()
fs.ProcMu.Unlock()
}
// Switch switches so that the current Proc() filestate is now the Done()
// it is assumed to be called under ProcMu.Locking cover, and also
// does the Swtich locking.
func (fs *FileStates) Switch() {
fs.SwitchMu.Lock()
defer fs.SwitchMu.Unlock()
fs.DoneIndex++
fs.DoneIndex = fs.DoneIndex % 2
// fmt.Printf("switched: %v %v\n", fs.DoneIndex, fs.Filename)
}
// MetaData returns given meta data string for given key,
// returns true if present, false if not
func (fs *FileStates) MetaData(key string) (string, bool) {
if fs.Meta == nil {
return "", false
}
md, ok := fs.Meta[key]
return md, ok
}
// SetMetaData sets given meta data record
func (fs *FileStates) SetMetaData(key, value string) {
if fs.Meta == nil {
fs.Meta = make(map[string]string)
}
fs.Meta[key] = value
}
// DeleteMetaData deletes given meta data record
func (fs *FileStates) DeleteMetaData(key string) {
if fs.Meta == nil {
return
}
delete(fs.Meta, key)
}
// Copyright (c) 2020, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copied and only lightly modified from:
// https://github.com/nickng/bibtex
// Licensed under an Apache-2.0 license
// and presumably Copyright (c) 2017 by Nick Ng
// Package bibtex reads BibTeX files of bibliographic references.
package bibtex
import (
"bytes"
"fmt"
"slices"
"sort"
"strconv"
"strings"
"text/tabwriter"
)
// BibString is a segment of a bib string.
type BibString interface {
RawString() string // Internal representation.
String() string // Displayed string.
}
// BibVar is a string variable.
type BibVar struct {
Key string // Variable key.
Value BibString // Variable actual value.
}
// RawString is the internal representation of the variable.
func (v *BibVar) RawString() string {
return v.Key
}
func (v *BibVar) String() string {
if v == nil {
return ""
}
return v.Value.String()
}
// BibConst is a string constant.
type BibConst string
// NewBibConst converts a constant string to BibConst.
func NewBibConst(c string) BibConst {
return BibConst(c)
}
// RawString is the internal representation of the constant (i.e. the string).
func (c BibConst) RawString() string {
return fmt.Sprintf("{%s}", string(c))
}
func (c BibConst) String() string {
return string(c)
}
// BibComposite is a composite string, may contain both variable and string.
type BibComposite []BibString
// NewBibComposite creates a new composite with one element.
func NewBibComposite(s BibString) *BibComposite {
comp := &BibComposite{}
return comp.Append(s)
}
// Append adds a BibString to the composite
func (c *BibComposite) Append(s BibString) *BibComposite {
*c = append(*c, s) // the composite itself, as the grammar uses it
return c
}
func (c *BibComposite) String() string {
var buf bytes.Buffer
for _, s := range *c {
buf.WriteString(s.String())
}
return buf.String()
}
// RawString returns a raw (bibtex) representation of the composite string.
func (c *BibComposite) RawString() string {
var buf bytes.Buffer
for i, comp := range *c {
if i > 0 {
buf.WriteString(" # ")
}
buf.WriteString(comp.RawString())
}
return buf.String()
}
// BibEntry is a record of BibTeX record.
type BibEntry struct {
Type string
CiteName string
Fields map[string]BibString
}
// NewBibEntry creates a new BibTeX entry.
func NewBibEntry(entryType string, citeName string) *BibEntry {
spaceStripper := strings.NewReplacer(" ", "")
cleanedType := strings.ToLower(spaceStripper.Replace(entryType))
cleanedName := spaceStripper.Replace(citeName)
return &BibEntry{
Type: cleanedType,
CiteName: cleanedName,
Fields: map[string]BibString{},
}
}
// AddField adds a field (key-value) to a BibTeX entry.
func (entry *BibEntry) AddField(name string, value BibString) {
entry.Fields[strings.TrimSpace(name)] = value
}
// BibTex is a list of BibTeX entries.
type BibTex struct {
Preambles []BibString // List of Preambles
Entries []*BibEntry // Items in a bibliography.
KeyMap map[string]*BibEntry // fast key lookup map -- made on demand in Lookup
StringVar map[string]*BibVar // Map from string variable to string.
}
// NewBibTex creates a new BibTex data structure.
func NewBibTex() *BibTex {
return &BibTex{
Preambles: []BibString{},
Entries: []*BibEntry{},
StringVar: make(map[string]*BibVar),
}
}
// AddPreamble adds a preamble to a bibtex.
func (bib *BibTex) AddPreamble(p BibString) {
bib.Preambles = append(bib.Preambles, p)
}
// AddEntry adds an entry to the BibTeX data structure.
func (bib *BibTex) AddEntry(entry *BibEntry) {
bib.Entries = append(bib.Entries, entry)
}
// AddStringVar adds a new string var (if does not exist).
func (bib *BibTex) AddStringVar(key string, val BibString) {
bib.StringVar[key] = &BibVar{Key: key, Value: val}
}
// SortEntries sorts entries by CiteName.
func (bib *BibTex) SortEntries() {
slices.SortFunc(bib.Entries, func(a, b *BibEntry) int {
return strings.Compare(a.CiteName, b.CiteName)
})
}
// GetStringVar looks up a string by its key.
func (bib *BibTex) GetStringVar(key string) *BibVar {
if bv, ok := bib.StringVar[key]; ok {
return bv
}
// at this point, key is usually a month -- just pass through
bib.AddStringVar(key, NewBibConst(key))
return bib.StringVar[key]
}
// String returns a BibTex data structure as a simplified BibTex string.
func (bib *BibTex) String() string {
var bibtex bytes.Buffer
for _, entry := range bib.Entries {
fmt.Fprintf(&bibtex, "@%s{%s,\n", entry.Type, entry.CiteName)
for key, val := range entry.Fields {
if i, err := strconv.Atoi(strings.TrimSpace(val.String())); err == nil {
fmt.Fprintf(&bibtex, " %s = %d,\n", key, i)
} else {
fmt.Fprintf(&bibtex, " %s = {%s},\n", key, strings.TrimSpace(val.String()))
}
}
bibtex.Truncate(bibtex.Len() - 2)
fmt.Fprintf(&bibtex, "\n}\n")
}
return bibtex.String()
}
// RawString returns a BibTex data structure in its internal representation.
func (bib *BibTex) RawString() string {
var bibtex bytes.Buffer
for k, strvar := range bib.StringVar {
fmt.Fprintf(&bibtex, "@string{%s = {%s}}\n", k, strvar.String())
}
for _, preamble := range bib.Preambles {
fmt.Fprintf(&bibtex, "@preamble{%s}\n", preamble.RawString())
}
for _, entry := range bib.Entries {
fmt.Fprintf(&bibtex, "@%s{%s,\n", entry.Type, entry.CiteName)
for key, val := range entry.Fields {
if i, err := strconv.Atoi(strings.TrimSpace(val.String())); err == nil {
fmt.Fprintf(&bibtex, " %s = %d,\n", key, i)
} else {
fmt.Fprintf(&bibtex, " %s = %s,\n", key, val.RawString())
}
}
bibtex.Truncate(bibtex.Len() - 2)
fmt.Fprintf(&bibtex, "\n}\n")
}
return bibtex.String()
}
// PrettyString pretty prints a BibTex.
func (bib *BibTex) PrettyString() string {
var buf bytes.Buffer
for i, entry := range bib.Entries {
if i != 0 {
fmt.Fprint(&buf, "\n")
}
fmt.Fprintf(&buf, "@%s{%s,\n", entry.Type, entry.CiteName)
// Determine key order.
keys := []string{}
for key := range entry.Fields {
keys = append(keys, key)
}
priority := map[string]int{"title": -3, "author": -2, "url": -1}
sort.Slice(keys, func(i, j int) bool {
pi, pj := priority[keys[i]], priority[keys[j]]
return pi < pj || (pi == pj && keys[i] < keys[j])
})
// Write fields.
tw := tabwriter.NewWriter(&buf, 1, 4, 1, ' ', 0)
for _, key := range keys {
value := entry.Fields[key].String()
format := stringformat(value)
fmt.Fprintf(tw, " %s\t=\t"+format+",\n", key, value)
}
tw.Flush()
// Close.
buf.WriteString("}\n")
}
return buf.String()
}
// stringformat determines the correct formatting verb for the given BibTeX field value.
func stringformat(v string) string {
// Numbers may be represented unquoted.
if _, err := strconv.Atoi(v); err == nil {
return "%s"
}
// Strings with certain characters must be brace quoted.
if strings.ContainsAny(v, "\"{}") {
return "{%s}"
}
// Default to quoted string.
return "%q"
}
// MakeKeyMap creates the KeyMap from CiteName to entry
func (bib *BibTex) MakeKeyMap() {
bib.KeyMap = make(map[string]*BibEntry, len(bib.Entries))
for _, be := range bib.Entries {
bib.KeyMap[be.CiteName] = be
}
}
// Lookup finds CiteName in entries, using fast KeyMap (made on demand)
// returns nil, false if not found
func (bib *BibTex) Lookup(cite string) (*BibEntry, bool) {
if bib.KeyMap == nil {
bib.MakeKeyMap()
}
be, has := bib.KeyMap[cite]
return be, has
}
// Copyright (c) 2020, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copied and only lightly modified from:
// https://github.com/nickng/bibtex
// Licensed under an Apache-2.0 license
// and presumably Copyright (c) 2017 by Nick Ng
package bibtex
import __yyfmt__ "fmt"
import (
"io"
)
type bibTag struct {
key string
val BibString
}
var bib *BibTex // Only for holding current bib
type bibtexSymType struct {
yys int
bibtex *BibTex
strval string
bibentry *BibEntry
bibtag *bibTag
bibtags []*bibTag
strings BibString
}
const COMMENT = 57346
const STRING = 57347
const PREAMBLE = 57348
const ATSIGN = 57349
const COLON = 57350
const EQUAL = 57351
const COMMA = 57352
const POUND = 57353
const LBRACE = 57354
const RBRACE = 57355
const DQUOTE = 57356
const LPAREN = 57357
const RPAREN = 57358
const BAREIDENT = 57359
const IDENT = 57360
var bibtexToknames = [...]string{
"$end",
"error",
"$unk",
"COMMENT",
"STRING",
"PREAMBLE",
"ATSIGN",
"COLON",
"EQUAL",
"COMMA",
"POUND",
"LBRACE",
"RBRACE",
"DQUOTE",
"LPAREN",
"RPAREN",
"BAREIDENT",
"IDENT",
}
var bibtexStatenames = [...]string{}
const bibtexEofCode = 1
const bibtexErrCode = 2
const bibtexInitialStackSize = 16
// Parse is the entry point to the bibtex parser.
func Parse(r io.Reader) (*BibTex, error) {
l := NewLexer(r)
bibtexParse(l)
select {
case err := <-l.Errors:
return nil, err
default:
return bib, nil
}
}
var bibtexExca = [...]int8{
-1, 1,
1, -1,
-2, 0,
}
const bibtexPrivate = 57344
const bibtexLast = 61
var bibtexAct = [...]int8{
22, 39, 40, 41, 9, 10, 11, 24, 23, 44,
43, 27, 26, 33, 21, 48, 25, 8, 52, 28,
29, 50, 33, 33, 20, 31, 18, 38, 34, 19,
49, 16, 14, 42, 17, 15, 45, 46, 12, 33,
33, 13, 51, 48, 36, 33, 47, 37, 30, 35,
54, 53, 33, 7, 32, 4, 1, 6, 5, 3,
2,
}
var bibtexPact = [...]int16{
-32768, -32768, 46, -32768, -32768, -32768, -32768, 0, 26, 20,
19, 14, 7, -3, -10, -10, -5, -6, -10, -10,
38, 15, 41, -32768, -32768, 12, 40, 35, 34, 11,
-14, -14, -32768, -8, -32768, -10, -10, -32768, -32768, 33,
-32768, 21, 5, -32768, -32768, 29, 2, -32768, -14, -10,
-32768, -32768, -32768, -32768, 28,
}
var bibtexPgo = [...]int8{
0, 60, 59, 2, 58, 1, 0, 57, 56, 55,
}
var bibtexR1 = [...]int8{
0, 8, 1, 1, 1, 1, 1, 2, 2, 9,
9, 4, 4, 7, 7, 6, 6, 6, 6, 3,
3, 5, 5,
}
var bibtexR2 = [...]int8{
0, 1, 0, 2, 2, 2, 2, 7, 7, 5,
5, 7, 7, 5, 5, 1, 1, 3, 3, 0,
3, 1, 3,
}
var bibtexChk = [...]int16{
-32768, -8, -1, -2, -9, -4, -7, 7, 17, 4,
5, 6, 12, 15, 12, 15, 12, 15, 12, 15,
17, 17, -6, 18, 17, -6, 17, 17, -6, -6,
10, 10, 13, 11, 16, 9, 9, 13, 16, -5,
-3, 17, -5, 18, 17, -6, -6, 13, 10, 9,
16, 13, 16, -3, -6,
}
var bibtexDef = [...]int8{
2, -2, 1, 3, 4, 5, 6, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 15, 16, 0, 0, 0, 0, 0,
19, 19, 9, 0, 10, 0, 0, 13, 14, 0,
21, 0, 0, 17, 18, 0, 0, 7, 19, 0,
8, 11, 12, 22, 20,
}
var bibtexTok1 = [...]int8{
1,
}
var bibtexTok2 = [...]int8{
2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18,
}
var bibtexTok3 = [...]int8{
0,
}
var bibtexErrorMessages = [...]struct {
state int
token int
msg string
}{}
/* parser for yacc output */
var (
bibtexDebug = 0
bibtexErrorVerbose = false
)
type bibtexLexer interface {
Lex(lval *bibtexSymType) int
Error(s string)
}
type bibtexParser interface {
Parse(bibtexLexer) int
Lookahead() int
}
type bibtexParserImpl struct {
lval bibtexSymType
stack [bibtexInitialStackSize]bibtexSymType
char int
}
func (p *bibtexParserImpl) Lookahead() int {
return p.char
}
func bibtexNewParser() bibtexParser {
return &bibtexParserImpl{}
}
const bibtexFlag = -32768
func bibtexTokname(c int) string {
if c >= 1 && c-1 < len(bibtexToknames) {
if bibtexToknames[c-1] != "" {
return bibtexToknames[c-1]
}
}
return __yyfmt__.Sprintf("tok-%v", c)
}
func bibtexStatname(s int) string {
if s >= 0 && s < len(bibtexStatenames) {
if bibtexStatenames[s] != "" {
return bibtexStatenames[s]
}
}
return __yyfmt__.Sprintf("state-%v", s)
}
func bibtexErrorMessage(state, lookAhead int) string {
const TOKSTART = 4
if !bibtexErrorVerbose {
return "syntax error"
}
for _, e := range bibtexErrorMessages {
if e.state == state && e.token == lookAhead {
return "syntax error: " + e.msg
}
}
res := "syntax error: unexpected " + bibtexTokname(lookAhead)
// To match Bison, suggest at most four expected tokens.
expected := make([]int, 0, 4)
// Look for shiftable tokens.
base := int(bibtexPact[state])
for tok := TOKSTART; tok-1 < len(bibtexToknames); tok++ {
if n := base + tok; n >= 0 && n < bibtexLast && int(bibtexChk[int(bibtexAct[n])]) == tok {
if len(expected) == cap(expected) {
return res
}
expected = append(expected, tok)
}
}
if bibtexDef[state] == -2 {
i := 0
for bibtexExca[i] != -1 || int(bibtexExca[i+1]) != state {
i += 2
}
// Look for tokens that we accept or reduce.
for i += 2; bibtexExca[i] >= 0; i += 2 {
tok := int(bibtexExca[i])
if tok < TOKSTART || bibtexExca[i+1] == 0 {
continue
}
if len(expected) == cap(expected) {
return res
}
expected = append(expected, tok)
}
// If the default action is to accept or reduce, give up.
if bibtexExca[i+1] != 0 {
return res
}
}
for i, tok := range expected {
if i == 0 {
res += ", expecting "
} else {
res += " or "
}
res += bibtexTokname(tok)
}
return res
}
func bibtexlex1(lex bibtexLexer, lval *bibtexSymType) (char, token int) {
token = 0
char = lex.Lex(lval)
if char <= 0 {
token = int(bibtexTok1[0])
goto out
}
if char < len(bibtexTok1) {
token = int(bibtexTok1[char])
goto out
}
if char >= bibtexPrivate {
if char < bibtexPrivate+len(bibtexTok2) {
token = int(bibtexTok2[char-bibtexPrivate])
goto out
}
}
for i := 0; i < len(bibtexTok3); i += 2 {
token = int(bibtexTok3[i+0])
if token == char {
token = int(bibtexTok3[i+1])
goto out
}
}
out:
if token == 0 {
token = int(bibtexTok2[1]) /* unknown char */
}
if bibtexDebug >= 3 {
__yyfmt__.Printf("lex %s(%d)\n", bibtexTokname(token), uint(char))
}
return char, token
}
func bibtexParse(bibtexlex bibtexLexer) int {
return bibtexNewParser().Parse(bibtexlex)
}
func (bibtexrcvr *bibtexParserImpl) Parse(bibtexlex bibtexLexer) int {
var bibtexn int
var bibtexVAL bibtexSymType
var bibtexDollar []bibtexSymType
_ = bibtexDollar // silence set and not used
bibtexS := bibtexrcvr.stack[:]
Nerrs := 0 /* number of errors */
Errflag := 0 /* error recovery flag */
bibtexstate := 0
bibtexrcvr.char = -1
bibtextoken := -1 // bibtexrcvr.char translated into internal numbering
defer func() {
// Make sure we report no lookahead when not parsing.
bibtexstate = -1
bibtexrcvr.char = -1
bibtextoken = -1
}()
bibtexp := -1
goto bibtexstack
ret0:
return 0
ret1:
return 1
bibtexstack:
/* put a state and value onto the stack */
if bibtexDebug >= 4 {
__yyfmt__.Printf("char %v in %v\n", bibtexTokname(bibtextoken), bibtexStatname(bibtexstate))
}
bibtexp++
if bibtexp >= len(bibtexS) {
nyys := make([]bibtexSymType, len(bibtexS)*2)
copy(nyys, bibtexS)
bibtexS = nyys
}
bibtexS[bibtexp] = bibtexVAL
bibtexS[bibtexp].yys = bibtexstate
bibtexnewstate:
bibtexn = int(bibtexPact[bibtexstate])
if bibtexn <= bibtexFlag {
goto bibtexdefault /* simple state */
}
if bibtexrcvr.char < 0 {
bibtexrcvr.char, bibtextoken = bibtexlex1(bibtexlex, &bibtexrcvr.lval)
}
bibtexn += bibtextoken
if bibtexn < 0 || bibtexn >= bibtexLast {
goto bibtexdefault
}
bibtexn = int(bibtexAct[bibtexn])
if int(bibtexChk[bibtexn]) == bibtextoken { /* valid shift */
bibtexrcvr.char = -1
bibtextoken = -1
bibtexVAL = bibtexrcvr.lval
bibtexstate = bibtexn
if Errflag > 0 {
Errflag--
}
goto bibtexstack
}
bibtexdefault:
/* default state action */
bibtexn = int(bibtexDef[bibtexstate])
if bibtexn == -2 {
if bibtexrcvr.char < 0 {
bibtexrcvr.char, bibtextoken = bibtexlex1(bibtexlex, &bibtexrcvr.lval)
}
/* look through exception table */
xi := 0
for {
if bibtexExca[xi+0] == -1 && int(bibtexExca[xi+1]) == bibtexstate {
break
}
xi += 2
}
for xi += 2; ; xi += 2 {
bibtexn = int(bibtexExca[xi+0])
if bibtexn < 0 || bibtexn == bibtextoken {
break
}
}
bibtexn = int(bibtexExca[xi+1])
if bibtexn < 0 {
goto ret0
}
}
if bibtexn == 0 {
/* error ... attempt to resume parsing */
switch Errflag {
case 0: /* brand new error */
bibtexlex.Error(bibtexErrorMessage(bibtexstate, bibtextoken))
Nerrs++
if bibtexDebug >= 1 {
__yyfmt__.Printf("%s", bibtexStatname(bibtexstate))
__yyfmt__.Printf(" saw %s\n", bibtexTokname(bibtextoken))
}
fallthrough
case 1, 2: /* incompletely recovered error ... try again */
Errflag = 3
/* find a state where "error" is a legal shift action */
for bibtexp >= 0 {
bibtexn = int(bibtexPact[bibtexS[bibtexp].yys]) + bibtexErrCode
if bibtexn >= 0 && bibtexn < bibtexLast {
bibtexstate = int(bibtexAct[bibtexn]) /* simulate a shift of "error" */
if int(bibtexChk[bibtexstate]) == bibtexErrCode {
goto bibtexstack
}
}
/* the current p has no shift on "error", pop stack */
if bibtexDebug >= 2 {
__yyfmt__.Printf("error recovery pops state %d\n", bibtexS[bibtexp].yys)
}
bibtexp--
}
/* there is no state on the stack with an error shift ... abort */
goto ret1
case 3: /* no shift yet; clobber input char */
if bibtexDebug >= 2 {
__yyfmt__.Printf("error recovery discards %s\n", bibtexTokname(bibtextoken))
}
if bibtextoken == bibtexEofCode {
goto ret1
}
bibtexrcvr.char = -1
bibtextoken = -1
goto bibtexnewstate /* try again in the same state */
}
}
/* reduction by production bibtexn */
if bibtexDebug >= 2 {
__yyfmt__.Printf("reduce %v in:\n\t%v\n", bibtexn, bibtexStatname(bibtexstate))
}
bibtexnt := bibtexn
bibtexpt := bibtexp
_ = bibtexpt // guard against "declared and not used"
bibtexp -= int(bibtexR2[bibtexn])
// bibtexp is now the index of $0. Perform the default action. Iff the
// reduced production is ε, $1 is possibly out of range.
if bibtexp+1 >= len(bibtexS) {
nyys := make([]bibtexSymType, len(bibtexS)*2)
copy(nyys, bibtexS)
bibtexS = nyys
}
bibtexVAL = bibtexS[bibtexp+1]
/* consult goto table to find next state */
bibtexn = int(bibtexR1[bibtexn])
bibtexg := int(bibtexPgo[bibtexn])
bibtexj := bibtexg + bibtexS[bibtexp].yys + 1
if bibtexj >= bibtexLast {
bibtexstate = int(bibtexAct[bibtexg])
} else {
bibtexstate = int(bibtexAct[bibtexj])
if int(bibtexChk[bibtexstate]) != -bibtexn {
bibtexstate = int(bibtexAct[bibtexg])
}
}
// dummy call; replaced with literal code
switch bibtexnt {
case 1:
bibtexDollar = bibtexS[bibtexpt-1 : bibtexpt+1]
{
}
case 2:
bibtexDollar = bibtexS[bibtexpt-0 : bibtexpt+1]
{
bibtexVAL.bibtex = NewBibTex()
bib = bibtexVAL.bibtex
}
case 3:
bibtexDollar = bibtexS[bibtexpt-2 : bibtexpt+1]
{
bibtexVAL.bibtex = bibtexDollar[1].bibtex
bibtexVAL.bibtex.AddEntry(bibtexDollar[2].bibentry)
}
case 4:
bibtexDollar = bibtexS[bibtexpt-2 : bibtexpt+1]
{
bibtexVAL.bibtex = bibtexDollar[1].bibtex
}
case 5:
bibtexDollar = bibtexS[bibtexpt-2 : bibtexpt+1]
{
bibtexVAL.bibtex = bibtexDollar[1].bibtex
bibtexVAL.bibtex.AddStringVar(bibtexDollar[2].bibtag.key, bibtexDollar[2].bibtag.val)
}
case 6:
bibtexDollar = bibtexS[bibtexpt-2 : bibtexpt+1]
{
bibtexVAL.bibtex = bibtexDollar[1].bibtex
bibtexVAL.bibtex.AddPreamble(bibtexDollar[2].strings)
}
case 7:
bibtexDollar = bibtexS[bibtexpt-7 : bibtexpt+1]
{
bibtexVAL.bibentry = NewBibEntry(bibtexDollar[2].strval, bibtexDollar[4].strval)
for _, t := range bibtexDollar[6].bibtags {
bibtexVAL.bibentry.AddField(t.key, t.val)
}
}
case 8:
bibtexDollar = bibtexS[bibtexpt-7 : bibtexpt+1]
{
bibtexVAL.bibentry = NewBibEntry(bibtexDollar[2].strval, bibtexDollar[4].strval)
for _, t := range bibtexDollar[6].bibtags {
bibtexVAL.bibentry.AddField(t.key, t.val)
}
}
case 9:
bibtexDollar = bibtexS[bibtexpt-5 : bibtexpt+1]
{
}
case 10:
bibtexDollar = bibtexS[bibtexpt-5 : bibtexpt+1]
{
}
case 11:
bibtexDollar = bibtexS[bibtexpt-7 : bibtexpt+1]
{
bibtexVAL.bibtag = &bibTag{key: bibtexDollar[4].strval, val: bibtexDollar[6].strings}
}
case 12:
bibtexDollar = bibtexS[bibtexpt-7 : bibtexpt+1]
{
bibtexVAL.bibtag = &bibTag{key: bibtexDollar[4].strval, val: bibtexDollar[6].strings}
}
case 13:
bibtexDollar = bibtexS[bibtexpt-5 : bibtexpt+1]
{
bibtexVAL.strings = bibtexDollar[4].strings
}
case 14:
bibtexDollar = bibtexS[bibtexpt-5 : bibtexpt+1]
{
bibtexVAL.strings = bibtexDollar[4].strings
}
case 15:
bibtexDollar = bibtexS[bibtexpt-1 : bibtexpt+1]
{
bibtexVAL.strings = NewBibConst(bibtexDollar[1].strval)
}
case 16:
bibtexDollar = bibtexS[bibtexpt-1 : bibtexpt+1]
{
bibtexVAL.strings = bib.GetStringVar(bibtexDollar[1].strval)
}
case 17:
bibtexDollar = bibtexS[bibtexpt-3 : bibtexpt+1]
{
bibtexVAL.strings = NewBibComposite(bibtexDollar[1].strings)
bibtexVAL.strings.(*BibComposite).Append(NewBibConst(bibtexDollar[3].strval))
}
case 18:
bibtexDollar = bibtexS[bibtexpt-3 : bibtexpt+1]
{
bibtexVAL.strings = NewBibComposite(bibtexDollar[1].strings)
bibtexVAL.strings.(*BibComposite).Append(bib.GetStringVar(bibtexDollar[3].strval))
}
case 19:
bibtexDollar = bibtexS[bibtexpt-0 : bibtexpt+1]
{
}
case 20:
bibtexDollar = bibtexS[bibtexpt-3 : bibtexpt+1]
{
bibtexVAL.bibtag = &bibTag{key: bibtexDollar[1].strval, val: bibtexDollar[3].strings}
}
case 21:
bibtexDollar = bibtexS[bibtexpt-1 : bibtexpt+1]
{
bibtexVAL.bibtags = []*bibTag{bibtexDollar[1].bibtag}
}
case 22:
bibtexDollar = bibtexS[bibtexpt-3 : bibtexpt+1]
{
if bibtexDollar[3].bibtag == nil {
bibtexVAL.bibtags = bibtexDollar[1].bibtags
} else {
bibtexVAL.bibtags = append(bibtexDollar[1].bibtags, bibtexDollar[3].bibtag)
}
}
}
goto bibtexstack /* stack new state and value */
}
// Copyright (c) 2020, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copied and only lightly modified from:
// https://github.com/nickng/bibtex
// Licensed under an Apache-2.0 license
// and presumably Copyright (c) 2017 by Nick Ng
package bibtex
import (
"errors"
"fmt"
)
var (
// ErrUnexpectedAtsign is an error for unexpected @ in {}.
ErrUnexpectedAtsign = errors.New("unexpected @ sign")
// ErrUnknownStringVar is an error for looking up undefined string var.
ErrUnknownStringVar = errors.New("unknown string variable")
)
// ErrParse is a parse error.
type ErrParse struct {
Pos TokenPos
Err string // Error string returned from parser.
}
func (e *ErrParse) Error() string {
return fmt.Sprintf("Parse failed at %s: %s", e.Pos, e.Err)
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package bibtex
import (
"errors"
"fmt"
"os"
"path/filepath"
"time"
)
// File maintains a record for an bibtex file
type File struct {
// file name -- full path
File string
// bibtex data loaded from file
BibTex *BibTex
// mod time for loaded bibfile -- to detect updates
Mod time.Time
}
// FullPath returns full path to given bibtex file,
// looking on standard BIBINPUTS or TEXINPUTS env var paths if not found locally.
func FullPath(fname string) (string, error) {
_, err := os.Stat(fname)
path := fname
nfErr := fmt.Errorf("bibtex file not found, even on BIBINPUTS or TEXINPUTS paths: %s", fname)
if os.IsNotExist(err) {
bin := os.Getenv("BIBINPUTS")
if bin == "" {
bin = os.Getenv("TEXINPUTS")
}
if bin == "" {
return "", errors.New("BIBINPUTS and TEXINPUTS variables are empty")
}
pth := filepath.SplitList(bin)
got := false
for _, p := range pth {
bf := filepath.Join(p, fname)
_, err = os.Stat(bf)
if err == nil {
path = bf
got = true
break
}
}
if !got {
return "", nfErr
}
}
path, err = filepath.Abs(path)
if err != nil {
return path, err
}
return path, nil
}
// Open [re]opens the given filename, looking on standard BIBINPUTS or TEXINPUTS
// env var paths if not found locally. If Mod >= mod timestamp on the file,
// and BibTex is already loaded, then nothing happens (already have it), but
// otherwise it parses the file and puts contents in BibTex field.
func (fl *File) Open(fname string) error {
path := fname
var err error
if fl.File == "" {
path, err = FullPath(fname)
if err != nil {
return err
}
fl.File = path
fl.BibTex = nil
fl.Mod = time.Time{}
// fmt.Printf("first open file: %s path: %s\n", fname, fl.File)
}
st, err := os.Stat(fl.File)
if err != nil {
return err
}
if fl.BibTex != nil && !fl.Mod.Before(st.ModTime()) {
// fmt.Printf("existing file: %v is fine: file mod: %v last mod: %v\n", fl.File, st.ModTime(), fl.Mod)
return nil
}
f, err := os.Open(fl.File)
if err != nil {
return err
}
defer f.Close()
parsed, err := Parse(f)
if err != nil {
err = fmt.Errorf("the BibTeX bibliography %s was not loaded due to error(s):\n%v", fl.File, err)
return err
}
fl.BibTex = parsed
fl.Mod = st.ModTime()
// fmt.Printf("(re)loaded bibtex bibliography: %s\n", fl.File)
return nil
}
//////// Files
// Files is a map of bibtex files
type Files map[string]*File
// Open [re]opens the given filename, looking on standard BIBINPUTS or TEXINPUTS
// env var paths if not found locally. If Mod >= mod timestamp on the file,
// and BibTex is already loaded, then nothing happens (already have it), but
// otherwise it parses the file and puts contents in BibTex field.
func (fl *Files) Open(fname string) (*File, error) {
if *fl == nil {
*fl = make(Files)
}
fr, has := (*fl)[fname]
if has {
err := fr.Open(fname)
return fr, err
}
fr = &File{}
err := fr.Open(fname)
if err != nil {
return nil, err
}
(*fl)[fname] = fr
return fr, nil
}
// Copyright (c) 2020, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copied and only lightly modified from:
// https://github.com/nickng/bibtex
// Licensed under an Apache-2.0 license
// and presumably Copyright (c) 2017 by Nick Ng
//go:generate goyacc -p bibtex -o bibtex.y.go bibtex.y
package bibtex
import "io"
// Lexer for bibtex.
type Lexer struct {
scanner *Scanner
Errors chan error
}
// NewLexer returns a new yacc-compatible lexer.
func NewLexer(r io.Reader) *Lexer {
return &Lexer{scanner: NewScanner(r), Errors: make(chan error, 1)}
}
// Lex is provided for yacc-compatible parser.
func (l *Lexer) Lex(yylval *bibtexSymType) int {
token, strval := l.scanner.Scan()
yylval.strval = strval
return int(token)
}
// Error handles error.
func (l *Lexer) Error(err string) {
l.Errors <- &ErrParse{Err: err, Pos: l.scanner.pos}
}
// Copyright (c) 2020, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copied and only lightly modified from:
// https://github.com/nickng/bibtex
// Licensed under an Apache-2.0 license
// and presumably Copyright (c) 2017 by Nick Ng
package bibtex
import (
"bufio"
"bytes"
"io"
"strconv"
"strings"
)
// Scanner is a lexical scanner
type Scanner struct {
r *bufio.Reader
pos TokenPos
// parseField is whether a field value is being scanned (after an =),
// in which a brace starts a braced string.
parseField bool
// depth is the depth of the braces or parentheses of the current entry:
// the text outside of entries (at depth 0, before an @) is ignored,
// as comments, as in BibTeX.
depth int
// inEntry is whether an entry has been started with an @.
inEntry bool
// lastTok is the last token returned.
lastTok Token
// pending are tokens to return before scanning more.
pending []pendingToken
}
// pendingToken is a token with its literal value.
type pendingToken struct {
tok Token
lit string
}
// NewScanner returns a new instance of Scanner.
func NewScanner(r io.Reader) *Scanner {
return &Scanner{r: bufio.NewReader(r), pos: TokenPos{Char: 0, Lines: []int{}}}
}
// read reads the next rune from the buffered reader.
// Returns the rune(0) if an error occurs (or io.eof is returned).
func (s *Scanner) read() rune {
ch, _, err := s.r.ReadRune()
if err != nil {
return eof
}
if ch == '\n' {
s.pos.Lines = append(s.pos.Lines, s.pos.Char)
s.pos.Char = 0
} else {
s.pos.Char++
}
return ch
}
// unread places the previously read rune back on the reader.
func (s *Scanner) unread() {
_ = s.r.UnreadRune()
if s.pos.Char == 0 {
s.pos.Char = s.pos.Lines[len(s.pos.Lines)-1]
s.pos.Lines = s.pos.Lines[:len(s.pos.Lines)-1]
} else {
s.pos.Char--
}
}
// Scan returns the next token and literal value.
func (s *Scanner) Scan() (tok Token, lit string) {
tok, lit = s.scan()
s.lastTok = tok
return
}
// scan returns the next token and literal value (see [Scanner.Scan]).
func (s *Scanner) scan() (tok Token, lit string) {
if len(s.pending) > 0 {
p := s.pending[0]
s.pending = s.pending[1:]
return p.tok, p.lit
}
ch := s.read()
if !s.inEntry { // text outside of entries is ignored, up to an @
for ch != '@' && ch != eof {
ch = s.read()
}
}
if isWhitespace(ch) {
s.ignoreWhitespace()
ch = s.read()
}
if isAlphanum(ch) {
s.unread()
return s.scanIdent()
}
switch ch {
case eof:
return 0, ""
case '@':
s.inEntry = true
return ATSIGN, string(ch)
case ':':
return COLON, string(ch)
case ',':
s.parseField = false // reset parseField if reached end of field.
return COMMA, string(ch)
case '=':
s.parseField = true // set parseField if = sign outside quoted or ident.
return EQUAL, string(ch)
case '"':
return s.scanQuoted()
case '{', '(':
if ch == '{' && s.parseField {
return s.scanBraced()
}
open, close := Token(LBRACE), Token(RBRACE)
if ch == '(' {
open, close = LPAREN, RPAREN
}
if s.lastTok == COMMENT { // the text of a comment, as it is
text := s.scanUntilClose(ch)
s.pending = append(s.pending, pendingToken{IDENT, text}, pendingToken{close, ""})
s.inEntry = false
return open, string(ch)
}
s.depth++
if s.lastTok == PREAMBLE { // its content is a value, as after an =
s.parseField = true
}
return open, string(ch)
case '}', ')':
s.parseField = false // reset parseField if reached end of entry.
s.depth--
if s.depth <= 0 {
s.depth = 0
s.inEntry = false
}
if ch == ')' {
return RPAREN, string(ch)
}
return RBRACE, string(ch)
case '#':
return POUND, string(ch)
case ' ':
s.ignoreWhitespace()
}
return ILLEGAL, string(ch)
}
// scanIdent categorises a string to one of three categories.
func (s *Scanner) scanIdent() (tok Token, lit string) {
switch ch := s.read(); ch {
case '"':
return s.scanQuoted()
case '{':
return s.scanBraced()
default:
s.unread() // Not open quote/brace.
return s.scanBare()
}
}
func (s *Scanner) scanBare() (Token, string) {
var buf bytes.Buffer
for {
ch := s.read()
if ch == eof {
break
}
if !isAlphanum(ch) && !isBareSymbol(ch) || isWhitespace(ch) {
s.unread()
break
}
_, _ = buf.WriteRune(ch)
}
str := buf.String()
if strings.ToLower(str) == "comment" {
return COMMENT, str
} else if strings.ToLower(str) == "preamble" {
return PREAMBLE, str
} else if strings.ToLower(str) == "string" {
return STRING, str
} else if _, err := strconv.Atoi(str); err == nil && s.parseField { // Special case for numeric
return IDENT, str
}
return BAREIDENT, str
}
// scanBraced parses a braced string, like {this}.
func (s *Scanner) scanBraced() (Token, string) {
var buf bytes.Buffer
var macro bool
brace := 1
for {
if ch := s.read(); ch == eof {
break
} else if ch == '\\' {
_, _ = buf.WriteRune(ch)
macro = true
} else if ch == '{' {
_, _ = buf.WriteRune(ch)
brace++
} else if ch == '}' {
brace--
macro = false
if brace == 0 { // Balances open brace.
return IDENT, buf.String()
}
_, _ = buf.WriteRune(ch)
} else if ch == '@' {
if macro {
_, _ = buf.WriteRune(ch)
// } else {
// log.Printf("%s: %s", ErrUnexpectedAtsign, buf.String())
}
} else if isWhitespace(ch) {
_, _ = buf.WriteRune(ch)
macro = false
} else {
_, _ = buf.WriteRune(ch)
}
}
return ILLEGAL, buf.String()
}
// scanUntilClose returns the text up to the given open brace or
// parenthesis that matches it, which is read too.
func (s *Scanner) scanUntilClose(open rune) string {
close := '}'
if open == '(' {
close = ')'
}
var buf bytes.Buffer
depth := 1
for {
ch := s.read()
if ch == eof {
break
}
if ch == open {
depth++
} else if ch == close {
depth--
if depth == 0 {
break
}
}
buf.WriteRune(ch)
}
return buf.String()
}
// scanQuoted parses a quoted string, like "this".
func (s *Scanner) scanQuoted() (Token, string) {
var buf bytes.Buffer
brace := 0
for {
if ch := s.read(); ch == eof {
break
} else if ch == '{' {
brace++
} else if ch == '}' {
brace--
} else if ch == '"' {
if brace == 0 { // Matches open quote, unescaped
return IDENT, buf.String()
}
_, _ = buf.WriteRune(ch)
} else {
_, _ = buf.WriteRune(ch)
}
}
return ILLEGAL, buf.String()
}
// ignoreWhitespace consumes the current rune and all contiguous whitespace.
func (s *Scanner) ignoreWhitespace() {
for {
if ch := s.read(); ch == eof {
break
} else if !isWhitespace(ch) {
s.unread()
break
}
}
}
// Copyright (c) 2020, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copied and only lightly modified from:
// https://github.com/nickng/bibtex
// Licensed under an Apache-2.0 license
// and presumably Copyright (c) 2017 by Nick Ng
package bibtex
import (
"fmt"
"strings"
)
// Token is a lexer token.
type Token int
const (
// ILLEGAL stands for an invalid token.
ILLEGAL Token = iota
)
var eof = rune(0)
// TokenPos is a pair of coordinate to identify start of token.
type TokenPos struct {
Char int
Lines []int
}
func (p TokenPos) String() string {
return fmt.Sprintf("%d:%d", len(p.Lines)+1, p.Char)
}
func isWhitespace(ch rune) bool {
return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r'
}
func isAlpha(ch rune) bool {
return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z')
}
func isDigit(ch rune) bool {
return ('0' <= ch && ch <= '9')
}
func isAlphanum(ch rune) bool {
return isAlpha(ch) || isDigit(ch)
}
func isBareSymbol(ch rune) bool {
return strings.ContainsRune("-_:./+", ch)
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package golang
import (
"strings"
"sync"
"unsafe"
"cogentcore.org/core/icons"
"cogentcore.org/core/text/parse"
"cogentcore.org/core/text/parse/complete"
"cogentcore.org/core/text/parse/syms"
)
var BuiltinTypes syms.TypeMap
// installBuiltinTypesOnce makes InstallBuiltinTypes initialize
// the BuiltinTypes map only once, as parsing goroutines call it at once.
var installBuiltinTypesOnce sync.Once
// InstallBuiltinTypes initializes the BuiltinTypes map
func InstallBuiltinTypes() {
installBuiltinTypesOnce.Do(func() {
for _, tk := range BuiltinTypeKind {
ty := syms.NewType(tk.Name, tk.Kind)
ty.Size = []int{tk.Size}
BuiltinTypes.Add(ty)
}
})
}
func (gl *GoLang) CompleteBuiltins(fs *parse.FileState, seed string, md *complete.Matches) {
for _, tk := range BuiltinTypeKind {
if strings.HasPrefix(tk.Name, seed) {
c := complete.Completion{Text: tk.Name, Label: tk.Name, Icon: icons.Type}
md.Matches = append(md.Matches, c)
}
}
for _, bs := range BuiltinMisc {
if strings.HasPrefix(bs, seed) {
c := complete.Completion{Text: bs, Label: bs, Icon: icons.Variable}
md.Matches = append(md.Matches, c)
}
}
for _, bs := range BuiltinFuncs {
if strings.HasPrefix(bs, seed) {
bs = bs + "()"
c := complete.Completion{Text: bs, Label: bs, Icon: icons.Function}
md.Matches = append(md.Matches, c)
}
}
for _, bs := range BuiltinPackages {
if strings.HasPrefix(bs, seed) {
c := complete.Completion{Text: bs, Label: bs, Icon: icons.Type} // todo: was types
md.Matches = append(md.Matches, c)
}
}
for _, bs := range BuiltinKeywords {
if strings.HasPrefix(bs, seed) {
c := complete.Completion{Text: bs, Label: bs, Icon: icons.Constant}
md.Matches = append(md.Matches, c)
}
}
}
// BuiltinTypeKind are the type names and kinds for builtin Go primitive types
// (i.e., those with names)
var BuiltinTypeKind = []syms.TypeKindSize{
{Name: "int", Kind: syms.Int, Size: int(unsafe.Sizeof(int(0)))},
{Name: "int8", Kind: syms.Int8, Size: 1},
{Name: "int16", Kind: syms.Int16, Size: 2},
{Name: "int32", Kind: syms.Int32, Size: 4},
{Name: "int64", Kind: syms.Int64, Size: 8},
{Name: "uint", Kind: syms.Uint, Size: int(unsafe.Sizeof(uint(0)))},
{Name: "uint8", Kind: syms.Uint8, Size: 1},
{Name: "uint16", Kind: syms.Uint16, Size: 2},
{Name: "uint32", Kind: syms.Uint32, Size: 4},
{Name: "uint64", Kind: syms.Uint64, Size: 8},
{Name: "uintptr", Kind: syms.Uintptr, Size: 8},
{Name: "byte", Kind: syms.Uint8, Size: 1},
{Name: "rune", Kind: syms.Int32, Size: 4},
{Name: "float32", Kind: syms.Float32, Size: 4},
{Name: "float64", Kind: syms.Float64, Size: 8},
{Name: "complex64", Kind: syms.Complex64, Size: 8},
{Name: "complex128", Kind: syms.Complex128, Size: 16},
{Name: "bool", Kind: syms.Bool, Size: 1},
{Name: "string", Kind: syms.String, Size: 0},
{Name: "error", Kind: syms.Interface, Size: 0},
{Name: "struct{}", Kind: syms.Struct, Size: 0},
{Name: "interface{}", Kind: syms.Interface, Size: 0},
}
// BuiltinMisc are misc builtin items
var BuiltinMisc = []string{
"true",
"false",
}
// BuiltinFuncs are functions builtin to the Go language
var BuiltinFuncs = []string{
"append",
"copy",
"delete",
"len",
"cap",
"make",
"new",
"complex",
"real",
"imag",
"close",
"panic",
"recover",
}
// BuiltinKeywords are keywords built into Go -- for, range, etc
var BuiltinKeywords = []string{
"break",
"case",
"chan",
"const",
"continue",
"default",
"defer",
"else",
"fallthrough",
"for",
"func",
"go",
"goto",
"if",
"import",
"interface",
"map",
"package",
"range",
"return",
"select",
"struct",
"switch",
"type",
"var",
}
// BuiltinPackages are the standard library packages
var BuiltinPackages = []string{
"bufio",
"bytes",
"context",
"crypto",
"compress",
"encoding",
"errors",
"expvar",
"flag",
"fmt",
"hash",
"html",
"image",
"io",
"log",
"math",
"mime",
"net",
"os",
"path",
"plugin",
"reflect",
"regexp",
"runtime",
"sort",
"strconv",
"strings",
"sync",
"syscall",
"testing",
"time",
"unicode",
"unsafe",
"tar",
"zip",
"bzip2",
"flate",
"gzip",
"lzw",
"zlib",
"heap",
"list",
"ring",
"aes",
"cipher",
"des",
"dsa",
"ecdsa",
"ed25519",
"elliptic",
"hmac",
"md5",
"rc4",
"rsa",
"sha1",
"sha256",
"sha512",
"tls",
"x509",
"sql",
"ascii85",
"asn1",
"base32",
"base64",
"binary",
"csv",
"gob",
"hex",
"json",
"pem",
"xml",
"ast",
"build",
"constant",
"doc",
"format",
"importer",
"parser",
"printer",
"scanner",
"token",
"types",
"adler32",
"crc32",
"crc64",
"fnv",
"template",
"color",
"draw",
"gif",
"jpeg",
"png",
"suffixarray",
"ioutil",
"syslog",
"big",
"bits",
"cmplx",
"rand",
"multipart",
"quotedprintable",
"http",
"cookiejar",
"cgi",
"httptrace",
"httputil",
"pprof",
"socktest",
"mail",
"rpc",
"jsonrpc",
"smtp",
"textproto",
"url",
"exec",
"signal",
"user",
"filepath",
"syntax",
"cgo",
"debug",
"atomic",
"math",
"sys",
"msan",
"race",
"trace",
"atomic",
"js",
"scanner",
"tabwriter",
"template",
"utf16",
"utf8",
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package golang
import (
"fmt"
"os"
"path/filepath"
"strings"
"unicode"
"unicode/utf8"
"cogentcore.org/core/icons"
"cogentcore.org/core/text/parse"
"cogentcore.org/core/text/parse/complete"
"cogentcore.org/core/text/parse/lexer"
"cogentcore.org/core/text/parse/parser"
"cogentcore.org/core/text/parse/syms"
"cogentcore.org/core/text/textpos"
"cogentcore.org/core/text/token"
"cogentcore.org/core/tree"
)
var CompleteTrace = false
// Lookup is the main api called by completion code in giv/complete.go to lookup item
func (gl *GoLang) Lookup(fss *parse.FileStates, str string, pos textpos.Pos) (ld complete.Lookup) {
if str == "" {
return
}
origStr := str
str = lexer.LastScopedString(str)
if len(str) == 0 {
return
}
fs := fss.Done()
if len(fs.ParseState.Scopes) == 0 {
return // need a package
}
// not a read lock, as packages can be added to ExtSyms
fs.SymsMu.Lock()
defer fs.SymsMu.Unlock()
pr := gl.Parser()
if pr == nil {
return
}
fpath, _ := filepath.Abs(fs.Src.Filename)
if CompleteTrace {
fmt.Printf("lookup str: %v orig: %v\n", str, origStr)
}
lfs := pr.ParseString(str, fpath, fs.Src.Known)
if lfs == nil {
return
}
if CompleteTrace {
lfs.ParseState.AST.WriteTree(os.Stdout, 0)
lfs.LexState.Errs.Report(20, "", lexer.ShowSrc, lexer.ShowRule)
lfs.ParseState.Errs.Report(20, "", lexer.ShowSrc, lexer.ShowRule)
}
var scopes syms.SymMap // scope(s) for position, fname
scope := gl.CompletePosScope(fs, pos, fpath, &scopes)
start, last := gl.CompleteASTStart(lfs.ParseState.AST, scope)
if CompleteTrace {
if start == nil {
fmt.Printf("start = nil\n")
return
}
fmt.Printf("\n####################\nlookup start in scope: %v\n", scope)
lfs.ParseState.AST.WriteTree(os.Stdout, 0)
fmt.Printf("Start tree:\n")
start.WriteTree(os.Stdout, 0)
}
pkg := fs.ParseState.Scopes[0]
start.SrcReg.Start = pos
if start == last { // single-item
seed := start.Src
if seed != "" {
return gl.LookupString(fs, pkg, scopes, seed)
}
return gl.LookupString(fs, pkg, scopes, str)
}
typ, nxt, got := gl.TypeFromASTExprStart(fs, pkg, pkg, start)
lststr := ""
if nxt != nil {
lststr = nxt.Src
}
if got {
if lststr != "" {
for _, mt := range typ.Meths {
nm := mt.Name
if !strings.HasPrefix(nm, lststr) {
continue
}
if mt.Filename != "" {
ld.SetFile(mt.Filename, mt.Region.Start.Line, mt.Region.End.Line)
return
}
}
}
// fmt.Printf("got lookup type: %v, last str: %v\n", typ.String(), lststr)
ld.SetFile(typ.Filename, typ.Region.Start.Line, typ.Region.End.Line)
return
}
// see if it starts with a package name..
snxt := start.NextAST()
lststr = last.Src
if snxt != nil && snxt.Src != "" {
ststr := snxt.Src
if lststr != "" && lststr != ststr {
ld = gl.LookupString(fs, pkg, nil, ststr+"."+lststr)
} else {
ld = gl.LookupString(fs, pkg, nil, ststr)
}
} else {
ld = gl.LookupString(fs, pkg, scopes, lststr)
}
if ld.Filename == "" { // didn't work
ld = gl.LookupString(fs, pkg, scopes, str)
}
return
}
// CompleteLine is the main api called by completion code in giv/complete.go
func (gl *GoLang) CompleteLine(fss *parse.FileStates, str string, pos textpos.Pos) (md complete.Matches) {
if str == "" {
return
}
origStr := str
str = lexer.LastScopedString(str)
if len(str) > 0 {
lstchr := str[len(str)-1]
mbrace, right := lexer.BracePair(rune(lstchr))
if mbrace != 0 && right { // don't try to match after closing expr
return
}
}
fs := fss.Done()
if len(fs.ParseState.Scopes) == 0 {
return // need a package
}
// not a read lock, as packages can be added to ExtSyms
fs.SymsMu.Lock()
defer fs.SymsMu.Unlock()
pr := gl.Parser()
if pr == nil {
return
}
fpath, _ := filepath.Abs(fs.Src.Filename)
if CompleteTrace {
fmt.Printf("complete str: %v orig: %v\n", str, origStr)
}
lfs := pr.ParseString(str, fpath, fs.Src.Known)
if lfs == nil {
return
}
if CompleteTrace {
lfs.ParseState.AST.WriteTree(os.Stdout, 0)
lfs.LexState.Errs.Report(20, "", lexer.ShowSrc, lexer.ShowRule)
lfs.ParseState.Errs.Report(20, "", lexer.ShowSrc, lexer.ShowRule)
}
var scopes syms.SymMap // scope(s) for position, fname
scope := gl.CompletePosScope(fs, pos, fpath, &scopes)
start, last := gl.CompleteASTStart(lfs.ParseState.AST, scope)
if CompleteTrace {
if start == nil {
fmt.Printf("start = nil\n")
return
}
fmt.Printf("\n####################\ncompletion start in scope: %v\n", scope)
lfs.ParseState.AST.WriteTree(os.Stdout, 0)
fmt.Printf("Start tree:\n")
start.WriteTree(os.Stdout, 0)
}
pkg := fs.ParseState.Scopes[0]
start.SrcReg.Start = pos
if start == last { // single-item
seed := start.Src
if CompleteTrace {
fmt.Printf("start == last: %v\n", seed)
}
md.Seed = seed
if start.Name == "TypeNm" {
gl.CompleteTypeName(fs, pkg, seed, &md)
return
}
if len(scopes) > 0 {
syms.AddCompleteSymsPrefix(scopes, "", seed, &md)
}
gl.CompletePkgSyms(fs, pkg, seed, &md)
gl.CompleteBuiltins(fs, seed, &md)
return
}
typ, nxt, got := gl.TypeFromASTExprStart(fs, pkg, pkg, start)
lststr := ""
if nxt != nil {
lststr = nxt.Src
}
if got && typ != nil {
// fmt.Printf("got completion type: %v, last str: %v\n", typ.String(), lststr)
syms.AddCompleteTypeNames(typ, typ.Name, lststr, &md)
} else {
// see if it starts with a package name..
// todo: move this to a function as in lookup
snxt := start.NextAST()
if snxt != nil && snxt.Src != "" {
ststr := snxt.Src
psym, has := gl.PkgSyms(fs, pkg.Children, ststr)
if has {
lststr := last.Src
if lststr != "" && lststr != ststr {
var matches syms.SymMap
psym.Children.FindNamePrefixScoped(lststr, &matches)
syms.AddCompleteSyms(matches, ststr, &md)
md.Seed = lststr
} else {
syms.AddCompleteSyms(psym.Children, ststr, &md)
}
return
}
}
if CompleteTrace {
fmt.Printf("completion type not found\n")
}
}
// if len(md.Matches) == 0 {
// fmt.Printf("complete str: %v orig: %v\n", str, origStr)
// lfs.ParseState.AST.WriteTree(os.Stdout, 0)
// }
return
}
// CompletePosScope returns the scope for given position in given filename,
// and fills in the scoping symbol(s) in scMap
func (gl *GoLang) CompletePosScope(fs *parse.FileState, pos textpos.Pos, fpath string, scopes *syms.SymMap) token.Tokens {
fs.Syms.FindContainsRegion(fpath, pos, 2, token.None, scopes) // None matches any, 2 extra lines to add for new typing
if len(*scopes) == 0 {
return token.None
}
if len(*scopes) == 1 {
for _, sy := range *scopes {
if CompleteTrace {
fmt.Printf("scope: %v reg: %v pos: %v\n", sy.Name, sy.Region, pos)
}
return sy.Kind
}
}
var last *syms.Symbol
for _, sy := range *scopes {
if sy.Kind.SubCat() == token.NameFunction {
return sy.Kind
}
last = sy
}
if CompleteTrace {
fmt.Printf(" > 1 scopes!\n")
scopes.WriteDoc(os.Stdout, 0)
}
return last.Kind
}
// CompletePkgSyms matches all package symbols using seed
func (gl *GoLang) CompletePkgSyms(fs *parse.FileState, pkg *syms.Symbol, seed string, md *complete.Matches) {
md.Seed = seed
var matches syms.SymMap
pkg.Children.FindNamePrefixScoped(seed, &matches)
syms.AddCompleteSyms(matches, "", md)
}
// CompleteTypeName matches builtin and package type names to seed
func (gl *GoLang) CompleteTypeName(fs *parse.FileState, pkg *syms.Symbol, seed string, md *complete.Matches) {
md.Seed = seed
for _, tk := range BuiltinTypeKind {
if strings.HasPrefix(tk.Name, seed) {
c := complete.Completion{Text: tk.Name, Label: tk.Name, Icon: icons.Type}
md.Matches = append(md.Matches, c)
}
}
sfunc := strings.HasPrefix(seed, "func ")
for _, tk := range pkg.Types {
if !sfunc && strings.HasPrefix(tk.Name, "func ") {
continue
}
if strings.HasPrefix(tk.Name, seed) {
c := complete.Completion{Text: tk.Name, Label: tk.Name, Icon: icons.Type}
md.Matches = append(md.Matches, c)
}
}
}
// LookupString attempts to lookup a string, which could be a type name,
// (with package qualifier), could be partial, etc
func (gl *GoLang) LookupString(fs *parse.FileState, pkg *syms.Symbol, scopes syms.SymMap, str string) (ld complete.Lookup) {
str = lexer.TrimLeftToAlpha(str)
pnm, tnm := SplitType(str)
if pnm != "" && tnm != "" {
psym, has := gl.PkgSyms(fs, pkg.Children, pnm)
if has {
tnm = lexer.TrimLeftToAlpha(tnm)
var matches syms.SymMap
psym.Children.FindNamePrefixScoped(tnm, &matches)
if len(matches) == 1 {
var psy *syms.Symbol
for _, sy := range matches {
psy = sy
}
ld.SetFile(psy.Filename, psy.Region.Start.Line, psy.Region.End.Line)
return
}
}
if CompleteTrace {
fmt.Printf("Lookup: package-qualified string not found: %v\n", str)
}
return
}
// try types to str:
var tym *syms.Type
nmatch := 0
for _, tk := range pkg.Types {
if strings.HasPrefix(tk.Name, str) {
tym = tk
nmatch++
}
}
if nmatch == 1 {
ld.SetFile(tym.Filename, tym.Region.Start.Line, tym.Region.End.Line)
return
}
var matches syms.SymMap
if len(scopes) > 0 {
scopes.FindNamePrefixRecursive(str, &matches)
if len(matches) > 0 {
for _, sy := range matches {
ld.SetFile(sy.Filename, sy.Region.Start.Line, sy.Region.End.Line) // take first
return
}
}
}
pkg.Children.FindNamePrefixScoped(str, &matches)
if len(matches) > 0 {
for _, sy := range matches {
ld.SetFile(sy.Filename, sy.Region.Start.Line, sy.Region.End.Line) // take first
return
}
}
if CompleteTrace {
fmt.Printf("Lookup: string not found: %v\n", str)
}
return
}
// CompleteASTStart finds the best starting point in the given current-line AST
// to start completion process, which walks back down from that starting point
func (gl *GoLang) CompleteASTStart(ast *parser.AST, scope token.Tokens) (start, last *parser.AST) {
curi := tree.Last(ast)
if curi == nil {
return
}
cur := curi.(*parser.AST)
last = cur
start = cur
prv := cur
for {
var parent *parser.AST
if cur.Parent != nil {
parent = cur.Parent.(*parser.AST)
}
switch {
case cur.Name == "TypeNm":
return cur, last
case cur.Name == "File":
if prv != last && prv.Src == last.Src {
return last, last // triggers single-item completion
}
return prv, last
case cur.Name == "Selector":
if parent != nil {
if parent.Name[:4] == "Asgn" {
return cur, last
}
if strings.HasSuffix(parent.Name, "Expr") {
return cur, last
}
} else {
flds := strings.Fields(cur.Src)
cur.Src = flds[len(flds)-1] // skip any spaces
return cur, last
}
case cur.Name == "Name":
if cur.Src == "if" { // weird parsing if incomplete
if prv != last && prv.Src == last.Src {
return last, last // triggers single-item completion
}
return prv, last
}
if parent != nil {
if parent.Name[:4] == "Asgn" {
return prv, last
}
if strings.HasSuffix(parent.Name, "Expr") {
return cur, last
}
}
case cur.Name == "ExprStmt":
if scope == token.None {
return prv, last
}
if cur.Src != "(" && cur.Src == prv.Src {
return prv, last
}
if cur.Src != "(" && prv != last {
return prv, last
}
case strings.HasSuffix(cur.Name, "Stmt"):
return prv, last
case cur.Name == "Args":
return prv, last
}
nxt := cur.PrevAST()
if nxt == nil {
return cur, last
}
prv = cur
cur = nxt
}
}
// CompleteEdit returns the completion edit data for integrating the selected completion
// into the source
func (gl *GoLang) CompleteEdit(fss *parse.FileStates, text string, cp int, comp complete.Completion, seed string) (ed complete.Edit) {
// if the original is ChildByName() and the cursor is between d and B and the comp is Children,
// then delete the portion after "Child" and return the new comp and the number or runes past
// the cursor to delete
rn := []rune(text)
s2 := string(rn[min(cp, len(rn)):]) // cp is a rune position
gotParen := false
if r, _ := utf8.DecodeRuneInString(s2); len(s2) > 0 && lexer.IsLetterOrDigit(r) {
for i, c := range s2 {
if c == '(' {
gotParen = true
s2 = s2[:i]
break
}
isalnum := c == '_' || unicode.IsLetter(c) || unicode.IsDigit(c)
if !isalnum {
s2 = s2[:i]
break
}
}
} else {
// a paren right after the cursor is the call of the name
gotParen = strings.HasPrefix(s2, "(")
s2 = ""
}
var nw = comp.Text
if gotParen && strings.HasSuffix(nw, "()") {
nw = nw[:len(nw)-2]
}
// fmt.Printf("text: %v|%v comp: %v s2: %v\n", text[:cp], text[cp:], nw, s2)
ed.NewText = nw
ed.ForwardDelete = utf8.RuneCountInString(s2)
return ed
}
// Copyright (c) 2020, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package golang
import (
"fmt"
"os"
"path/filepath"
"strings"
"cogentcore.org/core/text/parse"
"cogentcore.org/core/text/parse/parser"
"cogentcore.org/core/text/parse/syms"
"cogentcore.org/core/text/token"
)
// TypeFromASTExprStart starts walking the ast expression to find the type.
// This computes the last ast point as the stopping point for processing
// and then calls TypeFromASTExpr.
// It returns the type, any AST node that remained unprocessed at the end, and bool if found.
func (gl *GoLang) TypeFromASTExprStart(fs *parse.FileState, origPkg, pkg *syms.Symbol, tyast *parser.AST) (*syms.Type, *parser.AST, bool) {
last := tyast.NextSiblingAST()
// fmt.Printf("last: %v \n", last.PathUnique())
return gl.TypeFromASTExpr(fs, origPkg, pkg, tyast, last)
}
// TypeFromASTExpr walks the ast expression to find the type.
// It returns the type, any AST node that remained unprocessed at the end, and bool if found.
func (gl *GoLang) TypeFromASTExpr(fs *parse.FileState, origPkg, pkg *syms.Symbol, tyast, last *parser.AST) (*syms.Type, *parser.AST, bool) {
pos := tyast.SrcReg.Start
fpath, _ := filepath.Abs(fs.Src.Filename)
// containers of given region -- local scoping
var conts syms.SymMap
fs.Syms.FindContainsRegion(fpath, pos, 2, token.NameFunction, &conts) // 2 extra lines always!
// if TraceTypes && len(conts) == 0 {
// fmt.Printf("TExpr: no conts for fpath: %v pos: %v\n", fpath, pos)
// }
// if TraceTypes {
// tyast.WriteTree(os.Stdout, 0)
// }
tnm := tyast.Name
switch {
case tnm == "FuncCall":
fun := tyast.NextAST()
if fun == nil {
return nil, nil, false
}
funm := fun.Src
sym, got := fs.FindNameScoped(funm, conts)
if got {
if !gl.InferEmptySymbolType(sym, fs, pkg) {
return nil, fun, false
}
if sym.Type == "" {
if TraceTypes {
fmt.Printf("TExpr: FuncCall: function type not set yet: %v\n", funm)
}
gl.InferSymbolType(sym, fs, pkg, true)
}
ftnm := sym.Type
ftyp, _ := gl.FindTypeName(ftnm, fs, pkg)
if ftyp != nil && len(ftyp.Size) == 2 {
return gl.TypeFromFuncCall(fs, origPkg, pkg, tyast, last, ftyp)
}
if TraceTypes {
fmt.Printf("TExpr: FuncCall: could not find function: %v\n", funm)
}
return nil, fun, false
}
if funm == "len" || funm == "cap" {
return BuiltinTypes["int"], nil, true
}
if funm == "append" {
farg := fun.NextAST().NextAST()
return gl.TypeFromASTExpr(fs, origPkg, pkg, farg, last)
}
ctyp, _ := gl.FindTypeName(funm, fs, pkg) // conversion
if ctyp != nil {
return ctyp, nil, true
}
if TraceTypes {
fmt.Printf("TExpr: FuncCall: could not find function: %v\n", funm)
}
return nil, fun, false
case tnm == "Selector":
if tyast.NumChildren() == 0 { // incomplete
return nil, nil, false
}
tnmA := tyast.ChildAST(0)
if tnmA.Name != "Name" {
if TraceTypes {
fmt.Printf("TExpr: selector start node kid is not a Name: %v, src: %v\n", tnmA.Name, tnmA.Src)
tnmA.WriteTree(os.Stdout, 0)
}
return nil, tnmA, false
}
return gl.TypeFromASTName(fs, origPkg, pkg, tnmA, last, conts)
case tnm == "Slice": // strings.HasPrefix(tnm, "Slice"):
if tyast.NumChildren() == 0 { // incomplete
return nil, nil, false
}
tnmA := tyast.ChildAST(0)
if tnmA.Name != "Name" {
if TraceTypes {
fmt.Printf("TExpr: slice start node kid is not a Name: %v, src: %v\n", tnmA.Name, tnmA.Src)
}
return nil, tnmA, false
}
snm := tnmA.Src
sym, got := fs.FindNameScoped(snm, conts)
if got {
return gl.TypeFromASTSym(fs, origPkg, pkg, tnmA, last, sym)
}
if TraceTypes {
fmt.Printf("TExpr: could not find symbol for slice var name: %v\n", snm)
}
return nil, tnmA, false
case tnm == "Name":
return gl.TypeFromASTName(fs, origPkg, pkg, tyast, last, conts)
case strings.HasPrefix(tnm, "Lit"):
sty, got := gl.TypeFromASTLit(fs, pkg, nil, tyast)
return sty, nil, got
case strings.HasSuffix(tnm, "AutoType"):
sty, got := gl.SubTypeFromAST(fs, pkg, tyast, 0)
return sty, nil, got
case tnm == "CompositeLit":
sty, got := gl.SubTypeFromAST(fs, pkg, tyast, 0)
return sty, nil, got
case tnm == "AddrExpr":
if !tyast.HasChildren() {
return nil, nil, false
}
ch := tyast.ChildAST(0)
snm := tyast.Src[1:] // after &
var sty *syms.Type
switch ch.Name {
case "CompositeLit":
sty, _ = gl.SubTypeFromAST(fs, pkg, ch, 0)
case "Selector":
sty, _ = gl.TypeFromAST(fs, pkg, nil, ch)
case "Name":
sym, got := fs.FindNameScoped(snm, conts)
if got {
sty, _, _ = gl.TypeFromASTSym(fs, origPkg, pkg, ch, last, sym) // (sty is nil if not found)
} else {
if snm == "true" || snm == "false" {
return BuiltinTypes["bool"], nil, true
}
if TraceTypes {
fmt.Printf("TExpr: could not find symbol named: %v\n", snm)
}
}
}
if sty != nil {
ty := &syms.Type{}
ty.Kind = syms.Ptr
tynm := SymTypeNameForPkg(sty, pkg)
ty.Name = "*" + tynm
ty.Els.Add("ptr", tynm)
return ty, nil, true
}
if TraceTypes {
fmt.Printf("TExpr: could not process addr expr:\n")
tyast.WriteTree(os.Stdout, 0)
}
return nil, tyast, false
case tnm == "DePtrExpr":
sty, got := gl.SubTypeFromAST(fs, pkg, tyast, 0) // first child
return sty, nil, got
case tnm == "SendExpr": // <-ch, which receives (the grammar names it by its arrow)
if !tyast.HasChildren() {
return nil, tyast, false
}
cty, _, got := gl.TypeFromASTExpr(fs, origPkg, pkg, tyast.ChildAST(0), last)
if !got || cty.Kind != syms.Chan || len(cty.Els) == 0 {
return nil, tyast, false
}
ety, _ := gl.FindTypeName(cty.Els[0].Type, fs, pkg)
return ety, nil, ety != nil
case tnm == "NotExpr", tnm == "EqExpr", tnm == "NotEqExpr", tnm == "LessExpr", tnm == "LtEqExpr",
tnm == "GreaterExpr", tnm == "GtEqExpr", tnm == "LogAndExpr", tnm == "LogOrExpr":
return BuiltinTypes["bool"], nil, true
case tnm == "AddExpr" && tyast.HasChildren():
// strings are concatenated; numbers are taken to be float64 (see below)
if cty, _, got := gl.TypeFromASTExpr(fs, origPkg, pkg, tyast.ChildAST(0), last); got && cty.Kind == syms.String {
return cty, nil, true
}
return BuiltinTypes["float64"], nil, true
case tnm == "NewCall": // new(T) is a *T
sty, got := gl.SubTypeFromAST(fs, pkg, tyast, 0)
if !got {
return nil, tyast, false
}
ty := &syms.Type{Kind: syms.Ptr}
tynm := SymTypeNameForPkg(sty, pkg)
ty.Name = "*" + tynm
ty.Els.Add("ptr", tynm)
return ty, nil, true
case tnm == "FuncLit": // its signature, as for a FuncType
ty := &syms.Type{Kind: syms.Func}
gl.FuncTypeFromAST(fs, pkg, tyast, ty)
ty.Name = fs.NextAnonName(pkg.Name + "_func")
pkg.Types.Add(ty)
return ty, nil, true
case strings.HasSuffix(tnm, "Expr"):
// note: could figure out actual numerical type, but in practice we don't care
// for lookup / completion, so ignoring for now.
return BuiltinTypes["float64"], nil, true
case tnm == "TypeAssert":
sty, got := gl.SubTypeFromAST(fs, pkg, tyast, 1) // type is second child
return sty, nil, got
case tnm == "MakeCall":
sty, got := gl.SubTypeFromAST(fs, pkg, tyast, 0)
return sty, nil, got
case strings.Contains(tnm, "Chan"): // a channel type
sty, got := gl.TypeFromAST(fs, pkg, nil, tyast)
return sty, nil, got
default:
if TraceTypes {
fmt.Printf("TExpr: cannot start with: %v\n", tyast.Name)
tyast.WriteTree(os.Stdout, 0)
}
return nil, tyast, false
}
}
// TypeFromASTSym attempts to get the type from given symbol as part of expression.
// It returns the type, any AST node that remained unprocessed at the end, and bool if found.
func (gl *GoLang) TypeFromASTSym(fs *parse.FileState, origPkg, pkg *syms.Symbol, tyast, last *parser.AST, sym *syms.Symbol) (*syms.Type, *parser.AST, bool) {
// if TraceTypes {
// fmt.Printf("TExpr: sym named: %v kind: %v type: %v\n", sym.Name, sym.Kind, sym.Type)
// }
if sym.Kind.SubCat() == token.NameScope {
// if TraceTypes {
// fmt.Printf("TExpr: symbol has scope type (package) -- will be looked up in a sec\n")
// }
return nil, nil, false // higher-level will catch it
}
if !gl.InferEmptySymbolType(sym, fs, pkg) {
return nil, tyast, false
}
tnm := sym.Type
return gl.TypeFromASTType(fs, origPkg, pkg, tyast, last, tnm)
}
// TypeFromASTType walks the ast expression to find the type, starting from current type name.
// It returns the type, any AST node that remained unprocessed at the end, and bool if found.
func (gl *GoLang) TypeFromASTType(fs *parse.FileState, origPkg, pkg *syms.Symbol, tyast, last *parser.AST, tnm string) (*syms.Type, *parser.AST, bool) {
if tnm[0] == '*' {
tnm = tnm[1:]
}
ttp, npkg := gl.FindTypeName(tnm, fs, pkg)
if ttp == nil {
if TraceTypes {
fmt.Printf("TExpr: error -- couldn't find type name: %v\n", tnm)
}
return nil, tyast, false
}
pkgnm := ""
if pi := strings.Index(ttp.Name, "."); pi > 0 {
pkgnm = ttp.Name[:pi]
}
if npkg != origPkg { // need to make a package-qualified copy of type
if pkgnm == "" {
pkgnm = npkg.Name
qtnm := QualifyType(pkgnm, ttp.Name)
if qtnm != ttp.Name {
if etyp, ok := pkg.Types[qtnm]; ok {
ttp = etyp
} else {
ntyp := &syms.Type{}
*ntyp = *ttp
ntyp.Name = qtnm
origPkg.Types.Add(ntyp)
ttp = ntyp
}
}
}
}
pkg = npkg // update to new context
// if TraceTypes {
// fmt.Printf("TExpr: found type: %v kind: %v\n", ttp.Name, ttp.Kind)
// }
if tyast == nil || tyast == last {
return ttp, tyast, true
}
if tyast.Name == "QualType" && tnm != tyast.Src {
// tyast.Src is new type name
return gl.TypeFromASTType(fs, origPkg, pkg, tyast, last, tyast.Src)
}
nxt := tyast
for {
nxt = nxt.NextAST()
if nxt == nil || nxt == last {
// if TraceTypes {
// fmt.Printf("TExpr: returning terminal type\n")
// }
return ttp, nxt, true
}
brk := false
switch {
case nxt.Name == "Name":
brk = true
case strings.HasPrefix(nxt.Name, "Lit"):
sty, got := gl.TypeFromASTLit(fs, pkg, nil, nxt)
return sty, nil, got
case nxt.Name == "TypeAssert":
sty, got := gl.SubTypeFromAST(fs, origPkg, nxt, 1) // type is second child, switch back to orig pkg
return sty, nil, got
case nxt.Name == "Slice":
continue
case strings.HasPrefix(nxt.Name, "Slice"):
// the expression continues after the index (or slice) expression
end := lastDescendant(nxt)
if last != nil && last != nxt && last.ParentLevel(nxt) > 0 {
end = nxt
}
if nxt.Name == "SliceTwo" || nxt.Name == "SliceThree" { // a slice of the same type
return gl.TypeFromASTType(fs, origPkg, pkg, end, last, ttp.Name)
}
eltyp := ttp.Els.ByName("val")
if eltyp != nil {
elnm := QualifyType(pkgnm, eltyp.Type)
// if TraceTypes {
// fmt.Printf("TExpr: slice/map el type: %v\n", elnm)
// }
return gl.TypeFromASTType(fs, origPkg, pkg, end, last, elnm)
}
if ttp.Name == "string" {
return BuiltinTypes["string"], nil, true
}
if TraceTypes {
fmt.Printf("TExpr: slice operator not on slice: %v\n", ttp.Name)
tyast.WriteTree(os.Stdout, 0)
}
case nxt.Name == "FuncCall":
// ttp is the function type name
fun := nxt.NextAST()
if fun == nil || fun == last {
return ttp, fun, true
}
funm := fun.Src
ftyp, got := ttp.Meths[funm]
if got && len(ftyp.Size) == 2 {
return gl.TypeFromFuncCall(fs, origPkg, pkg, nxt, last, ftyp)
}
if TraceTypes {
fmt.Printf("TExpr: FuncCall: could not find method: %v in type: %v\n", funm, ttp.Name)
tyast.WriteTree(os.Stdout, 0)
}
return nil, fun, false
}
if brk { // (nxt is neither nil nor last here: see the start of the loop)
break
}
// if TraceTypes {
// fmt.Printf("TExpr: skipping over %v\n", nxt.Nm)
// }
}
nm := nxt.Src
stp := ttp.Els.ByName(nm)
if stp != nil {
// if TraceTypes {
// fmt.Printf("TExpr: found Name: %v in type els\n", nm)
// }
return gl.TypeFromASTType(fs, origPkg, pkg, nxt, last, stp.Type)
}
// if TraceTypes {
// fmt.Printf("TExpr: error -- Name: %v not found in type els\n", nm)
// // ttp.WriteDoc(os.Stdout, 0)
// }
return ttp, nxt, true // robust, needed for completion
}
// TypeFromFuncCall gets return type of function call as return value, and returns the sibling node to
// continue parsing in, skipping over everything in the function call
func (gl *GoLang) TypeFromFuncCall(fs *parse.FileState, origPkg, pkg *syms.Symbol, tyast, last *parser.AST, ftyp *syms.Type) (*syms.Type, *parser.AST, bool) {
nxt := tyast.NextSiblingAST() // skip over everything within method in ast
if len(ftyp.Size) != 2 {
if TraceTypes {
fmt.Printf("TExpr: FuncCall: %v is not properly initialized with sizes\n", ftyp.Name)
}
return nil, nxt, false
}
npars := ftyp.Size[0] // first size is number of params
nrval := ftyp.Size[1] // second size is number of return values
if nrval == 0 {
if TraceTypes {
fmt.Printf("TExpr: FuncCall: %v has no return value\n", ftyp.Name)
}
return nil, nxt, false // no return -- shouldn't happen
}
rtyp := ftyp.Els[npars] // first return
if nxt != nil && nxt.Name == "Name" { // direct de-ref on function return value -- ASTType assumes nxt is type el
prv := nxt.PrevAST()
if prv != tyast {
nxt = prv
}
}
// if TraceTypes {
// fmt.Printf("got return type: %v\n", rtyp)
// }
return gl.TypeFromASTType(fs, origPkg, pkg, nxt, last, rtyp.Type)
}
// TypeFromASTName gets type from a Name in a given context (conts)
func (gl *GoLang) TypeFromASTName(fs *parse.FileState, origPkg, pkg *syms.Symbol, tyast, last *parser.AST, conts syms.SymMap) (*syms.Type, *parser.AST, bool) {
snm := tyast.Src
sym, got := fs.FindNameScoped(snm, conts)
if got && sym.Kind.SubCat() != token.NameScope {
tsym, nnxt, got := gl.TypeFromASTSym(fs, origPkg, pkg, tyast, last, sym)
if got {
return tsym, nnxt, got
}
if TraceTypes {
fmt.Printf("TExpr: got symbol but could not get type from sym name: %v\n", snm)
// tyast.WriteTree(os.Stdout, 0)
}
}
if snm == "true" || snm == "false" {
return BuiltinTypes["bool"], nil, true
}
// maybe it is a package name
psym, has := gl.PkgSyms(fs, pkg.Children, snm)
if has {
// if TraceTypes {
// fmt.Printf("TExpr: entering package name: %v\n", snm)
// }
nxt := tyast.NextAST()
if nxt != nil {
if nxt.Name == "Selector" {
nxt = nxt.NextAST()
}
return gl.TypeFromASTExpr(fs, origPkg, psym, nxt, last)
}
if TraceTypes {
fmt.Printf("TExpr: package alone not useful\n")
}
return nil, tyast, false // package alone not useful
}
if TraceTypes {
fmt.Printf("TExpr: could not find symbol for name: %v\n", snm)
}
return nil, tyast, false
}
// lastDescendant returns the last node within the given node, in the
// depth-first order of [parser.AST.NextAST]: the next node after it is
// the node after the given node and all of its descendants.
func lastDescendant(ast *parser.AST) *parser.AST {
for ast.HasChildren() {
ast = ast.ChildAST(len(ast.Children) - 1)
}
return ast
}
// Copyright (c) 2020, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package golang
import (
"fmt"
"unicode"
"cogentcore.org/core/text/parse"
"cogentcore.org/core/text/parse/parser"
"cogentcore.org/core/text/parse/syms"
"cogentcore.org/core/text/token"
)
// TypeMeths gathers method types from the type symbol's children
func (gl *GoLang) TypeMeths(fs *parse.FileState, pkg *syms.Symbol, ty *syms.Type) {
_, tnm := SplitType(ty.Name)
tsym, got := pkg.Children.FindNameScoped(tnm)
if !got {
if !unicode.IsLower(rune(tnm[0])) && TraceTypes {
fmt.Printf("TypeMeths: error -- did NOT get type sym: %v in pkg: %v\n", tnm, pkg.Name)
}
return
}
for _, sy := range tsym.Children {
if sy.Kind.SubCat() != token.NameFunction || sy.AST == nil {
continue
}
fty := gl.FuncTypeFromAST(fs, pkg, sy.AST.(*parser.AST), nil)
if fty != nil {
fty.Kind = syms.Method
fty.Name = sy.Name
fty.Filename = sy.Filename
fty.Region = sy.Region
ty.Meths.Add(fty)
// if TraceTypes {
// fmt.Printf("TypeMeths: Added method: %v\n", fty)
// }
} else {
if TraceTypes {
fmt.Printf("TypeMeths: method failed: %v\n", sy.Name)
}
}
}
}
// NamesFromAST returns a slice of name(s) from namelist nodes
func (gl *GoLang) NamesFromAST(fs *parse.FileState, pkg *syms.Symbol, ast *parser.AST, idx int) []string {
sast := ast.ChildAST(idx)
if sast == nil {
if TraceTypes {
fmt.Printf("TraceTypes: could not find child 0 on ast %v", ast)
}
return nil
}
var sary []string
if sast.HasChildren() {
for i := range sast.Children {
sary = append(sary, gl.NamesFromAST(fs, pkg, sast, i)...)
}
} else {
sary = append(sary, sast.Src)
}
return sary
}
// FuncTypeFromAST initializes a function type from ast -- type can either be anon
// or a named type -- if anon then the name is the full type signature without param names
func (gl *GoLang) FuncTypeFromAST(fs *parse.FileState, pkg *syms.Symbol, ast *parser.AST, fty *syms.Type) *syms.Type {
// ast.WriteTree(os.Stdout, 0)
if ast == nil || !ast.HasChildren() {
return nil
}
pars := ast.ChildAST(0)
if pars == nil {
if TraceTypes {
fmt.Printf("TraceTypes: could not find child 0 on ast %v", ast)
}
return nil
}
if fty == nil {
fty = &syms.Type{}
fty.Kind = syms.Func
}
poff := 0
isMeth := false
if pars.Name == "MethRecvName" && len(ast.Children) > 2 {
isMeth = true
rcv := pars.Children[0].(*parser.AST)
rtyp := pars.Children[1].(*parser.AST)
fty.Els.Add(rcv.Src, rtyp.Src)
poff = 2
pars = ast.ChildAST(2)
} else if pars.Name == "Name" && len(ast.Children) > 1 {
poff = 1
pars = ast.ChildAST(1)
}
npars := len(pars.Children)
var sigpars *parser.AST
if npars > 0 && (pars.Name == "SigParams" || pars.Name == "SigParamsResult") {
if ps := pars.ChildAST(0); ps != nil {
sigpars = pars
pars = ps
npars = len(pars.Children)
} else {
npars = 0 // not really
}
}
if npars > 0 {
gl.ParamsFromAST(fs, pkg, pars, fty, "param")
npars = len(fty.Els) // how many we added -- auto-includes receiver for method
} else {
if isMeth {
npars = 1
}
}
nrvals := 0
if sigpars != nil && len(sigpars.Children) >= 2 {
rvals := sigpars.ChildAST(1)
gl.RvalsFromAST(fs, pkg, rvals, fty)
nrvals = len(fty.Els) - npars // how many we added..
} else if poff < 2 && (len(ast.Children) >= poff+2) {
rvals := ast.ChildAST(poff + 1)
gl.RvalsFromAST(fs, pkg, rvals, fty)
nrvals = len(fty.Els) - npars // how many we added..
}
fty.Size = []int{npars, nrvals}
return fty
}
// ParamsFromAST sets params as Els for given function type (also for return types)
func (gl *GoLang) ParamsFromAST(fs *parse.FileState, pkg *syms.Symbol, pars *parser.AST, fty *syms.Type, name string) {
npars := len(pars.Children)
var pnames []string // param names that all share same type
for i := range npars {
par := pars.Children[i].(*parser.AST)
psz := len(par.Children)
if par.Name == "ParType" && psz == 1 {
ptypa := par.Children[0].(*parser.AST)
if ptypa.Name == "TypeNm" { // could be multiple args with same type or a separate type-only arg
if ptl, _ := gl.FindTypeName(par.Src, fs, pkg); ptl != nil {
fty.Els.Add(fmt.Sprintf("%s_%v", name, i), par.Src)
continue
}
pnames = append(pnames, par.Src) // add to later type
} else {
ptyp, ok := gl.SubTypeFromAST(fs, pkg, par, 0)
if ok {
pnsz := len(pnames)
if pnsz > 0 {
for _, pn := range pnames {
fty.Els.Add(pn, ptyp.Name)
}
}
fty.Els.Add(fmt.Sprintf("%s_%v", name, i), ptyp.Name)
continue
}
pnames = nil
}
} else if psz == 2 { // ParName
pnm := par.Children[0].(*parser.AST)
ptyp, ok := gl.SubTypeFromAST(fs, pkg, par, 1)
if ok {
pnsz := len(pnames)
if pnsz > 0 {
for _, pn := range pnames {
fty.Els.Add(pn, ptyp.Name)
}
}
fty.Els.Add(pnm.Src, ptyp.Name)
continue
}
pnames = nil
}
}
}
// RvalsFromAST sets return value(s) as Els for given function type
func (gl *GoLang) RvalsFromAST(fs *parse.FileState, pkg *syms.Symbol, rvals *parser.AST, fty *syms.Type) {
if rvals.Name == "Block" { // todo: maybe others
return
}
nrvals := len(rvals.Children)
if nrvals == 1 { // single rval, unnamed, has type directly..
rval := rvals.ChildAST(0)
if rval.Name != "ParName" {
nrvals = 1
rtyp, ok := gl.SubTypeFromAST(fs, pkg, rvals, 0)
if ok {
fty.Els.Add("rval", rtyp.Name)
return
}
}
}
gl.ParamsFromAST(fs, pkg, rvals, fty, "rval")
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package golang provides the support for the Go language of the parse
// package: its parser, symbols, type inference, and completion.
package golang
import (
_ "embed"
"fmt"
"log"
"os"
"path/filepath"
"unicode"
"cogentcore.org/core/base/fileinfo"
"cogentcore.org/core/base/indent"
"cogentcore.org/core/text/parse"
"cogentcore.org/core/text/parse/languages"
"cogentcore.org/core/text/parse/lexer"
"cogentcore.org/core/text/textpos"
"cogentcore.org/core/text/token"
)
//go:embed go.parse
var parserBytes []byte
// GoLang implements the Lang interface for the Go language
type GoLang struct {
Pr *parse.Parser
}
// TheGoLang is the instance variable providing support for the Go language
var TheGoLang = GoLang{}
func init() {
parse.StandardLanguageProperties[fileinfo.Go].Lang = &TheGoLang
languages.ParserBytes[fileinfo.Go] = parserBytes
}
func (gl *GoLang) Parser() *parse.Parser {
if gl.Pr != nil {
return gl.Pr
}
lp, _ := parse.LanguageSupport.Properties(fileinfo.Go)
if lp.Parser == nil {
parse.LanguageSupport.OpenLanguage(fileinfo.Go)
}
gl.Pr = lp.Parser
if gl.Pr == nil {
return nil
}
return gl.Pr
}
// ParseFile is the main point of entry for external calls into the parser
func (gl *GoLang) ParseFile(fss *parse.FileStates, txt []byte) {
pr := gl.Parser()
if pr == nil {
log.Println("ParseFile: no parser; must call parse.LangSupport.OpenStandard() at startup!")
return
}
pfs := fss.StartProc(txt) // current processing one
ext := filepath.Ext(pfs.Src.Filename)
if ext == ".mod" { // note: mod doesn't parse!
fss.EndProc()
return
}
// fmt.Println("\nstarting Parse:", pfs.Src.Filename)
// lprf := profile.Start("LexAll")
pr.LexAll(pfs)
// lprf.End()
// pprf := profile.Start("ParseAll")
pr.ParseAll(pfs)
// pprf.End()
fss.EndProc() // only symbols still need locking, done separately
path := filepath.Dir(pfs.Src.Filename)
// fmt.Println("done parse")
if len(pfs.ParseState.Scopes) > 0 { // should be for complete files, not for snippets
pkg := pfs.ParseState.Scopes[0]
// The symbols can still be updated in the goroutine of the last
// parse of this file state, under the lock.
pfs.SymsMu.Lock()
pfs.Syms[pkg.Name] = pkg // keep around..
pfs.SymsMu.Unlock()
// fmt.Printf("main pkg name: %v\n", pkg.Name)
pfs.WaitGp.Add(1)
go func() {
gl.AddPathToSyms(pfs, path)
gl.AddImportsToExts(fss, pfs, pkg) // will do ResolveTypes when it finishes
// fmt.Println("done import")
}()
} else {
if TraceTypes {
fmt.Printf("not importing scope for: %v\n", path)
}
pfs.SymsMu.Lock()
pfs.ClearAST()
if pfs.AST.HasChildren() {
pfs.AST.DeleteChildren()
}
pfs.SymsMu.Unlock()
// fmt.Println("done no import")
}
}
func (gl *GoLang) LexLine(fs *parse.FileState, line int, txt []rune) lexer.Line {
pr := gl.Parser()
if pr == nil {
return nil
}
return pr.LexLine(fs, line, txt)
}
func (gl *GoLang) ParseLine(fs *parse.FileState, line int) *parse.FileState {
pr := gl.Parser()
if pr == nil {
return nil
}
lfs := pr.ParseLine(fs, line) // should highlight same line?
return lfs
}
func (gl *GoLang) HighlightLine(fss *parse.FileStates, line int, txt []rune) lexer.Line {
pr := gl.Parser()
if pr == nil {
return nil
}
pfs := fss.Done()
ll := pr.LexLine(pfs, line, txt)
lfs := pr.ParseLine(pfs, line)
if lfs != nil {
ll = lfs.Src.Lexs[0]
cml := pfs.Src.Comments[line]
merge := lexer.MergeLines(ll, cml)
mc := merge.Clone()
if len(cml) > 0 {
initDepth := pfs.Src.PrevDepth(line)
pr.PassTwo.NestDepthLine(mc, initDepth)
}
lfs.Syms.WriteDoc(os.Stdout, 0)
lfs.Destroy()
return mc
}
return ll
}
// IndentLine returns the indentation level for given line based on
// previous line's indentation level, and any delta change based on
// e.g., brackets starting or ending the previous or current line, or
// other language-specific keywords. See lexer.BracketIndentLine for example.
// Indent level is in increments of tabSz for spaces, and tabs for tabs.
// Operates on rune source with markup lex tags per line.
func (gl *GoLang) IndentLine(fs *parse.FileStates, src [][]rune, tags []lexer.Line, ln int, tabSz int) (pInd, delInd, pLn int, ichr indent.Character) {
if ln == 0 { // the first line has no previous line to indent from
return
}
pInd, pLn, ichr = lexer.PrevLineIndent(src, tags, ln, tabSz)
curUnd, _ := lexer.LineStartEndBracket(src[ln], tags[ln])
_, prvInd := lexer.LineStartEndBracket(src[pLn], tags[pLn])
brackParen := false // true if line only has bracket and paren -- outdent current
if len(tags[pLn]) >= 2 { // allow for comments
pl := tags[pLn][0]
ll := tags[pLn][1]
if ll.Token.Token == token.PunctGpRParen && pl.Token.Token == token.PunctGpRBrace {
brackParen = true
}
}
delInd = 0
if brackParen {
delInd-- // outdent
}
switch {
case prvInd && curUnd:
case prvInd:
delInd++
case curUnd:
delInd--
}
pwrd := lexer.FirstWord(string(src[pLn]))
cwrd := lexer.FirstWord(string(src[ln]))
if cwrd == "case" || cwrd == "default" {
switch pwrd {
case "switch":
delInd = 0
case "case":
delInd = 0
default:
delInd = -1
}
} else if pwrd == "case" || pwrd == "default" {
delInd = 1
}
if pInd == 0 && delInd < 0 { // error..
delInd = 0
}
return
}
// AutoBracket returns what to do when a user types a starting bracket character
// (bracket, brace, paren) while typing.
// pos = position where bra will be inserted, and curLn is the current line
// match = insert the matching ket, and newLine = insert a new line.
func (gl *GoLang) AutoBracket(fs *parse.FileStates, bra rune, pos textpos.Pos, curLn []rune) (match, newLine bool) {
lnLen := len(curLn)
if bra == '{' {
if pos.Char == lnLen {
if lnLen == 0 || unicode.IsSpace(curLn[pos.Char-1]) {
newLine = true
}
match = true
} else {
match = unicode.IsSpace(curLn[pos.Char])
}
} else {
match = pos.Char == lnLen || unicode.IsSpace(curLn[pos.Char]) // at end or if space after
}
return
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !js
package golang
import (
"fmt"
"golang.org/x/tools/go/packages"
)
// packageGoFile returns the first Go file of the package with the given
// import path, using [packages.Load], which deals with GOPATH vs. modules, etc.
func packageGoFile(path string) (string, bool) {
pkgs, err := packages.Load(&packages.Config{Mode: packages.NeedName | packages.NeedFiles}, path)
if err != nil {
// this is too many errors!
// log.Println(err)
return "", false
}
if len(pkgs) != 1 {
fmt.Printf("More than one package for path: %v\n", path)
return "", false
}
pkg := pkgs[0]
if len(pkg.GoFiles) == 0 {
// fmt.Printf("No Go files found in package: %v\n", path)
return "", false
}
return pkg.GoFiles[0], true
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package golang
import (
"fmt"
"log"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"unicode"
"unicode/utf8"
"cogentcore.org/core/base/fileinfo"
"cogentcore.org/core/base/fsx"
"cogentcore.org/core/text/parse"
"cogentcore.org/core/text/parse/syms"
"cogentcore.org/core/text/token"
)
// ParseDirLock provides a lock protecting parsing of a package directory
type ParseDirLock struct {
// logical import path
Path string
Processing bool
// mutex protecting processing of this path
Mu sync.Mutex `json:"-" xml:"-"`
}
// ParseDirLocks manages locking for parsing package directories
type ParseDirLocks struct {
// map of paths with processing status
Dirs map[string]*ParseDirLock
// mutex protecting access to Dirs
Mu sync.Mutex `json:"-" xml:"-"`
}
// TheParseDirs is the parse dirs locking manager
var TheParseDirs ParseDirLocks
// ParseDir is how you call ParseDir on a given path in a secure way that is
// managed for multiple accesses. If dir is currently being parsed, then
// the mutex is locked and caller will wait until that is done -- at which point
// the next one should be able to load parsed symbols instead of parsing fresh.
// Once the symbols are returned, then the local FileState SymsMu lock must be
// used when integrating any external symbols back into another filestate.
// As long as all the symbol resolution etc is all happening outside of the
// external syms linking, then it does not need to be protected.
func (pd *ParseDirLocks) ParseDir(gl *GoLang, fs *parse.FileState, path string, opts parse.LanguageDirOptions) *syms.Symbol {
pfld := strings.Fields(path)
if len(pfld) > 1 { // remove first alias
path = pfld[1]
}
pd.Mu.Lock()
if pd.Dirs == nil {
pd.Dirs = make(map[string]*ParseDirLock)
}
ds, has := pd.Dirs[path]
if !has {
ds = &ParseDirLock{Path: path}
pd.Dirs[path] = ds
}
pd.Mu.Unlock()
ds.Mu.Lock()
ds.Processing = true
rsym := gl.ParseDirImpl(fs, path, opts)
ds.Processing = false
ds.Mu.Unlock()
return rsym
}
// ParseDirExcludes are files to exclude in processing directories
// because they take a long time and aren't very useful (data files).
// Any file that contains one of these strings is excluded.
var ParseDirExcludes = []string{
"/image/font/gofont/",
"zerrors_",
"unicode/tables.go",
"filecat/mimetype.go",
"/html/entity.go",
"/draw/impl.go",
"/truetype/hint.go",
"/runtime/proc.go",
}
// ParseDir is the interface call for parsing a directory
func (gl *GoLang) ParseDir(fs *parse.FileState, path string, opts parse.LanguageDirOptions) *syms.Symbol {
if path == "" || path == "C" || path[0] == '_' {
return nil
}
return TheParseDirs.ParseDir(gl, fs, path, opts)
}
// ParseDirImpl does the actual work of parsing a directory.
// Path is assumed to be a package import path or a local file name
func (gl *GoLang) ParseDirImpl(fs *parse.FileState, path string, opts parse.LanguageDirOptions) *syms.Symbol {
var files []string
var pkgPathAbs string
gm := os.Getenv("GO111MODULE")
if filepath.IsAbs(path) {
pkgPathAbs = path
} else {
pkgPathAbs = path
if gm == "off" { // note: using GOPATH manual mechanism as packages.Load is very slow
// fmt.Printf("nomod\n")
_, err := os.Stat(pkgPathAbs)
if os.IsNotExist(err) {
pkgPathAbs, err = fsx.GoSrcDir(pkgPathAbs)
if err != nil {
if TraceTypes {
log.Println(err)
}
return nil
}
} else if err != nil {
log.Println(err.Error())
return nil
}
pkgPathAbs, _ = filepath.Abs(pkgPathAbs)
} else { // modules mode
fabs, has := fs.PathMapLoad(path) // only use cache for modules mode -- GOPATH is fast
if has && !opts.Rebuild { // rebuild always re-paths
pkgPathAbs = fabs
// fmt.Printf("using cached path: %s to: %s\n", path, pkgPathAbs)
} else {
// fmt.Printf("mod: loading package: %s\n", path)
fgo, ok := packageGoFile(path)
if !ok {
return nil
}
pkgPathAbs, _ = filepath.Abs(filepath.Dir(fgo))
// fmt.Printf("mod: %v package: %v PkgPath: %s\n", gm, path, pkgPathAbs)
}
fs.PathMapStore(path, pkgPathAbs) // cache for later
}
// fmt.Printf("Parsing, loading path: %v\n", path)
}
files = fsx.Filenames(pkgPathAbs, ".go")
if len(files) == 0 {
// fmt.Printf("No go files, bailing\n")
return nil
}
files = slices.DeleteFunc(files, func(s string) bool {
return strings.Contains(s, "_test.go") || strings.HasPrefix(s, "_")
})
for i, pt := range files {
files[i] = filepath.Join(pkgPathAbs, pt)
}
if !opts.Rebuild {
csy, cts, err := syms.OpenSymCache(fileinfo.Go, pkgPathAbs)
if err == nil && csy != nil {
sydir := filepath.Dir(csy.Filename)
diffPath := sydir != pkgPathAbs
// if diffPath {
// fmt.Printf("rebuilding %v because path: %v != cur path: %v\n", path, sydir, pkgPathAbs)
// }
if diffPath || (!gl.Pr.ModTime.IsZero() && cts.Before(gl.Pr.ModTime)) {
// fmt.Printf("rebuilding %v because parser: %v is newer than cache: %v\n", path, gl.Pr.ModTime, cts)
} else {
lstmod := fsx.LatestMod(pkgPathAbs, ".go")
if lstmod.Before(cts) {
// fmt.Printf("loaded cache for: %v from: %v\n", pkgPathAbs, cts)
return csy
}
}
}
}
pr := gl.Parser()
var pkgsym *syms.Symbol
var fss []*parse.FileState // file states for each file
for _, fpath := range files {
fnm := filepath.Base(fpath)
if strings.HasSuffix(fnm, "_test.go") {
continue
}
// avoid processing long slow files that aren't needed anyway:
excl := false
for _, ex := range ParseDirExcludes {
if strings.Contains(fpath, ex) {
excl = true
break
}
}
if excl {
continue
}
fs := parse.NewFileState() // we use a separate fs for each file, so we have full ast
fss = append(fss, fs)
// optional monitoring of parsing
// fs.ParseState.Trace.On = true
// fs.ParseState.Trace.Match = true
// fs.ParseState.Trace.NoMatch = true
// fs.ParseState.Trace.Run = true
// fs.ParseState.Trace.RunAct = true
// fs.ParseState.Trace.StdOut()
err := fs.Src.OpenFile(fpath)
if err != nil {
continue
}
// fmt.Printf("parsing file: %v\n", fnm)
// stt := time.Now()
pr.LexAll(fs)
// lxdur := time.Since(stt)
pr.ParseAll(fs)
// prdur := time.Since(stt)
// if prdur > 500*time.Millisecond {
// fmt.Printf("file: %s full parse: %v\n", fpath, prdur)
// }
if len(fs.ParseState.Scopes) > 0 { // should be
pkg := fs.ParseState.Scopes[0]
gl.DeleteUnexported(pkg, pkg.Name)
if pkgsym == nil {
pkgsym = pkg
} else {
pkgsym.CopyFromScope(pkg)
if TraceTypes {
pkgsym.Types.PrintUnknowns()
}
}
// } else {
// fmt.Printf("\tno parse state scopes!\n")
}
}
if pkgsym == nil || len(fss) == 0 {
return nil
}
pfs := fss[0] // parse.NewFileState() // master overall package file state
gl.ResolveTypes(pfs, pkgsym, false) // false = don't include function-internal scope items
gl.DeleteExternalTypes(pkgsym)
if !opts.Nocache {
syms.SaveSymCache(pkgsym, fileinfo.Go, pkgPathAbs)
}
pkgsym.ClearAST() // otherwise memory can be huge -- can comment this out for debugging
for _, fs := range fss {
fs.Destroy()
}
return pkgsym
}
/////////////////////////////////////////////////////////////////////////////
// Go util funcs
// DeleteUnexported deletes lower-case unexported items from map, and
// children of symbols on map
func (gl *GoLang) DeleteUnexported(sy *syms.Symbol, pkgsc string) {
if sy.Kind.SubCat() != token.NameScope { // only for top-level scopes
return
}
for nm, ss := range sy.Children {
if ss == sy {
fmt.Printf("warning: child is self!: %v\n", sy.String())
delete(sy.Children, nm)
continue
}
if ss.Kind.SubCat() != token.NameScope { // typically lowercase
rn, _ := utf8.DecodeRuneInString(nm)
if nm == "" || unicode.IsLower(rn) {
delete(sy.Children, nm)
continue
}
// sc, has := ss.Scopes[token.NamePackage]
// if has && sc != pkgsc {
// fmt.Printf("excluding out-of-scope symbol: %v %v\n", sc, ss.String())
// delete(sy.Children, nm)
// continue
// }
}
if ss.HasChildren() {
gl.DeleteUnexported(ss, pkgsc)
}
}
}
// DeleteExternalTypes deletes types from outside current package scope.
// These can be created during ResolveTypes but should be deleted before
// saving symbol type.
func (gl *GoLang) DeleteExternalTypes(sy *syms.Symbol) {
pkgsc := sy.Name
for nm, ty := range sy.Types {
sc, has := ty.Scopes[token.NamePackage]
if has && sc != pkgsc {
// fmt.Printf("excluding out-of-scope type: %v %v\n", sc, ty.String())
delete(sy.Types, nm)
continue
}
}
}
// ImportPathPkg returns the package (last dir) and base of import path
// from import path string -- removes any quotes around path first.
func (gl *GoLang) ImportPathPkg(im string) (path, base, pkg string) {
sz := len(im)
if sz < 3 {
return
}
path = im
if im[0] == '"' {
path = im[1 : sz-1]
}
base, pkg = filepath.Split(path)
return
}
// PkgSyms attempts to find package symbols for given package name.
// Is also passed any current package symbol context in psyms which might be
// different from default filestate context.
// It can add the package to ExtSyms, so the FileState SymsMu lock must
// be locked by the caller.
func (gl *GoLang) PkgSyms(fs *parse.FileState, psyms syms.SymMap, pnm string) (*syms.Symbol, bool) {
psym, has := fs.ExtSyms[pnm]
if has {
return psym, has
}
ipsym, has := gl.FindImportPkg(fs, psyms, pnm) // look for import within psyms package symbols
if has {
gl.AddImportToExts(fs, ipsym.Name, false) // no lock
psym, has = fs.ExtSyms[pnm]
}
return psym, has
}
// AddImportsToExts adds imports from given package into parse.FileState.ExtSyms list
// imports are coded as NameLibrary symbols with names = import path
func (gl *GoLang) AddImportsToExts(fss *parse.FileStates, pfs *parse.FileState, pkg *syms.Symbol) {
var imps syms.SymMap
pfs.SymsMu.RLock()
pkg.Children.FindKindScoped(token.NameLibrary, &imps)
pfs.SymsMu.RUnlock()
for _, im := range imps {
if im.Name == "C" {
continue
}
// lock, as other parsing goroutines can add to the same ExtSyms
gl.AddImportToExts(pfs, im.Name, true)
}
// now all the info is in place: parse it
if TraceTypes {
fmt.Printf("\n#####################\nResolving Types now for: %v\n", pfs.Src.Filename)
}
// the types are resolved with or without imports
gl.ResolveTypes(pfs, pkg, true) // true = do include function-internal scope items
pfs.SymsMu.Lock()
pfs.ClearAST()
pkg.ClearAST()
pfs.SymsMu.Unlock()
// if pfs.AST.HasChildren() {
// pfs.AST.DeleteChildren()
// }
}
// AddImportToExts adds given import into parse.FileState.ExtSyms list.
// If lock is true, it adds it under the FileState SymsMu lock, which
// must otherwise already be locked by the caller.
func (gl *GoLang) AddImportToExts(fs *parse.FileState, im string, lock bool) {
im, _, pkg := gl.ImportPathPkg(im)
psym := gl.ParseDir(fs, im, parse.LanguageDirOptions{})
if psym != nil {
psym.Name = pkg
if lock {
fs.SymsMu.Lock()
}
gl.AddPkgToExts(fs, psym)
if lock {
fs.SymsMu.Unlock()
}
}
}
// AddPathToSyms adds given path into parse.FileState.Syms list
// Is called as a separate goroutine in ParseFile with WaitGp
func (gl *GoLang) AddPathToSyms(fs *parse.FileState, path string) {
psym := gl.ParseDir(fs, path, parse.LanguageDirOptions{})
if psym != nil {
gl.AddPkgToSyms(fs, psym)
}
fs.WaitGp.Done()
}
// AddPkgToSyms adds given package symbol, with children from package
// to parse.FileState.Syms map -- merges with anything already there
// does NOT add imports -- that is an optional second step.
// Returns true if there was an existing entry for this package.
func (gl *GoLang) AddPkgToSyms(fs *parse.FileState, pkg *syms.Symbol) bool {
fs.SymsMu.Lock()
psy, has := fs.Syms[pkg.Name]
if has {
// fmt.Printf("AddPkgToSyms: importing pkg types: %v\n", pkg.Name)
psy.CopyFromScope(pkg)
if TraceTypes {
psy.Types.PrintUnknowns()
}
} else {
fs.Syms[pkg.Name] = pkg
}
fs.SymsMu.Unlock()
return has
}
// AddPathToExts adds given path into parse.FileState.ExtSyms list
// assumed to be called as a separate goroutine
func (gl *GoLang) AddPathToExts(fs *parse.FileState, path string) {
psym := gl.ParseDir(fs, path, parse.LanguageDirOptions{})
if psym != nil {
fs.SymsMu.Lock()
gl.AddPkgToExts(fs, psym)
fs.SymsMu.Unlock()
}
}
// AddPkgToExts adds given package symbol, with children from package
// to parse.FileState.ExtSyms map -- merges with anything already there
// does NOT add imports -- that is an optional second step.
// Returns true if there was an existing entry for this package.
// The FileState SymsMu lock must be locked by the caller.
func (gl *GoLang) AddPkgToExts(fs *parse.FileState, pkg *syms.Symbol) bool {
psy, has := fs.ExtSyms[pkg.Name]
if has {
psy.CopyFromScope(pkg)
pkg = psy
} else {
if fs.ExtSyms == nil {
fs.ExtSyms = make(syms.SymMap)
}
fs.ExtSyms[pkg.Name] = pkg
}
return has
}
// FindImportPkg attempts to find an import package based on symbols in
// an existing package. For indirect loading of packages from other packages
// that we don't direct import.
func (gl *GoLang) FindImportPkg(fs *parse.FileState, psyms syms.SymMap, nm string) (*syms.Symbol, bool) {
for _, sy := range psyms {
if sy.Kind != token.NameLibrary {
continue
}
_, _, pkg := gl.ImportPathPkg(sy.Name)
if pkg == nm {
return sy, true
}
}
return nil, false
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package golang
import (
"fmt"
"os"
"strings"
"cogentcore.org/core/text/parse"
"cogentcore.org/core/text/parse/parser"
"cogentcore.org/core/text/parse/syms"
"cogentcore.org/core/text/token"
)
// TypeErr indicates is the type name we use to indicate that the type could not be inferred
var TypeErr = "<err>"
// TypeInProcess indicates is the type name we use to indicate that the type
// is currently being processed -- prevents loops
var TypeInProcess = "<in-process>"
// InferSymbolType infers the symbol types for given symbol and all of its children
// funInternal determines whether to include function-internal symbols
// (e.g., variables within function scope -- only for local files).
func (gl *GoLang) InferSymbolType(sy *syms.Symbol, fs *parse.FileState, pkg *syms.Symbol, funInternal bool) {
if sy.Name == "" {
sy.Type = TypeErr
return
}
if sy.Name[0] == '_' {
sy.Type = TypeErr
return
}
if sy.AST != nil {
ast := sy.AST.(*parser.AST)
switch {
case sy.Kind == token.NameField:
stsc, ok := sy.Scopes[token.NameStruct]
if ok {
stty, _ := gl.FindTypeName(stsc, fs, pkg)
if stty != nil {
fldel := stty.Els.ByName(sy.Name)
if fldel != nil {
sy.Type = fldel.Type
// fmt.Printf("set field type: %s\n", sy.Label())
} else {
if TraceTypes {
fmt.Printf("InferSymbolType: field named: %v not found in struct type: %v\n", sy.Name, stty.Name)
}
}
} else {
if TraceTypes {
fmt.Printf("InferSymbolType: field named: %v struct type: %v not found\n", sy.Name, stsc)
}
}
if sy.Type == "" {
sy.Type = stsc + "." + sy.Name
}
} else {
if TraceTypes {
fmt.Printf("InferSymbolType: field named: %v doesn't have NameStruct scope\n", sy.Name)
}
}
case sy.Kind == token.NameVarClass: // method receiver
stsc, ok := sy.Scopes.SubCat(token.NameType)
if ok {
sy.Type = stsc
}
case sy.Kind.SubCat() == token.NameVar:
var astyp *parser.AST
if ast.HasChildren() {
if strings.HasPrefix(ast.Name, "ForRange") {
gl.InferForRangeSymbolType(sy, fs, pkg)
} else if vty, ok, multi := gl.multiValueType(sy, fs, pkg, ast); multi {
if ok {
sy.Type = SymTypeNameForPkg(vty, pkg)
} else {
sy.Type = TypeErr
}
} else {
astyp = ast.ChildAST(len(ast.Children) - 1)
vty, ok := gl.TypeFromAST(fs, pkg, nil, astyp)
if ok {
sy.Type = SymTypeNameForPkg(vty, pkg)
// if TraceTypes {
// fmt.Printf("namevar: %v type: %v from ast\n", sy.Name, sy.Type)
// }
} else {
sy.Type = TypeErr // actively mark as err so not re-processed
if TraceTypes {
fmt.Printf("InferSymbolType: NameVar: %v NOT resolved from ast: %v\n", sy.Name, astyp.Path())
astyp.WriteTree(os.Stdout, 0)
}
}
}
} else {
sy.Type = TypeErr
if TraceTypes {
fmt.Printf("InferSymbolType: NameVar: %v has no children\n", sy.Name)
}
}
case sy.Kind == token.NameConstant:
if !strings.HasPrefix(ast.Name, "ConstSpec") {
if TraceTypes {
fmt.Printf("InferSymbolType: NameConstant: %v not a const: %v\n", sy.Name, ast.Name)
}
return
}
parent := ast.ParentAST()
if parent != nil && parent.HasChildren() {
fc := parent.ChildAST(0)
if fc.HasChildren() {
ffc := fc.ChildAST(0)
if ffc.Name == "Name" {
ffc = ffc.NextAST()
}
var vty *syms.Type
if ffc != nil {
vty, _ = gl.TypeFromAST(fs, pkg, nil, ffc)
}
if vty != nil {
sy.Type = SymTypeNameForPkg(vty, pkg)
} else {
sy.Type = TypeErr
if TraceTypes {
fmt.Printf("InferSymbolType: NameConstant: %v NOT resolved from ast: %v\n", sy.Name, ffc.Path())
ffc.WriteTree(os.Stdout, 1)
}
}
} else {
sy.Type = TypeErr
}
} else {
sy.Type = TypeErr
}
case sy.Kind.SubCat() == token.NameType:
vty, _ := gl.FindTypeName(sy.Name, fs, pkg)
if vty != nil {
sy.Type = SymTypeNameForPkg(vty, pkg)
} else {
// if TraceTypes {
// fmt.Printf("InferSymbolType: NameType: %v\n", sy.Name)
// }
if ast.HasChildren() {
astyp := ast.ChildAST(len(ast.Children) - 1)
if astyp.Name == "FieldTag" {
// ast.WriteTree(os.Stdout, 1)
astyp = ast.ChildAST(len(ast.Children) - 2)
}
vty, ok := gl.TypeFromAST(fs, pkg, nil, astyp)
if ok {
sy.Type = SymTypeNameForPkg(vty, pkg)
// if TraceTypes {
// fmt.Printf("InferSymbolType: NameType: %v type: %v from ast\n", sy.Name, sy.Type)
// }
} else {
sy.Type = TypeErr // actively mark as err so not re-processed
if TraceTypes {
fmt.Printf("InferSymbolType: NameType: %v NOT resolved from ast: %v\n", sy.Name, astyp.Path())
ast.WriteTree(os.Stdout, 1)
}
}
} else {
sy.Type = TypeErr
}
}
case sy.Kind == token.NameFunction:
ftyp := gl.FuncTypeFromAST(fs, pkg, ast, nil)
if ftyp != nil {
ftyp.Name = "func " + sy.Name
ftyp.Filename = sy.Filename
ftyp.Region = sy.Region
sy.Type = ftyp.Name
pkg.Types.Add(ftyp)
sy.Detail = "(" + ftyp.ArgString() + ") " + ftyp.ReturnString()
// if TraceTypes {
// fmt.Printf("InferSymbolType: added function type: %v %v\n", ftyp.Name, ftyp.String())
// }
}
}
}
if !funInternal && sy.Kind.SubCat() == token.NameFunction {
sy.Children = nil // nuke!
} else {
for _, ss := range sy.Children {
if sy != ss {
if false && TraceTypes {
fmt.Printf("InferSymbolType: processing child: %v\n", ss)
}
gl.InferSymbolType(ss, fs, pkg, funInternal)
}
}
}
}
// multiValueType returns the type of a variable of a definition of
// several variables, as a, b := x, y or v, err := f(), from the value
// that it gets. multi is false for a definition of one variable, whose
// type is that of the last child of the ast (its value).
func (gl *GoLang) multiValueType(sy *syms.Symbol, fs *parse.FileState, pkg *syms.Symbol, ast *parser.AST) (vty *syms.Type, ok, multi bool) {
// the variables are the names followed by a comma or :=
nvars := 0
idx := -1
for i := range ast.Children {
ch := ast.ChildAST(i)
if ch.Name != "Name" {
break
}
pos, valid := fs.Src.ValidTokenPos(ch.TokReg.End)
if !valid {
break
}
tok := fs.Src.LexAt(pos).Token.Token
if tok != token.PunctSepComma && tok != token.OpAsgnDefine {
break
}
if ch.Src == sy.Name {
idx = i
}
nvars++
if tok == token.OpAsgnDefine {
break
}
}
if nvars < 2 || idx < 0 {
return nil, false, false
}
vals := ast.Children[nvars:]
if len(vals) == nvars { // a, b := x, y
vty, ok = gl.TypeFromAST(fs, pkg, nil, vals[idx].(*parser.AST))
return vty, ok, true
}
if len(vals) != 1 {
return nil, false, true
}
val := vals[0].(*parser.AST)
if val.Name != "FuncCall" { // v, ok := m[k], x.(T), <-ch
if idx == 0 {
vty, ok = gl.TypeFromAST(fs, pkg, nil, val)
return vty, ok, true
}
return BuiltinTypes["bool"], true, true
}
// v, err := f(): only for a call of a function by name
fun := val.ChildAST(0)
if fun == nil || fun.Name != "Name" || val.NumChildren() != 1 {
if idx == 0 {
vty, ok = gl.TypeFromAST(fs, pkg, nil, val)
}
return vty, ok, true
}
fsym, got := fs.FindNameScoped(fun.Src, nil)
if !got || !gl.InferEmptySymbolType(fsym, fs, pkg) {
return nil, false, true
}
ftyp, _ := gl.FindTypeName(fsym.Type, fs, pkg)
if ftyp == nil || len(ftyp.Size) != 2 || idx >= ftyp.Size[1] {
return nil, false, true
}
rv := ftyp.Els[ftyp.Size[0]+idx]
vty, _ = gl.FindTypeName(rv.Type, fs, pkg)
return vty, vty != nil, true
}
// InferForRangeSymbolType infers the type of a ForRange expr
// gets the container type properly
func (gl *GoLang) InferForRangeSymbolType(sy *syms.Symbol, fs *parse.FileState, pkg *syms.Symbol) {
ast := sy.AST.(*parser.AST)
if ast.NumChildren() < 2 {
sy.Type = TypeErr // actively mark as err so not re-processed
if TraceTypes {
fmt.Printf("InferSymbolType: ForRange NameVar: %v does not have expected 2+ children\n", sy.Name)
ast.WriteTree(os.Stdout, 0)
}
return
}
// vars are in first child, type is in second child, rest of code is on last node
astyp := ast.ChildAST(1)
vty, ok := gl.TypeFromAST(fs, pkg, nil, astyp)
if !ok {
sy.Type = TypeErr // actively mark as err so not re-processed
if TraceTypes {
fmt.Printf("InferSymbolType: NameVar: %v NOT resolved from ForRange ast: %v\n", sy.Name, astyp.Path())
astyp.WriteTree(os.Stdout, 0)
}
return
}
varidx := 1 // which variable are we: first or second?
vast := ast.ChildAST(0)
if vast.NumChildren() <= 1 {
varidx = 0
} else if vast.ChildAST(0).Src == sy.Name {
varidx = 0
}
// vty is the container -- first el should be the type of element
switch vty.Kind {
case syms.Map: // need to know if we are the key or el
if len(vty.Els) > 1 {
tn := vty.Els[varidx].Type
if IsQualifiedType(vty.Name) && !IsQualifiedType(tn) {
pnm, _ := SplitType(vty.Name)
sy.Type = QualifyType(pnm, tn)
} else {
sy.Type = tn
}
} else {
sy.Type = TypeErr
if TraceTypes {
fmt.Printf("InferSymbolType: %s has ForRange over Map on type without an el type: %v\n", sy.Name, vty.Name)
}
}
case syms.Array, syms.List:
if varidx == 0 {
sy.Type = "int"
} else if len(vty.Els) > 0 {
tn := vty.Els[0].Type
if IsQualifiedType(vty.Name) && !IsQualifiedType(tn) {
pnm, _ := SplitType(vty.Name)
sy.Type = QualifyType(pnm, tn)
} else {
sy.Type = tn
}
} else {
sy.Type = TypeErr
if TraceTypes {
fmt.Printf("InferSymbolType: %s has ForRange over Array, List on type without an el type: %v\n", sy.Name, vty.Name)
}
}
case syms.String:
if varidx == 0 {
sy.Type = "int"
} else {
sy.Type = "rune"
}
case syms.Chan: // the values received
if len(vty.Els) > 0 {
sy.Type = vty.Els[0].Type
} else {
sy.Type = TypeErr
}
default:
sy.Type = TypeErr
if TraceTypes {
fmt.Printf("InferSymbolType: %s has ForRange over non-container type: %v kind: %v\n", sy.Name, vty.Name, vty.Kind)
}
}
}
// InferEmptySymbolType ensures that any empty symbol type is resolved during
// processing of other type information -- returns true if was able to resolve
func (gl *GoLang) InferEmptySymbolType(sym *syms.Symbol, fs *parse.FileState, pkg *syms.Symbol) bool {
if sym.Type == "" { // hasn't happened yet
// if TraceTypes {
// fmt.Printf("TExpr: trying to infer type\n")
// }
sym.Type = TypeInProcess
gl.InferSymbolType(sym, fs, pkg, true)
}
if sym.Type == TypeInProcess {
if TraceTypes {
fmt.Printf("TExpr: source symbol is in process -- we have a loop: %v kind: %v\n", sym.Name, sym.Kind)
}
sym.Type = TypeErr
return false
}
if sym.Type == TypeErr {
if TraceTypes {
fmt.Printf("TExpr: source symbol has type err: %v kind: %v\n", sym.Name, sym.Kind)
}
return false
}
if sym.Type == "" { // shouldn't happen
sym.Type = TypeErr
if TraceTypes {
fmt.Printf("TExpr: source symbol has type err (but wasn't marked): %v kind: %v\n", sym.Name, sym.Kind)
}
return false
}
return true
}
func SymTypeNameForPkg(ty *syms.Type, pkg *syms.Symbol) string {
sc, has := ty.Scopes[token.NamePackage]
if has && sc != pkg.Name {
return QualifyType(sc, ty.Name)
}
return ty.Name
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package golang
import (
"cogentcore.org/core/text/parse/syms"
"cogentcore.org/core/text/token"
"slices"
)
// FuncParams returns the parameters of given function / method symbol,
// in proper order, name type for each param space separated in string
func (gl *GoLang) FuncParams(fsym *syms.Symbol) []string {
// the params are in the order of their positions in the source, and
// in the order of their indexes for the same position (the names
// of one type, as in w, h float64), which is the order of the parser.
var params []*syms.Symbol
for _, cs := range fsym.Children {
if cs.Kind == token.NameVarParam {
params = append(params, cs)
}
}
slices.SortFunc(params, func(a, b *syms.Symbol) int {
switch {
case a.Region.Start.IsLess(b.Region.Start):
return -1
case b.Region.Start.IsLess(a.Region.Start):
return 1
}
return a.Index - b.Index
})
ps := make([]string, len(params))
for i, cs := range params {
ps[i] = cs.Name + " " + cs.Type
}
return ps
}
// Copyright (c) 2020, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package golang
import (
"fmt"
"strings"
"sync/atomic"
"cogentcore.org/core/text/parse"
"cogentcore.org/core/text/parse/parser"
"cogentcore.org/core/text/parse/syms"
"cogentcore.org/core/text/token"
)
var TraceTypes = false
// IsQualifiedType returns true if type is qualified by a package prefix
// is sensitive to [] or map[ prefix so it does NOT report as a qualified type in that
// case -- it is a compound local type defined in terms of a qualified type.
func IsQualifiedType(tnm string) bool {
if strings.HasPrefix(tnm, "[]") || strings.HasPrefix(tnm, "map[") {
return false
}
return strings.Index(tnm, ".") > 0
}
// QualifyType returns the type name tnm qualified by pkgnm if it is non-empty
// and only if tnm is not a basic type name
func QualifyType(pkgnm, tnm string) string {
if pkgnm == "" || IsQualifiedType(tnm) {
return tnm
}
// the element type of a composite type is qualified, with the package
// outside (as by [PrefixType]): pkg.[]T and pkg.*T, but []byte
for _, pfx := range []string{"[]", "*", "chan ", "<-chan ", "chan<- "} {
if strings.HasPrefix(tnm, pfx) {
epkg, etnm := SplitType(QualifyType(pkgnm, tnm[len(pfx):]))
if epkg == "" { // a builtin element type
return pfx + etnm
}
return epkg + "." + pfx + etnm
}
}
if strings.HasPrefix(tnm, "map[") || strings.HasPrefix(tnm, "func") {
return tnm // (its parts are not parsed here)
}
if _, btyp := BuiltinTypes[tnm]; btyp {
return tnm
}
return pkgnm + "." + tnm
}
// SplitType returns the package and type names from a potentially qualified
// type name -- if it is not qualified, package name is empty.
// is sensitive to [] prefix so it does NOT split in that case
func SplitType(nm string) (pkgnm, tnm string) {
if !IsQualifiedType(nm) {
return "", nm
}
sci := strings.Index(nm, ".")
return nm[:sci], nm[sci+1:]
}
// PrefixType returns the type name prefixed with given prefix -- keeps any
// package name as the outer scope.
func PrefixType(pfx, nm string) string {
pkgnm, tnm := SplitType(nm)
return QualifyType(pkgnm, pfx+tnm)
}
// FindTypeName finds given type name in pkg and in broader context
// returns new package symbol if type name is in a different package
// else returns pkg arg.
func (gl *GoLang) FindTypeName(tynm string, fs *parse.FileState, pkg *syms.Symbol) (*syms.Type, *syms.Symbol) {
if tynm == "" {
return nil, nil
}
if tynm[0] == '*' {
tynm = tynm[1:]
}
pnm, tnm := SplitType(tynm)
if pnm == "" {
if btyp, ok := BuiltinTypes[tnm]; ok {
return btyp, pkg
}
if gtyp, ok := pkg.Types[tnm]; ok {
return gtyp, pkg
}
// if TraceTypes {
// fmt.Printf("FindTypeName: unqualified type name: %v not found in package: %v\n", tnm, pkg.Name)
// }
return nil, pkg
}
if npkg, ok := gl.PkgSyms(fs, pkg.Children, pnm); ok {
if gtyp, ok := npkg.Types[tnm]; ok {
return gtyp, npkg
}
if TraceTypes {
fmt.Printf("FindTypeName: type name: %v not found in package: %v\n", tnm, pnm)
}
} else {
if TraceTypes {
fmt.Printf("FindTypeName: could not find package: %v\n", pnm)
}
}
if TraceTypes {
fmt.Printf("FindTypeName: type name: %v not found in package: %v\n", tynm, pkg.Name)
}
return nil, pkg
}
// ResolveTypes initializes all user-defined types from AST data
// and then resolves types of symbols. The pkg must be a single
// package symbol i.e., the children there are all the elements of the
// package and the types are all the global types within the package.
// funInternal determines whether to include function-internal symbols
// (e.g., variables within function scope -- only for local files).
func (gl *GoLang) ResolveTypes(fs *parse.FileState, pkg *syms.Symbol, funInternal bool) {
fs.SymsMu.Lock()
gl.TypesFromAST(fs, pkg)
gl.InferSymbolType(pkg, fs, pkg, funInternal)
fs.SymsMu.Unlock()
}
// TypesFromAST initializes the types from their AST parse
func (gl *GoLang) TypesFromAST(fs *parse.FileState, pkg *syms.Symbol) {
InstallBuiltinTypes()
for _, ty := range pkg.Types {
gl.InitTypeFromAST(fs, pkg, ty)
}
}
// InitTypeFromAST initializes given type from ast
func (gl *GoLang) InitTypeFromAST(fs *parse.FileState, pkg *syms.Symbol, ty *syms.Type) {
if ty.AST == nil || len(ty.AST.AsTree().Children) < 2 {
// if TraceTypes {
// fmt.Printf("TypesFromAST: Type has nil AST! %v\n", ty.String())
// }
return
}
tyast := ty.AST.(*parser.AST).ChildAST(1)
if tyast == nil {
if TraceTypes {
fmt.Printf("TypesFromAST: Type has invalid AST! %v missing child 1\n", ty.String())
}
return
}
if ty.Name == "" {
if TraceTypes {
fmt.Printf("TypesFromAST: Type has no name! %v\n", ty.String())
}
return
}
if ty.Initialized {
// if TraceTypes {
// fmt.Printf("Type: %v already initialized\n", ty.Name)
// }
return
}
gl.TypeFromAST(fs, pkg, ty, tyast)
gl.TypeMeths(fs, pkg, ty) // all top-level named types might have methods
ty.Initialized = true
}
// SubTypeFromAST returns a subtype from child ast at given index, nil if failed
func (gl *GoLang) SubTypeFromAST(fs *parse.FileState, pkg *syms.Symbol, ast *parser.AST, idx int) (*syms.Type, bool) {
sast := ast.ChildASTTry(idx)
if sast == nil {
if TraceTypes {
fmt.Printf("TraceTypes: could not find child %d on ast %v", idx, ast)
}
return nil, false
}
return gl.TypeFromAST(fs, pkg, nil, sast)
}
// TypeToKindMap maps AST type names to syms.Kind basic categories for how we
// treat them for subsequent processing. Basically: Primitive or Composite
var TypeToKindMap = map[string]syms.Kinds{
"BasicType": syms.Primitive,
"TypeNm": syms.Primitive,
"QualType": syms.Primitive,
"PointerType": syms.Primitive,
"MapType": syms.Composite,
"SliceType": syms.Composite,
"ArrayType": syms.Composite,
"StructType": syms.Composite,
"InterfaceType": syms.Composite,
"FuncType": syms.Composite,
"SRChanType": syms.Composite, // chan T
"SendChanType": syms.Composite, // <-chan T (the grammar names it by its arrow)
"RecvChanType": syms.Composite, // chan<- T
"StringDbl": syms.KindsN, // note: Lit is removed by ASTTypeName
"StringTicks": syms.KindsN,
"Rune": syms.KindsN,
"NumInteger": syms.KindsN,
"NumFloat": syms.KindsN,
"NumImag": syms.KindsN,
}
// ASTTypeName returns the effective type name from ast node
// dropping the "Lit" for example.
func (gl *GoLang) ASTTypeName(tyast *parser.AST) string {
return strings.TrimPrefix(tyast.Name, "Lit")
}
// TypeFromAST returns type from AST parse -- returns true if successful.
// This is used both for initialization of global types via TypesFromAST
// and also for online type processing in the course of tracking down
// other types while crawling the AST. In the former case, ty is non-nil
// and the goal is to fill out the type information -- the ty will definitely
// have a name already. In the latter case, the ty will be nil, but the
// tyast node may have a Src name that will first be looked up to determine
// if a previously processed type is already available. The tyast.Name is
// the parser categorization of the type (BasicType, StructType, etc).
func (gl *GoLang) TypeFromAST(fs *parse.FileState, pkg *syms.Symbol, ty *syms.Type, tyast *parser.AST) (*syms.Type, bool) {
tnm := gl.ASTTypeName(tyast)
bkind, ok := TypeToKindMap[tnm]
if !ok { // must be some kind of expression
sty, _, got := gl.TypeFromASTExprStart(fs, pkg, pkg, tyast)
return sty, got
}
switch bkind {
case syms.Primitive:
return gl.TypeFromASTPrim(fs, pkg, ty, tyast)
case syms.Composite:
return gl.TypeFromASTComp(fs, pkg, ty, tyast)
case syms.KindsN:
return gl.TypeFromASTLit(fs, pkg, ty, tyast)
}
return nil, false
}
// TypeFromASTPrim handles primitive (non composite) type processing
func (gl *GoLang) TypeFromASTPrim(fs *parse.FileState, pkg *syms.Symbol, ty *syms.Type, tyast *parser.AST) (*syms.Type, bool) {
tnm := gl.ASTTypeName(tyast)
src := tyast.Src
etyp, tpkg := gl.FindTypeName(src, fs, pkg)
if etyp != nil {
if ty == nil { // if we can find an existing type, and not filling in global, use it
if tpkg != pkg {
pkgnm := tpkg.Name
qtnm := QualifyType(pkgnm, etyp.Name)
if qtnm != etyp.Name {
if letyp, ok := pkg.Types[qtnm]; ok {
etyp = letyp
} else {
ntyp := &syms.Type{}
*ntyp = *etyp
ntyp.Name = qtnm
pkg.Types.Add(ntyp)
etyp = ntyp
}
}
}
return etyp, true
}
} else {
if TraceTypes && src != "" {
fmt.Printf("TypeFromAST: primitive type name: %v not found\n", src)
}
}
switch tnm {
case "BasicType":
if etyp != nil {
ty.Kind = etyp.Kind
ty.Els.Add("par", etyp.Name) // parent type
return ty, true
}
return nil, false
case "TypeNm", "QualType":
if etyp != nil && etyp != ty {
ty.Kind = etyp.Kind
if ty.Name != etyp.Name {
ty.Els.Add("par", etyp.Name) // parent type
if TraceTypes {
fmt.Printf("TypeFromAST: TypeNm %v defined from parent type: %v\n", ty.Name, etyp.Name)
}
}
return ty, true
}
return nil, false
case "PointerType":
if ty == nil {
ty = &syms.Type{}
}
ty.Kind = syms.Ptr
if sty, ok := gl.SubTypeFromAST(fs, pkg, tyast, 0); ok {
ty.Els.Add("ptr", sty.Name)
if ty.Name == "" {
ty.Name = "*" + sty.Name
pkg.Types.Add(ty) // add pointers so we don't have to keep redefining
if TraceTypes {
fmt.Printf("TypeFromAST: Adding PointerType: %v\n", ty.String())
}
}
return ty, true
}
return nil, false
}
return nil, false
}
// typeDepth is the depth of nested [GoLang.TypeFromASTComp] calls, to stop
// runaway recursion. It is atomic because packages can be parsed in
// different goroutines at the same time.
var typeDepth atomic.Int32
// TypeFromASTComp handles composite type processing
func (gl *GoLang) TypeFromASTComp(fs *parse.FileState, pkg *syms.Symbol, ty *syms.Type, tyast *parser.AST) (*syms.Type, bool) {
if typeDepth.Add(1) > 100 {
typeDepth.Store(0)
return nil, false
}
defer typeDepth.Add(-1)
tnm := gl.ASTTypeName(tyast)
newTy := false
if ty == nil {
newTy = true
ty = &syms.Type{}
}
switch tnm {
case "MapType":
ty.Kind = syms.Map
keyty, kok := gl.SubTypeFromAST(fs, pkg, tyast, 0)
valty, vok := gl.SubTypeFromAST(fs, pkg, tyast, 1)
if kok && vok {
ty.Els.Add("key", SymTypeNameForPkg(keyty, pkg))
ty.Els.Add("val", SymTypeNameForPkg(valty, pkg))
if newTy {
ty.Name = "map[" + keyty.Name + "]" + valty.Name
}
} else {
return nil, false
}
case "SliceType":
ty.Kind = syms.List
valty, ok := gl.SubTypeFromAST(fs, pkg, tyast, 0)
if ok {
ty.Els.Add("val", SymTypeNameForPkg(valty, pkg))
if newTy {
ty.Name = "[]" + valty.Name
}
} else {
return nil, false
}
case "ArrayType":
ty.Kind = syms.Array
valty, ok := gl.SubTypeFromAST(fs, pkg, tyast, 1)
if ok {
ty.Els.Add("val", SymTypeNameForPkg(valty, pkg))
if newTy {
ty.Name = "[]" + valty.Name // todo: get size from child0, set to Size
}
} else {
return nil, false
}
case "StructType":
ty.Kind = syms.Struct
nfld := len(tyast.Children)
if nfld == 0 {
return BuiltinTypes["struct{}"], true
}
ty.Size = []int{nfld}
for i := range nfld {
fld := tyast.Children[i].(*parser.AST)
fsrc := fld.Src
switch fld.Name {
case "NamedField":
if len(fld.Children) <= 1 { // anonymous, non-qualified
ty.Els.Add(fsrc, fsrc)
gl.StructInheritEls(fs, pkg, ty, fsrc)
continue
}
fldty, ok := gl.SubTypeFromAST(fs, pkg, fld, 1)
if ok {
nms := gl.NamesFromAST(fs, pkg, fld, 0)
for _, nm := range nms {
ty.Els.Add(nm, SymTypeNameForPkg(fldty, pkg))
}
}
case "AnonQualField", "AnonPtrField": // embedded pkg.Type or *Type
flds := strings.Fields(strings.TrimPrefix(fsrc, "*")) // (without any tag)
if len(flds) == 0 {
continue
}
tnm := flds[0]
_, fnm := SplitType(tnm) // the field is named by the type, without its package
if fld.Name == "AnonPtrField" {
ty.Els.Add(fnm, "*"+tnm)
} else {
ty.Els.Add(fnm, tnm)
}
gl.StructInheritEls(fs, pkg, ty, tnm)
}
}
if newTy {
ty.Name = fs.NextAnonName(pkg.Name + "_struct")
}
// if TraceTypes {
// fmt.Printf("TypeFromAST: New struct type defined: %v\n", ty.Name)
// ty.WriteDoc(os.Stdout, 0)
// }
case "InterfaceType":
ty.Kind = syms.Interface
nmth := len(tyast.Children)
if nmth == 0 {
return BuiltinTypes["interface{}"], true
}
ty.Size = []int{nmth}
for i := range nmth {
fld := tyast.Children[i].(*parser.AST)
fsrc := fld.Src
switch fld.Name {
case "MethSpecAnonLocal":
fallthrough
case "MethSpecAnonQual":
ty.Els.Add(fsrc, fsrc) // anon two are same
case "MethSpecName":
if nm := fld.ChildAST(0); nm != nil {
mty := syms.NewType(ty.Name+":"+nm.Src, syms.Method)
pkg.Types.Add(mty) // add interface methods as new types..
gl.FuncTypeFromAST(fs, pkg, fld, mty) // todo: this is not working -- debug
ty.Els.Add(nm.Src, mty.Name)
}
}
}
if newTy {
if nmth == 0 {
ty.Name = "interface{}"
} else {
ty.Name = fs.NextAnonName(pkg.Name + "_interface")
}
}
case "SRChanType", "SendChanType", "RecvChanType":
ty.Kind = syms.Chan
valty, ok := gl.SubTypeFromAST(fs, pkg, tyast, 0)
if !ok {
return nil, false
}
vnm := SymTypeNameForPkg(valty, pkg)
ty.Els.Add("val", vnm)
if newTy {
ty.Name = map[string]string{"SRChanType": "chan ", "SendChanType": "<-chan ", "RecvChanType": "chan<- "}[tnm] + vnm
}
case "FuncType":
ty.Kind = syms.Func
gl.FuncTypeFromAST(fs, pkg, tyast, ty)
if newTy {
if len(ty.Els) == 0 {
ty.Name = "func()"
} else {
ty.Name = fs.NextAnonName(pkg.Name + "_func")
}
}
}
if newTy {
etyp, has := pkg.Types[ty.Name]
if has {
return etyp, true
}
pkg.Types.Add(ty) // add anon composite types
// if TraceTypes {
// fmt.Printf("TypeFromASTComp: Created new anon composite type: %v %s\n", ty.Name, ty.String())
// }
}
return ty, true // fallthrough is true..
}
// TypeFromASTLit gets type from literals
func (gl *GoLang) TypeFromASTLit(fs *parse.FileState, pkg *syms.Symbol, ty *syms.Type, tyast *parser.AST) (*syms.Type, bool) {
tnm := tyast.Name
var bty *syms.Type
switch tnm {
case "LitStringDbl":
bty = BuiltinTypes["string"]
case "LitStringTicks":
bty = BuiltinTypes["string"]
case "LitRune":
bty = BuiltinTypes["rune"]
case "LitNumInteger":
bty = BuiltinTypes["int"]
case "LitNumFloat":
bty = BuiltinTypes["float64"]
case "LitNumImag":
bty = BuiltinTypes["complex128"]
}
if bty == nil {
return nil, false
}
if ty == nil {
return bty, true
}
ty.Kind = bty.Kind
ty.Els.Add("par", bty.Name) // parent type
return ty, true
}
// StructInheritEls inherits struct fields and meths from given embedded type.
// Ensures that copied values are properly qualified if from another package.
func (gl *GoLang) StructInheritEls(fs *parse.FileState, pkg *syms.Symbol, ty *syms.Type, etynm string) {
ety, _ := gl.FindTypeName(etynm, fs, pkg)
if ety == nil {
if TraceTypes {
fmt.Printf("Embedded struct type not found: %v for type: %v\n", etynm, ty.Name)
}
return
}
if !ety.Initialized {
// if TraceTypes {
// fmt.Printf("Embedded struct type not yet initialized, initializing: %v for type: %v\n", ety.Name, ty.Name)
// }
gl.InitTypeFromAST(fs, pkg, ety)
}
pkgnm := pkg.Name
diffPkg := false
epkg, has := ety.Scopes[token.NamePackage]
if has && epkg != pkgnm {
diffPkg = true
}
if diffPkg {
for i := range ety.Els {
nt := ety.Els[i].Clone()
tnm := nt.Type
_, isb := BuiltinTypes[tnm]
if !isb && !IsQualifiedType(tnm) {
tnm = QualifyType(epkg, tnm)
// fmt.Printf("Fixed type: %v to %v\n", ety.Els[i].Type, tnm)
}
nt.Type = tnm
ty.Els = append(ty.Els, *nt)
}
nmt := len(ety.Meths)
if nmt > 0 {
if ty.Meths == nil { // (adding to those of other embedded types)
ty.Meths = make(syms.TypeMap, nmt)
}
for mn, mt := range ety.Meths {
nmt := mt.Clone()
for i := range nmt.Els {
t := &nmt.Els[i]
tnm := t.Type
_, isb := BuiltinTypes[tnm]
if !isb && !IsQualifiedType(tnm) {
tnm = QualifyType(epkg, tnm)
}
t.Type = tnm
}
ty.Meths[mn] = nmt
}
}
} else {
ty.Els.CopyFrom(ety.Els)
ty.Meths.CopyFrom(ety.Meths, false) // dest is newer
}
ty.Size[0] += len(ety.Els)
// if TraceTypes {
// fmt.Printf("Struct Type: %v inheriting from: %v\n", ty.Name, ety.Name)
// }
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package languages provides the parsers of the languages of the parse
// package, by their known file types.
package languages
import (
"fmt"
"cogentcore.org/core/base/fileinfo"
)
var ParserBytes map[fileinfo.Known][]byte = make(map[fileinfo.Known][]byte)
func OpenParser(sl fileinfo.Known) ([]byte, error) {
parserBytes, ok := ParserBytes[sl]
if !ok {
return nil, fmt.Errorf("langs.OpenParser: no parser bytes for %v", sl)
}
return parserBytes, nil
}
// Copyright (c) 2020, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package markdown
import (
"log"
"strings"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/icons"
"cogentcore.org/core/text/csl"
"cogentcore.org/core/text/parse"
"cogentcore.org/core/text/parse/complete"
"cogentcore.org/core/text/parse/languages/bibtex"
"cogentcore.org/core/text/textpos"
)
// CompleteCite does completion on citation
func (ml *MarkdownLang) CompleteCite(fss *parse.FileStates, origStr, str string, pos textpos.Pos) (md complete.Matches) {
bfile, has := fss.MetaData("bibfile")
if !has {
return
}
if strings.HasSuffix(bfile, ".bib") {
bf, err := ml.Bibs.Open(bfile)
if err != nil {
return
}
md.Seed = str
for _, be := range bf.BibTex.Entries {
if strings.HasPrefix(be.CiteName, str) {
c := complete.Completion{Text: be.CiteName, Label: be.CiteName, Icon: icons.Field}
md.Matches = append(md.Matches, c)
}
}
return md
}
bf, err := ml.CSLs.Open(bfile)
if errors.Log(err) != nil {
return
}
md.Seed = str
for _, it := range bf.Items.Values {
if strings.HasPrefix(it.CitationKey, str) {
c := complete.Completion{Text: it.CitationKey, Label: it.CitationKey, Icon: icons.Field}
md.Matches = append(md.Matches, c)
}
}
return md
}
// LookupCite does lookup on citation.
func (ml *MarkdownLang) LookupCite(fss *parse.FileStates, origStr, str string, pos textpos.Pos) (ld complete.Lookup) {
bfile, has := fss.MetaData("bibfile")
if !has {
return
}
if strings.HasSuffix(bfile, ".bib") {
bf, err := ml.Bibs.Open(bfile)
if err != nil {
return
}
lkbib := bibtex.NewBibTex()
for _, be := range bf.BibTex.Entries {
if strings.HasPrefix(be.CiteName, str) {
lkbib.Entries = append(lkbib.Entries, be)
}
}
if len(lkbib.Entries) > 0 {
ld.SetFile(fss.Filename, 0, 0)
ld.Text = []byte(lkbib.PrettyString())
}
return ld
}
bf, err := ml.CSLs.Open(bfile)
if err != nil {
return
}
var items []csl.Item
for _, be := range bf.Items.Values {
if strings.HasPrefix(be.CitationKey, str) {
items = append(items, *be)
}
}
if len(items) > 0 {
kl := csl.NewKeyList(items)
ld.SetFile(fss.Filename, 0, 0)
ld.Text = []byte(kl.PrettyString())
}
return ld
}
// OpenBibfile attempts to find the bibliography file, and load it.
// Sets meta data "bibfile" to resulting file if found, and deletes it if not.
func (ml *MarkdownLang) OpenBibfile(fss *parse.FileStates, pfs *parse.FileState) error {
bfile := ml.FindBibliography(pfs)
if bfile == "" {
fss.DeleteMetaData("bibfile")
return nil
}
if strings.HasSuffix(bfile, ".bib") {
_, err := ml.Bibs.Open(bfile)
if err != nil {
log.Println(err)
fss.DeleteMetaData("bibfile")
return err
}
fss.SetMetaData("bibfile", bfile)
return nil
}
_, err := ml.CSLs.Open(bfile)
if err != nil {
log.Println(err)
fss.DeleteMetaData("bibfile")
return err
}
fss.SetMetaData("bibfile", bfile)
return nil
}
// FindBibliography looks for yaml metadata at top of markdown file
func (ml *MarkdownLang) FindBibliography(pfs *parse.FileState) string {
nlines := pfs.Src.NLines()
if nlines < 3 {
return ""
}
fln := string(pfs.Src.Lines[0])
if fln != "---" && fln != "+++" {
return ""
}
trg := `bibfile`
trgln := len(trg)
mx := min(nlines, 100)
for i := 1; i < mx; i++ {
sln := pfs.Src.Lines[i]
lstr := string(sln)
if lstr == "---" || lstr == "+++" {
return ""
}
lnln := len(sln)
if lnln <= trgln {
continue
}
if strings.HasPrefix(lstr, trg) {
fnm := lstr[trgln:lnln]
if fnm[0] == ':' { // yaml: bibfile: name
return strings.Trim(strings.TrimSpace(fnm[1:]), `"'`)
}
flds := strings.Fields(fnm)
if len(flds) != 2 || flds[0] != "=" {
continue
}
if flds[1][0] == '"' {
fnm = flds[1][1 : len(flds[1])-1]
return fnm
}
}
}
return ""
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package markdown provides the support for Markdown of the parse package,
// with the completion of citations and links.
package markdown
import (
_ "embed"
"strings"
"unicode"
"unicode/utf8"
"cogentcore.org/core/base/fileinfo"
"cogentcore.org/core/base/indent"
"cogentcore.org/core/text/csl"
"cogentcore.org/core/text/parse"
"cogentcore.org/core/text/parse/complete"
"cogentcore.org/core/text/parse/languages"
"cogentcore.org/core/text/parse/languages/bibtex"
"cogentcore.org/core/text/parse/lexer"
"cogentcore.org/core/text/parse/syms"
"cogentcore.org/core/text/textpos"
"cogentcore.org/core/text/token"
)
//go:embed markdown.parse
var parserBytes []byte
// MarkdownLang implements the Lang interface for the Markdown language
type MarkdownLang struct {
Pr *parse.Parser
// BibBeX bibliography files that have been loaded,
// keyed by file path from bibfile metadata stored in filestate.
Bibs bibtex.Files
// CSL bibliography files that have been loaded,
// keyed by file path from bibfile metadata stored in filestate.
CSLs csl.Files
}
// TheMarkdownLang is the instance variable providing support for the Markdown language
var TheMarkdownLang = MarkdownLang{}
func init() {
parse.StandardLanguageProperties[fileinfo.Markdown].Lang = &TheMarkdownLang
languages.ParserBytes[fileinfo.Markdown] = parserBytes
}
func (ml *MarkdownLang) Parser() *parse.Parser {
if ml.Pr != nil {
return ml.Pr
}
lp, _ := parse.LanguageSupport.Properties(fileinfo.Markdown)
if lp.Parser == nil {
parse.LanguageSupport.OpenLanguage(fileinfo.Markdown)
}
ml.Pr = lp.Parser
if ml.Pr == nil {
return nil
}
return ml.Pr
}
func (ml *MarkdownLang) ParseFile(fss *parse.FileStates, txt []byte) {
pr := ml.Parser()
if pr == nil {
return
}
pfs := fss.StartProc(txt) // current processing one
pr.LexAll(pfs)
ml.OpenBibfile(fss, pfs)
fss.EndProc() // now done
// no parser
}
func (ml *MarkdownLang) LexLine(fs *parse.FileState, line int, txt []rune) lexer.Line {
pr := ml.Parser()
if pr == nil {
return nil
}
return pr.LexLine(fs, line, txt)
}
func (ml *MarkdownLang) ParseLine(fs *parse.FileState, line int) *parse.FileState {
// n/a
return nil
}
func (ml *MarkdownLang) HighlightLine(fss *parse.FileStates, line int, txt []rune) lexer.Line {
fs := fss.Done()
return ml.LexLine(fs, line, txt)
}
// citeKeyStr returns a string with a citation key of the form @[^]Ref
// or empty string if not of this form.
func citeKeyStr(str string) string {
if len(str) < 2 {
return ""
}
if str[0] != '@' {
return ""
}
str = str[1:]
if str[0] == '^' { // narrative cite
str = str[1:]
}
return str
}
func (ml *MarkdownLang) CompleteLine(fss *parse.FileStates, str string, pos textpos.Pos) (md complete.Matches) {
origStr := str
lfld := lexer.LastField(str)
str = citeKeyStr(lexer.InnerBracketScope(lfld, "[", "]"))
if str != "" {
return ml.CompleteCite(fss, origStr, str, pos)
}
// n/a
return md
}
// Lookup is the main api called by completion code in giv/complete.go to lookup item
func (ml *MarkdownLang) Lookup(fss *parse.FileStates, str string, pos textpos.Pos) (ld complete.Lookup) {
origStr := str
lfld := lexer.LastField(str)
str = citeKeyStr(lexer.InnerBracketScope(lfld, "[", "]"))
if str != "" {
return ml.LookupCite(fss, origStr, str, pos)
}
return
}
func (ml *MarkdownLang) CompleteEdit(fs *parse.FileStates, text string, cp int, comp complete.Completion, seed string) (ed complete.Edit) {
// if the original is ChildByName() and the cursor is between d and B and the comp is Children,
// then delete the portion after "Child" and return the new comp and the number or runes past
// the cursor to delete
rn := []rune(text)
s2 := string(rn[min(cp, len(rn)):]) // cp is a rune position
// gotParen := false
if r, _ := utf8.DecodeRuneInString(s2); len(s2) > 0 && lexer.IsLetterOrDigit(r) {
for i, c := range s2 {
if c == '{' {
// gotParen = true
s2 = s2[:i]
break
}
isalnum := c == '_' || unicode.IsLetter(c) || unicode.IsDigit(c)
if !isalnum {
s2 = s2[:i]
break
}
}
} else {
s2 = ""
}
var nw = comp.Text
// if gotParen && strings.HasSuffix(nw, "()") {
// nw = nw[:len(nw)-2]
// }
// fmt.Printf("text: %v|%v comp: %v s2: %v\n", text[:cp], text[cp:], nw, s2)
ed.NewText = nw
ed.ForwardDelete = utf8.RuneCountInString(s2)
return ed
}
func (ml *MarkdownLang) ParseDir(fs *parse.FileState, path string, opts parse.LanguageDirOptions) *syms.Symbol {
// n/a
return nil
}
// ListKeys are the list keywords (for indent).
var ListKeys = map[string]struct{}{"*": {}, "+": {}, "-": {}}
// IndentLine returns the indentation level for given line based on
// previous line's indentation level, and any delta change based on
// e.g., brackets starting or ending the previous or current line, or
// other language-specific keywords. See lexer.BracketIndentLine for example.
// Indent level is in increments of tabSz for spaces, and tabs for tabs.
// Operates on rune source with markup lex tags per line.
func (ml *MarkdownLang) IndentLine(fs *parse.FileStates, src [][]rune, tags []lexer.Line, ln int, tabSz int) (pInd, delInd, pLn int, ichr indent.Character) {
if ln == 0 { // the first line has no previous line to indent from
return
}
pInd, pLn, ichr = lexer.PrevLineIndent(src, tags, ln, tabSz)
delInd = 0
ptg := tags[pLn]
ctg := tags[ln]
if len(ptg) == 0 || len(ctg) == 0 {
return
}
fpt := ptg[0]
fct := ctg[0]
if fpt.Token.Token != token.Keyword || fct.Token.Token != token.Keyword {
return
}
pk := strings.TrimSpace(string(fpt.Src(src[pLn])))
ck := strings.TrimSpace(string(fct.Src(src[ln])))
// fmt.Printf("pk: %v ck: %v\n", string(pk), string(ck))
if len(pk) >= 1 && len(ck) >= 1 {
_, pky := ListKeys[pk]
_, cky := ListKeys[ck]
if unicode.IsDigit(rune(pk[0])) {
pk = "1"
pky = true
}
if unicode.IsDigit(rune(ck[0])) {
ck = "1"
cky = true
}
if pky && cky {
if pk != ck {
delInd = 1
return
}
return
}
}
return
}
// AutoBracket returns what to do when a user types a starting bracket character
// (bracket, brace, paren) while typing.
// pos = position where bra will be inserted, and curLn is the current line
// match = insert the matching ket, and newLine = insert a new line.
func (ml *MarkdownLang) AutoBracket(fs *parse.FileStates, bra rune, pos textpos.Pos, curLn []rune) (match, newLine bool) {
lnLen := len(curLn)
match = pos.Char == lnLen || unicode.IsSpace(curLn[pos.Char]) // at end or if space after
newLine = false
return
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tex
import (
"log"
"strings"
"cogentcore.org/core/icons"
"cogentcore.org/core/text/parse"
"cogentcore.org/core/text/parse/complete"
"cogentcore.org/core/text/parse/languages/bibtex"
"cogentcore.org/core/text/textpos"
)
// CompleteCite does completion on citation
func (tl *TexLang) CompleteCite(fss *parse.FileStates, origStr, str string, pos textpos.Pos) (md complete.Matches) {
bfile, has := fss.MetaData("bibfile")
if !has {
return
}
bf, err := tl.Bibs.Open(bfile)
if err != nil {
return
}
md.Seed = str
for _, be := range bf.BibTex.Entries {
if strings.HasPrefix(be.CiteName, str) {
c := complete.Completion{Text: be.CiteName, Label: be.CiteName, Icon: icons.Field}
md.Matches = append(md.Matches, c)
}
}
return md
}
// LookupCite does lookup on citation
func (tl *TexLang) LookupCite(fss *parse.FileStates, origStr, str string, pos textpos.Pos) (ld complete.Lookup) {
bfile, has := fss.MetaData("bibfile")
if !has {
return
}
bf, err := tl.Bibs.Open(bfile)
if err != nil {
return
}
lkbib := bibtex.NewBibTex()
for _, be := range bf.BibTex.Entries {
if strings.HasPrefix(be.CiteName, str) {
lkbib.Entries = append(lkbib.Entries, be)
}
}
if len(lkbib.Entries) > 0 {
ld.SetFile(fss.Filename, 0, 0)
ld.Text = []byte(lkbib.PrettyString())
}
return ld
}
// OpenBibfile attempts to open the /bibliography file.
// Sets meta data "bibfile" to resulting file if found, and deletes it if not.
func (tl *TexLang) OpenBibfile(fss *parse.FileStates, pfs *parse.FileState) error {
bfile := tl.FindBibliography(pfs)
if bfile == "" {
fss.DeleteMetaData("bibfile")
return nil
}
_, err := tl.Bibs.Open(bfile)
if err != nil {
log.Println(err)
fss.DeleteMetaData("bibfile")
return err
}
fss.SetMetaData("bibfile", bfile)
return nil
}
func (tl *TexLang) FindBibliography(pfs *parse.FileState) string {
nlines := pfs.Src.NLines()
trg := `\bibliography{`
trgln := len(trg)
for i := nlines - 1; i >= 0; i-- {
sln := pfs.Src.Lines[i]
lnln := len(sln)
if lnln == 0 {
continue
}
if sln[0] != '\\' {
continue
}
if lnln > 100 {
continue
}
lstr := string(sln)
if strings.HasPrefix(lstr, trg) {
return lstr[trgln:len(sln)-1] + ".bib"
}
}
return ""
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tex
import (
"strings"
"unicode"
"unicode/utf8"
"cogentcore.org/core/icons"
"cogentcore.org/core/text/parse"
"cogentcore.org/core/text/parse/complete"
"cogentcore.org/core/text/parse/lexer"
"cogentcore.org/core/text/textpos"
)
func (tl *TexLang) CompleteLine(fss *parse.FileStates, str string, pos textpos.Pos) (md complete.Matches) {
origStr := str
lfld := lexer.LastField(str)
str = lexer.LastScopedString(str)
if len(lfld) < 2 {
return md
}
if lfld[0] == '\\' && lfld[1:] == str { // use the /
str = lfld
}
if HasCite(lfld) {
return tl.CompleteCite(fss, origStr, str, pos)
}
md.Seed = str
if len(LaTeXCommandsAll) == 0 {
LaTeXCommandsAll = append(LaTeXCommands, CiteCommands...)
}
for _, ls := range LaTeXCommandsAll {
if strings.HasPrefix(ls, str) {
c := complete.Completion{Text: ls, Label: ls, Icon: icons.Function}
md.Matches = append(md.Matches, c)
}
}
return md
}
// Lookup is the main api called by completion code in giv/complete.go to lookup item
func (tl *TexLang) Lookup(fss *parse.FileStates, str string, pos textpos.Pos) (ld complete.Lookup) {
origStr := str
lfld := lexer.LastField(str)
str = lexer.LastScopedString(str)
if HasCite(lfld) {
return tl.LookupCite(fss, origStr, str, pos)
}
return
}
func (tl *TexLang) CompleteEdit(fss *parse.FileStates, text string, cp int, comp complete.Completion, seed string) (ed complete.Edit) {
// if the original is ChildByName() and the cursor is between d and B and the comp is Children,
// then delete the portion after "Child" and return the new comp and the number or runes past
// the cursor to delete
rn := []rune(text)
s2 := string(rn[min(cp, len(rn)):]) // cp is a rune position
// gotParen := false
if r, _ := utf8.DecodeRuneInString(s2); len(s2) > 0 && lexer.IsLetterOrDigit(r) {
for i, c := range s2 {
if c == '{' {
// gotParen = true
s2 = s2[:i]
break
}
isalnum := c == '_' || unicode.IsLetter(c) || unicode.IsDigit(c)
if !isalnum {
s2 = s2[:i]
break
}
}
} else {
s2 = ""
}
var nw = comp.Text
// if gotParen && strings.HasSuffix(nw, "()") {
// nw = nw[:len(nw)-2]
// }
// fmt.Printf("text: %v|%v comp: %v s2: %v\n", text[:cp], text[cp:], nw, s2)
ed.NewText = nw
ed.ForwardDelete = utf8.RuneCountInString(s2)
return ed
}
// CiteCommands is a list of latex citation commands (APA style requires many variations).
// We include all the variations so they show up in completion.
var CiteCommands = []string{`\cite`, `\citep`, `\citet`, `\citeNP`, `\citeyearpar`, `\citeyear`, `\citeauthor`, `\citeA`, `\citealp`, `\citeyearNP`, `\parencite`, `\textcite`, `\nptextcite`, `\incite`, `\nopcite`, `\yrcite`, `\yrnopcite`, `\abbrevcite`, `\abbrevincite`}
// HasCite returns true if string has Prefix in CiteCmds
func HasCite(str string) bool {
for _, cc := range CiteCommands {
if strings.HasPrefix(str, cc) {
return true
}
}
return false
}
// LaTeXCommandsAll concatenates LaTeXCmds and CiteCmds
var LaTeXCommandsAll []string
// LaTeXCommands is a big list of standard commands
var LaTeXCommands = []string{
`\em`,
`\emph`,
`\textbf`,
`\textit`,
`\texttt`,
`\textsf`,
`\textrm`,
`\tiny`,
`\scriptsize`,
`\footnotesize`,
`\small`,
`\normalsize`,
`\large`,
`\Large`,
`\LARGE`,
`\huge`,
`\Huge`,
`\begin`,
`\end`,
`enumerate`,
`itemize`,
`description`,
`\item`,
`figure`,
`table`,
`tabular`,
`array`,
`\hline`,
`\cline`,
`\multicolumn`,
`equation`,
`center`,
`\centering`,
`\verb`,
`verbatim`,
`quote`,
`\section`,
`\subsection`,
`\subsubsection`,
`\paragraph`,
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package tex provides the support for TeX and LaTeX of the parse package,
// with the completion of commands and citations.
package tex
import (
_ "embed"
"strings"
"unicode"
"cogentcore.org/core/base/fileinfo"
"cogentcore.org/core/base/indent"
"cogentcore.org/core/text/parse"
"cogentcore.org/core/text/parse/languages"
"cogentcore.org/core/text/parse/languages/bibtex"
"cogentcore.org/core/text/parse/lexer"
"cogentcore.org/core/text/parse/syms"
"cogentcore.org/core/text/textpos"
)
//go:embed tex.parse
var parserBytes []byte
// TexLang implements the Lang interface for the Tex / LaTeX language
type TexLang struct {
Pr *parse.Parser
// bibliography files that have been loaded, keyed by file path from bibfile metadata stored in filestate
Bibs bibtex.Files
}
// TheTexLang is the instance variable providing support for the Go language
var TheTexLang = TexLang{}
func init() {
parse.StandardLanguageProperties[fileinfo.TeX].Lang = &TheTexLang
languages.ParserBytes[fileinfo.TeX] = parserBytes
}
func (tl *TexLang) Parser() *parse.Parser {
if tl.Pr != nil {
return tl.Pr
}
lp, _ := parse.LanguageSupport.Properties(fileinfo.TeX)
if lp.Parser == nil {
parse.LanguageSupport.OpenLanguage(fileinfo.TeX)
}
tl.Pr = lp.Parser
if tl.Pr == nil {
return nil
}
return tl.Pr
}
func (tl *TexLang) ParseFile(fss *parse.FileStates, txt []byte) {
pr := tl.Parser()
if pr == nil {
return
}
pfs := fss.StartProc(txt) // current processing one
pr.LexAll(pfs)
tl.OpenBibfile(fss, pfs)
fss.EndProc() // now done
// no parser
}
func (tl *TexLang) LexLine(fs *parse.FileState, line int, txt []rune) lexer.Line {
pr := tl.Parser()
if pr == nil {
return nil
}
return pr.LexLine(fs, line, txt)
}
func (tl *TexLang) ParseLine(fs *parse.FileState, line int) *parse.FileState {
// n/a
return nil
}
func (tl *TexLang) HighlightLine(fss *parse.FileStates, line int, txt []rune) lexer.Line {
fs := fss.Done()
return tl.LexLine(fs, line, txt)
}
func (tl *TexLang) ParseDir(fs *parse.FileState, path string, opts parse.LanguageDirOptions) *syms.Symbol {
// n/a
return nil
}
// IndentLine returns the indentation level for given line based on
// previous line's indentation level, and any delta change based on
// e.g., brackets starting or ending the previous or current line, or
// other language-specific keywords. See lexer.BracketIndentLine for example.
// Indent level is in increments of tabSz for spaces, and tabs for tabs.
// Operates on rune source with markup lex tags per line.
func (tl *TexLang) IndentLine(fs *parse.FileStates, src [][]rune, tags []lexer.Line, ln int, tabSz int) (pInd, delInd, pLn int, ichr indent.Character) {
if ln == 0 { // the first line has no previous line to indent from
return
}
pInd, pLn, ichr = lexer.PrevLineIndent(src, tags, ln, tabSz)
curUnd, _ := lexer.LineStartEndBracket(src[ln], tags[ln])
_, prvInd := lexer.LineStartEndBracket(src[pLn], tags[pLn])
delInd = 0
switch {
case prvInd && curUnd:
delInd = 0 // offset
case prvInd:
delInd = 1 // indent
case curUnd:
delInd = -1 // undent
}
pst := lexer.FirstNonSpaceRune(src[pLn])
cst := lexer.FirstNonSpaceRune(src[ln])
pbeg := false
if pst >= 0 {
sts := string(src[pLn][pst:])
if strings.HasPrefix(sts, "\\begin{") {
pbeg = true
}
}
cend := false
if cst >= 0 {
sts := string(src[ln][cst:])
if strings.HasPrefix(sts, "\\end{") {
cend = true
}
}
switch {
case pbeg && cend:
delInd = 0
case pbeg:
delInd = 1
case cend:
delInd = -1
}
if pInd == 0 && delInd < 0 { // error..
delInd = 0
}
return
}
// AutoBracket returns what to do when a user types a starting bracket character
// (bracket, brace, paren) while typing.
// pos = position where bra will be inserted, and curLn is the current line
// match = insert the matching ket, and newLine = insert a new line.
func (tl *TexLang) AutoBracket(fs *parse.FileStates, bra rune, pos textpos.Pos, curLn []rune) (match, newLine bool) {
lnLen := len(curLn)
match = pos.Char == lnLen || unicode.IsSpace(curLn[pos.Char]) // at end or if space after
newLine = false
return
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package parse
import (
"fmt"
"slices"
"time"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/fileinfo"
"cogentcore.org/core/text/parse/languages"
"cogentcore.org/core/text/parse/lexer"
)
// LanguageFlags are special properties of a given language
type LanguageFlags int32 //enums:enum
// LangFlags
const (
// NoFlags = nothing special
NoFlags LanguageFlags = iota
// IndentSpace means that spaces must be used for this language
IndentSpace
// IndentTab means that tabs must be used for this language
IndentTab
// ReAutoIndent causes current line to be re-indented during AutoIndent for Enter
// (newline) -- this should only be set for strongly indented languages where
// the previous + current line can tell you exactly what indent the current line
// should be at.
ReAutoIndent
)
// LanguageProperties contains properties of languages supported by the parser
// framework
type LanguageProperties struct {
// known language -- must be a supported one from Known list
Known fileinfo.Known
// character(s) that start a single-line comment -- if empty then multi-line comment syntax will be used
CommentLn string
// character(s) that start a multi-line comment or one that requires both start and end
CommentSt string
// character(s) that end a multi-line comment or one that requires both start and end
CommentEd string
// special properties for this language -- as an explicit list of options to make them easier to see and set in defaults
Flags []LanguageFlags
// Lang interface for this language
Lang Language `json:"-" xml:"-"`
// parser for this language -- initialized in OpenStandard
Parser *Parser `json:"-" xml:"-"`
}
// HasFlag returns true if given flag is set in Flags
func (lp *LanguageProperties) HasFlag(flg LanguageFlags) bool {
return slices.Contains(lp.Flags, flg)
}
// StandardLanguageProperties is the standard compiled-in set of language properties
var StandardLanguageProperties = map[fileinfo.Known]*LanguageProperties{
fileinfo.Ada: {fileinfo.Ada, "--", "", "", nil, nil, nil},
fileinfo.Bash: {fileinfo.Bash, "# ", "", "", nil, nil, nil},
fileinfo.Csh: {fileinfo.Csh, "# ", "", "", nil, nil, nil},
fileinfo.C: {fileinfo.C, "// ", "/* ", " */", nil, nil, nil},
fileinfo.CSharp: {fileinfo.CSharp, "// ", "/* ", " */", nil, nil, nil},
fileinfo.D: {fileinfo.D, "// ", "/* ", " */", nil, nil, nil},
fileinfo.ObjC: {fileinfo.ObjC, "// ", "/* ", " */", nil, nil, nil},
fileinfo.Go: {fileinfo.Go, "// ", "/* ", " */", []LanguageFlags{IndentTab}, nil, nil},
fileinfo.Java: {fileinfo.Java, "// ", "/* ", " */", nil, nil, nil},
fileinfo.JavaScript: {fileinfo.JavaScript, "// ", "/* ", " */", nil, nil, nil},
fileinfo.Eiffel: {fileinfo.Eiffel, "--", "", "", nil, nil, nil},
fileinfo.Haskell: {fileinfo.Haskell, "--", "{- ", "-}", nil, nil, nil},
fileinfo.Lisp: {fileinfo.Lisp, "; ", "", "", nil, nil, nil},
fileinfo.Lua: {fileinfo.Lua, "--", "---[[ ", "--]]", nil, nil, nil},
fileinfo.Makefile: {fileinfo.Makefile, "# ", "", "", []LanguageFlags{IndentTab}, nil, nil},
fileinfo.Matlab: {fileinfo.Matlab, "% ", "%{ ", " %}", nil, nil, nil},
fileinfo.OCaml: {fileinfo.OCaml, "", "(* ", " *)", nil, nil, nil},
fileinfo.Pascal: {fileinfo.Pascal, "// ", " ", " }", nil, nil, nil},
fileinfo.Perl: {fileinfo.Perl, "# ", "", "", nil, nil, nil},
fileinfo.Python: {fileinfo.Python, "# ", "", "", []LanguageFlags{IndentSpace}, nil, nil},
fileinfo.PHP: {fileinfo.PHP, "// ", "/* ", " */", nil, nil, nil},
fileinfo.R: {fileinfo.R, "# ", "", "", nil, nil, nil},
fileinfo.Ruby: {fileinfo.Ruby, "# ", "", "", nil, nil, nil},
fileinfo.Rust: {fileinfo.Rust, "// ", "/* ", " */", nil, nil, nil},
fileinfo.Scala: {fileinfo.Scala, "// ", "/* ", " */", nil, nil, nil},
fileinfo.HTML: {fileinfo.HTML, "", "<!-- ", " -->", nil, nil, nil},
fileinfo.TeX: {fileinfo.TeX, "% ", "", "", nil, nil, nil},
fileinfo.Markdown: {fileinfo.Markdown, "", "<!--- ", " -->", []LanguageFlags{IndentSpace}, nil, nil},
fileinfo.YAML: {fileinfo.YAML, "#", "", "", []LanguageFlags{IndentSpace}, nil, nil},
}
// LanguageSupporter provides general support for supported languages.
// e.g., looking up lexers and parsers by name.
// Also implements the lexer.LangLexer interface to provide access to other
// Guest Lexers
type LanguageSupporter struct{}
// LanguageSupport is the main language support hub for accessing parse
// support interfaces for each supported language
var LanguageSupport = LanguageSupporter{}
// OpenStandard opens all the standard parsers for languages, from the langs/ directory
func (ll *LanguageSupporter) OpenStandard() error {
for sl, lp := range StandardLanguageProperties {
if err := ll.open(sl, lp); err != nil {
return err
}
}
return nil
}
// OpenLanguage opens the standard parser for the given language, from the
// langs/ directory, unless it is already open. It does nothing for a
// language without a standard parser. The parsers are opened as needed,
// as reading them takes time.
func (ll *LanguageSupporter) OpenLanguage(sl fileinfo.Known) error {
lp, has := StandardLanguageProperties[sl]
if !has || lp.Parser != nil {
return nil
}
return ll.open(sl, lp)
}
// open opens the standard parser for the given language into lp, if it has one.
func (ll *LanguageSupporter) open(sl fileinfo.Known, lp *LanguageProperties) error {
lexer.TheLanguageLexer = &LanguageSupport
pib, err := languages.OpenParser(sl)
if err != nil {
return nil
}
pr := NewParser()
err = pr.ReadJSON(pib)
if err != nil {
return errors.Log(err)
}
pr.ModTime = time.Date(2023, 02, 10, 00, 00, 00, 0, time.UTC)
pr.InitAll()
lp.Parser = pr
return nil
}
// Properties looks up language properties by fileinfo.Known const int type
func (ll *LanguageSupporter) Properties(sup fileinfo.Known) (*LanguageProperties, error) {
lp, has := StandardLanguageProperties[sup]
if !has {
err := fmt.Errorf("parse.LangSupport.Properties: no specific support for language: %v", sup)
return nil, err
}
return lp, nil
}
// PropertiesByName looks up language properties by string name of language
// (with case-insensitive fallback). Returns error if not supported.
func (ll *LanguageSupporter) PropertiesByName(lang string) (*LanguageProperties, error) {
sup, err := fileinfo.KnownByName(lang)
if err != nil {
// log.Println(err.Error()) // don't want output during lexing..
return nil, err
}
return ll.Properties(sup)
}
// LexerByName looks up Lexer for given language by name
// (with case-insensitive fallback). Returns nil if not supported.
func (ll *LanguageSupporter) LexerByName(lang string) *lexer.Rule {
lp, err := ll.PropertiesByName(lang)
if err != nil {
return nil
}
if lp.Parser == nil {
ll.OpenLanguage(lp.Known)
}
if lp.Parser == nil {
// log.Printf("core.LangSupport: no lexer / parser support for language: %v\n", lang)
return nil
}
return lp.Parser.Lexer
}
// Copyright (c) 2020, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lexer
import (
"cogentcore.org/core/text/textpos"
"cogentcore.org/core/text/token"
)
// BracePair returns the matching brace-like punctuation for given rune,
// which must be a left or right brace {}, bracket [] or paren ().
// Also returns true if it is *right*
func BracePair(r rune) (match rune, right bool) {
right = false
switch r {
case '{':
match = '}'
case '}':
right = true
match = '{'
case '(':
match = ')'
case ')':
right = true
match = '('
case '[':
match = ']'
case ']':
right = true
match = '['
}
return
}
// BraceMatch finds the brace, bracket, or paren that is the partner
// of the one passed to function, within maxLns lines of start.
// Operates on rune source with markup lex tags per line (tags exclude comments).
func BraceMatch(src [][]rune, tags []Line, r rune, st textpos.Pos, maxLns int) (en textpos.Pos, found bool) {
en.Line = -1
found = false
match, rt := BracePair(r)
var left int
var right int
if rt {
right++
} else {
left++
}
ch := st.Char
ln := st.Line
nln := len(src)
mx := min(nln-ln, maxLns)
mn := min(ln, maxLns)
// isCode returns whether the rune at i in line l is not in a comment.
isCode := func(l, i int) bool {
lx, _ := tags[l].AtPos(i)
return lx == nil || lx.Token.Token.Cat() != token.Comment
}
if left > right {
// lines ln to ln+mx-1, after the brace on its line
for l := ln; l < ln+mx && !found; l++ {
txt := src[l]
from := 0
if l == ln {
from = ch + 1
}
for i := from; i < len(txt); i++ {
switch txt[i] {
case r:
if isCode(l, i) {
left++
}
case match:
if isCode(l, i) {
right++
if left == right {
en = textpos.Pos{Line: l, Char: i}
found = true
}
}
}
if found {
break
}
}
}
} else {
// lines ln down to ln-mn, before the brace on its line
for l := ln; l >= ln-mn && !found; l-- {
txt := src[l]
from := len(txt) - 1
if l == ln {
from = min(ch, len(txt)) - 1
}
for i := from; i >= 0; i-- {
switch txt[i] {
case r:
if isCode(l, i) {
right++
}
case match:
if isCode(l, i) {
left++
if left == right {
en = textpos.Pos{Line: l, Char: i}
found = true
}
}
}
if found {
break
}
}
}
}
return en, found
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Much of this is directly copied from Go's go/scanner package:
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lexer
import (
"fmt"
"io"
"path/filepath"
"reflect"
"sort"
"strings"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/text/textpos"
"cogentcore.org/core/tree"
)
// Error is an error of an ErrorList, in which it is a *Error.
// The position Pos, if valid, points to the beginning of
// the offending token, and the error condition is described
// by Msg.
type Error struct {
// position where the error occurred in the source
Pos textpos.Pos
// full filename with path
Filename string
// brief error message
Msg string
// line of source where error was
Src string
// lexer or parser rule that emitted the error
Rule tree.Node
}
// Error implements the error interface -- gives the minimal version of error string
func (e *Error) Error() string {
if e.Filename != "" {
_, fn := filepath.Split(e.Filename)
return fn + ":" + e.Pos.String() + ": " + e.Msg
}
return e.Pos.String() + ": " + e.Msg
}
// Report provides customizable output options for viewing errors:
// - basepath if non-empty shows filename relative to that path.
// - showSrc shows the source line on a second line -- truncated to 30 chars around err
// - showRule prints the rule name
func (e Error) Report(basepath string, showSrc ReportSource, showRule ReportRule) string {
var err error
fnm := ""
if e.Filename != "" {
if basepath != "" {
fnm, err = filepath.Rel(basepath, e.Filename)
}
if basepath == "" || err != nil {
_, fnm = filepath.Split(e.Filename)
}
}
str := fnm + ":" + e.Pos.String() + ": " + e.Msg
if showRule == ShowRule && !reflectx.IsNil(reflect.ValueOf(e.Rule)) {
str += fmt.Sprintf(" (rule: %v)", e.Rule.AsTree().Name)
}
ssz := len(e.Src)
if showSrc && ssz > 0 && ssz >= e.Pos.Char {
str += "<br>\n\t> "
if ssz > e.Pos.Char+30 {
str += e.Src[e.Pos.Char : e.Pos.Char+30]
} else if ssz > e.Pos.Char {
str += e.Src[e.Pos.Char:]
}
}
return str
}
// ErrorList is a list of *Errors.
// The zero value for an ErrorList is an empty ErrorList ready to use.
type ErrorList []*Error
// Add adds an Error with given position and error message to an ErrorList.
func (p *ErrorList) Add(pos textpos.Pos, fname, msg string, srcln string, rule tree.Node) *Error {
e := &Error{pos, fname, msg, srcln, rule}
*p = append(*p, e)
return e
}
// Reset resets an ErrorList to no errors.
func (p *ErrorList) Reset() { *p = (*p)[0:0] }
// Len implements the sort Interface.
func (p ErrorList) Len() int { return len(p) }
func (p ErrorList) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p ErrorList) Less(i, j int) bool {
e := p[i]
f := p[j]
if e.Filename != f.Filename {
return e.Filename < f.Filename
}
if e.Pos.Line != f.Pos.Line {
return e.Pos.Line < f.Pos.Line
}
if e.Pos.Char != f.Pos.Char {
return e.Pos.Char < f.Pos.Char
}
return e.Msg < f.Msg
}
// Sort sorts an ErrorList. *Error entries are sorted by position,
// other errors are sorted by error message, and before any *Error
// entry.
func (p ErrorList) Sort() {
sort.Sort(p)
}
// RemoveMultiples sorts an ErrorList and removes all but the first error per line.
func (p *ErrorList) RemoveMultiples() {
sort.Sort(p)
var last textpos.Pos // initial last.Line is != any legal error line
var lastfn string
i := 0
for _, e := range *p {
if e.Filename != lastfn || e.Pos.Line != last.Line {
last = e.Pos
lastfn = e.Filename
(*p)[i] = e
i++
}
}
(*p) = (*p)[0:i]
}
// Error implements the error interface.
func (p ErrorList) Error() string {
switch len(p) {
case 0:
return "no errors"
case 1:
return p[0].Error()
}
return fmt.Sprintf("%s (and %d more errors)", p[0], len(p)-1)
}
// Err returns an error equivalent to this error list.
// If the list is empty, Err returns nil.
func (p ErrorList) Err() error {
if len(p) == 0 {
return nil
}
return p
}
// Report returns all (or up to maxN if > 0) errors in the list in one string
// with customizable output options for viewing errors:
// - basepath if non-empty shows filename relative to that path.
// - showSrc shows the source line on a second line -- truncated to 30 chars around err
// - showRule prints the rule name
func (p ErrorList) Report(maxN int, basepath string, showSrc ReportSource, showRule ReportRule) string {
ne := len(p)
if ne == 0 {
return ""
}
var str strings.Builder
if maxN == 0 {
maxN = ne
} else {
maxN = min(ne, maxN)
}
cnt := 0
lstln := -1
lstfn := ""
rest := 0 // the number of errors after the last one reported
for ei := range ne {
er := p[ei]
// only one error is reported per line of a file
if er.Pos.Line == lstln && er.Filename == lstfn {
continue
}
str.WriteString(p[ei].Report(basepath, showSrc, showRule))
str.WriteString("<br>\n")
lstln = er.Pos.Line
lstfn = er.Filename
cnt++
if cnt == maxN {
rest = ne - ei - 1
break
}
}
if rest > 0 {
fmt.Fprintf(&str, "... and %v more errors<br>\n", rest)
}
return str.String()
}
// PrintError is a utility function that prints a list of errors to w,
// one error per line, if the err parameter is an ErrorList. Otherwise
// it prints the err string.
func PrintError(w io.Writer, err error) {
if list, ok := err.(ErrorList); ok {
for _, e := range list {
fmt.Fprintf(w, "%s\n", e)
}
} else if err != nil {
fmt.Fprintf(w, "%s\n", err)
}
}
// ReportSource specifies whether an error report includes the source line:
// [ShowSrc] or [NoSrc].
type ReportSource bool
const (
// ShowSrc includes the source line.
ShowSrc ReportSource = true
// NoSrc does not include the source line.
NoSrc ReportSource = false
)
// ReportRule specifies whether an error report includes the parsing rule:
// [ShowRule] or [NoRule].
type ReportRule bool
const (
// ShowRule includes the rule.
ShowRule ReportRule = true
// NoRule does not include the rule.
NoRule ReportRule = false
)
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lexer
import (
"bytes"
"io"
"log"
"os"
"slices"
"strings"
"cogentcore.org/core/base/fileinfo"
"cogentcore.org/core/text/textpos"
"cogentcore.org/core/text/token"
)
// File contains the contents of the file being parsed -- all kept in
// memory, and represented by Line as runes, so that positions in
// the file are directly convertible to indexes in Lines structure
type File struct {
// the current file being lex'd
Filename string
// the known file type, if known (typically only known files are processed)
Known fileinfo.Known
// base path for reporting file names -- this must be set externally e.g., by gide for the project root path
BasePath string
// lex'd version of the lines -- allocated to size of Lines
Lexs []Line
// comment tokens are stored separately here, so parser doesn't need to worry about them, but they are available for highlighting and other uses
Comments []Line
// stack present at the end of each line -- needed for contextualizing line-at-time lexing while editing
LastStacks []Stack
// token positions per line for the EOS (end of statement) tokens -- very important for scoping top-down parsing
EosPos []EosPos
// contents of the file as lines of runes
Lines [][]rune
}
// SetSrc sets the source to given content, and alloc Lexs -- if basepath is empty
// then it is set to the path for the filename
func (fl *File) SetSrc(src [][]rune, fname, basepath string, known fileinfo.Known) {
fl.Filename = fname
if basepath != "" {
fl.BasePath = basepath
}
fl.Known = known
fl.Lines = src
fl.AllocLines()
}
// AllocLines allocates the data per line: lex outputs and stack.
// We reset state so stale state is not hanging around.
func (fl *File) AllocLines() {
if fl.Lines == nil {
return
}
nlines := fl.NLines()
fl.Lexs = make([]Line, nlines)
fl.Comments = make([]Line, nlines)
fl.LastStacks = make([]Stack, nlines)
fl.EosPos = make([]EosPos, nlines)
}
// LinesInserted inserts new lines -- called e.g., by core.TextBuf to sync
// the markup with ongoing edits. The lines can extend beyond the lines
// of this file, which can be a partial or stale state that is updated
// by the next parse, so they are clipped to it.
func (fl *File) LinesInserted(stln, nlns int) {
fl.Lexs = insertLines(fl.Lexs, stln, nlns)
fl.Comments = insertLines(fl.Comments, stln, nlns)
fl.LastStacks = insertLines(fl.LastStacks, stln, nlns)
fl.EosPos = insertLines(fl.EosPos, stln, nlns)
}
// LinesDeleted deletes lines -- called e.g., by core.TextBuf to sync
// the markup with ongoing edits. The lines can extend beyond the lines
// of this file, which can be a partial or stale state that is updated
// by the next parse, e.g., only the first lines are parsed for the
// initial markup, so they are clipped to it.
func (fl *File) LinesDeleted(stln, edln int) {
fl.Lexs = deleteLines(fl.Lexs, stln, edln)
fl.Comments = deleteLines(fl.Comments, stln, edln)
fl.LastStacks = deleteLines(fl.LastStacks, stln, edln)
fl.EosPos = deleteLines(fl.EosPos, stln, edln)
}
// insertLines inserts n zero lines at st in s, clipped to its length.
func insertLines[T any](s []T, st, n int) []T {
return slices.Insert(s, min(max(st, 0), len(s)), make([]T, n)...)
}
// deleteLines deletes lines st to ed (exclusive) from s, clipped to its length.
func deleteLines[T any](s []T, st, ed int) []T {
st, ed = max(st, 0), min(ed, len(s))
if st >= ed {
return s
}
return slices.Delete(s, st, ed)
}
// RunesFromBytes returns the lines of runes from a basic byte array
func RunesFromBytes(b []byte) [][]rune {
lns := bytes.Split(b, []byte("\n"))
nlines := len(lns)
rns := make([][]rune, nlines)
for ln, txt := range lns {
rns[ln] = bytes.Runes(txt)
}
return rns
}
// RunesFromString returns the lines of runes from a string (more efficient
// than converting to bytes)
func RunesFromString(str string) [][]rune {
lns := strings.Split(str, "\n")
nlines := len(lns)
rns := make([][]rune, nlines)
for ln, txt := range lns {
rns[ln] = []rune(txt)
}
return rns
}
// OpenFileBytes returns bytes in given file, and logs any errors as well
func OpenFileBytes(fname string) ([]byte, error) {
fp, err := os.Open(fname)
if err != nil {
log.Println(err.Error())
return nil, err
}
alltxt, err := io.ReadAll(fp)
fp.Close()
if err != nil {
log.Println(err.Error())
return nil, err
}
return alltxt, nil
}
// OpenFile sets source to be parsed from given filename
func (fl *File) OpenFile(fname string) error {
alltxt, err := OpenFileBytes(fname)
if err != nil {
return err
}
rns := RunesFromBytes(alltxt)
known := fileinfo.KnownFromFile(fname)
fl.SetSrc(rns, fname, "", known)
return nil
}
// SetBytes sets source to be parsed from given bytes
func (fl *File) SetBytes(txt []byte) {
if txt == nil {
return
}
fl.Lines = RunesFromBytes(txt)
fl.AllocLines()
}
// SetLineSrc sets source runes from given line of runes.
// Returns false if out of range.
func (fl *File) SetLineSrc(ln int, txt []rune) bool {
nlines := fl.NLines()
if ln >= nlines || ln < 0 || txt == nil {
return false
}
fl.Lines[ln] = slices.Clone(txt)
return true
}
// InitFromLine initializes from one line of source file
func (fl *File) InitFromLine(sfl *File, ln int) bool {
nlines := sfl.NLines()
if ln >= nlines || ln < 0 {
return false
}
src := [][]rune{sfl.Lines[ln], {}} // need extra blank
fl.SetSrc(src, sfl.Filename, sfl.BasePath, sfl.Known)
fl.Lexs = []Line{sfl.Lexs[ln], {}}
fl.Comments = []Line{sfl.Comments[ln], {}}
fl.EosPos = []EosPos{sfl.EosPos[ln], {}}
return true
}
// InitFromString initializes from given string. Returns false if string is empty
func (fl *File) InitFromString(str string, fname string, known fileinfo.Known) bool {
if str == "" {
return false
}
src := RunesFromString(str)
if len(src) == 1 { // need more than 1 line
src = append(src, []rune{})
}
fl.SetSrc(src, fname, "", known)
return true
}
///////////////////////////////////////////////////////////////////////////
// Accessors
// NLines returns the number of lines in source
func (fl *File) NLines() int {
if fl.Lines == nil {
return 0
}
return len(fl.Lines)
}
// SrcLine returns given line of source, as a string, or "" if out of range
func (fl *File) SrcLine(ln int) string {
nlines := fl.NLines()
if ln < 0 || ln >= nlines {
return ""
}
return string(fl.Lines[ln])
}
// SetLine sets the line data from the lexer -- does a clone to keep the copy
func (fl *File) SetLine(ln int, lexs, comments Line, stack Stack) {
if len(fl.Lexs) <= ln {
fl.AllocLines()
}
if len(fl.Lexs) <= ln {
return
}
fl.Lexs[ln] = lexs.Clone()
fl.Comments[ln] = comments.Clone()
fl.LastStacks[ln] = stack.Clone()
fl.EosPos[ln] = nil
}
// LexLine returns the lexing output for given line,
// combining comments and all other tokens
// and allocating new memory using clone
func (fl *File) LexLine(ln int) Line {
if len(fl.Lexs) <= ln {
return nil
}
merge := MergeLines(fl.Lexs[ln], fl.Comments[ln])
return merge.Clone()
}
// NTokens returns number of lex tokens for given line
func (fl *File) NTokens(ln int) int {
if fl == nil || fl.Lexs == nil {
return 0
}
if len(fl.Lexs) <= ln {
return 0
}
return len(fl.Lexs[ln])
}
// IsLexPosValid returns true if given lexical token position is valid
func (fl *File) IsLexPosValid(pos textpos.Pos) bool {
if pos.Line < 0 || pos.Line >= fl.NLines() {
return false
}
nt := fl.NTokens(pos.Line)
if pos.Char < 0 || pos.Char >= nt {
return false
}
return true
}
// LexAt returns Lex item at given position, with no checking
func (fl *File) LexAt(cp textpos.Pos) *Lex {
return &fl.Lexs[cp.Line][cp.Char]
}
// LexAtSafe returns the Lex item at given position, or last lex item if beyond end
func (fl *File) LexAtSafe(cp textpos.Pos) Lex {
nln := fl.NLines()
if nln == 0 {
return Lex{}
}
if cp.Line >= nln {
cp.Line = nln - 1
}
sz := len(fl.Lexs[cp.Line])
if sz == 0 {
if cp.Line > 0 {
cp.Line--
return fl.LexAtSafe(cp)
}
return Lex{}
}
if cp.Char < 0 {
cp.Char = 0
}
if cp.Char >= sz {
cp.Char = sz - 1
}
return *fl.LexAt(cp)
}
// ValidTokenPos returns the next valid token position starting at given point,
// false if at end of tokens
func (fl *File) ValidTokenPos(pos textpos.Pos) (textpos.Pos, bool) {
for pos.Char >= fl.NTokens(pos.Line) {
pos.Line++
pos.Char = 0
if pos.Line >= fl.NLines() {
pos.Line = fl.NLines() - 1 // make valid
return pos, false
}
}
return pos, true
}
// NextTokenPos returns the next token position, false if at end of tokens
func (fl *File) NextTokenPos(pos textpos.Pos) (textpos.Pos, bool) {
pos.Char++
return fl.ValidTokenPos(pos)
}
// PrevTokenPos returns the previous token position, false if at end of tokens
func (fl *File) PrevTokenPos(pos textpos.Pos) (textpos.Pos, bool) {
pos.Char--
if pos.Char < 0 {
pos.Line--
if pos.Line < 0 {
return pos, false
}
for fl.NTokens(pos.Line) == 0 {
pos.Line--
if pos.Line < 0 {
pos.Line = 0
pos.Char = 0
return pos, false
}
}
pos.Char = fl.NTokens(pos.Line) - 1
}
return pos, true
}
// Token gets lex token at given Pos (Ch = token index)
func (fl *File) Token(pos textpos.Pos) token.KeyToken {
return fl.Lexs[pos.Line][pos.Char].Token
}
// PrevDepth returns the depth of the token immediately prior to given line
func (fl *File) PrevDepth(ln int) int {
pos := textpos.Pos{Line: ln, Char: 0}
pos, ok := fl.PrevTokenPos(pos)
if !ok {
return 0
}
lx := fl.LexAt(pos)
depth := lx.Token.Depth
if lx.Token.Token.IsPunctGpLeft() {
depth++
}
return depth
}
// PrevStack returns the stack from the previous line
func (fl *File) PrevStack(ln int) Stack {
if ln <= 0 {
return nil
}
if len(fl.LastStacks) <= ln {
return nil
}
return fl.LastStacks[ln-1]
}
// TokenMapReg creates a TokenMap of tokens in region, including their
// Cat and SubCat levels -- err's on side of inclusiveness -- used
// for optimizing token matching
func (fl *File) TokenMapReg(reg textpos.Region) TokenMap {
m := make(TokenMap)
cp, ok := fl.ValidTokenPos(reg.Start)
for ok && cp.IsLess(reg.End) {
tok := fl.Token(cp).Token
m.Set(tok)
subc := tok.SubCat()
if subc != tok {
m.Set(subc)
}
cat := tok.Cat()
if cat != tok {
m.Set(cat)
}
cp, ok = fl.NextTokenPos(cp)
}
return m
}
/////////////////////////////////////////////////////////////////////
// Source access from pos, reg, tok
// TokenSrc gets source runes for given token position
func (fl *File) TokenSrc(pos textpos.Pos) []rune {
if !fl.IsLexPosValid(pos) {
return nil
}
lx := fl.Lexs[pos.Line][pos.Char]
return fl.Lines[pos.Line][lx.Start:lx.End]
}
// TokenSrcPos returns source reg associated with lex token at given token position
func (fl *File) TokenSrcPos(pos textpos.Pos) textpos.Region {
if !fl.IsLexPosValid(pos) {
return textpos.Region{}
}
lx := fl.Lexs[pos.Line][pos.Char]
return textpos.Region{Start: textpos.Pos{Line: pos.Line, Char: lx.Start}, End: textpos.Pos{Line: pos.Line, Char: lx.End}}
}
// TokenSrcReg translates a region of tokens into a region of source
func (fl *File) TokenSrcReg(reg textpos.Region) textpos.Region {
if !fl.IsLexPosValid(reg.Start) || reg.IsNil() {
return textpos.Region{}
}
st := fl.Lexs[reg.Start.Line][reg.Start.Char].Start
ep, _ := fl.PrevTokenPos(reg.End) // ed is exclusive -- go to prev
ed := fl.Lexs[ep.Line][ep.Char].End
return textpos.Region{Start: textpos.Pos{Line: reg.Start.Line, Char: st}, End: textpos.Pos{Line: ep.Line, Char: ed}}
}
// RegSrc returns the source (as a string) for given region
func (fl *File) RegSrc(reg textpos.Region) string {
if reg.End.Line == reg.Start.Line {
if reg.End.Char > reg.Start.Char {
return string(fl.Lines[reg.End.Line][reg.Start.Char:reg.End.Char])
}
return ""
}
src := string(fl.Lines[reg.Start.Line][reg.Start.Char:])
nln := reg.End.Line - reg.Start.Line
if nln > 10 {
src += "|>" + string(fl.Lines[reg.Start.Line+1]) + "..."
src += "|>" + string(fl.Lines[reg.End.Line-1])
return src
}
for ln := reg.Start.Line + 1; ln < reg.End.Line; ln++ {
src += "|>" + string(fl.Lines[ln])
}
src += "|>" + string(fl.Lines[reg.End.Line][:reg.End.Char])
return src
}
// TokenRegSrc returns the source code associated with the given token region
func (fl *File) TokenRegSrc(reg textpos.Region) string {
if !fl.IsLexPosValid(reg.Start) {
return ""
}
srcreg := fl.TokenSrcReg(reg)
return fl.RegSrc(srcreg)
}
// LexTagSrcLn returns the lex'd tagged source line for given line
func (fl *File) LexTagSrcLn(ln int) string {
return fl.Lexs[ln].TagSrc(fl.Lines[ln])
}
// LexTagSrc returns the lex'd tagged source for entire source
func (fl *File) LexTagSrc() string {
var txt strings.Builder
nlines := fl.NLines()
for ln := range nlines {
txt.WriteString(fl.LexTagSrcLn(ln))
txt.WriteString("\n")
}
return txt.String()
}
/////////////////////////////////////////////////////////////////
// EOS end of statement processing
// InsertEos inserts an EOS just after the given token position
// (e.g., cp = last token in line)
func (fl *File) InsertEos(cp textpos.Pos) textpos.Pos {
np := textpos.Pos{Line: cp.Line, Char: cp.Char + 1}
elx := fl.LexAt(cp)
depth := elx.Token.Depth
fl.Lexs[cp.Line].Insert(np.Char, Lex{Token: token.KeyToken{Token: token.EOS, Depth: depth}, Start: elx.End, End: elx.End})
fl.EosPos[np.Line] = append(fl.EosPos[np.Line], np.Char)
return np
}
// ReplaceEos replaces given token with an EOS
func (fl *File) ReplaceEos(cp textpos.Pos) {
clex := fl.LexAt(cp)
clex.Token.Token = token.EOS
fl.EosPos[cp.Line] = append(fl.EosPos[cp.Line], cp.Char)
}
// EnsureFinalEos makes sure that the given line ends with an EOS (if it
// has tokens).
// Used for line-at-time parsing just to make sure it matches even if
// you haven't gotten to the end etc.
func (fl *File) EnsureFinalEos(ln int) {
if ln >= fl.NLines() {
return
}
sz := len(fl.Lexs[ln])
if sz == 0 {
return // can't get depth or anything -- useless
}
ep := textpos.Pos{Line: ln, Char: sz - 1}
elx := fl.LexAt(ep)
if elx.Token.Token == token.EOS {
return
}
fl.InsertEos(ep)
}
// NextEos finds the next EOS position at given depth, false if none
func (fl *File) NextEos(stpos textpos.Pos, depth int) (textpos.Pos, bool) {
// prf := profile.Start("NextEos")
// defer prf.End()
ep := stpos
nlines := fl.NLines()
if stpos.Line >= nlines {
return ep, false
}
eps := fl.EosPos[stpos.Line]
for i := range eps {
if eps[i] < stpos.Char {
continue
}
ep.Char = eps[i]
lx := fl.LexAt(ep)
if lx.Token.Depth == depth {
return ep, true
}
}
for ep.Line = stpos.Line + 1; ep.Line < nlines; ep.Line++ {
eps := fl.EosPos[ep.Line]
sz := len(eps)
if sz == 0 {
continue
}
for i := range sz {
ep.Char = eps[i]
lx := fl.LexAt(ep)
if lx.Token.Depth == depth {
return ep, true
}
}
}
return ep, false
}
// NextEosAnyDepth finds the next EOS at any depth
func (fl *File) NextEosAnyDepth(stpos textpos.Pos) (textpos.Pos, bool) {
ep := stpos
nlines := fl.NLines()
if stpos.Line >= nlines {
return ep, false
}
eps := fl.EosPos[stpos.Line]
if np := eps.FindGtEq(stpos.Char); np >= 0 {
ep.Char = np
return ep, true
}
ep.Char = 0
for ep.Line = stpos.Line + 1; ep.Line < nlines; ep.Line++ {
sz := len(fl.EosPos[ep.Line])
if sz == 0 {
continue
}
return ep, true
}
return ep, false
}
// Copyright (c) 2020, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lexer
import (
"cogentcore.org/core/base/indent"
"cogentcore.org/core/text/token"
)
// these functions support indentation algorithms,
// operating on marked-up rune source.
// LineIndent returns the number of tabs or spaces at start of given rune-line,
// based on target tab-size (only relevant for spaces).
// If line starts with tabs, then those are counted, else spaces --
// combinations of tabs and spaces won't produce sensible results.
func LineIndent(src []rune, tabSz int) (ind int, ichr indent.Character) {
ichr = indent.Tab
sz := len(src)
if sz == 0 {
return
}
if src[0] == ' ' {
ichr = indent.Space
ind = 1
} else if src[0] != '\t' {
return
} else {
ind = 1
}
if ichr == indent.Space {
for i := 1; i < sz; i++ {
if src[i] == ' ' {
ind++
} else {
ind /= tabSz
return
}
}
ind /= tabSz
return
}
for i := 1; i < sz; i++ {
if src[i] == '\t' {
ind++
} else {
return
}
}
return
}
// PrevLineIndent returns indentation level of previous line
// from given line that has indentation -- skips blank lines.
// Returns indent level and previous line number, and indent char.
// indent level is in increments of tabSz for spaces, and tabs for tabs.
// Operates on rune source with markup lex tags per line.
func PrevLineIndent(src [][]rune, tags []Line, ln int, tabSz int) (ind, pln int, ichr indent.Character) {
ln--
for ln >= 0 {
if len(src[ln]) == 0 {
ln--
continue
}
ind, ichr = LineIndent(src[ln], tabSz)
pln = ln
return
}
ind = 0
pln = 0
return
}
// BracketIndentLine returns the indentation level for given line based on
// previous line's indentation level, and any delta change based on
// brackets starting or ending the previous or current line.
// indent level is in increments of tabSz for spaces, and tabs for tabs.
// Operates on rune source with markup lex tags per line.
func BracketIndentLine(src [][]rune, tags []Line, ln int, tabSz int) (pInd, delInd, pLn int, ichr indent.Character) {
if ln == 0 { // the first line has no previous line to indent from
return
}
pInd, pLn, ichr = PrevLineIndent(src, tags, ln, tabSz)
curUnd, _ := LineStartEndBracket(src[ln], tags[ln])
_, prvInd := LineStartEndBracket(src[pLn], tags[pLn])
delInd = 0
switch {
case prvInd && curUnd:
delInd = 0 // offset
case prvInd:
delInd = 1 // indent
case curUnd:
delInd = -1 // undent
}
if pInd == 0 && delInd < 0 { // error..
delInd = 0
}
return
}
// LastLexIgnoreComment returns the last token of the tags, ignoring
// any final comment at end
func LastLexIgnoreComment(tags Line) (*Lex, int) {
var ll *Lex
li := -1
nt := len(tags)
for i := nt - 1; i >= 0; i-- {
l := &tags[i]
if l.Token.Token.Cat() == token.Comment || l.Token.Token < token.Keyword {
continue
}
ll = l
li = i
break
}
return ll, li
}
// LineStartEndBracket checks if line starts with a closing bracket
// or ends with an opening bracket. This is used for auto-indent for example.
// Bracket is Paren, Bracket, or Brace.
func LineStartEndBracket(src []rune, tags Line) (start, end bool) {
if len(src) == 0 {
return
}
nt := len(tags)
if nt > 0 {
ftok := tags[0].Token.Token
if ftok.InSubCat(token.PunctGp) {
if ftok.IsPunctGpRight() {
start = true
}
}
ll, _ := LastLexIgnoreComment(tags)
if ll != nil {
ltok := ll.Token.Token
if ltok.InSubCat(token.PunctGp) {
if ltok.IsPunctGpLeft() {
end = true
}
}
}
return
}
// no tags -- do it manually
fi := FirstNonSpaceRune(src)
if fi >= 0 {
bp, rt := BracePair(src[fi])
if bp != 0 && rt {
start = true
}
}
li := LastNonSpaceRune(src)
if li >= 0 {
bp, rt := BracePair(src[li])
if bp != 0 && !rt {
end = true
}
}
return
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package lexer provides all the lexing functions that transform text
// into lexical tokens, using token types defined in the token package.
// It also has the basic file source and position / region management
// functionality.
package lexer
//go:generate core generate
import (
"fmt"
"cogentcore.org/core/base/nptime"
"cogentcore.org/core/text/textpos"
"cogentcore.org/core/text/token"
)
// Lex represents a single lexical element, with a token, and start and end rune positions
// within a line of a file. Critically it also contains the nesting depth computed from
// all the parens, brackets, braces. Todo: also support XML < > </ > tag depth.
type Lex struct {
// Token includes cache of keyword for keyword types, and also has nesting depth: starting at 0 at start of file and going up for every increment in bracket / paren / start tag and down for every decrement. Is computed once and used extensively in parsing.
Token token.KeyToken
// start rune index within original source line for this token
Start int
// end rune index within original source line for this token (exclusive -- ends one before this)
End int
// time when region was set -- used for updating locations in the text based on time stamp (using efficient non-pointer time)
Time nptime.Time
}
func NewLex(tok token.KeyToken, st, ed int) Lex {
lx := Lex{Token: tok, Start: st, End: ed}
return lx
}
// Src returns the rune source for given lex item (does no validity checking)
func (lx *Lex) Src(src []rune) []rune {
return src[lx.Start:lx.End]
}
// Now sets the time stamp to now
func (lx *Lex) Now() {
lx.Time.Now()
}
// String satisfies the fmt.Stringer interface
func (lx *Lex) String() string {
return fmt.Sprintf("[+%d:%v:%v:%v]", lx.Token.Depth, lx.Start, lx.End, lx.Token.String())
}
// ContainsPos returns true if the Lex element contains given character position
func (lx *Lex) ContainsPos(pos int) bool {
return pos >= lx.Start && pos < lx.End
}
// OverlapsReg returns true if the two regions overlap
func (lx *Lex) OverlapsReg(or Lex) bool {
// start overlaps
if (lx.Start >= or.Start && lx.Start < or.End) || (or.Start >= lx.Start && or.Start < lx.End) {
return true
}
// end overlaps
return (lx.End > or.Start && lx.End <= or.End) || (or.End > lx.Start && or.End <= lx.End)
}
// Region returns the region for this lexical element, at given line
func (lx *Lex) Region(ln int) textpos.Region {
return textpos.Region{Start: textpos.Pos{Line: ln, Char: lx.Start}, End: textpos.Pos{Line: ln, Char: lx.End}}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lexer
import (
"slices"
"sort"
"strings"
"unicode"
"cogentcore.org/core/text/token"
)
// Line is one line of Lex'd text
type Line []Lex
// Add adds one element to the lex line (just append)
func (ll *Line) Add(lx Lex) {
*ll = append(*ll, lx)
}
// AddLex adds one element to the lex line with given params, returns pointer to that new lex
func (ll *Line) AddLex(tok token.KeyToken, st, ed int) *Lex {
lx := NewLex(tok, st, ed)
li := len(*ll)
ll.Add(lx)
return &(*ll)[li]
}
// Insert inserts one element to the lex line at given point
func (ll *Line) Insert(idx int, lx Lex) {
sz := len(*ll)
*ll = append(*ll, lx)
if idx < sz {
copy((*ll)[idx+1:], (*ll)[idx:sz])
(*ll)[idx] = lx
}
}
// AtPos returns the Lex in place for given position, and index, or nil, -1 if none
func (ll *Line) AtPos(pos int) (*Lex, int) {
for i := range *ll {
lx := &((*ll)[i])
if lx.ContainsPos(pos) {
return lx, i
}
}
return nil, -1
}
// Clone returns a new copy of the line
func (ll *Line) Clone() Line {
if len(*ll) == 0 {
return nil
}
cp := make(Line, len(*ll))
copy(cp, *ll)
return cp
}
// AddSort adds a new lex element in sorted order to list, sorted by start
// position, and if at the same start position, then sorted *decreasing*
// by end position -- this allows outer tags to be processed before inner tags
// which fits a stack-based tag markup logic.
func (ll *Line) AddSort(lx Lex) {
for i, t := range *ll {
if t.Start < lx.Start {
continue
}
if t.Start == lx.Start && t.End >= lx.End {
continue
}
*ll = append(*ll, lx)
copy((*ll)[i+1:], (*ll)[i:])
(*ll)[i] = lx
return
}
*ll = append(*ll, lx)
}
// Sort sorts the lex elements by starting pos, and ending pos *decreasing* if a tie
func (ll *Line) Sort() {
sort.Slice((*ll), func(i, j int) bool {
return (*ll)[i].Start < (*ll)[j].Start || ((*ll)[i].Start == (*ll)[j].Start && (*ll)[i].End > (*ll)[j].End)
})
}
// DeleteIndex deletes at given index
func (ll *Line) DeleteIndex(idx int) {
*ll = append((*ll)[:idx], (*ll)[idx+1:]...)
}
// DeleteToken deletes a specific token type from list
func (ll *Line) DeleteToken(tok token.Tokens) {
nt := len(*ll)
for i := nt - 1; i >= 0; i-- { // remove
t := (*ll)[i]
if t.Token.Token == tok {
ll.DeleteIndex(i)
}
}
}
// RuneStrings returns array of strings for Lex regions defined in Line, for
// given rune source string
func (ll *Line) RuneStrings(rstr []rune) []string {
regs := make([]string, len(*ll))
for i, t := range *ll {
regs[i] = string(rstr[t.Start:t.End])
}
return regs
}
// MergeLines merges the two lines of lex regions into a combined list
// properly ordered by sequence of tags within the line.
func MergeLines(t1, t2 Line) Line {
sz1 := len(t1)
sz2 := len(t2)
if sz1 == 0 {
return t2
}
if sz2 == 0 {
return t1
}
tsz := sz1 + sz2
tl := make(Line, sz1, tsz)
copy(tl, t1)
for i := range sz2 {
tl.AddSort(t2[i])
}
return tl
}
// String satisfies the fmt.Stringer interface
func (ll *Line) String() string {
var str strings.Builder
for _, t := range *ll {
str.WriteString(t.String())
str.WriteString(" ")
}
return str.String()
}
// TagSrc returns the token-tagged source
func (ll *Line) TagSrc(src []rune) string {
var str strings.Builder
for _, t := range *ll {
s := t.Src(src)
str.WriteString(t.String())
str.WriteString(`"`)
str.WriteString(string(s))
str.WriteString(`"`)
str.WriteString(" ")
}
return str.String()
}
// Strings returns a slice of strings for each of the Lex items in given rune src
// split by Line Lex's. Returns nil if Line empty.
func (ll *Line) Strings(src []rune) []string {
nl := len(*ll)
if nl == 0 {
return nil
}
sa := make([]string, nl)
for i, t := range *ll {
sa[i] = string(t.Src(src))
}
return sa
}
// NonCodeWords returns a Line of white-space separated word tokens in given tagged source
// that ignores token.IsCode token regions -- i.e., the "regular" words
// present in the source line -- this is useful for things like spell checking
// or manual parsing.
func (ll *Line) NonCodeWords(src []rune) Line {
wsrc := slices.Clone(src)
for _, t := range *ll { // blank out code parts first
if t.Token.Token.IsCode() {
for i := t.Start; i < t.End; i++ {
if i < len(wsrc) {
wsrc[i] = ' '
}
}
}
}
return RuneFields(wsrc)
}
// RuneFields returns a Line of Lex's defining the non-white-space "fields"
// in the given rune string
func RuneFields(src []rune) Line {
if len(src) == 0 {
return nil
}
var ln Line
cur := Lex{}
pspc := unicode.IsSpace(src[0])
cspc := pspc
for i, r := range src {
cspc = unicode.IsSpace(r)
if pspc {
if !cspc {
cur.Start = i
}
} else {
if cspc {
cur.End = i
ln.Add(cur)
}
}
pspc = cspc
}
if !pspc {
cur.End = len(src)
cur.Now()
ln.Add(cur)
}
return ln
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lexer
import (
"strings"
"unicode"
"cogentcore.org/core/text/token"
)
// These functions provide "manual" lexing support for specific cases, such as completion, where a string must be processed further.
// FirstWord returns the first contiguous sequence of purely [unicode.IsLetter] runes within the given string.
// It skips over any leading non-letters until a letter is found.
// Note that this function does not include numbers. For that, you can use the FirstWordDigits function.
func FirstWord(str string) string {
rstr := ""
for _, s := range str {
if !IsLetter(s) {
if len(rstr) == 0 {
continue
}
break
}
rstr += string(s)
}
return rstr
}
// FirstWordDigits returns the first contiguous sequence of purely [IsLetterOrDigit]
// runes within the given string. It skips over any leading non-letters until a letter
// (not digit) is found.
func FirstWordDigits(str string) string {
rstr := ""
for _, s := range str {
if !IsLetterOrDigit(s) {
if len(rstr) == 0 {
continue
}
break
}
if len(rstr) == 0 && IsDigit(s) { // can't start with digit
continue
}
rstr += string(s)
}
return rstr
}
// FirstWordApostrophe returns the first contiguous sequence of purely
// [unicode.IsLetter] runes that can also contain an apostrophe within
// the word but not at the end. This is for spell checking: also excludes
// any _ values.
func FirstWordApostrophe(str string) string {
rstr := ""
for _, s := range str {
if !IsLetterNoUnderbar(s) && s != '\'' {
if len(rstr) == 0 {
continue
}
break
}
if len(rstr) == 0 && s == '\'' { // can't start with '
continue
}
rstr += string(s)
}
rstr = strings.TrimRight(rstr, "'") // get rid of any trailing ones!
return rstr
}
// TrimLeftToAlpha returns string without any leading non-alpha runes.
func TrimLeftToAlpha(nm string) string {
return strings.TrimLeftFunc(nm, func(r rune) bool {
return !unicode.IsLetter(r)
})
}
// FirstNonSpaceRune returns the index of first non-space rune, -1 if not found
func FirstNonSpaceRune(src []rune) int {
for i, s := range src {
if !unicode.IsSpace(s) {
return i
}
}
return -1
}
// LastNonSpaceRune returns the index of last non-space rune, -1 if not found
func LastNonSpaceRune(src []rune) int {
sz := len(src)
if sz == 0 {
return -1
}
for i := sz - 1; i >= 0; i-- {
s := src[i]
if !unicode.IsSpace(s) {
return i
}
}
return -1
}
// InnerBracketScope returns the inner scope for a given bracket type if it is
// imbalanced. It is important to do completion based on just that inner scope
// if that is where the user is at.
func InnerBracketScope(str string, brl, brr string) string {
nlb := strings.Count(str, brl)
nrb := strings.Count(str, brr)
if nlb == nrb {
return str
}
if nlb > nrb {
li := strings.LastIndex(str, brl)
if li == len(str)-1 {
return InnerBracketScope(str[:li], brl, brr) // get rid of open ending and try again
}
str = str[li+1:]
ri := strings.Index(str, brr)
if ri < 0 {
return str
}
return str[:ri]
}
// nrb > nlb -- we're missing the left guys -- go to first rb
ri := strings.Index(str, brr)
if ri == 0 {
return InnerBracketScope(str[1:], brl, brr) // get rid of opening and try again
}
str = str[:ri]
li := strings.Index(str, brl)
if li < 0 {
return str
}
return str[li+1:]
}
// LastField returns the last white-space separated string
func LastField(str string) string {
if str == "" {
return ""
}
flds := strings.Fields(str)
return flds[len(flds)-1]
}
// ObjPathAt returns the starting Lex, before given lex,
// that include sequences of PunctSepPeriod and NameTag
// which are used for object paths (e.g., field.field.field)
func ObjPathAt(line Line, lx *Lex) *Lex {
stlx := lx
if lx.Start > 1 {
_, lxidx := line.AtPos(lx.Start - 1)
for i := lxidx; i >= 0; i-- {
clx := &line[i]
if clx.Token.Token == token.PunctSepPeriod || clx.Token.Token.InCat(token.Name) {
stlx = clx
} else {
break
}
}
}
return stlx
}
// LastScopedString returns the last white-space separated, and bracket
// enclosed string from given string.
func LastScopedString(str string) string {
str = LastField(str)
bstr := str
str = InnerBracketScope(str, "{", "}")
str = InnerBracketScope(str, "(", ")")
str = InnerBracketScope(str, "[", "]")
if str == "" {
return bstr
}
str = TrimLeftToAlpha(str)
if str == "" {
str = TrimLeftToAlpha(bstr)
if str == "" {
return bstr
}
}
flds := strings.Split(str, ",")
return flds[len(flds)-1]
}
// HasUpperCase returns true if string has an upper-case letter
func HasUpperCase(str string) bool {
for _, r := range str {
if unicode.IsUpper(r) {
return true
}
}
return false
}
// MatchCase uses the source string case (upper / lower) to set corresponding
// case in target string, returning that string.
func MatchCase(src, trg string) string {
rsc := []rune(src)
rtg := []rune(trg)
mx := min(len(rsc), len(rtg))
for i := range mx {
t := rtg[i]
if unicode.IsUpper(rsc[i]) {
if !unicode.IsUpper(t) {
rtg[i] = unicode.ToUpper(t)
}
} else {
if !unicode.IsLower(t) {
rtg[i] = unicode.ToLower(t)
}
}
}
return string(rtg)
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lexer
import (
"unicode"
"unicode/utf8"
)
// Matches are what kind of lexing matches to make
type Matches int32 //enums:enum
// Matching rules
const (
// String means match a specific string as given in the rule
// Note: this only looks for the string with no constraints on
// what happens after this string -- use StrName to match entire names
String Matches = iota
// StrName means match a specific string that is a complete alpha-numeric
// string (including underbar _) with some other char at the end
// must use this for all keyword matches to ensure that it isn't just
// the start of a longer name
StrName
// Match any letter, including underscore
Letter
// Match digit 0-9
Digit
// Match any white space (space, tab) -- input is already broken into lines
WhiteSpace
// CurState means match current state value set by a PushState action, using String value in rule
// all CurState cases must generally be first in list of rules so they can preempt
// other rules when the state is active
CurState
// AnyRune means match any rune -- use this as the last condition where other terminators
// come first!
AnyRune
)
// MatchPos are special positions for a match to occur
type MatchPos int32 //enums:enum
// Matching position rules
const (
// AnyPos matches at any position
AnyPos MatchPos = iota
// StartOfLine matches at start of line
StartOfLine
// EndOfLine matches at end of line
EndOfLine
// MiddleOfLine matches not at the start or end
MiddleOfLine
// StartOfWord matches at start of word
StartOfWord
// EndOfWord matches at end of word
EndOfWord
// MiddleOfWord matches not at the start or end
MiddleOfWord
)
//////// Match functions -- see also state for more complex ones
func IsLetter(ch rune) bool {
return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || (ch >= utf8.RuneSelf && unicode.IsLetter(ch))
}
func IsLetterNoUnderbar(ch rune) bool {
return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || (ch >= utf8.RuneSelf && unicode.IsLetter(ch))
}
func IsDigit(ch rune) bool {
return '0' <= ch && ch <= '9' || ch >= utf8.RuneSelf && unicode.IsDigit(ch)
}
func IsLetterOrDigit(ch rune) bool {
return IsLetter(ch) || IsDigit(ch)
}
func IsWhiteSpace(ch rune) bool {
return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r'
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lexer
import (
"strings"
"cogentcore.org/core/text/textpos"
"cogentcore.org/core/text/token"
)
// PassTwo performs second pass(s) through the lexicalized version of the source,
// computing nesting depth for every token once and for all -- this is essential for
// properly matching tokens and also for colorization in syntax highlighting.
// Optionally, a subsequent pass finds end-of-statement (EOS) tokens, which are essential
// for parsing to first break the source down into statement-sized chunks. A separate
// list of EOS token positions is maintained for very fast access.
type PassTwo struct {
// should we perform EOS detection on this type of file?
DoEos bool
// use end-of-line as a default EOS, if nesting depth is same as start of line (python) -- see also EolToks
Eol bool
// replace all semicolons with EOS to keep it consistent (C, Go..)
Semi bool
// use backslash as a line continuer (python)
Backslash bool
// if a right-brace } is detected anywhere in the line, insert an EOS *before* RBrace AND after it (needed for Go) -- do not include RBrace in EolToks in this case
RBraceEos bool
// specific tokens to recognize at the end of a line that trigger an EOS (Go)
EolToks token.KeyTokenList
}
// TwoState is the state maintained for the PassTwo process
type TwoState struct {
// position in lex tokens we're on
Pos textpos.Pos
// file that we're operating on
Src *File
// stack of nesting tokens
NestStack []token.Tokens
// any error messages accumulated during lexing specifically
Errs ErrorList
}
// Init initializes state for a new pass -- called at start of NestDepth
func (ts *TwoState) Init() {
ts.Pos = textpos.PosZero
ts.NestStack = ts.NestStack[0:0]
}
// SetSrc sets the source we're operating on
func (ts *TwoState) SetSrc(src *File) {
ts.Src = src
}
// NextLine advances to next line
func (ts *TwoState) NextLine() {
ts.Pos.Line++
ts.Pos.Char = 0
}
// Error adds an passtwo error at current position
func (ts *TwoState) Error(msg string) {
ppos := ts.Pos
ppos.Char--
clex := ts.Src.LexAtSafe(ppos)
ts.Errs.Add(textpos.Pos{Line: ts.Pos.Line, Char: clex.Start}, ts.Src.Filename, "PassTwo: "+msg, ts.Src.SrcLine(ts.Pos.Line), nil)
}
// NestStackStr returns the token stack as strings
func (ts *TwoState) NestStackStr() string {
var str strings.Builder
for _, tok := range ts.NestStack {
switch tok {
case token.PunctGpLParen:
str.WriteString("paren ( ")
case token.PunctGpLBrack:
str.WriteString("bracket [ ")
case token.PunctGpLBrace:
str.WriteString("brace { ")
}
}
return str.String()
}
/////////////////////////////////////////////////////////////////////
// PassTwo
// Error adds an passtwo error at given position
func (pt *PassTwo) Error(ts *TwoState, msg string) {
ts.Error(msg)
}
// HasErrs reports if there are errors in eosing process
func (pt *PassTwo) HasErrs(ts *TwoState) bool {
return len(ts.Errs) > 0
}
// MismatchError reports a mismatch for given type of parentheses / bracket
func (pt *PassTwo) MismatchError(ts *TwoState, tok token.Tokens) {
switch tok {
case token.PunctGpRParen:
pt.Error(ts, "mismatching parentheses -- right paren ')' without matching left paren '('")
case token.PunctGpRBrack:
pt.Error(ts, "mismatching square brackets -- right bracket ']' without matching left bracket '['")
case token.PunctGpRBrace:
pt.Error(ts, "mismatching curly braces -- right brace '}' without matching left bracket '{'")
}
}
// PushNest pushes a nesting left paren / bracket onto stack
func (pt *PassTwo) PushNest(ts *TwoState, tok token.Tokens) {
ts.NestStack = append(ts.NestStack, tok)
}
// PopNest attempts to pop given token off of nesting stack, generating error if it mismatches
func (pt *PassTwo) PopNest(ts *TwoState, tok token.Tokens) {
sz := len(ts.NestStack)
if sz == 0 {
pt.MismatchError(ts, tok)
return
}
cur := ts.NestStack[sz-1]
ts.NestStack = ts.NestStack[:sz-1] // better to clear than keep even if err
if cur != tok.PunctGpMatch() {
pt.MismatchError(ts, tok)
}
}
// NestDepth performs the nesting depth computation.
func (pt *PassTwo) NestDepth(ts *TwoState) {
ts.Init()
nlines := ts.Src.NLines()
if nlines == 0 {
return
}
// if len(ts.Src.Lexs[nlines-1]) > 0 { // last line ends with tokens -- parser needs empty last line..
// ts.Src.Lexs = append(ts.Src.Lexs, Line{})
// *ts.Src.Lines = append(*ts.Src.Lines, []rune{})
// }
for ts.Pos.Line < nlines {
sz := len(ts.Src.Lexs[ts.Pos.Line])
if sz == 0 {
ts.NextLine()
continue
}
lx := ts.Src.LexAt(ts.Pos)
tok := lx.Token.Token
if tok.IsPunctGpLeft() {
lx.Token.Depth = len(ts.NestStack) // depth increments AFTER -- this turns out to be ESSENTIAL!
pt.PushNest(ts, tok)
} else if tok.IsPunctGpRight() {
pt.PopNest(ts, tok)
lx.Token.Depth = len(ts.NestStack) // end has same depth as start, which is same as SURROUND
} else {
lx.Token.Depth = len(ts.NestStack)
}
ts.Pos.Char++
if ts.Pos.Char >= sz {
ts.NextLine()
}
}
stsz := len(ts.NestStack)
if stsz > 0 {
pt.Error(ts, "mismatched grouping -- end of file with these left unmatched: "+ts.NestStackStr())
}
}
// NestDepthLine performs the nesting depth computation on only one line, starting at
// given initial depth -- updates the given line
func (pt *PassTwo) NestDepthLine(line Line, initDepth int) {
sz := len(line)
if sz == 0 {
return
}
depth := initDepth
for i := range sz {
lx := &line[i]
tok := lx.Token.Token
if tok.IsPunctGpLeft() {
lx.Token.Depth = depth
depth++
} else if tok.IsPunctGpRight() {
depth--
lx.Token.Depth = depth
} else {
lx.Token.Depth = depth
}
}
}
// EosDetect performs EOS detection.
func (pt *PassTwo) EosDetect(ts *TwoState) {
nlines := ts.Src.NLines()
pt.EosDetectPos(ts, textpos.PosZero, nlines)
}
// EosDetectPos performs EOS detection at given starting position, for given number of lines
func (pt *PassTwo) EosDetectPos(ts *TwoState, pos textpos.Pos, nln int) {
ts.Pos = pos
nlines := ts.Src.NLines()
ok := false
for lc := 0; ts.Pos.Line < nlines && lc < nln; lc++ {
sz := len(ts.Src.Lexs[ts.Pos.Line])
if sz == 0 {
ts.NextLine()
continue
}
if pt.Semi {
for ts.Pos.Char = 0; ts.Pos.Char < sz; ts.Pos.Char++ {
lx := ts.Src.LexAt(ts.Pos)
if lx.Token.Token == token.PunctSepSemicolon {
ts.Src.ReplaceEos(ts.Pos)
}
}
}
if pt.RBraceEos {
skip := false
for ci := 0; ci < sz; ci++ {
lx := ts.Src.LexAt(textpos.Pos{Line: ts.Pos.Line, Char: ci})
if lx.Token.Token == token.PunctGpRBrace {
if ci == 0 {
ip := textpos.Pos{Line: ts.Pos.Line, Char: 0}
ip, ok = ts.Src.PrevTokenPos(ip)
if ok {
ilx := ts.Src.LexAt(ip)
if ilx.Token.Token != token.PunctGpLBrace && ilx.Token.Token != token.EOS {
ts.Src.InsertEos(ip)
}
}
} else {
ip := textpos.Pos{Line: ts.Pos.Line, Char: ci - 1}
ilx := ts.Src.LexAt(ip)
if ilx.Token.Token != token.PunctGpLBrace {
ts.Src.InsertEos(ip)
ci++
sz++
}
}
if ci == sz-1 {
ip := textpos.Pos{Line: ts.Pos.Line, Char: ci}
ts.Src.InsertEos(ip)
sz++
skip = true
}
}
}
if skip {
ts.NextLine()
continue
}
}
ep := textpos.Pos{Line: ts.Pos.Line, Char: sz - 1} // end of line token
elx := ts.Src.LexAt(ep)
if pt.Eol {
sp := textpos.Pos{Line: ts.Pos.Line, Char: 0} // start of line token
slx := ts.Src.LexAt(sp)
if slx.Token.Depth == elx.Token.Depth {
ts.Src.InsertEos(ep)
}
}
if len(pt.EolToks) > 0 { // not depth specific
if pt.EolToks.Match(elx.Token) {
ts.Src.InsertEos(ep)
}
}
ts.NextLine()
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lexer
import (
"cogentcore.org/core/text/token"
)
// EosPos is a line of EOS token positions, always sorted low-to-high
type EosPos []int
// FindGt returns any pos value greater than given token pos, -1 if none
func (ep EosPos) FindGt(ch int) int {
for i := range ep {
if ep[i] > ch {
return ep[i]
}
}
return -1
}
// FindGtEq returns any pos value greater than or equal to given token pos, -1 if none
func (ep EosPos) FindGtEq(ch int) int {
for i := range ep {
if ep[i] >= ch {
return ep[i]
}
}
return -1
}
//////// TokenMap
// TokenMap is a token map, for optimizing token exclusion
type TokenMap map[token.Tokens]struct{}
// Set sets map for given token
func (tm TokenMap) Set(tok token.Tokens) {
tm[tok] = struct{}{}
}
// Has returns true if given token is in the map
func (tm TokenMap) Has(tok token.Tokens) bool {
_, has := tm[tok]
return has
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lexer
import (
"fmt"
"io"
"strconv"
"strings"
"text/tabwriter"
"unicode"
"cogentcore.org/core/base/indent"
"cogentcore.org/core/text/token"
"cogentcore.org/core/tree"
)
// Trace is whether to print debug trace info.
var Trace = false
// Rule operates on the text input to produce the lexical tokens.
//
// Lexing is done line-by-line -- you must push and pop states to
// coordinate across multiple lines, e.g., for multi-line comments.
//
// There is full access to entire line and you can decide based on future
// (offset) characters.
//
// In general it is best to keep lexing as simple as possible and
// leave the more complex things for the parsing step.
type Rule struct {
tree.NodeBase
// disable this rule -- useful for testing and exploration
Off bool `json:",omitempty"`
// description / comments about this rule
Desc string `json:",omitempty"`
// the token value that this rule generates -- use None for non-terminals
Token token.Tokens
// the lexical match that we look for to engage this rule
Match Matches
// position where match can occur
Pos MatchPos
// if action is LexMatch, this is the string we match
String string
// offset into the input to look for a match: 0 = current char, 1 = next one, etc
Offset int `json:",omitempty"`
// adjusts the size of the region (plus or minus) that is processed for the Next action -- allows broader and narrower matching relative to tagging
SizeAdj int `json:",omitempty"`
// the action(s) to perform, in order, if there is a match -- these are performed prior to iterating over child nodes
Acts []Actions
// string(s) for ReadUntil action -- will read until any of these strings are found -- separate different options with | -- if you need to read until a literal | just put two || in a row and that will show up as a blank, which is interpreted as a literal |
Until string `json:",omitempty"`
// the state to push if our action is PushState -- note that State matching is on String, not this value
PushState string `json:",omitempty"`
// create an optimization map for this rule, which must be a parent with children that all match against a Name string -- this reads the Name and directly activates the associated rule with that String, without having to iterate through them -- use this for keywords etc -- produces a SIGNIFICANT speedup for long lists of keywords.
NameMap bool `json:",omitempty"`
// length of source that matched -- if Next is called, this is what will be skipped to
MatchLen int `display:"-" json:"-" xml:"-"`
// NameMap lookup map -- created during Compile
NmMap map[string]*Rule `edit:"-" json:"-" xml:"-"`
}
// CompileAll is called on the top-level Rule to compile all nodes.
// returns true if everything is ok
func (lr *Rule) CompileAll(ls *State) bool {
allok := false
for k := range lr.All() {
lri := k.(*Rule)
ok := lri.Compile(ls)
if !ok {
allok = false
}
}
return allok
}
// Compile performs any one-time compilation steps on the rule
// returns false if there are any problems.
func (lr *Rule) Compile(ls *State) bool {
if lr.Off {
lr.SetProperty("inactive", true)
} else {
lr.DeleteProperty("inactive")
}
valid := true
lr.ComputeMatchLen(ls)
if lr.NameMap {
if !lr.CompileNameMap(ls) {
valid = false
}
}
return valid
}
// CompileNameMap compiles name map -- returns false if there are problems.
func (lr *Rule) CompileNameMap(ls *State) bool {
valid := true
lr.NmMap = make(map[string]*Rule, len(lr.Children))
for _, klri := range lr.Children {
klr := klri.(*Rule)
if !klr.Validate(ls) {
valid = false
}
if klr.String == "" {
ls.Error(0, "CompileNameMap: must have non-empty String to match", lr)
valid = false
continue
}
if _, has := lr.NmMap[klr.String]; has {
ls.Error(0, fmt.Sprintf("CompileNameMap: multiple rules have the same string name: %v -- must be unique!", klr.String), lr)
valid = false
} else {
lr.NmMap[klr.String] = klr
}
}
return valid
}
// Validate checks for any errors in the rules and issues warnings,
// returns true if valid (no err) and false if invalid (errs)
func (lr *Rule) Validate(ls *State) bool {
valid := true
if !tree.IsRoot(lr) {
switch lr.Match {
case StrName:
fallthrough
case String:
if len(lr.String) == 0 {
valid = false
ls.Error(0, "match = String or StrName but String is empty", lr)
}
case CurState:
for _, act := range lr.Acts {
if act == Next {
valid = false
ls.Error(0, "match = CurState cannot have Action = Next -- no src match", lr)
}
}
if len(lr.String) == 0 {
ls.Error(0, "match = CurState must have state to match in String -- is empty", lr)
}
if len(lr.PushState) > 0 {
ls.Error(0, "match = CurState has non-empty PushState -- must have state to match in String instead", lr)
}
}
}
if !lr.HasChildren() && len(lr.Acts) == 0 {
valid = false
ls.Error(0, "rule has no children and no action -- does nothing", lr)
}
hasPos := false
for _, act := range lr.Acts {
if act >= Name && act <= EOL {
hasPos = true
}
if act == Next && hasPos {
valid = false
ls.Error(0, "action = Next incompatible with action that reads item such as Name, Number, Quoted", lr)
}
}
if lr.Token.Cat() == token.Keyword && lr.Match != StrName {
valid = false
ls.Error(0, "Keyword token must use StrName to match entire name", lr)
}
// now we iterate over our kids
for _, klri := range lr.Children {
klr := klri.(*Rule)
if !klr.Validate(ls) {
valid = false
}
}
return valid
}
// ComputeMatchLen computes MatchLen based on match type
func (lr *Rule) ComputeMatchLen(ls *State) {
switch lr.Match {
case String:
sz := len(lr.String)
lr.MatchLen = lr.Offset + sz + lr.SizeAdj
case StrName:
sz := len(lr.String)
lr.MatchLen = lr.Offset + sz + lr.SizeAdj
case Letter:
lr.MatchLen = lr.Offset + 1 + lr.SizeAdj
case Digit:
lr.MatchLen = lr.Offset + 1 + lr.SizeAdj
case WhiteSpace:
lr.MatchLen = lr.Offset + 1 + lr.SizeAdj
case CurState:
lr.MatchLen = 0
case AnyRune:
lr.MatchLen = lr.Offset + 1 + lr.SizeAdj
}
}
// LexStart is called on the top-level lex node to start lexing process for one step
func (lr *Rule) LexStart(ls *State) *Rule {
hasGuest := ls.GuestLex != nil
cpos := ls.Pos
lxsz := len(ls.Lex)
mrule := lr
for _, klri := range lr.Children {
klr := klri.(*Rule)
if mrule = klr.Lex(ls); mrule != nil { // first to match takes it -- order matters!
break
}
}
ls.setGuestLex()
if hasGuest && ls.GuestLex != nil && lr != ls.GuestLex {
ls.Pos = cpos // backup and undo what the standard rule did, and redo with guest..
// this is necessary to allow main lex to detect when to turn OFF the guest!
if lxsz > 0 {
ls.Lex = ls.Lex[:lxsz]
} else {
ls.Lex = nil
}
mrule = ls.GuestLex.LexStart(ls)
}
if Trace {
ls.printTrace()
}
if !ls.AtEol() && cpos == ls.Pos {
ls.Error(cpos, "did not advance position -- need more rules to match current input", lr)
return nil
}
return mrule
}
// Lex tries to apply rule to given input state, returns lowest-level rule that matched, nil if none
func (lr *Rule) Lex(ls *State) *Rule {
if lr.Off || !lr.IsMatch(ls) {
return nil
}
st := ls.Pos // starting pos that we're consuming
tok := token.KeyToken{Token: lr.Token}
for _, act := range lr.Acts {
lr.DoAct(ls, act, &tok)
}
ed := ls.Pos // our ending state
if ed > st {
if tok.Token.IsKeyword() {
tok.Key = lr.String // if we matched, this is it
}
ls.Add(tok, st, ed)
if Trace {
ls.addTrace("Lex: " + lr.Desc + " Added token: " + tok.String() + " at: " + strconv.Itoa(st) + " " + strconv.Itoa(ed))
}
}
if !lr.HasChildren() {
return lr
}
if lr.NameMap && lr.NmMap != nil {
nm := ls.ReadNameTmp(lr.Offset)
klr, ok := lr.NmMap[nm]
if ok {
if mrule := klr.Lex(ls); mrule != nil { // should!
return mrule
}
}
} else {
// now we iterate over our kids
for _, klri := range lr.Children {
klr := klri.(*Rule)
if mrule := klr.Lex(ls); mrule != nil { // first to match takes it -- order matters!
return mrule
}
}
}
// if kids don't match and we don't have any actions, we are just a grouper
// and thus we depend entirely on kids matching
if len(lr.Acts) == 0 {
if Trace {
ls.addTrace("Lex: " + lr.Desc + " fallthrough")
}
return nil
}
return lr
}
// IsMatch tests if the rule matches for current input state, returns true if so, false if not
func (lr *Rule) IsMatch(ls *State) bool {
if !lr.IsMatchPos(ls) {
return false
}
switch lr.Match {
case String:
return ls.MatchString(lr.Offset, lr.String)
case StrName:
nm := ls.ReadNameTmp(lr.Offset)
if nm != lr.String {
return false
}
return true
case Letter:
rn, ok := ls.RuneAt(lr.Offset)
if !ok {
return false
}
if IsLetter(rn) {
return true
}
return false
case Digit:
rn, ok := ls.RuneAt(lr.Offset)
if !ok {
return false
}
if IsDigit(rn) {
return true
}
return false
case WhiteSpace:
rn, ok := ls.RuneAt(lr.Offset)
if !ok {
return false
}
if IsWhiteSpace(rn) {
return true
}
return false
case CurState:
if ls.MatchState(lr.String) {
return true
}
return false
case AnyRune:
_, ok := ls.RuneAt(lr.Offset)
return ok
}
return false
}
// IsMatchPos tests if the rule matches position
func (lr *Rule) IsMatchPos(ls *State) bool {
lsz := len(ls.Src)
switch lr.Pos {
case AnyPos:
return true
case StartOfLine:
return ls.Pos == 0
case EndOfLine: // the target ends at the end of the line
tsz := lr.TargetLen(ls)
return ls.Pos+tsz == lsz
case MiddleOfLine:
if ls.Pos == 0 {
return false
}
tsz := lr.TargetLen(ls)
return ls.Pos+tsz < lsz
case StartOfWord:
return ls.Pos == 0 || unicode.IsSpace(ls.Src[ls.Pos-1])
case EndOfWord:
tsz := lr.TargetLen(ls)
ep := ls.Pos + tsz // the end of the target, after which is a space or the end
return ep == lsz || (ep < lsz && unicode.IsSpace(ls.Src[ep]))
case MiddleOfWord:
if ls.Pos == 0 || unicode.IsSpace(ls.Src[ls.Pos-1]) {
return false
}
tsz := lr.TargetLen(ls)
ep := ls.Pos + tsz
if ep >= lsz || unicode.IsSpace(ls.Src[ep]) {
return false
}
return true
}
return true
}
// TargetLen returns the length of the target including offset
func (lr *Rule) TargetLen(ls *State) int {
switch lr.Match {
case StrName:
fallthrough
case String:
sz := len(lr.String)
return lr.Offset + sz
case Letter:
return lr.Offset + 1
case Digit:
return lr.Offset + 1
case WhiteSpace:
return lr.Offset + 1
case AnyRune:
return lr.Offset + 1
case CurState:
return 0
}
return 0
}
// DoAct performs given action
func (lr *Rule) DoAct(ls *State, act Actions, tok *token.KeyToken) {
switch act {
case Next:
ls.Next(lr.MatchLen)
case Name:
ls.ReadName()
case Number:
tok.Token = ls.ReadNumber()
case Quoted:
ls.ReadQuoted()
case QuotedRaw:
ls.ReadQuoted() // todo: raw!
case EOL:
ls.Pos = len(ls.Src)
case ReadUntil:
ls.ReadUntil(lr.Until)
ls.Pos += lr.SizeAdj
case PushState:
ls.PushState(lr.PushState)
case PopState:
ls.PopState()
case SetGuestLex:
if ls.LastName == "" {
ls.Error(ls.Pos, "SetGuestLex action requires prior Name action -- name is empty", lr)
} else {
ls.guestName = ls.LastName
ls.guestStack = ls.Stack.Clone()
}
case PopGuestLex:
if ls.guestName != "" { // set in this same step: cancel it
ls.Stack = ls.guestStack
ls.guestName = ""
ls.guestStack = nil
} else if ls.SaveStack != nil {
ls.Stack = ls.SaveStack
ls.SaveStack = nil
}
ls.GuestLex = nil
}
}
///////////////////////////////////////////////////////////////////////
// Non-lexing functions
// Find looks for rules in the tree that contain given string in String or Name fields
func (lr *Rule) Find(find string) []*Rule {
var res []*Rule
for k := range lr.All() {
lri := k.(*Rule)
if strings.Contains(lri.String, find) || strings.Contains(lri.Name, find) {
res = append(res, lri)
}
}
return res
}
// WriteGrammar outputs the lexer rules as a formatted grammar in a BNF-like format
// it is called recursively
func (lr *Rule) WriteGrammar(writer io.Writer, depth int) {
if tree.IsRoot(lr) {
for _, k := range lr.Children {
lri := k.(*Rule)
lri.WriteGrammar(writer, depth)
}
} else {
ind := indent.Tabs(depth)
gpstr := ""
if lr.HasChildren() {
gpstr = " {"
}
offstr := ""
if lr.Pos != AnyPos {
offstr += fmt.Sprintf("@%v:", lr.Pos)
}
if lr.Offset > 0 {
offstr += fmt.Sprintf("+%d:", lr.Offset)
}
actstr := ""
if len(lr.Acts) > 0 {
actstr = "\t do: "
for _, ac := range lr.Acts {
actstr += ac.String()
switch ac {
case PushState:
actstr += ": " + lr.PushState
case ReadUntil:
actstr += ": \"" + lr.Until + "\""
}
actstr += "; "
}
}
if lr.Desc != "" {
fmt.Fprintf(writer, "%v// %v %v \n", ind, lr.Name, lr.Desc)
}
if (lr.Match >= Letter && lr.Match <= WhiteSpace) || lr.Match == AnyRune {
fmt.Fprintf(writer, "%v%v:\t\t %v\t\t if %v%v%v%v\n", ind, lr.Name, lr.Token, offstr, lr.Match, actstr, gpstr)
} else {
fmt.Fprintf(writer, "%v%v:\t\t %v\t\t if %v%v == \"%v\"%v%v\n", ind, lr.Name, lr.Token, offstr, lr.Match, lr.String, actstr, gpstr)
}
if lr.HasChildren() {
w := tabwriter.NewWriter(writer, 4, 4, 2, ' ', 0)
for _, k := range lr.Children {
lri := k.(*Rule)
lri.WriteGrammar(w, depth+1)
}
w.Flush()
fmt.Fprintf(writer, "%v}\n", ind)
}
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lexer
// Stack is the stack for states
type Stack []string
// Top returns the state at the top of the stack
func (ss *Stack) Top() string {
sz := len(*ss)
if sz == 0 {
return ""
}
return (*ss)[sz-1]
}
// Push appends state to stack
func (ss *Stack) Push(state string) {
*ss = append(*ss, state)
}
// Pop takes state off the stack and returns it
func (ss *Stack) Pop() string {
sz := len(*ss)
if sz == 0 {
return ""
}
st := (*ss)[sz-1]
*ss = (*ss)[:sz-1]
return st
}
// Clone returns a copy of the stack
func (ss *Stack) Clone() Stack {
sz := len(*ss)
if sz == 0 {
return nil
}
cl := make(Stack, sz)
copy(cl, *ss)
return cl
}
// Reset stack
func (ss *Stack) Reset() {
*ss = nil
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lexer
import (
"fmt"
"strconv"
"strings"
"unicode"
"cogentcore.org/core/base/nptime"
"cogentcore.org/core/text/textpos"
"cogentcore.org/core/text/token"
)
// LanguageLexer looks up lexer for given language; implementation in parent parse package
// so we need the interface
type LanguageLexer interface {
// LexerByName returns the top-level [Rule] for given language (case invariant lookup)
LexerByName(lang string) *Rule
}
// TheLanguageLexer is the instance of LangLexer interface used to lookup lexers
// for languages -- is set in parse/languages.go
var TheLanguageLexer LanguageLexer
// State is the state maintained for lexing
type State struct {
// the current file being lex'd
Filename string
// if true, record whitespace tokens -- else ignore
KeepWS bool
// the current line of source being processed
Src []rune
// the lex output for this line
Lex Line
// the comments output for this line -- kept separately
Comments Line
// the current rune char position within the line
Pos int
// the line within overall source that we're operating on (0 indexed)
Line int
// the current rune read by NextRune
Rune rune
// state stack
Stack Stack
// the last name that was read
LastName string
// a guest lexer that can be installed for managing a different language type, e.g., quoted text in markdown files
GuestLex *Rule
// copy of stack at point when guest lexer was installed -- restore when popped
SaveStack Stack
// time stamp for lexing -- set at start of new lex process
Time nptime.Time
// any error messages accumulated during lexing specifically
Errs ErrorList
// traceLines are the lines of the [Trace] output that [Rule.Lex] adds,
// which [Rule.LexStart] prints. Lex does no output itself, so that it
// is not an async function when compiled to JavaScript, which would make
// each of its many calls much slower there.
traceLines []string
// guestName is the name of the guest lexer that a [SetGuestLex] action
// has requested in the current step, which [Rule.LexStart] installs
// with setGuestLex, along with guestStack, the state stack at the time
// of the action. The lookup of the guest lexer is a call of the
// [LanguageLexer] interface, which is done once per step in LexStart
// rather than in [Rule.DoAct], so that DoAct and [Rule.Lex] do not call
// an interface method, which makes them async functions when compiled to
// JavaScript, and much slower there.
guestName string
guestStack Stack
}
// setGuestLex installs the guest lexer that a [SetGuestLex] action has
// requested in this step, if any.
func (ls *State) setGuestLex() {
if ls.guestName == "" {
return
}
if lx := TheLanguageLexer.LexerByName(ls.guestName); lx != nil {
ls.GuestLex = lx
ls.SaveStack = ls.guestStack
}
ls.guestName = ""
ls.guestStack = nil
}
// addTrace adds a line of [Trace] output, which is printed by printTrace.
func (ls *State) addTrace(line string) {
ls.traceLines = append(ls.traceLines, line)
}
// printTrace prints the lines of [Trace] output added by addTrace.
func (ls *State) printTrace() {
for _, line := range ls.traceLines {
fmt.Println(line)
}
ls.traceLines = ls.traceLines[:0]
}
// Init initializes the state at start of parsing
func (ls *State) Init() {
ls.GuestLex = nil
ls.Stack.Reset()
ls.Line = 0
ls.SetLine(nil)
ls.SaveStack = nil
ls.guestName = ""
ls.guestStack = nil
ls.Errs.Reset()
}
// SetLine sets a new line for parsing and initializes the lex output and pos
func (ls *State) SetLine(src []rune) {
ls.Src = src
ls.Lex = nil
ls.Comments = nil
ls.Pos = 0
}
// LineString returns the current lex output as tagged source
func (ls *State) LineString() string {
return fmt.Sprintf("[%v,%v]: %v", ls.Line, ls.Pos, ls.Lex.TagSrc(ls.Src))
}
// Error adds a lexing error at given position
func (ls *State) Error(pos int, msg string, rule *Rule) {
ls.Errs.Add(textpos.Pos{Line: ls.Line, Char: pos}, ls.Filename, "Lexer: "+msg, string(ls.Src), rule)
}
// AtEol returns true if current position is at end of line
func (ls *State) AtEol() bool {
sz := len(ls.Src)
return ls.Pos >= sz
}
// String gets the string at given offset and length from current position, returns false if out of range
func (ls *State) String(off, sz int) (string, bool) {
idx := ls.Pos + off
ei := idx + sz
if ei > len(ls.Src) {
return "", false
}
return string(ls.Src[idx:ei]), true
}
// MatchString returns whether the source at the given offset from the
// current position matches the given string, without allocating a string.
func (ls *State) MatchString(off int, s string) bool {
idx := ls.Pos + off
if idx < 0 {
return false
}
for _, r := range s {
if idx >= len(ls.Src) || ls.Src[idx] != r {
return false
}
idx++
}
return true
}
// RuneAt gets the rune at given offset from current position, returns false if out of range
func (ls *State) RuneAt(off int) (rune, bool) {
idx := ls.Pos + off
if idx >= len(ls.Src) {
return 0, false
}
return ls.Src[idx], true
}
// Next moves to next position using given increment in source line -- returns false if at end
func (ls *State) Next(inc int) bool {
sz := len(ls.Src)
ls.Pos += inc
if ls.Pos >= sz {
ls.Pos = sz
return false
}
return true
}
// NextRune reads the next rune into Rune and returns false if at end of
// line, where Rune is -1
func (ls *State) NextRune() bool {
sz := len(ls.Src)
ls.Pos++
if ls.Pos >= sz {
ls.Pos = sz
ls.Rune = -1 // (not the last rune again, as for an escape at the end)
return false
}
ls.Rune = ls.Src[ls.Pos]
return true
}
// CurRuneAt reads the current rune into Ch and returns false if at end of line
func (ls *State) CurRuneAt() bool {
sz := len(ls.Src)
if ls.Pos >= sz {
ls.Pos = sz
ls.Rune = -1
return false
}
ls.Rune = ls.Src[ls.Pos]
return true
}
// Add adds a lex token for given region -- merges with prior if same
func (ls *State) Add(tok token.KeyToken, st, ed int) {
if tok.Token == token.TextWhitespace && !ls.KeepWS {
return
}
lxl := &ls.Lex
if tok.Token.Cat() == token.Comment {
lxl = &ls.Comments
}
sz := len(*lxl)
if sz > 0 && tok.Token.CombineRepeats() {
lst := &(*lxl)[sz-1]
if lst.Token.Token == tok.Token && lst.End == st {
lst.End = ed
return
}
}
lx := (*lxl).AddLex(tok, st, ed)
lx.Time = ls.Time
}
// PushState pushes state onto stack
func (ls *State) PushState(st string) {
ls.Stack.Push(st)
}
// CurState returns the current state
func (ls *State) CurState() string {
return ls.Stack.Top()
}
// PopState pops state off of stack
func (ls *State) PopState() string {
return ls.Stack.Pop()
}
// MatchState returns true if the current state matches the string
func (ls *State) MatchState(st string) bool {
sz := len(ls.Stack)
if sz == 0 {
return false
}
return ls.Stack[sz-1] == st
}
// ReadNameTmp reads a standard alpha-numeric_ name and returns it.
// Does not update the lexing position -- a "lookahead" name read
func (ls *State) ReadNameTmp(off int) string {
cp := ls.Pos
ls.Pos += off
ls.ReadName()
ls.Pos = cp
return ls.LastName
}
// ReadName reads a standard alpha-numeric_ name -- saves in LastName
func (ls *State) ReadName() {
st := ls.Pos
sz := len(ls.Src)
for ls.Pos < sz && IsLetterOrDigit(ls.Src[ls.Pos]) {
ls.Pos++
}
ls.LastName = string(ls.Src[st:ls.Pos])
}
// NextSrcLine returns the next line of text
func (ls *State) NextSrcLine() string {
if ls.AtEol() {
return "EOL"
}
return string(ls.Src[ls.Pos:])
}
// ReadUntil reads until given string(s) -- does do depth tracking if looking for a bracket
// open / close kind of symbol.
// For multiple "until" string options, separate each by |
// and use empty to match a single | or || in combination with other options.
// Terminates at end of line without error
func (ls *State) ReadUntil(until string) {
ustrs := strings.Split(until, "|")
if len(ustrs) == 0 || (len(ustrs) == 1 && len(ustrs[0]) == 0) {
ustrs = []string{"|"}
}
sz := len(ls.Src)
got := false
depth := 0
match := rune(0)
if len(ustrs) == 1 && len(ustrs[0]) == 1 {
switch ustrs[0][0] {
case '}':
match = '{'
case ')':
match = '('
case ']':
match = '['
}
}
for ls.NextRune() {
if match != 0 {
if ls.Rune == match {
depth++
continue
} else if ls.Rune == rune(ustrs[0][0]) {
if depth > 0 {
depth--
continue
}
}
if depth > 0 {
continue
}
}
for _, un := range ustrs {
usz := len(un)
if usz == 0 { // ||
if ls.Rune == '|' {
ls.NextRune() // move past
break
}
} else {
ep := ls.Pos + usz
if ep < sz && ls.Pos < ep {
sm := string(ls.Src[ls.Pos:ep])
if sm == un {
ls.Pos += usz
got = true
break
}
}
}
}
if got {
break
}
}
}
// ReadNumber reads a number of any sort, returning the type of the number
func (ls *State) ReadNumber() token.Tokens {
offs := ls.Pos
tok := token.LitNumInteger
ls.CurRuneAt()
if ls.Rune == '0' {
// int or float
offs := ls.Pos
ls.NextRune()
if ls.Rune == 'x' || ls.Rune == 'X' {
// hexadecimal int
ls.NextRune()
ls.ScanMantissa(16)
if ls.Pos-offs <= 2 {
// only scanned "0x" or "0X"
ls.Error(offs, "illegal hexadecimal number", nil)
}
} else {
// octal int or float
seenDecimalDigit := false
ls.ScanMantissa(8)
if ls.Rune == '8' || ls.Rune == '9' {
// illegal octal int or float
seenDecimalDigit = true
ls.ScanMantissa(10)
}
if ls.Rune == '.' || ls.Rune == 'e' || ls.Rune == 'E' || ls.Rune == 'i' {
goto fraction
}
// octal int
if seenDecimalDigit {
ls.Error(offs, "illegal octal number", nil)
}
}
goto exit
}
// decimal int or float
ls.ScanMantissa(10)
fraction:
if ls.Rune == '.' {
tok = token.LitNumFloat
ls.NextRune()
ls.ScanMantissa(10)
}
if ls.Rune == 'e' || ls.Rune == 'E' {
tok = token.LitNumFloat
ls.NextRune()
if ls.Rune == '-' || ls.Rune == '+' {
ls.NextRune()
}
if DigitValue(ls.Rune) < 10 {
ls.ScanMantissa(10)
} else {
ls.Error(offs, "illegal floating-point exponent", nil)
}
}
if ls.Rune == 'i' {
tok = token.LitNumImag
ls.NextRune()
}
exit:
return tok
}
func DigitValue(ch rune) int {
switch {
case '0' <= ch && ch <= '9':
return int(ch - '0')
case 'a' <= ch && ch <= 'f':
return int(ch - 'a' + 10)
case 'A' <= ch && ch <= 'F':
return int(ch - 'A' + 10)
}
return 16 // larger than any legal digit val
}
func (ls *State) ScanMantissa(base int) {
for DigitValue(ls.Rune) < base {
if !ls.NextRune() {
break
}
}
}
func (ls *State) ReadQuoted() {
delim, _ := ls.RuneAt(0)
offs := ls.Pos
ls.NextRune()
for {
ch := ls.Rune
if ch == delim {
ls.NextRune() // move past
break
}
if ch == '\\' {
ls.ReadEscape(delim)
}
if !ls.NextRune() {
ls.Error(offs, "string literal not terminated", nil)
break
}
}
}
// ReadEscape parses an escape sequence where rune is the accepted
// escaped quote. In case of a syntax error, it stops at the offending
// character (without consuming it) and returns false. Otherwise
// it returns true.
func (ls *State) ReadEscape(quote rune) bool {
offs := ls.Pos
var n int
var base, max uint32
switch ls.Rune {
case 'a', 'b', 'f', 'n', 'r', 't', 'v', '\\', quote:
ls.NextRune()
return true
case '0', '1', '2', '3', '4', '5', '6', '7':
n, base, max = 3, 8, 255
case 'x':
ls.NextRune()
n, base, max = 2, 16, 255
case 'u':
ls.NextRune()
n, base, max = 4, 16, unicode.MaxRune
case 'U':
ls.NextRune()
n, base, max = 8, 16, unicode.MaxRune
default:
msg := "unknown escape sequence"
if ls.Rune < 0 {
msg = "escape sequence not terminated"
}
ls.Error(offs, msg, nil)
return false
}
var x uint32
for n > 0 {
d := uint32(DigitValue(ls.Rune))
if d >= base {
msg := "illegal character " + unicodeString(ls.Rune) + " in escape sequence"
if ls.Rune < 0 {
msg = "escape sequence not terminated"
}
ls.Error(ls.Pos, msg, nil)
return false
}
x = x*base + d
ls.NextRune()
n--
}
if x > max || 0xD800 <= x && x < 0xE000 {
ls.Error(ls.Pos, "escape sequence is invalid Unicode code point", nil)
return false
}
return true
}
// unicodeString formats r as the %#U verb of fmt does, such as U+0041 'A'.
// It is used rather than fmt in the lexer, so that the lexing functions are
// not async functions when compiled to JavaScript, where fmt is async.
func unicodeString(r rune) string {
hex := strings.ToUpper(strconv.FormatInt(int64(r), 16))
if len(hex) < 4 {
hex = strings.Repeat("0", 4-len(hex)) + hex
}
s := "U+" + hex
if strconv.IsPrint(r) {
s += " '" + string(r) + "'"
}
return s
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package lsp contains types for the Language Server Protocol
// LSP: https://microsoft.github.io/language-server-protocol/specification
// and mappings from these elements into the token.Tokens types
// which are used internally in parse.
package lsp
//go:generate core generate
import (
"cogentcore.org/core/text/token"
)
// SymbolKind is the Language Server Protocol (LSP) SymbolKind, which
// we map onto the token.Tokens that are used internally.
type SymbolKind int32 //enums:enum
// SymbolKind is the list of SymbolKind items from LSP
const (
NoSymbolKind SymbolKind = iota
File // 1 in LSP
Module
Namespace
Package
Class
Method
Property
Field
Constructor
Enum
Interface
Function
Variable
Constant
String
Number
Boolean
Array
Object
Key
Null
EnumMember
Struct
Event
Operator
TypeParameter // 26 in LSP
)
// SymbolKindTokenMap maps between symbols and token.Tokens
var SymbolKindTokenMap = map[SymbolKind]token.Tokens{
Module: token.NameModule,
Namespace: token.NameNamespace,
Package: token.NamePackage,
Class: token.NameClass,
Method: token.NameMethod,
Property: token.NameProperty,
Field: token.NameField,
Constructor: token.NameConstructor,
Enum: token.NameEnum,
Interface: token.NameInterface,
Function: token.NameFunction,
Variable: token.NameVar,
Constant: token.NameConstant,
String: token.LitStr,
Number: token.LitNum,
Boolean: token.LiteralBool,
Array: token.NameArray,
Object: token.NameObject,
Key: token.NameTag,
Null: token.None,
EnumMember: token.NameEnumMember,
Struct: token.NameStruct,
Event: token.NameEvent,
Operator: token.Operator,
TypeParameter: token.NameTypeParam,
}
// TokenSymbolKindMap maps from tokens to LSP SymbolKind
var TokenSymbolKindMap map[token.Tokens]SymbolKind
func init() {
for s, t := range SymbolKindTokenMap {
TokenSymbolKindMap[t] = s
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package parse
//go:generate core generate -add-types
import (
"encoding/json"
"fmt"
"os"
"time"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/fileinfo"
"cogentcore.org/core/base/iox/jsonx"
"cogentcore.org/core/text/parse/lexer"
"cogentcore.org/core/text/parse/parser"
"cogentcore.org/core/text/textpos"
)
// Parser is the overall parser for managing the parsing
type Parser struct {
// lexer rules for first pass of lexing file
Lexer *lexer.Rule
// second pass after lexing -- computes nesting depth and EOS finding
PassTwo lexer.PassTwo
// parser rules for parsing lexed tokens
Parser *parser.Rule
// file name for overall parser (not file being parsed!)
Filename string
// if true, reports errors after parsing, to stdout
ReportErrs bool
// when loaded from file, this is the modification time of the parser -- re-processes cache if parser is newer than cached files
ModTime time.Time `json:"-" xml:"-"`
}
// Init initializes the parser -- must be called after creation
func (pr *Parser) Init() {
pr.Lexer = lexer.NewRule()
pr.Parser = parser.NewRule()
}
// NewParser returns a new initialized parser
func NewParser() *Parser {
pr := &Parser{}
pr.Init()
return pr
}
// InitAll initializes everything about the parser -- call this when setting up a new
// parser after it has been loaded etc
func (pr *Parser) InitAll() {
fs := &FileState{} // dummy, for error recording
fs.Init()
pr.Lexer.CompileAll(&fs.LexState)
pr.Lexer.Validate(&fs.LexState)
pr.Parser.CompileAll(&fs.ParseState)
pr.Parser.Validate(&fs.ParseState)
}
// LexInit gets the lexer ready to start lexing
func (pr *Parser) LexInit(fs *FileState) {
fs.LexState.Init()
fs.LexState.Time.Now()
fs.TwoState.Init()
if fs.Src.NLines() > 0 {
fs.LexState.SetLine(fs.Src.Lines[0])
}
}
// LexNext does next step of lexing -- returns lowest-level rule that
// matched, and nil when nomatch err or at end of source input
func (pr *Parser) LexNext(fs *FileState) *lexer.Rule {
if fs.LexState.Line >= fs.Src.NLines() {
return nil
}
for {
if fs.LexState.AtEol() {
fs.Src.SetLine(fs.LexState.Line, fs.LexState.Lex, fs.LexState.Comments, fs.LexState.Stack)
fs.LexState.Line++
if fs.LexState.Line >= fs.Src.NLines() {
return nil
}
fs.LexState.SetLine(fs.Src.Lines[fs.LexState.Line])
}
mrule := pr.Lexer.LexStart(&fs.LexState)
if mrule != nil {
return mrule
}
if !fs.LexState.AtEol() { // err
break
}
}
return nil
}
// LexNextLine does next line of lexing -- returns lowest-level rule that
// matched at end, and nil when nomatch err or at end of source input
func (pr *Parser) LexNextLine(fs *FileState) *lexer.Rule {
if fs.LexState.Line >= fs.Src.NLines() {
return nil
}
var mrule *lexer.Rule
for {
if fs.LexState.AtEol() {
fs.Src.SetLine(fs.LexState.Line, fs.LexState.Lex, fs.LexState.Comments, fs.LexState.Stack)
fs.LexState.Line++
if fs.LexState.Line >= fs.Src.NLines() {
return nil
}
fs.LexState.SetLine(fs.Src.Lines[fs.LexState.Line])
return mrule
}
mrule = pr.Lexer.LexStart(&fs.LexState)
if mrule == nil {
return nil
}
}
}
// LexRun keeps running LextNext until it stops
func (pr *Parser) LexRun(fs *FileState) {
for pr.LexNext(fs) != nil {
}
}
// LexLine runs lexer for given single line of source, which is updated
// from the given text (if non-nil)
// Returns merged regular and token comment lines, cloned and ready for use.
func (pr *Parser) LexLine(fs *FileState, ln int, txt []rune) lexer.Line {
nlines := fs.Src.NLines()
if ln >= nlines || ln < 0 {
return nil
}
fs.Src.SetLineSrc(ln, txt)
fs.LexState.SetLine(fs.Src.Lines[ln])
pst := fs.Src.PrevStack(ln)
fs.LexState.Stack = pst.Clone()
for !fs.LexState.AtEol() {
mrule := pr.Lexer.LexStart(&fs.LexState)
if mrule == nil {
break
}
}
initDepth := fs.Src.PrevDepth(ln)
pr.PassTwo.NestDepthLine(fs.LexState.Lex, initDepth) // important to set this one's depth
fs.Src.SetLine(ln, fs.LexState.Lex, fs.LexState.Comments, fs.LexState.Stack) // before saving here
fs.TwoState.SetSrc(&fs.Src)
fs.Src.EosPos[ln] = nil // reset eos
pr.PassTwo.EosDetectPos(&fs.TwoState, textpos.Pos{Line: ln}, 1)
merge := lexer.MergeLines(fs.LexState.Lex, fs.LexState.Comments)
mc := merge.Clone()
if len(fs.LexState.Comments) > 0 {
pr.PassTwo.NestDepthLine(mc, initDepth)
}
return mc
}
// DoPassTwo does the second pass after lexing
func (pr *Parser) DoPassTwo(fs *FileState) {
fs.TwoState.SetSrc(&fs.Src)
pr.PassTwo.NestDepth(&fs.TwoState)
if pr.PassTwo.DoEos {
pr.PassTwo.EosDetect(&fs.TwoState)
}
}
// LexAll runs a complete pass of the lexer and pass two, on current state
func (pr *Parser) LexAll(fs *FileState) {
pr.LexInit(fs)
// lprf := profile.Start("LexRun") // quite fast now..
pr.LexRun(fs)
// fs.LexErrReport()
// lprf.End()
pr.DoPassTwo(fs) // takes virtually no time
}
// ParserInit initializes the parser prior to running
func (pr *Parser) ParserInit(fs *FileState) bool {
fs.AnonCtr = 0
// The symbols of the last parse are cleared, which can still be updated
// in another goroutine under the lock, as for the imports of Go.
fs.SymsMu.Lock()
fs.ParseState.Init(&fs.Src, fs.AST)
fs.SymsMu.Unlock()
return true
}
// ParseNext does next step of parsing -- returns lowest-level rule that matched
// or nil if no match error or at end
func (pr *Parser) ParseNext(fs *FileState) *parser.Rule {
mrule := pr.Parser.StartParse(&fs.ParseState)
return mrule
}
// ParseRun continues running the parser until the end of the file
func (pr *Parser) ParseRun(fs *FileState) {
for {
pr.Parser.StartParse(&fs.ParseState)
if fs.ParseState.AtEofNext() {
break
}
}
}
// ParseAll does full parsing, including ParseInit and ParseRun, assuming LexAll
// has been done already
func (pr *Parser) ParseAll(fs *FileState) {
if !pr.ParserInit(fs) {
return
}
pr.ParseRun(fs)
if pr.ReportErrs {
if fs.ParseHasErrs() {
fmt.Println(fs.ParseErrReport())
}
}
}
// ParseLine runs parser for given single line of source
// does Parsing in a separate FileState and returns that with
// AST etc (or nil if nothing). Assumes LexLine has already
// been run on given line.
func (pr *Parser) ParseLine(fs *FileState, ln int) *FileState {
nlines := fs.Src.NLines()
if ln >= nlines || ln < 0 {
return nil
}
lfs := NewFileState()
lfs.Src.InitFromLine(&fs.Src, ln)
lfs.Src.EnsureFinalEos(0)
lfs.ParseState.Init(&lfs.Src, lfs.AST)
pr.ParseRun(lfs)
return lfs
}
// ParseString runs lexer and parser on given string of text, returning
// FileState of results (can be nil if string is empty or no lexical tokens).
// Also takes supporting contextual info for file / language that this string
// is associated with (only for reference)
func (pr *Parser) ParseString(str string, fname string, sup fileinfo.Known) *FileState {
if str == "" {
return nil
}
lfs := NewFileState()
lfs.Src.InitFromString(str, fname, sup)
// lfs.ParseState.Trace.FullOn()
// lfs.ParseSTate.Trace.StdOut()
lfs.ParseState.Init(&lfs.Src, lfs.AST)
pr.LexAll(lfs)
lxs := lfs.Src.Lexs[0]
if len(lxs) == 0 {
return nil
}
lfs.Src.EnsureFinalEos(0)
pr.ParseAll(lfs)
return lfs
}
// ReadJSON opens lexer and parser rules from Bytes, in a standard JSON-formatted file
func (pr *Parser) ReadJSON(b []byte) error {
err := json.Unmarshal(b, pr)
return errors.Log(err)
}
// OpenJSON opens lexer and parser rules from the given filename, in a standard JSON-formatted file
func (pr *Parser) OpenJSON(filename string) error {
err := jsonx.Open(pr, filename)
return errors.Log(err)
}
// SaveJSON saves lexer and parser rules, in a standard JSON-formatted file
func (pr *Parser) SaveJSON(filename string) error {
err := jsonx.Save(pr, filename)
return errors.Log(err)
}
// SaveGrammar saves lexer and parser grammar rules to BNF-like .parsegrammar file
func (pr *Parser) SaveGrammar(filename string) error {
ofl, err := os.Create(filename)
if err != nil {
return errors.Log(err)
}
fmt.Fprintf(ofl, "// %v Lexer\n\n", filename)
pr.Lexer.WriteGrammar(ofl, 0)
fmt.Fprintf(ofl, "\n\n///////////////////////////////////////////////////\n// %v Parser\n\n", filename)
pr.Parser.WriteGrammar(ofl, 0)
return ofl.Close()
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package parser
import (
"fmt"
"strings"
"cogentcore.org/core/text/parse/lexer"
"cogentcore.org/core/text/token"
)
// Actions are parsing actions to perform
type Actions int32 //enums:enum
// The parsing acts
const (
// ChangeToken changes the token to the Tok specified in the Act action
ChangeToken Actions = iota
// AddSymbol means add name as a symbol, using current scoping and token type
// or the token specified in the Act action if != None
AddSymbol
// PushScope means look for an existing symbol of given name
// to push onto current scope -- adding a new one if not found --
// does not add new item to overall symbol list. This is useful
// for e.g., definitions of methods on a type, where this is not
// the definition of the type itself.
PushScope
// PushNewScope means add a new symbol to the list and also push
// onto scope stack, using given token type or the token specified
// in the Act action if != None
PushNewScope
// PopScope means remove the most recently added scope item
PopScope
// PopScopeReg means remove the most recently added scope item, and also
// updates the source region for that item based on final SrcReg from
// corresponding AST node -- for "definitional" scope
PopScopeReg
// AddDetail adds src at given path as detail info for the last-added symbol
// if there is already something there, a space is added for this new addition
AddDetail
// AddType Adds a type with the given name -- sets the AST node for this rule
// and actual type is resolved later in a second language-specific pass
AddType
// PushStack adds name to stack -- provides context-sensitivity option for
// optimizing and ambiguity resolution
PushStack
// PopStack pops the stack
PopStack
)
// Act is one action to perform, operating on the AST output
type Act struct {
// at what point during sequence of sub-rules / tokens should this action be run? -1 = at end, 0 = before first rule, 1 = before second rule, etc -- must be at point when relevant AST nodes have been added, but for scope setting, must be early enough so that scope is present
RunIndex int
// what action to perform
Act Actions
// AST path, relative to current node: empty = current node; specifies a child node by index, and a name specifies it by name -- include name/name for sub-nodes etc -- multiple path options can be specified by | or & and will be tried in order until one succeeds (for |) or all that succeed will be used for &. ... means use all nodes with given name (only for change token) -- for PushStack, this is what to push on the stack
Path string `width:"50"`
// for ChangeToken, the new token type to assign to token at given path
Token token.Tokens
// for ChangeToken, only change if token is this to start with (only if != None))
FromToken token.Tokens
// paths are the alternative paths in Path, split by & or |,
// which are set by [Act.compilePaths].
paths []string
}
// compilePaths splits the Path into its alternative paths.
func (ac *Act) compilePaths() {
if strings.Contains(ac.Path, "&") {
ac.paths = strings.Split(ac.Path, "&")
} else {
ac.paths = strings.Split(ac.Path, "|")
}
}
// String satisfies fmt.Stringer interface
func (ac Act) String() string {
if ac.FromToken != token.None {
return fmt.Sprintf(`%v:%v:"%v":%v<-%v`, ac.RunIndex, ac.Act, ac.Path, ac.Token, ac.FromToken)
}
return fmt.Sprintf(`%v:%v:"%v":%v`, ac.RunIndex, ac.Act, ac.Path, ac.Token)
}
// ChangeToken changes the token type, using FromToken logic
func (ac *Act) ChangeToken(lx *lexer.Lex) {
if ac.FromToken == token.None {
lx.Token.Token = ac.Token
return
}
if lx.Token.Token != ac.FromToken {
return
}
lx.Token.Token = ac.Token
}
// Acts are multiple actions
type Acts []Act
// String satisfies fmt.Stringer interface
func (ac Acts) String() string {
if len(ac) == 0 {
return ""
}
var str strings.Builder
str.WriteString("{ ")
for i := range ac {
str.WriteString(ac[i].String())
str.WriteString("; ")
}
str.WriteString("}")
return str.String()
}
// ASTActs are actions to perform on the [AST] nodes
type ASTActs int32 //enums:enum
// The [AST] actions
const (
// NoAST means don't create an AST node for this rule
NoAST ASTActs = iota
// AddAST means create an AST node for this rule, adding it to the current anchor AST.
// Any sub-rules within this rule are *not* added as children of this node -- see
// SubAST and AnchorAST. This is good for token-only terminal nodes and list elements
// that should be added to a list.
AddAST
// SubAST means create an AST node and add all the elements of *this rule* as
// children of this new node (including sub-rules), *except* for the very last rule
// which is assumed to be a recursive rule -- that one goes back up to the parent node.
// This is good for adding more complex elements with sub-rules to a recursive list,
// without creating a new hierarchical depth level for every such element.
SubAST
// AnchorAST means create an AST node and set it as the anchor that subsequent
// sub-nodes are added into. This is for a new hierarchical depth level
// where everything under this rule gets organized.
AnchorAST
// AnchorFirstAST means create an AST node and set it as the anchor that subsequent
// sub-nodes are added into, *only* if this is the first time that this rule has
// matched within the current sequence (i.e., if the parent of this rule is the same
// rule then don't add a new AST node). This is good for starting a new list
// of recursively defined elements, without creating increasing depth levels.
AnchorFirstAST
)
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package parser
//go:generate core generate
import (
"fmt"
"io"
"cogentcore.org/core/base/indent"
"cogentcore.org/core/text/parse/lexer"
"cogentcore.org/core/text/parse/syms"
"cogentcore.org/core/text/textpos"
"cogentcore.org/core/tree"
)
// AST is a node in the abstract syntax tree generated by the parsing step
// the name of the node (from tree.NodeBase) is the type of the element
// (e.g., expr, stmt, etc)
// These nodes are generated by the parser.Rule's by matching tokens
type AST struct {
tree.NodeBase
// region in source lexical tokens corresponding to this AST node -- Ch = index in lex lines
TokReg textpos.Region `set:"-"`
// region in source file corresponding to this AST node
SrcReg textpos.Region `set:"-"`
// source code corresponding to this AST node
Src string `set:"-"`
// stack of symbols created for this node
Syms syms.SymStack `set:"-"`
}
func (ast *AST) Destroy() {
ast.Syms.ClearAST()
ast.Syms = nil
ast.NodeBase.Destroy()
}
// ChildAST returns the Child at given index as an AST.
// Will panic if index is invalid -- use Try if unsure.
func (ast *AST) ChildAST(idx int) *AST {
return ast.Child(idx).(*AST)
}
// ChildASTTry returns the Child at given index as an AST,
// nil if not in range.
func (ast *AST) ChildASTTry(idx int) *AST {
if ast == nil {
return nil
}
if idx < 0 || idx >= len(ast.Children) {
return nil
}
return ast.Child(idx).(*AST)
}
// ParentAST returns the Parent as an AST.
func (ast *AST) ParentAST() *AST {
if ast.Parent == nil {
return nil
}
pn := ast.Parent.AsTree().This
if pn == nil {
return nil
}
return pn.(*AST)
}
// NextAST returns the next node in the AST tree, or nil if none
func (ast *AST) NextAST() *AST {
nxti := tree.Next(ast)
if nxti == nil {
return nil
}
return nxti.(*AST)
}
// NextSiblingAST returns the next sibling node in the AST tree, or nil if none
func (ast *AST) NextSiblingAST() *AST {
nxti := tree.NextSibling(ast)
if nxti == nil {
return nil
}
return nxti.(*AST)
}
// PrevAST returns the previous node in the AST tree, or nil if none
func (ast *AST) PrevAST() *AST {
nxti := tree.Previous(ast)
if nxti == nil {
return nil
}
return nxti.(*AST)
}
// SetTokReg sets the token region for this rule to given region
func (ast *AST) SetTokReg(reg textpos.Region, src *lexer.File) {
ast.TokReg = reg
ast.SrcReg = src.TokenSrcReg(ast.TokReg)
ast.Src = src.RegSrc(ast.SrcReg)
}
// SetTokRegEnd updates the ending token region to given position --
// token regions are typically over-extended and get narrowed as tokens actually match
func (ast *AST) SetTokRegEnd(pos textpos.Pos, src *lexer.File) {
ast.TokReg.End = pos
ast.SrcReg = src.TokenSrcReg(ast.TokReg)
ast.Src = src.RegSrc(ast.SrcReg)
}
// WriteTree writes the AST tree data to the writer -- not attempting to re-render
// source code -- just for debugging etc
func (ast *AST) WriteTree(out io.Writer, depth int) {
ind := indent.Tabs(depth)
fmt.Fprintf(out, "%v%v: %v\n", ind, ast.Name, ast.Src)
for _, k := range ast.Children {
ai := k.(*AST)
ai.WriteTree(out, depth+1)
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package parser does the parsing stage after lexing, using a top-down recursive-descent
// (TDRD) strategy, with a special reverse mode to deal with left-associative binary expressions
// which otherwise end up being right-associative for TDRD parsing.
// Higher-level rules provide scope to lower-level ones, with a special EOS end-of-statement
// scope recognized for
package parser
import (
"fmt"
"io"
"slices"
"strconv"
"strings"
"sync/atomic"
"text/tabwriter"
"cogentcore.org/core/base/indent"
"cogentcore.org/core/base/slicesx"
"cogentcore.org/core/text/parse/lexer"
"cogentcore.org/core/text/parse/syms"
"cogentcore.org/core/text/textpos"
"cogentcore.org/core/text/token"
"cogentcore.org/core/tree"
)
// GUIActive is set to true if the gui (parseview) is active -- ensures that the
// AST tree is updated when nodes are swapped in reverse mode, and maybe
// other things. It must only be set before any parsing starts: use
// [SetGUIActive] to set it while files can be parsed in other goroutines.
var GUIActive = false
// guiActive is set by [SetGUIActive].
var guiActive atomic.Bool
// SetGUIActive sets whether the gui is active (see [GUIActive]), safely
// while files are being parsed in other goroutines.
func SetGUIActive(on bool) {
guiActive.Store(on)
}
// isGUIActive returns whether the gui is active, as set by [GUIActive] or
// [SetGUIActive].
func isGUIActive() bool {
return GUIActive || guiActive.Load()
}
// DepthLimit is the infinite recursion prevention cutoff
var DepthLimit = 10000
// Rule operates on the lexically tokenized input, not the raw source.
//
// The overall strategy is pragmatically based on the current known form of
// most languages, which are organized around a sequence of statements having
// a clear scoping defined by the EOS (end of statement), which is identified
// in a first pass through tokenized output in PassTwo.
//
// We use a top-down, recursive-descent style parsing, with flexible lookahead
// based on scoping provided by the EOS tags. Each rule progressively scopes
// down the space, using token matches etc to bracket the space for flexible
// elements.
//
// There are two different rule types:
// 1. Parents with multiple children (i.e. Groups), which are all the different
// variations for satisfying that rule, with precedence encoded directly in the
// ordering of the children. These have empty "Rule" string and Rules.
// 2. Explicit rules specified in the Rule string.
//
// The first step is matching which searches in order for matches within the
// children of parent nodes, and for explicit rule nodes, it looks first
// through all the explicit tokens in the rule. If there are no explicit tokens
// then matching defers to ONLY the first node listed by default -- you can
// add a @ prefix to indicate a rule that is also essential to match.
//
// After a rule matches, it then proceeds through the rules narrowing the scope
// and calling the sub-nodes..
type Rule struct {
tree.NodeBase
// disable this rule -- useful for testing and exploration
Off bool `json:",omitempty"`
// description / comments about this rule
Desc string `json:",omitempty"`
// the rule as a space-separated list of rule names and token(s) -- use single quotes around 'tokens' (using token.Tokens names or symbols). For keywords use 'key:keyword'. All tokens are matched at the same nesting depth as the start of the scope of this rule, unless they have a +D relative depth value differential before the token. Use @ prefix for a sub-rule to require that rule to match -- by default explicit tokens are used if available, and then only the first sub-rule failing that. Use ! by itself to define start of an exclusionary rule -- doesn't match when those rule elements DO match. Use : prefix for a special group node that matches a single token at start of scope, and then defers to the child rules to perform full match -- this is used for FirstTokenMap when there are multiple versions of a given keyword rule. Use - prefix for tokens anchored by the end (next token) instead of the previous one -- typically just for token prior to 'EOS' but also a block of tokens that need to go backward in the middle of a sequence to avoid ambiguity can be marked with -
Rule string
// if present, this rule only fires if stack has this on it
StackMatch string `json:",omitempty"`
// what action should be take for this node when it matches
AST ASTActs
// actions to perform based on parsed AST tree data, when this rule is done executing
Acts Acts `json:",omitempty"`
// for group-level rules having lots of children and lots of recursiveness, and also of high-frequency, when we first encounter such a rule, make a map of all the tokens in the entire scope, and use that for a first-pass rejection on matching tokens
OptTokenMap bool `json:",omitempty"`
// for group-level rules with a number of rules that match based on first tokens / keywords, build map to directly go to that rule -- must also organize all of these rules sequentially from the start -- if no match, goes directly to first non-lookup case
FirstTokenMap bool `json:",omitempty"`
// rule elements compiled from Rule string
Rules RuleList `json:"-" xml:"-"`
// strategic matching order for matching the rules
Order []int `edit:"-" json:"-" xml:"-"`
// map from first tokens / keywords to rules for FirstTokenMap case
FiTokenMap map[string]*Rule `edit:"-" json:"-" xml:"-" set:"-"`
// for FirstTokenMap, the start of the else cases not covered by the map
FiTokenElseIndex int `edit:"-" json:"-" xml:"-" set:"-"`
// exclusionary key index -- this is the token in Rules that we need to exclude matches for using ExclFwd and ExclRev rules
ExclKeyIndex int `edit:"-" json:"-" xml:"-" set:"-"`
// exclusionary forward-search rule elements compiled from Rule string
ExclFwd RuleList `edit:"-" json:"-" xml:"-" set:"-"`
// exclusionary reverse-search rule elements compiled from Rule string
ExclRev RuleList `edit:"-" json:"-" xml:"-" set:"-"`
// Bool flags:
// setsScope means that this rule sets its own scope, because it ends with EOS
setsScope bool
// reverse means that this rule runs in reverse (starts with - sign) -- for arithmetic
// binary expressions only: this is needed to produce proper associativity result for
// mathematical expressions in the recursive descent parser.
// Only for rules of form: Expr '+' Expr -- two sub-rules with a token operator
// in the middle.
reverse bool
// noTokens means that this rule doesn't have any explicit tokens -- only refers to
// other rules
noTokens bool
// onlyTokens means that this rule only has explicit tokens for matching -- can be
// optimized
onlyTokens bool
// tokenMatchGroup is a group node that also has a single token match, so it can
// be used in a FirstTokenMap to optimize lookup of rules
tokenMatchGroup bool
}
// RuleEl is an element of a parsing rule -- either a pointer to another rule or a token
type RuleEl struct {
// sub-rule for this position -- nil if token
Rule *Rule
// token, None if rule
Token token.KeyToken
// start increment for matching -- this is the number of non-optional, non-match items between (start | last match) and this item -- increments start region for matching
StInc int
// if true, this rule must match for rule to fire -- by default only tokens and, failing that, the first sub-rule is used for matching -- use @ to require a match
Match bool
// this rule is optional -- will absorb tokens if they exist -- indicated with ? prefix
Opt bool
// match this rule working backward from the next token -- triggered by - (minus) prefix and optimizes cases where there can be a lot of tokens going forward but few going from end -- must be anchored by a terminal EOS or other FromNext elements and is ignored if at the very end
FromNext bool
}
func (re RuleEl) IsRule() bool {
return re.Rule != nil
}
func (re RuleEl) IsToken() bool {
return re.Rule == nil
}
// RuleList is a list (slice) of rule elements
type RuleList []RuleEl
// Last returns the last rule -- only used in cases where there are rules
func (rl RuleList) Last() *RuleEl {
return &rl[len(rl)-1]
}
// RuleMap is a map of all the rule names, for quick lookup
var RuleMap map[string]*Rule
// Matches encodes the regions of each match, Err for no match
type Matches []textpos.Region
// StartEnd returns the first and last non-zero positions in the Matches list as a region
func (mm Matches) StartEnd() textpos.Region {
reg := textpos.RegionZero
for _, mp := range mm {
if mp.Start != textpos.PosZero {
if reg.Start == textpos.PosZero {
reg.Start = mp.Start
}
reg.End = mp.End
}
}
return reg
}
// StartEndExcl returns the first and last non-zero positions in the Matches list as a region
// moves the end to next toke to make it the usual exclusive end pos
func (mm Matches) StartEndExcl(ps *State) textpos.Region {
reg := mm.StartEnd()
reg.End, _ = ps.Src.NextTokenPos(reg.End)
return reg
}
///////////////////////////////////////////////////////////////////////
// Rule
// IsGroup returns true if this node is a group, else it should have rules
func (pr *Rule) IsGroup() bool {
return pr.HasChildren()
}
// SetRuleMap is called on the top-level Rule and initializes the RuleMap
func (pr *Rule) SetRuleMap(ps *State) {
RuleMap = map[string]*Rule{}
for k := range pr.All() {
pri := k.(*Rule)
if epr, has := RuleMap[pri.Name]; has {
ps.Error(textpos.PosZero, fmt.Sprintf("Parser Compile: multiple rules with same name: %v and %v", pri.Path(), epr.Path()), pri)
} else {
RuleMap[pri.Name] = pri
}
}
}
// CompileAll is called on the top-level Rule to compile all nodes
// it calls SetRuleMap first.
// Returns true if everything is ok, false if there were compile errors
func (pr *Rule) CompileAll(ps *State) bool {
pr.SetRuleMap(ps)
allok := true
for k := range pr.All() {
pri := k.(*Rule)
ok := pri.Compile(ps)
if !ok {
allok = false
}
}
return allok
}
// Compile compiles string rules into their runnable elements.
// Returns true if everything is ok, false if there were compile errors.
func (pr *Rule) Compile(ps *State) bool {
for i := range pr.Acts {
pr.Acts[i].compilePaths()
}
if pr.Off {
pr.SetProperty("inactive", true)
} else {
pr.DeleteProperty("inactive")
}
if pr.Rule == "" { // parent
pr.Rules = nil
pr.setsScope = false
return true
}
valid := true
rstr := pr.Rule
if pr.Rule[0] == '-' {
rstr = rstr[1:]
pr.reverse = true
} else {
pr.reverse = false
}
rs := strings.Split(rstr, " ")
nr := len(rs)
pr.Rules = make(RuleList, nr)
pr.ExclFwd = nil
pr.ExclRev = nil
pr.noTokens = false
pr.onlyTokens = true // default is this..
pr.setsScope = false
pr.tokenMatchGroup = false
pr.Order = nil
nmatch := 0
ntok := 0
curStInc := 0
eoses := 0
for ri := range rs {
rn := strings.TrimSpace(rs[ri])
if len(rn) == 0 {
ps.Error(textpos.PosZero, "Compile: Rules has empty string -- make sure there is only one space between rule elements", pr)
valid = false
break
}
if rn == "!" { // exclusionary rule
nr = ri
pr.Rules = pr.Rules[:ri]
if !pr.CompileExcl(ps, rs, ri+1) {
valid = false
}
break
}
if rn[0] == ':' {
pr.tokenMatchGroup = true
}
rr := &pr.Rules[ri]
tokst := strings.Index(rn, "'")
if tokst >= 0 {
if rn[0] == '?' {
rr.Opt = true
} else {
rr.StInc = curStInc
rr.Match = true // all tokens match by default
pr.Order = append(pr.Order, ri)
nmatch++
ntok++
curStInc = 0
}
sz := len(rn)
switch rn[0] {
case '+':
td, _ := strconv.ParseInt(rn[1:tokst], 10, 64)
rr.Token.Depth = int(td)
case '-':
rr.FromNext = true
}
tn := rn[tokst+1 : sz-1]
if len(tn) > 4 && tn[:4] == "key:" {
rr.Token.Token = token.Keyword
rr.Token.Key = tn[4:]
} else {
if pmt, has := token.OpPunctMap[tn]; has {
rr.Token.Token = pmt
} else {
err := rr.Token.Token.SetString(tn)
if err != nil {
ps.Error(textpos.PosZero, fmt.Sprintf("Compile: token convert error: %v", err.Error()), pr)
valid = false
}
}
}
if rr.Token.Token == token.EOS {
eoses++
if ri == nr-1 {
rr.StInc = eoses
pr.setsScope = true
}
}
} else {
st := 0
if rn[:2] == "?@" || rn[:2] == "@?" {
st = 2
rr.Opt = true
rr.Match = true
} else if rn[0] == '?' {
st = 1
rr.Opt = true
} else if rn[0] == '@' {
st = 1
rr.Match = true
pr.onlyTokens = false
pr.Order = append(pr.Order, ri)
nmatch++
} else {
curStInc++
}
rp, ok := RuleMap[rn[st:]]
if !ok {
ps.Error(textpos.PosZero, fmt.Sprintf("Compile: refers to rule %v not found", rn), pr)
valid = false
} else {
rr.Rule = rp
}
}
}
if pr.reverse {
pr.AST = AnchorAST // must be
}
if ntok == 0 && nmatch == 0 {
pr.Rules[0].Match = true
pr.Order = append(pr.Order, 0)
pr.noTokens = true
} else {
pr.OptimizeOrder(ps)
}
return valid
}
// OptimizeOrder optimizes the order of processing rule elements, including:
// * A block of reversed elements that match from next
func (pr *Rule) OptimizeOrder(ps *State) {
osz := len(pr.Order)
if osz == 0 {
return
}
nfmnxt := 0
fmnSt := -1
fmnEd := -1
lastwas := false
for oi := range osz {
ri := pr.Order[oi]
rr := &pr.Rules[ri]
if rr.FromNext {
nfmnxt++
if fmnSt < 0 {
fmnSt = oi
}
if lastwas {
fmnEd = oi // end of block
}
lastwas = true
} else {
lastwas = false
}
}
if nfmnxt > 1 && fmnEd > 0 {
nword := make([]int, osz)
for oi := 0; oi < fmnSt; oi++ {
nword[oi] = pr.Order[oi]
}
idx := fmnSt
for oi := fmnEd - 1; oi >= fmnSt; oi-- {
nword[idx] = pr.Order[oi]
idx++
}
for oi := fmnEd; oi < osz; oi++ {
nword[oi] = pr.Order[oi]
}
pr.Order = nword
}
}
// CompileTokMap compiles first token map
func (pr *Rule) CompileTokMap(ps *State) bool {
valid := true
pr.FiTokenMap = make(map[string]*Rule, len(pr.Children))
pr.FiTokenElseIndex = len(pr.Children)
for i, kpri := range pr.Children {
kpr := kpri.(*Rule)
if len(kpr.Rules) == 0 || !kpr.Rules[0].IsToken() {
pr.FiTokenElseIndex = i
break
}
fr := kpr.Rules[0]
skey := fr.Token.StringKey()
if _, has := pr.FiTokenMap[skey]; has {
ps.Error(textpos.PosZero, fmt.Sprintf("CompileFirstTokenMap: multiple rules have the same first token: %v -- must be unique -- use a :'tok' group to match that first token and put all the sub-rules as children of that node", fr.Token), pr)
pr.FiTokenElseIndex = 0
valid = false
} else {
pr.FiTokenMap[skey] = kpr
}
}
return valid
}
// CompileExcl compiles exclusionary rules starting at given point
// currently only working for single-token matching rule
func (pr *Rule) CompileExcl(ps *State, rs []string, rist int) bool {
valid := true
nr := len(rs)
var ktok token.KeyToken
ktoki := -1
for ri := 0; ri < rist && ri < len(pr.Rules); ri++ { // (the rules are cut at the !)
rr := &pr.Rules[ri]
if !rr.IsToken() {
continue
}
ktok = rr.Token
ktoki = ri
break
}
if ktoki < 0 {
ps.Error(textpos.PosZero, "CompileExcl: no token found for matching exclusion rules", pr)
return false
}
pr.ExclRev = make(RuleList, nr-rist)
ki := -1
for ri := rist; ri < nr; ri++ {
rn := strings.TrimSpace(rs[ri])
rr := &pr.ExclRev[ri-rist]
if rn[0] == '?' {
rr.Opt = true
}
tokst := strings.Index(rn, "'")
if tokst < 0 {
continue // pure optional
}
if !rr.Opt {
rr.Match = true // all tokens match by default
}
sz := len(rn)
if rn[0] == '+' {
td, _ := strconv.ParseInt(rn[1:tokst], 10, 64)
rr.Token.Depth = int(td)
}
tn := rn[tokst+1 : sz-1]
if len(tn) > 4 && tn[:4] == "key:" {
rr.Token.Token = token.Keyword
rr.Token.Key = tn[4:]
} else {
if pmt, has := token.OpPunctMap[tn]; has {
rr.Token.Token = pmt
} else {
err := rr.Token.Token.SetString(tn)
if err != nil {
ps.Error(textpos.PosZero, fmt.Sprintf("CompileExcl: token convert error: %v", err.Error()), pr)
valid = false
}
}
}
if rr.Token.Equal(ktok) {
ki = ri
}
}
if ki < 0 {
ps.Error(textpos.PosZero, fmt.Sprintf("CompileExcl: key token: %v not found in exclusion rule", ktok), pr)
valid = false
return valid
}
pr.ExclKeyIndex = ktoki
pr.ExclFwd = pr.ExclRev[ki+1-rist:]
pr.ExclRev = pr.ExclRev[:ki-rist]
return valid
}
// Validate checks for any errors in the rules and issues warnings,
// returns true if valid (no err) and false if invalid (errs)
func (pr *Rule) Validate(ps *State) bool {
valid := true
// do this here so everything else is compiled
if len(pr.Rules) == 0 && pr.FirstTokenMap {
pr.CompileTokMap(ps)
}
if len(pr.Rules) == 0 && !pr.HasChildren() && !tree.IsRoot(pr) {
ps.Error(textpos.PosZero, "Validate: rule has no rules and no children", pr)
valid = false
}
if !pr.tokenMatchGroup && len(pr.Rules) > 0 && pr.HasChildren() {
ps.Error(textpos.PosZero, "Validate: rule has both rules and children -- should be either-or", pr)
valid = false
}
if pr.reverse {
if len(pr.Rules) != 3 {
ps.Error(textpos.PosZero, "Validate: a Reverse (-) rule must have 3 children -- for binary operator expressions only", pr)
valid = false
} else {
if !pr.Rules[1].IsToken() {
ps.Error(textpos.PosZero, "Validate: a Reverse (-) rule must have a token to be recognized in the middle of two rules -- for binary operator expressions only", pr)
}
}
}
if len(pr.Rules) > 0 {
if pr.Rules[0].IsRule() && (pr.Rules[0].Rule == pr || pr.ParentLevel(pr.Rules[0].Rule) >= 0) { // left recursive
if pr.Rules[0].Match {
ps.Error(textpos.PosZero, fmt.Sprintf("Validate: rule refers to itself recursively in first sub-rule: %v and that sub-rule is marked as a Match -- this is infinite recursion and is not allowed! Must use distinctive tokens in rule to match this rule, and then left-recursive elements will be filled in when the rule runs, but they cannot be used for matching rule.", pr.Rules[0].Rule.Name), pr)
valid = false
}
ntok := 0
for _, rr := range pr.Rules {
if rr.IsToken() {
ntok++
}
}
if ntok == 0 {
ps.Error(textpos.PosZero, fmt.Sprintf("Validate: rule refers to itself recursively in first sub-rule: %v, and does not have any tokens in the rule -- MUST promote tokens to this rule to disambiguate match, otherwise will just do infinite recursion!", pr.Rules[0].Rule.Name), pr)
valid = false
}
}
}
// now we iterate over our kids
for _, kpri := range pr.Children {
kpr := kpri.(*Rule)
if !kpr.Validate(ps) {
valid = false
}
}
return valid
}
// StartParse is called on the root of the parse rule tree to start the parsing process
func (pr *Rule) StartParse(ps *State) *Rule {
if ps.AtEofNext() || !pr.HasChildren() {
ps.GotoEof()
return nil
}
kpr := pr.Children[0].(*Rule) // first rule is special set of valid top-level matches
var parAST *AST
scope := textpos.Region{Start: ps.Pos}
if ps.AST.HasChildren() {
parAST = ps.AST.ChildAST(0)
} else {
parAST = NewAST(ps.AST)
parAST.SetName(kpr.Name)
ok := false
scope.Start, ok = ps.Src.ValidTokenPos(scope.Start)
if !ok {
ps.GotoEof()
return nil
}
ps.Pos = scope.Start
}
didErr := false
for {
cpos := ps.Pos
mrule := kpr.Parse(ps, pr, parAST, scope, nil, 0)
ps.ResetNonMatches()
if ps.AtEof() {
return nil
}
if cpos == ps.Pos {
if !didErr {
ps.Error(cpos, "did not advance position -- need more rules to match current input -- skipping to next EOS", pr)
didErr = true
}
cp, ok := ps.Src.NextTokenPos(ps.Pos)
if !ok {
ps.GotoEof()
return nil
}
ep, ok := ps.Src.NextEosAnyDepth(cp)
if !ok {
ps.GotoEof()
return nil
}
ps.Pos = ep
} else {
return mrule
}
}
}
// Parse tries to apply rule to given input state, returns rule that matched or nil
// parent is the parent rule that we're being called from.
// parAST is the current ast node that we add to.
// scope is the region to search within, defined by parent or EOS if we have a terminal
// one
func (pr *Rule) Parse(ps *State, parent *Rule, parAST *AST, scope textpos.Region, optMap lexer.TokenMap, depth int) *Rule {
if pr.Off {
return nil
}
if depth >= DepthLimit {
ps.Error(scope.Start, "depth limit exceeded -- parser rules error -- look for recursive cases", pr)
return nil
}
nr := len(pr.Rules)
if !pr.tokenMatchGroup && nr > 0 {
return pr.ParseRules(ps, parent, parAST, scope, optMap, depth)
}
if optMap == nil && pr.OptTokenMap {
optMap = ps.Src.TokenMapReg(scope)
if ps.Trace.On {
ps.Trace.Out(ps, pr, Run, scope.Start, scope, parAST, fmt.Sprintf("made optmap of size: %d", len(optMap)))
}
}
// pure group types just iterate over kids
for _, kpri := range pr.Children {
kpr := kpri.(*Rule)
if mrule := kpr.Parse(ps, pr, parAST, scope, optMap, depth+1); mrule != nil {
return mrule
}
}
return nil
}
// ParseRules parses rules and returns this rule if it matches, nil if not
func (pr *Rule) ParseRules(ps *State, parent *Rule, parAST *AST, scope textpos.Region, optMap lexer.TokenMap, depth int) *Rule {
ok := false
if pr.setsScope {
scope, ok = pr.Scope(ps, parAST, scope)
if !ok {
return nil
}
} else if isGUIActive() {
if scope == textpos.RegionZero {
ps.Error(scope.Start, "scope is empty and no EOS in rule -- invalid rules -- starting rules must all have EOS", pr)
return nil
}
}
match, nscope, mpos := pr.Match(ps, parAST, scope, 0, optMap)
if !match {
return nil
}
rparent := parent.Parent.(*Rule)
if parent.AST != NoAST && parent.IsGroup() {
if parAST.Name != parent.Name {
mreg := mpos.StartEndExcl(ps)
newAST := ps.AddAST(parAST, parent.Name, mreg)
if parent.AST == AnchorAST {
parAST = newAST
}
}
} else if parent.IsGroup() && rparent.AST != NoAST && rparent.IsGroup() { // two-level group...
if parAST.Name != rparent.Name {
mreg := mpos.StartEndExcl(ps)
newAST := ps.AddAST(parAST, rparent.Name, mreg)
if rparent.AST == AnchorAST {
parAST = newAST
}
}
}
valid := pr.DoRules(ps, parent, parAST, nscope, mpos, optMap, depth) // returns validity but we don't care once matched..
if !valid {
return nil
}
return pr
}
// Scope finds the potential scope region for looking for tokens -- either from
// EOS position or State ScopeStack pushed from parents.
// Returns new scope and false if no valid scope found.
func (pr *Rule) Scope(ps *State, parAST *AST, scope textpos.Region) (textpos.Region, bool) {
// prf := profile.Start("Scope")
// defer prf.End()
nscope := scope
creg := scope
lr := pr.Rules.Last()
for ei := 0; ei < lr.StInc; ei++ {
stlx := ps.Src.LexAt(creg.Start)
ep, ok := ps.Src.NextEos(creg.Start, stlx.Token.Depth)
if !ok {
// ps.Error(creg.Start, "could not find EOS at target nesting depth -- parens / bracket / brace mismatch?", pr)
return nscope, false
}
if scope.End != textpos.PosZero && lr.Opt && scope.End.IsLess(ep) {
// optional tokens can't take us out of scope
return scope, true
}
if ei == lr.StInc-1 {
nscope.End = ep
if ps.Trace.On {
ps.Trace.Out(ps, pr, SubMatch, nscope.Start, nscope, parAST, fmt.Sprintf("from EOS: starting scope: %v new scope: %v end pos: %v depth: %v", scope, nscope, ep, stlx.Token.Depth))
}
} else {
creg.Start, ok = ps.Src.NextTokenPos(ep) // advance
if !ok {
// ps.Error(scope.St, "end of file looking for EOS tokens -- premature file end?", pr)
return nscope, false
}
}
}
return nscope, true
}
// Match attempts to match the rule, returns true if it matches, and the
// match positions, along with any update to the scope
func (pr *Rule) Match(ps *State, parAST *AST, scope textpos.Region, depth int, optMap lexer.TokenMap) (bool, textpos.Region, Matches) {
if pr.Off {
return false, scope, nil
}
if depth > DepthLimit {
ps.Error(scope.Start, "depth limit exceeded -- parser rules error -- look for recursive cases", pr)
return false, scope, nil
}
if ps.IsNonMatch(scope, pr) {
return false, scope, nil
}
if pr.StackMatch != "" {
if ps.Stack.Top() != pr.StackMatch {
return false, scope, nil
}
}
// mprf := profile.Start("Match")
// defer mprf.End()
// Note: uncomment the following to see which rules are taking the most
// time -- very helpful for focusing effort on optimizing those rules.
// prf := profile.Start(pr.Nm)
// defer prf.End()
nr := len(pr.Rules)
if pr.tokenMatchGroup || nr == 0 { // Group
return pr.MatchGroup(ps, parAST, scope, depth, optMap)
}
// prf := profile.Start("IsMatch")
if mst, match := ps.IsMatch(pr, scope); match {
// prf.End()
return true, scope, mst.Regs
}
// prf.End()
var mpos Matches
match := false
if pr.noTokens {
match, mpos = pr.MatchNoToks(ps, parAST, scope, depth, optMap)
} else if pr.onlyTokens {
match, mpos = pr.MatchOnlyToks(ps, parAST, scope, depth, optMap)
} else {
match, mpos = pr.MatchMixed(ps, parAST, scope, depth, optMap)
}
if !match {
ps.AddNonMatch(scope, pr)
return false, scope, nil
}
if len(pr.ExclFwd) > 0 || len(pr.ExclRev) > 0 {
ktpos := mpos[pr.ExclKeyIndex]
if pr.MatchExclude(ps, scope, ktpos, depth, optMap) {
if ps.Trace.On {
ps.Trace.Out(ps, pr, NoMatch, ktpos.Start, scope, parAST, "Exclude criteria matched")
}
ps.AddNonMatch(scope, pr)
return false, scope, nil
}
}
mreg := mpos.StartEnd()
ps.AddMatch(pr, scope, mpos)
if ps.Trace.On {
ps.Trace.Out(ps, pr, Match, mreg.Start, scope, parAST, fmt.Sprintf("Full Match reg: %v", mreg))
}
return true, scope, mpos
}
// MatchOnlyToks matches rules having only tokens
func (pr *Rule) MatchOnlyToks(ps *State, parAST *AST, scope textpos.Region, depth int, optMap lexer.TokenMap) (bool, Matches) {
nr := len(pr.Rules)
var mpos Matches
scstlx := ps.Src.LexAt(scope.Start) // scope starting lex
scstDepth := scstlx.Token.Depth
creg := scope
osz := len(pr.Order)
for oi := range osz {
ri := pr.Order[oi]
rr := &pr.Rules[ri]
kt := rr.Token
if optMap != nil && !optMap.Has(kt.Token) { // not even a possibility
return false, nil
}
if rr.FromNext {
if mpos == nil {
mpos = make(Matches, nr) // make on demand -- cuts out a lot of allocations!
}
mpos[nr-1] = textpos.Region{Start: scope.End, End: scope.End}
}
kt.Depth += scstDepth // always use starting scope depth
match, tpos := pr.MatchToken(ps, rr, ri, kt, &creg, mpos, parAST, scope, depth, optMap)
if !match {
if ps.Trace.On {
if tpos != textpos.PosZero {
tlx := ps.Src.LexAt(tpos)
ps.Trace.Out(ps, pr, NoMatch, creg.Start, creg, parAST, fmt.Sprintf("%v token: %v, was: %v", ri, kt.String(), tlx.String()))
} else {
ps.Trace.Out(ps, pr, NoMatch, creg.Start, creg, parAST, fmt.Sprintf("%v token: %v, nil region", ri, kt.String()))
}
}
return false, nil
}
if mpos == nil {
mpos = make(Matches, nr) // make on demand -- cuts out a lot of allocations!
}
mpos[ri] = textpos.Region{Start: tpos, End: tpos}
if ps.Trace.On {
ps.Trace.Out(ps, pr, SubMatch, creg.Start, creg, parAST, fmt.Sprintf("%v token: %v", ri, kt.String()))
}
}
return true, mpos
}
// MatchToken matches one token sub-rule -- returns true for match and
// false if no match -- and the position where it was / should have been
func (pr *Rule) MatchToken(ps *State, rr *RuleEl, ri int, kt token.KeyToken, creg *textpos.Region, mpos Matches, parAST *AST, scope textpos.Region, depth int, optMap lexer.TokenMap) (bool, textpos.Pos) {
nr := len(pr.Rules)
ok := false
matchst := false // match start of creg
matched := false // match end of creg
var tpos textpos.Pos
if ri == 0 {
matchst = true
} else if mpos != nil {
lpos := mpos[ri-1].End
if lpos != textpos.PosZero { // previous has matched
matchst = true
} else if ri < nr-1 && rr.FromNext {
lpos := mpos[ri+1].Start
if lpos != textpos.PosZero { // previous has matched
creg.End, _ = ps.Src.PrevTokenPos(lpos)
matched = true
}
}
}
for stinc := 0; stinc < rr.StInc; stinc++ {
creg.Start, _ = ps.Src.NextTokenPos(creg.Start)
}
if ri == nr-1 && rr.Token.Token == token.EOS {
return true, scope.End
}
if creg.IsNil() && !matched {
return false, tpos
}
if matchst { // start token must be right here
if !ps.MatchToken(kt, creg.Start) {
return false, creg.Start
}
tpos = creg.Start
} else if matched {
if !ps.MatchToken(kt, creg.End) {
return false, creg.End
}
tpos = creg.End
} else {
// prf := profile.Start("FindToken")
if pr.reverse {
tpos, ok = ps.FindTokenReverse(kt, *creg)
} else {
tpos, ok = ps.FindToken(kt, *creg)
}
// prf.End()
if !ok {
return false, tpos
}
}
creg.Start, _ = ps.Src.NextTokenPos(tpos) // always ratchet up
return true, tpos
}
// MatchMixed matches mixed tokens and non-tokens
func (pr *Rule) MatchMixed(ps *State, parAST *AST, scope textpos.Region, depth int, optMap lexer.TokenMap) (bool, Matches) {
nr := len(pr.Rules)
var mpos Matches
scstlx := ps.Src.LexAt(scope.Start) // scope starting lex
scstDepth := scstlx.Token.Depth
creg := scope
osz := len(pr.Order)
// first pass filter on tokens
if optMap != nil {
for oi := range osz {
ri := pr.Order[oi]
rr := &pr.Rules[ri]
if rr.IsToken() {
kt := rr.Token
if !optMap.Has(kt.Token) { // not even a possibility
return false, nil
}
}
}
}
for oi := range osz {
ri := pr.Order[oi]
rr := &pr.Rules[ri]
/////////////////////////////////////////////
// Token
if rr.IsToken() {
kt := rr.Token
if rr.FromNext {
if mpos == nil {
mpos = make(Matches, nr) // make on demand -- cuts out a lot of allocations!
}
mpos[nr-1] = textpos.Region{Start: scope.End, End: scope.End}
}
kt.Depth += scstDepth // always use starting scope depth
match, tpos := pr.MatchToken(ps, rr, ri, kt, &creg, mpos, parAST, scope, depth, optMap)
if !match {
if ps.Trace.On {
if tpos != textpos.PosZero {
tlx := ps.Src.LexAt(tpos)
ps.Trace.Out(ps, pr, NoMatch, creg.Start, creg, parAST, fmt.Sprintf("%v token: %v, was: %v", ri, kt.String(), tlx.String()))
} else {
ps.Trace.Out(ps, pr, NoMatch, creg.Start, creg, parAST, fmt.Sprintf("%v token: %v, nil region", ri, kt.String()))
}
}
return false, nil
}
if mpos == nil {
mpos = make(Matches, nr) // make on demand -- cuts out a lot of allocations!
}
mpos[ri] = textpos.Region{Start: tpos, End: tpos}
if ps.Trace.On {
ps.Trace.Out(ps, pr, SubMatch, creg.Start, creg, parAST, fmt.Sprintf("%v token: %v", ri, kt.String()))
}
continue
}
//////////////////////////////////////////////
// Sub-Rule
if creg.IsNil() {
ps.Trace.Out(ps, pr, NoMatch, creg.Start, creg, parAST, fmt.Sprintf("%v sub-rule: %v, nil region", ri, rr.Rule.Name))
return false, nil
}
// first, limit region to same depth or greater as start of region -- prevents
// overflow beyond natural boundaries
stlx := ps.Src.LexAt(creg.Start) // scope starting lex
cp, _ := ps.Src.NextTokenPos(creg.Start)
stdp := stlx.Token.Depth
for cp.IsLess(creg.End) {
lx := ps.Src.LexAt(cp)
if lx.Token.Depth < stdp {
creg.End = cp
break
}
cp, _ = ps.Src.NextTokenPos(cp)
}
if ps.Trace.On {
ps.Trace.Out(ps, pr, SubMatch, creg.Start, creg, parAST, fmt.Sprintf("%v trying sub-rule: %v", ri, rr.Rule.Name))
}
match, _, smpos := rr.Rule.Match(ps, parAST, creg, depth+1, optMap)
if !match {
if ps.Trace.On {
ps.Trace.Out(ps, pr, NoMatch, creg.Start, creg, parAST, fmt.Sprintf("%v sub-rule: %v", ri, rr.Rule.Name))
}
return false, nil
}
creg.End = scope.End // back to full scope
// look through smpos for last valid position -- use that as last match pos
mreg := smpos.StartEnd()
lmnpos, ok := ps.Src.NextTokenPos(mreg.End)
if !ok && (ri != nr-1 && (ri != nr-2 || !pr.setsScope)) {
// if at end, or ends in EOS, then ok..
if ps.Trace.On {
ps.Trace.Out(ps, pr, NoMatch, creg.Start, creg, parAST, fmt.Sprintf("%v sub-rule: %v -- not at end and no tokens left", ri, rr.Rule.Name))
}
return false, nil
}
if mpos == nil {
mpos = make(Matches, nr) // make on demand -- cuts out a lot of allocations!
}
mpos[ri] = mreg
creg.Start = lmnpos
if ps.Trace.On {
msreg := mreg
msreg.End = lmnpos
ps.Trace.Out(ps, pr, SubMatch, mreg.Start, msreg, parAST, fmt.Sprintf("%v rule: %v reg: %v", ri, rr.Rule.Name, msreg))
}
}
return true, mpos
}
// MatchNoToks matches NoToks case -- just does single sub-rule match
func (pr *Rule) MatchNoToks(ps *State, parAST *AST, scope textpos.Region, depth int, optMap lexer.TokenMap) (bool, Matches) {
creg := scope
ri := 0
rr := &pr.Rules[0]
if ps.Trace.On {
ps.Trace.Out(ps, pr, SubMatch, creg.Start, creg, parAST, fmt.Sprintf("%v trying sub-rule: %v", ri, rr.Rule.Name))
}
match, _, smpos := rr.Rule.Match(ps, parAST, creg, depth+1, optMap)
if !match {
if ps.Trace.On {
ps.Trace.Out(ps, pr, NoMatch, creg.Start, creg, parAST, fmt.Sprintf("%v sub-rule: %v", ri, rr.Rule.Name))
}
return false, nil
}
if ps.Trace.On {
mreg := smpos.StartEnd() // todo: should this include creg start instead?
ps.Trace.Out(ps, pr, SubMatch, mreg.Start, mreg, parAST, fmt.Sprintf("%v rule: %v reg: %v", ri, rr.Rule.Name, mreg))
}
return true, smpos
}
// MatchGroup does matching for Group rules
func (pr *Rule) MatchGroup(ps *State, parAST *AST, scope textpos.Region, depth int, optMap lexer.TokenMap) (bool, textpos.Region, Matches) {
// prf := profile.Start("SubMatch")
if mst, match := ps.IsMatch(pr, scope); match {
// prf.End()
return true, scope, mst.Regs
}
// prf.End()
sti := 0
nk := len(pr.Children)
if pr.FirstTokenMap {
stlx := ps.Src.LexAt(scope.Start)
if kpr, has := pr.FiTokenMap[stlx.Token.StringKey()]; has {
match, nscope, mpos := kpr.Match(ps, parAST, scope, depth+1, optMap)
if match {
if ps.Trace.On {
ps.Trace.Out(ps, pr, SubMatch, scope.Start, scope, parAST, fmt.Sprintf("first token group child: %v", kpr.Name))
}
ps.AddMatch(pr, scope, mpos)
return true, nscope, mpos
}
}
sti = pr.FiTokenElseIndex
}
for i := sti; i < nk; i++ {
kpri := pr.Children[i]
kpr := kpri.(*Rule)
match, nscope, mpos := kpr.Match(ps, parAST, scope, depth+1, optMap)
if match {
if ps.Trace.On {
ps.Trace.Out(ps, pr, SubMatch, scope.Start, scope, parAST, fmt.Sprintf("group child: %v", kpr.Name))
}
ps.AddMatch(pr, scope, mpos)
return true, nscope, mpos
}
}
ps.AddNonMatch(scope, pr)
return false, scope, nil
}
// MatchExclude looks for matches of exclusion tokens -- if found, they exclude this rule
// return is true if exclude matches and rule should be excluded
func (pr *Rule) MatchExclude(ps *State, scope textpos.Region, ktpos textpos.Region, depth int, optMap lexer.TokenMap) bool {
nf := len(pr.ExclFwd)
nr := len(pr.ExclRev)
scstlx := ps.Src.LexAt(scope.Start) // scope starting lex
scstDepth := scstlx.Token.Depth
if nf > 0 {
cp, ok := ps.Src.NextTokenPos(ktpos.Start)
if !ok {
return false
}
prevAny := false
for ri := 0; ri < nf; ri++ {
rr := pr.ExclFwd[ri]
kt := rr.Token
kt.Depth += scstDepth // always use starting scope depth
if kt.Token == token.None {
prevAny = true // wild card
continue
}
if prevAny {
creg := scope
creg.Start = cp
pos, ok := ps.FindToken(kt, creg)
if !ok {
return false
}
cp = pos
} else {
if !ps.MatchToken(kt, cp) {
if !rr.Opt {
return false
}
lx := ps.Src.LexAt(cp)
if lx.Token.Depth != kt.Depth {
break
}
// ok, keep going -- no info..
}
}
cp, ok = ps.Src.NextTokenPos(cp)
if !ok && ri < nf-1 {
return false
}
if scope.End == cp || scope.End.IsLess(cp) { // out of scope -- if non-opt left, nomatch
ri++
for ; ri < nf; ri++ {
rr := pr.ExclFwd[ri]
if !rr.Opt {
return false
}
}
break
}
prevAny = false
}
}
if nr > 0 {
cp, ok := ps.Src.PrevTokenPos(ktpos.Start)
if !ok {
return false
}
prevAny := false
for ri := nr - 1; ri >= 0; ri-- {
rr := pr.ExclRev[ri]
kt := rr.Token
kt.Depth += scstDepth // always use starting scope depth
if kt.Token == token.None {
prevAny = true // wild card
continue
}
if prevAny {
creg := scope
creg.End = cp
pos, ok := ps.FindTokenReverse(kt, creg)
if !ok {
return false
}
cp = pos
} else {
if !ps.MatchToken(kt, cp) {
if !rr.Opt {
return false
}
lx := ps.Src.LexAt(cp)
if lx.Token.Depth != kt.Depth {
break
}
// ok, keep going -- no info..
}
}
cp, ok = ps.Src.PrevTokenPos(cp)
if !ok && ri > 0 {
return false
}
if cp.IsLess(scope.Start) {
ri--
for ; ri >= 0; ri-- {
rr := pr.ExclRev[ri]
if !rr.Opt {
return false
}
}
break
}
prevAny = false
}
}
return true
}
// DoRules after we have matched, goes through rest of the rules -- returns false if
// there were any issues encountered
func (pr *Rule) DoRules(ps *State, parent *Rule, parentAST *AST, scope textpos.Region, mpos Matches, optMap lexer.TokenMap, depth int) bool {
trcAST := parentAST
var ourAST *AST
anchorFirst := (pr.AST == AnchorFirstAST && parentAST.Name != pr.Name)
if pr.AST != NoAST {
// prf := profile.Start("AddAST")
ourAST = ps.AddAST(parentAST, pr.Name, scope)
// prf.End()
trcAST = ourAST
if ps.Trace.On {
ps.Trace.Out(ps, pr, Run, scope.Start, scope, trcAST, fmt.Sprintf("running with new ast: %v", trcAST.Path()))
}
} else {
if ps.Trace.On {
ps.Trace.Out(ps, pr, Run, scope.Start, scope, trcAST, fmt.Sprintf("running with parent ast: %v", trcAST.Path()))
}
}
if pr.reverse {
return pr.DoRulesRevBinExp(ps, parent, parentAST, scope, mpos, ourAST, optMap, depth)
}
nr := len(pr.Rules)
valid := true
creg := scope
for ri := range nr {
pr.DoActs(ps, ri, parent, ourAST, parentAST)
rr := &pr.Rules[ri]
if rr.IsToken() && !rr.Opt {
mp := mpos[ri].Start
if mp == ps.Pos {
ps.Pos, _ = ps.Src.NextTokenPos(ps.Pos) // already matched -- move past
if ps.Trace.On {
ps.Trace.Out(ps, pr, Run, mp, scope, trcAST, fmt.Sprintf("%v: token at expected pos: %v", ri, rr.Token))
}
} else if mp.IsLess(ps.Pos) {
// ps.Pos has moved beyond our expected token -- sub-rule has eaten more than expected!
if rr.Token.Token == token.EOS {
if ps.Trace.On {
ps.Trace.Out(ps, pr, Run, mp, scope, trcAST, fmt.Sprintf("%v: EOS token consumed by sub-rule: %v", ri, rr.Token))
}
} else {
ps.Error(mp, fmt.Sprintf("expected token: %v (at rule index: %v) was consumed by prior sub-rule(s)", rr.Token, ri), pr)
}
} else if ri == nr-1 && rr.Token.Token == token.EOS {
ps.ResetNonMatches() // passed this chunk of inputs -- don't need those nonmatches
} else {
ps.Error(mp, fmt.Sprintf("token: %v (at rule index: %v) has extra preceding input inconsistent with grammar", rr.Token, ri), pr)
ps.Pos, _ = ps.Src.NextTokenPos(mp) // move to token for more robustness
}
if ourAST != nil {
ourAST.SetTokRegEnd(ps.Pos, ps.Src) // update our end to any tokens that match
}
continue
}
creg.Start = ps.Pos
creg.End = scope.End
if !pr.noTokens {
for mi := ri + 1; mi < nr; mi++ {
if mpos[mi].Start != textpos.PosZero {
creg.End = mpos[mi].Start // only look up to point of next matching token
break
}
}
}
if rr.IsToken() { // opt by definition here
if creg.IsNil() { // no tokens left..
if ps.Trace.On {
ps.Trace.Out(ps, pr, Run, creg.Start, scope, trcAST, fmt.Sprintf("%v: opt token: %v no more src", ri, rr.Token))
}
continue
}
stlx := ps.Src.LexAt(creg.Start)
kt := rr.Token
kt.Depth += stlx.Token.Depth
pos, ok := ps.FindToken(kt, creg)
if !ok {
if ps.Trace.On {
ps.Trace.Out(ps, pr, NoMatch, creg.Start, creg, parentAST, fmt.Sprintf("%v token: %v", ri, kt.String()))
}
continue
}
if ps.Trace.On {
ps.Trace.Out(ps, pr, Match, pos, creg, parentAST, fmt.Sprintf("%v token: %v", ri, kt))
}
ps.Pos, _ = ps.Src.NextTokenPos(pos)
continue
}
////////////////////////////////////////////////////
// Below here is a Sub-Rule
if creg.IsNil() { // no tokens left..
if rr.Opt {
if ps.Trace.On {
ps.Trace.Out(ps, pr, Run, creg.Start, scope, trcAST, fmt.Sprintf("%v: opt rule: %v no more src", ri, rr.Rule.Name))
}
continue
}
ps.Error(creg.Start, fmt.Sprintf("missing expected input for: %v", rr.Rule.Name), pr)
valid = false
break // no point in continuing
}
useAST := parentAST
if pr.AST == AnchorAST || anchorFirst || (pr.AST == SubAST && ri < nr-1) {
useAST = ourAST
}
// NOTE: we can't use anything about the previous match here, because it could have
// come from a sub-sub-rule and in any case is not where you want to start
// because is could have been a token in the middle.
if ps.Trace.On {
ps.Trace.Out(ps, pr, Run, creg.Start, creg, trcAST, fmt.Sprintf("%v: trying rule: %v", ri, rr.Rule.Name))
}
subm := rr.Rule.Parse(ps, pr, useAST, creg, optMap, depth+1)
if subm == nil {
if !rr.Opt {
ps.Error(creg.Start, fmt.Sprintf("required element: %v did not match input", rr.Rule.Name), pr)
valid = false
break
}
if ps.Trace.On {
ps.Trace.Out(ps, pr, Run, creg.Start, creg, trcAST, fmt.Sprintf("%v: optional rule: %v failed", ri, rr.Rule.Name))
}
}
if !rr.Opt && ourAST != nil {
ourAST.SetTokRegEnd(ps.Pos, ps.Src) // update our end to include non-optional elements
}
}
if valid {
pr.DoActs(ps, -1, parent, ourAST, parentAST)
}
return valid
}
// DoRulesRevBinExp reverse version of do rules for binary expression rule with
// one key token in the middle -- we just pay attention to scoping rest of sub-rules
// relative to that, and don't otherwise adjust scope or position. In particular all
// the position updating taking place in sup-rules is then just ignored and we set the
// position to the end position matched by the "last" rule (which was the first processed)
func (pr *Rule) DoRulesRevBinExp(ps *State, parent *Rule, parentAST *AST, scope textpos.Region, mpos Matches, ourAST *AST, optMap lexer.TokenMap, depth int) bool {
nr := len(pr.Rules)
valid := true
creg := scope
trcAST := parentAST
if ourAST != nil {
trcAST = ourAST
}
tokpos := mpos[1].Start
aftMpos, ok := ps.Src.NextTokenPos(tokpos)
if !ok {
ps.Error(tokpos, "premature end of input", pr)
return false
}
epos := scope.End
for i := nr - 1; i >= 0; i-- {
rr := &pr.Rules[i]
if i > 1 {
creg.Start = aftMpos // end expr is in region from key token to end of scope
ps.Pos = creg.Start // only works for a single rule after key token -- sub-rules not necc reverse
creg.End = scope.End
} else if i == 1 {
if ps.Trace.On {
ps.Trace.Out(ps, pr, Run, tokpos, scope, trcAST, fmt.Sprintf("%v: key token: %v", i, rr.Token))
}
continue
} else { // start
creg.Start = scope.Start
ps.Pos = creg.Start
creg.End = tokpos
}
if rr.IsRule() { // non-key tokens ignored
if creg.IsNil() { // no tokens left..
ps.Error(creg.Start, fmt.Sprintf("missing expected input for: %v", rr.Rule.Name), pr)
valid = false
continue
}
useAST := parentAST
if pr.AST == AnchorAST {
useAST = ourAST
}
if ps.Trace.On {
ps.Trace.Out(ps, pr, Run, creg.Start, creg, trcAST, fmt.Sprintf("%v: trying rule: %v", i, rr.Rule.Name))
}
subm := rr.Rule.Parse(ps, pr, useAST, creg, optMap, depth+1)
if subm == nil {
if !rr.Opt {
ps.Error(creg.Start, fmt.Sprintf("required element: %v did not match input", rr.Rule.Name), pr)
valid = false
}
}
}
}
// our AST is now backwards -- need to swap them
if len(ourAST.Children) == 2 {
slicesx.Swap(ourAST.Children, 0, 1)
// if GuiActive {
// we have a very strange situation here: the tree of the AST will typically
// have two children, named identically (e.g., Expr, Expr) and it will not update
// after our swap. If we could use UniqNames then it would be ok, but that doesn't
// work for tree names.. really need an option that supports uniqname AND reg names
// https://cogentcore.org/core/ki/issues/2
// ourAST.NewChild(ASTType, "Dummy")
// ourAST.DeleteChildAt(2, true)
// }
}
ps.Pos = epos
return valid
}
// DoActs performs actions at given point in rule execution (ri = rule index, is -1 at end)
func (pr *Rule) DoActs(ps *State, ri int, parent *Rule, ourAST, parentAST *AST) bool {
if len(pr.Acts) == 0 {
return false
}
// prf := profile.Start("DoActs")
// defer prf.End()
valid := true
for ai := range pr.Acts {
act := &pr.Acts[ai]
if act.RunIndex != ri {
continue
}
if !pr.DoAct(ps, act, parent, ourAST, parentAST) {
valid = false
}
}
return valid
}
// DoAct performs one action after a rule executes
func (pr *Rule) DoAct(ps *State, act *Act, parent *Rule, ourAST, parAST *AST) bool {
switch act.Act {
case PushStack:
ps.Stack.Push(act.Path)
return true
case PopStack:
ps.Stack.Pop()
return true
}
useAST := ourAST
if useAST == nil {
useAST = parAST
}
apath := "" // only used for tracing
if ps.Trace.On {
apath = useAST.Path()
}
var node tree.Node
var adnl []tree.Node // additional nodes
if act.paths == nil && act.Path != "" { // not compiled
act.compilePaths()
}
if act.Path == "" {
node = useAST
} else if andidx := strings.Index(act.Path, "&"); andidx >= 0 {
for _, p := range act.paths {
findAll := false
if strings.HasSuffix(p, "...") {
findAll = true
p = strings.TrimSuffix(p, "...")
}
var nd *AST
if p[:3] == "../" {
nd = parAST.findPath(p[3:])
} else {
nd = useAST.findPath(p)
}
if nd != nil {
if node == nil {
node = nd
}
if findAll {
adnl = append(adnl, listSiblings(ps, nd)...)
} else if node != tree.Node(nd) {
adnl = append(adnl, nd)
}
}
}
} else {
for _, p := range act.paths {
findAll := false
if strings.HasSuffix(p, "...") {
findAll = true
p = strings.TrimSuffix(p, "...")
}
var nd *AST
if p[:3] == "../" {
nd = parAST.findPath(p[3:])
} else {
nd = useAST.findPath(p)
}
if nd != nil {
node = nd
if findAll {
adnl = listSiblings(ps, nd)
}
break
}
}
}
if node == nil {
if ps.Trace.On {
ps.Trace.Out(ps, pr, RunAct, ps.Pos, textpos.RegionZero, useAST, fmt.Sprintf("Act %v: ERROR: node not found at path(s): %v in node: %v", act.Act, act.Path, apath))
}
return false
}
ast := node.(*AST)
lx := ps.Src.LexAt(ast.TokReg.Start)
useTok := lx.Token.Token
if act.Token != token.None {
useTok = act.Token
}
nm := ast.Src
nms := strings.Split(nm, ",")
if len(adnl) > 0 {
for _, pk := range adnl {
nast := pk.(*AST)
if nast != ast {
nms = append(nms, strings.Split(nast.Src, ",")...)
}
}
}
for i := range nms {
nms[i] = strings.TrimSpace(nms[i])
}
switch act.Act {
case ChangeToken:
cp := ast.TokReg.Start
for cp.IsLess(ast.TokReg.End) {
tlx := ps.Src.LexAt(cp)
act.ChangeToken(tlx)
cp, _ = ps.Src.NextTokenPos(cp)
}
if len(adnl) > 0 {
for _, pk := range adnl {
nast := pk.(*AST)
cp := nast.TokReg.Start
for cp.IsLess(nast.TokReg.End) {
tlx := ps.Src.LexAt(cp)
act.ChangeToken(tlx)
cp, _ = ps.Src.NextTokenPos(cp)
}
}
}
if ps.Trace.On {
ps.Trace.Out(ps, pr, RunAct, ast.TokReg.Start, ast.TokReg, ast, fmt.Sprintf("Act: Token set to: %v from path: %v = %v in node: %v", act.Token, act.Path, nm, apath))
}
return false
case AddSymbol:
for i := range nms {
n := nms[i]
if n == "" || n == "_" { // go special case..
continue
}
sy, has := ps.FindNameTopScope(n) // only look in top scope
added := false
if has {
sy.Region = ast.SrcReg
sy.Kind = useTok
if ps.Trace.On {
ps.Trace.Out(ps, pr, RunAct, ast.TokReg.Start, ast.TokReg, ast, fmt.Sprintf("Act: Add sym already exists: %v from path: %v = %v in node: %v", sy.String(), act.Path, n, apath))
}
} else {
sy = syms.NewSymbol(n, useTok, ps.Src.Filename, ast.SrcReg)
added = sy.AddScopesStack(ps.Scopes)
if !added {
ps.Syms.Add(sy)
}
}
useAST.Syms.Push(sy)
sy.AST = useAST.This
if ps.Trace.On {
ps.Trace.Out(ps, pr, RunAct, ast.TokReg.Start, ast.TokReg, ast, fmt.Sprintf("Act: Added sym: %v from path: %v = %v in node: %v", sy.String(), act.Path, n, apath))
}
}
case PushScope:
sy, has := ps.FindNameTopScope(nm) // Scoped(nm)
if !has {
sy = syms.NewSymbol(nm, useTok, ps.Src.Filename, ast.SrcReg) // textpos.RegionZero) // zero = tmp
added := sy.AddScopesStack(ps.Scopes)
if !added {
ps.Syms.Add(sy)
}
}
ps.Scopes.Push(sy)
useAST.Syms.Push(sy)
if ps.Trace.On {
ps.Trace.Out(ps, pr, RunAct, ast.TokReg.Start, ast.TokReg, ast, fmt.Sprintf("Act: Pushed Sym: %v from path: %v = %v in node: %v", sy.String(), act.Path, nm, apath))
}
case PushNewScope:
// add plus push
sy, has := ps.FindNameTopScope(nm) // Scoped(nm)
if has {
if ps.Trace.On {
ps.Trace.Out(ps, pr, RunAct, ast.TokReg.Start, ast.TokReg, ast, fmt.Sprintf("Act: Push New sym already exists: %v from path: %v = %v in node: %v", sy.String(), act.Path, nm, apath))
}
} else {
sy = syms.NewSymbol(nm, useTok, ps.Src.Filename, ast.SrcReg)
added := sy.AddScopesStack(ps.Scopes)
if !added {
ps.Syms.Add(sy)
}
}
ps.Scopes.Push(sy) // key diff from add..
useAST.Syms.Push(sy)
sy.AST = useAST.This
if ps.Trace.On {
ps.Trace.Out(ps, pr, RunAct, ast.TokReg.Start, ast.TokReg, ast, fmt.Sprintf("Act: Pushed New Sym: %v from path: %v = %v in node: %v", sy.String(), act.Path, nm, apath))
}
case PopScope:
sy := ps.Scopes.Pop()
if ps.Trace.On {
ps.Trace.Out(ps, pr, RunAct, ast.TokReg.Start, ast.TokReg, ast, fmt.Sprintf("Act: Popped Sym: %v in node: %v", sy.String(), apath))
}
case PopScopeReg:
sy := ps.Scopes.Pop()
sy.Region = ast.SrcReg // update source region to final -- select remains initial trigger one
if ps.Trace.On {
ps.Trace.Out(ps, pr, RunAct, ast.TokReg.Start, ast.TokReg, ast, fmt.Sprintf("Act: Popped Sym: %v in node: %v", sy.String(), apath))
}
case AddDetail:
sy := useAST.Syms.Top()
if sy != nil {
if sy.Detail == "" {
sy.Detail = nm
} else {
sy.Detail += " " + nm
}
if ps.Trace.On {
ps.Trace.Out(ps, pr, RunAct, ast.TokReg.Start, ast.TokReg, ast, fmt.Sprintf("Act: Added Detail: %v to Sym: %v in node: %v", nm, sy.String(), apath))
}
} else {
if ps.Trace.On {
ps.Trace.Out(ps, pr, RunAct, ast.TokReg.Start, ast.TokReg, ast, fmt.Sprintf("Act: Add Detail: %v ERROR -- symbol not found in node: %v", nm, apath))
}
}
case AddType:
scp := ps.Scopes.Top()
if scp == nil {
ps.Trace.Out(ps, pr, RunAct, ast.TokReg.Start, ast.TokReg, ast, fmt.Sprintf("Act: Add Type: %v ERROR -- requires current scope -- none set in node: %v", nm, apath))
return false
}
for i := range nms {
n := nms[i]
if n == "" || n == "_" { // go special case..
continue
}
ty := syms.NewType(n, syms.Unknown)
ty.Filename = ps.Src.Filename
ty.Region = ast.SrcReg
ty.AST = useAST.This
ty.AddScopesStack(ps.Scopes)
scp.Types.Add(ty)
if ps.Trace.On {
ps.Trace.Out(ps, pr, RunAct, ast.TokReg.Start, ast.TokReg, ast, fmt.Sprintf("Act: Added type: %v from path: %v = %v in node: %v", ty.String(), act.Path, n, apath))
}
}
}
return true
}
///////////////////////////////////////////////////////////////////////
// Non-parsing functions
// Find looks for rules in the tree that contain given string in Rule or Name fields
func (pr *Rule) Find(find string) []*Rule {
var res []*Rule
for k := range pr.All() {
pri := k.(*Rule)
if strings.Contains(pri.Rule, find) || strings.Contains(pri.Name, find) {
res = append(res, pri)
}
}
return res
}
// WriteGrammar outputs the parser rules as a formatted grammar in a BNF-like format
// it is called recursively
func (pr *Rule) WriteGrammar(writer io.Writer, depth int) {
if tree.IsRoot(pr) {
for _, k := range pr.Children {
pri := k.(*Rule)
pri.WriteGrammar(writer, depth)
}
} else {
ind := indent.Tabs(depth)
nmstr := pr.Name
if pr.Off {
nmstr = "// OFF: " + nmstr
}
if pr.Desc != "" {
fmt.Fprintf(writer, "%v// %v %v \n", ind, nmstr, pr.Desc)
}
if pr.IsGroup() {
fmt.Fprintf(writer, "%v%v {\n", ind, nmstr)
w := tabwriter.NewWriter(writer, 4, 4, 2, ' ', 0)
for _, k := range pr.Children {
pri := k.(*Rule)
pri.WriteGrammar(w, depth+1)
}
w.Flush()
fmt.Fprintf(writer, "%v}\n", ind)
} else {
astr := ""
switch pr.AST {
case AddAST:
astr = "+AST"
case SubAST:
astr = "_AST"
case AnchorAST:
astr = ">AST"
case AnchorFirstAST:
astr = ">1AST"
}
fmt.Fprintf(writer, "%v%v:\t%v\t%v\n", ind, nmstr, pr.Rule, astr)
if len(pr.Acts) > 0 {
fmt.Fprintf(writer, "%v--->Acts:%v\n", ind, pr.Acts.String())
}
}
}
}
// findPath returns the node at the given path relative to this node, as
// [tree.NodeBase.FindPath] does, except that a name specifies the first
// child of the name: the names of AST nodes are not unique (they are the
// names of their rules), and FindPath finds any child of a name.
func (ast *AST) findPath(path string) *AST {
cur := ast
for pe := range strings.SplitSeq(strings.TrimSpace(path), "/") {
if pe == "" {
continue
}
var idx int
if pe[0] == '[' && pe[len(pe)-1] == ']' {
i, err := strconv.Atoi(pe[1 : len(pe)-1])
if err != nil {
return nil
}
if i < 0 {
i += len(cur.Children)
}
idx = i
} else {
idx = slices.IndexFunc(cur.Children, func(k tree.Node) bool { return k.AsTree().Name == pe })
}
if idx < 0 || idx >= len(cur.Children) {
return nil
}
cur = cur.ChildAST(idx)
}
return cur
}
// listSiblings returns the siblings of the given node of a path ending in
// "...": the nodes of the same name that follow it in a comma-separated
// list, as the other names of a, b, c in a, b, c := x, y, z.
func listSiblings(ps *State, nd *AST) []tree.Node {
var sibs []tree.Node
par := nd.Parent
if par == nil {
return nil
}
kids := par.AsTree().Children
prev := nd
for _, k := range kids[nd.IndexInParent()+1:] {
if k.AsTree().Name != nd.Name {
break
}
pos, ok := ps.Src.ValidTokenPos(prev.TokReg.End)
if !ok || ps.Src.LexAt(pos).Token.Token != token.PunctSepComma {
break
}
sibs = append(sibs, k)
prev = k.(*AST)
}
return sibs
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package parser
import (
"fmt"
"strings"
"cogentcore.org/core/text/parse/lexer"
"cogentcore.org/core/text/parse/syms"
"cogentcore.org/core/text/textpos"
"cogentcore.org/core/text/token"
)
// State is the state maintained for parsing
type State struct {
// source and lexed version of source we're parsing
Src *lexer.File `display:"no-inline"`
// tracing for this parser
Trace TraceOptions
// root of the AST abstract syntax tree we're updating
AST *AST
// symbol map that everything gets added to from current file of parsing -- typically best for subsequent management to just have a single outer-most scoping symbol here (e.g., in Go it is the package), and then everything is a child under that
Syms syms.SymMap
// stack of scope(s) added to FileSyms e.g., package, library, module-level elements of which this file is a part -- these are reset at the start and must be added by parsing actions within the file itself
Scopes syms.SymStack
// the current lex token position
Pos textpos.Pos
// any error messages accumulated during parsing specifically
Errs lexer.ErrorList `display:"no-inline"`
// rules that matched and ran at each point, in 1-to-1 correspondence with the Src.Lex tokens for the lines and char pos dims
Matches [][]MatchStack `display:"no-inline"`
// nonMatches are the rules that did not match at each point, in 1-to-1
// correspondence with the Src.Lex tokens like Matches, for the scopes
// that start there.
nonMatches [][]nonMatchSet
// nonMatched has the positions in nonMatches that have rules,
// which are cleared by [State.ResetNonMatches].
nonMatched []textpos.Pos
// matchBuf and nonMatchBuf are the buffers for Matches and nonMatches,
// which are reused for the next parse, typically of the same file after
// an edit, along with the slices for each position (see [State.AllocRules]).
matchBuf []MatchStack
nonMatchBuf []nonMatchSet
// stack for context-sensitive rules
Stack lexer.Stack `display:"no-inline"`
}
// Init initializes the state at start of parsing
func (ps *State) Init(src *lexer.File, ast *AST) {
// fmt.Println("in init")
// if ps.Src != nil {
// fmt.Println("was:", ps.Src.Filename)
// }
// if src != nil {
// fmt.Println("new:", src.Filename)
// }
ps.Src = src
if ps.AST != nil && ps.AST.This != nil {
// fmt.Println("deleting old ast")
ps.AST.DeleteChildren()
}
ps.AST = ast
if ps.AST != nil && ps.AST.This != nil {
// fmt.Println("deleting new ast")
ps.AST.DeleteChildren()
}
ps.ClearAST()
ps.Syms.Reset()
ps.Scopes.Reset()
ps.Stack.Reset()
if ps.Src != nil {
ps.Pos, _ = ps.Src.ValidTokenPos(textpos.PosZero)
}
ps.Errs.Reset()
ps.Trace.Init()
ps.AllocRules()
}
func (ps *State) ClearAST() {
ps.Syms.ClearAST()
ps.Scopes.ClearAST()
}
func (ps *State) Destroy() {
if ps.AST != nil && ps.AST.This != nil {
ps.AST.DeleteChildren()
}
ps.AST = nil
ps.ClearAST()
ps.Syms.Reset()
ps.Scopes.Reset()
ps.Stack.Reset()
if ps.Src != nil {
ps.Pos, _ = ps.Src.ValidTokenPos(textpos.PosZero)
}
ps.Errs.Reset()
ps.Trace.Init()
}
// AllocRules allocate the match, nonmatch rule state in correspondence with the src state
func (ps *State) AllocRules() {
nlines := ps.Src.NLines()
if nlines == 0 {
return
}
if len(ps.Src.Lexs) != nlines {
return
}
ntot := 0
for ln := range nlines {
ntot += len(ps.Src.Lexs[ln])
}
// We make one allocation for all of the lines, and reuse the buffers
// of the previous parse when they are big enough, truncating the slices
// of each position so that their capacity is also reused.
if cap(ps.matchBuf) < ntot {
ps.matchBuf = make([]MatchStack, ntot, ntot+ntot/4)
ps.nonMatchBuf = make([]nonMatchSet, ntot, ntot+ntot/4)
} else {
ps.matchBuf = ps.matchBuf[:ntot]
ps.nonMatchBuf = ps.nonMatchBuf[:ntot]
for i := range ntot {
ps.matchBuf[i] = ps.matchBuf[i][:0]
nm := &ps.nonMatchBuf[i]
nm.rules = nm.rules[:0]
nm.endLines = nm.endLines[:0]
nm.endChars = nm.endChars[:0]
}
}
if cap(ps.Matches) < nlines {
ps.Matches = make([][]MatchStack, nlines, nlines+nlines/4)
ps.nonMatches = make([][]nonMatchSet, nlines, nlines+nlines/4)
} else {
ps.Matches = ps.Matches[:nlines]
ps.nonMatches = ps.nonMatches[:nlines]
}
ps.nonMatched = ps.nonMatched[:0]
off := 0
for ln := range nlines {
sz := len(ps.Src.Lexs[ln])
ps.Matches[ln] = ps.matchBuf[off : off+sz : off+sz]
ps.nonMatches[ln] = ps.nonMatchBuf[off : off+sz : off+sz]
off += sz
}
}
// Error adds a parsing error at given lex token position
func (ps *State) Error(pos textpos.Pos, msg string, rule *Rule) {
if pos != textpos.PosZero {
pos = ps.Src.TokenSrcPos(pos).Start
}
e := ps.Errs.Add(pos, ps.Src.Filename, msg, ps.Src.SrcLine(pos.Line), rule)
if isGUIActive() {
erstr := e.Report(ps.Src.BasePath, lexer.ShowSrc, lexer.ShowRule)
fmt.Fprintln(ps.Trace.OutWrite, "ERROR: "+erstr)
}
}
// AtEof returns true if current position is at end of file -- this includes
// common situation where it is just at the very last token
func (ps *State) AtEof() bool {
if ps.Pos.Line >= ps.Src.NLines() {
return true
}
_, ok := ps.Src.ValidTokenPos(ps.Pos)
return !ok
}
// AtEofNext returns true if current OR NEXT position is at end of file -- this includes
// common situation where it is just at the very last token
func (ps *State) AtEofNext() bool {
if ps.AtEof() {
return true
}
return ps.Pos.Line == ps.Src.NLines()-1
}
// GotoEof sets current position at EOF
func (ps *State) GotoEof() {
ps.Pos.Line = ps.Src.NLines()
ps.Pos.Char = 0
}
// NextSrcLine returns the next line of text
func (ps *State) NextSrcLine() string {
sp, ok := ps.Src.ValidTokenPos(ps.Pos)
if !ok {
return ""
}
ep := sp
ep.Char = ps.Src.NTokens(ep.Line)
if ep.Char == sp.Char+1 { // only one
nep, ok := ps.Src.ValidTokenPos(ep)
if ok {
ep = nep
ep.Char = ps.Src.NTokens(ep.Line)
}
}
reg := textpos.Region{Start: sp, End: ep}
return ps.Src.TokenRegSrc(reg)
}
// MatchLex is our optimized matcher method, matching tkey depth as well
func (ps *State) MatchLex(lx *lexer.Lex, tkey token.KeyToken, isCat, isSubCat bool, cp textpos.Pos) bool {
if lx.Token.Depth != tkey.Depth {
return false
}
if lx.Token.Token != tkey.Token && (!isCat || lx.Token.Token.Cat() != tkey.Token) && (!isSubCat || lx.Token.Token.SubCat() != tkey.Token) {
return false
}
if tkey.Key == "" {
return true
}
return tkey.Key == lx.Token.Key
}
// FindToken looks for token in given region, returns position where found, false if not.
// Only matches when depth is same as at reg.Start start at the start of the search.
// All positions in token indexes.
func (ps *State) FindToken(tkey token.KeyToken, reg textpos.Region) (textpos.Pos, bool) {
// prf := profile.Start("FindToken")
// defer prf.End()
cp, ok := ps.Src.ValidTokenPos(reg.Start)
if !ok {
return cp, false
}
tok := tkey.Token
isCat := tok.Cat() == tok
isSubCat := tok.SubCat() == tok
for cp.IsLess(reg.End) {
lx := ps.Src.LexAt(cp)
if ps.MatchLex(lx, tkey, isCat, isSubCat, cp) {
return cp, true
}
cp, ok = ps.Src.NextTokenPos(cp)
if !ok {
return cp, false
}
}
return cp, false
}
// MatchToken returns true if token matches at given position -- must be
// a valid position!
func (ps *State) MatchToken(tkey token.KeyToken, pos textpos.Pos) bool {
tok := tkey.Token
isCat := tok.Cat() == tok
isSubCat := tok.SubCat() == tok
lx := ps.Src.LexAt(pos)
tkey.Depth = lx.Token.Depth
return ps.MatchLex(lx, tkey, isCat, isSubCat, pos)
}
// FindTokenReverse looks *backwards* for token in given region, with same depth as reg.End-1 end
// where the search starts. Returns position where found, false if not.
// Automatically deals with possible confusion with unary operators -- if there are two
// ambiguous operators in a row, automatically gets the first one. This is mainly / only used for
// binary operator expressions (mathematical binary operators).
// All positions are in token indexes.
func (ps *State) FindTokenReverse(tkey token.KeyToken, reg textpos.Region) (textpos.Pos, bool) {
// prf := profile.Start("FindTokenReverse")
// defer prf.End()
cp, ok := ps.Src.PrevTokenPos(reg.End)
if !ok {
return cp, false
}
tok := tkey.Token
isCat := tok.Cat() == tok
isSubCat := tok.SubCat() == tok
isAmbigUnary := tok.IsAmbigUnaryOp()
for reg.Start.IsLess(cp) || cp == reg.Start {
lx := ps.Src.LexAt(cp)
if ps.MatchLex(lx, tkey, isCat, isSubCat, cp) {
if isAmbigUnary { // make sure immed prior is not also!
pp, ok := ps.Src.PrevTokenPos(cp)
if ok {
pt := ps.Src.Token(pp)
if tok == token.OpMathMul {
if !pt.Token.IsUnaryOp() {
return cp, true
}
} else {
if !pt.Token.IsAmbigUnaryOp() {
return cp, true
}
}
// otherwise we don't match -- cannot match second opr
} else {
return cp, true
}
} else {
return cp, true
}
}
ok := false
cp, ok = ps.Src.PrevTokenPos(cp)
if !ok {
return cp, false
}
}
return cp, false
}
// AddAST adds a child AST node to given parent AST node
func (ps *State) AddAST(parAST *AST, rule string, reg textpos.Region) *AST {
chAST := NewAST(parAST)
chAST.SetName(rule)
chAST.SetTokReg(reg, ps.Src)
return chAST
}
///////////////////////////////////////////////////////////////////////////
// Match State, Stack
// MatchState holds state info for rules that matched, recorded at starting position of match
type MatchState struct {
// rule that either matched or ran here
Rule *Rule
// scope for match
Scope textpos.Region
// regions of match for each sub-region
Regs Matches
}
// String is fmt.Stringer
func (rs MatchState) String() string {
if rs.Rule == nil {
return ""
}
return fmt.Sprintf("%v%v", rs.Rule.Name, rs.Scope)
}
// MatchStack is the stack of rules that matched or ran for each token point
type MatchStack []MatchState
// Add given rule to stack
func (rs *MatchStack) Add(pr *Rule, scope textpos.Region, regs Matches) {
*rs = append(*rs, MatchState{Rule: pr, Scope: scope, Regs: regs})
}
// Find looks for given rule and scope on the stack
func (rs *MatchStack) Find(pr *Rule, scope textpos.Region) (*MatchState, bool) {
s := *rs
for i := range s {
// We only take the address of a match, which is costly in JavaScript.
if s[i].Rule == pr && s[i].Scope == scope {
return &s[i], true
}
}
return nil, false
}
// AddMatch adds given rule to rule stack at given scope
func (ps *State) AddMatch(pr *Rule, scope textpos.Region, regs Matches) {
rs := &ps.Matches[scope.Start.Line][scope.Start.Char]
rs.Add(pr, scope, regs)
}
// IsMatch looks for rule at given scope in list of matches, if found
// returns match state info
func (ps *State) IsMatch(pr *Rule, scope textpos.Region) (*MatchState, bool) {
rs := &ps.Matches[scope.Start.Line][scope.Start.Char]
sz := len(*rs)
if sz == 0 {
return nil, false
}
return rs.Find(pr, scope)
}
// RuleString returns the rule info for entire source -- if full
// then it includes the full stack at each point -- otherwise just the top
// of stack
func (ps *State) RuleString(full bool) string {
var txt strings.Builder
nlines := ps.Src.NLines()
for ln := range nlines {
sz := len(ps.Matches[ln])
if sz == 0 {
txt.WriteString("\n")
} else {
for ch := range sz {
rs := ps.Matches[ln][ch]
sd := len(rs)
txt.WriteString(` "`)
txt.WriteString(string(ps.Src.TokenSrc(textpos.Pos{Line: ln, Char: ch})))
txt.WriteString(`"`)
if sd == 0 {
txt.WriteString("-")
} else {
if !full {
txt.WriteString(rs[sd-1].String())
} else {
fmt.Fprintf(&txt, "[%v: ", sd)
for i := range sd {
txt.WriteString(rs[i].String())
}
txt.WriteString("]")
}
}
}
txt.WriteString("\n")
}
}
return txt.String()
}
///////////////////////////////////////////////////////////////////////////
// NonMatch
// nonMatchSet has the rules that did not match for the scopes that start at
// its position in [State.nonMatches], with the line and character of the end
// of each scope. These are in separate slices of basic types, which are
// faster to search than a slice of structs, especially in JavaScript.
type nonMatchSet struct {
rules []*Rule
endLines []int
endChars []int
}
// nonMatchesAt returns the non-matching rules at the start of the given
// scope, or nil if it is outside of the source.
func (ps *State) nonMatchesAt(scope textpos.Region) *nonMatchSet {
ln, ch := scope.Start.Line, scope.Start.Char
if ln < 0 || ln >= len(ps.nonMatches) || ch < 0 || ch >= len(ps.nonMatches[ln]) {
return nil
}
return &ps.nonMatches[ln][ch]
}
// AddNonMatch adds given rule to non-matching rule set for this scope
func (ps *State) AddNonMatch(scope textpos.Region, pr *Rule) {
nm := ps.nonMatchesAt(scope)
if nm == nil {
return
}
if len(nm.rules) == 0 {
ps.nonMatched = append(ps.nonMatched, scope.Start)
}
nm.rules = append(nm.rules, pr)
nm.endLines = append(nm.endLines, scope.End.Line)
nm.endChars = append(nm.endChars, scope.End.Char)
}
// IsNonMatch looks for rule in nonmatch list at given scope
func (ps *State) IsNonMatch(scope textpos.Region, pr *Rule) bool {
nm := ps.nonMatchesAt(scope)
if nm == nil {
return false
}
eln, ech := scope.End.Line, scope.End.Char
endLines, endChars := nm.endLines, nm.endChars
for i, r := range nm.rules {
if r == pr && endLines[i] == eln && endChars[i] == ech {
return true
}
}
return false
}
// ResetNonMatches resets the non-matching rules -- do after every EOS
func (ps *State) ResetNonMatches() {
for _, p := range ps.nonMatched {
nm := &ps.nonMatches[p.Line][p.Char]
nm.rules = nm.rules[:0]
nm.endLines = nm.endLines[:0]
nm.endChars = nm.endChars[:0]
}
ps.nonMatched = ps.nonMatched[:0]
}
///////////////////////////////////////////////////////////////////////////
// Symbol management
// FindNameScoped searches top-down in the stack for something with the given name
// in symbols that are of subcategory token.NameScope (i.e., namespace, module, package, library)
// also looks in ps.Syms if not found in Scope stack.
func (ps *State) FindNameScoped(nm string) (*syms.Symbol, bool) {
sy, has := ps.Scopes.FindNameScoped(nm)
if has {
return sy, has
}
return ps.Syms.FindNameScoped(nm)
}
// FindNameTopScope searches only in top of current scope for something
// with the given name in symbols
// also looks in ps.Syms if not found in Scope stack.
func (ps *State) FindNameTopScope(nm string) (*syms.Symbol, bool) {
sy := ps.Scopes.Top()
if sy == nil {
return nil, false
}
chs, has := sy.Children[nm]
return chs, has
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package parser
import (
"fmt"
"os"
"slices"
"strings"
"cogentcore.org/core/text/textpos"
)
// TraceOptions provides options for debugging / monitoring the rule matching and execution process
type TraceOptions struct {
// perform tracing
On bool
// trace specific named rules here (space separated) -- if blank, then all rules are traced
Rules string `width:"50"`
// trace full rule matches -- when a rule fully matches
Match bool
// trace sub-rule matches -- when the parts of each rule match
SubMatch bool
// trace sub-rule non-matches -- why a rule doesn't match -- which terminates the matching process at first non-match (can be a lot of info)
NoMatch bool
// trace progress running through each of the sub-rules when a rule has matched and is 'running'
Run bool
// trace actions performed by running rules
RunAct bool
// if true, shows the full scope source for every trace statement
ScopeSrc bool
// for the ParseOut display, whether to display the full stack of rules at each position, or just the deepest one
FullStackOut bool
// list of rules
RulesList []string `display:"-" json:"-" xml:"-"`
// trace output is written here, connected via os.Pipe to OutRead
OutWrite *os.File `display:"-" json:"-" xml:"-"`
// trace output is read here; can connect this using [textcore.OutputBuffer] to monitor tracing output
OutRead *os.File `display:"-" json:"-" xml:"-"`
}
// Init intializes tracer after any changes -- opens pipe if not already open
func (pt *TraceOptions) Init() {
if pt.Rules == "" {
pt.RulesList = nil
} else {
pt.RulesList = strings.Split(pt.Rules, " ")
}
}
// FullOn sets all options on
func (pt *TraceOptions) FullOn() {
pt.On = true
pt.Match = true
pt.SubMatch = true
pt.NoMatch = true
pt.Run = true
pt.RunAct = true
pt.ScopeSrc = true
}
// PipeOut sets output to a pipe for monitoring (OutWrite -> OutRead)
func (pt *TraceOptions) PipeOut() {
if pt.OutWrite == nil {
pt.OutRead, pt.OutWrite, _ = os.Pipe() // seriously, does this ever fail?
}
}
// Stdout sets [TraceOptions.OutWrite] to [os.Stdout]
func (pt *TraceOptions) Stdout() {
pt.OutWrite = os.Stdout
}
// CheckRule checks if given rule should be traced
func (pt *TraceOptions) CheckRule(rule string) bool {
if len(pt.RulesList) == 0 {
if pt.Rules != "" {
pt.Init()
if len(pt.RulesList) == 0 {
return true
}
} else {
return true
}
}
return slices.Contains(pt.RulesList, rule)
}
// Out outputs a trace message -- returns true if actually output
func (pt *TraceOptions) Out(ps *State, pr *Rule, step Steps, pos textpos.Pos, scope textpos.Region, ast *AST, msg string) bool {
if !pt.On {
return false
}
if !pt.CheckRule(pr.Name) {
return false
}
switch step {
case Match:
if !pt.Match {
return false
}
case SubMatch:
if !pt.SubMatch {
return false
}
case NoMatch:
if !pt.NoMatch {
return false
}
case Run:
if !pt.Run {
return false
}
case RunAct:
if !pt.RunAct {
return false
}
}
tokSrc := pos.String() + `"` + string(ps.Src.TokenSrc(pos)) + `"`
plev := ast.ParentLevel(ps.AST)
var ind strings.Builder
for range plev {
ind.WriteString("\t")
}
fmt.Fprintf(pt.OutWrite, "%v%v:\t %v\t %v\t tok: %v\t scope: %v\t ast: %v\n", ind.String(), pr.Name, step, msg, tokSrc, scope, ast.Path())
if pt.ScopeSrc {
scopeSrc := ps.Src.TokenRegSrc(scope)
fmt.Fprintf(pt.OutWrite, "%v\t%v\n", ind.String(), scopeSrc)
}
return true
}
// CopyOpts copies just the options
func (pt *TraceOptions) CopyOpts(ot *TraceOptions) {
pt.On = ot.On
pt.Rules = ot.Rules
pt.Match = ot.Match
pt.SubMatch = ot.SubMatch
pt.NoMatch = ot.NoMatch
pt.Run = ot.Run
pt.RunAct = ot.RunAct
pt.ScopeSrc = ot.ScopeSrc
}
// Steps are the different steps of the parsing processing
type Steps int32 //enums:enum
// The parsing steps
const (
// Match happens when a rule matches
Match Steps = iota
// SubMatch is when a sub-rule within a rule matches
SubMatch
// NoMatch is when the rule fails to match (recorded at first non-match, which terminates
// matching process
NoMatch
// Run is when the rule is running and iterating through its sub-rules
Run
// RunAct is when the rule is running and performing actions
RunAct
)
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package syms
import (
"log"
"os"
"os/user"
"path/filepath"
"strings"
"time"
"cogentcore.org/core/base/fileinfo"
"cogentcore.org/core/base/fsx"
)
// ParseCacheDir returns the parse cache directory for given language, and ensures that it exists.
func ParseCacheDir(lang fileinfo.Known) (string, error) {
ucdir, err := os.UserCacheDir()
if err != nil {
return "", err
}
cdir := filepath.Join(filepath.Join(ucdir, "Cogent Core", "parse"), lang.String())
err = os.MkdirAll(cdir, 0775)
if err != nil {
log.Printf("ParseCacheDir: cache not available: %v\n", err)
}
return cdir, err
}
// GoRelPath returns the GOPATH or GOROOT relative path for given filename
func GoRelPath(filename string) (string, error) {
absfn, err := filepath.Abs(filename)
if err != nil {
return absfn, err
}
relfn := absfn
got := false
for _, srcDir := range fsx.GoSrcDirs() {
if after, ok := strings.CutPrefix(absfn, srcDir); ok {
relfn = after
got = true
break
}
}
if got {
return relfn, nil
}
usr, err := user.Current()
if err != nil {
return relfn, err
}
homedir := usr.HomeDir
if after, ok := strings.CutPrefix(absfn, homedir); ok {
relfn = after
}
return relfn, nil
}
// CacheFilename returns the filename to use for cache file for given filename
func CacheFilename(lang fileinfo.Known, filename string) (string, error) {
cdir, err := ParseCacheDir(lang)
if err != nil {
return "", err
}
relfn, err := GoRelPath(filename)
if err != nil {
return "", err
}
path := relfn
if filepath.Ext(path) != "" { // if it has an ext, it is not a dir..
path, _ = filepath.Split(path)
}
path = filepath.Clean(path)
if path[0] == filepath.Separator {
path = path[1:]
}
path = strings.ReplaceAll(path, string(filepath.Separator), "%")
path = filepath.Join(cdir, path)
return path, nil
}
// SaveSymCache saves cache of symbols starting with given symbol
// (typically a package, module, library), which is at given
// filename
func SaveSymCache(sy *Symbol, lang fileinfo.Known, filename string) error {
cfile, err := CacheFilename(lang, filename)
if err != nil {
return err
}
return sy.SaveJSON(cfile)
}
// SaveSymDoc saves doc file of syms -- for double-checking contents etc
func SaveSymDoc(sy *Symbol, lang fileinfo.Known, filename string) error {
cfile, err := CacheFilename(lang, filename)
if err != nil {
return err
}
cfile += ".doc"
ofl, err := os.Create(cfile)
if err != nil {
return err
}
sy.WriteDoc(ofl, 0)
return nil
}
// OpenSymCache opens cache of symbols into given symbol
// (typically a package, module, library), which is at given
// filename -- returns time stamp when cache was last saved
func OpenSymCache(lang fileinfo.Known, filename string) (*Symbol, time.Time, error) {
cfile, err := CacheFilename(lang, filename)
if err != nil {
return nil, time.Time{}, err
}
info, err := os.Stat(cfile)
if os.IsNotExist(err) {
return nil, time.Time{}, err
}
sy := &Symbol{}
err = sy.OpenJSON(cfile)
return sy, info.ModTime(), err
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package syms
import (
"strings"
"cogentcore.org/core/icons"
"cogentcore.org/core/text/parse/complete"
"cogentcore.org/core/text/token"
)
// AddCompleteSyms adds given symbols as matches in the given match data
// Scope is e.g., type name (label only)
func AddCompleteSyms(sym SymMap, scope string, md *complete.Matches) {
if len(sym) == 0 {
return
}
sys := sym.Slice(true) // sorted
for _, sy := range sys {
if sy.Name[0] == '_' { // internal / import
continue
}
nm := sy.Name
lbl := sy.Label()
if sy.Kind.SubCat() == token.NameFunction {
nm += "()"
}
if scope != "" {
lbl = lbl + " (" + scope + ".)"
}
c := complete.Completion{Text: nm, Label: lbl, Icon: sy.Kind.Icon(), Desc: sy.Detail}
// fmt.Printf("nm: %v kind: %v icon: %v\n", nm, sy.Kind, c.Icon)
md.Matches = append(md.Matches, c)
}
}
// AddCompleteTypeNames adds names from given type as matches in the given match data
// Scope is e.g., type name (label only), and seed is prefix filter for names
func AddCompleteTypeNames(typ *Type, scope, seed string, md *complete.Matches) {
md.Seed = seed
for _, te := range typ.Els {
nm := te.Name
if seed != "" {
if !strings.HasPrefix(nm, seed) {
continue
}
}
lbl := nm
if scope != "" {
lbl = lbl + " (" + scope + ".)"
}
icon := icons.Field // assume..
c := complete.Completion{Text: nm, Label: lbl, Icon: icon}
// fmt.Printf("nm: %v kind: %v icon: %v\n", nm, sy.Kind, c.Icon)
md.Matches = append(md.Matches, c)
}
for _, mt := range typ.Meths {
nm := mt.Name
if seed != "" {
if !strings.HasPrefix(nm, seed) {
continue
}
}
lbl := nm + "(" + mt.ArgString() + ") " + mt.ReturnString()
if scope != "" {
lbl = lbl + " (" + scope + ".)"
}
nm += "()"
icon := icons.Method // assume..
c := complete.Completion{Text: nm, Label: lbl, Icon: icon}
// fmt.Printf("nm: %v kind: %v icon: %v\n", nm, sy.Kind, c.Icon)
md.Matches = append(md.Matches, c)
}
}
// AddCompleteSymsPrefix adds subset of symbols that match seed prefix to given match data
func AddCompleteSymsPrefix(sym SymMap, scope, seed string, md *complete.Matches) {
matches := &sym
if seed != "" {
matches = &SymMap{}
md.Seed = seed
sym.FindNamePrefixRecursive(seed, matches)
}
AddCompleteSyms(*matches, scope, md)
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package syms
//go:generate core generate
import (
"reflect"
)
// Kinds is a complete set of basic type categories and sub(sub..) categories -- these
// describe builtin types -- user-defined types must be some combination / version
// of these builtin types.
//
// See: https://en.wikipedia.org/wiki/List_of_data_structures
type Kinds int32 //enums:enum
// CatMap is the map into the category level for each kind
var CatMap map[Kinds]Kinds
// SubCatMap is the map into the sub-category level for each kind
var SubCatMap map[Kinds]Kinds
// Sub2CatMap is the map into the sub2-category level for each kind
var Sub2CatMap map[Kinds]Kinds
func init() {
InitCatMap()
InitSubCatMap()
InitSub2CatMap()
}
// Cat returns the category that a given kind lives in, using CatMap
func (tk Kinds) Cat() Kinds {
return CatMap[tk]
}
// SubCat returns the sub-category that a given kind lives in, using SubCatMap
func (tk Kinds) SubCat() Kinds {
return SubCatMap[tk]
}
// Sub2Cat returns the sub2-category that a given kind lives in, using Sub2CatMap
func (tk Kinds) Sub2Cat() Kinds {
return Sub2CatMap[tk]
}
// IsCat returns true if this is a category-level kind
func (tk Kinds) IsCat() bool {
return tk.Cat() == tk
}
// IsSubCat returns true if this is a sub-category-level kind
func (tk Kinds) IsSubCat() bool {
return tk.SubCat() == tk
}
// IsSub2Cat returns true if this is a sub2-category-level kind
func (tk Kinds) IsSub2Cat() bool {
return tk.Sub2Cat() == tk
}
func (tk Kinds) InCat(other Kinds) bool {
return tk.Cat() == other.Cat()
}
func (tk Kinds) InSubCat(other Kinds) bool {
return tk.SubCat() == other.SubCat()
}
func (tk Kinds) InSub2Cat(other Kinds) bool {
return tk.Sub2Cat() == other.Sub2Cat()
}
func (tk Kinds) IsPtr() bool {
return tk >= Ptr && tk <= UnsafePtr
}
func (tk Kinds) IsPrimitiveNonPtr() bool {
return tk.Cat() == Primitive && !tk.IsPtr()
}
// The list of Kinds
const (
// Unknown is the nil kind -- kinds should be known in general..
Unknown Kinds = iota
// Category: Primitive, in the strict sense of low-level, atomic, small, fixed size
Primitive
// SubCat: Numeric
Numeric
// Sub2Cat: Integer
Integer
// Sub3Cat: Signed -- track this using properties in types, not using Sub3 level
Signed
Int
Int8
Int16
Int32
Int64
// Sub3Cat: Unsigned
Unsigned
Uint
Uint8
Uint16
Uint32
Uint64
Uintptr // generic raw pointer data value -- see also Ptr, Ref for more semantic cases
// Sub3Cat: Ptr, Ref etc -- in Numeric, Integer even though in some languages
// pointer arithmetic might not be allowed, for some cases, etc
Ptr // pointer -- element is what we point to (kind of a composite type)
Ref // reference -- element is what we refer to
UnsafePtr // for case where these are distinguished from Ptr (Go) -- similar to Uintptr
// Sub2Cat: Fixed point -- could be under integer, but..
Fixed
Fixed26_6
Fixed16_6
Fixed0_32
// Sub2Cat: Floating point
Float
Float16
Float32
Float64
// Sub3Cat: Complex -- under floating point
Complex
Complex64
Complex128
// SubCat: Bool
Bool
// Category: Composite -- types composed of above primitive types
Composite
// SubCat: Tuple -- a fixed length 1d collection of elements that can be of any type
// Type.Els required for each element
Tuple
Range // a special kind of tuple for Python ranges
// SubCat: Array -- a fixed length 1d collection of same-type elements
// Type.Els has one element for type
Array
// SubCat: List -- a variable-length 1d collection of same-type elements
// This is Slice for Go
// Type.Els has one element for type
List
String // List of some type of char rep -- Type.Els is type, as all Lists
// SubCat: Matrix -- a twod collection of same-type elements
// has two Size values, one for each dimension
Matrix
// SubCat: Tensor -- an n-dimensional collection of same-type elements
// first element of Size is number of dimensions, rest are dimensions
Tensor
// SubCat: Map -- an associative array / hash map / dictionary
// Type.Els first el is key, second is type
Map
// SubCat: Set -- typically a degenerate form of hash map with no value
Set
FrozenSet // python's frozen set of fixed values
// SubCat: Struct -- like a tuple but with specific semantics in most languages
// Type.Els are the fields, and if there is an inheritance relationship these
// are put first with relevant identifiers -- in Go these are unnamed fields
Struct
Class
Object
// Chan: a channel (Go Specific)
Chan
// Category: Function -- types that are functions
// Type.Els are the params and return values in order, with Size[0] being number
// of params and Size[1] number of returns
Function
// SubCat: Func -- a standalone function
Func
// SubCat: Method -- a function with a specific receiver (e.g., on a Class in C++,
// or on any type in Go).
// First Type.Els is receiver param -- included in Size[0]
Method
// SubCat: Interface -- an abstract definition of a set of methods (in Go)
// Type.Els are the Methods with the receiver type missing or Unknown
Interface
)
// Cats are the categories of the kinds.
var Cats = []Kinds{
Unknown,
Primitive,
Composite,
Function,
KindsN,
}
// SubCats are the sub-categories of the kinds.
var SubCats = []Kinds{
Unknown,
Primitive,
Numeric,
Bool,
Composite,
Tuple,
Array,
List,
Matrix,
Tensor,
Map,
Set,
Struct,
Chan,
Function,
Func,
Method,
Interface,
KindsN,
}
// Sub2Cats are the second-level sub-categories of the kinds.
var Sub2Cats = []Kinds{
Unknown,
Primitive,
Numeric,
Integer,
Fixed,
Float,
Bool,
Composite,
Tuple,
Array,
List,
Matrix,
Tensor,
Map,
Set,
Struct,
Chan,
Function,
Func,
Method,
Interface,
KindsN,
}
// InitCatMap initializes the CatMap
func InitCatMap() {
if CatMap != nil {
return
}
CatMap = make(map[Kinds]Kinds, KindsN)
for tk := range KindsN {
for c := 1; c < len(Cats); c++ {
if tk < Cats[c] {
CatMap[tk] = Cats[c-1]
break
}
}
}
}
// InitSubCatMap initializes the SubCatMap
func InitSubCatMap() {
if SubCatMap != nil {
return
}
SubCatMap = make(map[Kinds]Kinds, KindsN)
for tk := range KindsN {
for c := 1; c < len(SubCats); c++ {
if tk < SubCats[c] {
SubCatMap[tk] = SubCats[c-1]
break
}
}
}
}
// InitSub2CatMap initializes the SubCatMap
func InitSub2CatMap() {
if Sub2CatMap != nil {
return
}
Sub2CatMap = make(map[Kinds]Kinds, KindsN)
for tk := range KindsN {
for c := 1; c < len(SubCats); c++ {
if tk < Sub2Cats[c] {
Sub2CatMap[tk] = Sub2Cats[c-1]
break
}
}
}
}
///////////////////////////////////////////////////////////////////////
// Reflect map
// ReflectKindMap maps reflect kinds to syms.Kinds
var ReflectKindMap = map[reflect.Kind]Kinds{
reflect.Invalid: Unknown,
reflect.Int: Int,
reflect.Int8: Int8,
reflect.Int16: Int16,
reflect.Int32: Int32,
reflect.Int64: Int64,
reflect.Uint: Uint,
reflect.Uint8: Uint8,
reflect.Uint16: Uint16,
reflect.Uint32: Uint32,
reflect.Uint64: Uint64,
reflect.Uintptr: Uintptr,
reflect.Float32: Float32,
reflect.Float64: Float64,
reflect.Complex64: Complex64,
reflect.Complex128: Complex128,
reflect.Bool: Bool,
reflect.Array: Array,
reflect.Chan: Chan,
reflect.Func: Func,
reflect.Interface: Interface,
reflect.Map: Map,
reflect.Pointer: Ptr,
reflect.Slice: List,
reflect.String: String,
reflect.Struct: Struct,
reflect.UnsafePointer: Ptr,
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package syms defines the symbols and their properties that
// are accumulated from a parsed file, and are then used for
// e.g., completion lookup, etc.
//
// We looked at several different standards for formats, types, etc:
//
// LSP: https://microsoft.github.io/language-server-protocol/specification
// useful to enable parse to act as an LSP server at some point.
// additional symbol kinds:
// https://github.com/Microsoft/language-server-protocol/issues/344
//
// See also: github.com/sourcegraph/sourcegraph
// and specifically: /cmd/frontend/graphqlbackend/search_symbols.go
// it seems to use https://github.com/universal-ctags/ctags
// for the raw data..
//
// Other relevant guidance comes from the go compiler system which is
// used extensively in github.com/mdemsky/gocode for example.
// In particular: go/types/scope.go type.go, and package.go contain the
// relevant data structures for how information is organized for
// compiled go packages, which have all this data cached and avail
// to be imported via the go/importer which returns a go/types/Package
// which in turn contains Scope's which in turn contain Objects that
// define the elements of the compiled language.
package syms
import (
"encoding/json"
"fmt"
"io"
"maps"
"os"
"strings"
"cogentcore.org/core/base/indent"
"cogentcore.org/core/text/textpos"
"cogentcore.org/core/text/token"
"cogentcore.org/core/tree"
)
// Symbol contains the information for everything about a given
// symbol that is created by parsing, and can be looked up.
// It corresponds to the LSP DocumentSymbol structure, and
// the Go Object type.
type Symbol struct {
// name of the symbol
Name string
// additional detail and specification of the symbol -- e.g. if a function, the signature of the function
Detail string
// lexical kind of symbol, using token.Tokens list
Kind token.Tokens
// Type name for this symbol -- if it is a type, this is its corresponding type representation -- if it is a variable then this is its type
Type string
// index for ordering children within a given scope, e.g., fields in a struct / class
Index int
// full filename / URI of source
Filename string
// region in source encompassing this item -- if = RegZero then this is a temp symbol and children are not added to it
Region textpos.Region
// region that should be selected when activated, etc
SelectReg textpos.Region
// relevant scoping / parent symbols, e.g., namespace, package, module, class, function, etc..
Scopes SymNames
// children of this symbol -- this includes e.g., methods and fields of classes / structs / types, and all elements within packages, etc
Children SymMap
// types defined within the scope of this symbol
Types TypeMap
// AST node that created this symbol -- only valid during parsing
AST tree.Node `json:"-" xml:"-"`
}
// NewSymbol returns a new symbol with the basic info filled in -- SelectReg defaults to Region
func NewSymbol(name string, kind token.Tokens, fname string, reg textpos.Region) *Symbol {
sy := &Symbol{Name: name, Kind: kind, Filename: fname, Region: reg, SelectReg: reg}
return sy
}
// CopyFromSrc copies all the source-related fields from other symbol
// (no Type, Types, or Children). AST is only copied if non-nil.
func (sy *Symbol) CopyFromSrc(cp *Symbol) {
sy.Detail = cp.Detail
sy.Kind = cp.Kind
sy.Index = cp.Index
sy.Filename = cp.Filename
sy.Region = cp.Region
sy.SelectReg = cp.SelectReg
// if cp.AST != nil {
// sy.AST = cp.AST
// }
}
// IsTemp returns true if this is temporary symbol that is used for scoping but is not
// otherwise permanently added to list of symbols. Indicated by Zero Region.
func (sy *Symbol) IsTemp() bool {
return sy.Region == textpos.RegionZero
}
// HasChildren returns true if this symbol has children
func (sy *Symbol) HasChildren() bool {
return len(sy.Children) > 0
}
// String satisfies fmt.Stringer interface
func (sy *Symbol) String() string {
return fmt.Sprintf("%v: %v (%v)", sy.Name, sy.Kind, sy.Region)
}
// Label satisfies core.Labeler interface -- nicer presentation label
func (sy *Symbol) Label() string {
lbl := sy.Name
switch {
case sy.Kind.SubCat() == token.NameFunction:
pi := strings.Index(sy.Detail, "(")
if pi >= 0 {
lbl += sy.Detail[pi:]
} else {
lbl += "()"
}
default:
if sy.Type != "" {
lbl += " (" + sy.Type + ")"
}
}
return lbl
}
// Clone returns a clone copy of this symbol.
// Does NOT copy the Children or Types -- caller can decide about that.
func (sy *Symbol) Clone() *Symbol {
nsy := &Symbol{Name: sy.Name, Detail: sy.Detail, Kind: sy.Kind, Type: sy.Type, Index: sy.Index, Filename: sy.Filename, Region: sy.Region, SelectReg: sy.SelectReg}
nsy.Scopes = sy.Scopes.Clone()
// nsy.AST = sy.AST
return nsy
}
// AddChild adds a child symbol, if this parent symbol is not temporary
// returns true if item name was added and NOT already on the map,
// and false if it was already or parent is temp.
// Always adds new symbol in any case.
// If parent symbol is of the NameType subcategory, then index of child is set
// to the size of this child map before adding.
func (sy *Symbol) AddChild(child *Symbol) bool {
// if sy.IsTemp() {
// return false
// }
sy.Children.Alloc()
_, on := sy.Children[child.Name]
idx := len(sy.Children)
child.Index = idx // always record index
sy.Children[child.Name] = child
return !on
}
// AllocScopes allocates scopes map if nil
func (sy *Symbol) AllocScopes() {
if sy.Scopes == nil {
sy.Scopes = make(SymNames)
}
}
// AddScopesMap adds a given scope element(s) from map to this Symbol.
// if add is true, add this symbol to those scopes if they are not temporary.
func (sy *Symbol) AddScopesMap(sm SymMap, add bool) {
if len(sm) == 0 {
return
}
sy.AllocScopes()
for _, s := range sm {
sy.Scopes[s.Kind] = s.Name
if add {
s.AddChild(sy)
}
}
}
// AddScopesStack adds a given scope element(s) from stack to this Symbol.
// Adds this symbol as a child to the top of the scopes if it is not temporary --
// returns true if so added.
func (sy *Symbol) AddScopesStack(ss SymStack) bool {
sz := len(ss)
if sz == 0 {
return false
}
sy.AllocScopes()
added := false
for i := range sz {
sc := ss[i]
sy.Scopes[sc.Kind] = sc.Name
if i == sz-1 {
added = sc.AddChild(sy)
}
}
return added
}
// FindAnyChildren finds children of this symbol using either
// direct children if those are present, or the type name if
// present -- used for completion routines. Adds to kids map.
// scope1, scope2 are used for looking up type name.
// If seed is non-empty it is used as a prefix for filtering children names.
// Returns false if no children were found.
func (sy *Symbol) FindAnyChildren(seed string, scope1, scope2 SymMap, kids *SymMap) bool {
sym := sy
if len(sym.Children) == 0 {
if sym.Type != "" {
tynm := sym.NonPtrTypeName()
if typ, got := scope1.FindNameScoped(tynm); got {
sym = typ
} else if typ, got := scope2.FindNameScoped(tynm); got {
sym = typ
} else {
return false
}
}
}
if seed != "" {
sym.Children.FindNamePrefixRecursive(seed, kids)
} else {
kids.CopyFrom(sym.Children, true) // srcIsNewer
}
return len(*kids) > 0
}
// NonPtrTypeName returns the name of the type without any leading * or &
func (sy *Symbol) NonPtrTypeName() string {
return strings.TrimPrefix(strings.TrimPrefix(sy.Type, "&"), "*")
}
// CopyFromScope copies the Children and Types from given other symbol
// for scopes (e.g., Go package), to merge with existing.
func (sy *Symbol) CopyFromScope(src *Symbol) {
sy.Children.CopyFrom(src.Children, false) // src is NOT newer
sy.Types.CopyFrom(src.Types, false) // src is NOT newer
}
// OpenJSON opens from a JSON-formatted file.
func (sy *Symbol) OpenJSON(filename string) error {
b, err := os.ReadFile(filename)
if err != nil {
return err
}
return json.Unmarshal(b, sy)
}
// SaveJSON saves to a JSON-formatted file.
func (sy *Symbol) SaveJSON(filename string) error {
b, err := json.MarshalIndent(sy, "", " ")
if err != nil {
return err
}
err = os.WriteFile(filename, b, 0644)
return err
}
// WriteDoc writes basic doc info
func (sy *Symbol) WriteDoc(out io.Writer, depth int) {
ind := indent.Tabs(depth)
fmt.Fprintf(out, "%v%v: %v", ind, sy.Name, sy.Kind)
if sy.Type != "" {
fmt.Fprintf(out, " (%v)", sy.Type)
}
if len(sy.Types) > 0 {
fmt.Fprint(out, " Types: {\n")
sy.Types.WriteDoc(out, depth+1)
fmt.Fprintf(out, "%v}\n", ind)
}
if sy.HasChildren() {
fmt.Fprint(out, " {\n")
sy.Children.WriteDoc(out, depth+1)
fmt.Fprintf(out, "%v}\n", ind)
} else {
fmt.Fprint(out, "\n")
}
}
// ClearAST sets the AST pointers to nil for all symbols in this one.
// otherwise the AST memory is never freed and can get quite large.
func (sy *Symbol) ClearAST() {
sy.AST = nil
sy.Children.ClearAST()
sy.Types.ClearAST()
}
// ClearAST sets the AST pointers to nil for all symbols.
// otherwise the AST memory is never freed and can get quite large.
func (sm *SymMap) ClearAST() {
for _, ss := range *sm {
ss.ClearAST()
}
}
// ClearAST sets the AST pointers to nil for all symbols in this one.
// otherwise the AST memory is never freed and can get quite large.
func (ty *Type) ClearAST() {
ty.AST = nil
ty.Meths.ClearAST()
}
// ClearAST sets the AST pointers to nil for all symbols.
// otherwise the AST memory is never freed and can get quite large.
func (tm *TypeMap) ClearAST() {
for _, ty := range *tm {
ty.ClearAST()
}
}
//////////////////////////////////////////////////////////////////
// SymNames
// SymNames provides a map-list of symbol names, indexed by their token kinds.
// Used primarily for specifying Scopes
type SymNames map[token.Tokens]string
// SubCat returns a scope with the given SubCat type, or false if not found
func (sn *SymNames) SubCat(sc token.Tokens) (string, bool) {
for tk, nm := range *sn {
if tk.SubCat() == sc {
return nm, true
}
}
return "", false
}
// Clone returns a clone copy of this map (nil if empty)
func (sn *SymNames) Clone() SymNames {
sz := len(*sn)
if sz == 0 {
return nil
}
nsn := make(SymNames, sz)
maps.Copy(nsn, *sn)
return nsn
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package syms
import (
"encoding/json"
"io"
"os"
"path/filepath"
"sort"
"strings"
"cogentcore.org/core/text/parse/lexer"
"cogentcore.org/core/text/textpos"
"cogentcore.org/core/text/token"
)
// SymMap is a map between symbol names and their full information.
// A given project will have a top-level SymMap and perhaps local
// maps for individual files, etc. Namespaces / packages can be
// created and elements added to them to create appropriate
// scoping structure etc. Note that we have to use pointers
// for symbols b/c otherwise it is very expensive to re-assign
// values all the time -- https://github.com/golang/go/issues/3117
type SymMap map[string]*Symbol
// Alloc ensures that map is made
func (sm *SymMap) Alloc() {
if *sm == nil {
*sm = make(SymMap)
}
}
// Add adds symbol to map
func (sm *SymMap) Add(sy *Symbol) {
sm.Alloc()
(*sm)[sy.Name] = sy
}
// AddNew adds a new symbol to the map with the basic info
func (sm *SymMap) AddNew(name string, kind token.Tokens, fname string, reg textpos.Region) *Symbol {
sy := NewSymbol(name, kind, fname, reg)
sm.Alloc()
(*sm)[name] = sy
return sy
}
// Reset resets the symbol map
func (sm *SymMap) Reset() {
*sm = make(SymMap)
}
// CopyFrom copies all the symbols from given source map into this one,
// including merging everything from common elements.
// Symbols with Type resolved are retained when there are duplicates.
// srcIsNewer means that the src map has the newer information to grab for
// updating the symbol region info during the merge.
func (sm *SymMap) CopyFrom(src SymMap, srcIsNewer bool) {
sm.Alloc()
for nm, ssy := range src {
dsy, has := (*sm)[nm]
if !has {
(*sm)[nm] = ssy
continue
}
if srcIsNewer {
dsy.CopyFromSrc(ssy)
} else {
ssy.CopyFromSrc(dsy)
}
if dsy.Type != "" {
// fmt.Printf("dupe sym: %v, using existing with type: %v\n", nm, dsy.Type)
// fmt.Printf("\texisting region: %v new source region: %v\n", dsy.Region, ssy.Region)
dsy.Children.CopyFrom(ssy.Children, srcIsNewer)
} else if ssy.Type != "" {
// fmt.Printf("dupe sym: %v, using new with type: %v\n", nm, ssy.Type)
// fmt.Printf("\texisting region: %v new source region: %v\n", dsy.Region, ssy.Region)
ssy.Children.CopyFrom(dsy.Children, !srcIsNewer)
(*sm)[nm] = ssy
} else {
dsy.Children.CopyFrom(ssy.Children, srcIsNewer)
}
}
}
// First returns the first symbol in the map -- only sensible when there
// is just one such element
func (sm *SymMap) First() *Symbol {
for _, sy := range *sm {
return sy
}
return nil
}
// Slice returns a slice of the elements in the map, optionally sorted by name
func (sm *SymMap) Slice(sorted bool) []*Symbol {
sys := make([]*Symbol, len(*sm))
idx := 0
for _, sy := range *sm {
sys[idx] = sy
idx++
}
if sorted {
sort.Slice(sys, func(i, j int) bool {
return sys[i].Name < sys[j].Name
})
}
return sys
}
// FindName looks for given symbol name within this map and any children on the map
func (sm *SymMap) FindName(nm string) (*Symbol, bool) {
if *sm == nil {
return nil, false
}
sy, has := (*sm)[nm]
if has {
return sy, has
}
for _, ss := range *sm {
if sy, has = ss.Children.FindName(nm); has {
return sy, has
}
}
return nil, false
}
// FindNameScoped looks for given symbol name within this map and any children on the map
// that are of subcategory token.NameScope (i.e., namespace, module, package, library)
func (sm *SymMap) FindNameScoped(nm string) (*Symbol, bool) {
if *sm == nil {
return nil, false
}
sy, has := (*sm)[nm]
if has {
return sy, has
}
for _, ss := range *sm {
if ss.Kind.SubCat() == token.NameScope {
if sy, has = ss.Children.FindNameScoped(nm); has {
return sy, has
}
}
}
return nil, false
}
// FindKind looks for given symbol kind within this map and any children on the map
// Returns all instances found. Uses cat / subcat based token matching -- if you
// specify a category-level or subcategory level token, it will match everything in that group
func (sm *SymMap) FindKind(kind token.Tokens, matches *SymMap) {
if *sm == nil {
return
}
for _, sy := range *sm {
if kind.Match(sy.Kind) {
if *matches == nil {
*matches = make(SymMap)
}
(*matches)[sy.Name] = sy
}
}
for _, ss := range *sm {
ss.Children.FindKind(kind, matches)
}
}
// FindKindScoped looks for given symbol kind within this map and any children on the map
// that are of subcategory token.NameScope (i.e., namespace, module, package, library).
// Returns all instances found. Uses cat / subcat based token matching -- if you
// specify a category-level or subcategory level token, it will match everything in that group
func (sm *SymMap) FindKindScoped(kind token.Tokens, matches *SymMap) {
if *sm == nil {
return
}
for _, sy := range *sm {
if kind.Match(sy.Kind) {
if *matches == nil {
*matches = make(SymMap)
}
(*matches)[sy.Name] = sy
}
}
for _, ss := range *sm {
if ss.Kind.SubCat() == token.NameScope {
ss.Children.FindKindScoped(kind, matches)
}
}
}
// FindContainsRegion looks for given symbol kind that contains the given
// source file path (must be filepath.Abs file path) and position.
// Returns all instances found. Uses cat / subcat based token matching -- if you
// specify a category-level or subcategory level token, it will match everything
// in that group. if you specify kind = token.None then all tokens that contain
// region will be returned. extraLns are extra lines added to the symbol region
// for purposes of matching.
func (sm *SymMap) FindContainsRegion(fpath string, pos textpos.Pos, extraLns int, kind token.Tokens, matches *SymMap) {
if *sm == nil {
return
}
for _, sy := range *sm {
fp, _ := filepath.Abs(sy.Filename)
if fp != fpath {
continue
}
reg := sy.Region
if extraLns > 0 {
reg.End.Line += extraLns
}
if !reg.Contains(pos) {
continue
}
if kind == token.None || kind.Match(sy.Kind) {
if *matches == nil {
*matches = make(SymMap)
}
(*matches)[sy.Name] = sy
}
}
for _, ss := range *sm {
ss.Children.FindContainsRegion(fpath, pos, extraLns, kind, matches)
}
}
// OpenJSON opens from a JSON-formatted file.
func (sm *SymMap) OpenJSON(filename string) error {
b, err := os.ReadFile(filename)
if err != nil {
return err
}
return json.Unmarshal(b, sm)
}
// SaveJSON saves to a JSON-formatted file.
func (sm *SymMap) SaveJSON(filename string) error {
b, err := json.MarshalIndent(sm, "", " ")
if err != nil {
return err
}
err = os.WriteFile(filename, b, 0644)
return err
}
// Names returns a slice of the names in this map, optionally sorted
func (sm *SymMap) Names(sorted bool) []string {
nms := make([]string, len(*sm))
idx := 0
for _, sy := range *sm {
nms[idx] = sy.Name
idx++
}
if sorted {
sort.StringSlice(nms).Sort()
}
return nms
}
// KindNames returns a slice of the kind:names in this map, optionally sorted
func (sm *SymMap) KindNames(sorted bool) []string {
nms := make([]string, len(*sm))
idx := 0
for _, sy := range *sm {
nms[idx] = sy.Kind.String() + ":" + sy.Name
idx++
}
if sorted {
sort.StringSlice(nms).Sort()
}
return nms
}
// WriteDoc writes basic doc info, sorted by kind and name
func (sm *SymMap) WriteDoc(out io.Writer, depth int) {
nms := sm.KindNames(true)
for _, nm := range nms {
ci := strings.Index(nm, ":")
sy := (*sm)[nm[ci+1:]]
sy.WriteDoc(out, depth)
}
}
//////////////////////////////////////////////////////////////////////
// Partial lookups
// FindNamePrefix looks for given symbol name prefix within this map
// adds to given matches map (which can be nil), for more efficient recursive use
func (sm *SymMap) FindNamePrefix(seed string, matches *SymMap) {
noCase := !lexer.HasUpperCase(seed)
for _, sy := range *sm {
nm := sy.Name
if noCase {
nm = strings.ToLower(nm)
}
if strings.HasPrefix(nm, seed) {
if *matches == nil {
*matches = make(SymMap)
}
(*matches)[sy.Name] = sy
}
}
}
// FindNamePrefixRecursive looks for given symbol name prefix within this map
// and any children on the map.
// adds to given matches map (which can be nil), for more efficient recursive use
func (sm *SymMap) FindNamePrefixRecursive(seed string, matches *SymMap) {
noCase := !lexer.HasUpperCase(seed)
for _, sy := range *sm {
nm := sy.Name
if noCase {
nm = strings.ToLower(nm)
}
if strings.HasPrefix(nm, seed) {
if *matches == nil {
*matches = make(SymMap)
}
(*matches)[sy.Name] = sy
}
}
for _, ss := range *sm {
ss.Children.FindNamePrefixRecursive(seed, matches)
}
}
// FindNamePrefixScoped looks for given symbol name prefix within this map
// and any children on the map that are of subcategory
// token.NameScope (i.e., namespace, module, package, library)
// adds to given matches map (which can be nil), for more efficient recursive use
func (sm *SymMap) FindNamePrefixScoped(seed string, matches *SymMap) {
noCase := !lexer.HasUpperCase(seed)
for _, sy := range *sm {
nm := sy.Name
if nm[0] == '"' {
nm = strings.Trim(nm, `"`) // path names may be quoted
nm = filepath.Base(nm) // sorry, this is a bit of a Go-specific hack to look at package names only
sy = sy.Clone()
sy.Name = nm
}
mnm := nm // the lower case name is only for the match
if noCase {
mnm = strings.ToLower(nm)
}
if strings.HasPrefix(mnm, seed) {
if *matches == nil {
*matches = make(SymMap)
}
(*matches)[nm] = sy
}
}
for _, ss := range *sm {
if ss.Kind.SubCat() == token.NameScope {
ss.Children.FindNamePrefixScoped(seed, matches)
}
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package syms
import (
"cogentcore.org/core/text/textpos"
"cogentcore.org/core/text/token"
)
// SymStack is a simple stack (slice) of symbols
type SymStack []*Symbol
// Top returns the state at the top of the stack (could be nil)
func (ss *SymStack) Top() *Symbol {
sz := len(*ss)
if sz == 0 {
return nil
}
return (*ss)[sz-1]
}
// Push appends symbol to stack
func (ss *SymStack) Push(sy *Symbol) {
*ss = append(*ss, sy)
}
// PushNew adds a new symbol to the stack with the basic info
func (ss *SymStack) PushNew(name string, kind token.Tokens, fname string, reg textpos.Region) *Symbol {
sy := NewSymbol(name, kind, fname, reg)
ss.Push(sy)
return sy
}
// Pop takes symbol off the stack and returns it
func (ss *SymStack) Pop() *Symbol {
sz := len(*ss)
if sz == 0 {
return nil
}
sy := (*ss)[sz-1]
*ss = (*ss)[:sz-1]
return sy
}
// Reset resets the stack
func (ss *SymStack) Reset() {
*ss = nil
}
// FindNameScoped searches top-down in the stack for something with the given name
// in symbols that are of subcategory token.NameScope (i.e., namespace, module, package, library)
func (ss *SymStack) FindNameScoped(nm string) (*Symbol, bool) {
sz := len(*ss)
if sz == 0 {
return nil, false
}
for i := sz - 1; i >= 0; i-- {
sy := (*ss)[i]
if sy.Name == nm {
return sy, true
}
ssy, has := sy.Children.FindNameScoped(nm)
if has {
return ssy, true
}
}
return nil, false
}
func (ss *SymStack) ClearAST() {
for _, sy := range *ss {
sy.ClearAST()
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package syms
import (
"fmt"
"io"
"maps"
"slices"
"strings"
"cogentcore.org/core/base/indent"
"cogentcore.org/core/text/textpos"
"cogentcore.org/core/tree"
)
// Type contains all the information about types. Types can be builtin
// or composed of builtin types. Each type can have one or more elements,
// e.g., fields for a struct or class, multiple values for a go function,
// or the two types for a map (key, value), etc..
type Type struct {
// name of the type -- can be the name of a field or the role for a type element
Name string
// kind of type -- overall nature of the type
Kind Kinds
// documentation about this type, extracted from code
Desc string
// set to true after type has been initialized during post-parse processing
Initialized bool `edit:"-"`
// elements of this type -- ordering and meaning varies depending on the Kind of type -- for Primitive types this is the parent type, for Composite types it describes the key elements of the type: Tuple = each element's type; Array = type of elements; Struct = each field, etc (see docs for each in Kinds)
Els TypeEls
// methods defined for this type
Meths TypeMap
// for primitive types, this is the number of bytes, for composite types, it is the number of elements, which can be multi-dimensional (e.g., for functions, number of params is (including receiver param for methods) and return vals is )
Size []int
// full filename / URI of source where type is defined (may be empty for auto types)
Filename string
// region in source encompassing this type
Region textpos.Region
// relevant scoping / parent symbols, e.g., namespace, package, module, class, function, etc..
Scopes SymNames
// additional type properties, such as const, virtual, static -- these are just recorded textually and not systematized to keep things open-ended -- many of the most important properties can be inferred from the Kind property
Properties map[string]any
// AST node that corresponds to this type -- only valid during parsing
AST tree.Node `json:"-" xml:"-"`
}
// NewType returns a new Type struct initialized with given name and kind
func NewType(name string, kind Kinds) *Type {
ty := &Type{Name: name, Kind: kind}
return ty
}
// AllocScopes allocates scopes map if nil
func (ty *Type) AllocScopes() {
if ty.Scopes == nil {
ty.Scopes = make(SymNames)
}
}
// CopyFromSrc copies source-level data from given other type
func (ty *Type) CopyFromSrc(cp *Type) {
ty.Filename = cp.Filename
ty.Region = cp.Region
if cp.AST != nil {
ty.AST = cp.AST
}
}
// Clone returns a deep copy of this type, cloning / copying all sub-elements
// except the AST and Initialized
func (ty *Type) Clone() *Type {
// note: not copying Initialized
nty := &Type{Name: ty.Name, Kind: ty.Kind, Desc: ty.Desc, Filename: ty.Filename, Region: ty.Region, AST: ty.AST}
nty.Els.CopyFrom(ty.Els)
nty.Meths = ty.Meths.Clone()
nty.Size = slices.Clone(ty.Size)
nty.Scopes = ty.Scopes.Clone()
maps.Copy(nty.Properties, ty.Properties)
return nty
}
// AddScopesStack adds a given scope element(s) from stack to this Type.
func (ty *Type) AddScopesStack(ss SymStack) {
sz := len(ss)
if sz == 0 {
return
}
ty.AllocScopes()
for i := range sz {
sc := ss[i]
ty.Scopes[sc.Kind] = sc.Name
}
}
// String satisfies the fmt.Stringer interface
func (ty *Type) String() string {
switch {
case ty.Kind.Cat() == Function && len(ty.Size) == 2:
str := "func "
npars := ty.Size[0]
if ty.Kind.SubCat() == Method {
str += "(" + ty.Els.StringRange(0, 1) + ") " + ty.Name + "(" + ty.Els.StringRange(1, npars-1) + ")"
} else {
str += ty.Name + "(" + ty.Els.StringRange(0, npars) + ")"
}
nrets := ty.Size[1]
if nrets == 1 {
tel := ty.Els[npars]
str += " " + tel.Type
} else if nrets > 1 {
str += " (" + ty.Els.StringRange(npars, nrets) + ")"
}
return str
case ty.Kind.SubCat() == Map:
return "map[" + ty.Els[0].Type + "]" + ty.Els[1].Type
case ty.Kind == String:
return "string"
case ty.Kind.SubCat() == List:
return "[]" + ty.Els[0].Type
}
return ty.Name + ": " + ty.Kind.String()
}
// ArgString returns string of args to function if it is a function type
func (ty *Type) ArgString() string {
if ty.Kind.Cat() != Function || len(ty.Size) != 2 {
return ""
}
npars := ty.Size[0]
if ty.Kind.SubCat() == Method {
return ty.Els.StringRange(1, npars-1)
}
return ty.Els.StringRange(0, npars)
}
// ReturnString returns string of return vals of function if it is a function type
func (ty *Type) ReturnString() string {
if ty.Kind.Cat() != Function || len(ty.Size) != 2 {
return ""
}
npars := ty.Size[0]
nrets := ty.Size[1]
if nrets == 1 {
tel := ty.Els[npars]
return tel.Type
} else if nrets > 1 {
return "(" + ty.Els.StringRange(npars, nrets) + ")"
}
return ""
}
// NonPtrType returns the non-pointer name of this type, if it is a pointer type
// otherwise just returns Name
func (ty *Type) NonPtrType() string {
if ty.Kind != Ptr && ty.Kind != Ref && ty.Kind != UnsafePtr {
return ty.Name
}
if len(ty.Els) == 1 {
return ty.Els[0].Type
}
return ty.Name // shouldn't happen
}
// WriteDoc writes basic doc info
func (ty *Type) WriteDoc(out io.Writer, depth int) {
ind := indent.Tabs(depth)
fmt.Fprintf(out, "%v%v: %v", ind, ty.Name, ty.Kind)
if len(ty.Size) == 1 {
fmt.Fprintf(out, " Size: %v", ty.Size[0])
} else if len(ty.Size) > 1 {
fmt.Fprint(out, " Size: { ")
for i := range ty.Size {
fmt.Fprintf(out, "%v, ", ty.Size[i])
}
fmt.Fprint(out, " }")
}
if ty.Kind.SubCat() == Struct && len(ty.Els) > 0 {
fmt.Fprint(out, " {\n")
indp := indent.Tabs(depth + 1)
for i := range ty.Els {
fmt.Fprintf(out, "%v%v\n", indp, ty.Els[i].String())
}
fmt.Fprintf(out, "%v}\n", ind)
} else {
fmt.Fprint(out, "\n")
}
if len(ty.Meths) > 0 {
fmt.Fprint(out, "Methods: {\n")
indp := indent.Tabs(depth + 1)
for _, m := range ty.Meths {
fmt.Fprintf(out, "%v%v\n", indp, m.String())
}
fmt.Fprintf(out, "%v}\n", ind)
} else {
fmt.Fprint(out, "\n")
}
}
//////////////////////////////////////////////////////////////////////////////////
// TypeEls
// TypeEl is a type element -- has a name (local to the type, e.g., field name)
// and a type name that can be looked up in a master list of types
type TypeEl struct {
// element name -- e.g., field name for struct, or functional name for other types
Name string
// type name -- looked up on relevant lists -- includes scoping / package / namespace name as appropriate
Type string
}
// String satisfies the fmt.Stringer interface
func (tel *TypeEl) String() string {
if tel.Name != "" {
return tel.Name + " " + tel.Type
}
return tel.Type
}
// Clone returns a copy of this el
func (tel *TypeEl) Clone() *TypeEl {
te := &TypeEl{Name: tel.Name, Type: tel.Type}
return te
}
// TypeEls are the type elements for types
type TypeEls []TypeEl
// Add adds a new type element
func (te *TypeEls) Add(nm, typ string) {
(*te) = append(*te, TypeEl{Name: nm, Type: typ})
}
// CopyFrom copies from another list
func (te *TypeEls) CopyFrom(cp TypeEls) {
*te = append(*te, cp...)
}
// ByName returns type el with given name, nil if not there
func (te *TypeEls) ByName(nm string) *TypeEl {
for i := range *te {
el := &(*te)[i]
if el.Name == nm {
return el
}
}
return nil
}
// ByType returns type el with given type, nil if not there
func (te *TypeEls) ByType(typ string) *TypeEl {
for i := range *te {
el := &(*te)[i]
if el.Type == typ {
return el
}
}
return nil
}
// String satisfies the fmt.Stringer interface
func (te *TypeEls) String() string {
return te.StringRange(0, len(*te))
}
// StringRange returns a string rep of range of items
func (te *TypeEls) StringRange(st, n int) string {
n = min(n, len(*te))
var str strings.Builder
for i := 0; i < n; i++ {
tel := (*te)[st+i]
str.WriteString(tel.String())
if i < n-1 {
str.WriteString(", ")
}
}
return str.String()
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package syms
import (
"fmt"
"io"
"sort"
"strings"
)
// TypeMap is a map of types for quick looking up by name
type TypeMap map[string]*Type
// Alloc ensures that map is made
func (tm *TypeMap) Alloc() {
if *tm == nil {
*tm = make(TypeMap)
}
}
// Add adds a type to the map, handling allocation for nil maps
func (tm *TypeMap) Add(ty *Type) {
tm.Alloc()
(*tm)[ty.Name] = ty
}
// CopyFrom copies all the types from given source map into this one.
// Types that have Kind != Unknown are retained over unknown ones.
// srcIsNewer means that the src type is newer and should be used for
// other data like source
func (tm *TypeMap) CopyFrom(src TypeMap, srcIsNewer bool) {
tm.Alloc()
for nm, sty := range src {
ety, has := (*tm)[nm]
if !has {
(*tm)[nm] = sty
continue
}
if srcIsNewer {
ety.CopyFromSrc(sty)
} else {
sty.CopyFromSrc(ety)
}
if ety.Kind != Unknown {
// if len(sty.Els) > 0 && len(sty.Els) != len(ety.Els) {
// fmt.Printf("TypeMap dupe type: %v existing kind: %v els: %v new els: %v kind: %v\n", nm, ety.Kind, len(ety.Els), len(sty.Els), sty.Kind)
// }
} else if sty.Kind != Unknown {
// if len(ety.Els) > 0 && len(sty.Els) != len(ety.Els) {
// fmt.Printf("TypeMap dupe type: %v new kind: %v els: %v existing els: %v\n", nm, sty.Kind, len(sty.Els), len(ety.Els))
// }
(*tm)[nm] = sty
// } else {
// fmt.Printf("TypeMap dupe type: %v both unknown: existing els: %v new els: %v\n", nm, len(ety.Els), len(sty.Els))
}
}
}
// Clone returns deep copy of this type map -- types are Clone() copies.
// returns nil if this map is empty
func (tm *TypeMap) Clone() TypeMap {
sz := len(*tm)
if sz == 0 {
return nil
}
ntm := make(TypeMap, sz)
for nm, sty := range *tm {
ntm[nm] = sty.Clone()
}
return ntm
}
// Names returns a slice of the names in this map, optionally sorted
func (tm *TypeMap) Names(sorted bool) []string {
nms := make([]string, len(*tm))
idx := 0
for _, ty := range *tm {
nms[idx] = ty.Name
idx++
}
if sorted {
sort.StringSlice(nms).Sort()
}
return nms
}
// KindNames returns a slice of the kind:names in this map, optionally sorted
func (tm *TypeMap) KindNames(sorted bool) []string {
nms := make([]string, len(*tm))
idx := 0
for _, ty := range *tm {
nms[idx] = ty.Kind.String() + ":" + ty.Name
idx++
}
if sorted {
sort.StringSlice(nms).Sort()
}
return nms
}
// PrintUnknowns prints all the types that have a Kind = Unknown
// indicates an error in type resolution
func (tm *TypeMap) PrintUnknowns() {
for _, ty := range *tm {
if ty.Kind != Unknown {
continue
}
fmt.Printf("Type named: %v has Kind = Unknown! From file: %v:%v\n", ty.Name, ty.Filename, ty.Region)
}
}
// WriteDoc writes basic doc info, sorted by kind and name
func (tm *TypeMap) WriteDoc(out io.Writer, depth int) {
nms := tm.KindNames(true)
for _, nm := range nms {
ci := strings.Index(nm, ":")
ty := (*tm)[nm[ci+1:]]
ty.WriteDoc(out, depth)
}
}
// TypeKindSize is used for initialization of builtin typemaps
type TypeKindSize struct {
Name string
Kind Kinds
Size int
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package printer
import (
"cogentcore.org/core/math32"
"cogentcore.org/core/styles/units"
)
// PageSizes are standard physical drawing sizes
type PageSizes int32 //enums:enum
const (
// Custom = nonstandard
Custom PageSizes = iota
// Image 1280x720 Px = 720p
Img1280x720
// Image 1920x1080 Px = 1080p HD
Img1920x1080
// Image 3840x2160 Px = 4K
Img3840x2160
// Image 7680x4320 Px = 8K
Img7680x4320
// Image 1024x768 Px = XGA
Img1024x768
// Image 720x480 Px = DVD
Img720x480
// Image 640x480 Px = VGA
Img640x480
// Image 320x240 Px = old CRT
Img320x240
// A4 = 210 x 297 mm
A4
// USLetter = 8.5 x 11 in = 612 x 792 pt
USLetter
// USLegal = 8.5 x 14 in = 612 x 1008 pt
USLegal
// A0 = 841 x 1189 mm
A0
// A1 = 594 x 841 mm
A1
// A2 = 420 x 594 mm
A2
// A3 = 297 x 420 mm
A3
// A5 = 148 x 210 mm
A5
// A6 = 105 x 148 mm
A6
// A7 = 74 x 105
A7
// A8 = 52 x 74 mm
A8
// A9 = 37 x 52
A9
// A10 = 26 x 37
A10
)
// Size returns the corresponding size values and units.
func (s PageSizes) Size() (un units.Units, size math32.Vector2) {
v := sizesMap[s]
return v.un, math32.Vec2(v.x, v.y)
}
// Match returns a matching standard size for given units and dimension.
func Match(un units.Units, wd, ht float32) PageSizes {
trgl := values{un: un, x: wd, y: ht}
trgp := values{un: un, x: ht, y: wd}
for k, v := range sizesMap {
if *v == trgl || *v == trgp {
return k
}
}
return Custom
}
// values are values for standard sizes
type values struct {
un units.Units
x float32
y float32
}
// sizesMap is the map of size values for each standard size
var sizesMap = map[PageSizes]*values{
Img1280x720: {units.UnitPx, 1280, 720},
Img1920x1080: {units.UnitPx, 1920, 1080},
Img3840x2160: {units.UnitPx, 3840, 2160},
Img7680x4320: {units.UnitPx, 7680, 4320},
Img1024x768: {units.UnitPx, 1024, 768},
Img720x480: {units.UnitPx, 720, 480},
Img640x480: {units.UnitPx, 640, 480},
Img320x240: {units.UnitPx, 320, 240},
A4: {units.UnitMm, 210, 297},
USLetter: {units.UnitPt, 612, 792},
USLegal: {units.UnitPt, 612, 1008},
A0: {units.UnitMm, 841, 1189},
A1: {units.UnitMm, 594, 841},
A2: {units.UnitMm, 420, 594},
A3: {units.UnitMm, 297, 420},
A5: {units.UnitMm, 148, 210},
A6: {units.UnitMm, 105, 148},
A7: {units.UnitMm, 74, 105},
A8: {units.UnitMm, 52, 74},
A9: {units.UnitMm, 37, 52},
A10: {units.UnitMm, 26, 37},
}
// DefaultPageSizeForRegion returns the default page size based on locale
// region value, per the https://www.rfc-editor.org/rfc/bcp/bcp47.txt standard.
// See [system.Locale] and [system.App] for how to get this.
func DefaultPageSizeForRegion(region string) PageSizes {
switch region {
case "US", "CA", "BZ", "CL", "CR", "GT", "NI", "PA", "PR", "SV", "VE", "MX", "CO", "PH":
return USLetter
default:
return A4
}
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:generate core generate -add-types
// Package printer provides standard printer settings.
package printer
import (
"path/filepath"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles/sides"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/system"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/tree"
)
// Settings provides the default printer settings.
// This is initialized by the system.App because it depends on
// the locale for initialization.
var Settings SettingsData
// SettingsData has standard printer settings.
type SettingsData struct {
// PageSize specifies a standard page size, or Custom.
PageSize PageSizes
// Units are the units in which the page size is specified.
// Will automatically be set if PageSize != Custom.
Units units.Units
// Size is the page size in given units.
// Will automatically be set if PageSize != Custom.
Size math32.Vector2
// Margins specify the page margins in the size units.
Margins sides.Floats `display:"inline"`
// FontFamily specifies the font family to use for printing.
// The default SansSerif font used on screen may not be desired
// for printouts, where Serif is more typically used.
FontFamily rich.Family
// FontSize specifies the base font size to use for scaling printed
// text output (i.e., the default Text font will be this size, with
// larger elements scaled appropriately).
FontSize units.Value
// LineHeight is the default line height for standard text elements,
// in proportion to the font size (e.g., 1.25), which determines the
// spacing between lines.
LineHeight float32
}
func (ps *SettingsData) Defaults() {
ps.PageSize = DefaultPageSizeForRegion(system.TheApp.SystemLocale().Region())
ps.Update()
switch ps.Units {
case units.UnitMm:
ps.Margins.Set(25) // basically one inch
case units.UnitPt:
ps.Margins.Set(72)
case units.UnitPx:
ps.Margins.Set(24)
}
ps.FontFamily = rich.Serif
ps.FontSize.Pt(11)
ps.LineHeight = 1.25
ps.Update()
}
func (ps *SettingsData) Update() {
if ps.PageSize != Custom {
pU := ps.Units
ps.Units, ps.Size = ps.PageSize.Size()
if pU != ps.Units {
uc := units.NewContext()
sc := uc.Convert(1, pU, ps.Units)
ps.Margins = ps.Margins.MulScalar(sc)
}
}
}
func (ps *SettingsData) Apply() {
ps.Update()
}
func (ps *SettingsData) Label() string {
return "Printer"
}
func (ps *SettingsData) Filename() string {
return filepath.Join(system.TheApp.CogentCoreDataDir(), "printer-settings.toml")
}
func (ps *SettingsData) MakeToolbar(p *tree.Plan) {
}
// ToDots returns the measurement values in rendering dots (actual pixels)
// based on the given units context.
// size = page size; body = content area inside margins
func (ps *SettingsData) ToDots(un *units.Context) (size, body math32.Vector2, margins sides.Floats) {
sc := un.ToDots(1, ps.Units)
size = ps.Size.MulScalar(sc).Floor()
margins = ps.Margins.MulScalar(sc)
body.X = size.X - (margins.Left + margins.Right)
body.Y = size.Y - (margins.Top + margins.Bottom)
return
}
// FontScale returns the scaling factor based on FontSize,
// relative to the core default font size of 16 Dp.
func (ps *SettingsData) FontScale() float32 {
uc := units.NewContext()
sc := uc.Convert(16, units.UnitDp, ps.FontSize.Unit)
return ps.FontSize.Value / sc
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package rich
import (
"cogentcore.org/core/text/textpos"
)
// Hyperlink represents a hyperlink within shaped text.
type Hyperlink struct {
// Label is the text label for the link.
Label string
// URL is the full URL for the link.
URL string
// Range defines the starting and ending positions of the link,
// in terms of source rune indexes.
Range textpos.Range
}
// GetLinks gets all the links from the source.
func (tx Text) GetLinks() []Hyperlink {
var lks []Hyperlink
n := len(tx)
for si := 0; si < n; si++ {
sp := RuneToSpecial(tx[si][0])
if sp != Link {
continue
}
lr := tx.SpecialRange(si)
if lr.End < 0 || lr.End <= lr.Start {
continue
}
ls := tx[lr.Start:lr.End]
s, _ := tx.Span(si)
lk := Hyperlink{}
lk.URL = s.URL
sr, _ := tx.Range(lr.Start)
_, er := tx.Range(lr.End)
lk.Range = textpos.Range{Start: sr, End: er}
lk.Label = string(ls.Join())
lks = append(lks, lk)
si = lr.End - 1 // continue after the link
}
return lks
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package rich
import (
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/colors"
"cogentcore.org/core/colors/gradient"
"cogentcore.org/core/enums"
"cogentcore.org/core/styles/styleprops"
"strconv"
"strings"
)
// FromProperties sets style field values based on the given property list.
func (s *Style) FromProperties(parent *Style, properties map[string]any, ctxt colors.Context) {
for key, val := range properties {
if len(key) == 0 {
continue
}
if key[0] == '#' || key[0] == '.' || key[0] == ':' || key[0] == '_' {
continue
}
s.FromProperty(parent, key, val, ctxt)
}
}
// FromProperty sets style field values based on the given property key and value.
func (s *Style) FromProperty(parent *Style, key string, val any, cc colors.Context) {
if sfunc, ok := styleFuncs[key]; ok {
if parent != nil {
sfunc(s, key, val, parent, cc)
} else {
sfunc(s, key, val, nil, cc)
}
return
}
}
// FontSizes maps standard font names to standard point sizes -- we use
// dpi zoom scaling instead of rescaling "medium" font size, so generally use
// these values as-is. smaller and larger relative scaling can move in 2pt increments
var FontSizes = map[string]float32{
"xx-small": 6.0 / 12.0,
"x-small": 8.0 / 12.0,
"small": 10.0 / 12.0, // small is also "smaller"
"smallf": 10.0 / 12.0, // smallf = small font size..
"medium": 1,
"large": 14.0 / 12.0,
"x-large": 18.0 / 12.0,
"xx-large": 24.0 / 12.0,
}
// styleFuncs are functions for styling the rich.Style object.
var styleFuncs = map[string]styleprops.Func{
// note: text.Style handles the standard units-based font-size settings
"font-size": func(obj any, key string, val any, parent any, cc colors.Context) {
fs := obj.(*Style)
if inh, init := styleprops.InhInit(val, parent); inh || init {
if inh {
fs.Size = parent.(*Style).Size
} else if init {
fs.Size = 1.0
}
return
}
switch vt := val.(type) {
case string:
if psz, ok := FontSizes[vt]; ok {
fs.Size = psz
} else if pct, ok := strings.CutSuffix(vt, "%"); ok {
// relative to the size of the surrounding text
if f, err := strconv.ParseFloat(strings.TrimSpace(pct), 32); err == nil {
fs.Size = float32(f) / 100
}
} else if em, ok := strings.CutSuffix(vt, "em"); ok {
if f, err := strconv.ParseFloat(strings.TrimSpace(em), 32); err == nil {
fs.Size = float32(f)
}
}
}
},
"font-family": styleprops.Enum(SansSerif,
func(obj *Style) enums.EnumSetter { return &obj.Family }),
"font-style": styleprops.Enum(SlantNormal,
func(obj *Style) enums.EnumSetter { return &obj.Slant }),
"font-weight": styleprops.Enum(Normal,
func(obj *Style) enums.EnumSetter { return &obj.Weight }),
"font-stretch": styleprops.Enum(StretchNormal,
func(obj *Style) enums.EnumSetter { return &obj.Stretch }),
"text-decoration": func(obj any, key string, val any, parent any, cc colors.Context) {
fs := obj.(*Style)
cflags := fs.Decoration & colorFlagsMask
if inh, init := styleprops.InhInit(val, parent); inh || init {
if inh {
fs.Decoration = parent.(*Style).Decoration
} else if init {
fs.Decoration = cflags
}
return
}
switch vt := val.(type) {
case string:
if vt == "none" {
fs.Decoration = cflags
} else {
fs.Decoration.SetString(vt)
fs.Decoration |= cflags
}
case Decorations:
fs.Decoration = cflags | vt
default:
iv, err := reflectx.ToInt(val)
if err == nil {
fs.Decoration = cflags | Decorations(iv)
} else {
styleprops.SetError(key, val, err)
}
}
},
"direction": styleprops.Enum(LTR,
func(obj *Style) enums.EnumSetter { return &obj.Direction }),
"color": func(obj any, key string, val any, parent any, cc colors.Context) {
fs := obj.(*Style)
if inh, init := styleprops.InhInit(val, parent); inh || init {
if inh {
fs.SetFillColor(parent.(*Style).FillColor())
} else if init {
fs.SetFillColor(nil)
}
return
}
if str, ok := val.(string); ok && strings.EqualFold(strings.TrimSpace(str), "currentcolor") {
// the color that it inherits (as the links of github.com,
// whose text was transparent)
if ps, ok := parent.(*Style); ok && ps != nil {
fs.SetFillColor(ps.FillColor())
} else {
fs.SetFillColor(nil)
}
return
}
fs.SetFillColor(colors.ToUniform(errors.Log1(gradient.FromAny(val, cc))))
},
"stroke-color": func(obj any, key string, val any, parent any, cc colors.Context) {
fs := obj.(*Style)
if inh, init := styleprops.InhInit(val, parent); inh || init {
if inh {
fs.SetStrokeColor(parent.(*Style).StrokeColor())
} else if init {
fs.SetStrokeColor(nil)
}
return
}
fs.SetStrokeColor(colors.ToUniform(errors.Log1(gradient.FromAny(val, cc))))
},
"background-color": func(obj any, key string, val any, parent any, cc colors.Context) {
fs := obj.(*Style)
if inh, init := styleprops.InhInit(val, parent); inh || init {
if inh {
fs.SetBackground(parent.(*Style).Background())
} else if init {
fs.SetBackground(nil)
}
return
}
fs.SetBackground(colors.ToUniform(errors.Log1(gradient.FromAny(val, cc))))
},
"opacity": func(obj any, key string, val any, parent any, cc colors.Context) {
fs := obj.(*Style)
if inh, init := styleprops.InhInit(val, parent); inh || init {
return
}
fv, _ := reflectx.ToFloat(val)
if fv < 1 {
if fs.background != nil {
fs.background = colors.ApplyOpacity(fs.background, float32(fv))
}
if fs.strokeColor != nil {
fs.strokeColor = colors.ApplyOpacity(fs.strokeColor, float32(fv))
}
if fs.fillColor != nil {
fs.fillColor = colors.ApplyOpacity(fs.fillColor, float32(fv))
}
}
},
}
// SetFromHTMLTag sets the styling parameters for simple HTML style tags.
// Returns true if handled.
func (s *Style) SetFromHTMLTag(tag string) bool {
did := false
switch tag {
case "b", "strong":
s.Weight = Bold
did = true
case "i", "em", "var", "cite":
s.Slant = Italic
did = true
case "ins":
fallthrough
case "u":
s.Decoration.SetFlag(true, Underline)
did = true
case "s", "del", "strike":
s.Decoration.SetFlag(true, LineThrough)
did = true
case "small":
s.Size = 0.8
did = true
case "big":
s.Size = 1.2
did = true
case "xx-small", "x-small", "smallf", "medium", "large", "x-large", "xx-large":
s.Size = FontSizes[tag]
did = true
case "mark":
s.SetBackground(colors.ToUniform(colors.Scheme.Warn.Container))
did = true
case "abbr", "acronym":
s.Decoration.SetFlag(true, DottedUnderline)
did = true
case "tt", "kbd", "samp", "code":
s.Family = Monospace
s.SetBackground(colors.ToUniform(colors.Scheme.SurfaceContainer))
did = true
}
return did
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package rich
import (
"strings"
"github.com/cogentcore/typesetting/language"
)
func init() {
Settings.Defaults()
}
// Settings contains the global text settings,
// for language, script and font names to use.
// To use different settings temporarily, save current
// and swap.
var Settings SettingsData
// FontName is a special string that provides a font chooser.
// It is aliased to [core.FontName] as well.
type FontName string
// SettingsData holds the global settings for rich text styling,
// including language, script, and preferred font faces for
// each category of font.
type SettingsData struct {
// Language is the preferred language used for rendering text.
Language language.Language
// Script is the specific writing system used for rendering text.
// todo: no idea how to set this based on language or anything else.
Script language.Script `display:"-"`
// SansSerif is a font without serifs, where glyphs have plain stroke endings,
// without ornamentation. Example sans-serif fonts include Arial, Helvetica,
// Noto Sans, Open Sans, Fira Sans, Lucida Sans, Lucida Sans Unicode, Trebuchet MS,
// Liberation Sans, Nimbus Sans L, Roboto.
// This can be a list of comma-separated names, tried in order.
// "sans-serif" will be added automatically as a final backup.
SansSerif FontName `default:"Noto Sans"`
// Serif is a small line or stroke attached to the end of a larger stroke
// in a letter. In serif fonts, glyphs have finishing strokes, flared or
// tapering ends. Examples include Times New Roman, Lucida Bright,
// Lucida Fax, Palatino, Palatino Linotype, Palladio, and URW Palladio.
// This can be a list of comma-separated names, tried in order.
// "serif" will be added automatically as a final backup.
Serif FontName
// Monospace fonts have all glyphs with he same fixed width.
// Example monospace fonts include Roboto Mono, Fira Mono, DejaVu Sans Mono,
// Menlo, Consolas, Liberation Mono, Monaco, and Lucida Console.
// This can be a list of comma-separated names. serif will be added
// automatically as a final backup.
// This can be a list of comma-separated names, tried in order.
// "monospace" will be added automatically as a final backup.
Monospace FontName `default:"Roboto Mono"`
// Cursive glyphs generally have either joining strokes or other cursive
// characteristics beyond those of italic typefaces. The glyphs are partially
// or completely connected, and the result looks more like handwritten pen or
// brush writing than printed letter work. Example cursive fonts include
// Brush Script MT, Brush Script Std, Lucida Calligraphy, Lucida Handwriting,
// and Apple Chancery.
// This can be a list of comma-separated names, tried in order.
// "cursive" will be added automatically as a final backup.
Cursive FontName
// Fantasy fonts are primarily decorative fonts that contain playful
// representations of characters. Example fantasy fonts include Papyrus,
// Herculanum, Party LET, Curlz MT, and Harrington.
// This can be a list of comma-separated names, tried in order.
// "fantasy" will be added automatically as a final backup.
Fantasy FontName
// Math fonts are for displaying mathematical expressions, for example
// superscript and subscript, brackets that cross several lines, nesting
// expressions, and double-struck glyphs with distinct meanings.
// This can be a list of comma-separated names, tried in order.
// "math" will be added automatically as a final backup.
Math FontName
// Emoji fonts are specifically designed to render emoji.
// This can be a list of comma-separated names, tried in order.
// "emoji" will be added automatically as a final backup.
Emoji FontName
// Fangsong are a particular style of Chinese characters that are between
// serif-style Song and cursive-style Kai forms. This style is often used
// for government documents.
// This can be a list of comma-separated names, tried in order.
// "fangsong" will be added automatically as a final backup.
Fangsong FontName
}
func (rts *SettingsData) Defaults() {
rts.Language = language.DefaultLanguage()
rts.SansSerif = "Noto Sans"
rts.Monospace = "Roboto Mono"
}
// AddFamily adds a family specifier to the given font string,
// handling the comma properly.
func AddFamily(rts FontName, fam string) string {
if rts == "" {
return fam
}
s := string(rts)
// if strings.Contains(s, " ") { // no! this is bad
// s = `"` + s + `"`
// }
return s + ", " + fam
}
// FamiliesToList returns a list of the families, split by comma and space removed.
func FamiliesToList(fam string) []string {
fs := strings.Split(fam, ",")
os := make([]string, 0, len(fs))
for _, f := range fs {
rts := strings.TrimSpace(f)
if rts == "" {
continue
}
os = append(os, rts)
}
return os
}
// Family returns the font family specified by the given [Family] enum.
func (rts *SettingsData) Family(fam Family) string {
switch fam {
case SansSerif:
return AddFamily(rts.SansSerif, `-apple-system, BlinkMacSystemFont, "Segoe UI", Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif, emoji`)
case Serif:
return AddFamily(rts.Serif, `serif, emoji`)
case Monospace:
return AddFamily(rts.Monospace, `monospace, emoji`)
case Cursive:
return AddFamily(rts.Cursive, `cursive, emoji`)
case Fantasy:
return AddFamily(rts.Fantasy, `fantasy, emoji`)
case Math:
return AddFamily(rts.Math, "math")
case Emoji:
return AddFamily(rts.Emoji, "emoji")
case Fangsong:
return AddFamily(rts.Fangsong, "fangsong")
}
return "sans-serif"
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package rich
import (
"image/color"
"math"
)
// srune is a uint32 rune value that encodes the font styles.
// There is no attempt to pack these values into the Private Use Areas
// of unicode, because they are never encoded into the unicode directly.
// Because we have the room, we use at least 4 bits = 1 hex F for each
// element of the style property. Size and Color values are added after
// the main style rune element.
// RuneFromStyle returns the style rune that encodes the given style values.
func RuneFromStyle(s *Style) rune {
return RuneFromDecoration(s.Decoration) | RuneFromSpecial(s.Special) | RuneFromStretch(s.Stretch) | RuneFromWeight(s.Weight) | RuneFromSlant(s.Slant) | RuneFromFamily(s.Family) | RuneFromDirection(s.Direction)
}
// RuneToStyle sets all the style values decoded from given rune.
func RuneToStyle(s *Style, r rune) {
s.Decoration = RuneToDecoration(r)
s.Special = RuneToSpecial(r)
s.Stretch = RuneToStretch(r)
s.Weight = RuneToWeight(r)
s.Slant = RuneToSlant(r)
s.Family = RuneToFamily(r)
s.Direction = RuneToDirection(r)
}
// SpanLen returns the length of the starting style runes and
// following content runes for given slice of span runes.
// Does not need to decode full style, so is very efficient.
func SpanLen(s []rune) (sn int, rn int) {
r0 := s[0]
nc := RuneToDecoration(r0).NumColors()
sn = 2 + nc // style + size + nc
isLink := RuneToSpecial(r0) == Link
if !isLink {
rn = max(0, len(s)-sn)
return
}
ln := int(s[sn]) // link len
sn += ln + 1
rn = max(0, len(s)-sn)
return
}
// FromRunes sets the Style properties from the given rune encodings
// which must be the proper length including colors. Any remaining
// runes after the style runes are returned: this is the source string.
func (s *Style) FromRunes(rs []rune) []rune {
RuneToStyle(s, rs[0])
s.Size = math.Float32frombits(uint32(rs[1]))
ci := 2
if s.Decoration.HasFlag(fillColor) {
s.fillColor = ColorFromRune(rs[ci])
ci++
}
if s.Decoration.HasFlag(strokeColor) {
s.strokeColor = ColorFromRune(rs[ci])
ci++
}
if s.Decoration.HasFlag(background) {
s.background = ColorFromRune(rs[ci])
ci++
}
if s.Special == Link {
ln := int(rs[ci])
ci++
s.URL = string(rs[ci : ci+ln])
ci += ln
}
if ci < len(rs) {
return rs[ci:]
}
return nil
}
// ToRunes returns the rune(s) that encode the given style
// including any additional colors beyond the style and size runes,
// and the URL for a link.
func (s *Style) ToRunes() []rune {
r := RuneFromStyle(s)
rs := []rune{r, rune(math.Float32bits(s.Size))}
if s.Decoration.HasFlag(fillColor) {
rs = append(rs, ColorToRune(s.fillColor))
}
if s.Decoration.HasFlag(strokeColor) {
rs = append(rs, ColorToRune(s.strokeColor))
}
if s.Decoration.HasFlag(background) {
rs = append(rs, ColorToRune(s.background))
}
if s.Special == Link { // its length in runes (not bytes), as it is read
url := []rune(s.URL)
rs = append(rs, rune(len(url)))
rs = append(rs, url...)
}
return rs
}
// ColorToRune converts given color to a rune uint32 value.
func ColorToRune(c color.Color) rune {
r, g, b, a := c.RGBA() // uint32
r8 := r >> 8
g8 := g >> 8
b8 := b >> 8
a8 := a >> 8
return rune(r8<<24) + rune(g8<<16) + rune(b8<<8) + rune(a8)
}
// ColorFromRune converts given color from a rune uint32 value.
func ColorFromRune(r rune) color.RGBA {
ru := uint32(r)
r8 := uint8((ru & 0xFF000000) >> 24)
g8 := uint8((ru & 0x00FF0000) >> 16)
b8 := uint8((ru & 0x0000FF00) >> 8)
a8 := uint8((ru & 0x000000FF))
return color.RGBA{r8, g8, b8, a8}
}
const (
DecorationStart = 0
DecorationMask = 0x000007FF // 11 bits reserved for deco
SlantStart = 11
SlantMask = 0x00000800 // 1 bit for slant
SpecialStart = 12
SpecialMask = 0x0000F000
StretchStart = 16
StretchMask = 0x000F0000
WeightStart = 20
WeightMask = 0x00F00000
FamilyStart = 24
FamilyMask = 0x0F000000
DirectionStart = 28
DirectionMask = 0xF0000000
)
// RuneFromDecoration returns the rune bit values for given decoration.
func RuneFromDecoration(d Decorations) rune {
return rune(d)
}
// RuneToDecoration returns the Decoration bit values from given rune.
func RuneToDecoration(r rune) Decorations {
return Decorations(uint32(r) & DecorationMask)
}
// RuneFromSpecial returns the rune bit values for given special.
func RuneFromSpecial(d Specials) rune {
return rune(d << SpecialStart)
}
// RuneToSpecial returns the Specials value from given rune.
func RuneToSpecial(r rune) Specials {
return Specials((uint32(r) & SpecialMask) >> SpecialStart)
}
// RuneFromStretch returns the rune bit values for given stretch.
func RuneFromStretch(d Stretch) rune {
return rune(d << StretchStart)
}
// RuneToStretch returns the Stretch value from given rune.
func RuneToStretch(r rune) Stretch {
return Stretch((uint32(r) & StretchMask) >> StretchStart)
}
// RuneFromWeight returns the rune bit values for given weight.
func RuneFromWeight(d Weights) rune {
return rune(d << WeightStart)
}
// RuneToWeight returns the Weights value from given rune.
func RuneToWeight(r rune) Weights {
return Weights((uint32(r) & WeightMask) >> WeightStart)
}
// RuneFromSlant returns the rune bit values for given slant.
func RuneFromSlant(d Slants) rune {
return rune(d << SlantStart)
}
// RuneToSlant returns the Slants value from given rune.
func RuneToSlant(r rune) Slants {
return Slants((uint32(r) & SlantMask) >> SlantStart)
}
// RuneFromFamily returns the rune bit values for given family.
func RuneFromFamily(d Family) rune {
return rune(d << FamilyStart)
}
// RuneToFamily returns the Familys value from given rune.
func RuneToFamily(r rune) Family {
return Family((uint32(r) & FamilyMask) >> FamilyStart)
}
// RuneFromDirection returns the rune bit values for given direction.
func RuneFromDirection(d Directions) rune {
return rune(d << DirectionStart)
}
// RuneToDirection returns the Directions value from given rune.
func RuneToDirection(r rune) Directions {
return Directions((uint32(r) & DirectionMask) >> DirectionStart)
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package rich
import (
"fmt"
"image/color"
"math"
"strings"
"cogentcore.org/core/colors"
"github.com/cogentcore/typesetting/di"
)
//go:generate core generate
// IMPORTANT: enums must remain in sync with
// "github.com/cogentcore/typesetting/font"
// and props.go must be updated as needed.
// Style contains all of the rich text styling properties, that apply to one
// span of text. These are encoded into a uint32 rune value in [rich.Text].
// See [text.Style] and [Settings] for additional context needed for full specification.
type Style struct { //types:add -setters
// Size is the font size multiplier relative to the standard font size
// specified in the [text.Style].
Size float32
// Family indicates the generic family of typeface to use, where the
// specific named values to use for each are provided in the [Settings],
// or [text.Style] for [Custom].
Family Family
// Slant allows italic or oblique faces to be selected.
Slant Slants
// Weights are the degree of blackness or stroke thickness of a font.
// This value ranges from 100.0 to 900.0, with 400.0 as normal.
Weight Weights
// Stretch is the width of a font as an approximate fraction of the normal width.
// Widths range from 0.5 to 2.0 inclusive, with 1.0 as the normal width.
Stretch Stretch
// Special additional formatting factors that are not otherwise
// captured by changes in font rendering properties or decorations.
// See [Specials] for usage information: use [Text.StartSpecial]
// and [Text.EndSpecial] to set.
Special Specials
// Decorations are underline, line-through, etc, as bit flags
// that must be set using [Decorations.SetFlag].
Decoration Decorations `set:"-"`
// Direction is the direction to render the text.
Direction Directions
// fillColor is the color to use for glyph fill (i.e., the standard "ink" color).
// Must use SetFillColor to set Decoration fillColor flag.
// This will be encoded in a uint32 following the style rune, in rich.Text spans.
fillColor color.Color
// strokeColor is the color to use for glyph outline stroking.
// Must use SetStrokeColor to set Decoration strokeColor flag.
// This will be encoded in a uint32 following the style rune, in rich.Text spans.
strokeColor color.Color
// background is the color to use for the background region.
// Must use SetBackground to set the Decoration background flag.
// This will be encoded in a uint32 following the style rune, in rich.Text spans.
background color.Color `set:"-"`
// URL is the URL for a link element. It is encoded in runes after the style runes.
URL string
}
func NewStyle() *Style {
s := &Style{}
s.Defaults()
return s
}
// Clone returns a copy of this style.
func (s *Style) Clone() *Style {
ns := &Style{}
*ns = *s
return ns
}
// NewStyleFromRunes returns a new style initialized with data from given runes,
// returning the remaining actual rune string content after style data.
func NewStyleFromRunes(rs []rune) (*Style, []rune) {
s := NewStyle()
c := s.FromRunes(rs)
return s, c
}
func (s *Style) Defaults() {
s.Size = 1
s.Weight = Normal
s.Stretch = StretchNormal
s.Direction = Default
}
// InheritFields from parent
func (s *Style) InheritFields(parent *Style) {
// fs.Color = par.Color
s.Family = parent.Family
s.Slant = parent.Slant
if parent.Size != 0 {
s.Size = parent.Size
}
s.Weight = parent.Weight
s.Stretch = parent.Stretch
}
// FontFamily returns the font family name(s) based on [Style.Family] and the
// values specified in the given [Settings].
func (s *Style) FontFamily(ctx *SettingsData) string {
return ctx.Family(s.Family)
}
// Family specifies the generic family of typeface to use, where the
// specific named values to use for each are provided in the Settings.
type Family int32 //enums:enum -trim-prefix Family -transform kebab
const (
// SansSerif is a font without serifs, where glyphs have plain stroke endings,
// without ornamentation. Example sans-serif fonts include Arial, Helvetica,
// Open Sans, Fira Sans, Lucida Sans, Lucida Sans Unicode, Trebuchet MS,
// Liberation Sans, and Nimbus Sans L.
SansSerif Family = iota
// Serif is a small line or stroke attached to the end of a larger stroke
// in a letter. In serif fonts, glyphs have finishing strokes, flared or
// tapering ends. Examples include Times New Roman, Lucida Bright,
// Lucida Fax, Palatino, Palatino Linotype, Palladio, and URW Palladio.
Serif
// Monospace fonts have all glyphs with he same fixed width.
// Example monospace fonts include Courier, Fira Mono, DejaVu Sans Mono,
// Menlo, Consolas, Liberation Mono, Monaco, and Lucida Console.
Monospace
// Cursive glyphs generally have either joining strokes or other cursive
// characteristics beyond those of italic typefaces. The glyphs are partially
// or completely connected, and the result looks more like handwritten pen or
// brush writing than printed letter work. Example cursive fonts include
// Brush Script MT, Brush Script Std, Lucida Calligraphy, Lucida Handwriting,
// and Apple Chancery.
Cursive
// Fantasy fonts are primarily decorative fonts that contain playful
// representations of characters. Example fantasy fonts include Papyrus,
// Herculanum, Party LET, Curlz MT, and Harrington.
Fantasy
// Math fonts are for displaying mathematical expressions, for example
// superscript and subscript, brackets that cross several lines, nesting
// expressions, and double-struck glyphs with distinct meanings.
Math
// Emoji fonts are specifically designed to render emoji.
Emoji
// Fangsong are a particular style of Chinese characters that are between
// serif-style Song and cursive-style Kai forms. This style is often used
// for government documents.
Fangsong
// Custom is a custom font name that is specified in the [text.Style]
// CustomFont name.
Custom
)
// Slants (also called style) allows italic or oblique faces to be selected.
type Slants int32 //enums:enum -trim-prefix Slant -transform kebab
const (
// A face that is neither italic not obliqued.
SlantNormal Slants = iota
// A form that is generally cursive in nature or slanted.
// This groups what is usually called Italic or Oblique.
Italic
)
// Weights are the degree of blackness or stroke thickness of a font.
// The corresponding value ranges from 100.0 to 900.0, with 400.0 as normal.
type Weights int32 //enums:enum -transform kebab
const (
// Thin weight (100), the thinnest value.
Thin Weights = iota
// Extra light weight (200).
ExtraLight
// Light weight (300).
Light
// Normal (400).
Normal
// Medium weight (500, higher than normal).
Medium
// Semibold weight (600).
Semibold
// Bold weight (700).
Bold
// Extra-bold weight (800).
ExtraBold
// Black weight (900), the thickest value.
Black
)
// ToFloat32 converts the weight to its numerical 100x value
func (w Weights) ToFloat32() float32 {
return float32((w + 1) * 100)
}
// WeightFromFloat32 returns the weight of the given numerical weight,
// as in CSS and OpenType (100 = [Thin], 400 = [Normal], 700 = [Bold]),
// the inverse of [Weights.ToFloat32].
func WeightFromFloat32(w float32) Weights {
return Weights(min(max(int(math.Round(float64(w)/100))-1, int(Thin)), int(Black)))
}
func (w Weights) HTMLTag() string {
switch w {
case Bold:
return "b"
}
return ""
}
// Stretch is the width of a font as an approximate fraction of the normal width.
// Widths range from 0.5 to 2.0 inclusive, with 1.0 as the normal width.
type Stretch int32 //enums:enum -trim-prefix Stretch -transform kebab
const (
// Ultra-condensed width (50%), the narrowest possible.
UltraCondensed Stretch = iota
// Extra-condensed width (62.5%).
ExtraCondensed
// Condensed width (75%).
Condensed
// Semi-condensed width (87.5%).
SemiCondensed
// Normal width (100%).
StretchNormal
// Semi-expanded width (112.5%).
SemiExpanded
// Expanded width (125%).
Expanded
// Extra-expanded width (150%).
ExtraExpanded
// Ultra-expanded width (200%), the widest possible.
UltraExpanded
)
var stretchFloatValues = []float32{0.5, 0.625, 0.75, 0.875, 1, 1.125, 1.25, 1.5, 2.0}
// ToFloat32 converts the stretch to its numerical multiplier value
func (s Stretch) ToFloat32() float32 {
return stretchFloatValues[s]
}
// note: 11 bits reserved, 8 used
// Decorations are underline, line-through, etc, as bit flags
// that must be set using [Font.SetDecoration].
type Decorations int32 //enums:bitflag -transform kebab
const (
// Underline indicates to place a line below text.
Underline Decorations = iota
// Overline indicates to place a line above text.
Overline
// LineThrough indicates to place a line through text.
LineThrough
// DottedUnderline is used for abbr tag.
DottedUnderline
// ParagraphStart indicates that this text is the start of a paragraph,
// and therefore may be indented according to [text.Style] settings.
ParagraphStart
// fillColor means that the fill color of the glyph is set.
// The standard font rendering uses this fill color (compare to StrokeColor).
fillColor
// strokeColor means that the stroke color of the glyph is set.
// This is normally not rendered: it looks like an outline of the glyph at
// larger font sizes, and will make smaller font sizes look significantly thicker.
strokeColor
// background means that the background region behind the text is colored.
// The background is not normally colored so it renders over any background.
background
// colorFlagsMask is a mask for the color flags, to exclude them as needed.
colorFlagsMask = 1<<fillColor | 1<<strokeColor | 1<<background
)
// NumColors returns the number of colors used by this decoration setting.
func (d Decorations) NumColors() int {
nc := 0
if d.HasFlag(fillColor) {
nc++
}
if d.HasFlag(strokeColor) {
nc++
}
if d.HasFlag(background) {
nc++
}
return nc
}
// Specials are special additional mutually exclusive formatting factors that are not
// otherwise captured by changes in font rendering properties or decorations.
// Each special must be terminated by an End span element, on its own, which
// pops the stack on the last special that was started.
// Use [Text.StartSpecial] and [Text.EndSpecial] to manage the specials,
// avoiding the potential for repeating the start of a given special.
type Specials int32 //enums:enum -transform kebab
const (
// Nothing special.
Nothing Specials = iota
// Super starts super-scripted text.
Super
// Sub starts sub-scripted text.
Sub
// Link starts a hyperlink, which is in the URL field of the
// style, and encoded in the runes after the style runes.
// It also identifies this span for functional interactions
// such as hovering and clicking. It does not specify the styling,
// which therefore must be set in addition.
Link
// MathInline starts a TeX formatted math sequence, styled for
// inclusion inline with other text.
MathInline
// MathDisplay starts a TeX formatted math sequence, styled as
// a larger standalone display.
MathDisplay
// Quote starts an indented paragraph-level quote.
Quote
// todo: could add SmallCaps here?
// End must be added to terminate the last Special started: use [Text.AddEnd].
// The renderer maintains a stack of special elements.
End
)
// Directions specifies the text layout direction.
type Directions int32 //enums:enum -transform kebab
const (
// LTR is Left-to-Right text.
LTR Directions = iota
// RTL is Right-to-Left text.
RTL
// TTB is Top-to-Bottom text.
TTB
// BTT is Bottom-to-Top text.
BTT
// Default uses the [text.Style] default direction.
Default
)
// ToGoText returns the go-text version of direction.
func (d Directions) ToGoText() di.Direction {
return di.Direction(d)
}
// IsVertical returns true if given text is vertical.
func (d Directions) IsVertical() bool {
return d >= TTB && d <= BTT
}
// SetDecoration sets given decoration flag(s) on.
func (s *Style) SetDecoration(deco ...Decorations) *Style {
for _, d := range deco {
s.Decoration.SetFlag(true, d)
}
return s
}
func (s *Style) FillColor() color.Color {
if s.Decoration.HasFlag(fillColor) {
return s.fillColor
}
return nil
}
func (s *Style) StrokeColor() color.Color {
if s.Decoration.HasFlag(strokeColor) {
return s.strokeColor
}
return nil
}
func (s *Style) Background() color.Color {
if s.Decoration.HasFlag(background) {
return s.background
}
return nil
}
// SetFillColor sets the fill color to given color, setting the Decoration
// flag and the color value.
func (s *Style) SetFillColor(clr color.Color) *Style {
s.fillColor = clr
s.Decoration.SetFlag(clr != nil, fillColor)
return s
}
// SetStrokeColor sets the stroke color to given color, setting the Decoration
// flag and the color value.
// This is normally not set: it looks like an outline of the glyph at
// larger font sizes, and will make smaller font sizes look significantly thicker.
func (s *Style) SetStrokeColor(clr color.Color) *Style {
s.strokeColor = clr
s.Decoration.SetFlag(clr != nil, strokeColor)
return s
}
// SetBackground sets the background color to given color, setting the Decoration
// flag and the color value.
// The background is not normally colored so it renders over any background.
func (s *Style) SetBackground(clr color.Color) *Style {
s.background = clr
s.Decoration.SetFlag(clr != nil, background)
return s
}
// SetLinkStyle sets the default hyperlink styling: primary.Base color (e.g., blue)
// and Underline.
func (s *Style) SetLinkStyle() *Style {
s.SetFillColor(colors.ToUniform(colors.Scheme.Primary.Base))
s.Decoration.SetFlag(true, Underline)
return s
}
// SetLink sets the given style as a hyperlink, with given URL, and
// default link styling.
func (s *Style) SetLink(url string) *Style {
s.URL = url
s.Special = Link
return s.SetLinkStyle()
}
// IsMath returns true if is a Special MathInline or MathDisplay.
func (s *Style) IsMath() bool {
return s.Special == MathInline || s.Special == MathDisplay
}
func (s *Style) String() string {
var str strings.Builder
if s.Special == End {
return "{End Special}"
}
if s.Size != 1 {
fmt.Fprintf(&str, "%5.2fx ", s.Size)
}
if s.Family != SansSerif {
str.WriteString(s.Family.String())
str.WriteString(" ")
}
if s.Slant != SlantNormal {
str.WriteString(s.Slant.String())
str.WriteString(" ")
}
if s.Weight != Normal {
str.WriteString(s.Weight.String())
str.WriteString(" ")
}
if s.Stretch != StretchNormal {
str.WriteString(s.Stretch.String())
str.WriteString(" ")
}
if s.Special != Nothing {
str.WriteString(s.Special.String())
str.WriteString(" ")
if s.Special == Link {
str.WriteString("[")
str.WriteString(s.URL)
str.WriteString("] ")
}
}
for d := Underline; d <= ParagraphStart; d++ {
if s.Decoration.HasFlag(d) {
str.WriteString(d.BitIndexString())
str.WriteString(" ")
}
}
if s.Decoration.HasFlag(fillColor) {
str.WriteString("fill-color ")
}
if s.Decoration.HasFlag(strokeColor) {
str.WriteString("stroke-color ")
}
if s.Decoration.HasFlag(background) {
str.WriteString("background ")
}
return strings.TrimSpace(str.String())
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package rich provides the `rich.Text` type, which is the standard representation
// for formatted text, used as the input to the `shaped` package for text layout
// and rendering. It is encoded purely using `[]rune` slices for each span, with
// the style information represented with special rune values at the start of
// each span. This is an efficient and GPU-friendly pure-value format that
// avoids any issues of style struct pointer management etc.
package rich
import (
"fmt"
"slices"
"strings"
"unicode"
"cogentcore.org/core/text/textpos"
)
// Text is the basic rich text representation, with spans of []rune unicode characters
// that share a common set of text styling properties, which are represented
// by the first rune(s) in each span. If custom colors are used, they are encoded
// after the first style and size runes.
// This compact and efficient representation can be Join'd back into the raw
// unicode source, and indexing by rune index in the original is fast.
// It provides a GPU-compatible representation, and is the text equivalent of
// the [ppath.Path] encoding.
type Text [][]rune
// NewText returns a new [Text] starting with given style and runes string,
// which can be empty.
func NewText(s *Style, r []rune) Text {
tx := Text{}
tx.AddSpan(s, r)
return tx
}
// NewPlainText returns a new [Text] starting with default style and runes string,
// which can be empty.
func NewPlainText(r []rune) Text {
return NewText(NewStyle(), r)
}
// NumSpans returns the number of spans in this Text.
func (tx Text) NumSpans() int {
return len(tx)
}
// Len returns the total number of runes in this Text.
func (tx Text) Len() int {
n := 0
for _, s := range tx {
_, rn := SpanLen(s)
n += rn
}
return n
}
// Range returns the start, end range of indexes into original source
// for given span index.
func (tx Text) Range(span int) (start, end int) {
ci := 0
for si, s := range tx {
_, rn := SpanLen(s)
if si == span {
return ci, ci + rn
}
ci += rn
}
return -1, -1
}
// Index returns the span index, number of style runes at start of span,
// and index into actual runes within the span after style runes,
// for the given logical index into the original source rune slice
// without spans or styling elements.
// If the logical index is invalid for the text returns -1,-1,-1.
func (tx Text) Index(li int) (span, stylen, ridx int) {
ci := 0
for si, s := range tx {
sn, rn := SpanLen(s)
if li >= ci && li < ci+rn {
return si, sn, sn + (li - ci)
}
ci += rn
}
return -1, -1, -1
}
// AtTry returns the rune at given logical index, as in the original
// source rune slice without any styling elements. Returns 0
// and false if index is invalid.
func (tx Text) AtTry(li int) (rune, bool) {
ci := 0
for _, s := range tx {
sn, rn := SpanLen(s)
if li >= ci && li < ci+rn {
return s[sn+(li-ci)], true
}
ci += rn
}
return -1, false
}
// At returns the rune at given logical index into the original
// source rune slice without any styling elements. Returns 0
// if index is invalid. See AtTry for a version that also returns a bool
// indicating whether the index is valid.
func (tx Text) At(li int) rune {
r, _ := tx.AtTry(li)
return r
}
// Split returns the raw rune spans without any styles.
// The rune span slices here point directly into the Text rune slices.
// See SplitCopy for a version that makes a copy instead.
func (tx Text) Split() [][]rune {
ss := make([][]rune, 0, len(tx))
for _, s := range tx {
sn, _ := SpanLen(s)
ss = append(ss, s[sn:])
}
return ss
}
// SplitCopy returns the raw rune spans without any styles.
// The rune span slices here are new copies; see also [Text.Split].
func (tx Text) SplitCopy() [][]rune {
ss := make([][]rune, 0, len(tx))
for _, s := range tx {
sn, _ := SpanLen(s)
ss = append(ss, slices.Clone(s[sn:]))
}
return ss
}
// Join returns a single slice of runes with the contents of all span runes.
func (tx Text) Join() []rune {
ss := make([]rune, 0, tx.Len())
for _, s := range tx {
sn, _ := SpanLen(s)
if sn < len(s) {
ss = append(ss, s[sn:]...)
}
}
return ss
}
// Span returns the [Style] and []rune content for given span index.
// Returns nil if out of range.
func (tx Text) Span(si int) (*Style, []rune) {
n := len(tx)
if si < 0 || si >= n || len(tx[si]) == 0 {
return nil, nil
}
return NewStyleFromRunes(tx[si])
}
// SetSpanStyle sets the style for given span, updating the runes to encode it.
func (tx *Text) SetSpanStyle(si int, nsty *Style) *Text {
sty, r := tx.Span(si)
*sty = *nsty
nr := sty.ToRunes()
nr = append(nr, r...)
(*tx)[si] = nr
return tx
}
// SetSpanRunes sets the runes for given span.
func (tx *Text) SetSpanRunes(si int, r []rune) *Text {
sty, _ := tx.Span(si)
nr := sty.ToRunes()
nr = append(nr, r...)
(*tx)[si] = nr
return tx
}
// AddSpan adds a span to the Text using the given Style and runes.
// The Text is modified for convenience in the high-frequency use-case.
// Clone first to avoid changing the original.
func (tx *Text) AddSpan(s *Style, r []rune) *Text {
nr := s.ToRunes()
nr = append(nr, r...)
*tx = append(*tx, nr)
return tx
}
// AddSpanString adds a span to the Text using the given Style and string content.
// The Text is modified for convenience in the high-frequency use-case.
// Clone first to avoid changing the original.
func (tx *Text) AddSpanString(s *Style, r string) *Text {
nr := s.ToRunes()
nr = append(nr, []rune(r)...)
*tx = append(*tx, nr)
return tx
}
// InsertSpan inserts a span to the Text at given span index,
// using the given Style and runes.
// The Text is modified for convenience in the high-frequency use-case.
// Clone first to avoid changing the original.
func (tx *Text) InsertSpan(at int, s *Style, r []rune) *Text {
nr := s.ToRunes()
nr = append(nr, r...)
*tx = slices.Insert(*tx, at, nr)
return tx
}
// SplitSpan splits an existing span at the given logical source index,
// with the span containing that logical index truncated to contain runes
// just before the index, and a new span inserted starting at that index,
// with the remaining contents of the original containing span.
// If that logical index is already the start of a span, or the logical
// index is invalid, nothing happens. Returns the index of span,
// which will be negative if the logical index is out of range.
func (tx *Text) SplitSpan(li int) int {
si, sn, ri := tx.Index(li)
if si < 0 {
return si
}
if sn == ri { // already the start
return si
}
nr := slices.Clone((*tx)[si][:sn]) // style runes
nr = append(nr, (*tx)[si][ri:]...)
(*tx)[si] = (*tx)[si][:ri] // truncate
*tx = slices.Insert(*tx, si+1, nr)
return si + 1
}
// StartSpecial adds a Span of given Special type to the Text,
// using given style and rune text. This creates a new style
// with the special value set, to avoid accidentally repeating
// the start of new specials.
func (tx *Text) StartSpecial(s *Style, special Specials, r []rune) *Text {
ss := *s
ss.Special = special
return tx.AddSpan(&ss, r)
}
// EndSpecial adds an [End] Special to the Text, to terminate the current
// Special. All [Specials] must be terminated with this empty end tag.
func (tx *Text) EndSpecial() *Text {
s := NewStyle()
s.Special = End
return tx.AddSpan(s, nil)
}
// InsertEndSpecial inserts an [End] Special to the Text at given span
// index, to terminate the current Special. All [Specials] must be
// terminated with this empty end tag.
func (tx *Text) InsertEndSpecial(at int) *Text {
s := NewStyle()
s.Special = End
return tx.InsertSpan(at, s, nil)
}
// SpecialRange returns the range of spans for the
// special starting at given span index. Returns -1 if span
// at given index is not a special.
func (tx Text) SpecialRange(si int) textpos.Range {
sp := RuneToSpecial(tx[si][0])
if sp == Nothing {
return textpos.Range{Start: -1, End: -1}
}
depth := 1
n := len(tx)
for j := si + 1; j < n; j++ {
s := RuneToSpecial(tx[j][0])
switch s {
case End:
depth--
if depth == 0 {
return textpos.Range{Start: si, End: j}
}
case Nothing: // a span of text in the special, as of an element in it
default:
depth++
}
}
return textpos.Range{Start: -1, End: -1}
}
// AddLink adds a [Link] special with given url and label text.
// This calls StartSpecial and EndSpecial for you. If the link requires
// further formatting, use those functions separately.
func (tx *Text) AddLink(s *Style, url, label string) *Text {
ss := *s
ss.URL = url
tx.StartSpecial(&ss, Link, []rune(label))
return tx.EndSpecial()
}
// AddSuper adds a [Super] special with given text.
// This calls StartSpecial and EndSpecial for you. If the Super requires
// further formatting, use those functions separately.
func (tx *Text) AddSuper(s *Style, text string) *Text {
tx.StartSpecial(s, Super, []rune(text))
return tx.EndSpecial()
}
// AddSub adds a [Sub] special with given text.
// This calls StartSpecial and EndSpecial for you. If the Sub requires
// further formatting, use those functions separately.
func (tx *Text) AddSub(s *Style, text string) *Text {
tx.StartSpecial(s, Sub, []rune(text))
return tx.EndSpecial()
}
// AddMathInline adds a [MathInline] special with given text.
// This calls StartSpecial and EndSpecial for you. If the Math requires
// further formatting, use those functions separately.
func (tx *Text) AddMathInline(s *Style, text string) *Text {
tx.StartSpecial(s, MathInline, []rune(text))
return tx.EndSpecial()
}
// AddMathDisplay adds a [MathDisplay] special with given text.
// This calls StartSpecial and EndSpecial for you. If the Math requires
// further formatting, use those functions separately.
func (tx *Text) AddMathDisplay(s *Style, text string) *Text {
tx.StartSpecial(s, MathDisplay, []rune(text))
return tx.EndSpecial()
}
// AddRunes adds given runes to current span.
// If no existing span, then a new default one is made.
func (tx *Text) AddRunes(r []rune) *Text {
n := len(*tx)
if n == 0 {
return tx.AddSpan(NewStyle(), r)
}
(*tx)[n-1] = append((*tx)[n-1], r...)
return tx
}
func (tx Text) String() string {
var str strings.Builder
for _, rs := range tx {
s := &Style{}
ss := s.FromRunes(rs)
sstr := s.String()
str.WriteString("[")
str.WriteString(sstr)
str.WriteString("]: \"")
str.WriteString(string(ss))
str.WriteString("\"\n")
}
return str.String()
}
// Join joins multiple texts into one text. Just appends the spans.
func Join(txts ...Text) Text {
nt := Text{}
for _, tx := range txts {
nt = append(nt, tx...)
}
return nt
}
func (tx Text) DebugDump() {
for i := range tx {
s, r := tx.Span(i)
fmt.Println(i, len(tx[i]), tx[i])
fmt.Printf("style: %#v\n", s)
fmt.Printf("chars: %q\n", string(r))
}
}
// Clone returns a deep copy clone of the current text, safe for subsequent
// modification without affecting this one.
func (tx Text) Clone() Text {
ct := make(Text, len(tx))
for i := range tx {
ct[i] = slices.Clone(tx[i])
}
return ct
}
// SplitSpaces splits this text after first unicode space after non-space.
func (tx *Text) SplitSpaces() {
txt := tx.Join()
if len(txt) == 0 {
return
}
prevSp := unicode.IsSpace(txt[0])
for i, r := range txt {
isSp := unicode.IsSpace(r)
if prevSp && isSp {
continue
}
if isSp {
prevSp = true
tx.SplitSpan(i + 1) // already doesn't re-split
} else {
prevSp = false
}
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
Package runes provides a small subset of functions for rune slices that are found in the
strings and bytes standard packages. For rendering and other logic, it is best to
keep raw data in runes, and not having to convert back and forth to bytes or strings
is more efficient.
These are largely copied from the strings or bytes packages.
*/
package runes
import (
"unicode"
"unicode/utf8"
"cogentcore.org/core/base/slicesx"
)
// SetFromBytes sets slice of runes from given slice of bytes,
// using efficient memory reallocation of existing slice.
// returns potentially modified slice: use assign to update.
func SetFromBytes(rs []rune, s []byte) []rune {
n := utf8.RuneCount(s)
rs = slicesx.SetLength(rs, n)
i := 0
for len(s) > 0 {
r, l := utf8.DecodeRune(s)
rs[i] = r
i++
s = s[l:]
}
return rs
}
const maxInt = int(^uint(0) >> 1)
// Equal reports whether a and b
// are the same length and contain the same bytes.
// A nil argument is equivalent to an empty slice.
func Equal(a, b []rune) bool {
// Neither cmd/compile nor gccgo allocates for these string conversions.
return string(a) == string(b)
}
// // Compare returns an integer comparing two byte slices lexicographically.
// // The result will be 0 if a == b, -1 if a < b, and +1 if a > b.
// // A nil argument is equivalent to an empty slice.
// func Compare(a, b []rune) int {
// return bytealg.Compare(a, b)
// }
// Count counts the number of non-overlapping instances of sep in s.
// If sep is an empty slice, Count returns 1 + the number of UTF-8-encoded code points in s.
func Count(s, sep []rune) int {
n := 0
for {
i := Index(s, sep)
if i == -1 {
return n
}
n++
s = s[i+len(sep):]
}
}
// Contains reports whether subslice is within b.
func Contains(b, subslice []rune) bool {
return Index(b, subslice) != -1
}
// ContainsRune reports whether the rune is contained in the UTF-8-encoded byte slice b.
func ContainsRune(b []rune, r rune) bool {
return Index(b, []rune{r}) >= 0
// return IndexRune(b, r) >= 0
}
// ContainsFunc reports whether any of the UTF-8-encoded code points r within b satisfy f(r).
func ContainsFunc(b []rune, f func(rune) bool) bool {
return IndexFunc(b, f) >= 0
}
// containsRune is a simplified version of strings.ContainsRune
// to avoid importing the strings package.
// We avoid bytes.ContainsRune to avoid allocating a temporary copy of s.
func containsRune(s string, r rune) bool {
for _, c := range s {
if c == r {
return true
}
}
return false
}
// Trim returns a subslice of s by slicing off all leading and
// trailing UTF-8-encoded code points contained in cutset.
func Trim(s []rune, cutset string) []rune {
if len(s) == 0 {
// This is what we've historically done.
return nil
}
if cutset == "" {
return s
}
return TrimLeft(TrimRight(s, cutset), cutset)
}
// TrimLeft returns a subslice of s by slicing off all leading
// UTF-8-encoded code points contained in cutset.
func TrimLeft(s []rune, cutset string) []rune {
if len(s) == 0 {
// This is what we've historically done.
return nil
}
if cutset == "" {
return s
}
for len(s) > 0 {
r := s[0]
if !containsRune(cutset, r) {
break
}
s = s[1:]
}
if len(s) == 0 {
// This is what we've historically done.
return nil
}
return s
}
// TrimRight returns a subslice of s by slicing off all trailing
// UTF-8-encoded code points that are contained in cutset.
func TrimRight(s []rune, cutset string) []rune {
if len(s) == 0 || cutset == "" {
return s
}
for len(s) > 0 {
r := s[len(s)-1]
if !containsRune(cutset, r) {
break
}
s = s[:len(s)-1]
}
return s
}
// TrimSpace returns a subslice of s by slicing off all leading and
// trailing white space, as defined by Unicode.
func TrimSpace(s []rune) []rune {
return TrimFunc(s, unicode.IsSpace)
}
// TrimLeftFunc treats s as UTF-8-encoded bytes and returns a subslice of s by slicing off
// all leading UTF-8-encoded code points c that satisfy f(c).
func TrimLeftFunc(s []rune, f func(r rune) bool) []rune {
i := indexFunc(s, f, false)
if i == -1 {
return nil
}
return s[i:]
}
// TrimRightFunc returns a subslice of s by slicing off all trailing
// UTF-8-encoded code points c that satisfy f(c).
func TrimRightFunc(s []rune, f func(r rune) bool) []rune {
i := lastIndexFunc(s, f, false)
return s[0 : i+1]
}
// TrimFunc returns a subslice of s by slicing off all leading and trailing
// UTF-8-encoded code points c that satisfy f(c).
func TrimFunc(s []rune, f func(r rune) bool) []rune {
return TrimRightFunc(TrimLeftFunc(s, f), f)
}
// TrimPrefix returns s without the provided leading prefix string.
// If s doesn't start with prefix, s is returned unchanged.
func TrimPrefix(s, prefix []rune) []rune {
if HasPrefix(s, prefix) {
return s[len(prefix):]
}
return s
}
// TrimSuffix returns s without the provided trailing suffix string.
// If s doesn't end with suffix, s is returned unchanged.
func TrimSuffix(s, suffix []rune) []rune {
if HasSuffix(s, suffix) {
return s[:len(s)-len(suffix)]
}
return s
}
// Replace returns a copy of the slice s with the first n
// non-overlapping instances of old replaced by new.
// The old string cannot be empty.
// If n < 0, there is no limit on the number of replacements.
func Replace(s, old, new []rune, n int) []rune {
if len(old) == 0 {
panic("runes Replace: old cannot be empty")
}
m := 0
if n != 0 {
// Compute number of replacements.
m = Count(s, old)
}
if m == 0 {
// Just return a copy.
return append([]rune(nil), s...)
}
if n < 0 || m < n {
n = m
}
// Apply replacements to buffer.
t := make([]rune, len(s)+n*(len(new)-len(old)))
w := 0
start := 0
for i := 0; i < n; i++ {
j := start
if len(old) == 0 {
if i > 0 {
j++
}
} else {
j += Index(s[start:], old)
}
w += copy(t[w:], s[start:j])
w += copy(t[w:], new)
start = j + len(old)
}
w += copy(t[w:], s[start:])
return t[0:w]
}
// ReplaceAll returns a copy of the slice s with all
// non-overlapping instances of old replaced by new.
// If old is empty, it matches at the beginning of the slice
// and after each UTF-8 sequence, yielding up to k+1 replacements
// for a k-rune slice.
func ReplaceAll(s, old, new []rune) []rune {
return Replace(s, old, new, -1)
}
// EqualFold reports whether s and t are equal under Unicode case-folding.
// copied from strings.EqualFold
func EqualFold(s, t []rune) bool {
for len(s) > 0 && len(t) > 0 {
// Extract first rune from each string.
var sr, tr rune
sr, s = s[0], s[1:]
tr, t = t[0], t[1:]
// If they match, keep going; if not, return false.
// Easy case.
if tr == sr {
continue
}
// Make sr < tr to simplify what follows.
if tr < sr {
tr, sr = sr, tr
}
// Fast check for ASCII.
if tr < utf8.RuneSelf {
// ASCII only, sr/tr must be upper/lower case
if 'A' <= sr && sr <= 'Z' && tr == sr+'a'-'A' {
continue
}
return false
}
// General case. SimpleFold(x) returns the next equivalent rune > x
// or wraps around to smaller values.
r := unicode.SimpleFold(sr)
for r != sr && r < tr {
r = unicode.SimpleFold(r)
}
if r == tr {
continue
}
return false
}
// One string is empty. Are both?
return len(s) == len(t)
}
// Index returns the index of given rune string in the text, returning -1 if not found.
func Index(txt, find []rune) int {
fsz := len(find)
if fsz == 0 {
return -1
}
tsz := len(txt)
if tsz < fsz {
return -1
}
mn := tsz - fsz
for i := 0; i <= mn; i++ {
found := true
for j := range find {
if txt[i+j] != find[j] {
found = false
break
}
}
if found {
return i
}
}
return -1
}
// IndexFold returns the index of given rune string in the text, using case folding
// (i.e., case insensitive matching). Returns -1 if not found.
func IndexFold(txt, find []rune) int {
fsz := len(find)
if fsz == 0 {
return -1
}
tsz := len(txt)
if tsz < fsz {
return -1
}
mn := tsz - fsz
for i := 0; i <= mn; i++ {
if EqualFold(txt[i:i+fsz], find) {
return i
}
}
return -1
}
// Repeat returns a new rune slice consisting of count copies of b.
//
// It panics if count is negative or if
// the result of (len(b) * count) overflows.
func Repeat(r []rune, count int) []rune {
if count == 0 {
return []rune{}
}
// Since we cannot return an error on overflow,
// we should panic if the repeat will generate
// an overflow.
// See Issue golang.org/issue/16237.
if count < 0 {
panic("runes: negative Repeat count")
} else if len(r)*count/count != len(r) {
panic("runes: Repeat count causes overflow")
}
nb := make([]rune, len(r)*count)
bp := copy(nb, r)
for bp < len(nb) {
copy(nb[bp:], nb[:bp])
bp *= 2
}
return nb
}
// Generic split: splits after each instance of sep,
// including sepSave bytes of sep in the subslices.
func genSplit(s, sep []rune, sepSave, n int) [][]rune {
if n == 0 {
return nil
}
if len(sep) == 0 {
panic("rune split: separator cannot be empty!")
}
if n < 0 {
n = Count(s, sep) + 1
}
if n > len(s)+1 {
n = len(s) + 1
}
a := make([][]rune, n)
n--
i := 0
for i < n {
m := Index(s, sep)
if m < 0 {
break
}
a[i] = s[: m+sepSave : m+sepSave]
s = s[m+len(sep):]
i++
}
a[i] = s
return a[:i+1]
}
// SplitN slices s into subslices separated by sep and returns a slice of
// the subslices between those separators.
// Sep cannot be empty.
// The count determines the number of subslices to return:
//
// n > 0: at most n subslices; the last subslice will be the unsplit remainder.
// n == 0: the result is nil (zero subslices)
// n < 0: all subslices
//
// To split around the first instance of a separator, see Cut.
func SplitN(s, sep []rune, n int) [][]rune { return genSplit(s, sep, 0, n) }
// SplitAfterN slices s into subslices after each instance of sep and
// returns a slice of those subslices.
// If sep is empty, SplitAfterN splits after each UTF-8 sequence.
// The count determines the number of subslices to return:
//
// n > 0: at most n subslices; the last subslice will be the unsplit remainder.
// n == 0: the result is nil (zero subslices)
// n < 0: all subslices
func SplitAfterN(s, sep []rune, n int) [][]rune {
return genSplit(s, sep, len(sep), n)
}
// Split slices s into all subslices separated by sep and returns a slice of
// the subslices between those separators.
// If sep is empty, Split splits after each UTF-8 sequence.
// It is equivalent to SplitN with a count of -1.
//
// To split around the first instance of a separator, see Cut.
func Split(s, sep []rune) [][]rune { return genSplit(s, sep, 0, -1) }
// SplitAfter slices s into all subslices after each instance of sep and
// returns a slice of those subslices.
// If sep is empty, SplitAfter splits after each UTF-8 sequence.
// It is equivalent to SplitAfterN with a count of -1.
func SplitAfter(s, sep []rune) [][]rune {
return genSplit(s, sep, len(sep), -1)
}
// Fields interprets s as a sequence of UTF-8-encoded code points.
// It splits the slice s around each instance of one or more consecutive white space
// characters, as defined by unicode.IsSpace, returning a slice of subslices of s or an
// empty slice if s contains only white space.
func Fields(s []rune) [][]rune {
return FieldsFunc(s, unicode.IsSpace)
}
// FieldsFunc interprets s as a sequence of UTF-8-encoded code points.
// It splits the slice s at each run of code points c satisfying f(c) and
// returns a slice of subslices of s. If all code points in s satisfy f(c), or
// len(s) == 0, an empty slice is returned.
//
// FieldsFunc makes no guarantees about the order in which it calls f(c)
// and assumes that f always returns the same value for a given c.
func FieldsFunc(s []rune, f func(rune) bool) [][]rune {
// A span is used to record a slice of s of the form s[start:end].
// The start index is inclusive and the end index is exclusive.
type span struct {
start int
end int
}
spans := make([]span, 0, 32)
// Find the field start and end indices.
// Doing this in a separate pass (rather than slicing the string s
// and collecting the result substrings right away) is significantly
// more efficient, possibly due to cache effects.
start := -1 // valid span start if >= 0
for end, rune := range s {
if f(rune) {
if start >= 0 {
spans = append(spans, span{start, end})
// Set start to a negative value.
// Note: using -1 here consistently and reproducibly
// slows down this code by a several percent on amd64.
start = ^start
}
} else {
if start < 0 {
start = end
}
}
}
// Last field might end at EOF.
if start >= 0 {
spans = append(spans, span{start, len(s)})
}
// Create strings from recorded field indices.
a := make([][]rune, len(spans))
for i, span := range spans {
a[i] = s[span.start:span.end:span.end] // last end makes it copy
}
return a
}
// Join concatenates the elements of s to create a new byte slice. The separator
// sep is placed between elements in the resulting slice.
func Join(s [][]rune, sep []rune) []rune {
if len(s) == 0 {
return []rune{}
}
if len(s) == 1 {
// Just return a copy.
return append([]rune(nil), s[0]...)
}
var n int
if len(sep) > 0 {
if len(sep) >= maxInt/(len(s)-1) {
panic("bytes: Join output length overflow")
}
n += len(sep) * (len(s) - 1)
}
for _, v := range s {
if len(v) > maxInt-n {
panic("bytes: Join output length overflow")
}
n += len(v)
}
b := make([]rune, n)
bp := copy(b, s[0])
for _, v := range s[1:] {
bp += copy(b[bp:], sep)
bp += copy(b[bp:], v)
}
return b
}
// HasPrefix reports whether the byte slice s begins with prefix.
func HasPrefix(s, prefix []rune) bool {
return len(s) >= len(prefix) && Equal(s[0:len(prefix)], prefix)
}
// HasSuffix reports whether the byte slice s ends with suffix.
func HasSuffix(s, suffix []rune) bool {
return len(s) >= len(suffix) && Equal(s[len(s)-len(suffix):], suffix)
}
// IndexFunc interprets s as a sequence of UTF-8-encoded code points.
// It returns the byte index in s of the first Unicode
// code point satisfying f(c), or -1 if none do.
func IndexFunc(s []rune, f func(r rune) bool) int {
return indexFunc(s, f, true)
}
// LastIndexFunc interprets s as a sequence of UTF-8-encoded code points.
// It returns the byte index in s of the last Unicode
// code point satisfying f(c), or -1 if none do.
func LastIndexFunc(s []rune, f func(r rune) bool) int {
return lastIndexFunc(s, f, true)
}
// indexFunc is the same as IndexFunc except that if
// truth==false, the sense of the predicate function is
// inverted.
func indexFunc(s []rune, f func(r rune) bool, truth bool) int {
for i, r := range s {
if f(r) == truth {
return i
}
}
return -1
}
// lastIndexFunc is the same as LastIndexFunc except that if
// truth==false, the sense of the predicate function is
// inverted.
func lastIndexFunc(s []rune, f func(r rune) bool, truth bool) int {
for i := len(s) - 1; i >= 0; i-- {
v := s[i]
if f(v) == truth {
return i
}
}
return -1
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package search
import (
"errors"
"io/fs"
"path/filepath"
"regexp"
"sort"
"cogentcore.org/core/base/fileinfo"
"cogentcore.org/core/core"
"cogentcore.org/core/text/textpos"
)
// All returns list of all files under given root path, in all subdirs,
// of given language(s) that contain the given string, sorted in
// descending order by number of occurrences.
// - useCase is whether the search is case-sensitive ([textpos.UseCase]).
// - regExp uses the go regexp syntax for the find string.
// - exclude is a list of filenames to exclude.
func All(root, find string, useCase textpos.CaseSensitive, regExp textpos.MatchSyntax, langs []fileinfo.Known, exclude ...string) ([]Results, error) {
fsz := len(find)
if fsz == 0 {
return nil, nil
}
fb := []byte(find)
var re *regexp.Regexp
var err error
if regExp {
re, err = regexp.Compile(find)
if err != nil {
return nil, err
}
}
mls := make([]Results, 0)
var errs []error
filepath.Walk(root, func(fpath string, info fs.FileInfo, err error) error {
if err != nil {
errs = append(errs, err)
return err
}
if info.IsDir() {
return nil
}
if int(info.Size()) > core.SystemSettings.BigFileSize {
return nil
}
fname := info.Name()
skip, err := excludeFile(&exclude, fname, fpath)
if err != nil {
errs = append(errs, err)
}
if skip {
return nil
}
fi, err := fileinfo.NewFileInfo(fpath)
if err != nil {
errs = append(errs, err)
}
if fi.Generated {
return nil
}
if !LangCheck(fi, langs) {
return nil
}
var cnt int
var matches []textpos.Match
if regExp {
cnt, matches = FileRegexp(fpath, re)
} else {
cnt, matches = File(fpath, fb, useCase)
}
if cnt > 0 {
fpabs, err := filepath.Abs(fpath)
if err != nil {
errs = append(errs, err)
}
mls = append(mls, Results{fpabs, cnt, matches})
}
return nil
})
sort.Slice(mls, func(i, j int) bool {
return mls[i].Count > mls[j].Count
})
return mls, errors.Join(errs...)
}
// Copyright (c) 2020, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package search
import (
"bufio"
"bytes"
"fmt"
"io"
"log"
"os"
"regexp"
"strings"
"unicode/utf8"
"cogentcore.org/core/text/parse/lexer"
"cogentcore.org/core/text/runes"
"cogentcore.org/core/text/textpos"
)
// Results is used to report search results.
type Results struct {
Filepath string
Count int
Matches []textpos.Match
}
func (r *Results) String() string {
var str strings.Builder
str.WriteString(fmt.Sprintf("%s: %d", r.Filepath, r.Count))
for _, m := range r.Matches {
str.WriteString("\n" + m.String())
}
return str.String()
}
// RuneLines looks for a string (no regexp) within lines of runes,
// with given case-sensitivity returning number of occurrences
// and specific match position list. Column positions are in runes.
func RuneLines(src [][]rune, find []byte, useCase textpos.CaseSensitive) (int, []textpos.Match) {
fr := bytes.Runes(find)
fsz := len(fr)
if fsz == 0 {
return 0, nil
}
cnt := 0
var matches []textpos.Match
for ln, rn := range src {
sz := len(rn)
ci := 0
for ci < sz {
var i int
if useCase == textpos.IgnoreCase {
i = runes.IndexFold(rn[ci:], fr)
} else {
i = runes.Index(rn[ci:], fr)
}
if i < 0 {
break
}
i += ci
ci = i + fsz
mat := textpos.NewMatch(rn, i, ci, ln)
matches = append(matches, mat)
cnt++
}
}
return cnt, matches
}
// LexItems looks for a string (no regexp),
// as entire lexically tagged items,
// with given case-sensitivity returning number of occurrences
// and specific match position list. Column positions are in runes.
func LexItems(src [][]rune, lexs []lexer.Line, find []byte, useCase textpos.CaseSensitive) (int, []textpos.Match) {
fr := bytes.Runes(find)
fsz := len(fr)
if fsz == 0 {
return 0, nil
}
cnt := 0
var matches []textpos.Match
mx := min(len(src), len(lexs))
for ln := range mx {
rln := src[ln]
lxln := lexs[ln]
for _, lx := range lxln {
sz := lx.End - lx.Start
if sz != fsz {
continue
}
rn := rln[lx.Start:lx.End]
var i int
if useCase == textpos.IgnoreCase {
i = runes.IndexFold(rn, fr)
} else {
i = runes.Index(rn, fr)
}
if i < 0 {
continue
}
mat := textpos.NewMatch(rln, lx.Start, lx.End, ln)
matches = append(matches, mat)
cnt++
}
}
return cnt, matches
}
// Reader looks for a literal string (no regexp) from an io.Reader input stream,
// using given case-sensitivity.
// Returns number of occurrences and specific match position list.
// Column positions are in runes.
func Reader(reader io.Reader, find []byte, useCase textpos.CaseSensitive) (int, []textpos.Match) {
fr := bytes.Runes(find)
fsz := len(fr)
if fsz == 0 {
return 0, nil
}
cnt := 0
var matches []textpos.Match
scan := bufio.NewScanner(reader)
ln := 0
for scan.Scan() {
rn := bytes.Runes(scan.Bytes()) // note: temp -- must copy -- convert to runes anyway
sz := len(rn)
ci := 0
for ci < sz {
var i int
if useCase == textpos.IgnoreCase {
i = runes.IndexFold(rn[ci:], fr)
} else {
i = runes.Index(rn[ci:], fr)
}
if i < 0 {
break
}
i += ci
ci = i + fsz
mat := textpos.NewMatch(rn, i, ci, ln)
matches = append(matches, mat)
cnt++
}
ln++
}
return cnt, matches
}
// File looks for a literal string (no regexp) within a file, in given
// case-sensitive way, returning number of occurrences and specific match
// position list. Column positions are in runes.
func File(filename string, find []byte, useCase textpos.CaseSensitive) (int, []textpos.Match) {
fp, err := os.Open(filename)
if err != nil {
log.Printf("search.File: open error: %v\n", err)
return 0, nil
}
defer fp.Close()
return Reader(fp, find, useCase)
}
// ReaderRegexp looks for a string using Go regexp expression,
// from an io.Reader input stream.
// Returns number of occurrences and specific match position list.
// Column positions are in runes.
func ReaderRegexp(reader io.Reader, re *regexp.Regexp) (int, []textpos.Match) {
cnt := 0
var matches []textpos.Match
scan := bufio.NewScanner(reader)
ln := 0
for scan.Scan() {
b := scan.Bytes() // note: temp -- must copy -- convert to runes anyway
fi := re.FindAllIndex(b, -1)
if fi == nil {
ln++
continue
}
sz := len(b)
ri := make([]int, sz+1) // byte indexes to rune indexes
rn := make([]rune, 0, sz)
for i, w := 0, 0; i < sz; i += w {
r, wd := utf8.DecodeRune(b[i:])
w = wd
ri[i] = len(rn)
rn = append(rn, r)
}
ri[sz] = len(rn)
for _, f := range fi {
st := f[0]
ed := f[1]
mat := textpos.NewMatch(rn, ri[st], ri[ed], ln)
matches = append(matches, mat)
cnt++
}
ln++
}
return cnt, matches
}
// FileRegexp looks for a string using Go regexp expression
// within a file, returning number of occurrences and specific match
// position list. Column positions are in runes.
func FileRegexp(filename string, re *regexp.Regexp) (int, []textpos.Match) {
fp, err := os.Open(filename)
if err != nil {
log.Printf("search.FileRegexp: open error: %v\n", err)
return 0, nil
}
defer fp.Close()
return ReaderRegexp(fp, re)
}
// RuneLinesRegexp looks for a regexp within lines of runes,
// with given case-sensitivity returning number of occurrences
// and specific match position list. Column positions are in runes.
func RuneLinesRegexp(src [][]rune, re *regexp.Regexp) (int, []textpos.Match) {
cnt := 0
var matches []textpos.Match
for ln := range src {
// note: insane that we have to convert back and forth from bytes!
b := []byte(string(src[ln]))
fi := re.FindAllIndex(b, -1)
if fi == nil {
continue
}
sz := len(b)
ri := make([]int, sz+1) // byte indexes to rune indexes
rn := make([]rune, 0, sz)
for i, w := 0, 0; i < sz; i += w {
r, wd := utf8.DecodeRune(b[i:])
w = wd
ri[i] = len(rn)
rn = append(rn, r)
}
ri[sz] = len(rn)
for _, f := range fi {
st := f[0]
ed := f[1]
mat := textpos.NewMatch(rn, ri[st], ri[ed], ln)
matches = append(matches, mat)
cnt++
}
}
return cnt, matches
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package search
import (
"errors"
"os"
"path/filepath"
"regexp"
"slices"
"sort"
"cogentcore.org/core/base/fileinfo"
"cogentcore.org/core/core"
"cogentcore.org/core/text/textpos"
)
// excludeFile does the exclude match against either file name or file path,
// removes any problematic exclude expressions from the list.
func excludeFile(exclude *[]string, fname, fpath string) (bool, error) {
var errs []error
for ei, ex := range *exclude {
exp, err := filepath.Match(ex, fpath)
if err != nil {
errs = append(errs, err)
*exclude = slices.Delete(*exclude, ei, ei+1)
}
if exp {
return true, errors.Join(errs...)
}
exf, _ := filepath.Match(ex, fname)
if exf {
return true, errors.Join(errs...)
}
}
return false, errors.Join(errs...)
}
// LangCheck checks if file matches list of target languages: true if
// matches (or no langs)
func LangCheck(fi *fileinfo.FileInfo, langs []fileinfo.Known) bool {
if len(langs) == 0 {
return true
}
if fileinfo.IsMatchList(langs, fi.Known) {
return true
}
return false
}
// Paths returns list of all files in given list of paths (only: no subdirs),
// of language(s) that contain the given string, sorted in descending order
// by number of occurrences. Paths can be relative to current working directory.
// Automatically skips generated files.
// - useCase is whether the search is case-sensitive ([textpos.UseCase]).
// - regExp uses the go regexp syntax for the find string.
// - exclude is a list of filenames to exclude: can use standard Glob patterns.
func Paths(paths []string, find string, useCase textpos.CaseSensitive, regExp textpos.MatchSyntax, langs []fileinfo.Known, exclude ...string) ([]Results, error) {
fsz := len(find)
if fsz == 0 {
return nil, nil
}
fb := []byte(find)
var re *regexp.Regexp
var err error
if regExp {
re, err = regexp.Compile(find)
if err != nil {
return nil, err
}
}
mls := make([]Results, 0)
var errs []error
for _, path := range paths {
files, err := os.ReadDir(path)
if err != nil {
errs = append(errs, err)
continue
}
for _, de := range files {
if de.IsDir() {
continue
}
fname := de.Name()
fpath := filepath.Join(path, fname)
skip, err := excludeFile(&exclude, fname, fpath)
if err != nil {
errs = append(errs, err)
}
if skip {
continue
}
fi, err := fileinfo.NewFileInfo(fpath)
if err != nil {
errs = append(errs, err)
}
if int(fi.Size) > core.SystemSettings.BigFileSize {
continue
}
if fi.Generated {
continue
}
if !LangCheck(fi, langs) {
continue
}
var cnt int
var matches []textpos.Match
if regExp {
cnt, matches = FileRegexp(fpath, re)
} else {
cnt, matches = File(fpath, fb, useCase)
}
if cnt > 0 {
fpabs, err := filepath.Abs(fpath)
if err != nil {
errs = append(errs, err)
}
mls = append(mls, Results{fpabs, cnt, matches})
}
}
}
sort.Slice(mls, func(i, j int) bool {
return mls[i].Count > mls[j].Count
})
return mls, errors.Join(errs...)
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package shaped
import (
"fmt"
"image"
"image/color"
"strings"
"cogentcore.org/core/math32"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/text"
"cogentcore.org/core/text/textpos"
"golang.org/x/image/math/fixed"
)
// todo: split source at para boundaries and use wrap para on those.
// Lines is a list of Lines of shaped text, with an overall bounding
// box and position for the entire collection. This is the renderable
// unit of text, although it is not a [render.Item] because it lacks
// a position, and it can potentially be re-used in different positions.
type Lines struct {
// Source is the original input source that generated this set of lines.
// Each Line has its own set of spans that describes the Line contents.
Source rich.Text
// Lines are the shaped lines.
Lines []Line
// Offset is an optional offset to add to the position given when rendering.
Offset math32.Vector2
// Bounds is the bounding box for the entire set of rendered text,
// relative to a rendering Position (and excluding any contribution
// of Offset). Use Size() method to get the size and ToRect() to get
// an [image.Rectangle].
Bounds math32.Box2
// FontSize is the [rich.Context] StandardSize from the Context used
// at the time of shaping. Actual lines can be larger depending on font
// styling parameters.
FontSize float32
// LineHeight is the line height used at the time of shaping.
LineHeight float32
// Truncated indicates whether any lines were truncated.
Truncated bool
// Direction is the default text rendering direction from the Context.
Direction rich.Directions
// Links holds any hyperlinks within shaped text.
Links []rich.Hyperlink
// Color is the default fill color to use for inking text.
Color color.Color
// SelectionColor is the color to use for rendering selected regions.
SelectionColor image.Image
// HighlightColor is the color to use for rendering highlighted regions.
HighlightColor image.Image
// Anchor provides a named link destination associated with this text item.
// Used for document navigation, e.g., in PDF rendering. Must be a unique name.
// Is set in [core.Text] based on the id property, which is set by [content].
Anchor string
}
// Line is one line of shaped text, containing multiple Runs.
// This is not an independent render target: see [Lines] (can always
// use one Line per Lines as needed).
type Line struct {
// Source is the input source corresponding to the line contents,
// derived from the original Lines Source. The style information for
// each Run is embedded here.
Source rich.Text
// SourceRange is the range of runes in the original [Lines.Source] that
// are represented in this line.
SourceRange textpos.Range
// Runs are the shaped [Run] elements.
Runs []Run
// Offset specifies the relative offset from the Lines Position
// determining where to render the line in a target render image.
// This is the baseline position (not the upper left: see Bounds for that).
Offset math32.Vector2
// Bounds is the bounding box for the Line of rendered text,
// relative to the baseline rendering position (excluding any contribution
// of Offset). This is centered at the baseline and the upper left
// typically has a negative Y. Use Size() method to get the size
// and ToRect() to get an [image.Rectangle]. This is based on the output
// LineBounds, not the actual GlyphBounds.
Bounds math32.Box2
// Selections specifies region(s) of runes within this line that are selected,
// and will be rendered with the [Lines.SelectionColor] background,
// replacing any other background color that might have been specified.
Selections []textpos.Range
// Highlights specifies region(s) of runes within this line that are highlighted,
// and will be rendered with the [Lines.HighlightColor] background,
// replacing any other background color that might have been specified.
Highlights []textpos.Range
}
func (ln *Line) String() string {
return ln.Source.String() + fmt.Sprintf(" runs: %d\n", len(ln.Runs))
}
func (ls *Lines) String() string {
var str strings.Builder
for li := range ls.Lines {
ln := &ls.Lines[li]
fmt.Fprintf(&str, "#### Line: %d\n", li)
str.WriteString(ln.String())
}
return str.String()
}
// StartAtBaseline removes the offset from the first line that causes
// the lines to be rendered starting at the upper left corner, so they
// will instead be rendered starting at the baseline position.
func (ls *Lines) StartAtBaseline() {
if len(ls.Lines) == 0 {
return
}
ls.Lines[0].Offset = math32.Vector2{}
}
// SetGlyphXAdvance sets the x advance on all glyphs to given value:
// for monospaced case. If width is non-nil, it returns the number of
// cells for each rune, by which its advance is multiplied, for wide
// characters that take two cells.
func (ls *Lines) SetGlyphXAdvance(adv fixed.Int26_6, width func(r rune) int) {
var cells func(ri int) int
if width != nil {
src := ls.Source.Join()
cells = func(ri int) int {
if ri < 0 || ri >= len(src) {
return 1
}
return width(src[ri])
}
}
for li := range ls.Lines {
ln := &ls.Lines[li]
for ri := range ln.Runs {
rn := ln.Runs[ri]
rn.SetGlyphXAdvance(adv, cells)
}
}
}
// GetLinks gets the links for these lines, which are cached in Links.
func (ls *Lines) GetLinks() []rich.Hyperlink {
if ls.Links != nil {
return ls.Links
}
ls.Links = ls.Source.GetLinks()
return ls.Links
}
// AlignXFactor aligns the lines along X axis according to alignment factor,
// as a proportion of size difference to add to offset (0.5 = center,
// 1 = right)
func (ls *Lines) AlignXFactor(fact float32) {
wd := ls.Bounds.Size().X
for li := range ls.Lines {
ln := &ls.Lines[li]
lwd := ln.Bounds.Size().X
if lwd < wd {
ln.Offset.X += fact * (wd - lwd)
}
}
}
// AlignX aligns the lines along X axis according to text style.
func (ls *Lines) AlignX(tsty *text.Style) {
fact, _ := tsty.AlignFactors()
if fact > 0 {
ls.AlignXFactor(fact)
}
}
// Clone returns a Clone copy of the Lines, with new Lines elements
// that still point to the same underlying Runs.
func (ls *Lines) Clone() *Lines {
nls := &Lines{}
*nls = *ls
nln := len(ls.Lines)
if nln > 0 {
nln := make([]Line, nln)
copy(nln, ls.Lines)
nls.Lines = nln
}
return nls
}
// UpdateStyle updates the Decoration, Fill and Stroke colors from the given
// rich.Text Styles for each line and given text style.
// This rich.Text must match the content of the shaped one, and differ only
// in these non-layout styles.
func (ls *Lines) UpdateStyle(tx rich.Text, tsty *text.Style) {
ls.Source = tx
ls.Color = tsty.Color
for i := range ls.Lines {
ln := &ls.Lines[i]
ln.UpdateStyle(tx, tsty)
}
}
// UpdateStyle updates the Decoration, Fill and Stroke colors from the current
// rich.Text Style for each run and given text style.
// This rich.Text must match the content of the shaped one, and differ only
// in these non-layout styles.
func (ln *Line) UpdateStyle(tx rich.Text, tsty *text.Style) {
ln.Source = tx
for ri, rn := range ln.Runs {
fs := ln.RunStyle(ln.Source, ri)
rb := rn.AsBase()
rb.SetFromStyle(fs, tsty)
}
}
// RunStyle returns the rich text style for given run index.
func (ln *Line) RunStyle(tx rich.Text, ri int) *rich.Style {
rn := ln.Runs[ri]
rs := rn.Runes().Start
si, _, _ := tx.Index(rs)
sty, _ := tx.Span(si)
return sty
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package shaped
import (
"cogentcore.org/core/math32"
"cogentcore.org/core/text/textpos"
)
// SelectRegion adds the selection to given region of runes from
// the original source runes. Use SelectReset to clear first if desired.
func (ls *Lines) SelectRegion(r textpos.Range) {
nr := ls.Source.Len()
r = r.Intersect(textpos.Range{Start: 0, End: nr})
for li := range ls.Lines {
ln := &ls.Lines[li]
lr := r.Intersect(ln.SourceRange)
if lr.Len() > 0 {
ln.Selections = append(ln.Selections, lr)
}
}
}
// SelectReset removes all existing selected regions.
func (ls *Lines) SelectReset() {
for li := range ls.Lines {
ln := &ls.Lines[li]
ln.Selections = nil
}
}
// HighlightRegion adds the selection(s) to given region of runes from
// the original source runes. Use HighlightReset to clear first if desired.
func (ls *Lines) HighlightRegion(rs ...textpos.Range) {
nr := ls.Source.Len()
for _, r := range rs {
r = r.Intersect(textpos.Range{Start: 0, End: nr})
for li := range ls.Lines {
ln := &ls.Lines[li]
lr := r.Intersect(ln.SourceRange)
if lr.Len() > 0 {
ln.Highlights = append(ln.Highlights, lr)
}
}
}
}
// HighlightReset removes all existing selected regions.
func (ls *Lines) HighlightReset() {
for li := range ls.Lines {
ln := &ls.Lines[li]
ln.Highlights = nil
}
}
// RuneToLinePos returns the [textpos.Pos] line and character position for given rune
// index in Lines source. If ti >= source Len(), returns a position just after
// the last actual rune.
func (ls *Lines) RuneToLinePos(ti int) textpos.Pos {
if len(ls.Lines) == 0 {
return textpos.Pos{}
}
n := ls.Source.Len()
el := len(ls.Lines) - 1
ep := textpos.Pos{Line: el, Char: ls.Lines[el].SourceRange.End}
if ti >= n {
return ep
}
for li := range ls.Lines {
ln := &ls.Lines[li]
if !ln.SourceRange.Contains(ti) {
continue
}
return textpos.Pos{Line: li, Char: ti - ln.SourceRange.Start}
}
return ep // shouldn't happen
}
// RuneFromLinePos returns the rune index in Lines source for given
// [textpos.Pos] line and character position. Returns Len() of source
// if it goes past that.
func (ls *Lines) RuneFromLinePos(tp textpos.Pos) int {
if len(ls.Lines) == 0 {
return 0
}
n := ls.Source.Len()
nl := len(ls.Lines)
if tp.Line >= nl {
return n
}
ln := &ls.Lines[tp.Line]
return ln.SourceRange.Start + tp.Char
}
// RuneAtLineDelta returns the rune index in Lines source at given
// relative vertical offset in lines from the current line for given rune.
// It uses pixel locations of glyphs and the LineHeight to find the
// rune at given vertical offset with the same horizontal position.
// If the delta goes out of range, it will return the appropriate in-range
// rune index at the closest horizontal position.
func (ls *Lines) RuneAtLineDelta(ti, lineDelta int) int {
rp := ls.RuneBounds(ti).Center()
tp := rp
ld := float32(lineDelta) * ls.LineHeight // todo: should iterate over lines for different sizes..
tp.Y = math32.Clamp(tp.Y+ld, ls.Bounds.Min.Y+2, ls.Bounds.Max.Y-2)
return ls.RuneAtPoint(tp, math32.Vector2{})
}
// RuneBounds returns the glyph bounds for given rune index in Lines source,
// relative to the upper-left corner of the lines bounding box.
// If the index is >= the source length, it returns a box at the end of the
// rendered text (i.e., where a cursor should be to add more text).
func (ls *Lines) RuneBounds(ti int) math32.Box2 {
n := ls.Source.Len()
zb := math32.Box2{}
if len(ls.Lines) == 0 {
return zb
}
start := ls.Offset
if ti >= n { // goto end
ln := ls.Lines[len(ls.Lines)-1]
off := start.Add(ln.Offset)
ep := ln.Bounds.Max.Add(off)
ep.Y = ln.Bounds.Min.Y + off.Y
return math32.Box2{Min: ep, Max: ep}
}
for li := range ls.Lines {
ln := &ls.Lines[li]
if !ln.SourceRange.Contains(ti) {
continue
}
off := start.Add(ln.Offset)
for ri := range ln.Runs {
run := ln.Runs[ri]
rr := run.Runes()
if ti >= rr.End {
off.X += run.Advance()
continue
}
bb := run.RuneBounds(ti)
return bb.Translate(off)
}
}
return zb
}
// RuneAtPoint returns the rune index in Lines source, at given rendered location,
// based on given starting location for rendering. If the point is out of the
// line bounds, the nearest point is returned (e.g., start of line based on Y coordinate).
func (ls *Lines) RuneAtPoint(pt math32.Vector2, start math32.Vector2) int {
start.SetAdd(ls.Offset)
lbb := ls.Bounds.Translate(start)
if !lbb.ContainsPoint(pt) {
// smaller bb so point will be inside stuff
sbb := math32.Box2{Min: lbb.Min.Add(math32.Vec2(0, 2)), Max: lbb.Max.Sub(math32.Vec2(0, 2))}
pt = sbb.ClampPoint(pt)
}
nl := len(ls.Lines)
for li := range ls.Lines {
ln := &ls.Lines[li]
off := start.Add(ln.Offset)
lbb := ln.Bounds.Translate(off)
if !lbb.ContainsPoint(pt) {
if pt.Y >= lbb.Min.Y && pt.Y < lbb.Max.Y { // this is our line
if pt.X <= lbb.Min.X {
return ln.SourceRange.Start
}
return ln.SourceRange.End
}
continue
}
for ri := range ln.Runs {
run := ln.Runs[ri]
rbb := run.AsBase().MaxBounds.Translate(off)
if !rbb.ContainsPoint(pt) {
off.X += run.Advance()
continue
}
rp := run.RuneAtPoint(ls.Source, pt, off)
if rp == run.Runes().End && li < nl-1 { // if not at full end, don't go past
rp--
}
return rp
}
return ln.SourceRange.End
}
return 0
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package shaped
import (
"image"
"cogentcore.org/core/colors"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint/ppath"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/text"
"cogentcore.org/core/text/textpos"
"golang.org/x/image/math/fixed"
)
// Run is a span of shaped text with the same font properties,
// with layout information to enable GUI interaction with shaped text.
type Run interface {
// AsBase returns the base type with relevant shaped text information.
AsBase() *RunBase
// LineBounds returns the Line-level Bounds for given Run as rect bounding box.
LineBounds() math32.Box2
// Runes returns our rune range in original source using textpos.Range.
Runes() textpos.Range
// Advance returns the total distance to advance in going from one run to the next.
Advance() float32
// RuneBounds returns the maximal line-bounds level bounding box for given rune index.
RuneBounds(ri int) math32.Box2
// RuneAtPoint returns the rune index in Lines source, at given rendered location,
// based on given starting location for rendering. If the point is out of the
// line bounds, the nearest point is returned (e.g., start of line based on Y coordinate).
RuneAtPoint(src rich.Text, pt math32.Vector2, start math32.Vector2) int
// SetGlyphXAdvance sets the x advance on all glyphs to given value:
// for monospaced case. If cells is non-nil, the advance of each glyph is
// multiplied by the number of cells for the index of its source rune,
// for wide characters.
SetGlyphXAdvance(adv fixed.Int26_6, cells func(ri int) int)
}
// Math holds the output of a TeX math expression.
type Math struct {
Path ppath.Path
BBox math32.Box2
}
// RunBase is a span of text with the same font properties, with full rendering information.
type RunBase struct {
// Font is the [text.Font] compact encoding of the font to use for rendering.
Font text.Font
// MaxBounds are the maximal line-level bounds for this run, suitable for region
// rendering and mouse interaction detection.
MaxBounds math32.Box2
// Decoration are the decorations from the style to apply to this run.
Decoration rich.Decorations
// Math holds the output of Math formatting via the tex package.
Math Math
// FillColor is the color to use for glyph fill (i.e., the standard "ink" color).
// Will only be non-nil if set for this run; Otherwise use default.
FillColor image.Image
// StrokeColor is the color to use for glyph outline stroking, if non-nil.
StrokeColor image.Image
// Background is the color to use for the background region, if non-nil.
Background image.Image
}
// SetFromStyle sets the run styling parameters from given styles.
// Will also update non-Font elements, but font can only be set first time
// in the initial shaping process, otherwise the render is off.
func (run *RunBase) SetFromStyle(sty *rich.Style, tsty *text.Style) {
run.Decoration = sty.Decoration
if run.Font.Size == 0 {
run.Font = *text.NewFont(sty, tsty)
}
run.FillColor = colors.Uniform(sty.FillColor())
run.StrokeColor = colors.Uniform(sty.StrokeColor())
run.Background = colors.Uniform(sty.Background())
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package shaped provides the interfaces and types of the shaping of rich text
// into lines of runs of glyphs, for rendering.
package shaped
import (
"cogentcore.org/core/math32"
"cogentcore.org/core/paint/ppath"
"cogentcore.org/core/text/fonts"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/text"
"github.com/cogentcore/typesetting/di"
)
//go:generate core generate
var (
// NewShaper returns the correct type of shaper.
NewShaper func() Shaper
// ShapeMath is a function that returns a path representing the
// given math expression, in TeX syntax.
// Import _ cogentcore.org/core/text/tex to set this function
// (incurs a significant additional memory footprint due to fonts
// and other packages), or call texcache.SetShapeMath() from
// cogentcore.org/core/text/texcache for fully cached version that
// saves on all the memory, but requires all equations to be generated
// in advance and saved.
ShapeMath func(expr string, fontHeight float32) (ppath.Path, error)
)
// Shaper is a text shaping system that can shape the layout of [rich.Text],
// including line wrapping. All functions are protected by a mutex.
type Shaper interface {
// Shape turns given input spans into [Runs] of rendered text,
// using given context needed for complete styling.
// The results are only valid until the next call to Shape or WrapParagraph:
// use slices.Clone if needed longer than that.
// This is called under a mutex lock, so it is safe for parallel use.
Shape(tx rich.Text, tsty *text.Style) []Run
// WrapLines performs line wrapping and shaping on the given rich text source,
// using the given style information, where the [rich.Style] provides the default
// style information reflecting the contents of the source (e.g., the default family,
// weight, etc), for use in computing the default line height. Paragraphs are extracted
// first using standard newline markers, assumed to coincide with separate spans in the
// source text, and wrapped separately. For horizontal text, the Lines will render with
// a position offset at the upper left corner of the overall bounding box of the text.
// This is called under a mutex lock, so it is safe for parallel use.
WrapLines(tx rich.Text, defSty *rich.Style, tsty *text.Style, size math32.Vector2) *Lines
// FontFamilies returns a list of available font family names on this system.
FontList() []fonts.Info
}
// WrapSizeEstimate is the size to use for layout during the SizeUp pass,
// for word wrap case, where the sizing actually matters,
// based on trying to fit the given number of characters into the given content size
// with given font height, and ratio of width to height.
// Ratio is used when csz is 0: 1.618 is golden, and smaller numbers to allow
// for narrower, taller text columns.
func WrapSizeEstimate(csz math32.Vector2, nChars int, ratio float32, sty *rich.Style, tsty *text.Style) math32.Vector2 {
chars := float32(nChars)
fht := tsty.FontHeight(sty)
if fht == 0 {
fht = 16
}
area := chars * fht * fht
if csz.X > 0 && csz.Y > 0 {
ratio = csz.X / csz.Y
}
// w = ratio * h
// w * h = a
// h^2 = a / r
// h = sqrt(a / r)
h := math32.Sqrt(area / ratio)
h = max(fht*math32.Floor(h/fht), fht)
w := area / h
if w < csz.X { // must be at least this
w = csz.X
h = area / w
h = max(h, csz.Y)
}
sz := math32.Vec2(w, h)
return sz
}
// GoTextDirection gets the proper go-text direction value from styles.
func GoTextDirection(rdir rich.Directions, tsty *text.Style) di.Direction {
dir := tsty.Direction
if rdir != rich.Default {
dir = rdir
}
return dir.ToGoText()
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package shapedgt
import (
"fmt"
"slices"
"strings"
"github.com/cogentcore/typesetting/font"
"github.com/cogentcore/typesetting/font/opentype"
"github.com/cogentcore/typesetting/fontscan"
"github.com/cogentcore/typesetting/language"
)
// maxFaceSets is the number of queries and scripts that a [fontMap] keeps
// the faces of runes for before it starts over.
const maxFaceSets = 64
// fontMap is a [fontscan.FontMap] that keeps the faces of runes per query
// and script, and does not set the query or script that it already has,
// which the shaper sets for every span and the segmenter for every script
// run. The FontMap keeps the candidate fonts of its recent queries and
// scripts itself, which used to be built again on every face cache miss
// after a new query, as text alternates between families.
type fontMap struct {
*fontscan.FontMap
// query and script are the last ones set, when hasQuery and hasScript.
query fontscan.Query
script language.Script
hasQuery bool
hasScript bool
// faces are the faces of runes resolved for the query and script, when
// they are set; faceSets has those of each query and script. The FontMap
// itself caches faces by a hash of the query families and the rune, which
// costs more than shaping the rune when the query changes span by span.
faces map[rune]*font.Face
faceSets map[string]map[rune]*font.Face
// variants are the faces of variable fonts with the weight of a query
// (as the variable web fonts of pages, of which the FontMap gives the
// default instance), which are faces of their own, as the runs that
// are shaped with them keep them for rendering.
variants map[faceVariant]*font.Face
}
// faceVariant is the key of a variant of a face of a variable font.
type faceVariant struct {
face *font.Face
weight float32
}
// wghtTag is the tag of the weight axis of variable fonts.
var wghtTag = opentype.MustNewTag("wght")
// variant returns the face with the weight of the query, for a variable
// font with a weight axis, or the face itself.
func (fm *fontMap) variant(face *font.Face) *font.Face {
if face == nil || !fm.hasQuery || fm.query.Aspect.Weight == 0 {
return face
}
key := faceVariant{face, float32(fm.query.Aspect.Weight)}
if v, ok := fm.variants[key]; ok {
return v
}
v := font.NewFace(face.Font)
v.SetVariations([]font.Variation{{Tag: wghtTag, Value: key.weight}})
if len(v.Coords()) == 0 { // not a variable font
v = face
}
if fm.variants == nil || len(fm.variants) >= 256 {
fm.variants = map[faceVariant]*font.Face{}
}
fm.variants[key] = v
return v
}
// ResolveFace returns the face of the rune for the query and script.
func (fm *fontMap) ResolveFace(r rune) *font.Face {
// Without both set, the FontMap resolves it as it is.
if fm.faces == nil {
if !fm.hasQuery || !fm.hasScript {
return fm.FontMap.ResolveFace(r)
}
fm.useFaceSet()
}
// The face of a rune is resolved once.
if face, ok := fm.faces[r]; ok {
return face
}
face := fm.variant(fm.FontMap.ResolveFace(r))
fm.faces[r] = face
return face
}
// useFaceSet sets faces to the set for the current query and script.
func (fm *fontMap) useFaceSet() {
key := fmt.Sprintf("%s\x00%v\x00%v", strings.Join(fm.query.Families, "\x00"), fm.query.Aspect, fm.script)
if fm.faceSets == nil || len(fm.faceSets) >= maxFaceSets {
fm.faceSets = make(map[string]map[rune]*font.Face)
}
fm.faces = fm.faceSets[key]
if fm.faces == nil {
fm.faces = make(map[rune]*font.Face)
fm.faceSets[key] = fm.faces
}
}
// SetQuery sets the query of the font map unless it already has it.
func (fm *fontMap) SetQuery(query fontscan.Query) {
if fm.hasQuery && query.Aspect == fm.query.Aspect && slices.Equal(query.Families, fm.query.Families) {
return
}
fm.query = query
fm.hasQuery = true
fm.faces = nil
fm.FontMap.SetQuery(query)
}
// SetScript sets the script of the font map unless it already has it.
func (fm *fontMap) SetScript(script language.Script) {
if fm.hasScript && script == fm.script {
return
}
fm.script = script
fm.hasScript = true
fm.faces = nil
fm.FontMap.SetScript(script)
}
// forget forgets the last query and script, so that the next ones are always
// set, and the faces of runes, as when other code may have set the query or
// script of the FontMap, or added fonts to it.
func (fm *fontMap) forget() {
fm.hasQuery = false
fm.hasScript = false
fm.faces = nil
fm.faceSets = nil
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package shapedgt
import (
"os"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/text/fonts"
"cogentcore.org/core/text/rich"
"github.com/cogentcore/typesetting/fontscan"
)
// FontList returns the list of fonts that have been loaded.
func (sh *Shaper) FontList() []fonts.Info {
str := errors.Log1(os.UserCacheDir())
ft := errors.Log1(fontscan.SystemFonts(nil, str))
fi := make([]fonts.Info, len(ft))
for i := range ft {
fi[i].Family = ft[i].Family
as := ft[i].Aspect
fi[i].Weight = rich.WeightFromFloat32(float32(as.Weight))
fi[i].Slant = rich.Slants(as.Style - 1)
// fi[i].Stretch = rich.Stretch() // not avail
fi[i].Stretch = rich.StretchNormal
fi[i].Font = ft[i]
}
return fi
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package shapedgt
import (
"slices"
"cogentcore.org/core/math32"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/shaped"
"cogentcore.org/core/text/textpos"
"github.com/cogentcore/typesetting/di"
"github.com/cogentcore/typesetting/shaping"
"golang.org/x/image/math/fixed"
)
// Run is a span of text with the same font properties, with full rendering information.
type Run struct {
shaped.RunBase
shaping.Output
}
func (run *Run) AsBase() *shaped.RunBase {
return &run.RunBase
}
func (run *Run) Advance() float32 {
return math32.FromFixed(run.Output.Advance)
}
// Runes returns our rune range using textpos.Range
func (run *Run) Runes() textpos.Range {
return textpos.Range{Start: run.Output.Runes.Offset, End: run.Output.Runes.Offset + run.Output.Runes.Count}
}
// GlyphBoundsBox returns the math32.Box2 version of [Run.GlyphBounds],
// providing a tight bounding box for given glyph within this run.
func (run *Run) GlyphBoundsBox(g *shaping.Glyph) math32.Box2 {
if run.Math.Path != nil {
return run.MaxBounds
}
return math32.B2FromFixed(run.GlyphBounds(g))
}
// GlyphBounds returns the tight bounding box for given glyph within this run.
func (run *Run) GlyphBounds(g *shaping.Glyph) fixed.Rectangle26_6 {
if run.Math.Path != nil {
return run.MaxBounds.ToFixed()
}
if run.Direction.IsVertical() {
if run.Direction.IsSideways() {
return fixed.Rectangle26_6{Min: fixed.Point26_6{X: g.XBearing, Y: -g.YBearing}, Max: fixed.Point26_6{X: g.XBearing + g.Width, Y: -g.YBearing - g.Height}}
}
return fixed.Rectangle26_6{Min: fixed.Point26_6{X: -g.XBearing - g.Width/2, Y: g.Height - g.YOffset}, Max: fixed.Point26_6{X: g.XBearing + g.Width/2, Y: -(g.YBearing + g.Height) - g.YOffset}}
}
return fixed.Rectangle26_6{Min: fixed.Point26_6{X: g.XBearing, Y: -g.YBearing}, Max: fixed.Point26_6{X: g.XBearing + g.Width, Y: -g.YBearing - g.Height}}
}
// GlyphLineBoundsBox returns the math32.Box2 version of [Run.GlyphLineBounds],
// providing a line-level bounding box for given glyph within this run.
func (run *Run) GlyphLineBoundsBox(g *shaping.Glyph) math32.Box2 {
if run.Math.Path != nil {
return run.MaxBounds
}
return math32.B2FromFixed(run.GlyphLineBounds(g))
}
// GlyphLineBounds returns the line-level bounding box for given glyph within this run.
func (run *Run) GlyphLineBounds(g *shaping.Glyph) fixed.Rectangle26_6 {
if run.Math.Path != nil {
return run.MaxBounds.ToFixed()
}
rb := run.Bounds()
if run.Direction.IsVertical() { // todo: fixme
if run.Direction.IsSideways() {
return fixed.Rectangle26_6{Min: fixed.Point26_6{X: g.XBearing, Y: -g.YBearing}, Max: fixed.Point26_6{X: g.XBearing + g.Width, Y: -g.YBearing - g.Height}}
}
return fixed.Rectangle26_6{Min: fixed.Point26_6{X: -g.XBearing - g.Width/2, Y: g.Height - g.YOffset}, Max: fixed.Point26_6{X: g.XBearing + g.Width/2, Y: -(g.YBearing + g.Height) - g.YOffset}}
}
return fixed.Rectangle26_6{Min: fixed.Point26_6{X: g.XBearing, Y: rb.Min.Y}, Max: fixed.Point26_6{X: g.XBearing + g.Width, Y: rb.Max.Y}}
}
// LineBounds returns the LineBounds for given Run as a math32.Box2
// bounding box
func (run *Run) LineBounds() math32.Box2 {
if run.Math.Path != nil {
return run.MaxBounds
}
return math32.B2FromFixed(run.Bounds())
}
// Bounds returns the LineBounds for given Run as rect bounding box.
// See [Run.BoundsBox] for a version returning the float32 [math32.Box2].
func (run *Run) Bounds() fixed.Rectangle26_6 {
if run.Math.Path != nil {
return run.MaxBounds.ToFixed()
}
mb := run.MaxBounds
// todo: for a vertical run, ascent and descent describe horizontal, and
// advance is vertical: fixed.Rectangle26_6{Min: fixed.Point26_6{X: -lb.Ascent, Y: 0},
// Max: fixed.Point26_6{X: -gapdec, Y: -run.Output.Advance}}
return fixed.Rectangle26_6{Min: fixed.Point26_6{X: 0, Y: mb.Min.ToFixed().Y},
Max: fixed.Point26_6{X: run.Output.Advance, Y: mb.Max.ToFixed().Y}}
}
// RunBounds returns the Advance-based Bounds for this Run as rect bounding box,
// that reflects the total space of the run, using Ascent & Descent for font
// for the vertical dimension in horizontal text.
func (run *Run) RunBounds() fixed.Rectangle26_6 {
if run.Math.Path != nil {
return run.MaxBounds.ToFixed()
}
lb := &run.Output.LineBounds
if run.Direction.IsVertical() {
// ascent, descent describe horizontal, advance is vertical
return fixed.Rectangle26_6{Min: fixed.Point26_6{X: -lb.Ascent, Y: 0},
Max: fixed.Point26_6{X: -lb.Descent, Y: -run.Output.Advance}}
}
return fixed.Rectangle26_6{Min: fixed.Point26_6{X: 0, Y: -lb.Ascent},
Max: fixed.Point26_6{X: run.Output.Advance, Y: -lb.Descent}}
}
// GlyphsAt returns the indexs of the glyph(s) at given original source rune index.
// Empty if none found.
func (run *Run) GlyphsAt(i int) []int {
var gis []int
for gi := range run.Glyphs {
g := &run.Glyphs[gi]
if g.TextIndex() > i {
break
}
if g.TextIndex() == i {
gis = append(gis, gi)
}
}
return gis
}
// FirstGlyphAt returns the index of the first glyph at or above given original
// source rune index, returns -1 if none found.
func (run *Run) FirstGlyphAt(i int) int {
for gi := range run.Glyphs {
g := &run.Glyphs[gi]
if g.TextIndex() >= i {
return gi
}
}
return -1
}
// LastGlyphAt returns the index of the last glyph at given original source rune index,
// returns -1 if none found.
func (run *Run) LastGlyphAt(i int) int {
ng := len(run.Glyphs)
for gi := ng - 1; gi >= 0; gi-- {
g := &run.Glyphs[gi]
if g.TextIndex() <= i {
return gi
}
}
return -1
}
// SetGlyphXAdvance sets the x advance on all glyphs to given value:
// for monospaced case. If cells is non-nil, the advance of each glyph is
// multiplied by the number of cells for the index of its source rune,
// for wide characters, which are centered in their cells. Glyphs that
// do not have it yet are copied first, as runs of the shape cache share them.
func (run *Run) SetGlyphXAdvance(adv fixed.Int26_6, cells func(ri int) int) {
ncells := func(g *shaping.Glyph) int {
if cells == nil {
return 1
}
return cells(g.TextIndex())
}
if slices.ContainsFunc(run.Glyphs, func(g shaping.Glyph) bool { return g.Advance != adv*fixed.Int26_6(ncells(&g)) }) {
run.Glyphs = slices.Clone(run.Glyphs)
}
run.Output.Advance = 0
for gi := range run.Glyphs {
g := &run.Glyphs[gi]
n := ncells(g)
gadv := adv * fixed.Int26_6(n)
if n > 1 { // center in the cells, from the last advance
g.XOffset += (gadv - g.Advance) / 2
}
g.Advance = gadv
run.Output.Advance += g.Advance
}
if !run.Direction.IsVertical() { // the background etc use the max bounds
run.MaxBounds.Max.X = math32.FromFixed(run.Output.Advance)
}
}
// RuneAtPoint returns the index of the rune in the source, which contains given point,
// using the maximal glyph bounding box. Off is the offset for this run within overall
// image rendering context of point coordinates. Assumes point is already identified
// as being within the [Run.MaxBounds].
func (run *Run) RuneAtPoint(src rich.Text, pt, off math32.Vector2) int {
// todo: vertical case!
adv := off.X
rr := run.Runes()
for gi := range run.Glyphs {
g := &run.Glyphs[gi]
cri := g.TextIndex()
gadv := math32.FromFixed(g.Advance)
mx := adv + gadv
// fmt.Println(gi, cri, adv, mx, pt.X)
if pt.X >= adv && pt.X < mx {
// fmt.Println("fits!")
return cri
}
adv += gadv
}
return rr.End
}
// RuneBounds returns the maximal line-bounds level bounding box for given rune index.
func (run *Run) RuneBounds(ri int) math32.Box2 {
gis := run.GlyphsAt(ri)
if len(gis) == 0 {
return run.clusterRuneBounds(ri)
}
return run.GlyphRegionBounds(gis[0], gis[len(gis)-1])
}
// clusterRuneBounds returns the bounds of the given rune within the glyph
// cluster that it is shaped into, but does not start, such as the i of an
// fi ligature: its share of the advance of the cluster, from the start of
// the cluster in the direction of the run. Empty if it is not in a cluster.
func (run *Run) clusterRuneBounds(ri int) math32.Box2 {
if run.Direction.IsVertical() {
return math32.Box2{}
}
off, adv := float32(0), float32(0)
nr, k := 0, -1
for gi := range run.Glyphs {
g := &run.Glyphs[gi]
ga := math32.FromFixed(g.Advance)
if g.TextIndex() <= ri && ri < g.TextIndex()+g.RunesCount() {
adv += ga
nr, k = g.RunesCount(), ri-g.TextIndex()
continue
}
if k >= 0 {
break
}
off += ga
}
if k < 0 || nr == 0 {
return math32.Box2{}
}
// the share of the rune, counted from the right for right-to-left text
if run.Direction.Progression() != di.FromTopLeft {
k = nr - 1 - k
}
w := adv / float32(nr)
mb := run.MaxBounds
mb.Min.X = off + float32(k)*w
mb.Max.X = mb.Min.X + w
return mb
}
// GlyphRegionBounds returns the maximal line-bounds level bounding box
// between two glyphs in this run, where the st comes before the ed.
func (run *Run) GlyphRegionBounds(st, ed int) math32.Box2 {
if run.Direction.IsVertical() {
// todo: write me!
return math32.Box2{}
}
sg := &run.Glyphs[st]
stb := run.GlyphLineBoundsBox(sg)
mb := run.MaxBounds
off := float32(0)
for gi := range st {
g := &run.Glyphs[gi]
off += math32.FromFixed(g.Advance)
}
mb.Min.X = off + stb.Min.X - 2
for gi := st; gi <= ed; gi++ {
g := &run.Glyphs[gi]
gb := run.GlyphBoundsBox(g)
mb.Max.X = off + gb.Max.X + 2
off += math32.FromFixed(g.Advance)
}
return mb
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package shapedgt
import (
"math"
"slices"
"cogentcore.org/core/math32"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/shaped"
"cogentcore.org/core/text/text"
"github.com/cogentcore/typesetting/di"
"github.com/cogentcore/typesetting/segmenter"
"github.com/cogentcore/typesetting/shaping"
)
// maxShapeCache is the number of texts that the shape cache holds at most.
const maxShapeCache = 8192
// shapeCache caches the shaped outputs of texts. The layout of a text wraps
// it several times (sizing up and then down, in more than one iteration), at
// different sizes, and pages repeat texts (such as the cells of a table), but
// the shaping of a text does not depend on the size it is wrapped to. Shaping
// is the main cost of wrapping, so the cache saves most of it.
//
// When the cache is full, the least recently used text is dropped, so the
// texts that are in use, such as those of the rest of a window while an
// editor scrolls through a long text, are kept.
type shapeCache struct {
// entries are the cached texts by hash, with hash collisions chained.
entries map[uint32]*shapeEntry
// n is the number of entries.
n int
// newest and oldest are the most and least recently used entries,
// the ends of the list of entries in the order of their use.
newest, oldest *shapeEntry
// settings are the [rich.Settings] that the entries were shaped with.
settings rich.SettingsData
}
// shapeEntry is the shaped outputs of one text in a [shapeCache].
type shapeEntry struct {
// tx is a copy of the source text.
tx rich.Text
// fontSize, direction and customFont are the [text.Style] values that
// shaping depends on.
fontSize float32
direction rich.Directions
customFont rich.FontName
// outs are the shaped outputs, which callers get copies of.
outs []shaping.Output
// maths are the shaped math spans of the text by span index (see
// [Shaper.shapeMaths]), which are not changed once made.
maths map[int]*shaped.Math
// wraps are the most recent wrappings of the outputs.
wraps []wrapEntry
// hash is the hash of the text and style.
hash uint32
// seg has the line and grapheme break opportunities of the text,
// which the line wrapper uses for every wrapping of the text that
// is not cached; it is made by the first one (see [shapeEntry.segmenter]).
seg *segmenter.Segmenter
// next is the next entry with the same hash.
next *shapeEntry
// newer and older are the next entries in the order of their use.
newer, older *shapeEntry
}
// maxWraps is the number of wrappings of a text that a [shapeEntry] holds.
const maxWraps = 4
// wrapEntry is the lines of a text wrapped with a configuration and size.
type wrapEntry struct {
maxSize int
direction di.Direction
truncateAfter int
policy shaping.LineBreakPolicy
noTrim bool
truncator bool // whether the lines end with an ellipsis when cut
lines []shaping.Line
truncated int
// bounds are the most recent lines with bounds of the wrapped lines.
bounds []boundsEntry
}
// maxBounds is the number of lines with bounds that a [wrapEntry] holds.
const maxBounds = 2
// boundsKey has the values other than those of the [shapeEntry] and the
// [wrapEntry] that [Shaper.LinesBounds] depends on, except for the colors,
// which are set on each copy.
type boundsKey struct {
width float32 // the exact width, of which the wrap size is the integer part
defSize float32 // the size of the default style
lineHeight float32
whiteSpace text.WhiteSpaces
align text.Aligns
}
// boundsEntry is the lines with bounds of wrapped lines for a [boundsKey].
type boundsEntry struct {
key boundsKey
lines *shaped.Lines
}
// ResetCache empties the cache of shaped and wrapped texts, as when the
// fonts that they are measured with change.
// This should already have the mutex lock.
func (sh *Shaper) ResetCache() {
sh.shapes.reset()
}
// ForgetTexts removes the cached texts for which forget returns true, given
// the text and the custom font of its style, as when the fonts of some of
// their runes have changed, and returns how many it removed.
// This should already have the mutex lock, and is used by shapedjs.
func (sh *Shaper) ForgetTexts(forget func(tx rich.Text, customFont rich.FontName) bool) int {
return sh.shapes.forget(forget)
}
// forget removes the entries for which forget returns true (see [Shaper.ForgetTexts]).
func (sc *shapeCache) forget(forget func(tx rich.Text, customFont rich.FontName) bool) int {
removed := 0
for h, se := range sc.entries {
// The chain of the hash keeps the other entries, in order.
var kept, last *shapeEntry
for ; se != nil; se = se.next {
if forget(se.tx, se.customFont) {
sc.unlink(se)
removed++
continue
}
if last == nil {
kept = se
} else {
last.next = se
}
last = se
}
if last != nil {
last.next = nil
}
// A hash without entries is deleted.
if kept == nil {
delete(sc.entries, h)
} else {
sc.entries[h] = kept
}
}
sc.n -= removed
return removed
}
// reset empties the cache.
func (sc *shapeCache) reset() {
sc.entries = nil
sc.n = 0
sc.newest, sc.oldest = nil, nil
}
// hashText returns the hash of the text and the style values that shaping
// depends on (FNV-1a).
func hashText(tx rich.Text, tsty *text.Style) uint32 {
h := uint32(2166136261)
for _, s := range tx {
h = (h ^ uint32(len(s))) * 16777619
for _, r := range s {
h = (h ^ uint32(r)) * 16777619
}
}
h = (h ^ math.Float32bits(tsty.FontSize.Dots)) * 16777619
return (h ^ uint32(tsty.Direction)) * 16777619
}
// matches returns whether the entry is for the given text and style.
func (se *shapeEntry) matches(tx rich.Text, tsty *text.Style) bool {
if se.fontSize != tsty.FontSize.Dots || se.direction != tsty.Direction || se.customFont != tsty.CustomFont || len(se.tx) != len(tx) {
return false
}
for i, s := range tx {
if !slices.Equal(se.tx[i], s) {
return false
}
}
return true
}
// get returns the cache entry for the given text and style, with its hash,
// or nil if it is not cached.
func (sc *shapeCache) get(tx rich.Text, tsty *text.Style) (*shapeEntry, uint32) {
// Entries shaped with other global settings no longer apply.
if sc.settings != rich.Settings {
sc.reset()
sc.settings = rich.Settings
}
// The entry for the text, if any, is in the chain of its hash.
h := hashText(tx, tsty)
for se := sc.entries[h]; se != nil; se = se.next {
if se.matches(tx, tsty) {
if se != sc.newest {
sc.unlink(se)
sc.pushNewest(se)
}
return se, h
}
}
return nil, h
}
// add adds an entry with a copy of the outputs of the given text and style,
// with the hash that get returned.
func (sc *shapeCache) add(tx rich.Text, tsty *text.Style, h uint32, outs []shaping.Output) *shapeEntry {
// A full cache drops its least recently used entry.
if sc.entries == nil {
sc.entries = make(map[uint32]*shapeEntry)
}
if sc.n >= maxShapeCache {
sc.remove(sc.oldest)
}
// The entry has its own copies of the text and the outputs.
se := &shapeEntry{tx: make(rich.Text, len(tx)), fontSize: tsty.FontSize.Dots, direction: tsty.Direction, customFont: tsty.CustomFont, hash: h}
for i, s := range tx {
se.tx[i] = slices.Clone(s)
}
se.outs = copyOutputs(outs)
se.next = sc.entries[h]
sc.entries[h] = se
sc.pushNewest(se)
sc.n++
return se
}
// remove removes the entry from the cache.
func (sc *shapeCache) remove(se *shapeEntry) {
// The entry is taken out of the chain of its hash.
var prev *shapeEntry
for e := sc.entries[se.hash]; e != se; e = e.next {
prev = e
}
switch {
case prev != nil:
prev.next = se.next
case se.next != nil:
sc.entries[se.hash] = se.next
default:
delete(sc.entries, se.hash)
}
sc.unlink(se)
sc.n--
}
// pushNewest adds the entry to the list of entries in the order of their
// use as the most recently used one.
func (sc *shapeCache) pushNewest(se *shapeEntry) {
se.older = sc.newest
se.newer = nil
if sc.newest != nil {
sc.newest.newer = se
} else {
sc.oldest = se
}
sc.newest = se
}
// unlink removes the entry from the list of entries in the order of their use.
func (sc *shapeCache) unlink(se *shapeEntry) {
if se.newer != nil {
se.newer.older = se.older
} else {
sc.newest = se.older
}
if se.older != nil {
se.older.newer = se.newer
} else {
sc.oldest = se.newer
}
se.newer, se.older = nil, nil
}
// copyOutputs returns a copy of the outputs with their own glyphs, as line
// wrapping changes the glyphs at the ends of lines.
func copyOutputs(outs []shaping.Output) []shaping.Output {
cp := slices.Clone(outs)
for i := range cp {
cp[i].Glyphs = slices.Clone(cp[i].Glyphs)
}
return cp
}
// cacheable returns whether the shaped outputs of the text can be cached,
// which they cannot when the text is empty.
func cacheable(tx rich.Text) bool {
return tx.Len() > 0
}
// WrapLinesCached returns the lines of the text wrapped to the given size,
// as [Shaper.WrapLinesOutput] wraps the outputs of [Shaper.ShapeTextOutput],
// using a cache of the shaped outputs and wrapped lines of recent texts.
// The adjust function, if non-nil, adjusts the outputs of newly shaped texts
// and of newly wrapped lines, as shapedjs does with the measurements of the
// browser. As it adjusts the outputs of wrapped lines anew, the outputs of
// texts that fit on one line keep their adjustments, without trimming their
// trailing whitespace. The lines are the caller's to change.
// This should already have the mutex lock, and is used by shapedjs but is
// not an end-user call.
func (sh *Shaper) WrapLinesCached(tx rich.Text, defSty *rich.Style, tsty *text.Style, size math32.Vector2, adjust func(outs []shaping.Output)) ([]shaping.Line, int) {
lines, truncated, _, cached := sh.wrapCached(tx, defSty, tsty, size, adjust)
if cached {
lines = copyLines(lines)
}
return lines, truncated
}
// wrapCached is [Shaper.WrapLinesCached], also returning the cache entry of
// the wrapping, which is nil when it is not cached, and whether the lines are
// those of the entry, which were wrapped before and are not the caller's to change.
func (sh *Shaper) wrapCached(tx rich.Text, defSty *rich.Style, tsty *text.Style, size math32.Vector2, adjust func(outs []shaping.Output)) ([]shaping.Line, int, *wrapEntry, bool) {
cfg, maxSize := wrapConfig(defSty, tsty, size)
if truncates(tsty) {
cfg.Truncator = sh.truncator(defSty, tsty) // (before the text is shaped)
}
// Texts that cannot be cached are shaped and wrapped every time.
if !cacheable(tx) {
txt := tx.Join()
outs := sh.ShapeTextOutput(tx, tsty, txt)
if adjust != nil {
adjust(outs)
}
lines, truncated := sh.wrapOutputs(outs, txt, cfg, maxSize, adjust, nil)
return lines, truncated, nil, false
}
// The text is shaped unless it is cached, with its math spans, which its
// lines use, and its runes are only needed to wrap it.
var txt []rune
se, h := sh.shapes.get(tx, tsty)
if se == nil {
txt = tx.Join()
outs := sh.ShapeTextOutput(tx, tsty, txt)
if adjust != nil {
adjust(outs)
}
se = sh.shapes.add(tx, tsty, h, outs)
se.maths = sh.maths
}
sh.maths = se.maths
// The text is wrapped unless it is cached wrapped to this size.
if we := se.wrapEntry(cfg, maxSize); we != nil {
return we.lines, we.truncated, we, true
}
if txt == nil {
txt = tx.Join()
}
lines, truncated := sh.wrapOutputs(copyOutputs(se.outs), txt, cfg, maxSize, adjust, se)
return lines, truncated, se.addWrap(cfg, maxSize, lines, truncated), false
}
// WrapLinesBoundsCached returns the lines with bounds of the text wrapped to
// the given size, as [Shaper.LinesBounds] makes them from the lines of
// [Shaper.WrapLinesCached], using the cache of recent texts, which also
// keeps the lines with bounds of their recent wrappings. The adjust function
// is as for [Shaper.WrapLinesCached]. The lines are the caller's to change.
// This should already have the mutex lock, and is used by shapedjs but is
// not an end-user call.
func (sh *Shaper) WrapLinesBoundsCached(tx rich.Text, defSty *rich.Style, tsty *text.Style, size math32.Vector2, adjust func(outs []shaping.Output)) *shaped.Lines {
// Lines of wrappings that are not cached are made every time.
lines, truncated, we, cached := sh.wrapCached(tx, defSty, tsty, size, adjust)
if we == nil {
return sh.LinesBounds(lines, truncated, tx, defSty, tsty, size)
}
// Cached lines with bounds are copied.
key := boundsKey{width: size.X, defSize: defSty.Size, lineHeight: tsty.LineHeight, whiteSpace: tsty.WhiteSpace, align: tsty.Align}
for i := range we.bounds {
if be := &we.bounds[i]; be.key == key {
return copyBounds(be.lines, tx, tsty)
}
}
// New bounds are kept as a copy, replacing the oldest ones when there are maxBounds.
if cached {
lines = copyLines(lines)
}
lns := sh.LinesBounds(lines, truncated, tx, defSty, tsty, size)
be := boundsEntry{key: key, lines: copyBounds(lns, nil, tsty)}
if len(we.bounds) < maxBounds {
we.bounds = append(we.bounds, be)
} else {
copy(we.bounds, we.bounds[1:])
we.bounds[maxBounds-1] = be
}
return lns
}
// copyBounds returns a copy of the lines with bounds, with their own runs
// and spans, for the given source text and the colors of the given style.
// The runs share the glyphs, which [Run.SetGlyphXAdvance] copies before
// changing them, the only change made to the glyphs of shaped lines.
func copyBounds(lns *shaped.Lines, tx rich.Text, tsty *text.Style) *shaped.Lines {
cp := *lns
cp.Source = tx
cp.Color, cp.SelectionColor, cp.HighlightColor = tsty.Color, tsty.SelectColor, tsty.HighlightColor
cp.Lines = slices.Clone(lns.Lines)
for li := range cp.Lines {
ln := &cp.Lines[li]
ln.Source = slices.Clone(ln.Source)
for si := range ln.Source {
ln.Source[si] = slices.Clone(ln.Source[si])
}
ln.Runs = slices.Clone(ln.Runs)
for ri, r := range ln.Runs {
run := *r.(*Run)
ln.Runs[ri] = &run
}
}
return &cp
}
// wrapOutputs wraps the outputs into lines, adjusting the outputs of the
// lines with adjust if non-nil (see [Shaper.WrapLinesCached]). The cache
// entry of the text, if non-nil, keeps its break opportunities. The lines
// are only valid until the next call.
func (sh *Shaper) wrapOutputs(outs []shaping.Output, txt []rune, cfg shaping.WrapConfig, maxSize int, adjust func(outs []shaping.Output), se *shapeEntry) ([]shaping.Line, int) {
// Text that fits on one line does not need the line wrapper.
if lines, ok := singleLine(outs, txt, cfg, maxSize, adjust == nil && !cfg.DisableTrailingWhitespaceTrim); ok {
return lines, 0
}
// Wrapping can cut outputs, which are adjusted again.
var seg *segmenter.Segmenter
if se != nil {
seg = se.segmenter(txt)
}
lines, truncated := sh.wrapParagraph(cfg, maxSize, txt, outs, seg)
if adjust != nil {
for _, ln := range lines {
// the truncator (…) that ends a line that is cut is not of the
// text, whose runes adjust measures (its glyphs indexed it out
// of range, panicking on the web)
if n := len(ln); truncated > 0 && n > 0 && isTruncator(ln[n-1], cfg.Truncator) {
ln = ln[:n-1]
}
adjust(ln)
}
}
return lines, truncated
}
// isTruncator returns whether the given output is the given truncator,
// which the line wrapper adds to the end of a line that is cut.
func isTruncator(o, truncator shaping.Output) bool {
return len(o.Glyphs) > 0 && len(truncator.Glyphs) > 0 && &o.Glyphs[0] == &truncator.Glyphs[0]
}
// segmenter returns the segmenter of the entry, initialized with its text
// (the given runes) the first time.
func (se *shapeEntry) segmenter(txt []rune) *segmenter.Segmenter {
if se.seg == nil {
se.seg = &segmenter.Segmenter{}
se.seg.Init(txt)
}
return se.seg
}
// wrapEntry returns the cached wrapping of the entry with the given
// configuration and size, or nil if it is not cached.
func (se *shapeEntry) wrapEntry(cfg shaping.WrapConfig, maxSize int) *wrapEntry {
for i := range se.wraps {
if we := &se.wraps[i]; we.matches(cfg, maxSize) {
return we
}
}
return nil
}
// addWrap adds a copy of the lines of the entry wrapped with the given
// configuration and size, replacing the oldest one when it has maxWraps,
// and returns it, or nil when wrappings with the configuration are not cached.
func (se *shapeEntry) addWrap(cfg shaping.WrapConfig, maxSize int, lines []shaping.Line, truncated int) *wrapEntry {
we := wrapEntry{maxSize: maxSize, direction: cfg.Direction, truncateAfter: cfg.TruncateAfterLines, policy: cfg.BreakPolicy, noTrim: cfg.DisableTrailingWhitespaceTrim, truncator: len(cfg.Truncator.Glyphs) > 0, lines: copyLines(lines), truncated: truncated}
if !we.matches(cfg, maxSize) {
return nil
}
if len(se.wraps) < maxWraps {
se.wraps = append(se.wraps, we)
return &se.wraps[len(se.wraps)-1]
}
copy(se.wraps, se.wraps[1:])
se.wraps[maxWraps-1] = we
return &se.wraps[maxWraps-1]
}
// matches returns whether the wrapped lines are for the given configuration and size.
func (we *wrapEntry) matches(cfg shaping.WrapConfig, maxSize int) bool {
return we.maxSize == maxSize && we.direction == cfg.Direction && we.truncateAfter == cfg.TruncateAfterLines && we.policy == cfg.BreakPolicy && we.noTrim == cfg.DisableTrailingWhitespaceTrim && !cfg.TextContinues && we.truncator == (len(cfg.Truncator.Glyphs) > 0)
}
// copyLines returns a copy of the lines with their own outputs and glyphs.
func copyLines(lines []shaping.Line) []shaping.Line {
cp := make([]shaping.Line, len(lines))
for i, ln := range lines {
cp[i] = copyOutputs(ln)
}
return cp
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package shapedgt shapes text with the HarfBuzz shaper of go-text, and wraps
// it into lines.
package shapedgt
import (
"bytes"
"fmt"
"io/fs"
"os"
"sync"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/math32"
"cogentcore.org/core/text/fonts"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/shaped"
"cogentcore.org/core/text/text"
"github.com/cogentcore/typesetting/di"
"github.com/cogentcore/typesetting/font"
"github.com/cogentcore/typesetting/fontscan"
"github.com/cogentcore/typesetting/shaping"
"golang.org/x/image/math/fixed"
)
// Shaper is the text shaper and wrapper, from go-text/shaping.
type Shaper struct {
shaper shaping.HarfbuzzShaper
wrapper shaping.LineWrapper
fontMap fontMap
splitter shaping.Segmenter
maths map[int]*shaped.Math
// outBuff is the output buffer to avoid excessive memory consumption.
outBuff []shaping.Output
// shapes caches the shaped outputs of recent texts for wrapping.
shapes shapeCache
// webFonts is the number of the web fonts of [fonts.WebFonts]
// that have been added to the font map.
webFonts int
// SimpleSpans is whether spans of simple text (Latin, Greek and Cyrillic
// scripts, common punctuation and symbols) are shaped without the go-text
// shaper, as a glyph for each rune with its nominal glyph,
// for a shaper whose outputs are measured again after shaping, as those
// of shapedjs are measured by the browser.
SimpleSpans bool
sync.Mutex
}
type nilLogger struct{}
func (nl *nilLogger) Printf(format string, args ...any) {}
// NewShaper returns a new text shaper.
func NewShaper() shaped.Shaper {
sh := &Shaper{}
sh.fontMap.FontMap = fontscan.NewFontMap(&nilLogger{})
// TODO(text): figure out cache dir situation (especially on mobile and web)
str, err := os.UserCacheDir()
errors.Log(err) // (the system fonts are not loaded then)
// fmt.Println("cache dir:", str)
// the error is expected on the js platform, which has no system fonts
_ = sh.fontMap.UseSystemFonts(str)
errors.Log(fonts.UseEmbeddedInMap(sh.fontMap.FontMap))
sh.shaper.SetFontCacheSize(32)
return sh
}
// NewShaperWithFonts returns a new text shaper using
// given filesystem with fonts.
func NewShaperWithFonts(fss []fs.FS) shaped.Shaper {
sh := &Shaper{}
sh.fontMap.FontMap = fontscan.NewFontMap(&nilLogger{})
errors.Log(fonts.UseInMap(sh.fontMap.FontMap, fss))
sh.shaper.SetFontCacheSize(32)
return sh
}
// FontMap returns the font map used for this shaper.
func (sh *Shaper) FontMap() *fontscan.FontMap {
// The caller may set the query or script of the map, or add fonts,
// which can change how texts are shaped.
sh.Lock()
defer sh.Unlock()
sh.fontMap.forget()
sh.shapes.reset()
return sh.fontMap.FontMap
}
// Shape turns given input spans into [Runs] of rendered text,
// using given context needed for complete styling.
// The results are only valid until the next call to Shape or WrapParagraph:
// use slices.Clone if needed longer than that.
// This is called under a mutex lock, so it is safe for parallel use.
func (sh *Shaper) Shape(tx rich.Text, tsty *text.Style) []shaped.Run {
sh.Lock()
defer sh.Unlock()
sh.addWebFonts()
return sh.ShapeText(tx, tsty, tx.Join())
}
// ShapeText shapes the spans in the given text using given style and settings,
// returning [shaped.Run] results.
// This should already have the mutex lock, and is used by shapedjs but is
// not an end-user call.
func (sh *Shaper) ShapeText(tx rich.Text, tsty *text.Style, txt []rune) []shaped.Run {
outs := sh.ShapeTextOutput(tx, tsty, txt)
runs := make([]shaped.Run, len(outs))
for i := range outs {
run := &Run{Output: outs[i]}
si, _, _ := tx.Index(run.Runes().Start)
sty, _ := tx.Span(si)
run.SetFromStyle(sty, tsty)
if sty.IsMath() {
mt := sh.maths[si]
if mt != nil {
run.Math = *mt
run.MaxBounds = mt.BBox
run.Output.Advance = math32.ToFixed(mt.BBox.Size().X)
}
}
runs[i] = run
}
return runs
}
// ShapeTextOutput shapes the spans in the given text using given style and settings,
// returning raw go-text [shaping.Output].
// This should already have the mutex lock, and is used by shapedjs but is
// not an end-user call.
func (sh *Shaper) ShapeTextOutput(tx rich.Text, tsty *text.Style, txt []rune) []shaping.Output {
if tx.Len() == 0 {
return nil
}
sh.shapeMaths(tx, tsty)
sty := rich.NewStyle()
sh.outBuff = sh.outBuff[:0]
for si, s := range tx {
in := shaping.Input{}
start, end := tx.Range(si)
stx := sty.FromRunes(s) // sets sty, returns runes for span
if len(stx) == 0 {
continue
}
if sty.IsMath() {
mt := sh.maths[si]
o := shaping.Output{}
o.Runes.Offset = start
o.Runes.Count = end - start
if mt != nil {
o.Advance = math32.ToFixed(mt.BBox.Size().X)
}
sh.outBuff = append(sh.outBuff, o)
continue // (the end special, next, has no text)
}
q := StyleToQuery(sty, tsty)
sh.fontMap.SetQuery(q)
in.Text = txt
in.RunStart = start
in.RunEnd = end
in.Direction = shaped.GoTextDirection(sty.Direction, tsty)
fsz := tsty.FontHeight(sty)
in.Size = math32.ToFixed(fsz)
in.Script = rich.Settings.Script
in.Language = rich.Settings.Language
// Simple text that is measured again after shaping is not shaped.
if sh.SimpleSpans {
if o, ok := sh.simpleOutput(&in); ok {
sh.outBuff = append(sh.outBuff, o)
continue
}
}
ins := sh.splitter.Split(in, &sh.fontMap) // this is essential
for _, in := range ins {
if in.Face == nil {
fmt.Println("nil face in input", len(stx), string(stx))
// fmt.Printf("nil face for in: %#v\n", in)
continue
}
o := sh.shaper.Shape(in)
FixOutputZeros(&o)
sh.outBuff = append(sh.outBuff, o)
}
}
return sh.outBuff
}
// shapeMaths runs TeX on all Math specials, saving results in maths
// map indexed by the span index.
func (sh *Shaper) shapeMaths(tx rich.Text, tsty *text.Style) {
sh.maths = make(map[int]*shaped.Math)
if shaped.ShapeMath == nil {
return
}
for si := range tx {
sty, stx := tx.Span(si)
if sty.IsMath() {
mt := sh.shapeMath(sty, tsty, stx)
sh.maths[si] = mt // can be nil if error
}
}
}
// shapeMath runs tex math to get path for math special
func (sh *Shaper) shapeMath(sty *rich.Style, tsty *text.Style, stx []rune) *shaped.Math {
if shaped.ShapeMath == nil {
return nil
}
mstr := string(stx)
if sty.Special == rich.MathDisplay {
mstr = "$" + mstr + "$"
}
p := errors.Log1(shaped.ShapeMath(mstr, tsty.FontHeight(sty)))
if p != nil {
bb := p.FastBounds()
bb.Max.X += 5 // extra space
return &shaped.Math{Path: p, BBox: bb}
}
return nil
}
// todo: do the paragraph splitting! write fun in rich.Text
// DirectionAdvance advances given position based on given direction.
func DirectionAdvance(dir di.Direction, pos fixed.Point26_6, adv fixed.Int26_6) fixed.Point26_6 {
if dir.IsVertical() {
pos.Y += -adv
} else {
pos.X += adv
}
return pos
}
// StyleToQuery translates the rich.Style to go-text fontscan.Query parameters.
func StyleToQuery(sty *rich.Style, tsty *text.Style) fontscan.Query {
q := fontscan.Query{}
fam := tsty.FontFamily(sty)
q.Families = rich.FamiliesToList(fam)
q.Aspect = StyleToAspect(sty)
return q
}
// StyleToAspect translates the rich.Style to go-text font.Aspect parameters.
func StyleToAspect(sty *rich.Style) font.Aspect {
as := font.Aspect{}
as.Style = font.Style(1 + sty.Slant)
as.Weight = font.Weight(sty.Weight.ToFloat32())
as.Stretch = font.Stretch(sty.Stretch.ToFloat32())
return as
}
// FixOutputZeros fixes zero values in output, which can happen with emojis.
func FixOutputZeros(o *shaping.Output) {
for gi := range o.Glyphs {
g := &o.Glyphs[gi]
if g.Width == 0 {
// fmt.Println(gi, g.GlyphID, "fixed width:", g.XAdvance)
g.Width = g.XAdvance
}
if g.Height == 0 {
// fmt.Println(gi, "fixed height:", o.Size)
g.Height = o.Size
}
}
}
// addWebFonts adds the web fonts of [fonts.WebFonts] that have been added
// since it was last called to the font map (with the lock held).
func (sh *Shaper) addWebFonts() {
wfs, n := fonts.WebFonts(sh.webFonts)
if len(wfs) == 0 {
return
}
for i, wf := range wfs {
id := fmt.Sprintf("web-font-%d-%s", sh.webFonts+i, wf.Family)
errors.Log(sh.fontMap.AddFont(bytes.NewReader(wf.Data), id, wf.Family))
}
sh.webFonts = n
sh.fontMap.forget()
sh.shapes.reset()
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package shapedgt
import (
"math"
"unicode"
"github.com/cogentcore/typesetting/di"
"github.com/cogentcore/typesetting/language"
"github.com/cogentcore/typesetting/shaping"
"golang.org/x/image/math/fixed"
)
// isSimple returns whether the rune is shaped as one glyph of its own,
// left to right, by itself: runes of the Latin, Greek and Cyrillic scripts
// and of common punctuation and symbols, without combining marks, control,
// format and line break characters, which need the go-text shaper (or its
// line wrapper treats them specially).
func isSimple(r rune) bool {
switch {
case r < 0x20:
return false
case r < 0x7f:
return true
case r < 0xa0: // DEL and C1 controls
return false
case r < 0x300:
return r != 0xad // soft hyphen
case r < 0x370: // combining diacritical marks
return false
case r < 0x483: // Greek, Cyrillic
return true
case r < 0x48a: // Cyrillic combining marks
return false
case r < 0x530: // Cyrillic, Cyrillic Supplement
return true
case r < 0x1e00:
return false
case r < 0x2000: // Latin Extended Additional, Greek Extended
return true
case r < 0x2010: // spaces and format characters
return r <= 0x200a && r != 0x2007
case r < 0x2028:
return true
case r < 0x2030: // separators, embedding controls, narrow no-break space
return false
case r < 0x205f:
return true
case r < 0x2070: // format characters
return false
case r < 0x20d0: // superscripts and subscripts, currency
return true
case r < 0x2100: // combining marks for symbols
return false
case r < 0x2400: // letterlike, number forms, arrows, math operators, technical
return true
case r < 0x2460:
return false
case r < 0x2600: // enclosed alphanumerics, box drawing, blocks, shapes
return true
}
return false
}
// simpleOutput returns the output of the span of the input when it is simple
// text (see [isSimple]) in one face, with a glyph for each rune with the
// nominal glyph of the face (and the advance of the face for spaces), or
// false when it needs the go-text shaper. The shaper uses this for
// [Shaper.SimpleSpans], when the outputs are measured again after shaping
// (as in shapedjs), so the glyph extents, kerning and ligatures of the
// go-text shaper are not needed.
func (sh *Shaper) simpleOutput(in *shaping.Input) (shaping.Output, bool) {
rs := in.Text[in.RunStart:in.RunEnd]
if in.Direction != di.DirectionLTR || len(rs) == 0 {
return shaping.Output{}, false
}
for _, r := range rs {
if !isSimple(r) {
return shaping.Output{}, false
}
}
// The face is that of the first rune, which must have the glyphs of the
// others. The font map resolves them to it as well, unless it is a
// fallback face for the first rune and the face of the query has some of
// them, which only changes the glyphs that other renderers draw, as the
// browser measures and draws the text with its own fonts.
sh.fontMap.SetScript(language.LookupScript(rs[0]))
face := sh.fontMap.ResolveFace(rs[0])
if face == nil {
return shaping.Output{}, false
}
// Each rune is a glyph, whose advance is replaced by the measured one.
// Empty glyphs keep the advance of the go-text shaper, scaled as it scales
// it, as their width (see [FixOutputZeros]).
out := shaping.Output{Size: in.Size, Direction: in.Direction, Face: face, Runes: shaping.Range{Offset: in.RunStart, Count: len(rs)}}
out.Glyphs = make([]shaping.Glyph, len(rs))
scale := float64(int32(in.Size.Ceil())<<6) / float64(face.Upem())
for i, r := range rs {
gid, ok := face.NominalGlyph(r)
if !ok {
return shaping.Output{}, false
}
g := &out.Glyphs[i]
*g = shaping.Glyph{ClusterIndex: in.RunStart + i, RuneCount: 1, GlyphCount: 1, GlyphID: gid}
if unicode.IsSpace(r) {
g.XAdvance = fixed.Int26_6(math.Round(float64(face.HorizontalAdvance(gid)) * scale))
}
}
return out, true
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package shapedgt
import (
"fmt"
"math"
"slices"
"cogentcore.org/core/math32"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/shaped"
"cogentcore.org/core/text/text"
"github.com/cogentcore/typesetting/di"
"github.com/cogentcore/typesetting/segmenter"
"github.com/cogentcore/typesetting/shaping"
"golang.org/x/image/math/fixed"
)
// WrapLines performs line wrapping and shaping on the given rich text source,
// using the given style information, where the [rich.Style] provides the default
// style information reflecting the contents of the source (e.g., the default family,
// weight, etc), for use in computing the default line height. Paragraphs are extracted
// first using standard newline markers, assumed to coincide with separate spans in the
// source text, and wrapped separately. For horizontal text, the Lines will render with
// a position offset at the upper left corner of the overall bounding box of the text.
// This is called under a mutex lock, so it is safe for parallel use.
func (sh *Shaper) WrapLines(tx rich.Text, defSty *rich.Style, tsty *text.Style, size math32.Vector2) *shaped.Lines {
sh.Lock()
defer sh.Unlock()
sh.addWebFonts()
if tsty.FontSize.Dots == 0 {
tsty.FontSize.Dots = 16
}
return sh.WrapLinesBoundsCached(tx, defSty, tsty, size, nil)
}
// truncates returns whether text in the given style is cut with an
// ellipsis when it has too many lines or does not fit on its line.
func truncates(tsty *text.Style) bool {
return tsty.LineClamp > 0 || tsty.Ellipsis
}
// truncator returns the ellipsis (…) that ends the last line of text that is
// cut (see [text.Style.LineClamp] and [text.Style.Ellipsis]), shaped in the
// default style of the text. It reuses the buffers of shaping, so it is
// shaped before the text is.
func (sh *Shaper) truncator(defSty *rich.Style, tsty *text.Style) shaping.Output {
r := []rune("…")
outs := sh.ShapeTextOutput(rich.NewText(defSty, r), tsty, r)
if len(outs) == 0 {
return shaping.Output{}
}
o := outs[0]
o.Glyphs = slices.Clone(o.Glyphs)
return o
}
// WrapLinesOutput wraps the given outputs into lines. The mutex should
// already be locked; it is used by shapedjs but is not an end-user call.
// Returns new lines and number of truncations.
func (sh *Shaper) WrapLinesOutput(outs []shaping.Output, txt []rune, tx rich.Text, defSty *rich.Style, tsty *text.Style, size math32.Vector2) ([]shaping.Line, int) {
cfg, maxSize := wrapConfig(defSty, tsty, size)
if truncates(tsty) {
// (shaped first, as shaping reuses the buffers of the outputs)
outs = slices.Clone(outs)
cfg.Truncator = sh.truncator(defSty, tsty)
}
if lines, ok := singleLine(outs, txt, cfg, maxSize, !cfg.DisableTrailingWhitespaceTrim); ok {
return lines, 0
}
return sh.wrapParagraph(cfg, maxSize, txt, outs, nil)
}
// singleLine returns the outputs as one line when they fit on one line, as
// the line wrapper returns them, with the trailing whitespace of more than one
// run trimmed if trim, or false when the line wrapper is needed. The wrapper
// returns a single run that fits as it is, when the text has no mandatory line
// break before its end. For more than one run, the wrapper is needed when the
// text has a line break character, may break at every opportunity, is vertical
// or has runs in more than one direction, or does not fit.
func singleLine(outs []shaping.Output, txt []rune, cfg shaping.WrapConfig, maxSize int, trim bool) ([]shaping.Line, bool) {
if len(outs) == 0 {
return nil, false
}
maxWidth := fixed.I(min(maxSize, math.MaxInt32>>6))
// A single run is checked as the wrapper checks it, in any direction.
if len(outs) == 1 {
if outs[0].Advance > maxWidth || hasMandatoryBreak(txt) {
return nil, false
}
return []shaping.Line{outs}, true
}
// More runs must all be in the horizontal direction of the paragraph.
dir := cfg.Direction
if cfg.BreakPolicy == shaping.Always || dir.IsVertical() || dir.Progression() != di.FromTopLeft {
return nil, false
}
var adv fixed.Int26_6
for i := range outs {
if outs[i].Direction != dir {
return nil, false
}
adv += outs[i].Advance
}
if adv > maxWidth {
return nil, false
}
// Any line break character (line break classes BK, CR, LF and NL) needs the wrapper.
if slices.ContainsFunc(txt, isLineBreak) {
return nil, false
}
// The wrapper sets the visual order of the runs (logical here)
// and trims the trailing whitespace.
for i := range outs {
outs[i].VisualIndex = int32(i)
}
if !trim {
return []shaping.Line{outs}, true
}
last := &outs[len(outs)-1]
if n := len(last.Glyphs); n > 0 {
if g := &last.Glyphs[n-1]; g.Width == 0 {
g.XAdvance = 0
g.Advance = 0
}
last.RecomputeAdvance()
}
return []shaping.Line{outs}, true
}
// isLineBreak returns whether the rune is a line break character
// (line break classes BK, CR, LF and NL).
func isLineBreak(r rune) bool {
switch r {
case '\n', '\r', '\v', '\f', 0x85, 0x2028, 0x2029:
return true
}
return false
}
// hasMandatoryBreak returns whether the text has a mandatory line break before
// its end, as the line wrapper finds them: after a line break character other
// than the last rune, where CR followed by LF breaks after the LF.
func hasMandatoryBreak(txt []rune) bool {
for i := 0; i < len(txt)-1; i++ {
if r := txt[i]; isLineBreak(r) && (r != '\r' || txt[i+1] != '\n') {
return true
}
}
return false
}
// wrapParagraph wraps the outputs as the line wrapper's WrapParagraph does,
// for outputs that [singleLine] has found need wrapping. WrapParagraph first
// checks for the case of singleLine, finding the break opportunities of the
// whole text, which it then finds again to wrap it. The segmenter, if
// non-nil, has the break opportunities of the text already, as kept for all
// the wrappings of a cached text; otherwise they are found for this one.
func (sh *Shaper) wrapParagraph(cfg shaping.WrapConfig, maxSize int, txt []rune, outs []shaping.Output, seg *segmenter.Segmenter) ([]shaping.Line, int) {
if seg != nil {
sh.wrapper.PrepareSegmented(cfg, seg, shaping.NewSliceIterator(outs))
} else {
sh.wrapper.Prepare(cfg, txt, shaping.NewSliceIterator(outs))
}
var lines []shaping.Line
for {
line, done := sh.wrapper.WrapNextLine(maxSize)
if line.Line != nil {
lines = append(lines, line.Line)
}
if done {
return lines, line.Truncated
}
}
}
// wrapConfig returns the line wrapping configuration and the maximum line
// size for wrapping text with the given styles to the given size.
func wrapConfig(defSty *rich.Style, tsty *text.Style, size math32.Vector2) (shaping.WrapConfig, int) {
lht := tsty.LineHeightDots(defSty)
dir := shaped.GoTextDirection(rich.Default, tsty)
nlines := int(math32.Floor(size.Y/lht)) * 2
maxSize := int(size.X)
if dir.IsVertical() {
nlines = int(math32.Floor(size.X / lht))
maxSize = int(size.Y)
// fmt.Println(lht, nlines, maxSize)
}
// fmt.Println("lht:", lns.LineHeight, lgap, nlines)
brk := shaping.WhenNecessary
switch tsty.WhiteSpace {
case text.WrapNever:
brk = shaping.Never
case text.WhiteSpacePre:
maxSize = 100000
case text.WrapAlways:
brk = shaping.Always
}
if brk == shaping.Never {
maxSize = 100000
nlines = 1
if tsty.Ellipsis && !dir.IsVertical() {
// it is cut to fit on one line, with an ellipsis, within words
brk = shaping.WhenNecessary
maxSize = int(size.X)
}
}
if tsty.LineClamp > 0 && (nlines <= 0 || tsty.LineClamp < nlines) {
nlines = tsty.LineClamp
}
// fmt.Println(brk, nlines, maxSize)
cfg := shaping.WrapConfig{
Direction: dir,
TruncateAfterLines: nlines,
TextContinues: false, // todo! no effect if TruncateAfterLines is 0
BreakPolicy: brk, // or Never, Always
DisableTrailingWhitespaceTrim: tsty.WhiteSpace.KeepWhiteSpace(),
}
// from gio:
// if wc.TruncateAfterLines > 0 {
// if len(params.Truncator) == 0 {
// params.Truncator = "…"
// }
// // We only permit a single run as the truncator, regardless of whether more were generated.
// // Just use the first one.
// wc.Truncator = s.ShapeText(params.PxPerEm, params.Locale, []rune(params.Truncator))[0]
// }
// todo: WrapParagraph does NOT handle vertical text! file issue.
return cfg, maxSize
}
// LinesBounds returns the shaped lines of the given lines, with their
// bounds. The mutex should already be locked; it is used by shapedjs but is
// not an end-user call.
func (sh *Shaper) LinesBounds(lines []shaping.Line, truncated int, tx rich.Text, defSty *rich.Style, tsty *text.Style, size math32.Vector2) *shaped.Lines {
lht := tsty.LineHeightDots(defSty)
lns := &shaped.Lines{Source: tx, Color: tsty.Color, SelectionColor: tsty.SelectColor, HighlightColor: tsty.HighlightColor, LineHeight: lht}
lns.Truncated = truncated > 0
fsz := tsty.FontHeight(defSty)
dir := shaped.GoTextDirection(rich.Default, tsty)
// fmt.Println(fsz, lht, lht/fsz, tsty.LineHeight)
cspi := 0
cspSt, cspEd := tx.Range(cspi)
var off math32.Vector2
for li, lno := range lines {
// fmt.Println("line:", li, off)
ln := shaped.Line{}
var lsp rich.Text
var pos fixed.Point26_6
setFirst := false
var maxAsc fixed.Int26_6
maxLHt := lht
for oi := range lno {
out := &lno[oi]
FixOutputZeros(out)
if !dir.IsVertical() { // todo: vertical
maxAsc = max(out.LineBounds.Ascent, maxAsc)
}
run := Run{Output: *out}
rns := run.Runes()
if !setFirst {
ln.SourceRange.Start = rns.Start
setFirst = true
}
ln.SourceRange.End = rns.End
for rns.Start >= cspEd {
cspi++
cspSt, cspEd = tx.Range(cspi)
}
sty, cr := rich.NewStyleFromRunes(tx[cspi])
if lns.FontSize == 0 {
lns.FontSize = sty.Size * fsz
}
nsp := sty.ToRunes()
coff := rns.Start - cspSt
cend := coff + rns.Len()
crsz := len(cr)
if coff >= crsz || cend > crsz {
// fmt.Println("out of bounds:", string(cr), crsz, coff, cend)
cend = min(crsz, cend)
coff = min(crsz, coff)
}
if cend-coff == 0 {
continue
}
nr := cr[coff:cend] // note: not a copy!
nsp = append(nsp, nr...)
lsp = append(lsp, nsp)
// fmt.Println(sty, string(nr))
if cend > (cspEd - cspSt) { // shouldn't happen, to combine multiple original spans
fmt.Println("combined original span:", cend, cspEd-cspSt, cspi, string(cr), "prev:", string(nr), "next:", string(cr[cend:]))
}
run.SetFromStyle(sty, tsty)
if sty.IsMath() {
mt := sh.maths[cspi]
if mt != nil {
run.Math = *mt
run.MaxBounds = mt.BBox
bb := run.MaxBounds.Translate(math32.Vector2FromFixed(pos))
ln.Bounds.ExpandByBox(bb)
pos.X += math32.ToFixed(run.MaxBounds.Size().X)
ysz := bb.Size().Y
// fmt.Println("math ysz:", ysz, "maxAsc:", maxAsc)
maxAsc = max(maxAsc, math32.ToFixed(-bb.Min.Y))
maxLHt = max(maxLHt, ysz)
}
} else {
llht := tsty.LineHeightDots(sty)
maxLHt = max(maxLHt, llht)
bb := math32.B2FromFixed(run.RunBounds().Add(pos))
ln.Bounds.ExpandByBox(bb)
// fmt.Println("adv:", pos, run.Output.Advance, bb.Size().X)
pos = DirectionAdvance(run.Direction, pos, run.Output.Advance)
}
ln.Runs = append(ln.Runs, &run)
}
if li == 0 { // set offset for first line based on max ascent
if !dir.IsVertical() { // todo: vertical!
off.Y = math32.FromFixed(maxAsc)
}
}
ln.Source = lsp
// offset has prior line's size built into it, but we need to also accommodate
// any extra size in _our_ line beyond what is expected.
ourOff := off
// fmt.Println(ln.Bounds)
// advance offset:
if dir.IsVertical() {
lwd := ln.Bounds.Size().X
extra := max(lwd-lns.LineHeight, 0)
if dir.Progression() == di.FromTopLeft {
// fmt.Println("ftl lwd:", lwd, off.X)
off.X += lwd // ?
ourOff.X += extra
} else {
// fmt.Println("!ftl lwd:", lwd, off.X)
off.X -= lwd // ?
ourOff.X -= extra
}
} else { // always top-down, no progression issues
lby := ln.Bounds.Size().Y // the result at this point is centered with this height
// which includes the natural line height property of the font itself.
lpd := 0.5 * (maxLHt - lby) // half of diff
// the extra height of the line is half above its text and half
// below it, as the half-leading of CSS, the first line too (as
// the labels of buttons with a line height of their height,
// which were at their tops)
ourOff.Y += lpd
if li > 0 {
ourOff.Y += maxLHt - lns.LineHeight
}
ln.Bounds.Min.Y -= lpd
ln.Bounds.Max.Y += lpd
off.Y += maxLHt
// fmt.Println("lby:", lby, fsz, maxLHt, lpd, ourOff.Y)
}
// go back through and give every run the expanded line-level box
for ri := range ln.Runs {
run := ln.Runs[ri]
rb := run.LineBounds()
if dir.IsVertical() {
rb.Min.X, rb.Max.X = ln.Bounds.Min.X, ln.Bounds.Max.X
rb.Min.Y -= 1 // ensure some overlap along direction of rendering adjacent
rb.Max.Y += 1
} else {
rb.Min.Y, rb.Max.Y = ln.Bounds.Min.Y, ln.Bounds.Max.Y
rb.Min.X -= 1
rb.Max.Y += 1
}
run.AsBase().MaxBounds = rb
}
ln.Offset = ourOff
if tsty.WhiteSpace.HasWordWrap() && size.X > 0 && ln.Bounds.Size().X > size.X {
// fmt.Println("size exceeded:", ln.Bounds.Size().X, size.X)
ln.Bounds.Max.X -= ln.Bounds.Size().X - size.X
}
lns.Bounds.ExpandByBox(ln.Bounds.Translate(ln.Offset))
lns.Lines = append(lns.Lines, ln)
}
if lns.Bounds.Size().Y < lht {
lns.Bounds.Max.Y = lns.Bounds.Min.Y + lht
}
// fmt.Println(lns.Bounds)
lns.AlignX(tsty)
return lns
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package shapedjs shapes text on the web, with the shaper of go-text,
// corrected by the measurements of the text in a browser canvas.
package shapedjs
import (
"strconv"
"strings"
"cogentcore.org/core/text/rich"
)
// webFace is a web font face that has finished loading.
type webFace struct {
// family is the family name, without quotes.
family string
// italic is whether the face is italic (or oblique).
italic bool
// ranges are the inclusive ranges of the runes of the face,
// or nil for all runes.
ranges [][2]rune
}
// parseUnicodeRange returns the inclusive rune ranges of a CSS unicode-range,
// such as "U+0-FF, U+131, U+4??", or nil (all runes) if it cannot parse it.
func parseUnicodeRange(s string) [][2]rune {
var ranges [][2]rune
for part := range strings.SplitSeq(s, ",") {
part = strings.TrimSpace(part)
if len(part) < 3 || (part[0] != 'U' && part[0] != 'u') || part[1] != '+' {
return nil
}
part = part[2:]
// A range is lo-hi; wildcards (?) are the lowest and highest digits.
lo, hi, ok := strings.Cut(part, "-")
if !ok {
lo, hi = strings.ReplaceAll(part, "?", "0"), strings.ReplaceAll(part, "?", "F")
}
l, err1 := strconv.ParseUint(lo, 16, 32)
h, err2 := strconv.ParseUint(hi, 16, 32)
if err1 != nil || err2 != nil {
return nil
}
ranges = append(ranges, [2]rune{rune(l), rune(h)})
}
return ranges
}
// has returns whether the face has any of the runes.
func (wf *webFace) has(rs []rune) bool {
if wf.ranges == nil {
return len(rs) > 0
}
for _, r := range rs {
for _, rg := range wf.ranges {
if r >= rg[0] && r <= rg[1] {
return true
}
}
}
return false
}
// usedBy returns whether the face is one that texts in the given font
// family list and slant are measured with: a regular face is also used for
// italic texts without an italic face.
func (wf *webFace) usedBy(families string, italic bool) bool {
if wf.italic && !italic {
return false
}
for f := range strings.SplitSeq(families, ",") {
if strings.Trim(f, `"' `) == wf.family {
return true
}
}
return false
}
// textUsesFaces returns whether the text has runes that are measured with
// any of the given faces.
func textUsesFaces(tx rich.Text, customFont rich.FontName, faces []webFace) bool {
for si := range tx {
sty, rs := tx.Span(si)
if sty.IsMath() {
continue
}
families := string(customFont)
if sty.Family != rich.Custom {
families = sty.FontFamily(&rich.Settings)
}
for i := range faces {
if faces[i].usedBy(families, sty.Slant == rich.Italic) && faces[i].has(rs) {
return true
}
}
}
return false
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package shapedjs
import (
"math"
"unicode"
"github.com/cogentcore/typesetting/di"
"github.com/cogentcore/typesetting/shaping"
"golang.org/x/image/math/fixed"
)
// fitWords scales the advances of the glyphs of each word of the output,
// whose text is the given runes starting at rune index start, to add up to
// the width of the word, which width returns. The glyphs are measured by
// themselves, without the kerning (and ligatures) that the browser applies
// to the text it draws, so they add up to more than the words: the line
// wrapper, which wraps runs by the advances of their glyphs, would wrap
// lines that fit, and the positions of the runes would differ from those
// that the browser draws. Only left to right outputs are fit.
func fitWords(out *shaping.Output, rs []rune, start int, width func(word []rune) fixed.Int26_6) {
if out.Direction != di.DirectionLTR {
return
}
gs := out.Glyphs
space := func(g *shaping.Glyph) bool {
i := g.TextIndex() - start
return i < 0 || i >= len(rs) || unicode.IsSpace(rs[i])
}
for i := 0; i < len(gs); {
// A word is the glyphs up to the next space.
if space(&gs[i]) {
i++
continue
}
j := i + 1
for j < len(gs) && !space(&gs[j]) {
j++
}
// A word of more than one glyph is fit to its width.
if j-i > 1 {
first, last := &gs[i], &gs[j-1]
end := min(last.TextIndex()-start+last.RunesCount(), len(rs))
fitAdvances(gs[i:j], width(rs[first.TextIndex()-start:end]))
}
i = j
}
}
// fitAdvances scales the advances of the glyphs to add up to the given
// advance, unless they differ from it by more than kerning does.
func fitAdvances(gs []shaping.Glyph, adv fixed.Int26_6) {
var sum fixed.Int26_6
for i := range gs {
sum += gs[i].Advance
}
if sum <= 0 || sum == adv {
return
}
f := float64(adv) / float64(sum)
if f < 0.8 || f > 1.2 {
return
}
// The last glyph has the rest of the advance, so that they add up exactly.
var total fixed.Int26_6
last := len(gs) - 1
for i := range last {
g := &gs[i]
g.Advance = fixed.Int26_6(math.Round(float64(g.Advance) * f))
total += g.Advance
}
gs[last].Advance = adv - total
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !js
package shapers
import (
"cogentcore.org/core/text/shaped"
"cogentcore.org/core/text/shaped/shapers/shapedgt"
)
func init() {
shaped.NewShaper = shapedgt.NewShaper
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package spell
import (
"strings"
"unicode/utf8"
"cogentcore.org/core/text/parse/lexer"
"cogentcore.org/core/text/token"
)
// CheckLexLine returns the Lex regions for any words that are misspelled
// within given line of text with existing Lex tags -- automatically
// excludes any Code token regions (see token.IsCode). Token is set
// to token.TextSpellErr on returned Lex's
func CheckLexLine(src []rune, tags lexer.Line) lexer.Line {
wrds := tags.NonCodeWords(src)
var lexs lexer.Line
var words []string
for _, t := range wrds {
wrd := string(t.Src(src))
lwrd := lexer.FirstWordApostrophe(wrd)
if len(lwrd) <= 2 {
continue
}
// Start and End are rune indexes.
t.Start += utf8.RuneCountInString(wrd[:strings.Index(wrd, lwrd)])
t.End = t.Start + utf8.RuneCountInString(lwrd)
lexs = append(lexs, t)
words = append(words, lwrd)
}
var ser lexer.Line
for _, i := range Spell.Misspelled(words) {
t := lexs[i]
t.Token.Token = token.TextSpellErr
t.Now()
ser = append(ser, t)
}
return ser
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package spell
import (
"io/fs"
"os"
"slices"
"strings"
"cogentcore.org/core/base/fsx"
"cogentcore.org/core/base/stringsx"
"golang.org/x/exp/maps"
)
type Dict map[string]struct{}
func (d Dict) Add(word string) {
d[word] = struct{}{}
}
func (d Dict) Exists(word string) bool {
_, ex := d[word]
return ex
}
// List returns a list (slice) of words in dictionary
// in alpha-sorted order
func (d Dict) List() []string {
wl := maps.Keys(d)
slices.Sort(wl)
return wl
}
// Save saves a dictionary list of words
// to a simple one-word-per-line list, in alpha order
func (d Dict) Save(fname string) error {
wl := d.List()
ws := strings.Join(wl, "\n")
return os.WriteFile(fname, []byte(ws), 0666)
}
// NewDictFromList makes a new dictionary from given list
// (slice) of words
func NewDictFromList(wl []string) Dict {
d := make(Dict, len(wl))
for _, w := range wl {
d.Add(w)
}
return d
}
// OpenDict opens a dictionary list of words
// from a simple one-word-per-line list
func OpenDict(fname string) (Dict, error) {
dfs, fnm, err := fsx.DirFS(fname)
if err != nil {
return nil, err
}
return OpenDictFS(dfs, fnm)
}
// OpenDictFS opens a dictionary list of words
// from a simple one-word-per-line list, from given filesystem
func OpenDictFS(fsys fs.FS, filename string) (Dict, error) {
f, err := fs.ReadFile(fsys, filename)
if err != nil {
return nil, err
}
wl := stringsx.SplitLines(string(f))
d := NewDictFromList(wl)
return d, nil
}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"log/slog"
"cogentcore.org/core/cli"
"cogentcore.org/core/text/spell"
)
//go:generate core generate -add-types -add-funcs
// Config is the configuration information for the dict cli.
type Config struct {
// InputA is the first input dictionary file
InputA string `posarg:"0" required:"+"`
// InputB is the second input dictionary file
InputB string `posarg:"1" required:"+"`
// Output is the output file for merge command
Output string `cmd:"merge" posarg:"2" required:"-"`
}
func main() { //types:skip
opts := cli.DefaultOptions("dict", "runs dictionary commands")
cli.Run(opts, &Config{}, Compare, Merge)
}
// Compare compares two dictionaries
func Compare(c *Config) error { //cli:cmd -root
a, err := spell.OpenDict(c.InputA)
if err != nil {
slog.Error(err.Error())
return err
}
b, err := spell.OpenDict(c.InputB)
if err != nil {
slog.Error(err.Error())
return err
}
fmt.Printf("In %s not in %s:\n", c.InputA, c.InputB)
for aw := range a {
if !b.Exists(aw) {
fmt.Println(aw)
}
}
fmt.Printf("\n########################\nIn %s not in %s:\n", c.InputB, c.InputA)
for bw := range b {
if !a.Exists(bw) {
fmt.Println(bw)
}
}
return nil
}
// Merge combines two dictionaries
func Merge(c *Config) error { //cli:cmd
return nil
}
// Copyright (c) 2020, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// this code is adapted from: https://github.com/sajari/fuzzy
// https://www.sajari.com/
// Most of which seems to have been written by Hamish @sajari
// it does not have a copyright notice in the code itself but does have
// an MIT license file.
//
// key change is to ignore counts and just use a flat Dict dictionary
// list of words.
package spell
import (
"strings"
"sync"
"golang.org/x/exp/maps"
)
// Model is the full data model
type Model struct {
// list of all words, combining Base and User dictionaries
Dict Dict
// user dictionary of additional words
UserDict Dict
// words to ignore for this session
Ignore Dict
// map of misspelled word to potential correct spellings
Suggest map[string][]string
// depth of edits to include in Suggest map (2 is only sensible value)
Depth int
sync.RWMutex
}
// NewModel creates and initializes a new model
func NewModel() *Model {
md := new(Model)
return md.Init()
}
func (md *Model) Init() *Model {
md.Suggest = make(map[string][]string)
md.Ignore = make(Dict)
md.Depth = 2
return md
}
func (md *Model) SetDicts(base, user Dict) {
md.Dict = base
md.UserDict = user
maps.Copy(md.Dict, md.UserDict)
go md.addSuggestionsForWords(md.Dict.List())
}
// addSuggestionsForWords
func (md *Model) addSuggestionsForWords(terms []string) {
md.Lock()
// st := time.Now()
for _, term := range terms {
md.createSuggestKeys(term)
}
// fmt.Println("train took:", time.Since(st)) // about 500 msec for 32k words, 5 sec for 235k
md.Unlock()
}
// AddWord adds a new word to user dictionary,
// and generates new suggestions for it
func (md *Model) AddWord(term string) {
md.Lock()
defer md.Unlock()
if md.Dict.Exists(term) {
return
}
md.UserDict.Add(term)
md.Dict.Add(term)
md.createSuggestKeys(term)
}
// Delete removes given word from the dictionary and the user dictionary,
// which undoes learning it.
func (md *Model) Delete(term string) {
md.Lock()
edits := md.EditsMulti(term, md.Depth) // the keys that it was added for
for _, edit := range edits {
sug := md.Suggest[edit]
ns := len(sug)
for i := ns - 1; i >= 0; i-- {
hit := sug[i]
if hit == term {
sug = append(sug[:i], sug[i+1:]...)
}
}
if len(sug) == 0 {
delete(md.Suggest, edit)
} else {
md.Suggest[edit] = sug
}
}
delete(md.Dict, term)
delete(md.UserDict, term) // so that it is not saved as learned
md.Unlock()
}
// setUserDict sets the user dictionary to the given one, as read again
// from its file, which can have words learned or deleted by another app:
// they are added to or deleted from the dictionary too.
func (md *Model) setUserDict(user Dict) {
old := md.UserDict
for w := range old {
if !user.Exists(w) {
md.Delete(w)
}
}
for w := range user {
if !old.Exists(w) {
md.AddWord(w)
}
}
md.Lock()
md.UserDict = user
md.Unlock()
}
// For a given term, create the partially deleted lookup keys
func (md *Model) createSuggestKeys(term string) {
edits := md.EditsMulti(term, md.Depth)
for _, edit := range edits {
skip := false
for _, hit := range md.Suggest[edit] {
if hit == term {
// Already know about this one
skip = true
continue
}
}
if !skip && len(edit) > 1 {
md.Suggest[edit] = append(md.Suggest[edit], term)
}
}
}
// EditsMulti returns the edits at any depth for a given term. The depth of the model is used
func (md *Model) EditsMulti(term string, depth int) []string {
edits := Edits1(term)
for {
depth--
if depth <= 0 {
break
}
for _, edit := range edits {
edits2 := Edits1(edit)
edits = append(edits, edits2...)
}
}
return edits
}
type Pair struct {
str1 string
str2 string
}
// Edits1 creates a set of terms that are 1 char delete from the input term
func Edits1(word string) []string {
splits := []Pair{}
for i := 0; i <= len(word); i++ {
splits = append(splits, Pair{word[:i], word[i:]})
}
totalSet := []string{}
for _, elem := range splits {
//deletion
if len(elem.str2) > 0 {
totalSet = append(totalSet, elem.str1+elem.str2[1:])
} else {
totalSet = append(totalSet, elem.str1)
}
}
// Special case ending in "ies" or "ys"
if strings.HasSuffix(word, "ies") {
totalSet = append(totalSet, word[:len(word)-3]+"ys")
}
if strings.HasSuffix(word, "ys") {
totalSet = append(totalSet, word[:len(word)-2]+"ies")
}
return totalSet
}
// For a given input term, suggest some alternatives.
// if the input is in the dictionary, it will be the only item
// returned.
func (md *Model) suggestPotential(input string) []string {
input = strings.ToLower(input)
// 0 - If this is a dictionary term we're all good, no need to go further
if md.Dict.Exists(input) {
return []string{input}
}
ss := make(Dict)
var sord []string
// 1 - See if the input matches a "suggest" key
if sugg, ok := md.Suggest[input]; ok {
for _, pot := range sugg {
if !ss.Exists(pot) {
sord = append(sord, pot)
ss.Add(pot)
}
}
}
// 2 - See if edit1 matches input
edits := md.EditsMulti(input, md.Depth)
got := false
for _, edit := range edits {
if len(edit) > 2 && md.Dict.Exists(edit) {
got = true
if !ss.Exists(edit) {
sord = append(sord, edit)
ss.Add(edit)
}
}
}
if got {
return sord
}
// 3 - No hits on edit1 distance, look for transposes and replaces
// Note: these are more complex, we need to check the guesses
// more thoroughly, e.g. levals=[valves] in a raw sense, which
// is incorrect
for _, edit := range edits {
if sugg, ok := md.Suggest[edit]; ok {
// Is this a real transpose or replace?
for _, pot := range sugg {
lev := Levenshtein(&input, &pot)
if lev <= md.Depth+1 { // The +1 doesn't seem to impact speed, but has greater coverage when the depth is not sufficient to make suggestions
if !ss.Exists(pot) {
sord = append(sord, pot)
ss.Add(pot)
}
}
}
}
}
return sord
}
// Suggestions returns the most likely corrections in order from best to worst
func (md *Model) Suggestions(input string, n int) []string {
md.RLock()
suggestions := md.suggestPotential(input)
md.RUnlock()
return suggestions
}
// Levenshtein calculates the Levenshtein distance between two strings
func Levenshtein(a, b *string) int {
la := len(*a)
lb := len(*b)
d := make([]int, la+1)
var lastdiag, olddiag, temp int
for i := 1; i <= la; i++ {
d[i] = i
}
for i := 1; i <= lb; i++ {
d[0] = i
lastdiag = i - 1
for j := 1; j <= la; j++ {
olddiag = d[j]
min := d[j] + 1
if (d[j-1] + 1) < min {
min = d[j-1] + 1
}
if (*a)[j-1] == (*b)[i-1] {
temp = 0
} else {
temp = 1
}
if (lastdiag + temp) < min {
min = lastdiag + temp
}
d[j] = min
lastdiag = olddiag
}
}
return d[la]
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package spell
// nativeChecker is a platform spell checker provided by the operating
// system (NSSpellChecker on macOS, UITextChecker on iOS, ISpellChecker
// on Windows, Enchant on Linux, SpellCheckerSession on Android). Words
// learned through it go to the system user dictionary, shared with other
// apps (except on Android). Implementations must be safe to call from
// any goroutine.
type nativeChecker interface {
// misspelled returns the indexes of the misspelled words
// in the given list of words, in increasing order. ok is false
// if the words could not be checked, so the result is not cached.
misspelled(words []string) (bad []int, ok bool)
// suggest returns suggested corrections for a misspelled word.
suggest(word string) []string
// learn adds word to the system user dictionary.
learn(word string)
// unlearn removes word from the system user dictionary.
unlearn(word string)
}
// newNative returns the platform spell checker, or nil if there is none
// available. It is set by the platform-specific files.
var newNative func() nativeChecker
// UseNative determines whether the operating system spell checker is used
// when available. If false, or if there is no system spell checker, the
// built-in dictionary-based checker is used instead. It must be set before
// [NewSpell] is called.
var UseNative = true
// HasNative returns true if an operating system spell checker is
// supported on this platform and [UseNative] is true. The checker
// may still turn out to be unavailable when [NewSpell] is called.
func HasNative() bool {
return UseNative && newNative != nil
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build linux && !android && cgo
package spell
/*
#cgo LDFLAGS: -ldl
#include <dlfcn.h>
#include <stdlib.h>
#include <sys/types.h>
// Enchant-2 is loaded at run time with dlopen, so that building
// does not need its headers, and running does not need it installed.
typedef void *(*brokerInitFunc)(void);
typedef void *(*requestDictFunc)(void *broker, const char *tag);
typedef int (*dictCheckFunc)(void *dict, const char *word, ssize_t len);
typedef char **(*dictSuggestFunc)(void *dict, const char *word, ssize_t len, size_t *n);
typedef void (*dictFreeListFunc)(void *dict, char **list);
typedef void (*dictWordFunc)(void *dict, const char *word, ssize_t len);
static brokerInitFunc brokerInit;
static requestDictFunc requestDict;
static dictCheckFunc dictCheck;
static dictSuggestFunc dictSuggest;
static dictFreeListFunc dictFreeList;
static dictWordFunc dictAdd;
static dictWordFunc dictRemove;
static void *broker;
static int enchantLoad(void) {
void *lib = dlopen("libenchant-2.so.2", RTLD_NOW);
if (lib == NULL) {
lib = dlopen("libenchant-2.so", RTLD_NOW);
}
if (lib == NULL) {
return 0;
}
brokerInit = (brokerInitFunc)dlsym(lib, "enchant_broker_init");
requestDict = (requestDictFunc)dlsym(lib, "enchant_broker_request_dict");
dictCheck = (dictCheckFunc)dlsym(lib, "enchant_dict_check");
dictSuggest = (dictSuggestFunc)dlsym(lib, "enchant_dict_suggest");
dictFreeList = (dictFreeListFunc)dlsym(lib, "enchant_dict_free_string_list");
dictAdd = (dictWordFunc)dlsym(lib, "enchant_dict_add");
dictRemove = (dictWordFunc)dlsym(lib, "enchant_dict_remove");
if (!brokerInit || !requestDict || !dictCheck || !dictSuggest || !dictFreeList || !dictAdd || !dictRemove) {
return 0;
}
broker = brokerInit();
return broker != NULL;
}
static void *enchantDict(const char *tag) {
return requestDict(broker, tag);
}
static int enchantCheck(void *dict, const char *word, int len) {
return dictCheck(dict, word, len);
}
static char **enchantSuggest(void *dict, const char *word, int len, size_t *n) {
return dictSuggest(dict, word, len, n);
}
static void enchantFreeList(void *dict, char **list) {
dictFreeList(dict, list);
}
static void enchantAdd(void *dict, const char *word, int len) {
dictAdd(dict, word, len);
}
static void enchantRemove(void *dict, const char *word, int len) {
dictRemove(dict, word, len);
}
*/
import "C"
import (
"os"
"strings"
"sync"
"unsafe"
)
func init() {
newNative = newEnchantChecker
}
// enchantChecker uses the Enchant-2 library, which uses whatever
// spell checking backends and dictionaries are installed (Hunspell,
// Nuspell, Aspell, etc), and the user's personal dictionary in
// ~/.config/enchant, shared with other apps that use Enchant.
type enchantChecker struct {
// mu serializes access to the Enchant dictionary.
mu sync.Mutex
dict unsafe.Pointer
}
// enchantOnce loads Enchant at most once.
var enchantOnce = sync.OnceValue(func() bool {
return C.enchantLoad() != 0
})
func newEnchantChecker() nativeChecker {
if !enchantOnce() {
return nil
}
for _, tag := range localeTags() {
ct := C.CString(tag)
dict := C.enchantDict(ct)
C.free(unsafe.Pointer(ct))
if dict != nil {
return &enchantChecker{dict: dict}
}
}
return nil
}
// localeTags returns the language tags to try, from the
// locale environment variables, with English as a fallback.
func localeTags() []string {
var tags []string
for _, env := range []string{"LC_ALL", "LC_MESSAGES", "LANG"} {
v := os.Getenv(env)
if i := strings.IndexAny(v, ".@"); i >= 0 {
v = v[:i]
}
if v == "" || v == "C" || v == "POSIX" {
continue
}
tags = append(tags, v)
if i := strings.IndexByte(v, '_'); i > 0 {
tags = append(tags, v[:i])
}
break
}
return append(tags, "en_US", "en")
}
func (ec *enchantChecker) misspelled(words []string) ([]int, bool) {
var bad []int
ec.mu.Lock()
defer ec.mu.Unlock()
for i, w := range words {
cw := C.CString(w)
if C.enchantCheck(ec.dict, cw, C.int(len(w))) > 0 {
bad = append(bad, i)
}
C.free(unsafe.Pointer(cw))
}
return bad, true
}
func (ec *enchantChecker) suggest(word string) []string {
cw := C.CString(word)
defer C.free(unsafe.Pointer(cw))
ec.mu.Lock()
defer ec.mu.Unlock()
var n C.size_t
list := C.enchantSuggest(ec.dict, cw, C.int(len(word)), &n)
if list == nil {
return nil
}
defer C.enchantFreeList(ec.dict, list)
sugs := make([]string, int(n))
for i, s := range unsafe.Slice(list, int(n)) {
sugs[i] = C.GoString(s)
}
return sugs
}
func (ec *enchantChecker) learn(word string) {
cw := C.CString(word)
defer C.free(unsafe.Pointer(cw))
ec.mu.Lock()
defer ec.mu.Unlock()
C.enchantAdd(ec.dict, cw, C.int(len(word)))
}
func (ec *enchantChecker) unlearn(word string) {
cw := C.CString(word)
defer C.free(unsafe.Pointer(cw))
ec.mu.Lock()
defer ec.mu.Unlock()
C.enchantRemove(ec.dict, cw, C.int(len(word)))
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package spell
import (
"embed"
"log/slog"
"maps"
"strings"
"sync"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/sharedfile"
"cogentcore.org/core/text/parse/lexer"
)
//go:embed dict_en_us
var embedDict embed.FS
// Spell is the global shared spell
var Spell *SpellData
// SpellData is a spell checker. It uses the operating system spell checker
// when available (see [UseNative]), in which case learned words go to the
// system user dictionary. Otherwise it uses a built-in English dictionary,
// with learned words saved in UserFile, which is shared by all apps: it is
// read again when another app has changed it, and the words learned and
// deleted are saved right away, with those of the other apps (see
// [sharedfile]).
type SpellData struct {
// UserFile is path to user's dictionary where learned words go,
// only for the built-in checker: a list of words, one per line.
UserFile string
// native is the operating system spell checker, if available.
native nativeChecker
// known caches the words checked with the native checker,
// with true if spelled correctly.
known map[string]bool
// ignore has the lowercase words to ignore for this session,
// for the native checker.
ignore Dict
model *Model
// user is the shared file of the user dictionary.
user sharedfile.File[Dict]
// added and deleted are the words learned and deleted since the user
// dictionary was last saved, which are applied to the words of its
// file when it is saved, so that those of other apps are kept.
added, deleted Dict
mu sync.RWMutex // we need our own mutex in case of loading a new model
}
// maxKnownCache is the maximum number of words in the native known cache.
const maxKnownCache = 100_000
// NewSpell returns a new spell checker, using the operating system
// spell checker if available and [UseNative] is true, and otherwise
// the built-in checker with the given user dictionary file.
func NewSpell(userFile string) *SpellData {
if UseNative && newNative != nil {
if nc := newNative(); nc != nil {
return &SpellData{UserFile: userFile, native: nc, known: map[string]bool{}, ignore: Dict{}}
}
}
d, err := OpenDictFS(embedDict, "dict_en_us")
if err != nil {
slog.Error(err.Error())
return nil
}
sp := &SpellData{UserFile: userFile, added: Dict{}, deleted: Dict{}}
sp.model = NewModel()
uf := sp.userFile()
errors.Log(uf.Reload())
sp.model.SetDicts(d, cloneDict(uf.Data))
return sp
}
// userFile returns the shared file of the user dictionary, with the path
// of [SpellData.UserFile], which can be changed.
func (sp *SpellData) userFile() *sharedfile.File[Dict] {
sp.user.Path = sp.UserFile
sp.user.Encode = func(d Dict) ([]byte, error) {
return []byte(strings.Join(d.List(), "\n")), nil // as Dict.Save
}
sp.user.Decode = func(b []byte) (Dict, error) {
d := Dict{}
for _, w := range strings.Split(string(b), "\n") {
if w = strings.TrimSpace(w); w != "" {
d.Add(w)
}
}
return d, nil
}
return &sp.user
}
// cloneDict returns a copy of the given dictionary, which is empty if nil.
func cloneDict(d Dict) Dict {
c := make(Dict, len(d))
maps.Copy(c, d)
return c
}
// IsNative returns true if the operating system spell checker is being used.
func (sp *SpellData) IsNative() bool {
return sp != nil && sp.native != nil
}
// OpenUser opens user dictionary of words, for the built-in checker,
// if it has changed since it was last read.
func (sp *SpellData) OpenUser() error {
if sp.native != nil {
return nil
}
sp.mu.Lock()
defer sp.mu.Unlock()
return sp.openUser()
}
// openUser is the implementation of [SpellData.OpenUser], called with
// the mutex locked.
func (sp *SpellData) openUser() error {
uf := sp.userFile()
err := uf.Reload()
sp.setUser()
return err
}
// setUser sets the user dictionary of the model to that of its file, with
// the words learned and deleted since it was last saved. Called with the
// mutex locked.
func (sp *SpellData) setUser() {
d := cloneDict(sp.user.Data)
for w := range sp.added {
d.Add(w)
}
for w := range sp.deleted {
delete(d, w)
}
sp.model.setUserDict(d)
}
// OpenUserCheck opens the user dictionary again if its file has been
// changed (by another app) since it was last read or saved.
func (sp *SpellData) OpenUserCheck() error {
if sp == nil || sp.native != nil || sp.UserFile == "" {
return nil
}
sp.mu.Lock()
defer sp.mu.Unlock()
if !sp.userFile().Changed() {
return nil
}
return sp.openUser()
}
// SaveUser saves the words learned and deleted since the user dictionary
// was last saved to its file, with the words of its file, which another
// app may have changed, which are then those of the user dictionary.
func (sp *SpellData) SaveUser() error {
sp.mu.Lock()
defer sp.mu.Unlock()
if sp.native != nil || sp.model == nil || sp.UserFile == "" {
return nil
}
err := sp.userFile().Update(func(d *Dict) {
if *d == nil {
*d = Dict{}
}
for w := range sp.added {
d.Add(w)
}
for w := range sp.deleted {
delete(*d, w)
}
})
if err != nil {
slog.Error("spell: error saving the user dictionary", "file", sp.UserFile, "err", err)
return err // (the words are saved next time)
}
clear(sp.added)
clear(sp.deleted)
sp.setUser()
return nil
}
// SaveUserIfLearn saves the user dictionary if words have been learned or
// deleted since it was last saved, and otherwise opens it again if its file
// has changed.
func (sp *SpellData) SaveUserIfLearn() error {
if sp == nil || sp.native != nil || sp.UserFile == "" {
return nil
}
sp.mu.RLock()
changed := len(sp.added) > 0 || len(sp.deleted) > 0
sp.mu.RUnlock()
if !changed {
return sp.OpenUserCheck()
}
return sp.SaveUser()
}
// CheckWord checks a single word and returns suggestions if word is unknown.
// bool is true if word is in the dictionary, false otherwise.
func (sp *SpellData) CheckWord(word string) ([]string, bool) {
if sp == nil {
return nil, false
}
w := lexer.FirstWordApostrophe(word) // only lookup words
if sp.native != nil {
if len(sp.Misspelled([]string{w})) == 0 {
return nil, true
}
return sp.native.suggest(w), false
}
if sp.model == nil {
return nil, false
}
orig := w
w = strings.ToLower(w)
sp.mu.RLock()
defer sp.mu.RUnlock()
if sp.model.Ignore.Exists(w) {
return nil, true
}
suggests := sp.model.Suggestions(w, 10)
if suggests == nil { // no sug and not known
return nil, false
}
if len(suggests) == 1 && suggests[0] == w {
return nil, true
}
for i, s := range suggests {
suggests[i] = lexer.MatchCase(orig, s)
}
return suggests, false
}
// Misspelled returns the indexes of the misspelled words in the given
// list of words, in increasing order. The words must already be
// isolated, as with [lexer.FirstWordApostrophe].
func (sp *SpellData) Misspelled(words []string) []int {
if sp == nil {
return nil
}
if sp.native == nil {
var bad []int
for i, w := range words {
if _, known := sp.CheckWord(w); !known {
bad = append(bad, i)
}
}
return bad
}
// Only send the words that are not already cached or ignored
// to the native checker.
sp.mu.RLock()
var check []string
for _, w := range words {
if _, ok := sp.known[w]; ok || sp.ignore.Exists(strings.ToLower(w)) {
continue
}
check = append(check, w)
}
sp.mu.RUnlock()
if len(check) > 0 {
// If the check fails, nothing is cached, so the words are
// checked again next time.
if bad, ok := sp.native.misspelled(check); ok {
sp.mu.Lock()
if len(sp.known)+len(check) > maxKnownCache {
clear(sp.known)
}
for _, w := range check {
sp.known[w] = true
}
for _, bi := range bad {
sp.known[check[bi]] = false
}
sp.mu.Unlock()
}
}
sp.mu.RLock()
defer sp.mu.RUnlock()
var bad []int
for i, w := range words {
if sp.ignore.Exists(strings.ToLower(w)) {
continue
}
if known, ok := sp.known[w]; ok && !known {
bad = append(bad, i)
}
}
return bad
}
// AddWord adds given word to the user dictionary.
// For the native checker, this is the system user dictionary,
// and the word is added with the given case.
func (sp *SpellData) AddWord(word string) {
if sp.native != nil {
sp.native.learn(word)
sp.clearKnown()
return
}
sp.mu.Lock()
lword := strings.ToLower(word)
if !sp.model.Dict.Exists(lword) { // (words of the dictionary are not learned)
sp.model.AddWord(lword)
sp.added.Add(lword)
delete(sp.deleted, lword)
}
sp.mu.Unlock()
sp.SaveUser()
}
// DeleteWord removes word from the user dictionary,
// in case accidentally added.
func (sp *SpellData) DeleteWord(word string) {
if sp.native != nil {
sp.native.unlearn(word)
sp.clearKnown()
return
}
sp.mu.Lock()
lword := strings.ToLower(word)
sp.model.Delete(lword)
sp.deleted.Add(lword)
delete(sp.added, lword)
sp.mu.Unlock()
sp.SaveUser()
}
// clearKnown clears the native known word cache.
func (sp *SpellData) clearKnown() {
sp.mu.Lock()
clear(sp.known)
sp.mu.Unlock()
}
/*
// Complete finds possible completions based on the prefix s
func (sp *SpellData) Complete(s string) []string {
if model == nil {
log.Println("spell.Complete: programmer error -- Spelling not initialized!")
OpenDefault() // backup
}
sp.mu.RLock()
defer sp.mu.RUnlock()
result, _ := model.Autocomplete(s)
return result
}
*/
// IgnoreWord adds the word to the list of words
// to ignore for this session.
func (sp *SpellData) IgnoreWord(word string) {
word = strings.ToLower(word)
sp.mu.Lock()
defer sp.mu.Unlock()
if sp.native != nil {
sp.ignore.Add(word)
return
}
sp.model.Ignore.Add(word)
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// basic is a terminal app that runs the given command, or the user's shell.
package main
import (
"os"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/text/terminal"
)
func main() {
b := core.NewBody("Terminal")
tm := terminal.NewTerminal(b)
if len(os.Args) > 1 {
tm.SetCommand(os.Args[1:]...)
}
tm.OnTitle(func(title string) {
b.SetTitle(title)
})
tm.OnExit(func(err error) {
core.MessageSnackbar(tm, "the program has exited: press a key to restart it")
})
b.OnShow(func(e events.Event) {
tm.SetFocus()
})
b.RunMainWindow()
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package terminal
import (
"io"
"sync"
)
// inputQueue is a queue of input for the program, which is written to it
// in a separate goroutine, so that sending input never blocks, even when
// the program is not reading its input.
type inputQueue struct {
mu sync.Mutex
cond *sync.Cond
queue [][]byte
stopped bool
}
// newInputQueue returns a new input queue that writes to the given writer
// until it is stopped.
func newInputQueue(w io.Writer) *inputQueue {
iq := &inputQueue{}
iq.cond = sync.NewCond(&iq.mu)
go iq.write(w)
return iq
}
// stop stops writing the input.
func (iq *inputQueue) stop() {
iq.mu.Lock()
iq.stopped = true
iq.queue = nil
iq.cond.Broadcast()
iq.mu.Unlock()
}
// send adds the given input to the queue.
func (iq *inputQueue) send(b []byte) {
iq.mu.Lock()
defer iq.mu.Unlock()
if iq.stopped {
return
}
iq.queue = append(iq.queue, b)
iq.cond.Signal()
}
// write writes the input in the queue to w, until stopped.
func (iq *inputQueue) write(w io.Writer) {
for {
iq.mu.Lock()
for !iq.stopped && len(iq.queue) == 0 {
iq.cond.Wait()
}
if iq.stopped {
iq.mu.Unlock()
return
}
b := iq.queue[0]
iq.queue = iq.queue[1:]
iq.mu.Unlock()
if _, err := w.Write(b); err != nil {
iq.stop()
return
}
}
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package terminal
import (
"strings"
"unicode"
"cogentcore.org/core/events"
"cogentcore.org/core/events/key"
"cogentcore.org/core/keymap"
)
// The keys of a terminal go to the program running in it, including all
// of the Control keys, which are the ASCII control characters that
// programs use (Control+C to interrupt, Control+N for the next history
// line, and so on). The [keymap] bindings of the GUI are reached in two
// ways, as in other terminals:
// - Chords with Meta (Command on macOS) never go to the program, so
// they have their usual functions.
// - On other platforms, where the bindings use Control for Command,
// the binding Control+X (for a letter X) is reached with
// Control+Shift+X, which sends the same control character as
// Control+X, so the program does not lose any keys.
//
// [KeyFunction] and [ShortcutChord] apply these rules, so that the
// terminal and apps that use it follow the user's key bindings.
// KeyFunction returns the key function of the given key event in
// a terminal, or [keymap.None] if the key goes to the program.
func KeyFunction(e events.Event) keymap.Functions {
return keyFunctionOf(e.KeyChord())
}
// keyFunctionOf returns the key function of the given key chord in
// a terminal: see [KeyFunction].
func keyFunctionOf(ch key.Chord) keymap.Functions {
mods, k := key.ModifiersFromString(string(ch))
if mods.HasFlag(key.Meta) {
return keymap.Of(ch)
}
if isMacOS() || !mods.HasFlag(key.Control) || !mods.HasFlag(key.Shift) || !isLetter(k) {
return keymap.None
}
mods.SetFlag(false, key.Shift)
return keymap.Of(key.Chord(mods.ModifiersString() + k))
}
// ShortcutChord returns the key chords of the given key function that
// work in a terminal, for showing as a shortcut (see [KeyFunction]):
// its bindings with Meta, and elsewhere than macOS, those with Control
// and a letter, with Shift added. It is "" if there are none.
func ShortcutChord(kf keymap.Functions) key.Chord {
var chords []string
for ch := range strings.SplitSeq(string(kf.Chord()), "\n") {
mods, k := key.ModifiersFromString(ch)
switch {
case mods.HasFlag(key.Meta):
chords = append(chords, ch)
case !isMacOS() && mods.HasFlag(key.Control) && !mods.HasFlag(key.Shift) && isLetter(k):
mods.SetFlag(true, key.Shift)
chords = append(chords, mods.ModifiersString()+k)
}
}
return key.Chord(strings.Join(chords, "\n"))
}
// isLetter returns whether the given key of a chord is a letter.
func isLetter(k string) bool {
rs := []rune(k)
return len(rs) == 1 && unicode.IsLetter(rs[0])
}
// isMacOS returns whether the app is running on macOS.
func isMacOS() bool {
return key.SystemPlatform == "MacOS"
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package terminal
import (
"fmt"
"unicode"
"cogentcore.org/core/events/key"
"cogentcore.org/core/text/terminal/vt"
)
// keyBytes returns the bytes to send to the terminal program for the
// given key chord, or nil if the key does not send anything. If altMeta
// is set, Alt (Option) with a character sends Escape and then the
// character of the key without Alt, which is given by the key code (as
// the rune is the composed character on macOS): for character events,
// which have no code, the code of the last key down event is given.
func keyBytes(rn rune, code key.Codes, mods key.Modifiers, md *vt.Modes, altMeta bool) []byte {
shift := mods.HasFlag(key.Shift)
ctrl := mods.HasFlag(key.Control)
alt := mods.HasFlag(key.Alt)
mod := 1
if shift {
mod++
}
if alt {
mod += 2
}
if ctrl {
mod += 4
}
esc := func(s string) []byte {
if alt && altMeta {
return []byte("\x1b" + s)
}
return []byte(s)
}
// cursor returns the code for a cursor key, which has the SS3
// form in application mode.
cursor := func(final byte) []byte {
if mod > 1 {
return fmt.Appendf(nil, "\x1b[1;%d%c", mod, final)
}
if md.AppCursorKeys {
return []byte{0x1b, 'O', final}
}
return []byte{0x1b, '[', final}
}
// tilde returns the code for a key with the CSI n ~ form.
tilde := func(n int) []byte {
if mod > 1 {
return fmt.Appendf(nil, "\x1b[%d;%d~", n, mod)
}
return fmt.Appendf(nil, "\x1b[%d~", n)
}
// function returns the code for F1-F4.
function := func(final byte) []byte {
if mod > 1 {
return fmt.Appendf(nil, "\x1b[1;%d%c", mod, final)
}
return []byte{0x1b, 'O', final}
}
switch code {
case key.CodeReturnEnter:
return esc("\r")
case key.CodeKeypadEnter:
if md.AppKeypad {
return []byte("\x1bOM")
}
return esc("\r")
case key.CodeEscape:
return esc("\x1b")
case key.CodeBackspace:
if ctrl {
return esc("\x08")
}
return esc("\x7f")
case key.CodeTab:
if shift {
return []byte("\x1b[Z")
}
return esc("\t")
case key.CodeUpArrow:
return cursor('A')
case key.CodeDownArrow:
return cursor('B')
case key.CodeRightArrow:
return cursor('C')
case key.CodeLeftArrow:
return cursor('D')
case key.CodeHome:
return cursor('H')
case key.CodeEnd:
return cursor('F')
case key.CodeInsert:
return tilde(2)
case key.CodeDelete:
return tilde(3)
case key.CodePageUp:
return tilde(5)
case key.CodePageDown:
return tilde(6)
case key.CodeF1:
return function('P')
case key.CodeF2:
return function('Q')
case key.CodeF3:
return function('R')
case key.CodeF4:
return function('S')
case key.CodeF5:
return tilde(15)
case key.CodeF6:
return tilde(17)
case key.CodeF7:
return tilde(18)
case key.CodeF8:
return tilde(19)
case key.CodeF9:
return tilde(20)
case key.CodeF10:
return tilde(21)
case key.CodeF11:
return tilde(23)
case key.CodeF12:
return tilde(24)
}
if rn == 0 {
return nil
}
if alt && altMeta {
if r, ok := key.CodeRuneMap[code]; ok {
rn = r
}
if !shift {
rn = unicode.ToLower(rn)
}
}
if ctrl {
if c, ok := controlChar(rn); ok {
return esc(string(c))
}
}
return esc(string(rn))
}
// controlChar returns the control character for the given character
// typed with the Control key.
func controlChar(rn rune) (rune, bool) {
switch {
case rn >= 'a' && rn <= 'z':
return rn - 'a' + 1, true
case rn >= '@' && rn <= '_': // A-Z [ \ ] ^ _
return rn - '@', true
case rn == ' ' || rn == '2':
return 0, true
case rn >= '3' && rn <= '7':
return rn - '3' + 0x1b, true
case rn == '8' || rn == '?':
return 0x7f, true
case rn == '/':
return 0x1f, true
}
return 0, false
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package terminal
import (
"image/color"
"cogentcore.org/core/colors"
"cogentcore.org/core/colors/matcolor"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/terminal/vt"
)
// Palette is the set of 16 standard terminal colors: black, red, green,
// yellow, blue, magenta, cyan, white, and their bright versions.
type Palette [16]color.RGBA
var (
// DarkPalette is the palette used with a dark color scheme.
DarkPalette = Palette{
{0x00, 0x00, 0x00, 0xff}, {0xcd, 0x31, 0x31, 0xff}, {0x0d, 0xbc, 0x79, 0xff}, {0xe5, 0xe5, 0x10, 0xff},
{0x24, 0x72, 0xc8, 0xff}, {0xbc, 0x3f, 0xbc, 0xff}, {0x11, 0xa8, 0xcd, 0xff}, {0xe5, 0xe5, 0xe5, 0xff},
{0x66, 0x66, 0x66, 0xff}, {0xf1, 0x4c, 0x4c, 0xff}, {0x23, 0xd1, 0x8b, 0xff}, {0xf5, 0xf5, 0x43, 0xff},
{0x3b, 0x8e, 0xea, 0xff}, {0xd6, 0x70, 0xd6, 0xff}, {0x29, 0xb8, 0xdb, 0xff}, {0xff, 0xff, 0xff, 0xff},
}
// LightPalette is the palette used with a light color scheme.
LightPalette = Palette{
{0x00, 0x00, 0x00, 0xff}, {0xcd, 0x31, 0x31, 0xff}, {0x00, 0xa0, 0x00, 0xff}, {0x94, 0x98, 0x00, 0xff},
{0x04, 0x51, 0xa5, 0xff}, {0xbc, 0x05, 0xbc, 0xff}, {0x05, 0x98, 0xbc, 0xff}, {0x80, 0x80, 0x80, 0xff},
{0x66, 0x66, 0x66, 0xff}, {0xe0, 0x30, 0x30, 0xff}, {0x14, 0xb8, 0x14, 0xff}, {0xb5, 0xba, 0x00, 0xff},
{0x04, 0x51, 0xa5, 0xff}, {0xbc, 0x05, 0xbc, 0xff}, {0x05, 0x98, 0xbc, 0xff}, {0xa5, 0xa5, 0xa5, 0xff},
}
)
// colorMap converts terminal colors and styles to rich text styles.
type colorMap struct {
// palette is the palette of the 16 standard colors.
palette *Palette
// fg and bg are the default foreground and background colors.
fg, bg color.RGBA
// base is the base text style.
base *rich.Style
// links are the hyperlink URLs.
links []string
// cursor is the color of the cursor, which is blended with
// the background of the cell that it is on.
cursor color.RGBA
// cursorFocused is whether the view with the cursor is focused,
// in which case the cursor is blended, and otherwise it is
// [colorMap.cursor] as is.
cursorFocused bool
}
// newColorMap returns a new color map for the current color scheme.
func newColorMap(base *rich.Style, links []string) *colorMap {
cm := &colorMap{base: base, links: links}
cm.palette = &LightPalette
if matcolor.SchemeIsDark {
cm.palette = &DarkPalette
}
cm.fg = colors.ToUniform(colors.Scheme.OnSurface)
cm.bg = colors.ToUniform(colors.Scheme.Surface)
return cm
}
// color returns the RGB color for the given terminal color,
// which must not be the default.
func (cm *colorMap) color(c vt.Color) color.RGBA {
if r, g, b, ok := c.RGB(); ok {
return color.RGBA{r, g, b, 0xff}
}
i, _ := c.Index()
switch {
case i < 16:
return cm.palette[i]
case i < 232: // 6x6x6 cube
i -= 16
lev := func(v uint8) uint8 {
if v == 0 {
return 0
}
return 55 + v*40
}
return color.RGBA{lev(i / 36), lev((i / 6) % 6), lev(i % 6), 0xff}
default: // grayscale
v := 8 + (i-232)*10
return color.RGBA{v, v, v, 0xff}
}
}
// style returns the rich text style for the given cell style.
func (cm *colorMap) style(st vt.Style) *rich.Style {
rs := *cm.base
at := st.Attrs
if at&vt.Bold != 0 {
rs.Weight = rich.Bold
}
if at&vt.Italic != 0 {
rs.Slant = rich.Italic
}
if at&(vt.Underline|vt.DoubleUnderline) != 0 {
rs.Decoration.SetFlag(true, rich.Underline)
}
if at&vt.Strikethrough != 0 {
rs.Decoration.SetFlag(true, rich.LineThrough)
}
if at&vt.Overline != 0 {
rs.Decoration.SetFlag(true, rich.Overline)
}
if at&(vt.Reverse|vt.Faint|vt.Invisible) == 0 && st.Fg.IsDefault() && st.Bg.IsDefault() {
return cm.link(&rs, st)
}
fg, bg := cm.fg, cm.bg
if !st.Fg.IsDefault() {
fg = cm.color(st.Fg)
}
if !st.Bg.IsDefault() {
bg = cm.color(st.Bg)
}
if at&vt.Reverse != 0 {
fg, bg = bg, fg
}
if at&vt.Faint != 0 {
fg = colors.Blend(colors.RGB, 50, fg, bg)
}
if at&vt.Invisible != 0 {
fg = bg
}
if fg != cm.fg {
rs.SetFillColor(fg)
}
if bg != cm.bg || at&vt.Reverse != 0 {
rs.SetBackground(bg)
}
return cm.link(&rs, st)
}
// link sets the link of the style, if the cell has one.
func (cm *colorMap) link(rs *rich.Style, st vt.Style) *rich.Style {
if st.Link == 0 || int(st.Link) > len(cm.links) {
return rs
}
rs.URL = cm.links[st.Link-1]
rs.Special = rich.Link
return rs
}
// lineMarkup returns the text and markup for the given cells, which
// has one character for each cell, except the cell after a wide
// character, as the wide character takes two cells in the view,
// without the trailing blank cells, but with at least minLen cells (for
// the cursor). The cursor is shown on the cell at the given index, unless
// it is negative: it is drawn as the background of the cell, which fills
// the cell exactly.
func (cm *colorMap) lineMarkup(cells []vt.Cell, minLen, cursor int) ([]rune, rich.Text) {
n := len(cells)
for n > 0 && cells[n-1].IsBlank() {
n--
}
n = max(n, min(minLen, len(cells)))
rs := make([]rune, 0, max(n, minLen))
cellOf := make([]int, 0, max(n, minLen)) // the cell index of each char
for i := range max(n, minLen) {
switch {
case i >= n:
rs = append(rs, ' ')
case cells[i].Width == 0: // after a wide character
continue
case cells[i].Rune == 0:
rs = append(rs, ' ')
default:
rs = append(rs, cells[i].Rune)
}
cellOf = append(cellOf, i)
}
cursorChar := -1
if cursor >= 0 {
cursorChar = cellChar(cells, cursor)
}
var tx rich.Text
addSpan := func(sty *rich.Style, start, end int) {
if end <= start {
return
}
if sty.Special == rich.Link {
tx.StartSpecial(sty, rich.Link, rs[start:end])
tx.EndSpecial()
} else {
tx.AddSpan(sty, rs[start:end])
}
}
// the chars, with the cursor char as its own span
charStyle := func(i int) vt.Style {
if ci := cellOf[i]; ci < n {
return cells[ci].Style
}
return vt.Style{}
}
start := 0
for i := 1; i <= len(rs); i++ {
if i < len(rs) && i != cursorChar && i-1 != cursorChar && charStyle(i) == charStyle(start) {
continue
}
sty := cm.style(charStyle(start))
if start == cursorChar {
sty = cm.cursorStyle(sty)
}
addSpan(sty, start, i)
start = i
}
if len(tx) == 0 {
tx = rich.NewText(cm.base, rs)
}
return rs, tx
}
// cellChar returns the index of the char for the cell at the given
// column in the text of the given cells (see [colorMap.lineMarkup]),
// where the cell after a wide character is part of it.
func cellChar(cells []vt.Cell, col int) int {
ci := 0
for i := 1; i <= col; i++ {
if i >= len(cells) || cells[i].Width != 0 {
ci++
}
}
return ci
}
// cursorStyle returns the given style with the cursor background.
func (cm *colorMap) cursorStyle(sty *rich.Style) *rich.Style {
cs := *sty
clr := cm.cursor
if cm.cursorFocused {
bg := cm.bg
if c := sty.Background(); c != nil {
bg = colors.AsRGBA(c)
}
clr = colors.Blend(colors.RGB, 50, cm.cursor, bg)
}
cs.SetBackground(clr)
return &cs
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package terminal
import (
"fmt"
"cogentcore.org/core/events/key"
"cogentcore.org/core/text/terminal/vt"
)
// mouseAction is the kind of mouse event to report to the program.
type mouseAction int
const (
mousePress mouseAction = iota
mouseRelease
mouseMotion
)
// Mouse button numbers in the terminal mouse protocol.
const (
mouseLeft = 0
mouseMiddle = 1
mouseRight = 2
mouseNoButton = 3
mouseWheelUp = 64
mouseWheelDown = 65
)
// mouseBytes returns the bytes that report the given mouse event to the
// program, for the mouse mode that it has set, or nil if it is not
// reported. The row and column are 0-based.
func mouseBytes(md *vt.Modes, action mouseAction, button, row, col int, mods key.Modifiers) []byte {
switch md.Mouse {
case vt.MouseNone:
return nil
case vt.MouseX10:
if action != mousePress {
return nil
}
case vt.MouseNormal:
if action == mouseMotion {
return nil
}
case vt.MouseButton:
if action == mouseMotion && button == mouseNoButton {
return nil
}
}
b := button
if md.Mouse != vt.MouseX10 {
if mods.HasFlag(key.Shift) {
b += 4
}
if mods.HasFlag(key.Alt) {
b += 8
}
if mods.HasFlag(key.Control) {
b += 16
}
}
if action == mouseMotion {
b += 32
}
if md.MouseSGR {
final := 'M'
if action == mouseRelease {
final = 'm'
}
return fmt.Appendf(nil, "\x1b[<%d;%d;%d%c", b, col+1, row+1, final)
}
if action == mouseRelease {
b = b&^3 | mouseNoButton
}
enc := func(v int) byte {
return byte(min(v+32, 255))
}
return []byte{0x1b, '[', 'M', enc(b), enc(col + 1), enc(row + 1)}
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package terminal
import (
"context"
"os"
"os/exec"
"runtime"
"strconv"
"strings"
"time"
)
// processDir returns the working directory of the process of the given
// id, or "" if it cannot be found: from /proc on Linux, and with lsof on
// macOS and the BSDs.
func processDir(pid int) string {
switch runtime.GOOS {
case "linux", "android":
dir, _ := os.Readlink("/proc/" + strconv.Itoa(pid) + "/cwd")
return dir
case "darwin", "freebsd", "netbsd", "openbsd", "dragonfly":
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
lsof, err := exec.LookPath("lsof")
if err != nil {
lsof = "/usr/sbin/lsof" // (often not in the path)
}
out, err := exec.CommandContext(ctx, lsof, "-a", "-p", strconv.Itoa(pid), "-d", "cwd", "-Fn").Output()
if err != nil {
return ""
}
for line := range strings.Lines(string(out)) {
if dir, ok := strings.CutPrefix(strings.TrimRight(line, "\n"), "n"); ok {
return dir
}
}
}
return ""
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package pty runs a command in a pseudo-terminal (pty), so that it
// acts as it does in a terminal: for example, a shell is interactive.
// It can also run a function of this process with a pseudo-terminal
// (see [Run]), such as an interpreter of the app.
// It uses github.com/creack/pty on Unix, and Windows ConPTY through
// github.com/charmbracelet/x/xpty.
package pty
import (
"context"
"errors"
"os"
"os/exec"
"runtime"
"time"
)
// ErrUnsupported is returned on platforms without pseudo-terminals.
var ErrUnsupported = errors.New("pty: pseudo-terminals are not supported on this platform")
// Pty is a command or function running in a pseudo-terminal. Reading from it
// returns the output of the program, and writing to it sends input to it.
type Pty struct {
// Cmd is the command, if it was started with [Start].
Cmd *exec.Cmd
// In and Out are the terminal device of the pseudo-terminal, if it
// was started with [Run]: the function uses them as its standard
// input and output, and gives them to the commands it runs.
// They are the same file, except on Windows.
In, Out *os.File
// pty is the pseudo-terminal.
pty pseudoTerminal
// done is closed when the function of [Run] returns, with its error in err.
done chan struct{}
err error
}
// pseudoTerminal is the interface of the platform pseudo-terminal.
type pseudoTerminal interface {
Read(b []byte) (int, error)
Write(b []byte) (int, error)
Close() error
Resize(cols, rows int) error
}
// Start starts the given command in a new pseudo-terminal of the given size.
func Start(cmd *exec.Cmd, cols, rows int) (*Pty, error) {
pt, err := start(cmd, cols, rows)
if err != nil {
return nil, err
}
return &Pty{Cmd: cmd, pty: pt}, nil
}
// Run runs the given function in a goroutine with a new pseudo-terminal
// of the given size, whose terminal device it gets as in and out: it uses
// them as its standard input and output, as a command started with [Start]
// does, and it can give them to the commands it runs. This is for programs
// that run in this process, such as an interpreter of the app. The terminal
// device is closed when the function returns, and the program ends
// (see [Pty.Wait]). Closing the pseudo-terminal makes the reads and
// writes of the terminal device fail, which should make the function
// return. Unlike a command, it gets no signals: see [Pty.Signals] and
// [Pty.Resize].
//
// In and out are the same file, except on Windows, where they are the
// input and output of the console of the pseudo-terminal, which this
// process is attached to while the function runs, instead of its own
// console, if any, with its standard handles set to them. As a process
// has only one console, only one function can run at a time there.
// The commands that it runs are in that console, and get the Control+C
// typed in it, which this process ignores, except that it ends a read
// of the input that is not raw, with [io.EOF].
func Run(fun func(in, out *os.File) error, cols, rows int) (*Pty, error) {
pt, in, out, err := open(cols, rows)
if err != nil {
return nil, err
}
p := &Pty{In: in, Out: out, pty: pt, done: make(chan struct{})}
go func() {
p.err = fun(in, out)
in.Close()
out.Close()
if d, ok := pt.(interface{ detach() }); ok {
d.detach() // on Windows, so that another function can run
}
close(p.done)
// reading the output does not end when the terminal device is
// closed on macOS, or while a read of it is still pending
time.AfterFunc(200*time.Millisecond, func() { pt.Close() })
}()
return p, nil
}
// Read reads output from the command.
func (p *Pty) Read(b []byte) (int, error) {
return p.pty.Read(b)
}
// Write writes input to the command.
func (p *Pty) Write(b []byte) (int, error) {
return p.pty.Write(b)
}
// Resize sets the size of the terminal, which the command is told about.
func (p *Pty) Resize(cols, rows int) error {
return p.pty.Resize(cols, rows)
}
// Close closes the pseudo-terminal, which ends the command if it is still running
// (a shell gets a hangup signal).
func (p *Pty) Close() error {
return p.pty.Close()
}
// Signals returns whether the terminal makes signals of the
// interrupt, quit and suspend characters (ISIG), as it does unless the
// program reads raw input; on Windows, whether the console makes events
// of Control+C (ENABLE_PROCESSED_INPUT). A function started with [Run]
// gets no signals, so the caller has to tell it about these characters.
func (p *Pty) Signals() bool {
return signals(p.pty)
}
// Wait waits for the command or function to finish and returns its error.
func (p *Pty) Wait() error {
if p.Cmd == nil {
<-p.done
return p.err
}
return wait(context.Background(), p.Cmd)
}
// DefaultShell returns the default shell command for the user:
// $SHELL, or /bin/sh, and on Windows, powershell.exe if available,
// or else %ComSpec% (cmd.exe).
func DefaultShell() []string {
if runtime.GOOS == "windows" {
if p, err := exec.LookPath("powershell.exe"); err == nil {
return []string{p, "-NoLogo"}
}
if cs := os.Getenv("ComSpec"); cs != "" {
return []string{cs}
}
return []string{"cmd.exe"}
}
if sh := os.Getenv("SHELL"); sh != "" {
return []string{sh}
}
return []string{"/bin/sh"}
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !windows && !js
package pty
import (
"context"
"os"
"os/exec"
"github.com/creack/pty"
"golang.org/x/sys/unix"
)
// unixPty is the master side of a Unix pty.
type unixPty struct {
*os.File
}
// start starts the command in a new session with the pty as its
// controlling terminal, as needed for job control in shells.
func start(cmd *exec.Cmd, cols, rows int) (pseudoTerminal, error) {
f, err := pty.StartWithSize(cmd, &pty.Winsize{Cols: uint16(cols), Rows: uint16(rows)})
if err != nil {
return nil, err
}
return &unixPty{f}, nil
}
// open opens a new pty, returning its master side and terminal device,
// as both the input and output.
func open(cols, rows int) (pseudoTerminal, *os.File, *os.File, error) {
f, tty, err := pty.Open()
if err != nil {
return nil, nil, nil, err
}
p := &unixPty{f}
if err := p.Resize(cols, rows); err != nil {
f.Close()
tty.Close()
return nil, nil, nil, err
}
return p, tty, tty, nil
}
func signals(pt pseudoTerminal) bool {
p, ok := pt.(*unixPty)
if !ok {
return false
}
t, err := unix.IoctlGetTermios(int(p.Fd()), ioctlGetTermios)
return err == nil && t.Lflag&unix.ISIG != 0
}
func (p *unixPty) Resize(cols, rows int) error {
return pty.Setsize(p.File, &pty.Winsize{Cols: uint16(cols), Rows: uint16(rows)})
}
func wait(_ context.Context, cmd *exec.Cmd) error {
return cmd.Wait()
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package terminal provides a terminal widget that runs a program,
// typically a shell, in a pseudo-terminal. The output of the program is
// shown in a lines view, which has the scrollback and the screen
// as lines of text that are wrapped to the width of the view, using
// [lines.Lines]. Full-screen programs such as editors use the alternate
// screen, which is shown in a grid view on top of the lines view. The
// terminal state is in the vt package and the pseudo-terminal in the
// pty package.
package terminal
//go:generate core generate
import (
"fmt"
"image"
"image/color"
"os"
"os/exec"
"path/filepath"
"runtime"
"slices"
"strings"
"sync/atomic"
"time"
"cogentcore.org/core/base/fileinfo"
"cogentcore.org/core/base/fileinfo/mimedata"
"cogentcore.org/core/colors"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/text/lines"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/terminal/pty"
"cogentcore.org/core/text/terminal/vt"
"cogentcore.org/core/text/textpos"
"cogentcore.org/core/tree"
)
// Terminal is a terminal widget that runs a program, typically a shell,
// in a pseudo-terminal: a command, or a function of this process, such
// as an interpreter of the app (see [Terminal.Func]). It starts the
// program when it is first shown,
// unless it has been started already with [Terminal.Start]. It has a
// lines view of the scrollback and the screen, and a grid view of the
// alternate screen used by full-screen programs, in a stack, with the
// one in use on top. The context menus added to the terminal with
// [core.WidgetBase.AddContextMenu] are shown in the context menu of
// the views, before the items for copying, pasting, and clearing.
type Terminal struct {
core.Frame
// Command is the program to run, with its arguments.
// The default is the user's shell (see [pty.DefaultShell]).
Command []string
// Func, if set, is run instead of [Terminal.Command], in a goroutine
// of this process, such as an interpreter of the app, with the
// terminal device of the pseudo-terminal as its standard input and
// output (see [pty.Run]); the program ends when it returns. As it
// gets no signals, use [Terminal.OnInterrupt] and [Terminal.OnResize]
// to handle interrupts and changes in the size of the terminal.
Func func(in, out *os.File) error `set:"-" display:"-"`
// Dir is the directory to start the program in.
// The default is the current directory.
Dir string
// Env are environment variables to add to the environment
// of the program, as "key=value". The standard variables for
// the terminal type (TERM etc) are added automatically.
Env []string
// MaxScrollback is the maximum number of lines of scrollback to keep.
MaxScrollback int
// AltAsMeta makes the Alt key (Option on macOS) with a character
// send Escape and the character, as the Meta key, which is used by
// shells for word movement etc, rather than the special characters
// that Option makes on macOS.
AltAsMeta bool
// emulator is the terminal emulator, with the terminal state.
emulator *vt.Emulator
// pty is the pseudo-terminal of the running program.
pty *pty.Pty
// linesView is the view of the scrollback and the primary screen.
linesView *View
// gridView is the view of the alternate screen.
gridView *View
// numScrollback is the number of lines of scrollback in the lines view,
// after which the lines of the screen are.
numScrollback int
// pending are the lines that have scrolled into the scrollback whose
// text continues on the next line (wrapped), which are shown with
// the screen until the end of their text has scrolled too.
pending []*vt.Line
// size is the size of the terminal, from the lines view.
size image.Point
// altShown is whether the alternate screen is shown.
altShown bool
// toEnd is set when the lines view should scroll to the end
// at the next update, after input from the user.
toEnd bool
// syncScheduled is set when an update of the views is scheduled.
syncScheduled atomic.Bool
// infoChanged is set when the title, directory, or commands changed.
infoChanged atomic.Bool
// exited is set when the program has exited.
exited atomic.Bool
// exitErr is the error of the exited program.
exitErr error
// title and dir are the last title and directory sent to listeners.
title, dir string
// input is the queue of input to send to the running program.
input atomic.Pointer[inputQueue]
titleFuncs, dirFuncs []func(s string)
exitFuncs []func(err error)
commandFuncs []func(c *vt.Command)
userCommandFuncs []func(cmd string)
interruptFuncs []func()
resizeFuncs []func(cols, rows int)
// numCommands is the number of commands reported to listeners.
numCommands int
// exitSent is whether the exit has been sent to listeners.
exitSent bool
// linesCursor is the position of the terminal cursor in the lines view,
// with a Line of -1 if it is not there.
linesCursor textpos.Pos
// gridCursor is the position of the terminal cursor in the grid view.
gridCursor textpos.Pos
// inputStart is where the user started typing the current command line
// in the lines view, with a Line of -1 if not started, for
// [Terminal.OnUserCommand].
inputStart textpos.Pos
// entered are the starts of the command lines entered by the user,
// which are reported when the cursor has left their lines
// (see [Terminal.reportUserCommands]).
entered []textpos.Pos
}
func (tm *Terminal) Init() {
tm.Frame.Init()
tm.inputStart.Line = -1
tm.MaxScrollback = 10000
tm.AltAsMeta = true
tm.emulator = vt.NewEmulator(80, 24)
tm.emulator.Reply = func(b []byte) { tm.send(b, false) }
tm.emulator.Changed = func() {
tm.infoChanged.Store(true)
}
tm.emulator.Clipboard = func(text string) {
// not with the terminal locked, as sync has the render lock first
go func() {
if tm.AsyncLockIfShown() {
tm.Clipboard().Write(mimedata.NewText(text))
tm.AsyncUnlock()
}
}()
}
tm.Styler(func(s *styles.Style) {
s.Display = styles.Stacked
s.Grow.Set(1, 1)
s.Min.X.Ch(20)
s.Min.Y.Em(4)
s.Padding.Zero()
s.Gap.Zero()
s.Font.Family = rich.Monospace
})
tm.OnShow(func(e events.Event) {
tm.sync()
})
tree.AddChildAt(tm, "lines", func(w *View) {
tm.linesView = w
w.Terminal = tm
tm.configLines(w)
})
tree.AddChildAt(tm, "grid", func(w *View) {
tm.gridView = w
w.Terminal = tm
w.isGrid = true
tm.configLines(w)
})
}
// Destroy stops the program, if it is running.
func (tm *Terminal) Destroy() {
tm.Stop()
tm.Frame.Destroy()
}
// configLines configures the lines of the given view.
func (tm *Terminal) configLines(vw *View) {
ln := lines.NewLines()
ln.SetReadOnly(true)
ln.SetUndoOn(false)
vw.SetLines(ln)
vw.Styler(func(s *styles.Style) {
ln.Settings.LineNumbers = false // the editor sets it from the settings
})
}
// Emulator returns the terminal emulator, with the terminal state,
// which must be locked to use it.
func (tm *Terminal) Emulator() *vt.Emulator {
return tm.emulator
}
// LinesView returns the view of the scrollback and the primary screen.
func (tm *Terminal) LinesView() *View {
return tm.linesView
}
// GridView returns the view of the alternate screen.
func (tm *Terminal) GridView() *View {
return tm.gridView
}
// ActiveView returns the view that is shown: the grid view when a
// program uses the alternate screen, and otherwise the lines view.
func (tm *Terminal) ActiveView() *View {
if tm.altShown {
return tm.gridView
}
return tm.linesView
}
// SetFocus sets the focus to the view that is shown.
func (tm *Terminal) SetFocus() {
if vw := tm.ActiveView(); vw != nil {
vw.SetFocus()
return
}
tm.Frame.SetFocus()
}
// IsRunning returns whether the program is running.
func (tm *Terminal) IsRunning() bool {
return tm.pty != nil && !tm.exited.Load()
}
// Start starts the program, if it is not already running.
// It is called automatically when the terminal is first shown.
func (tm *Terminal) Start() error {
if tm.IsRunning() {
return nil
}
cols, rows := 80, 24
if tm.size.X > 0 && tm.size.Y > 0 {
cols, rows = tm.size.X, tm.size.Y
}
tm.emulator.Lock()
tm.emulator.Resize(cols, rows)
tm.emulator.Unlock()
var p *pty.Pty
var err error
name := "the program"
if tm.Func != nil {
p, err = pty.Run(tm.Func, cols, rows)
} else {
args := tm.Command
if len(args) == 0 {
args = pty.DefaultShell()
}
name = strings.Join(args, " ")
cmd := exec.Command(args[0], args[1:]...)
cmd.Dir = tm.Dir
cmd.Env = append(os.Environ(), "TERM=xterm-256color", "COLORTERM=truecolor", "TERM_PROGRAM=CogentCore")
cmd.Env = append(cmd.Env, tm.Env...)
p, err = pty.Start(cmd, cols, rows)
}
if err != nil {
tm.emulator.Lock()
tm.emulator.WriteString(fmt.Sprintf("\r\n[could not start %s: %v]\r\n", name, err))
tm.emulator.Unlock()
tm.scheduleSync()
return err
}
tm.emulator.Lock()
tm.pty = p
tm.emulator.Unlock()
tm.exitSent = false
tm.exited.Store(false)
tm.exitErr = nil
tm.input.Store(newInputQueue(p))
go tm.readOutput(p)
return nil
}
// Stop ends the program, if it is running, by closing the pseudo-terminal,
// which sends it a hangup signal.
func (tm *Terminal) Stop() {
if tm.pty == nil {
return
}
tm.pty.Close()
if tm.pty.Cmd != nil && tm.pty.Cmd.Process != nil && runtime.GOOS != "windows" {
go func(p *os.Process) {
time.Sleep(time.Second)
p.Kill() // in case it ignores the hangup
}(tm.pty.Cmd.Process)
}
}
// Restart stops the program if it is running, and starts it again.
func (tm *Terminal) Restart() error {
tm.Stop()
tm.emulator.Lock()
tm.pty = nil
tm.emulator.Unlock()
return tm.Start()
}
// restartOnKey restarts the program after it has exited,
// returning true if it does.
func (tm *Terminal) restartOnKey() bool {
if tm.pty == nil || !tm.exited.Load() {
return false
}
tm.emulator.Lock()
tm.pty = nil
tm.emulator.WriteString("\r\n")
tm.emulator.Unlock()
tm.Start()
return true
}
// readOutput reads the output of the program until it exits.
func (tm *Terminal) readOutput(p *pty.Pty) {
buf := make([]byte, 64*1024)
for {
n, err := p.Read(buf)
if n > 0 {
tm.emulator.Lock()
tm.emulator.Write(buf[:n])
tm.emulator.Unlock()
tm.scheduleSync()
}
if err != nil {
break
}
}
err := p.Wait()
p.Close()
tm.emulator.Lock()
defer tm.emulator.Unlock()
if tm.pty != p { // restarted
return
}
if iq := tm.input.Swap(nil); iq != nil {
iq.stop()
}
msg := "[process exited]"
if err != nil {
msg = fmt.Sprintf("[process exited: %v]", err)
}
tm.emulator.WriteString("\x1b[?1049l\x1b[0m\r\n" + msg + " (press a key to restart)")
tm.exitErr = err
tm.exited.Store(true)
tm.infoChanged.Store(true)
tm.scheduleSync()
}
// send sends the given input to the program. If user is set,
// it is input from the user, after which the lines view scrolls
// to the end.
func (tm *Terminal) send(b []byte, user bool) {
if len(b) == 0 {
return
}
if user {
tm.toEnd = true
if tm.linesView != nil && !tm.altShown {
tm.linesView.SetCursorTarget(textpos.PosErr)
}
}
if user {
tm.userInput(b)
}
// Whether Control+C is an interrupt is decided before the input is
// sent, as the program can read it right away and change the mode
// (as when it reads one raw byte and then restores the terminal).
interrupt := false
if user && tm.Func != nil && len(tm.interruptFuncs) > 0 && slices.Contains(b, 0x03) {
p := tm.pty
interrupt = p != nil && tm.IsRunning() && p.Signals()
}
if iq := tm.input.Load(); iq != nil {
iq.send(b)
}
if interrupt {
for _, fun := range tm.interruptFuncs {
fun()
}
}
}
// SendText sends the given text to the program as input,
// as if it was typed, without any processing.
func (tm *Terminal) SendText(s string) {
tm.send([]byte(s), true)
}
// Paste sends the given text to the program as pasted text: line
// breaks are sent as carriage returns (as for the Return key), and the
// text is bracketed if the program asks for it, so that, for example,
// shells do not run the lines in it until Return is pressed.
func (tm *Terminal) Paste(s string) {
s = strings.ReplaceAll(s, "\r\n", "\r")
s = strings.ReplaceAll(s, "\n", "\r")
md := tm.modes()
if md.BracketedPaste {
s = "\x1b[200~" + strings.ReplaceAll(s, "\x1b[201~", "") + "\x1b[201~"
}
tm.send([]byte(s), true)
}
// PasteClipboard pastes the text in the clipboard.
func (tm *Terminal) PasteClipboard() {
data := tm.Clipboard().Read([]string{fileinfo.TextPlain})
if data == nil {
return
}
tm.Paste(data.Text(fileinfo.TextPlain))
}
// Run runs the given command line, by sending it to the shell
// followed by Return. It is up to the user to only do this
// when the shell is waiting for a command.
func (tm *Terminal) Run(cmd string) {
tm.SendText(cmd + "\r")
}
// Cd changes the directory of the shell to the given one,
// by running the cd command with it.
func (tm *Terminal) Cd(dir string) {
if abs, err := filepath.Abs(dir); err == nil {
dir = abs
}
tm.Run(cdCommand(tm.shellName(), dir))
}
// shellName returns the base name of the program, without any extension.
func (tm *Terminal) shellName() string {
args := tm.Command
if len(args) == 0 {
args = pty.DefaultShell()
}
nm := strings.ToLower(filepath.Base(args[0]))
return strings.TrimSuffix(nm, filepath.Ext(nm))
}
// cdCommand returns the command to change to the given directory in the
// given shell, with the directory quoted as needed.
func cdCommand(shell, dir string) string {
switch shell {
case "cmd":
return `cd /d "` + dir + `"`
case "powershell", "pwsh":
return "cd '" + strings.ReplaceAll(dir, "'", "''") + "'"
}
return "cd '" + strings.ReplaceAll(dir, "'", `'\''`) + "'"
}
// ClearScrollback clears the scrollback and the screen, except for the line
// of the cursor, which is typically the prompt of the shell.
func (tm *Terminal) ClearScrollback() {
tm.emulator.Lock()
tm.emulator.ClearScrollback()
tm.emulator.Unlock()
tm.sync()
}
// WorkingDir returns the working directory of the shell, as it reports
// with shell integration (OSC 7), or else that of its process, where it can
// be found (Linux, macOS, and the BSDs), or else the starting directory.
func (tm *Terminal) WorkingDir() string {
tm.emulator.Lock()
dir := tm.emulator.Dir
tm.emulator.Unlock()
if dir != "" {
return dir
}
if tm.pty != nil && tm.pty.Cmd != nil && tm.pty.Cmd.Process != nil {
if dir := processDir(tm.pty.Cmd.Process.Pid); dir != "" {
return dir
}
}
return tm.Dir
}
// Title returns the title set by the program.
func (tm *Terminal) Title() string {
tm.emulator.Lock()
defer tm.emulator.Unlock()
return tm.emulator.Title
}
// Commands returns copies of the commands that have been run, as reported
// by the shell with shell integration (OSC 133 or 633).
func (tm *Terminal) Commands() []vt.Command {
tm.emulator.Lock()
defer tm.emulator.Unlock()
cs := make([]vt.Command, len(tm.emulator.Commands))
for i, c := range tm.emulator.Commands {
cs[i] = *c
}
return cs
}
// OnTitle adds a function to call when the title set by the program changes.
func (tm *Terminal) OnTitle(fun func(title string)) {
tm.titleFuncs = append(tm.titleFuncs, fun)
}
// OnDir adds a function to call when the working directory of the shell
// changes, as reported with shell integration (OSC 7).
func (tm *Terminal) OnDir(fun func(dir string)) {
tm.dirFuncs = append(tm.dirFuncs, fun)
}
// OnExit adds a function to call when the program exits.
func (tm *Terminal) OnExit(fun func(err error)) {
tm.exitFuncs = append(tm.exitFuncs, fun)
}
// OnCommand adds a function to call when a command finishes, as reported
// by the shell with shell integration (OSC 133 or 633).
func (tm *Terminal) OnCommand(fun func(c *vt.Command)) {
tm.commandFuncs = append(tm.commandFuncs, fun)
}
// OnUserCommand adds a function to call with each command line that the
// user enters (with Return) at the prompt of the shell, or of another
// program that reads lines on the primary screen, but not those that the
// program runs itself, as in a script. It is the text of the line as the
// program shows it, from where the user started typing, so that it
// includes the changes of line editing, completion, and the history,
// and it is reported once the program has accepted it: when the cursor
// has left the line.
func (tm *Terminal) OnUserCommand(fun func(cmd string)) {
tm.userCommandFuncs = append(tm.userCommandFuncs, fun)
}
// userInput records where the user starts typing a command line, and the
// command lines entered with Return, for [Terminal.OnUserCommand].
func (tm *Terminal) userInput(b []byte) {
if len(tm.userCommandFuncs) == 0 || tm.altShown {
return
}
for _, c := range b {
if c == '\r' {
if tm.inputStart.Line >= 0 {
tm.entered = append(tm.entered, tm.inputStart)
tm.inputStart.Line = -1
}
continue
}
if tm.inputStart.Line >= 0 || tm.linesCursor.Line < 0 {
continue
}
if n := len(tm.entered); n > 0 && tm.linesCursor.Line <= tm.entered[n-1].Line {
continue // the cursor is still on the last line entered
}
tm.inputStart = tm.linesCursor
}
}
// reportUserCommands reports the command lines entered by the user whose
// lines the cursor has left (see [Terminal.OnUserCommand]).
func (tm *Terminal) reportUserCommands() {
ln := tm.linesView.Lines
for len(tm.entered) > 0 {
st := tm.entered[0]
if tm.linesCursor.Line < 0 || tm.linesCursor.Line <= st.Line {
return // not accepted yet
}
tm.entered = tm.entered[1:]
if st.Line >= ln.NumLines() {
continue
}
line := ln.Line(st.Line)
cmd := strings.TrimSpace(string(line[min(st.Char, len(line)):]))
if cmd == "" {
continue
}
for _, f := range tm.userCommandFuncs {
f(cmd)
}
}
}
// shiftUserInput moves the positions of the user input up by the given
// number of lines removed from the start of the lines view, removing
// those that are no longer there.
func (tm *Terminal) shiftUserInput(n int) {
if tm.inputStart.Line >= 0 {
tm.inputStart.Line = max(tm.inputStart.Line-n, -1)
}
tm.entered = slices.DeleteFunc(tm.entered, func(p textpos.Pos) bool { return p.Line < n })
for i := range tm.entered {
tm.entered[i].Line -= n
}
}
// OnInterrupt adds a function to call when the user types the interrupt
// character (Control+C) while the program does not read raw input, for
// a program run with [Terminal.Func], which does not get the interrupt
// signal that a command gets then.
func (tm *Terminal) OnInterrupt(fun func()) {
tm.interruptFuncs = append(tm.interruptFuncs, fun)
}
// OnResize adds a function to call when the size of the terminal changes
// while the program runs, with the new number of columns and rows. A
// program run with [Terminal.Func] needs this, as it does not get the
// window size signal that a command gets.
func (tm *Terminal) OnResize(fun func(cols, rows int)) {
tm.resizeFuncs = append(tm.resizeFuncs, fun)
}
// modes returns the current terminal modes.
func (tm *Terminal) modes() vt.Modes {
tm.emulator.Lock()
defer tm.emulator.Unlock()
return tm.emulator.Modes
}
// focusChanged reports a focus change to the program, if it asks for it.
func (tm *Terminal) focusChanged(focused bool) {
if md := tm.modes(); md.FocusEvents {
if focused {
tm.send([]byte("\x1b[I"), false)
} else {
tm.send([]byte("\x1b[O"), false)
}
}
tm.scheduleSync() // the cursor color
}
// viewSized is called when the lines view has been sized,
// with the number of columns and rows that it shows.
func (tm *Terminal) viewSized(sz image.Point) {
if sz.X <= 0 || sz.Y <= 0 || sz == tm.size {
return
}
tm.size = sz
if tm.pty == nil {
tm.Start()
return
}
tm.emulator.Lock()
tm.emulator.Resize(sz.X, sz.Y)
tm.emulator.Unlock()
if tm.IsRunning() {
tm.pty.Resize(sz.X, sz.Y)
for _, fun := range tm.resizeFuncs {
fun(sz.X, sz.Y)
}
}
tm.sync()
}
// scheduleSync schedules an update of the views from the terminal state,
// shortly, so that output that comes in many pieces is shown at once.
func (tm *Terminal) scheduleSync() {
if tm.syncScheduled.Swap(true) {
return
}
time.AfterFunc(10*time.Millisecond, func() {
tm.syncScheduled.Store(false)
if !tm.AsyncLockIfShown() {
return
}
tm.sync()
tm.AsyncUnlock()
})
}
// sync updates the views from the terminal state.
func (tm *Terminal) sync() {
lv, gv := tm.linesView, tm.gridView
if lv == nil || gv == nil || lv.Lines == nil || gv.Lines == nil {
return
}
t := tm.emulator
t.Lock()
scrolled, cleared := t.TakeScrolled()
alt := t.IsAltScreen()
cm := newColorMap(lv.Lines.FontStyle(), slices.Clone(t.Links))
cm.cursor, cm.cursorFocused = tm.cursorColor()
t.Foreground, t.Background = cm.fg, cm.bg
md := t.Modes
cur := t.Cursor
var gridText [][]rune
var gridMarkup []rich.Text
if alt {
for r, ln := range t.Lines() {
minLen, cursor := 0, -1
if r == cur.Row {
minLen = cur.Col + 1
if !md.CursorHidden {
cursor = cur.Col
}
tm.gridCursor = textpos.Pos{Line: r, Char: cellChar(ln.Cells, cur.Col)}
}
rs, mu := cm.lineMarkup(ln.Cells, minLen, cursor)
gridText = append(gridText, rs)
gridMarkup = append(gridMarkup, mu)
}
}
var screen []*vt.Line
pcur := t.PrimaryCursor()
if !alt || len(scrolled) > 0 || cleared || tm.numScrollback == 0 {
screen = slices.Clone(t.PrimaryLines())
for i, ln := range screen {
screen[i] = &vt.Line{Cells: slices.Clone(ln.Cells), Wrapped: ln.Wrapped}
}
}
t.Unlock()
toEnd := tm.toEnd || lv.IsScrolledToEnd()
tm.toEnd = false
// the text being composed with an input method is virtual text at the
// cursor, which is lost when the lines are replaced, so it is shown again
lvIME, gvIME := lv.VirtualText(imeLayer), gv.VirtualText(imeLayer)
if screen != nil {
tm.syncLines(cm, scrolled, cleared, screen, pcur, !md.CursorHidden && !alt)
tm.reportUserCommands()
}
if alt {
gv.Lines.ReplaceLinesMarkup(0, -1, gridText, gridMarkup)
gv.NeedsRender()
}
lv.restoreComposition(lvIME)
gv.restoreComposition(gvIME)
if alt != tm.altShown {
tm.altShown = alt
focused := lv.StateIs(states.Focused) || gv.StateIs(states.Focused)
tm.StackTop = 0
if alt {
tm.StackTop = 1
}
tm.NeedsLayout()
if focused {
tm.ActiveView().SetFocus()
}
}
if toEnd && !alt {
lv.SetCursorTarget(textpos.PosErr)
}
lv.NeedsRender()
tm.sendInfo()
}
// syncLines updates the lines view from the given lines scrolled into
// the scrollback, and the lines of the primary screen, with its cursor,
// which is shown if showCursor is true.
func (tm *Terminal) syncLines(cm *colorMap, scrolled []*vt.Line, cleared bool, screen []*vt.Line, cur vt.Cursor, showCursor bool) {
lv := tm.linesView
ln := lv.Lines
if cleared {
tm.pending = nil
tm.numScrollback = 0
tm.inputStart.Line = -1
tm.entered = nil
}
var text [][]rune
var markup []rich.Text
addLine := func(rows []*vt.Line, cursorOff int) {
var cells []vt.Cell
for _, r := range rows {
cells = append(cells, r.Cells...)
}
cursor := -1
if showCursor {
cursor = cursorOff
}
rs, mu := cm.lineMarkup(cells, cursorOff+1, cursor)
text = append(text, rs)
markup = append(markup, mu)
}
// complete lines of scrollback
rows := append(tm.pending, scrolled...)
st := 0
for i, r := range rows {
if !r.Wrapped {
addLine(rows[st:i+1], -1)
st = i + 1
}
}
tm.pending = slices.Clone(rows[st:])
nhist := len(text)
// the screen, with the pending lines
live := append(slices.Clone(tm.pending), screen...)
crow := len(tm.pending) + cur.Row
tm.linesCursor = textpos.Pos{Line: -1}
st = 0
for i, r := range live {
if !r.Wrapped || i == len(live)-1 {
off := -1
if crow >= st && crow <= i {
off = cur.Col
var cells []vt.Cell
for _, pr := range live[st : i+1] {
cells = append(cells, pr.Cells...)
}
for _, pr := range live[st:crow] {
off += len(pr.Cells)
}
tm.linesCursor = textpos.Pos{Line: tm.numScrollback + len(text), Char: cellChar(cells, off)}
}
addLine(live[st:i+1], off)
st = i + 1
}
}
ln.ReplaceLinesMarkup(tm.numScrollback, -1, text, markup)
tm.numScrollback += nhist
if over := tm.numScrollback - tm.MaxScrollback; tm.MaxScrollback > 0 && over > tm.MaxScrollback/10 {
ln.ReplaceLinesMarkup(0, over, nil, nil)
tm.numScrollback -= over
tm.linesCursor.Line -= over
tm.shiftUserInput(over)
}
}
// cursorColor returns the color of the cursor, and whether the view
// that shows it is focused, in which case the color is blended with
// the background of the cell.
func (tm *Terminal) cursorColor() (color.RGBA, bool) {
vw := tm.ActiveView()
if vw != nil && vw.StateIs(states.Focused) {
return colors.ToUniform(colors.Scheme.Primary.Base), true
}
return colors.ToUniform(colors.Scheme.OutlineVariant), false
}
// sendInfo calls the listener functions for changes in the title,
// directory, and commands, and for the exit of the program.
func (tm *Terminal) sendInfo() {
if !tm.infoChanged.Swap(false) {
return
}
t := tm.emulator
t.Lock()
title, dir := t.Title, t.Dir
var done []vt.Command
for i := tm.numCommands; i < len(t.Commands); i++ {
c := t.Commands[i]
if !c.Done {
break
}
done = append(done, *c)
tm.numCommands = i + 1
}
if tm.numCommands > len(t.Commands) { // trimmed
tm.numCommands = len(t.Commands)
}
t.Unlock()
if title != tm.title {
tm.title = title
for _, f := range tm.titleFuncs {
f(title)
}
}
if dir != tm.dir {
tm.dir = dir
for _, f := range tm.dirFuncs {
f(dir)
}
}
for i := range done {
for _, f := range tm.commandFuncs {
f(&done[i])
}
}
if tm.exited.Load() && !tm.exitSent {
tm.exitSent = true
for _, f := range tm.exitFuncs {
f(tm.exitErr)
}
}
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package terminal
import (
"image"
"strings"
"cogentcore.org/core/base/fileinfo/mimedata"
"cogentcore.org/core/colors"
"cogentcore.org/core/core"
"cogentcore.org/core/cursors"
"cogentcore.org/core/events"
"cogentcore.org/core/events/key"
"cogentcore.org/core/icons"
"cogentcore.org/core/keymap"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/lines"
"cogentcore.org/core/text/terminal/vt"
"cogentcore.org/core/text/textcore"
"cogentcore.org/core/text/textpos"
)
// View is a view of the terminal text, which is either the lines view,
// with the scrollback and the primary screen as lines of text that are
// wrapped to the view width, or the grid view of the alternate screen
// that full-screen programs use. All key events go to the program,
// except for the keys for copying and pasting, and for scrolling the
// lines view (Shift with PageUp, PageDown, Home, and End). The text can
// be selected with the mouse, unless the program uses the mouse, in
// which case the Shift key can be held to select.
type View struct {
textcore.Editor
// Terminal is the terminal of this view.
Terminal *Terminal `set:"-" display:"-" json:"-" xml:"-"`
// isGrid is whether this is the grid view.
isGrid bool
// lastKeyDown is the code of the last key down event,
// for Alt with a character.
lastKeyDown key.Codes
// mouseDown is the button that is down, reported to the program.
mouseDown int
// scrollDelta accumulates mouse wheel scrolling, in lines.
scrollDelta float32
}
func (vw *View) Init() {
vw.Editor.Init()
vw.mouseDown = mouseNoButton
vw.SetReadOnly(true)
vw.InputPos = vw.inputPos
vw.Styler(func(s *styles.Style) {
s.SetAbilities(true, abilities.Focusable)
s.Cursor = cursors.Text
s.Text.LineHeight = 1 // the backgrounds of lines touch
s.Border.Radius = styles.BorderRadiusLarge // as in the editor
s.Border.Width.Zero()
s.MaxBorder.Width.Set(units.Dp(2)) // the focus border, as in the editor
s.Padding.Set(units.Em(0.5)) // room for the radius, as in the editor
s.Background = colors.Scheme.Surface
s.Grow.Set(1, 1)
s.Min.X.Ch(20)
s.Min.Y.Em(4)
if !vw.isGrid {
s.Overflow.Y = styles.OverflowScroll // stable width
}
})
vw.On(events.KeyDown, func(e events.Event) {
vw.lastKeyDown = e.KeyCode()
})
vw.OnKeyChord(func(e events.Event) {
vw.keyChord(e)
})
vw.OnFocus(func(e events.Event) {
vw.Terminal.focusChanged(true)
})
vw.OnFocusLost(func(e events.Event) {
vw.Terminal.focusChanged(false)
})
vw.handleMouse()
vw.ContextMenus = nil // not those of the editor
vw.AddContextMenu(vw.contextMenu)
vw.AddContextMenu(func(m *core.Scene, pos image.Point) {
// those of the terminal, first
cms := vw.Terminal.ContextMenus
for ri := len(cms) - 1; ri >= 0; ri-- {
cm := cms[ri]
if m.NumChildren() > 0 {
core.NewSeparator(m)
}
cm(m, pos)
}
})
}
// inputPos returns the position of the terminal cursor in the view,
// where the text being composed with an input method is shown,
// and whether the program is running there.
func (vw *View) inputPos() (textpos.Pos, bool) {
tm := vw.Terminal
if tm == nil || !tm.IsRunning() {
return textpos.Pos{}, false
}
if vw.isGrid {
return tm.gridCursor, tm.altShown
}
return tm.linesCursor, !tm.altShown && tm.linesCursor.Line >= 0
}
// imeLayer is the layer of the virtual text of the text being composed
// with an input method, as in textcore.
const imeLayer = "ime"
// restoreComposition shows the given virtual text of the text being
// composed with an input method again at the input position, after the
// lines have been replaced, unless there is no input there any more.
func (vw *View) restoreComposition(vts []lines.VirtualText) {
if len(vts) == 0 || len(vw.VirtualText(imeLayer)) > 0 {
return
}
pos, ok := vw.inputPos()
if !ok {
return
}
for i := range vts {
vts[i].Pos = pos
}
vw.SetVirtualText(imeLayer, vts...)
}
// contextMenu adds the items of the terminal to the context menu.
func (vw *View) contextMenu(m *core.Scene, pos image.Point) {
tm := vw.Terminal
if m.NumChildren() > 0 {
core.NewSeparator(m)
}
core.NewButton(m).SetText("Copy").SetIcon(icons.ContentCopy).
SetShortcut(ShortcutChord(keymap.Copy)).SetState(!vw.HasSelection(), states.Disabled).
OnClick(func(e events.Event) {
vw.copy()
})
core.NewButton(m).SetText("Select all").SetIcon(icons.SelectAll).
SetShortcut(ShortcutChord(keymap.SelectAll)).
OnClick(func(e events.Event) {
vw.selectAll()
})
core.NewButton(m).SetText("Paste").SetIcon(icons.ContentPaste).
SetShortcut(ShortcutChord(keymap.Paste)).SetState(vw.Clipboard().IsEmpty(), states.Disabled).
OnClick(func(e events.Event) {
tm.PasteClipboard()
})
core.NewButton(m).SetText("Clear scrollback").SetIcon(icons.ClearAll).
SetShortcut(ShortcutChord(keymap.Kill)).
OnClick(func(e events.Event) {
tm.ClearScrollback()
})
}
// SizeFinal resizes the terminal to fit the lines view.
func (vw *View) SizeFinal() {
vw.Editor.SizeFinal()
if !vw.isGrid && vw.Terminal != nil {
vw.Terminal.viewSized(vw.VisibleSize())
}
}
// keyChord handles a key chord event.
func (vw *View) keyChord(e events.Event) {
tm := vw.Terminal
if tm == nil {
return
}
if vw.shortcut(e) {
e.SetHandled()
return
}
if !vw.isGrid {
// the keys for the tabs that the terminal is in go to them, except
// in full-screen programs (the grid), which use them
core.TabKeys(vw, e)
if e.IsHandled() {
return
}
// as does the key of the menu (search) of the app (Control+M,
// which is the same as Return for the program)
if keymap.Of(e.KeyChord()) == keymap.Menu {
return
}
}
mods := e.Modifiers()
if mods.HasFlag(key.Meta) { // app shortcuts
return
}
code := e.KeyCode()
if code == key.CodeUnknown && mods.HasFlag(key.Alt) {
code = vw.lastKeyDown
}
md := tm.modes()
b := keyBytes(e.KeyRune(), code, mods, &md, tm.AltAsMeta)
if b == nil {
return
}
e.SetHandled()
if tm.restartOnKey() {
return
}
vw.SelectReset()
tm.send(b, true)
}
// shortcut handles the shortcut keys of the terminal GUI,
// returning true if the key is one.
func (vw *View) shortcut(e events.Event) bool {
tm := vw.Terminal
mods := e.Modifiers()
switch KeyFunction(e) {
case keymap.Copy:
vw.copy()
return true
case keymap.SelectAll:
vw.selectAll()
return true
case keymap.Paste:
tm.PasteClipboard()
return true
case keymap.Kill:
tm.ClearScrollback()
return true
}
// the Copy key copies when there is a selection, even if it goes to
// the program otherwise (Control+C), as in Windows Terminal
if keymap.Of(e.KeyChord()) == keymap.Copy && vw.HasSelection() {
vw.copy()
return true
}
if !mods.HasFlag(key.Shift) || vw.isGrid {
return false
}
lv := tm.linesView
switch e.KeyCode() {
case key.CodePageUp:
lv.SetScrollPos(lv.ScrollPos() - float32(max(1, lv.VisibleSize().Y-1)))
case key.CodePageDown:
lv.SetScrollPos(lv.ScrollPos() + float32(max(1, lv.VisibleSize().Y-1)))
if lv.IsScrolledToEnd() {
lv.SetCursorTarget(textpos.PosErr)
}
case key.CodeHome:
lv.SetScrollPos(0)
case key.CodeEnd:
lv.SetCursorTarget(textpos.PosErr)
default:
return false
}
return true
}
// selectAll selects all of the text, up to the end of the last line that
// is not blank, leaving out the blank lines of the screen below the output.
func (vw *View) selectAll() {
ln := vw.Lines
if ln == nil {
return
}
end := textpos.Pos{}
for i := ln.NumLines() - 1; i >= 0; i-- {
if n := len([]rune(strings.TrimRight(string(ln.Line(i)), " "))); n > 0 {
end = textpos.Pos{Line: i, Char: n}
break
}
}
vw.SelectRegion.Start = textpos.PosZero
vw.SelectRegion.End = end
vw.NeedsRender()
}
// copy copies the selected text to the clipboard (see [View.selectedText]).
func (vw *View) copy() {
if !vw.HasSelection() {
return
}
vw.Clipboard().Write(mimedata.NewText(vw.selectedText()))
}
// selectedText returns the selected text, without the spaces at the ends
// of lines, which fill the lines of the terminal, and the blank lines at
// the end.
func (vw *View) selectedText() string {
tbe := vw.Selection()
if tbe == nil {
return ""
}
lines := strings.Split(string(tbe.ToBytes()), "\n")
for i, l := range lines {
lines[i] = strings.TrimRight(l, " ")
}
return strings.TrimRight(strings.Join(lines, "\n"), "\n")
}
// mouseReporting returns whether mouse events are reported to the
// program, which is only done in the grid view when the program has
// asked for them, and the Shift key is not down.
func (vw *View) mouseReporting(e events.Event) bool {
if !vw.isGrid || e.HasAnyModifier(key.Shift) {
return false
}
md := vw.Terminal.modes()
return md.Mouse != vt.MouseNone
}
// cellAt returns the terminal row and column at the given event position,
// for the grid view.
func (vw *View) cellAt(e events.Event) (row, col int) {
pt := e.Pos()
pos := vw.PixelToCursor(vw.PointToRelPos(pt))
row = max(0, pos.Line)
cs := vw.CharSize()
if cs.X <= 0 {
return row, 0
}
st := vw.CharStartPos(textpos.Pos{Line: row})
col = max(0, int(math32.Floor((float32(pt.X)-st.X)/cs.X)))
return row, col
}
// reportMouse reports the given mouse event to the program,
// returning true if it was reported.
func (vw *View) reportMouse(e events.Event, action mouseAction, button int) bool {
if !vw.mouseReporting(e) {
return false
}
md := vw.Terminal.modes()
row, col := vw.cellAt(e)
if b := mouseBytes(&md, action, button, row, col, e.Modifiers()); b != nil {
vw.Terminal.send(b, false)
}
return true
}
// mouseButton returns the terminal mouse button for the event.
func mouseButton(e events.Event) int {
switch e.MouseButton() {
case events.Middle:
return mouseMiddle
case events.Right:
return mouseRight
}
return mouseLeft
}
// handleMouse handles the mouse events that are reported to the
// program, and the mouse wheel in the grid view.
func (vw *View) handleMouse() {
vw.On(events.MouseDown, func(e events.Event) {
b := mouseButton(e)
if vw.reportMouse(e, mousePress, b) {
vw.mouseDown = b
vw.SetFocus()
e.SetHandled()
}
})
vw.On(events.MouseUp, func(e events.Event) {
if vw.mouseDown != mouseNoButton && vw.reportMouse(e, mouseRelease, vw.mouseDown) {
e.SetHandled()
}
vw.mouseDown = mouseNoButton
})
vw.On(events.MouseMove, func(e events.Event) {
if vw.reportMouse(e, mouseMotion, vw.mouseDown) {
e.SetHandled()
}
})
vw.On(events.MouseDrag, func(e events.Event) {
if vw.reportMouse(e, mouseMotion, vw.mouseDown) {
e.SetHandled()
}
})
// the events for selection are not used when reporting
for _, typ := range []events.Types{events.Click, events.DoubleClick, events.TripleClick, events.SlideStart, events.SlideMove, events.SlideStop, events.ContextMenu} {
vw.On(typ, func(e events.Event) {
if vw.mouseReporting(e) {
e.SetHandled()
}
})
}
vw.On(events.Scroll, func(e events.Event) {
if !vw.isGrid {
return
}
e.SetHandled()
se := e.(*events.MouseScroll)
cs := vw.CharSize()
if cs.Y <= 0 {
return
}
vw.scrollDelta += se.Delta.Y / cs.Y
n := int(vw.scrollDelta)
if n == 0 {
return
}
vw.scrollDelta -= float32(n)
md := vw.Terminal.modes()
button, keyCode := mouseWheelDown, key.CodeDownArrow
if n < 0 {
n = -n
button, keyCode = mouseWheelUp, key.CodeUpArrow
}
for range n {
if md.Mouse != vt.MouseNone {
row, col := vw.cellAt(e)
vw.Terminal.send(mouseBytes(&md, mousePress, button, row, col, e.Modifiers()), false)
} else if md.AltScroll {
vw.Terminal.send(keyBytes(0, keyCode, 0, &md, false), false)
}
}
})
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package vt
import "fmt"
// Color is a terminal color: the default color, an index into the
// 256 color palette, or a 24-bit RGB value.
type Color uint32
const (
// ColorDefault is the default foreground or background color.
ColorDefault Color = 0
colorIndexed Color = 1 << 24
colorRGB Color = 2 << 24
colorKind Color = 0xff << 24
)
// IndexedColor returns the color for the given palette index:
// 0-7 are the standard colors, 8-15 the bright ones, 16-231 a
// 6x6x6 color cube, and 232-255 a grayscale ramp.
func IndexedColor(i uint8) Color {
return colorIndexed | Color(i)
}
// RGBColor returns the 24-bit color with the given components.
func RGBColor(r, g, b uint8) Color {
return colorRGB | Color(r)<<16 | Color(g)<<8 | Color(b)
}
// IsDefault returns whether this is the default color.
func (c Color) IsDefault() bool {
return c == ColorDefault
}
// Index returns the palette index of an indexed color, and whether it is one.
func (c Color) Index() (uint8, bool) {
return uint8(c & 0xff), c&colorKind == colorIndexed
}
// RGB returns the components of a 24-bit color, and whether it is one.
func (c Color) RGB() (r, g, b uint8, ok bool) {
return uint8(c >> 16), uint8(c >> 8), uint8(c), c&colorKind == colorRGB
}
func (c Color) String() string {
if i, ok := c.Index(); ok {
return fmt.Sprintf("%d", i)
}
if r, g, b, ok := c.RGB(); ok {
return fmt.Sprintf("#%02x%02x%02x", r, g, b)
}
return "default"
}
// Attrs are the text attributes of a cell, as bit flags.
type Attrs uint16
const (
Bold Attrs = 1 << iota
Faint
Italic
Underline
DoubleUnderline
Blink
Reverse
Invisible
Strikethrough
Overline
)
// Style is the style of a cell.
type Style struct {
// Fg is the foreground (text) color.
Fg Color
// Bg is the background color.
Bg Color
// Attrs are the text attributes.
Attrs Attrs
// Link is the 1-based index of the hyperlink of the cell
// in [Emulator.Links], or 0 for none.
Link uint32
}
// IsDefault returns whether this is the default style.
func (s Style) IsDefault() bool {
return s == Style{}
}
// Cell is one character cell in the terminal grid.
type Cell struct {
// Rune is the character in the cell, or 0 for an empty cell,
// which is shown as a space. A wide character, such as a CJK
// ideograph, takes two cells: the second has Rune 0 and Width 0.
Rune rune
// Width is the number of cells that the character takes:
// 1 normally, 2 for a wide character, and 0 for the cell
// after a wide character.
Width uint8
// Style is the style of the cell.
Style Style
}
// blankCell returns an empty cell with the given background color,
// as used for erasing.
func blankCell(bg Color) Cell {
return Cell{Width: 1, Style: Style{Bg: bg}}
}
// IsBlank returns whether the cell is empty with the default style.
func (c *Cell) IsBlank() bool {
return (c.Rune == 0 || c.Rune == ' ') && c.Width == 1 && c.Style.IsDefault()
}
// Line is one row of cells in the terminal grid.
type Line struct {
// Cells are the cells in the line.
Cells []Cell
// Wrapped is whether the text of this line continues on the next
// line, because it was wrapped at the end of the line (a soft wrap),
// rather than ending with a line feed.
Wrapped bool
}
// newLine returns a new blank line with the given number of cells
// and background color.
func newLine(cols int, bg Color) *Line {
ln := &Line{Cells: make([]Cell, cols)}
ln.clear(0, cols, bg)
return ln
}
// clear clears the cells from st up to ed with the given background color.
func (ln *Line) clear(st, ed int, bg Color) {
bc := blankCell(bg)
for i := st; i < ed; i++ {
ln.Cells[i] = bc
}
}
// Len returns the length of the line without trailing blank cells.
func (ln *Line) Len() int {
n := len(ln.Cells)
for n > 0 && ln.Cells[n-1].IsBlank() {
n--
}
return n
}
// String returns the text of the line, without the trailing blank cells.
func (ln *Line) String() string {
return string(ln.Runes(ln.Len()))
}
// Runes returns the runes of the first n cells of the line,
// with a space for each empty cell, and nothing for the cell after
// a wide character.
func (ln *Line) Runes(n int) []rune {
rs := make([]rune, 0, n)
for i := range min(n, len(ln.Cells)) {
c := &ln.Cells[i]
switch {
case c.Width == 0:
case c.Rune == 0:
rs = append(rs, ' ')
default:
rs = append(rs, c.Rune)
}
}
return rs
}
// clone returns a copy of the line.
func (ln *Line) clone() *Line {
return &Line{Cells: append([]Cell(nil), ln.Cells...), Wrapped: ln.Wrapped}
}
// resize changes the number of cells in the line to n,
// adding blank cells as needed.
func (ln *Line) resize(n int) {
cur := len(ln.Cells)
if n <= cur {
ln.Cells = ln.Cells[:n]
if n > 0 && ln.Cells[n-1].Width == 2 { // half of a wide character
ln.Cells[n-1] = blankCell(ln.Cells[n-1].Style.Bg)
}
return
}
ln.Cells = append(ln.Cells, make([]Cell, n-cur)...)
ln.clear(cur, n, ColorDefault)
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package vt implements a virtual terminal emulator, [Emulator]:
// the grid of character
// cells that results from the output of programs that use the standard
// (VT100 / xterm) terminal control sequences, with the scrolling
// scrollback, modes, and other state of the terminal. It has no GUI:
// see the parent terminal package for the widget that shows it.
// The control sequences are parsed with github.com/charmbracelet/x/ansi.
package vt
import (
"image/color"
"strings"
"sync"
"github.com/charmbracelet/x/ansi"
)
// Emulator emulates a terminal: it has the state of the terminal,
// mainly the cell grid of the current screen, which is updated from the
// output of a program, given to [Emulator.Write]. Replies to queries from the program, such as for the
// cursor position, are sent to [Emulator.Reply]. The methods do not
// lock the terminal: users that access it from multiple goroutines
// must use its mutex.
type Emulator struct {
// Cols is the number of columns (cells per line).
Cols int
// Rows is the number of rows (lines) in the screen.
Rows int
// Cursor is the cursor position and the state that goes with it.
Cursor Cursor
// Modes are the terminal modes set by the program.
Modes Modes
// Title is the window title, set by the program.
Title string
// Dir is the current working directory of the program,
// as reported by it with the OSC 7 sequence (as shells do with
// shell integration).
Dir string
// Links are the URLs of hyperlinks (OSC 8), indexed by [Style.Link]-1.
Links []string
// Commands are the commands that have been run, as reported by
// the shell with shell integration sequences (OSC 133 or OSC 633).
Commands []*Command
// MaxCommands is the maximum number of [Emulator.Commands] to keep.
MaxCommands int
// Foreground and Background are the default colors, which are reported
// to programs that query them (OSC 10 and 11), such as editors that
// choose a light or dark theme.
Foreground, Background color.RGBA
// Reply is called with the replies to queries from the program,
// which must be written to its input.
Reply func(b []byte)
// Bell is called for the bell control character.
Bell func()
// Changed is called when the title, the working directory, or the
// commands have changed.
Changed func()
// Clipboard is called when the program sets the clipboard (OSC 52).
// It is off unless set, for security.
Clipboard func(text string)
// primary is the main screen, which has the scrollback.
primary *screen
// alt is the alternate screen used by full-screen programs.
alt *screen
// screen is the current screen, primary or alt.
screen *screen
// scrolled are the lines scrolled off the top of the primary screen
// since the last [Emulator.TakeScrolled].
scrolled []*Line
// numScrolled is the total number of lines scrolled off the top of
// the primary screen, for the absolute line numbers of [Command]s.
numScrolled int
// scrollbackCleared is set when the program clears the scrollback (ED 3).
scrollbackCleared bool
// top and bottom are the scroll region rows (bottom is inclusive).
top, bottom int
// tabStops are the tab stop columns.
tabStops []bool
// lastRune is the last printed character, for the REP sequence.
lastRune rune
// linkURL is the current hyperlink index (1-based), or 0.
link uint32
// parser is the control sequence parser.
parser *ansi.Parser
// Mutex is for users of the Emulator from multiple goroutines.
sync.Mutex
}
// Cursor is the cursor position and the state that is saved and
// restored with it.
type Cursor struct {
// Row and Col are the cursor position.
Row, Col int
// Style is the style for newly written characters.
Style Style
// pendingWrap is set when a character is written in the last
// column, so the next one wraps to the next line.
pendingWrap bool
// charsets are the G0 and G1 character sets.
charsets [2]charset
// shift is the active character set (0 or 1).
shift int
// originMode is the DECOM mode, which is saved with the cursor.
originMode bool
}
// charset is a character set designation.
type charset uint8
const (
charsetASCII charset = iota
charsetDECGraphics
)
// Modes are the terminal modes that programs set.
type Modes struct {
// AutoWrap wraps text at the end of a line (DECAWM). On by default.
AutoWrap bool
// Insert inserts characters rather than replacing them (IRM).
Insert bool
// NewLine makes a line feed also do a carriage return (LNM).
NewLine bool
// CursorHidden is set when the program hides the cursor (DECTCEM).
CursorHidden bool
// AppCursorKeys makes the cursor keys send application codes (DECCKM).
AppCursorKeys bool
// AppKeypad makes the keypad send application codes (DECKPAM).
AppKeypad bool
// ReverseVideo swaps the default colors of the screen (DECSCNM).
ReverseVideo bool
// BracketedPaste brackets pasted text with escape codes.
BracketedPaste bool
// FocusEvents sends codes when the terminal gains or loses focus.
FocusEvents bool
// Mouse is the mouse tracking mode.
Mouse MouseModes
// MouseSGR uses the SGR encoding for mouse events (mode 1006).
MouseSGR bool
// AltScroll sends cursor keys for the mouse wheel in the alternate
// screen (mode 1007). On by default.
AltScroll bool
// CursorShape is the cursor shape set by the program (DECSCUSR):
// 0-1 blinking block, 2 block, 3-4 underline, 5-6 bar.
CursorShape int
}
// MouseModes are the mouse tracking modes.
type MouseModes uint8
const (
// MouseNone does no mouse tracking.
MouseNone MouseModes = iota
// MouseX10 reports button presses (mode 9).
MouseX10
// MouseNormal reports button presses and releases (mode 1000).
MouseNormal
// MouseButton also reports motion with a button down (mode 1002).
MouseButton
// MouseAny reports all motion (mode 1003).
MouseAny
)
// NewEmulator returns a new terminal with the given size.
func NewEmulator(cols, rows int) *Emulator {
em := &Emulator{MaxCommands: 1000}
em.parser = ansi.NewParser()
em.parser.SetHandler(ansi.Handler{
Print: em.print,
Execute: em.execute,
HandleCsi: em.handleCSI,
HandleEsc: em.handleESC,
HandleOsc: em.handleOSC,
})
em.Foreground = color.RGBA{0, 0, 0, 255}
em.Background = color.RGBA{255, 255, 255, 255}
em.Cols = max(cols, 1)
em.Rows = max(rows, 1)
em.primary = newScreen(em.Cols, em.Rows)
em.alt = newScreen(em.Cols, em.Rows)
em.reset()
return em
}
// reset sets the terminal to its initial state, except for the scrollback.
func (em *Emulator) reset() {
em.screen = em.primary
em.primary.clear()
em.alt.clear()
em.Cursor = Cursor{}
em.primary.saved = Cursor{}
em.alt.saved = Cursor{}
em.Modes = Modes{AutoWrap: true, AltScroll: true}
em.top = 0
em.bottom = em.Rows - 1
em.resetTabStops()
em.link = 0
em.Links = nil
}
// Write processes the given output of the program.
// It always returns len(b), nil.
func (em *Emulator) Write(b []byte) (int, error) {
em.parser.Parse(b)
return len(b), nil
}
// WriteString processes the given output of the program.
func (em *Emulator) WriteString(s string) {
em.Write([]byte(s))
}
// IsAltScreen returns whether the alternate screen is active,
// as it is for full-screen programs such as editors.
func (em *Emulator) IsAltScreen() bool {
return em.screen == em.alt
}
// Lines returns the lines of the current screen. They must not be
// changed, and are only valid until the next Write.
func (em *Emulator) Lines() []*Line {
return em.screen.lines
}
// PrimaryLines returns the lines of the primary screen, even when the
// alternate screen is active. They must not be changed, and are only
// valid until the next Write.
func (em *Emulator) PrimaryLines() []*Line {
return em.primary.lines
}
// PrimaryCursor returns the cursor of the primary screen, which is
// saved while the alternate screen is active.
func (em *Emulator) PrimaryCursor() Cursor {
if em.IsAltScreen() {
return em.primary.saved
}
return em.Cursor
}
// ClearScrollback clears the scrollback and the lines of the primary screen
// above the cursor line, which becomes the first line, as for a clear
// command in the terminal GUI that keeps the current prompt.
func (em *Emulator) ClearScrollback() {
em.scrolled = nil
em.scrollbackCleared = true
if em.IsAltScreen() {
return
}
row := em.Cursor.Row
for row > 0 && em.primary.lines[row-1].Wrapped {
row--
}
if row > 0 {
top, bottom := em.top, em.bottom
em.top, em.bottom = 0, em.Rows-1
em.scrollUpRegion(0, row, false)
em.top, em.bottom = top, bottom
em.Cursor.Row -= row
}
}
// Line returns the given row of the current screen.
func (em *Emulator) Line(row int) *Line {
return em.screen.lines[row]
}
// String returns the text of the current screen, without the trailing
// blank cells of each line, with a line feed after each line.
func (em *Emulator) String() string {
var sb strings.Builder
for _, ln := range em.screen.lines {
sb.WriteString(ln.String())
sb.WriteByte('\n')
}
return sb.String()
}
// TakeScrolled returns the lines that have scrolled off the top of the
// primary screen since the last call, for the scrollback,
// and whether the scrollback was cleared (ED 3) before them.
func (em *Emulator) TakeScrolled() (lines []*Line, cleared bool) {
lines, cleared = em.scrolled, em.scrollbackCleared
em.scrolled = nil
em.scrollbackCleared = false
return
}
// NumScrolled returns the total number of lines that have scrolled
// off the top of the primary screen. The absolute line number of a
// row in the screen is NumScrolled + row.
func (em *Emulator) NumScrolled() int {
return em.numScrolled
}
// reply sends the given reply to the program.
func (em *Emulator) reply(s string) {
if em.Reply != nil {
em.Reply([]byte(s))
}
}
// changed calls the Changed function.
func (em *Emulator) changed() {
if em.Changed != nil {
em.Changed()
}
}
// resetTabStops sets tab stops every 8 columns.
func (em *Emulator) resetTabStops() {
em.tabStops = make([]bool, em.Cols)
for i := 8; i < em.Cols; i += 8 {
em.tabStops[i] = true
}
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package vt
import (
"encoding/base64"
"fmt"
"image/color"
"net/url"
"strconv"
"strings"
)
// handleOSC handles an operating system command, which has the
// command number and then its data: "cmd;data".
func (em *Emulator) handleOSC(cmd int, data []byte) {
s := string(data)
if i := strings.IndexByte(s, ';'); i >= 0 {
s = s[i+1:]
} else {
s = ""
}
switch cmd {
case 0, 2:
em.Title = s
em.changed()
case 7:
em.setDir(dirFromURL(s))
case 8:
em.setLink(s)
case 10:
if s == "?" {
em.reply(colorReply(10, em.Foreground))
}
case 11:
if s == "?" {
em.reply(colorReply(11, em.Background))
}
case 52:
em.setClipboard(s)
case 133:
em.shellMark(s, false)
case 633:
em.shellMark(s, true)
case 1337:
if dir, ok := strings.CutPrefix(s, "CurrentDir="); ok {
em.setDir(dir)
}
}
}
// setDir sets the current working directory.
func (em *Emulator) setDir(dir string) {
if dir == "" || dir == em.Dir {
return
}
em.Dir = dir
if len(em.Commands) > 0 {
if c := em.Commands[len(em.Commands)-1]; !c.Done && c.Dir == "" {
c.Dir = dir
}
}
em.changed()
}
// dirFromURL returns the path of a file URL, as sent with OSC 7.
func dirFromURL(s string) string {
u, err := url.Parse(s)
if err != nil || u.Scheme != "file" {
return ""
}
p := u.Path
if len(p) > 2 && p[0] == '/' && p[2] == ':' { // Windows drive: /C:/dir
p = p[1:]
}
return p
}
// colorReply returns the reply to a query for the given color.
func colorReply(cmd int, c color.RGBA) string {
return fmt.Sprintf("\x1b]%d;rgb:%04x/%04x/%04x\x1b\\", cmd, uint16(c.R)*0x101, uint16(c.G)*0x101, uint16(c.B)*0x101)
}
// setLink starts or ends a hyperlink (OSC 8): "params;uri",
// with an empty uri ending it.
func (em *Emulator) setLink(s string) {
_, uri, _ := strings.Cut(s, ";")
if uri == "" {
em.link = 0
return
}
for i, l := range em.Links {
if l == uri {
em.link = uint32(i + 1)
return
}
}
em.Links = append(em.Links, uri)
em.link = uint32(len(em.Links))
}
// setClipboard handles OSC 52: "selection;base64 data".
func (em *Emulator) setClipboard(s string) {
if em.Clipboard == nil {
return
}
_, d, _ := strings.Cut(s, ";")
if d == "?" { // queries are not answered, for security
return
}
b, err := base64.StdEncoding.DecodeString(d)
if err != nil {
return
}
em.Clipboard(string(b))
}
// Command is a command run in the shell, as reported by the shell with
// shell integration sequences: OSC 133 (FinalTerm) or OSC 633 (VS Code).
// Lines are absolute line numbers (see [Emulator.NumScrolled]).
type Command struct {
// PromptLine is the line where the prompt starts.
PromptLine int
// InputLine and InputCol are where the command input starts,
// after the prompt.
InputLine, InputCol int
// OutputLine is the line where the output of the command starts,
// or -1 before it is run.
OutputLine int
// EndLine is the line where the command finished, or -1.
EndLine int
// Text is the command line.
Text string
// Dir is the working directory of the command, if known.
Dir string
// ExitCode is the exit code of the command, if it is Done
// and the shell reported it, or -1.
ExitCode int
// Done is whether the command has finished.
Done bool
}
// shellMark handles a shell integration mark: A prompt start,
// B command start, C command executed (output start), D[;exit code]
// command finished, and for OSC 633 (vscode), E;command line and
// P;Cwd=dir.
func (em *Emulator) shellMark(s string, vscode bool) {
if s == "" {
return
}
kind, arg, _ := strings.Cut(s, ";")
line := em.numScrolled + em.Cursor.Row
last := func() *Command {
if len(em.Commands) == 0 {
return nil
}
return em.Commands[len(em.Commands)-1]
}
switch kind {
case "A":
if c := last(); c != nil && !c.Done && c.OutputLine < 0 {
c.PromptLine = line // a new prompt without running a command
return
}
em.Commands = append(em.Commands, &Command{PromptLine: line, InputLine: -1, OutputLine: -1, EndLine: -1, ExitCode: -1, Dir: em.Dir})
if len(em.Commands) > em.MaxCommands && em.MaxCommands > 0 {
em.Commands = em.Commands[len(em.Commands)-em.MaxCommands:]
}
case "B":
if c := last(); c != nil && !c.Done {
c.InputLine, c.InputCol = line, em.Cursor.Col
}
case "C":
if c := last(); c != nil && !c.Done {
c.OutputLine = line
if c.Text == "" {
c.Text = em.inputText(c)
}
}
case "D":
if c := last(); c != nil && !c.Done {
c.Done = true
c.EndLine = line
if code, err := strconv.Atoi(strings.TrimSpace(arg)); err == nil {
c.ExitCode = code
}
}
case "E":
if c := last(); c != nil && vscode {
cmd, _, _ := strings.Cut(arg, ";")
c.Text = unescapeVSCode(cmd)
}
return
case "P":
if dir, ok := strings.CutPrefix(arg, "Cwd="); ok {
em.setDir(unescapeVSCode(dir))
}
return
default:
return
}
em.changed()
}
// inputText returns the text of the command input from the screen,
// from its start up to the cursor line, if it is still on the screen.
func (em *Emulator) inputText(c *Command) string {
if c.InputLine < 0 {
return ""
}
st := c.InputLine - em.numScrolled
ed := em.Cursor.Row
if em.Cursor.Col == 0 && ed > st {
ed--
}
if st < 0 || st > ed || ed >= em.Rows {
return ""
}
var sb strings.Builder
for r := st; r <= ed; r++ {
ln := em.screen.lines[r]
rs := ln.Runes(len(ln.Cells))
if r == st {
rs = rs[min(c.InputCol, len(rs)):]
}
if !ln.Wrapped {
rs = []rune(strings.TrimRight(string(rs), " "))
}
sb.WriteString(string(rs))
if !ln.Wrapped && r < ed {
sb.WriteByte('\n')
}
}
return strings.TrimSpace(sb.String())
}
// unescapeVSCode unescapes the \xAB hex escapes in OSC 633 values.
func unescapeVSCode(s string) string {
if !strings.Contains(s, `\`) {
return s
}
var sb strings.Builder
for i := 0; i < len(s); i++ {
if s[i] == '\\' && i+1 < len(s) {
if s[i+1] == '\\' {
sb.WriteByte('\\')
i++
continue
}
if s[i+1] == 'x' && i+3 < len(s) {
if b, err := strconv.ParseUint(s[i+2:i+4], 16, 8); err == nil {
sb.WriteByte(byte(b))
i += 3
continue
}
}
}
sb.WriteByte(s[i])
}
return sb.String()
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package vt
import (
"fmt"
"github.com/charmbracelet/x/ansi"
)
// execute handles a C0 control character.
func (em *Emulator) execute(b byte) {
cur := &em.Cursor
switch b {
case ansi.BEL:
if em.Bell != nil {
em.Bell()
}
case ansi.BS:
if cur.pendingWrap {
cur.pendingWrap = false
} else if cur.Col > 0 {
cur.Col--
}
case ansi.HT:
em.tabForward(1)
case ansi.LF, ansi.VT, ansi.FF:
em.index()
if em.Modes.NewLine {
cur.Col = 0
}
case ansi.CR:
cur.Col = 0
cur.pendingWrap = false
case ansi.SO:
cur.shift = 1
case ansi.SI:
cur.shift = 0
}
}
// tabForward moves the cursor to the n-th next tab stop.
func (em *Emulator) tabForward(n int) {
cur := &em.Cursor
for ; n > 0 && cur.Col < em.Cols-1; n-- {
cur.Col++
for cur.Col < em.Cols-1 && !em.tabStops[cur.Col] {
cur.Col++
}
}
cur.pendingWrap = false
}
// tabBackward moves the cursor to the n-th previous tab stop.
func (em *Emulator) tabBackward(n int) {
cur := &em.Cursor
for ; n > 0 && cur.Col > 0; n-- {
cur.Col--
for cur.Col > 0 && !em.tabStops[cur.Col] {
cur.Col--
}
}
cur.pendingWrap = false
}
// moveTo moves the cursor to the given position, which is relative
// to the scroll region in origin mode.
func (em *Emulator) moveTo(row, col int) {
cur := &em.Cursor
minRow, maxRow := 0, em.Rows-1
if cur.originMode {
row += em.top
minRow, maxRow = em.top, em.bottom
}
cur.Row = max(minRow, min(row, maxRow))
cur.Col = max(0, min(col, em.Cols-1))
cur.pendingWrap = false
}
// moveRel moves the cursor by the given amounts, stopping at the
// scroll region margins if it starts within them.
func (em *Emulator) moveRel(drow, dcol int) {
cur := &em.Cursor
row := cur.Row + drow
minRow, maxRow := 0, em.Rows-1
if cur.Row >= em.top && cur.Row <= em.bottom {
minRow, maxRow = em.top, em.bottom
}
cur.Row = max(minRow, min(row, maxRow))
cur.Col = max(0, min(cur.Col+dcol, em.Cols-1))
cur.pendingWrap = false
}
// handleCSI handles a control sequence.
func (em *Emulator) handleCSI(cmd ansi.Cmd, params ansi.Params) {
cur := &em.Cursor
// param returns parameter i, with 0 and missing values as def.
param := func(i, def int) int {
p, _, _ := params.Param(i, def)
if p == 0 {
return def
}
return p
}
// param0 returns parameter i, with missing values as 0.
param0 := func(i int) int {
p, _, _ := params.Param(i, 0)
return p
}
prefix, inter := cmd.Prefix(), cmd.Intermediate()
switch {
case prefix == '?':
em.handleCSIPrivate(cmd, params)
return
case prefix == '>':
if cmd.Final() == 'c' { // secondary device attributes
em.reply("\x1b[>0;10;1c")
}
return
case prefix != 0:
return
case inter == ' ':
if cmd.Final() == 'q' { // DECSCUSR cursor shape
em.Modes.CursorShape = param0(0)
}
return
case inter == '!':
if cmd.Final() == 'p' { // DECSTR soft reset
em.softReset()
}
return
case inter != 0:
return
}
switch cmd.Final() {
case '@': // ICH
em.insertCells(param(0, 1))
case 'A': // CUU
em.moveRel(-param(0, 1), 0)
case 'B', 'e': // CUD, VPR
em.moveRel(param(0, 1), 0)
case 'C', 'a': // CUF, HPR
em.moveRel(0, param(0, 1))
case 'D': // CUB
em.moveRel(0, -param(0, 1))
case 'E': // CNL
em.moveRel(param(0, 1), 0)
cur.Col = 0
case 'F': // CPL
em.moveRel(-param(0, 1), 0)
cur.Col = 0
case 'G', '`': // CHA, HPA
cur.Col = max(0, min(param(0, 1)-1, em.Cols-1))
cur.pendingWrap = false
case 'H', 'f': // CUP, HVP
em.moveTo(param(0, 1)-1, param(1, 1)-1)
case 'I': // CHT
em.tabForward(param(0, 1))
case 'J': // ED
em.eraseDisplay(param0(0))
case 'K': // EL
em.eraseLine(param0(0))
case 'L': // IL
em.insertLines(param(0, 1))
case 'M': // DL
em.deleteLines(param(0, 1))
case 'P': // DCH
em.deleteCells(param(0, 1))
case 'S': // SU
em.scrollUp(param(0, 1))
case 'T': // SD
if len(params) <= 1 {
em.scrollDown(param(0, 1))
}
case 'X': // ECH
em.eraseCells(param(0, 1))
case 'Z': // CBT
em.tabBackward(param(0, 1))
case 'b': // REP
if em.lastRune != 0 {
for range min(param(0, 1), em.Cols*em.Rows) {
em.print(em.lastRune)
}
}
case 'c': // primary device attributes: VT220 with ANSI color
if param0(0) == 0 {
em.reply("\x1b[?62;22c")
}
case 'd': // VPA
em.moveTo(param(0, 1)-1, cur.Col)
if cur.originMode {
cur.Row = max(em.top, min(param(0, 1)-1+em.top, em.bottom))
}
case 'g': // TBC
switch param0(0) {
case 0:
em.tabStops[cur.Col] = false
case 3:
clear(em.tabStops)
}
case 'h', 'l': // SM, RM
on := cmd.Final() == 'h'
for i := range params {
switch param0(i) {
case 4:
em.Modes.Insert = on
case 20:
em.Modes.NewLine = on
}
}
case 'm': // SGR
em.handleSGR(params)
case 'n': // DSR
switch param0(0) {
case 5:
em.reply("\x1b[0n")
case 6:
row := cur.Row
if cur.originMode {
row -= em.top
}
em.reply(fmt.Sprintf("\x1b[%d;%dR", row+1, cur.Col+1))
}
case 'r': // DECSTBM
top, bottom := param(0, 1)-1, param(1, em.Rows)-1
bottom = min(bottom, em.Rows-1)
if top < bottom {
em.top, em.bottom = top, bottom
em.moveTo(0, 0)
}
case 's': // SCOSC
em.saveCursor()
case 'u': // SCORC
em.restoreCursor()
case 't': // window operations
switch param0(0) {
case 18: // text area size in characters
em.reply(fmt.Sprintf("\x1b[8;%d;%dt", em.Rows, em.Cols))
}
}
}
// handleCSIPrivate handles a DEC private control sequence (CSI ? ...).
func (em *Emulator) handleCSIPrivate(cmd ansi.Cmd, params ansi.Params) {
switch cmd.Final() {
case 'h', 'l':
on := cmd.Final() == 'h'
for i := range params {
p, _, _ := params.Param(i, 0)
em.setPrivateMode(p, on)
}
case 'J': // DECSED
p, _, _ := params.Param(0, 0)
em.eraseDisplay(p)
case 'K': // DECSEL
p, _, _ := params.Param(0, 0)
em.eraseLine(p)
case 'n': // DECXCPR
if p, _, _ := params.Param(0, 0); p == 6 {
em.reply(fmt.Sprintf("\x1b[?%d;%dR", em.Cursor.Row+1, em.Cursor.Col+1))
}
}
}
// setPrivateMode sets the given DEC private mode.
func (em *Emulator) setPrivateMode(mode int, on bool) {
md := &em.Modes
switch mode {
case 1:
md.AppCursorKeys = on
case 3: // DECCOLM: 132 columns, which we do not do, but it clears
em.eraseDisplay(2)
em.moveTo(0, 0)
case 5:
md.ReverseVideo = on
case 6:
em.Cursor.originMode = on
em.moveTo(0, 0)
case 7:
md.AutoWrap = on
case 9:
md.Mouse = mouseMode(on, MouseX10)
case 25:
md.CursorHidden = !on
case 47, 1047:
em.setAltScreen(on, false)
case 1000:
md.Mouse = mouseMode(on, MouseNormal)
case 1002:
md.Mouse = mouseMode(on, MouseButton)
case 1003:
md.Mouse = mouseMode(on, MouseAny)
case 1004:
md.FocusEvents = on
case 1006:
md.MouseSGR = on
case 1007:
md.AltScroll = on
case 1048:
if on {
em.saveCursor()
} else {
em.restoreCursor()
}
case 1049:
em.setAltScreen(on, true)
case 2004:
md.BracketedPaste = on
}
}
// mouseMode returns the mouse mode for setting the given mode on or off.
func mouseMode(on bool, mode MouseModes) MouseModes {
if on {
return mode
}
return MouseNone
}
// setAltScreen switches to or from the alternate screen. If
// saveCursor is set, the cursor is saved before switching to it and
// restored after switching back, and it is cleared (mode 1049).
func (em *Emulator) setAltScreen(on, saveCursor bool) {
if on == em.IsAltScreen() {
return
}
if on {
if saveCursor {
em.saveCursor()
}
em.screen = em.alt
if saveCursor {
em.alt.clear()
}
} else {
if em.screen == em.alt && saveCursor {
em.alt.clear()
}
em.screen = em.primary
if saveCursor {
em.restoreCursor()
}
}
em.Cursor.pendingWrap = false
}
// saveCursor saves the cursor state (DECSC).
func (em *Emulator) saveCursor() {
em.screen.saved = em.Cursor
}
// restoreCursor restores the saved cursor state (DECRC).
func (em *Emulator) restoreCursor() {
em.Cursor = em.screen.saved
em.Cursor.Row = min(em.Cursor.Row, em.Rows-1)
em.Cursor.Col = min(em.Cursor.Col, em.Cols-1)
}
// softReset does a soft terminal reset (DECSTR).
func (em *Emulator) softReset() {
em.Modes.CursorHidden = false
em.Modes.Insert = false
em.Modes.AutoWrap = true
em.Modes.AppCursorKeys = false
em.Modes.AppKeypad = false
em.top, em.bottom = 0, em.Rows-1
em.Cursor.Style = Style{}
em.Cursor.originMode = false
em.Cursor.charsets = [2]charset{}
em.Cursor.shift = 0
em.screen.saved = Cursor{}
}
// handleESC handles an escape sequence.
func (em *Emulator) handleESC(cmd ansi.Cmd) {
cur := &em.Cursor
inter, final := cmd.Intermediate(), cmd.Final()
switch inter {
case '(', ')': // designate G0 or G1 character set
g := 0
if inter == ')' {
g = 1
}
cs := charsetASCII
if final == '0' {
cs = charsetDECGraphics
}
cur.charsets[g] = cs
return
case '#':
if final == '8' { // DECALN: fill the screen with E
for _, ln := range em.screen.lines {
for i := range ln.Cells {
ln.Cells[i] = Cell{Rune: 'E', Width: 1}
}
ln.Wrapped = false
}
}
return
case 0:
default:
return
}
switch final {
case '7': // DECSC
em.saveCursor()
case '8': // DECRC
em.restoreCursor()
case 'D': // IND
em.index()
case 'E': // NEL
em.index()
cur.Col = 0
case 'H': // HTS
em.tabStops[cur.Col] = true
case 'M': // RI
em.reverseIndex()
case 'c': // RIS
em.reset()
em.eraseDisplay(3)
case '=': // DECKPAM
em.Modes.AppKeypad = true
case '>': // DECKPNM
em.Modes.AppKeypad = false
}
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package vt
// Resize changes the size of the terminal. The text of the primary
// screen is rewrapped to the new number of columns, and lines that
// no longer fit above the cursor go to the scrollback. The alternate
// screen is cut or extended, as full-screen programs redraw it.
func (em *Emulator) Resize(cols, rows int) {
cols, rows = max(cols, 1), max(rows, 1)
if cols == em.Cols && rows == em.Rows {
return
}
alt := em.IsAltScreen()
pcur, acur := em.Cursor, em.alt.saved
if alt {
pcur, acur = em.primary.saved, em.Cursor
}
oldCols := em.Cols
em.Cols, em.Rows = cols, rows
// the primary screen
if cols != oldCols {
em.reflow(&pcur)
} else {
em.resizeRows(em.primary, &pcur, true)
}
// the alternate screen
for _, ln := range em.alt.lines {
ln.resize(cols)
}
em.resizeRows(em.alt, &acur, false)
if alt {
em.primary.saved, em.Cursor = pcur, acur
} else {
em.Cursor, em.alt.saved = pcur, acur
}
clampCursor(&em.primary.saved, cols, rows)
clampCursor(&em.Cursor, cols, rows)
em.top, em.bottom = 0, rows-1
em.resetTabStops()
}
// clampCursor keeps the cursor within the given size.
func clampCursor(cur *Cursor, cols, rows int) {
cur.Row = max(0, min(cur.Row, rows-1))
cur.Col = max(0, min(cur.Col, cols-1))
cur.pendingWrap = false
}
// resizeRows changes the number of lines of the given screen to
// em.Rows, which must already have em.Cols cells, keeping the cursor
// line. Lines removed from the top go to the scrollback if scrollback is set.
func (em *Emulator) resizeRows(sc *screen, cur *Cursor, scrollback bool) {
lns := sc.lines
rows := em.Rows
if len(lns) > rows {
// remove blank lines below the cursor first
n := len(lns)
for n > rows && n-1 > cur.Row && lns[n-1].Len() == 0 {
n--
}
lns = lns[:n]
if over := len(lns) - rows; over > 0 {
if over > cur.Row { // keep the cursor line: cut the rest from the bottom
lns = lns[:len(lns)-(over-cur.Row)]
over = cur.Row
}
if scrollback {
em.scrolled = append(em.scrolled, lns[:over]...)
em.numScrolled += over
}
lns = lns[over:]
cur.Row -= over
}
}
for len(lns) < rows {
lns = append(lns, newLine(em.Cols, ColorDefault))
}
sc.lines = lns
}
// reflow rewraps the lines of the primary screen to em.Cols columns,
// keeping the cursor at the same place in the text.
func (em *Emulator) reflow(cur *Cursor) {
lns := em.primary.lines
// logical lines: rows joined at soft wraps
type logical struct {
cells []Cell
cursorOff int // offset of the cursor in the cells, or -1
}
var lls []logical
var ll logical
ll.cursorOff = -1
last := 0 // last row with text, or the cursor
for r, ln := range lns {
if r == cur.Row {
ll.cursorOff = len(ll.cells) + cur.Col
}
ll.cells = append(ll.cells, ln.Cells...)
if ln.Len() > 0 || r == cur.Row {
last = len(lls)
}
if !ln.Wrapped || r == len(lns)-1 {
lls = append(lls, ll)
ll = logical{cursorOff: -1}
}
}
lls = lls[:last+1]
var out []*Line
crow, ccol := 0, 0
cols := em.Cols
for _, ll := range lls {
n := len(ll.cells)
for n > 0 && ll.cells[n-1].IsBlank() {
n--
}
if ll.cursorOff >= 0 {
n = max(n, min(ll.cursorOff, len(ll.cells)))
}
cells := ll.cells[:n]
ln := newLine(cols, ColorDefault)
col := 0
place := func(i int) { // the cursor at cell i of the logical line
if i == ll.cursorOff {
crow, ccol = len(out), col
}
}
for i := range len(cells) {
c := cells[i]
if c.Width == 0 { // the cell after a wide character, added with it
place(i)
continue
}
w := int(c.Width)
if col+w > cols {
ln.Wrapped = true
out = append(out, ln)
ln = newLine(cols, ColorDefault)
col = 0
}
place(i)
ln.Cells[col] = c
if w == 2 && col+1 < cols {
ln.Cells[col+1] = Cell{Style: c.Style}
}
col += w
}
if ll.cursorOff >= len(cells) {
if col >= cols {
crow, ccol = len(out), cols-1
} else {
crow, ccol = len(out), col
}
}
out = append(out, ln)
}
cur.Row, cur.Col = crow, ccol
em.primary.lines = out
em.resizeRows(em.primary, cur, true)
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package vt
import (
"slices"
"github.com/charmbracelet/x/ansi"
"golang.org/x/text/unicode/norm"
)
// screen is a grid of cells: the primary or alternate screen.
type screen struct {
// lines are the rows of the screen.
lines []*Line
// saved is the saved cursor (DECSC).
saved Cursor
}
// newScreen returns a new blank screen of the given size.
func newScreen(cols, rows int) *screen {
sc := &screen{lines: make([]*Line, rows)}
for i := range rows {
sc.lines[i] = newLine(cols, ColorDefault)
}
return sc
}
// clear clears all of the lines.
func (sc *screen) clear() {
for _, ln := range sc.lines {
ln.clear(0, len(ln.Cells), ColorDefault)
ln.Wrapped = false
}
}
// line returns the line at the cursor.
func (em *Emulator) line() *Line {
return em.screen.lines[em.Cursor.Row]
}
// bg returns the current background color, used for erasing (BCE).
func (em *Emulator) bg() Color {
return em.Cursor.Style.Bg
}
// print writes the given character at the cursor.
func (em *Emulator) print(r rune) {
cs := em.Cursor.charsets[em.Cursor.shift]
if cs == charsetDECGraphics && r >= 0x5f && r <= 0x7e {
r = decGraphics[r-0x5f]
}
w := ansi.StringWidth(string(r))
if w == 0 {
em.combine(r)
return
}
w = min(w, 2)
cur := &em.Cursor
if cur.pendingWrap && em.Modes.AutoWrap {
em.line().Wrapped = true
cur.Col = 0
em.index()
}
cur.pendingWrap = false
if w == 2 && cur.Col == em.Cols-1 { // no room for a wide character
if !em.Modes.AutoWrap || em.Cols < 2 {
return
}
em.setCell(cur.Col, blankCell(em.bg()))
em.line().Wrapped = true
cur.Col = 0
em.index()
}
if em.Modes.Insert {
em.insertCells(w)
}
em.setCell(cur.Col, Cell{Rune: r, Width: uint8(w), Style: em.cellStyle()})
if w == 2 {
em.setCell(cur.Col+1, Cell{Width: 0, Style: em.cellStyle()})
}
em.lastRune = r
cur.Col += w
if cur.Col >= em.Cols {
cur.Col = em.Cols - 1
if em.Modes.AutoWrap {
cur.pendingWrap = true
}
}
}
// cellStyle returns the style for a new character.
func (em *Emulator) cellStyle() Style {
st := em.Cursor.Style
st.Link = em.link
return st
}
// setCell sets the cell at the given column of the cursor line,
// clearing any wide character that it overwrites part of.
func (em *Emulator) setCell(col int, c Cell) {
ln := em.line()
if col < 0 || col >= len(ln.Cells) {
return
}
old := ln.Cells[col]
if old.Width == 2 && c.Width != 0 && col+1 < len(ln.Cells) {
ln.Cells[col+1] = blankCell(old.Style.Bg)
}
if old.Width == 0 && c.Width != 0 && col > 0 && ln.Cells[col-1].Width == 2 {
ln.Cells[col-1] = blankCell(ln.Cells[col-1].Style.Bg)
}
ln.Cells[col] = c
}
// combine combines a zero-width character, such as an accent, with
// the previous character, if they compose into a single character.
func (em *Emulator) combine(r rune) {
ln := em.line()
col := em.Cursor.Col - 1
if em.Cursor.pendingWrap {
col = em.Cursor.Col
}
for col > 0 && ln.Cells[col].Width == 0 {
col--
}
if col < 0 || ln.Cells[col].Rune == 0 {
return
}
c := &ln.Cells[col]
rs := []rune(norm.NFC.String(string([]rune{c.Rune, r})))
if len(rs) == 1 {
c.Rune = rs[0]
}
}
// index moves the cursor down one line, scrolling at the bottom
// of the scroll region (IND, LF).
func (em *Emulator) index() {
cur := &em.Cursor
cur.pendingWrap = false
switch {
case cur.Row == em.bottom:
em.scrollUp(1)
case cur.Row < em.Rows-1:
cur.Row++
}
}
// reverseIndex moves the cursor up one line, scrolling at the top
// of the scroll region (RI).
func (em *Emulator) reverseIndex() {
cur := &em.Cursor
cur.pendingWrap = false
switch {
case cur.Row == em.top:
em.scrollDown(1)
case cur.Row > 0:
cur.Row--
}
}
// scrollUp scrolls the lines of the scroll region up by n lines.
// Lines scrolled off the top of the primary screen go to the scrollback.
func (em *Emulator) scrollUp(n int) {
em.scrollUpRegion(em.top, n, true)
}
// scrollUpRegion scrolls the lines from the top row to the bottom of
// the scroll region up by n lines. If scrollback is true, lines scrolled
// off the top of the primary screen go to the scrollback.
func (em *Emulator) scrollUpRegion(top, n int, scrollback bool) {
n = min(n, em.bottom-top+1)
if n <= 0 {
return
}
lns := em.screen.lines
if scrollback && top == 0 && em.screen == em.primary {
for i := range n {
em.scrolled = append(em.scrolled, lns[i].clone())
}
em.numScrolled += n
}
reg := lns[top : em.bottom+1]
removed := slices.Clone(reg[:n])
copy(reg, reg[n:])
for i, ln := range removed { // reuse the line memory
ln.clear(0, len(ln.Cells), em.bg())
ln.Wrapped = false
reg[len(reg)-n+i] = ln
}
}
// scrollDown scrolls the lines of the scroll region down by n lines.
func (em *Emulator) scrollDown(n int) {
em.scrollDownRegion(em.top, n)
}
// scrollDownRegion scrolls the lines from the top row to the bottom
// of the scroll region down by n lines.
func (em *Emulator) scrollDownRegion(top, n int) {
n = min(n, em.bottom-top+1)
if n <= 0 {
return
}
reg := em.screen.lines[top : em.bottom+1]
removed := slices.Clone(reg[len(reg)-n:])
copy(reg[n:], reg)
for i, ln := range removed {
ln.clear(0, len(ln.Cells), em.bg())
ln.Wrapped = false
reg[i] = ln
}
}
// insertLines inserts n blank lines at the cursor, within the scroll region (IL).
func (em *Emulator) insertLines(n int) {
row := em.Cursor.Row
if row < em.top || row > em.bottom {
return
}
em.scrollDownRegion(row, n)
em.Cursor.Col = 0
em.Cursor.pendingWrap = false
}
// deleteLines deletes n lines at the cursor, within the scroll region (DL).
func (em *Emulator) deleteLines(n int) {
row := em.Cursor.Row
if row < em.top || row > em.bottom {
return
}
em.scrollUpRegion(row, n, false)
em.Cursor.Col = 0
em.Cursor.pendingWrap = false
}
// insertCells inserts n blank cells at the cursor, shifting the rest
// of the line right (ICH).
func (em *Emulator) insertCells(n int) {
ln := em.line()
col := em.Cursor.Col
n = min(n, em.Cols-col)
if n <= 0 {
return
}
cs := ln.Cells
copy(cs[col+n:], cs[col:])
ln.clear(col, col+n, em.bg())
if last := &cs[em.Cols-1]; last.Width == 2 {
*last = blankCell(last.Style.Bg)
}
em.Cursor.pendingWrap = false
}
// deleteCells deletes n cells at the cursor, shifting the rest
// of the line left (DCH).
func (em *Emulator) deleteCells(n int) {
ln := em.line()
col := em.Cursor.Col
n = min(n, em.Cols-col)
if n <= 0 {
return
}
cs := ln.Cells
copy(cs[col:], cs[col+n:])
ln.clear(em.Cols-n, em.Cols, em.bg())
em.Cursor.pendingWrap = false
}
// eraseCells erases n cells at the cursor (ECH).
func (em *Emulator) eraseCells(n int) {
col := em.Cursor.Col
em.line().clear(col, min(col+n, em.Cols), em.bg())
em.Cursor.pendingWrap = false
}
// eraseLine erases part of the cursor line (EL):
// 0 to the end, 1 from the start, 2 all.
func (em *Emulator) eraseLine(mode int) {
ln := em.line()
col := em.Cursor.Col
switch mode {
case 0:
ln.clear(col, em.Cols, em.bg())
ln.Wrapped = false
case 1:
ln.clear(0, min(col+1, em.Cols), em.bg())
case 2:
ln.clear(0, em.Cols, em.bg())
ln.Wrapped = false
}
em.Cursor.pendingWrap = false
}
// eraseDisplay erases part of the screen (ED): 0 from the cursor to
// the end, 1 from the start to the cursor, 2 all, 3 the scrollback.
// Erasing all of the primary screen first moves its text into the
// scrollback, so that it is not lost (as in most modern terminals).
func (em *Emulator) eraseDisplay(mode int) {
lns := em.screen.lines
row := em.Cursor.Row
switch mode {
case 0:
em.eraseLine(0)
for _, ln := range lns[row+1:] {
ln.clear(0, em.Cols, em.bg())
ln.Wrapped = false
}
if row > 0 {
lns[row-1].Wrapped = lns[row-1].Wrapped && lns[row].Len() > 0
}
case 1:
for _, ln := range lns[:row] {
ln.clear(0, em.Cols, em.bg())
ln.Wrapped = false
}
em.eraseLine(1)
case 2:
if em.screen == em.primary {
em.saveScreenToScrollback()
}
for _, ln := range lns {
ln.clear(0, em.Cols, em.bg())
ln.Wrapped = false
}
case 3:
em.scrolled = nil
em.scrollbackCleared = true
}
em.Cursor.pendingWrap = false
}
// saveScreenToScrollback adds the lines of the primary screen, up to the
// last one with text, to the scrollback.
func (em *Emulator) saveScreenToScrollback() {
lns := em.primary.lines
n := len(lns)
for n > 0 && lns[n-1].Len() == 0 {
n--
}
for _, ln := range lns[:n] {
em.scrolled = append(em.scrolled, ln.clone())
}
em.numScrolled += n
}
// decGraphics are the DEC special graphics characters for 0x5f-0x7e,
// used for drawing lines and boxes.
var decGraphics = [...]rune{
' ', '◆', '▒', '␉', '␌', '␍', '␊', '°', '±', '', '␋', '┘', '┐', '┌', '└', '┼',
'⎺', '⎻', '─', '⎼', '⎽', '├', '┤', '┴', '┬', '│', '≤', '≥', 'π', '≠', '£', '·',
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package vt
import "github.com/charmbracelet/x/ansi"
// handleSGR handles the Select Graphic Rendition sequence,
// which sets the style of the following text.
func (em *Emulator) handleSGR(params ansi.Params) {
st := &em.Cursor.Style
if len(params) == 0 {
st.Fg, st.Bg, st.Attrs = ColorDefault, ColorDefault, 0
return
}
for i := 0; i < len(params); i++ {
p, more, _ := params.Param(i, 0)
switch {
case p == 0:
st.Fg, st.Bg, st.Attrs = ColorDefault, ColorDefault, 0
case p == 1:
st.Attrs |= Bold
case p == 2:
st.Attrs |= Faint
case p == 3:
st.Attrs |= Italic
case p == 4:
st.Attrs &^= Underline | DoubleUnderline
if more { // 4:n underline style
i++
if u, _, _ := params.Param(i, 1); u == 0 {
break
} else if u == 2 {
st.Attrs |= DoubleUnderline
break
}
}
st.Attrs |= Underline
case p == 5 || p == 6:
st.Attrs |= Blink
case p == 7:
st.Attrs |= Reverse
case p == 8:
st.Attrs |= Invisible
case p == 9:
st.Attrs |= Strikethrough
case p == 21:
st.Attrs |= DoubleUnderline
case p == 22:
st.Attrs &^= Bold | Faint
case p == 23:
st.Attrs &^= Italic
case p == 24:
st.Attrs &^= Underline | DoubleUnderline
case p == 25:
st.Attrs &^= Blink
case p == 27:
st.Attrs &^= Reverse
case p == 28:
st.Attrs &^= Invisible
case p == 29:
st.Attrs &^= Strikethrough
case p >= 30 && p <= 37:
st.Fg = IndexedColor(uint8(p - 30))
case p == 38:
c, n, ok := extendedColor(params, i)
if ok {
st.Fg = c
}
i += n
case p == 39:
st.Fg = ColorDefault
case p >= 40 && p <= 47:
st.Bg = IndexedColor(uint8(p - 40))
case p == 48:
c, n, ok := extendedColor(params, i)
if ok {
st.Bg = c
}
i += n
case p == 49:
st.Bg = ColorDefault
case p == 53:
st.Attrs |= Overline
case p == 55:
st.Attrs &^= Overline
case p == 58: // underline color: not supported, skip its parameters
_, n, _ := extendedColor(params, i)
i += n
case p >= 90 && p <= 97:
st.Fg = IndexedColor(uint8(p - 90 + 8))
case p >= 100 && p <= 107:
st.Bg = IndexedColor(uint8(p - 100 + 8))
}
}
}
// extendedColor parses the extended color starting at parameter i
// (38, 48, or 58), in either the 38;5;n / 38;2;r;g;b form or the
// 38:5:n / 38:2::r:g:b form. It returns the color, the number of
// following parameters that it used, and whether it is valid.
func extendedColor(params ansi.Params, i int) (Color, int, bool) {
if i+1 >= len(params) {
return ColorDefault, 0, false
}
colon := params[i].HasMore()
kind := params[i+1].Param(0)
var vals []int
if colon {
for j := i + 2; j < len(params) && params[j-1].HasMore(); j++ {
vals = append(vals, max(0, min(params[j].Param(0), 255)))
}
} else {
nv := 3
if kind == 5 {
nv = 1
}
for j := i + 2; j < len(params) && len(vals) < nv; j++ {
vals = append(vals, max(0, min(params[j].Param(0), 255)))
}
}
n := 1 + len(vals)
switch {
case kind == 5 && len(vals) >= 1:
return IndexedColor(uint8(vals[0])), n, true
case kind == 2 && len(vals) >= 4 && colon: // with the color space
return RGBColor(uint8(vals[1]), uint8(vals[2]), uint8(vals[3])), n, true
case kind == 2 && len(vals) >= 3:
return RGBColor(uint8(vals[0]), uint8(vals[1]), uint8(vals[2])), n, true
}
return ColorDefault, n, false
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// note: adapted from https://github.com/tdewolff/canvas,
// Copyright (c) 2015 Taco de Wolff, under an MIT License.
package tex
type charMaps int32 //enums:enum
const (
CMR charMaps = iota
CMMI
CMSY
CMEX
CMTT
AMSAM
AMSBM
)
func (cm charMaps) Table() map[uint32]rune {
switch cm {
case CMR:
return cmapCMR
case CMMI:
return cmapCMMI
case CMSY:
return cmapCMSY
case CMEX:
return cmapCMEX
case CMTT:
return cmapCMTT
case AMSAM:
return cmapAMSAM
case AMSBM:
return cmapAMSBM
}
return nil
}
var cmapCMR = map[uint32]rune{
0x00: '\u0393',
0x01: '\u0394',
0x02: '\u0398',
0x03: '\u039B',
0x04: '\u039E',
0x05: '\u03A0',
0x06: '\u03A3',
0x07: '\u03A5',
0x08: '\u03A6',
0x09: '\u03A8',
0x0A: '\u03A9',
0x0B: '\uFB00',
0x0C: '\uFB01',
0x0D: '\uFB02',
0x0E: '\uFB03',
0x0F: '\uFB04',
0x10: '\u0131',
0x11: '\u0237',
0x12: '\u0300',
0x13: '\u0301',
0x14: '\u030C',
0x15: '\u0306',
0x16: '\u0305',
0x17: '\u030A',
0x18: '\u0327',
0x19: '\u00DF',
0x1A: '\u00E6',
0x1B: '\u0153',
0x1C: '\u00F8',
0x1D: '\u00C6',
0x1E: '\u0152',
0x1F: '\u00D8',
0x20: '\u0337',
0x21: '\u0021',
0x22: '\u201D',
0x23: '\u0023',
0x24: '\u0024',
0x25: '\u0025',
0x26: '\u0026',
0x27: '\u0027',
0x28: '\u0028',
0x29: '\u0029',
0x2A: '\u002A',
0x2B: '\u002B',
0x2C: '\u002C',
0x2D: '\u002D',
0x2E: '\u002E',
0x2F: '\u002F',
0x30: '\u0030',
0x31: '\u0031',
0x32: '\u0032',
0x33: '\u0033',
0x34: '\u0034',
0x35: '\u0035',
0x36: '\u0036',
0x37: '\u0037',
0x38: '\u0038',
0x39: '\u0039',
0x3A: '\u003A',
0x3B: '\u003B',
0x3C: '\u00A1',
0x3D: '\u003D',
0x3E: '\u00BF',
0x3F: '\u003F',
0x40: '\u0040',
0x41: '\u0041',
0x42: '\u0042',
0x43: '\u0043',
0x44: '\u0044',
0x45: '\u0045',
0x46: '\u0046',
0x47: '\u0047',
0x48: '\u0048',
0x49: '\u0049',
0x4A: '\u004A',
0x4B: '\u004B',
0x4C: '\u004C',
0x4D: '\u004D',
0x4E: '\u004E',
0x4F: '\u004F',
0x50: '\u0050',
0x51: '\u0051',
0x52: '\u0052',
0x53: '\u0053',
0x54: '\u0054',
0x55: '\u0055',
0x56: '\u0056',
0x57: '\u0057',
0x58: '\u0058',
0x59: '\u0059',
0x5A: '\u005A',
0x5B: '\u005B',
0x5C: '\u201C',
0x5D: '\u005D',
0x5E: '\u0302',
0x5F: '\u02D9',
0x60: '\u2018',
0x61: '\u0061',
0x62: '\u0062',
0x63: '\u0063',
0x64: '\u0064',
0x65: '\u0065',
0x66: '\u0066',
0x67: '\u0067',
0x68: '\u0068',
0x69: '\u0069',
0x6A: '\u006A',
0x6B: '\u006B',
0x6C: '\u006C',
0x6D: '\u006D',
0x6E: '\u006E',
0x6F: '\u006F',
0x70: '\u0070',
0x71: '\u0071',
0x72: '\u0072',
0x73: '\u0073',
0x74: '\u0074',
0x75: '\u0075',
0x76: '\u0076',
0x77: '\u0077',
0x78: '\u0078',
0x79: '\u0079',
0x7A: '\u007A',
0x7B: '\u2013',
0x7C: '\u2014',
0x7D: '\u030B',
0x7E: '\u0303',
0x7F: '\u0308',
}
var cmapCMMI = map[uint32]rune{
0x00: '\u0393',
0x01: '\u0394',
0x02: '\u0398',
0x03: '\u039B',
0x04: '\u039E',
0x05: '\u03A0',
0x06: '\u03A3',
0x07: '\u03A5',
0x08: '\u03A6',
0x09: '\u03A8',
0x0A: '\u03A9',
0x0B: '\u03B1',
0x0C: '\u03B2',
0x0D: '\u03B3',
0x0E: '\u03B4',
0x0F: '\u03F5',
0x10: '\u03B6',
0x11: '\u03B7',
0x12: '\u03B8',
0x13: '\u03B9',
0x14: '\u03BA',
0x15: '\u03BB',
0x16: '\u03BC',
0x17: '\u03BD',
0x18: '\u03BE',
0x19: '\u03C0',
0x1A: '\u03C1',
0x1B: '\u03C3',
0x1C: '\u03C4',
0x1D: '\u03C5',
0x1E: '\u03D5',
0x1F: '\u03C7',
0x20: '\u03C8',
0x21: '\u03C9',
0x22: '\u03B5',
0x23: '\u03D1',
0x24: '\u03D6',
0x25: '\u03F1',
0x26: '\u03C2',
0x27: '\u03C6',
0x28: '\u21BC',
0x29: '\u21BD',
0x2A: '\u21C0',
0x2B: '\u21C1',
0x2C: '\u21AA',
0x2D: '\u21A9',
0x2E: '\u22B3',
0x2F: '\u22B2',
0x30: '\u0030',
0x31: '\u0031',
0x32: '\u0032',
0x33: '\u0033',
0x34: '\u0034',
0x35: '\u0035',
0x36: '\u0036',
0x37: '\u0037',
0x38: '\u0038',
0x39: '\u0039',
0x3A: '\u002E',
0x3B: '\u002C',
0x3C: '\u003C',
0x3D: '\u002F',
0x3E: '\u003E',
0x3F: '\u22C6',
0x40: '\u2202',
0x41: '\u0041',
0x42: '\u0042',
0x43: '\u0043',
0x44: '\u0044',
0x45: '\u0045',
0x46: '\u0046',
0x47: '\u0047',
0x48: '\u0048',
0x49: '\u0049',
0x4A: '\u004A',
0x4B: '\u004B',
0x4C: '\u004C',
0x4D: '\u004D',
0x4E: '\u004E',
0x4F: '\u004F',
0x50: '\u0050',
0x51: '\u0051',
0x52: '\u0052',
0x53: '\u0053',
0x54: '\u0054',
0x55: '\u0055',
0x56: '\u0056',
0x57: '\u0057',
0x58: '\u0058',
0x59: '\u0059',
0x5A: '\u005A',
0x5B: '\u266D',
0x5C: '\u266E',
0x5D: '\u266F',
0x5E: '\u2323',
0x5F: '\u2322',
0x60: '\u2113',
0x61: '\u0061',
0x62: '\u0062',
0x63: '\u0063',
0x64: '\u0064',
0x65: '\u0065',
0x66: '\u0066',
0x67: '\u0067',
0x68: '\u0068',
0x69: '\u0069',
0x6A: '\u006A',
0x6B: '\u006B',
0x6C: '\u006C',
0x6D: '\u006D',
0x6E: '\u006E',
0x6F: '\u006F',
0x70: '\u0070',
0x71: '\u0071',
0x72: '\u0072',
0x73: '\u0073',
0x74: '\u0074',
0x75: '\u0075',
0x76: '\u0076',
0x77: '\u0077',
0x78: '\u0078',
0x79: '\u0079',
0x7A: '\u007A',
0x7B: '\u0131',
0x7C: '\u0237',
0x7D: '\u2118',
0x7E: '\u20D7',
0x7F: '\u0311',
}
var cmapCMSY = map[uint32]rune{
0x00: '\u2212',
0x01: '\u00B7',
0x02: '\u00D7',
0x03: '\u2217',
0x04: '\u00F7',
0x05: '\u22C4',
0x06: '\u00B1',
0x07: '\u2213',
0x08: '\u2295',
0x09: '\u2296',
0x0A: '\u2297',
0x0B: '\u2298',
0x0C: '\u2299',
0x0D: '\u25CB',
0x0E: '\u2218',
0x0F: '\u2219',
0x10: '\u224D',
0x11: '\u2261',
0x12: '\u2286',
0x13: '\u2287',
0x14: '\u2264',
0x15: '\u2265',
0x16: '\u227C',
0x17: '\u227D',
0x18: '\u223C',
0x19: '\u2248',
0x1A: '\u2282',
0x1B: '\u2283',
0x1C: '\u226A',
0x1D: '\u226B',
0x1E: '\u227A',
0x1F: '\u227B',
0x20: '\u2190',
0x21: '\u2192',
0x22: '\u2191',
0x23: '\u2193',
0x24: '\u2194',
0x25: '\u2197',
0x26: '\u2198',
0x27: '\u2243',
0x28: '\u21D0',
0x29: '\u21D2',
0x2A: '\u21D1',
0x2B: '\u21D3',
0x2C: '\u21D4',
0x2D: '\u2196',
0x2E: '\u2199',
0x2F: '\u221D',
0x30: '\u2032',
0x31: '\u221E',
0x32: '\u2208',
0x33: '\u220B',
0x34: '\u25B3',
0x35: '\u25BD',
0x36: '\u0338',
0x37: '\u21A6',
0x38: '\u2200',
0x39: '\u2203',
0x3A: '\u00AC',
0x3B: '\u2205',
0x3C: '\u211C',
0x3D: '\u2111',
0x3E: '\u22A4',
0x3F: '\u22A5',
0x40: '\u2135',
0x41: '\U0001D49C',
0x42: '\u212C',
0x43: '\U0001D49E',
0x44: '\U0001D49F',
0x45: '\u2130',
0x46: '\u2131',
0x47: '\U0001D4A2',
0x48: '\u210B',
0x49: '\u2110',
0x4A: '\U0001D4A5',
0x4B: '\U0001D4A6',
0x4C: '\u2112',
0x4D: '\u2133',
0x4E: '\U0001D4A9',
0x4F: '\U0001D4AA',
0x50: '\U0001D4AB',
0x51: '\U0001D4AC',
0x52: '\u211B',
0x53: '\U0001D4AE',
0x54: '\U0001D4AF',
0x55: '\U0001D4B0',
0x56: '\U0001D4B1',
0x57: '\U0001D4B2',
0x58: '\U0001D4B3',
0x59: '\U0001D4B4',
0x5A: '\U0001D4B5',
0x5B: '\u222A',
0x5C: '\u2229',
0x5D: '\u228E',
0x5E: '\u2227',
0x5F: '\u2228',
0x60: '\u22A2',
0x61: '\u22A3',
0x62: '\u230A',
0x63: '\u230B',
0x64: '\u2308',
0x65: '\u2309',
0x66: '\u007B',
0x67: '\u007D',
0x68: '\u2329',
0x69: '\u232A',
0x6A: '\u2223',
0x6B: '\u2225',
0x6C: '\u2195',
0x6D: '\u21D5',
0x6E: '\u2216',
0x6F: '\u2240',
0x70: '\u221A',
0x71: '\u2210',
0x72: '\u2207',
0x73: '\u222B',
0x74: '\u2294',
0x75: '\u2293',
0x76: '\u2291',
0x77: '\u2292',
0x78: '\u00A7',
0x79: '\u2020',
0x7A: '\u2021',
0x7B: '\u00B6',
0x7C: '\u2663',
0x7D: '\u2662',
0x7E: '\u2661',
0x7F: '\u2660',
}
// See Figure 6, Appendix F, The TeXbook, D. E. Knuth, 1984, 1986, 1991
var cmapCMEX = map[uint32]rune{
0x00: '\u0028', // (
0x01: '\u0029', // )
0x02: '\u005B', // [
0x03: '\u005D', // ]
0x04: '\u230A', // ⌊
0x05: '\u230B', // ⌋
0x06: '\u2308', // ⌈
0x07: '\u2309', // ⌉
0x08: '\u007B', // {
0x09: '\u007D', // }
0x0A: '\u2329', // 〈
0x0B: '\u232A', // 〉
0x0C: '\u2223', // ∣
0x0D: '\u2225', // ∥
0x0E: '\u2215', // ∕
0x0F: '\u2216', // \
0x10: '\u0028', // ( mag3
0x11: '\u0029', // ) mag3
0x12: '\u0028', // ( mag4
0x13: '\u0029', // ) mag4
0x14: '\u005B', // [ mag4
0x15: '\u005D', // ] mag4
0x16: '\u230A', // ⌊ mag4
0x17: '\u230B', // ⌋ mag4
0x18: '\u2308', // ⌈ mag4
0x19: '\u2309', // ⌉ mag4
0x1A: '\u007B', // { mag4
0x1B: '\u007D', // } mag4
0x1C: '\u2329', // 〈 mag4
0x1D: '\u232A', // 〉 mag4
0x1E: '\u2215', // ∕ mag4
0x1F: '\u2216', // \ mag4
0x20: '\u0028', // ( mag5
0x21: '\u0029', // ) mag5
0x22: '\u005B', // [ mag5
0x23: '\u005D', // ] mag5
0x24: '\u230A', // ⌊ mag5
0x25: '\u230B', // ⌋ mag5
0x26: '\u2308', // ⌈ mag5
0x27: '\u2309', // ⌉ mag5
0x28: '\u007B', // { mag5
0x29: '\u007D', // } mag5
0x2A: '\u2329', // 〈 mag5
0x2B: '\u232A', // 〉 mag5
0x2C: '\u2215', // ∕ mag5
0x2D: '\u2216', // \ mag5
0x2E: '\u2215', // ∕ mag3
0x2F: '\u2216', // \ mag3
0x30: '\u239B', // ⎛ mag2
0x31: '\u239E', // ⎞ mag2
0x32: '\u23A1', // ⎡ mag2 note: thicker series here
0x33: '\u23A4', // ⎤ "
0x34: '\u23A3', // ⎣ "
0x35: '\u23A6', // ⎦ "
0x36: '\u23A2', // ⎢ "
0x37: '\u23A5', // ⎥ "
0x38: '\u23A7', // ⎧ braces mag2
0x39: '\u23AB', // ⎫
0x3A: '\u23A9', // ⎩
0x3B: '\u23AD', // ⎭
0x3C: '\u23A8', // ⎨
0x3D: '\u23AC', // ⎬
0x3E: '\u23AA', // ⎪
0x3F: '\u2223', // ∣ ?? unclear
0x40: '\u239D', // ⎝ mag2
0x41: '\u23A0', // ⎠ mag2
0x42: '\u239C', // ⎜ mag2
0x43: '\u239F', // ⎟ mag2
0x44: '\u2329', // 〈 mag2
0x45: '\u232A', // 〉 mag2
0x46: '\u2A06', // ⨆
0x47: '\u2A06', // ⨆ mag2
0x48: '\u222E', // ∮
0x49: '\u222E', // ∮ mag2
0x4A: '\u2A00', // ⨀
0x4B: '\u2A00', // ⨀ mag2
0x4C: '\u2A01', // ⨁
0x4D: '\u2A01', // ⨁ mag2
0x4E: '\u2A02', // ⨂
0x4F: '\u2A02', // ⨂ mag2
0x50: '\u2211', // ∑
0x51: '\u220F', // ∏
0x52: '\u222B', // ∫
0x53: '\u22C3', // ⋃
0x54: '\u22C2', // ⋂
0x55: '\u2A05', // ⨄
0x56: '\u22C0', // ⋀
0x57: '\u22C1', // ⋁
0x58: '\u2211', // ∑ mag2
0x59: '\u220F', // ∏ mag2
0x5A: '\u222B', // ∫ mag2
0x5B: '\u22C3', // ⋃ mag2
0x5C: '\u22C2', // ⋂ mag2
0x5D: '\u2A04', // ⨄ mag2
0x5E: '\u22C0', // ⋀ mag2
0x5F: '\u22C1', // ⋁ mag2
0x60: '\u2210', // ∐
0x61: '\u2210', // ∐ mag2
0x62: '\u0302', // ̂
0x63: '\u0302', // ̂ mag2
0x64: '\u0302', // ̂ mag3?
0x65: '\u0303', // ˜
0x66: '\u0303', // ˜ mag2
0x67: '\u0303', // ˜ mag3?
0x68: '\u005B', // [ mag3
0x69: '\u005D', // ] mag3
0x6A: '\u230A', // ⌊ mag2
0x6B: '\u230B', // ⌋ mag2
0x6C: '\u2308', // ⌈ mag2
0x6D: '\u2309', // ⌉ mag2
0x6E: '\u007B', // { mag2
0x6F: '\u007D', // } mag2
0x70: '\u221A', // √
0x71: '\u221A', // √ mag3
0x72: '\u221A', // √ mag4
0x73: '\u221A', // √ mag5
0x74: '\u23B7', // ⎷ mag1
0x75: '\u23D0', // ⏐ mag1
0x76: '\u250C', // ┌ mag1
0x77: '\u2225', // ∥
0x78: '\u2191', // ↑
0x79: '\u2193', // ↓
0x7A: '\u252C', // '\u0331', // '\u23DC', // right bottom middle
0x7B: '\u2524', // '\u2581', // '\u23DC', // left bottom middle
0x7C: '\u250C', // '\u23DD', // left bottom brack
0x7D: '\u2524', // \u23DD', // right bottom brack
0x7E: '\u21D1', // ⇑
0x7F: '\u21D3', // ⇓
}
var cmapCMTT = map[uint32]rune{
0x00: '\u0393',
0x01: '\u0394',
0x02: '\u0398',
0x03: '\u039B',
0x04: '\u039E',
0x05: '\u03A0',
0x06: '\u03A3',
0x07: '\u03A5',
0x08: '\u03A6',
0x09: '\u03A8',
0x0A: '\u03A9',
0x0B: '\u2191',
0x0C: '\u2193',
0x0D: '\u0027',
0x0E: '\u00A1',
0x0F: '\u00BF',
0x10: '\u0131',
0x11: '\u0237',
0x12: '\u0300',
0x13: '\u0301',
0x14: '\u030C',
0x15: '\u0306',
0x16: '\u0305',
0x17: '\u030A',
0x18: '\u0327',
0x19: '\u00DF',
0x1A: '\u00E6',
0x1B: '\u0153',
0x1C: '\u00F8',
0x1D: '\u00C6',
0x1E: '\u0152',
0x1F: '\u00D8',
0x20: '\u0337',
0x21: '\u0021',
0x22: '\u201D',
0x23: '\u0023',
0x24: '\u0024',
0x25: '\u0025',
0x26: '\u0026',
0x27: '\u0027',
0x28: '\u0028',
0x29: '\u0029',
0x2A: '\u002A',
0x2B: '\u002B',
0x2C: '\u002C',
0x2D: '\u002D',
0x2E: '\u002E',
0x2F: '\u002F',
0x30: '\u0030',
0x31: '\u0031',
0x32: '\u0032',
0x33: '\u0033',
0x34: '\u0034',
0x35: '\u0035',
0x36: '\u0036',
0x37: '\u0037',
0x38: '\u0038',
0x39: '\u0039',
0x3A: '\u003A',
0x3B: '\u003B',
0x3C: '\u003C',
0x3D: '\u003D',
0x3E: '\u003E',
0x3F: '\u003F',
0x40: '\u0040',
0x41: '\u0041',
0x42: '\u0042',
0x43: '\u0043',
0x44: '\u0044',
0x45: '\u0045',
0x46: '\u0046',
0x47: '\u0047',
0x48: '\u0048',
0x49: '\u0049',
0x4A: '\u004A',
0x4B: '\u004B',
0x4C: '\u004C',
0x4D: '\u004D',
0x4E: '\u004E',
0x4F: '\u004F',
0x50: '\u0050',
0x51: '\u0051',
0x52: '\u0052',
0x53: '\u0053',
0x54: '\u0054',
0x55: '\u0055',
0x56: '\u0056',
0x57: '\u0057',
0x58: '\u0058',
0x59: '\u0059',
0x5A: '\u005A',
0x5B: '\u005B',
0x5C: '\u005C',
0x5D: '\u005D',
0x5E: '\u0302',
0x5F: '\u005F',
0x60: '\u2018',
0x61: '\u0061',
0x62: '\u0062',
0x63: '\u0063',
0x64: '\u0064',
0x65: '\u0065',
0x66: '\u0066',
0x67: '\u0067',
0x68: '\u0068',
0x69: '\u0069',
0x6A: '\u006A',
0x6B: '\u006B',
0x6C: '\u006C',
0x6D: '\u006D',
0x6E: '\u006E',
0x6F: '\u006F',
0x70: '\u0070',
0x71: '\u0071',
0x72: '\u0072',
0x73: '\u0073',
0x74: '\u0074',
0x75: '\u0075',
0x76: '\u0076',
0x77: '\u0077',
0x78: '\u0078',
0x79: '\u0079',
0x7A: '\u007A',
0x7B: '\u007B',
0x7C: '\u007C',
0x7D: '\u007D',
0x7E: '\u0303',
0x7F: '\u0308',
}
// AMS A math symbols (font 5)
var cmapAMSAM = map[uint32]rune{
0x00: '\u22A1', // \boxdot
0x01: '\u229E', // \boxplus
0x02: '\u22A0', // \boxtimes
0x03: '\u25A1', // \Box
0x04: '\u2588', // \blacksquare
0x05: '\u25AA', // \centerdot
0x06: '\u25CA', // \Diamond
0x07: '\u2666', // \blacklozenge
0x08: '\u21BB', // \circlearrowright
0x09: '\u21BA', // \circlearrowleft
0x0A: '\u21CC', // \rightleftharpoons
0x0B: '\u21CB', // \leftrightharpoons
0x0C: '\u229F', // \boxminus
0x0D: '\u22A9', // \Vdash
0x0E: '\u22AA', // \Vvdash
0x0F: '\u22A8', // \vDash
0x10: '\u21A0', // \twoheadrightarrow
0x11: '\u219E', // \twoheadleftarrow
0x12: '\u21C7', // \leftleftarrows
0x13: '\u21C9', // \rightrightarrows
0x14: '\u21C8', // \upuparrows
0x15: '\u21CA', // \downdownarrows
0x16: '\u21BE', // \upharpoonright
0x17: '\u21C2', // \downharpoonright
0x18: '\u21BF', // \upharpoonleft
0x19: '\u21C3', // \downharpoonleft
0x1A: '\u21A3', // \rightarrowtail
0x1B: '\u21A2', // \leftarrowtail
0x1C: '\u21C6', // \leftrightarrows
0x1D: '\u21C4', // \rightleftarrows
0x1E: '\u21B0', // \Lsh
0x1F: '\u21B1', // \Rsh
0x20: '\u21DD', // \leadsto
0x21: '\u21AD', // \leftrightsquigarrow
0x22: '\u21AB', // \looparrowleft
0x23: '\u21AC', // \looparrowright
0x24: '\u2257', // \circeq
0x25: '\u227F', // \succsim
0x26: '\u2273', // \gtrsim
0x27: '\u2A86', // \gtrapprox
0x28: '\u22B8', // \multimap
0x29: '\u2234', // \therefore
0x2A: '\u2235', // \because
0x2B: '\u2251', // \doteqdot
0x2C: '\u225C', // \triangleq
0x2D: '\u227E', // \precsim
0x2E: '\u2272', // \lesssim
0x2F: '\u2A85', // \lessapprox
0x30: '\u2A95', // \eqslantless
0x31: '\u2A96', // \eqslantgtr
0x32: '\u22DE', // \curlyeqprec
0x33: '\u22DF', // \curlyeqsucc
0x34: '\u227C', // \preccurlyeq
0x35: '\u2266', // \leqq
0x36: '\u2A7D', // \leqslant
0x37: '\u2276', // \lessgtr
0x38: '\u2035', // \backprime
// 0x39 is a - sign apparently?
0x3A: '\u2253', // \risingdotseq
0x3B: '\u2252', // \fallingdotseq
0x3C: '\u227D', // \succcurlyeq
0x3D: '\u2267', // \geqq
0x3E: '\u2A7E', // \geqslant
0x3F: '\u2277', // \gtrless
0x40: '\u228F', // \sqsubset
0x41: '\u2290', // \sqsupset
0x42: '\u22B3', // \rhd
0x43: '\u22B2', // \lhd
0x44: '\u22B5', // \unrhd
0x45: '\u22B4', // \unlhd
0x46: '\u22C6', // \bigstar
0x47: '\u226C', // \between
0x48: '\u25BC', // \blacktriangledown
0x49: '\u25B6', // \blacktriangleright
0x4A: '\u25C0', // \blacktriangleleft
0x4B: '\u27A1', // thicker arrow right
0x4C: '\u2B05', // thicker arrow left
0x4D: '\u25B3', // \vartriangle note: not var
0x4E: '\u25B2', // \blacktriangle
0x4F: '\u25BD', // \triangledown
0x50: '\u2256', // \eqcirc
0x51: '\u22DA', // \lesseqgtr
0x52: '\u22DB', // \gtreqless
0x53: '\u2A8B', // \lesseqqgtr
0x54: '\u2A8C', // \gtreqqless
0x55: '\u00A5', // \yen
0x56: '\u21DB', // \Rrightarrow
0x57: '\u21DA', // \Lleftarrow
0x58: '\u2713', // \checkmark
0x59: '\u22BB', // \veebar
0x5A: '\u22BC', // \barwedge
0x5B: '\u22BC', // \doublebarwedge todo: not found! render as \bar \barwedge!
0x5C: '\u2220', // \angle
0x5D: '\u2221', // \measuredangle
0x5E: '\u2222', // \sphericalangle
0x5F: '\u221D', // \varpropto note: not var -- just regular
0x60: '\u2323', // \smallsmile
0x61: '\u2322', // \smallfrown
0x62: '\u22D0', // \Subset
0x63: '\u22D1', // \Supset
0x64: '\u22D3', // \Cup
0x65: '\u22D2', // \Cap
0x66: '\u22CF', // \curlywedge
0x67: '\u22CE', // \curlyvee
0x68: '\u22CB', // \leftthreetimes
0x69: '\u22CC', // \rightthreetimes
0x6A: '\u2286', // \subseteqq note: subseteq
0x6B: '\u2287', // \supseteqq note: supseteq
0x6C: '\u224F', // \bumpeq
0x6D: '\u224E', // \Bumpeq
0x6E: '\u22D8', // \lll
0x6F: '\u22D9', // \ggg
0x70: '\u231C', // \ulcorner
0x71: '\u231D', // \urcorner
0x72: '\u00AE', // \circledR
0x73: '\u2120', // \circledS todo: draw as an S inside circle -- this is SM
0x74: '\u22D2', // \pitchfork todo: not right -- using \Cap
0x75: '\u2214', // \dotplus
0x76: '\u223D', // \backsim
0x77: '\u224C', // \backsimeq note: not correct but semantically ok
0x78: '\u231E', // \llcorner
0x79: '\u231F', // \lrcorner
0x7A: '\u2720', // \maltese
0x7B: '\u2201', // \complement
0x7C: '\u22A4', // \intercal note: not as bold as should be
0x7D: '\u229A', // \circledcirc
0x7E: '\u229B', // \circledast
0x7F: '\u229D', // \circleddash
}
// AMS B math symbols (font 6)
var cmapAMSBM = map[uint32]rune{
// 0x00: \lvertneqq
// 0x01: \gvertneqq
0x02: '\u2270', // \nleq
0x03: '\u2271', // \ngeq
0x04: '\u226E', // \nless
0x05: '\u226F', // \ngtr
0x06: '\u2280', // \nprec
0x07: '\u2281', // \nsucc
0x08: '\u2268', // \lneqq
0x09: '\u2269', // \gneqq
// 0x0A: \nleqslant
// 0x0B: \ngeqslant
0x0C: '\u2A87', // \lneq
0x0D: '\u2A88', // \gneq
0x0E: '\u22E0', // \npreceq note: actually npreccurlyeq
0x0F: '\u22E1', // \nsucceq note: actually nsucccurlyeq
0x10: '\u22E8', // \precnsim
0x11: '\u22E9', // \succnsim
0x12: '\u22E6', // \lnsim
0x13: '\u22E7', // \gnsim
0x14: '\u2268', // \nleqq
0x15: '\u2269', // \ngeqq
// 0x16: \precneq
// 0x17: \succneq
0x18: '\u22E8', // \precnapprox note: actually precnsim
0x19: '\u22E9', // \succnapprox note: actually succnsim
0x1A: '\u2A89', // \lnapprox
0x1B: '\u2A8A', // \gnapprox
0x1C: '\u2241', // \nsim
0x1D: '\u2247', // \ncong
0x1E: '\u2215', // \diagup
0x1F: '\u2216', // \diagdown
0x20: '\u228A', // \varsubsetneq \subsetneq -- no var
0x21: '\u228B', // \varsupsetneq \supsetneq -- no var
0x22: '\u2288', // \nsubseteqq
0x23: '\u2289', // \nsupseteqq note: actually nsupseteq
0x24: '\u228A', // \subsetneqq note: actually subsetneq
0x25: '\u228B', // \supsetneqq note: actually supsetneq
0x26: '\u228A', // \varsubsetneqq note: actually subsetneq -- no var
0x27: '\u228B', // \varsupsetneqq note: actually supsetneq -- no var
0x28: '\u228A', // \subsetneq
0x29: '\u228B', // \supsetneq
0x2A: '\u2288', // \nsubseteq
0x2B: '\u2289', // \nsupseteq
0x2C: '\u2226', // \nparallel
0x2D: '\u2224', // \nmid
0x2E: '\u2224', // \nshortmid // note: no short!
0x2F: '\u2226', // \nshortparallel // note: no short!
0x30: '\u22AC', // \nvdash
0x31: '\u22AE', // ?
0x32: '\u22AD', // \nvDash
0x33: '\u22AF', // \nVDash
0x34: '\u22ED', // \ntrianglerighteq
0x35: '\u22EC', // \ntrianglelefteq
0x36: '\u22EA', // \ntriangleleft
0x37: '\u22EB', // \ntriangleright
0x38: '\u219A', // \nleftarrow
0x39: '\u219B', // \nrightarrow
0x3A: '\u21CD', // \nLeftarrow
0x3B: '\u21CF', // \nRightarrow
0x3C: '\u21CE', // \nLeftrightarrow
0x3D: '\u21AE', // \nleftrightarrow
0x3E: '\u203B', // \divideontimes
0x3F: '\u2300', // \varnothing
0x40: '\u2204', // \nexists
// 0x41-5A is double-lined letters A-Z
// 0x5B-0x5F are big hat chars
0x60: '\u22A7', // \Finv note: not correct -- looks kinda close
0x61: '\u0122', // \Game note: not correct -- using cyrillic G
// 0x62-65 are blank!
0x66: '\u2127', // \mho
0x67: '\u2202', // \eth note: using partial -- needs a bar
0x68: '\u2242', // ?
0x69: '\u2136', // \beth
0x6A: '\u2137', // \gimel
0x6B: '\u2138', // \daleth
0x6C: '\u22D6', // \lessdot
0x6D: '\u22D7', // \gtrdot
0x6E: '\u22C9', // \ltimes
0x6F: '\u22CA', // \rtimes
0x70: '\u23D0', // \shortmid
0x71: '\u2225', // \shortparallel todo: not short!
0x72: '\u2216', // \smallsetminus todo: probably not quite right -- more backslash
0x73: '\u223C', // \thicksim note: no thick avail
0x74: '\u2248', // \thickapprox note: no thick avail
0x75: '\u224A', // \approxeq
0x76: '\u227F', // \succapprox note: using succsim -- no approx
0x77: '\u227E', // \precapprox note: using precsim -- no approx
0x78: '\u21B6', // \curvearrowleft
0x79: '\u21B7', // \curvearrowright
0x7A: '\u0046', // \digamma note: using F
0x7B: '\u03F0', // \varkappa note: using kappa
0x7C: '\u212A', // \Bbbk note: not the right double-outlined font
0x7D: '\u210F', // \hslash
0x7E: '\u210F', // \hbar note: not correct: using /hslash
0x7F: '\u220D', // \backepsilon todo: not quite right but same shape
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// note: adapted from https://github.com/tdewolff/canvas,
// Copyright (c) 2015 Taco de Wolff, under an MIT License.
package tex
import (
"encoding/binary"
"fmt"
"cogentcore.org/core/paint/ppath"
)
var Debug = false
type state struct {
h, v, w, x, y, z int32
}
// note: use dvitype --show-opcodes to show the dvi in human-readable format,
// with command opcodes
// DVIToPath parses a DVI file (output from TeX) and returns ppath.Path.
// fontSizeDots specifies the actual font size in dots (actual pixels)
// for a 10pt font in the DVI system.
func DVIToPath(b []byte, fonts *dviFonts, fontSizeDots float32) (ppath.Path, error) {
// state
var fnt uint32 // font index
s := state{}
stack := []state{}
f := float32(1.0) // scale factor in mm/units
mag := uint32(1000) // is set explicitly in preamble
fnts := map[uint32]*dviFont{} // selected fonts for indices
fontScale := fontSizeDots / 8 // factor for scaling font itself
fontScaleFactor := fontSizeDots / 2.8 // factor for scaling the math
// default font
fnts[0] = fonts.Get("cmr10", 1)
// first position of baseline which will be the path's origin
firstChar := true
// min pos
v0 := int32(0)
h0 := int32(0)
p := ppath.Path{}
r := &dviReader{b, 0}
for 0 < r.len() {
if Debug {
fmt.Printf("## At: %d\n", r.i)
}
cmd := r.readByte()
if cmd <= 127 {
// set_char
if firstChar {
v0 = s.v
h0 = s.h
firstChar = false
}
// v0 = min(v0, s.v) // note: this doesn't work in general
h0 = min(h0, s.h)
c := uint32(cmd)
fntd, ok := fnts[fnt]
if !ok {
return nil, fmt.Errorf("bad command: font %v undefined at position %v", fnt, r.i)
}
w := int32(fnts[fnt].Draw(&p, f*float32(s.h), f*float32(s.v), c, fontScale) / f)
if Debug {
fmt.Printf("\nchar font %d, cid: %d, 0x%x, rune: %s, pos: (%v,%v) = (%v,%v) w: %v to h: %v\n", fntd.cmapType, c, c, string(rune(c)), s.h, s.v, f*float32(s.h), f*float32(s.v), w, s.h+w)
}
s.h += w
} else if 128 <= cmd && cmd <= 131 {
// set
if firstChar {
h0, v0 = s.h, s.v
firstChar = false
}
n := int(cmd - 127)
if r.len() < n {
return nil, fmt.Errorf("bad command: %v at position %v", cmd, r.i)
}
c := r.readUint32N(n)
if _, ok := fnts[fnt]; !ok {
return nil, fmt.Errorf("bad command: font %v undefined at position %v", fnt, r.i)
}
// fmt.Println("print:", string(rune(c)), s.v)
s.h += int32(fnts[fnt].Draw(&p, f*float32(s.h), f*float32(s.v), c, fontScale) / f)
} else if cmd == 132 {
// set_rule
height := r.readInt32()
width := r.readInt32()
if 0 < width && 0 < height {
p.MoveTo(f*float32(s.h), f*float32(s.v))
p.LineTo(f*float32(s.h+width), f*float32(s.v))
p.LineTo(f*float32(s.h+width), f*float32(s.v-height))
p.LineTo(f*float32(s.h), f*float32(s.v-height))
p.Close()
}
s.h += width
} else if 133 <= cmd && cmd <= 136 {
// put
if firstChar {
h0, v0 = s.h, s.v
firstChar = false
}
n := int(cmd - 132)
if r.len() < n {
return nil, fmt.Errorf("bad command: %v at position %v", cmd, r.i)
}
c := r.readUint32N(n)
if _, ok := fnts[fnt]; !ok {
return nil, fmt.Errorf("bad command: font %v undefined at position %v", fnt, r.i)
}
// fmt.Println("print:", string(rune(c)), s.v)
fnts[fnt].Draw(&p, f*float32(s.h), f*float32(s.v), c, fontScale)
} else if cmd == 137 {
// put_rule
height := r.readInt32()
width := r.readInt32()
if 0 < width && 0 < height {
p.MoveTo(f*float32(s.h), f*float32(s.v))
p.LineTo(f*float32(s.h+width), f*float32(s.v))
p.LineTo(f*float32(s.h+width), f*float32(s.v-height))
p.LineTo(f*float32(s.h), f*float32(s.v-height))
p.Close()
}
} else if cmd == 138 {
// nop
} else if cmd == 139 {
// bop
fnt = 0
s = state{0, 0, 0, 0, 0, 0}
stack = stack[:0]
_ = r.readBytes(10 * 4)
_ = r.readUint32() // pointer
} else if cmd == 140 {
// eop
} else if cmd == 141 {
// push
stack = append(stack, s)
if Debug {
fmt.Printf("push to: %d\n", len(stack))
}
} else if cmd == 142 {
// pop
// if len(stack) == 0 {
// return nil, fmt.Errorf("bad command: stack is empty at position %v", r.i)
// }
if len(stack) == 0 {
fmt.Printf("bad command: stack is empty at position %v\n", r.i)
} else {
s = stack[len(stack)-1]
stack = stack[:len(stack)-1]
if Debug {
fmt.Printf("pop to: %d\n", len(stack))
}
}
} else if 143 <= cmd && cmd <= 146 {
// right
n := int(cmd - 142)
if r.len() < n {
return nil, fmt.Errorf("bad command: %v at position %v", cmd, r.i)
}
d := r.readInt32N(n)
s.h += d
if Debug {
fmt.Printf("right %d to %d\n", d, s.h)
}
} else if 147 <= cmd && cmd <= 151 {
// w
if cmd == 147 {
s.h += s.w
if Debug {
fmt.Printf("right w %d to %d\n", s.w, s.h)
}
} else {
n := int(cmd - 147)
if r.len() < n {
return nil, fmt.Errorf("bad command: %v at position %v", cmd, r.i)
}
d := r.readInt32N(n)
s.w = d
s.h += d
if Debug {
fmt.Printf("right arg w %d to %d\n", d, s.h)
}
}
} else if 152 <= cmd && cmd <= 156 {
// x
if cmd == 152 {
s.h += s.x
if Debug {
fmt.Printf("right x %d to %d\n", s.x, s.h)
}
} else {
n := int(cmd - 152)
if r.len() < n {
return nil, fmt.Errorf("bad command: %v at position %v", cmd, r.i)
}
d := r.readInt32N(n)
s.x = d
s.h += d
if Debug {
fmt.Printf("right spec x %d to %d\n", s.x, s.h)
}
}
} else if 157 <= cmd && cmd <= 160 {
// down
n := int(cmd - 156)
if r.len() < n {
return nil, fmt.Errorf("bad command: %v at position %v", cmd, r.i)
}
d := r.readInt32N(n)
s.v += d
if Debug {
fmt.Printf("down %d to %d\n", d, s.v)
}
} else if 161 <= cmd && cmd <= 165 {
// y
if cmd == 161 {
s.v += s.y
if Debug {
fmt.Printf("down y %d to %d\n", s.y, s.v)
}
} else {
n := int(cmd - 161)
if r.len() < n {
return nil, fmt.Errorf("bad command: %v at position %v", cmd, r.i)
}
d := r.readInt32N(n)
s.y = d
s.v += d
if Debug {
fmt.Printf("down spec y %d to %d\n", s.y, s.v)
}
}
} else if 166 <= cmd && cmd <= 170 {
// z
if cmd == 166 {
s.v += s.z
if Debug {
fmt.Printf("down z %d to %d\n", s.z, s.v)
}
} else {
n := int(cmd - 166)
if r.len() < n {
return nil, fmt.Errorf("bad command: %v at position %v", cmd, r.i)
}
d := r.readInt32N(n)
s.z = d
s.v += d
if Debug {
fmt.Printf("down spec z %d to %d\n", s.z, s.v)
}
}
} else if 171 <= cmd && cmd <= 234 {
// fnt_num
fnt = uint32(cmd - 171)
} else if 235 <= cmd && cmd <= 238 {
// fnt
n := int(cmd - 234)
if r.len() < n {
return nil, fmt.Errorf("bad command: %v at position %v", cmd, r.i)
}
fnt = r.readUint32N(n)
} else if 239 <= cmd && cmd <= 242 {
// xxx
n := int(cmd - 238)
if r.len() < n {
return nil, fmt.Errorf("bad command: %v at position %v", cmd, r.i)
}
k := int(r.readUint32N(n))
if r.len() < k {
return nil, fmt.Errorf("bad command: %v at position %v", cmd, r.i)
}
ignore := r.readBytes(k)
_ = ignore
if Debug {
fmt.Println("cmd:", cmd, "len:", k, "bytes:", string(ignore))
}
} else if 243 <= cmd && cmd <= 246 {
// fnt_def
n := int(cmd - 242)
if r.len() < n+14 {
return nil, fmt.Errorf("bad command: %v at position %v", cmd, r.i)
}
k := r.readUint32N(n)
_ = r.readBytes(4) // checksum
size := r.readUint32()
design := r.readUint32() // design
a := r.readByte()
l := r.readByte()
if r.len() < int(a+l) {
return nil, fmt.Errorf("bad command: %v at position %v", cmd, r.i)
}
_ = r.readString(int(a)) // area
fscale := float32(mag) * float32(size) / 1000.0 / float32(design)
// this is 1 for 10pt font:
name := r.readString(int(l))
fnts[k] = fonts.Get(name, fscale)
if Debug {
fmt.Printf("\ndefine font #:%d name: %s, size: %v, mag: %v, design: %v, scale: %v\n", k, name, size, mag, design, fscale)
}
} else if cmd == 247 {
// pre
_ = r.readByte() // version
num := r.readUint32()
den := r.readUint32()
mag = r.readUint32()
f = fontScaleFactor * float32(num) / float32(den) * float32(mag) / 1000.0 / 10000.0 // in units/mm
n := int(r.readByte())
cmt := r.readString(n) // comment
_ = cmt
if Debug {
fmt.Println("num:", num, "mag:", mag, "den:", den, "f:", f, "cmt len:", n, "cmt:", cmt)
}
} else if cmd == 248 {
_ = r.readUint32() // pointer to final bop
_ = r.readUint32() // num
_ = r.readUint32() // den
_ = r.readUint32() // mag
_ = r.readUint32() // largest height
_ = r.readUint32() // largest width
_ = r.readUint16() // maximum stack depth
_ = r.readUint16() // number of pages
} else if cmd == 249 {
_ = r.readUint32() // pointer to post
_ = r.readByte() // version
for 0 < r.len() {
if r.readByte() != 223 {
break
}
}
} else {
return nil, fmt.Errorf("bad command: %v at position %v", cmd, r.i)
}
}
// fmt.Println("start offsets:", h0, v0)
p = p.Translate(-f*float32(h0), -f*float32(v0))
return p, nil
}
type dviReader struct {
b []byte
i int
}
func (r *dviReader) len() int {
return len(r.b) - r.i
}
func (r *dviReader) readByte() byte {
r.i++
return r.b[r.i-1]
}
func (r *dviReader) readUint16() uint16 {
num := binary.BigEndian.Uint16(r.b[r.i : r.i+2])
r.i += 2
return num
}
func (r *dviReader) readUint32() uint32 {
num := binary.BigEndian.Uint32(r.b[r.i : r.i+4])
r.i += 4
return num
}
func (r *dviReader) readInt32() int32 {
return int32(r.readUint32())
}
func (r *dviReader) readUint32N(n int) uint32 {
switch n {
case 1:
return uint32(r.readByte())
case 2:
return uint32(r.readUint16())
case 3:
a := r.readByte()
b := r.readByte()
c := r.readByte()
return uint32(a)<<16 | uint32(b)<<8 | uint32(c)
case 4:
return r.readUint32()
}
r.i += n
return 0
}
func (r *dviReader) readInt32N(n int) int32 {
if n == 3 {
a := r.readByte()
b := r.readByte()
c := r.readByte()
if a < 128 {
return int32(uint32(a)<<16 | uint32(b)<<8 | uint32(c))
}
return int32((uint32(a)-256)<<16 | uint32(b)<<8 | uint32(c))
}
return int32(r.readUint32N(n))
}
func (r *dviReader) readBytes(n int) []byte {
b := r.b[r.i : r.i+n]
r.i += n
return b
}
func (r *dviReader) readString(n int) string {
return string(r.readBytes(n))
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// note: adapted from https://github.com/tdewolff/canvas,
// Copyright (c) 2015 Taco de Wolff, under an MIT License.
// and gioui: Unlicense OR MIT, Copyright (c) 2019 The Gio authors
package tex
import (
"bytes"
"fmt"
"strconv"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint/ppath"
"cogentcore.org/core/text/fonts"
"github.com/cogentcore/typesetting/font"
"github.com/cogentcore/typesetting/font/opentype"
"github.com/go-fonts/latin-modern/lmmath"
"github.com/go-fonts/latin-modern/lmmono10italic"
"github.com/go-fonts/latin-modern/lmmono10regular"
"github.com/go-fonts/latin-modern/lmmono12regular"
"github.com/go-fonts/latin-modern/lmmono8regular"
"github.com/go-fonts/latin-modern/lmmono9regular"
"github.com/go-fonts/latin-modern/lmmonocaps10regular"
"github.com/go-fonts/latin-modern/lmmonoslant10regular"
"github.com/go-fonts/latin-modern/lmroman10bold"
"github.com/go-fonts/latin-modern/lmroman10bolditalic"
"github.com/go-fonts/latin-modern/lmroman10italic"
"github.com/go-fonts/latin-modern/lmroman10regular"
"github.com/go-fonts/latin-modern/lmroman12bold"
"github.com/go-fonts/latin-modern/lmroman12italic"
"github.com/go-fonts/latin-modern/lmroman12regular"
"github.com/go-fonts/latin-modern/lmroman17regular"
"github.com/go-fonts/latin-modern/lmroman5bold"
"github.com/go-fonts/latin-modern/lmroman5regular"
"github.com/go-fonts/latin-modern/lmroman6bold"
"github.com/go-fonts/latin-modern/lmroman6regular"
"github.com/go-fonts/latin-modern/lmroman7bold"
"github.com/go-fonts/latin-modern/lmroman7italic"
"github.com/go-fonts/latin-modern/lmroman7regular"
"github.com/go-fonts/latin-modern/lmroman8bold"
"github.com/go-fonts/latin-modern/lmroman8italic"
"github.com/go-fonts/latin-modern/lmroman8regular"
"github.com/go-fonts/latin-modern/lmroman9bold"
"github.com/go-fonts/latin-modern/lmroman9italic"
"github.com/go-fonts/latin-modern/lmroman9regular"
"github.com/go-fonts/latin-modern/lmromancaps10regular"
"github.com/go-fonts/latin-modern/lmromandunh10regular"
"github.com/go-fonts/latin-modern/lmromanslant10bold"
"github.com/go-fonts/latin-modern/lmromanslant10regular"
"github.com/go-fonts/latin-modern/lmromanslant12regular"
"github.com/go-fonts/latin-modern/lmromanslant17regular"
"github.com/go-fonts/latin-modern/lmromanslant8regular"
"github.com/go-fonts/latin-modern/lmromanslant9regular"
"github.com/go-fonts/latin-modern/lmromanunsl10regular"
"github.com/go-fonts/latin-modern/lmsans10bold"
"github.com/go-fonts/latin-modern/lmsans10oblique"
"github.com/go-fonts/latin-modern/lmsans10regular"
"github.com/go-fonts/latin-modern/lmsans12oblique"
"github.com/go-fonts/latin-modern/lmsans12regular"
"github.com/go-fonts/latin-modern/lmsans17oblique"
"github.com/go-fonts/latin-modern/lmsans17regular"
"github.com/go-fonts/latin-modern/lmsans8oblique"
"github.com/go-fonts/latin-modern/lmsans8regular"
"github.com/go-fonts/latin-modern/lmsans9oblique"
"github.com/go-fonts/latin-modern/lmsans9regular"
"github.com/go-fonts/latin-modern/lmsansdemicond10regular"
"github.com/go-fonts/latin-modern/lmsansquot8oblique"
"github.com/go-fonts/latin-modern/lmsansquot8regular"
)
// LMFontsLoad loads the LMFonts.
func LMFontsLoad() {
for i := range LMFonts {
fd := &LMFonts[i]
errors.Log(fd.Load())
}
}
// LMFonts are tex latin-modern fonts.
var LMFonts = []fonts.Data{
{Family: "cmbsy", Data: lmmath.TTF},
{Family: "cmr17", Data: lmroman17regular.TTF},
{Family: "cmr12", Data: lmroman12regular.TTF},
{Family: "cmr10", Data: lmroman10regular.TTF},
{Family: "cmr9", Data: lmroman9regular.TTF},
{Family: "cmr8", Data: lmroman8regular.TTF},
{Family: "cmr7", Data: lmroman7regular.TTF},
{Family: "cmr6", Data: lmroman6regular.TTF},
{Family: "cmr5", Data: lmroman5regular.TTF},
// cmb, cmbx
{Family: "cmb12", Data: lmroman12bold.TTF},
{Family: "cmb10", Data: lmroman10bold.TTF},
{Family: "cmb9", Data: lmroman9bold.TTF},
{Family: "cmb8", Data: lmroman8bold.TTF},
{Family: "cmb7", Data: lmroman7bold.TTF},
{Family: "cmb6", Data: lmroman6bold.TTF},
{Family: "cmb5", Data: lmroman5bold.TTF},
// cmti
{Family: "cmti12", Data: lmroman12italic.TTF},
{Family: "cmti10", Data: lmroman10italic.TTF},
{Family: "cmti9", Data: lmroman9italic.TTF},
{Family: "cmti8", Data: lmroman8italic.TTF},
{Family: "cmti7", Data: lmroman7italic.TTF},
// cmsl
{Family: "cmsl17", Data: lmromanslant17regular.TTF},
{Family: "cmsl12", Data: lmromanslant12regular.TTF},
{Family: "cmsl10", Data: lmromanslant10regular.TTF},
{Family: "cmsl9", Data: lmromanslant9regular.TTF},
{Family: "cmsl8", Data: lmromanslant8regular.TTF},
// cmbxsl
{Family: "cmbxsl10", Data: lmromanslant10bold.TTF},
// cmbxti, cmmib with cmapCMMI
{Family: "cmmib10", Data: lmroman10bolditalic.TTF},
// cmcsc
{Family: "cmcsc10", Data: lmromancaps10regular.TTF},
// cmdunh
{Family: "cmdunh10", Data: lmromandunh10regular.TTF},
// cmu
{Family: "cmu10", Data: lmromanunsl10regular.TTF},
// cmss
{Family: "cmss17", Data: lmsans17regular.TTF},
{Family: "cmss12", Data: lmsans12regular.TTF},
{Family: "cmss10", Data: lmsans10regular.TTF},
{Family: "cmss9", Data: lmsans9regular.TTF},
{Family: "cmss8", Data: lmsans8regular.TTF},
// cmssb, cmssbx
{Family: "cmssb10", Data: lmsans10bold.TTF},
// cmssdc
{Family: "cmssdc10", Data: lmsansdemicond10regular.TTF},
// cmssi
{Family: "cmssi17", Data: lmsans17oblique.TTF},
{Family: "cmssi12", Data: lmsans12oblique.TTF},
{Family: "cmssi10", Data: lmsans10oblique.TTF},
{Family: "cmssi9", Data: lmsans9oblique.TTF},
{Family: "cmssi8", Data: lmsans8oblique.TTF},
// cmssq
{Family: "cmssq8", Data: lmsansquot8regular.TTF},
// cmssqi
{Family: "cmssqi8", Data: lmsansquot8oblique.TTF},
// cmtt
{Family: "cmtt12", Data: lmmono12regular.TTF},
{Family: "cmtt10", Data: lmmono10regular.TTF},
{Family: "cmtt9", Data: lmmono9regular.TTF},
{Family: "cmtt8", Data: lmmono8regular.TTF},
// cmti
// {Family: "cmti", Data: lmmono12italic.TTF},
{Family: "cmti10", Data: lmmono10italic.TTF},
// {Family: "cmti", Data: lmmono9italic.TTF},
// {Family: "cmti", Data: lmmono8italic.TTF},
// cmtcsc
{Family: "cmtcsc10", Data: lmmonocaps10regular.TTF},
}
//////// dviFonts
// dviFonts supports rendering of following standard DVI fonts:
//
// cmr: Roman (5--10pt)
// cmmi: Math Italic (5--10pt)
// cmsy: Math Symbols (5--10pt)
// cmex: Math Extension (10pt)
// cmss: Sans serif (10pt)
// cmssqi: Sans serif quote italic (8pt)
// cmssi: Sans serif Italic (10pt)
// cmbx: Bold Extended (10pt)
// cmtt: Typewriter (8--10pt)
// cmsltt: Slanted typewriter (10pt)
// cmsl: Slanted roman (8--10pt)
// cmti: Text italic (7--10pt)
// cmu: Unslanted text italic (10pt)
// cmmib: Bold math italic (10pt)
// cmbsy: Bold math symbols (10pt)
// cmcsc: Caps and Small caps (10pt)
// cmssbx: Sans serif bold extended (10pt)
// cmdunh: Dunhill style (10pt)
type dviFonts struct {
font map[string]*dviFont
mathSyms *dviFont // always available as backup for any rune
}
type dviFont struct {
face *font.Face
cmapType charMaps
cmap map[uint32]rune
size float32
italic bool
ex bool
mathSyms *dviFont // always available as backup for any rune
}
func newFonts() *dviFonts {
return &dviFonts{
font: map[string]*dviFont{},
}
}
func (fs *dviFonts) Get(name string, scale float32) *dviFont {
i := 0
for i < len(name) && 'a' <= name[i] && name[i] <= 'z' {
i++
}
fontname := name[:i]
fontsize := float32(10.0)
if ifontsize, err := strconv.Atoi(name[i:]); err == nil {
fontsize = float32(ifontsize)
}
// fmt.Println("font name:", fontname, fontsize, scale)
if fs.mathSyms == nil {
fs.mathSyms = fs.loadFont("cmsy", CMSY, 10.0, scale, lmmath.TTF)
}
cmap := CMR
f, ok := fs.font[name]
if !ok {
var fontSizes map[float32][]byte
switch fontname {
case "cmb", "cmbx":
fontSizes = map[float32][]byte{
12.0: lmroman12bold.TTF,
10.0: lmroman10bold.TTF,
9.0: lmroman9bold.TTF,
8.0: lmroman8bold.TTF,
7.0: lmroman7bold.TTF,
6.0: lmroman6bold.TTF,
5.0: lmroman5bold.TTF,
}
case "cmbsy":
cmap = CMSY
fontSizes = map[float32][]byte{
fontsize: lmmath.TTF,
}
case "cmbxsl":
fontSizes = map[float32][]byte{
fontsize: lmromanslant10bold.TTF,
}
case "cmbxti":
fontSizes = map[float32][]byte{
10.0: lmroman10bolditalic.TTF,
}
case "cmcsc":
cmap = CMTT
fontSizes = map[float32][]byte{
10.0: lmromancaps10regular.TTF,
}
case "cmdunh":
fontSizes = map[float32][]byte{
10.0: lmromandunh10regular.TTF,
}
case "cmex":
cmap = CMEX
fontSizes = map[float32][]byte{
fontsize: lmmath.TTF,
}
case "cmitt":
cmap = CMTT
fontSizes = map[float32][]byte{
10.0: lmmono10italic.TTF,
}
case "cmmi":
cmap = CMMI
fontSizes = map[float32][]byte{
12.0: lmroman12italic.TTF,
10.0: lmroman10italic.TTF,
9.0: lmroman9italic.TTF,
8.0: lmroman8italic.TTF,
7.0: lmroman7italic.TTF,
}
case "cmmib":
cmap = CMMI
fontSizes = map[float32][]byte{
10.0: lmroman10bolditalic.TTF,
}
case "cmr":
fontSizes = map[float32][]byte{
17.0: lmroman17regular.TTF,
12.0: lmroman12regular.TTF,
10.0: lmroman10regular.TTF,
9.0: lmroman9regular.TTF,
8.0: lmroman8regular.TTF,
7.0: lmroman7regular.TTF,
6.0: lmroman6regular.TTF,
5.0: lmroman5regular.TTF,
}
case "cmsl":
fontSizes = map[float32][]byte{
17.0: lmromanslant17regular.TTF,
12.0: lmromanslant12regular.TTF,
10.0: lmromanslant10regular.TTF,
9.0: lmromanslant9regular.TTF,
8.0: lmromanslant8regular.TTF,
}
case "cmsltt":
fontSizes = map[float32][]byte{
10.0: lmmonoslant10regular.TTF,
}
case "cmss":
fontSizes = map[float32][]byte{
17.0: lmsans17regular.TTF,
12.0: lmsans12regular.TTF,
10.0: lmsans10regular.TTF,
9.0: lmsans9regular.TTF,
8.0: lmsans8regular.TTF,
}
case "cmssb", "cmssbx":
fontSizes = map[float32][]byte{
10.0: lmsans10bold.TTF,
}
case "cmssdc":
fontSizes = map[float32][]byte{
10.0: lmsansdemicond10regular.TTF,
}
case "cmssi":
fontSizes = map[float32][]byte{
17.0: lmsans17oblique.TTF,
12.0: lmsans12oblique.TTF,
10.0: lmsans10oblique.TTF,
9.0: lmsans9oblique.TTF,
8.0: lmsans8oblique.TTF,
}
case "cmssq":
fontSizes = map[float32][]byte{
8.0: lmsansquot8regular.TTF,
}
case "cmssqi":
fontSizes = map[float32][]byte{
8.0: lmsansquot8oblique.TTF,
}
case "cmsy":
cmap = CMSY
fontSizes = map[float32][]byte{
fontsize: lmmath.TTF,
}
case "cmtcsc":
cmap = CMTT
fontSizes = map[float32][]byte{
10.0: lmmonocaps10regular.TTF,
}
//case "cmtex":
//cmap = nil
case "cmti":
fontSizes = map[float32][]byte{
12.0: lmroman12italic.TTF,
10.0: lmroman10italic.TTF,
9.0: lmroman9italic.TTF,
8.0: lmroman8italic.TTF,
7.0: lmroman7italic.TTF,
}
case "cmtt":
cmap = CMTT
fontSizes = map[float32][]byte{
12.0: lmmono12regular.TTF,
10.0: lmmono10regular.TTF,
9.0: lmmono9regular.TTF,
8.0: lmmono8regular.TTF,
}
case "cmu":
fontSizes = map[float32][]byte{
10.0: lmromanunsl10regular.TTF,
}
//case "cmvtt":
//cmap = cmapCTT
case "msam":
cmap = AMSAM
fontSizes = map[float32][]byte{
fontsize: lmmath.TTF,
}
case "msbm":
cmap = AMSBM
fontSizes = map[float32][]byte{
fontsize: lmmath.TTF,
}
default:
fmt.Println("WARNING: unknown font", fontname)
}
// select closest matching font size
var data []byte
var size float32
for isize, idata := range fontSizes {
if data == nil || math32.Abs(isize-fontsize) < math32.Abs(size-fontsize) {
data = idata
size = isize
}
}
f = fs.loadFont(fontname, cmap, fontsize, scale, data)
fs.font[name] = f
}
return f
}
func (fs *dviFonts) loadFont(fontname string, cmap charMaps, fontsize, scale float32, data []byte) *dviFont {
faces, err := font.ParseTTC(bytes.NewReader(data))
if err != nil { // todo: should still work presumably?
panic(fmt.Errorf("dviFonts error: no font found %s: %w", fontname, err))
}
face := faces[0]
fsize := scale * fontsize
isItalic := 0 < len(fontname) && fontname[len(fontname)-1] == 'i'
isEx := fontname == "cmex"
return &dviFont{face: face, cmapType: cmap, cmap: cmap.Table(), size: fsize, italic: isItalic, ex: isEx, mathSyms: fs.mathSyms}
}
type xxbearing struct {
cmap charMaps
x int32
}
// glyphs for which bearings should be used: most are better without.
// outline versions of font data are kinda weird it seems here.
// value is extra adjustment to apply.
var useXBearings = map[uint32]xxbearing{
0x16: {CMR, 0}, // h-bar
0x30: {CMSY, -200}, // ' (prime)
0x36: {CMSY, -720}, // / in neq
0x5E: {CMR, 0}, // ^
0x7E: {CMMI, -150}, // -> vec
0x7F: {CMR, -150}, // .. ddot
}
const (
mag1 = 1.2
mag2 = 1.2 * 1.2
mag3 = 1.2 * 1.2 * 1.2
mag4 = 1.2 * 1.2 * 1.2 * 1.2 * 1.2
mag5 = 3.2
)
var cmexScales = map[uint32]float32{
0x00: mag1,
0x01: mag1,
0x02: mag1,
0x03: mag1,
0x04: mag1,
0x05: mag1,
0x06: mag1,
0x07: mag1,
0x08: mag1,
0x0A: mag1,
0x0B: mag1,
0x0C: mag1,
0x0D: mag1,
0x0E: mag1,
0x0F: mag1,
0x10: mag3, // (
0x11: mag3, // )
0x12: mag4, // (
0x13: mag4, // )
0x14: mag4, // [
0x15: mag4, // ]
0x16: mag4, // ⌊
0x17: mag4, // ⌋
0x18: mag4, // ⌈
0x19: mag4, // ⌉
0x1A: mag4, // {
0x1B: mag4, // }
0x1C: mag4, // 〈
0x1D: mag4, // 〉
0x1E: mag4, // ∕
0x1F: mag4, // \
0x20: mag5, // (
0x21: mag5, // )
0x22: mag5, // [
0x23: mag5, // ]
0x24: mag5, // ⌊
0x25: mag5, // ⌋
0x26: mag5, // ⌈
0x27: mag5, // ⌉
0x28: mag5, // {
0x29: mag5, // }
0x2A: mag5, // 〈
0x2B: mag5, // 〉
0x2C: mag5, // ∕
0x2D: mag5, // \
0x2E: mag3, // ∕
0x2F: mag3, // \
0x30: mag2, // ⎛
0x31: mag2, // ⎞
0x32: mag2, // ⌈
0x33: mag2, // ⌉
0x34: mag2, // ⌊
0x35: mag2, // ⌋
0x36: mag2, // ⎢
0x37: mag2, // ⎥
0x38: mag2, // ⎧ // big braces start
0x39: mag2, // ⎫
0x3A: mag2, // ⎩
0x3B: mag2, // ⎭
0x3C: mag2, // ⎨
0x3D: mag2, // ⎬
0x3E: mag2, // ⎪
0x3F: mag2, // ∣ ?? unclear
0x40: mag2, // ⎝ // big parens
0x41: mag2, // ⎠
0x42: mag2, // ⎜
0x43: mag2, // ⎟
0x44: mag2, // 〈
0x45: mag2, // 〉
0x47: mag2, // ⨆
0x49: mag2, // ∮
0x4B: mag2, // ⨀
0x4D: mag2, // ⨁
0x4F: mag2, // ⨂
0x58: mag2, // ∑
0x59: mag2, // ∏
0x5A: mag2, // ∫
0x5B: mag2, // ⋃
0x5C: mag2, // ⋂
0x5D: mag2, // ⨄
0x5E: mag2, // ⋀
0x5F: mag2, // ⋁
0x61: mag2, // ∐
0x63: mag2, // ̂
0x64: mag4, // ̂
0x66: mag2, // ˜
0x67: mag4, // ˜
0x68: mag3, // [
0x69: mag3, // ]
0x6B: mag2, // ⌋
0x6C: mag2, // ⌈
0x6D: mag2, // ⌉
0x6E: mag3, // {
0x6F: mag3, // }
0x71: mag3, // √
0x72: mag4, // √
0x73: mag5, // √
0x74: mag1, // ⎷
0x75: mag1, // ⏐
0x76: mag1, // ⌜
}
const (
italicYX = 0.2
)
// Draw renders the font, and returns the width advance
func (f *dviFont) Draw(p *ppath.Path, x, y float32, cid uint32, scale float32) float32 {
r := f.cmap[cid]
if r == 0x337 {
r = ' '
}
face := f.face
gid, ok := face.Cmap.Lookup(r)
if !ok {
if f.mathSyms != nil {
face = f.mathSyms.face
gid, ok = face.Cmap.Lookup(r)
if !ok {
fmt.Printf("rune not found in mathSyms, cid: %x, hex: %x, string: %q\n", cid, r, string(r))
}
} else {
fmt.Println("rune not found:", string(r))
}
}
// fmt.Printf("rune: 0x%0x gid: %d, r: 0x%0X\n", cid, gid, int(r))
// adcb
// cbad
outline := face.GlyphData(gid).(font.GlyphOutline)
sc := scale * f.size / float32(face.Upem())
xsc := float32(1)
// fmt.Println("draw scale:", sc, "f.size:", f.size, "face.Upem()", face.Upem())
ext, has := face.GlyphExtents(gid)
var xb, yb float32
if has {
xb = ext.XBearing
yb = ext.YBearing
ex, useX := useXBearings[cid]
if useX {
if f.cmapType == ex.cmap {
x -= sc * (xb + float32(ex.x))
}
}
}
if f.ex {
exsc, has := cmexScales[cid]
if has {
sc *= exsc
// fmt.Printf("%x: ex scale %g\n", cid, exsc)
}
ybb := yb
switch cid {
case 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F:
// larger delims are too thick
xsc = .7
case 0x20, 0x21, 0x22, 0x23, 0x28, 0x29, 0x2A, 0x2B:
// same for even larger ones
xsc = .6
case 0x3C, 0x3D: // braces middles need shifting
ybb += 150
case 0x3A, 0x3B: // braces bottom shifting
ybb += 400
case 0x5A, 0x49: // \int and \oint are off in large size
ybb += 200
case 0x64: // ^ big
ybb -= 400
x += sc * 600
// below are fixes for all the square root elements
case 0x70:
x += sc * 120
case 0x71:
x += sc * 80
xsc = .6
case 0x72:
x -= sc * 80
xsc = .6
case 0x73:
x -= sc * 80
xsc = .5
case 0x74:
ybb += 150
case 0x75:
x += sc * 560
case 0x76:
x += sc * 400
ybb -= 36
}
y += sc * ybb
}
doItal := f.italic && f.cmapType == CMMI && cid == 0x40 // an italic symbol
for _, s := range outline.Segments {
p0 := math32.Vec2(s.Args[0].X*xsc*sc+x, -s.Args[0].Y*sc+y)
if doItal {
p0.X += italicYX * s.Args[0].Y * xsc * sc
}
// fmt.Println(s.Args[0].X, s.Args[0].Y, s.Args[0])
switch s.Op {
case opentype.SegmentOpMoveTo:
p.MoveTo(p0.X, p0.Y)
case opentype.SegmentOpLineTo:
p.LineTo(p0.X, p0.Y)
case opentype.SegmentOpQuadTo:
p1 := math32.Vec2(s.Args[1].X*xsc*sc+x, -s.Args[1].Y*sc+y)
if doItal {
p1.X += italicYX * s.Args[1].Y * xsc * sc
}
p.QuadTo(p0.X, p0.Y, p1.X, p1.Y)
case opentype.SegmentOpCubeTo:
p1 := math32.Vec2(s.Args[1].X*xsc*sc+x, -s.Args[1].Y*sc+y)
p2 := math32.Vec2(s.Args[2].X*xsc*sc+x, -s.Args[2].Y*sc+y)
if doItal {
p1.X += italicYX * s.Args[1].Y * xsc * sc
p2.X += italicYX * s.Args[2].Y * xsc * sc
}
p.CubeTo(p0.X, p0.Y, p1.X, p1.Y, p2.X, p2.Y)
}
}
p.Close()
hadv := face.HorizontalAdvance(gid)
if hadv == 0 {
hadv = 500
}
adv := sc * hadv
return adv
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package tex typesets LaTeX math expressions into paths, with the fonts of TeX.
package tex
import (
"bytes"
"embed"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"sync"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/fsx"
"cogentcore.org/core/paint/ppath"
"cogentcore.org/core/system"
"cogentcore.org/core/text/shaped"
"cogentcore.org/core/text/tex/texcache"
tex "github.com/cogentcore/star-tex"
)
//go:embed texmf
var texmf embed.FS
var (
texEngine *tex.LaTeXEngine
texFonts *dviFonts
texMu sync.Mutex
// this is set to path where texmf files were installed
texmfAt string
// note: must be standalone to work properly for inline paths.
// standalone cannot use standard \begin{equation} so using $\displaymath
preamble = `\documentclass{standalone}
\usepackage{amsmath}
\usepackage{amssymb}
\begin{document}
`
postamble = `
\end{document}
`
)
func init() {
shaped.ShapeMath = LaTeXMath
}
// LaTeXMath parses a LaTeX math expression and returns a path
// rendering that expression. To activate display math mode, add an additional $
// surrounding the expression: one set of $ $ is automatically included to produce
// inline math mode rendering by default.
// The additional $ activates displaystyle math.
// fontSizeDots specifies the actual font size in dots (actual pixels)
// for a 10pt font in the DVI system.
func LaTeXMath(expr string, fontSizeDots float32) (ppath.Path, error) {
texMu.Lock()
defer texMu.Unlock()
expr = strings.TrimSpace(expr)
if len(expr) == 0 {
return nil, fmt.Errorf("LaTeXMath: empty expr")
}
p := texcache.Get(expr, fontSizeDots)
if p != nil {
return p, nil
}
InstallTexMF()
txt := preamble
if expr[0] == '$' {
txt += "$\\displaystyle " + expr[1:len(expr)-1] + " $"
} else {
txt += "$" + expr + "$"
}
txt += postamble
if Debug {
fmt.Println("Input:")
fmt.Println(txt)
}
r := strings.NewReader(txt)
w := &bytes.Buffer{}
stdout := &bytes.Buffer{}
if texEngine == nil {
texEngine = tex.NewLaTeX()
}
texEngine.Stdout = stdout
if err := texEngine.Process(w, r); err != nil {
fmt.Println(stdout.String())
return nil, err
}
if texFonts == nil {
texFonts = newFonts()
}
p, err := DVIToPath(w.Bytes(), texFonts, fontSizeDots)
if err != nil {
fmt.Println("got DVIToPath error:", err)
fmt.Println(stdout.String())
return nil, err
}
texcache.Add(expr, fontSizeDots, p)
return p, nil
}
// InstallTexMF installs the specific TeX class and style files that
// we depend on, if not yet installed. Returns true if we just did
// the install. Must be called under texMu lock.
func InstallTexMF() bool {
if texmfAt != "" {
return false
}
if system.TheApp == nil {
// presumably testing, just use local files and be done!
dir := "./texmf"
texmfAt = dir
os.Setenv("TEXMF", dir)
return true
}
dir := system.TheApp.CogentCoreDataDir()
tdir := filepath.Join(dir, "texmf")
if ex, _ := fsx.DirExists(tdir); ex {
texmfAt = tdir
os.Setenv("TEXMF", tdir)
return true
}
err := os.MkdirAll(tdir, 0777)
if errors.Log(err) != nil {
return false
}
fs.WalkDir(texmf, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return errors.Log(err)
}
if d.IsDir() {
op := filepath.Join(dir, path)
err = os.MkdirAll(op, 0777)
if errors.Log(err) != nil {
return err
}
return nil
}
// fmt.Println(path)
b, err := fs.ReadFile(texmf, path)
if err != nil {
return errors.Log(err)
}
op := filepath.Join(dir, path)
// fmt.Println(op)
err = os.WriteFile(op, b, 0666)
if err != nil {
return errors.Log(err)
}
return nil
})
texmfAt = tdir
os.Setenv("TEXMF", tdir)
return true
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package texcache caches the paths of typeset LaTeX math expressions, which
// can be saved to a file and opened again, so that TeX is not needed for them.
package texcache
import (
"encoding/json"
"fmt"
"io"
"io/fs"
"maps"
"strings"
"sync"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/iox/gzipx"
"cogentcore.org/core/base/iox/jsonx"
"cogentcore.org/core/paint/ppath"
"cogentcore.org/core/text/shaped"
)
var (
// cache is a cache of equations and a corresponding SVG-encoded path string
cache map[string]*cached
// mu guards all operations on cache
mu sync.Mutex
)
// cached is one cache entry
type cached struct {
// svg encoded path string
Path string
// font size in dots that it was encoded in
// use scale transform to render in new target size.
FontSizeDots float32
// actual loaded PPath, in FontSizeDots.
pp ppath.Path
// sizes are the paths scaled from pp to other font sizes in dots,
// which are made once per size, so that texts of different sizes
// sharing an expression do not scale it again on each use.
sizes map[float32]ppath.Path
// call DeleteUnused to remove any that haven't been accessed or added.
used bool
}
// SetShapeMath sets the standard text shaping math function to use only
// cached math paths, not live generation of paths from TeX. This saves
// a lot of memory in the resulting executable, and is recommended for
// any math-heavy uses where all the equations can be cached in advance
// (e.g., the content system).
func SetShapeMath() {
shaped.ShapeMath = func(expr string, fontSizeDots float32) (ppath.Path, error) {
expr = strings.TrimSpace(expr)
p := Get(expr, fontSizeDots)
if p != nil {
return p, nil
}
return nil, fmt.Errorf("texcache: no cached path for expression: %q", expr)
}
}
// Get tries to get a cached path for given equation at given fontsize in dots.
// returns nil if not available. The returned path is a copy, so the caller
// can transform it in place (as [ppath.Path.Translate] does) without
// changing the cached path.
func Get(expr string, fontSizeDots float32) ppath.Path {
mu.Lock()
defer mu.Unlock()
cd, ok := cache[expr]
if !ok {
return nil
}
cd.used = true
if cd.pp == nil { // lazy loading
p, err := ppath.ParseSVGPath(cd.Path)
if err != nil {
fmt.Println("texcache parsing error -- shouldn't happen!", err)
delete(cache, expr)
return nil
}
cd.pp = p
}
if cd.FontSizeDots == fontSizeDots {
return cd.pp.Clone()
}
// Other sizes are scaled from the path in its own size, not from
// another scaled one, so they are the same in any order of use.
np, ok := cd.sizes[fontSizeDots]
if !ok {
sc := fontSizeDots / cd.FontSizeDots
np = cd.pp.Clone().Scale(sc, sc)
if cd.sizes == nil {
cd.sizes = make(map[float32]ppath.Path)
}
cd.sizes[fontSizeDots] = np
}
return np.Clone()
}
// Add adds a new entry
func Add(expr string, fontSizeDots float32, pp ppath.Path) {
mu.Lock()
defer mu.Unlock()
if cache == nil {
cache = make(map[string]*cached)
}
cache[expr] = &cached{FontSizeDots: fontSizeDots, pp: pp.Clone(), used: true}
}
func setCache(c map[string]*cached) {
if cache == nil {
cache = c
return
}
maps.Copy(cache, c)
}
// OpenFS opens saved cache entries from given file system (e.g., for embed).
// If the filename ends in .gz, it is unzipped for reading.
func OpenFS(fsys fs.FS, filename string) error {
mu.Lock()
defer mu.Unlock()
var c map[string]*cached
err := gzipx.OpenFS(fsys, filename, func(r io.Reader) error {
return readCache(&c, r)
})
if err != nil {
return errors.Log(err)
}
setCache(c)
return nil
}
// Open opens saved cache entries from given file
// If the filename ends in .gz, it is unzipped for reading.
func Open(filename string) error {
mu.Lock()
defer mu.Unlock()
var c map[string]*cached
err := gzipx.Open(filename, func(r io.Reader) error {
return readCache(&c, r)
})
if err != nil {
return errors.Log(err)
}
setCache(c)
return nil
}
// readCache reads the cache entries from the given reader. The cache is one
// large JSON object, which is read whole and then unmarshaled, which is much
// faster on the web (js platform) than decoding it from the stream.
func readCache(c *map[string]*cached, r io.Reader) error {
b, err := io.ReadAll(r)
if err != nil {
return err
}
return json.Unmarshal(b, c)
}
// DeleteUnused deletes any cache entries that have not been
// accessed since the cache was loaded.
// Use this in generate functions that save all generated cache.
func DeleteUnused() {
for k, v := range cache {
if !v.used {
delete(cache, k)
}
}
}
// SaveAs saves cache entries to given file
// If the filename ends in .gz, it is zipped.
// When generating, can call DeleteUnused to filter
// all unused items.
func SaveAs(filename string) error {
mu.Lock()
defer mu.Unlock()
if cache == nil {
return errors.New("texcache.SaveAs: no cache entries")
}
for _, v := range cache {
v.Path = v.pp.ToSVG()
}
err := gzipx.Save(filename, func(w io.Writer) error {
return jsonx.Write(cache, w)
})
return errors.Log(err)
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package text
import (
"cogentcore.org/core/text/rich"
)
// Font is a compact encoding of font properties, which can be used
// to reconstruct the corresponding [rich.Style] from [text.Style].
type Font struct {
// StyleRune is the rune-compressed version of the [rich.Style] parameters.
StyleRune rune
// Size is the Text.Style.FontSize.Dots value of the font size,
// multiplied by font rich.Style.Size.
Size float32
// Family is a nonstandard family name: if standard, then empty,
// and value is determined by [rich.Settings] and Style.Family.
Family string
}
func NewFont(fsty *rich.Style, tsty *Style) *Font {
fn := &Font{StyleRune: rich.RuneFromStyle(fsty), Size: tsty.FontHeight(fsty)}
if fsty.Family == rich.Custom {
fn.Family = string(tsty.CustomFont)
}
return fn
}
// Style returns the [rich.Style] version of this Font.
func (fn *Font) Style(tsty *Style) *rich.Style {
sty := rich.NewStyle()
rich.RuneToStyle(sty, fn.StyleRune)
sty.Size = fn.Size / tsty.FontSize.Dots
return sty
}
// FontFamily returns the string value of the font Family for given [rich.Style],
// using [text.Style] CustomFont or [rich.Settings] values.
func (ts *Style) FontFamily(sty *rich.Style) string {
if sty.Family == rich.Custom {
return string(ts.CustomFont)
}
return sty.FontFamily(&rich.Settings)
}
func (fn *Font) FamilyString(tsty *Style) string {
if fn.Family != "" {
return fn.Family
}
return tsty.FontFamily(fn.Style(tsty))
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package text
import (
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/colors"
"cogentcore.org/core/colors/gradient"
"cogentcore.org/core/enums"
"cogentcore.org/core/styles/styleprops"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/rich"
)
// FromProperties sets style field values based on the given property list.
func (ts *Style) FromProperties(parent *Style, properties map[string]any, ctxt colors.Context) {
for key, val := range properties {
if len(key) == 0 {
continue
}
if key[0] == '#' || key[0] == '.' || key[0] == ':' || key[0] == '_' {
continue
}
ts.FromProperty(parent, key, val, ctxt)
}
}
// FromProperty sets style field values based on the given property key and value.
func (ts *Style) FromProperty(parent *Style, key string, val any, cc colors.Context) {
if sfunc, ok := styleFuncs[key]; ok {
if parent != nil {
sfunc(ts, key, val, parent, cc)
} else {
sfunc(ts, key, val, nil, cc)
}
return
}
}
// styleFuncs are functions for styling the text.Style object.
var styleFuncs = map[string]styleprops.Func{
"text-align": AlignProperty(func(obj *Style) enums.EnumSetter { return &obj.Align }),
"text-vertical-align": styleprops.Enum(Start,
func(obj *Style) enums.EnumSetter { return &obj.AlignV }),
// note: text-style reads the font-size setting for regular units cases.
"font-size": styleprops.Units(units.Value{},
func(obj *Style) *units.Value { return &obj.FontSize }),
"line-height": styleprops.FloatProportion(float32(1.3),
func(obj *Style) *float32 { return &obj.LineHeight }),
"line-spacing": styleprops.FloatProportion(float32(1.3),
func(obj *Style) *float32 { return &obj.LineHeight }),
"para-spacing": styleprops.FloatProportion(float32(1.5),
func(obj *Style) *float32 { return &obj.ParaSpacing }),
"white-space": styleprops.Enum(WrapAsNeeded,
func(obj *Style) enums.EnumSetter { return &obj.WhiteSpace }),
"direction": styleprops.Enum(rich.LTR,
func(obj *Style) enums.EnumSetter { return &obj.Direction }),
"text-indent": styleprops.Units(units.Value{},
func(obj *Style) *units.Value { return &obj.Indent }),
"text-hanging": styleprops.Units(units.Value{},
func(obj *Style) *units.Value { return &obj.Hanging }),
"tab-size": styleprops.Int(int(4),
func(obj *Style) *int { return &obj.TabSize }),
"select-color": func(obj any, key string, val any, parent any, cc colors.Context) {
fs := obj.(*Style)
if inh, init := styleprops.InhInit(val, parent); inh || init {
if inh {
fs.SelectColor = parent.(*Style).SelectColor
} else if init {
fs.SelectColor = colors.Scheme.Select.Container
}
return
}
fs.SelectColor = errors.Log1(gradient.FromAny(val, cc))
},
"highlight-color": func(obj any, key string, val any, parent any, cc colors.Context) {
fs := obj.(*Style)
if inh, init := styleprops.InhInit(val, parent); inh || init {
if inh {
fs.HighlightColor = parent.(*Style).HighlightColor
} else if init {
fs.HighlightColor = colors.Scheme.Warn.Container
}
return
}
fs.HighlightColor = errors.Log1(gradient.FromAny(val, cc))
},
}
// ToProperties sets map[string]any properties based on non-default style values.
// properties map must be non-nil.
func (ts *Style) ToProperties(sty *rich.Style, p map[string]any) {
if ts.FontSize.Unit != units.UnitDp || ts.FontSize.Value != 16 || sty.Size != 1 {
sz := ts.FontSize
sz.Value *= sty.Size
p["font-size"] = sz.StringCSS()
}
if sty.Family == rich.Custom && ts.CustomFont != "" {
p["font-family"] = ts.CustomFont
}
if sty.Slant != rich.SlantNormal {
p["font-style"] = sty.Slant.String()
}
if sty.Weight != rich.Normal {
p["font-weight"] = sty.Weight.String()
}
if sty.Stretch != rich.StretchNormal {
p["font-stretch"] = sty.Stretch.String()
}
if dstr := sty.Decoration.String(); dstr != "" {
p["text-decoration"] = dstr
} else {
p["text-decoration"] = "none"
}
if ts.Align != Start {
p["text-align"] = ts.Align.String()
}
if ts.AlignV != Start {
p["text-vertical-align"] = ts.AlignV.String()
}
if ts.LineHeight != 1.3 {
p["line-height"] = reflectx.ToString(ts.LineHeight)
}
if ts.WhiteSpace != WrapAsNeeded {
p["white-space"] = ts.WhiteSpace.String()
}
if ts.Direction != rich.LTR {
p["direction"] = ts.Direction.String()
}
if ts.TabSize != 4 {
p["tab-size"] = reflectx.ToString(ts.TabSize)
}
p["fill"] = colors.AsHex(ts.FillColor(sty))
if sc := sty.StrokeColor(); sc != nil {
p["stroke-color"] = colors.AsHex(sc)
}
if ts.SelectColor != nil {
p["select-color"] = colors.AsHex(colors.ToUniform(ts.SelectColor))
}
if ts.HighlightColor != nil {
p["highlight-color"] = colors.AsHex(colors.ToUniform(ts.HighlightColor))
}
}
// AlignProperty returns the style function of the text-align property of
// the given field of the alignment of text, of type [Aligns], whose initial
// value is [Start], and for which the CSS values left and right are
// [Start] and [End], as in the default left-to-right direction.
func AlignProperty[T any](getField func(obj *T) enums.EnumSetter) styleprops.Func {
f := styleprops.Enum(Start, getField)
return func(obj any, key string, val any, parent any, cc colors.Context) {
if s, ok := val.(string); ok {
switch s {
case "left":
val = "start"
case "right":
val = "end"
}
}
f(obj, key, val, parent, cc)
}
}
// Copyright (c) 2020, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package text
// EditorSettings contains text editor settings.
type EditorSettings struct { //types:add
// size of a tab, in chars; also determines indent level for space indent
TabSize int `default:"4"`
// use spaces for indentation, otherwise tabs
SpaceIndent bool
// wrap lines at word boundaries; otherwise long lines scroll off the end
WordWrap bool `default:"true"`
// whether to show line numbers
LineNumbers bool `default:"true"`
// use the completion system to suggest options while typing
Completion bool `default:"true"`
// suggest corrections for unknown words while typing
SpellCorrect bool `default:"true"`
// automatically indent lines when enter, tab, }, etc pressed
AutoIndent bool `default:"true"`
// use emacs-style undo, where after a non-undo command, all the current undo actions are added to the undo stack, such that a subsequent undo is actually a redo
EmacsUndo bool
// colorize the background according to nesting depth
DepthColor bool `default:"true"`
}
func (es *EditorSettings) Defaults() {
es.TabSize = 4
es.SpaceIndent = false
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package text provides the styles of the layout of text, such as its
// alignment, line height, and white space, and the settings of text editors.
package text
import (
"image"
"image/color"
"cogentcore.org/core/colors"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/rich"
)
//go:generate core generate
// IMPORTANT: any changes here must be updated in props.go
// note: the go-text shaping framework does not support letter spacing
// or word spacing. These are uncommonly adjusted and not compatible with
// internationalized text in any case.
// todo: bidi override?
// Style is used for text layout styling.
// Most of these are inherited
type Style struct { //types:add
// Align specifies how to align text along the default direction (inherited).
// This *only* applies to the text within its containing element,
// and is relevant only for multi-line text.
Align Aligns
// AlignV specifies "vertical" (orthogonal to default direction)
// alignment of text (inherited).
// This *only* applies to the text within its containing element:
// if that element does not have a specified size
// that is different from the text size, then this has *no effect*.
AlignV Aligns
// FontSize is the default font size. The rich text styling specifies
// sizes relative to this value, with the normal text size factor = 1.
// In the [styles.Style.Text] context, this is copied from [styles.Font.Size].
FontSize units.Value
// LineHeight is a multiplier on the default font size for spacing between lines.
// If there are larger font elements within a line, they will be accommodated, with
// the same amount of total spacing added above that maximum size as if it was all
// the same height. The default of 1.3 represents standard "single spaced" text.
LineHeight float32 `default:"1.3"`
// ParaSpacing is the line spacing between paragraphs (inherited).
// This will be copied from [Style.Margin] if that is non-zero,
// or can be set directly. Like [LineHeight], this is a multiplier on
// the default font size.
ParaSpacing float32 `default:"1.5"`
// WhiteSpace (not inherited) specifies how white space is processed,
// and how lines are wrapped. If set to WhiteSpaceNormal (default) lines are wrapped.
// See info about interactions with Grow.X setting for this and the NoWrap case.
WhiteSpace WhiteSpaces
// LineClamp (not inherited), if positive, is the most lines that the
// text has: the text after them is cut, and the last line ends with an
// ellipsis (…), as the -webkit-line-clamp property of CSS.
LineClamp int
// Ellipsis (not inherited) is whether text that does not wrap and is
// wider than its box is cut to fit in it, ending with an ellipsis (…),
// as text-overflow: ellipsis in CSS.
Ellipsis bool
// Direction specifies the default text direction, which can be overridden if the
// unicode text is typically written in a different direction.
Direction rich.Directions
// Indent specifies how much to indent the first line in a paragraph (inherited).
Indent units.Value
// Hanging specifies how much to indent all but the first line
// in a paragraph (inherited).
Hanging units.Value
// TabSize specifies the tab size, in number of characters (inherited).
TabSize int
// Color is the default font fill color, used for inking fonts unless otherwise
// specified in the [rich.Style].
Color color.Color
// SelectColor is the color to use for the background region of selected text (inherited).
SelectColor image.Image
// HighlightColor is the color to use for the background region of highlighted text (inherited).
HighlightColor image.Image
// CustomFont specifies the Custom font name for rich.Style.Family = Custom.
CustomFont rich.FontName
}
func NewStyle() *Style {
s := &Style{}
s.Defaults()
return s
}
func (ts *Style) Defaults() {
ts.Align = Start
ts.AlignV = Start
ts.FontSize.Dp(16)
ts.LineHeight = 1.3
ts.ParaSpacing = 1.5
ts.Direction = rich.LTR
ts.TabSize = 4
ts.Color = colors.ToUniform(colors.Scheme.OnSurface)
ts.SelectColor = colors.Scheme.Select.Container
ts.HighlightColor = colors.Scheme.Warn.Container
}
// ToDots runs ToDots on unit values, to compile down to raw pixels
func (ts *Style) ToDots(uc *units.Context) {
ts.FontSize.ToDots(uc)
ts.FontSize.Dots = math32.Round(ts.FontSize.Dots)
ts.Indent.ToDots(uc)
ts.Hanging.ToDots(uc)
}
// InheritFields from parent
func (ts *Style) InheritFields(parent *Style) {
ts.Align = parent.Align
ts.AlignV = parent.AlignV
ts.LineHeight = parent.LineHeight
ts.ParaSpacing = parent.ParaSpacing
// ts.WhiteSpace = par.WhiteSpace // todo: we can't inherit this b/c label base default then gets overwritten
ts.Direction = parent.Direction
ts.Indent = parent.Indent
ts.Hanging = parent.Hanging
ts.TabSize = parent.TabSize
ts.SelectColor = parent.SelectColor
ts.HighlightColor = parent.HighlightColor
}
// FontHeight returns the effective font height based on
// FontSize * [rich.Style] Size multiplier.
func (ts *Style) FontHeight(sty *rich.Style) float32 {
return math32.Round(ts.FontSize.Dots * sty.Size)
}
// FillColor returns the effective text fill color (main color)
// using any special setting in the given [rich.Style], falling back
// on the Color setting on this text style.
func (ts *Style) FillColor(sty *rich.Style) color.Color {
fc := sty.FillColor()
if fc != nil {
return fc
}
return ts.Color
}
// LineHeightDots returns the effective line height in dots (actual pixels)
// as FontHeight * LineHeight
func (ts *Style) LineHeightDots(sty *rich.Style) float32 {
return math32.Ceil(ts.FontHeight(sty) * ts.LineHeight)
}
// AlignFactors gets basic text alignment factors
func (ts *Style) AlignFactors() (ax, ay float32) {
ax = ts.Align.Factor()
val := ts.AlignV
switch val {
case Start:
ay = 0.9 // todo: need to find out actual baseline
case Center:
ay = 0.45 // todo: determine if font is horiz or vert..
case End:
ay = -0.1 // todo: need actual baseline
}
return
}
// Aligns has the different types of alignment and justification for
// the text.
type Aligns int32 //enums:enum -transform kebab
const (
// Start aligns to the start (top, left) of text region.
Start Aligns = iota
// End aligns to the end (bottom, right) of text region.
End
// Center aligns to the center of text region.
Center
// Justify spreads words to cover the entire text region.
Justify
)
// Factor returns the alignment factor (0, .5, 1).
func (al Aligns) Factor() float32 {
switch al {
case Start:
return 0
case Center:
return 0.5
case End:
return 1
}
return 0
}
// WhiteSpaces determine how white space is processed and line wrapping
// occurs, either only at whitespace or within words.
type WhiteSpaces int32 //enums:enum -trim-prefix WhiteSpace
const (
// WrapAsNeeded means that all white space is collapsed to a single
// space, and text wraps at white space except if there is a long word
// that cannot fit on the next line, or would otherwise be truncated.
// To get full word wrapping to expand to all available space, you also
// need to set GrowWrap = true. Use the SetTextWrap convenience method
// to set both.
WrapAsNeeded WhiteSpaces = iota
// WrapAlways is like [WrapAsNeeded] except that line wrap will always
// occur within words if it allows more content to fit on a line.
WrapAlways
// WrapSpaceOnly means that line wrapping only occurs at white space,
// and never within words. This means that long words may then exceed
// the available space and will be truncated. White space is collapsed
// to a single space.
WrapSpaceOnly
// WrapNever means that lines are never wrapped to fit. If there is an
// explicit line or paragraph break, that will still result in
// a new line. In general you also don't want simple non-wrapping
// text labels to Grow (GrowWrap = false). Use the SetTextWrap method
// to set both. White space is collapsed to a single space.
WrapNever
// WhiteSpacePre means that whitespace is preserved, including line
// breaks. Text will only wrap on explicit line or paragraph breaks.
// This acts like the <pre> tag in HTML.
WhiteSpacePre
// WhiteSpacePreWrap means that whitespace is preserved.
// Text will wrap when necessary, and on line breaks
WhiteSpacePreWrap
)
// HasWordWrap returns true if value supports word wrap.
func (ws WhiteSpaces) HasWordWrap() bool {
switch ws {
case WrapNever, WhiteSpacePre:
return false
default:
return true
}
}
// KeepWhiteSpace returns true if value preserves existing whitespace.
func (ws WhiteSpaces) KeepWhiteSpace() bool {
switch ws {
case WhiteSpacePre, WhiteSpacePreWrap:
return true
default:
return false
}
}
// SetUnitContext sets the font-specific information in the given
// units.Context, based on the given styles. Just uses standardized
// fractions of the font size for the other less common units such as ex, ch.
func (ts *Style) SetUnitContext(uc *units.Context) {
fsz := math32.Round(ts.FontSize.Dots)
if fsz == 0 {
fsz = 16
}
uc.SetFont(fsz)
}
// TODO(text): ?
// UnicodeBidi determines the type of bidirectional text support.
// See https://pkg.go.dev/golang.org/x/text/unicode/bidi.
// type UnicodeBidi int32 //enums:enum -trim-prefix Bidi -transform kebab
//
// const (
// BidiNormal UnicodeBidi = iota
// BidiEmbed
// BidiBidiOverride
// )
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package textcore provides the widgets for viewing and editing text:
// [Base], [Editor], and the diff and twin editors built on them.
package textcore
//go:generate core generate
import (
"image"
"sync"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/colors"
"cogentcore.org/core/core"
"cogentcore.org/core/cursors"
"cogentcore.org/core/events"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/highlighting"
"cogentcore.org/core/text/lines"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/shaped"
"cogentcore.org/core/text/text"
"cogentcore.org/core/text/textpos"
)
// TODO: move these into an editor settings object
var (
// Maximum amount of clipboard history to retain
clipboardHistoryMax = 100 // `default:"100" min:"0" max:"1000" step:"5"`
)
// Base is a widget with basic infrastructure for viewing and editing
// [lines.Lines] of monospaced text, used in [textcore.Editor] and
// terminal. There can be multiple Base widgets for each lines buffer.
//
// Use NeedsRender to drive an render update for any change that does
// not change the line-level layout of the text.
//
// All updating in the Base should be within a single goroutine,
// as it would require extensive protections throughout code otherwise.
type Base struct { //core:embedder
core.Frame
// Lines is the text lines content for this editor.
Lines *lines.Lines `set:"-" json:"-" xml:"-"`
// CursorWidth is the width of the cursor.
// This should be set in Stylers like all other style properties.
CursorWidth units.Value
// LineNumberColor is the color used for the side bar containing the line numbers.
// This should be set in Stylers like all other style properties.
LineNumberColor image.Image
// SelectColor is the color used for the user text selection background color.
// This should be set in Stylers like all other style properties.
SelectColor image.Image
// ErrorColor is the background color of the regions of the code errors
// of the text (see [Base.SetCodeErrors]).
// This should be set in Stylers like all other style properties.
ErrorColor image.Image
// HighlightColor is the color used for the text highlight background color (like in find).
// This should be set in Stylers like all other style properties.
HighlightColor image.Image
// CursorColor is the color used for the text editor cursor bar.
// This should be set in Stylers like all other style properties.
CursorColor image.Image
// AutoscrollOnInput scrolls the display to the end when Input events are received.
AutoscrollOnInput bool
// viewID is the unique id of the Lines view.
viewID int
// cursorOn is whether the cursor of this editor is on: started and not
// stopped (see [Base.toggleCursor]), so that it is started again when
// the sprites are removed, even if the editor is not focused (as when
// its cursor is shown with [Base.SetCursorShow]).
cursorOn bool
// charSize is the render size of one character (rune).
// Y = line height, X = total glyph advance.
charSize math32.Vector2
// visSizeAlloc is the Geom.Size.Alloc.Total subtracting extra space,
// available for rendering text lines and line numbers.
visSizeAlloc math32.Vector2
// lastVisSizeAlloc is the last visSizeAlloc used in laying out lines.
// It is used to trigger a new layout only when needed.
lastVisSizeAlloc math32.Vector2
// visSize is the height in lines and width in chars of the visible area.
visSize image.Point
// linesSize is the height in lines and width in chars of the Lines text area,
// (excluding line numbers), which can be larger than the visSize.
linesSize image.Point
// scrollPos is the position of the scrollbar, in units of lines of text.
// fractional scrolling is supported.
scrollPos float32
// hasLineNumbers indicates that this editor has line numbers
// (per [Editor] option)
hasLineNumbers bool
// lineNumberOffset is the horizontal offset in chars for the start of text
// after line numbers. This is 0 if no line numbers.
lineNumberOffset int
// totalSize is total size of all text, including line numbers,
// multiplied by charSize.
totalSize math32.Vector2
// lineNumberDigits is the number of line number digits needed.
lineNumberDigits int
// CursorPos is the current cursor position.
CursorPos textpos.Pos `set:"-" edit:"-" json:"-" xml:"-"`
// blinkOn oscillates between on and off for blinking.
blinkOn bool
// cursorMu is a mutex protecting cursor rendering, shared between blink and main code.
cursorMu sync.Mutex
// isScrolling is true when scrolling: prevents keeping current cursor position
// in view.
isScrolling bool
// cursorTarget is the target cursor position for externally set targets.
// It ensures that the target position is visible.
cursorTarget textpos.Pos
// composition is the state of text being composed with an input method.
composition composition
// cursorColumn is the desired cursor column, in cells, where the cursor
// was last when moved using left / right arrows.
// It is used when doing up / down to not always go to short line columns.
cursorColumn int
// posHistoryIndex is the current index within PosHistory.
posHistoryIndex int
// selectStart is the starting point for selection, which will either
// be the start or end of selected region depending on subsequent selection.
selectStart textpos.Pos
// SelectRegion is the current selection region.
SelectRegion textpos.Region `set:"-" edit:"-" json:"-" xml:"-"`
// previousSelectRegion is the previous selection region that was actually rendered.
// It is needed to update the render.
previousSelectRegion textpos.Region
// codeErrors are the code errors of the text (see [Base.SetCodeErrors]).
codeErrors []CodeError
// Highlights is a slice of regions representing the highlighted
// regions, e.g., for search results.
Highlights []textpos.Region `set:"-" edit:"-" json:"-" xml:"-"`
// scopelights is a slice of regions representing the highlighted
// regions specific to scope markers.
scopelights []textpos.Region
// InputPos, if set, returns the position at which text is input in a
// read-only editor that sends the text typed in it elsewhere, such as
// the cursor of a terminal, and whether text is input now. The text
// being composed with an input method (IME) is shown there.
InputPos func() (textpos.Pos, bool)
// LinkHandler handles link clicks.
// If it is nil, they are sent to the standard web URL handler.
LinkHandler func(tl *rich.Hyperlink)
// lineRenders are the cached rendered lines of text.
lineRenders []renderCache
// lineNoRenders are the cached rendered line numbers
lineNoRenders []renderCache
// tabRender is a shaped tab
tabRender *shaped.Lines
// selectMode is a boolean indicating whether to select text as the cursor moves.
selectMode bool
// lastWasTabAI indicates that last key was a Tab auto-indent
lastWasTabAI bool
// lastWasUndo indicates that last key was an undo
lastWasUndo bool
// targetSet indicates that the CursorTarget is set
targetSet bool
lastRecenter int
// autoInserted is the stack of closing brackets that were
// auto-inserted after the cursor on line autoInsertLine, which are
// typed over when typed right before them, so that typing the
// closing bracket does not duplicate it.
autoInserted []rune
autoInsertLine int
lastFilename string
}
func (ed *Base) WidgetValue() any { return ed.Lines.Text() }
func (ed *Base) SetWidgetValue(value any) error {
ed.Lines.SetString(reflectx.ToString(value))
return nil
}
func (ed *Base) Init() {
ed.Frame.Init()
ed.Styles.Font.Family = rich.Monospace // critical
ed.SetLines(lines.NewLines())
ed.Styler(func(s *styles.Style) {
s.SetAbilities(true, abilities.Activatable, abilities.Hoverable, abilities.Slideable, abilities.DoubleClickable, abilities.TripleClickable)
s.SetAbilities(!ed.IsReadOnly(), abilities.Focusable)
s.SetAbilities(false, abilities.ScrollableUnattended)
ed.CursorWidth.Dp(1)
ed.LineNumberColor = nil
ed.SelectColor = colors.Scheme.Select.Container
ed.HighlightColor = colors.Scheme.Warn.Container
ed.ErrorColor = colors.Scheme.Error.Container
ed.CursorColor = colors.Scheme.Primary.Base
s.Cursor = cursors.Text
s.VirtualKeyboard = styles.KeyboardMultiLine
// if core.SystemSettings.Base.WordWrap {
// s.Text.WhiteSpace = styles.WhiteSpacePreWrap
// } else {
// s.Text.WhiteSpace = styles.WhiteSpacePre
// }
s.Text.LineHeight = 1.3
s.Text.WhiteSpace = text.WrapNever
s.Font.Family = rich.Monospace
s.Grow.Set(1, 0)
s.Overflow.Set(styles.OverflowAuto) // absorbs all
s.Border.Radius = styles.BorderRadiusLarge
s.Margin.Zero()
s.Padding.Set(units.Em(0.5))
s.Align.Content = styles.Start
s.Align.Items = styles.Start
s.Text.Align = text.Start
s.Text.AlignV = text.Start
s.Text.TabSize = core.SystemSettings.Editor.TabSize
s.Color = colors.Scheme.OnSurface
s.Min.X.Em(10)
s.MaxBorder.Width.Set(units.Dp(2))
s.Background = colors.Scheme.SurfaceContainerLow
if s.IsReadOnly() {
s.Background = colors.Scheme.SurfaceContainer
}
// note: a blank background does NOT work for depth color rendering
if s.Is(states.Focused) {
s.StateLayer = 0
s.Border.Width.Set(units.Dp(2))
}
})
ed.OnClose(func(e events.Event) {
ed.editDone()
})
}
func (ed *Base) Destroy() {
ed.stopCursor()
// Our view is deleted so that its listeners, which use us,
// are not called anymore.
if ed.Lines != nil {
ed.Lines.DeleteView(ed.viewID)
ed.viewID = -1
}
ed.Frame.Destroy()
}
func (ed *Base) NumLines() int {
if ed.Lines != nil {
return ed.Lines.NumLines()
}
return 0
}
// editDone completes editing and copies the active edited text to the text;
// called when the return key is pressed or goes out of focus
func (ed *Base) editDone() {
if ed.Lines != nil {
ed.Lines.EditDone() // sends the change event
}
ed.clearSelected()
}
// reMarkup triggers a complete re-markup of the entire text --
// can do this when needed if the markup gets off due to multi-line
// formatting issues -- via Recenter key
func (ed *Base) reMarkup() {
if ed.Lines == nil {
return
}
ed.Lines.ReMarkup()
}
// IsNotSaved returns true if buffer was changed (edited) since last Save.
func (ed *Base) IsNotSaved() bool {
return ed.Lines != nil && ed.Lines.IsNotSaved()
}
// Clear resets all the text in the buffer for this editor.
func (ed *Base) Clear() {
if ed.Lines == nil {
return
}
ed.Lines.SetText([]byte{})
}
// resetState resets all the random state variables, when opening a new buffer etc
func (ed *Base) resetState() {
ed.SelectReset()
ed.Highlights = nil
ed.scopelights = nil
if ed.Lines == nil || ed.lastFilename != ed.Lines.Filename() { // don't reset if reopening..
ed.CursorPos = textpos.Pos{}
}
}
// SendInput sends the [events.Input] event, for fine-grained updates.
func (ed *Base) SendInput() {
ed.Send(events.Input)
}
// SendClose sends the [events.Close] event, when lines buffer is closed.
func (ed *Base) SendClose() {
ed.Send(events.Close)
}
// SetLines sets the [lines.Lines] that this is an editor of,
// creating a new view for this editor and connecting to events.
func (ed *Base) SetLines(ln *lines.Lines) *Base {
oldln := ed.Lines
if ed == nil || (ln != nil && oldln == ln) {
return ed
}
if oldln != nil {
oldln.DeleteView(ed.viewID)
ed.viewID = -1
}
ed.Lines = ln
ed.resetState()
if ln != nil {
ln.Settings.EditorSettings = core.SystemSettings.Editor
wd := ed.linesSize.X
if wd == 0 {
wd = 80
}
ed.viewID = ln.NewView(wd)
ln.OnChange(ed.viewID, func(e events.Event) {
ed.validateCursor() // could have changed with remarkup
ed.NeedsRender()
ed.SendChange()
})
ln.OnInput(ed.viewID, func(e events.Event) {
if ed.AutoscrollOnInput {
ed.SetCursorTarget(textpos.PosErr) // special code to go to end
}
ed.NeedsRender()
ed.SendInput()
})
// The markup is updated in the background, and then the
// listeners must have the lock of our scene. They only render
// us again, so they are skipped if our scene is not shown, so
// that a scene that is closing does not block the updates of the
// other views.
ln.SetAsyncRunner(ed.viewID, func(f func()) {
if !ed.AsyncLockIfShown() {
return
}
defer ed.AsyncUnlock()
f()
})
ln.OnVirtualText(ed.viewID, func(e events.Event) {
ed.NeedsRender()
})
ln.OnClose(ed.viewID, func(e events.Event) {
ed.SetLines(nil)
ed.SendClose()
})
phl := ln.PosHistoryLen()
if phl > 0 {
cp, _ := ln.PosHistoryAt(phl - 1)
ed.posHistoryIndex = phl - 1
ed.SetCursorShow(cp)
} else {
ed.SetCursorShow(textpos.Pos{})
}
}
ed.NeedsRender()
return ed
}
// styleBase applies the editor styles.
func (ed *Base) styleBase() {
if ed.NeedsRebuild() {
highlighting.UpdateFromTheme()
if ed.Lines != nil {
ed.Lines.SetHighlighting(core.AppearanceSettings.Highlighting)
}
}
ed.Frame.Style()
ed.CursorWidth.ToDots(&ed.Styles.UnitContext)
}
func (ed *Base) Style() {
ed.styleBase()
ed.styleSizes()
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package textcore
import (
"image"
"cogentcore.org/core/math32"
"cogentcore.org/core/text/textpos"
"cogentcore.org/core/text/token"
)
// CodeError is an error of the text of an editor at a region of it, such
// as an error of running the text as code, which [Base.SetCodeErrors]
// shows in the editor.
type CodeError struct {
// Region is the region of the text that the error is about.
Region textpos.Region
// Msg is the message of the error.
Msg string
}
// SetCodeErrors sets the errors of the text of the editor, such as those of
// running it as code, replacing any previous ones. Their regions are shown
// with the background color [Base.ErrorColor], and a dotted underline (the
// [token.Error] tag), and their messages are the tooltip of the editor at
// their regions. The regions follow the edits of the text. No errors
// clears them.
func (ed *Base) SetCodeErrors(errs ...CodeError) {
if ed.Lines != nil {
for _, ce := range ed.codeErrors {
reg := ed.Lines.AdjustRegion(ce.Region)
if !reg.IsNil() {
ed.Lines.RemoveTag(reg.Start, token.Error)
}
}
for i := range errs {
reg := &errs[i].Region
reg.TimeNow() // so that it can be adjusted for later edits
for ln := reg.Start.Line; ln <= reg.End.Line; ln++ {
st, end := 0, ed.Lines.LineLen(ln)
if ln == reg.Start.Line {
st = reg.Start.Char
}
if ln == reg.End.Line {
end = reg.End.Char
}
if end > st {
ed.Lines.AddTag(ln, st, end, token.Error)
}
}
}
}
ed.codeErrors = errs
ed.Restyle() // for the tooltip ability (see [Base.WidgetTooltip])
}
// CodeErrors returns the errors of the text of the editor
// (see [Base.SetCodeErrors]).
func (ed *Base) CodeErrors() []CodeError { return ed.codeErrors }
// codeErrorAt returns the error whose region contains the given text
// position, if any.
func (ed *Base) codeErrorAt(pos textpos.Pos) (CodeError, bool) {
for _, ce := range ed.codeErrors {
reg := ed.Lines.AdjustRegion(ce.Region)
if !reg.IsNil() && reg.Contains(pos) {
return ce, true
}
}
return CodeError{}, false
}
// WidgetTooltip returns the message of the code error at the given
// position, if any (see [Base.SetCodeErrors]), and otherwise the tooltip
// of the editor. Without a position (as when styling, to know whether
// the editor has a tooltip), it returns the message of the first error.
func (ed *Base) WidgetTooltip(pos image.Point) (string, image.Point) {
if ed.Lines != nil && len(ed.codeErrors) > 0 {
if pos.X < 0 {
return ed.codeErrors[0].Msg, pos
}
tp := ed.PixelToCursor(pos.Sub(ed.Geom.ContentBBox.Min))
if ce, ok := ed.codeErrorAt(tp); ok {
return ce.Msg, pos
}
}
return ed.Frame.WidgetTooltip(pos)
}
// renderCodeErrors renders the backgrounds of the regions of the code
// errors (see [Base.SetCodeErrors]), in [Base.ErrorColor]. It must not
// be called with the Lines locked, as charStartPos locks them.
func (ed *Base) renderCodeErrors() {
if len(ed.codeErrors) == 0 || ed.ErrorColor == nil {
return
}
pc := &ed.Scene.Painter
var off math32.Vector2 // charStartPos is in the coordinates of the window
if ed.Scene != nil {
off = math32.FromPoint(ed.Scene.SceneGeom.Pos)
}
fill := func(start math32.Vector2, endX float32) {
if endX > start.X {
pc.FillBox(start.Sub(off), math32.Vec2(endX-start.X, ed.charSize.Y), ed.ErrorColor)
}
}
for _, ce := range ed.codeErrors {
reg := ed.Lines.AdjustRegion(ce.Region)
if reg.IsNil() {
continue
}
for ln := reg.Start.Line; ln <= reg.End.Line; ln++ {
st, end := 0, ed.Lines.LineLen(ln)
if ln == reg.Start.Line {
st = reg.Start.Char
}
if ln == reg.End.Line {
end = min(reg.End.Char, end)
}
if end <= st {
continue
}
// A rectangle for each visual line of the region, which can wrap.
rowStart := ed.charStartPos(textpos.Pos{Line: ln, Char: st})
for c := st + 1; c <= end; c++ {
p := ed.charStartPos(textpos.Pos{Line: ln, Char: c})
switch {
case p.Y != rowStart.Y: // c starts a new visual line
prev := ed.Lines.PosToView(ed.viewID, textpos.Pos{Line: ln, Char: c - 1})
prev.Char++ // the end of the char, which can be wide
fill(rowStart, ed.viewCharStartPos(prev).X)
rowStart = p
case c == end:
fill(rowStart, p.X)
}
}
}
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package textcore
import (
"fmt"
"strings"
"unicode/utf8"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/text/highlighting"
"cogentcore.org/core/text/lines"
"cogentcore.org/core/text/parse"
"cogentcore.org/core/text/parse/complete"
"cogentcore.org/core/text/parse/parser"
"cogentcore.org/core/text/textpos"
)
// setCompleter sets completion functions so that completions will
// automatically be offered as the user types
func (ed *Editor) setCompleter(data any, matchFun complete.MatchFunc, editFun complete.EditFunc,
lookupFun complete.LookupFunc) {
if ed.Complete != nil {
if ed.Complete.Context == data {
ed.Complete.MatchFunc = matchFun
ed.Complete.EditFunc = editFun
ed.Complete.LookupFunc = lookupFun
return
}
ed.deleteCompleter()
}
ed.Complete = core.NewComplete().SetContext(data).SetMatchFunc(matchFun).
SetEditFunc(editFun).SetLookupFunc(lookupFun)
ed.Complete.OnSelect(func(e events.Event) {
ed.completeText(ed.Complete.Completion)
})
// todo: what about CompleteExtend event type?
// TODO(kai/complete): clean this up and figure out what to do about Extend and only connecting once
// note: only need to connect once..
// tb.Complete.CompleteSig.ConnectOnly(func(dlg *core.Dialog) {
// tbf, _ := recv.Embed(TypeBuf).(*Buf)
// if sig == int64(core.CompleteSelect) {
// tbf.CompleteText(data.(string)) // always use data
// } else if sig == int64(core.CompleteExtend) {
// tbf.CompleteExtend(data.(string)) // always use data
// }
// })
}
func (ed *Editor) deleteCompleter() {
if ed.Complete == nil {
return
}
ed.Complete.Cancel()
ed.Complete = nil
}
// completeText edits the text using the string chosen from the completion menu
func (ed *Editor) completeText(s string) {
if s == "" {
return
}
// give the completer a chance to edit the completion before insert,
// also it return a number of runes past the cursor to delete
st := textpos.Pos{Line: ed.Complete.SrcLn, Char: 0}
en := textpos.Pos{Line: ed.Complete.SrcLn, Char: ed.Lines.LineLen(ed.Complete.SrcLn)}
var tbes string
tbe := ed.Lines.Region(st, en)
if tbe != nil {
tbes = string(tbe.ToBytes())
}
c := ed.Complete.GetCompletion(s)
pos := textpos.Pos{Line: ed.Complete.SrcLn, Char: ed.Complete.SrcCh}
ced := ed.Complete.EditFunc(ed.Complete.Context, tbes, ed.Complete.SrcCh, c, ed.Complete.Seed)
if ced.ForwardDelete > 0 {
delEn := textpos.Pos{Line: ed.Complete.SrcLn, Char: ed.Complete.SrcCh + ced.ForwardDelete}
ed.Lines.DeleteText(pos, delEn)
}
// now the normal completion insertion
// note: positions are in runes, not bytes
st = pos
st.Char -= utf8.RuneCountInString(ed.Complete.Seed)
ed.Lines.ReplaceText(st, pos, st, ced.NewText, lines.ReplaceNoMatchCase)
ep := st
ep.Char += utf8.RuneCountInString(ced.NewText) + ced.CursorAdjust
ed.SetCursorShow(ep)
}
// offerComplete pops up a menu of possible completions
func (ed *Editor) offerComplete() {
if ed.Complete == nil || ed.ISearch.On || ed.QReplace.On || ed.IsDisabled() {
return
}
ed.Complete.Cancel()
if !ed.Lines.Settings.Completion {
return
}
if ed.Lines.InComment(ed.CursorPos) || ed.Lines.InLitString(ed.CursorPos) {
return
}
ed.Complete.SrcLn = ed.CursorPos.Line
ed.Complete.SrcCh = ed.CursorPos.Char
st := textpos.Pos{Line: ed.CursorPos.Line, Char: 0}
en := textpos.Pos{Line: ed.CursorPos.Line, Char: ed.CursorPos.Char}
tbe := ed.Lines.Region(st, en)
var s string
if tbe != nil {
s = string(tbe.ToBytes())
s = strings.TrimLeft(s, " \t") // trim ' ' and '\t'
}
// count := ed.Buf.ByteOffs[ed.CursorPos.Line] + ed.CursorPos.Char
cpos := ed.charStartPos(ed.CursorPos).ToPoint() // physical location
cpos.X += 5
cpos.Y += 10
ed.Complete.SrcLn = ed.CursorPos.Line
ed.Complete.SrcCh = ed.CursorPos.Char
ed.Complete.Show(ed, cpos, s)
}
// CancelComplete cancels any pending completion.
// Call this when new events have moved beyond any prior completion scenario.
func (ed *Editor) CancelComplete() {
if ed.Lines == nil {
return
}
if ed.Complete == nil {
return
}
ed.Complete.Cancel()
}
// Lookup attempts to lookup symbol at current location, popping up a window
// if something is found.
func (ed *Editor) Lookup() { //types:add
if ed.ISearch.On || ed.QReplace.On || ed.IsDisabled() {
return
}
if ed.Complete == nil {
return
}
var ln int
var ch int
if ed.HasSelection() {
ln = ed.SelectRegion.Start.Line
if ed.SelectRegion.End.Line != ln {
return // no multiline selections for lookup
}
ch = ed.SelectRegion.End.Char
} else {
ln = ed.CursorPos.Line
if ed.Lines.IsWordEnd(ed.CursorPos) {
ch = ed.CursorPos.Char
} else {
ch = ed.Lines.WordAt(ed.CursorPos).End.Char
}
}
ed.Complete.SrcLn = ln
ed.Complete.SrcCh = ch
st := textpos.Pos{Line: ed.CursorPos.Line, Char: 0}
en := textpos.Pos{Line: ed.CursorPos.Line, Char: ch}
tbe := ed.Lines.Region(st, en)
var s string
if tbe != nil {
s = string(tbe.ToBytes())
s = strings.TrimLeft(s, " \t") // trim ' ' and '\t'
}
// count := ed.Buf.ByteOffs[ed.CursorPos.Line] + ed.CursorPos.Char
cpos := ed.charStartPos(ed.CursorPos).ToPoint() // physical location
cpos.X += 5
cpos.Y += 10
ed.Complete.Lookup(s, ed.CursorPos.Line, ed.CursorPos.Char, ed.Scene, cpos)
}
// completeParse uses [parse] symbols and language; the string is a line of text
// up to point where user has typed.
// The data must be the *FileState from which the language type is obtained.
func completeParse(data any, text string, posLine, posChar int) (md complete.Matches) {
sfs := data.(*parse.FileStates)
if sfs == nil {
// log.Printf("CompletePi: data is nil not FileStates or is nil - can't complete\n")
return md
}
lp := highlighting.ParseLanguage(sfs.Known)
if lp == nil {
return md
}
// note: must have this set to ture to allow viewing of AST
// must set it in pi/parse directly -- so it is changed in the fileparse too
parser.SetGUIActive(true) // note: this is key for debugging -- runs slower but makes the tree unique
md = lp.Lang.CompleteLine(sfs, text, textpos.Pos{Line: posLine, Char: posChar})
return md
}
// completeEditParse uses the selected completion to edit the text.
func completeEditParse(data any, text string, cursorPos int, comp complete.Completion, seed string) (ed complete.Edit) {
sfs := data.(*parse.FileStates)
if sfs == nil {
// log.Printf("CompleteEditPi: data is nil not FileStates or is nil - can't complete\n")
return ed
}
lp := highlighting.ParseLanguage(sfs.Known)
if lp == nil {
return ed
}
return lp.Lang.CompleteEdit(sfs, text, cursorPos, comp, seed)
}
// lookupParse uses [parse] symbols and language; the string is a line of text
// up to point where user has typed.
// The data must be the *FileState from which the language type is obtained.
func lookupParse(data any, txt string, posLine, posChar int) (ld complete.Lookup) {
sfs := data.(*parse.FileStates)
if sfs == nil {
// log.Printf("LookupPi: data is nil not FileStates or is nil - can't lookup\n")
return ld
}
lp := highlighting.ParseLanguage(sfs.Known)
if lp == nil {
return ld
}
// note: must have this set to ture to allow viewing of AST
// must set it in pi/parse directly -- so it is changed in the fileparse too
parser.SetGUIActive(true) // note: this is key for debugging -- runs slower but makes the tree unique
ld = lp.Lang.Lookup(sfs, txt, textpos.Pos{Line: posLine, Char: posChar})
if len(ld.Text) > 0 {
// todo:
// TextDialog(nil, "Lookup: "+txt, string(ld.Text))
return ld
}
if ld.Filename != "" {
tx := lines.FileRegionBytes(ld.Filename, ld.StLine, ld.EdLine, true, 10) // comments, 10 lines back max
prmpt := fmt.Sprintf("%v [%d:%d]", ld.Filename, ld.StLine, ld.EdLine)
_ = tx
_ = prmpt
// todo:
// TextDialog(nil, "Lookup: "+txt+": "+prmpt, string(tx))
return ld
}
return ld
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package textcore
import (
"image"
"cogentcore.org/core/core"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/text/textpos"
)
// cursorSpriteName is the name of the window sprite used for the cursor
var cursorSpriteName = "textcore.Base.Cursor"
// startCursor starts the cursor blinking and renders it.
// This must be called to update the cursor position -- is called in render.
func (ed *Base) startCursor() {
if ed == nil || ed.This == nil || !ed.IsVisible() {
return
}
if ed.IsReadOnly() || !ed.AbilityIs(abilities.Focusable) {
return
}
ed.toggleCursor(true)
}
// stopCursor stops the cursor from blinking
func (ed *Base) stopCursor() {
ed.toggleCursor(false)
}
// toggleSprite turns on or off the cursor sprite.
func (ed *Base) toggleCursor(on bool) {
ed.cursorOn = on
core.TextCursor(on, ed.AsWidget(), cursorSpriteName, ed.CursorWidth.Dots, ed.charSize.Y, ed.CursorColor, func() image.Point {
return core.TextCursorPoint(ed.charStartPos(ed.CursorPos))
})
}
// updateCursorPosition updates the position of the cursor.
func (ed *Base) updateCursorPosition() {
// An editor that is not focused updates its cursor only if it is on
// (as with [Base.SetCursorShow]) and no other widget has it now.
if !ed.StateIs(states.Focused) {
if !ed.cursorOn {
return
}
if owner := core.TextCursorOwner(ed.AsWidget(), cursorSpriteName); owner != nil && owner != ed.This {
return
}
}
if ed.IsReadOnly() { // no cursor, but there can be an InputPos
ed.updateTextInput()
return
}
sc := ed.Scene
if sc == nil || sc.Stage == nil || sc.Stage.Main == nil {
return
}
ms := sc.Stage.Main
ms.Sprites.Lock()
sp, ok := ms.Sprites.SpriteByNameNoLock(cursorSpriteName)
if ok {
sp.EventBBox.Min = core.TextCursorPoint(ed.charStartPos(ed.CursorPos))
}
ms.Sprites.Unlock()
// The sprites are removed when the scene is rebuilt or resized,
// so the cursor is started again.
if !ok {
ed.startCursor()
}
ed.updateTextInput()
}
// cursorBBox returns a bounding-box for a cursor at given position
func (ed *Base) cursorBBox(pos textpos.Pos) image.Rectangle {
cpos := ed.charStartPos(pos)
cbmin := cpos.SubScalar(ed.CursorWidth.Dots)
cbmax := cpos.AddScalar(ed.CursorWidth.Dots)
cbmax.Y += ed.charSize.Y
curBBox := image.Rectangle{cbmin.ToPointFloor(), cbmax.ToPointCeil()}
return curBBox
}
// Copyright (c) 2020, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package textcore
import (
"bytes"
"fmt"
"log/slog"
"os"
"strings"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/fileinfo/mimedata"
"cogentcore.org/core/base/fsx"
"cogentcore.org/core/base/stringsx"
"cogentcore.org/core/base/vcs"
"cogentcore.org/core/colors"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/text/lines"
"cogentcore.org/core/text/parse/lexer"
"cogentcore.org/core/text/textpos"
"cogentcore.org/core/text/token"
"cogentcore.org/core/tree"
)
// DiffFiles shows the diffs between this file as the A file, and other file as B file,
// in a DiffEditorDialog
func DiffFiles(ctx core.Widget, afile, bfile string) (*DiffEditor, error) {
ab, err := os.ReadFile(afile)
if err != nil {
slog.Error(err.Error())
return nil, err
}
bb, err := os.ReadFile(bfile)
if err != nil {
slog.Error(err.Error())
return nil, err
}
astr := stringsx.SplitLines(string(ab))
bstr := stringsx.SplitLines(string(bb))
dlg := DiffEditorDialog(ctx, "Diff File View", astr, bstr, afile, bfile, "", "")
return dlg, nil
}
// DiffEditorDialogFromRevs opens a dialog for displaying diff between file
// at two different revisions from given repository
// if empty, defaults to: A = current HEAD, B = current WC file.
// -1, -2 etc also work as universal ways of specifying prior revisions.
func DiffEditorDialogFromRevs(ctx core.Widget, repo vcs.Repo, file string, fbuf *lines.Lines, revA, revB string) (*DiffEditor, error) {
var astr, bstr []string
if revB == "" { // default to current file
if fbuf != nil {
bstr = fbuf.Strings(false)
} else {
fb, err := lines.FileBytes(file)
if err != nil {
core.ErrorDialog(ctx, err)
return nil, err
}
bstr = lines.BytesToLineStrings(fb, false) // don't add new lines
}
} else {
fb, err := repo.FileContents(file, revB)
if err != nil {
core.ErrorDialog(ctx, err)
return nil, err
}
bstr = lines.BytesToLineStrings(fb, false) // don't add new lines
}
if revA == "" { // FileContents returns the working copy for ""
revA = "HEAD"
}
fb, err := repo.FileContents(file, revA)
if err != nil {
core.ErrorDialog(ctx, err)
return nil, err
}
astr = lines.BytesToLineStrings(fb, false) // don't add new lines
return DiffEditorDialog(ctx, "DiffVcs: "+fsx.DirAndFile(file), astr, bstr, file, file, revA, revB), nil
}
// DiffEditorDialog opens a dialog for displaying diff between two files as line-strings
func DiffEditorDialog(ctx core.Widget, title string, astr, bstr []string, afile, bfile, arev, brev string) *DiffEditor {
d := core.NewBody("Diff editor")
d.SetTitle(title)
de := NewDiffEditor(d)
de.SetFileA(afile).SetFileB(bfile).SetRevisionA(arev).SetRevisionB(brev)
de.DiffStrings(astr, bstr)
d.AddTopBar(func(bar *core.Frame) {
tb := core.NewToolbar(bar)
de.toolbar = tb
tb.Maker(de.MakeToolbar)
})
d.NewWindow().SetContext(ctx).SetNewWindow(true).Run()
return de
}
// TextDialog opens a dialog for displaying text string
func TextDialog(ctx core.Widget, title, text string) *Editor {
d := core.NewBody(title)
ed := NewEditor(d)
ed.Styler(func(s *styles.Style) {
s.Grow.Set(1, 1)
})
ed.Lines.SetText([]byte(text))
d.AddBottomBar(func(bar *core.Frame) {
core.NewButton(bar).SetText("Copy to clipboard").SetIcon(icons.ContentCopy).
OnClick(func(e events.Event) {
d.Clipboard().Write(mimedata.NewText(text))
})
d.AddOK(bar)
})
d.RunWindowDialog(ctx)
return ed
}
// DiffEditor presents two side-by-side [Editor]s showing the differences
// between two files (represented as lines of strings).
type DiffEditor struct {
core.Frame
// first file name being compared
FileA string
// second file name being compared
FileB string
// revision for first file, if relevant
RevisionA string
// revision for second file, if relevant
RevisionB string
// [lines.Lines] for A showing the aligned edit view
linesA *lines.Lines
// [lines.Lines] for B showing the aligned edit view
linesB *lines.Lines
// aligned diffs records diff for aligned lines
alignD lines.Diffs
// diffs applied
diffs lines.DiffSelected
inInputEvent bool
toolbar *core.Toolbar
}
func (dv *DiffEditor) Init() {
dv.Frame.Init()
dv.linesA = lines.NewLines()
dv.linesB = lines.NewLines()
dv.linesA.Settings.LineNumbers = true
dv.linesB.Settings.LineNumbers = true
dv.Styler(func(s *styles.Style) {
s.Grow.Set(1, 1)
})
f := func(name string, buf *lines.Lines) {
tree.AddChildAt(dv, name, func(w *DiffTextEditor) {
w.SetLines(buf)
w.SetReadOnly(true)
w.Styler(func(s *styles.Style) {
s.Min.X.Ch(80)
s.Min.Y.Em(40)
})
w.On(events.Scroll, func(e events.Event) {
dv.syncEditors(events.Scroll, name)
})
w.On(events.Input, func(e events.Event) {
dv.syncEditors(events.Input, name)
})
})
}
f("text-a", dv.linesA)
f("text-b", dv.linesB)
}
func (dv *DiffEditor) updateToolbar() {
if dv.toolbar == nil {
return
}
dv.toolbar.Restyle()
}
// setFilenames sets the filenames and updates markup accordingly.
// Called in DiffStrings
func (dv *DiffEditor) setFilenames() {
dv.linesA.SetFilename(dv.FileA)
dv.linesB.SetFilename(dv.FileB)
dv.linesA.Stat()
dv.linesB.Stat()
}
// syncEditors synchronizes the text [Editor] scrolling and cursor positions
func (dv *DiffEditor) syncEditors(typ events.Types, name string) {
tva, tvb := dv.textEditors()
me, other := tva, tvb
if name == "text-b" {
me, other = tvb, tva
}
switch typ {
case events.Scroll:
other.isScrolling = true
other.updateScroll(me.scrollPos)
case events.Input:
if dv.inInputEvent {
return
}
dv.inInputEvent = true
other.SetCursorShow(me.CursorPos)
dv.inInputEvent = false
}
}
// nextDiff moves to next diff region
func (dv *DiffEditor) nextDiff(ab int) bool {
tva, tvb := dv.textEditors()
tv := tva
if ab == 1 {
tv = tvb
}
nd := len(dv.alignD)
curLn := tv.CursorPos.Line
di, df := dv.alignD.DiffForLine(curLn)
if di < 0 {
return false
}
for {
di++
if di >= nd {
return false
}
df = dv.alignD[di]
if df.Tag != 'e' {
break
}
}
tva.SetCursorTarget(textpos.Pos{Line: df.I1})
tvb.SetCursorTarget(textpos.Pos{Line: df.I1})
return true
}
// prevDiff moves to previous diff region
func (dv *DiffEditor) prevDiff(ab int) bool {
tva, tvb := dv.textEditors()
tv := tva
if ab == 1 {
tv = tvb
}
curLn := tv.CursorPos.Line
di, df := dv.alignD.DiffForLine(curLn)
if di < 0 {
return false
}
for {
di--
if di < 0 {
return false
}
df = dv.alignD[di]
if df.Tag != 'e' {
break
}
}
tva.SetCursorTarget(textpos.Pos{Line: df.I1})
tvb.SetCursorTarget(textpos.Pos{Line: df.I1})
return true
}
// saveAs saves A or B edits into given file.
// It checks for an existing file, prompts to overwrite or not.
func (dv *DiffEditor) saveAs(ab bool, filename core.Filename) {
if !errors.Log1(fsx.FileExists(string(filename))) {
dv.saveFile(ab, filename)
} else {
d := core.NewBody("File Exists, Overwrite?")
core.NewText(d).SetType(core.TextSupporting).SetText(fmt.Sprintf("File already exists, overwrite? File: %v", filename))
d.AddBottomBar(func(bar *core.Frame) {
d.AddCancel(bar)
d.AddOK(bar).OnClick(func(e events.Event) {
dv.saveFile(ab, filename)
})
})
d.RunDialog(dv)
}
}
// saveFile writes A or B edits to file, with no prompting, etc
func (dv *DiffEditor) saveFile(ab bool, filename core.Filename) error {
var txt string
if ab {
txt = strings.Join(dv.diffs.B.Edit, "\n")
} else {
txt = strings.Join(dv.diffs.A.Edit, "\n")
}
err := os.WriteFile(string(filename), []byte(txt), 0644)
if err != nil {
core.ErrorSnackbar(dv, err)
slog.Error(err.Error())
}
return err
}
// saveFileA saves the current state of file A to given filename
func (dv *DiffEditor) saveFileA(fname core.Filename) { //types:add
dv.saveAs(false, fname)
dv.updateToolbar()
}
// saveFileB saves the current state of file B to given filename
func (dv *DiffEditor) saveFileB(fname core.Filename) { //types:add
dv.saveAs(true, fname)
dv.updateToolbar()
}
// DiffStrings computes differences between two lines-of-strings and displays in
// DiffEditor.
func (dv *DiffEditor) DiffStrings(astr, bstr []string) {
dv.setFilenames()
dv.diffs.SetStringLines(astr, bstr)
dv.linesA.DeleteLineColor(-1)
dv.linesB.DeleteLineColor(-1)
del := colors.Scheme.Error.Base
ins := colors.Scheme.Success.Base
chg := colors.Scheme.Primary.Base
nd := len(dv.diffs.Diffs)
dv.alignD = make(lines.Diffs, nd)
var ab, bb [][]byte
absln := 0
bspc := []byte(" ")
for i, df := range dv.diffs.Diffs {
switch df.Tag {
case 'r':
di := df.I2 - df.I1
dj := df.J2 - df.J1
mx := max(di, dj)
ad := df
ad.I1 = absln
ad.I2 = absln + di
ad.J1 = absln
ad.J2 = absln + dj
dv.alignD[i] = ad
for i := range mx {
dv.linesA.SetLineColor(absln+i, chg)
dv.linesB.SetLineColor(absln+i, chg)
blen := 0
alen := 0
if i < di {
aln := []byte(astr[df.I1+i])
alen = len(aln)
ab = append(ab, aln)
}
if i < dj {
bln := []byte(bstr[df.J1+i])
blen = len(bln)
bb = append(bb, bln)
} else {
bb = append(bb, bytes.Repeat(bspc, alen))
}
if i >= di {
ab = append(ab, bytes.Repeat(bspc, blen))
}
}
absln += mx
case 'd':
di := df.I2 - df.I1
ad := df
ad.I1 = absln
ad.I2 = absln + di
ad.J1 = absln
ad.J2 = absln + di
dv.alignD[i] = ad
for i := range di {
dv.linesA.SetLineColor(absln+i, ins)
dv.linesB.SetLineColor(absln+i, del)
aln := []byte(astr[df.I1+i])
alen := len(aln)
ab = append(ab, aln)
bb = append(bb, bytes.Repeat(bspc, alen))
}
absln += di
case 'i':
dj := df.J2 - df.J1
ad := df
ad.I1 = absln
ad.I2 = absln + dj
ad.J1 = absln
ad.J2 = absln + dj
dv.alignD[i] = ad
for i := range dj {
dv.linesA.SetLineColor(absln+i, del)
dv.linesB.SetLineColor(absln+i, ins)
bln := []byte(bstr[df.J1+i])
blen := len(bln)
bb = append(bb, bln)
ab = append(ab, bytes.Repeat(bspc, blen))
}
absln += dj
case 'e':
di := df.I2 - df.I1
ad := df
ad.I1 = absln
ad.I2 = absln + di
ad.J1 = absln
ad.J2 = absln + di
dv.alignD[i] = ad
for i := range di {
ab = append(ab, []byte(astr[df.I1+i]))
bb = append(bb, []byte(bstr[df.J1+i]))
}
absln += di
}
}
dv.linesA.SetTextLines(ab) // don't copy
dv.linesB.SetTextLines(bb) // don't copy
dv.tagWordDiffs()
dv.linesA.ReMarkup()
dv.linesB.ReMarkup()
}
// tagWordDiffs goes through replace diffs and tags differences at the
// word level between the two regions.
func (dv *DiffEditor) tagWordDiffs() {
for _, df := range dv.alignD {
if df.Tag != 'r' {
continue
}
di := df.I2 - df.I1
dj := df.J2 - df.J1
mx := max(di, dj)
stln := df.I1
for i := range mx {
ln := stln + i
ra := dv.linesA.Line(ln)
rb := dv.linesB.Line(ln)
lna := lexer.RuneFields(ra)
lnb := lexer.RuneFields(rb)
fla := lna.RuneStrings(ra)
flb := lnb.RuneStrings(rb)
nab := max(len(fla), len(flb))
ldif := lines.DiffLines(fla, flb)
ndif := len(ldif)
if nab > 25 && ndif > nab/2 { // more than half of big diff -- skip
continue
}
for _, ld := range ldif {
switch ld.Tag {
case 'r':
sla := lna[ld.I1]
ela := lna[ld.I2-1]
dv.linesA.AddTag(ln, sla.Start, ela.End, token.TextStyleError)
slb := lnb[ld.J1]
elb := lnb[ld.J2-1]
dv.linesB.AddTag(ln, slb.Start, elb.End, token.TextStyleError)
case 'd':
sla := lna[ld.I1]
ela := lna[ld.I2-1]
dv.linesA.AddTag(ln, sla.Start, ela.End, token.TextStyleDeleted)
case 'i':
slb := lnb[ld.J1]
elb := lnb[ld.J2-1]
dv.linesB.AddTag(ln, slb.Start, elb.End, token.TextStyleDeleted)
}
}
}
}
}
// applyDiff applies change from the other lines to the lines for given file
// name, from diff that includes given line.
func (dv *DiffEditor) applyDiff(ab int, line int) bool {
tva, tvb := dv.textEditors()
tv := tva
if ab == 1 {
tv = tvb
}
if line < 0 {
line = tv.CursorPos.Line
}
di, df := dv.alignD.DiffForLine(line)
if di < 0 || df.Tag == 'e' {
return false
}
if ab == 0 {
dv.linesA.SetUndoOn(true)
// srcLen := len(dv.BufB.Lines[df.J2])
spos := textpos.Pos{Line: df.I1, Char: 0}
epos := textpos.Pos{Line: df.I2, Char: 0}
src := dv.linesB.Region(spos, epos)
dv.linesA.DeleteText(spos, epos)
dv.linesA.InsertTextLines(spos, src.Text) // we always just copy, is blank for delete..
dv.diffs.BtoA(di)
} else {
dv.linesB.SetUndoOn(true)
spos := textpos.Pos{Line: df.J1, Char: 0}
epos := textpos.Pos{Line: df.J2, Char: 0}
src := dv.linesA.Region(spos, epos)
dv.linesB.DeleteText(spos, epos)
dv.linesB.InsertTextLines(spos, src.Text)
dv.diffs.AtoB(di)
}
dv.updateToolbar()
return true
}
// undoDiff undoes last applied change, if any.
func (dv *DiffEditor) undoDiff(ab int) error {
tva, tvb := dv.textEditors()
if ab == 1 {
if !dv.diffs.B.Undo() {
err := errors.New("No more edits to undo")
core.ErrorSnackbar(dv, err)
return err
}
tvb.undo()
} else {
if !dv.diffs.A.Undo() {
err := errors.New("No more edits to undo")
core.ErrorSnackbar(dv, err)
return err
}
tva.undo()
}
return nil
}
func (dv *DiffEditor) MakeToolbar(p *tree.Plan) {
txta := "A: " + fsx.DirAndFile(dv.FileA)
if dv.RevisionA != "" {
txta += ": " + dv.RevisionA
}
tree.Add(p, func(w *core.Text) {
w.SetText(txta)
})
tree.Add(p, func(w *core.Button) {
w.SetText("Next").SetIcon(icons.KeyboardArrowDown).SetTooltip("move down to next diff region")
w.OnClick(func(e events.Event) {
dv.nextDiff(0)
})
w.Styler(func(s *styles.Style) {
s.SetState(len(dv.alignD) <= 1, states.Disabled)
})
})
tree.Add(p, func(w *core.Button) {
w.SetText("Prev").SetIcon(icons.KeyboardArrowUp).SetTooltip("move up to previous diff region")
w.OnClick(func(e events.Event) {
dv.prevDiff(0)
})
w.Styler(func(s *styles.Style) {
s.SetState(len(dv.alignD) <= 1, states.Disabled)
})
})
tree.Add(p, func(w *core.Button) {
w.SetText("A <- B").SetIcon(icons.ContentCopy).SetTooltip("for current diff region, apply change from corresponding version in B, and move to next diff")
w.OnClick(func(e events.Event) {
dv.applyDiff(0, -1)
dv.nextDiff(0)
})
w.Styler(func(s *styles.Style) {
s.SetState(len(dv.alignD) <= 1, states.Disabled)
})
})
tree.Add(p, func(w *core.Button) {
w.SetText("Undo").SetIcon(icons.Undo).SetTooltip("undo last diff apply action (A <- B)")
w.OnClick(func(e events.Event) {
dv.undoDiff(0)
})
w.Styler(func(s *styles.Style) {
s.SetState(!dv.linesA.IsNotSaved(), states.Disabled)
})
})
tree.Add(p, func(w *core.Button) {
w.SetText("Save").SetIcon(icons.Save).SetTooltip("save edited version of file with the given; prompts for filename")
w.OnClick(func(e events.Event) {
fb := core.NewSoloFuncButton(w).SetFunc(dv.saveFileA)
fb.Args[0].SetValue(core.Filename(dv.FileA))
fb.CallFunc()
})
w.Styler(func(s *styles.Style) {
s.SetState(!dv.linesA.IsNotSaved(), states.Disabled)
})
})
tree.Add(p, func(w *core.Separator) {})
txtb := "B: " + fsx.DirAndFile(dv.FileB)
if dv.RevisionB != "" {
txtb += ": " + dv.RevisionB
}
tree.Add(p, func(w *core.Text) {
w.SetText(txtb)
})
tree.Add(p, func(w *core.Button) {
w.SetText("Next").SetIcon(icons.KeyboardArrowDown).SetTooltip("move down to next diff region")
w.OnClick(func(e events.Event) {
dv.nextDiff(1)
})
w.Styler(func(s *styles.Style) {
s.SetState(len(dv.alignD) <= 1, states.Disabled)
})
})
tree.Add(p, func(w *core.Button) {
w.SetText("Prev").SetIcon(icons.KeyboardArrowUp).SetTooltip("move up to previous diff region")
w.OnClick(func(e events.Event) {
dv.prevDiff(1)
})
w.Styler(func(s *styles.Style) {
s.SetState(len(dv.alignD) <= 1, states.Disabled)
})
})
tree.Add(p, func(w *core.Button) {
w.SetText("A -> B").SetIcon(icons.ContentCopy).SetTooltip("for current diff region, apply change from corresponding version in A, and move to next diff")
w.OnClick(func(e events.Event) {
dv.applyDiff(1, -1)
dv.nextDiff(1)
})
w.Styler(func(s *styles.Style) {
s.SetState(len(dv.alignD) <= 1, states.Disabled)
})
})
tree.Add(p, func(w *core.Button) {
w.SetText("Undo").SetIcon(icons.Undo).SetTooltip("undo last diff apply action (A -> B)")
w.OnClick(func(e events.Event) {
dv.undoDiff(1)
})
w.Styler(func(s *styles.Style) {
s.SetState(!dv.linesB.IsNotSaved(), states.Disabled)
})
})
tree.Add(p, func(w *core.Button) {
w.SetText("Save").SetIcon(icons.Save).SetTooltip("save edited version of file -- prompts for filename -- this will convert file back to its original form (removing side-by-side alignment) and end the diff editing function")
w.OnClick(func(e events.Event) {
fb := core.NewSoloFuncButton(w).SetFunc(dv.saveFileB)
fb.Args[0].SetValue(core.Filename(dv.FileB))
fb.CallFunc()
})
w.Styler(func(s *styles.Style) {
s.SetState(!dv.linesB.IsNotSaved(), states.Disabled)
})
})
}
func (dv *DiffEditor) textEditors() (*DiffTextEditor, *DiffTextEditor) {
av := dv.Child(0).(*DiffTextEditor)
bv := dv.Child(1).(*DiffTextEditor)
return av, bv
}
//////// DiffTextEditor
// DiffTextEditor supports double-click based application of edits from one
// lines to the other.
type DiffTextEditor struct {
Editor
}
func (ed *DiffTextEditor) Init() {
ed.Editor.Init()
ed.Styler(func(s *styles.Style) {
s.Grow.Set(1, 1)
})
ed.OnDoubleClick(func(e events.Event) {
pt := ed.PointToRelPos(e.Pos())
if pt.X >= 0 && pt.X < int(ed.LineNumberPixels()) {
newPos := ed.PixelToCursor(pt)
ln := newPos.Line
dv := ed.diffEditor()
if dv != nil && ed.Lines != nil {
if ed.Name == "text-a" {
dv.applyDiff(0, ln)
} else {
dv.applyDiff(1, ln)
}
}
e.SetHandled()
return
}
})
}
func (ed *DiffTextEditor) diffEditor() *DiffEditor {
return tree.ParentByType[*DiffEditor](ed)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package textcore
import (
"fmt"
"image"
"unicode"
"cogentcore.org/core/base/fileinfo"
"cogentcore.org/core/base/indent"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/core"
"cogentcore.org/core/cursors"
"cogentcore.org/core/events"
"cogentcore.org/core/events/key"
"cogentcore.org/core/icons"
"cogentcore.org/core/keymap"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/text/lines"
"cogentcore.org/core/text/parse"
"cogentcore.org/core/text/parse/lexer"
"cogentcore.org/core/text/textpos"
)
// Editor is a widget for editing multiple lines of complicated text (as compared to
// [core.TextField] for a single line of simple text). The Editor is driven by a
// [lines.Lines] buffer which contains all the text, and manages all the edits,
// sending update events out to the editors.
//
// Use NeedsRender to drive an render update for any change that does
// not change the line-level layout of the text.
//
// Multiple editors can be attached to a given buffer. All updating in the
// Editor should be within a single goroutine, as it would require
// extensive protections throughout code otherwise.
type Editor struct { //core:embedder
Base
// ISearch is the interactive search data.
ISearch ISearch `set:"-" edit:"-" json:"-" xml:"-"`
// QReplace is the query replace data.
QReplace QReplace `set:"-" edit:"-" json:"-" xml:"-"`
// Complete is the functions and data for text completion.
Complete *core.Complete `json:"-" xml:"-"`
// spell is the functions and data for spelling correction.
spell *spellCheck
// curFilename is the current filename from Lines. Used to detect changed file.
curFilename string
}
func (ed *Editor) Init() {
ed.Base.Init()
ed.editorSetLines(ed.Lines)
ed.setSpell()
ed.AddContextMenu(ed.contextMenu)
ed.handleKeyChord()
ed.handleMouse()
ed.handleLinkCursor()
ed.handleFocus()
}
// UpdateNewFile checks if there is a new file in the Lines editor and updates
// any relevant editor settings accordingly.
func (ed *Editor) UpdateNewFile() {
ln := ed.Lines
if ln == nil {
ed.curFilename = ""
ed.viewID = -1
return
}
fnm := ln.Filename()
if ed.curFilename == fnm {
return
}
ed.curFilename = fnm
if ln.FileInfo().Known != fileinfo.Unknown {
_, ps := ln.ParseState()
ed.setCompleter(ps, completeParse, completeEditParse, lookupParse)
} else {
ed.deleteCompleter()
}
}
// SetLines sets the [lines.Lines] that this is an editor of,
// creating a new view for this editor and connecting to events.
func (ed *Editor) SetLines(ln *lines.Lines) *Editor {
ed.Base.SetLines(ln)
ed.editorSetLines(ln)
return ed
}
// editorSetLines does the editor specific part of SetLines.
func (ed *Editor) editorSetLines(ln *lines.Lines) {
if ln == nil {
ed.curFilename = ""
return
}
ln.OnChange(ed.viewID, func(e events.Event) {
ed.UpdateNewFile()
})
ln.FileModPromptFunc = func() {
FileModPrompt(ed.Scene, ln)
}
}
// SaveAs saves the current text into given file; does an editDone first to save edits
// and checks for an existing file; if it does exist then prompts to overwrite or not.
func (ed *Editor) SaveAs(filename core.Filename) { //types:add
ed.editDone()
SaveAs(ed.Scene, ed.Lines, string(filename), nil)
}
// Save saves the current text into the current filename associated with this buffer.
// Do NOT use this in an OnChange event handler as it emits a Change event! Use
// [Editor.SaveQuiet] instead.
func (ed *Editor) Save() error { //types:add
ed.editDone()
return Save(ed.Scene, ed.Lines)
}
// SaveQuiet saves the current text into the current filename associated with this buffer.
// This version does not emit a change event, so it is safe to use
// in an OnChange event handler, unlike [Editor.Save].
func (ed *Editor) SaveQuiet() error { //types:add
ed.clearSelected()
return Save(ed.Scene, ed.Lines)
}
// Close closes the lines viewed by this editor, prompting to save if there are changes.
// If afterFunc is non-nil, then it is called with the status of the user action.
func (ed *Editor) Close(afterFunc func(canceled bool)) bool {
return Close(ed.Scene, ed.Lines, afterFunc)
}
func (ed *Editor) handleFocus() {
ed.OnFocusLost(func(e events.Event) {
// the focused state is cleared by WidgetBase for all widgets,
// including read-only editors, which used to keep it
ed.SetState(false, states.Focused)
if !ed.IsReadOnly() && ed.AbilityIs(abilities.Focusable) {
ed.editDone()
}
ed.endComposition()
ed.ClearTextInput()
})
ed.OnFocus(func(e events.Event) {
ed.startCursor()
})
}
func (ed *Editor) handleKeyChord() {
ed.OnKeyChord(func(e events.Event) {
ed.keyInput(e)
})
ed.On(events.Composition, func(e events.Event) {
ed.compose(e.(*events.TextComposition))
e.SetHandled()
})
}
// shiftSelect sets the selection start if the shift key is down but wasn't on the last key move.
// If the shift key has been released the select region is set to textpos.Region{}
func (ed *Editor) shiftSelect(kt events.Event) {
hasShift := kt.HasAnyModifier(key.Shift)
if hasShift {
if ed.SelectRegion == (textpos.Region{}) {
ed.selectStart = ed.CursorPos
}
} else {
ed.SelectRegion = textpos.Region{}
}
}
// shiftSelectExtend updates the select region if the shift key is down and renders the selected lines.
// If the shift key is not down the previously selected text is rerendered to clear the highlight
func (ed *Editor) shiftSelectExtend(kt events.Event) {
hasShift := kt.HasAnyModifier(key.Shift)
if hasShift {
ed.selectRegionUpdate(ed.CursorPos)
}
}
// keyInput handles keyboard input into the text field and from the completion menu
func (ed *Editor) keyInput(e events.Event) {
ed.isScrolling = false
if core.DebugSettings.KeyEventTrace {
fmt.Printf("View KeyInput: %v\n", ed.Path())
}
kf := keymap.Of(e.KeyChord())
if e.IsHandled() {
return
}
if ed.Lines == nil || ed.Lines.NumLines() == 0 {
return
}
// cancelAll cancels search, completer, and..
cancelAll := func() {
ed.CancelComplete()
ed.cancelCorrect()
ed.iSearchCancel()
ed.qReplaceCancel()
ed.autoInserted = nil
}
if kf != keymap.Recenter { // always start at centering
ed.lastRecenter = 0
}
if kf != keymap.Undo && ed.lastWasUndo {
ed.Lines.EmacsUndoSave()
ed.lastWasUndo = false
}
gotTabAI := false // got auto-indent tab this time
// first all the keys that work for both inactive and active
switch kf {
case keymap.MoveRight:
cancelAll()
e.SetHandled()
ed.shiftSelect(e)
ed.cursorForward(1)
ed.shiftSelectExtend(e)
ed.iSpellKeyInput(e)
case keymap.WordRight:
cancelAll()
e.SetHandled()
ed.shiftSelect(e)
ed.cursorForwardWord(1)
ed.shiftSelectExtend(e)
case keymap.MoveLeft:
cancelAll()
e.SetHandled()
ed.shiftSelect(e)
ed.cursorBackward(1)
ed.shiftSelectExtend(e)
case keymap.WordLeft:
cancelAll()
e.SetHandled()
ed.shiftSelect(e)
ed.cursorBackwardWord(1)
ed.shiftSelectExtend(e)
case keymap.MoveUp:
cancelAll()
e.SetHandled()
ed.shiftSelect(e)
ed.cursorUp(1)
ed.shiftSelectExtend(e)
ed.iSpellKeyInput(e)
case keymap.MoveDown:
cancelAll()
e.SetHandled()
ed.shiftSelect(e)
ed.cursorDown(1)
ed.shiftSelectExtend(e)
ed.iSpellKeyInput(e)
case keymap.PageUp:
cancelAll()
e.SetHandled()
ed.shiftSelect(e)
ed.cursorPageUp(1)
ed.shiftSelectExtend(e)
case keymap.PageDown:
cancelAll()
e.SetHandled()
ed.shiftSelect(e)
ed.cursorPageDown(1)
ed.shiftSelectExtend(e)
case keymap.Home:
cancelAll()
e.SetHandled()
ed.shiftSelect(e)
ed.cursorLineStart()
ed.shiftSelectExtend(e)
case keymap.End:
cancelAll()
e.SetHandled()
ed.shiftSelect(e)
ed.cursorLineEnd()
ed.shiftSelectExtend(e)
case keymap.DocHome:
cancelAll()
e.SetHandled()
ed.shiftSelect(e)
ed.CursorStartDoc()
ed.shiftSelectExtend(e)
case keymap.DocEnd:
cancelAll()
e.SetHandled()
ed.shiftSelect(e)
ed.cursorEndDoc()
ed.shiftSelectExtend(e)
case keymap.Recenter:
cancelAll()
e.SetHandled()
ed.reMarkup()
ed.cursorRecenter()
case keymap.SelectMode:
cancelAll()
e.SetHandled()
ed.selectModeToggle()
case keymap.CancelSelect:
ed.CancelComplete()
e.SetHandled()
ed.escPressed() // generic cancel
case keymap.SelectAll:
cancelAll()
e.SetHandled()
ed.selectAll()
case keymap.Copy:
cancelAll()
e.SetHandled()
ed.Copy(core.SelectReset)
case keymap.Search:
e.SetHandled()
ed.qReplaceCancel()
ed.CancelComplete()
ed.iSearchStart()
case keymap.Abort:
cancelAll()
e.SetHandled()
ed.escPressed()
case keymap.Jump:
cancelAll()
e.SetHandled()
ed.JumpToLinePrompt()
case keymap.HistPrev:
cancelAll()
e.SetHandled()
if ed.Lines != nil && ed.posHistoryIndex == ed.Lines.PosHistoryLen()-1 {
ed.savePosHistory(ed.CursorPos) // save current if end
ed.posHistoryIndex--
}
ed.CursorToHistoryPrev()
case keymap.HistNext:
cancelAll()
e.SetHandled()
ed.CursorToHistoryNext()
case keymap.Lookup:
cancelAll()
e.SetHandled()
ed.Lookup()
}
if ed.IsReadOnly() {
switch {
case kf == keymap.Kill: // (Command+K), as in the context menu
e.SetHandled()
ed.Clear()
case kf == keymap.FocusNext: // tab
e.SetHandled()
ed.CursorNextLink(Wraparound)
ed.OpenLinkAt(ed.CursorPos)
case kf == keymap.FocusPrev: // tab
e.SetHandled()
ed.CursorPrevLink(Wraparound)
ed.OpenLinkAt(ed.CursorPos)
case kf == keymap.None && ed.ISearch.On:
if unicode.IsPrint(e.KeyRune()) && !e.HasAnyModifier(key.Control, key.Meta) {
ed.iSearchKeyInput(e)
}
case e.KeyRune() == ' ' || kf == keymap.Accept || kf == keymap.Enter:
e.SetHandled()
ed.CursorPos = ed.Lines.MoveBackward(ed.CursorPos, 1)
ed.CursorNextLink(Wraparound) // todo: cursorcurlink
ed.OpenLinkAt(ed.CursorPos)
}
return
}
if e.IsHandled() {
ed.lastWasTabAI = gotTabAI
return
}
switch kf {
case keymap.Replace:
e.SetHandled()
ed.CancelComplete()
ed.iSearchCancel()
ed.QReplacePrompt()
case keymap.Backspace:
// todo: previous item in qreplace
if ed.ISearch.On {
ed.iSearchBackspace()
} else {
e.SetHandled()
ed.cursorBackspace(1)
ed.iSpellKeyInput(e)
ed.offerComplete()
}
case keymap.Kill:
cancelAll()
e.SetHandled()
ed.cursorKill()
case keymap.Delete:
cancelAll()
e.SetHandled()
ed.cursorDelete(1)
ed.iSpellKeyInput(e)
case keymap.BackspaceWord:
cancelAll()
e.SetHandled()
ed.cursorBackspaceWord(1)
case keymap.DeleteWord:
cancelAll()
e.SetHandled()
ed.cursorDeleteWord(1)
case keymap.Cut:
cancelAll()
e.SetHandled()
ed.Cut()
case keymap.Paste:
cancelAll()
e.SetHandled()
ed.Paste()
case keymap.Transpose:
cancelAll()
e.SetHandled()
ed.cursorTranspose()
case keymap.TransposeWord:
cancelAll()
e.SetHandled()
ed.cursorTransposeWord()
case keymap.PasteHist:
cancelAll()
e.SetHandled()
ed.pasteHistory()
case keymap.Accept:
cancelAll()
e.SetHandled()
ed.editDone()
case keymap.Undo:
cancelAll()
e.SetHandled()
ed.undo()
ed.lastWasUndo = true
case keymap.Redo:
cancelAll()
e.SetHandled()
ed.redo()
case keymap.Complete:
ed.iSearchCancel()
e.SetHandled()
if ed.isSpellEnabled(ed.CursorPos) {
ed.offerCorrect()
} else {
ed.offerComplete()
}
case keymap.Enter:
cancelAll()
if !e.HasAnyModifier(key.Control, key.Meta) {
e.SetHandled()
if ed.Lines.Settings.AutoIndent {
lp, _ := ed.Lines.ParseState()
if lp != nil && lp.Lang != nil && lp.HasFlag(parse.ReAutoIndent) {
// only re-indent current line for supported types
tbe, _, _ := ed.Lines.AutoIndent(ed.CursorPos.Line) // reindent current line
if tbe != nil {
// go back to end of line!
npos := textpos.Pos{Line: ed.CursorPos.Line, Char: ed.Lines.LineLen(ed.CursorPos.Line)}
ed.setCursor(npos)
}
}
ed.InsertAtCursor([]byte("\n"))
tbe, _, cpos := ed.Lines.AutoIndent(ed.CursorPos.Line)
if tbe != nil {
ed.SetCursorShow(textpos.Pos{Line: tbe.Region.End.Line, Char: cpos})
}
} else {
ed.InsertAtCursor([]byte("\n"))
}
ed.iSpellKeyInput(e)
}
// todo: KeFunFocusPrev -- unindent
case keymap.FocusNext: // tab
cancelAll()
if !e.HasAnyModifier(key.Control, key.Meta) {
e.SetHandled()
lasttab := ed.lastWasTabAI
if !lasttab && ed.CursorPos.Char == 0 && ed.Lines.Settings.AutoIndent {
_, _, cpos := ed.Lines.AutoIndent(ed.CursorPos.Line)
ed.CursorPos.Char = cpos
gotTabAI = true
} else {
ed.InsertAtCursor(indent.Bytes(ed.Lines.Settings.IndentChar(), 1, ed.Styles.Text.TabSize))
}
ed.NeedsRender()
ed.iSpellKeyInput(e)
}
case keymap.FocusPrev: // shift-tab
cancelAll()
if !e.HasAnyModifier(key.Control, key.Meta) {
e.SetHandled()
if ed.CursorPos.Char > 0 {
ind, _ := lexer.LineIndent(ed.Lines.Line(ed.CursorPos.Line), ed.Styles.Text.TabSize)
if ind > 0 {
ed.Lines.IndentLine(ed.CursorPos.Line, ind-1)
intxt := indent.Bytes(ed.Lines.Settings.IndentChar(), ind-1, ed.Styles.Text.TabSize)
npos := textpos.Pos{Line: ed.CursorPos.Line, Char: len(intxt)}
ed.SetCursorShow(npos)
}
}
ed.iSpellKeyInput(e)
}
case keymap.None:
if unicode.IsPrint(e.KeyRune()) {
if !e.HasAnyModifier(key.Control, key.Meta) {
ed.keyInputInsertRune(e)
}
}
ed.iSpellKeyInput(e)
}
ed.lastWasTabAI = gotTabAI
ed.startCursor()
}
// keyInputInsertBracket handle input of opening bracket-like entity
// (paren, brace, bracket)
func (ed *Editor) keyInputInsertBracket(kt events.Event) {
pos := ed.CursorPos
match := true
newLine := false
curLn := ed.Lines.Line(pos.Line)
lnLen := len(curLn)
lp, ps := ed.Lines.ParseState()
if lp != nil && lp.Lang != nil {
match, newLine = lp.Lang.AutoBracket(ps, kt.KeyRune(), pos, curLn)
} else {
if kt.KeyRune() == '{' {
if pos.Char == lnLen {
if lnLen == 0 || unicode.IsSpace(curLn[pos.Char-1]) {
newLine = true
}
match = true
} else {
match = unicode.IsSpace(curLn[pos.Char])
}
} else {
match = pos.Char == lnLen || unicode.IsSpace(curLn[pos.Char]) // at end or if space after
}
}
if match {
ket, _ := lexer.BracePair(kt.KeyRune())
if newLine && ed.Lines.Settings.AutoIndent {
ed.InsertAtCursor([]byte(string(kt.KeyRune()) + "\n"))
tbe, _, cpos := ed.Lines.AutoIndent(ed.CursorPos.Line)
if tbe != nil {
pos = textpos.Pos{Line: tbe.Region.End.Line, Char: cpos}
ed.SetCursorShow(pos)
}
ed.InsertAtCursor([]byte("\n" + string(ket)))
ed.Lines.AutoIndent(ed.CursorPos.Line)
} else {
ed.InsertAtCursor([]byte(string(kt.KeyRune()) + string(ket)))
pos.Char++
if ed.autoInsertLine != pos.Line {
ed.autoInserted = nil
}
ed.autoInserted = append(ed.autoInserted, ket)
ed.autoInsertLine = pos.Line
}
} else {
ed.InsertAtCursor([]byte(string(kt.KeyRune())))
pos.Char++
}
ed.SetCursorShow(pos)
ed.setCursorColumn(ed.CursorPos)
}
// typeOverAutoInserted returns whether the given typed rune is the most
// recently auto-inserted closing bracket that is still pending, right
// after the cursor, in which case it is removed from the pending stack
// and should be typed over instead of inserted.
func (ed *Editor) typeOverAutoInserted(r rune) bool {
n := len(ed.autoInserted)
if n == 0 || ed.autoInserted[n-1] != r {
return false
}
pos := ed.CursorPos
if pos.Line != ed.autoInsertLine {
ed.autoInserted = nil
return false
}
ln := ed.Lines.Line(pos.Line)
if pos.Char >= len(ln) || ln[pos.Char] != r {
return false
}
ed.autoInserted = ed.autoInserted[:n-1]
return true
}
// keyInputInsertRune handles the insertion of a typed character
func (ed *Editor) keyInputInsertRune(kt events.Event) {
kt.SetHandled()
if ed.ISearch.On {
ed.CancelComplete()
ed.iSearchKeyInput(kt)
return
}
if ed.QReplace.On {
ed.CancelComplete()
ed.qReplaceKeyInput(kt)
return
}
switch {
case kt.KeyRune() == '{' || kt.KeyRune() == '(' || kt.KeyRune() == '[':
ed.keyInputInsertBracket(kt)
case kt.KeyRune() == '}' && ed.Lines.Settings.AutoIndent && ed.CursorPos.Char == ed.Lines.LineLen(ed.CursorPos.Line):
ed.CancelComplete()
ed.autoInserted = nil
ed.InsertAtCursor([]byte(string(kt.KeyRune())))
tbe, _, cpos := ed.Lines.AutoIndent(ed.CursorPos.Line)
if tbe != nil {
ed.SetCursorShow(textpos.Pos{Line: tbe.Region.End.Line, Char: cpos})
}
case ed.typeOverAutoInserted(kt.KeyRune()): // just move past what we inserted
ed.CursorPos.Char++
ed.SetCursorShow(ed.CursorPos)
default:
ed.InsertAtCursor([]byte(string(kt.KeyRune())))
if kt.KeyRune() == ' ' {
ed.CancelComplete()
} else {
ed.offerComplete()
}
}
if kt.KeyRune() == '}' || kt.KeyRune() == ')' || kt.KeyRune() == ']' {
cp := ed.CursorPos
np := cp
np.Char--
tp, found := ed.Lines.BraceMatchRune(kt.KeyRune(), np)
if found {
ed.addScopelights(np, tp)
}
}
}
// handleMouse handles mouse events
func (ed *Editor) handleMouse() {
ed.OnClick(func(e events.Event) {
ed.SetFocus()
pt := ed.PointToRelPos(e.Pos())
newPos := ed.PixelToCursor(pt)
if newPos == textpos.PosErr {
return
}
switch e.MouseButton() {
case events.Left:
lk, _ := ed.OpenLinkAt(newPos)
if lk == nil {
if !e.HasAnyModifier(key.Shift, key.Meta, key.Alt) {
ed.SelectReset()
}
ed.setCursorFromMouse(pt, newPos, e.SelectMode())
ed.savePosHistory(ed.CursorPos)
}
case events.Middle:
if !ed.IsReadOnly() {
ed.Paste()
}
}
ed.startCursor()
})
ed.OnDoubleClick(func(e events.Event) {
if !ed.StateIs(states.Focused) {
ed.SetFocus()
ed.Send(events.Focus, e) // sets focused flag
}
e.SetHandled()
if ed.selectWord() {
ed.CursorPos = ed.SelectRegion.Start
}
ed.startCursor()
ed.NeedsRender()
})
ed.On(events.TripleClick, func(e events.Event) {
if !ed.StateIs(states.Focused) {
ed.SetFocus()
ed.Send(events.Focus, e) // sets focused flag
}
e.SetHandled()
sz := ed.Lines.LineLen(ed.CursorPos.Line)
if sz > 0 {
ed.SelectRegion.Start.Line = ed.CursorPos.Line
ed.SelectRegion.Start.Char = 0
ed.SelectRegion.End.Line = ed.CursorPos.Line
ed.SelectRegion.End.Char = sz
}
ed.startCursor()
ed.NeedsRender()
})
ed.On(events.Scroll, func(e events.Event) {
ed.isScrolling = true
})
ed.On(events.SlideStart, func(e events.Event) {
e.SetHandled()
ed.SetState(true, states.Sliding)
ed.isScrolling = true
pt := ed.PointToRelPos(e.Pos())
pt.X -= int(0.8 * ed.charSize.X) // favor inclusive positioning on left
newPos := ed.PixelToCursor(pt)
if ed.selectMode || e.SelectMode() != events.SelectOne { // extend existing select
ed.setCursorFromMouse(pt, newPos, e.SelectMode())
} else {
ed.CursorPos = newPos
if !ed.selectMode {
ed.selectModeToggle()
}
}
ed.startCursor()
ed.savePosHistory(ed.CursorPos)
})
ed.On(events.SlideMove, func(e events.Event) {
e.SetHandled()
ed.selectMode = true
pt := ed.PointToRelPos(e.Pos())
newPos := ed.PixelToCursor(pt)
ed.setCursorFromMouse(pt, newPos, events.SelectOne)
ed.startCursor()
})
ed.On(events.SlideStop, func(e events.Event) {
e.SetHandled()
ed.isScrolling = false
ed.startCursor()
})
}
func (ed *Editor) handleLinkCursor() {
ed.On(events.MouseMove, func(e events.Event) {
pt := ed.PointToRelPos(e.Pos())
newPos := ed.PixelToCursor(pt)
if newPos == textpos.PosErr {
return
}
lk, _ := ed.linkAt(newPos)
if lk != nil {
ed.Styles.Cursor = cursors.Pointer
} else {
ed.Styles.Cursor = cursors.Text
}
})
}
//////// Context Menu
// ContextMenuPos returns the position of the context menu: that of the
// mouse event, or else below the cursor, as for the keyboard.
func (ed *Editor) ContextMenuPos(e events.Event) image.Point {
if e != nil && e.HasPos() {
return e.WindowPos()
}
pos := ed.charStartPos(ed.CursorPos)
pos.Y += ed.charSize.Y
return pos.ToPoint()
}
// ShowContextMenu displays the context menu with options dependent on situation
func (ed *Editor) ShowContextMenu(e events.Event) {
if ed.spell != nil && !ed.HasSelection() && ed.isSpellEnabled(ed.CursorPos) {
if ed.offerCorrect() {
return
}
}
ed.WidgetBase.ShowContextMenu(e)
}
// contextMenu builds the text editor context menu
func (ed *Editor) contextMenu(m *core.Scene, pos image.Point) {
core.NewButton(m).SetText("Copy").SetIcon(icons.ContentCopy).
SetKey(keymap.Copy).SetState(!ed.HasSelection(), states.Disabled).
OnClick(func(e events.Event) {
ed.Copy(core.SelectReset)
})
if !ed.IsReadOnly() {
core.NewButton(m).SetText("Cut").SetIcon(icons.ContentCopy).
SetKey(keymap.Cut).SetState(!ed.HasSelection(), states.Disabled).
OnClick(func(e events.Event) {
ed.Cut()
})
core.NewButton(m).SetText("Paste").SetIcon(icons.ContentPaste).
SetKey(keymap.Paste).SetState(ed.Clipboard().IsEmpty(), states.Disabled).
OnClick(func(e events.Event) {
ed.Paste()
})
core.NewSeparator(m)
core.NewFuncButton(m).SetFunc(ed.Save).SetIcon(icons.Save)
core.NewFuncButton(m).SetFunc(ed.SaveAs).SetIcon(icons.SaveAs)
core.NewFuncButton(m).SetFunc(ed.Lines.Open).SetIcon(icons.Open)
core.NewFuncButton(m).SetFunc(ed.Lines.Revert).SetIcon(icons.Reset)
} else {
core.NewButton(m).SetText("Clear").SetIcon(icons.ClearAll).SetKey(keymap.Kill).
OnClick(func(e events.Event) {
ed.Clear()
})
if ed.Lines != nil && ed.Lines.FileInfo().Generated {
core.NewButton(m).SetText("Set editable").SetIcon(icons.Edit).
OnClick(func(e events.Event) {
ed.SetReadOnly(false)
ed.Lines.FileInfo().Generated = false
ed.Update()
})
}
}
}
// JumpToLinePrompt jumps to given line number (minus 1) from prompt
func (ed *Editor) JumpToLinePrompt() {
val := ""
d := core.NewBody("Jump to line")
core.NewText(d).SetType(core.TextSupporting).SetText("Line number to jump to")
tf := core.NewTextField(d).SetPlaceholder("Line number")
tf.OnChange(func(e events.Event) {
val = tf.Text()
})
d.AddBottomBar(func(bar *core.Frame) {
d.AddCancel(bar)
d.AddOK(bar).SetText("Jump").OnClick(func(e events.Event) {
val = tf.Text()
ln, err := reflectx.ToInt(val)
if err == nil {
ed.jumpToLine(int(ln))
}
})
})
d.RunDialog(ed)
}
// jumpToLine jumps to given line number (minus 1)
func (ed *Editor) jumpToLine(ln int) {
ed.SetCursorShow(textpos.Pos{Line: ln - 1})
ed.savePosHistory(ed.CursorPos)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package textcore
import (
"fmt"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/fsx"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/text/lines"
)
// SaveAs saves the given Lines text into the given file.
// Checks for an existing file: If it does exist then prompts to overwrite or not.
// If afterFunc is non-nil, then it is called with the status of the user action.
func SaveAs(sc *core.Scene, lns *lines.Lines, filename string, afterFunc func(canceled bool)) {
if !errors.Log1(fsx.FileExists(filename)) {
saveFile(sc, lns, filename)
if afterFunc != nil {
afterFunc(false)
}
} else {
d := core.NewBody("File exists")
core.NewText(d).SetType(core.TextSupporting).SetText(fmt.Sprintf("The file already exists; do you want to overwrite it? File: %v", filename))
d.AddBottomBar(func(bar *core.Frame) {
d.AddCancel(bar).OnClick(func(e events.Event) {
if afterFunc != nil {
afterFunc(true)
}
})
d.AddOK(bar).OnClick(func(e events.Event) {
saveFile(sc, lns, filename)
if afterFunc != nil {
afterFunc(false)
}
})
})
d.RunDialog(sc)
}
}
// Save saves the given Lines into the current filename associated with this buffer,
// prompting if the file is changed on disk since the last save, in which case it
// returns nil without saving, and the user's choice determines what happens.
func Save(sc *core.Scene, lns *lines.Lines) error {
fname := lns.Filename()
if fname == "" {
return errors.New("core.Editor: filename is empty for Save")
}
if lns.ChangedOnDisk() {
d := core.NewBody("File Changed on Disk")
core.NewText(d).SetType(core.TextSupporting).SetText(fmt.Sprintf("File has changed on disk since you opened or saved it; what do you want to do? File: %v", fname))
d.AddBottomBar(func(bar *core.Frame) {
core.NewButton(bar).SetText("Save to different file").OnClick(func(e events.Event) {
d.Close()
fd := core.NewBody("Save file as")
fv := core.NewFilePicker(fd).SetFilename(fname)
fv.OnSelect(func(e events.Event) {
SaveAs(sc, lns, fv.SelectedFile(), nil)
})
fd.RunWindowDialog(sc)
})
core.NewButton(bar).SetText("Open from disk, losing changes").OnClick(func(e events.Event) {
d.Close()
lns.Revert()
})
core.NewButton(bar).SetText("Save file, overwriting").OnClick(func(e events.Event) {
d.Close()
saveFile(sc, lns, fname)
})
})
d.RunDialog(sc)
return nil
}
return saveFile(sc, lns, fname)
}
// saveFile saves the given Lines into the given file,
// reporting any error in a snackbar.
func saveFile(sc *core.Scene, lns *lines.Lines, fname string) error {
err := lns.SaveFile(fname)
core.ErrorSnackbar(sc, err, "Error saving file")
return err
}
// Close closes the lines viewed by this editor, prompting to save if there are changes.
// If afterFunc is non-nil, then it is called with the status of the user action.
// Returns false if the file was actually not closed pending input from the user.
func Close(sc *core.Scene, lns *lines.Lines, afterFunc func(canceled bool)) bool {
if !lns.IsNotSaved() {
lns.Close()
if afterFunc != nil {
afterFunc(false)
}
return true
}
lns.StopDelayedReMarkup()
fname := lns.Filename()
if fname == "" {
d := core.NewBody("Close without saving?")
core.NewText(d).SetType(core.TextSupporting).SetText("Do you want to save your changes (no filename for this buffer yet)? If so, Cancel and then do Save As")
d.AddBottomBar(func(bar *core.Frame) {
d.AddCancel(bar).OnClick(func(e events.Event) {
if afterFunc != nil {
afterFunc(true)
}
})
d.AddOK(bar).SetText("Close without saving").OnClick(func(e events.Event) {
lns.ClearNotSaved()
lns.AutosaveDelete()
Close(sc, lns, afterFunc)
})
})
d.RunDialog(sc)
return false // awaiting decisions..
}
d := core.NewBody("Close without saving?")
core.NewText(d).SetType(core.TextSupporting).SetText(fmt.Sprintf("Do you want to save your changes to file: %v?", fname))
d.AddBottomBar(func(bar *core.Frame) {
core.NewButton(bar).SetText("Cancel").OnClick(func(e events.Event) {
d.Close()
if afterFunc != nil {
afterFunc(true)
}
})
core.NewButton(bar).SetText("Close without saving").OnClick(func(e events.Event) {
d.Close()
lns.ClearNotSaved()
lns.AutosaveDelete()
Close(sc, lns, afterFunc)
})
core.NewButton(bar).SetText("Save").OnClick(func(e events.Event) {
d.Close()
Save(sc, lns)
if lns.IsNotSaved() { // save failed or is waiting for a prompt
if afterFunc != nil {
afterFunc(true)
}
return
}
Close(sc, lns, afterFunc) // 2nd time through won't prompt
})
})
d.RunDialog(sc)
return false
}
// FileModPrompt is called when a file has been modified in the filesystem
// and it is about to be modified through an edit, in the fileModCheck function.
// The prompt determines whether the user wants to revert, overwrite, or
// save current version as a different file.
func FileModPrompt(sc *core.Scene, lns *lines.Lines) bool {
fname := lns.Filename()
d := core.NewBody("File changed on disk: " + fsx.DirAndFile(fname))
core.NewText(d).SetType(core.TextSupporting).SetText(fmt.Sprintf("File has changed on disk since being opened or saved by you; what do you want to do? If you <code>Revert from Disk</code>, you will lose any existing edits in open buffer. If you <code>Ignore and Proceed</code>, the next save will overwrite the changed file on disk, losing any changes there. File: %v", fname))
d.AddBottomBar(func(bar *core.Frame) {
core.NewButton(bar).SetText("Save as to different file").OnClick(func(e events.Event) {
d.Close()
fd := core.NewBody("Save file as")
fv := core.NewFilePicker(fd).SetFilename(fname)
fv.OnSelect(func(e events.Event) {
SaveAs(sc, lns, fv.SelectedFile(), nil)
})
fd.RunWindowDialog(sc)
})
core.NewButton(bar).SetText("Revert from disk").OnClick(func(e events.Event) {
d.Close()
lns.Revert()
})
core.NewButton(bar).SetText("Ignore and proceed").OnClick(func(e events.Event) {
d.Close()
lns.SetFileModOK(true)
})
})
d.RunDialog(sc)
return true
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package textcore
import (
"unicode"
"cogentcore.org/core/base/stringsx"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/styles"
"cogentcore.org/core/text/lines"
"cogentcore.org/core/text/parse/lexer"
"cogentcore.org/core/text/textpos"
)
// findMatches finds the matches with given search string (literal, not regex)
// and case sensitivity, updates highlights for all. returns false if none
// found
func (ed *Editor) findMatches(find string, useCase bool, lexItems textpos.MatchScope) ([]textpos.Match, bool) {
fsz := len(find)
if fsz == 0 {
ed.Highlights = nil
return nil, false
}
_, matches := ed.Lines.Search([]byte(find), textpos.CaseSensitive(useCase), lexItems)
if len(matches) == 0 {
ed.Highlights = nil
return matches, false
}
hi := make([]textpos.Region, len(matches))
for i, m := range matches {
hi[i] = m.Region
if i > viewMaxFindHighlights {
break
}
}
ed.Highlights = hi
return matches, true
}
// matchFromPos finds the match at or after the given text position -- returns 0, false if none
func (ed *Editor) matchFromPos(matches []textpos.Match, cpos textpos.Pos) (int, bool) {
for i, m := range matches {
reg := ed.Lines.AdjustRegion(m.Region)
if reg.Start == cpos || cpos.IsLess(reg.Start) {
return i, true
}
}
return 0, false
}
// ISearch holds all the interactive search data
type ISearch struct {
// if true, in interactive search mode
On bool `json:"-" xml:"-"`
// current interactive search string
Find string `json:"-" xml:"-"`
// pay attention to case in isearch -- triggered by typing an upper-case letter
useCase bool
// current search matches
Matches []textpos.Match `json:"-" xml:"-"`
// position within isearch matches
pos int
// position in search list from previous search
prevPos int
// starting position for search -- returns there after on cancel
startPos textpos.Pos
}
// viewMaxFindHighlights is the maximum number of regions to highlight on find
var viewMaxFindHighlights = 1000
// PrevISearchString is the previous ISearch string
var PrevISearchString string
// iSearchMatches finds ISearch matches -- returns true if there are any
func (ed *Editor) iSearchMatches() bool {
got := false
ed.ISearch.Matches, got = ed.findMatches(ed.ISearch.Find, ed.ISearch.useCase, textpos.AnyText)
return got
}
// iSearchNextMatch finds next match after given cursor position, and highlights
// it, etc
func (ed *Editor) iSearchNextMatch(cpos textpos.Pos) bool {
if len(ed.ISearch.Matches) == 0 {
ed.iSearchEvent()
return false
}
ed.ISearch.pos, _ = ed.matchFromPos(ed.ISearch.Matches, cpos)
ed.iSearchSelectMatch(ed.ISearch.pos)
return true
}
// iSearchSelectMatch selects match at given match index (e.g., ed.ISearch.Pos)
func (ed *Editor) iSearchSelectMatch(midx int) {
nm := len(ed.ISearch.Matches)
if midx >= nm {
ed.iSearchEvent()
return
}
m := ed.ISearch.Matches[midx]
reg := ed.Lines.AdjustRegion(m.Region)
pos := reg.Start
ed.SelectRegion = reg
ed.setCursor(pos)
ed.savePosHistory(ed.CursorPos)
ed.scrollCursorToCenterIfHidden()
ed.iSearchEvent()
}
// iSearchEvent sends the signal that ISearch is updated
func (ed *Editor) iSearchEvent() {
ed.Send(events.Input)
}
// iSearchStart is an emacs-style interactive search mode -- this is called when
// the search command itself is entered
func (ed *Editor) iSearchStart() {
if ed.ISearch.On {
if ed.ISearch.Find != "" { // already searching -- find next
sz := len(ed.ISearch.Matches)
if sz > 0 {
if ed.ISearch.pos < sz-1 {
ed.ISearch.pos++
} else {
ed.ISearch.pos = 0
}
ed.iSearchSelectMatch(ed.ISearch.pos)
}
} else { // restore prev
if PrevISearchString != "" {
ed.ISearch.Find = PrevISearchString
ed.ISearch.useCase = lexer.HasUpperCase(ed.ISearch.Find)
ed.iSearchMatches()
ed.iSearchNextMatch(ed.CursorPos)
ed.ISearch.startPos = ed.CursorPos
}
// nothing..
}
} else {
ed.ISearch.On = true
ed.ISearch.Find = ""
ed.ISearch.startPos = ed.CursorPos
ed.ISearch.useCase = false
ed.ISearch.Matches = nil
ed.SelectReset()
ed.ISearch.pos = -1
ed.iSearchEvent()
}
ed.NeedsRender()
}
// iSearchKeyInput is an emacs-style interactive search mode -- this is called
// when keys are typed while in search mode
func (ed *Editor) iSearchKeyInput(kt events.Event) {
kt.SetHandled()
r := kt.KeyRune()
// if ed.ISearch.Find == PrevISearchString { // undo starting point
// ed.ISearch.Find = ""
// }
if unicode.IsUpper(r) { // todo: more complex
ed.ISearch.useCase = true
}
ed.ISearch.Find += string(r)
ed.iSearchMatches()
sz := len(ed.ISearch.Matches)
if sz == 0 {
ed.ISearch.pos = -1
ed.iSearchEvent()
return
}
ed.iSearchNextMatch(ed.CursorPos)
ed.NeedsRender()
}
// iSearchBackspace gets rid of one item in search string
func (ed *Editor) iSearchBackspace() {
if ed.ISearch.Find == PrevISearchString { // undo starting point
ed.ISearch.Find = ""
ed.ISearch.useCase = false
ed.ISearch.Matches = nil
ed.SelectReset()
ed.ISearch.pos = -1
ed.iSearchEvent()
return
}
if len(ed.ISearch.Find) <= 1 {
ed.SelectReset()
ed.ISearch.Find = ""
ed.ISearch.useCase = false
return
}
ed.ISearch.Find = ed.ISearch.Find[:len(ed.ISearch.Find)-1]
ed.iSearchMatches()
sz := len(ed.ISearch.Matches)
if sz == 0 {
ed.ISearch.pos = -1
ed.iSearchEvent()
return
}
ed.iSearchNextMatch(ed.CursorPos)
ed.NeedsRender()
}
// iSearchCancel cancels ISearch mode
func (ed *Editor) iSearchCancel() {
if !ed.ISearch.On {
return
}
if ed.ISearch.Find != "" {
PrevISearchString = ed.ISearch.Find
}
ed.ISearch.prevPos = ed.ISearch.pos
ed.ISearch.Find = ""
ed.ISearch.useCase = false
ed.ISearch.On = false
ed.ISearch.pos = -1
ed.ISearch.Matches = nil
ed.Highlights = nil
ed.savePosHistory(ed.CursorPos)
ed.SelectReset()
ed.iSearchEvent()
ed.NeedsRender()
}
// QReplace holds all the query-replace data
type QReplace struct {
// if true, in interactive search mode
On bool `json:"-" xml:"-"`
// current interactive search string
Find string `json:"-" xml:"-"`
// current interactive search string
Replace string `json:"-" xml:"-"`
// pay attention to case in isearch -- triggered by typing an upper-case letter
useCase bool
// search only as entire lexically tagged item boundaries -- key for replacing short local variables like i
lexItems textpos.MatchScope
// current search matches
Matches []textpos.Match `json:"-" xml:"-"`
// position within isearch matches
pos int `json:"-" xml:"-"`
// starting position for search -- returns there after on cancel
startPos textpos.Pos
}
var (
// prevQReplaceFinds are the previous QReplace strings
prevQReplaceFinds []string
// prevQReplaceRepls are the previous QReplace strings
prevQReplaceRepls []string
)
// qReplaceEvent sends the event that QReplace is updated
func (ed *Editor) qReplaceEvent() {
ed.Send(events.Input)
}
// QReplacePrompt is an emacs-style query-replace mode -- this starts the process, prompting
// user for items to search etc
func (ed *Editor) QReplacePrompt() {
find := ""
if ed.HasSelection() {
find = string(ed.Selection().ToBytes())
}
d := core.NewBody("Query-Replace")
core.NewText(d).SetType(core.TextSupporting).SetText("Enter strings for find and replace, then select Query-Replace; with dialog dismissed press <b>y</b> to replace current match, <b>n</b> to skip, <b>Enter</b> or <b>q</b> to quit, <b>!</b> to replace-all remaining")
fc := core.NewChooser(d).SetEditable(true).SetDefaultNew(true)
fc.Styler(func(s *styles.Style) {
s.Grow.Set(1, 0)
s.Min.X.Ch(80)
})
fc.SetStrings(prevQReplaceFinds...).SetCurrentIndex(0)
if find != "" {
fc.SetCurrentValue(find)
}
rc := core.NewChooser(d).SetEditable(true).SetDefaultNew(true)
rc.Styler(func(s *styles.Style) {
s.Grow.Set(1, 0)
s.Min.X.Ch(80)
})
rc.SetStrings(prevQReplaceRepls...).SetCurrentIndex(0)
lexitems := ed.QReplace.lexItems
lxi := core.NewSwitch(d).SetText("Lexical Items").SetChecked(lexitems == textpos.LexItems)
lxi.SetTooltip("search matches entire lexically tagged items -- good for finding local variable names like 'i' and not matching everything")
d.AddBottomBar(func(bar *core.Frame) {
d.AddCancel(bar)
d.AddOK(bar).SetText("Query-Replace").OnClick(func(e events.Event) {
var find, repl string
if s, ok := fc.CurrentItem.Value.(string); ok {
find = s
}
if s, ok := rc.CurrentItem.Value.(string); ok {
repl = s
}
lexItems := lxi.IsChecked()
ed.QReplaceStart(find, repl, textpos.MatchScope(lexItems))
})
})
d.RunDialog(ed)
}
// QReplaceStart starts query-replace using given find, replace strings
func (ed *Editor) QReplaceStart(find, repl string, lexItems textpos.MatchScope) {
ed.QReplace.On = true
ed.QReplace.Find = find
ed.QReplace.Replace = repl
ed.QReplace.lexItems = lexItems
ed.QReplace.startPos = ed.CursorPos
ed.QReplace.useCase = lexer.HasUpperCase(find)
ed.QReplace.Matches = nil
ed.QReplace.pos = -1
stringsx.InsertFirstUnique(&prevQReplaceFinds, find, core.SystemSettings.SavedPathsMax)
stringsx.InsertFirstUnique(&prevQReplaceRepls, repl, core.SystemSettings.SavedPathsMax)
ed.qReplaceMatches()
ed.QReplace.pos, _ = ed.matchFromPos(ed.QReplace.Matches, ed.CursorPos)
ed.qReplaceSelectMatch(ed.QReplace.pos)
ed.qReplaceEvent()
ed.NeedsRender()
}
// qReplaceMatches finds QReplace matches -- returns true if there are any
func (ed *Editor) qReplaceMatches() bool {
got := false
ed.QReplace.Matches, got = ed.findMatches(ed.QReplace.Find, ed.QReplace.useCase, textpos.MatchScope(ed.QReplace.lexItems))
return got
}
// qReplaceNextMatch finds next match using, QReplace.Pos and highlights it, etc
func (ed *Editor) qReplaceNextMatch() bool {
nm := len(ed.QReplace.Matches)
if nm == 0 {
return false
}
ed.QReplace.pos++
if ed.QReplace.pos >= nm {
return false
}
ed.qReplaceSelectMatch(ed.QReplace.pos)
return true
}
// qReplaceSelectMatch selects match at given match index (e.g., ed.QReplace.Pos)
func (ed *Editor) qReplaceSelectMatch(midx int) {
nm := len(ed.QReplace.Matches)
if midx >= nm {
return
}
m := ed.QReplace.Matches[midx]
reg := ed.Lines.AdjustRegion(m.Region)
pos := reg.Start
ed.SelectRegion = reg
ed.setCursor(pos)
ed.savePosHistory(ed.CursorPos)
ed.scrollCursorToCenterIfHidden()
ed.qReplaceEvent()
}
// qReplaceReplace replaces at given match index (e.g., ed.QReplace.Pos)
func (ed *Editor) qReplaceReplace(midx int) {
nm := len(ed.QReplace.Matches)
if midx >= nm {
return
}
m := ed.QReplace.Matches[midx]
rep := ed.QReplace.Replace
reg := ed.Lines.AdjustRegion(m.Region)
pos := reg.Start
// last arg is matchCase, only if not using case to match and rep is also lower case
matchCase := !ed.QReplace.useCase && !lexer.HasUpperCase(rep)
ed.Lines.ReplaceText(reg.Start, reg.End, pos, rep, lines.MatchCase(matchCase))
ed.Highlights[midx] = textpos.Region{}
ed.setCursor(pos)
ed.savePosHistory(ed.CursorPos)
ed.scrollCursorToCenterIfHidden()
ed.qReplaceEvent()
}
// QReplaceReplaceAll replaces all remaining from index
func (ed *Editor) QReplaceReplaceAll(midx int) {
nm := len(ed.QReplace.Matches)
if midx >= nm {
return
}
for mi := midx; mi < nm; mi++ {
ed.qReplaceReplace(mi)
}
}
// qReplaceKeyInput is an emacs-style interactive search mode -- this is called
// when keys are typed while in search mode
func (ed *Editor) qReplaceKeyInput(kt events.Event) {
kt.SetHandled()
switch {
case kt.KeyRune() == 'y':
ed.qReplaceReplace(ed.QReplace.pos)
if !ed.qReplaceNextMatch() {
ed.qReplaceCancel()
}
case kt.KeyRune() == 'n':
if !ed.qReplaceNextMatch() {
ed.qReplaceCancel()
}
case kt.KeyRune() == 'q' || kt.KeyChord() == "ReturnEnter":
ed.qReplaceCancel()
case kt.KeyRune() == '!':
ed.QReplaceReplaceAll(ed.QReplace.pos)
ed.qReplaceCancel()
}
ed.NeedsRender()
}
// qReplaceCancel cancels QReplace mode
func (ed *Editor) qReplaceCancel() {
if !ed.QReplace.On {
return
}
ed.QReplace.On = false
ed.QReplace.pos = -1
ed.QReplace.Matches = nil
ed.Highlights = nil
ed.savePosHistory(ed.CursorPos)
ed.SelectReset()
ed.qReplaceEvent()
ed.NeedsRender()
}
// escPressed emitted for [keymap.Abort] or [keymap.CancelSelect];
// effect depends on state.
func (ed *Editor) escPressed() {
switch {
case ed.ISearch.On:
ed.iSearchCancel()
ed.SetCursorShow(ed.ISearch.startPos)
case ed.QReplace.On:
ed.qReplaceCancel()
ed.SetCursorShow(ed.ISearch.startPos)
case ed.HasSelection():
ed.SelectReset()
default:
ed.Highlights = nil
}
ed.NeedsRender()
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package textcore
import (
"image"
"cogentcore.org/core/colors"
"cogentcore.org/core/events"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/system"
"cogentcore.org/core/text/lines"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/textpos"
)
// imeLayer is the virtual text layer of the composition of an input method.
const imeLayer = "ime"
// composition is the state of text being composed with an input method (IME),
// which is shown as virtual text at the cursor until it is committed.
type composition struct {
// active is whether text is being composed.
active bool
// pos is the source position of the composition.
pos textpos.Pos
// start and end are the range of the selected part of the
// composition, in runes, where end is the input method cursor.
start, end int
}
// compose handles a [events.Composition] event from an input method,
// showing the text being composed at the cursor as virtual text, or
// ending the composition if it is empty, in which case the committed
// text follows as KeyChord events.
// In a read-only editor with an [Base.InputPos], it is shown there.
func (ed *Editor) compose(e *events.TextComposition) {
if ed.Lines == nil {
return
}
ipos, input := ed.inputPos()
if !input {
return
}
if e.Text == "" {
ed.endComposition()
return
}
cp := &ed.composition
switch {
case ed.InputPos != nil: // where text is input now
cp.active = true
cp.pos = ipos
case !cp.active:
if ed.HasSelection() { // typing replaces the selection
tbe := ed.deleteSelection()
ed.CursorPos = tbe.AdjustPos(ed.CursorPos, textpos.AdjustPosDelStart)
}
cp.active = true
cp.pos = ed.CursorPos
}
txt := []rune(e.Text)
cp.start = max(0, min(e.Start, len(txt)))
cp.end = max(cp.start, min(e.End, len(txt)))
ed.SetVirtualText(imeLayer, lines.VirtualText{Pos: cp.pos, Text: ed.compositionText(txt, cp.start, cp.end)})
ed.NeedsRender()
}
// inputPos returns the position at which text is input, which is the
// cursor, or the [Base.InputPos] if it is set, and whether text is
// input, which it is not in a read-only editor without an InputPos.
func (ed *Base) inputPos() (textpos.Pos, bool) {
if ed.InputPos != nil {
return ed.InputPos()
}
if ed.IsReadOnly() {
return textpos.Pos{}, false
}
return ed.CursorPos, true
}
// endComposition ends any composition, removing its text.
func (ed *Base) endComposition() {
if !ed.composition.active {
return
}
ed.composition.active = false
ed.ClearVirtualText(imeLayer)
ed.NeedsRender()
}
// compositionText returns the text being composed as rich text, which is
// underlined, with the selected part, such as the clause being converted,
// also highlighted.
func (ed *Base) compositionText(txt []rune, start, end int) rich.Text {
sty := ed.CompositionStyle()
var tx rich.Text
tx.AddSpan(sty, txt[:start])
if end > start {
sel := *sty
sel.SetBackground(colors.ToUniform(colors.Scheme.Select.Container))
tx.AddSpan(&sel, txt[start:end])
}
tx.AddSpan(sty, txt[end:])
return tx
}
// updateTextInput updates the text input state of the window for the input
// method, with the position of the cursor, or that of the input method
// within the text being composed, where its candidate window is shown.
func (ed *Base) updateTextInput() {
if !ed.StateIs(states.Focused) {
return
}
ipos, input := ed.inputPos()
if !input {
ed.ClearTextInput()
return
}
pos := ed.charStartPos(ipos)
if cp := &ed.composition; cp.active {
if p, ok := ed.VirtualCharStartPos(imeLayer, cp.pos, cp.end); ok {
pos = p
}
}
cmin := pos.ToPointFloor()
ti := system.TextInput{Caret: image.Rectangle{Min: cmin, Max: cmin.Add(ed.charSize.ToPointCeil())}}
if ed.Lines != nil && ipos.Line >= 0 && ipos.Line < ed.Lines.NumLines() {
line := ed.Lines.Line(ipos.Line) // (the text being composed is not in it)
ti.Before = system.TextInputBefore(line[:max(0, min(ipos.Char, len(line)))])
}
ed.SetTextInput(ti)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package textcore
import (
"fmt"
"image"
"cogentcore.org/core/core"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/textpos"
)
// maxGrowLines is the maximum number of lines to grow to
// (subject to other styling constraints).
const maxGrowLines = 25
// styleSizes gets the charSize based on Style settings,
// and updates lineNumberOffset.
func (ed *Base) styleSizes() {
ed.lineNumberDigits = max(1+int(math32.Log10(float32(ed.NumLines()))), 3)
sty, tsty := ed.Styles.NewRichText()
lno := true
if ed.Lines != nil {
lno = ed.Lines.Settings.LineNumbers
ed.Lines.SetFontStyle(sty)
}
if lno {
ed.hasLineNumbers = true
ed.lineNumberOffset = ed.lineNumberDigits + 2
} else {
ed.hasLineNumbers = false
ed.lineNumberOffset = 0
}
if ed.Scene == nil {
ed.charSize.Set(16, 22)
return
}
sh := ed.Scene.TextShaper()
if sh != nil {
lht := ed.Styles.LineHeightDots()
tx := rich.NewText(sty, []rune{'M'})
r := sh.Shape(tx, tsty)
ed.charSize.X = math32.Round(r[0].Advance())
ed.charSize.Y = lht
}
}
// visSizeFromAlloc updates visSize based on allocated size.
func (ed *Base) visSizeFromAlloc() {
asz := ed.Geom.Size.Alloc.Content
sbw := math32.Ceil(ed.Styles.ScrollbarWidth.Dots)
if ed.HasScroll[math32.Y] {
asz.X -= sbw
}
if ed.HasScroll[math32.X] {
asz.Y -= sbw
}
ed.visSizeAlloc = asz
ed.visSize.Y = visChars(asz.Y, ed.charSize.Y)
ed.visSize.X = visChars(asz.X, ed.charSize.X)
// fmt.Println("vis size:", ed.visSize, "alloc:", asz, "charSize:", ed.charSize, "grow:", sty.Grow)
}
// visChars returns the number of characters of the given size that fit in
// the given allocated size, which is 0 if either is not positive: the
// conversion of NaN or -Inf (as from a char size of 0 before styling) to
// int is MinInt64 on amd64, which made a slice of negative length.
func visChars(alloc, char float32) int {
if alloc <= 0 || char <= 0 {
return 0
}
return int(math32.Floor(alloc / char))
}
// layoutAllLines uses the visSize width to update the line wrapping
// of the Lines text, getting the total height.
func (ed *Base) layoutAllLines() {
ed.visSizeFromAlloc()
if ed.visSize.Y == 0 || ed.Lines == nil || ed.Lines.NumLines() == 0 {
return
}
ed.lastFilename = ed.Lines.Filename()
sty := &ed.Styles
buf := ed.Lines
// todo: self-lock method for this, and general better api
buf.Highlighter.TabSize = sty.Text.TabSize
// todo: may want to support horizontal scroll and min width
ed.linesSize.X = ed.visSize.X - ed.lineNumberOffset // width
buf.SetWidth(ed.viewID, ed.linesSize.X) // inexpensive if same, does update
ed.linesSize.Y = buf.ViewLines(ed.viewID)
ed.totalSize.X = ed.charSize.X * float32(ed.visSize.X)
ed.totalSize.Y = ed.charSize.Y * float32(ed.linesSize.Y)
ed.lineRenders = make([]renderCache, ed.visSize.Y+1)
ed.lineNoRenders = make([]renderCache, ed.visSize.Y+1)
// ed.hasLinks = false // todo: put on lines
ed.lastVisSizeAlloc = ed.visSizeAlloc
}
// reLayoutAllLines updates the Renders Layout given current size, if changed
func (ed *Base) reLayoutAllLines() {
ed.visSizeFromAlloc()
if ed.visSize.Y == 0 || ed.Lines == nil || ed.Lines.NumLines() == 0 {
return
}
if ed.lastVisSizeAlloc == ed.visSizeAlloc {
return
}
ed.layoutAllLines()
}
// note: Layout reverts to basic Widget behavior for layout if no kids, like us..
// sizeToLines sets the Actual.Content size based on number of lines of text,
// subject to maxGrowLines, for the non-grow case.
func (ed *Base) sizeToLines() {
if ed.Styles.Grow.Y > 0 {
return
}
nln := ed.Lines.ViewLines(ed.viewID)
// if ed.linesSize.Y > 0 { // we have already been through layout
// nln = ed.linesSize.Y
// }
nln = min(maxGrowLines, nln)
maxh := float32(nln) * ed.charSize.Y
sz := &ed.Geom.Size
ty := styles.ClampMin(styles.ClampMax(maxh, sz.Max.Y), sz.Min.Y)
sz.Actual.Content.Y = ty
sz.Actual.Total.Y = sz.Actual.Content.Y + sz.Space.Y
if core.DebugSettings.LayoutTrace {
fmt.Println(ed, "textcore.Base sizeToLines targ:", ty, "nln:", nln, "Actual:", sz.Actual.Content)
}
}
func (ed *Base) SizeUp() {
ed.Frame.SizeUp() // sets Actual size based on styles
if ed.Lines == nil || ed.Lines.NumLines() == 0 {
return
}
ed.sizeToLines()
}
func (ed *Base) SizeDown(iter int) bool {
if iter == 0 {
if ed.NeedsRebuild() && ed.Lines != nil {
ed.Lines.ReMarkup()
}
ed.layoutAllLines()
} else {
ed.reLayoutAllLines()
}
ed.sizeToLines()
redo := ed.Frame.SizeDown(iter)
chg := ed.ManageOverflow(iter, true)
if !ed.HasScroll[math32.Y] {
ed.scrollPos = 0
}
return redo || chg
}
func (ed *Base) SizeFinal() {
ed.Frame.SizeFinal()
ed.reLayoutAllLines()
}
func (ed *Base) Position() {
ed.Frame.Position()
ed.ConfigScrolls()
}
func (ed *Base) ApplyScenePos() {
ed.Frame.ApplyScenePos()
ed.PositionScrolls()
}
func (ed *Base) ScrollValues(d math32.Dims) (maxSize, visSize, visPct float32) {
if d == math32.X {
return ed.Frame.ScrollValues(d)
}
maxSize = float32(max(ed.linesSize.Y, 1)) * ed.charSize.Y
visSize = float32(ed.visSize.Y) * ed.charSize.Y
visPct = visSize / maxSize
// fmt.Println("scroll values:", maxSize, visSize, visPct)
return
}
func (ed *Base) ScrollChanged(d math32.Dims, sb *core.Slider) {
ed.isScrolling = true
if d == math32.X {
ed.Frame.ScrollChanged(d, sb)
return
}
ed.scrollPos = sb.Value / ed.charSize.Y
ed.lineRenders = make([]renderCache, ed.visSize.Y+1)
ed.lineNoRenders = make([]renderCache, ed.visSize.Y+1)
ed.NeedsRender()
}
func (ed *Base) SetScrollParams(d math32.Dims, sb *core.Slider) {
if d == math32.X {
ed.Frame.SetScrollParams(d, sb)
return
}
sb.Min = 0
sb.Step = 1
if ed.visSize.Y > 0 {
sb.PageStep = float32(ed.visSize.Y) * ed.charSize.Y
}
}
// VisibleSize returns the number of characters per line (excluding
// any line numbers) and the number of lines that are visible, as of the
// last layout, for example to size a terminal.
func (ed *Base) VisibleSize() image.Point {
return image.Point{ed.linesSize.X, ed.visSize.Y}
}
// CharSize returns the size of one character cell, in dots.
func (ed *Base) CharSize() math32.Vector2 {
return ed.charSize
}
// IsScrolledToEnd returns whether the view is scrolled to show the last
// lines of the text, as of the last layout.
func (ed *Base) IsScrolledToEnd() bool {
return !ed.HasScroll[math32.Y] || ed.scrollPos >= float32(ed.linesSize.Y-ed.visSize.Y)-0.5
}
// ScrollPos returns the vertical scroll position, in lines of text.
func (ed *Base) ScrollPos() float32 {
return ed.scrollPos
}
// SetScrollPos sets the vertical scroll position, in lines of text,
// e.g., to restore a position from [Base.ScrollPos] after the text has
// been replaced.
func (ed *Base) SetScrollPos(pos float32) {
ed.updateScroll(pos)
}
// updateScroll sets the scroll position to given value, in lines.
// calls a NeedsRender if changed.
func (ed *Base) updateScroll(pos float32) bool {
if !ed.HasScroll[math32.Y] || ed.Scrolls[math32.Y] == nil {
return false
}
if pos < 0 {
pos = 0
}
ed.scrollPos = pos
ppos := pos * ed.charSize.Y
sb := ed.Scrolls[math32.Y]
if sb.Value != ppos {
ed.isScrolling = true
sb.SetValue(ppos)
ed.NeedsRender()
return true
}
return false
}
//////// Scrolling -- Vertical
// scrollLineToTop positions scroll so that the line of given source position
// is at the top (to the extent possible).
func (ed *Base) scrollLineToTop(pos textpos.Pos) bool {
vp := ed.Lines.PosToView(ed.viewID, pos)
return ed.updateScroll(float32(vp.Line))
}
// scrollCursorToTop positions scroll so the cursor line is at the top.
func (ed *Base) scrollCursorToTop() bool {
return ed.scrollLineToTop(ed.CursorPos)
}
// scrollLineToBottom positions scroll so that the line of given source position
// is at the bottom (to the extent possible).
func (ed *Base) scrollLineToBottom(pos textpos.Pos) bool {
vp := ed.Lines.PosToView(ed.viewID, pos)
return ed.updateScroll(float32(vp.Line - ed.visSize.Y + 1))
}
// scrollCursorToBottom positions scroll so cursor line is at the bottom.
func (ed *Base) scrollCursorToBottom() bool {
return ed.scrollLineToBottom(ed.CursorPos)
}
// scrollLineToCenter positions scroll so that the line of given source position
// is at the center (to the extent possible).
func (ed *Base) scrollLineToCenter(pos textpos.Pos) bool {
vp := ed.Lines.PosToView(ed.viewID, pos)
return ed.updateScroll(float32(max(vp.Line-ed.visSize.Y/2, 0)))
}
func (ed *Base) scrollCursorToCenter() bool {
return ed.scrollLineToCenter(ed.CursorPos)
}
// scrollCursorToTarget moves the cursor to its target, and scrolls to it,
// unless the lines have been closed since the target was set.
func (ed *Base) scrollCursorToTarget() {
ed.targetSet = false
if ed.Lines == nil {
return
}
if ed.cursorTarget == textpos.PosErr {
ed.cursorEndDoc()
return
}
ed.CursorPos = ed.cursorTarget
ed.scrollCursorToCenter()
}
// scrollToCenterIfHidden checks if the given position is not in view,
// and scrolls to center if so. returns false if in view already.
func (ed *Base) scrollToCenterIfHidden(pos textpos.Pos) bool {
if ed.Lines == nil {
return false
}
vp := ed.Lines.PosToView(ed.viewID, pos)
spos := ed.Geom.ContentBBox.Min.X + int(ed.LineNumberPixels())
epos := ed.Geom.ContentBBox.Max.X
csp := ed.charStartPos(pos).ToPoint()
if vp.Line >= int(ed.scrollPos) && vp.Line < int(ed.scrollPos)+ed.visSize.Y {
if csp.X >= spos && csp.X < epos {
return false
}
} else {
ed.scrollLineToCenter(pos)
}
if csp.X < spos {
ed.scrollCursorToRight()
} // (a cursor after the end, csp.X > epos, could scroll to the left)
ed.updateCursorPosition()
return true
}
// scrollCursorToCenterIfHidden checks if the cursor position is not in view,
// and scrolls to center if so. returns false if in view already.
func (ed *Base) scrollCursorToCenterIfHidden() bool {
return ed.scrollToCenterIfHidden(ed.CursorPos)
}
//////// Scrolling -- Horizontal
// scrollToRight tells any parent scroll layout to scroll to get given
// horizontal coordinate at right of view to extent possible -- returns true
// if scrolled
func (ed *Base) scrollToRight(pos int) bool {
return ed.ScrollDimToEnd(math32.X, pos)
}
// scrollCursorToRight tells any parent scroll layout to scroll to get cursor
// at right of view to extent possible -- returns true if scrolled.
func (ed *Base) scrollCursorToRight() bool {
curBBox := ed.cursorBBox(ed.CursorPos)
return ed.scrollToRight(curBBox.Max.X)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package textcore
import (
"cogentcore.org/core/system"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/textpos"
)
// openLink opens given link, using the LinkHandler if non-nil,
// or the default system.TheApp.OpenURL() which will open a browser.
func (ed *Base) openLink(tl *rich.Hyperlink) {
if ed.LinkHandler != nil {
ed.LinkHandler(tl)
} else {
system.TheApp.OpenURL(tl.URL)
}
}
// linkAt returns hyperlink at given source position, if one exists there,
// otherwise returns nil.
func (ed *Base) linkAt(pos textpos.Pos) (*rich.Hyperlink, int) {
lk := ed.Lines.LinkAt(pos)
if lk == nil {
return nil, -1
}
return lk, pos.Line
}
// OpenLinkAt opens a link at given cursor position, if one exists there.
// returns the link if found, else nil. Also highlights the selected link.
func (ed *Base) OpenLinkAt(pos textpos.Pos) (*rich.Hyperlink, int) {
tl, ln := ed.linkAt(pos)
if tl == nil {
return nil, -1
}
ed.HighlightsReset()
reg := ed.highlightLink(tl, ln)
ed.SetCursorShow(reg.Start)
ed.openLink(tl)
return tl, pos.Line
}
// highlightLink highlights given hyperlink
func (ed *Base) highlightLink(lk *rich.Hyperlink, ln int) textpos.Region {
reg := textpos.NewRegion(ln, lk.Range.Start, ln, lk.Range.End)
ed.HighlightRegion(reg)
return reg
}
// LinkWrap specifies whether going to the next or previous link wraps
// around the ends of the text: [Wraparound] or [NoWraparound].
type LinkWrap bool
const (
// Wraparound goes from the last link to the first, and back.
Wraparound LinkWrap = true
// NoWraparound stops at the first and last links.
NoWraparound LinkWrap = false
)
// CursorNextLink moves cursor to next link. wraparound wraps around to top of
// buffer if none found -- returns true if found
func (ed *Base) CursorNextLink(wraparound LinkWrap) bool {
if ed.NumLines() == 0 {
return false
}
ed.validateCursor()
nl, ln := ed.Lines.NextLink(ed.CursorPos)
if nl == nil {
if !wraparound {
return false
}
// wraparound: a link at the start is the next one, which NextLink
// would skip as the current one.
nl, ln = ed.Lines.LinkAt(textpos.Pos{}), 0
if nl == nil {
nl, ln = ed.Lines.NextLink(textpos.Pos{})
}
if nl == nil {
return false
}
}
ed.HighlightsReset()
reg := ed.highlightLink(nl, ln)
ed.SetCursorTarget(reg.Start)
ed.savePosHistory(reg.Start)
ed.NeedsRender()
return true
}
// CursorPrevLink moves cursor to next link. wraparound wraps around to bottom of
// buffer if none found -- returns true if found
func (ed *Base) CursorPrevLink(wraparound LinkWrap) bool {
if ed.NumLines() == 0 {
return false
}
ed.validateCursor()
nl, ln := ed.Lines.PrevLink(ed.CursorPos)
if nl == nil {
if !wraparound {
return false
}
nl, ln = ed.Lines.PrevLink(ed.Lines.EndPos()) // wraparound
if nl == nil {
return false
}
}
ed.HighlightsReset()
reg := ed.highlightLink(nl, ln)
ed.SetCursorTarget(reg.Start)
ed.savePosHistory(reg.Start)
ed.NeedsRender()
return true
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package textcore
import (
"image"
"cogentcore.org/core/events"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/text/textpos"
)
// validateCursor sets current cursor to a valid cursor position
func (ed *Base) validateCursor() textpos.Pos {
if ed.Lines != nil {
ed.CursorPos = ed.Lines.ValidPos(ed.CursorPos)
} else {
ed.CursorPos = textpos.Pos{}
}
return ed.CursorPos
}
// setCursor sets a new cursor position, enforcing it in range.
// This is the main final pathway for all cursor movement.
func (ed *Base) setCursor(pos textpos.Pos) {
if ed.Lines == nil {
ed.CursorPos = textpos.PosZero
return
}
ed.scopelightsReset()
ed.CursorPos = ed.Lines.ValidPos(pos)
ed.startCursor()
bm, has := ed.Lines.BraceMatch(pos)
if has {
ed.addScopelights(pos, bm)
ed.NeedsRender()
}
}
// SetCursorShow sets a new cursor position, enforcing it in range, and shows
// the cursor (scroll to if hidden, render)
func (ed *Base) SetCursorShow(pos textpos.Pos) {
ed.setCursor(pos)
ed.scrollCursorToCenterIfHidden()
}
// SetCursorTarget sets a new cursor target position, ensures that it is visible.
// Setting the textpos.PosErr value causes it to go the end of doc, the position
// of which may not be known at the time the target is set.
func (ed *Base) SetCursorTarget(pos textpos.Pos) {
ed.isScrolling = false
ed.targetSet = true
ed.cursorTarget = pos
if pos == textpos.PosErr {
ed.cursorEndDoc()
return
}
ed.SetCursorShow(pos)
// fmt.Println(ed, "set target:", ed.CursorTarg)
}
// savePosHistory saves the cursor position in history stack of cursor positions.
// Tracks across views. Returns false if position was on same line as last one saved.
func (ed *Base) savePosHistory(pos textpos.Pos) bool {
if ed.Lines == nil {
return false
}
did := ed.Lines.PosHistorySave(pos)
if did {
ed.posHistoryIndex = ed.Lines.PosHistoryLen() - 1
}
return did
}
// CursorToHistoryPrev moves cursor to previous position on history list.
// returns true if moved
func (ed *Base) CursorToHistoryPrev() bool {
if ed.Lines == nil {
ed.CursorPos = textpos.Pos{}
return false
}
sz := ed.Lines.PosHistoryLen()
if sz == 0 {
return false
}
if ed.posHistoryIndex < 0 {
ed.posHistoryIndex = 0
return false
}
ed.posHistoryIndex = min(sz-1, ed.posHistoryIndex)
pos, _ := ed.Lines.PosHistoryAt(ed.posHistoryIndex)
ed.CursorPos = ed.Lines.ValidPos(pos)
if ed.posHistoryIndex > 0 {
ed.posHistoryIndex--
}
ed.scrollCursorToCenterIfHidden()
ed.SendInput()
return true
}
// CursorToHistoryNext moves cursor to previous position on history list --
// returns true if moved
func (ed *Base) CursorToHistoryNext() bool {
if ed.Lines == nil {
ed.CursorPos = textpos.Pos{}
return false
}
sz := ed.Lines.PosHistoryLen()
if sz == 0 {
return false
}
ed.posHistoryIndex++
if ed.posHistoryIndex >= sz-1 {
ed.posHistoryIndex = sz - 1
}
pos, _ := ed.Lines.PosHistoryAt(ed.posHistoryIndex)
ed.CursorPos = ed.Lines.ValidPos(pos)
ed.scrollCursorToCenterIfHidden()
ed.startCursor()
ed.SendInput()
return true
}
// setCursorColumn sets the current target cursor column (cursorColumn) to that
// of the given position, in cells (see [lines.Lines.ViewCell]).
func (ed *Base) setCursorColumn(pos textpos.Pos) {
if ed.Lines == nil {
return
}
vpos := ed.Lines.PosToView(ed.viewID, pos)
ed.cursorColumn = ed.Lines.ViewCell(ed.viewID, vpos)
}
//////// cursor moving
// cursorSelect updates selection based on cursor movements, given starting
// cursor position and ed.CursorPos is current
func (ed *Base) cursorSelect() {
if !ed.selectMode {
return
}
ed.selectRegionUpdate(ed.CursorPos)
}
// cursorSelectShow does SetCursorShow, cursorSelect, and NeedsRender.
// This is typically called for move actions.
func (ed *Base) cursorSelectShow() {
ed.SetCursorShow(ed.CursorPos)
ed.cursorSelect()
ed.SendInput()
ed.NeedsRender()
}
// cursorForward moves the cursor forward
func (ed *Base) cursorForward(steps int) {
org := ed.validateCursor()
ed.CursorPos = ed.Lines.MoveForward(org, steps)
ed.setCursorColumn(ed.CursorPos)
ed.cursorSelectShow()
}
// cursorForwardWord moves the cursor forward by words
func (ed *Base) cursorForwardWord(steps int) {
org := ed.validateCursor()
ed.CursorPos = ed.Lines.MoveForwardWord(org, steps)
ed.setCursorColumn(ed.CursorPos)
ed.cursorSelectShow()
}
// cursorBackward moves the cursor backward
func (ed *Base) cursorBackward(steps int) {
org := ed.validateCursor()
ed.CursorPos = ed.Lines.MoveBackward(org, steps)
ed.setCursorColumn(ed.CursorPos)
ed.cursorSelectShow()
}
// cursorBackwardWord moves the cursor backward by words
func (ed *Base) cursorBackwardWord(steps int) {
org := ed.validateCursor()
ed.CursorPos = ed.Lines.MoveBackwardWord(org, steps)
ed.setCursorColumn(ed.CursorPos)
ed.cursorSelectShow()
}
// cursorDown moves the cursor down line(s)
func (ed *Base) cursorDown(steps int) {
org := ed.validateCursor()
ed.CursorPos = ed.Lines.MoveDown(ed.viewID, org, steps, ed.cursorColumn)
ed.cursorSelectShow()
}
// cursorPageDown moves the cursor down page(s), where a page is defined
// dynamically as just moving the cursor off the screen
func (ed *Base) cursorPageDown(steps int) {
ed.validateCursor()
vp := ed.Lines.PosToView(ed.viewID, ed.CursorPos)
cpr := max(0, vp.Line-int(ed.scrollPos))
nln := max(1, ed.visSize.Y-cpr)
for range steps {
ed.CursorPos = ed.Lines.MoveDown(ed.viewID, ed.CursorPos, nln, ed.cursorColumn)
}
ed.setCursor(ed.CursorPos)
ed.scrollCursorToTop()
ed.startCursor()
ed.cursorSelect()
ed.SendInput()
ed.NeedsRender()
}
// cursorUp moves the cursor up line(s)
func (ed *Base) cursorUp(steps int) {
org := ed.validateCursor()
ed.CursorPos = ed.Lines.MoveUp(ed.viewID, org, steps, ed.cursorColumn)
ed.cursorSelectShow()
}
// cursorPageUp moves the cursor up page(s), where a page is defined
// dynamically as just moving the cursor off the screen
func (ed *Base) cursorPageUp(steps int) {
ed.validateCursor()
vp := ed.Lines.PosToView(ed.viewID, ed.CursorPos)
cpr := max(0, vp.Line-int(ed.scrollPos))
nln := max(1, cpr)
for range steps {
ed.CursorPos = ed.Lines.MoveUp(ed.viewID, ed.CursorPos, nln, ed.cursorColumn)
}
ed.setCursor(ed.CursorPos)
ed.scrollCursorToBottom()
ed.startCursor()
ed.cursorSelect()
ed.SendInput()
ed.NeedsRender()
}
// cursorRecenter re-centers the view around the cursor position, toggling
// between putting cursor in middle, top, and bottom of view
func (ed *Base) cursorRecenter() {
ed.validateCursor()
ed.savePosHistory(ed.CursorPos)
cur := (ed.lastRecenter + 1) % 3
switch cur {
case 0:
ed.scrollCursorToBottom()
case 1:
ed.scrollCursorToCenter()
case 2:
ed.scrollCursorToTop()
}
ed.lastRecenter = cur
}
// cursorLineStart moves the cursor to the start of the line, updating selection
// if select mode is active
func (ed *Base) cursorLineStart() {
org := ed.validateCursor()
ed.CursorPos = ed.Lines.MoveLineStart(ed.viewID, org)
ed.cursorColumn = 0
ed.scrollCursorToRight()
ed.cursorSelectShow()
}
// CursorStartDoc moves the cursor to the start of the text, updating selection
// if select mode is active
func (ed *Base) CursorStartDoc() {
ed.validateCursor()
ed.CursorPos.Line = 0
ed.CursorPos.Char = 0
ed.cursorColumn = 0
ed.scrollCursorToTop()
ed.cursorSelectShow()
}
// cursorLineEnd moves the cursor to the end of the text
func (ed *Base) cursorLineEnd() {
org := ed.validateCursor()
ed.CursorPos = ed.Lines.MoveLineEnd(ed.viewID, org)
ed.setCursorColumn(ed.CursorPos)
ed.scrollCursorToRight()
ed.cursorSelectShow()
}
// cursorEndDoc moves the cursor to the end of the text, updating selection if
// select mode is active
func (ed *Base) cursorEndDoc() {
ed.validateCursor()
ed.CursorPos = ed.Lines.EndPos()
ed.setCursorColumn(ed.CursorPos)
ed.scrollCursorToBottom()
ed.cursorSelectShow()
}
// todo: ctrl+backspace = delete word
// shift+arrow = select
// uparrow = start / down = end
// cursorBackspace deletes character(s) immediately before cursor
func (ed *Base) cursorBackspace(steps int) {
org := ed.validateCursor()
if ed.HasSelection() {
org = ed.SelectRegion.Start
ed.deleteSelection()
ed.SetCursorShow(org)
return
}
// note: no update b/c signal from buf will drive update
ed.cursorBackward(steps)
ed.scrollCursorToCenterIfHidden()
ed.Lines.DeleteText(ed.CursorPos, org)
ed.NeedsRender()
}
// cursorDelete deletes character(s) immediately after the cursor
func (ed *Base) cursorDelete(steps int) {
org := ed.validateCursor()
if ed.HasSelection() {
ed.deleteSelection()
return
}
// note: no update b/c signal from buf will drive update
ed.cursorForward(steps)
ed.Lines.DeleteText(org, ed.CursorPos)
ed.SetCursorShow(org)
ed.NeedsRender()
}
// cursorBackspaceWord deletes words(s) immediately before cursor
func (ed *Base) cursorBackspaceWord(steps int) {
org := ed.validateCursor()
if ed.HasSelection() {
ed.deleteSelection()
ed.SetCursorShow(org)
return
}
ed.cursorBackwardWord(steps)
ed.scrollCursorToCenterIfHidden()
ed.Lines.DeleteText(ed.CursorPos, org)
ed.NeedsRender()
}
// cursorDeleteWord deletes word(s) immediately after the cursor
func (ed *Base) cursorDeleteWord(steps int) {
org := ed.validateCursor()
if ed.HasSelection() {
ed.deleteSelection()
return
}
ed.cursorForwardWord(steps)
ed.Lines.DeleteText(org, ed.CursorPos)
ed.SetCursorShow(org)
ed.NeedsRender()
}
// cursorKill deletes text from cursor to end of text.
// if line is empty, deletes the line.
func (ed *Base) cursorKill() {
org := ed.validateCursor()
llen := ed.Lines.LineLen(ed.CursorPos.Line)
if ed.CursorPos.Char == llen { // at end
ed.cursorForward(1)
} else {
ed.cursorLineEnd()
}
ed.Lines.DeleteText(org, ed.CursorPos)
ed.SetCursorShow(org)
ed.NeedsRender()
}
// cursorTranspose swaps the character at the cursor with the one before it.
func (ed *Base) cursorTranspose() {
ed.validateCursor()
pos := ed.CursorPos
if pos.Char == 0 {
return
}
ed.Lines.TransposeChar(ed.viewID, pos)
// ed.SetCursorShow(pos)
ed.NeedsRender()
}
// cursorTransposeWord swaps the word at or before the cursor with the
// next word, moving the cursor after them.
func (ed *Base) cursorTransposeWord() {
ed.validateCursor()
if pos, ok := ed.Lines.TransposeWord(ed.CursorPos); ok {
ed.SetCursorShow(pos)
}
ed.NeedsRender()
}
// setCursorFromMouse sets cursor position from mouse mouse action -- handles
// the selection updating etc.
func (ed *Base) setCursorFromMouse(pt image.Point, newPos textpos.Pos, selMode events.SelectModes) {
oldPos := ed.CursorPos
if newPos == oldPos || newPos == textpos.PosErr {
return
}
// fmt.Printf("set cursor fm mouse: %v\n", newPos)
defer ed.NeedsRender()
if !ed.selectMode && selMode == events.ExtendContinuous {
if ed.SelectRegion == (textpos.Region{}) {
ed.selectStart = ed.CursorPos
}
ed.setCursor(newPos)
ed.selectRegionUpdate(ed.CursorPos)
ed.startCursor()
return
}
ed.setCursor(newPos)
if ed.selectMode || selMode != events.SelectOne {
if !ed.selectMode && selMode != events.SelectOne {
ed.selectMode = true
ed.selectStart = newPos
ed.selectRegionUpdate(ed.CursorPos)
}
if !ed.StateIs(states.Sliding) && selMode == events.SelectOne {
ln := ed.CursorPos.Line
ch := ed.CursorPos.Char
if ln != ed.SelectRegion.Start.Line || ch < ed.SelectRegion.Start.Char || ch > ed.SelectRegion.End.Char {
ed.SelectReset()
}
} else {
ed.selectRegionUpdate(ed.CursorPos)
}
if ed.StateIs(states.Sliding) {
scPos := math32.FromPoint(pt) // already relative to editor
ed.AutoScroll(scPos)
} else {
ed.scrollCursorToCenterIfHidden()
}
} else if ed.HasSelection() {
ln := ed.CursorPos.Line
ch := ed.CursorPos.Char
if ln != ed.SelectRegion.Start.Line || ch < ed.SelectRegion.Start.Char || ch > ed.SelectRegion.End.Char {
ed.SelectReset()
}
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package textcore
import (
"bufio"
"errors"
"io"
"log/slog"
"os"
"sync"
"syscall"
"time"
"cogentcore.org/core/text/lines"
"cogentcore.org/core/text/rich"
)
// OutputBufferMarkupFunc is a function that returns a marked-up version
// of a given line of output text. It is essential that it not add any
// new text, just splits into spans with different styles.
type OutputBufferMarkupFunc func(buf *lines.Lines, line []rune) rich.Text
// OutputBuffer is a buffer that records the output from an [io.Reader] using
// [bufio.Scanner]. It is optimized to combine fast chunks of output into
// large blocks of updating. It also supports an arbitrary markup function
// that operates on each line of output text.
type OutputBuffer struct { //types:add -setters
// the output that we are reading from, as an io.Reader
Output io.Reader
// the [lines.Lines] that we output to
Lines *lines.Lines
// how much time to wait while batching output (default: 200ms)
Batch time.Duration
// MarkupFunc is an optional markup function that adds html tags to given line
// of output. It is essential that it not add any new text, just splits into spans
// with different styles.
MarkupFunc OutputBufferMarkupFunc
// current buffered output raw lines, which are not yet sent to the Buffer
bufferedLines [][]rune
// current buffered output markup lines, which are not yet sent to the Buffer
bufferedMarkup []rich.Text
// time when last output was sent to buffer
lastOutput time.Time
// time.AfterFunc that is started after new input is received and not
// immediately output. Ensures that it will get output if no further burst happens.
afterTimer *time.Timer
// mutex protecting updates
sync.Mutex
}
// MonitorOutput monitors the output and updates the [OutputBuffer.Lines].
// It runs until the output ends, so it is typically called in a separate
// goroutine. It must not be called with the lock of the views of the
// [lines.Lines] held (as in an event handler), as their updates for the
// new output get that lock (see [lines.Lines.AppendTextMarkupAsync]).
func (ob *OutputBuffer) MonitorOutput() {
if ob.Batch == 0 {
ob.Batch = 200 * time.Millisecond
}
sty := ob.Lines.FontStyle()
ob.bufferedLines = make([][]rune, 0, 100)
ob.bufferedMarkup = make([]rich.Text, 0, 100)
outscan := bufio.NewScanner(ob.Output) // line at a time
// (long lines, as of minified output, must not end the output)
outscan.Buffer(make([]byte, 0, 64*1024), 16*1024*1024)
for outscan.Scan() {
ob.Lock()
b := outscan.Bytes()
rln := []rune(string(b))
if ob.afterTimer != nil {
ob.afterTimer.Stop()
ob.afterTimer = nil
}
ob.bufferedLines = append(ob.bufferedLines, rln)
if ob.MarkupFunc != nil {
mup := ob.MarkupFunc(ob.Lines, rln)
ob.bufferedMarkup = append(ob.bufferedMarkup, mup)
} else {
mup := rich.NewText(sty, rln)
ob.bufferedMarkup = append(ob.bufferedMarkup, mup)
}
lag := time.Since(ob.lastOutput)
if lag > ob.Batch {
ob.lastOutput = time.Now()
ob.outputToBuffer()
} else {
ob.afterTimer = time.AfterFunc(ob.Batch*2, func() {
ob.Lock()
ob.lastOutput = time.Now()
ob.outputToBuffer()
ob.afterTimer = nil
ob.Unlock()
})
}
ob.Unlock()
}
// a closed pipe, or a pseudo-terminal whose process ended (EIO), is
// the normal end of the output
if err := outscan.Err(); err != nil && !errors.Is(err, os.ErrClosed) && !errors.Is(err, io.ErrClosedPipe) && !errors.Is(err, syscall.EIO) {
slog.Error("textcore.OutputBuffer: reading the output", "err", err)
}
ob.Lock()
ob.outputToBuffer()
ob.Unlock()
}
// outputToBuffer sends the current output to Buffer.
// MUST be called under mutex protection
func (ob *OutputBuffer) outputToBuffer() {
if len(ob.bufferedLines) == 0 {
return
}
ob.Lines.SetUndoOn(false)
ob.Lines.AppendTextMarkupAsync(ob.bufferedLines, ob.bufferedMarkup)
ob.bufferedLines = make([][]rune, 0, 100)
ob.bufferedMarkup = make([]rich.Text, 0, 100)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package textcore
import (
"fmt"
"image"
"image/color"
"slices"
"cogentcore.org/core/colors"
"cogentcore.org/core/colors/gradient"
"cogentcore.org/core/colors/matcolor"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint/render"
"cogentcore.org/core/styles/sides"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/text/lines"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/shaped"
"cogentcore.org/core/text/textpos"
)
func (ed *Base) reLayout() {
if ed.Lines == nil {
return
}
prevLines := ed.linesSize.Y
lns := ed.Lines.ViewLines(ed.viewID)
if lns == prevLines {
return
}
ed.layoutAllLines()
chg := ed.ManageOverflow(1, true)
if ed.Styles.Grow.Y == 0 && lns < maxGrowLines || prevLines < maxGrowLines {
chg = prevLines != ed.linesSize.Y || chg
}
if chg {
// fmt.Println(chg, lns, prevLines, ed.visSize.Y, ed.linesSize.Y)
ed.NeedsLayout()
if !ed.HasScroll[math32.Y] {
ed.scrollPos = 0
}
}
}
func (ed *Base) RenderWidget() {
if ed.Lines != nil {
ed.Lines.StartDeferredMarkup()
}
if ed.StartRender() {
ed.reLayout()
if ed.targetSet {
ed.scrollCursorToTarget()
}
if !ed.isScrolling {
ed.scrollCursorToCenterIfHidden()
}
ed.PositionScrolls()
ed.renderLines()
ed.RenderChildren()
ed.RenderScrolls()
ed.updateCursorPosition()
ed.EndRender()
}
}
// renderBBox is the bounding box for the text render area (ContentBBox)
func (ed *Base) renderBBox() image.Rectangle {
return ed.Geom.ContentBBox
}
// renderLineStartEnd returns the starting and ending (inclusive) lines to render
// based on the scroll position. Also returns the starting upper left position
// for rendering the first line.
func (ed *Base) renderLineStartEnd() (stln, edln int, spos math32.Vector2) {
spos = ed.Geom.Pos.Content
stln = int(math32.Floor(ed.scrollPos))
spos.Y += (float32(stln) - ed.scrollPos) * ed.charSize.Y
edln = min(ed.linesSize.Y-1, stln+ed.visSize.Y)
return
}
// posIsVisible returns true if given position is visible,
// in terms of the vertical lines in view.
func (ed *Base) posIsVisible(pos textpos.Pos) bool {
if ed.Lines == nil {
return false
}
vpos := ed.Lines.PosToView(ed.viewID, pos)
sp := int(math32.Floor(ed.scrollPos))
return vpos.Line >= sp && vpos.Line <= sp+ed.visSize.Y
}
// renderLines renders the visible lines and line numbers.
func (ed *Base) renderLines() {
ed.RenderStandardBox()
if ed.Lines == nil {
return
}
bb := ed.renderBBox()
stln, edln, spos := ed.renderLineStartEnd()
pc := &ed.Scene.Painter
pc.PushContext(nil, render.NewBoundsRect(bb, sides.NewFloats()))
if ed.hasLineNumbers {
ed.renderLineNumbersBox()
li := 0
lastln := -1
for ln := stln; ln <= edln; ln++ {
sp := ed.Lines.PosFromView(ed.viewID, textpos.Pos{Line: ln})
if sp.Char == 0 && sp.Line != lastln { // Char=0 is start of source line
// but also get 0 for out-of-range..
ed.renderLineNumber(spos, li, sp.Line)
lastln = sp.Line
}
li++
}
}
ed.renderDepthBackground(spos, stln, edln)
ed.renderCodeErrors()
if ed.hasLineNumbers {
tbb := bb
tbb.Min.X += int(ed.LineNumberPixels())
pc.PushContext(nil, render.NewBoundsRect(tbb, sides.NewFloats()))
}
buf := ed.Lines
rpos := spos
rpos.X += ed.LineNumberPixels()
vsel := buf.RegionToView(ed.viewID, ed.SelectRegion)
rtoview := func(rs []textpos.Region) []textpos.Region {
if len(rs) == 0 {
return nil
}
hlts := make([]textpos.Region, 0, len(rs))
for _, reg := range rs {
reg := ed.Lines.AdjustRegion(reg)
if !reg.IsNil() {
hlts = append(hlts, buf.RegionToView(ed.viewID, reg))
}
}
return hlts
}
hlts := rtoview(ed.Highlights)
slts := rtoview(ed.scopelights)
hlts = append(hlts, slts...)
buf.Lock()
li := 0
for ln := stln; ln <= edln; ln++ {
ed.renderLine(li, ln, rpos, vsel, hlts)
rpos.Y += ed.charSize.Y
li++
}
buf.Unlock()
if ed.hasLineNumbers {
pc.PopContext()
}
pc.PopContext()
}
type renderCache struct {
// tx is the rich text of the line, including the styles of its spans.
tx []rune
lns *shaped.Lines
}
// renderLine renders given line, dealing with tab stops etc
func (ed *Base) renderLine(li, ln int, rpos math32.Vector2, vsel textpos.Region, hlts []textpos.Region) {
buf := ed.Lines
sh := ed.Scene.TextShaper()
pc := &ed.Scene.Painter
sz := ed.charSize
sz.X *= float32(ed.linesSize.X)
vlr := buf.ViewLineRegionNoLock(ed.viewID, ln)
vseli := vlr.Intersect(vsel, ed.linesSize.X)
tx := buf.ViewMarkupLine(ed.viewID, ln)
ts := ed.Lines.Settings.TabSize
indent := 0
sty, tsty := ed.Styles.NewRichText()
shapeTab := func(stx rich.Text, ssz math32.Vector2) *shaped.Lines {
if ed.tabRender != nil {
return ed.tabRender.Clone()
}
lns := sh.WrapLines(stx, sty, tsty, ssz)
ed.tabRender = lns
return lns
}
shapeSpan := func(stx rich.Text, ssz math32.Vector2) *shaped.Lines {
txt := slices.Concat(stx...) // with the styles, which change with highlighting
rc := ed.lineRenders[li]
if rc.lns != nil && slices.Compare(rc.tx, txt) == 0 {
return rc.lns
}
lns := sh.WrapLines(stx, sty, tsty, ssz)
ed.lineRenders[li] = renderCache{tx: txt, lns: lns}
return lns
}
// The chars of the line are positioned in cells, where wide chars
// take two cells, and tabs go to tab stops.
cells := lines.LineCells(tx, ts)
cellX := func(ci int) float32 {
return float32(cells[min(ci, len(cells)-1)]) * ed.charSize.X
}
// rendSpan renders the given shaped span, starting at char coff,
// where tabCells is the width in cells of a tab, which is 0 otherwise.
rendSpan := func(lns *shaped.Lines, pos math32.Vector2, coff, tabCells int) {
// The shaped spans are cached (the tab, and the lines with the same
// text), so their colors are set from the current style of the
// editor, which changes with the color scheme, as from light to
// dark mode.
lns.Color, lns.SelectionColor, lns.HighlightColor = tsty.Color, ed.SelectColor, ed.HighlightColor
lns.SelectReset()
lns.HighlightReset()
if tabCells > 0 {
lns.SetGlyphXAdvance(math32.ToFixed(float32(tabCells)*ed.charSize.X), nil)
} else {
lns.SetGlyphXAdvance(math32.ToFixed(ed.charSize.X), lines.RuneWidth)
}
if !vseli.IsNil() {
lns.SelectRegion(textpos.Range{Start: vseli.Start.Char - coff, End: vseli.End.Char - coff})
}
for _, hlrg := range hlts {
hlsi := vlr.Intersect(hlrg, ed.linesSize.X)
if !hlsi.IsNil() {
lns.HighlightRegion(textpos.Range{Start: hlsi.Start.Char - coff, End: hlsi.End.Char - coff})
}
}
pc.DrawText(lns, pos)
}
// rendTab renders the tab at char ci.
rendTab := func(stx rich.Text, ci int) {
pos := rpos
pos.X += cellX(ci)
tsz := sz
tsz.X -= cellX(ci)
rendSpan(shapeTab(stx, tsz), pos, ci, cells[ci+1]-cells[ci])
}
for si := range tx { // tabs encoded as single chars at start
sn, rn := rich.SpanLen(tx[si])
if rn == 1 && tx[si][sn] == '\t' {
rendTab(tx[si:si+1], indent)
indent++
} else {
break
}
}
rtx := tx[indent:]
hasTab := false
for si := range rtx {
sn, rn := rich.SpanLen(rtx[si])
if rn > 0 && rtx[si][sn] == '\t' {
hasTab = true
break
}
}
if !hasTab {
lpos := rpos
lpos.X += cellX(indent)
lsz := sz
lsz.X -= cellX(indent)
rendSpan(shapeSpan(rtx, lsz), lpos, indent, 0)
return
}
coff := indent
for si := range rtx {
sn, rn := rich.SpanLen(rtx[si])
if rn == 0 {
continue
}
if rtx[si][sn] == '\t' {
for range rn {
rendTab(rtx[si:si+1], coff)
coff++
}
continue
}
spos := rpos
spos.X += cellX(coff)
ssz := sz
ssz.X -= cellX(coff)
rendSpan(shapeSpan(rtx[si:si+1], ssz), spos, coff, 0)
coff += rn
}
}
// renderLineNumbersBox renders the background for the line numbers in the LineNumberColor
func (ed *Base) renderLineNumbersBox() {
if !ed.hasLineNumbers {
return
}
pc := &ed.Scene.Painter
bb := ed.renderBBox()
spos := math32.FromPoint(bb.Min)
epos := math32.FromPoint(bb.Max)
epos.X = spos.X + ed.LineNumberPixels()
sz := epos.Sub(spos)
pc.Fill.Color = ed.LineNumberColor
pc.RoundedRectangleSides(spos.X, spos.Y, sz.X, sz.Y, ed.Styles.Border.Radius.Dots())
pc.Draw()
}
// renderLineNumber renders given line number at given li index.
func (ed *Base) renderLineNumber(pos math32.Vector2, li, ln int) {
if !ed.hasLineNumbers || ed.Lines == nil {
return
}
pos.Y += float32(li) * ed.charSize.Y
pc := &ed.Scene.Painter
sh := ed.Scene.TextShaper()
sty, tsty := ed.Styles.NewRichText()
sty.SetBackground(nil)
lfmt := fmt.Sprintf("%d", ed.lineNumberDigits)
lfmt = "%" + lfmt + "d"
lnstr := fmt.Sprintf(lfmt, ln+1)
if ed.CursorPos.Line == ln {
sty.SetFillColor(colors.ToUniform(colors.Scheme.Primary.Base))
sty.Weight = rich.Bold
} else {
sty.SetFillColor(colors.ToUniform(colors.Scheme.OnSurfaceVariant))
}
sz := ed.charSize
sz.X *= float32(ed.lineNumberOffset)
var lns *shaped.Lines
rc := ed.lineNoRenders[li]
tx := rich.NewText(sty, []rune(lnstr))
if rc.lns != nil && slices.Compare(rc.tx, tx[0]) == 0 { // captures styling
lns = rc.lns
} else {
lns = sh.WrapLines(tx, sty, tsty, sz)
ed.lineNoRenders[li] = renderCache{tx: tx[0], lns: lns}
}
pc.DrawText(lns, pos)
// render circle
lineColor, has := ed.Lines.LineColor(ln)
if has {
pos.X += float32(ed.lineNumberDigits) * ed.charSize.X
r := 0.7 * ed.charSize.X
center := pos.AddScalar(r)
center.Y += 0.3 * ed.charSize.Y
center.X += 0.3 * ed.charSize.X
pc.Fill.Color = lineColor
pc.Circle(center.X, center.Y, r)
pc.Draw()
}
}
func (ed *Base) LineNumberPixels() float32 {
return float32(ed.lineNumberOffset) * ed.charSize.X
}
// TODO: make viewDepthColors HCT based?
// viewDepthColors are changes in color values from default background for different
// depths. For dark mode, these are increments, for light mode they are decrements.
var viewDepthColors = []color.RGBA{
{0, 0, 0, 0},
{4, 4, 0, 0},
{8, 8, 0, 0},
{4, 8, 0, 0},
{0, 8, 4, 0},
{0, 8, 8, 0},
{0, 4, 8, 0},
{4, 0, 8, 0},
{4, 0, 4, 0},
}
// renderDepthBackground renders the depth background color.
func (ed *Base) renderDepthBackground(pos math32.Vector2, stln, edln int) {
if !ed.Lines.Settings.DepthColor || ed.IsDisabled() || !ed.StateIs(states.Focused) {
return
}
pos.X += ed.LineNumberPixels()
buf := ed.Lines
bbmax := float32(ed.Geom.ContentBBox.Max.X)
pc := &ed.Scene.Painter
sty := &ed.Styles
isDark := matcolor.SchemeIsDark
nclrs := len(viewDepthColors)
for ln := stln; ln <= edln; ln++ {
sp := ed.Lines.PosFromView(ed.viewID, textpos.Pos{Line: ln})
depth := buf.LineLexDepth(sp.Line)
if depth <= 0 {
continue
}
var vdc color.RGBA
if isDark { // reverse order too
vdc = viewDepthColors[(nclrs-1)-(depth%nclrs)]
} else {
vdc = viewDepthColors[depth%nclrs]
}
bg := gradient.Apply(sty.Background, func(c color.Color) color.Color {
if isDark { // reverse order too
return colors.Add(c, vdc)
}
return colors.Sub(c, vdc)
})
spos := pos
spos.Y += float32(ln-stln) * ed.charSize.Y
epos := spos
epos.Y += ed.charSize.Y
epos.X = bbmax
pc.FillBox(spos, epos.Sub(spos), bg)
}
}
// PixelToCursor finds the cursor position that corresponds to the given pixel
// location (e.g., from mouse click), in widget-relative coordinates.
func (ed *Base) PixelToCursor(pt image.Point) textpos.Pos {
if ed.Lines == nil {
return textpos.PosErr
}
stln, _, spos := ed.renderLineStartEnd()
ptf := math32.FromPoint(pt)
ptf.X += ed.Geom.Pos.Content.X
ptf.Y -= (spos.Y - ed.Geom.Pos.Content.Y) // fractional bit
cp := ptf.Div(ed.charSize)
if cp.Y < 0 {
return textpos.PosErr
}
// The chars of the view line are found in view coordinates, which
// include any virtual text, which maps to its source position.
// A point in the second half of a char is after it.
vln := stln + int(math32.Floor(cp.Y))
vpos := textpos.Pos{Line: vln, Char: 0}
stp := ed.viewCharStartPos(vpos)
if ptf.X < stp.X {
return ed.Lines.PosFromView(ed.viewID, vpos)
}
col := (ptf.X - stp.X) / ed.charSize.X
cells := ed.viewLineCells(vln)
vll := ed.Lines.ViewLineLen(ed.viewID, vln)
for cc := range min(vll, len(cells)-1) {
if 2*col < float32(cells[cc]+cells[cc+1]) {
vpos.Char = cc
return ed.Lines.PosFromView(ed.viewID, vpos)
}
}
vpos.Char = vll
return ed.Lines.PosFromView(ed.viewID, vpos)
}
// CharStartPos returns the starting (top left) render coords for the
// given source text position, in the same scene-based coordinates the
// editor uses to render text (see [Editor.charStartPos]). Popups such
// as the completion popup anchor themselves relative to this position.
func (ed *Base) CharStartPos(pos textpos.Pos) math32.Vector2 {
return ed.charStartPos(pos)
}
// charStartPos returns the starting (top left) render coords for the
// given source text position.
func (ed *Base) charStartPos(pos textpos.Pos) math32.Vector2 {
if ed.Lines == nil {
return math32.Vector2{}
}
return ed.viewCharStartPos(ed.Lines.PosToView(ed.viewID, pos))
}
// viewLineCells returns the cell column of the start of each char
// of the given view line, followed by its end (see [lines.LineCells]).
func (ed *Base) viewLineCells(vln int) []int {
ed.Lines.Lock() // required by ViewMarkupLine; never called from renderLines
tx := ed.Lines.ViewMarkupLine(ed.viewID, vln)
ed.Lines.Unlock()
return lines.LineCells(tx, ed.Lines.Settings.TabSize)
}
// viewCharStartPos returns the starting (top left) render coords for the
// given view position, in view lines and display chars, which include
// any virtual text. Positions beyond the end of the line are at its end.
func (ed *Base) viewCharStartPos(vpos textpos.Pos) math32.Vector2 {
if ed.Lines == nil {
return math32.Vector2{}
}
scpos := image.Point{}
if ed.Scene != nil {
scpos = ed.Scene.SceneGeom.Pos
}
spos := ed.Geom.Pos.Content.Add(math32.FromPoint(scpos))
spos.X += ed.LineNumberPixels() - ed.Geom.Scroll.X
spos.Y += (float32(vpos.Line) - ed.scrollPos) * ed.charSize.Y
cells := ed.viewLineCells(vpos.Line)
ci := min(max(vpos.Char, 0), len(cells)-1)
spos.X += float32(cells[ci]) * ed.charSize.X
return spos
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package textcore
import (
"cogentcore.org/core/base/fileinfo"
"cogentcore.org/core/base/fileinfo/mimedata"
"cogentcore.org/core/base/strcase"
"cogentcore.org/core/core"
"cogentcore.org/core/text/lines"
"cogentcore.org/core/text/textpos"
)
//////// Regions
// HighlightRegion adds a new highlighted region. Use HighlightsReset to
// clear any existing prior to this if only one region desired.
func (ed *Base) HighlightRegion(reg textpos.Region) {
ed.Highlights = append(ed.Highlights, reg)
ed.NeedsRender()
}
// HighlightsReset resets the list of all highlighted regions.
func (ed *Base) HighlightsReset() {
if len(ed.Highlights) == 0 {
return
}
ed.Highlights = ed.Highlights[:0]
ed.NeedsRender()
}
// scopelightsReset clears the scopelights slice of all regions.
// does needsrender if actually reset.
func (ed *Base) scopelightsReset() {
if len(ed.scopelights) == 0 {
return
}
sl := make([]textpos.Region, len(ed.scopelights))
copy(sl, ed.scopelights)
ed.scopelights = ed.scopelights[:0]
ed.NeedsRender()
}
func (ed *Base) addScopelights(st, end textpos.Pos) {
ed.scopelights = append(ed.scopelights, textpos.NewRegionPos(st, textpos.Pos{Line: st.Line, Char: st.Char + 1}))
ed.scopelights = append(ed.scopelights, textpos.NewRegionPos(end, textpos.Pos{Line: end.Line, Char: end.Char + 1}))
}
//////// Selection
// clearSelected resets both the global selected flag and any current selection
func (ed *Base) clearSelected() {
// ed.WidgetBase.ClearSelected()
ed.SelectReset()
}
// HasSelection returns whether there is a selected region of text
func (ed *Base) HasSelection() bool {
return ed.SelectRegion.Start.IsLess(ed.SelectRegion.End)
}
// validateSelection ensures that the selection region is still valid.
func (ed *Base) validateSelection() {
ed.SelectRegion.Start = ed.Lines.ValidPos(ed.SelectRegion.Start)
ed.SelectRegion.End = ed.Lines.ValidPos(ed.SelectRegion.End)
}
// Selection returns the currently selected text as a textpos.Edit, which
// captures start, end, and full lines in between -- nil if no selection
func (ed *Base) Selection() *textpos.Edit {
if ed.HasSelection() {
ed.validateSelection()
return ed.Lines.Region(ed.SelectRegion.Start, ed.SelectRegion.End)
}
return nil
}
// selectModeToggle toggles the SelectMode, updating selection with cursor movement
func (ed *Base) selectModeToggle() {
if ed.selectMode {
ed.selectMode = false
} else {
ed.selectMode = true
ed.selectStart = ed.CursorPos
ed.selectRegionUpdate(ed.CursorPos)
}
ed.savePosHistory(ed.CursorPos)
}
// selectRegionUpdate updates current select region based on given cursor position
// relative to SelectStart position
func (ed *Base) selectRegionUpdate(pos textpos.Pos) {
if pos.IsLess(ed.selectStart) {
ed.SelectRegion.Start = pos
ed.SelectRegion.End = ed.selectStart
} else {
ed.SelectRegion.Start = ed.selectStart
ed.SelectRegion.End = pos
}
}
// selectAll selects all the text
func (ed *Base) selectAll() {
ed.SelectRegion.Start = textpos.PosZero
ed.SelectRegion.End = ed.Lines.EndPos()
ed.NeedsRender()
}
// selectWord selects the word (whitespace, punctuation delimited) that the cursor is on.
// returns true if word selected
func (ed *Base) selectWord() bool {
if ed.Lines == nil {
return false
}
reg := ed.Lines.WordAt(ed.CursorPos)
ed.SelectRegion = reg
ed.selectStart = ed.SelectRegion.Start
return true
}
// SelectReset resets the selection
func (ed *Base) SelectReset() {
ed.selectMode = false
if !ed.HasSelection() {
return
}
ed.SelectRegion = textpos.Region{}
ed.previousSelectRegion = textpos.Region{}
}
//////// Undo / Redo
// undo undoes previous action
func (ed *Base) undo() {
tbes := ed.Lines.Undo()
if tbes != nil {
tbe := tbes[len(tbes)-1]
if tbe.Delete { // now an insert
ed.SetCursorShow(tbe.Region.End)
} else {
ed.SetCursorShow(tbe.Region.Start)
}
} else {
ed.SendInput() // updates status..
ed.scrollCursorToCenterIfHidden()
}
ed.savePosHistory(ed.CursorPos)
ed.NeedsRender()
}
// redo redoes previously undone action
func (ed *Base) redo() {
tbes := ed.Lines.Redo()
if tbes != nil {
tbe := tbes[len(tbes)-1]
if tbe.Delete {
ed.SetCursorShow(tbe.Region.Start)
} else {
ed.SetCursorShow(tbe.Region.End)
}
} else {
ed.scrollCursorToCenterIfHidden()
}
ed.savePosHistory(ed.CursorPos)
ed.NeedsRender()
}
//////// Cut / Copy / Paste
// editorClipboardHistory is the [Base] clipboard history; everything that has been copied
var editorClipboardHistory [][]byte
// addBaseClipboardHistory adds the given clipboard bytes to top of history stack
func addBaseClipboardHistory(clip []byte) {
max := clipboardHistoryMax
if editorClipboardHistory == nil {
editorClipboardHistory = make([][]byte, 0, max)
}
ch := &editorClipboardHistory
sz := len(*ch)
if sz > max {
*ch = (*ch)[:max]
}
if sz >= max {
copy((*ch)[1:max], (*ch)[0:max-1])
(*ch)[0] = clip
} else {
*ch = append(*ch, nil)
if sz > 0 {
copy((*ch)[1:], (*ch)[0:sz])
}
(*ch)[0] = clip
}
}
// editorClipHistoryChooserLength is the max length of clip history to show in chooser
var editorClipHistoryChooserLength = 40
// editorClipHistoryChooserList returns a string slice of length-limited clip history, for chooser
func editorClipHistoryChooserList() []string {
cl := make([]string, len(editorClipboardHistory))
for i, hc := range editorClipboardHistory {
szl := len(hc)
if szl > editorClipHistoryChooserLength {
cl[i] = string(hc[:editorClipHistoryChooserLength])
} else {
cl[i] = string(hc)
}
}
return cl
}
// pasteHistory presents a chooser of clip history items, pastes into text if selected
func (ed *Base) pasteHistory() {
if editorClipboardHistory == nil {
return
}
cl := editorClipHistoryChooserList()
m := core.NewMenuFromStrings(cl, "", func(idx int) {
clip := editorClipboardHistory[idx]
if clip != nil {
ed.Clipboard().Write(mimedata.NewTextBytes(clip))
ed.InsertAtCursor(clip)
ed.savePosHistory(ed.CursorPos)
ed.NeedsRender()
}
})
core.NewMenuStage(m, ed, ed.cursorBBox(ed.CursorPos).Min).Run()
}
// Cut cuts any selected text and adds it to the clipboard, also returns cut text
func (ed *Base) Cut() *textpos.Edit {
if !ed.HasSelection() {
return nil
}
ed.validateSelection()
org := ed.SelectRegion.Start
cut := ed.deleteSelection()
if cut != nil {
cb := cut.ToBytes()
ed.Clipboard().Write(mimedata.NewTextBytes(cb))
addBaseClipboardHistory(cb)
}
ed.SetCursorShow(org)
ed.savePosHistory(ed.CursorPos)
ed.NeedsRender()
return cut
}
// deleteSelection deletes any selected text, without adding to clipboard --
// returns text deleted as textpos.Edit (nil if none)
func (ed *Base) deleteSelection() *textpos.Edit {
ed.validateSelection()
tbe := ed.Lines.DeleteText(ed.SelectRegion.Start, ed.SelectRegion.End)
ed.SelectReset()
return tbe
}
// Copy copies any selected text to the clipboard, and returns that text,
// optionally resetting the current selection
func (ed *Base) Copy(reset core.SelectionReset) *textpos.Edit {
tbe := ed.Selection()
if tbe == nil {
return nil
}
cb := tbe.ToBytes()
addBaseClipboardHistory(cb)
ed.Clipboard().Write(mimedata.NewTextBytes(cb))
if reset {
ed.SelectReset()
}
ed.savePosHistory(ed.CursorPos)
ed.NeedsRender()
return tbe
}
// Paste inserts text from the clipboard at current cursor position
func (ed *Base) Paste() {
data := ed.Clipboard().Read([]string{fileinfo.TextPlain})
if data != nil {
ed.InsertAtCursor(data.TypeData(fileinfo.TextPlain))
ed.savePosHistory(ed.CursorPos)
}
ed.NeedsRender()
}
// InsertAtCursor inserts given text at current cursor position
func (ed *Base) InsertAtCursor(txt []byte) {
if ed.HasSelection() {
tbe := ed.deleteSelection()
ed.CursorPos = tbe.AdjustPos(ed.CursorPos, textpos.AdjustPosDelStart) // move to start if in reg
}
cp := ed.validateCursor()
tbe := ed.Lines.InsertText(cp, []rune(string(txt)))
if tbe == nil {
return
}
pos := tbe.Region.End
if len(txt) == 1 && txt[0] == '\n' {
pos.Char = 0 // sometimes it doesn't go to the start..
}
ed.SetCursorShow(pos)
ed.setCursorColumn(ed.CursorPos)
ed.NeedsRender()
}
//////// Rectangular regions
// editorClipboardRect is the internal clipboard for Rect rectangle-based
// regions -- the raw text is posted on the system clipboard but the
// rect information is in a special format.
var editorClipboardRect *textpos.Edit
// CutRect cuts rectangle defined by selected text (upper left to lower right)
// and adds it to the clipboard, also returns cut lines.
func (ed *Base) CutRect() *textpos.Edit {
if !ed.HasSelection() {
return nil
}
ed.validateSelection()
npos := textpos.Pos{Line: ed.SelectRegion.End.Line, Char: ed.SelectRegion.Start.Char}
cut := ed.Lines.DeleteTextRect(ed.SelectRegion.Start, ed.SelectRegion.End)
if cut != nil {
cb := cut.ToBytes()
ed.Clipboard().Write(mimedata.NewTextBytes(cb))
editorClipboardRect = cut
}
ed.SetCursorShow(npos)
ed.savePosHistory(ed.CursorPos)
ed.NeedsRender()
return cut
}
// CopyRect copies any selected text to the clipboard, and returns that text,
// optionally resetting the current selection
func (ed *Base) CopyRect(reset core.SelectionReset) *textpos.Edit {
ed.validateSelection()
tbe := ed.Lines.RegionRect(ed.SelectRegion.Start, ed.SelectRegion.End)
if tbe == nil {
return nil
}
cb := tbe.ToBytes()
ed.Clipboard().Write(mimedata.NewTextBytes(cb))
editorClipboardRect = tbe
if reset {
ed.SelectReset()
}
ed.savePosHistory(ed.CursorPos)
ed.NeedsRender()
return tbe
}
// PasteRect inserts text from the clipboard at current cursor position
func (ed *Base) PasteRect() {
if editorClipboardRect == nil {
return
}
ce := editorClipboardRect.Clone()
nl := ce.Region.End.Line - ce.Region.Start.Line
nch := ce.Region.End.Char - ce.Region.Start.Char
ce.Region.Start.Line = ed.CursorPos.Line
ce.Region.End.Line = ed.CursorPos.Line + nl
ce.Region.Start.Char = ed.CursorPos.Char
ce.Region.End.Char = ed.CursorPos.Char + nch
tbe := ed.Lines.InsertTextRect(ce)
pos := tbe.Region.End
ed.SetCursorShow(pos)
ed.setCursorColumn(ed.CursorPos)
ed.savePosHistory(ed.CursorPos)
ed.NeedsRender()
}
// ReCaseSelection changes the case of the currently selected lines.
// Returns the new text; empty if nothing selected.
func (ed *Base) ReCaseSelection(c strcase.Cases) string {
if !ed.HasSelection() {
return ""
}
sel := ed.Selection()
nstr := strcase.To(string(sel.ToBytes()), c)
ed.Lines.ReplaceText(sel.Region.Start, sel.Region.End, sel.Region.Start, nstr, lines.ReplaceNoMatchCase)
return nstr
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package textcore
import (
"strings"
"unicode"
"cogentcore.org/core/base/fileinfo"
"cogentcore.org/core/events"
"cogentcore.org/core/keymap"
"cogentcore.org/core/text/lines"
"cogentcore.org/core/text/parse/lexer"
"cogentcore.org/core/text/spell"
"cogentcore.org/core/text/textpos"
"cogentcore.org/core/text/token"
)
// iSpellKeyInput locates the word to spell check based on cursor position and
// the key input, then passes the text region to SpellCheck
func (ed *Editor) iSpellKeyInput(kt events.Event) {
if !ed.isSpellEnabled(ed.CursorPos) {
return
}
isDoc := ed.Lines.FileInfo().Cat == fileinfo.Doc
tp := ed.CursorPos
kf := keymap.Of(kt.KeyChord())
switch kf {
case keymap.MoveUp:
if isDoc {
ed.spellCheckLineTag(tp.Line)
}
case keymap.MoveDown:
if isDoc {
ed.spellCheckLineTag(tp.Line)
}
case keymap.MoveRight:
if ed.Lines.IsWordEnd(tp) {
reg := ed.Lines.WordBefore(tp)
ed.spellCheck(reg)
break
}
if tp.Char == 0 { // end of line
tp.Line--
if tp.Line < 0 {
tp.Line = 0
}
if isDoc {
ed.spellCheckLineTag(tp.Line) // redo prior line
}
tp.Char = ed.Lines.LineLen(tp.Line)
reg := ed.Lines.WordBefore(tp)
ed.spellCheck(reg)
break
}
txt := ed.Lines.Line(tp.Line)
var r rune
atend := false
if tp.Char >= len(txt) {
atend = true
tp.Char++
} else {
r = txt[tp.Char]
}
if atend || textpos.IsWordBreak(r, rune(-1)) {
tp.Char-- // we are one past the end of word
if tp.Char < 0 {
tp.Char = 0
}
reg := ed.Lines.WordBefore(tp)
ed.spellCheck(reg)
}
case keymap.Enter:
tp.Line--
if tp.Line < 0 {
tp.Line = 0
}
if isDoc {
ed.spellCheckLineTag(tp.Line) // redo prior line
}
tp.Char = ed.Lines.LineLen(tp.Line)
reg := ed.Lines.WordBefore(tp)
ed.spellCheck(reg)
case keymap.FocusNext:
tp.Char-- // we are one past the end of word
if tp.Char < 0 {
tp.Char = 0
}
reg := ed.Lines.WordBefore(tp)
ed.spellCheck(reg)
case keymap.Backspace, keymap.Delete:
if ed.Lines.IsWordMiddle(ed.CursorPos) {
reg := ed.Lines.WordAt(ed.CursorPos)
ed.spellCheck(ed.Lines.Region(reg.Start, reg.End))
} else {
reg := ed.Lines.WordBefore(tp)
ed.spellCheck(reg)
}
case keymap.None:
if unicode.IsSpace(kt.KeyRune()) || unicode.IsPunct(kt.KeyRune()) && kt.KeyRune() != '\'' { // contractions!
tp.Char-- // we are one past the end of word
if tp.Char < 0 {
tp.Char = 0
}
reg := ed.Lines.WordBefore(tp)
ed.spellCheck(reg)
} else {
if ed.Lines.IsWordMiddle(ed.CursorPos) {
reg := ed.Lines.WordAt(ed.CursorPos)
ed.spellCheck(ed.Lines.Region(reg.Start, reg.End))
}
}
}
}
// spellCheck offers spelling corrections if we are at a word break or other word termination
// and the word before the break is unknown -- returns true if misspelled word found
func (ed *Editor) spellCheck(reg *textpos.Edit) bool {
if ed.spell == nil {
return false
}
wb := string(reg.ToBytes())
lwb := lexer.FirstWordApostrophe(wb) // only lookup words
if len(lwb) <= 2 {
return false
}
widx := strings.Index(wb, lwb) // adjust region for actual part looking up
ld := len(wb) - len(lwb)
reg.Region.Start.Char += widx
reg.Region.End.Char += widx - ld
sugs, knwn := ed.spell.checkWord(lwb)
if knwn {
ed.Lines.RemoveTag(reg.Region.Start, token.TextSpellErr)
return false
}
// fmt.Printf("spell err: %s\n", wb)
ed.spell.setWord(wb, sugs, reg.Region.Start.Line, reg.Region.Start.Char)
ed.Lines.RemoveTag(reg.Region.Start, token.TextSpellErr)
ed.Lines.AddTagEdit(reg, token.TextSpellErr)
return true
}
// OfferCorrect pops up a menu of possible spelling corrections for the
// word at the current CursorPos, if spelling correction is enabled there
// and the word is misspelled, as the [keymap.Complete] key does.
// Returns false if no menu was shown.
func (ed *Editor) OfferCorrect() bool {
if !ed.isSpellEnabled(ed.CursorPos) {
return false
}
return ed.offerCorrect()
}
// offerCorrect pops up a menu of possible spelling corrections for word at
// current CursorPos. If no misspelling there or not in spellcorrect mode
// returns false
func (ed *Editor) offerCorrect() bool {
if ed.spell == nil || ed.ISearch.On || ed.QReplace.On || ed.IsDisabled() {
return false
}
sel := ed.SelectRegion
if !ed.selectWord() {
ed.SelectRegion = sel
return false
}
tbe := ed.Selection()
if tbe == nil {
ed.SelectRegion = sel
return false
}
ed.SelectRegion = sel
wb := string(tbe.ToBytes())
wbn := strings.TrimLeft(wb, " \t")
if len(wb) != len(wbn) {
return false // SelectWord captures leading whitespace - don't offer if there is leading whitespace
}
sugs, knwn := ed.spell.checkWord(wb)
if knwn && !ed.spell.isLastLearned(wb) {
return false
}
ed.spell.setWord(wb, sugs, tbe.Region.Start.Line, tbe.Region.Start.Char)
cpos := ed.charStartPos(ed.CursorPos).ToPoint() // physical location
cpos.X += 5
cpos.Y += 10
ed.spell.show(wb, ed.Scene, cpos)
return true
}
// cancelCorrect cancels any pending spell correction.
// Call this when new events have moved beyond any prior correction scenario.
func (ed *Editor) cancelCorrect() {
if ed.spell == nil || ed.ISearch.On || ed.QReplace.On {
return
}
if !ed.Lines.Settings.SpellCorrect {
return
}
ed.spell.cancel()
}
// isSpellEnabled returns true if spelling correction is enabled,
// taking into account given position in text if it is relevant for cases
// where it is only conditionally enabled
func (ed *Editor) isSpellEnabled(pos textpos.Pos) bool {
if ed.spell == nil || !ed.Lines.Settings.SpellCorrect {
return false
}
switch ed.Lines.FileInfo().Cat {
case fileinfo.Doc: // not in code!
return !ed.Lines.InTokenCode(pos)
case fileinfo.Code:
return ed.Lines.InComment(pos) || ed.Lines.InLitString(pos)
default:
return false
}
}
// setSpell sets spell correct functions so that spell correct will
// automatically be offered as the user types
func (ed *Editor) setSpell() {
if ed.spell != nil {
return
}
initSpell()
ed.spell = newSpell()
ed.spell.onSelect(func(e events.Event) {
ed.correctText(ed.spell.correction)
})
}
// correctText edits the text using the string chosen from the correction menu
func (ed *Editor) correctText(s string) {
st := textpos.Pos{Line: ed.spell.srcLn, Char: ed.spell.srcCh} // start of word
ed.Lines.RemoveTag(st, token.TextSpellErr)
oend := st
oend.Char += len(ed.spell.word)
ed.Lines.ReplaceText(st, oend, st, s, lines.ReplaceNoMatchCase)
ep := st
ep.Char += len(s)
ed.SetCursorShow(ep)
}
// SpellCheckLineErrors runs spell check on given line, and returns Lex tags
// with token.TextSpellErr for any misspelled words
func (ed *Editor) SpellCheckLineErrors(ln int) lexer.Line {
if !ed.Lines.IsValidLine(ln) {
return nil
}
return spell.CheckLexLine(ed.Lines.Line(ln), ed.Lines.HiTags(ln))
}
// spellCheckLineTag runs spell check on given line, and sets Tags for any
// misspelled words and updates markup for that line.
func (ed *Editor) spellCheckLineTag(ln int) {
if !ed.Lines.IsValidLine(ln) {
return
}
ser := ed.SpellCheckLineErrors(ln)
ntgs := ed.Lines.AdjustedTags(ln)
ntgs.DeleteToken(token.TextSpellErr)
for _, t := range ser {
ntgs.AddSort(t)
}
ed.Lines.SetTags(ln, ntgs)
ed.Lines.MarkupLines(ln, ln)
ed.Lines.StartDelayedReMarkup()
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package textcore
// TODO: consider moving back to core or somewhere else based on the
// result of https://github.com/cogentcore/core/issues/711
import (
"image"
"log/slog"
"path/filepath"
"strings"
"sync"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/text/spell"
)
// initSpell ensures that the [spell.Spell] spell checker is set up.
func initSpell() error {
if spell.Spell != nil {
return nil
}
pdir := core.TheApp.CogentCoreDataDir()
openpath := filepath.Join(pdir, "user_dict_en_us")
if !spell.HasNative() && core.TheApp.Platform().IsMobile() {
return nil // the built-in checker is too slow on mobile
}
spell.Spell = spell.NewSpell(openpath)
return nil
}
// spellCheck has all the texteditor spell check state
type spellCheck struct {
// line number in source that spelling is operating on, if relevant
srcLn int
// character position in source that spelling is operating on (start of word to be corrected)
srcCh int
// list of suggested corrections
suggest []string
// word being checked
word string
// last word learned, which can be undone
lastLearned string
// the user's correction selection
correction string
// the event listeners for the spell (it sends Select events)
listeners events.Listeners
// stage is the popup [core.Stage] associated with the [spellState]
stage *core.Stage
showMu sync.Mutex
}
// newSpell returns a new [spellState]
func newSpell() *spellCheck {
initSpell()
return &spellCheck{}
}
// checkWord checks the model to determine if the word is known,
// bool is true if known, false otherwise. If not known,
// returns suggestions for close matching words.
func (sp *spellCheck) checkWord(word string) ([]string, bool) {
if spell.Spell == nil {
return nil, false
}
return spell.Spell.CheckWord(word)
}
// setWord sets the word to spell and other associated info
func (sp *spellCheck) setWord(word string, sugs []string, srcLn, srcCh int) *spellCheck {
sp.word = word
sp.suggest = sugs
sp.srcLn = srcLn
sp.srcCh = srcCh
return sp
}
// show is the main call for listing spelling corrections.
// Calls ShowNow which builds the correction popup menu
// Similar to completion.show but does not use a timer
// Displays popup immediately for any unknown word
func (sp *spellCheck) show(text string, ctx core.Widget, pos image.Point) {
if sp.stage != nil {
sp.cancel()
}
sp.showNow(text, ctx, pos)
}
// showNow actually builds the correction popup menu
func (sp *spellCheck) showNow(word string, ctx core.Widget, pos image.Point) {
if sp.stage != nil {
sp.cancel()
}
sp.showMu.Lock()
defer sp.showMu.Unlock()
sc := core.NewScene(ctx.AsTree().Name + "-spell")
core.StyleMenuScene(sc)
sp.stage = core.NewPopupStage(core.CompleterStage, sc, ctx).SetPos(pos)
if sp.isLastLearned(word) {
core.NewButton(sc).SetText("unlearn").SetTooltip("unlearn the last learned word").
OnClick(func(e events.Event) {
sp.cancel()
sp.unLearnLast()
})
} else {
count := len(sp.suggest)
if count == 1 && sp.suggest[0] == word {
return
}
if count == 0 {
core.NewButton(sc).SetText("no suggestion")
} else {
for i := range count {
text := sp.suggest[i]
core.NewButton(sc).SetText(text).OnClick(func(e events.Event) {
sp.cancel()
sp.spell(text)
})
}
}
core.NewSeparator(sc)
core.NewButton(sc).SetText("learn").OnClick(func(e events.Event) {
sp.cancel()
sp.learnWord()
})
core.NewButton(sc).SetText("ignore").OnClick(func(e events.Event) {
sp.cancel()
sp.ignoreWord()
})
}
if sc.NumChildren() > 0 {
sc.Events.SetStartFocus(sc.Child(0).(core.Widget))
}
sp.stage.Run()
}
// spell sends a Select event to Listeners indicating that the user has made a
// selection from the list of possible corrections
func (sp *spellCheck) spell(s string) {
sp.cancel()
sp.correction = s
sp.listeners.Call(&events.Base{Typ: events.Select})
}
// onSelect registers given listener function for Select events on Value.
// This is the primary notification event for all Complete elements.
func (sp *spellCheck) onSelect(fun func(e events.Event)) {
sp.on(events.Select, fun)
}
// on adds an event listener function for the given event type
func (sp *spellCheck) on(etype events.Types, fun func(e events.Event)) {
sp.listeners.Add(etype, fun)
}
// learnWord gets the misspelled/unknown word and passes to learnWord
func (sp *spellCheck) learnWord() {
sp.lastLearned = sp.word
spell.Spell.AddWord(sp.word)
}
// isLastLearned returns true if given word was the last one learned
func (sp *spellCheck) isLastLearned(wrd string) bool {
return sp.lastLearned != "" && strings.EqualFold(wrd, sp.lastLearned)
}
// unLearnLast unlearns the last learned word -- in case accidental
func (sp *spellCheck) unLearnLast() {
if sp.lastLearned == "" {
slog.Error("spell.UnLearnLast: no last learned word")
return
}
lword := sp.lastLearned
sp.lastLearned = ""
spell.Spell.DeleteWord(lword)
}
// ignoreWord adds the word to the ignore list
func (sp *spellCheck) ignoreWord() {
spell.Spell.IgnoreWord(sp.word)
}
// cancel cancels any pending spell correction.
// call when new events nullify prior correction.
// returns true if canceled
func (sp *spellCheck) cancel() bool {
if sp.stage == nil {
return false
}
st := sp.stage
sp.stage = nil
st.ClosePopup()
return true
}
// Copyright (c) 2020, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package textcore
import (
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/styles"
"cogentcore.org/core/text/lines"
"cogentcore.org/core/tree"
)
// TwinEditors presents two side-by-side [Editor]s in [core.Splits]
// that scroll in sync with each other.
type TwinEditors struct {
core.Splits
// [Buffer] for A
BufferA *lines.Lines `json:"-" xml:"-"`
// [Buffer] for B
BufferB *lines.Lines `json:"-" xml:"-"`
inInputEvent bool
}
func (te *TwinEditors) Init() {
te.Splits.Init()
te.BufferA = lines.NewLines()
te.BufferB = lines.NewLines()
f := func(name string, buf *lines.Lines) {
tree.AddChildAt(te, name, func(w *Editor) {
w.SetLines(buf)
w.Styler(func(s *styles.Style) {
s.Min.X.Ch(80)
s.Min.Y.Em(40)
})
w.On(events.Scroll, func(e events.Event) {
te.syncEditors(events.Scroll, name)
})
w.On(events.Input, func(e events.Event) {
te.syncEditors(events.Input, name)
})
})
}
f("text-a", te.BufferA)
f("text-b", te.BufferB)
}
// SetFiles sets the files for each [Buffer].
func (te *TwinEditors) SetFiles(fileA, fileB string) {
te.BufferA.SetFilename(fileA)
te.BufferA.Stat() // update markup
te.BufferB.SetFilename(fileB)
te.BufferB.Stat() // update markup
}
// syncEditors synchronizes the [Editor] scrolling and cursor positions
func (te *TwinEditors) syncEditors(typ events.Types, name string) {
tva, tvb := te.Editors()
me, other := tva, tvb
if name == "text-b" {
me, other = tvb, tva
}
switch typ {
case events.Scroll:
other.updateScroll(me.scrollPos)
case events.Input:
if te.inInputEvent {
return
}
te.inInputEvent = true
other.SetCursorShow(me.CursorPos)
te.inInputEvent = false
}
}
// Editors returns the two text [Editor]s.
func (te *TwinEditors) Editors() (*Editor, *Editor) {
ae := te.Child(0).(*Editor)
be := te.Child(1).(*Editor)
return ae, be
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package textcore
import (
"cogentcore.org/core/colors"
"cogentcore.org/core/math32"
"cogentcore.org/core/text/lines"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/textpos"
)
// SetVirtualText sets the virtual text in the given layer that is shown
// only in this editor, such as the composition of an input method or
// a suggested completion (see [lines.Lines.SetVirtualText]).
// Virtual text shown in all editors of the same [lines.Lines], such as
// language server inlay hints, is set on the Lines directly, with a
// view of -1.
func (ed *Base) SetVirtualText(layer string, vts ...lines.VirtualText) {
if ed.Lines == nil {
return
}
ed.Lines.SetVirtualText(layer, ed.viewID, vts...)
}
// ClearVirtualText removes the virtual text in the given layer
// that is shown only in this editor.
func (ed *Base) ClearVirtualText(layer string) {
ed.SetVirtualText(layer)
}
// VirtualText returns the virtual text in the given layer that is
// shown only in this editor, with positions updated for any edits.
func (ed *Base) VirtualText(layer string) []lines.VirtualText {
if ed.Lines == nil {
return nil
}
return ed.Lines.VirtualText(layer, ed.viewID)
}
// VirtualCharStartPos returns the starting (top left) render coords of the
// char at the given offset within the virtual text in the given layer at
// the given source position (see [lines.Lines.VirtualTextView]), in the
// same coordinates as [Base.CharStartPos]. For example, an input method
// places its candidate window at its composition cursor. It returns false
// if there is no such virtual text shown in this editor.
func (ed *Base) VirtualCharStartPos(layer string, pos textpos.Pos, offset int) (math32.Vector2, bool) {
if ed.Lines == nil {
return math32.Vector2{}, false
}
vp, ok := ed.Lines.VirtualTextView(ed.viewID, layer, pos, offset)
if !ok {
return math32.Vector2{}, false
}
return ed.viewCharStartPos(vp), true
}
// virtualStyle returns a copy of the font style of the text.
func (ed *Base) virtualStyle() *rich.Style {
sty := *rich.NewStyle()
if ed.Lines != nil {
sty = *ed.Lines.FontStyle()
}
return &sty
}
// CompositionStyle returns the style for the composition of an input
// method, which is underlined.
func (ed *Base) CompositionStyle() *rich.Style {
return ed.virtualStyle().SetDecoration(rich.Underline)
}
// HintStyle returns the style for hints, such as language server
// inlay hints, which are dimmed, on a subtle background.
func (ed *Base) HintStyle() *rich.Style {
sty := ed.virtualStyle()
sty.SetFillColor(colors.ToUniform(colors.Scheme.OnSurfaceVariant))
sty.SetBackground(colors.ToUniform(colors.Scheme.SurfaceContainerHigh))
return sty
}
// SuggestionStyle returns the style for suggested text, such as
// suggested completions, which is dimmed and italic.
func (ed *Base) SuggestionStyle() *rich.Style {
sty := ed.virtualStyle()
sty.Slant = rich.Italic
sty.SetFillColor(colors.ToUniform(colors.Scheme.OnSurfaceVariant))
return sty
}
// Copyright (c) 2020, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package textpos
//go:generate core generate
import (
"fmt"
"slices"
"strings"
"time"
"cogentcore.org/core/text/runes"
)
// Edit describes an edit action to line-based text, operating on
// a [Region] of the text.
// Actions are only deletions and insertions (a change is a sequence
// of each, given normal editing processes).
type Edit struct {
// Region for the edit, specifying the region to delete, or the size
// of the region to insert, corresponding to the Text.
// Also contains the Time stamp for this edit.
Region Region
// Text deleted or inserted, in rune lines. For Rect this is the
// spanning character distance per line, times number of lines.
Text [][]rune
// Group is the optional grouping number, for grouping edits in Undo for example.
Group int
// Delete indicates a deletion, otherwise an insertion.
Delete bool
// Rect is a rectangular region with upper left corner = Region.Start
// and lower right corner = Region.End.
// Otherwise it is for the full continuous region.
Rect bool
}
// NewEditFromRunes returns a 0-based edit from given runes.
func NewEditFromRunes(text []rune) *Edit {
if len(text) == 0 {
return &Edit{}
}
lns := runes.Split(text, []rune("\n"))
nl := len(lns)
ec := len(lns[nl-1])
ed := &Edit{}
ed.Region = NewRegion(0, 0, nl-1, ec)
ed.Text = lns
return ed
}
// ToBytes returns the Text of this edit record to a byte string, with
// newlines at end of each line -- nil if Text is empty
func (te *Edit) ToBytes() []byte {
if te == nil {
return nil
}
sz := len(te.Text)
if sz == 0 {
return nil
}
if sz == 1 {
return []byte(string(te.Text[0]))
}
tsz := 0
for i := range te.Text {
tsz += len(te.Text[i]) + 10 // don't bother converting to runes, just extra slack
}
b := make([]byte, 0, tsz)
for i := range te.Text {
b = append(b, []byte(string(te.Text[i]))...)
if i < sz-1 {
b = append(b, '\n')
}
}
return b
}
// AdjustPos adjusts the given text position as a function of the edit.
// If the position was within a deleted region of text, del determines
// what is returned.
func (te *Edit) AdjustPos(pos Pos, del AdjustPosDel) Pos {
if te == nil {
return pos
}
if pos.IsLess(te.Region.Start) || pos == te.Region.Start {
return pos
}
st, ed := te.Region.Start, te.Region.End
dl := ed.Line - st.Line
if te.Delete {
// pos is before the edit, so the deleted region is in it
if pos.IsLess(ed) {
switch del {
case AdjustPosDelStart:
return st
case AdjustPosDelEnd:
return ed
case AdjustPosDelErr:
return PosErr
}
}
// the rest of the end line joins the start line
if pos.Line == ed.Line {
return Pos{Line: st.Line, Char: st.Char + pos.Char - ed.Char}
}
pos.Line -= dl
return pos
}
// pos is before the insert: the rest of the start line moves to the
// end of the inserted text
if pos.Line == st.Line {
return Pos{Line: ed.Line, Char: ed.Char + pos.Char - st.Char}
}
pos.Line += dl
return pos
}
// AdjustPosDel determines what to do with positions within deleted region
type AdjustPosDel int32 //enums:enum
// these are options for what to do with positions within deleted region
// for the AdjustPos function
const (
// AdjustPosDelErr means return a PosErr when in deleted region.
AdjustPosDelErr AdjustPosDel = iota
// AdjustPosDelStart means return start of deleted region.
AdjustPosDelStart
// AdjustPosDelEnd means return end of deleted region.
AdjustPosDelEnd
)
// Clone returns a clone of the edit record.
func (te *Edit) Clone() *Edit {
rc := &Edit{}
rc.Copy(te)
return rc
}
// Copy copies from other Edit, making a clone of the source text.
func (te *Edit) Copy(cp *Edit) {
*te = *cp
nl := len(cp.Text)
if nl == 0 {
te.Text = nil
return
}
te.Text = make([][]rune, nl)
for i, r := range cp.Text {
te.Text[i] = slices.Clone(r)
}
}
// AdjustPosIfAfterTime checks the time stamp and IfAfterTime,
// it adjusts the given text position as a function of the edit
// del determines what to do with positions within a deleted region
// either move to start or end of the region, or return an error.
func (te *Edit) AdjustPosIfAfterTime(pos Pos, t time.Time, del AdjustPosDel) Pos {
if te == nil {
return pos
}
if te.Region.IsAfterTime(t) {
return te.AdjustPos(pos, del)
}
return pos
}
// AdjustRegion adjusts the given text region as a function of the edit, including
// checking that the timestamp on the region is after the edit time, if
// the region has a valid Time stamp (otherwise always does adjustment).
// If the starting position is within a deleted region, it is moved to the
// end of the deleted region, and if the ending position was within a deleted
// region, it is moved to the start.
func (te *Edit) AdjustRegion(reg Region) Region {
if te == nil {
return reg
}
if !reg.Time.IsZero() && !te.Region.IsAfterTime(reg.Time.Time()) {
return reg
}
reg.Start = te.AdjustPos(reg.Start, AdjustPosDelEnd)
reg.End = te.AdjustPos(reg.End, AdjustPosDelStart)
if reg.IsNil() {
return Region{}
}
return reg
}
func (te *Edit) String() string {
var str strings.Builder
str.WriteString(te.Region.String())
if te.Rect {
str.WriteString(" [Rect]")
}
if te.Delete {
str.WriteString(" [Delete]")
}
fmt.Fprintf(&str, " Gp: %d\n", te.Group)
for li := range te.Text {
fmt.Fprintf(&str, "%d\t%s\n", li, string(te.Text[li]))
}
return str.String()
}
// Copyright (c) 2020, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package textpos
// Match records one match for search within file, positions in runes.
type Match struct {
// Region of the match. Column positions are in runes.
Region Region
// Text surrounding the match, at most MatchContext on either side
// (within a single line).
Text []rune
// TextMatch has the Range within the Text where the match is.
TextMatch Range
}
func (m *Match) String() string {
return m.Region.String() + ": " + string(m.Text)
}
// MatchContext is how much text to include on either side of the match.
var MatchContext = 30
// NewMatch returns a new Match entry for given rune line with match starting
// at st and ending before ed, on given line
func NewMatch(rn []rune, st, ed, ln int) Match {
sz := len(rn)
reg := NewRegion(ln, st, ln, ed)
cist := max(st-MatchContext, 0)
cied := min(ed+MatchContext, sz)
sctx := rn[cist:st]
fstr := rn[st:ed]
ectx := rn[ed:cied]
tlen := len(sctx) + len(fstr) + len(ectx)
txt := make([]rune, tlen)
copy(txt, sctx)
ti := st - cist
copy(txt[ti:], fstr)
ti += len(fstr)
copy(txt[ti:], ectx)
return Match{Region: reg, Text: txt, TextMatch: Range{Start: len(sctx), End: len(sctx) + len(fstr)}}
}
// CaseSensitive specifies whether a search is case-sensitive: [UseCase] or
// [IgnoreCase].
type CaseSensitive bool
const (
// UseCase is passed to search functions for a case-sensitive search.
UseCase CaseSensitive = true
// IgnoreCase is passed to search functions for a search that ignores case.
IgnoreCase CaseSensitive = false
)
// MatchSyntax specifies whether a search string is a regular expression
// ([RegExp], in the syntax of the regexp package) or literal text ([Literal]).
type MatchSyntax bool
const (
// RegExp searches for a regular expression.
RegExp MatchSyntax = true
// Literal searches for the literal text.
Literal MatchSyntax = false
)
// MatchScope specifies whether a search only matches entire lexically tagged
// items ([LexItems]) or any text ([AnyText]).
type MatchScope bool
const (
// LexItems only matches entire lexically tagged items, e.g., whole words.
LexItems MatchScope = true
// AnyText matches any text.
AnyText MatchScope = false
)
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package textpos provides positions, ranges, regions, and edits of text in
// lines of runes.
package textpos
import (
"fmt"
"strings"
)
// Pos is a text position in terms of line and character index within a line,
// using 0-based line numbers, which are converted to 1 base for the String()
// representation. Char positions are always in runes, and can also
// be used for other units such as tokens, spans, or runs.
type Pos struct {
Line int
Char int
}
// AddLine returns a Pos with Line number added.
func (ps Pos) AddLine(ln int) Pos {
ps.Line += ln
return ps
}
// AddChar returns a Pos with Char number added.
func (ps Pos) AddChar(ch int) Pos {
ps.Char += ch
return ps
}
// String satisfies the fmt.Stringer interferace
func (ps Pos) String() string {
s := fmt.Sprintf("%d", ps.Line+1)
if ps.Char != 0 {
s += fmt.Sprintf(":%d", ps.Char)
}
return s
}
var (
// PosErr represents an error text position (-1 for both line and char)
// used as a return value for cases where error positions are possible.
PosErr = Pos{-1, -1}
PosZero = Pos{}
)
// IsLess returns true if receiver position is less than given comparison.
func (ps Pos) IsLess(cmp Pos) bool {
switch {
case ps.Line < cmp.Line:
return true
case ps.Line == cmp.Line:
return ps.Char < cmp.Char
default:
return false
}
}
// FromString decodes text position from a string representation of form:
// [#]LxxCxx. Used in e.g., URL links. Returns true if successful.
func (ps *Pos) FromString(link string) bool {
link = strings.TrimPrefix(link, "#")
lidx := strings.Index(link, "L")
cidx := strings.Index(link, "C")
switch {
case lidx >= 0 && cidx >= 0:
fmt.Sscanf(link, "L%dC%d", &ps.Line, &ps.Char)
ps.Line-- // link is 1-based, we use 0-based
ps.Char-- // ditto
case lidx >= 0:
fmt.Sscanf(link, "L%d", &ps.Line)
ps.Line-- // link is 1-based, we use 0-based
case cidx >= 0:
fmt.Sscanf(link, "C%d", &ps.Char)
ps.Char--
default:
// todo: could support other formats
return false
}
return true
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package textpos
// Range defines a range with a start and end index, where end is typically
// exclusive, as in standard slice indexing and for loop conventions.
type Range struct {
// St is the starting index of the range.
Start int
// Ed is the ending index of the range.
End int
}
// Len returns the length of the range: End - Start.
func (r Range) Len() int {
return r.End - r.Start
}
// Contains returns true if range contains given index.
func (r Range) Contains(i int) bool {
return i >= r.Start && i < r.End
}
// Intersect returns the intersection of two ranges.
// If they do not overlap, then the Start and End will be -1
func (r Range) Intersect(o Range) Range {
o.Start = max(o.Start, r.Start)
o.End = min(o.End, r.End)
if o.Len() <= 0 {
return Range{-1, -1}
}
return o
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package textpos
import (
"fmt"
"strings"
"time"
"cogentcore.org/core/base/nptime"
)
var RegionZero = Region{}
// Region is a contiguous region within a source file with lines of rune chars,
// defined by start and end [Pos] positions.
// End.Char position is _exclusive_ so the last char is the one before End.Char.
// End.Line position is _inclusive_, so the last line is End.Line.
// There is a Time stamp for when the region was created as valid positions
// into the lines source, which is critical for tracking edits in live documents.
type Region struct {
// Start is the starting position of region.
Start Pos
// End is the ending position of region.
// Char position is _exclusive_ so the last char is the one before End.Char.
// Line position is _inclusive_, so the last line is End.Line.
End Pos
// Time when region was set: needed for updating locations in the text based
// on time stamp (using efficient non-pointer time).
Time nptime.Time
}
// NewRegion creates a new text region using separate line and char
// values for start and end. Sets timestamp to now.
func NewRegion(stLn, stCh, edLn, edCh int) Region {
tr := Region{Start: Pos{Line: stLn, Char: stCh}, End: Pos{Line: edLn, Char: edCh}}
tr.TimeNow()
return tr
}
// NewRegionPos creates a new text region using position values.
// Sets timestamp to now.
func NewRegionPos(st, ed Pos) Region {
tr := Region{Start: st, End: ed}
tr.TimeNow()
return tr
}
// NewRegionLen makes a new Region from a starting point and a length
// along same line. Sets timestamp to now.
func NewRegionLen(start Pos, len int) Region {
tr := Region{Start: start}
tr.End = start
tr.End.Char += len
tr.TimeNow()
return tr
}
// IsNil checks if the region is empty, because the start is after or equal to the end.
func (tr Region) IsNil() bool {
return !tr.Start.IsLess(tr.End)
}
// Contains returns true if region contains given position.
func (tr Region) Contains(ps Pos) bool {
return ps.IsLess(tr.End) && (tr.Start == ps || tr.Start.IsLess(ps))
}
// ContainsLine returns true if line is within region
func (tr Region) ContainsLine(ln int) bool {
return ln >= tr.Start.Line && ln <= tr.End.Line
}
// NumLines is the number of lines in this region, based on inclusive end line.
func (tr Region) NumLines() int {
return 1 + (tr.End.Line - tr.Start.Line)
}
// Intersect returns the intersection of this region with given
// other region, where the other region is assumed to be the larger,
// constraining region, within which you are fitting the receiver region.
// Char level start / end are only constrained if on same Start / End line.
// The given endChar value is used for the end of an interior line.
func (tr Region) Intersect(or Region, endChar int) Region {
switch {
case tr.Start.Line < or.Start.Line:
tr.Start = or.Start
case tr.Start.Line == or.Start.Line:
tr.Start.Char = max(tr.Start.Char, or.Start.Char)
case tr.Start.Line < or.End.Line:
tr.Start.Char = 0
case tr.Start.Line == or.End.Line:
tr.Start.Char = min(tr.Start.Char, or.End.Char-1)
default:
return Region{} // not in bounds
}
if tr.End.Line == tr.Start.Line { // keep valid
tr.End.Char = max(tr.End.Char, tr.Start.Char)
}
switch {
case tr.End.Line < or.End.Line:
tr.End.Char = endChar
case tr.End.Line == or.End.Line:
tr.End.Char = min(tr.End.Char, or.End.Char)
}
return tr
}
// ShiftLines returns a new Region with the start and End lines
// shifted by given number of lines.
func (tr Region) ShiftLines(ln int) Region {
tr.Start.Line += ln
tr.End.Line += ln
return tr
}
// MoveToLine returns a new Region with the Start line
// set to given line.
func (tr Region) MoveToLine(ln int) Region {
nl := tr.NumLines()
tr.Start.Line = ln
tr.End.Line = ln + nl - 1
return tr
}
//////// Time
// TimeNow grabs the current time as the edit time.
func (tr *Region) TimeNow() {
tr.Time.Now()
}
// IsAfterTime reports if this region's time stamp is after given time value
// if region Time stamp has not been set, it always returns true
func (tr *Region) IsAfterTime(t time.Time) bool {
if tr.Time.IsZero() {
return true
}
return tr.Time.Time().After(t)
}
// Ago returns how long ago this Region's time stamp is relative
// to given time.
func (tr *Region) Ago(t time.Time) time.Duration {
return t.Sub(tr.Time.Time())
}
// Age returns the time interval from [time.Now]
func (tr *Region) Age() time.Duration {
return tr.Ago(time.Now())
}
// Since returns the time interval between
// this Region's time stamp and that of the given earlier region's stamp.
func (tr *Region) Since(earlier *Region) time.Duration {
return earlier.Ago(tr.Time.Time())
}
// FromStringURL decodes text region from a string representation of form:
// [#]LxxCxx-LxxCxx. Used in e.g., URL links. returns true if successful
func (tr *Region) FromStringURL(link string) bool {
link = strings.TrimPrefix(link, "#")
fmt.Sscanf(link, "L%dC%d-L%dC%d", &tr.Start.Line, &tr.Start.Char, &tr.End.Line, &tr.End.Char)
return true
}
func (tr *Region) String() string {
return fmt.Sprintf("[%s - %s]", tr.Start, tr.End)
}
// Copyright (c) 2025, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package textpos
import "unicode"
// RuneIsWordBreak returns true if given rune counts as a word break
// for the purposes of selecting words.
func RuneIsWordBreak(r rune) bool {
return unicode.IsSpace(r) || unicode.IsSymbol(r) || unicode.IsPunct(r)
}
// IsWordBreak defines what counts as a word break for the purposes of selecting words.
// r1 is the rune in question, r2 is the rune past r1 in the direction you are moving.
// Pass -1 for r2 if there is no rune past r1.
func IsWordBreak(r1, r2 rune) bool {
if r2 == -1 {
return RuneIsWordBreak(r1)
}
if unicode.IsSpace(r1) || unicode.IsSymbol(r1) {
return true
}
if unicode.IsPunct(r1) && r1 != rune('\'') {
return true
}
if unicode.IsPunct(r1) && r1 == rune('\'') {
return unicode.IsSpace(r2) || unicode.IsSymbol(r2) || unicode.IsPunct(r2)
}
return false
}
// WordAt returns the range for a word within given text starting at given
// position index. If the current position is a word break then go to next
// break after the first non-break.
func WordAt(txt []rune, pos int) Range {
var rg Range
sz := len(txt)
if sz == 0 {
return rg
}
if pos < 0 {
pos = 0
}
if pos >= sz {
pos = sz - 1
}
rg.Start = pos
if !RuneIsWordBreak(txt[rg.Start]) {
for rg.Start > 0 {
if RuneIsWordBreak(txt[rg.Start-1]) {
break
}
rg.Start--
}
rg.End = pos + 1
for rg.End < sz {
if RuneIsWordBreak(txt[rg.End]) {
break
}
rg.End++
}
return rg
}
// keep the space start -- go to next space..
rg.End = pos + 1
for rg.End < sz {
if !RuneIsWordBreak(txt[rg.End]) {
break
}
rg.End++
}
for rg.End < sz {
if RuneIsWordBreak(txt[rg.End]) {
break
}
rg.End++
}
return rg
}
// ForwardWord moves position index forward by words, for given
// number of steps. Returns the number of steps actually moved,
// given the amount of text available.
func ForwardWord(txt []rune, pos, steps int) (wpos, nstep int) {
sz := len(txt)
if sz == 0 {
return 0, 0
}
if pos >= sz-1 {
return sz - 1, 0
}
if pos < 0 {
pos = 0
}
for range steps {
if pos == sz-1 {
break
}
ch := pos
for ch < sz-1 { // if on a wb, go past
if !IsWordBreak(txt[ch], txt[ch+1]) {
break
}
ch++
}
for ch < sz-1 { // now go to next wb
if IsWordBreak(txt[ch], txt[ch+1]) {
break
}
ch++
}
pos = ch
nstep++
}
return pos, nstep
}
// BackwardWord moves position index backward by words, for given
// number of steps. Returns the number of steps actually moved,
// given the amount of text available.
func BackwardWord(txt []rune, pos, steps int) (wpos, nstep int) {
sz := len(txt)
if sz == 0 {
return 0, 0
}
if pos <= 0 {
return 0, 0
}
if pos >= sz {
pos = sz - 1
}
for range steps {
if pos == 0 {
break
}
ch := pos
for ch > 0 { // if on a wb, go past
if !IsWordBreak(txt[ch], txt[ch-1]) {
break
}
ch--
}
for ch > 0 { // now go to next wb
if IsWordBreak(txt[ch], txt[ch-1]) {
break
}
ch--
}
pos = ch
nstep++
}
return pos, nstep
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package token defines a complete set of all lexical tokens for any kind of
// language! It is based on the alecthomas/chroma / pygments lexical tokens
// plus all the more detailed tokens needed for actually parsing languages
package token
//go:generate core generate
import (
"strconv"
"cogentcore.org/core/icons"
)
// Tokens is a complete set of lexical tokens that encompasses all programming and text
// markup languages. It includes everything in alecthomas/chroma (pygments) and
// everything needed for Go, C, C++, Python, etc.
//
// There are categories and sub-categories, and methods to get those from a given
// element. The first category is 'None'.
//
// See http://pygments.org/docs/tokens/ for more docs on the different categories
//
// Anything missing should be added via a pull request etc
type Tokens int32 //enums:enum
// CatMap is the map into the category level for each token
var CatMap map[Tokens]Tokens
// SubCatMap is the map into the sub-category level for each token
var SubCatMap map[Tokens]Tokens
func init() {
InitCatMap()
InitSubCatMap()
}
// Cat returns the category that a given token lives in, using CatMap
func (tk Tokens) Cat() Tokens {
return CatMap[tk]
}
// SubCat returns the sub-category that a given token lives in, using SubCatMap
func (tk Tokens) SubCat() Tokens {
return SubCatMap[tk]
}
// IsCat returns true if this is a category-level token
func (tk Tokens) IsCat() bool {
return tk.Cat() == tk
}
// IsSubCat returns true if this is a sub-category-level token
func (tk Tokens) IsSubCat() bool {
return tk.SubCat() == tk
}
// InCat returns true if this is in same category as given token
func (tk Tokens) InCat(other Tokens) bool {
return tk.Cat() == other.Cat()
}
// InSubCat returns true if this is in same sub-category as given token
func (tk Tokens) InSubCat(other Tokens) bool {
return tk.SubCat() == other.SubCat()
}
// IsCode returns true if this token is in Keyword, Name, Operator, or Punctuation categs.
// these are recognized code (program) elements that can usefully be distinguished from
// other forms of raw text (e.g., for spell checking)
func (tk Tokens) IsCode() bool {
return tk.InCat(Keyword) || tk.InCat(Name) || tk.InCat(Operator) || tk.InCat(Punctuation)
}
// IsKeyword returns true if this in the Keyword category
func (tk Tokens) IsKeyword() bool {
return tk.Cat() == Keyword
}
// Parent returns the closest parent-level of this token (subcat or cat)
func (tk Tokens) Parent() Tokens {
if tk.IsSubCat() {
return tk.Cat()
}
return tk.SubCat()
}
// Match returns true if the two tokens match, in a category / subcategory sensitive manner:
// if receiver token is a category, then it matches other token if it is the same category
// and likewise for subcategory
func (tk Tokens) Match(otk Tokens) bool {
if tk == otk {
return true
}
if tk.IsCat() && otk.Cat() == tk {
return true
}
return tk.IsSubCat() && otk.SubCat() == tk
}
// IsPunctGpLeft returns true if token is a PunctGpL token -- left paren, brace, bracket
func (tk Tokens) IsPunctGpLeft() bool {
return (tk == PunctGpLParen || tk == PunctGpLBrack || tk == PunctGpLBrace)
}
// IsPunctGpRight returns true if token is a PunctGpR token -- right paren, brace, bracket
func (tk Tokens) IsPunctGpRight() bool {
return (tk == PunctGpRParen || tk == PunctGpRBrack || tk == PunctGpRBrace)
}
// PunctGpMatch returns the matching token for given PunctGp token
func (tk Tokens) PunctGpMatch() Tokens {
switch tk {
case PunctGpLParen:
return PunctGpRParen
case PunctGpRParen:
return PunctGpLParen
case PunctGpLBrack:
return PunctGpRBrack
case PunctGpRBrack:
return PunctGpLBrack
case PunctGpLBrace:
return PunctGpRBrace
case PunctGpRBrace:
return PunctGpLBrace
}
return None
}
// IsAmbigUnaryOp returns true if this token is an operator that could either be
// a Unary or Binary operator -- need special matching for this.
// includes * and & which are used for address operations in C-like languages
func (tk Tokens) IsAmbigUnaryOp() bool {
return (tk == OpMathSub || tk == OpMathMul || tk == OpBitAnd || tk == OpMathAdd || tk == OpBitXor)
}
// IsUnaryOp returns true if this token is an operator that is typically used as
// a Unary operator: - + & * ! ^ ! <-
func (tk Tokens) IsUnaryOp() bool {
return (tk == OpMathSub || tk == OpMathMul || tk == OpBitAnd || tk == OpMathAdd ||
tk == OpBitXor || tk == OpLogNot || tk == OpAsgnArrow)
}
// CombineRepeats are token types where repeated tokens of the same type should
// be combined together -- literals, comments, text
func (tk Tokens) CombineRepeats() bool {
cat := tk.Cat()
return (cat == Literal || cat == Comment || cat == Text || cat == Name)
}
// StyleName returns the abbreviated 2-3 letter style name of the tag
func (tk Tokens) StyleName() string {
return Names[tk]
}
// ClassName returns the . prefixed CSS classname of the tag style
// for styling, a CSS property should exist with this name
func (tk Tokens) ClassName() string {
return "." + tk.StyleName()
}
/////////////////////////////////////////////////////////////////////////////
// KeyToken -- keyword + token
// KeyToken combines a token and an optional keyword name for Keyword token types
// if Tok is in Keyword category, then Key string can be used to check for same keyword.
// Also has a Depth for matching against a particular nesting depth
type KeyToken struct {
Token Tokens
Key string
Depth int
}
var KeyTokenZero = KeyToken{}
func (kt KeyToken) String() string {
ds := ""
if kt.Depth != 0 {
ds = "+" + strconv.Itoa(kt.Depth) + ":"
}
if kt.Key != "" {
return ds + kt.Token.String() + ": " + kt.Key
}
return ds + kt.Token.String()
}
// Equal compares equality of two tokens including keywords if token is in Keyword category.
// See also Match for version that uses category / subcategory matching
func (kt KeyToken) Equal(okt KeyToken) bool {
if kt.Token.IsKeyword() && kt.Key != "" {
return kt.Token == okt.Token && kt.Key == okt.Key
}
return kt.Token == okt.Token
}
// Match compares equality of two tokens including keywords if token is in Keyword category.
// returns true if the two tokens match, in a category / subcategory sensitive manner:
// if receiver token is a category, then it matches other token if it is the same category
// and likewise for subcategory
func (kt KeyToken) Match(okt KeyToken) bool {
if kt.Token.IsKeyword() && kt.Key != "" {
return kt.Token.Match(okt.Token) && kt.Key == okt.Key
}
return kt.Token.Match(okt.Token)
}
// MatchDepth compares equality of two tokens including depth -- see Match for other matching
// criteria
func (kt KeyToken) MatchDepth(okt KeyToken) bool {
if kt.Depth != okt.Depth {
return false
}
return kt.Match(okt)
}
// StringKey encodes token into a string for optimized string-based map key lookup
func (kt KeyToken) StringKey() string {
tstr := string([]byte{byte(kt.Token)})
if kt.Token.IsKeyword() {
return tstr + kt.Key
}
return tstr
}
// KeyTokenList is a list (slice) of KeyTokens
type KeyTokenList []KeyToken
// Match returns true if given keytoken matches any of the items on the list
func (kl KeyTokenList) Match(okt KeyToken) bool {
for _, kt := range kl {
if kt.Match(okt) {
return true
}
}
return false
}
// Icon returns the appropriate icon for the type of lexical item this is.
func (tk Tokens) Icon() icons.Icon {
switch {
case tk.SubCat() == NameVar:
return icons.Variable
case tk == NameConstant || tk == NameEnum || tk == NameEnumMember:
return icons.Constant
case tk == NameField:
return icons.Field
case tk.SubCat() == NameType:
return icons.Type
case tk == NameMethod:
return icons.Method
case tk.SubCat() == NameFunction:
return icons.Function
}
return ""
}
/////////////////////////////////////////////////////////////////////////////
// Tokens
// The list of tokens
const (
// None is the nil token value -- for non-terminal cases or TBD
None Tokens = iota
// Error is an input that could not be tokenized due to syntax error etc
Error
// EOF is end of file
EOF
// EOL is end of line (typically implicit -- used for rule matching)
EOL
// EOS is end of statement -- a key meta-token -- in C it is ;, in Go it is either ; or EOL
EOS
// Background is for syntax highlight styles based on these tokens
Background
// Cat: Keywords (actual keyword is just the string)
Keyword
KeywordConstant
KeywordDeclaration
KeywordNamespace // incl package, import
KeywordPseudo
KeywordReserved
KeywordType
// Cat: Names.
Name
NameBuiltin // e.g., true, false -- builtin values..
NameBuiltinPseudo // e.g., this, self
NameOther
NamePseudo
// SubCat: Type names
NameType
NameClass
NameStruct
NameField
NameInterface
NameConstant
NameEnum
NameEnumMember
NameArray // includes slice etc
NameMap
NameObject
NameTypeParam // for generics, templates
// SubCat: Function names
NameFunction
NameDecorator // function-like wrappers in python
NameFunctionMagic // e.g., __init__ in python
NameMethod
NameOperator
NameConstructor // includes destructor..
NameException
NameLabel // e.g., goto label
NameEvent // for LSP -- not really sure what it is..
// SubCat: Scoping names
NameScope
NameNamespace
NameModule
NamePackage
NameLibrary
// SubCat: NameVar -- variable names
NameVar
NameVarAnonymous
NameVarClass
NameVarGlobal
NameVarInstance
NameVarMagic
NameVarParam
// SubCat: Value -- data-like elements
NameValue
NameTag // e.g., HTML tag
NameProperty
NameAttribute // e.g., HTML attr
NameEntity // special entities. (e.g. in HTML). seems like other..
// Cat: Literals.
Literal
LiteralDate
LiteralOther
LiteralBool
// SubCat: Literal Strings.
LitStr
LitStrAffix // unicode specifiers etc
LitStrAtom
LitStrBacktick
LitStrBoolean
LitStrChar
LitStrDelimiter
LitStrDoc // doc-specific strings where syntactically noted
LitStrDouble
LitStrEscape // esc sequences within strings
LitStrHeredoc // in ruby, perl
LitStrInterpol // interpolated parts of strings in #{foo} in Ruby
LitStrName
LitStrOther
LitStrRegex
LitStrSingle
LitStrSymbol
LitStrFile // filename
// SubCat: Literal Numbers.
LitNum
LitNumBin
LitNumFloat
LitNumHex
LitNumInteger
LitNumIntegerLong
LitNumOct
LitNumImag
// Cat: Operators.
Operator
OperatorWord
// SubCat: Math operators
OpMath
OpMathAdd // +
OpMathSub // -
OpMathMul // *
OpMathDiv // /
OpMathRem // %
// SubCat: Bitwise operators
OpBit
OpBitAnd // &
OpBitOr // |
OpBitNot // ~
OpBitXor // ^
OpBitShiftLeft // <<
OpBitShiftRight // >>
OpBitAndNot // &^
// SubCat: Assign operators
OpAsgn
OpAsgnAssign // =
OpAsgnInc // ++
OpAsgnDec // --
OpAsgnArrow // <-
OpAsgnDefine // :=
// SubCat: Math Assign operators
OpMathAsgn
OpMathAsgnAdd // +=
OpMathAsgnSub // -=
OpMathAsgnMul // *=
OpMathAsgnDiv // /=
OpMathAsgnRem // %=
// SubCat: Bitwise Assign operators
OpBitAsgn
OpBitAsgnAnd // &=
OpBitAsgnOr // |=
OpBitAsgnXor // ^=
OpBitAsgnShiftLeft // <<=
OpBitAsgnShiftRight // >>=
OpBitAsgnAndNot // &^=
// SubCat: Logical operators
OpLog
OpLogAnd // &&
OpLogOr // ||
OpLogNot // !
// SubCat: Relational operators
OpRel
OpRelEqual // ==
OpRelNotEqual // !=
OpRelLess // <
OpRelGreater // >
OpRelLtEq // <=
OpRelGtEq // >=
// SubCat: List operators
OpList
OpListEllipsis // ...
// Cat: Punctuation.
Punctuation
// SubCat: Grouping punctuation
PunctGp
PunctGpLParen // (
PunctGpRParen // )
PunctGpLBrack // [
PunctGpRBrack // ]
PunctGpLBrace // {
PunctGpRBrace // }
// SubCat: Separator punctuation
PunctSep
PunctSepComma // ,
PunctSepPeriod // .
PunctSepSemicolon // ;
PunctSepColon // :
// SubCat: String punctuation
PunctStr
PunctStrDblQuote // "
PunctStrQuote // '
PunctStrBacktick // `
PunctStrEsc // \
// Cat: Comments.
Comment
CommentHashbang
CommentMultiline
CommentSingle
CommentSpecial
// SubCat: Preprocessor "comments".
CommentPreproc
CommentPreprocFile
// Cat: Text.
Text
TextWhitespace
TextSymbol
TextPunctuation
TextSpellErr
// SubCat: TextStyle (corresponds to Generic in chroma / pygments) todo: look in font deco for more
TextStyle
TextStyleDeleted // strike-through
TextStyleEmph // italics
TextStyleError
TextStyleHeading
TextStyleInserted
TextStyleOutput
TextStylePrompt
TextStyleStrong // bold
TextStyleSubheading
TextStyleTraceback
TextStyleUnderline
TextStyleLink
)
// Cats are the categories of the tokens.
var Cats = []Tokens{
None,
Keyword,
Name,
Literal,
Operator,
Punctuation,
Comment,
Text,
TokensN,
}
// SubCats are the sub-categories of the tokens.
var SubCats = []Tokens{
None,
Keyword,
Name,
NameType,
NameFunction,
NameScope,
NameVar,
NameValue,
Literal,
LitStr,
LitNum,
Operator,
OpMath,
OpBit,
OpAsgn,
OpMathAsgn,
OpBitAsgn,
OpLog,
OpRel,
OpList,
Punctuation,
PunctGp,
PunctSep,
PunctStr,
Comment,
CommentPreproc,
Text,
TextStyle,
TokensN,
}
// InitCatMap initializes the CatMap
func InitCatMap() {
if CatMap != nil {
return
}
CatMap = make(map[Tokens]Tokens, TokensN)
for tk := range TokensN {
for c := 1; c < len(Cats); c++ {
if tk < Cats[c] {
CatMap[tk] = Cats[c-1]
break
}
}
}
}
// InitSubCatMap initializes the SubCatMap
func InitSubCatMap() {
if SubCatMap != nil {
return
}
SubCatMap = make(map[Tokens]Tokens, TokensN)
for tk := range TokensN {
for c := 1; c < len(SubCats); c++ {
if tk < SubCats[c] {
SubCatMap[tk] = SubCats[c-1]
break
}
}
}
}
// OpPunctMap provides a lookup of operators and punctuation tokens by their usual
// string representation
var OpPunctMap = map[string]Tokens{
"+": OpMathAdd,
"-": OpMathSub,
"*": OpMathMul,
"/": OpMathDiv,
"%": OpMathRem,
"&": OpBitAnd,
"|": OpBitOr,
"~": OpBitNot,
"^": OpBitXor,
"<<": OpBitShiftLeft,
">>": OpBitShiftRight,
"&^": OpBitAndNot,
"=": OpAsgnAssign,
"++": OpAsgnInc,
"--": OpAsgnDec,
"<-": OpAsgnArrow,
":=": OpAsgnDefine,
"+=": OpMathAsgnAdd,
"-=": OpMathAsgnSub,
"*=": OpMathAsgnMul,
"/=": OpMathAsgnDiv,
"%=": OpMathAsgnRem,
"&=": OpBitAsgnAnd,
"|=": OpBitAsgnOr,
"^=": OpBitAsgnXor,
"<<=": OpBitAsgnShiftLeft,
">>=": OpBitAsgnShiftRight,
"&^=": OpBitAsgnAndNot,
"&&": OpLogAnd,
"||": OpLogOr,
"!": OpLogNot,
"==": OpRelEqual,
"!=": OpRelNotEqual,
"<": OpRelLess,
">": OpRelGreater,
"<=": OpRelLtEq,
">=": OpRelGtEq,
"...": OpListEllipsis,
"(": PunctGpLParen,
")": PunctGpRParen,
"[": PunctGpLBrack,
"]": PunctGpRBrack,
"{": PunctGpLBrace,
"}": PunctGpRBrace,
",": PunctSepComma,
".": PunctSepPeriod,
";": PunctSepSemicolon,
":": PunctSepColon,
"\"": PunctStrDblQuote,
"'": PunctStrQuote,
"`": PunctStrBacktick,
"\\": PunctStrEsc,
}
// Names are the short tag names for each token, used e.g., for syntax highlighting
// These are based on alecthomas/chroma / pygments
var Names = map[Tokens]string{
None: "",
Error: "err",
EOF: "EOF",
EOL: "EOL",
EOS: "EOS",
Background: "bg",
Keyword: "k",
KeywordConstant: "kc",
KeywordDeclaration: "kd",
KeywordNamespace: "kn",
KeywordPseudo: "kp",
KeywordReserved: "kr",
KeywordType: "kt",
Name: "n",
NameBuiltin: "nb",
NameBuiltinPseudo: "bp",
NameOther: "nx",
NamePseudo: "pu",
NameType: "nt",
NameClass: "nc",
NameStruct: "ns",
NameField: "nfl",
NameInterface: "nti",
NameConstant: "no",
NameEnum: "nen",
NameEnumMember: "nem",
NameArray: "nr",
NameMap: "nm",
NameObject: "nj",
NameTypeParam: "ntp",
NameFunction: "nf",
NameDecorator: "nd",
NameFunctionMagic: "fm",
NameMethod: "mt",
NameOperator: "np",
NameConstructor: "cr",
NameException: "ne",
NameLabel: "nl",
NameEvent: "ev",
NameScope: "nsc",
NameNamespace: "nn",
NameModule: "md",
NamePackage: "pk",
NameLibrary: "lb",
NameVar: "nv",
NameVarAnonymous: "ay",
NameVarClass: "vc",
NameVarGlobal: "vg",
NameVarInstance: "vi",
NameVarMagic: "vm",
NameVarParam: "vp",
NameValue: "vl",
NameTag: "ng",
NameProperty: "py",
NameAttribute: "na",
NameEntity: "ni",
Literal: "l",
LiteralDate: "ld",
LiteralOther: "lo",
LiteralBool: "bo",
LitStr: "s",
LitStrAffix: "sa",
LitStrAtom: "st",
LitStrBacktick: "sb",
LitStrBoolean: "so",
LitStrChar: "sc",
LitStrDelimiter: "dl",
LitStrDoc: "sd",
LitStrDouble: "s2",
LitStrEscape: "se",
LitStrHeredoc: "sh",
LitStrInterpol: "si",
LitStrName: "sn",
LitStrOther: "sx",
LitStrRegex: "sr",
LitStrSingle: "s1",
LitStrSymbol: "ss",
LitStrFile: "fl",
LitNum: "m",
LitNumBin: "mb",
LitNumFloat: "mf",
LitNumHex: "mh",
LitNumInteger: "mi",
LitNumIntegerLong: "il",
LitNumOct: "mo",
LitNumImag: "mj",
Operator: "o",
OperatorWord: "ow",
// don't really need these -- only have at sub-categ level
OpMath: "om",
OpBit: "ob",
OpAsgn: "oa",
OpMathAsgn: "pa",
OpBitAsgn: "ba",
OpLog: "ol",
OpRel: "or",
OpList: "oi",
Punctuation: "p",
PunctGp: "pg",
PunctSep: "ps",
PunctStr: "pr",
Comment: "c",
CommentHashbang: "ch",
CommentMultiline: "cm",
CommentSingle: "c1",
CommentSpecial: "cs",
CommentPreproc: "cp",
CommentPreprocFile: "cpf",
Text: "",
TextWhitespace: "w",
TextSymbol: "ts",
TextPunctuation: "tp",
TextSpellErr: "te",
TextStyle: "g",
TextStyleDeleted: "gd",
TextStyleEmph: "ge",
TextStyleError: "gr",
TextStyleHeading: "gh",
TextStyleInserted: "gi",
TextStyleOutput: "go",
TextStylePrompt: "gp",
TextStyleStrong: "gs",
TextStyleSubheading: "gu",
TextStyleTraceback: "gt",
TextStyleUnderline: "gl",
TextStyleLink: "ga",
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tree
import (
"reflect"
"slices"
"strconv"
"sync/atomic"
"cogentcore.org/core/base/slicesx"
"cogentcore.org/core/types"
)
// admin.go has infrastructure code outside of the [Node] interface.
// New returns a new node of the given type with the given optional parent.
// If the name is unspecified, it defaults to the ID (kebab-case) name of
// the type, plus the [Node.NumLifetimeChildren] of the parent.
func New[T NodeValue](parent ...Node) *T {
n := new(T)
ni := any(n).(Node)
InitNode(ni)
if len(parent) == 0 {
ni.AsTree().SetName(ni.AsTree().NodeType().IDName)
return n
}
p := parent[0]
p.AsTree().Children = append(p.AsTree().Children, ni)
SetParent(ni, p)
return n
}
// NewOfType returns a new node of the given [types.Type] with the given optional parent.
// If the name is unspecified, it defaults to the ID (kebab-case) name of
// the type, plus the [Node.NumLifetimeChildren] of the parent.
func NewOfType(typ *types.Type, parent ...Node) Node {
if len(parent) == 0 {
n := newOfType(typ)
InitNode(n)
n.AsTree().SetName(n.AsTree().NodeType().IDName)
return n
}
return parent[0].AsTree().NewChild(typ)
}
// InitNode initializes the node. It should not be called by end-user code.
// It must be exported since it is referenced in generic functions that
// interpreters run from source (such as the mvm generic shims of mvmcore).
func InitNode(n Node) {
nb := n.AsTree()
if nb.This != n {
nb.This = n
nb.This.Init()
}
}
// SetParent sets the parent of the given node to the given parent node.
// This is only for nodes with no existing parent; see [MoveToParent] to
// move nodes that already have a parent. It does not add the node to the
// parent's list of children; see [Node.AddChild] for a version that does.
// It automatically gets the [Node.This] of the parent.
func SetParent(child Node, parent Node) {
nb := child.AsTree()
nb.Parent = parent.AsTree().This
setUniqueName(child, false)
child.AsTree().This.OnAdd()
if oca := nb.Parent.AsTree().OnChildAdded; oca != nil {
oca(child)
}
}
// MoveToParent removes the given node from its current parent
// and adds it as a child of the given new parent.
// The old and new parents can be in different trees (or not).
func MoveToParent(child Node, parent Node) {
oldParent := child.AsTree().Parent
if oldParent != nil {
idx := IndexOf(oldParent.AsTree().Children, child)
if idx >= 0 {
oldParent.AsTree().Children = slices.Delete(oldParent.AsTree().Children, idx, idx+1)
}
}
parent.AsTree().AddChild(child)
}
// ParentByType returns the first parent of the given node that is
// of the given type, if any such node exists.
func ParentByType[T Node](n Node) T {
if IsRoot(n) {
var z T
return z
}
if p, ok := n.AsTree().Parent.(T); ok {
return p
}
return ParentByType[T](n.AsTree().Parent)
}
// ChildByType returns the first child of the given node that is
// of the given type, if any such node exists. If a start index is
// given, the search starts there and goes in both directions (see
// [slicesx.Search]), finding the nearest one.
func ChildByType[T Node](n Node, startIndex ...int) T {
nb := n.AsTree()
if len(startIndex) == 0 {
startIndex = []int{0} // the first one
}
idx := slicesx.Search(nb.Children, func(ch Node) bool {
_, ok := ch.(T)
return ok
}, startIndex...)
ch := nb.Child(idx)
if ch == nil {
var z T
return z
}
return ch.(T)
}
// IsNil returns true if the Node interface is nil, or the underlying
// This pointer is nil, which happens when the node is deleted.
func IsNil(n Node) bool {
return n == nil || n.AsTree() == nil || n.AsTree().This == nil
}
// IsRoot returns whether the given node is the root node in its tree.
func IsRoot(n Node) bool {
return n.AsTree().Parent == nil
}
// Root returns the root node of the given node's tree.
func Root(n Node) Node {
if IsRoot(n) {
return n
}
return Root(n.AsTree().Parent)
}
// nodeType is the [reflect.Type] of [Node].
var nodeType = reflect.TypeFor[Node]()
// IsNode returns whether the given type or a pointer to it
// implements the [Node] interface.
func IsNode(typ reflect.Type) bool {
if typ == nil {
return false
}
return typ.Implements(nodeType) || reflect.PointerTo(typ).Implements(nodeType)
}
// newOfType returns a new instance of the given [Node] type.
func newOfType(typ *types.Type) Node {
return reflect.New(reflect.TypeOf(typ.Instance).Elem()).Interface().(Node)
}
// SetUniqueName sets the name of the node to be unique, using
// the number of lifetime children of the parent node as a unique
// identifier. If the node already has a name, it adds the unique id
// to it. Otherwise, it uses the type name of the node plus the unique id.
func SetUniqueName(n Node) {
setUniqueName(n, true)
}
// setUniqueName is the implementation of [SetUniqueName] that takes whether
// to add the unique id to the name even if it is already set.
func setUniqueName(n Node, addIfSet bool) {
nb := n.AsTree()
pn := nb.Parent
if pn == nil {
return
}
c := atomic.AddUint64(&pn.AsTree().numLifetimeChildren, 1)
id := "-" + strconv.FormatUint(c-1, 10) // must subtract 1 so we start at 0
if nb.Name == "" {
nb.SetName(nb.NodeType().IDName + id)
} else if addIfSet {
nb.SetName(nb.Name + id)
}
}
// SetUniqueNameIfDuplicate adds a unique name id to the given new child
// of given parent node if there is already a child by that name.
// Returns true if renamed. This is slow, and should not be used in
// performance-critical code (ensure names are unique in advance).
func SetUniqueNameIfDuplicate(par, child Node) bool {
ct := child.AsTree()
if IndexByName(par.AsTree().Children, ct.Name) < 0 {
return false
}
opar := ct.Parent
ct.Parent = par // unique name relies on parent
setUniqueName(child, true)
ct.Parent = opar
return true
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tree
import "iter"
// All returns an iterator over this node and all of its descendants, in
// depth-first order, as [NodeBase.WalkDown] visits them (including the
// nodes that [Node.NodeWalkDown] adds, such as the parts of widgets).
// Unlike with WalkDown, where [Break] only skips the children of a node,
// breaking out of the loop stops the iteration:
//
// for n := range root.All() {
// if isTarget(n) {
// return n
// }
// }
//
// To skip the children of some nodes, use WalkDown.
func (n *NodeBase) All() iter.Seq[Node] {
return func(yield func(Node) bool) {
stopped := false
n.WalkDown(func(c Node) bool {
if stopped || !yield(c) {
stopped = true // the remaining nodes are skipped
return Break
}
return Continue
})
}
}
// Ancestors returns an iterator over the parents of this node, from its
// parent up to the root, as [NodeBase.WalkUpParent] visits them.
func (n *NodeBase) Ancestors() iter.Seq[Node] {
return func(yield func(Node) bool) {
n.WalkUpParent(func(p Node) bool {
return yield(p)
})
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tree
import (
"bytes"
"encoding/json"
"fmt"
"reflect"
"slices"
"strconv"
"strings"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/types"
)
// MarshalJSON marshals the node by injecting the [Node.NodeType] as a nodeType
// field and the [NodeBase.NumChildren] as a numChildren field at the start of
// the standard JSON encoding output.
func (n *NodeBase) MarshalJSON() ([]byte, error) {
// the non pointer value does not implement MarshalJSON, so it will not result in infinite recursion
b, err := json.Marshal(reflectx.Underlying(reflect.ValueOf(n.This)).Interface())
if err != nil {
return b, err
}
data := `"nodeType":"` + n.NodeType().Name + `",`
if n.NumChildren() > 0 {
data += `"numChildren":` + strconv.Itoa(n.NumChildren()) + ","
}
b = slices.Insert(b, 1, []byte(data)...)
return b, nil
}
// jsonFieldsCache is a cache of the results of [jsonFields] for each type.
var jsonFieldsCache = map[reflect.Type]map[string][]int{}
// jsonFields returns a map from the JSON names of the fields of the given
// struct type to their field indexes, following the encoding/json rules for
// field names and embedded structs. Each name is also included in lowercase,
// to support the case-insensitive matching of encoding/json.
func jsonFields(typ reflect.Type) map[string][]int {
if fields, ok := jsonFieldsCache[typ]; ok {
return fields
}
fields := map[string][]int{}
var add func(t reflect.Type, index []int)
add = func(t reflect.Type, index []int) {
for i := range t.NumField() {
f := t.Field(i)
tag := f.Tag.Get("json")
if tag == "-" {
continue
}
name, _, _ := strings.Cut(tag, ",")
fi := append(slices.Clip(index), i)
if f.Anonymous && name == "" && f.Type.Kind() == reflect.Struct {
add(f.Type, fi)
continue
}
if !f.IsExported() {
continue
}
if name == "" {
name = f.Name
}
// outer fields take precedence over embedded ones
if _, has := fields[name]; !has {
fields[name] = fi
}
lower := strings.ToLower(name)
if _, has := fields[lower]; !has {
fields[lower] = fi
}
}
}
add(typ, nil)
jsonFieldsCache[typ] = fields
return fields
}
// UnmarshalJSON unmarshals the node by extracting the nodeType field added by
// [NodeBase.MarshalJSON] and then updating the node to the correct type and
// creating children of the correct types. Note that this method can not update the type
// of the node if it has no parent; to load a root node from JSON and have it be of the
// correct type, see the [UnmarshalRootJSON] function. If the type of the node is changed
// by this function, the node pointer will no longer be valid, and the node must be fetched
// again through the children of its parent. You do not need to call [UnmarshalRootJSON]
// or worry about pointers changing if this node is already of the correct type.
func (n *NodeBase) UnmarshalJSON(b []byte) error {
typ, err := unmarshalNodeType(b)
if err != nil {
return err
}
// if our type does not match, we must replace our This to make it match
if n.NodeType() != typ {
parent := n.Parent
index := n.IndexInParent()
if index >= 0 {
n.Delete()
n.This = NewOfType(typ)
parent.AsTree().InsertChild(n.This, index)
n = n.This.AsTree() // our NodeBase pointer is now different
}
}
// We must delete any existing children first.
n.DeleteChildren()
// The children are unmarshaled separately below, so that each one can be
// made with the correct type before it is unmarshaled, and the fields
// of this node are unmarshaled without them.
var fields map[string]json.RawMessage
err = json.Unmarshal(b, &fields)
if err != nil {
return err
}
children := fields["Children"]
delete(fields, "Children")
delete(fields, "nodeType")
delete(fields, "numChildren")
// We unmarshal each field directly, since unmarshaling the node as a
// whole would call this UnmarshalJSON method again.
uv := reflectx.Underlying(reflect.ValueOf(n.This))
jfields := jsonFields(uv.Type())
for name, data := range fields {
index, ok := jfields[name]
if !ok {
index, ok = jfields[strings.ToLower(name)]
}
if !ok {
continue // unknown fields are ignored, as in encoding/json
}
fv, err := uv.FieldByIndexErr(index)
if err != nil {
continue // nil embedded pointer
}
err = json.Unmarshal(data, fv.Addr().Interface())
if err != nil {
return err
}
}
if len(children) == 0 {
return nil
}
var kids []json.RawMessage
err = json.Unmarshal(children, &kids)
if err != nil {
return err
}
for _, kb := range kids {
ktyp, err := unmarshalNodeType(kb)
if err != nil {
return err
}
kid := NewOfType(ktyp)
n.AddChild(kid)
err = kid.AsTree().UnmarshalJSON(kb)
if err != nil {
return err
}
}
return nil
}
// unmarshalNodeType returns the type of the node in the given JSON,
// based on the nodeType field added by [NodeBase.MarshalJSON].
func unmarshalNodeType(b []byte) (*types.Type, error) {
typeName := ""
key := []byte(`"nodeType"`)
if _, after, ok := bytes.Cut(b, key); ok {
rest := after
if start := bytes.IndexByte(rest, '"'); start >= 0 {
rest = rest[start+1:]
if end := bytes.IndexByte(rest, '"'); end >= 0 {
typeName = string(rest[:end])
}
}
}
typ := types.TypeByName(typeName)
if typ == nil {
return nil, fmt.Errorf("tree.NodeBase.UnmarshalJSON: type %q not found", typeName)
}
return typ, nil
}
// UnmarshalRootJSON loads the given JSON to produce a new root node of
// the correct type with all properties and children loaded. If you have
// a root node that you know is already of the correct type, you can just
// call [NodeBase.UnmarshalJSON] on it instead.
func UnmarshalRootJSON(b []byte) (Node, error) {
// we must make a temporary parent so that the type of the node can be updated
parent := New[NodeBase]()
// this NodeBase type is just temporary and will be fixed by [NodeBase.UnmarshalJSON]
nb := New[NodeBase](parent)
err := nb.UnmarshalJSON(b)
if err != nil {
return nil, err
}
// the node must be fetched from the parent's children since the pointer may have changed
n := parent.Child(0)
// we must safely remove the node from its temporary parent
n.AsTree().Parent = nil
parent.Children = nil
parent.Destroy()
return n, nil
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package tree provides a powerful and extensible tree system,
// centered on the core [Node] interface.
package tree
//go:generate core generate
//go:generate core generate ./testdata
import (
"cogentcore.org/core/base/plan"
)
// Node is an interface that all tree nodes satisfy. The core functionality
// of a tree node is defined on [NodeBase], and all higher-level tree types
// must embed it. This interface only contains the tree functionality that
// higher-level tree types may need to override. You can call [Node.AsTree]
// to get the [NodeBase] of a Node and access the core tree functionality.
// All values that implement [Node] are pointer values; see [NodeValue]
// for an interface for non-pointer values.
type Node interface {
// AsTree returns the [NodeBase] of this Node. Most core
// tree functionality is implemented on [NodeBase].
AsTree() *NodeBase
// Init is called when the node is first initialized.
// It is called before the node is added to the tree,
// so it will not have any parents or siblings.
// It will be called only once in the lifetime of the node.
// It does nothing by default, but it can be implemented
// by higher-level types that want to do something.
// It is the main place that initialization steps should
// be done, like adding Stylers, Makers, and event handlers
// to widgets in Cogent Core.
Init()
// OnAdd is called when the node is added to a parent.
// It will be called only once in the lifetime of the node,
// unless the node is moved. It will not be called on root
// nodes, as they are never added to a parent.
// It does nothing by default, but it can be implemented
// by higher-level types that want to do something.
OnAdd()
// Destroy recursively deletes and destroys the node, all of its children,
// and all of its children's children, etc. Node types can implement this
// to do additional necessary destruction; if they do, they should call
// [NodeBase.Destroy] at the end of their implementation.
Destroy()
// NodeWalkDown is a method that nodes can implement to traverse additional nodes
// like widget parts during [NodeBase.WalkDown]. It is called with the function passed
// to [Node.WalkDown] after the function is called with the node itself.
NodeWalkDown(fun func(n Node) bool)
// CopyFieldsFrom copies the fields of the node from the given node.
// By default, it is [NodeBase.CopyFieldsFrom], which automatically does
// a deep copy of all of the fields of the node that do not a have a
// `copier:"-"` struct tag. Node types should only implement a custom
// CopyFieldsFrom method when they have fields that need special copying
// logic that can not be automatically handled. All custom CopyFieldsFrom
// methods should call [NodeBase.CopyFieldsFrom] first and then only do manual
// handling of specific fields that can not be automatically copied. See
// [cogentcore.org/core/core.WidgetBase.CopyFieldsFrom] for an example of a
// custom CopyFieldsFrom method.
CopyFieldsFrom(from Node)
// This is necessary for tree planning to work.
plan.Namer
}
// NodeValue is an interface that all non-pointer tree nodes satisfy.
// Pointer tree nodes satisfy [Node], not NodeValue. NodeValue and [Node]
// are mutually exclusive; a [Node] cannot be a NodeValue and vice versa.
// However, a pointer to a NodeValue type is guaranteed to be a [Node],
// and a non-pointer version of a [Node] type is guaranteed to be a NodeValue.
type NodeValue interface {
// NodeValue should only be implemented by [NodeBase],
// and it should not be called. It must be exported due
// to a nuance with the way that [reflect.StructOf] works,
// which results in panics with embedded structs that have
// unexported non-pointer methods.
NodeValue()
}
// NodeValue implements [NodeValue]. It should not be called.
func (n NodeBase) NodeValue() {}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tree
import (
"log/slog"
"maps"
"reflect"
"slices"
"strconv"
"strings"
"cogentcore.org/core/base/elide"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/base/strcase"
"cogentcore.org/core/base/tiered"
"cogentcore.org/core/types"
)
// NodeBase implements the [Node] interface and provides the core functionality
// for the Cogent Core tree system. You must use NodeBase as an embedded struct
// in all higher-level tree types.
//
// All nodes must be properly initialized by using one of [New], [NodeBase.NewChild],
// [NodeBase.AddChild], [NodeBase.InsertChild], [NodeBase.Clone], [Update], or [Plan].
// This ensures that the [NodeBase.This] field is set correctly and the [Node.Init]
// method is called.
//
// All nodes support JSON marshalling and unmarshalling through the standard [encoding/json]
// interfaces, so you can use the standard functions for loading and saving trees. However,
// if you want to load a root node of the correct type from JSON, you need to use the
// [UnmarshalRootJSON] function.
//
// All node types must be added to the Cogent Core type registry via typegen,
// so you must add a go:generate line that runs `core generate` to any packages
// you write that have new node types defined.
type NodeBase struct {
// Name is the name of this node, which is typically unique relative to other children of
// the same parent. It can be used for finding and serializing nodes. If not otherwise set,
// it defaults to the ID (kebab-case) name of the node type combined with the total number
// of children that have ever been added to the node's parent.
Name string `copier:"-"`
// This is the value of this Node as its true underlying type. This allows methods
// defined on base types to call methods defined on higher-level types, which
// is necessary for various parts of tree and widget functionality. This is set
// to nil when the node is deleted.
This Node `copier:"-" json:"-" xml:"-" display:"-" set:"-"`
// Parent is the parent of this node, which is set automatically when this node is
// added as a child of a parent. To change the parent of a node, use [MoveToParent];
// you should typically not set this field directly. Nodes can only have one parent
// at a time.
Parent Node `copier:"-" json:"-" xml:"-" display:"-" set:"-"`
// Children is the list of children of this node. All of them are set to have this node
// as their parent. You can directly modify this list, but you should typically use the
// various NodeBase child helper functions when applicable so that everything is updated
// properly, such as when deleting children.
Children []Node `table:"-" copier:"-" set:"-" json:",omitempty"`
// Properties is a property map for arbitrary key-value properties.
// When possible, use typed fields on a new type embedding NodeBase instead of this.
// You should typically use the [NodeBase.SetProperty], [NodeBase.Property], and
// [NodeBase.DeleteProperty] methods for modifying and accessing properties.
Properties map[string]any `table:"-" xml:"-" copier:"-" set:"-" json:",omitempty"`
// Updaters is a tiered set of functions called in sequential descending (reverse) order
// in [NodeBase.RunUpdaters] to update the node. You can use [NodeBase.Updater],
// [NodeBase.FirstUpdater], or [NodeBase.FinalUpdater] to add one. This typically
// typically contains [NodeBase.UpdateFromMake] at the start of the normal list.
Updaters tiered.Tiered[[]func()] `table:"-" copier:"-" json:"-" xml:"-" set:"-" edit:"-" display:"add-fields"`
// Makers is a tiered set of functions called in sequential ascending order
// in [NodeBase.Make] to make the plan for how the node's children should
// be configured. You can use [NodeBase.Maker], [NodeBase.FirstMaker], or
// [NodeBase.FinalMaker] to add one.
Makers tiered.Tiered[[]func(p *Plan)] `table:"-" copier:"-" json:"-" xml:"-" set:"-" edit:"-" display:"add-fields"`
// OnChildAdded is called when a node is added as a direct child of this node.
// When a node is added to a parent, it calls [Node.OnAdd] on itself and then
// this function on its parent if it is non-nil.
OnChildAdded func(n Node) `table:"-" copier:"-" json:"-" xml:"-" edit:"-"`
// numLifetimeChildren is the number of children that have ever been added to this
// node, which is used for automatic unique naming.
numLifetimeChildren uint64 // (not an atomic.Uint64, as NodeBase is copied by value)
// index is the last value of our index, which is used as a starting point for
// finding us in our parent next time. It is not guaranteed to be accurate;
// use the [NodeBase.IndexInParent] method.
index int
// depth is the depth of the node while using [NodeBase.WalkDownBreadth].
depth int
// nodeType is the cached result of [NodeBase.NodeType], which would
// otherwise use reflection to look up the type each time.
nodeType *types.Type
}
// String implements the [fmt.Stringer] interface by returning the path of the node.
func (n *NodeBase) String() string {
if n == nil || n.This == nil {
return "nil"
}
return elide.Middle(n.Path(), 38)
}
// AsTree returns the [NodeBase] for this Node.
func (n *NodeBase) AsTree() *NodeBase {
return n
}
// PlanName implements [plan.Namer].
func (n *NodeBase) PlanName() string {
return n.Name
}
// NodeType returns the [types.Type] of this node.
// If there is no [types.Type] registered for this node already,
// it registers one and then returns it.
func (n *NodeBase) NodeType() *types.Type {
if n.nodeType != nil {
return n.nodeType
}
if t := types.TypeByValue(n.This); t != nil {
if t.Instance == nil {
t.Instance = n.NewInstance()
}
n.nodeType = t
return t
}
name := types.TypeNameValue(n.This)
li := strings.LastIndex(name, ".")
n.nodeType = types.AddType(&types.Type{
Name: name,
IDName: strcase.ToKebab(name[li+1:]),
Instance: n.NewInstance(),
})
return n.nodeType
}
// NewInstance returns a new instance of this node type.
func (n *NodeBase) NewInstance() Node {
return reflect.New(reflect.TypeOf(n.This).Elem()).Interface().(Node)
}
// Parents:
// IndexInParent returns our index within our parent node. It caches the
// last value and uses that for an optimized search so subsequent calls
// are typically quite fast. Returns -1 if we don't have a parent.
func (n *NodeBase) IndexInParent() int {
if n.Parent == nil {
return -1
}
idx := IndexOf(n.Parent.AsTree().Children, n.This, n.index) // very fast if index is close
n.index = idx
return idx
}
// ParentLevel finds a given potential parent node recursively up the
// hierarchy, returning the number of levels between this node and the parent
// (0 for its direct parent, 1 for the parent of that, etc), and -1 if not found.
func (n *NodeBase) ParentLevel(parent Node) int {
parLev := -1
level := 0
for k := range n.Ancestors() {
if k == parent {
parLev = level
break
}
level++
}
return parLev
}
// ParentByName finds first parent recursively up hierarchy that matches
// the given name. It returns nil if not found.
func (n *NodeBase) ParentByName(name string) Node {
if IsRoot(n) {
return nil
}
if n.Parent.AsTree().Name == name {
return n.Parent
}
return n.Parent.AsTree().ParentByName(name)
}
// Children:
// HasChildren returns whether this node has any children.
func (n *NodeBase) HasChildren() bool {
return len(n.Children) > 0
}
// NumChildren returns the number of children this node has.
func (n *NodeBase) NumChildren() int {
return len(n.Children)
}
// Child returns the child of this node at the given index and returns nil if
// the index is out of range.
func (n *NodeBase) Child(i int) Node {
if i >= len(n.Children) || i < 0 {
return nil
}
return n.Children[i]
}
// ChildByName returns the first child that has the given name, and nil
// if no such element is found. startIndex arg allows for optimized
// bidirectional find if you have an idea where it might be, which
// can be a key speedup for large lists. If no value is specified for
// startIndex, it starts in the middle, which is a good default.
func (n *NodeBase) ChildByName(name string, startIndex ...int) Node {
return n.Child(IndexByName(n.Children, name, startIndex...))
}
// Paths:
// TODO: is this the best way to escape paths?
// EscapePathName returns a name that replaces any / with \\
func EscapePathName(name string) string {
return strings.ReplaceAll(name, "/", `\\`)
}
// UnescapePathName returns a name that replaces any \\ with /
func UnescapePathName(name string) string {
return strings.ReplaceAll(name, `\\`, "/")
}
// Path returns the path to this node from the tree root,
// using [Node.Name]s separated by / delimeters. Any
// existing / characters in names are escaped to \\
func (n *NodeBase) Path() string {
if n.Parent != nil {
return n.Parent.AsTree().Path() + "/" + EscapePathName(n.Name)
}
return "/" + EscapePathName(n.Name)
}
// PathFrom returns the path to this node from the given parent node,
// using [Node.Name]s separated by / delimeters. Any
// existing / characters in names are escaped to \\
//
// The paths that it returns exclude the
// name of the parent and the leading slash; for example, in the tree
// a/b/c/d/e, the result of d.PathFrom(b) would be c/d. PathFrom
// automatically gets the [NodeBase.This] version of the given parent,
// so a base type can be passed in without manually accessing [NodeBase.This].
func (n *NodeBase) PathFrom(parent Node) string {
if n.This == parent {
return ""
}
// critical to get `This`
parent = parent.AsTree().This
// we bail a level below the parent so it isn't in the path
if n.Parent == nil || n.Parent == parent {
return EscapePathName(n.Name)
}
ppath := n.Parent.AsTree().PathFrom(parent)
return ppath + "/" + EscapePathName(n.Name)
}
// FindPath returns the node at the given path from this node.
// FindPath only works correctly when names are unique.
// The given path must be consistent with the format produced
// by [NodeBase.PathFrom]. There is also support for index-based
// access (ie: [0] for the first child) for cases where indexes
// are more useful than names. It returns nil if no node is found
// at the given path.
func (n *NodeBase) FindPath(path string) Node {
curn := n.This
pels := strings.SplitSeq(strings.Trim(strings.TrimSpace(path), "\""), "/")
for pe := range pels {
if len(pe) == 0 {
continue
}
idx := findPathChild(curn, UnescapePathName(pe))
if idx < 0 {
return nil
}
curn = curn.AsTree().Children[idx]
}
return curn
}
// findPathChild finds the child with the given string representation in [NodeBase.FindPath].
func findPathChild(n Node, child string) int {
if child[0] == '[' && child[len(child)-1] == ']' {
idx, err := strconv.Atoi(child[1 : len(child)-1])
if err != nil {
return -1
}
nc := len(n.AsTree().Children)
if idx < 0 { // from end
idx = nc + idx
}
if idx < 0 || idx >= nc {
return -1
}
return idx
}
return IndexByName(n.AsTree().Children, child)
}
// Adding and Inserting Children:
// AddChild adds given child at end of children list.
// The kid node is assumed to not be on another tree (see [MoveToParent])
// and the existing name should be unique among children.
func (n *NodeBase) AddChild(kid Node) {
InitNode(kid)
n.Children = append(n.Children, kid)
SetParent(kid, n) // key to set new parent before deleting: indicates move instead of delete
}
// NewChild creates a new child of the given type and adds it at the end
// of the list of children. The name defaults to the ID (kebab-case) name
// of the type, plus the [Node.NumLifetimeChildren] of the parent.
func (n *NodeBase) NewChild(typ *types.Type) Node {
kid := newOfType(typ)
InitNode(kid)
n.Children = append(n.Children, kid)
SetParent(kid, n)
return kid
}
// InsertChild adds given child at position in children list.
// The kid node is assumed to not be on another tree (see [MoveToParent])
// and the existing name should be unique among children.
func (n *NodeBase) InsertChild(kid Node, index int) {
InitNode(kid)
n.Children = slices.Insert(n.Children, index, kid)
SetParent(kid, n)
}
// Deleting Children:
// DeleteChildAt deletes child at the given index. It returns false
// if there is no child at the given index.
func (n *NodeBase) DeleteChildAt(index int) bool {
child := n.Child(index)
if child == nil {
return false
}
n.Children = slices.Delete(n.Children, index, index+1)
child.Destroy()
return true
}
// DeleteChild deletes the given child node, returning false if
// it can not find it.
func (n *NodeBase) DeleteChild(child Node) bool {
if child == nil {
return false
}
idx := IndexOf(n.Children, child)
if idx < 0 {
return false
}
return n.DeleteChildAt(idx)
}
// DeleteChildByName deletes child node by name, returning false
// if it can not find it.
func (n *NodeBase) DeleteChildByName(name string) bool {
idx := IndexByName(n.Children, name)
if idx < 0 {
return false
}
return n.DeleteChildAt(idx)
}
// DeleteChildren deletes all children nodes.
func (n *NodeBase) DeleteChildren() {
kids := n.Children
n.Children = n.Children[:0] // preserves capacity of list
for _, kid := range kids {
if kid == nil {
continue
}
kid.Destroy()
}
}
// Delete deletes this node from its parent's children list
// and then destroys itself.
func (n *NodeBase) Delete() {
if n.Parent == nil {
n.This.Destroy()
} else {
n.Parent.AsTree().DeleteChild(n.This)
}
}
// Destroy recursively deletes and destroys the node, all of its children,
// and all of its children's children, etc.
func (n *NodeBase) Destroy() {
if n.This == nil { // already destroyed
return
}
n.DeleteChildren()
n.This = nil
}
// Property Storage:
// SetProperty sets given the given property to the given value.
func (n *NodeBase) SetProperty(key string, value any) {
if n.Properties == nil {
n.Properties = map[string]any{}
}
n.Properties[key] = value
}
// Property returns the property value for the given key.
// It returns nil if it doesn't exist.
func (n *NodeBase) Property(key string) any {
return n.Properties[key]
}
// DeleteProperty deletes the property with the given key.
func (n *NodeBase) DeleteProperty(key string) {
if n.Properties == nil {
return
}
delete(n.Properties, key)
}
// Tree Walking:
const (
// Continue = true can be returned from tree iteration functions to continue
// processing down the tree, as compared to Break = false which stops this branch.
Continue = true
// Break = false can be returned from tree iteration functions to stop processing
// this branch of the tree. In the walks down the tree ([NodeBase.WalkDown]),
// it skips the children of the node, and the walk continues with the rest
// of the tree: to stop at the first node that matches, range over
// [NodeBase.All] instead.
Break = false
)
// WalkUp calls the given function on the node and all of its parents,
// sequentially in the current goroutine (generally necessary for going up,
// which is typically quite fast anyway). It stops walking if the function
// returns [Break] and keeps walking if it returns [Continue]. It returns
// whether walking was finished (false if it was aborted with [Break]).
func (n *NodeBase) WalkUp(fun func(n Node) bool) bool {
cur := n.This
for {
if !fun(cur) { // false return means stop
return false
}
parent := cur.AsTree().Parent
if parent == nil || parent == cur { // prevent loops
return true
}
cur = parent
}
}
// WalkUpParent calls the given function on all of the node's parents (but not
// the node itself), sequentially in the current goroutine (generally necessary
// for going up, which is typically quite fast anyway). It stops walking if the
// function returns [Break] and keeps walking if it returns [Continue]. It returns
// whether walking was finished (false if it was aborted with [Break]).
func (n *NodeBase) WalkUpParent(fun func(n Node) bool) bool {
if IsRoot(n) {
return true
}
cur := n.Parent
for {
if !fun(cur) { // false return means stop
return false
}
parent := cur.AsTree().Parent
if parent == nil || parent == cur { // prevent loops
return true
}
cur = parent
}
}
// WalkDown strategy: https://stackoverflow.com/questions/5278580/non-recursive-depth-first-search-algorithm
// WalkDown calls the given function on the node and all of its children
// in a depth-first manner over all of the children, sequentially in the
// current goroutine. It stops walking the current branch of the tree if
// the function returns [Break] and keeps walking if it returns [Continue].
// It is non-recursive and safe for concurrent calling. The [Node.NodeWalkDown]
// method is called for every node after the given function, which enables nodes
// to also traverse additional nodes, like widget parts.
func (n *NodeBase) WalkDown(fun func(n Node) bool) {
if n.This == nil {
return
}
tm := make(walkStack, 0, 16) // traversal state of the current path
start := n.This
cur := start
tm.push(cur, -1)
outer:
for {
cb := cur.AsTree()
// fun can destroy the node, so we have to check for nil before and after.
// A false return from fun indicates to stop.
if cb.This != nil && fun(cur) && cb.This != nil {
cb.This.NodeWalkDown(fun)
if cb.HasChildren() {
tm.set(cur, 0) // 0 for no fields
nxt := cb.Child(0)
if nxt != nil && nxt.AsTree().This != nil {
cur = nxt.AsTree().This
tm.push(cur, -1)
continue
}
}
} else {
tm.set(cur, cb.NumChildren())
}
// if we get here, we're in the ascent branch -- move to the right and then up
for {
cb := cur.AsTree() // may have changed, so must get again
curChild := tm.get(cur)
if (curChild + 1) < cb.NumChildren() {
curChild++
tm.set(cur, curChild)
nxt := cb.Child(curChild)
if nxt != nil && nxt.AsTree().This != nil {
cur = nxt.AsTree().This
tm.push(cur, -1)
continue outer
}
continue
}
tm.delete(cur)
// couldn't go right, move up..
if cur == start {
break outer // done!
}
parent := cb.Parent
if parent == nil || parent == cur { // shouldn't happen, but does..
// fmt.Printf("nil / cur parent %v\n", par)
break outer
}
cur = parent
}
}
}
// NodeWalkDown is a placeholder implementation of [Node.NodeWalkDown]
// that does nothing.
func (n *NodeBase) NodeWalkDown(fun func(n Node) bool) {}
// WalkDownPost iterates in a depth-first manner over the children, calling
// shouldContinue on each node to test if processing should proceed (if it returns
// [Break] then that branch of the tree is not further processed),
// and then calls the given function after all of a node's children
// have been iterated over. In effect, this means that the given function
// is called for deeper nodes first. This uses node state information to manage
// the traversal and is very fast, but can only be called by one goroutine at a
// time, so you should use a Mutex if there is a chance of multiple threads
// running at the same time. The nodes are processed in the current goroutine.
func (n *NodeBase) WalkDownPost(shouldContinue func(n Node) bool, fun func(n Node) bool) {
if n.This == nil {
return
}
tm := make(walkStack, 0, 16) // traversal state of the current path
start := n.This
cur := start
tm.push(cur, -1)
outer:
for {
cb := cur.AsTree()
if cb.This != nil && shouldContinue(cur) { // false return means stop
if cb.HasChildren() {
tm.set(cur, 0) // 0 for no fields
nxt := cb.Child(0)
if nxt != nil && nxt.AsTree().This != nil {
cur = nxt.AsTree().This
tm.push(cur, -1)
continue
}
}
} else {
tm.set(cur, cb.NumChildren())
}
// if we get here, we're in the ascent branch -- move to the right and then up
for {
cb := cur.AsTree() // may have changed, so must get again
curChild := tm.get(cur)
if (curChild + 1) < cb.NumChildren() {
curChild++
tm.set(cur, curChild)
nxt := cb.Child(curChild)
if nxt != nil && nxt.AsTree().This != nil {
cur = nxt.AsTree().This
tm.push(cur, -1)
continue outer
}
continue
}
fun(cur) // now we call the function, last..
// couldn't go right, move up..
tm.delete(cur)
if cur == start {
break outer // done!
}
parent := cb.Parent
if parent == nil || parent == cur { // shouldn't happen
break outer
}
cur = parent
}
}
}
// Note: it does not appear that there is a good
// recursive breadth-first-search strategy:
// https://herringtondarkholme.github.io/2014/02/17/generator/
// https://stackoverflow.com/questions/2549541/performing-breadth-first-search-recursively/2549825#2549825
// WalkDownBreadth calls the given function on the node and all of its children
// in breadth-first order. It stops walking the current branch of the tree if the
// function returns [Break] and keeps walking if it returns [Continue]. It is
// non-recursive, but not safe for concurrent calling.
func (n *NodeBase) WalkDownBreadth(fun func(n Node) bool) {
start := n.This
level := 0
start.AsTree().depth = level
queue := make([]Node, 1)
queue[0] = start
for len(queue) > 0 {
cur := queue[0]
depth := cur.AsTree().depth
queue = queue[1:]
if cur.AsTree().This != nil && fun(cur) { // false return means don't proceed
for _, cn := range cur.AsTree().Children {
if cn != nil && cn.AsTree().This != nil {
cn.AsTree().depth = depth + 1
queue = append(queue, cn)
}
}
}
}
}
// Deep Copy:
// note: we use the copy from direction (instead of copy to), as the receiver
// is modified whereas the from is not and assignment is typically in the same
// direction.
// CopyFrom copies the data and children of the given node to this node.
// It is essential that the source node has unique names. It is very efficient
// by using the [Node.ConfigChildren] method which attempts to preserve any
// existing nodes in the destination if they have the same name and type, so a
// copy from a source to a target that only differ minimally will be
// minimally destructive. Only copying to the same type is supported.
// The struct field tag copier:"-" can be added for any fields that
// should not be copied. Unexported fields are copied shallowly.
// See [Node.CopyFieldsFrom] for more information on field copying.
func (n *NodeBase) CopyFrom(from Node) {
if from == nil {
slog.Error("tree.NodeBase.CopyFrom: nil source", "destinationNode", n)
return
}
copyFrom(n.This, from)
}
// copyFrom is the implementation of [NodeBase.CopyFrom].
func copyFrom(to, from Node) {
tot := to.AsTree()
fromt := from.AsTree()
fc := fromt.Children
if len(fc) == 0 {
tot.DeleteChildren()
} else {
p := make(TypePlan, len(fc))
for i, c := range fc {
p[i].Type = c.AsTree().NodeType()
p[i].Name = c.AsTree().Name
}
UpdateSlice(&tot.Children, to, p)
}
if fromt.Properties != nil {
if tot.Properties == nil {
tot.Properties = map[string]any{}
}
maps.Copy(tot.Properties, fromt.Properties)
}
tot.This.CopyFieldsFrom(from)
for i, kid := range tot.Children {
fmk := fromt.Child(i)
copyFrom(kid, fmk)
}
}
// Clone creates and returns a deep copy of the tree from this node down.
// Any pointers within the cloned tree will correctly point within the new
// cloned tree (see [Node.CopyFrom] for more information).
func (n *NodeBase) Clone() Node {
nc := n.NewInstance()
InitNode(nc)
nc.AsTree().SetName(n.Name)
nc.AsTree().CopyFrom(n.This)
return nc
}
// CopyFieldsFrom copies the fields of the node from the given node.
// By default, it is [NodeBase.CopyFieldsFrom], which automatically does
// a deep copy of all of the fields of the node that do not a have a
// `copier:"-"` struct tag, using [reflectx.CopyStructDeep]. Node types should only implement a custom
// CopyFieldsFrom method when they have fields that need special copying
// logic that can not be automatically handled. All custom CopyFieldsFrom
// methods should call [NodeBase.CopyFieldsFrom] first and then only do manual
// handling of specific fields that can not be automatically copied. See
// [cogentcore.org/core/core.WidgetBase.CopyFieldsFrom] for an example of a
// custom CopyFieldsFrom method.
func (n *NodeBase) CopyFieldsFrom(from Node) {
ft := from.AsTree().This
if reflect.TypeOf(n.This) != reflect.TypeOf(ft) {
slog.Error("tree.NodeBase.CopyFieldsFrom: can only copy between nodes of the same type", "to", n.This, "from", ft)
return
}
reflectx.CopyStructDeep(n.This, ft)
}
// Event methods:
// Init is a placeholder implementation of
// [Node.Init] that does nothing.
func (n *NodeBase) Init() {}
// OnAdd is a placeholder implementation of
// [Node.OnAdd] that does nothing.
func (n *NodeBase) OnAdd() {}
// Copyright (c) 2024, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tree
import (
"log/slog"
"path/filepath"
"runtime"
"strconv"
"strings"
"cogentcore.org/core/base/plan"
"cogentcore.org/core/base/profile"
)
// Plan represents a plan for how the children of a [Node] should be configured.
// A Plan instance is passed to [NodeBase.Makers], which are responsible for
// configuring it. To add a child item to a plan, use [Add], [AddAt], or [AddNew].
// To add a child item maker to a [Node], use [AddChild] or [AddChildAt]. To extend
// an existing child item, use [AddInit] or [AddChildInit].
type Plan struct {
// Children are the [PlanItem]s for the children.
Children []*PlanItem
// EnforceEmpty is whether an empty plan results in the removal
// of all children of the parent. If there are [NodeBase.Makers]
// defined then this is true by default; otherwise it is false.
EnforceEmpty bool
}
// PlanItem represents a plan for how a child [Node] should be constructed and initialized.
// See [Plan] for more information.
type PlanItem struct {
// Name is the name of the planned node.
Name string
// New returns a new node of the correct type for this child.
New func() Node
// Init is a slice of functions that are called once in sequential ascending order
// after [PlanItem.New] to initialize the node for the first time.
Init []func(n Node)
}
// Updater adds a new function to [NodeBase.Updaters.Normal], which are called in sequential
// descending (reverse) order in [NodeBase.RunUpdaters] to update the node.
func (n *NodeBase) Updater(updater func()) {
n.Updaters.Normal = append(n.Updaters.Normal, updater)
}
// FirstUpdater adds a new function to [NodeBase.Updaters.First], which are called in sequential
// descending (reverse) order in [NodeBase.RunUpdaters] to update the node.
func (n *NodeBase) FirstUpdater(updater func()) {
n.Updaters.First = append(n.Updaters.First, updater)
}
// FinalUpdater adds a new function to [NodeBase.Updaters.Final], which are called in sequential
// descending (reverse) order in [NodeBase.RunUpdaters] to update the node.
func (n *NodeBase) FinalUpdater(updater func()) {
n.Updaters.Final = append(n.Updaters.Final, updater)
}
// Maker adds a new function to [NodeBase.Makers.Normal], which are called in sequential
// ascending order in [NodeBase.Make] to make the plan for how the node's children
// should be configured.
func (n *NodeBase) Maker(maker func(p *Plan)) {
n.Makers.Normal = append(n.Makers.Normal, maker)
}
// FirstMaker adds a new function to [NodeBase.Makers.First], which are called in sequential
// ascending order in [NodeBase.Make] to make the plan for how the node's children
// should be configured.
func (n *NodeBase) FirstMaker(maker func(p *Plan)) {
n.Makers.First = append(n.Makers.First, maker)
}
// FinalMaker adds a new function to [NodeBase.Makers.Final], which are called in sequential
// ascending order in [NodeBase.Make] to make the plan for how the node's children
// should be configured.
func (n *NodeBase) FinalMaker(maker func(p *Plan)) {
n.Makers.Final = append(n.Makers.Final, maker)
}
// Make makes a plan for how the node's children should be structured.
// It does this by running [NodeBase.Makers] in sequential ascending order.
func (n *NodeBase) Make(p *Plan) {
// only enforce empty if makers exist
if len(n.Makers.First) > 0 || len(n.Makers.Normal) > 0 || len(n.Makers.Final) > 0 {
p.EnforceEmpty = true
}
n.Makers.Do(func(makers *[]func(p *Plan)) {
for _, maker := range *makers {
maker(p)
}
})
}
// UpdateFromMake updates the node using [NodeBase.Make].
func (n *NodeBase) UpdateFromMake() {
p := &Plan{}
n.Make(p)
p.Update(n)
}
// RunUpdaters runs the [NodeBase.Updaters] in sequential descending (reverse) order.
// It is called in [cogentcore.org/core/core.WidgetBase.UpdateWidget] and other places
// such as in xyz to update the node.
func (n *NodeBase) RunUpdaters() {
n.Updaters.Do(func(updaters *[]func()) {
for i := len(*updaters) - 1; i >= 0; i-- {
(*updaters)[i]()
}
})
}
// Add adds a new [PlanItem] to the given [Plan] for a [Node] with
// the given function to initialize the node. The node is
// guaranteed to be added to its parent before the init function
// is called. The name of the node is automatically generated based
// on the file and line number of the calling function.
//
//goscript:callsite
func Add[T NodeValue](p *Plan, init func(w *T)) {
AddAt(p, AutoPlanName(2), init)
}
// AutoPlanName returns the dir-filename of [runtime.Caller](level),
// with all / . replaced to -, which is suitable as a unique name
// for a [PlanItem.Name].
//
// Under GoScript, the //goscript:callsite directive on it and on the functions
// that call it makes their callers pass the Go file and line of each call,
// so that the names are the same as in Go even in a minified JavaScript bundle.
//
//goscript:callsite
func AutoPlanName(level int) string {
_, file, line, _ := runtime.Caller(level)
name := filepath.Base(file)
dir := filepath.Base(filepath.Dir(file))
path := dir + "-" + name
path = strings.ReplaceAll(strings.ReplaceAll(path, "/", "-"), ".", "-") + "-" + strconv.Itoa(line)
return path
}
// AddAt adds a new [PlanItem] to the given [Plan] for a [Node] with
// the given name and function to initialize the node. The node
// is guaranteed to be added to its parent before the init function
// is called.
func AddAt[T NodeValue](p *Plan, name string, init func(w *T)) {
p.Add(name, func() Node {
return any(New[T]()).(Node)
}, func(n Node) {
init(any(n).(*T))
})
}
// AddNew adds a new [PlanItem] to the given [Plan] for a [Node] with
// the given name, function for constructing the node, and function
// for initializing the node. The node is guaranteed to be added
// to its parent before the init function is called.
// It should only be called instead of [Add] and [AddAt] when the node
// must be made new, like when using [cogentcore.org/core/core.NewValue].
func AddNew[T Node](p *Plan, name string, new func() T, init func(w T)) {
p.Add(name, func() Node {
return new()
}, func(n Node) {
init(n.(T))
})
}
// AddInit adds a new function for initializing the [Node] with the given name
// in the given [Plan]. The node must already exist in the plan; this is for
// extending an existing [PlanItem], not adding a new one. The node is guaranteed to
// be added to its parent before the init function is called. The init functions are
// called in sequential ascending order.
func AddInit[T NodeValue](p *Plan, name string, init func(w *T)) {
for _, child := range p.Children {
if child.Name == name {
child.Init = append(child.Init, func(n Node) {
init(any(n).(*T))
})
return
}
}
slog.Error("AddInit: child not found", "name", name)
}
// AddChild adds a new [NodeBase.Maker] to the the given parent [Node] that
// adds a [PlanItem] with the given init function using [Add]. In other words,
// this adds a maker that will add a child to the given parent.
//
//goscript:callsite
func AddChild[T NodeValue](parent Node, init func(w *T)) {
name := AutoPlanName(2) // must get here to get correct name
parent.AsTree().Maker(func(p *Plan) {
AddAt(p, name, init)
})
}
// AddChildAt adds a new [NodeBase.Maker] to the the given parent [Node] that
// adds a [PlanItem] with the given name and init function using [AddAt]. In other
// words, this adds a maker that will add a child to the given parent.
func AddChildAt[T NodeValue](parent Node, name string, init func(w *T)) {
parent.AsTree().Maker(func(p *Plan) {
AddAt(p, name, init)
})
}
// AddChildInit adds a new [NodeBase.Maker] to the the given parent [Node] that
// adds a new function for initializing the node with the given name
// in the given [Plan]. The node must already exist in the plan; this is for
// extending an existing [PlanItem], not adding a new one. The node is guaranteed
// to be added to its parent before the init function is called. The init functions are
// called in sequential ascending order.
func AddChildInit[T NodeValue](parent Node, name string, init func(w *T)) {
parent.AsTree().Maker(func(p *Plan) {
AddInit(p, name, init)
})
}
// Add adds a new [PlanItem] with the given name and functions to the [Plan].
// It should typically not be called by end-user code; see the generic
// [Add], [AddAt], [AddNew], [AddChild], [AddChildAt], [AddInit], and [AddChildInit]
// functions instead.
func (p *Plan) Add(name string, new func() Node, init func(w Node)) {
p.Children = append(p.Children, &PlanItem{Name: name, New: new, Init: []func(n Node){init}})
}
// Update updates the children of the given [Node] in accordance with the [Plan].
func (p *Plan) Update(n Node) {
if len(p.Children) == 0 && !p.EnforceEmpty {
return
}
pr := profile.Start("plan.Update")
plan.Update(&n.AsTree().Children, len(p.Children),
func(i int) string {
return p.Children[i].Name
}, func(name string, i int) Node {
item := p.Children[i]
child := item.New()
child.AsTree().SetName(item.Name)
return child
}, func(child Node, i int) {
SetParent(child, n)
for _, f := range p.Children[i].Init {
f(child)
}
}, func(child Node) {
child.Destroy()
},
)
pr.End()
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tree
import (
"cogentcore.org/core/base/slicesx"
)
// IndexOf returns the index of the given node in the given slice,
// or -1 if it is not found. The optional startIndex argument
// allows for optimized bidirectional searching if you have a guess
// at where the node might be, which can be a key speedup for large
// slices. If no value is specified for startIndex, it starts in the
// middle, which is a good default.
func IndexOf(slice []Node, child Node, startIndex ...int) int {
return slicesx.Search(slice, func(e Node) bool { return e == child }, startIndex...)
}
// IndexByName returns the index of the first element in the given slice that
// has the given name, or -1 if none is found. See [IndexOf] for info on startIndex.
func IndexByName(slice []Node, name string, startIndex ...int) int {
return slicesx.Search(slice, func(ch Node) bool { return ch.AsTree().Name == name }, startIndex...)
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tree
import (
"cogentcore.org/core/base/plan"
"cogentcore.org/core/types"
)
// TypePlan is a plan for the organization of a list of tree nodes,
// specified by the Type of element at a given index, with a given name.
// It is used in [Update] and [UpdateSlice] to actually update the items
// according to the plan.
type TypePlan []TypePlanItem
// TypePlanItem holds a type and a name, for specifying the [TypePlan].
type TypePlanItem struct {
Type *types.Type
Name string
}
// Add adds a new [TypePlanItem] with the given type and name.
func (t *TypePlan) Add(typ *types.Type, name string) {
*t = append(*t, TypePlanItem{typ, name})
}
// UpdateSlice ensures that the given slice contains the elements
// according to the [TypePlan], specified by unique element names.
// The given Node is set as the parent of the created nodes.
// It returns whether any changes were made.
func UpdateSlice(slice *[]Node, parent Node, p TypePlan) bool {
return plan.Update(slice, len(p),
func(i int) string { return p[i].Name },
func(name string, i int) Node {
n := newOfType(p[i].Type)
n.AsTree().SetName(name)
InitNode(n)
return n
}, func(child Node, i int) {
if parent != nil {
SetParent(child, parent)
}
},
func(child Node) {
child.Destroy()
},
)
}
// Update ensures that the children of the given [Node] contain the elements
// according to the [TypePlan], specified by unique element names.
// It returns whether any changes were made.
func Update(n Node, p TypePlan) bool {
return UpdateSlice(&n.AsTree().Children, n, p)
}
// Copyright (c) 2020, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
This file provides basic tree walking functions for iterative traversal
of the tree in up / down directions. As compared to the Node walk methods,
these are for more dynamic, piecemeal processing.
*/
package tree
// Last returns the last node in the tree.
func Last(n Node) Node {
n = lastChild(n)
last := n
for k := range n.AsTree().All() {
last = k
}
return last
}
// lastChild returns the last child under the given node,
// or the node itself if it has no children.
func lastChild(n Node) Node {
nb := n.AsTree()
if nb.HasChildren() {
return lastChild(nb.Child(nb.NumChildren() - 1))
}
return n
}
// Previous returns the previous node in the tree,
// or nil if this is the root node.
func Previous(n Node) Node {
nb := n.AsTree()
if nb.Parent == nil {
return nil
}
myidx := n.AsTree().IndexInParent()
if myidx > 0 {
nn := nb.Parent.AsTree().Child(myidx - 1)
return lastChild(nn)
}
return nb.Parent
}
// Next returns next node in the tree,
// or nil if this is the last node.
func Next(n Node) Node {
if !n.AsTree().HasChildren() {
return NextSibling(n)
}
return n.AsTree().Child(0)
}
// NextSibling returns the next sibling of this node,
// or nil if it has none.
func NextSibling(n Node) Node {
nb := n.AsTree()
if nb.Parent == nil {
return nil
}
myidx := n.AsTree().IndexInParent()
if myidx >= 0 && myidx < nb.Parent.AsTree().NumChildren()-1 {
return nb.Parent.AsTree().Child(myidx + 1)
}
return NextSibling(nb.Parent)
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tree
// walkStack holds the current child index of each node on the path of a
// depth-first walk, in place of a map from node to index: the path has few
// nodes, and the node looked up is nearly always the deepest one, so it is
// searched from the end. It behaves as the map would, including for nodes
// that are not on it.
type walkStack []walkEntry
// walkEntry is the current child index of a node in a [walkStack].
type walkEntry struct {
node Node
child int
}
// get returns the child index of n, or 0 if n is not in the stack.
func (ws walkStack) get(n Node) int {
for ri := len(ws) - 1; ri >= 0; ri-- {
w := ws[ri]
if w.node == n {
return w.child
}
}
return 0
}
// set sets the child index of n, adding n to the end if it is not in the stack.
func (ws *walkStack) set(n Node, child int) {
s := *ws
for i := len(s) - 1; i >= 0; i-- {
if s[i].node == n {
s[i].child = child
return
}
}
*ws = append(s, walkEntry{n, child})
}
// push adds n with the given child index to the end of the stack, for a
// node that is known not to be in it, such as a child of the deepest node,
// which cannot also be on the path above it.
func (ws *walkStack) push(n Node, child int) {
*ws = append(*ws, walkEntry{n, child})
}
// delete removes n from the stack, if it is in it.
func (ws *walkStack) delete(n Node) {
s := *ws
for i := len(s) - 1; i >= 0; i-- {
v := s[i]
if v.node == n {
*ws = append(s[:i], s[i+1:]...)
return
}
}
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Command typgen provides the generation of type information for
// Go types, methods, and functions.
package main
import (
"cogentcore.org/core/cli"
"cogentcore.org/core/types/typegen"
)
func main() {
opts := cli.DefaultOptions("typegen", "Typegen provides the generation of type information for Go types, methods, and functions.")
cli.Run(opts, &typegen.Config{}, typegen.Generate)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package types
import (
"strings"
)
// Directive represents a comment directive in the format:
//
// //tool:directive args...
type Directive struct {
Tool string
Directive string
Args []string
}
// String returns a string representation of the directive
// in the format:
//
// //tool:directive args...
func (d Directive) String() string {
return "//" + d.Tool + ":" + d.Directive + " " + strings.Join(d.Args, " ")
}
func (d Directive) GoString() string { return StructGoString(d) }
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package types
import (
"reflect"
"cogentcore.org/core/base/reflectx"
)
// Field represents a field or embed in a struct.
type Field struct {
// Name is the name of the field (eg: Icon)
Name string
// Doc has all of the comment documentation
// info as one string with directives removed.
Doc string
}
func (f Field) GoString() string { return StructGoString(f) }
// GetField recursively attempts to extract the [Field]
// with the given name from the given struct [reflect.Value],
// by searching through all of the embeds if it can not find
// it directly in the struct.
func GetField(val reflect.Value, field string) *Field {
val = reflectx.NonPointerValue(val)
if !val.IsValid() {
return nil
}
typ := TypeByName(TypeName(val.Type()))
// if we are not in the type registry, there is nothing that we can do
if typ == nil {
return nil
}
for _, f := range typ.Fields {
if f.Name == field {
// we have successfully gotten the field
return &f
}
}
// otherwise, we go through all of the embeds and call
// GetField recursively on them
for _, e := range typ.Embeds {
rf := val.FieldByName(e.Name)
f := GetField(rf, field)
// we have successfully gotten the field
if f != nil {
return f
}
}
return nil
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package types
// Func represents a global function.
type Func struct {
// Name is the fully qualified name of the function
// (eg: cogentcore.org/core/core.NewButton)
Name string
// Doc has all of the comment documentation
// info as one string with directives removed.
Doc string
// Directives are the parsed comment directives
Directives []Directive
// Args are the names of the arguments to the function
Args []string
// Returns are the names of the return values of the function
Returns []string
// ID is the unique function ID number
ID uint64
}
func (f Func) GoString() string { return StructGoString(f) }
// Method represents a method.
type Method struct {
// Name is the name of the method (eg: NewChild)
Name string
// Doc has all of the comment documentation
// info as one string with directives removed.
Doc string
// Directives are the parsed comment directives
Directives []Directive
// Args are the names of the arguments to the function
Args []string
// Returns are the names of the return values of the function
Returns []string
}
func (m Method) GoString() string { return StructGoString(m) }
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package types
import (
"fmt"
"log/slog"
"reflect"
"runtime"
"sync/atomic"
)
var (
// Funcs records all types (i.e., a type registry)
// key is long type name: package_url.Func, e.g., cogentcore.org/core/core.Button
Funcs = map[string]*Func{}
// FuncIDCounter is an atomically incremented uint64 used
// for assigning new [Func.ID] numbers
FuncIDCounter uint64
)
// FuncByName returns a Func by name (package_url.Type, e.g., cogentcore.org/core/core.Button),
func FuncByName(nm string) *Func {
fi, ok := Funcs[nm]
if !ok {
return nil
}
return fi
}
// FuncByNameTry returns a Func by name (package_url.Type, e.g., cogentcore.org/core/core.Button),
// or error if not found
func FuncByNameTry(nm string) (*Func, error) {
fi, ok := Funcs[nm]
if !ok {
return nil, fmt.Errorf("func %q not found", nm)
}
return fi, nil
}
// FuncInfo returns function info for given function.
func FuncInfo(f any) *Func {
return FuncByName(FuncName(f))
}
// FuncInfoTry returns function info for given function.
func FuncInfoTry(f any) (*Func, error) {
return FuncByNameTry(FuncName(f))
}
// AddFunc adds a constructed [Func] to the registry
// and returns it. This sets the ID.
func AddFunc(fun *Func) *Func {
if _, has := Funcs[fun.Name]; has {
slog.Debug("types.AddFunc: Func already exists", "Func.Name", fun.Name)
return fun
}
fun.ID = atomic.AddUint64(&FuncIDCounter, 1)
Funcs[fun.Name] = fun
return fun
}
// FuncName returns the fully package-qualified name of given function
// This is guaranteed to be unique and used for the Funcs registry.
func FuncName(f any) string {
return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package types
import (
"fmt"
"reflect"
"strings"
)
// Type represents a type.
type Type struct {
// Name is the fully package-path-qualified name of the type
// (eg: cogentcore.org/core/core.Button).
Name string
// IDName is the short, package-unqualified, kebab-case name of
// the type that is suitable for use in an ID (eg: button).
IDName string
// Doc has all of the comment documentation
// info as one string with directives removed.
Doc string
// Directives has the parsed comment directives.
Directives []Directive
// Methods of the type, which are available for all types.
Methods []Method
// Embedded fields of struct types.
Embeds []Field
// Fields of struct types.
Fields []Field
// Instance is an instance of a non-nil pointer to the type,
// which is set by [For] and other external functions such that
// a [Type] can be used to make new instances of the type by
// reflection. It is not set by typegen.
Instance any
// ID is the unique type ID number set by [AddType].
ID uint64
}
func (tp *Type) String() string {
return tp.Name
}
// ShortName returns the short name of the type (package.Type)
func (tp *Type) ShortName() string {
if tp == nil {
return ""
}
li := strings.LastIndex(tp.Name, "/")
return tp.Name[li+1:]
}
func (tp *Type) Label() string {
return tp.ShortName()
}
// ReflectType returns the [reflect.Type] for this type, using [Type.Instance].
func (tp *Type) ReflectType() reflect.Type {
if tp.Instance == nil {
return nil
}
return reflect.TypeOf(tp.Instance).Elem()
}
// StructGoString creates a GoString for the given struct,
// omitting any zero values.
func StructGoString(str any) string {
s := reflect.ValueOf(str)
typ := s.Type()
strs := []string{}
for i := 0; i < s.NumField(); i++ {
f := s.Field(i)
if f.IsZero() {
continue
}
nm := typ.Field(i).Name
strs = append(strs, fmt.Sprintf("%s: %#v", nm, f))
}
return "{" + strings.Join(strs, ", ") + "}"
}
func (tp Type) GoString() string { return StructGoString(tp) }
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package typegen
import (
"reflect"
"strings"
"text/template"
"unicode"
"cogentcore.org/core/types"
)
// TypeTmpl is the template for [types.Type] declarations.
// It takes a [*Type] as its value.
var TypeTmpl = template.Must(template.New("Type").
Funcs(template.FuncMap{
"TypesTypeOf": TypesTypeOf,
}).Parse(
`
var _ = types.AddType(&types.Type
{{- $typ := TypesTypeOf . -}}
{{- printf "%#v" $typ -}}
)
`))
// TypesTypeOf converts the given [*Type] to a [*types.Type].
func TypesTypeOf(typ *Type) *types.Type {
cp := typ.Type
res := &cp
res.Fields = typ.Fields.Fields
res.Embeds = typ.Embeds.Fields
return res
}
// FuncTmpl is the template for [types.Func] declarations.
// It takes a [*types.Func] as its value.
var FuncTmpl = template.Must(template.New("Func").Parse(
`
var _ = types.AddFunc(&types.Func
{{- printf "%#v" . -}}
)
`))
// SetterMethodsTmpl is the template for setter methods for a type.
// It takes a [*Type] as its value.
var SetterMethodsTmpl = template.Must(template.New("SetterMethods").
Funcs(template.FuncMap{
"SetterFields": SetterFields,
"SetterType": SetterType,
"DocToComment": DocToComment,
}).Parse(
`
{{$typ := .}}
{{range (SetterFields .)}}
// Set{{.Name}} sets the [{{$typ.LocalName}}.{{.Name}}] {{- if ne .Doc ""}}:{{end}}
{{DocToComment .Doc}}
func (t *{{$typ.LocalName}}) Set{{.Name}}(v {{SetterType . $typ}}) *{{$typ.LocalName}} { t.{{.Name}} = v; return t }
{{end}}
`))
// SetterFields returns all of the exported fields and embedded fields of the given type
// that don't have a `set:"-"` struct tag.
func SetterFields(typ *Type) []types.Field {
res := []types.Field{}
for _, f := range typ.Fields.Fields {
// we do not generate setters for unexported fields
if unicode.IsLower([]rune(f.Name)[0]) {
continue
}
// unspecified indicates to add a set method; only "-" means no set
hasSetter := reflect.StructTag(typ.Fields.Tags[f.Name]).Get("set") != "-"
if hasSetter {
res = append(res, f)
}
}
return res
}
// SetterType returns the setter type name for the given field in the context of the
// given type. It converts slices to variadic arguments.
func SetterType(f types.Field, typ *Type) string {
lt := typ.Fields.LocalTypes[f.Name]
if after, ok := strings.CutPrefix(lt, "[]"); ok {
return "..." + after
}
return lt
}
// DocToComment converts the given doc string to an appropriate comment string.
func DocToComment(doc string) string {
return "// " + strings.ReplaceAll(doc, "\n", "\n// ")
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package typegen provides the generation of type information for
// Go types, methods, and functions.
package typegen
//go:generate core generate
import (
"fmt"
"cogentcore.org/core/base/generate"
"golang.org/x/tools/go/packages"
)
// ParsePackages parses the package(s) located in the configuration source directory.
func ParsePackages(cfg *Config) ([]*packages.Package, error) {
pcfg := &packages.Config{
Mode: PackageModes(cfg),
// TODO: Need to think about types and functions in test files. Maybe write typegen_test.go
// in a separate pass? For later.
Tests: false,
}
pkgs, err := generate.Load(pcfg, cfg.Dir)
if err != nil {
return nil, fmt.Errorf("typegen: Generate: error parsing package: %w", err)
}
return pkgs, err
}
// Generate generates typegen type info, using the
// configuration information, loading the packages from the
// configuration source directory, and writing the result
// to the configuration output file.
//
// It is a simple entry point to typegen that does all
// of the steps; for more specific functionality, create
// a new [Generator] with [NewGenerator] and call methods on it.
//
//cli:cmd -root
func Generate(cfg *Config) error { //types:add
pkgs, err := ParsePackages(cfg)
if err != nil {
return err
}
return GeneratePkgs(cfg, pkgs)
}
// GeneratePkgs generates enum methods using
// the given configuration object and packages parsed
// from the configuration source directory,
// and writes the result to the config output file.
// It is a simple entry point to typegen that does all
// of the steps; for more specific functionality, create
// a new [Generator] with [NewGenerator] and call methods on it.
func GeneratePkgs(cfg *Config, pkgs []*packages.Package) error {
g := NewGenerator(cfg, pkgs)
for _, pkg := range g.Pkgs {
g.Pkg = pkg
g.Buf.Reset()
err := g.Find()
if err != nil {
return fmt.Errorf("typegen: Generate: error finding types for package %q: %w", pkg.Name, err)
}
g.PrintHeader()
has, err := g.Generate()
if !has {
continue
}
if err != nil {
return fmt.Errorf("typegen: Generate: error generating code for package %q: %w", pkg.Name, err)
}
err = g.Write()
if err != nil {
return fmt.Errorf("typegen: Generate: error writing code for package %q: %w", pkg.Name, err)
}
}
return nil
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package typegen
import (
"bytes"
"fmt"
"go/ast"
"go/types"
"maps"
"os"
"slices"
"strings"
"text/template"
"log/slog"
"cogentcore.org/core/base/generate"
"cogentcore.org/core/base/keylist"
"cogentcore.org/core/base/strcase"
"cogentcore.org/core/cli"
ctypes "cogentcore.org/core/types"
"golang.org/x/tools/go/packages"
)
// Generator holds the state of the generator.
// It is primarily used to buffer the output.
type Generator struct {
Config *Config // The configuration information
Buf bytes.Buffer // The accumulated output.
Pkgs []*packages.Package // The packages we are scanning.
Pkg *packages.Package // The packages we are currently on.
File *ast.File // The file we are currently on.
Cmap ast.CommentMap // The comment map for the file we are currently on.
Types []*Type // The types
Methods keylist.List[string, []ctypes.Method] // The methods, keyed by the the full package name of the type of the receiver
Funcs keylist.List[string, ctypes.Func] // The functions
Interfaces keylist.List[string, *types.Interface] // The cached interfaces, created from [Config.InterfaceConfigs]
}
// NewGenerator returns a new generator with the
// given configuration information and parsed packages.
func NewGenerator(config *Config, pkgs []*packages.Package) *Generator {
return &Generator{Config: config, Pkgs: pkgs}
}
// PackageModes returns the package load modes needed for typegen,
// based on the given config information.
func PackageModes(cfg *Config) packages.LoadMode {
res := packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles | packages.NeedImports | packages.NeedTypes | packages.NeedTypesSizes | packages.NeedSyntax | packages.NeedTypesInfo
// we only need deps if we are checking for interface impls
if cfg.InterfaceConfigs.Len() > 0 {
res |= packages.NeedDeps
}
return res
}
// Printf prints the formatted string to the
// accumulated output in [Generator.Buf]
func (g *Generator) Printf(format string, args ...any) {
fmt.Fprintf(&g.Buf, format, args...)
}
// PrintHeader prints the header and package clause
// to the accumulated output
func (g *Generator) PrintHeader() {
// we need a manual import of types because it is
// external, but goimports will handle everything else
generate.PrintHeader(&g.Buf, g.Pkg.Name, "cogentcore.org/core/types", "cogentcore.org/core/base/keylist")
}
// Find goes through all of the types, functions, variables,
// and constants in the package, finds those marked with types:add,
// and adds them to [Generator.Types] and [Generator.Funcs]
func (g *Generator) Find() error {
err := g.GetInterfaces()
if err != nil {
return err
}
g.Types = []*Type{}
err = generate.Inspect(g.Pkg, g.Inspect, "enumgen.go", "typegen.go")
if err != nil {
return fmt.Errorf("error while inspecting: %w", err)
}
return nil
}
// GetInterfaces sets [Generator.Interfaces] based on
// [Generator.Config.InterfaceConfigs]. It should typically not
// be called by end-user code. The interfaces are looked up in
// the package and all of its dependencies, so the package does
// not need to reference them directly.
func (g *Generator) GetInterfaces() error {
if g.Config.InterfaceConfigs.Len() == 0 {
return nil
}
for _, nm := range g.Config.InterfaceConfigs.Keys {
before, after, ok0 := strings.CutLast(nm, ".")
if !ok0 {
return fmt.Errorf("invalid InterfaceConfigs key: %q is not a fully qualified type name", nm)
}
pkg := findPackage(g.Pkg, before, map[*packages.Package]bool{})
if pkg == nil || pkg.Types == nil {
continue
}
obj := pkg.Types.Scope().Lookup(after)
if obj == nil {
continue
}
utyp := obj.Type().Underlying()
iface, ok := utyp.(*types.Interface)
if !ok {
return fmt.Errorf("invalid InterfaceConfigs value: type %q is not a *types.Interface but a %T (type value %v)", nm, utyp, utyp)
}
g.Interfaces.Set(nm, iface)
}
return nil
}
// findPackage returns the package with the given path among
// the given package and its dependencies, or nil if there is none.
func findPackage(pkg *packages.Package, path string, visited map[*packages.Package]bool) *packages.Package {
if pkg.PkgPath == path {
return pkg
}
visited[pkg] = true
for _, ip := range pkg.Imports {
if visited[ip] {
continue
}
if fp := findPackage(ip, path, visited); fp != nil {
return fp
}
}
return nil
}
// AllowedEnumTypes are the types that can be used for enums
// that are not bit flags (bit flags can only be int64s).
// It is stored as a map for quick and convenient access.
var AllowedEnumTypes = map[string]bool{"int": true, "int64": true, "int32": true, "int16": true, "int8": true, "uint": true, "uint64": true, "uint32": true, "uint16": true, "uint8": true}
// Inspect looks at the given AST node and adds it
// to [Generator.Types] if it is marked with an appropriate
// comment directive. It returns whether the AST inspector should
// continue, and an error if there is one. It should only
// be called in [ast.Inspect].
func (g *Generator) Inspect(n ast.Node) (bool, error) {
switch v := n.(type) {
case *ast.File:
g.File = v
g.Cmap = ast.NewCommentMap(g.Pkg.Fset, v, v.Comments)
case *ast.GenDecl:
return g.InspectGenDecl(v)
case *ast.FuncDecl:
return g.InspectFuncDecl(v)
}
return true, nil
}
// InspectGenDecl is the implementation of [Generator.Inspect]
// for [ast.GenDecl] nodes.
func (g *Generator) InspectGenDecl(gd *ast.GenDecl) (bool, error) {
doc := strings.TrimSuffix(gd.Doc.Text(), "\n")
for _, spec := range gd.Specs {
ts, ok := spec.(*ast.TypeSpec)
if !ok {
return true, nil
}
cfg := &Config{}
*cfg = *g.Config
if cfg.InterfaceConfigs.Len() > 0 {
typ := g.Pkg.TypesInfo.Defs[ts.Name].Type()
if !types.IsInterface(typ) {
for in, ic := range cfg.InterfaceConfigs.All() {
iface := g.Interfaces.At(in)
if iface == nil {
slog.Info("missing interface object", "interface", in)
continue
}
if !types.Implements(typ, iface) && !types.Implements(types.NewPointer(typ), iface) { // either base type or pointer can implement
continue
}
*cfg = *ic
}
}
}
// By default, we use the comments on the GenDecl, as that
// is where they are normally stored. However, when there
// are comments on the type spec itself, that means we are
// probably in a type block, and thus we must use the comments
// on the type spec itself.
commentNode := ast.Node(gd)
if ts.Doc != nil || ts.Comment != nil {
commentNode = ts
}
if ts.Doc != nil {
doc = strings.TrimSuffix(ts.Doc.Text(), "\n")
}
dirs, hasAdd, hasSkip, err := g.LoadFromNodeComments(cfg, commentNode)
if err != nil {
return false, err
}
if (!hasAdd && !cfg.AddTypes) || hasSkip { // we must be told to add or we will not add
return true, nil
}
typ := &Type{
Name: FullName(g.Pkg, ts.Name.Name),
IDName: strcase.ToKebab(ts.Name.Name),
Doc: doc,
Directives: dirs,
LocalName: ts.Name.Name,
AST: ts,
Pkg: g.Pkg.Name,
Config: cfg,
}
if st, ok := ts.Type.(*ast.StructType); ok && st.Fields != nil {
emblist := &ast.FieldList{}
delOff := 0
for i := range len(st.Fields.List) {
i -= delOff
field := st.Fields.List[i]
// if we have no names, we are embed, so add to embeds and remove from fields
if len(field.Names) == 0 {
emblist.List = append(emblist.List, field)
st.Fields.List = slices.Delete(st.Fields.List, i, i+1)
delOff++
}
}
embeds, err := g.GetFields(emblist, cfg)
if err != nil {
return false, err
}
typ.Embeds = embeds
fields, err := g.GetFields(st.Fields, cfg)
if err != nil {
return false, err
}
typ.Fields = fields
}
if in, ok := ts.Type.(*ast.InterfaceType); ok {
prev := g.Config.AddMethods
// the only point of an interface is the methods,
// so we add them by default
g.Config.AddMethods = true
for _, m := range in.Methods.List {
if f, ok := m.Type.(*ast.FuncType); ok {
// add in any line comments
if m.Doc == nil {
m.Doc = m.Comment
} else if m.Comment != nil {
m.Doc.List = append(m.Doc.List, m.Comment.List...)
}
g.InspectFuncDecl(&ast.FuncDecl{
Doc: m.Doc,
Recv: &ast.FieldList{List: []*ast.Field{{Type: ts.Name}}},
Name: m.Names[0],
Type: f,
})
}
}
g.Config.AddMethods = prev
}
g.Types = append(g.Types, typ)
}
return true, nil
}
// LocalTypeNameQualifier returns a [types.Qualifier] similar to that
// returned by [types.RelativeTo], but using the package name instead
// of the package path so that it can be used in code.
func LocalTypeNameQualifier(pkg *types.Package) types.Qualifier {
if pkg == nil {
return nil
}
return func(other *types.Package) string {
if pkg == other {
return "" // same package; unqualified
}
return other.Name()
}
}
// InspectFuncDecl is the implementation of [Generator.Inspect]
// for [ast.FuncDecl] nodes.
func (g *Generator) InspectFuncDecl(fd *ast.FuncDecl) (bool, error) {
cfg := &Config{}
*cfg = *g.Config
dirs, hasAdd, hasSkip, err := g.LoadFromNodeComments(cfg, fd)
if err != nil {
return false, err
}
doc := strings.TrimSuffix(fd.Doc.Text(), "\n")
if fd.Recv == nil {
if (!hasAdd && !cfg.AddFuncs) || hasSkip { // we must be told to add or we will not add
return true, nil
}
fun := ctypes.Func{
Name: FullName(g.Pkg, fd.Name.Name),
Doc: doc,
Directives: dirs,
}
args, err := g.GetFields(fd.Type.Params, cfg)
if err != nil {
return false, fmt.Errorf("error getting function args: %w", err)
}
for _, arg := range args.Fields {
fun.Args = append(fun.Args, arg.Name)
}
rets, err := g.GetFields(fd.Type.Results, cfg)
if err != nil {
return false, fmt.Errorf("error getting function return values: %w", err)
}
for _, ret := range rets.Fields {
fun.Returns = append(fun.Returns, ret.Name)
}
g.Funcs.Set(fun.Name, fun)
} else {
if (!hasAdd && !cfg.AddMethods) || hasSkip { // we must be told to add or we will not add
return true, nil
}
method := ctypes.Method{
Name: fd.Name.Name,
Doc: doc,
Directives: dirs,
}
args, err := g.GetFields(fd.Type.Params, cfg)
if err != nil {
return false, fmt.Errorf("error getting method args: %w", err)
}
for _, arg := range args.Fields {
method.Args = append(method.Args, arg.Name)
}
rets, err := g.GetFields(fd.Type.Results, cfg)
if err != nil {
return false, fmt.Errorf("error getting method return values: %w", err)
}
for _, ret := range rets.Fields {
method.Returns = append(method.Returns, ret.Name)
}
typ := fd.Recv.List[0].Type
// get rid of any pointer receiver
tnm := strings.TrimPrefix(types.ExprString(typ), "*")
typnm := FullName(g.Pkg, tnm)
g.Methods.Set(typnm, append(g.Methods.At(typnm), method))
}
return true, nil
}
// FullName returns the fully qualified name of an identifier
// in the given package with the given name.
func FullName(pkg *packages.Package, name string) string {
// idents in main packages are just "main.IdentName"
if pkg.Name == "main" {
return "main." + name
}
return pkg.PkgPath + "." + name
}
// GetFields creates and returns a new [ctypes.Fields] object
// from the given [ast.FieldList], in the context of the
// given surrounding config. If the given field list is
// nil, GetFields still returns an empty but valid
// [ctypes.Fields] value and no error.
func (g *Generator) GetFields(list *ast.FieldList, cfg *Config) (Fields, error) {
res := Fields{LocalTypes: map[string]string{}, Tags: map[string]string{}}
if list == nil {
return res, nil
}
for _, field := range list.List {
ltn := types.ExprString(field.Type)
ftyp := g.Pkg.TypesInfo.TypeOf(field.Type)
tn := ftyp.String()
switch ftyp.(type) {
case *types.Slice, *types.Array, *types.Map:
default:
// if the type is not a slice, array, or map, we get the name of the type
// before anything involving square brackets so that generic types don't confuse it
tn, _, _ = strings.Cut(tn, "[")
tn, _, _ = strings.Cut(tn, "]")
}
name := ""
if len(field.Names) == 1 {
name = field.Names[0].Name
} else if len(field.Names) == 0 {
// if we have no name, fall back on type name
name = tn
// we must get rid of any package name, as field
// names never have package names
li := strings.LastIndex(name, ".")
if li >= 0 {
name = name[li+1:] // need to get rid of .
}
} else {
// if we have more than one name, that typically indicates
// type-omitted arguments (eg: "func(x, y float32)"), so
// we handle all of the names seperately here and then continue.
for _, nm := range field.Names {
nfield := *field
nfield.Names = []*ast.Ident{nm}
nlist := &ast.FieldList{List: []*ast.Field{&nfield}}
nfields, err := g.GetFields(nlist, cfg)
if err != nil {
return res, err
}
res.Fields = append(res.Fields, nfields.Fields...)
maps.Copy(res.LocalTypes, nfields.LocalTypes)
maps.Copy(res.Tags, nfields.Tags)
}
continue
}
fo := ctypes.Field{
Name: name,
Doc: strings.TrimSuffix(field.Doc.Text(), "\n"),
}
res.Fields = append(res.Fields, fo)
res.LocalTypes[name] = ltn
tag := ""
if field.Tag != nil {
// need to get rid of leading and trailing backquotes
tag = strings.TrimPrefix(strings.TrimSuffix(field.Tag.Value, "`"), "`")
}
res.Tags[name] = tag
}
return res, nil
}
// LoadFromNodeComments is a helper function that calls [LoadFromComments] with the correctly
// filtered comment map comments of the given node.
func (g *Generator) LoadFromNodeComments(cfg *Config, n ast.Node) (dirs []ctypes.Directive, hasAdd bool, hasSkip bool, err error) {
cs := g.Cmap.Filter(n).Comments()
tf := g.Pkg.Fset.File(g.File.FileStart)
np := tf.Line(n.Pos())
keep := []*ast.CommentGroup{}
for _, c := range cs {
// if the comment's line is after ours, we ignore it, as it is likely associated with something else
if tf.Line(c.Pos()) > np {
continue
}
keep = append(keep, c)
}
return LoadFromComments(cfg, keep...)
}
// LoadFromComments is a helper function that combines the results of [LoadFromComment]
// for the given comment groups.
func LoadFromComments(cfg *Config, c ...*ast.CommentGroup) (dirs []ctypes.Directive, hasAdd bool, hasSkip bool, err error) {
for _, cg := range c {
cdirs, cadd, cskip, err := LoadFromComment(cg, cfg)
if err != nil {
return nil, false, false, err
}
dirs = append(dirs, cdirs...)
hasAdd = hasAdd || cadd
hasSkip = hasSkip || cskip
}
return
}
// LoadFromComment processes the given comment group, setting the
// values of the given config object based on any types directives
// in the comment group, and returning all directives found, whether
// there was a types:add directive, and any error. If the given
// documentation is nil, LoadFromComment still returns an empty but valid
// [ctypes.Directives] value, false, and no error.
func LoadFromComment(c *ast.CommentGroup, cfg *Config) (dirs []ctypes.Directive, hasAdd bool, hasSkip bool, err error) {
if c == nil {
return
}
for _, c := range c.List {
dir, err := cli.ParseDirective(c.Text)
if err != nil {
return nil, false, false, fmt.Errorf("error parsing comment directive from %q: %w", c.Text, err)
}
if dir == nil {
continue
}
if dir.Tool == "types" && dir.Directive == "add" {
hasAdd = true
}
if dir.Tool == "types" {
if dir.Directive == "skip" {
hasSkip = true
}
if dir.Directive == "add" || dir.Directive == "skip" {
leftovers, err := cli.SetFromArgs(cfg, dir.Args, cli.ErrNotFound)
if err != nil {
return nil, false, false, fmt.Errorf("error setting config info from comment directive args: %w (from directive %q)", err, c.Text)
}
if len(leftovers) > 0 {
return nil, false, false, fmt.Errorf("expected 0 positional arguments but got %d (list: %v) (from directive %q)", len(leftovers), leftovers, c.Text)
}
} else {
return nil, false, false, fmt.Errorf("unrecognized types directive %q (from %q)", dir.Directive, c.Text)
}
}
dirs = append(dirs, *dir)
}
return dirs, hasAdd, hasSkip, nil
}
// Generate produces the code for the types
// stored in [Generator.Types] and stores them in
// [Generator.Buf]. It returns whether there were
// any types to generate methods for, and
// any error that occurred.
func (g *Generator) Generate() (bool, error) {
if len(g.Types) == 0 && g.Funcs.Len() == 0 {
return false, nil
}
for _, typ := range g.Types {
typ.Methods = append(typ.Methods, g.Methods.At(typ.Name)...)
g.ExecTmpl(TypeTmpl, typ)
for _, tmpl := range typ.Config.Templates {
g.ExecTmpl(tmpl, typ)
}
if typ.Config.Setters {
g.ExecTmpl(SetterMethodsTmpl, typ)
}
}
for _, fun := range g.Funcs.Values {
g.ExecTmpl(FuncTmpl, fun)
}
return true, nil
}
// ExecTmpl executes the given template with the given data and
// writes the result to [Generator.Buf]. It fatally logs any error.
// All typegen templates take a [*Type] or [*ctypes.Func] as their data.
func (g *Generator) ExecTmpl(t *template.Template, data any) {
err := t.Execute(&g.Buf, data)
if err != nil {
slog.Error("programmer error: internal error: error executing template", "err", err)
os.Exit(1)
}
}
// Write formats the data in the the Generator's buffer
// ([Generator.Buf]) and writes it to the file specified by
// [Generator.Config.Output].
func (g *Generator) Write() error {
return generate.Write(generate.Filepath(g.Pkg, g.Config.Output), g.Buf.Bytes(), nil)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package types provides type information for Go types, methods,
// and functions.
package types
import (
"cmp"
"reflect"
"slices"
"strings"
"sync"
"sync/atomic"
"cogentcore.org/core/base/reflectx"
)
var (
// Types is a type registry, initialized to contain all builtin types. New types
// can be added with [AddType]. The key is the long type name: package/path.Type,
// e.g., cogentcore.org/core/core.Button.
Types = map[string]*Type{}
// typesMu guards [Types], as types (such as the types of new tree nodes)
// can be added in any goroutine, as in the event loops of windows.
typesMu sync.RWMutex
// typeIDCounter is an atomically incremented uint64 used
// for assigning new [Type.ID] numbers.
typeIDCounter atomic.Uint64
)
func init() {
addBuiltin[bool]("bool")
addBuiltin[complex64]("complex64")
addBuiltin[complex128]("complex128")
addBuiltin[float32]("float32")
addBuiltin[float64]("float64")
addBuiltin[int]("int")
addBuiltin[int8]("int8")
addBuiltin[int16]("int16")
addBuiltin[int32]("int32")
addBuiltin[int64]("int64")
addBuiltin[string]("string")
addBuiltin[uint]("uint")
addBuiltin[uint8]("uint8")
addBuiltin[uint16]("uint16")
addBuiltin[uint32]("uint32")
addBuiltin[uint64]("uint64")
addBuiltin[uintptr]("uintptr")
}
// addBuiltin adds the given builtin type with the given name to the type registry.
func addBuiltin[T any](name string) {
var v T
AddType(&Type{Name: name, IDName: name, Instance: v})
}
// TypeByName returns a Type by name (package/path.Type, e.g., cogentcore.org/core/core.Button),
func TypeByName(name string) *Type {
typesMu.RLock()
defer typesMu.RUnlock()
return Types[name]
}
// TypeByValue returns the [Type] of the given value
func TypeByValue(v any) *Type {
return TypeByName(TypeNameValue(v))
}
// TypeByReflectType returns the [Type] of the given reflect type
func TypeByReflectType(typ reflect.Type) *Type {
return TypeByName(TypeName(typ))
}
// For returns the [Type] of the generic type parameter,
// setting its [Type.Instance] to a new(T) if it is nil.
func For[T any]() *Type {
var v T
t := TypeByValue(v)
if t != nil && t.Instance == nil {
t.Instance = new(T)
}
return t
}
// AddType adds a constructed [Type] to the registry
// and returns it. This sets the ID.
func AddType(typ *Type) *Type {
typ.ID = typeIDCounter.Add(1)
typesMu.Lock()
Types[typ.Name] = typ
typesMu.Unlock()
return typ
}
// TypeName returns the long, full package-path qualified type name.
// This is guaranteed to be unique and used for the Types registry.
func TypeName(typ reflect.Type) string {
return reflectx.LongTypeName(typ)
}
// TypeNameValue returns the long, full package-path qualified type name
// of the given Go value. Automatically finds the non-pointer base type.
// This is guaranteed to be unique and used for the Types registry.
func TypeNameValue(v any) string {
typ := reflectx.Underlying(reflect.ValueOf(v)).Type()
return TypeName(typ)
}
// BuiltinTypes returns all of the builtin types in the type registry.
func BuiltinTypes() []*Type {
res := []*Type{}
for _, t := range Types {
if !strings.Contains(t.Name, ".") {
res = append(res, t)
}
}
slices.SortFunc(res, func(a, b *Type) int {
return cmp.Compare(a.Name, b.Name)
})
return res
}
// GetDoc gets the documentation for the given value with the given parent struct, field, and label.
// The value, parent value, and field may be nil/invalid. GetDoc uses the given label to format
// the documentation with [FormatDoc] before returning it.
func GetDoc(value, parent reflect.Value, field reflect.StructField, label string) (string, bool) {
// if we are not part of a struct, we just get the documentation for our type
if !parent.IsValid() {
if !value.IsValid() {
return "", false
}
rtyp := reflectx.NonPointerType(value.Type())
typ := TypeByName(TypeName(rtyp))
if typ == nil {
return "", false
}
return FormatDoc(typ.Doc, rtyp.Name(), label), true
}
// otherwise, we get our field documentation in our parent
f := GetField(parent, field.Name)
if f != nil {
return FormatDoc(f.Doc, field.Name, label), true
}
// if we aren't in the type registry, we fall back on struct tag
doc, ok := field.Tag.Lookup("doc")
if !ok {
return "", false
}
return FormatDoc(doc, field.Name, label), true
}
// FormatDoc formats the given Go documentation string for an identifier with the given
// CamelCase name and intended label. It replaces the name with the label and cleans
// up trailing punctuation.
func FormatDoc(doc, name, label string) string {
doc = strings.ReplaceAll(doc, name, label)
// if we only have one period, get rid of it if it is at the end
if strings.Count(doc, ".") == 1 {
doc = strings.TrimSuffix(doc, ".")
}
return doc
}
// Copyright (c) 2021, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
Package undo package provides a generic undo / redo functionality based on `[]string`
representations of any kind of state representation (typically JSON dump of the 'document'
state). It stores the compact diffs from one state change to the next, with raw copies saved
at infrequent intervals to tradeoff cost of computing diffs.
In addition to state (which is optional on any given step), a description of the action
and arbitrary string-encoded data can be saved with each record. Thus, for cases
where the state doesn't change, you can just save some data about the action sufficient
to undo / redo it.
A new record must be saved of the state just *before* an action takes place
and the nature of the action taken.
Thus, undoing the action restores the state to that prior state.
Redoing the action means restoring the state *after* the action.
This means that the first Undo action must save the current state
before doing the undo.
The Index is always on the last state saved, which will then be the one
that would be undone for an undo action.
*/
package undo
import (
"log"
"strings"
"sync"
"cogentcore.org/core/text/lines"
)
// DefaultRawInterval is interval for saving raw state -- need to do this
// at some interval to prevent having it take too long to compute patches
// from all the diffs.
var DefaultRawInterval = 50
// Record is one undo record, associated with one action that changed state from one to next.
// The state saved in this record is the state *before* the action took place.
// The state is either saved as a Raw value or as a diff Patch to the previous state.
type Record struct {
// description of this action, for user to see
Action string
// action data, encoded however you want -- some undo records can just be about this action data that can be interpreted to Undo / Redo a non-state-changing action
Data string
// if present, then direct save of full state -- do this at intervals to speed up computing prior states
Raw []string
// patch to get from previous record to this one
Patch lines.Patch
// this record is an UndoSave, when Undo first called from end of stack
UndoSave bool
}
// Init sets the action and data in a record -- overwriting any prior values
func (rc *Record) Init(action, data string) {
rc.Action = action
rc.Data = data
rc.Patch = nil
rc.Raw = nil
rc.UndoSave = false
}
// Stack is the undo stack manager that manages the undo and redo process.
type Stack struct {
// Index is the current index in the undo records.
// This is the record that will be undone if user hits undo.
Index int
// Records is the list of saved state / action records.
Records []*Record
// RawInterval is the interval for saving raw data.
// Need to do this at some interval to prevent having it take too long
// to compute patches from all the diffs.
RawInterval int
// Mu mutex that protects updates. Diff computation runs as a separate
// goroutine so it is instant from perspective of UI.
Mu sync.Mutex
}
// RecState returns the state for given index, reconstructing from diffs
// as needed. Must be called under lock.
func (us *Stack) RecState(idx int) []string {
stidx := 0
var cdt []string
for i := idx; i >= 0; i-- {
r := us.Records[i]
if r.Raw != nil {
stidx = i
cdt = r.Raw
break
}
}
for i := stidx + 1; i <= idx; i++ {
r := us.Records[i]
if r.Patch != nil {
cdt = r.Patch.Apply(cdt)
}
}
return cdt
}
// Save saves a new action as next action to be undone, with given action
// data and current full state of the system (either of which are optional).
// The state must be available for saving -- we do not copy in case we save the
// full raw copy.
func (us *Stack) Save(action, data string, state []string) {
us.Mu.Lock() // we start lock
if us.Records == nil {
if us.RawInterval == 0 {
us.RawInterval = DefaultRawInterval
}
us.Records = make([]*Record, 1)
us.Index = 0
nr := &Record{Action: action, Data: data, Raw: state}
us.Records[0] = nr
us.Mu.Unlock()
return
}
// recs will be [old..., Index] after this
us.Index++
var nr *Record
if len(us.Records) > us.Index {
us.Records = us.Records[:us.Index+1]
nr = us.Records[us.Index]
} else if len(us.Records) == us.Index {
nr = &Record{}
us.Records = append(us.Records, nr)
} else {
log.Printf("undo.Stack error: index: %d > len(um.Recs): %d\n", us.Index, len(us.Records))
us.Index = len(us.Records)
nr = &Record{}
us.Records = append(us.Records, nr)
}
nr.Init(action, data)
if state == nil {
us.Mu.Unlock()
return
}
go us.SaveState(nr, us.Index, state) // fork off save -- it will unlock when done
// now we return straight away, with lock still held
}
// MustSaveUndoStart returns true if the current state must be saved as the start of
// the first Undo action when at the end of the stack. If this returns true, then
// call SaveUndoStart. It sets a special flag on the record.
func (us *Stack) MustSaveUndoStart() bool {
return us.Index == len(us.Records)-1
}
// SaveUndoStart saves the current state -- call if MustSaveUndoStart is true.
// Sets a special flag for this record, and action, data are empty.
// Does NOT increment the index, so next undo is still as expected.
func (us *Stack) SaveUndoStart(state []string) {
us.Mu.Lock()
nr := &Record{UndoSave: true}
us.Records = append(us.Records, nr)
us.SaveState(nr, us.Index+1, state) // do it now because we need to immediately do Undo, does unlock
}
// SaveReplace replaces the current Undo record with new state,
// instead of creating a new record. This is useful for when
// you have a stream of the same type of manipulations
// and just want to save the last (it is better to handle that case
// up front as saving the state can be relatively expensive, but
// in some cases it is not possible).
func (us *Stack) SaveReplace(action, data string, state []string) {
us.Mu.Lock()
nr := us.Records[us.Index]
nr.Action = action
nr.Data = data
go us.SaveState(nr, us.Index, state)
}
// SaveState saves given record of state at given index
func (us *Stack) SaveState(nr *Record, idx int, state []string) {
if idx%us.RawInterval == 0 {
nr.Raw = state
us.Mu.Unlock()
return
}
prv := us.RecState(idx - 1)
dif := lines.DiffLines(prv, state)
nr.Patch = dif.ToPatch(state)
us.Mu.Unlock()
}
// HasUndoAvail returns true if there is at least one undo record available.
// This does NOT get the lock -- may rarely be inaccurate but is used for
// gui enabling so not such a big deal.
func (us *Stack) HasUndoAvail() bool {
return us.Index >= 0
}
// HasRedoAvail returns true if there is at least one redo record available.
// This does NOT get the lock -- may rarely be inaccurate but is used for
// GUI enabling so not such a big deal.
func (us *Stack) HasRedoAvail() bool {
return us.Index < len(us.Records)-2
}
// Undo returns the action, action data, and state at the current index
// and decrements the index to the previous record.
// This state is the state just prior to the action.
// If already at the start (Index = -1) then returns empty everything
// Before calling, first check MustSaveUndoStart() -- if false, then you need
// to call SaveUndoStart() so that the state just before Undoing can be redone!
func (us *Stack) Undo() (action, data string, state []string) {
us.Mu.Lock()
if us.Index < 0 || us.Index >= len(us.Records) {
us.Mu.Unlock()
return
}
rec := us.Records[us.Index]
action = rec.Action
data = rec.Data
state = us.RecState(us.Index)
us.Index--
us.Mu.Unlock()
return
}
// UndoTo returns the action, action data, and state at the given index
// and decrements the index to the previous record.
// If idx is out of range then returns empty everything
func (us *Stack) UndoTo(idx int) (action, data string, state []string) {
us.Mu.Lock()
if idx < 0 || idx >= len(us.Records) {
us.Mu.Unlock()
return
}
rec := us.Records[idx]
action = rec.Action
data = rec.Data
state = us.RecState(idx)
us.Index = idx - 1
us.Mu.Unlock()
return
}
// Redo returns the action, data at the *next* index, and the state at the
// index *after that*.
// returning nil if already at end of saved records.
func (us *Stack) Redo() (action, data string, state []string) {
us.Mu.Lock()
if us.Index >= len(us.Records)-2 {
us.Mu.Unlock()
return
}
us.Index++
rec := us.Records[us.Index] // action being redone is this one
action = rec.Action
data = rec.Data
state = us.RecState(us.Index + 1) // state is the one *after* it
us.Mu.Unlock()
return
}
// RedoTo returns the action, action data, and state at the given index,
// returning nil if already at end of saved records.
func (us *Stack) RedoTo(idx int) (action, data string, state []string) {
us.Mu.Lock()
if idx >= len(us.Records)-1 || idx <= 0 {
us.Mu.Unlock()
return
}
us.Index = idx
rec := us.Records[idx]
action = rec.Action
data = rec.Data
state = us.RecState(idx + 1)
us.Mu.Unlock()
return
}
// Reset resets the undo state
func (us *Stack) Reset() {
us.Mu.Lock()
us.Records = nil
us.Index = 0
us.Mu.Unlock()
}
// UndoList returns the list actions in order from the most recent back in time
// suitable for a menu of actions to undo.
func (us *Stack) UndoList() []string {
if us.Index < 0 || us.Index >= len(us.Records) {
return nil
}
al := make([]string, us.Index+1)
for i := us.Index; i >= 0; i-- {
al[us.Index-i] = us.Records[i].Action
}
return al
}
// RedoList returns the list actions in order from the current forward to end
// suitable for a menu of actions to redo
func (us *Stack) RedoList() []string {
nl := len(us.Records)
if us.Index >= nl-2 {
return nil
}
st := us.Index + 1
n := (nl - 1) - st
al := make([]string, n)
for i := st; i < nl-1; i++ {
al[i-st] = us.Records[i].Action
}
return al
}
// MemUsed reports the amount of memory used for record
func (rc *Record) MemUsed() int {
mem := 0
if rc.Raw != nil {
for _, s := range rc.Raw {
mem += len(s)
}
} else {
for _, pr := range rc.Patch {
for _, s := range pr.Blines {
mem += len(s)
}
}
}
return mem
}
// MemStats reports the memory usage statistics.
// if details is true, each record is reported.
func (us *Stack) MemStats(details bool) string {
sb := strings.Builder{}
// TODO(kai): add this back once we figure out how to do core.FileSize
/*
sum := 0
for i, r := range um.Recs {
mem := r.MemUsed()
sum += mem
if details {
sb.WriteString(fmt.Sprintf("%d\t%s\tmem:%s\n", i, r.Action, core.FileSize(mem).String()))
}
}
sb.WriteString(fmt.Sprintf("Total: %s\n", core.FileSize(sum).String()))
*/
return sb.String()
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !js && !novideo
package video
import (
"math"
"sync"
"sync/atomic"
"time"
"github.com/faiface/beep"
"github.com/faiface/beep/effects"
"github.com/faiface/beep/speaker"
)
// SpeakerSampleRate is the sample rate of the speaker.
const SpeakerSampleRate beep.SampleRate = sampleRate
// speakerInit initializes the speaker once, for all playbacks.
var speakerInit = sync.OnceValue(func() error {
return speaker.Init(SpeakerSampleRate, SpeakerSampleRate.N(time.Second/10))
})
// audioAvailable returns whether audio can be played.
func audioAvailable() bool { return speakerInit() == nil }
// audio is the audio of a playing on the speaker, or, without a speaker
// (as when the system has no audio device), of a silent playing that
// consumes the samples at their rate, which times the playing of media
// that has only audio (see [Playback]).
type audio struct {
ctrl *beep.Ctrl
volume *effects.Volume
// played is the number of samples played (not of the silence played
// while the samples are not decoded yet, as of a stream over the
// network), which is the time played.
played atomic.Int64
// ended is closed when all of the samples have been played.
ended chan struct{}
endedOnce sync.Once
// silent is whether it is played without a speaker, paused when paused
// and ending when stopped (with mu).
silent bool
mu sync.Mutex
paused, stopped bool
}
// playAudio starts playing the given audio samples on the speaker,
// paused if paused, at the given volume (see [Playback.Volume]), or muted.
// Without a speaker, the samples are played silently, at their rate.
func playAudio(samples <-chan [2]float64, paused bool, volume float32, muted bool) *audio {
a := &audio{ended: make(chan struct{})}
if !audioAvailable() {
a.silent, a.paused = true, paused
go a.playSilent(samples)
return a
}
a.ctrl = &beep.Ctrl{Streamer: a.streamSamples(samples), Paused: paused}
a.volume = &effects.Volume{Streamer: a.ctrl, Base: 2}
a.setVolumeLocked(volume, muted)
speaker.Play(a.volume)
return a
}
// setVolume sets the volume of the audio (see [Playback.Volume]), or mutes it.
func (a *audio) setVolume(volume float32, muted bool) {
if a.silent {
return
}
speaker.Lock()
a.setVolumeLocked(volume, muted)
speaker.Unlock()
}
// setVolumeLocked sets the volume, with the lock of the speaker held, or
// before it plays. The volume of beep is in powers of its base (2): a
// volume of 1/2 is -1.
func (a *audio) setVolumeLocked(volume float32, muted bool) {
if volume == 0 {
volume = 1
}
a.volume.Silent = muted || volume < 1e-3
a.volume.Volume = math.Log2(float64(volume))
}
// setPaused pauses or resumes the audio.
func (a *audio) setPaused(paused bool) {
if a.silent {
a.mu.Lock()
a.paused = paused
a.mu.Unlock()
return
}
speaker.Lock()
a.ctrl.Paused = paused
speaker.Unlock()
}
// stop stops the audio for good, removing it from the speaker (a paused
// streamer would stay in its mixer).
func (a *audio) stop() {
if a.silent {
a.mu.Lock()
a.stopped = true
a.mu.Unlock()
return
}
speaker.Lock()
a.ctrl.Streamer = nil // (a Ctrl without a streamer is drained)
speaker.Unlock()
}
// time returns the time of the audio played.
func (a *audio) time() time.Duration {
return time.Duration(a.played.Load()) * time.Second / sampleRate
}
// end marks the audio as having played all of its samples.
func (a *audio) end() {
a.endedOnce.Do(func() { close(a.ended) })
}
// streamSamples returns a streamer of the audio samples from the given
// channel. It does not wait for samples that are not decoded yet (which
// would stop all of the sounds of the speaker), playing silence instead,
// and it ends when the channel is closed.
func (a *audio) streamSamples(samples <-chan [2]float64) beep.Streamer {
return beep.StreamerFunc(func(out [][2]float64) (int, bool) {
n := 0
defer func() { a.played.Add(int64(n)) }()
for i := range out {
select {
case s, ok := <-samples:
if !ok {
a.end()
return i, i > 0
}
out[i] = s
n++
default:
out[i] = [2]float64{}
}
}
return len(out), true
})
}
// playSilent consumes the given samples at their rate while not paused,
// without a speaker, until the channel is closed.
func (a *audio) playSilent(samples <-chan [2]float64) {
tick := time.NewTicker(20 * time.Millisecond)
defer tick.Stop()
last := time.Now()
owed := 0.0 // the samples due to be played
for now := range tick.C {
a.mu.Lock()
paused, stopped := a.paused, a.stopped
a.mu.Unlock()
if stopped {
return
}
if !paused {
owed += now.Sub(last).Seconds() * sampleRate
}
last = now
consume:
for ; owed >= 1; owed-- {
select {
case _, ok := <-samples:
if !ok {
a.end()
return
}
a.played.Add(1)
default: // (not decoded yet: played as silence)
owed = 0
break consume
}
}
}
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package video
import (
"image"
"image/color"
"time"
"cogentcore.org/core/colors"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/events/key"
"cogentcore.org/core/icons"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/tree"
)
// Player is a player of a video that [Controls] control: a [Video], or
// another widget that shows a [Playback] (as a video of a web page).
type Player interface {
// TogglePlay plays the video if it is not playing, and pauses it if it is.
TogglePlay()
// IsPlaying returns whether the video is playing (not paused nor ended).
IsPlaying() bool
// Seek plays the video from the given time, staying paused if it is.
Seek(t time.Duration)
// SkipBy seeks the video by the given time from its current time.
SkipBy(d time.Duration)
// StepFrame pauses the video and shows its next frame, or the one
// before it for a negative n.
StepFrame(n int)
// CurrentTime returns the current time of the video.
CurrentTime() time.Duration
// Duration returns the duration of the video, or 0 if it is not known.
Duration() time.Duration
// IsMuted returns whether the audio is not heard.
IsMuted() bool
// SetMuted sets whether the audio is not heard.
SetMuted(muted bool)
// Volume returns the volume of the audio, from 0 to 1.
Volume() float32
// SetVolume sets the volume of the audio, from 0 to 1.
SetVolume(volume float32)
}
// controlsHideDelay is how long the controls stay shown after the mouse
// stops moving over the bottom of a playing video, and controlsLeaveDelay
// after it moves out of the bottom.
const (
controlsHideDelay = 2500 * time.Millisecond
controlsLeaveDelay = 500 * time.Millisecond
)
// Controls are the standard controls of a video player, as those of the
// video elements of browsers: a bar over the bottom of the video, partly
// transparent, with the position (a slider, which seeks when it is
// changed), buttons to skip back 10 seconds, to play and pause, and to
// skip forward 10 seconds, to mute, with the volume and the time.
// They are a child of the widget of the video (their target), which must
// be their containing block (positioned, as relative), and are shown while
// the mouse moves over them (see [Controls.inZone]), until 2.5
// seconds after it stops there, or half a second after it moves out of the
// bottom or leaves, and while the video is not playing. A click on the target (not on the
// controls) plays and pauses the video, and gives it the focus, for the
// keys of players (see [Controls.handleKey]). The target must be rendered as a
// whole when the controls change (see [Video.RenderGroup]), as they are
// partly transparent over the video. The controls of an audio player (see
// [Controls.SetAudio]) are one row that fills the target, always shown.
type Controls struct { //types:add
core.Frame
// player is the player that the controls control.
player Player
// target is the widget of the video that the controls are over.
target core.Widget
position *core.Slider
play *core.Button
mute *core.Button
volume *core.Slider
time *core.Text
// shownAt is when the controls were last shown by the mouse moving.
shownAt time.Time
// skips are the buttons that skip back and forward 10 seconds.
skips []*core.Button
// second is the second of the time that is shown.
second int
// audio is whether the controls are those of an audio player
// (see [Controls.SetAudio]).
audio bool
}
// SetAudio makes the controls those of an audio player, as of the audio
// elements of browsers: one row that fills the target (as a bar of the
// height of the row), always shown, with the play button, the time, the
// position, and the volume, without the skip buttons; the right and left
// arrows skip 5 seconds. It is called before [Controls.SetPlayer].
func (c *Controls) SetAudio() *Controls {
c.audio = true
row := c.play.Parent
for _, w := range []core.Widget{c.time, c.position, c.mute, c.volume} {
tree.MoveToParent(w, row)
}
return c
}
// SetPlayer sets the player of the controls and the widget of its video
// (their parent, as a [Video]), which shows them as the mouse moves over
// it, and plays and pauses the video when it is clicked.
func (c *Controls) SetPlayer(target core.Widget, player Player) *Controls {
c.player, c.target = player, target
tw := target.AsWidget()
tw.On(events.MouseMove, func(e events.Event) {
if c.This != nil {
c.mouseMoved(e.Pos())
}
})
tw.On(events.MouseLeave, func(e events.Event) {
if c.This != nil {
c.shownAt = time.Time{}
c.SetShown(!c.player.IsPlaying())
}
})
tw.OnClick(func(e events.Event) {
if c.This == nil || e.Pos().In(c.Geom.TotalBBox) {
return // (a click on the controls)
}
tw.SetFocus() // (for the keys)
c.player.TogglePlay()
c.Refresh()
e.SetHandled()
})
// the keys of players, when the video or its controls have the focus
// (first, before a control, as a slider, handles the arrows)
tw.Styler(func(s *styles.Style) {
s.SetAbilities(true, abilities.Focusable)
})
tw.OnShow(func(e events.Event) {
if c.This != nil {
c.focusTarget()
}
})
keys := func(e events.Event) {
if c.This != nil && !e.IsHandled() && c.handleKey(e) {
e.SetHandled()
}
}
// (first for the controls in it, as the first handlers are those of
// the widgets that the focus is in, and normal for itself)
tw.OnFirst(events.KeyChord, keys)
tw.OnKeyChord(keys)
c.Refresh()
return c
}
func (c *Controls) Init() {
c.Frame.Init()
white := colors.Uniform(color.White)
c.Styler(func(s *styles.Style) {
s.Position = styles.PositionAbsolute
s.Inset.Left, s.Inset.Right, s.Inset.Bottom = units.Zero(), units.Zero(), units.Zero()
s.InsetSet.Left, s.InsetSet.Right, s.InsetSet.Bottom = true, true, true
s.Direction = styles.Column
// (no background of its own: see Render)
s.Color = white
s.Padding.Set(units.Dp(4), units.Dp(8))
s.Gap.Zero()
if c.audio { // (the whole box, with the row in its middle)
s.Inset.Top, s.InsetSet.Top = units.Zero(), true
s.Justify.Content = styles.Center
}
})
// the position, which seeks when it is changed
c.position = core.NewSlider(c).SetMin(0).SetStep(1)
c.position.Styler(func(s *styles.Style) {
s.Grow.Set(1, 0)
})
c.position.FinalStyler(func(s *styles.Style) {
if c.audio { // (in the row, after the 20em of sliders)
s.Min.X.Dp(40)
}
})
c.position.OnChange(func(e events.Event) {
c.player.Seek(time.Duration(c.position.Value * float32(time.Second)))
c.Refresh()
})
// the buttons, volume and time
row := core.NewFrame(c)
row.Styler(func(s *styles.Style) {
s.Align.Items = styles.Center
s.Gap.X.Dp(2)
})
button := func(icon icons.Icon, tooltip string, do func()) *core.Button {
bt := core.NewButton(row).SetType(core.ButtonAction).SetIcon(icon)
bt.SetTooltip(tooltip)
bt.Styler(func(s *styles.Style) {
s.Color = white
s.Padding.Set(units.Dp(4))
s.IconSize.Set(units.Em(1.5))
})
bt.OnClick(func(e events.Event) {
do()
c.Refresh()
})
return bt
}
back := button(icons.Replay10, "Back 10 seconds", func() { c.player.SkipBy(-10 * time.Second) })
c.play = button(icons.PlayArrow, "Play", func() { c.player.TogglePlay() })
forward := button(icons.Forward10, "Forward 10 seconds", func() { c.player.SkipBy(10 * time.Second) })
c.skips = []*core.Button{back, forward}
for _, bt := range c.skips {
bt.Styler(func(s *styles.Style) {
if c.audio {
s.Display = styles.DisplayNone
}
})
}
c.mute = button(icons.VolumeUp, "Mute", func() { c.player.SetMuted(!c.player.IsMuted()) })
c.volume = core.NewSlider(row).SetMin(0).SetMax(1).SetStep(0.05)
c.volume.FinalStyler(func(s *styles.Style) { // (after the 20em of sliders)
w := float32(80)
if c.audio {
w = 50
}
s.Min.X.Dp(w)
s.Max.X.Dp(w)
s.Grow.Set(0, 0)
})
setVolume := func(e events.Event) {
c.player.SetVolume(c.volume.Value)
c.Refresh()
}
c.volume.OnInput(setVolume)
c.volume.OnChange(setVolume)
for _, sl := range []*core.Slider{c.position, c.volume} {
sl.Styler(func(s *styles.Style) {
// white, as in players, over a translucent track
// white, as in players, over a translucent track
sl.ValueColor, sl.ThumbColor = white, white
s.Background = colors.Uniform(color.RGBA{255, 255, 255, 80})
s.Padding.Set(units.Dp(6))
})
}
c.time = core.NewText(row)
c.time.Styler(func(s *styles.Style) {
s.Color = white
s.Margin.Left.Dp(8)
if c.audio {
s.Margin.Right.Dp(4)
}
})
}
// controlsBackground is the partly transparent background of the controls,
// and audioBackground is the background of those of an audio player.
var (
controlsBackground = colors.Uniform(color.RGBA{0, 0, 0, 150})
audioBackground = colors.Uniform(color.RGBA{48, 48, 48, 255})
)
// Render renders the partly transparent background of the controls over
// the video (see [Controls.ChildBackground]), or the background of those of
// an audio player.
func (c *Controls) Render() {
c.Frame.Render()
bg := controlsBackground
if c.audio {
bg = audioBackground
}
c.Scene.Painter.FillBox(c.Geom.Pos.Total, c.Geom.Size.Actual.Total, bg)
}
// ChildBackground returns transparent: the widgets of the controls are over
// the video, so they do not fill their boxes with the background around
// them, which is otherwise that of the widgets they are in, with partly
// transparent ones blended over the parent (opaque gray over a white page).
func (c *Controls) ChildBackground(child core.Widget) image.Image {
return colors.Uniform(color.Transparent)
}
// handleKey handles the keys of players, returning whether the given key
// event is one of them: space plays and pauses, the right and left arrows
// step a frame forward and back, and the up and down arrows skip 10 seconds
// forward and back. The controls are shown as for the mouse.
func (c *Controls) handleKey(e events.Event) bool {
if e.HasAnyModifier(key.Shift, key.Control, key.Alt, key.Meta) {
return false
}
code := e.KeyCode()
if e.KeyRune() == ' ' {
// (the drivers send space as its character, of an unknown code)
code = key.CodeSpacebar
}
switch code {
case key.CodeSpacebar:
c.player.TogglePlay()
case key.CodeRightArrow:
if c.audio {
c.player.SkipBy(5 * time.Second)
} else {
c.player.StepFrame(1)
}
case key.CodeLeftArrow:
if c.audio {
c.player.SkipBy(-5 * time.Second)
} else {
c.player.StepFrame(-1)
}
case key.CodeUpArrow:
c.player.SkipBy(10 * time.Second)
case key.CodeDownArrow:
c.player.SkipBy(-10 * time.Second)
default:
return false
}
c.Refresh()
c.shownAt = time.Now()
c.SetShown(true)
c.hideAfter(controlsHideDelay, c.shownAt)
return true
}
// Refresh updates the controls for the state of the player (with the
// lock of the widgets held).
func (c *Controls) Refresh() {
p := c.player
if p == nil || c.This == nil {
return
}
if p.IsPlaying() {
c.play.SetIcon(icons.Pause).SetTooltip("Pause")
} else {
c.play.SetIcon(icons.PlayArrow).SetTooltip("Play")
}
if p.IsMuted() || p.Volume() < 1e-3 {
c.mute.SetIcon(icons.VolumeOff).SetTooltip("Unmute")
} else {
c.mute.SetIcon(icons.VolumeUp).SetTooltip("Mute")
}
c.volume.SetValue(p.Volume())
c.position.SetMax(float32(max(p.Duration(), time.Second).Seconds()))
// (a live stream, of an unknown duration, is not seeked)
c.position.SetEnabled(p.Duration() > 0)
c.second = -1 // (the time is shown again)
c.SetTime(p.CurrentTime())
c.play.Update()
c.mute.Update()
if !p.IsPlaying() {
c.SetShown(true)
} else if c.IsShown() {
// hidden soon unless the mouse moves over them (as when it starts
// playing, as they are shown before)
c.hideAfter(controlsHideDelay, c.shownAt)
}
c.NeedsRender()
}
// SetTime shows the given current time of the video, once a second
// (unless the position is being dragged), as the video plays.
func (c *Controls) SetTime(t time.Duration) {
if c.player == nil || c.This == nil {
return
}
sec := int(t.Seconds())
if sec == c.second {
return
}
c.second = sec
if !c.position.StateIs(states.Sliding) {
c.position.SetValue(float32(t.Seconds()))
}
text := formatTime(t) // (only the time of a live stream)
if d := c.player.Duration(); d > 0 {
text += " / " + formatTime(d)
}
c.time.SetText(text).UpdateRender()
}
// mouseMoved shows the controls as the mouse moves over the bottom of the
// video (see [Controls.inZone]), and hides them [controlsHideDelay] after it
// stops there, or [controlsLeaveDelay] after it moves out of it, while the
// video plays.
func (c *Controls) mouseMoved(pos image.Point) {
c.focusTarget()
if !c.inZone(pos) {
if c.IsShown() && !c.shownAt.IsZero() {
c.shownAt = time.Time{}
c.hideAfter(controlsLeaveDelay, c.shownAt)
}
return
}
c.shownAt = time.Now()
c.SetShown(true)
c.hideAfter(controlsHideDelay, c.shownAt)
}
// inZone returns whether the given position of the mouse is in the bottom
// of the video, where it shows the controls: the region of the controls
// (or the bottom 15% of the video before they are laid out).
func (c *Controls) inZone(pos image.Point) bool {
tb := c.target.AsWidget().Geom.TotalBBox
top := float32(tb.Max.Y) - 0.15*float32(tb.Dy())
if cb := c.Geom.TotalBBox; !cb.Empty() {
top = float32(cb.Min.Y)
}
return pos.In(tb) && float32(pos.Y) >= top
}
// hideAfter hides the controls after the given delay, if they have not
// been shown again since the given time, while the video plays.
func (c *Controls) hideAfter(delay time.Duration, shownAt time.Time) {
time.AfterFunc(delay, func() {
if c.This == nil || !c.AsyncLockIfShown() {
return
}
defer c.AsyncUnlock()
if c.This != nil && c.shownAt.Equal(shownAt) && c.player.IsPlaying() && !c.position.StateIs(states.Sliding) {
c.SetShown(false)
}
})
}
// focusTarget gives the focus to the video (quietly) if nothing in its
// scene has the focus, as when the mouse moves over it or it is shown, so
// that the keys of players (see [Controls.handleKey]) work at once.
func (c *Controls) focusTarget() {
if tw := c.target.AsWidget(); tw.Scene != nil && !tw.Scene.ContainsFocus() {
tw.SetFocusQuiet()
}
}
// SetShown shows or hides the controls.
func (c *Controls) SetShown(shown bool) {
if c.audio && !shown {
return // (always shown)
}
if c.This == nil || c.StateIs(states.Invisible) == !shown {
return
}
if !shown && c.ContainsFocus() {
// the video gets the focus of a control (as a button that was
// clicked), which keys do not reach once it is hidden
c.target.AsWidget().SetFocusQuiet()
}
c.SetState(!shown, states.Invisible)
c.NeedsRender()
if c.target != nil {
c.target.AsWidget().NeedsRender()
}
}
// IsShown returns whether the controls are shown.
func (c *Controls) IsShown() bool {
return !c.StateIs(states.Invisible)
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package video
import (
"time"
"cogentcore.org/core/tree"
)
// The controls of a [Video] are [Controls], over the bottom of the video.
// The region of the video in the scene is transparent (see [Video.Render]):
// on desktop platforms, the video is drawn by its render source after the
// scene, which draws the region of the controls of the scene again over it;
// on the web, the video element of the browser is under the canvas of the
// scene. The video is rendered as a whole when its controls change
// ([Video.RenderGroup]), so that the transparent bar is drawn over the
// cleared region, not over its previous rendering.
// RenderGroup returns whether the video is rendered as a whole when any
// widget in it needs to be rendered: with its controls.
func (v *Video) RenderGroup() bool {
return v.Controls
}
// initControls adds the controls to the video if [Video.Controls].
func (v *Video) initControls() {
v.Maker(func(p *tree.Plan) {
if !v.Controls {
v.controls = nil
return
}
tree.AddAt(p, "controls", func(c *Controls) {
v.controls = c
c.SetPlayer(v, v)
})
})
}
// updatePosition shows the given current time in the controls.
func (v *Video) updatePosition(t time.Duration) {
if c := v.controls; c != nil {
c.SetTime(t)
}
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package video
import (
"errors"
"image"
"time"
)
// Frame is a decoded video frame.
type Frame struct {
// Image is the image of the frame.
Image *image.RGBA
// Time is the presentation time of the frame in the media, which
// starts at the time of the first frame (not always 0).
Time time.Duration
}
// decodeSink receives the decoded data; it returns false to stop decoding.
type decodeSink struct {
video func(f Frame) bool
audio func(samples [][2]float64) bool
}
const (
// sampleRate is the rate of the decoded audio samples.
sampleRate = 44100
// frameBufferSize is the number of decoded video frames buffered ahead
// of playback. Frames can be large (33 MB for 4K RGBA), so this is kept
// small; the audio buffer covers the interleaving of the streams.
frameBufferSize = 30
// sampleBufferSize is the number of audio samples buffered ahead of
// playback (12 seconds).
sampleBufferSize = 12 * sampleRate
)
// Decode starts decoding the video, and the audio if audio is true (and
// the media has audio), in a separate goroutine that sends the decoded
// data to the returned channels. Video frames are scaled to the given size,
// where 0 for a dimension means to keep the aspect ratio (both 0 = the
// inherent size). The audio samples are stereo at 44.1 kHz. The decoding
// stops at the end of the media, at an error, which is sent to the error
// channel, or when done is closed; all of the channels are closed then.
func (m *Media) Decode(width, height int, audio bool, done <-chan struct{}) (<-chan Frame, <-chan [2]float64, <-chan error, error) {
return m.DecodeFrom(0, width, height, audio, done)
}
// DecodeFrom is like [Media.Decode], starting at the given time of the
// media: the frames and audio before it are not sent.
func (m *Media) DecodeFrom(start time.Duration, width, height int, audio bool, done <-chan struct{}) (<-chan Frame, <-chan [2]float64, <-chan error, error) {
// Open the media again, for this decoding, from its start, unless the
// decoder that opened it is kept for it (see Media.probe).
var d *decoder
var err error
if start == 0 && audio && m.Source == nil {
d = m.takeProbe()
}
switch {
case d != nil:
case m.Source != nil:
d, err = openSourceDecoder(m.Source, start, audio)
default:
d, err = openDecoder(m.Path, m.Options, audio)
}
if err != nil {
return nil, nil, nil, err
}
if err := d.seek(start); err != nil {
d.free()
return nil, nil, nil, err
}
d.scaleWidth, d.scaleHeight = width, height
frames := make(chan Frame, frameBufferSize)
samples := make(chan [2]float64, sampleBufferSize)
errs := make(chan error, 1)
// Decode in a goroutine, which stops when done is closed.
go func() {
defer func() {
d.free()
close(frames)
close(samples)
close(errs)
}()
err := d.run(decodeSink{
video: func(f Frame) bool {
select {
case frames <- f:
return true
case <-done:
return false
}
},
audio: func(ss [][2]float64) bool {
for _, s := range ss {
select {
case samples <- s:
case <-done:
return false
}
}
return true
},
})
if err != nil {
errs <- err
}
}()
return frames, samples, errs, nil
}
// FirstFrame returns the first video frame of the media, scaled to the
// given size as for [Media.Decode], as to show before the media plays.
func (m *Media) FirstFrame(width, height int) (*image.RGBA, error) {
done := make(chan struct{})
defer close(done)
frames, _, errs, err := m.Decode(width, height, false, done)
if err != nil {
return nil, err
}
if f, ok := <-frames; ok {
return f.Image, nil
}
if err := <-errs; err != nil {
return nil, err
}
return nil, errors.New("video: the media has no video frames")
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package video
import (
"io"
"sync"
"time"
)
// Debug is whether to show the log messages of FFmpeg (warnings and errors
// about the media, as "Could not update timestamps for skipped samples"),
// which are not shown otherwise, as the errors are returned.
var Debug = false
// Media is a video file. On desktop platforms, it is decoded with FFmpeg
// via go-astiav: OpenMedia records the properties of the file, and each call
// to [Media.Decode] opens the file again, so that the media can be played
// any number of times. On the web, the browser plays it in a video element
// (see [Video]), so it is not decoded here, and its size is set once the
// browser has loaded it. With the novideo build tag, FFmpeg is not used,
// and OpenMedia returns an error (for apps that do not need video, built
// without the FFmpeg libraries).
type Media struct {
// Source is the source of the media, instead of its Path, if set
// (as the MediaSource of a web page).
Source Source
// Path is the path or URL of the media file (any URL that FFmpeg
// reads, as http and https).
Path string
// Options are the options of FFmpeg for opening the input, as
// user_agent and headers (as "Cookie: a=b\r\n") for http URLs.
Options map[string]string
// Width and Height are the inherent size of the video, in pixels.
Width, Height int
// FrameRate is the average number of video frames per second,
// or 0 if it is not known.
FrameRate float64
// Rotation is the rotation of the video for display, in degrees
// clockwise (0, 90, 180 or 270), from its metadata (as of the videos of
// phones). Its frames are turned by it, and Width and Height are of the
// turned frames.
Rotation int
// Duration is the duration of the media, or 0 if it is not known.
Duration time.Duration
// Metadata are the tags of the metadata of the media file, as
// creation_time, and those of phones, as com.apple.quicktime.creationdate
// and location (in ISO 6709, as +40.0257-105.2701/), with those of its
// video stream that the file does not have. It is not set on the web.
Metadata map[string]string
// HasAudio is whether the media has an audio stream.
HasAudio bool
// HasVideo is whether the media has a video stream: media with only
// audio (as an MP3 file or stream) has no size nor frames, and its
// playing is timed by its audio (see [Playback]).
HasVideo bool
// probe is the decoder that opened the media to read its properties,
// kept for its first decoding from its start (see takeProbe), so that
// it is not opened again (as a stream of a URL, which is read again
// from the network: the live stream of npr.org took 2.8s to start).
probe *decoder
probeMu sync.Mutex
}
// probeKeep is how long the decoder that opened a media is kept for its
// first decoding (see [Media.probe]); it is freed if none starts by then.
const probeKeep = 10 * time.Second
// keepProbe keeps the given decoder that opened the media, for its first
// decoding (see takeProbe), until [probeKeep] has passed.
func (m *Media) keepProbe(d *decoder) {
m.probeMu.Lock()
m.probe = d
m.probeMu.Unlock()
time.AfterFunc(probeKeep, func() {
if d := m.takeProbe(); d != nil {
d.free()
}
})
}
// Close frees the decoder kept from opening the media for its first
// decoding (see [Media.probe]), which is otherwise freed after a while,
// as for media opened only to read its properties or a frame of it, as
// for thumbnails of many videos. The media can still be decoded after.
func (m *Media) Close() {
if d := m.takeProbe(); d != nil {
d.free()
}
}
// takeProbe returns the decoder that opened the media, if it is still
// kept, which the caller then owns, or nil.
func (m *Media) takeProbe() *decoder {
m.probeMu.Lock()
defer m.probeMu.Unlock()
d := m.probe
m.probe = nil
return d
}
// Source is a source of the media of a [Media] other than a file or URL,
// as the MediaSource of a web page (Media Source Extensions), whose media
// is appended to it by the scripts of the page.
type Source interface {
// Streams returns new readers of the byte streams of the media (as one
// for its video and one for its audio, each a fragmented MP4), from the
// given time: they block until more of the media is available, return
// io.EOF at its end, and are closed when the decoding stops (which
// must return a blocked read).
Streams(start time.Duration) ([]io.ReadCloser, error)
// Duration returns the duration of the media, or 0 if it is not known.
Duration() time.Duration
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !js && !novideo
package video
import (
"encoding/binary"
"errors"
"fmt"
"image"
"io"
"math"
"sync"
"time"
"github.com/asticode/go-astiav"
)
// OpenMedia opens the media file at the given path or URL, with the given
// options of FFmpeg for the input (see [Media.Options]), which can be nil,
// and reads its properties.
func OpenMedia(fpath string, options map[string]string) (*Media, error) {
// Open the file and find its streams, to read their properties.
d, err := openDecoder(fpath, options, true)
if err != nil {
return nil, err
}
m := &Media{Path: fpath, Options: options}
d.setProperties(m)
m.keepProbe(d) // (for its first decoding, see Media.probe)
return m, nil
}
// OpenSource opens the media of the given [Source] (as the media of a
// MediaSource of a web page), and reads its properties, which waits for
// the start of its streams.
func OpenSource(src Source) (*Media, error) {
d, err := openSourceDecoder(src, 0, true)
if err != nil {
return nil, err
}
defer d.free()
m := &Media{Source: src}
d.setProperties(m)
if du := src.Duration(); du > 0 {
m.Duration = du
}
return m, nil
}
// setProperties sets the properties of the given media from the decoder.
func (d *decoder) setProperties(m *Media) {
m.HasAudio, m.HasVideo = d.audio != nil, d.video != nil
if d.video != nil { // (audio-only media has no size)
par := d.video.stream.CodecParameters()
m.Width, m.Height = par.Width(), par.Height()
if m.Rotation = d.rotation; m.Rotation == 90 || m.Rotation == 270 {
m.Width, m.Height = m.Height, m.Width // (its frames are turned)
}
if fr := d.video.stream.AvgFrameRate(); fr.Num() > 0 && fr.Den() > 0 {
m.FrameRate = fr.Float64()
}
}
if du := d.inputs[0].fc.Duration(); du > 0 {
m.Duration = time.Duration(du) * time.Second / time.Duration(astiav.TimeBase)
}
m.Metadata = map[string]string{}
addMetadata(m.Metadata, d.inputs[0].fc.Metadata())
if d.video != nil {
addMetadata(m.Metadata, d.video.stream.Metadata())
}
}
// addMetadata adds the entries of the given metadata to the given map,
// except for those that it has already.
func addMetadata(md map[string]string, dict *astiav.Dictionary) {
if dict == nil {
return
}
var e *astiav.DictionaryEntry
for {
e = dict.Get("", e, astiav.NewDictionaryFlags(astiav.DictionaryFlagIgnoreSuffix))
if e == nil {
return
}
if _, ok := md[e.Key()]; !ok {
md[e.Key()] = e.Value()
}
}
}
// decodeStream is an opened decoder for one stream of a media file.
type decodeStream struct {
stream *astiav.Stream
codec *astiav.CodecContext
// in is the input that the stream is in.
in *input
}
// input is an input of a decoder: a media file (or URL), or a stream of
// a [Source] (read through a custom IO context of FFmpeg).
type input struct {
fc *astiav.FormatContext
packet *astiav.Packet
frame *astiav.Frame
// io and reader are of a stream of a Source.
io *astiav.IOContext
reader io.ReadCloser
}
// free frees the input.
func (in *input) free() {
for _, f := range []*astiav.Frame{in.frame} {
if f != nil {
f.Free()
}
}
if in.packet != nil {
in.packet.Free()
}
in.fc.CloseInput()
in.fc.Free()
if in.io != nil {
in.io.Free()
}
if in.reader != nil {
in.reader.Close()
}
}
// decoder decodes the video and audio streams of a media file, or of the
// streams of a [Source] (each of which is an input).
type decoder struct {
inputs []*input
video, audio *decodeStream
// scaled is the decoded video frame converted to RGBA by scaler,
// at the size scaleWidth x scaleHeight (0 = inherent size).
scaled *astiav.Frame
scaler *astiav.SoftwareScaleContext
scaleWidth, scaleHeight int
// resampled is the decoded audio converted by resampler
// to interleaved float64 stereo samples at [sampleRate].
resampled *astiav.Frame
resampler *astiav.SoftwareResampleContext
// next is the time of the next video frame, for frames without
// a timestamp, and frameTime is the duration of a frame.
next, frameTime time.Duration
// start is the time to decode from (see [decoder.seek]): the frames
// and audio before it are dropped.
start time.Duration
// rotation is the rotation of the video for display (0, 90, 180 or 270
// degrees clockwise), from its display matrix (as of the videos of
// phones), by which its frames are turned.
rotation int
}
// setLogLevel sets the level of the log messages of FFmpeg, which are only
// shown for Debug.
func setLogLevel() {
if Debug {
astiav.SetLogLevel(astiav.LogLevelWarning)
} else {
astiav.SetLogLevel(astiav.LogLevelQuiet)
}
}
// openDecoder opens the media file at the given path with the given
// options, and opens a decoder for its first video stream, and for its
// first audio stream, if any and audio.
func openDecoder(fpath string, options map[string]string, audio bool) (*decoder, error) {
setLogLevel()
// Open the file and read its stream info.
in := &input{fc: astiav.AllocFormatContext()}
if in.fc == nil {
return nil, errors.New("video: allocating format context failed")
}
var dict *astiav.Dictionary
if len(options) > 0 {
dict = astiav.NewDictionary()
defer dict.Free()
for k, v := range options {
if err := dict.Set(k, v, 0); err != nil {
in.fc.Free()
return nil, fmt.Errorf("video: setting option %s: %w", k, err)
}
}
}
if err := in.fc.OpenInput(fpath, nil, dict); err != nil {
in.fc.Free()
return nil, fmt.Errorf("video: opening %q: %w", fpath, err)
}
d := &decoder{inputs: []*input{in}}
if err := d.openStreams(audio); err != nil {
d.free()
return nil, fmt.Errorf("video: %w in %q", err, fpath)
}
return d, nil
}
// openSourceDecoder opens the streams of the given [Source] from the given
// time, and opens a decoder for the first video stream in them, and for
// the first audio stream, if any and audio.
func openSourceDecoder(src Source, start time.Duration, audio bool) (*decoder, error) {
setLogLevel()
readers, err := src.Streams(start)
if err != nil {
return nil, err
}
d := &decoder{start: start}
for i, r := range readers {
in := &input{fc: astiav.AllocFormatContext(), reader: r}
if in.fc == nil {
r.Close()
d.free()
return nil, errors.New("video: allocating format context failed")
}
in.io, err = astiav.AllocIOContext(1<<16, false, r.Read, nil, nil)
if err != nil {
in.fc.Free()
r.Close()
d.free()
return nil, fmt.Errorf("video: allocating io context: %w", err)
}
in.fc.SetPb(in.io)
if err := in.fc.OpenInput("", nil, nil); err != nil {
in.io.Free()
in.fc.Free()
r.Close()
d.free()
return nil, fmt.Errorf("video: opening stream %d: %w", i, err)
}
d.inputs = append(d.inputs, in)
}
if err := d.openStreams(audio); err != nil {
d.free()
return nil, fmt.Errorf("video: %w in the streams", err)
}
return d, nil
}
// openStreams reads the stream info of the inputs, and opens a decoder for
// their first video stream, and for their first audio stream, if any and
// audio, with the packets and frames of the inputs.
func (d *decoder) openStreams(audio bool) error {
for _, in := range d.inputs {
if err := in.fc.FindStreamInfo(nil); err != nil {
return fmt.Errorf("finding stream info: %w", err)
}
in.packet = astiav.AllocPacket()
in.frame = astiav.AllocFrame()
for _, s := range in.fc.Streams() {
var target **decodeStream
switch s.CodecParameters().MediaType() {
case astiav.MediaTypeVideo:
target = &d.video
case astiav.MediaTypeAudio:
if audio {
target = &d.audio
}
}
if target == nil || *target != nil {
continue
}
ds, err := openDecodeStream(s)
if err != nil {
return err
}
ds.in = in
*target = ds
}
}
// Media is played with a video stream, or with only an audio stream
// (as of the audio elements of web pages).
switch {
case d.video == nil && d.audio == nil && audio:
return errors.New("no video or audio stream")
case d.video == nil && d.audio == nil:
return errors.New("no video stream")
}
d.frameTime = time.Second / 30
if d.video != nil {
if fr := d.video.stream.AvgFrameRate(); fr.Num() > 0 && fr.Den() > 0 {
d.frameTime = time.Duration(float64(time.Second) / fr.Float64())
}
if dm, ok := d.video.stream.CodecParameters().SideData().DisplayMatrix().Get(); ok {
d.rotation = ((int(math.Round(dm.Rotation()/90))%4 + 4) % 4) * 90
}
}
// Allocate the frames used for converting.
d.scaled = astiav.AllocFrame()
if d.audio != nil {
d.resampled = astiav.AllocFrame()
d.resampler = astiav.AllocSoftwareResampleContext()
}
return nil
}
// openDecodeStream opens a decoder for the given stream.
func openDecodeStream(s *astiav.Stream) (*decodeStream, error) {
par := s.CodecParameters()
codec := astiav.FindDecoder(par.CodecID())
if codec == nil {
return nil, fmt.Errorf("video: no decoder for codec %s", par.CodecID())
}
cc := astiav.AllocCodecContext(codec)
if cc == nil {
return nil, errors.New("video: allocating codec context failed")
}
if err := par.ToCodecContext(cc); err != nil {
cc.Free()
return nil, fmt.Errorf("video: setting codec parameters: %w", err)
}
if err := cc.Open(codec, nil); err != nil {
cc.Free()
return nil, fmt.Errorf("video: opening codec %s: %w", par.CodecID(), err)
}
return &decodeStream{stream: s, codec: cc}, nil
}
// free frees all of the resources of the decoder.
func (d *decoder) free() {
for _, f := range []*astiav.Frame{d.scaled, d.resampled} {
if f != nil {
f.Free()
}
}
if d.scaler != nil {
d.scaler.Free()
}
if d.resampler != nil {
d.resampler.Free()
}
for _, s := range []*decodeStream{d.video, d.audio} {
if s != nil {
s.codec.Free()
}
}
for _, in := range d.inputs {
in.free()
}
}
// run decodes the whole media, sending the results to the sink,
// until the end of the media, an error, or the sink returns false.
// The inputs (the streams of a Source) are decoded in parallel.
func (d *decoder) run(sink decodeSink) error {
if len(d.inputs) == 1 {
return d.runInput(d.inputs[0], sink)
}
var wg sync.WaitGroup
errs := make([]error, len(d.inputs))
stop := make(chan struct{})
var once sync.Once
for i, in := range d.inputs {
wg.Go(func() {
// (each stops the others when the sink asks to stop, or it fails)
s := decodeSink{
video: func(f Frame) bool {
select {
case <-stop:
return false
default:
}
ok := sink.video(f)
if !ok {
once.Do(func() { close(stop) })
}
return ok
},
audio: func(ss [][2]float64) bool {
select {
case <-stop:
return false
default:
}
ok := sink.audio(ss)
if !ok {
once.Do(func() { close(stop) })
}
return ok
},
}
if errs[i] = d.runInput(in, s); errs[i] != nil {
once.Do(func() { close(stop) })
}
})
}
wg.Wait()
return errors.Join(errs...)
}
// runInput decodes the given input, sending the results of its streams
// to the sink, until its end, an error, or the sink returns false.
func (d *decoder) runInput(in *input, sink decodeSink) error {
// Read packets and send them to the decoder of their stream. The end
// of an HTTP stream of an unknown length (as of a radio stream that
// ends, or a file sent without a length) is an I/O error of FFmpeg
// once it has been read.
read := false
for {
if err := in.fc.ReadFrame(in.packet); err != nil {
if errors.Is(err, astiav.ErrEof) || (read && errors.Is(err, astiav.ErrEio) && in.reader == nil) {
break
}
return fmt.Errorf("video: reading packet: %w", err)
}
read = true
var s *decodeStream
switch idx := in.packet.StreamIndex(); {
case d.video != nil && d.video.in == in && idx == d.video.stream.Index():
s = d.video
case d.audio != nil && d.audio.in == in && idx == d.audio.stream.Index():
s = d.audio
}
if s == nil {
in.packet.Unref()
continue
}
err := s.codec.SendPacket(in.packet)
in.packet.Unref()
if err != nil {
return fmt.Errorf("video: sending packet: %w", err)
}
if ok, err := d.receive(s, sink); !ok || err != nil {
return err
}
}
// Flush the frames remaining in the decoders.
for _, s := range []*decodeStream{d.video, d.audio} {
if s == nil || s.in != in {
continue
}
if err := s.codec.SendPacket(nil); err != nil {
return fmt.Errorf("video: flushing decoder: %w", err)
}
if ok, err := d.receive(s, sink); !ok || err != nil {
return err
}
}
return nil
}
// receive receives all of the frames available from the decoder of
// the given stream, and sends them to the sink. It returns false
// if the sink asked to stop.
func (d *decoder) receive(s *decodeStream, sink decodeSink) (bool, error) {
for {
if err := s.codec.ReceiveFrame(s.in.frame); err != nil {
if errors.Is(err, astiav.ErrEof) || errors.Is(err, astiav.ErrEagain) {
return true, nil
}
return false, fmt.Errorf("video: receiving frame: %w", err)
}
var ok bool
var err error
if s == d.video {
ok, err = d.sendVideo(sink)
} else {
ok, err = d.sendAudio(sink)
}
s.in.frame.Unref()
if !ok || err != nil {
return false, err
}
}
}
// sendVideo converts the decoded video frame to an RGBA image and sends it.
func (d *decoder) sendVideo(sink decodeSink) (bool, error) {
// The time of the frame, which is dropped if it is before the start.
f := d.video.in.frame
t := d.next
if pts := f.Pts(); pts != astiav.NoPtsValue {
t = streamTime(d.video.stream, pts)
}
d.next = t + d.frameTime
if t < d.start {
return true, nil
}
// (Re)create the scaler when the source format or size changes. The
// size to scale to is of the frame as it is shown (turned by its
// rotation), and so turned for scaling.
fw, fh := f.Width(), f.Height()
turned := d.rotation == 90 || d.rotation == 270
if turned {
fw, fh = fh, fw
}
w, h := d.scaleWidth, d.scaleHeight
switch {
case w <= 0 && h <= 0:
w, h = fw, fh
case w <= 0:
w = max(1, fw*h/fh)
case h <= 0:
h = max(1, fh*w/fw)
}
if turned {
w, h = h, w
}
if d.scaler == nil || d.scaler.SourceWidth() != f.Width() || d.scaler.SourceHeight() != f.Height() || d.scaler.SourcePixelFormat() != f.PixelFormat() {
if d.scaler != nil {
d.scaler.Free()
}
var err error
d.scaler, err = astiav.CreateSoftwareScaleContext(f.Width(), f.Height(), f.PixelFormat(), w, h, astiav.PixelFormatRgba, astiav.NewSoftwareScaleContextFlags(astiav.SoftwareScaleContextFlagBilinear))
if err != nil {
d.scaler = nil
return false, fmt.Errorf("video: creating scaler: %w", err)
}
d.scaled.Unref()
}
// Convert the frame and copy it into a new image, which the sink keeps.
if err := d.scaler.ScaleFrame(f, d.scaled); err != nil {
return false, fmt.Errorf("video: scaling frame: %w", err)
}
img := image.NewRGBA(image.Rect(0, 0, w, h))
if err := d.scaled.Data().ToImage(img); err != nil {
return false, fmt.Errorf("video: copying frame: %w", err)
}
return sink.video(Frame{Image: rotateImage(img, d.rotation), Time: t}), nil
}
// rotateImage returns the given image turned clockwise by the given
// rotation (0, 90, 180 or 270 degrees), which is the image itself for 0.
func rotateImage(img *image.RGBA, rotation int) *image.RGBA {
if rotation == 0 {
return img
}
sw, sh := img.Rect.Dx(), img.Rect.Dy()
dw, dh := sw, sh
if rotation != 180 {
dw, dh = sh, sw
}
dst := image.NewRGBA(image.Rect(0, 0, dw, dh))
for y := 0; y < dh; y++ {
for x := 0; x < dw; x++ {
// the pixel of the source that is at (x, y) once it is turned
var sx, sy int
switch rotation {
case 90:
sx, sy = y, sh-1-x
case 180:
sx, sy = sw-1-x, sh-1-y
case 270:
sx, sy = sw-1-y, x
}
si, di := img.PixOffset(sx, sy), dst.PixOffset(x, y)
copy(dst.Pix[di:di+4], img.Pix[si:si+4])
}
}
return dst
}
// streamTime returns the time of the given timestamp of the given stream.
func streamTime(s *astiav.Stream, ts int64) time.Duration {
tb := s.TimeBase()
return time.Duration(float64(ts) * float64(time.Second) * float64(tb.Num()) / float64(tb.Den()))
}
// seek seeks the media to the key frame at or before the given time,
// from which it is decoded, dropping the frames before the time.
func (d *decoder) seek(t time.Duration) error {
d.start = t
if t <= 0 || len(d.inputs) != 1 || d.inputs[0].reader != nil {
return nil // (a Source starts its streams at the time)
}
ts := int64(t) * int64(astiav.TimeBase) / int64(time.Second)
if err := d.inputs[0].fc.SeekFrame(-1, ts, astiav.NewSeekFlags(astiav.SeekFlagBackward)); err != nil {
return fmt.Errorf("video: seeking to %v: %w", t, err)
}
return nil
}
// sendAudio converts the decoded audio frame to stereo samples and sends them.
func (d *decoder) sendAudio(sink decodeSink) (bool, error) {
// The audio before the start is dropped.
af := d.audio.in.frame
if pts := af.Pts(); pts != astiav.NoPtsValue && streamTime(d.audio.stream, pts) < d.start {
return true, nil
}
// Resample into a new buffer of interleaved float64 stereo samples.
r := d.resampled
r.Unref()
r.SetChannelLayout(astiav.ChannelLayoutStereo)
r.SetSampleFormat(astiav.SampleFormatDbl)
r.SetSampleRate(sampleRate)
err := d.resampler.ConvertFrame(af, r)
if errors.Is(err, astiav.ErrInputChanged) {
// the format of the audio frames changed (as in the AVI files of old
// cameras), for which the resampler, which is configured from the
// first frame it converts, is made again, for the new format
d.resampler.Free()
d.resampler = astiav.AllocSoftwareResampleContext()
r.Unref()
r.SetChannelLayout(astiav.ChannelLayoutStereo)
r.SetSampleFormat(astiav.SampleFormatDbl)
r.SetSampleRate(sampleRate)
err = d.resampler.ConvertFrame(af, r)
}
if err != nil {
return false, fmt.Errorf("video: resampling audio: %w", err)
}
n := r.NbSamples()
if n == 0 {
return true, nil
}
b, err := r.Data().Bytes(1)
if err != nil {
return false, fmt.Errorf("video: copying audio: %w", err)
}
// Turn the raw little-endian bytes into samples.
samples := make([][2]float64, min(n, len(b)/16))
for i := range samples {
samples[i][0] = math.Float64frombits(binary.LittleEndian.Uint64(b[16*i:]))
samples[i][1] = math.Float64frombits(binary.LittleEndian.Uint64(b[16*i+8:]))
}
return sink.audio(samples), nil
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package video
import (
"sync"
"time"
"cogentcore.org/core/base/errors"
)
// Playback plays a [Media], independent of any widget: it calls OnFrame
// with each video frame at its time, and plays the audio on the speaker.
// A [Video] shows a playback; other widgets (as an image of a web page)
// can show one too. Media with only audio (as an MP3 file or stream) is
// timed by its audio played (see [Playback.OnTime]), also when there is
// no speaker, when it is played silently at its rate.
type Playback struct {
// Media is the media that is played.
Media *Media
// Width and Height are the size to which the frames are scaled,
// where 0 for a dimension keeps the aspect ratio (both 0 = the inherent
// size of the video).
Width, Height int
// Muted is whether the audio is not heard (see [Playback.SetMuted]).
Muted bool
// Volume is the volume of the audio, from 0 to 1, where the zero value
// is full volume (see [Playback.SetVolume]).
Volume float32
// Loop is whether to play the media again from the start at its end.
Loop bool
// OnFrame is called with each video frame at the time to show it,
// in the goroutine of the playback.
OnFrame func(f Frame)
// OnTime is called, if set, with the current time of media that has
// only audio (no frames) as it plays, ten times a second, in the
// goroutine of the playback.
OnTime func(t time.Duration)
// OnEnd is called, if set, at the end of the media (unless Loop),
// in the goroutine of the playback.
OnEnd func()
// OnError is called, if set, with an error decoding the media,
// which stops the playing; it is logged otherwise.
OnError func(err error)
mu sync.Mutex
// done is closed to stop the current playing.
done chan struct{}
// paused is whether the playing is paused, since pausedAt,
// and resume is closed when it is resumed.
paused bool
pausedAt time.Time
resume chan struct{}
// pauseShift is the time paused that run has not added to the start
// of the playing yet.
pauseShift time.Duration
// audio is the audio being played, if any.
audio *audio
// position is the time in the media of the frame shown last.
position time.Duration
// ended is whether the current playing has ended (not for Loop).
ended bool
}
// Play starts playing the media from the start, stopping any playing
// before. The media is decoded in the background, so this returns after
// opening it.
func (p *Playback) Play() error {
return p.PlayFrom(0)
}
// PlayFrom starts playing the media from the given time, stopping any
// playing before, as for [Playback.Play].
func (p *Playback) PlayFrom(t time.Duration) error {
return p.playFrom(t, false)
}
// playFrom plays the media from the given time, paused if paused.
func (p *Playback) playFrom(t time.Duration, paused bool) error {
if p.Media == nil {
return errors.New("video: no media to play")
}
p.Stop()
p.mu.Lock()
done := make(chan struct{})
p.done, p.paused, p.position = done, paused, t
if paused {
p.pausedAt, p.resume = time.Now(), make(chan struct{})
}
p.mu.Unlock()
frames, _, errs, a, err := p.start(t, done)
if err != nil {
p.Stop() // (not playing)
return err
}
if p.audioOnly() {
go p.runAudio(done, t, a, errs)
} else {
go p.run(done, frames, errs)
}
return nil
}
// audioOnly returns whether the media has only audio, whose playing is
// timed by its audio (see [Playback.runAudio]).
func (p *Playback) audioOnly() bool {
return p.Media.HasAudio && !p.Media.HasVideo
}
// Seek plays the media from the given time (within its duration), keeping
// it paused if it is paused, which then shows the frame at that time.
func (p *Playback) Seek(t time.Duration) error {
if d := p.Media.Duration; d > 0 && t > d {
t = d
}
return p.playFrom(max(t, 0), p.IsPaused())
}
// StepFrame shows the next frame of the media (or the one before it, for a
// negative n), pausing it: the first frame after a time half a frame after
// that of the frame shown (or one and a half before it), as a seek does.
func (p *Playback) StepFrame(n int) error {
ft := p.frameTime()
t := p.Position() + ft/2
if n < 0 {
t = p.Position() - 3*ft/2
}
if d := p.Media.Duration; d > 0 && t > d {
return nil // (the last frame)
}
return p.playFrom(max(t, 0), true)
}
// Position returns the time in the media of the frame shown last (or the
// time that it is played from, before its first frame is shown).
func (p *Playback) Position() time.Duration {
p.mu.Lock()
defer p.mu.Unlock()
return p.position
}
// SetMuted sets whether the audio is not heard, while it plays too.
func (p *Playback) SetMuted(muted bool) {
p.mu.Lock()
defer p.mu.Unlock()
p.Muted = muted
if p.audio != nil {
p.audio.setVolume(p.Volume, p.Muted)
}
}
// SetVolume sets the volume of the audio, from 0 to 1, while it plays too.
func (p *Playback) SetVolume(volume float32) {
p.mu.Lock()
defer p.mu.Unlock()
p.Volume = min(max(volume, 0), 1)
if p.Volume == 0 { // (0 is full volume as the zero value)
p.Volume = 1e-6
}
if p.audio != nil {
p.audio.setVolume(p.Volume, p.Muted)
}
}
// Audio returns the volume of the audio, from 0 to 1, and whether it is
// muted (see [Playback.SetVolume] and [Playback.SetMuted]).
func (p *Playback) Audio() (volume float32, muted bool) {
p.mu.Lock()
defer p.mu.Unlock()
if p.Volume == 0 {
return 1, p.Muted
}
return p.Volume, p.Muted
}
// start starts decoding the media from the given time, and playing its
// audio, if any (also when it is muted, so that it can be heard later),
// which it returns. Media with only audio is played without a speaker too
// (silently), as its audio times it.
func (p *Playback) start(t time.Duration, done chan struct{}) (<-chan Frame, <-chan [2]float64, <-chan error, *audio, error) {
hasAudio := p.Media.HasAudio && (audioAvailable() || p.audioOnly())
frames, samples, errs, err := p.Media.DecodeFrom(t, p.Width, p.Height, hasAudio, done)
if err != nil || !hasAudio {
return frames, samples, errs, nil, err
}
p.mu.Lock()
defer p.mu.Unlock()
if p.audio != nil { // (of the playing before, as in a loop)
p.audio.stop()
}
p.audio = playAudio(samples, p.paused, p.Volume, p.Muted) // (with the lock, as SetMuted)
return frames, samples, errs, p.audio, nil
}
// run shows the frames at their times, until the end of the media
// (playing it again for Loop), or until done is closed.
func (p *Playback) run(done chan struct{}, frames <-chan Frame, errs <-chan error) {
start := time.Now()
var first, base, last time.Duration // base: the start of this loop
firstFrame := true
for {
// Get the next frame, at the end of the media playing it again.
var f Frame
var ok bool
select {
case f, ok = <-frames:
case <-done:
return
}
if !ok {
if err := <-errs; err != nil {
p.error(err)
return
}
if !p.Loop {
p.mu.Lock()
if p.done == done {
p.ended = true
}
p.mu.Unlock()
if p.OnEnd != nil {
p.OnEnd()
}
return
}
var err error
if frames, _, errs, _, err = p.start(0, done); err != nil {
p.error(err)
return
}
base, firstFrame = last, true
continue
}
// The first frame (as of a seek) is shown at once, also while
// paused, and the others at their times after it.
showNow := firstFrame && base == 0 // (not again in a loop)
if firstFrame {
first, firstFrame = f.Time, false
if showNow { // the time of the playing starts now
start = p.restart()
}
}
at := base + f.Time - first
last = at + p.frameTime()
// Wait for its time, waiting longer while paused.
for !showNow {
// (the start moves later by the time paused)
start = p.startAfterPauses(start)
p.mu.Lock()
paused, resume := p.paused, p.resume
p.mu.Unlock()
if paused {
select {
case <-resume:
case <-done:
return
}
continue
}
wait := time.Until(start.Add(at))
if wait <= 0 {
break
}
select {
case <-time.After(wait):
case <-done:
return
}
}
select {
case <-done:
return
default:
}
p.mu.Lock()
p.position = f.Time
p.mu.Unlock()
p.OnFrame(f)
}
}
// runAudio plays media that has only audio from the given time, as the
// given audio plays it, until the end of the media (playing it again for
// Loop), or until done is closed. Its position is the time of the audio
// played, which is given to OnTime ten times a second.
func (p *Playback) runAudio(done chan struct{}, from time.Duration, a *audio, errs <-chan error) {
tick := time.NewTicker(100 * time.Millisecond)
defer tick.Stop()
for {
select {
case <-done:
return
case <-tick.C:
p.audioTime(done, from+a.time())
continue
case <-a.ended:
}
// At the end of the media, it is played again for Loop.
p.audioTime(done, from+a.time())
if err := <-errs; err != nil {
p.error(err)
return
}
if !p.Loop {
p.mu.Lock()
current := p.done == done
if current {
p.ended = true
}
p.mu.Unlock()
if current && p.OnEnd != nil {
p.OnEnd()
}
return
}
var err error
if _, _, errs, a, err = p.start(0, done); err != nil {
p.error(err)
return
}
from = 0
}
}
// audioTime sets the position of media that has only audio to the given
// time, if the given playing is the current one, and calls OnTime with it.
func (p *Playback) audioTime(done chan struct{}, t time.Duration) {
p.mu.Lock()
current := p.done == done
if current {
p.position = t
}
p.mu.Unlock()
if current && p.OnTime != nil {
p.OnTime(t)
}
}
// frameTime returns the duration of a frame of the media.
func (p *Playback) frameTime() time.Duration {
if fr := p.Media.FrameRate; fr > 0 {
return time.Duration(float64(time.Second) / fr)
}
return time.Second / 30
}
// restart returns the time now as the start of the playing, from which
// the time paused is counted again.
func (p *Playback) restart() time.Time {
p.mu.Lock()
defer p.mu.Unlock()
now := time.Now()
p.pauseShift = 0
if p.paused {
p.pausedAt = now
}
return now
}
// startAfterPauses returns the given start of the playing moved later
// by the time paused since the last call.
func (p *Playback) startAfterPauses(start time.Time) time.Time {
p.mu.Lock()
defer p.mu.Unlock()
start = start.Add(p.pauseShift)
p.pauseShift = 0
return start
}
// error handles an error decoding the media.
func (p *Playback) error(err error) {
if p.OnError != nil {
p.OnError(err)
return
}
errors.Log(err)
}
// Pause pauses the playing, if it is playing.
func (p *Playback) Pause() {
p.mu.Lock()
defer p.mu.Unlock()
if p.done == nil || p.paused {
return
}
p.paused, p.pausedAt = true, time.Now()
p.resume = make(chan struct{})
p.setAudioPaused(true)
}
// Resume resumes the playing, if it is paused.
func (p *Playback) Resume() {
p.mu.Lock()
defer p.mu.Unlock()
if !p.paused {
return
}
if p.Media != nil && p.Media.Duration <= 0 && p.Media.Source == nil && time.Since(p.pausedAt) > liveStale {
// a live stream (of no duration, as a radio stream) that was paused
// long plays again from its live point, as what was received before
// the pause is stale (and its connection may have ended), in the
// background, as it is opened again
go func() {
if err := p.PlayFrom(0); err != nil && p.OnError != nil {
p.OnError(err)
}
}()
return
}
p.paused = false
p.pauseShift += time.Since(p.pausedAt)
close(p.resume)
p.setAudioPaused(false)
}
// liveStale is how long a live stream is paused after which it plays again
// from its live point when it is resumed (see [Playback.Resume]).
var liveStale = 10 * time.Second
// setAudioPaused pauses or resumes the audio, with the lock held.
func (p *Playback) setAudioPaused(paused bool) {
if p.audio != nil {
p.audio.setPaused(paused)
}
}
// IsPlaying returns whether the media is playing, and not paused,
// nor ended.
func (p *Playback) IsPlaying() bool {
p.mu.Lock()
defer p.mu.Unlock()
return p.done != nil && !p.paused && !p.ended
}
// IsEnded returns whether the playing has ended, at the end of the media
// (not with Loop).
func (p *Playback) IsEnded() bool {
p.mu.Lock()
defer p.mu.Unlock()
return p.ended
}
// IsPaused returns whether the playing is paused.
func (p *Playback) IsPaused() bool {
p.mu.Lock()
defer p.mu.Unlock()
return p.paused
}
// Stop stops the playing, if any; Play plays the media from the start.
func (p *Playback) Stop() {
p.mu.Lock()
defer p.mu.Unlock()
if p.done != nil {
close(p.done)
p.done = nil
}
if p.paused {
close(p.resume)
}
p.paused, p.pauseShift, p.ended = false, 0, false
if p.audio != nil {
p.audio.stop()
}
p.audio = nil
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !js
package video
import (
"image"
"image/color"
"image/draw"
"cogentcore.org/core/colors"
"cogentcore.org/core/paint/renderers/rasterx"
"cogentcore.org/core/system/composer"
)
// videoSource implements [composer.Source] for core direct rendering:
// it draws the frame in the box of the video, fitted to it with black
// around it, as in players, and the region of the controls of the scene
// over it, as the region of the video in the scene is transparent
// (see [Video.Render]).
type videoSource struct {
// box is the visible part of the content of the video, in the
// coordinates of the window, which is filled with black.
box image.Rectangle
// destBBox and srcBBox are the regions of the window and the frame
// in which the visible part of the frame is drawn.
destBBox, srcBBox image.Rectangle
rotation float32
unchanged bool
frame *image.RGBA
// scene is the image of the scene, and controls is the region of the
// controls in it, which is drawn at controlsPos in the window.
scene image.Image
controls image.Rectangle
controlsPos image.Point
}
func (vs *videoSource) Draw(c composer.Composer) {
cd := c.(*composer.ComposerDrawer)
cd.Drawer.Copy(vs.box.Min, colors.Uniform(color.Black), vs.box, draw.Src, composer.Unchanged) // (a fill of the box, at its place)
if !vs.destBBox.Empty() {
cd.Drawer.Scale(vs.destBBox, vs.frame, vs.srcBBox, vs.rotation, draw.Src, vs.unchanged)
}
if vs.scene != nil && !vs.controls.Empty() {
// (the image of the scene is already on the GPU, drawn before)
cd.Drawer.Copy(vs.controlsPos, vs.scene, vs.controls, draw.Over, composer.Unchanged)
}
}
// RenderSource returns the [composer.Source] for direct rendering.
func (v *Video) RenderSource(op draw.Op) composer.Source {
frame, unchanged := v.CurrentFrame()
if frame == nil {
return nil
}
off := v.Scene.SceneGeom.Pos
visible := v.Geom.ContentBBox
if visible.Empty() {
return nil
}
vs := &videoSource{box: visible.Add(off), rotation: v.Rotation, unchanged: unchanged, frame: frame}
// The frame is fitted in the content of the video, keeping its
// aspect (turned for a rotation of 90 degrees).
pos := v.Geom.Pos.Content.ToPoint()
content := image.Rectangle{Min: pos, Max: pos.Add(v.Geom.Size.Actual.Content.ToPoint())}
fsz := frame.Bounds().Size()
if r := int(v.Rotation) % 180; r == 90 || r == -90 {
fsz.X, fsz.Y = fsz.Y, fsz.X
}
fit := fitRect(content, fsz)
dest := fit.Intersect(visible)
if v.Rotation == 0 && dest != fit && !dest.Empty() {
// the part of the frame of the visible part of its region
sx := float64(fsz.X) / float64(fit.Dx())
sy := float64(fsz.Y) / float64(fit.Dy())
vs.srcBBox = image.Rect(int(float64(dest.Min.X-fit.Min.X)*sx), int(float64(dest.Min.Y-fit.Min.Y)*sy),
int(float64(dest.Max.X-fit.Min.X)*sx), int(float64(dest.Max.Y-fit.Min.Y)*sy))
vs.destBBox = dest.Add(off)
} else if dest == fit {
vs.srcBBox, vs.destBBox = frame.Bounds(), fit.Add(off)
}
// The controls of the scene, over the frame.
if c := v.controls; c != nil && c.IsVisible() {
if rd, ok := v.Scene.Renderer.(*rasterx.Renderer); ok {
vs.scene = rd.Image()
vs.controls = c.Geom.TotalBBox.Intersect(visible)
vs.controlsPos = vs.controls.Min.Add(off)
}
}
return vs
}
// fitRect returns the rectangle of the given size fitted in the given
// rectangle, keeping its aspect, centered in it.
func fitRect(r image.Rectangle, size image.Point) image.Rectangle {
if size.X <= 0 || size.Y <= 0 || r.Empty() {
return image.Rectangle{}
}
w, h := r.Dx(), r.Dx()*size.Y/size.X
if h > r.Dy() {
w, h = r.Dy()*size.X/size.Y, r.Dy()
}
min := r.Min.Add(image.Pt((r.Dx()-w)/2, (r.Dy()-h)/2))
return image.Rectangle{Min: min, Max: min.Add(image.Pt(w, h))}
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package video implements a video player widget in Cogent Core.
package video
//go:generate core generate
import (
"fmt"
"image"
"image/color"
"sync"
"time"
"cogentcore.org/core/colors"
"cogentcore.org/core/core"
"cogentcore.org/core/styles"
)
// Video is a video player widget, with the standard playback controls over
// the bottom of the video if [Video.Controls] is set.
// On desktop platforms, the playing itself is a [Playback], which other
// widgets can show too, and the controls are Cogent Core widgets
// (see controls_notjs.go); on the web, the video is a video element of the
// browser, placed at the widget, with the controls of the browser.
type Video struct { //types:add
core.Frame
// Media is the video media.
Media *Media
// degrees of rotation to apply to the video images
// 90 = left 90, -90 = right 90
Rotation float32
// Muted is whether the audio is not heard (see [Video.SetMuted]).
Muted bool `set:"-"`
// Loop is whether to play the video again from the start at its end.
Loop bool
// Controls is whether to show the standard playback controls over the
// bottom of the video when the mouse is over it, or it is paused:
// play and pause, back and forward 10 seconds, the position (which can
// be dragged to seek), the volume, and the time.
Controls bool
// Poster is the URL of an image to show before the video plays,
// on the web (where the video is a video element of the browser).
Poster string
// playback is the current playing, if any.
playback *Playback
// playSize is the size given to Play, for playing again.
playSize [2]float32
// volume is the volume of the audio, from 0 to 1 (0 is full volume,
// as the zero value; see [Video.SetVolume]).
volume float32
// controls are the controls, if shown (on desktop platforms).
controls *Controls
// mu protects frame and changed, which are set by the playback.
mu sync.Mutex
// frame is the last frame of the playback, to render.
frame *image.RGBA
// changed is whether frame has changed since it was last rendered.
changed bool
}
func (v *Video) Init() {
v.Frame.Init()
v.Styler(func(s *styles.Style) {
// the black of players around the video (as in its letterbox),
// and the containing block of the controls
s.Background = colors.Uniform(color.Black)
s.Position = styles.PositionRelative
s.Padding.Zero()
s.Gap.Zero()
s.Direction = styles.Column
})
v.initControls()
}
func (v *Video) OnAdd() {
v.Frame.OnAdd()
v.Scene.AddDirectRender(v)
}
func (v *Video) Destroy() {
v.Stop()
v.release()
v.Scene.DeleteDirectRender(v)
v.Frame.Destroy()
}
// Open opens the video specified by the given filepath.
func (v *Video) Open(fpath string) error {
media, err := OpenMedia(fpath, nil)
if err != nil {
return err
}
v.Media = media
return nil
}
// TogglePlay plays the video if it is paused, has ended, or has not
// played yet, and pauses it if it is playing.
func (v *Video) TogglePlay() {
switch {
case v.IsPlaying():
v.Pause()
case v.isPaused():
v.Resume()
default:
v.Play(v.playSize[0], v.playSize[1])
}
}
// IsMuted returns whether the audio is not heard.
func (v *Video) IsMuted() bool {
return v.Muted
}
// SkipBy seeks the video by the given time from its position (back for
// a negative time), as the -10 and +10 controls do.
func (v *Video) SkipBy(d time.Duration) {
v.Seek(v.CurrentTime() + d)
}
// formatTime returns the given time as the controls of players show it:
// m:ss, or h:mm:ss for an hour or more.
func formatTime(t time.Duration) string {
s := int(max(t, 0).Seconds())
if s >= 3600 {
return fmt.Sprintf("%d:%02d:%02d", s/3600, s/60%60, s%60)
}
return fmt.Sprintf("%d:%02d", s/60, s%60)
}
// Copyright (c) 2026, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !js
package video
import (
"image"
"time"
"cogentcore.org/core/base/errors"
)
// On desktop platforms, a [Video] shows the frames of a [Playback], which
// its render source draws with the GPU in its box (see render_notjs.go),
// where its region of the scene is left transparent (see [Video.Render]),
// and the scene of its controls is drawn over it again.
// CurrentFrame returns the current frame (for rendering),
// and whether it is unchanged since it was last returned.
func (v *Video) CurrentFrame() (*image.RGBA, bool) {
if !v.IsVisible() {
return nil, true
}
v.mu.Lock()
defer v.mu.Unlock()
unchanged := !v.changed
v.changed = false
return v.frame, unchanged
}
// hasFrame returns whether the video has a frame to show.
func (v *Video) hasFrame() bool {
v.mu.Lock()
defer v.mu.Unlock()
return v.frame != nil
}
// Render renders the box of the video, whose content is left transparent
// once it has a frame, which the render source draws there, under the
// controls, which are drawn again over it.
func (v *Video) Render() {
v.Frame.Render()
if v.hasFrame() {
v.Scene.Painter.BlitBox(v.Geom.Pos.Content, v.Geom.Size.Actual.Content, nil)
}
}
// Play starts playing the video from the start, decoding its frames at the
// given size. Values of 0 indicate to use the inherent size of the video for
// that dimension (keeping its aspect ratio if only one is 0); with both 0,
// it is decoded at the size that fits in the box of the widget, if it is
// laid out, up to the inherent size.
func (v *Video) Play(width, height float32) error {
if v.Media == nil {
return errors.New("video: no media to play")
}
v.Stop()
v.playSize = [2]float32{width, height}
w, h := int(width), int(height)
if w == 0 && h == 0 {
w = v.fitWidth()
}
v.playback = &Playback{Media: v.Media, Width: w, Height: h, Muted: v.Muted, Loop: v.Loop, Volume: v.volume,
OnFrame: v.showFrame,
OnEnd: func() {
if v.AsyncLockIfShown() {
v.updateControls()
v.AsyncUnlock()
}
}}
err := v.playback.Play()
v.updateControls()
return err
}
// fitWidth returns the width at which the frames of the video fit in the
// content of the widget, keeping their aspect, up to the width of the
// video, or 0 (the width of the video) before it is laid out.
func (v *Video) fitWidth() int {
box := v.Geom.Size.Actual.Content
mw, mh := float32(v.Media.Width), float32(v.Media.Height)
if box.X <= 0 || box.Y <= 0 || mw <= 0 || mh <= 0 {
return 0
}
w := min(box.X, box.Y*mw/mh, mw)
return max(int(w), 1)
}
// showFrame shows the given frame (in the goroutine of the playback).
func (v *Video) showFrame(f Frame) {
v.mu.Lock()
v.frame, v.changed = f.Image, true
v.mu.Unlock()
if v.AsyncLockIfShown() {
v.NeedsRender()
v.updatePosition(f.Time)
v.AsyncUnlock()
}
}
// Pause pauses the playing, if it is playing.
func (v *Video) Pause() {
if v.playback != nil {
v.playback.Pause()
v.updateControls()
}
}
// Resume resumes the playing, if it is paused.
func (v *Video) Resume() {
if v.playback != nil {
v.playback.Resume()
v.updateControls()
}
}
// Stop stops the playing, if any.
func (v *Video) Stop() {
if v.playback != nil {
v.playback.Stop()
v.updateControls()
}
}
// IsPlaying returns whether the video is playing, and not paused nor ended.
func (v *Video) IsPlaying() bool {
return v.playback != nil && v.playback.IsPlaying()
}
// isPaused returns whether the video is paused.
func (v *Video) isPaused() bool {
return v.playback != nil && v.playback.IsPaused()
}
// Seek plays the video from the given time, staying paused if it is,
// which shows the frame at the time. It plays the video if it has not
// played yet, or has ended.
func (v *Video) Seek(t time.Duration) {
if v.playback == nil || v.playback.IsEnded() || (!v.IsPlaying() && !v.isPaused()) {
if errors.Log(v.Play(v.playSize[0], v.playSize[1])) != nil {
return
}
}
errors.Log(v.playback.Seek(t))
v.updateControls()
}
// CurrentTime returns the time in the video of the frame shown last.
func (v *Video) CurrentTime() time.Duration {
if v.playback == nil {
return 0
}
return v.playback.Position()
}
// Duration returns the duration of the video, or 0 if it is not known.
func (v *Video) Duration() time.Duration {
if v.Media == nil {
return 0
}
return v.Media.Duration
}
// SetMuted sets whether the audio is not heard, while it plays too.
func (v *Video) SetMuted(muted bool) {
v.Muted = muted
if v.playback != nil {
v.playback.SetMuted(muted)
}
v.updateControls()
}
// Volume returns the volume of the audio, from 0 to 1.
func (v *Video) Volume() float32 {
if v.volume == 0 {
return 1
}
return v.volume
}
// SetVolume sets the volume of the audio, from 0 to 1, while it plays too.
func (v *Video) SetVolume(volume float32) {
v.volume = max(min(volume, 1), 1e-6)
if v.playback != nil {
v.playback.SetVolume(volume)
}
v.updateControls()
}
// release releases the resources of the video (none on desktop).
func (v *Video) release() {}
// updateControls updates the controls for the state of the video.
func (v *Video) updateControls() {
if c := v.controls; c != nil {
c.Refresh()
}
}
// StepFrame pauses the video and shows its next frame, or the one before
// it for a negative n.
func (v *Video) StepFrame(n int) {
if v.playback == nil || v.playback.IsEnded() || (!v.IsPlaying() && !v.isPaused()) {
if errors.Log(v.Play(v.playSize[0], v.playSize[1])) != nil {
return
}
}
errors.Log(v.playback.StepFrame(n))
v.updateControls()
}
// Copyright (c) 2019, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package xyz
import (
"cogentcore.org/core/math32"
)
// BBox contains bounding box and other gross solid properties
type BBox struct {
// bounding box in local coords
BBox math32.Box3
// bounding sphere in local coords
BSphere math32.Sphere
// area
Area float32
// volume
Volume float32
}
// SetBounds sets BBox from min, max and updates other factors based on that
func (bb *BBox) SetBounds(min, max math32.Vector3) {
bb.BBox.Set(&min, &max)
bb.UpdateFromBBox()
}
// UpdateFromBBox updates other values from BBox
func (bb *BBox) UpdateFromBBox() {
bb.BSphere.SetFromBox(bb.BBox)
sz := bb.BBox.Size()
bb.Area = 2*sz.X + 2*sz.Y + 2*sz.Z
bb.Volume = sz.X * sz.Y * sz.Z
}
// Copyright (c) 2019, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package xyz
import (
"image"
"cogentcore.org/core/math32"
)
// Camera defines the properties of the camera
type Camera struct {
// Pose is the overall orientation and direction of the camera,
// relative to pointing at negative Z axis with up (positive Y) direction.
Pose Pose
// Target location for the camera to point at, which defaults to the origin.
// This moves with panning movements, and is reset by a call to LookAt method
Target math32.Vector3
// UpDir is the upward direction for camera, which defaults to positive Y axis,
// and is reset by LookAt method.
UpDir math32.Vector3
// Ortho switches to using Orthographic instead of default Perspective
// camera. For Ortho, the view includes the volume specified by the
// Near - Far distance (i.e., you probably want to decrease Far).
Ortho bool
// FOV is field of view in degrees.
FOV float32
// Aspect is the aspect ratio (width/height).
Aspect float32 `set:"-"`
// Near plane z coordinate.
Near float32
// Far plane z coordinate.
Far float32
// ViewMatrix is the inverse of the Pose.Matrix.
ViewMatrix math32.Matrix4 `display:"-"`
// ProjectionMatrix defines the camera perspective / ortho transform.
ProjectionMatrix math32.Matrix4 `display:"-"`
// InvProjectionMatrix is the inverse of the projection matrix.
InvProjectionMatrix math32.Matrix4 `display:"-"`
// Frustum of projection: viewable space defined by 6 planes of a pyrammidal shape.
Frustum *math32.Frustum `display:"-"`
}
func (cm *Camera) Defaults() {
cm.FOV = 30
cm.Aspect = 1.5
cm.Near = .01
cm.Far = 1000
cm.DefaultPose()
}
// DefaultPose resets the camera pose to default location and orientation, looking
// at the origin from 0,0,10, with up Y axis
func (cm *Camera) DefaultPose() {
cm.Pose.Defaults()
cm.Pose.Pos.Set(0, 0, 10)
cm.LookAtOrigin()
}
// GenGoSet returns code to set values at given path (var.member etc)
func (cm *Camera) GenGoSet(path string) string {
return cm.Pose.GenGoSet(path+".Pose") + "; " + cm.Target.GenGoSet(path+".Target") + "; " + cm.UpDir.GenGoSet(path+".UpDir")
}
// SetAspect sets the aspect ratio from the given frame size.
func (cm *Camera) SetAspect(size image.Point) {
cm.Aspect = float32(size.X) / float32(size.Y)
}
// UpdateMatrix updates the view and projection matricies
func (cm *Camera) UpdateMatrix() {
cm.Pose.UpdateMatrix()
cm.ViewMatrix.SetInverse(&cm.Pose.Matrix)
if cm.Ortho {
height := 2 * cm.Far * math32.Tan(math32.DegToRad(cm.FOV*0.5))
width := cm.Aspect * height
cm.ProjectionMatrix.SetOrthographic(width, height, cm.Near, cm.Far)
} else {
cm.ProjectionMatrix.SetPerspective(cm.FOV, cm.Aspect, cm.Near, cm.Far) // use for everything
}
cm.InvProjectionMatrix.SetInverse(&cm.ProjectionMatrix)
var proj math32.Matrix4
proj.MulMatrices(&cm.ProjectionMatrix, &cm.ViewMatrix)
cm.Frustum = math32.NewFrustumFromMatrix(&proj)
}
// LookAt points the camera at given target location, using given up direction,
// and sets the Target, UpDir fields for future camera movements.
func (cm *Camera) LookAt(target, upDir math32.Vector3) {
cm.Target = target
if upDir == (math32.Vector3{}) {
upDir = math32.Vec3(0, 1, 0)
}
cm.UpDir = upDir
cm.Pose.LookAt(target, upDir)
cm.UpdateMatrix()
}
// LookAtOrigin points the camera at origin with Y axis pointing Up (i.e., standard)
func (cm *Camera) LookAtOrigin() {
cm.LookAt(math32.Vector3{}, math32.Vec3(0, 1, 0))
}
// LookAtTarget points the camera at current target using current up direction
func (cm *Camera) LookAtTarget() {
cm.LookAt(cm.Target, cm.UpDir)
}
// ViewVector is the vector between the camera position and target
func (cm *Camera) ViewVector() math32.Vector3 {
return cm.Pose.Pos.Sub(cm.Target)
}
// DistanceTo is the distance from camera to given point
func (cm *Camera) DistanceTo(pt math32.Vector3) float32 {
dv := cm.Pose.Pos.Sub(pt)
return dv.Length()
}
// ViewMainAxis returns the dimension along which the view vector is largest
// along with the sign of that axis (+1 for positive, -1 for negative).
// this is useful for determining how manipulations should function, for example.
func (cm *Camera) ViewMainAxis() (dim math32.Dims, sign float32) {
vv := cm.ViewVector()
va := vv.Abs()
switch {
case va.X > va.Y && va.X > va.Z:
return math32.X, math32.Sign(vv.X)
case va.Y > va.X && va.Y > va.Z:
return math32.Y, math32.Sign(vv.Y)
default:
return math32.Z, math32.Sign(vv.Z)
}
}
// Orbit moves the camera along the given 2D axes in degrees
// (delX = left/right, delY = up/down),
// relative to current position and orientation,
// keeping the same distance from the Target, and rotating the camera and
// the Up direction vector to keep looking at the target.
func (cm *Camera) Orbit(delX, delY float32) {
ctdir := cm.ViewVector()
if ctdir == (math32.Vector3{}) {
ctdir.Set(0, 0, 1)
}
dir := ctdir.Normal()
up := cm.UpDir
right := cm.UpDir.Cross(dir).Normal()
// up := dir.Cross(right).Normal() // ensure ortho -- not needed
// delX rotates around the up vector
dxq := math32.NewQuatAxisAngle(up, math32.DegToRad(delX))
dx := dxq.MulVector(ctdir).Sub(ctdir)
// delY rotates around the right vector
dyq := math32.NewQuatAxisAngle(right, math32.DegToRad(delY))
dy := dyq.MulVector(ctdir).Sub(ctdir)
cm.Pose.Pos = cm.Pose.Pos.Add(dx).Add(dy)
cm.UpDir = dyq.MulVector(cm.UpDir) // this is only one that affects up
cm.LookAtTarget()
}
// Pan moves the camera along the given 2D axes (left/right, up/down),
// relative to current position and orientation (i.e., in the plane of the
// current window view)
// and it moves the target by the same increment, changing the target position.
func (cm *Camera) Pan(delX, delY float32) {
dx := cm.Pose.Quat.MulVector(math32.Vec3(-delX, 0, 0))
dy := cm.Pose.Quat.MulVector(math32.Vec3(0, -delY, 0))
td := dx.Add(dy)
cm.Pose.Pos.SetAdd(td)
cm.Target.SetAdd(td)
}
// PanAxis moves the camera and target along world X,Y axes
func (cm *Camera) PanAxis(delX, delY float32) {
td := math32.Vec3(-delX, -delY, 0)
cm.Pose.Pos.SetAdd(td)
cm.Target.SetAdd(td)
}
// PanTarget moves the target along world X,Y,Z axes and does LookAt
// at the new target location. It ensures that the target is not
// identical to the camera position.
func (cm *Camera) PanTarget(delX, delY, delZ float32) {
td := math32.Vec3(-delX, -delY, delZ)
cm.Target.SetAdd(td)
dist := cm.ViewVector().Length()
if dist == 0 {
cm.Target.SetAdd(td)
}
cm.LookAtTarget()
}
// TargetFromView updates the target location from the current view matrix,
// by projecting the current target distance along the current camera
// view matrix.
func (cm *Camera) TargetFromView() {
trgdist := cm.Pose.Pos.Sub(cm.Target).Length() // distance to existing target
tpos := math32.Vec4(0, 0, -trgdist, 1) // target is that distance along -Z axis in front of me
cm.Target = math32.Vector3FromVector4(tpos.MulMatrix4(&cm.Pose.Matrix))
}
// Zoom moves along axis given pct closer or further from the target
// it always moves the target back also if it distance is < 1
func (cm *Camera) Zoom(zoomPct float32) {
ctaxis := cm.ViewVector()
if ctaxis == (math32.Vector3{}) {
ctaxis.Set(0, 0, 1)
}
dist := ctaxis.Length()
del := ctaxis.MulScalar(zoomPct)
cm.Pose.Pos.SetAdd(del)
if zoomPct < 0 && dist < 1 {
cm.Target.SetAdd(del)
}
}
// ZoomTo moves along axis in vector pointing through the given 2D point as
// into the camera NDC normalized display coordinates. Point must be
// 0 normalized, (subtract the Scene ObjBBox.Min) and size of Scene is
// passed as size argument.
// ZoomPct is proportion closer (positive) or further (negative) from the target.
func (cm *Camera) ZoomTo(pt, size image.Point, zoomPct float32) {
fsize := math32.Vec2(float32(size.X), float32(size.Y))
fpt := math32.Vec2(float32(pt.X), float32(pt.Y))
ndc := fpt.WindowToNDC(fsize, math32.Vector2{}, math32.FlipY)
ndc.Z = -1 // at closest point
cdir := math32.Vector4FromVector3(ndc, 1).MulMatrix4(&cm.InvProjectionMatrix)
cdir.Z = -1
cdir.W = 0 // vec
// get world position / transform of camera: matrix is inverse of ViewMatrix
wdir := math32.Vector3FromVector4(cdir.MulMatrix4(&cm.Pose.Matrix))
del := wdir.MulScalar(zoomPct)
cm.Pose.Pos.SetAdd(del)
cm.UpdateMatrix()
cm.TargetFromView()
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package xyz
import (
"fmt"
"image"
"strings"
"cogentcore.org/core/events"
"cogentcore.org/core/events/key"
"cogentcore.org/core/math32"
"cogentcore.org/core/tree"
)
var (
OrbitFactor = float32(0.025)
PanFactor = float32(0.001)
)
// NodesUnderPoint returns list of nodes within given node that
// have their ScBBox within given 2D scene point (excludes starting node).
// This is a good first-pass step for node-level
// event handling based on 2D mouse events.
func NodesUnderPoint(n tree.Node, pt image.Point) []Node {
var ns []Node
n.AsTree().WalkDown(func(cn tree.Node) bool {
if cn == n {
return tree.Continue
}
ni, nb := AsNode(cn)
if !ni.IsVisible() {
return tree.Break
}
if pt.In(nb.SceneBBox) {
sbwd := nb.SceneBBox.Size().X
if nb.isLinear {
sp := math32.Vec3(0, 0, 0)
ep := math32.Vec3(1, 0, 0)
spr := sp.MulMatrix4(&nb.Pose.MVPMatrix)
epr := ep.MulMatrix4(&nb.Pose.MVPMatrix)
del := epr.Sub(spr)
angxy := math32.RadToDeg(math32.Atan2(del.Y, del.X))
if sbwd < 5 && ((angxy >= 89 && angxy <= 91) || (angxy >= -91 && angxy <= -89)) {
ns = append(ns, ni)
return tree.Continue
}
mn := math32.FromPoint(nb.SceneBBox.Min)
mx := math32.FromPoint(nb.SceneBBox.Max)
st := mn
ed := mx
flip := (angxy > 0 && angxy < 90) || (angxy < 0 && angxy < -90)
if flip {
st = math32.Vec2(mn.X, mx.Y)
ed = math32.Vec2(mx.X, mn.Y)
}
ln := math32.NewLine2(st, ed)
pos := math32.FromPoint(pt)
cpp := ln.ClosestPointToPoint(pos)
dst := cpp.Sub(pos).Length()
if dst < 10 { // pixels
ns = append(ns, ni)
}
return tree.Continue
}
ns = append(ns, ni)
}
return tree.Continue
})
return ns
}
func (sc *Scene) SlideMoveEvent(e events.Event) {
cdist := math32.Max(sc.Camera.DistanceTo(sc.Camera.Target), 1.0)
orbDel := OrbitFactor * cdist
panDel := PanFactor * cdist
del := e.PrevDelta()
dx := float32(del.X)
dy := float32(del.Y)
switch {
case e.HasAllModifiers(key.Shift):
sc.Camera.Pan(dx*panDel, -dy*panDel)
case e.HasAllModifiers(key.Control):
sc.Camera.PanAxis(dx*panDel, -dy*panDel)
case e.HasAllModifiers(key.Alt):
sc.Camera.PanTarget(dx*panDel, -dy*panDel, 0)
default:
if math32.Abs(dx) > math32.Abs(dy) {
dy = 0
} else {
dx = 0
}
sc.Camera.Orbit(-dx*orbDel, -dy*orbDel)
}
}
func (sc *Scene) MouseScrollEvent(e *events.MouseScroll) {
if sc.NoNav {
return
}
e.SetHandled()
pt := e.Pos()
sz := sc.Geom.Size
cdist := math32.Max(sc.Camera.DistanceTo(sc.Camera.Target), 1.0)
zoom := float32(e.Delta.Y) // float32(e.ScrollNonZeroDelta(false))
zoomDel := float32(.02) * cdist
switch {
case e.HasAllModifiers(key.Alt):
sc.Camera.PanTarget(0, 0, zoom*zoomDel)
default:
sc.Camera.ZoomTo(pt, sz, zoom*zoomDel)
}
}
func (sc *Scene) KeyChordEvent(e events.Event) {
if sc.NoNav {
return
}
sc.NavKeyEvents(e)
}
// NavKeyEvents handles standard viewer keyboard navigation events
func (sc *Scene) NavKeyEvents(kt events.Event) {
ch := string(kt.KeyChord())
// fmt.Printf(ch)
orbDeg := float32(5)
panDel := float32(.2)
zoomPct := float32(.05)
switch ch {
case "UpArrow":
sc.Camera.Orbit(0, orbDeg)
kt.SetHandled()
case "Shift+UpArrow":
sc.Camera.Pan(0, panDel)
kt.SetHandled()
case "Control+UpArrow":
sc.Camera.PanAxis(0, panDel)
kt.SetHandled()
case "Alt+UpArrow":
sc.Camera.PanTarget(0, panDel, 0)
kt.SetHandled()
case "DownArrow":
sc.Camera.Orbit(0, -orbDeg)
kt.SetHandled()
case "Shift+DownArrow":
sc.Camera.Pan(0, -panDel)
kt.SetHandled()
case "Control+DownArrow":
sc.Camera.PanAxis(0, -panDel)
kt.SetHandled()
case "Alt+DownArrow":
sc.Camera.PanTarget(0, -panDel, 0)
kt.SetHandled()
case "LeftArrow":
sc.Camera.Orbit(orbDeg, 0)
kt.SetHandled()
case "Shift+LeftArrow":
sc.Camera.Pan(-panDel, 0)
kt.SetHandled()
case "Control+LeftArrow":
sc.Camera.PanAxis(-panDel, 0)
kt.SetHandled()
case "Alt+LeftArrow":
sc.Camera.PanTarget(-panDel, 0, 0)
kt.SetHandled()
case "RightArrow":
sc.Camera.Orbit(-orbDeg, 0)
kt.SetHandled()
case "Shift+RightArrow":
sc.Camera.Pan(panDel, 0)
kt.SetHandled()
case "Control+RightArrow":
sc.Camera.PanAxis(panDel, 0)
kt.SetHandled()
case "Alt+RightArrow":
sc.Camera.PanTarget(panDel, 0, 0)
kt.SetHandled()
case "Alt++", "Alt+=":
sc.Camera.PanTarget(0, 0, panDel)
kt.SetHandled()
case "Alt+-", "Alt+_":
sc.Camera.PanTarget(0, 0, -panDel)
kt.SetHandled()
case "+", "=", "Shift++":
sc.Camera.Zoom(-zoomPct)
kt.SetHandled()
case "-", "_", "Shift+_":
sc.Camera.Zoom(zoomPct)
kt.SetHandled()
case " ", "Escape":
err := sc.SetCamera("default")
if err != nil {
sc.Camera.DefaultPose()
}
kt.SetHandled()
case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9":
err := sc.SetCamera(ch)
if err != nil {
sc.SaveCamera(ch)
fmt.Printf("Saved camera to: %v\n", ch)
} else {
fmt.Printf("Restored camera from: %v\n", ch)
}
kt.SetHandled()
case "Control+0", "Control+1", "Control+2", "Control+3", "Control+4", "Control+5", "Control+6", "Control+7", "Control+8", "Control+9":
cnm := strings.TrimPrefix(ch, "Control+")
sc.SaveCamera(cnm)
fmt.Printf("Saved camera to: %v\n", cnm)
kt.SetHandled()
case "t":
kt.SetHandled()
obj := sc.Child(0).(*Solid)
fmt.Printf("updated obj: %v\n", obj.Path())
return
}
}
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"image/color"
"cogentcore.org/core/base/iox/imagex"
"cogentcore.org/core/colors"
"cogentcore.org/core/math32"
_ "cogentcore.org/core/paint/renderers"
"cogentcore.org/core/xyz"
"cogentcore.org/core/xyz/examples/assets"
)
func main() {
sc := xyz.NewOffscreenScene()
// options - must be set here
// sc.MultiSample = 1
// sc.Wireframe = true
// sc.NoNav = true
sc.Background = colors.Scheme.Select.Container
xyz.NewAmbient(sc, "ambient", 0.3, xyz.DirectSun)
// sc.Camera.Pose.Pos.Set(-2, 9, 3)
sc.Camera.Pose.Pos.Set(-2, 2, 10)
sc.Camera.LookAt(math32.Vector3{}, math32.Vec3(0, 1, 0)) // defaults to looking at origin
dir := xyz.NewDirectional(sc, "dir", 1, xyz.DirectSun)
dir.Pos.Set(0, 2, 1) // default: 0,1,1 = above and behind us (we are at 0,0,X)
// point := xyz.NewPointLight(sc, "point", 1, xyz.DirectSun)
// point.Pos.Set(0, 5, 5)
// spot := xyz.NewSpotLight(sc, "spot", 1, xyz.DirectSun)
// spot.Pose.Pos.Set(0, 5, 5)
grtx := xyz.NewTextureFileFS(assets.Content, sc, "ground", "ground.png")
// _ = grtx
// wdtx := xyz.NewTextureFile(sc, "wood", "wood.png")
cbm := xyz.NewBox(sc, "cube1", 1, 1, 1)
cbm.Segs.Set(10, 10, 10) // not clear if any diff really..
rbgp := xyz.NewGroup(sc)
rcb := xyz.NewSolid(rbgp).SetMesh(cbm)
rcb.Pose.Pos.Set(-1, 0, 0)
rcb.Material.SetColor(colors.Red).SetShiny(500)
bcb := xyz.NewSolid(rbgp).SetMesh(cbm)
bcb.Pose.Pos.Set(1, 1, 0)
bcb.Pose.Scale.X = 2 // somehow causing to not render
bcb.Material.SetColor(colors.Blue).SetShiny(10).SetReflective(0.2)
gcb := xyz.NewSolid(rbgp).SetMesh(cbm)
gcb.Pose.Pos.Set(0, 0, 1)
gcb.Material.SetColor(color.RGBA{0, 255, 0, 128}).SetShiny(20) // alpha = .5 -- note: colors are NOT premultiplied here: will become so when rendered!
floorp := xyz.NewPlane(sc, "floor", 100, 100)
floor := xyz.NewSolid(sc).SetMesh(floorp)
floor.Pose.Pos.Set(0, -5, 0)
floor.Material.Color = colors.Tan
// floor.Mat.Emissive.SetName("brown")
// floor.Mat.Bright = 2 // .5 for wood / brown
floor.Material.SetTexture(grtx)
floor.Material.Tiling.Repeat.Set(40, 40)
// floor.SetDisabled() // not selectable
sc.Rebuild()
img := sc.RenderGrabImage()
imagex.Save(img, "render.png")
}
// Copyright (c) 2019, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package xyz
import (
"sort"
"cogentcore.org/core/math32"
"cogentcore.org/core/tree"
)
// Group collects individual elements in a scene but does not have a Mesh or Material of
// its own. It does have a transform that applies to all nodes under it.
type Group struct {
NodeBase
}
// UpdateMeshBBox updates the Mesh-based BBox info for all nodes.
// groups aggregate over elements
func (gp *Group) UpdateMeshBBox() {
// todo: radial, etc
gp.MeshBBox.BBox.SetEmpty()
for _, kid := range gp.Children {
nii, ni := AsNode(kid)
if nii == nil {
continue
}
nbb := ni.MeshBBox.BBox.MulMatrix4(&ni.Pose.Matrix)
gp.MeshBBox.BBox.ExpandByPoint(nbb.Min)
gp.MeshBBox.BBox.ExpandByPoint(nbb.Max)
}
// fmt.Printf("gp: %v bbox: %v\n", gp.Nm, gp.MeshBBox.BBox)
}
func (gp *Group) Defaults() {
gp.Pose.Defaults()
}
func (gp *Group) Update() {
gp.RunUpdaters()
for n := range gp.All() {
if n.AsTree().This == gp.This {
continue
}
n.(Node).Update()
}
}
func (gp *Group) RenderClass() RenderClasses {
return RClassNone
}
// SetPos sets the [Pose.Pos] position of the solid
func (gp *Group) SetPos(x, y, z float32) *Group {
gp.Pose.Pos.Set(x, y, z)
return gp
}
// SetScale sets the [Pose.Scale] scale of the solid
func (gp *Group) SetScale(x, y, z float32) *Group {
gp.Pose.Scale.Set(x, y, z)
return gp
}
// SetAxisRotation sets the [Pose.Quat] rotation of the solid,
// from local axis and angle in degrees.
func (gp *Group) SetAxisRotation(x, y, z, angle float32) *Group {
gp.Pose.SetAxisRotation(x, y, z, angle)
return gp
}
// SetEulerRotation sets the [Pose.Quat] rotation of the solid,
// from euler angles in degrees
func (gp *Group) SetEulerRotation(x, y, z float32) *Group {
gp.Pose.SetEulerRotation(x, y, z)
return gp
}
// SolidPoint contains a Solid and a Point on that solid
type SolidPoint struct {
Solid *Solid
Point math32.Vector3
}
// RaySolidIntersections returns a list of solids whose bounding box intersects
// with the given ray, with the point of intersection. Results are sorted
// from closest to furthest.
func (gp *Group) RaySolidIntersections(ray math32.Ray) []*SolidPoint {
var sp []*SolidPoint
gp.WalkDown(func(k tree.Node) bool {
ni, nb := AsNode(k)
if ni == nil {
return tree.Break // going into a different type of thing, bail
}
pt, has := ray.IntersectBox(nb.WorldBBox.BBox)
if !has {
return tree.Break
}
if !ni.IsSolid() {
return tree.Continue
}
sd := ni.AsSolid()
sp = append(sp, &SolidPoint{sd, pt})
return tree.Break
})
sort.Slice(sp, func(i, j int) bool {
di := sp[i].Point.DistanceTo(ray.Origin)
dj := sp[j].Point.DistanceTo(ray.Origin)
return di < dj
})
return sp
}
// test for impl
var _ Node = &Group{}
// Copyright (c) 2019, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package xyz
import (
"fmt"
"io"
"io/fs"
"path/filepath"
"strings"
"cogentcore.org/core/base/fsx"
"cogentcore.org/core/tree"
)
// Decoder parses 3D object / scene file(s) and imports into a Group or Scene.
// This interface is implemented by the different format-specific decoders.
type Decoder interface {
// New returns a new instance of the decoder used for a specific decoding
New() Decoder
// Desc returns the description of this decoder
Desc() string
// SetFile sets the file name being used for decoding, or error if not found.
// Returns a list of files that should be loaded along with the main one, if needed.
// For example, .obj decoder adds a corresponding .mtl file. In addition,
// decoded files may specify further files (textures, etc) that must be located
// relative to the same fsys directory.
// All file operations use the fsys file system for access, and this should be a
// Sub FS anchored at the directory where the filename is located.
SetFileFS(fsys fs.FS, fname string) ([]string, error)
// Decode reads the given data and decodes it, returning a new instance
// of the Decoder that contains all the decoded info.
// Some formats (e.g., Wavefront .obj) have separate .obj and .mtl files
// which are passed as two reader args.
Decode(rs []io.Reader) error
// SetGroup sets the group to contain the decoded objects within the
// given scene.
SetGroup(sc *Scene, gp *Group)
// HasScene returns true if this decoder has full scene information --
// otherwise it only supports objects to be used in SetGroup.
HasScene() bool
// SetScene sets the scene according to the decoded data.
SetScene(sc *Scene)
}
// Decoders is the master list of decoders, indexed by the primary extension.
// .obj = Wavefront object file -- only has mesh data, not scene info.
var Decoders = map[string]Decoder{}
// DecodeFile decodes the given file using a decoder based on the file
// extension. Returns decoder instance with full decoded state.
// Supported formats include:
// .obj = Wavefront OBJ format, including associated materials (.mtl) which
//
// must have same name as .obj, or a default material is used.
func DecodeFile(fname string) (Decoder, error) {
dfs, fnm, err := fsx.DirFS(fname)
if err != nil {
return nil, err
}
return DecodeFileFS(dfs, fnm)
}
// DecodeFileFS decodes the given file from the given filesystem using a decoder based on the file
// extension. Returns decoder instance with full decoded state.
// Supported formats include:
// .obj = Wavefront OBJ format, including associated materials (.mtl) which
//
// must have same name as .obj, or a default material is used.
func DecodeFileFS(fsys fs.FS, fname string) (Decoder, error) {
ext := filepath.Ext(fname)
dt, has := Decoders[ext]
if !has {
return nil, fmt.Errorf("xyz.DecodeFile: file extension: %v not found in Decoders list for file %v", ext, fname)
}
dec := dt.New()
fn := fname
subdir, fn := filepath.Split(fn)
var err error
if subdir != "" {
fsys, err = fs.Sub(fsys, subdir)
if err != nil {
return nil, fmt.Errorf("xyz.DecodeFile: file directory not found error: %v for file: %v", err, fname)
}
}
files, err := dec.SetFileFS(fsys, fn)
if err != nil {
return nil, fmt.Errorf("xyz.DecodeFile: file not found error: %v for file: %v", err, fname)
}
nf := len(files)
fs := make([]fs.File, nf)
rs := make([]io.Reader, nf)
defer func() {
for _, fi := range fs {
if fi != nil {
fi.Close()
}
}
}()
for i, f := range files {
fs[i], err = fsys.Open(f)
if err != nil {
return nil, err
}
rs[i] = fs[i]
}
err = dec.Decode(rs)
if err != nil {
return nil, err
}
return dec, nil
}
// OpenObj opens object(s) from given file into given group in scene,
// using a decoder based on the file extension.
// Supported formats include:
// .obj = Wavefront OBJ format, including associated materials (.mtl) which
//
// must have same name as .obj, or a default material is used.
func (sc *Scene) OpenObj(fname string, gp *Group) error {
dfs, fnm, err := fsx.DirFS(fname)
if err != nil {
return err
}
return sc.OpenObjFS(dfs, fnm, gp)
}
// OpenObjFS opens object(s) from given file in the given filesystem into given group in scene,
// using a decoder based on the file extension.
// Supported formats include:
// .obj = Wavefront OBJ format, including associated materials (.mtl) which
//
// must have same name as .obj, or a default material is used.
func (sc *Scene) OpenObjFS(fsys fs.FS, fname string, gp *Group) error {
dec, err := DecodeFileFS(fsys, fname)
if err != nil {
return err
}
dec.SetGroup(sc, gp)
// sc.Config() // needed after loading
return nil
}
// OpenNewObj opens object(s) from given file into a new group
// under given parent, using a decoder based on the file extension.
// Supported formats include:
// .obj = Wavefront OBJ format, including associated materials (.mtl) which
//
// must have same name as .obj, or a default material is used.
func (sc *Scene) OpenNewObj(fname string, parent tree.Node) (*Group, error) {
dfs, fnm, err := fsx.DirFS(fname)
if err != nil {
return nil, err
}
return sc.OpenNewObjFS(dfs, fnm, parent)
}
// OpenNewObjFS opens object(s) from given file in the given filesystem into a new group
// under given parent, using a decoder based on the file extension.
// Supported formats include:
// .obj = Wavefront OBJ format, including associated materials (.mtl) which
//
// must have same name as .obj, or a default material is used.
func (sc *Scene) OpenNewObjFS(fsys fs.FS, fname string, parent tree.Node) (*Group, error) {
dec, err := DecodeFileFS(fsys, fname)
if err != nil {
return nil, err
}
_, fn := filepath.Split(fname)
gp := NewGroup(parent)
gp.SetName(fn)
dec.SetGroup(sc, gp)
// if sc.Frame != nil { // has already been configured
// sc.Config()
// }
return gp, nil
}
// OpenToLibrary opens object(s) from given file into the scene's Library
// using a decoder based on the file extension. The library key name
// must be unique, and is given by libnm -- if empty, then the filename (only)
// without extension is used.
// Supported formats include:
// .obj = Wavefront OBJ format, including associated materials (.mtl) which
//
// must have same name as .obj, or a default material is used.
func (sc *Scene) OpenToLibrary(fname string, libnm string) (*Group, error) {
dfs, fnm, err := fsx.DirFS(fname)
if err != nil {
return nil, err
}
return sc.OpenToLibraryFS(dfs, fnm, libnm)
}
// OpenToLibraryFS opens object(s) from given file in the given filesystem into the scene's Library
// using a decoder based on the file extension. The library key name
// must be unique, and is given by libnm -- if empty, then the filename (only)
// without extension is used.
// Supported formats include:
// .obj = Wavefront OBJ format, including associated materials (.mtl) which
//
// must have same name as .obj, or a default material is used.
func (sc *Scene) OpenToLibraryFS(fsys fs.FS, fname string, libnm string) (*Group, error) {
dec, err := DecodeFileFS(fsys, fname)
if err != nil {
return nil, err
}
if libnm == "" {
_, fn := filepath.Split(fname)
ext := filepath.Ext(fn)
libnm = strings.TrimSuffix(fn, ext)
}
gp := sc.NewInLibrary(libnm)
dec.SetGroup(sc, gp)
return gp, nil
}
// OpenScene opens a scene from the given file, using a decoder based on
// the file extension in first file name.
// Supported formats include:
// .obj = Wavefront OBJ format, including associated materials (.mtl) which
//
// must have same name as .obj, or a default material is used.
// Does not support full scene data so only objects are loaded
// into a new group in scene.
func (sc *Scene) OpenScene(fname string) error {
dfs, fnm, err := fsx.DirFS(fname)
if err != nil {
return err
}
return sc.OpenSceneFS(dfs, fnm)
}
// OpenSceneFS opens a scene from the given file in the given filesystem, using a decoder based on
// the file extension in first file name.
// Supported formats include:
// .obj = Wavefront OBJ format, including associated materials (.mtl) which
//
// must have same name as .obj, or a default material is used.
// Does not support full scene data so only objects are loaded
// into a new group in scene.
func (sc *Scene) OpenSceneFS(fsys fs.FS, fname string) error {
dec, err := DecodeFileFS(fsys, fname)
if err != nil {
return err
}
dec.SetScene(sc)
// sc.Config() // needed after loading
return nil
}
// ReadObj reads object(s) from given reader(s) into given group in scene,
// using a decoder based on the extension of the given file name --
// even though the file name is not directly used to read the file, it is
// required for naming and decoding selection. This method can be used
// for loading data embedded in an executable for example.
// Supported formats include:
// .obj = Wavefront OBJ format, including associated materials (.mtl) which
//
// is the 2nd reader arg, or a default material is used.
func (sc *Scene) ReadObj(fname string, rs []io.Reader, gp *Group) error {
ext := filepath.Ext(fname)
dt, has := Decoders[ext]
if !has {
return fmt.Errorf("xyz.ReadObj: file extension: %v not found in Decoders list", ext)
}
dfs, fnm, err := fsx.DirFS(fname)
if err != nil {
return err
}
dec := dt.New()
dec.SetFileFS(dfs, fnm)
err = dec.Decode(rs)
if err != nil {
return err
}
dec.SetGroup(sc, gp)
// sc.Config() // needed after loading
return nil
}
// ReadScene reads scene from given reader(s), using a decoder based on the
// file name extension -- even though the file name is not directly used
// to read the file, it is required for naming and decoding selection.
// This method can be used for loading data embedded in an executable for example.
// Supported formats include:
// .obj = Wavefront OBJ format, including associated materials (.mtl) which
//
// must have same name as .obj, or a default material is used.
// Does not support full scene data so only objects are loaded
// into a new group in scene.
func (sc *Scene) ReadScene(fname string, rs []io.Reader, gp *Group) error {
ext := filepath.Ext(fname)
dt, has := Decoders[ext]
if !has {
return fmt.Errorf("xyz.ReadScene: file extension: %v not found in Decoders list", ext)
}
dfs, fnm, err := fsx.DirFS(fname)
if err != nil {
return err
}
dec := dt.New()
dec.SetFileFS(dfs, fnm)
err = dec.Decode(rs)
if err != nil {
return err
}
dec.SetScene(sc)
// sc.Config() // needed after loading
return nil
}
// Copyright (c) 2019, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This package is based extensively on https://github.com/g3n/engine
// Copyright 2016 The G3N Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package obj is used to parse the Wavefront OBJ file format (*.obj), including
// associated materials (*.mtl). Not all features of the OBJ format are
// supported. Basic format info: https://en.wikipedia.org/wiki/Wavefront_.obj_file
package obj
import (
"bufio"
"errors"
"fmt"
"image/color"
"io"
"io/fs"
"math"
"path/filepath"
"strconv"
"strings"
"cogentcore.org/core/base/fsx"
"cogentcore.org/core/colors"
"cogentcore.org/core/gpu/phong"
"cogentcore.org/core/math32"
"cogentcore.org/core/xyz"
)
func init() {
xyz.Decoders[".obj"] = &Decoder{}
}
// Decoder contains all decoded data from the obj and mtl files.
// It also implements the xyz.Decoder interface and an instance
// is registered to handle .obj files.
type Decoder struct {
FS fs.FS // filesystem, used for all loading
Objfile string // .obj filename within FS
Objects []Object // decoded objects
Matlib string // name of the material lib
Materials map[string]*Material // maps material name to object
Vertices math32.ArrayF32 // vertices positions array
Normals math32.ArrayF32 // vertices normals
Uvs math32.ArrayF32 // vertices texture coordinates
Warnings []string // warning messages
line uint // current line number
objCurrent *Object // current object
matCurrent *Material // current material
smoothCurrent bool // current smooth state
}
func (dec *Decoder) New() xyz.Decoder {
di := new(Decoder)
di.Objects = make([]Object, 0)
di.Warnings = make([]string, 0)
di.Materials = make(map[string]*Material)
di.Vertices = math32.NewArrayF32(0, 0)
di.Normals = math32.NewArrayF32(0, 0)
di.Uvs = math32.NewArrayF32(0, 0)
di.line = 1
return di
}
// Destroy deletes data created during loading
func (dec *Decoder) Destroy() {
for oi := range dec.Objects {
ob := &dec.Objects[oi]
ob.Destroy()
}
dec.Objects = nil
dec.Warnings = nil
dec.Materials = nil
dec.Vertices = nil
dec.Normals = nil
dec.Uvs = nil
dec.objCurrent = nil
dec.matCurrent = nil
}
func (dec *Decoder) Desc() string {
return ".obj = Wavefront OBJ format, including associated materials (.mtl) which can be specified as second file name -- otherwise auto-searched based on .obj filename, or a default material is used. Only supports Object-level data, not full Scene (camera, lights etc)."
}
func (dec *Decoder) HasScene() bool {
return false
}
func (dec *Decoder) SetFileFS(fsys fs.FS, fname string) ([]string, error) {
dec.FS = fsys
exists, err := fsx.FileExistsFS(dec.FS, fname)
if err != nil {
return nil, errors.New("xyz obj.Decoder: " + err.Error())
}
if !exists {
return nil, errors.New("xyz obj.Decoder: file not found: " + fname)
}
// the materials are used if there is a .mtl file of the same name
mtlf := strings.TrimSuffix(fname, ".obj") + ".mtl"
exists, _ = fsx.FileExistsFS(dec.FS, mtlf)
if exists {
return []string{fname, mtlf}, nil
}
return []string{fname}, nil
}
// Decode reads the given data and decodes into Decoder tmp vars.
// if 2 args are passed, first is .obj and second is .mtl
func (dec *Decoder) Decode(rs []io.Reader) error {
nf := len(rs)
if nf == 0 {
return errors.New("xyz obj.Decoder: no readers passed")
}
// Parses obj lines
err := dec.parse(rs[0], dec.parseObjLine)
if err != nil {
return err
}
dec.matCurrent = nil
dec.line = 1
useDef := nf == 1
if nf > 1 {
err = dec.parse(rs[1], dec.parseMtlLine)
if err != nil {
useDef = true
}
}
if useDef {
for key := range dec.Materials {
dec.Materials[key] = defaultMat
}
}
return nil
}
// Object contains all information about one decoded object
type Object struct {
Name string // Object name
Faces []Face // Faces
materials []string // Materials used in this object
}
func (ob *Object) Destroy() {
ob.materials = nil
for fi := range ob.Faces {
fc := &ob.Faces[fi]
fc.Destroy()
}
ob.Faces = nil
}
// Face contains all information about an object face
type Face struct {
Vertices []int // Indices to the face vertices
Uvs []int // Indices to the face UV coordinates
Normals []int // Indices to the face normals
Material string // Material name
Smooth bool // Smooth face
}
func (fc *Face) Destroy() {
fc.Vertices = nil
fc.Uvs = nil
fc.Normals = nil
}
// Material contains all information about an object material
type Material struct {
Name string // Material name
Illum int // Illumination model
Opacity float32 // Opacity factor
Refraction float32 // Refraction factor
Shininess float32 // Shininess (specular exponent)
Ambient color.RGBA // Ambient color reflectivity
Diffuse color.RGBA // Diffuse color reflectivity
Specular color.RGBA // Specular color reflectivity
Emissive color.RGBA // Emissive color
MapKd string // Texture file linked to diffuse color
Tiling phong.Tiling // Tiling parameters: repeat and offset
}
// Light gray default material used as when other materials cannot be loaded.
var defaultMat = &Material{
Diffuse: color.RGBA{R: 0xA0, G: 0xA0, B: 0xA0, A: 0xFF},
Ambient: color.RGBA{R: 0xA0, G: 0xA0, B: 0xA0, A: 0xFF},
Specular: color.RGBA{R: 0x80, G: 0x80, B: 0x80, A: 0xFF},
Shininess: 30.0,
}
// Local constants
const (
blanks = "\r\n\t "
invINDEX = math.MaxInt32
objType = "obj"
mtlType = "mtl"
)
// SetScene sets group with with all the decoded objects.
func (dec *Decoder) SetScene(sc *xyz.Scene) {
gp := xyz.NewGroup(sc)
gp.SetName(dec.Objfile)
dec.SetGroup(sc, gp)
}
// SetGroup sets group with with all the decoded objects.
// calls Destroy after to free memory
func (dec *Decoder) SetGroup(sc *xyz.Scene, gp *xyz.Group) {
for i := range dec.Objects {
obj := &dec.Objects[i]
if len(obj.Faces) == 0 {
continue
}
objgp := xyz.NewGroup(gp)
objgp.SetName(obj.Name)
dec.SetObject(sc, objgp, obj)
}
dec.Destroy()
}
// SetObject sets the object as a group with each xyz.Solid as a mesh with unique material
func (dec *Decoder) SetObject(sc *xyz.Scene, objgp *xyz.Group, ob *Object) {
matName := ""
var sld *xyz.Solid
var ms *xyz.GenMesh
sldidx := 0
idxs := make([]int, 0, 4)
for fi := range ob.Faces {
face := &ob.Faces[fi]
if face.Material != matName || sld == nil {
sldnm := fmt.Sprintf("%s_%d", ob.Name, sldidx)
ms = &xyz.GenMesh{}
ms.Name = sldnm
sc.AddMeshUnique(ms)
sld = xyz.NewSolid(objgp).SetMesh(ms)
sld.SetName(sldnm)
matName = face.Material
dec.SetMat(sc, sld, matName)
sldidx++
}
// Copy face vertices to geometry
// https://stackoverflow.com/questions/23723993/converting-quadriladerals-in-an-obj-file-into-triangles
// logic for 0, i, i+1
// note: the last comment at the end is *incorrect* -- it really is the triangle fans as impl here:
idxs = idxs[:3]
idxs[0] = dec.copyVertex(ms, face, 0)
idxs[1] = dec.copyVertex(ms, face, 1)
idxs[2] = dec.copyVertex(ms, face, 2)
dec.addNorms(ms, 0, 1, 2, idxs)
// copyVertex has indexed the first triangle, and each further
// vertex makes a triangle of the fan with the first and previous ones.
for idx := 3; idx < len(face.Vertices); idx++ {
dec.setIndex(ms, face, 0, &idxs)
dec.setIndex(ms, face, idx-1, &idxs)
dec.setIndex(ms, face, idx, &idxs)
dec.addNorms(ms, 0, idx-1, idx, idxs)
}
}
}
func (dec *Decoder) addNorms(ms *xyz.GenMesh, ai, bi, ci int, idxs []int) {
if len(ms.Normal) >= len(ms.Vertex) {
return
}
var a, b, c math32.Vector3
ms.Vertex.GetVector3(3*idxs[ai], &a)
ms.Vertex.GetVector3(3*idxs[bi], &b)
ms.Vertex.GetVector3(3*idxs[ci], &c)
nrm := math32.Normal(a, b, c)
for {
ms.Normal.AppendVector3(nrm)
if len(ms.Normal) >= len(ms.Vertex) {
break
}
}
}
func (dec *Decoder) setIndex(ms *xyz.GenMesh, face *Face, idx int, idxs *[]int) {
if len(*idxs) > idx {
ms.Index.Append(uint32((*idxs)[idx]))
} else {
*idxs = append(*idxs, dec.copyVertex(ms, face, idx))
}
}
func (dec *Decoder) copyVertex(ms *xyz.GenMesh, face *Face, idx int) int {
var vector3 math32.Vector3
var vector2 math32.Vector2
vidx := len(ms.Vertex) / 3
// Copy vertex position and append to geometry
dec.Vertices.GetVector3(3*face.Vertices[idx], &vector3)
ms.Vertex.AppendVector3(vector3)
// Copy vertex normal and append to geometry
if face.Normals[idx] != invINDEX {
i := 3 * face.Normals[idx]
if len(dec.Normals) > i {
dec.Normals.GetVector3(i, &vector3)
}
ms.Normal.AppendVector3(vector3)
}
// Copy vertex uv and append to geometry
if face.Uvs[idx] != invINDEX {
i := 2 * face.Uvs[idx]
if len(dec.Uvs) > i {
dec.Uvs.GetVector2(i, &vector2)
}
ms.TexCoord.AppendVector2(vector2)
}
ms.Index.Append(uint32(vidx))
return vidx
}
// SetMat sets the material for object
func (dec *Decoder) SetMat(sc *xyz.Scene, sld *xyz.Solid, matnm string) {
mat := dec.Materials[matnm]
if mat == nil {
mat = defaultMat
// log warning
msg := fmt.Sprintf("could not find material: %s for object %s. using default material.", matnm, sld.Name)
dec.appendWarn(objType, msg)
}
sld.Material.Defaults()
sld.Material.CullBack = false // obj files do not reliably work with this on!
sld.Material.Color = mat.Diffuse
if mat.Opacity > 0 {
sld.Material.Color.A = uint8(mat.Opacity * float32(0xFF))
}
// sld.Mat.Specular = mat.Specular
if mat.Shininess != 0 {
sld.Material.Shiny = mat.Shininess
}
// Loads material textures if specified
dec.loadTex(sc, sld, mat.MapKd, mat)
}
// loadTex loads given texture file
func (dec *Decoder) loadTex(sc *xyz.Scene, sld *xyz.Solid, texfn string, mat *Material) {
if texfn == "" {
return
}
_, tfn := filepath.Split(texfn)
tf, err := sc.TextureByName(tfn)
if err != nil {
tf = xyz.NewTextureFileFS(dec.FS, sc, tfn, texfn)
}
sld.Material.SetTexture(tf)
if mat.Tiling.Repeat.X > 0 {
sld.Material.Tiling.Repeat = mat.Tiling.Repeat
}
sld.Material.Tiling.Offset = mat.Tiling.Offset
}
// parse reads the lines from the specified reader and dispatch them
// to the specified line parser.
func (dec *Decoder) parse(reader io.Reader, parseLine func(string) error) error {
bufin := bufio.NewReader(reader)
dec.line = 1
for {
// Reads next line and abort on errors (not EOF)
line, err := bufin.ReadString('\n')
if err != nil && err != io.EOF {
return err
}
// Parses the line
line = strings.Trim(line, blanks)
perr := parseLine(line)
if perr != nil {
return perr
}
// If EOF ends of parsing.
if err == io.EOF {
break
}
dec.line++
}
return nil
}
// Parses obj file line, dispatching to specific parsers
func (dec *Decoder) parseObjLine(line string) error {
// Ignore empty lines
fields := strings.Fields(line)
if len(fields) == 0 {
return nil
}
// Ignore comment lines
ltype := fields[0]
if strings.HasPrefix(ltype, "#") {
return nil
}
switch ltype {
// Material library
case "mtllib":
return dec.parseMatlib(fields[1:])
// Object name
case "o":
return dec.parseObject(fields[1:])
// Group names. We are considering "group" the same as "object"
// This may not be right
case "g":
return dec.parseObject(fields[1:])
// Vertex coordinate
case "v":
return dec.parseVertex(fields[1:])
// Vertex normal coordinate
case "vn":
return dec.parseNormal(fields[1:])
// Vertex texture coordinate
case "vt":
return dec.parseTex(fields[1:])
// Face vertex
case "f":
return dec.parseFace(fields[1:])
// Use material
case "usemtl":
return dec.parseUsemtl(fields[1:])
// Smooth
case "s":
return dec.parseSmooth(fields[1:])
default:
dec.appendWarn(objType, "field not supported: "+ltype)
}
return nil
}
// Parses a mtllib line:
// mtllib <name>
func (dec *Decoder) parseMatlib(fields []string) error {
if len(fields) < 1 {
return errors.New("Material library (mtllib) with no fields")
}
dec.Matlib = fields[0]
return nil
}
// Parses an object line:
// o <name>
func (dec *Decoder) parseObject(fields []string) error {
if len(fields) < 1 {
return errors.New("Object line (o) with no fields")
}
dec.Objects = append(dec.Objects, makeObject(fields[0]))
dec.objCurrent = &dec.Objects[len(dec.Objects)-1]
return nil
}
// makes an Object with name.
func makeObject(name string) Object {
var ob Object
ob.Name = name
ob.Faces = make([]Face, 0)
ob.materials = make([]string, 0)
return ob
}
// Parses a vertex position line
// v <x> <y> <z> [w]
func (dec *Decoder) parseVertex(fields []string) error {
if len(fields) < 3 {
return errors.New("fewer than 3 vertices in 'v' line")
}
for _, f := range fields[:3] {
val, err := strconv.ParseFloat(f, 32)
if err != nil {
return err
}
dec.Vertices.Append(float32(val))
}
return nil
}
// Parses a vertex normal line
// vn <x> <y> <z>
func (dec *Decoder) parseNormal(fields []string) error {
if len(fields) < 3 {
return errors.New("fewer than 3 normals in 'vn' line")
}
for _, f := range fields[:3] {
val, err := strconv.ParseFloat(f, 32)
if err != nil {
return err
}
dec.Normals.Append(float32(val))
}
return nil
}
// Parses a vertex texture coordinate line:
// vt <u> <v> <w>
func (dec *Decoder) parseTex(fields []string) error {
if len(fields) < 2 {
return errors.New("fewer than 2 texture coords. in 'vt' line")
}
for _, f := range fields[:2] {
val, err := strconv.ParseFloat(f, 32)
if err != nil {
return err
}
dec.Uvs.Append(float32(val))
}
return nil
}
// parseFace parses a face decription line:
// f v1[/vt1][/vn1] v2[/vt2][/vn2] v3[/vt3][/vn3] ...
func (dec *Decoder) parseFace(fields []string) error {
if dec.objCurrent == nil {
// if a face line is encountered before a group (g) or object (o),
// create a new "default" object. This 'handles' the case when
// a g or o line is not specified (allowed in OBJ format)
dec.parseObject([]string{fmt.Sprintf("unnamed%d", dec.line)})
}
// If current object has no material, appends last material if defined
if len(dec.objCurrent.materials) == 0 && dec.matCurrent != nil {
dec.objCurrent.materials = append(dec.objCurrent.materials, dec.matCurrent.Name)
}
if len(fields) < 3 {
return dec.formatError("Face line with less 3 fields")
}
var face Face
face.Vertices = make([]int, len(fields))
face.Uvs = make([]int, len(fields))
face.Normals = make([]int, len(fields))
if dec.matCurrent != nil {
face.Material = dec.matCurrent.Name
} else {
// TODO (quillaja): do something better than spamming warnings for each line
// dec.appendWarn(objType, "No material defined")
face.Material = "internal default" // causes error on in NewGeom() if ""
// dec.matCurrent = defaultMat
}
face.Smooth = dec.smoothCurrent
for pos, f := range fields {
// Separate the current field in its components: v vt vn
vfields := strings.Split(f, "/")
if len(vfields) < 1 {
return dec.formatError("Face field with no parts")
}
// Get the index of this vertex position (must always exist)
val, err := strconv.ParseInt(vfields[0], 10, 32)
if err != nil {
return err
}
// Positive index is an absolute vertex index
nv := len(dec.Vertices) / 3
if val > 0 {
face.Vertices[pos] = int(val - 1)
// Negative vertex index is relative to the last parsed vertex
} else if val < 0 {
current := nv - 1
face.Vertices[pos] = current + int(val) + 1
// Vertex index could never be 0
} else {
return dec.formatError("Face vertex index value equal to 0")
}
// the vertexes of a face must be defined before it
if vi := face.Vertices[pos]; vi < 0 || vi >= nv {
return dec.formatError(fmt.Sprintf("Face vertex index %d of %d vertexes", val, nv))
}
// Get the index of this vertex UV coordinate (optional)
if len(vfields) > 1 && len(vfields[1]) > 0 {
val, err := strconv.ParseInt(vfields[1], 10, 32)
if err != nil {
return err
}
// Positive index is an absolute UV index
if val > 0 {
face.Uvs[pos] = int(val - 1)
// Negative vertex index is relative to the last parsed uv
} else if val < 0 {
current := (len(dec.Uvs) / 2) - 1
face.Uvs[pos] = current + int(val) + 1
// UV index could never be 0
} else {
return dec.formatError("Face uv index value equal to 0")
}
} else {
face.Uvs[pos] = invINDEX
}
// Get the index of this vertex normal (optional)
if len(vfields) >= 3 {
val, err = strconv.ParseInt(vfields[2], 10, 32)
if err != nil {
return err
}
// Positive index is an absolute normal index
if val > 0 {
face.Normals[pos] = int(val - 1)
// Negative vertex index is relative to the last parsed normal
} else if val < 0 {
current := (len(dec.Normals) / 3) - 1
face.Normals[pos] = current + int(val) + 1
// Normal index could never be 0
} else {
return dec.formatError("Face normal index value equal to 0")
}
} else {
face.Normals[pos] = invINDEX
}
}
// Appends this face to the current object
dec.objCurrent.Faces = append(dec.objCurrent.Faces, face)
return nil
}
// parseUsemtl parses a "usemtl" decription line:
// usemtl <name>
func (dec *Decoder) parseUsemtl(fields []string) error {
if len(fields) < 1 {
return dec.formatError("Usemtl with no fields")
}
// NOTE(quillaja): see similar nil test in parseFace()
if dec.objCurrent == nil {
dec.parseObject([]string{fmt.Sprintf("unnamed%d", dec.line)})
}
// Checks if this material has already been parsed
name := fields[0]
mat := dec.Materials[name]
// Creates material descriptor
if mat == nil {
mat = new(Material)
mat.Name = name
dec.Materials[name] = mat
}
dec.objCurrent.materials = append(dec.objCurrent.materials, name)
// Set this as the current material
dec.matCurrent = mat
return nil
}
// parseSmooth parses a "s" decription line:
// s <off|on|0|group number>
func (dec *Decoder) parseSmooth(fields []string) error {
if len(fields) < 1 {
return dec.formatError("'s' with no fields")
}
if fields[0] == "0" || fields[0] == "off" {
dec.smoothCurrent = false
return nil
}
if fields[0] == "on" {
dec.smoothCurrent = true
return nil
}
// a smoothing group number, of which 0 is off (above)
if n, err := strconv.ParseUint(fields[0], 10, 32); err == nil && n > 0 {
dec.smoothCurrent = true
return nil
}
return dec.formatError("'s' with invalid value")
}
/******************************************************************************
mtl parse functions
*/
// Parses material file line, dispatching to specific parsers
func (dec *Decoder) parseMtlLine(line string) error {
// Ignore empty lines
fields := strings.Fields(line)
if len(fields) == 0 {
return nil
}
// Ignore comment lines
ltype := fields[0]
if strings.HasPrefix(ltype, "#") {
return nil
}
if ltype != "newmtl" && dec.matCurrent == nil {
switch ltype {
case "d", "Ka", "Kd", "Ke", "Ks", "Ni", "Ns", "illum", "map_Kd":
return dec.formatError("'" + ltype + "' before any material (newmtl)")
}
}
switch ltype {
case "newmtl":
return dec.parseNewmtl(fields[1:])
case "d":
return dec.parseDissolve(fields[1:])
case "Ka":
return dec.parseKa(fields[1:])
case "Kd":
return dec.parseKd(fields[1:])
case "Ke":
return dec.parseKe(fields[1:])
case "Ks":
return dec.parseKs(fields[1:])
case "Ni":
return dec.parseNi(fields[1:])
case "Ns":
return dec.parseNs(fields[1:])
case "illum":
return dec.parseIllum(fields[1:])
case "map_Kd":
return dec.parseMapKd(fields[1:])
default:
dec.appendWarn(mtlType, "field not supported: "+ltype)
}
return nil
}
// Parses new material definition
// newmtl <mat_name>
func (dec *Decoder) parseNewmtl(fields []string) error {
if len(fields) < 1 {
return dec.formatError("newmtl with no fields")
}
// Checks if material has already been seen
name := fields[0]
mat := dec.Materials[name]
// Creates material descriptor
if mat == nil {
mat = new(Material)
mat.Name = name
dec.Materials[name] = mat
}
dec.matCurrent = mat
return nil
}
// Parses the dissolve factor (opacity)
// d <factor>
func (dec *Decoder) parseDissolve(fields []string) error {
if len(fields) < 1 {
return dec.formatError("'d' with no fields")
}
val, err := strconv.ParseFloat(fields[0], 32)
if err != nil {
return dec.formatError("'d' parse float error")
}
dec.matCurrent.Opacity = float32(val)
return nil
}
// Parses ambient reflectivity:
// Ka r g b
func (dec *Decoder) parseKa(fields []string) error {
if len(fields) < 3 {
return dec.formatError("'Ka' with less than 3 fields")
}
var clrs [3]float32
for pos, f := range fields[:3] {
val, err := strconv.ParseFloat(f, 32)
if err != nil {
return err
}
clrs[pos] = float32(val)
}
dec.matCurrent.Ambient = colors.FromRGBAF32(clrs[0], clrs[1], clrs[2], 1)
return nil
}
// Parses diffuse reflectivity:
// Kd r g b
func (dec *Decoder) parseKd(fields []string) error {
if len(fields) < 3 {
return dec.formatError("'Kd' with less than 3 fields")
}
var clrs [3]float32
for pos, f := range fields[:3] {
val, err := strconv.ParseFloat(f, 32)
if err != nil {
return err
}
clrs[pos] = float32(val)
}
dec.matCurrent.Diffuse = colors.FromRGBAF32(clrs[0], clrs[1], clrs[2], 1)
return nil
}
// Parses emissive color:
// Ke r g b
func (dec *Decoder) parseKe(fields []string) error {
if len(fields) < 3 {
return dec.formatError("'Ke' with less than 3 fields")
}
var clrs [3]float32
for pos, f := range fields[:3] {
val, err := strconv.ParseFloat(f, 32)
if err != nil {
return err
}
clrs[pos] = float32(val)
}
dec.matCurrent.Emissive = colors.FromRGBAF32(clrs[0], clrs[1], clrs[2], 1)
return nil
}
// Parses specular reflectivity:
// Ks r g b
func (dec *Decoder) parseKs(fields []string) error {
if len(fields) < 3 {
return dec.formatError("'Ks' with less than 3 fields")
}
var clrs [3]float32
for pos, f := range fields[:3] {
val, err := strconv.ParseFloat(f, 32)
if err != nil {
return err
}
clrs[pos] = float32(val)
}
dec.matCurrent.Specular = colors.FromRGBAF32(clrs[0], clrs[1], clrs[2], 1)
return nil
}
// Parses optical density, also known as index of refraction
// Ni <optical_density>
func (dec *Decoder) parseNi(fields []string) error {
if len(fields) < 1 {
return dec.formatError("'Ni' with no fields")
}
val, err := strconv.ParseFloat(fields[0], 32)
if err != nil {
return dec.formatError("'Ni' parse float error")
}
dec.matCurrent.Refraction = float32(val)
return nil
}
// Parses specular exponent
// Ns <specular_exponent>
func (dec *Decoder) parseNs(fields []string) error {
if len(fields) < 1 {
return dec.formatError("'Ns' with no fields")
}
val, err := strconv.ParseFloat(fields[0], 32)
if err != nil {
return dec.formatError("'Ns' parse float error")
}
dec.matCurrent.Shininess = float32(val)
return nil
}
// Parses illumination model (0 to 10)
// illum <ilum_#>
func (dec *Decoder) parseIllum(fields []string) error {
if len(fields) < 1 {
return dec.formatError("'illum' with no fields")
}
val, err := strconv.ParseUint(fields[0], 10, 32)
if err != nil {
return dec.formatError("'illum' parse int error")
}
dec.matCurrent.Illum = int(val)
return nil
}
// Parses color texture linked to the diffuse reflectivity of the material
// map_Kd [-options] <filename>
func (dec *Decoder) parseMapKd(fields []string) error {
if len(fields) < 1 {
return dec.formatError("No fields")
}
// values reads the one or two values of the option at index i, which
// are the same with one, and returns the index of the last one.
values := func(i int) (float32, float32, int, error) {
if i+1 >= len(fields) {
return 0, 0, i, dec.formatError("map_Kd option " + fields[i] + " with no value")
}
r1, err := strconv.ParseFloat(fields[i+1], 32)
if err != nil {
return 0, 0, i, dec.formatError("map_Kd option " + fields[i] + " parse float error")
}
i++
r2 := r1
if i+1 < len(fields) {
if rt, err := strconv.ParseFloat(fields[i+1], 32); err == nil {
r2 = rt
i++
}
}
return float32(r1), float32(r2), i, nil
}
nf := len(fields)
for i := 0; i < nf; i++ {
f := fields[i]
if f[0] == '-' {
switch f {
case "-s":
r1, r2, last, err := values(i)
if err != nil {
return err
}
i = last
dec.matCurrent.Tiling.Repeat.Set(r1, r2)
case "-o":
r1, r2, last, err := values(i)
if err != nil {
return err
}
i = last
dec.matCurrent.Tiling.Offset.Set(r1, r2)
}
} else {
dec.matCurrent.MapKd = f
}
}
return nil
}
func (dec *Decoder) formatError(msg string) error {
return fmt.Errorf("%s in line:%d", msg, dec.line)
}
func (dec *Decoder) appendWarn(ftype string, msg string) {
wline := fmt.Sprintf("%s(%d): %s", ftype, dec.line, msg)
dec.Warnings = append(dec.Warnings, wline)
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package xyz
import (
"fmt"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/tree"
)
// AddToLibrary adds given Group to library, using group's name as unique key
// in Library map.
func (sc *Scene) AddToLibrary(gp *Group) {
if sc.Library == nil {
sc.Library = make(map[string]*Group)
}
sc.Library[gp.Name] = gp
gp.Scene = sc
}
// NewInLibrary makes a new Group in library, using given name as unique key
// in Library map.
func (sc *Scene) NewInLibrary(nm string) *Group {
gp := NewGroup()
gp.SetName(nm)
gp.Scene = sc
sc.AddToLibrary(gp)
return gp
}
// AddFromLibrary adds a Clone of named item in the Library under given parent
// in the scenegraph. Returns an error if item not found.
func (sc *Scene) AddFromLibrary(nm string, parent tree.Node) (*Group, error) {
gp, ok := sc.Library[nm]
if !ok {
return nil, fmt.Errorf("Scene AddFromLibrary: Library item: %s not found", nm)
}
nwgp := gp.Clone().(*Group)
parent.AsTree().AddChild(nwgp)
tree.SetUniqueName(nwgp)
sc.SetScene(nwgp) // not parent, which can be the scene (not a Node)
return nwgp, nil
}
// Object is an object cloned from a Library.
type Object struct {
Group
// ObjectName is the name of the object to load from the Library.
ObjectName string
// currentName is the name of the object currently loaded.
// if ObjectName is different than this, it is loaded on Update.
currentName string
}
func (ob *Object) Update() {
if ob.currentName == ob.ObjectName {
return
}
if ob.Scene == nil {
return
}
gp, ok := ob.Scene.Library[ob.ObjectName]
if !ok {
err := fmt.Errorf("Object Update: Library item: %s not found", ob.ObjectName)
errors.Log(err)
}
ob.currentName = ob.ObjectName
nwgp := gp.Clone().(*Group)
ob.DeleteChildren()
ob.AddChild(nwgp)
ob.Scene.SetScene(ob)
}
// Copyright (c) 2019, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package xyz
import (
"image/color"
"cogentcore.org/core/math32"
)
// Light represents a light that illuminates a scene.
// These are stored on the [Scene] object and not within the tree.
type Light interface {
// AsLightBase returns the [LightBase] for this Light,
// which provides the core functionality of a light.
AsLightBase() *LightBase
}
// LightBase provides the core implementation of the [Light] interface.
type LightBase struct { //types:add --setters
// Name is the name of the light, which matters since lights are accessed by name.
Name string
// On is whether the light is turned on. TODO: support this being false.
On bool
// Lumens is the brightness/intensity/strength of the light
// in normalized 0-1 units.
// It is just multiplied by the color, and is convenient
// for easily modulating overall brightness.
Lumens float32 `min:"0" step:"0.1"`
// Color is the color of the light at full intensity.
Color color.RGBA
}
func (lb *LightBase) AsLightBase() *LightBase {
return lb
}
//////// Light types
// Ambient provides diffuse uniform lighting; typically only one of these in a [Scene].
type Ambient struct {
LightBase
}
// NewAmbient adds Ambient to given scene, with given name,
// standard color, and lumens (0-1 normalized).
func NewAmbient(sc *Scene, name string, lumens float32, color LightColors) *Ambient {
lt := &Ambient{}
lt.Name = name
lt.On = true
lt.Color = LightColorMap[color]
lt.Lumens = lumens
sc.AddLight(lt)
return lt
}
// Directional is directional light, which is assumed to project light toward
// the origin based on its position, with no attenuation, like the Sun.
// For rendering, the position is negated and normalized to get the direction
// vector (i.e., absolute distance doesn't matter)
type Directional struct {
LightBase
// position of direct light, assumed to point at the origin
// so this determines direction.
Pos math32.Vector3
}
// NewDirectional adds direct light to given scene, with given name,
// standard color, and lumens (0-1 normalized).
// By default it is located overhead and toward the default camera
// (0, 1, 1), change Pos otherwise.
func NewDirectional(sc *Scene, name string, lumens float32, color LightColors) *Directional {
lt := &Directional{}
lt.Name = name
lt.On = true
lt.Color = LightColorMap[color]
lt.Lumens = lumens
lt.Pos.Set(0, 1, 1)
sc.AddLight(lt)
return lt
}
// ViewDir gets the direction normal vector, pre-computing the view transform.
func (dl *Directional) ViewDir(viewMat *math32.Matrix4) math32.Vector3 {
// adding the 0 in the 4-vector negates any translation factors from the 4 matrix
return dl.Pos.MulMatrix4AsVector4(viewMat, 0)
}
// Point is an omnidirectional light with a position
// and associated decay factors, which divide the light
// intensity as a function of linear and quadratic distance.
// The quadratic factor dominates at longer distances.
type Point struct {
LightBase
// position of light in world coordinates.
Pos math32.Vector3
// Distance linear decay factor, defaults to .1
LinDecay float32
// Distance quadratic decay factor, defaults to .01. Dominates at longer distances.
QuadDecay float32
}
// NewPoint adds point light to given scene, with given name,
// standard color, and lumens (0-1 normalized).
// By default it is located at 0,5,5 (up and between default camera
// and origin) -- set Pos to change.
func NewPoint(sc *Scene, name string, lumens float32, color LightColors) *Point {
lt := &Point{}
lt.Name = name
lt.On = true
lt.Color = LightColorMap[color]
lt.Lumens = lumens
lt.LinDecay = .01
lt.QuadDecay = .001
lt.Pos.Set(0, 5, 5)
sc.AddLight(lt)
return lt
}
// ViewPos gets the position vector, pre-computing the view transform
func (pl *Point) ViewPos(viewMat *math32.Matrix4) math32.Vector3 {
return pl.Pos.MulMatrix4AsVector4(viewMat, 1)
}
// Spot is a spotlight: a light with a position and direction and
// associated decay factors and angles, which divide the light
// intensity as a function of linear and quadratic distance.
// The quadratic factor dominates at longer distances.
type Spot struct {
LightBase
Pose Pose // position and orientation.
// Angular decay factor, defaults to 15.
AngDecay float32
// Cut off angle (in degrees), defaults to 45; max of 90.
CutoffAngle float32 `max:"90" min:"1"`
// Distance linear decay factor, defaults to .01.
LinDecay float32
// Distance quadratic decay factor, defaults to .001; dominates at longer distances.
QuadDecay float32
}
// NewSpot adds spot light to given scene, with given name,
// standard color, and lumens (0-1 normalized).
// By default it is located at 0,5,5 (up and between default camera
// and origin) and pointing at the origin.
// Use the Pose LookAt function to point it at other locations.
// In its unrotated state, it points down the -Z axis (i.e., into the
// scene using default view parameters)
func NewSpot(sc *Scene, name string, lumens float32, color LightColors) *Spot {
lt := &Spot{}
lt.Name = name
lt.On = true
lt.Color = LightColorMap[color]
lt.Lumens = lumens
lt.AngDecay = 15
lt.CutoffAngle = 45
lt.LinDecay = .01
lt.QuadDecay = .001
lt.Pose.Defaults()
lt.Pose.Pos.Set(0, 2, 5)
lt.LookAtOrigin()
sc.AddLight(lt)
return lt
}
// ViewDir gets the direction normal vector, pre-computing the view transform
func (sl *Spot) ViewDir() math32.Vector3 {
idmat := math32.Identity4()
sl.Pose.UpdateMatrix()
sl.Pose.UpdateWorldMatrix(idmat)
// sl.Pose.UpdateMVPMatrix(viewMat, idmat)
vd := math32.Vec3(0, 0, -1).MulMatrix4AsVector4(&sl.Pose.WorldMatrix, 0).Normal()
return vd
}
// LookAt points the spotlight at given target location, using given up direction.
func (sl *Spot) LookAt(target, upDir math32.Vector3) {
sl.Pose.LookAt(target, upDir)
}
// LookAtOrigin points the spotlight at origin with Y axis pointing Up (i.e., standard)
func (sl *Spot) LookAtOrigin() {
sl.LookAt(math32.Vector3{}, math32.Vec3(0, 1, 0))
}
//////// Scene code
// AddLight adds given light to lights
// see NewX for convenience methods to add specific lights
func (sc *Scene) AddLight(lt Light) {
name := lt.AsLightBase().Name
sc.Lights.Add(name, lt)
if sc.IsLive() {
sc.addPhongLight(lt)
}
}
func (sc *Scene) addPhongLight(lt Light) {
clr := math32.NewVector3Color(lt.AsLightBase().Color).MulScalar(lt.AsLightBase().Lumens).SRGBToLinear()
switch l := lt.(type) {
case *Ambient:
sc.Phong.AddAmbient(clr)
case *Directional:
sc.Phong.AddDirectional(clr, l.Pos)
case *Point:
sc.Phong.AddPoint(clr, l.Pos, l.LinDecay, l.QuadDecay)
case *Spot:
sc.Phong.AddSpot(clr, l.Pose.Pos, l.ViewDir(), l.AngDecay, l.CutoffAngle, l.LinDecay, l.QuadDecay)
}
}
// setAllLights configures Phong 3D rendering for current lights.
func (sc *Scene) setAllLights() {
sc.Phong.ResetLights()
for _, lt := range sc.Lights.Values {
sc.addPhongLight(lt)
}
}
//////// Standard Light Colors
// http://planetpixelemporium.com/tutorialpages/light.html
// LightColors are standard light colors for different light sources
type LightColors int32 //enums:enum
const (
DirectSun LightColors = iota
CarbonArc
Halogen
Tungsten100W
Tungsten40W
Candle
Overcast
FluorWarm
FluorStd
FluorCool
FluorFull
FluorGrow
MercuryVapor
SodiumVapor
MetalHalide
)
// LightColorMap provides a map of named light colors
var LightColorMap = map[LightColors]color.RGBA{
DirectSun: {255, 255, 255, 255},
CarbonArc: {255, 250, 244, 255},
Halogen: {255, 241, 224, 255},
Tungsten100W: {255, 214, 170, 255},
Tungsten40W: {255, 197, 143, 255},
Candle: {255, 147, 41, 255},
Overcast: {201, 226, 255, 255},
FluorWarm: {255, 244, 229, 255},
FluorStd: {244, 255, 250, 255},
FluorCool: {212, 235, 255, 255},
FluorFull: {255, 244, 242, 255},
FluorGrow: {255, 239, 247, 255},
MercuryVapor: {216, 247, 255, 255},
SodiumVapor: {255, 209, 178, 255},
MetalHalide: {242, 252, 255, 255},
}
// Copyright (c) 2020, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package xyz
import (
"fmt"
"image/color"
"math"
"cogentcore.org/core/gpu/shape"
"cogentcore.org/core/math32"
"cogentcore.org/core/tree"
)
// Note: Raw line rendering via OpenGL is not very effective
// -- lines are often very thin and appearance is hardware dependent.
//
// The approach below produces consistent results across platforms,
// is very fast, and is "good enough" for most purposes.
// For high-quality vector rendering, use Embed2D with SVG etc.
// Lines are lines rendered as long thin boxes defined by points
// and width parameters. The Mesh must be drawn in the XY plane (i.e., use Z = 0
// or a constant unless specifically relevant to have full 3D variation).
// Rotate the solid to put into other planes.
type Lines struct {
MeshBase
// line points (must be 2 or more)
Points []math32.Vector3
// line width, Y = height perpendicular to line direction, and X = depth
Width math32.Vector2
// optional colors for each point -- actual color interpolates between
Colors []color.RGBA
// if true, connect the first and last points to form a closed shape
Closed bool
}
// LinesClosed specifies whether [NewLines] connects the first and last points:
// [CloseLines] or [OpenLines].
type LinesClosed bool
const (
// CloseLines is used for the closed arg in NewLines:
// connect first and last
CloseLines LinesClosed = true
// OpenLines is used for the closed arg in NewLines:
// don't connect first and last
OpenLines LinesClosed = false
)
// NewLines adds Lines mesh to given scene, with given start, end, and width
func NewLines(sc *Scene, name string, points []math32.Vector3, width math32.Vector2, closed LinesClosed) *Lines {
ln := &Lines{}
ln.Name = name
ln.Points = points
ln.Width = width
ln.Closed = bool(closed)
sc.SetMesh(ln)
return ln
}
func (ln *Lines) MeshSize() (numVertex, nIndex int, hasColor bool) {
ln.NumVertex, ln.NumIndex = shape.LinesN(len(ln.Points), ln.Closed)
ln.HasColor = len(ln.Colors) > 0
return ln.NumVertex, ln.NumIndex, ln.HasColor
}
func (ln *Lines) Set(vertex, normal, texcoord, clrs math32.ArrayF32, indexArray math32.ArrayU32) {
pos := math32.Vector3{}
bb := shape.SetLines(vertex, normal, texcoord, indexArray, 0, 0, ln.Points, ln.Width, ln.Closed, pos)
ln.BBox.SetBounds(bb.Min, bb.Max)
// todo: colors!
}
// UnitLineMesh returns the unit-sized line mesh, of name LineMeshName
func UnitLineMesh(sc *Scene) *Lines {
lm, _ := sc.MeshByName(LineMeshName)
if lm != nil {
return lm.(*Lines)
}
lmm := NewLines(sc, LineMeshName, []math32.Vector3{{X: -.5, Y: 0, Z: 0}, {X: .5, Y: 0, Z: 0}}, math32.Vec2(1, 1), OpenLines)
return lmm
}
// UnitConeMesh returns the unit-sized cone mesh, of name ConeMeshName-segs
func UnitConeMesh(sc *Scene, segs int) *Cylinder {
nm := fmt.Sprintf("%s-%d", ConeMeshName, segs)
cm, _ := sc.MeshByName(nm)
if cm != nil {
return cm.(*Cylinder)
}
cmm := NewCone(sc, nm, 1, 1, segs, 1, WithBottom)
return cmm
}
// SetLineStartEnd sets line Pose such that it starts / ends at given poitns.
func SetLineStartEnd(pose *Pose, st, ed math32.Vector3) {
wd := pose.Scale.Y
d := ed.Sub(st)
midp := st.Add(d.DivScalar(2))
pose.Pos = midp
dst := st.DistanceTo(ed)
pose.Scale.Set(dst, wd, wd)
dn := d.Normal()
pose.Quat.SetFromUnitVectors(math32.Vec3(1, 0, 0), dn)
}
// ArrowStart specifies whether [InitArrow] adds an arrow at the start:
// [StartArrow] or [NoStartArrow].
type ArrowStart bool
// ArrowEnd specifies whether [InitArrow] adds an arrow at the end: [EndArrow]
// or [NoEndArrow].
type ArrowEnd bool
const (
// StartArrow specifies to add a starting arrow
StartArrow ArrowStart = true
// NoStartArrow specifies not to add a starting arrow
NoStartArrow ArrowStart = false
// EndArrow specifies to add a ending arrow
EndArrow ArrowEnd = true
// EndArrow specifies not to add a ending arrow
NoEndArrow ArrowEnd = false
)
// InitLine is an Init function (e.g., for [tree] Maker functions)
// for making a line between two specified points, using a shared
// mesh unit line, which is rotated and positioned
// to go between the designated points.
func InitLine(ln *Solid, st, ed math32.Vector3, width float32, clr color.RGBA) {
lm := UnitLineMesh(ln.Scene)
ln.SetMesh(lm)
ln.isLinear = true
ln.Pose.Scale.Set(1, width, width)
SetLineStartEnd(&ln.Pose, st, ed)
ln.Material.Color = clr
}
// InitArrow returns an Init function (e.g., for [tree] Maker functions)
// for making a group with a new line + cone between two specified points,
// using shared mesh unit line and arrow heads, which are rotated and
// positioned to go between the designated points.
// The arrowSize is a multiplier on the width for the radius and length
// of the arrow head, with width providing an additional multiplicative
// factor for width to achieve "fat" vs. "thin" arrows.
// arrowSegs determines how many faces there are on the arrowhead
// 4 = a 4-sided pyramid, etc.
func InitArrow(g *Group, st, ed math32.Vector3, width float32, clr color.RGBA, startArrow ArrowStart, endArrow ArrowEnd, arrowSize, arrowWidth float32, arrowSegs int) {
cm := UnitConeMesh(g.Scene, arrowSegs)
g.isLinear = true
d := ed.Sub(st)
dst := d.Length()
awd := arrowSize * arrowWidth
asz := (arrowSize * width) / dst
hasz := 0.5 * asz
g.Maker(func(p *tree.Plan) {
tree.Add(p, func(ln *Solid) {
InitLine(ln, st, ed, width, clr)
ln.Pose.SetIdentity()
switch {
case startArrow == StartArrow && endArrow == EndArrow:
ln.Pose.Scale.X -= 2 * asz
case startArrow == StartArrow:
ln.Pose.Scale.X -= asz
ln.Pose.Pos.X += hasz
case endArrow == EndArrow:
ln.Pose.Scale.X -= asz
ln.Pose.Pos.X -= hasz
}
})
g.Pose.Scale.Set(1, width, width) // group does everything
SetLineStartEnd(&g.Pose, st, ed)
if startArrow {
tree.Add(p, func(ar *Solid) {
ar.SetMesh(cm)
ar.Pose.Scale.Set(awd, asz, awd) // Y is up
ar.Pose.Quat.SetFromAxisAngle(math32.Vec3(0, 0, 1), math.Pi/2) // rotate from XY up to -X
ar.Pose.Pos = math32.Vec3(-0.5+hasz, 0, 0)
ar.Material.Color = clr
})
}
if endArrow {
tree.Add(p, func(ar *Solid) {
ar.SetMesh(cm)
ar.Pose.Scale.Set(awd, asz, awd)
ar.Pose.Quat.SetFromAxisAngle(math32.Vec3(0, 0, 1), -math.Pi/2) // rotate from XY up to +X
ar.Pose.Pos = math32.Vec3(0.5-hasz, 0, 0)
ar.Material.Color = clr
})
}
})
}
// NewLineBoxMeshes adds two Meshes defining the edges of a Box.
// Meshes are named meshNm+"-front" and meshNm+"-side" -- need to be
// initialized, e.g., using sc.InitMesh()
func NewLineBoxMeshes(sc *Scene, meshNm string, bbox math32.Box3, width float32) (front, side *Lines) {
wd := math32.Vec2(width, width)
sz := bbox.Size()
hSz := sz.MulScalar(0.5)
// front mesh
fbl := math32.Vec3(-hSz.X, -hSz.Y, 0)
ftl := math32.Vec3(-hSz.X, hSz.Y, 0)
ftr := math32.Vec3(hSz.X, hSz.Y, 0)
fbr := math32.Vec3(hSz.X, -hSz.Y, 0)
front = NewLines(sc, meshNm+"-front", []math32.Vector3{fbl, ftl, ftr, fbr}, wd, CloseLines)
// side mesh in XY plane, Z -> X
sbl := math32.Vec3(-hSz.Z, -hSz.Y, 0)
stl := math32.Vec3(-hSz.Z, hSz.Y, 0)
str := math32.Vec3(hSz.Z, hSz.Y, 0)
sbr := math32.Vec3(hSz.Z, -hSz.Y, 0)
side = NewLines(sc, meshNm+"-side", []math32.Vector3{sbl, stl, str, sbr}, wd, CloseLines)
return
}
// Activity specifies whether nodes are flagged as inactive (not selectable):
// [Inactive] or [Active].
type Activity bool
const (
// Inactive is used for args indicating if node should be inactive
Inactive Activity = true
// Active is used for args indicating if node should be inactive or not
Active Activity = false
)
// InitLineBox returns an Init function (e.g., for [tree] Maker functions)
// that adds a new [Group] with [Solid]s and two Meshes defining the edges of a Box.
// This can be used for drawing a selection box around a Node in the scene,
// for example.
// offset is an arbitrary offset (for composing shapes).
// Meshes are named meshNm+"-front" and meshNm+"-side" -- need to be
// initialized, e.g., using sc.InitMesh()
// inactive indicates whether the box and solids should be flagged as inactive
// (not selectable).
func InitLineBox(g *Group, meshNm string, bbox math32.Box3, width float32, clr color.RGBA, inactive Activity) {
sz := bbox.Size()
hSz := sz.MulScalar(0.5)
front, side := NewLineBoxMeshes(g.Scene, meshNm, bbox, width)
ctr := bbox.Min.Add(hSz)
g.Pose.Pos = ctr
bs := NewSolid(g).SetMesh(front).SetColor(clr)
bs.SetName("back")
bs.Pose.Pos.Set(0, 0, -hSz.Z)
ls := NewSolid(g).SetMesh(side).SetColor(clr)
ls.SetName("left")
ls.Pose.Pos.Set(-hSz.X, 0, 0)
ls.Pose.SetAxisRotation(0, 1, 0, 90)
rs := NewSolid(g).SetMesh(side).SetColor(clr)
rs.SetName("right")
rs.Pose.Pos.Set(hSz.X, 0, 0)
rs.Pose.SetAxisRotation(0, 1, 0, -90)
fs := NewSolid(g).SetMesh(front).SetColor(clr)
fs.SetName("front")
fs.Pose.Pos.Set(0, 0, hSz.Z)
// todo:
// if inactive {
// g.SetDisabled()
// bs.SetDisabled()
// ls.SetDisabled()
// rs.SetDisabled()
// fs.SetDisabled()
// }
}
// Copyright (c) 2019, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package xyz
import (
"image/color"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/colors"
"cogentcore.org/core/gpu/phong"
)
// Material describes the material properties of a surface (colors, shininess, texture)
// i.e., phong lighting parameters.
// Main color is used for both ambient and diffuse color, and alpha component
// is used for opacity. The Emissive color is only for glowing objects.
// The Specular color is always white (multiplied by light color).
// Textures are stored on the Scene and accessed by name
type Material struct { //types:add -setters
// Color is the main color of surface, used for both ambient and diffuse color in standard Phong model -- alpha component determines transparency -- note that transparent objects require more complex rendering
Color color.RGBA
// Emissive is the color that surface emits independent of any lighting -- i.e., glow -- can be used for marking lights with an object
Emissive color.RGBA
// Shiny is the specular shininess factor -- how focally vs. broad the surface shines back directional light -- this is an exponential factor, with 0 = very broad diffuse reflection, and higher values (typically max of 128 or so but can go higher) having a smaller more focal specular reflection. Also set Reflective factor to change overall shininess effect.
Shiny float32
// Reflective is the specular reflectiveness factor -- how much it shines back directional light. The specular reflection color is always white * the incoming light.
Reflective float32
// Bright is an overall multiplier on final computed color value -- can be used to tune the overall brightness of various surfaces relative to each other for a given set of lighting parameters
Bright float32
// TextureName is the name of the texture to provide color for the surface.
TextureName TextureName `set:"-"`
// Tiling is the texture tiling parameters: repeat and offset.
Tiling phong.Tiling `display:"inline"`
// CullBack indicates to cull the back-facing surfaces.
CullBack bool
// CullFront indicates to cull the front-facing surfaces.
CullFront bool
// Texture is the cached [Texture] object set based on [Material.TextureName].
Texture Texture `set:"-" display:"-"`
}
// Defaults sets default surface parameters
func (mt *Material) Defaults() {
mt.Color = colors.FromRGB(128, 128, 128)
mt.Emissive = color.RGBA{0, 0, 0, 0}
mt.Shiny = 30
mt.Reflective = 1
mt.Bright = 1
mt.Tiling.Defaults()
mt.CullBack = true
}
func (mt *Material) ShowShow(field string) bool {
switch field {
case "Tiling":
return mt.TextureName != ""
}
return true
}
// Disconnect resets pointers etc
func (mt *Material) Disconnect() {
mt.Texture = nil
}
func (mt *Material) phongColors() *phong.Colors {
clr := phong.NewColors(mt.Color, mt.Emissive, mt.Shiny, mt.Reflective, mt.Bright)
clr.Tiling = mt.Tiling
return clr
}
func (mt Material) String() string {
return reflectx.StringJSON(mt)
}
// IsTransparent returns true if texture says it is, or if color has alpha < 255
func (mt *Material) IsTransparent() bool {
if mt.Texture != nil {
return mt.Texture.AsTextureBase().Transparent
}
return mt.Color.A < 255
}
// NoTexture resets any texture setting that might have been set
func (mt *Material) NoTexture() {
mt.TextureName = ""
mt.Texture = nil
}
// SetTextureName sets material to use given texture name
// (textures are accessed by name on Scene).
// If name is empty, then texture is reset
func (mt *Material) SetTextureName(sc *Scene, texName string) error {
if texName == "" {
mt.NoTexture()
return nil
}
tx, err := sc.TextureByName(texName)
if errors.Log(err) != nil {
return err
}
mt.TextureName = TextureName(texName)
mt.Texture = tx
return nil
}
// SetTexture sets material to use given texture
func (mt *Material) SetTexture(tex Texture) *Material {
mt.Texture = tex
if mt.Texture != nil {
mt.TextureName = TextureName(mt.Texture.AsTextureBase().Name)
} else {
mt.TextureName = ""
}
return mt
}
// Validate does overall material validation, including checking that material
// texture is valid if set
func (mt *Material) Validate(sc *Scene) error {
if mt.Bright == 0 {
mt.Bright = 1
}
mt.Tiling.Defaults()
if mt.TextureName == "" {
mt.Texture = nil
} else if mt.Texture == nil || mt.Texture.AsTextureBase().Name != string(mt.TextureName) {
err := mt.SetTextureName(sc, string(mt.TextureName))
if err != nil {
return err
}
}
return nil
}
// Copyright (c) 2019, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package xyz
import (
"fmt"
"cogentcore.org/core/gpu/shape"
"cogentcore.org/core/math32"
)
// MeshName is a [Mesh] name. This type provides an automatic GUI chooser for meshes.
// It is used on [Solid] to link to meshes by name.
type MeshName string
// Mesh parametrizes the mesh-based shape used for rendering a [Solid],
// using the [shape.Mesh] interface for basic shape data.
// Only indexed triangle meshes are supported.
// All Meshes must know in advance the number of vertex and index points
// they require, and the Set method writes the mesh data to arrays of
// appropriate vector data.
// Per-vertex Color is optional.
type Mesh interface {
shape.Mesh
// AsMeshBase returns the [MeshBase] for this Mesh,
// which provides the core functionality of a mesh.
AsMeshBase() *MeshBase
}
// MeshBase provides the core implementation of the [Mesh] interface.
type MeshBase struct { //types:add -setters
// Name is the name of the mesh. [Mesh]es are linked to [Solid]s
// by name so this matters.
Name string
// NumVertex is the number of [math32.Vector3] vertex points. This always
// includes [math32.Vector3] normals and [math32.Vector2] texture coordinates.
// This is only valid after [Mesh.Sizes] has been called.
NumVertex int `set:"-"`
// NumIndex is the number of [math32.ArrayU32] indexes.
// This is only valid after [Mesh.Sizes] has been called.
NumIndex int `set:"-"`
// HasColor is whether the mesh has per-vertex colors
// as [math32.Vector4] per vertex.
HasColor bool
// Transparent is whether the color has transparency;
// not worth checking manually. This is only valid if
// [MeshBase.HasColor] is true.
Transparent bool
// BBox has the computed bounding-box and other gross solid properties.
BBox BBox `set:"-"`
}
func (ms *MeshBase) AsMeshBase() *MeshBase {
return ms
}
func (ms *MeshBase) MeshSize() (numVertex, numIndex int, hasColor bool) {
return ms.NumVertex, ms.NumIndex, ms.HasColor
}
func (ms *MeshBase) MeshBBox() math32.Box3 {
return ms.BBox.BBox
}
func (ms *MeshBase) Offsets() (vtxOffset, idxOffset int) {
return 0, 0
}
func (ms *MeshBase) SetOffsets(vtxOffset, idxOffset int) {
// nop
}
// ComputeNorms computes the normals of the mesh (not implemented yet).
func (ms *MeshBase) ComputeNorms(pos, norm math32.ArrayF32) {
// norm := math32.Normal(vtxs[0], vtxs[1], vtxs[2])
}
////////////////////////////////////////////////////////////////////////
// Scene management
// SetMesh sets / updates the given mesh, updating any existing
// mesh of the same name.
// See NewX for convenience methods to add specific shapes.
func (sc *Scene) SetMesh(ms Mesh) {
name := ms.AsMeshBase().Name
sc.Meshes.Add(name, ms) // does replace
if sc.IsLive() {
sc.Phong.SetMesh(name, ms)
}
}
// setAllMeshes is called when the Phong system first is activated.
func (sc *Scene) setAllMeshes() {
ph := sc.Phong
for i, nm := range sc.Meshes.Keys {
ph.SetMesh(nm, sc.Meshes.Values[i])
}
}
// AddMeshUnique adds given mesh, ensuring that it has
// a unique name if one already exists.
// This is used e.g., in loading external files which may not
// obey this constraint.
func (sc *Scene) AddMeshUnique(ms Mesh) {
nm := ms.AsMeshBase().Name
_, err := sc.MeshByName(nm)
if err == nil {
nm += fmt.Sprintf("_%d", sc.Meshes.Len())
ms.AsMeshBase().SetName(nm)
}
sc.SetMesh(ms)
}
// MeshByName looks for mesh by name, returning error if not found.
func (sc *Scene) MeshByName(nm string) (Mesh, error) {
ms, ok := sc.Meshes.AtTry(nm)
if ok {
return ms, nil
}
return nil, fmt.Errorf("Mesh named: %v not found in Scene: %v", nm, sc.Name)
}
// MeshList returns a list of available meshes (e.g., for chooser)
func (sc *Scene) MeshList() []string {
return sc.Meshes.Keys
}
// ResetMeshes removes all meshes.
// Use this to remove unused meshes after significant update.
// Note that there is no Delete mechanism because the GPU Phong
// system does not support it for efficiency reasons.
func (sc *Scene) ResetMeshes() {
if sc.IsLive() {
sc.Phong.ResetMeshes()
}
sc.Meshes.Reset()
}
// PlaneMesh2D returns the special Plane mesh used for Text2D and Embed2D
// (creating it if it does not yet exist).
// This is a 1x1 plane with a normal pointing in +Z direction.
func (sc *Scene) PlaneMesh2D() Mesh {
nm := Plane2DMeshName
tm, err := sc.MeshByName(nm)
if err == nil {
return tm
}
tmp := NewPlane(sc, nm, 1, 1)
tmp.NormAxis = math32.Z
tmp.NormalNeg = false
return tmp
}
///////////////////////////////////////////////////////////////
// GenMesh
// GenMesh is a generic, arbitrary Mesh, storing its values
type GenMesh struct {
MeshBase
Vertex math32.ArrayF32
Normal math32.ArrayF32
TexCoord math32.ArrayF32
Color math32.ArrayF32
Index math32.ArrayU32
}
func (ms *GenMesh) MeshSize() (numVertex, nIndex int, hasColor bool) {
ms.NumVertex = len(ms.Vertex) / 3
ms.NumIndex = len(ms.Index)
ms.HasColor = len(ms.Color) > 0
return ms.NumVertex, ms.NumIndex, ms.HasColor
}
func (ms *GenMesh) Set(vertex, normal, texcoord, clrs math32.ArrayF32, index math32.ArrayU32) {
copy(vertex, ms.Vertex)
copy(normal, ms.Normal)
copy(texcoord, ms.TexCoord)
if ms.HasColor {
copy(clrs, ms.Color)
}
copy(index, ms.Index)
bb := shape.BBoxFromVtxs(ms.Vertex, 0, ms.NumVertex)
ms.BBox.SetBounds(bb.Min, bb.Max)
}
// Copyright (c) 2019, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package xyz
import (
"fmt"
"image"
"log"
"reflect"
"cogentcore.org/core/math32"
"cogentcore.org/core/tree"
"github.com/oliverbestmann/webgpu/wgpu"
)
// Node is the common interface for all xyz 3D tree nodes.
// [Solid] and [Group] are the two main types of nodes,
// which both extend [NodeBase] for the core functionality.
type Node interface {
tree.Node
// AsNodeBase returns the [NodeBase] for our node, which gives
// access to all the base-level data structures and methods
// without requiring interface methods.
AsNodeBase() *NodeBase
// IsSolid returns true if this is an [Solid] node (otherwise a [Group]).
IsSolid() bool
// AsSolid returns the node as a [Solid] (nil if not).
AsSolid() *Solid
// Validate checks that scene element is valid.
Validate() error
// UpdateWorldMatrix updates this node's local and world matrix based on parent's world matrix.
UpdateWorldMatrix(parWorld *math32.Matrix4)
// UpdateMeshBBox updates the Mesh-based BBox info for all nodes.
// groups aggregate over elements. It is called from WalkPost traversal.
UpdateMeshBBox()
// IsVisible provides the definitive answer as to whether a given node
// is currently visible. It is only entirely valid after a render pass
// for widgets in a visible window, but it checks the window and viewport
// for their visibility status as well, which is available always.
// Non-visible nodes are automatically not rendered and not connected to
// window events. The Invisible flag is one key element of the IsVisible
// calculus; it is set by e.g., TabView for invisible tabs, and is also
// set if a widget is entirely out of render range. But again, use
// IsVisible as the main end-user method.
// For robustness, it recursively calls the parent; this is typically
// a short path; propagating the Invisible flag properly can be
// very challenging without mistakenly overwriting invisibility at various
// levels.
IsVisible() bool
// IsTransparent returns true if solid has transparent color.
IsTransparent() bool
// Update does [tree] updating to dynamically update nodes / tree config.
Update()
// Config configures the node data for gpu rendering.
Config()
// RenderClass returns the class of rendering for this solid.
// It is used for organizing the ordering of rendering.
RenderClass() RenderClasses
// PreRender is called by Scene Render to upload
// all the object data to the Phong renderer.
PreRender()
// Render is called by Scene Render to actually render.
Render(rp *wgpu.RenderPassEncoder)
}
// NodeBase is the basic 3D tree node, which has the full transform information
// relative to parent, and computed bounding boxes, etc.
// It implements the [Node] interface and contains the core functionality
// common to all 3D nodes.
type NodeBase struct {
tree.NodeBase
// Invisible is whether this node is invisible.
Invisible bool
// Pose is the complete specification of position and orientation.
Pose Pose `set:"-"`
// Scene is the cached [Scene].
Scene *Scene `copier:"-" set:"-"`
// mesh-based local bounding box (aggregated for groups)
MeshBBox BBox `edit:"-" copier:"-" json:"-" xml:"-" set:"-"`
// world coordinates bounding box
WorldBBox BBox `edit:"-" copier:"-" json:"-" xml:"-" set:"-"`
// normalized display coordinates bounding box, used for frustrum clipping
NDCBBox math32.Box3 `edit:"-" copier:"-" json:"-" xml:"-" set:"-"`
// raw original bounding box for the widget within its parent Scene.
// This is prior to intersecting with Frame bounds.
BBox image.Rectangle `edit:"-" copier:"-" json:"-" xml:"-" set:"-"`
// 2D bounding box for region occupied within Scene Frame that we render onto.
// This is BBox intersected with Frame bounds.
SceneBBox image.Rectangle `edit:"-" copier:"-" json:"-" xml:"-" set:"-"`
// isLinear indicates that this element contains a line-like shape,
// which engages a more selective event processing logic to determine
// if the node was selected based on a mouse click point.
isLinear bool
}
// AsNode converts the given tree node to a [Node] and [NodeBase],
// returning nil if that is not possible.
func AsNode(n tree.Node) (Node, *NodeBase) {
ni, ok := n.(Node)
if ok {
return ni, ni.AsNodeBase()
}
return nil, nil
}
// AsNodeBase returns a generic NodeBase for our node, giving generic
// access to all the base-level data structures without requiring
// interface methods.
func (nb *NodeBase) AsNodeBase() *NodeBase {
return nb
}
func (nb *NodeBase) Init() {
nb.Updater(nb.UpdateFromMake)
}
func (nb *NodeBase) Update() {
nb.RunUpdaters()
}
// OnAdd is called when nodes are added to a parent.
// It sets the scene of the node to that of its parent.
// It should be called by all other OnAdd functions defined by node types.
func (nb *NodeBase) OnAdd() {
if nb.Parent == nil {
return
}
if sc, ok := nb.Parent.(*Scene); ok {
nb.Scene = sc
return
}
if _, pnb := AsNode(nb.Parent); pnb != nil {
nb.Scene = pnb.Scene
return
}
}
func (nb *NodeBase) BaseInterface() reflect.Type {
return reflect.TypeFor[NodeBase]()
}
func (nb *NodeBase) IsSolid() bool {
return false
}
func (nb *NodeBase) AsSolid() *Solid {
return nil
}
func (nb *NodeBase) Validate() error {
return nil
}
func (nb *NodeBase) IsVisible() bool {
if nb == nil || nb.This == nil || nb.Invisible {
return false
}
return true
}
func (nb *NodeBase) IsTransparent() bool {
return false
}
// UpdateWorldMatrix updates this node's world matrix based on parent's world matrix.
// If a nil matrix is passed, then the previously set parent world matrix is used.
func (nb *NodeBase) UpdateWorldMatrix(parWorld *math32.Matrix4) {
nb.Pose.UpdateMatrix() // note: can do this in special ways to bake in other
// automatic transforms as needed
nb.Pose.UpdateWorldMatrix(parWorld)
}
// UpdateMVPMatrix updates this node's MVP matrix based on given view, projection matricies from camera.
// Called during rendering.
func (nb *NodeBase) UpdateMVPMatrix(viewMat, projectionMat *math32.Matrix4) {
nb.Pose.UpdateMVPMatrix(viewMat, projectionMat)
}
// UpdateBBox2D updates this node's 2D bounding-box information based on scene
// size and min offset position.
func (nb *NodeBase) UpdateBBox2D(size math32.Vector2) {
off := math32.Vector2{}
nb.WorldBBox.BBox = nb.MeshBBox.BBox.MulMatrix4(&nb.Pose.WorldMatrix)
nb.NDCBBox = nb.MeshBBox.BBox.MVProjToNDC(&nb.Pose.MVPMatrix)
Wmin := nb.NDCBBox.Min.NDCToWindow(size, off, 0, 1, math32.FlipY)
Wmax := nb.NDCBBox.Max.NDCToWindow(size, off, 0, 1, math32.FlipY)
// BBox is always relative to scene
nb.BBox = image.Rectangle{Min: image.Point{int(Wmin.X), int(Wmax.Y)}, Max: image.Point{int(Wmax.X), int(Wmin.Y)}}
// note: BBox is inaccurate for objects extending behind camera
if nb.Scene == nil {
fmt.Println(nb, "Error: scene is nil")
return
}
isvis := nb.Scene.Camera.Frustum.IntersectsBox(nb.WorldBBox.BBox)
if isvis { // filter out invisible at objbbox level
scbounds := image.Rectangle{Max: nb.Scene.Geom.Size}
bbvis := nb.BBox.Intersect(scbounds)
nb.SceneBBox = bbvis
} else {
// fmt.Printf("not vis: %v wbb: %v\n", nb.Name, nb.WorldBBox.BBox)
nb.SceneBBox = image.Rectangle{}
}
}
// RayPick converts a given 2D point in scene image coordinates
// into a ray from the camera position pointing through line of sight of camera
// into *local* coordinates of the solid.
// This can be used to find point of intersection in local coordinates relative
// to a given plane of interest, for example (see Ray methods for intersections).
// To convert mouse window-relative coords into scene-relative coords
// subtract the sc.ObjBBox.Min which includes any scrolling effects
func (nb *NodeBase) RayPick(pos image.Point) math32.Ray {
// nb.PoseMu.RLock()
// nb.Sc.Camera.CamMu.RLock()
sz := nb.Scene.Geom.Size
size := math32.Vec2(float32(sz.X), float32(sz.Y))
fpos := math32.Vec2(float32(pos.X), float32(pos.Y))
ndc := fpos.WindowToNDC(size, math32.Vector2{}, math32.FlipY)
var err error
ndc.Z = -1 // at closest point
cdir := math32.Vector4FromVector3(ndc, 1).MulMatrix4(&nb.Scene.Camera.InvProjectionMatrix)
cdir.Z = -1
cdir.W = 0 // vec
// get world position / transform of camera: matrix is inverse of ViewMatrix
wdir := cdir.MulMatrix4(&nb.Scene.Camera.Pose.Matrix)
wpos := nb.Scene.Camera.Pose.Matrix.Pos()
// nb.Sc.Camera.CamMu.RUnlock()
invM, err := nb.Pose.WorldMatrix.Inverse()
// nb.PoseMu.RUnlock()
if err != nil {
log.Println(err)
}
lpos := math32.Vector4FromVector3(wpos, 1).MulMatrix4(invM)
ldir := wdir.MulMatrix4(invM)
ldir.SetNormal()
ray := math32.NewRay(math32.Vec3(lpos.X, lpos.Y, lpos.Z), math32.Vec3(ldir.X, ldir.Y, ldir.Z))
return *ray
}
// WorldMatrix returns the world matrix for this node
func (nb *NodeBase) WorldMatrix() *math32.Matrix4 {
return &nb.Pose.WorldMatrix
}
// NormDCBBox returns the normalized display coordinates bounding box
// which is used for clipping.
func (nb *NodeBase) NormDCBBox() math32.Box3 {
return nb.NDCBBox
}
func (nb *NodeBase) Config() {
// nop by default; could connect to scene for update signals or something
}
func (nb *NodeBase) PreRender() {
// nop
}
func (nb *NodeBase) Render(rp *wgpu.RenderPassEncoder) {
// nop
}
// SetPosePos sets Pose.Pos position to given value
func (nb *NodeBase) SetPosePos(pos math32.Vector3) {
nb.Pose.Pos = pos
}
// SetPoseScale sets Pose.Scale scale to given value
func (nb *NodeBase) SetPoseScale(scale math32.Vector3) {
nb.Pose.Scale = scale
}
// SetPoseQuat sets Pose.Quat to given value
func (nb *NodeBase) SetPoseQuat(quat math32.Quat) {
nb.Pose.Quat = quat
}
// TrackCamera moves this node to pose of camera
func (nb *NodeBase) TrackCamera() {
nb.Pose.CopyFrom(&nb.Scene.Camera.Pose)
UpdateWorldMatrix(nb.This)
}
// TrackLight moves node to position of light of given name.
// For Spot, copies entire Pose. Does not work for Ambient light
// which has no position information.
func (nb *NodeBase) TrackLight(lightName string) error {
lt, ok := nb.Scene.Lights.AtTry(lightName)
if !ok {
return fmt.Errorf("xyz Node: %v TrackLight named: %v not found", nb.Path(), lightName)
}
switch l := lt.(type) {
case *Directional:
nb.Pose.Pos = l.Pos
case *Point:
nb.Pose.Pos = l.Pos
case *Spot:
nb.Pose.CopyFrom(&l.Pose)
}
return nil
}
// Copyright (c) 2019, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package xyz
import (
"cogentcore.org/core/math32"
)
// Pose contains the full specification of position and orientation,
// always relevant to the parent element.
type Pose struct {
// position of center of element (relative to parent)
Pos math32.Vector3
// scale (relative to parent)
Scale math32.Vector3
// Node rotation specified as a Quat (relative to parent)
Quat math32.Quat `display:"inline"`
// Local matrix. Contains all position/rotation/scale information (relative to parent)
Matrix math32.Matrix4 `display:"-"`
// Parent's world matrix -- we cache this so that we can independently update our own matrix
ParMatrix math32.Matrix4 `display:"-"`
// World matrix. Contains all absolute position/rotation/scale information (i.e. relative to very top parent, generally the scene)
WorldMatrix math32.Matrix4 `display:"-"`
// model * view matrix -- tranforms into camera-centered coords
MVMatrix math32.Matrix4 `display:"-"`
// model * view * projection matrix -- full final render matrix
MVPMatrix math32.Matrix4 `display:"-"`
// normal matrix has no offsets, for normal vector rotation only, based on MVMatrix
NormMatrix math32.Matrix3 `display:"-"`
}
// Defaults sets defaults only if current values are nil
func (ps *Pose) Defaults() {
if ps.Scale == (math32.Vector3{}) {
ps.Scale.Set(1, 1, 1)
}
if ps.Quat.IsNil() {
ps.Quat.SetIdentity()
}
}
// SetIdentity sets the Pose to the identity transform.
func (ps *Pose) SetIdentity() {
ps.Pos.Set(0, 0, 0)
ps.Scale.Set(1, 1, 1)
ps.Quat.SetIdentity()
}
// CopyFrom copies just the pose information from the other pose, critically
// not copying the ParMatrix so that is preserved in the receiver.
func (ps *Pose) CopyFrom(op *Pose) {
ps.Pos = op.Pos
ps.Scale = op.Scale
ps.Quat = op.Quat
ps.UpdateMatrix()
}
func (ps *Pose) String() string {
return "Pos: " + ps.Pos.String() + "; Scale: " + ps.Scale.String() + "; Quat: " + ps.Quat.String()
}
// GenGoSet returns code to set values at given path (var.member etc)
func (ps *Pose) GenGoSet(path string) string {
return ps.Pos.GenGoSet(path+".Pos") + "; " + ps.Scale.GenGoSet(path+".Scale") + "; " + ps.Quat.GenGoSet(path+".Quat")
}
// UpdateMatrix updates the local transform matrix based on its position, quaternion, and scale.
// Also checks for degenerate nil values
func (ps *Pose) UpdateMatrix() {
ps.Defaults()
ps.Matrix.SetTransform(ps.Pos, ps.Quat, ps.Scale)
}
// MulMatrix multiplies current pose Matrix by given Matrix, and re-extracts the
// Pos, Scale, Quat from resulting matrix.
func (ps *Pose) MulMatrix(mat *math32.Matrix4) {
ps.Matrix.SetMul(mat)
pos, quat, sc := ps.Matrix.Decompose()
ps.Pos = pos
ps.Quat = quat
ps.Scale = sc
}
// UpdateWorldMatrix updates the world transform matrix based on Matrix and parent's WorldMatrix.
// Does NOT call UpdateMatrix so that can include other factors as needed.
func (ps *Pose) UpdateWorldMatrix(parWorld *math32.Matrix4) {
if parWorld != nil {
ps.ParMatrix.CopyFrom(parWorld)
}
ps.WorldMatrix.MulMatrices(&ps.ParMatrix, &ps.Matrix)
}
// UpdateMVPMatrix updates the model * view, * projection matricies based on camera view, projection matricies
// Assumes that WorldMatrix has been updated
func (ps *Pose) UpdateMVPMatrix(viewMat, projectionMat *math32.Matrix4) {
ps.MVMatrix.MulMatrices(viewMat, &ps.WorldMatrix)
ps.NormMatrix.SetNormalMatrix(&ps.MVMatrix)
ps.MVPMatrix.MulMatrices(projectionMat, &ps.MVMatrix)
}
///////////////////////////////////////////////////////
// Moving
// Note: you can just directly add to .Pos too..
// MoveOnAxis moves (translates) the specified distance on the specified local axis,
// relative to the current rotation orientation.
func (ps *Pose) MoveOnAxis(x, y, z, dist float32) {
ps.Pos.SetAdd(ps.Quat.MulVector(math32.Vec3(x, y, z).Normal()).MulScalar(dist))
}
// MoveOnAxisAbs moves (translates) the specified distance on the specified local axis,
// in absolute X,Y,Z coordinates.
func (ps *Pose) MoveOnAxisAbs(x, y, z, dist float32) {
ps.Pos.SetAdd(math32.Vec3(x, y, z).Normal().MulScalar(dist))
}
///////////////////////////////////////////////////////
// Rotating
// SetEulerRotation sets the rotation in Euler angles (degrees).
func (ps *Pose) SetEulerRotation(x, y, z float32) {
ps.Quat.SetFromEuler(math32.Vec3(x, y, z).MulScalar(math32.DegToRadFactor))
}
// SetEulerRotationRad sets the rotation in Euler angles (radians).
func (ps *Pose) SetEulerRotationRad(x, y, z float32) {
ps.Quat.SetFromEuler(math32.Vec3(x, y, z))
}
// EulerRotation returns the current rotation in Euler angles (degrees).
func (ps *Pose) EulerRotation() math32.Vector3 {
return ps.Quat.ToEuler().MulScalar(math32.RadToDegFactor)
}
// EulerRotationRad returns the current rotation in Euler angles (radians).
func (ps *Pose) EulerRotationRad() math32.Vector3 {
return ps.Quat.ToEuler()
}
// SetAxisRotation sets rotation from local axis and angle in degrees.
func (ps *Pose) SetAxisRotation(x, y, z, angle float32) {
ps.Quat.SetFromAxisAngle(math32.Vec3(x, y, z), math32.DegToRad(angle))
}
// SetAxisRotationRad sets rotation from local axis and angle in radians.
func (ps *Pose) SetAxisRotationRad(x, y, z, angle float32) {
ps.Quat.SetFromAxisAngle(math32.Vec3(x, y, z), angle)
}
// RotateOnAxis rotates around the specified local axis the specified angle in degrees.
func (ps *Pose) RotateOnAxis(x, y, z, angle float32) {
ps.Quat.SetMul(math32.NewQuatAxisAngle(math32.Vec3(x, y, z), math32.DegToRad(angle)))
}
// RotateOnAxisRad rotates around the specified local axis the specified angle in radians.
func (ps *Pose) RotateOnAxisRad(x, y, z, angle float32) {
ps.Quat.SetMul(math32.NewQuatAxisAngle(math32.Vec3(x, y, z), angle))
}
// RotateEuler rotates by given Euler angles (in degrees) relative to existing rotation.
func (ps *Pose) RotateEuler(x, y, z float32) {
ps.Quat.SetMul(math32.NewQuatEuler(math32.Vec3(x, y, z).MulScalar(math32.DegToRadFactor)))
}
// RotateEulerRad rotates by given Euler angles (in radians) relative to existing rotation.
func (ps *Pose) RotateEulerRad(x, y, z, angle float32) {
ps.Quat.SetMul(math32.NewQuatEuler(math32.Vec3(x, y, z)))
}
// SetMatrix sets the local transformation matrix and updates Pos, Scale, Quat.
func (ps *Pose) SetMatrix(m *math32.Matrix4) {
ps.Matrix = *m
ps.Pos, ps.Quat, ps.Scale = ps.Matrix.Decompose()
}
// LookAt points the element at given target location using given up direction.
func (ps *Pose) LookAt(target, upDir math32.Vector3) {
ps.Quat.SetFromRotationMatrix(math32.NewLookAt(ps.Pos, target, upDir))
}
///////////////////////////////////////////////////////
// World values
// WorldPos returns the current world position.
func (ps *Pose) WorldPos() math32.Vector3 {
pos := math32.Vector3{}
pos.SetFromMatrixPos(&ps.WorldMatrix)
return pos
}
// WorldQuat returns the current world quaternion.
func (ps *Pose) WorldQuat() math32.Quat {
_, quat, _ := ps.WorldMatrix.Decompose()
return quat
}
// WorldEulerRotation returns the current world rotation in Euler angles,
// in radians.
func (ps *Pose) WorldEulerRotation() math32.Vector3 {
return ps.WorldQuat().ToEuler()
}
// WorldScale returns he current world scale.
func (ps *Pose) WorldScale() math32.Vector3 {
_, _, scale := ps.WorldMatrix.Decompose()
return scale
}
/*
// PoseProperties define the Toolbar and MenuBar for Form
var PoseProperties = tree.Properties{
"Toolbar": tree.Propertieslice{
{"GenGoSet", tree.Properties{
"label": "Go Code",
"desc": "returns Go Code that sets the current Pose, based on given path to Pose.",
"icon": icons.Code,
"show-return": true,
"Args": tree.Propertieslice{
{"Path", tree.BlankProp{}},
},
}},
{"SetEulerRotation", tree.Properties{
"desc": "Set the local rotation (relative to parent) using Euler angles, in degrees.",
"icon": icons.X3DRotation,
"Args": tree.Propertieslice{
{"Pitch", tree.Properties{
"desc": "rotation up / down along the X axis (in the Y-Z plane), e.g., the altitude (climbing, descending) for motion along the Z depth axis",
}},
{"Yaw", tree.Properties{
"desc": "rotation along the Y axis (in the horizontal X-Z plane), e.g., the bearing or direction for motion along the Z depth axis",
}},
{"Roll", tree.Properties{
"desc": "rotation along the Z axis (in the X-Y plane), e.g., the bank angle for motion along the Z depth axis",
}},
},
}},
{"SetAxisRotation", tree.Properties{
"desc": "Set the local rotation (relative to parent) using Axis about which to rotate, and the angle.",
"icon": icons.X3DRotation,
"Args": tree.Propertieslice{
{"X", tree.BlankProp{}},
{"Y", tree.BlankProp{}},
{"Z", tree.BlankProp{}},
{"Angle", tree.BlankProp{}},
},
}},
{"RotateEuler", tree.Properties{
"desc": "rotate (relative to current rotation) using Euler angles, in degrees.",
"icon": icons.X3DRotation,
"Args": tree.Propertieslice{
{"Pitch", tree.Properties{
"desc": "rotation up / down along the X axis (in the Y-Z plane), e.g., the altitude (climbing, descending) for motion along the Z depth axis",
}},
{"Yaw", tree.Properties{
"desc": "rotation along the Y axis (in the horizontal X-Z plane), e.g., the bearing or direction for motion along the Z depth axis",
}},
{"Roll", tree.Properties{
"desc": "rotation along the Z axis (in the X-Y plane), e.g., the bank angle for motion along the Z depth axis",
}},
},
}},
{"RotateOnAxis", tree.Properties{
"desc": "Rotate (relative to current rotation) using Axis about which to rotate, and the angle.",
"icon": icons.X3DRotation,
"Args": tree.Propertieslice{
{"X", tree.BlankProp{}},
{"Y", tree.BlankProp{}},
{"Z", tree.BlankProp{}},
{"Angle", tree.BlankProp{}},
},
}},
{"LookAt", tree.Properties{
"icon": icons.X3DRotation,
"Args": tree.Propertieslice{
{"Target", tree.BlankProp{}},
{"UpDir", tree.BlankProp{}},
},
}},
{"EulerRotation", tree.Properties{
"desc": "The local rotation (relative to parent) in Euler angles in degrees (X = Pitch, Y = Yaw, Z = Roll)",
"icon": icons.X3DRotation,
"show-return": "true",
}},
{"sep-rot", tree.BlankProp{}},
{"MoveOnAxis", tree.Properties{
"desc": "Move given distance on given X,Y,Z axis relative to current rotation orientation.",
"icon": icons.PanTool,
"Args": tree.Propertieslice{
{"X", tree.BlankProp{}},
{"Y", tree.BlankProp{}},
{"Z", tree.BlankProp{}},
{"Dist", tree.BlankProp{}},
},
}},
{"MoveOnAxisAbs", tree.Properties{
"desc": "Move given distance on given X,Y,Z axis in absolute coords, not relative to current rotation orientation.",
"icon": icons.PanTool,
"Args": tree.Propertieslice{
{"X", tree.BlankProp{}},
{"Y", tree.BlankProp{}},
{"Z", tree.BlankProp{}},
{"Dist", tree.BlankProp{}},
},
}},
},
}
*/
// Copyright (c) 2019, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package xyz
import (
"image"
"sort"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/base/iox/imagex"
"cogentcore.org/core/gpu"
"cogentcore.org/core/gpu/phong"
"cogentcore.org/core/math32"
"cogentcore.org/core/tree"
)
// ConfigOffscreenFromSurface configures offscreen [gpu.RenderTexture]
// using GPU and Device from given [gpu.Surface].
func (sc *Scene) ConfigOffscreenFromSurface(surf *gpu.Surface) {
sc.ConfigOffscreen(surf.GPU, surf.Device())
}
// ConfigOffscreen configures offscreen [gpu.RenderTexture]
// using given gpu and device, and size set in Geom.Size.
// If Frame already exists, it ensures that the Size is correct.
func (sc *Scene) ConfigOffscreen(gp *gpu.GPU, dev *gpu.Device) {
sc.Lock()
defer sc.Unlock()
sz := sc.Geom.Size
if sz == (image.Point{}) {
sz = image.Point{480, 320}
}
if sc.Frame == nil {
sc.Frame = gpu.NewRenderTexture(gp, dev, sz, sc.MultiSample, gpu.Depth32)
sc.Phong = phong.NewPhong(gp, sc.Frame)
sc.ConfigNewPhong()
} else {
sc.Frame.SetSize(sz) // nop if same
}
sc.Camera.SetAspect(sz)
}
// Rebuild updates all the data resources.
// Is only effective when the GPU render is active.
func (sc *Scene) Rebuild() {
sc.Update()
if !sc.IsLive() {
return
}
// The lock keeps the textures and buffers that are released from
// being destroyed while a frame that uses them is being rendered.
sc.Lock()
defer sc.Unlock()
sc.Phong.ResetAll()
sc.ConfigNewPhong()
}
func (sc *Scene) ConfigNewPhong() {
sc.ConfigNodes()
UpdateWorldMatrix(sc.This)
sc.setAllLights()
sc.setAllMeshes()
sc.setAllTextures()
}
// UseAltFrame sets Phong to use the AltFrame [gpu.RenderTexture]
// using given size.
// If AltFrame already exists, it ensures that the Size is correct.
// Call UseMainFrame to return to Frame.
func (sc *Scene) UseAltFrame(sz image.Point) {
sc.Lock()
defer sc.Unlock()
if sc.AltFrame == nil {
var gp *gpu.GPU
var dev *gpu.Device
if sc.Phong != nil {
gp, dev = sc.Phong.System.GPU(), sc.Phong.System.Device()
} else {
var err error
gp, dev, err = gpu.NoDisplayGPU()
if errors.Log(err) != nil {
return
}
}
sc.AltFrame = gpu.NewRenderTexture(gp, dev, sz, sc.MultiSample, gpu.Depth32)
if sc.Phong == nil {
sc.Phong = phong.NewPhong(gp, sc.AltFrame)
sc.ConfigNewPhong()
}
} else {
sc.AltFrame.SetSize(sz) // nop if same
}
sc.AltFrame.Render().ClearColor = sc.Background.At(0, 0)
sc.Camera.SetAspect(sz)
sc.Phong.System.Renderer = sc.AltFrame
}
// UseMainFrame sets Phong to return to using the Frame [gpu.RenderTexture].
func (sc *Scene) UseMainFrame() {
if sc.Frame == nil || sc.Phong == nil {
return
}
sc.Lock()
defer sc.Unlock()
sc.Phong.System.Renderer = sc.Frame
sc.Camera.SetAspect(sc.Geom.Size)
}
// Render renders the scene to the Frame framebuffer.
// Returns false if currently already rendering.
func (sc *Scene) Render() bool {
if sc.Frame == nil || sc.Phong == nil {
return false
}
sc.render(false)
return true
}
// RenderGrabImage renders the scene to the Frame framebuffer.
// and returns the resulting image as an [image.NRGBA]
// which could be nil if there are any issues.
// The image data is a copy and can be modified etc.
func (sc *Scene) RenderGrabImage() *image.NRGBA {
if sc.Phong == nil {
return nil
}
return sc.render(true)
}
// render renders the scene to the Frame framebuffer.
// Returns false if currently already rendering.
func (sc *Scene) render(grabImage bool) *image.NRGBA {
sc.Lock()
defer sc.Unlock()
tex := sc.Phong.System.Renderer
sc.Phong.System.SetClearColor(sc.Background.At(0, 0))
sc.Camera.SetAspect(tex.Size())
if len(sc.SavedCams) == 0 {
sc.SaveCamera("default")
}
sc.TrackCamera()
UpdateWorldMatrix(sc.This)
sc.UpdateMeshBBox()
sc.Camera.UpdateMatrix()
sc.UpdateMVPMatrix()
return sc.renderImpl(grabImage)
}
// AssertImage asserts the [Scene.Image] at the given filename using [imagex.Assert].
// It first configures, updates, and renders the scene.
func (sc *Scene) AssertImage(t imagex.TestingT, filename string) {
sc.Rebuild()
img := sc.RenderGrabImage()
if img == nil {
t.Errorf("xyz.Scene.AssertImage: failure getting image")
return
}
imagex.Assert(t, img, filename)
}
// DepthImage returns the current rendered depth image
func (sc *Scene) DepthImage() ([]float32, error) {
fr := sc.Frame
if fr == nil {
return nil, errors.New("xyz.Scene DepthImage: Scene does not have a Frame")
}
// sy := &sc.Phong.System
// tcmd := sy.MemCmdStart()
// fr.GrabDepthImage(tcmd)
// sy.MemCmdEndSubmitWaitFree()
// depth, err := fr.Render.DepthImageArray()
// if err == nil {
// return depth, err
// }
return nil, nil //err
}
// UpdateMeshBBox updates the Mesh-based BBox info for all nodes.
// groups aggregate over elements
func (sc *Scene) UpdateMeshBBox() {
for _, c := range sc.Children {
cn, _ := AsNode(c)
if cn == nil {
continue
}
cn.AsTree().WalkDownPost(func(k tree.Node) bool {
ni, _ := AsNode(k)
if ni == nil {
return tree.Break
}
return tree.Continue
}, func(k tree.Node) bool {
ni, _ := AsNode(k)
if ni == nil {
return tree.Break
}
ni.UpdateMeshBBox()
return tree.Continue
})
}
}
// UpdateWorldMatrix updates the world matrix for node and everything inside it
func UpdateWorldMatrix(n tree.Node) {
idmtx := math32.Identity4()
for cn := range n.AsTree().All() {
ni, _ := AsNode(cn)
if ni == nil {
continue
}
_, pd := AsNode(cn.AsTree().Parent)
if pd == nil {
ni.UpdateWorldMatrix(idmtx)
} else {
ni.UpdateWorldMatrix(&pd.Pose.WorldMatrix)
}
}
}
// UpdateMVPMatrix updates the Model-View-Projection matrix for all scene elements
// and BBox2D
func (sc *Scene) UpdateMVPMatrix() {
sc.Camera.Pose.UpdateMatrix()
sz := sc.Geom.Size
size := math32.Vec2(float32(sz.X), float32(sz.Y))
sc.WalkDown(func(cn tree.Node) bool {
if cn == sc.This {
return tree.Continue
}
n, nb := AsNode(cn)
if n == nil {
return tree.Break // going into a different type of thing, bail
}
nb.UpdateMVPMatrix(&sc.Camera.ViewMatrix, &sc.Camera.ProjectionMatrix)
nb.UpdateBBox2D(size)
return tree.Continue
})
}
// ConfigNodes runs Config on all nodes
func (sc *Scene) ConfigNodes() {
sc.WalkDown(func(k tree.Node) bool {
if k == sc.This {
return tree.Continue
}
ni, _ := AsNode(k)
if ni == nil {
return tree.Break
}
ni.Config()
return tree.Continue
})
}
// TrackCamera -- a Group at the top-level named "TrackCamera"
// will automatically track the camera (i.e., its Pose is copied).
// Solids in that group can set their relative Pos etc to display
// relative to the camera, to achieve "first person" effects.
func (sc *Scene) TrackCamera() bool {
tci := sc.ChildByName("TrackCamera", 0)
if tci == nil {
return false
}
tc, ok := tci.(*Group)
if !ok {
return false
}
tc.TrackCamera()
return true
}
//////// renderImpl
// RenderClasses define the different classes of rendering
type RenderClasses int32 //enums:enum -trim-prefix RClass
const (
RClassNone RenderClasses = iota
RClassOpaqueTexture // textures tend to be in background
RClassOpaqueUniform
RClassOpaqueVertex
RClassTransTexture
RClassTransUniform
RClassTransVertex
)
// renderImpl renders the scene to the framebuffer.
// all scene-level resources must be initialized and activated at this point.
// if grabImage is true, the resulting rendered image is returned.
func (sc *Scene) renderImpl(grabImage bool) *image.NRGBA {
ph := sc.Phong
ph.SetCamera(&sc.Camera.ViewMatrix, &sc.Camera.ProjectionMatrix)
var rcs [RenderClassesN][]Node
sc.WalkDown(func(k tree.Node) bool {
if k == sc.This {
return tree.Continue
}
ni, _ := AsNode(k)
if ni == nil {
return tree.Break // going into a different type of thing, bail
}
// if !ni.IsVisible() || nb.ScBBox == (image.Rectangle{}) {
// return tree.Break
// }
if !ni.IsSolid() {
return tree.Continue
}
rc := min(ni.RenderClass(),
// all in one group b/c z-sorting is key
RClassTransTexture)
rcs[rc] = append(rcs[rc], ni)
return tree.Continue
})
for rci, objs := range rcs {
rc := RenderClasses(rci)
if len(objs) == 0 {
continue
}
if rc >= RClassTransTexture { // sort back-to-front for transparent
sort.Slice(objs, func(i, j int) bool { // TODO: use slices.SortFunc here and everywhere else we use sort.Slice
return objs[i].AsNodeBase().NormDCBBox().Min.Z > objs[j].AsNodeBase().NormDCBBox().Min.Z
})
} else { // sort front-to-back for opaque to allow "early z rejection"
sort.Slice(objs, func(i, j int) bool {
return objs[i].AsNodeBase().NormDCBBox().Min.Z < objs[j].AsNodeBase().NormDCBBox().Min.Z
})
}
// fmt.Printf("\nRender class: %v\n", rc)
// for i := range objs {
// fmt.Printf("obj: %s max z: %g min z: %g\n", objs[i].Name, objs[i].AsNode().NDCBBox.Max.Z, objs[i].AsNode().NDCBBox.Min.Z)
// }
for _, obj := range objs {
obj.PreRender()
}
}
rp, err := ph.RenderStart()
if err != nil {
return nil
}
for _, objs := range rcs {
for _, obj := range objs {
obj.Render(rp)
}
}
if grabImage {
return ph.RenderEndGrabImage(rp)
}
ph.RenderEnd(rp)
return nil
}
// Copyright (c) 2019, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package xyz provides a 3D graphics framework in Go.
package xyz
//go:generate core generate -add-types
import (
"fmt"
"image"
"sync"
"cogentcore.org/core/base/keylist"
"cogentcore.org/core/colors"
"cogentcore.org/core/gpu"
"cogentcore.org/core/gpu/phong"
"cogentcore.org/core/math32"
"cogentcore.org/core/text/shaped"
"cogentcore.org/core/tree"
)
// Update3DTrace can be set to true to get a trace of 3D updating.
var Update3DTrace = false
// note: Scene provides a complete separate representation of the
// render data, on top of gpu.phong. This allows a scene to be
// fully specified prior to the gpu being available.
// once phong is up and running, it directly pushes changes through it
// to the gpu, so dynamic changes are transparent and don't require
// further config steps.
// Scene is the overall scenegraph containing nodes as children.
// It can render offscreen to its own gpu.RenderTexture, or to an
// onscreen surface.
// The Image of this Frame is usable directly or, via xyzcore.Scene,
// where it is copied into an overall core.Scene image.
//
// There is default navigation event processing (disabled by setting NoNav)
// where mouse drag events Orbit the camera (Shift = Pan, Alt = PanTarget)
// and arrow keys do Orbit, Pan, PanTarget with same key modifiers.
// Spacebar restores original "default" camera, and numbers save (1st time)
// or restore (subsequently) camera views (Control = always save)
//
// A Group at the top-level named "TrackCamera" will automatically track
// the camera (i.e., its Pose is copied) -- Solids in that group can
// set their relative Pos etc to display relative to the camera, to achieve
// "first person" effects.
type Scene struct {
tree.NodeBase
// Background is the background of the scene,
// which is used directly as a solid color in Vulkan.
Background image.Image
// Viewport-level viewbox within any parent Viewport2D
Geom math32.Geom2DInt `set:"-"`
// number of samples in multisampling. Default of 4 produces smooth
// rendering.
MultiSample int `default:"4"`
// render using wireframe instead of filled polygons.
// This must be set prior to configuring the Phong rendering
// system (i.e., just after Scene is made).
// note: not currently working in WebGPU.
Wireframe bool `default:"false"`
// camera determines view onto scene
Camera Camera `set:"-"`
// all lights used in the scene
Lights keylist.List[string, Light] `set:"-"`
// meshes
Meshes keylist.List[string, Mesh] `set:"-"`
// textures
Textures keylist.List[string, Texture] `set:"-"`
// library of objects that can be used in the scene
Library map[string]*Group `set:"-"`
// don't activate the standard navigation keyboard and mouse
// event processing to move around the camera in the scene.
NoNav bool
// saved cameras, can Save and Set these to view the scene
// from different angles
SavedCams map[string]Camera `set:"-"`
// the phong rendering system
Phong *phong.Phong `set:"-"`
// Frame is the gpu render frame holding the rendered scene.
Frame gpu.Renderer `set:"-"`
// AltFrame is an alternative render frame that can be used,
// e.g., for grabbing images from different viewpoints.
// AltFrame is not used for xyzcore display purposes.
// call UseAltFrame and UseMainFrame to switch between.
AltFrame gpu.Renderer `set:"-"`
// TextShaper is the text shaping system for this scene, for doing text layout.
TextShaper shaped.Shaper
// mutex checked for rendering
sync.Mutex
}
func (sc *Scene) Init() {
sc.MultiSample = 4
sc.Camera.Defaults()
sc.Background = colors.Scheme.Surface
initTextShaper(sc)
sc.Updater(sc.UpdateFromMake)
}
// NewOffscreenScene returns a new [Scene] designed for offscreen
// rendering of 3D content. This can be used in unit tests and other
// cases not involving xyzcore. It makes a new [gpu.NoDisplayGPU].
func NewOffscreenScene() *Scene {
gpu, device, err := gpu.NoDisplayGPU()
if err != nil {
panic(fmt.Errorf("xyz.NewOffscreenScene: error initializing gpu.NoDisplayGPU: %w", err))
}
sc := NewScene().SetSize(image.Pt(1280, 960))
sc.ConfigOffscreen(gpu, device)
return sc
}
// Update does the [tree] Maker / Plan updating of nodes.
func (sc *Scene) Update() {
sc.RunUpdaters()
for n := range sc.All() {
if n.AsTree().This == sc.This {
continue
}
n.(Node).Update()
}
}
// IsLive indicates whether the Phong system is active and we can
// directly update that, vs just creating elements to be added later.
func (sc *Scene) IsLive() bool {
return sc.Phong != nil
}
// SaveCamera saves the current camera with given name -- can be restored later with SetCamera.
// "default" is a special name that is automatically saved on first render, and
// restored with the spacebar under default NavEvents.
// Numbered cameras 0-9 also saved / restored with corresponding keys.
func (sc *Scene) SaveCamera(name string) {
if sc.SavedCams == nil {
sc.SavedCams = make(map[string]Camera)
}
sc.SavedCams[name] = sc.Camera
// fmt.Printf("saved camera %s: %v\n", name, sc.Camera.Pose.GenGoSet(".Pose"))
}
// SetCamera sets the current camera to that of given name -- error if not found.
// "default" is a special name that is automatically saved on first render, and
// restored with the spacebar under default NavEvents.
// Numbered cameras 0-9 also saved / restored with corresponding keys.
func (sc *Scene) SetCamera(name string) error {
cam, ok := sc.SavedCams[name]
if !ok {
return fmt.Errorf("xyz.Scene: %v saved camera of name: %v not found", sc.Name, name)
}
sc.Camera = cam
return nil
}
// DeleteUnusedMeshes deletes all unused meshes
func (sc *Scene) DeleteUnusedMeshes() {
// used := make(map[string]struct{})
// iterate over scene, add to used, then iterate over mats and if not used, delete.
}
// Validate traverses the scene and validates all the elements -- errors are logged
// and a non-nil return indicates that at least one error was found.
func (sc *Scene) Validate() error {
// var errs []error // todo -- could do this
// if err != nil {
// *errs = append(*errs, err)
// }
hasError := false
sc.WalkDown(func(k tree.Node) bool {
if k == sc.This {
return tree.Continue
}
ni, _ := AsNode(k)
if !ni.IsVisible() {
return tree.Break
}
err := ni.Validate()
if err != nil {
hasError = true
}
return tree.Continue
})
if hasError {
return fmt.Errorf("xyz.Scene: %v Validate found at least one error (see log)", sc.Path())
}
return nil
}
// SetSize sets the size of the [Scene.Frame].
func (sc *Scene) SetSize(sz image.Point) *Scene {
if sz.X == 0 || sz.Y == 0 {
return sc
}
if sc.Frame != nil {
csz := sc.Frame.Render().Format.Size
if csz == sz {
sc.Geom.Size = sz // make sure
return sc
}
}
if sc.Frame != nil {
sc.Frame.SetSize(sz)
}
sc.Geom.Size = sz // make sure
// fmt.Printf("vp %v resized to: %v, bounds: %v\n", vp.Path(), nwsz, vp.Pixels.Bounds())
return sc
}
// Destroy releases the GPU resources of the scene. It locks the scene,
// so that its textures are not destroyed while a frame that uses them is
// being rendered.
func (sc *Scene) Destroy() {
sc.Lock()
defer sc.Unlock()
if sc.Phong != nil {
sc.Phong.Release()
sc.Phong = nil
}
if sc.Frame != nil {
sc.Frame.Release()
sc.Frame = nil
}
if sc.AltFrame != nil {
sc.AltFrame.Release()
sc.AltFrame = nil
}
}
// SolidsIntersectingPoint finds all the solids that contain given 2D window coordinate
func (sc *Scene) SolidsIntersectingPoint(pos image.Point) []Node {
var objs []Node
for _, c := range sc.Children {
cn, _ := AsNode(c)
cn.AsTree().WalkDown(func(k tree.Node) bool {
ni, _ := AsNode(k)
if ni == nil {
return tree.Break // going into a different type of thing, bail
}
if !ni.IsSolid() {
return tree.Continue
}
// if nb.PosInWinBBox(pos) {
objs = append(objs, ni)
// }
return tree.Continue
})
}
return objs
}
// SetScene sets the Scene pointer in given object and all of its children.
func (sc *Scene) SetScene(o tree.Node) {
o.AsTree().WalkDown(func(n tree.Node) bool {
ni, nb := AsNode(n)
if ni == nil {
return tree.Break
}
nb.Scene = sc
return tree.Continue
})
}
// Copyright (c) 2019, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package xyz
import (
"cogentcore.org/core/gpu/shape"
"cogentcore.org/core/math32"
)
const (
// TrackCameraName is a reserved top-level Group name -- this group
// will have its Pose updated to match that of the camera automatically.
TrackCameraName = "TrackCamera"
// Plane2DMeshName is the reserved name for the 2D plane mesh
// used for Text2D and Embed2D
Plane2DMeshName = "__Plane2D"
// LineMeshName is the reserved name for a unit-sized Line segment
LineMeshName = "__UnitLine"
// ConeMeshName is the reserved name for a unit-sized Cone segment.
// Has the number of segments appended.
ConeMeshName = "__UnitCone"
)
//////// Plane
// Plane is a flat 2D plane, which can be oriented along any
// axis facing either positive or negative
type Plane struct { //types:add -setters
MeshBase
// axis along which the normal perpendicular to the plane points. E.g., if the Y axis is specified, then it is a standard X-Z ground plane -- see also NormalNeg for whether it is facing in the positive or negative of the given axis.
NormAxis math32.Dims
// if false, the plane normal facing in the positive direction along specified NormAxis, otherwise it faces in the negative if true
NormalNeg bool
// 2D size of plane
Size math32.Vector2
// number of segments to divide plane into (enforced to be at least 1) -- may potentially increase rendering quality to have > 1
Segs math32.Vector2i
// offset from origin along direction of normal to the plane
Offset float32
}
// NewPlane adds Plane mesh to given scene,
// with given name and size, with its normal pointing
// by default in the positive Y axis (i.e., a "ground" plane).
// Offset is 0.
func NewPlane(sc *Scene, name string, width, height float32) *Plane {
pl := &Plane{}
pl.Name = name
pl.NormAxis = math32.Y
pl.NormalNeg = false
pl.Size.Set(width, height)
pl.Segs.Set(1, 1)
pl.Offset = 0
sc.SetMesh(pl)
return pl
}
func (pl *Plane) MeshSize() (numVertex, nIndex int, hasColor bool) {
pl.NumVertex, pl.NumIndex = shape.PlaneN(int(pl.Segs.X), int(pl.Segs.Y))
pl.HasColor = false
return pl.NumVertex, pl.NumIndex, pl.HasColor
}
func (pl *Plane) Set(vertex, normal, texcoord, clrs math32.ArrayF32, index math32.ArrayU32) {
pos := math32.Vector3{}
sz := shape.SetPlaneAxisSize(vertex, normal, texcoord, index, 0, 0, pl.NormAxis, pl.NormalNeg, pl.Size, pl.Segs, pl.Offset, pos)
mn := pos.Sub(sz)
mx := pos.Add(sz)
pl.BBox.SetBounds(mn, mx)
}
//////// Box
// Box is a rectangular-shaped solid (cuboid)
type Box struct { //types:add -setters
MeshBase
// size along each dimension
Size math32.Vector3
// number of segments to divide each plane into (enforced to be at least 1) -- may potentially increase rendering quality to have > 1
Segs math32.Vector3i
}
// NewBox adds Box mesh to given scene, with given name and size
func NewBox(sc *Scene, name string, width, height, depth float32) *Box {
bx := &Box{}
bx.Name = name
bx.Size.Set(width, height, depth)
bx.Segs.Set(1, 1, 1)
sc.SetMesh(bx)
return bx
}
func (bx *Box) MeshSize() (numVertex, nIndex int, hasColor bool) {
bx.NumVertex, bx.NumIndex = shape.BoxN(bx.Segs)
bx.HasColor = false
return bx.NumVertex, bx.NumIndex, bx.HasColor
}
func (bx *Box) Set(vertex, normal, texcoord, clrs math32.ArrayF32, index math32.ArrayU32) {
pos := math32.Vector3{}
hSz := shape.SetBox(vertex, normal, texcoord, index, 0, 0, bx.Size, bx.Segs, pos)
mn := pos.Sub(hSz)
mx := pos.Add(hSz)
bx.BBox.SetBounds(mn, mx)
}
//////// Sphere
// Sphere is a sphere mesh
type Sphere struct { //types:add -setters
MeshBase
// radius of the sphere
Radius float32
// number of segments around the width of the sphere (32 is reasonable default for full circle)
WidthSegs int `min:"3"`
// number of height segments (32 is reasonable default for full height)
HeightSegs int `min:"3"`
// starting radial angle in degrees, relative to -1,0,0 left side starting point
AngStart float32 `min:"0" max:"360" step:"5"`
// total radial angle to generate in degrees (max = 360)
AngLen float32 `min:"0" max:"360" step:"5"`
// starting elevation (height) angle in degrees - 0 = top of sphere, and Pi is bottom
ElevStart float32 `min:"0" max:"180" step:"5"`
// total angle to generate in degrees (max = 180)
ElevLen float32 `min:"0" max:"180" step:"5"`
}
// NewSphere creates a sphere mesh with the specified radius,
// number of segments (resolution).
func NewSphere(sc *Scene, name string, radius float32, segs int) *Sphere {
sp := &Sphere{}
sp.Name = name
sp.Radius = radius
sp.WidthSegs = segs
sp.HeightSegs = segs
sp.AngStart = 0
sp.AngLen = 360
sp.ElevStart = 0
sp.ElevLen = 180
sc.SetMesh(sp)
return sp
}
func (sp *Sphere) Defaults() {
sp.Radius = 1
sp.WidthSegs = 32
sp.HeightSegs = 32
sp.AngStart = 0
sp.AngLen = 360
sp.ElevStart = 0
sp.ElevLen = 180
}
func (sp *Sphere) MeshSize() (numVertex, nIndex int, hasColor bool) {
sp.NumVertex, sp.NumIndex = shape.SphereSectorN(sp.WidthSegs, sp.HeightSegs, sp.ElevStart, sp.ElevLen)
sp.HasColor = false
return sp.NumVertex, sp.NumIndex, sp.HasColor
}
func (sp *Sphere) Set(vertex, normal, texcoord, clrs math32.ArrayF32, index math32.ArrayU32) {
pos := math32.Vector3{}
bb := shape.SetSphereSector(vertex, normal, texcoord, index, 0, 0, sp.Radius, sp.WidthSegs, sp.HeightSegs, sp.AngStart, sp.AngLen, sp.ElevStart, sp.ElevLen, pos)
sp.BBox.SetBounds(bb.Min, bb.Max)
}
//////// Cylinder / Cone
// Cylinder is a generalized cylinder shape, including a cone
// or truncated cone by having different size circles at either end.
// Height is up along the Y axis.
type Cylinder struct { //types:add -setters
MeshBase
// height of the cylinder
Height float32
// radius of the top -- set to 0 for a cone
TopRad float32
// radius of the bottom
BotRad float32
// number of radial segments (32 is a reasonable default for full circle)
RadialSegs int `min:"1"`
// number of height segments
HeightSegs int
// render the top disc
Top bool
// render the bottom disc
Bottom bool
// starting angle in degrees, relative to -1,0,0 left side starting point
AngStart float32 `min:"0" max:"360" step:"5"`
// total angle to generate in degrees (max 360)
AngLen float32 `min:"0" max:"360" step:"5"`
}
// TopCap specifies whether a cylinder has a top cap: [WithTop] or [NoTop].
type TopCap = shape.TopCap
// BottomCap specifies whether a cylinder or cone has a bottom cap:
// [WithBottom] or [NoBottom].
type BottomCap = shape.BottomCap
const (
// WithTop adds the top cap.
WithTop = shape.WithTop
// NoTop leaves the top open.
NoTop = shape.NoTop
// WithBottom adds the bottom cap.
WithBottom = shape.WithBottom
// NoBottom leaves the bottom open.
NoBottom = shape.NoBottom
)
// NewCone creates a cone mesh with the specified base radius, height,
// number of radial segments, number of height segments, and presence of a bottom cap.
// Height is along the Y axis.
func NewCone(sc *Scene, name string, height, radius float32, radialSegs, heightSegs int, bottom BottomCap) *Cylinder {
return NewCylinderSector(sc, name, height, 0, radius, radialSegs, heightSegs, 0, 360, NoTop, bottom)
}
// NewCylinder creates a cylinder mesh with the specified radius, height,
// number of radial segments, number of height segments,
// and presence of a top and/or bottom cap.
// Height is along the Y axis.
func NewCylinder(sc *Scene, name string, height, radius float32, radialSegs, heightSegs int, top TopCap, bottom BottomCap) *Cylinder {
return NewCylinderSector(sc, name, height, radius, radius, radialSegs, heightSegs, 0, 360, top, bottom)
}
// NewCylinderSector creates a generalized cylinder (truncated cone) sector mesh
// with the specified top and bottom radii, height, number of radial segments,
// number of height segments, sector start angle in degrees,
// sector size angle in degrees, and presence of a top and/or bottom cap.
// Height is along the Y axis.
func NewCylinderSector(sc *Scene, name string, height, topRad, botRad float32, radialSegs, heightSegs int, angStart, angLen float32, top TopCap, bottom BottomCap) *Cylinder {
cy := &Cylinder{}
cy.Name = name
cy.Height = height
cy.TopRad = topRad
cy.BotRad = botRad
cy.RadialSegs = radialSegs
cy.HeightSegs = heightSegs
cy.AngStart = angStart
cy.AngLen = angLen
cy.Top = bool(top)
cy.Bottom = bool(bottom)
sc.SetMesh(cy)
return cy
}
func (cy *Cylinder) Defaults() {
cy.Height = 1
cy.TopRad = 0.5
cy.BotRad = 0.5
cy.RadialSegs = 32
cy.HeightSegs = 32
cy.Top = true
cy.Bottom = true
cy.AngStart = 0
cy.AngLen = 360
}
func (cy *Cylinder) MeshSize() (numVertex, nIndex int, hasColor bool) {
cy.NumVertex, cy.NumIndex = shape.CylinderSectorN(cy.RadialSegs, cy.HeightSegs, shape.TopCap(cy.Top), shape.BottomCap(cy.Bottom))
cy.HasColor = false
return cy.NumVertex, cy.NumIndex, cy.HasColor
}
func (cy *Cylinder) Set(vertex, normal, texcoord, clrs math32.ArrayF32, index math32.ArrayU32) {
pos := math32.Vector3{}
bb := shape.SetCylinderSector(vertex, normal, texcoord, index, 0, 0, cy.Height, cy.TopRad, cy.BotRad, cy.RadialSegs, cy.HeightSegs, cy.AngStart, cy.AngLen, shape.TopCap(cy.Top), shape.BottomCap(cy.Bottom), pos)
cy.BBox.SetBounds(bb.Min, bb.Max)
}
//////// Capsule
// Capsule is a generalized capsule shape: a cylinder with hemisphere end caps.
// Supports different radii on each end.
// Height is along the Y axis -- total height is Height + TopRad + BotRad.
type Capsule struct { //types:add -setters
MeshBase
// height of the cylinder portion
Height float32
// radius of the top -- set to 0 for a cone
TopRad float32
// radius of the bottom
BotRad float32
// number of radial segments (32 is a reasonable default for full circle)
RadialSegs int `min:"1"`
// number of height segments
HeightSegs int
// number of segments in the hemisphere cap ends (16 is a reasonable default)
CapSegs int
// starting angle in degrees, relative to -1,0,0 left side starting point
AngStart float32 `min:"0" max:"360" step:"5"`
// total angle to generate in degrees (max 360)
AngLen float32 `min:"0" max:"360" step:"5"`
}
// NewCapsule creates a generalized capsule mesh (cylinder + hemisphere caps)
// with the specified height and radius, number of radial, sphere segments,
// and number of height segments
// Height is along the Y axis.
func NewCapsule(sc *Scene, name string, height, radius float32, segs, heightSegs int) *Capsule {
cp := &Capsule{}
cp.Name = name
cp.Height = height
cp.TopRad = radius
cp.BotRad = radius
cp.RadialSegs = segs
cp.HeightSegs = heightSegs
cp.CapSegs = segs
cp.AngStart = 0
cp.AngLen = 360
sc.SetMesh(cp)
return cp
}
func (cp *Capsule) Defaults() {
cp.Height = 1
cp.TopRad = 0.5
cp.BotRad = 0.5
cp.RadialSegs = 32
cp.HeightSegs = 32
cp.CapSegs = 32
cp.AngStart = 0
cp.AngLen = 360
}
func (cp *Capsule) MeshSize() (numVertex, nIndex int, hasColor bool) {
numVertex, nIndex = shape.CylinderSectorN(cp.RadialSegs, cp.HeightSegs, shape.NoTop, shape.NoBottom)
if cp.BotRad > 0 {
nv, ni := shape.SphereSectorN(cp.RadialSegs, cp.CapSegs, 90, 90)
numVertex += nv
nIndex += ni
}
if cp.TopRad > 0 {
nv, ni := shape.SphereSectorN(cp.RadialSegs, cp.CapSegs, 0, 90)
numVertex += nv
nIndex += ni
}
return
}
func (cp *Capsule) Set(vertex, normal, texcoord, clrs math32.ArrayF32, index math32.ArrayU32) {
pos := math32.Vector3{}
voff := 0
ioff := 0
bb := shape.SetCylinderSector(vertex, normal, texcoord, index, voff, ioff, cp.Height, cp.TopRad, cp.BotRad, cp.RadialSegs, cp.HeightSegs, cp.AngStart, cp.AngLen, shape.NoTop, shape.NoBottom, pos)
nv, ni := shape.CylinderSectorN(cp.RadialSegs, cp.HeightSegs, shape.NoTop, shape.NoBottom)
voff += nv
ioff += ni
if cp.BotRad > 0 {
ps := pos
ps.Y -= cp.Height / 2
cbb := shape.SetSphereSector(vertex, normal, texcoord, index, voff, ioff, cp.BotRad, cp.RadialSegs, cp.CapSegs, cp.AngStart, cp.AngLen, 90, 90, ps)
bb.ExpandByBox(cbb)
nv, ni = shape.SphereSectorN(cp.RadialSegs, cp.CapSegs, 90, 90)
voff += nv
ioff += ni
}
if cp.TopRad > 0 {
ps := pos
ps.Y += cp.Height / 2
cbb := shape.SetSphereSector(vertex, normal, texcoord, index, voff, ioff, cp.TopRad, cp.RadialSegs, cp.CapSegs, cp.AngStart, cp.AngLen, 0, 90, ps)
bb.ExpandByBox(cbb)
}
cp.BBox.SetBounds(bb.Min, bb.Max)
}
//////// Torus
// Torus is a torus mesh, defined by the radius of the solid tube and the
// larger radius of the ring.
type Torus struct { //types:add -setters
MeshBase
// larger radius of the torus ring
Radius float32
// radius of the solid tube
TubeRadius float32
// number of segments around the radius of the torus (32 is reasonable default for full circle)
RadialSegs int `min:"1"`
// number of segments for the tube itself (32 is reasonable default for full height)
TubeSegs int `min:"1"`
// starting radial angle in degrees relative to 1,0,0 starting point
AngStart float32 `min:"0" max:"360" step:"5"`
// total radial angle to generate in degrees (max = 360)
AngLen float32 `min:"0" max:"360" step:"5"`
}
// NewTorus creates a sphere mesh with the specified outer ring radius,
// solid tube radius, and number of segments (resolution).
func NewTorus(sc *Scene, name string, radius, tubeRadius float32, segs int) *Torus {
sp := &Torus{}
sp.Name = name
sp.Radius = radius
sp.TubeRadius = tubeRadius
sp.RadialSegs = segs
sp.TubeSegs = segs
sp.AngStart = 0
sp.AngLen = 360
sc.SetMesh(sp)
return sp
}
func (tr *Torus) Defaults() {
tr.Radius = 1
tr.TubeRadius = .1
tr.RadialSegs = 32
tr.TubeSegs = 32
tr.AngStart = 0
tr.AngLen = 360
}
func (tr *Torus) MeshSize() (numVertex, nIndex int, hasColor bool) {
numVertex, nIndex = shape.TorusSectorN(tr.RadialSegs, tr.TubeSegs)
return
}
// Set sets points for torus in given allocated arrays
func (tr *Torus) Set(vertex, normal, texcoord, clrs math32.ArrayF32, index math32.ArrayU32) {
pos := math32.Vector3{}
bb := shape.SetTorusSector(vertex, normal, texcoord, index, 0, 0, tr.Radius, tr.TubeRadius, tr.RadialSegs, tr.TubeSegs, tr.AngStart, tr.AngLen, pos)
tr.BBox.SetBounds(bb.Min, bb.Max)
}
// Copyright (c) 2019, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package xyz
import (
"fmt"
"image/color"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/gpu/phong"
"github.com/oliverbestmann/webgpu/wgpu"
)
// https://www.khronos.org/opengl/wiki/Vertex_Specification_Best_Practices
// Solid represents an individual 3D solid element.
// It has its own unique spatial transforms and material properties,
// and points to a mesh structure defining the shape of the solid.
type Solid struct {
NodeBase
// MeshName is the name of the mesh shape information used for rendering
// this solid; all meshes are collected on the Scene.
MeshName MeshName `set:"-"`
// Material contains the material properties of the surface (color, shininess, texture, etc).
Material Material `display:"add-fields"`
// Mesh is the cached [Mesh] object set from [Solid.MeshName].
Mesh Mesh `display:"-" set:"-"`
}
func (sld *Solid) Init() {
sld.Defaults()
}
func (sld *Solid) IsSolid() bool {
return true
}
func (sld *Solid) AsSolid() *Solid {
return sld
}
// Defaults sets default initial settings for solid params.
// This is called automatically Init.
func (sld *Solid) Defaults() {
sld.Pose.Defaults()
sld.Material.Defaults()
}
// SetMeshName sets mesh to given mesh name.
func (sld *Solid) SetMeshName(meshName string) error {
if meshName == "" {
return nil
}
ms, err := sld.Scene.MeshByName(meshName)
if errors.Log(err) != nil {
return err
}
sld.MeshName = MeshName(meshName)
sld.Mesh = ms
return nil
}
// SetMesh sets mesh
func (sld *Solid) SetMesh(ms Mesh) *Solid {
sld.Mesh = ms
if sld.Mesh != nil {
sld.MeshName = MeshName(sld.Mesh.AsMeshBase().Name)
} else {
sld.MeshName = ""
}
return sld
}
// SetColor sets the [Material.Color]:
// prop: color = main color of surface, used for both ambient and diffuse color in standard Phong model -- alpha component determines transparency -- note that transparent objects require more complex rendering
func (sld *Solid) SetColor(v color.RGBA) *Solid {
sld.Material.Color = v
return sld
}
// SetEmissive sets the [Material.Emissive]:
// prop: emissive = color that surface emits independent of any lighting -- i.e., glow -- can be used for marking lights with an object
func (sld *Solid) SetEmissive(v color.RGBA) *Solid {
sld.Material.Emissive = v
return sld
}
// SetShiny sets the [Material.Shiny]:
// prop: shiny = specular shininess factor -- how focally vs. broad the surface shines back directional light -- this is an exponential factor, with 0 = very broad diffuse reflection, and higher values (typically max of 128 or so but can go higher) having a smaller more focal specular reflection. Also set Reflective factor to change overall shininess effect.
func (sld *Solid) SetShiny(v float32) *Solid {
sld.Material.Shiny = v
return sld
}
// SetReflective sets the [Material.Reflective]:
// prop: reflective = specular reflectiveness factor -- how much it shines back directional light. The specular reflection color is always white * the incoming light.
func (sld *Solid) SetReflective(v float32) *Solid {
sld.Material.Reflective = v
return sld
}
// SetBright sets the [Material.Bright]:
// prop: bright = overall multiplier on final computed color value -- can be used to tune the overall brightness of various surfaces relative to each other for a given set of lighting parameters
func (sld *Solid) SetBright(v float32) *Solid {
sld.Material.Bright = v
return sld
}
// SetTextureName sets material to use given texture name
// (textures are accessed by name on Scene).
// If name is empty, then texture is reset
func (sld *Solid) SetTextureName(texName string) *Solid {
sld.Material.SetTextureName(sld.Scene, texName)
return sld
}
// SetTexture sets material to use given texture
func (sld *Solid) SetTexture(tex Texture) *Solid {
sld.Material.SetTexture(tex)
return sld
}
// SetPos sets the [Pose.Pos] position of the solid
func (sld *Solid) SetPos(x, y, z float32) *Solid {
sld.Pose.Pos.Set(x, y, z)
return sld
}
// SetScale sets the [Pose.Scale] scale of the solid
func (sld *Solid) SetScale(x, y, z float32) *Solid {
sld.Pose.Scale.Set(x, y, z)
return sld
}
// SetAxisRotation sets the [Pose.Quat] rotation of the solid,
// from local axis and angle in degrees.
func (sld *Solid) SetAxisRotation(x, y, z, angle float32) *Solid {
sld.Pose.SetAxisRotation(x, y, z, angle)
return sld
}
// SetEulerRotation sets the [Pose.Quat] rotation of the solid,
// from euler angles in degrees
func (sld *Solid) SetEulerRotation(x, y, z float32) *Solid {
sld.Pose.SetEulerRotation(x, y, z)
return sld
}
func (sld *Solid) Config() {
sld.Validate()
sld.NodeBase.Config()
}
// ParentMaterial returns parent's material or nil if not avail
func (sld *Solid) ParentMaterial() *Material {
pn, ok := sld.Parent.(Node) // (the scene is not a node)
if !ok {
return nil
}
psi := pn.AsSolid()
if psi == nil {
return nil
}
return &(psi.Material)
}
// Validate checks that solid has valid mesh and texture settings, etc
func (sld *Solid) Validate() error {
if sld.MeshName == "" {
return errors.Log(fmt.Errorf("xyz.Solid: %s Mesh name is empty", sld.Path()))
}
if sld.Mesh == nil || sld.Mesh.AsMeshBase().Name != string(sld.MeshName) {
err := sld.SetMeshName(string(sld.MeshName))
if err != nil {
return err
}
}
return sld.Material.Validate(sld.Scene)
}
func (sld *Solid) IsVisible() bool {
if sld.Mesh == nil {
return false
}
return sld.NodeBase.IsVisible()
}
func (sld *Solid) IsTransparent() bool {
if sld.Mesh == nil {
return false
}
if sld.Mesh.AsMeshBase().HasColor {
return sld.Mesh.AsMeshBase().Transparent
}
return sld.Material.IsTransparent()
}
// UpdateMeshBBox updates the Mesh-based BBox info for all nodes.
// groups aggregate over elements
func (sld *Solid) UpdateMeshBBox() {
if sld.Mesh != nil {
mesh := sld.Mesh.AsMeshBase()
sld.MeshBBox = mesh.BBox
}
}
//////// Rendering
// RenderClass returns the class of rendering for this solid
// used for organizing the ordering of rendering
func (sld *Solid) RenderClass() RenderClasses {
switch {
case sld.Material.Texture != nil:
return RClassOpaqueTexture
case sld.Mesh.AsMeshBase().HasColor:
if sld.Mesh.AsMeshBase().Transparent {
return RClassTransVertex
}
return RClassOpaqueVertex
default:
if sld.Material.IsTransparent() {
return RClassTransUniform
}
return RClassOpaqueUniform
}
}
// PreRender activates this solid for rendering
func (sld *Solid) PreRender() {
ph := sld.Scene.Phong
nm := sld.Path()
ph.SetObject(nm, phong.NewObject(&sld.Pose.WorldMatrix, sld.Material.phongColors()))
// fmt.Println("pre:", nm, sld.Pose.Matrix, sld.Material.phongColors())
}
// Render activates this solid for rendering
func (sld *Solid) Render(rp *wgpu.RenderPassEncoder) {
nm := sld.Path()
ph := sld.Scene.Phong
ph.UseObject(nm)
ph.UseMesh(string(sld.MeshName))
if sld.Material.TextureName != "" {
ph.UseTexture(string(sld.Material.TextureName))
} else {
ph.UseNoTexture()
}
ph.Render(rp)
}
// Copyright (c) 2019, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package xyz
import (
"fmt"
"cogentcore.org/core/colors"
"cogentcore.org/core/gpu"
"cogentcore.org/core/gpu/phong"
"cogentcore.org/core/math32"
"cogentcore.org/core/paint"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/text/htmltext"
"cogentcore.org/core/text/rich"
"cogentcore.org/core/text/shaped"
"cogentcore.org/core/text/text"
)
// Text2D presents 2D rendered text on a vertically oriented plane, using a texture.
// Call SetText() which calls RenderText to update for text changes (re-renders texture).
// The native scale is such that a unit height value is the height of the default font
// set by the font-size property, and the X axis is scaled proportionally based on the
// rendered text size to maintain the aspect ratio. Further scaling can be applied on
// top of that by setting the Pose.Scale values as usual.
// Standard styling properties can be set on the node to set font size, family,
// and text alignment relative to the Pose.Pos position (e.g., Left, Top puts the
// upper-left corner of text at Pos).
// Note that higher quality is achieved by using a larger font size (36 default).
// The margin property creates blank margin of the background color around the text
// (2 px default) and the background-color defaults to transparent
// but can be set to any color.
type Text2D struct {
Solid
// the text string to display
Text string
// styling settings for the text
Styles styles.Style `set:"-" json:"-" xml:"-"`
// position offset of start of text rendering relative to upper-left corner
TextPos math32.Vector2 `set:"-" xml:"-" json:"-"`
// richText is the conversion of the HTML text source.
richText rich.Text
// render data for text label
textRender *shaped.Lines `set:"-" xml:"-" json:"-"`
// automatically set to true if the font render color is the default
// colors.Scheme.OnSurface. If so, it is automatically updated if the default
// changes, e.g., in light mode vs dark mode switching.
usesDefaultColor bool
}
func (txt *Text2D) Init() {
txt.Defaults()
}
func (txt *Text2D) Defaults() {
txt.Solid.Defaults()
txt.Pose.Scale.SetScalar(.005)
txt.Styles.Defaults()
txt.Styles.Font.Size.Pt(36)
txt.Styles.Margin.Set(units.Dp(2))
txt.Material.Bright = 4 // this is key for making e.g., a white background show up as white..
}
// TextSize returns the size of the text plane, applying all *local* scaling factors
// if nothing rendered yet, returns false
func (txt *Text2D) TextSize() (math32.Vector2, bool) {
txt.Pose.Defaults() // only if nil
sz := math32.Vector2{}
tx := txt.Material.Texture
if tx == nil {
return sz, false
}
tsz := tx.Image().Bounds().Size()
fsz := txt.Styles.Font.FontHeight()
if fsz == 0 {
fsz = 36
}
sz.Set(txt.Pose.Scale.X*float32(tsz.X)/fsz, txt.Pose.Scale.Y*float32(tsz.Y)/fsz)
return sz, true
}
func (txt *Text2D) Config() {
tm := txt.Scene.PlaneMesh2D()
txt.SetMesh(tm)
txt.Solid.Config()
txt.RenderText()
txt.Validate()
}
func (txt *Text2D) RenderText() {
if txt.Scene == nil || txt.Scene.TextShaper == nil {
return
}
// TODO(kai): do we need to set unit context sizes? (units.Context.SetSizes)
st := &txt.Styles
st.ToDots()
sty, tsty := st.NewRichText()
if sty.FillColor() == nil {
txt.usesDefaultColor = true
}
if txt.usesDefaultColor {
tsty.Color = colors.ToUniform(colors.Scheme.OnSurface)
}
sz := math32.Vec2(10000, 1000) // just a big size
txt.richText, _ = htmltext.HTMLToRich([]byte(txt.Text), sty, nil)
txt.textRender = txt.Scene.TextShaper.WrapLines(txt.richText, sty, tsty, sz)
sz = txt.textRender.Bounds.Size().Ceil()
if sz.X == 0 {
sz.X = 10
}
if sz.Y == 0 {
sz.Y = 10
}
marg := txt.Styles.TotalMargin()
sz.SetAdd(marg.Size())
txt.TextPos = marg.Pos().Round()
psty := styles.NewPaint()
psty.FromStyle(&txt.Styles)
pc := paint.NewPainter(sz)
pc.Paint = psty
if txt.Styles.Background != nil {
pc.Fill.Color = txt.Styles.Background
pc.Clear()
}
pc.DrawText(txt.textRender, txt.TextPos)
img := renderTextImage(pc)
var tx Texture
var err error
if txt.Material.Texture == nil {
txname := "__Text2D_" + txt.Name
tx, err = txt.Scene.TextureByName(txname)
if err != nil {
tx = &TextureBase{Name: txname}
tx.AsTextureBase().RGBA = img
txt.Scene.SetTexture(tx)
txt.Material.SetTexture(tx)
} else {
if gpu.Debug {
fmt.Printf("xyz.Text2D: error: texture name conflict: %s\n", txname)
}
txt.Material.SetTexture(tx)
}
} else {
tx = txt.Material.Texture
tx.AsTextureBase().RGBA = img
txt.Scene.Phong.SetTexture(tx.AsTextureBase().Name, phong.NewTexture(img))
}
}
// Validate checks that text has valid mesh and texture settings, etc
func (txt *Text2D) Validate() error {
// todo: validate more stuff here
return txt.Solid.Validate()
}
func (txt *Text2D) UpdateWorldMatrix(parWorld *math32.Matrix4) {
sz, ok := txt.TextSize()
if ok {
sc := math32.Vec3(sz.X, sz.Y, txt.Pose.Scale.Z)
ax := txt.Styles.Text.Align.Factor()
ay := float32(0.0)
al := txt.Styles.Text.AlignV
switch al {
case text.Start:
ay = -0.5
case text.Center:
ay = 0
case text.End:
ay = 0.5
}
ps := txt.Pose.Pos
ps.X += (0.5 - ax) * sz.X
ps.Y += ay * sz.Y
quat := txt.Pose.Quat
quat.SetMul(math32.NewQuatAxisAngle(math32.Vec3(0, 1, 0), math32.DegToRad(180)))
txt.Pose.Matrix.SetTransform(ps, quat, sc)
} else {
txt.Pose.UpdateMatrix()
}
txt.Pose.UpdateWorldMatrix(parWorld)
}
func (txt *Text2D) IsTransparent() bool {
return colors.ToUniform(txt.Styles.Background).A < 255
}
func (txt *Text2D) RenderClass() RenderClasses {
if txt.IsTransparent() {
return RClassTransTexture
}
return RClassOpaqueTexture
}
// Copyright (c) 2019, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !js
package xyz
import (
"image"
"cogentcore.org/core/base/iox/imagex"
"cogentcore.org/core/paint"
"cogentcore.org/core/text/shaped/shapers/shapedgt"
)
func initTextShaper(sc *Scene) {
sc.TextShaper = shapedgt.NewShaper()
}
// renderTextImage renders the given painter to an image.
func renderTextImage(pc *paint.Painter) *image.RGBA {
return imagex.AsRGBA(paint.RenderToImage(pc))
}
// Copyright (c) 2019, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package xyz
import (
"fmt"
"image"
"io/fs"
"log"
"log/slog"
"cogentcore.org/core/base/fsx"
"cogentcore.org/core/base/iox/imagex"
"cogentcore.org/core/gpu/phong"
)
// TextureName provides a GUI interface for choosing textures.
type TextureName string
// Texture is the interface for all textures.
type Texture interface {
// AsTextureBase returns the [TextureBase] for this texture,
// which contains the core data and functionality.
AsTextureBase() *TextureBase
// Image returns the image for the texture in the [image.RGBA] format used internally.
Image() *image.RGBA
}
//////// TextureBase
// TextureBase is the base texture implementation.
// It uses an [image.RGBA] as the underlying image storage
// to facilitate interface with GPU.
type TextureBase struct { //types:add --setters
// Name is the name of the texture;
// textures are connected to [Material]s by name.
Name string
// Transprent is whether the texture has transparency.
Transparent bool
// RGBA is the cached internal representation of the image.
RGBA *image.RGBA
}
func (tx *TextureBase) AsTextureBase() *TextureBase {
return tx
}
func (tx *TextureBase) Image() *image.RGBA {
return tx.RGBA
}
//////// TextureFile
// TextureFile is a texture loaded from a file
type TextureFile struct {
TextureBase
// filesystem for embedded etc
FS fs.FS
// filename for the texture
File string
}
// NewTextureFile adds a new texture from file of given name and filename
func NewTextureFile(sc *Scene, name string, filename string) *TextureFile {
tx := &TextureFile{}
tx.Name = name
dfs, fnm, err := fsx.DirFS(filename)
if err != nil {
slog.Error("xyz.NewTextureFile: Image not found error", "file:", filename, "error", err)
return nil
}
tx.FS = dfs
tx.File = fnm
sc.SetTexture(tx)
return tx
}
// NewTextureFileFS adds a new texture from file of given name and filename
func NewTextureFileFS(fsys fs.FS, sc *Scene, name string, filename string) *TextureFile {
tx := &TextureFile{}
tx.Name = name
tx.FS = fsys
tx.File = filename
sc.SetTexture(tx)
return tx
}
func (tx *TextureFile) Image() *image.RGBA {
if tx.RGBA != nil {
return tx.RGBA
}
if tx.File == "" {
err := fmt.Errorf("xyz.Texture: %v File must be set to a filename to load texture from", tx.Name)
log.Println(err)
return nil
}
img, _, err := imagex.OpenFS(tx.FS, tx.File)
if err != nil {
slog.Error("xyz.TextureFile: Image load error", "file:", tx.File, "error", err)
return nil
}
tx.RGBA = imagex.AsRGBA(img)
return tx.RGBA
}
// TextureCore is a dynamic texture material driven by a core.Scene.
// Anything rendered to the scene will be projected onto the surface of any
// solid using this texture. TODO: update this along with embed2d
type TextureCore struct {
TextureBase
// Scene2D *core.Scene
}
//////// Scene code
// SetTexture adds given texture to texture collection
// see NewTextureFile to add a texture that loads from file
func (sc *Scene) SetTexture(tx Texture) {
name := tx.AsTextureBase().Name
sc.Textures.Add(name, tx) // does replace
if sc.IsLive() {
sc.Phong.SetTexture(name, phong.NewTexture(tx.Image()))
}
}
func (sc *Scene) setAllTextures() {
ph := sc.Phong
for i, nm := range sc.Textures.Keys {
ph.SetTexture(nm, phong.NewTexture(sc.Textures.Values[i].Image()))
}
}
// TextureByName looks for texture by name, returning error if not found.
func (sc *Scene) TextureByName(nm string) (Texture, error) {
tx, ok := sc.Textures.AtTry(nm)
if ok {
return tx, nil
}
return nil, fmt.Errorf("Texture named: %v not found in Scene: %v", nm, sc.Name)
}
// TextureList returns a list of available textures (e.g., for chooser)
func (sc *Scene) TextureList() []string {
return sc.Textures.Keys
}
// Copyright (c) 2019, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package xyzcore
import (
"image/color"
"cogentcore.org/core/colors"
"cogentcore.org/core/events"
"cogentcore.org/core/events/key"
"cogentcore.org/core/math32"
"cogentcore.org/core/tree"
"cogentcore.org/core/xyz"
)
// SelectionModes are selection modes for Scene
type SelectionModes int32 //enums:enum
const (
// NotSelectable means that selection events are ignored entirely
NotSelectable SelectionModes = iota
// Selectable means that nodes can be selected but no visible consequence occurs
Selectable
// SelectionBox means that a selection bounding box is drawn around selected nodes
SelectionBox
// Manipulable means that a manipulation box will be created for selected nodes,
// which can update the Pose parameters dynamically.
Manipulable
)
const (
// SelectedBoxName is the reserved top-level Group name for holding
// a bounding box or manipulator for currently selected object.
// also used for meshes representing the box.
SelectedBoxName = "__SelectedBox"
// ManipBoxName is the reserved top-level name for meshes
// representing the manipulation box.
ManipBoxName = "__ManipBox"
)
// SelectionParams are parameters for selection / manipulation box
type SelectionParams struct {
// color for selection box (default yellow)
Color color.RGBA
// width of the box lines, scaled by view distance
Width float32 `default:"0.001"`
// radius of the manipulation control point spheres, scaled by view distance
Radius float32 `default:"0.005"`
}
func (sp *SelectionParams) Defaults() {
sp.Color = colors.Yellow
sp.Width = .001
sp.Radius = .005
}
/////////////////////////////////////////////////////////////////////////////////////
// Scene interface
// SetSelected -- if Selectable is true, then given object is selected
// if node is nil then selection is reset.
func (sw *Scene) SetSelected(nd xyz.Node) {
if sw.SelectionMode == NotSelectable {
return
}
if sw.CurrentSelected == nd {
return
}
xy := sw.XYZ
if nd == nil {
// if sv.CurSel != nil {
// sv.CurSel.AsNode().SetSelected(false)
// }
sw.CurrentManipPoint = nil
sw.CurrentSelected = nil
xy.DeleteChildByName(SelectedBoxName)
xy.DeleteChildByName(ManipBoxName)
return
}
manip, ok := nd.(*ManipPoint)
if ok {
sw.CurrentManipPoint = manip
return
}
sw.CurrentSelected = nd
// nd.AsNode().SetSelected()
switch sw.SelectionMode {
case Selectable:
return
case SelectionBox:
sw.SelectBox()
case Manipulable:
sw.ManipBox()
}
}
// SelectBox draws a selection box around selected node
func (sw *Scene) SelectBox() {
if sw.CurrentSelected == nil {
return
}
sc := sw.XYZ
nb := sw.CurrentSelected.AsNodeBase()
sc.DeleteChildByName(SelectedBoxName) // get rid of existing
clr := sw.SelectionParams.Color
g := xyz.NewGroup(sc)
g.SetName(SelectedBoxName)
xyz.InitLineBox(g, SelectedBoxName, nb.WorldBBox.BBox, sw.SelectionParams.Width, clr, xyz.Inactive)
sw.NeedsRender()
}
// ManipBox draws a manipulation box around selected node
func (sw *Scene) ManipBox() {
sw.CurrentManipPoint = nil
if sw.CurrentSelected == nil {
return
}
sc := sw.XYZ
nm := ManipBoxName
nb := sw.CurrentSelected.AsNodeBase()
// todo: definitely need to use plan based updating here!
sc.DeleteChildByName(nm) // get rid of existing
clr := sw.SelectionParams.Color
cdist := math32.Max(sc.Camera.DistanceTo(sc.Camera.Target), 1.0)
bbox := nb.WorldBBox.BBox
mb := xyz.NewGroup(sc)
mb.SetName(nm)
xyz.InitLineBox(mb, nm, bbox, sw.SelectionParams.Width*cdist, clr, xyz.Inactive)
mbspm := xyz.NewSphere(sc, nm+"-pt", sw.SelectionParams.Radius*cdist, 16)
bbox.Min.SetSub(mb.Pose.Pos)
bbox.Max.SetSub(mb.Pose.Pos)
NewManipPoint(mb, nm+"-lll", mbspm.Name, clr, bbox.Min)
NewManipPoint(mb, nm+"-llu", mbspm.Name, clr, math32.Vec3(bbox.Min.X, bbox.Min.Y, bbox.Max.Z))
NewManipPoint(mb, nm+"-lul", mbspm.Name, clr, math32.Vec3(bbox.Min.X, bbox.Max.Y, bbox.Min.Z))
NewManipPoint(mb, nm+"-ull", mbspm.Name, clr, math32.Vec3(bbox.Max.X, bbox.Min.Y, bbox.Min.Z))
NewManipPoint(mb, nm+"-luu", mbspm.Name, clr, math32.Vec3(bbox.Min.X, bbox.Max.Y, bbox.Max.Z))
NewManipPoint(mb, nm+"-ulu", mbspm.Name, clr, math32.Vec3(bbox.Max.X, bbox.Min.Y, bbox.Max.Z))
NewManipPoint(mb, nm+"-uul", mbspm.Name, clr, math32.Vec3(bbox.Max.X, bbox.Max.Y, bbox.Min.Z))
NewManipPoint(mb, nm+"-uuu", mbspm.Name, clr, bbox.Max)
sw.NeedsRender()
}
// ManipPoint is a manipulation control point.
type ManipPoint struct { //core:no-new
xyz.Solid
}
// NewManipPoint adds a new manipulation point
func NewManipPoint(parent tree.Node, name string, meshName string, clr color.RGBA, pos math32.Vector3) *ManipPoint { // TODO: more standard New functions?
mpt := tree.New[ManipPoint](parent)
mpt.SetName(name)
mpt.SetMeshName(meshName)
mpt.Defaults()
mpt.Pose.Pos = pos
mpt.Material.Color = clr
return mpt
}
func (sw *Scene) handleSelectEvents() {
sw.On(events.MouseDown, sw.handleSelectEventsImpl)
sw.On(events.DoubleClick, sw.handleSelectEventsImpl)
}
func (sw *Scene) handleSelectEventsImpl(e events.Event) {
xy := sw.XYZ
pos := sw.frameBBox().Min
e.SetLocalOff(e.LocalOff().Add(pos))
ns := xyz.NodesUnderPoint(xy, e.Pos())
nsel := len(ns)
switch nsel {
case 0:
sw.SetSelected(nil)
case 1:
sw.SetSelected(ns[0])
default:
for _, n := range ns {
if _, ok := n.(*ManipPoint); ok {
sw.SetSelected(n)
return
}
}
if sw.CurrentSelected == nil {
sw.SetSelected(ns[0])
} else {
got := false
for i, n := range ns {
if sw.CurrentSelected == n {
if i < nsel-1 {
sw.SetSelected(ns[i+1])
} else {
sw.SetSelected(ns[0])
}
got = true
break
}
}
if !got {
sw.SetSelected(ns[0])
}
}
}
}
func (sw *Scene) handleSlideEvents() {
sw.On(events.SlideMove, func(e events.Event) {
e.SetHandled()
pos := sw.frameBBox().Min
e.SetLocalOff(e.LocalOff().Add(pos))
xy := sw.XYZ
if sw.CurrentManipPoint == nil || sw.CurrentSelected == nil {
xy.SlideMoveEvent(e)
sw.NeedsRender()
return
}
sn := sw.CurrentSelected.AsNodeBase()
mpt := sw.CurrentManipPoint
mb := mpt.Parent.(*xyz.Group)
del := e.PrevDelta()
dx := float32(del.X)
dy := float32(del.Y)
mpos := mpt.Name[len(ManipBoxName)+1:] // has ull etc for where positioned
camd, sgn := xy.Camera.ViewMainAxis()
var dm math32.Vector3 // delta multiplier
if mpos[math32.X] == 'u' {
dm.X = 1
} else {
dm.X = -1
}
if mpos[math32.Y] == 'u' {
dm.Y = 1
} else {
dm.Y = -1
}
if mpos[math32.Z] == 'u' {
dm.Z = 1
} else {
dm.Z = -1
}
var dd math32.Vector3
switch camd {
case math32.X:
dd.Z = -sgn * dx
dd.Y = -dy
case math32.Y:
dd.X = dx
dd.Z = sgn * dy
case math32.Z:
dd.X = sgn * dx
dd.Y = -dy
}
// fmt.Printf("mpos: %v camd: %v sgn: %v dm: %v\n", mpos, camd, sgn, dm)
cdist := xy.Camera.DistanceTo(xy.Camera.Target)
scDel := float32(.0005) * cdist
panDel := float32(.0005) * cdist
// todo: use SVG ApplyDeltaXForm logic
switch {
case e.HasAllModifiers(key.Control): // scale
dsc := dd.Mul(dm).MulScalar(scDel)
mb.Pose.Scale.SetAdd(dsc)
msc := dsc.MulMatrix4AsVector4(&sn.Pose.ParMatrix, 0) // this is not quite right but close enough
sn.Pose.Scale.SetAdd(msc)
case e.HasAllModifiers(key.Alt): // rotation
dang := -sgn * dm.Y * (dx + dy)
if camd == math32.Y {
dang = -sgn * dm.X * (dy + dx)
}
dang *= 0.01 * cdist
var rvec math32.Vector3
rvec.SetDim(camd, 1)
mb.Pose.RotateOnAxis(rvec.X, rvec.Y, rvec.Z, dang)
inv, _ := sn.Pose.WorldMatrix.Inverse() // undo full transform
mvec := rvec.MulMatrix4AsVector4(inv, 0)
sn.Pose.RotateOnAxis(mvec.X, mvec.Y, mvec.Z, dang)
// case key.HasAllModifierBits(e.Modifiers, key.Shift):
default: // position
dpos := dd.MulScalar(panDel)
inv, _ := sn.Pose.ParMatrix.Inverse() // undo parent's transform
mpos := dpos.MulMatrix4AsVector4(inv, 0)
sn.Pose.Pos.SetAdd(mpos)
mb.Pose.Pos.SetAdd(dpos)
}
sw.NeedsRender()
})
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !js
package xyzcore
import (
"errors"
"image"
"image/draw"
"cogentcore.org/core/core"
"cogentcore.org/core/gpu"
"cogentcore.org/core/gpu/gpudraw"
"cogentcore.org/core/math32"
"cogentcore.org/core/system"
"cogentcore.org/core/system/composer"
)
// xyzSource implements [composer.Source] for core direct rendering.
type xyzSource struct {
destBBox, srcBBox image.Rectangle
texture *gpu.Texture
sw *Scene
}
func getGPUDrawer(c composer.Composer) *gpudraw.Drawer {
cd := c.(*composer.ComposerDrawer)
agd, ok := cd.Drawer.(*gpudraw.Drawer)
if !ok {
return nil
}
return agd.AsGPUDrawer()
}
func (xr *xyzSource) Draw(c composer.Composer) {
gdrw := getGPUDrawer(c)
if gdrw == nil {
return
}
if xr.sw.XYZ == nil {
return
}
xr.sw.XYZ.Lock()
gdrw.UseTexture(xr.texture)
gdrw.CopyUsed(xr.destBBox.Min, xr.srcBBox, draw.Src, math32.NoFlipY)
xr.sw.XYZ.Unlock()
}
// RenderSource returns the [composer.Source] for direct rendering.
func (sw *Scene) RenderSource(op draw.Op) composer.Source {
if sw.XYZ == nil || sw.XYZ.Frame == nil || !sw.IsVisible() {
return nil
}
sw.XYZ.Lock()
defer sw.XYZ.Unlock()
rt := sw.XYZ.Frame.(*gpu.RenderTexture)
tex := rt.CurrentFrame()
// The frame has the size of the whole scene, of which only the visible
// part, Geom.ContentBBox, is drawn, when it is scrolled out of its parent.
visible := sw.Geom.ContentBBox
sbb := visible.Sub(sw.frameBBox().Min).Intersect(tex.Format.Bounds())
if sbb.Empty() {
return nil
}
bb := image.Rectangle{Max: sbb.Size()}.Add(visible.Min.Add(sw.Scene.SceneGeom.Pos))
return &xyzSource{destBBox: bb, srcBBox: sbb, texture: tex, sw: sw}
}
// configFrame configures the render frame in a platform-specific manner.
func (sw *Scene) configFrame(sz image.Point) {
win := sw.WidgetBase.Scene.Events.RenderWindow()
if win == nil {
return
}
system.TheApp.RunOnMain(func() {
gdrw := getGPUDrawer(win.SystemWindow.Composer())
if gdrw == nil {
return
}
sf, ok := gdrw.Renderer().(*gpu.Surface)
if !ok {
core.ErrorSnackbar(sw, errors.New("WebGPU not available for 3D rendering"))
return
}
sw.XYZ.ConfigOffscreenFromSurface(sf) // does a full build if Frame == nil, else just new size
})
}
// destroyFrame releases platform-specific resources of the render frame.
func (sw *Scene) destroyFrame() {}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package xyzcore provides a core-based GUI view for a 3D xyz scene.
package xyzcore
//go:generate core generate
import (
"image"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/tree"
"cogentcore.org/core/xyz"
)
// Scene is a core.Widget that manages a xyz.Scene,
// providing the basic rendering logic for the 3D scene
// in the 2D core GUI context.
type Scene struct {
core.WidgetBase
// XYZ is the 3D xyz.Scene
XYZ *xyz.Scene `set:"-"`
// how to deal with selection / manipulation events
SelectionMode SelectionModes
// currently selected node
CurrentSelected xyz.Node `copier:"-" json:"-" xml:"-" display:"-"`
// currently selected manipulation control point
CurrentManipPoint *ManipPoint `copier:"-" json:"-" xml:"-" display:"-"`
// parameters for selection / manipulation box
SelectionParams SelectionParams `display:"inline"`
}
// NewSceneForScene returns a new [Scene] for existing [xyz.Scene],
// in given parent (optional).
func NewSceneForScene(sc *xyz.Scene, parent ...tree.Node) *Scene {
sc.Destroy() // reset any existing GPU stuff, so it gets properly rebuilt
n := &Scene{XYZ: sc}
ni := any(n).(tree.Node)
var p tree.Node
if len(parent) > 0 {
p = parent[0]
n.Scene = p.(core.Widget).AsWidget().Scene
}
tree.InitNode(ni)
if p == nil {
n.SetName(n.NodeType().IDName)
return n
}
p.AsTree().Children = append(p.AsTree().Children, ni)
tree.SetParent(ni, p)
return n
}
func (sw *Scene) Init() {
sw.WidgetBase.Init()
if sw.XYZ == nil {
sw.XYZ = xyz.NewScene()
}
sw.SelectionParams.Defaults()
sw.Styler(func(s *styles.Style) {
s.SetAbilities(true, abilities.Clickable, abilities.Focusable, abilities.Activatable, abilities.Slideable, abilities.LongHoverable, abilities.DoubleClickable)
s.Grow.Set(1, 1)
s.Min.Set(units.Em(2))
})
sw.On(events.Scroll, func(e events.Event) {
pos := sw.frameBBox().Min
e.SetLocalOff(e.LocalOff().Add(pos))
sw.XYZ.MouseScrollEvent(e.(*events.MouseScroll))
sw.NeedsRender()
})
sw.On(events.KeyChord, func(e events.Event) {
sw.XYZ.KeyChordEvent(e)
sw.NeedsRender()
})
sw.handleSlideEvents()
sw.handleSelectEvents()
sw.Updater(func() {
sw.XYZ.Update()
sw.ConfigXYZ()
})
}
// OnAdd registers [tree.NodeBase.This] for direct rendering, which is the
// outer widget when a type embeds Scene, so that the context of its render
// source is that of the canvas made by configFrame on the web.
func (sw *Scene) OnAdd() {
sw.WidgetBase.OnAdd()
sw.Scene.AddDirectRender(sw.This.(core.Widget))
}
func (sw *Scene) Destroy() {
sw.Scene.DeleteDirectRender(sw.This.(core.Widget))
// A composite of the window that is being drawn in another goroutine
// can use the frame texture of the scene after its source is drawn
// (see [xyzSource.Draw]), so the scene is destroyed under the lock of
// the window, which the composite holds.
if win := sw.Scene.Events.RenderWindow(); win != nil && win.SystemWindow.Lock() {
sw.XYZ.Destroy()
win.SystemWindow.Unlock()
} else {
sw.XYZ.Destroy()
}
sw.destroyFrame()
sw.WidgetBase.Destroy()
}
// SceneXYZ returns the xyz.Scene
func (sw *Scene) SceneXYZ() *xyz.Scene {
return sw.XYZ
}
func (sw *Scene) SizeFinal() {
sw.WidgetBase.SizeFinal()
if sw.XYZ.NumChildren() == 0 {
sw.XYZ.Update()
}
}
func (sw *Scene) Render() {
sw.ConfigXYZ() // ensure configured: no cost if not
if sw.XYZ.Frame == nil {
return
}
sw.XYZ.Render()
}
// frameBBox returns the bounding box of the whole render frame of the
// scene, in the coordinates of the core Scene. Unlike Geom.ContentBBox, it
// is not clipped by the parents of the widget, so that the size of the frame
// stays the same while the widget is partly scrolled out of its parent, and
// only the visible part of it, Geom.ContentBBox, is shown.
func (sw *Scene) frameBBox() image.Rectangle {
return math32.RectFromPosSizeMax(sw.Geom.Pos.Content, sw.Geom.Size.Actual.Content)
}
func (sw *Scene) ConfigXYZ() {
if !sw.IsVisible() {
return
}
// The visible part of the scene is within its frame once the layout is
// done. This only differs if the scene is rendered in the middle of a
// layout, where its size is its minimum size until it is allocated its
// space (which Toolbar used to do): the frame then keeps its size.
fb := sw.frameBBox()
if !sw.Geom.ContentBBox.In(fb) {
return
}
sz := fb.Size()
if sz.X <= 0 || sz.Y <= 0 {
sz = image.Point{10, 10}
}
sw.XYZ.Geom.Size = sz
doRebuild := sw.NeedsRebuild() // settings-driven full rebuild
if sw.XYZ.Frame != nil {
cursz := sw.XYZ.Frame.Render().Format.Size
if cursz == sz && !doRebuild {
return
}
} else {
doRebuild = false // will be done automatically b/c Frame == nil
}
sw.configFrame(sz)
if doRebuild {
sw.XYZ.Rebuild()
}
sw.NeedsRender()
}
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package xyzcore
import (
"fmt"
"cogentcore.org/core/core"
"cogentcore.org/core/events"
"cogentcore.org/core/events/key"
"cogentcore.org/core/icons"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/tree"
"cogentcore.org/core/xyz"
)
// SceneEditor provides a toolbar controller and manipulation abilities
// for a [Scene].
type SceneEditor struct {
core.Frame
}
// NewSceneEditorForScene returns a new [SceneEditor] for existing [xyz.Scene],
// in given parent (if non-nil).
func NewSceneEditorForScene(sc *xyz.Scene, parent ...tree.Node) *SceneEditor {
n := &SceneEditor{}
ni := any(n).(tree.Node)
tree.InitNode(ni)
var p tree.Node
if len(parent) > 0 {
p = parent[0]
n.Scene = p.(core.Widget).AsWidget().Scene
}
sw := NewSceneForScene(sc, ni)
sw.SetName("scene")
if p == nil {
n.SetName(n.NodeType().IDName)
return n
}
p.AsTree().Children = append(p.AsTree().Children, ni)
tree.SetParent(ni, p)
return n
}
func (sv *SceneEditor) Init() {
sv.Frame.Init()
sv.Styler(func(s *styles.Style) {
s.Direction = styles.Column
s.Grow.Set(1, 1)
})
tree.AddChildAt(sv, "scene", func(w *Scene) {})
tree.AddChildAt(sv, "tb", func(w *core.Toolbar) {
w.Maker(sv.MakeToolbar)
})
}
// SceneWidget returns the [Scene] widget.
func (sv *SceneEditor) SceneWidget() *Scene {
return sv.ChildByName("scene", 0).(*Scene)
}
// SceneXYZ returns the [xyz.Scene].
func (sv *SceneEditor) SceneXYZ() *xyz.Scene {
return sv.SceneWidget().XYZ
}
func (sv *SceneEditor) MakeToolbar(p *tree.Plan) {
sw := sv.SceneWidget()
sc := sv.SceneXYZ()
tree.Add(p, func(w *core.Button) {
w.SetIcon(icons.Update).SetTooltip("reset to default initial display").
OnClick(func(e events.Event) {
sc.SetCamera("default")
sw.Update()
sv.NeedsRender()
})
})
tree.Add(p, func(w *core.Button) {
w.SetIcon(icons.ZoomIn).SetTooltip("zoom in")
w.Styler(func(s *styles.Style) {
s.SetAbilities(true, abilities.RepeatClickable)
})
w.OnClick(func(e events.Event) {
sc.Camera.Zoom(-.05)
sv.NeedsRender()
})
})
tree.Add(p, func(w *core.Button) {
w.SetIcon(icons.ZoomOut).SetTooltip("zoom out")
w.Styler(func(s *styles.Style) {
s.SetAbilities(true, abilities.RepeatClickable)
})
w.OnClick(func(e events.Event) {
sc.Camera.Zoom(.05)
sv.NeedsRender()
})
})
tree.Add(p, func(w *core.Separator) {})
tree.Add(p, func(w *core.Text) {
w.SetText("Rot:").SetTooltip("rotate display")
})
tree.Add(p, func(w *core.Button) {
w.SetIcon(icons.KeyboardArrowLeft)
w.Styler(func(s *styles.Style) {
s.SetAbilities(true, abilities.RepeatClickable)
})
w.OnClick(func(e events.Event) {
sc.Camera.Orbit(5, 0)
sv.NeedsRender()
})
})
tree.Add(p, func(w *core.Button) {
w.SetIcon(icons.KeyboardArrowUp)
w.Styler(func(s *styles.Style) {
s.SetAbilities(true, abilities.RepeatClickable)
})
w.OnClick(func(e events.Event) {
sc.Camera.Orbit(0, 5)
sv.NeedsRender()
})
})
tree.Add(p, func(w *core.Button) {
w.SetIcon(icons.KeyboardArrowDown)
w.Styler(func(s *styles.Style) {
s.SetAbilities(true, abilities.RepeatClickable)
})
w.OnClick(func(e events.Event) {
sc.Camera.Orbit(0, -5)
sv.NeedsRender()
})
})
tree.Add(p, func(w *core.Button) {
w.SetIcon(icons.KeyboardArrowRight)
w.Styler(func(s *styles.Style) {
s.SetAbilities(true, abilities.RepeatClickable)
})
w.OnClick(func(e events.Event) {
sc.Camera.Orbit(-5, 0)
sv.NeedsRender()
})
})
tree.Add(p, func(w *core.Separator) {})
tree.Add(p, func(w *core.Text) {
w.SetText("Pan:").SetTooltip("pan display")
})
tree.Add(p, func(w *core.Button) {
w.SetIcon(icons.KeyboardArrowLeft)
w.Styler(func(s *styles.Style) {
s.SetAbilities(true, abilities.RepeatClickable)
})
w.OnClick(func(e events.Event) {
sc.Camera.Pan(-.2, 0)
sv.NeedsRender()
})
})
tree.Add(p, func(w *core.Button) {
w.SetIcon(icons.KeyboardArrowUp)
w.Styler(func(s *styles.Style) {
s.SetAbilities(true, abilities.RepeatClickable)
})
w.OnClick(func(e events.Event) {
sc.Camera.Pan(0, .2)
sv.NeedsRender()
})
})
tree.Add(p, func(w *core.Button) {
w.SetIcon(icons.KeyboardArrowDown)
w.Styler(func(s *styles.Style) {
s.SetAbilities(true, abilities.RepeatClickable)
})
w.OnClick(func(e events.Event) {
sc.Camera.Pan(0, -.2)
sv.NeedsRender()
})
})
tree.Add(p, func(w *core.Button) {
w.SetIcon(icons.KeyboardArrowRight)
w.Styler(func(s *styles.Style) {
s.SetAbilities(true, abilities.RepeatClickable)
})
w.OnClick(func(e events.Event) {
sc.Camera.Pan(.2, 0)
sv.NeedsRender()
})
})
tree.Add(p, func(w *core.Separator) {})
tree.Add(p, func(w *core.Text) {
w.SetText("Save:")
})
for i := 1; i <= 4; i++ {
nm := fmt.Sprintf("%d", i)
tree.AddAt(p, "save_"+nm, func(w *core.Button) {
w.SetText(nm).
SetTooltip("first click (or + Shift) saves current view, second click restores to saved state").
OnClick(func(e events.Event) {
cam := nm
if e.HasAllModifiers(key.Shift) {
sc.SaveCamera(cam)
} else {
err := sc.SetCamera(cam)
if err != nil {
sc.SaveCamera(cam)
}
}
fmt.Printf("Camera %s: %v\n", cam, sc.Camera.GenGoSet(""))
sv.NeedsRender()
})
})
}
tree.Add(p, func(w *core.Separator) {})
tree.Add(p, func(w *core.Chooser) {
core.Bind(&sw.SelectionMode, w)
})
tree.Add(p, func(w *core.Button) {
w.SetText("Edit").SetIcon(icons.Edit).
SetTooltip("edit the currently selected object").
OnClick(func(e events.Event) {
if sw.CurrentSelected == nil {
return
}
d := core.NewBody("Selected Node")
core.NewForm(d).SetStruct(sw.CurrentSelected)
d.RunWindowDialog(sv)
})
})
tree.Add(p, func(w *core.Button) {
w.SetText("Edit Scene").SetIcon(icons.Edit).
SetTooltip("edit the 3D Scene object (for access to meshes, textures etc)").
OnClick(func(e events.Event) {
d := core.NewBody("xyz.Scene")
core.NewForm(d).SetStruct(sv.SceneXYZ())
d.RunWindowDialog(sv)
})
})
}
// Copyright (c) 2019, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package xyzcore
import (
"cogentcore.org/core/core"
"cogentcore.org/core/icons"
"cogentcore.org/core/xyz"
)
func init() {
core.AddValueType[xyz.MeshName, MeshButton]()
}
// MeshButton represents an [xyz.MeshName] value with a button.
type MeshButton struct {
core.Button
MeshName string
}
func (mb *MeshButton) WidgetValue() any { return &mb.MeshName }
func (mb *MeshButton) Init() {
mb.Button.Init()
mb.SetType(core.ButtonTonal).SetIcon(icons.DeployedCode)
mb.Updater(func() {
if mb.MeshName == "" {
mb.SetText("Select mesh")
} else {
mb.SetText(mb.MeshName)
}
})
core.InitValueButton(mb, false, func(d *core.Body) {
d.SetTitle("Select a mesh")
// TODO: https://github.com/cogentcore/core/issues/1023
// if v.OwnKind != reflect.Struct {
// return false, nil
// }
// ndi, ok := v.Owner.(xyz.Node)
// if !ok {
// return false, nil
// }
// sci := ndi.ParentByType(xyz.SceneType, tree.Embeds)
// if sci == nil {
// slog.Error("missing parent scene for node", "node", ndi)
// return false, nil
// }
// sc := sci.(*xyz.Scene)
// sl := sc.MeshList()
// sort.Strings(sl)
// si := 0
// cur := reflectx.ToString(v.Value.Interface())
// core.NewList(d).SetSlice(&sl).SetSelectedValue(cur).BindSelect(&si)
// return true, func() {
// if si >= 0 {
// ms := sl[si]
// v.SetValue(ms)
// v.Update()
// }
// }
})
}
/*
TODO: This doesn't work because texture is on Material which doesn't have a pointer to the Scene! (https://github.com/cogentcore/core/issues/1023)
// Value restylesers TexValue as the viewer of TexName
func (mn TexName) Widget() core.Value {
vv := TexValue{}
vv.Init(&vv)
return &vv
}
// TexValue presents an action for displaying a TexName and selecting
// textures from a ChooserDialog
type TexValue struct {
core.ValueBase
}
func (vv *TexValue) WidgetType() reflect.Type {
vv.WidgetTyp = core.TypeAction
return vv.WidgetTyp
}
func (vv *TexValue) UpdateWidget() {
if vv.Widget == nil {
return
}
ac := vv.Widget.(*core.Button)
txt := reflectx.ToString(vv.Value.Interface())
if txt == "" {
txt = "(none, click to select)"
}
ac.SetText(txt)
}
func (vv *TexValue) Config(widg core.Node2D) {
vv.Widget = widg
ac := vv.Widget.(*core.Button)
ac.SetProp("border-radius", units.NewPx(4))
ac.ActionSig.ConnectOnly(vv.This, func(recv, send tree.Node, sig int64, data any) {
vvv, _ := recv.Embed(TypeTexValue).(*TexValue)
ac := vvv.Widget.(*core.Button)
vvv.Activate(ac.ViewportSafe(), nil, nil)
})
vv.UpdateWidget()
}
func (vv *TexValue) HasAction() bool {
return true
}
func (vv *TexValue) Activate(vp *core.Viewport2D, dlgRecv tree.Node, dlgFunc tree.RecvFunc) {
if vv.IsInactive() {
return
}
if vv.OwnKind != reflect.Struct {
return
}
mati, ok := vv.Owner.(*Material)
if !ok {
return
}
sci, err := ndi.ParentByType(TypeScene, tree.Embeds)
if errors.Log1(err) != nil {
return
}
sc := sci.Embed(TypeScene).(*Scene)
sl := sc.TextureList()
sort.Strings(sl)
cur := reflectx.ToString(vv.Value.Interface())
desc, _ := vv.Tag("desc")
core.ListSelectDialog(vp, &sl, cur, core.DlgOpts{Title: "Select a Texture", Prompt: desc}, nil,
vv.This, func(recv, send tree.Node, sig int64, data any) {
if sig == int64(core.DialogAccepted) {
ddlg := send.Embed(core.TypeDialog).(*core.Dialog)
si := core.ListSelectDialogValue(ddlg)
if si >= 0 {
vv.SetValue(sl[si])
vv.UpdateWidget()
}
}
if dlgRecv != nil && dlgFunc != nil {
dlgFunc(dlgRecv, send, sig, data)
}
})
}
*/