repo stringlengths 6 47 | file_url stringlengths 77 269 | file_path stringlengths 5 186 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-07 08:35:43 2026-01-07 08:55:24 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/docker/client/swarm_unlock.go | vendor/github.com/docker/docker/client/swarm_unlock.go | package client
import (
"context"
"github.com/docker/docker/api/types/swarm"
)
// SwarmUnlock unlocks locked swarm.
func (cli *Client) SwarmUnlock(ctx context.Context, req swarm.UnlockRequest) error {
resp, err := cli.post(ctx, "/swarm/unlock", nil, req, nil)
ensureReaderClosed(resp)
return err
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/docker/client/events.go | vendor/github.com/docker/docker/client/events.go | package client
import (
"context"
"encoding/json"
"net/url"
"time"
"github.com/docker/docker/api/types/events"
"github.com/docker/docker/api/types/filters"
timetypes "github.com/docker/docker/api/types/time"
)
// Events returns a stream of events in the daemon. It's up to the caller to close the stream
// by cancelling the context. Once the stream has been completely read an io.EOF error will
// be sent over the error channel. If an error is sent all processing will be stopped. It's up
// to the caller to reopen the stream in the event of an error by reinvoking this method.
func (cli *Client) Events(ctx context.Context, options events.ListOptions) (<-chan events.Message, <-chan error) {
messages := make(chan events.Message)
errs := make(chan error, 1)
started := make(chan struct{})
go func() {
defer close(errs)
query, err := buildEventsQueryParams(cli.version, options)
if err != nil {
close(started)
errs <- err
return
}
resp, err := cli.get(ctx, "/events", query, nil)
if err != nil {
close(started)
errs <- err
return
}
defer resp.Body.Close()
decoder := json.NewDecoder(resp.Body)
close(started)
for {
select {
case <-ctx.Done():
errs <- ctx.Err()
return
default:
var event events.Message
if err := decoder.Decode(&event); err != nil {
errs <- err
return
}
select {
case messages <- event:
case <-ctx.Done():
errs <- ctx.Err()
return
}
}
}
}()
<-started
return messages, errs
}
func buildEventsQueryParams(cliVersion string, options events.ListOptions) (url.Values, error) {
query := url.Values{}
ref := time.Now()
if options.Since != "" {
ts, err := timetypes.GetTimestamp(options.Since, ref)
if err != nil {
return nil, err
}
query.Set("since", ts)
}
if options.Until != "" {
ts, err := timetypes.GetTimestamp(options.Until, ref)
if err != nil {
return nil, err
}
query.Set("until", ts)
}
if options.Filters.Len() > 0 {
//nolint:staticcheck // ignore SA1019 for old code
filterJSON, err := filters.ToParamWithVersion(cliVersion, options.Filters)
if err != nil {
return nil, err
}
query.Set("filters", filterJSON)
}
return query, nil
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/docker/client/image_save.go | vendor/github.com/docker/docker/client/image_save.go | package client
import (
"context"
"io"
"net/url"
)
// ImageSave retrieves one or more images from the docker host as an io.ReadCloser.
//
// Platforms is an optional parameter that specifies the platforms to save from the image.
// This is only has effect if the input image is a multi-platform image.
func (cli *Client) ImageSave(ctx context.Context, imageIDs []string, saveOpts ...ImageSaveOption) (io.ReadCloser, error) {
var opts imageSaveOpts
for _, opt := range saveOpts {
if err := opt.Apply(&opts); err != nil {
return nil, err
}
}
query := url.Values{
"names": imageIDs,
}
if len(opts.apiOptions.Platforms) > 0 {
if err := cli.NewVersionError(ctx, "1.48", "platform"); err != nil {
return nil, err
}
p, err := encodePlatforms(opts.apiOptions.Platforms...)
if err != nil {
return nil, err
}
query["platform"] = p
}
resp, err := cli.get(ctx, "/images/get", query, nil)
if err != nil {
return nil, err
}
return resp.Body, nil
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/docker/client/container_top.go | vendor/github.com/docker/docker/client/container_top.go | package client
import (
"context"
"encoding/json"
"net/url"
"strings"
"github.com/docker/docker/api/types/container"
)
// ContainerTop shows process information from within a container.
func (cli *Client) ContainerTop(ctx context.Context, containerID string, arguments []string) (container.TopResponse, error) {
containerID, err := trimID("container", containerID)
if err != nil {
return container.TopResponse{}, err
}
query := url.Values{}
if len(arguments) > 0 {
query.Set("ps_args", strings.Join(arguments, " "))
}
resp, err := cli.get(ctx, "/containers/"+containerID+"/top", query, nil)
defer ensureReaderClosed(resp)
if err != nil {
return container.TopResponse{}, err
}
var response container.TopResponse
err = json.NewDecoder(resp.Body).Decode(&response)
return response, err
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/docker/client/container_inspect.go | vendor/github.com/docker/docker/client/container_inspect.go | package client
import (
"bytes"
"context"
"encoding/json"
"io"
"net/url"
"github.com/docker/docker/api/types/container"
)
// ContainerInspect returns the container information.
func (cli *Client) ContainerInspect(ctx context.Context, containerID string) (container.InspectResponse, error) {
containerID, err := trimID("container", containerID)
if err != nil {
return container.InspectResponse{}, err
}
resp, err := cli.get(ctx, "/containers/"+containerID+"/json", nil, nil)
defer ensureReaderClosed(resp)
if err != nil {
return container.InspectResponse{}, err
}
var response container.InspectResponse
err = json.NewDecoder(resp.Body).Decode(&response)
return response, err
}
// ContainerInspectWithRaw returns the container information and its raw representation.
func (cli *Client) ContainerInspectWithRaw(ctx context.Context, containerID string, getSize bool) (container.InspectResponse, []byte, error) {
containerID, err := trimID("container", containerID)
if err != nil {
return container.InspectResponse{}, nil, err
}
query := url.Values{}
if getSize {
query.Set("size", "1")
}
resp, err := cli.get(ctx, "/containers/"+containerID+"/json", query, nil)
defer ensureReaderClosed(resp)
if err != nil {
return container.InspectResponse{}, nil, err
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return container.InspectResponse{}, nil, err
}
var response container.InspectResponse
rdr := bytes.NewReader(body)
err = json.NewDecoder(rdr).Decode(&response)
return response, body, err
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/docker/client/network_create.go | vendor/github.com/docker/docker/client/network_create.go | package client
import (
"context"
"encoding/json"
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/api/types/versions"
)
// NetworkCreate creates a new network in the docker host.
func (cli *Client) NetworkCreate(ctx context.Context, name string, options network.CreateOptions) (network.CreateResponse, error) {
// Make sure we negotiated (if the client is configured to do so),
// as code below contains API-version specific handling of options.
//
// Normally, version-negotiation (if enabled) would not happen until
// the API request is made.
if err := cli.checkVersion(ctx); err != nil {
return network.CreateResponse{}, err
}
networkCreateRequest := network.CreateRequest{
CreateOptions: options,
Name: name,
}
if versions.LessThan(cli.version, "1.44") {
enabled := true
networkCreateRequest.CheckDuplicate = &enabled //nolint:staticcheck // ignore SA1019: CheckDuplicate is deprecated since API v1.44.
}
resp, err := cli.post(ctx, "/networks/create", nil, networkCreateRequest, nil)
defer ensureReaderClosed(resp)
if err != nil {
return network.CreateResponse{}, err
}
var response network.CreateResponse
err = json.NewDecoder(resp.Body).Decode(&response)
return response, err
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/docker/client/info.go | vendor/github.com/docker/docker/client/info.go | package client
import (
"context"
"encoding/json"
"fmt"
"net/url"
"github.com/docker/docker/api/types/system"
)
// Info returns information about the docker server.
func (cli *Client) Info(ctx context.Context) (system.Info, error) {
var info system.Info
resp, err := cli.get(ctx, "/info", url.Values{}, nil)
defer ensureReaderClosed(resp)
if err != nil {
return info, err
}
if err := json.NewDecoder(resp.Body).Decode(&info); err != nil {
return info, fmt.Errorf("Error reading remote info: %v", err)
}
return info, nil
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/docker/client/task_logs.go | vendor/github.com/docker/docker/client/task_logs.go | package client
import (
"context"
"io"
"net/url"
"time"
"github.com/docker/docker/api/types/container"
timetypes "github.com/docker/docker/api/types/time"
)
// TaskLogs returns the logs generated by a task in an io.ReadCloser.
// It's up to the caller to close the stream.
func (cli *Client) TaskLogs(ctx context.Context, taskID string, options container.LogsOptions) (io.ReadCloser, error) {
query := url.Values{}
if options.ShowStdout {
query.Set("stdout", "1")
}
if options.ShowStderr {
query.Set("stderr", "1")
}
if options.Since != "" {
ts, err := timetypes.GetTimestamp(options.Since, time.Now())
if err != nil {
return nil, err
}
query.Set("since", ts)
}
if options.Timestamps {
query.Set("timestamps", "1")
}
if options.Details {
query.Set("details", "1")
}
if options.Follow {
query.Set("follow", "1")
}
query.Set("tail", options.Tail)
resp, err := cli.get(ctx, "/tasks/"+taskID+"/logs", query, nil)
if err != nil {
return nil, err
}
return resp.Body, nil
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/docker/client/network_list.go | vendor/github.com/docker/docker/client/network_list.go | package client
import (
"context"
"encoding/json"
"net/url"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/network"
)
// NetworkList returns the list of networks configured in the docker host.
func (cli *Client) NetworkList(ctx context.Context, options network.ListOptions) ([]network.Summary, error) {
query := url.Values{}
if options.Filters.Len() > 0 {
//nolint:staticcheck // ignore SA1019 for old code
filterJSON, err := filters.ToParamWithVersion(cli.version, options.Filters)
if err != nil {
return nil, err
}
query.Set("filters", filterJSON)
}
var networkResources []network.Summary
resp, err := cli.get(ctx, "/networks", query, nil)
defer ensureReaderClosed(resp)
if err != nil {
return networkResources, err
}
err = json.NewDecoder(resp.Body).Decode(&networkResources)
return networkResources, err
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/docker/client/container_start.go | vendor/github.com/docker/docker/client/container_start.go | package client
import (
"context"
"net/url"
"github.com/docker/docker/api/types/container"
)
// ContainerStart sends a request to the docker daemon to start a container.
func (cli *Client) ContainerStart(ctx context.Context, containerID string, options container.StartOptions) error {
containerID, err := trimID("container", containerID)
if err != nil {
return err
}
query := url.Values{}
if options.CheckpointID != "" {
query.Set("checkpoint", options.CheckpointID)
}
if options.CheckpointDir != "" {
query.Set("checkpoint-dir", options.CheckpointDir)
}
resp, err := cli.post(ctx, "/containers/"+containerID+"/start", query, nil, nil)
ensureReaderClosed(resp)
return err
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/docker/client/plugin_remove.go | vendor/github.com/docker/docker/client/plugin_remove.go | package client
import (
"context"
"net/url"
"github.com/docker/docker/api/types"
)
// PluginRemove removes a plugin
func (cli *Client) PluginRemove(ctx context.Context, name string, options types.PluginRemoveOptions) error {
name, err := trimID("plugin", name)
if err != nil {
return err
}
query := url.Values{}
if options.Force {
query.Set("force", "1")
}
resp, err := cli.delete(ctx, "/plugins/"+name, query, nil)
defer ensureReaderClosed(resp)
return err
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/docker/client/image_save_opts.go | vendor/github.com/docker/docker/client/image_save_opts.go | package client
import (
"fmt"
"github.com/docker/docker/api/types/image"
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
)
type ImageSaveOption interface {
Apply(*imageSaveOpts) error
}
type imageSaveOptionFunc func(opt *imageSaveOpts) error
func (f imageSaveOptionFunc) Apply(o *imageSaveOpts) error {
return f(o)
}
// ImageSaveWithPlatforms sets the platforms to be saved from the image.
func ImageSaveWithPlatforms(platforms ...ocispec.Platform) ImageSaveOption {
return imageSaveOptionFunc(func(opt *imageSaveOpts) error {
if opt.apiOptions.Platforms != nil {
return fmt.Errorf("platforms already set to %v", opt.apiOptions.Platforms)
}
opt.apiOptions.Platforms = platforms
return nil
})
}
type imageSaveOpts struct {
apiOptions image.SaveOptions
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/docker/client/secret_list.go | vendor/github.com/docker/docker/client/secret_list.go | package client
import (
"context"
"encoding/json"
"net/url"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/swarm"
)
// SecretList returns the list of secrets.
func (cli *Client) SecretList(ctx context.Context, options swarm.SecretListOptions) ([]swarm.Secret, error) {
if err := cli.NewVersionError(ctx, "1.25", "secret list"); err != nil {
return nil, err
}
query := url.Values{}
if options.Filters.Len() > 0 {
filterJSON, err := filters.ToJSON(options.Filters)
if err != nil {
return nil, err
}
query.Set("filters", filterJSON)
}
resp, err := cli.get(ctx, "/secrets", query, nil)
defer ensureReaderClosed(resp)
if err != nil {
return nil, err
}
var secrets []swarm.Secret
err = json.NewDecoder(resp.Body).Decode(&secrets)
return secrets, err
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/docker/client/container_remove.go | vendor/github.com/docker/docker/client/container_remove.go | package client
import (
"context"
"net/url"
"github.com/docker/docker/api/types/container"
)
// ContainerRemove kills and removes a container from the docker host.
func (cli *Client) ContainerRemove(ctx context.Context, containerID string, options container.RemoveOptions) error {
containerID, err := trimID("container", containerID)
if err != nil {
return err
}
query := url.Values{}
if options.RemoveVolumes {
query.Set("v", "1")
}
if options.RemoveLinks {
query.Set("link", "1")
}
if options.Force {
query.Set("force", "1")
}
resp, err := cli.delete(ctx, "/containers/"+containerID, query, nil)
defer ensureReaderClosed(resp)
return err
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/docker/client/plugin_disable.go | vendor/github.com/docker/docker/client/plugin_disable.go | package client
import (
"context"
"net/url"
"github.com/docker/docker/api/types"
)
// PluginDisable disables a plugin
func (cli *Client) PluginDisable(ctx context.Context, name string, options types.PluginDisableOptions) error {
name, err := trimID("plugin", name)
if err != nil {
return err
}
query := url.Values{}
if options.Force {
query.Set("force", "1")
}
resp, err := cli.post(ctx, "/plugins/"+name+"/disable", query, nil, nil)
ensureReaderClosed(resp)
return err
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/docker/errdefs/http_helpers.go | vendor/github.com/docker/docker/errdefs/http_helpers.go | package errdefs
import (
"net/http"
)
// FromStatusCode creates an errdef error, based on the provided HTTP status-code
//
// Deprecated: Use [cerrdefs.ToNative] instead
func FromStatusCode(err error, statusCode int) error {
if err == nil {
return nil
}
switch statusCode {
case http.StatusNotFound:
return NotFound(err)
case http.StatusBadRequest:
return InvalidParameter(err)
case http.StatusConflict:
return Conflict(err)
case http.StatusUnauthorized:
return Unauthorized(err)
case http.StatusServiceUnavailable:
return Unavailable(err)
case http.StatusForbidden:
return Forbidden(err)
case http.StatusNotModified:
return NotModified(err)
case http.StatusNotImplemented:
return NotImplemented(err)
case http.StatusInternalServerError:
if IsCancelled(err) || IsSystem(err) || IsUnknown(err) || IsDataLoss(err) || IsDeadline(err) {
return err
}
return System(err)
default:
switch {
case statusCode >= http.StatusOK && statusCode < http.StatusBadRequest:
// it's a client error
return err
case statusCode >= http.StatusBadRequest && statusCode < http.StatusInternalServerError:
return InvalidParameter(err)
case statusCode >= http.StatusInternalServerError && statusCode < 600:
return System(err)
default:
return Unknown(err)
}
}
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/docker/errdefs/defs.go | vendor/github.com/docker/docker/errdefs/defs.go | package errdefs
// ErrNotFound signals that the requested object doesn't exist
type ErrNotFound interface {
NotFound()
}
// ErrInvalidParameter signals that the user input is invalid
type ErrInvalidParameter interface {
InvalidParameter()
}
// ErrConflict signals that some internal state conflicts with the requested action and can't be performed.
// A change in state should be able to clear this error.
type ErrConflict interface {
Conflict()
}
// ErrUnauthorized is used to signify that the user is not authorized to perform a specific action
type ErrUnauthorized interface {
Unauthorized()
}
// ErrUnavailable signals that the requested action/subsystem is not available.
type ErrUnavailable interface {
Unavailable()
}
// ErrForbidden signals that the requested action cannot be performed under any circumstances.
// When a ErrForbidden is returned, the caller should never retry the action.
type ErrForbidden interface {
Forbidden()
}
// ErrSystem signals that some internal error occurred.
// An example of this would be a failed mount request.
type ErrSystem interface {
System()
}
// ErrNotModified signals that an action can't be performed because it's already in the desired state
type ErrNotModified interface {
NotModified()
}
// ErrNotImplemented signals that the requested action/feature is not implemented on the system as configured.
type ErrNotImplemented interface {
NotImplemented()
}
// ErrUnknown signals that the kind of error that occurred is not known.
type ErrUnknown interface {
Unknown()
}
// ErrCancelled signals that the action was cancelled.
type ErrCancelled interface {
Cancelled()
}
// ErrDeadline signals that the deadline was reached before the action completed.
type ErrDeadline interface {
DeadlineExceeded()
}
// ErrDataLoss indicates that data was lost or there is data corruption.
type ErrDataLoss interface {
DataLoss()
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/docker/errdefs/doc.go | vendor/github.com/docker/docker/errdefs/doc.go | // Package errdefs defines a set of error interfaces that packages should use for communicating classes of errors.
// Errors that cross the package boundary should implement one (and only one) of these interfaces.
//
// Packages should not reference these interfaces directly, only implement them.
// To check if a particular error implements one of these interfaces, there are helper
// functions provided (e.g. `Is<SomeError>`) which can be used rather than asserting the interfaces directly.
// If you must assert on these interfaces, be sure to check the causal chain (`err.Unwrap()`).
package errdefs
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/docker/errdefs/helpers.go | vendor/github.com/docker/docker/errdefs/helpers.go | package errdefs
import (
"context"
cerrdefs "github.com/containerd/errdefs"
)
type errNotFound struct{ error }
func (errNotFound) NotFound() {}
func (e errNotFound) Cause() error {
return e.error
}
func (e errNotFound) Unwrap() error {
return e.error
}
// NotFound creates an [ErrNotFound] error from the given error.
// It returns the error as-is if it is either nil (no error) or already implements
// [ErrNotFound],
func NotFound(err error) error {
if err == nil || cerrdefs.IsNotFound(err) {
return err
}
return errNotFound{err}
}
type errInvalidParameter struct{ error }
func (errInvalidParameter) InvalidParameter() {}
func (e errInvalidParameter) Cause() error {
return e.error
}
func (e errInvalidParameter) Unwrap() error {
return e.error
}
// InvalidParameter creates an [ErrInvalidParameter] error from the given error.
// It returns the error as-is if it is either nil (no error) or already implements
// [ErrInvalidParameter],
func InvalidParameter(err error) error {
if err == nil || cerrdefs.IsInvalidArgument(err) {
return err
}
return errInvalidParameter{err}
}
type errConflict struct{ error }
func (errConflict) Conflict() {}
func (e errConflict) Cause() error {
return e.error
}
func (e errConflict) Unwrap() error {
return e.error
}
// Conflict creates an [ErrConflict] error from the given error.
// It returns the error as-is if it is either nil (no error) or already implements
// [ErrConflict],
func Conflict(err error) error {
if err == nil || cerrdefs.IsConflict(err) {
return err
}
return errConflict{err}
}
type errUnauthorized struct{ error }
func (errUnauthorized) Unauthorized() {}
func (e errUnauthorized) Cause() error {
return e.error
}
func (e errUnauthorized) Unwrap() error {
return e.error
}
// Unauthorized creates an [ErrUnauthorized] error from the given error.
// It returns the error as-is if it is either nil (no error) or already implements
// [ErrUnauthorized],
func Unauthorized(err error) error {
if err == nil || cerrdefs.IsUnauthorized(err) {
return err
}
return errUnauthorized{err}
}
type errUnavailable struct{ error }
func (errUnavailable) Unavailable() {}
func (e errUnavailable) Cause() error {
return e.error
}
func (e errUnavailable) Unwrap() error {
return e.error
}
// Unavailable creates an [ErrUnavailable] error from the given error.
// It returns the error as-is if it is either nil (no error) or already implements
// [ErrUnavailable],
func Unavailable(err error) error {
if err == nil || cerrdefs.IsUnavailable(err) {
return err
}
return errUnavailable{err}
}
type errForbidden struct{ error }
func (errForbidden) Forbidden() {}
func (e errForbidden) Cause() error {
return e.error
}
func (e errForbidden) Unwrap() error {
return e.error
}
// Forbidden creates an [ErrForbidden] error from the given error.
// It returns the error as-is if it is either nil (no error) or already implements
// [ErrForbidden],
func Forbidden(err error) error {
if err == nil || cerrdefs.IsPermissionDenied(err) {
return err
}
return errForbidden{err}
}
type errSystem struct{ error }
func (errSystem) System() {}
func (e errSystem) Cause() error {
return e.error
}
func (e errSystem) Unwrap() error {
return e.error
}
// System creates an [ErrSystem] error from the given error.
// It returns the error as-is if it is either nil (no error) or already implements
// [ErrSystem],
func System(err error) error {
if err == nil || cerrdefs.IsInternal(err) {
return err
}
return errSystem{err}
}
type errNotModified struct{ error }
func (errNotModified) NotModified() {}
func (e errNotModified) Cause() error {
return e.error
}
func (e errNotModified) Unwrap() error {
return e.error
}
// NotModified creates an [ErrNotModified] error from the given error.
// It returns the error as-is if it is either nil (no error) or already implements
// [NotModified],
func NotModified(err error) error {
if err == nil || cerrdefs.IsNotModified(err) {
return err
}
return errNotModified{err}
}
type errNotImplemented struct{ error }
func (errNotImplemented) NotImplemented() {}
func (e errNotImplemented) Cause() error {
return e.error
}
func (e errNotImplemented) Unwrap() error {
return e.error
}
// NotImplemented creates an [ErrNotImplemented] error from the given error.
// It returns the error as-is if it is either nil (no error) or already implements
// [ErrNotImplemented],
func NotImplemented(err error) error {
if err == nil || cerrdefs.IsNotImplemented(err) {
return err
}
return errNotImplemented{err}
}
type errUnknown struct{ error }
func (errUnknown) Unknown() {}
func (e errUnknown) Cause() error {
return e.error
}
func (e errUnknown) Unwrap() error {
return e.error
}
// Unknown creates an [ErrUnknown] error from the given error.
// It returns the error as-is if it is either nil (no error) or already implements
// [ErrUnknown],
func Unknown(err error) error {
if err == nil || cerrdefs.IsUnknown(err) {
return err
}
return errUnknown{err}
}
type errCancelled struct{ error }
func (errCancelled) Cancelled() {}
func (e errCancelled) Cause() error {
return e.error
}
func (e errCancelled) Unwrap() error {
return e.error
}
// Cancelled creates an [ErrCancelled] error from the given error.
// It returns the error as-is if it is either nil (no error) or already implements
// [ErrCancelled],
func Cancelled(err error) error {
if err == nil || cerrdefs.IsCanceled(err) {
return err
}
return errCancelled{err}
}
type errDeadline struct{ error }
func (errDeadline) DeadlineExceeded() {}
func (e errDeadline) Cause() error {
return e.error
}
func (e errDeadline) Unwrap() error {
return e.error
}
// Deadline creates an [ErrDeadline] error from the given error.
// It returns the error as-is if it is either nil (no error) or already implements
// [ErrDeadline],
func Deadline(err error) error {
if err == nil || cerrdefs.IsDeadlineExceeded(err) {
return err
}
return errDeadline{err}
}
type errDataLoss struct{ error }
func (errDataLoss) DataLoss() {}
func (e errDataLoss) Cause() error {
return e.error
}
func (e errDataLoss) Unwrap() error {
return e.error
}
// DataLoss creates an [ErrDataLoss] error from the given error.
// It returns the error as-is if it is either nil (no error) or already implements
// [ErrDataLoss],
func DataLoss(err error) error {
if err == nil || cerrdefs.IsDataLoss(err) {
return err
}
return errDataLoss{err}
}
// FromContext returns the error class from the passed in context
func FromContext(ctx context.Context) error {
e := ctx.Err()
if e == nil {
return nil
}
if e == context.Canceled {
return Cancelled(e)
}
if e == context.DeadlineExceeded {
return Deadline(e)
}
return Unknown(e)
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/docker/errdefs/is.go | vendor/github.com/docker/docker/errdefs/is.go | package errdefs
import (
"context"
"errors"
cerrdefs "github.com/containerd/errdefs"
)
// IsNotFound returns if the passed in error is an [ErrNotFound],
//
// Deprecated: use containerd [cerrdefs.IsNotFound]
var IsNotFound = cerrdefs.IsNotFound
// IsInvalidParameter returns if the passed in error is an [ErrInvalidParameter].
//
// Deprecated: use containerd [cerrdefs.IsInvalidArgument]
var IsInvalidParameter = cerrdefs.IsInvalidArgument
// IsConflict returns if the passed in error is an [ErrConflict].
//
// Deprecated: use containerd [cerrdefs.IsConflict]
var IsConflict = cerrdefs.IsConflict
// IsUnauthorized returns if the passed in error is an [ErrUnauthorized].
//
// Deprecated: use containerd [cerrdefs.IsUnauthorized]
var IsUnauthorized = cerrdefs.IsUnauthorized
// IsUnavailable returns if the passed in error is an [ErrUnavailable].
//
// Deprecated: use containerd [cerrdefs.IsUnavailable]
var IsUnavailable = cerrdefs.IsUnavailable
// IsForbidden returns if the passed in error is an [ErrForbidden].
//
// Deprecated: use containerd [cerrdefs.IsPermissionDenied]
var IsForbidden = cerrdefs.IsPermissionDenied
// IsSystem returns if the passed in error is an [ErrSystem].
//
// Deprecated: use containerd [cerrdefs.IsInternal]
var IsSystem = cerrdefs.IsInternal
// IsNotModified returns if the passed in error is an [ErrNotModified].
//
// Deprecated: use containerd [cerrdefs.IsNotModified]
var IsNotModified = cerrdefs.IsNotModified
// IsNotImplemented returns if the passed in error is an [ErrNotImplemented].
//
// Deprecated: use containerd [cerrdefs.IsNotImplemented]
var IsNotImplemented = cerrdefs.IsNotImplemented
// IsUnknown returns if the passed in error is an [ErrUnknown].
//
// Deprecated: use containerd [cerrdefs.IsUnknown]
var IsUnknown = cerrdefs.IsUnknown
// IsCancelled returns if the passed in error is an [ErrCancelled].
//
// Deprecated: use containerd [cerrdefs.IsCanceled]
var IsCancelled = cerrdefs.IsCanceled
// IsDeadline returns if the passed in error is an [ErrDeadline].
//
// Deprecated: use containerd [cerrdefs.IsDeadlineExceeded]
var IsDeadline = cerrdefs.IsDeadlineExceeded
// IsDataLoss returns if the passed in error is an [ErrDataLoss].
//
// Deprecated: use containerd [cerrdefs.IsDataLoss]
var IsDataLoss = cerrdefs.IsDataLoss
// IsContext returns if the passed in error is due to context cancellation or deadline exceeded.
func IsContext(err error) bool {
return errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded)
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/docker-credential-helpers/credentials/helper.go | vendor/github.com/docker/docker-credential-helpers/credentials/helper.go | package credentials
// Helper is the interface a credentials store helper must implement.
type Helper interface {
// Add appends credentials to the store.
Add(*Credentials) error
// Delete removes credentials from the store.
Delete(serverURL string) error
// Get retrieves credentials from the store.
// It returns username and secret as strings.
Get(serverURL string) (string, string, error)
// List returns the stored serverURLs and their associated usernames.
List() (map[string]string, error)
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/docker-credential-helpers/credentials/error.go | vendor/github.com/docker/docker-credential-helpers/credentials/error.go | package credentials
import (
"errors"
"strings"
)
const (
// ErrCredentialsNotFound standardizes the not found error, so every helper returns
// the same message and docker can handle it properly.
errCredentialsNotFoundMessage = "credentials not found in native keychain"
// ErrCredentialsMissingServerURL and ErrCredentialsMissingUsername standardize
// invalid credentials or credentials management operations
errCredentialsMissingServerURLMessage = "no credentials server URL"
errCredentialsMissingUsernameMessage = "no credentials username"
)
// errCredentialsNotFound represents an error
// raised when credentials are not in the store.
type errCredentialsNotFound struct{}
// Error returns the standard error message
// for when the credentials are not in the store.
func (errCredentialsNotFound) Error() string {
return errCredentialsNotFoundMessage
}
// NotFound implements the [ErrNotFound][errdefs.ErrNotFound] interface.
//
// [errdefs.ErrNotFound]: https://pkg.go.dev/github.com/docker/docker@v24.0.1+incompatible/errdefs#ErrNotFound
func (errCredentialsNotFound) NotFound() {}
// NewErrCredentialsNotFound creates a new error
// for when the credentials are not in the store.
func NewErrCredentialsNotFound() error {
return errCredentialsNotFound{}
}
// IsErrCredentialsNotFound returns true if the error
// was caused by not having a set of credentials in a store.
func IsErrCredentialsNotFound(err error) bool {
var target errCredentialsNotFound
return errors.As(err, &target)
}
// IsErrCredentialsNotFoundMessage returns true if the error
// was caused by not having a set of credentials in a store.
//
// This function helps to check messages returned by an
// external program via its standard output.
func IsErrCredentialsNotFoundMessage(err string) bool {
return strings.TrimSpace(err) == errCredentialsNotFoundMessage
}
// errCredentialsMissingServerURL represents an error raised
// when the credentials object has no server URL or when no
// server URL is provided to a credentials operation requiring
// one.
type errCredentialsMissingServerURL struct{}
func (errCredentialsMissingServerURL) Error() string {
return errCredentialsMissingServerURLMessage
}
// InvalidParameter implements the [ErrInvalidParameter][errdefs.ErrInvalidParameter]
// interface.
//
// [errdefs.ErrInvalidParameter]: https://pkg.go.dev/github.com/docker/docker@v24.0.1+incompatible/errdefs#ErrInvalidParameter
func (errCredentialsMissingServerURL) InvalidParameter() {}
// errCredentialsMissingUsername represents an error raised
// when the credentials object has no username or when no
// username is provided to a credentials operation requiring
// one.
type errCredentialsMissingUsername struct{}
func (errCredentialsMissingUsername) Error() string {
return errCredentialsMissingUsernameMessage
}
// InvalidParameter implements the [ErrInvalidParameter][errdefs.ErrInvalidParameter]
// interface.
//
// [errdefs.ErrInvalidParameter]: https://pkg.go.dev/github.com/docker/docker@v24.0.1+incompatible/errdefs#ErrInvalidParameter
func (errCredentialsMissingUsername) InvalidParameter() {}
// NewErrCredentialsMissingServerURL creates a new error for
// errCredentialsMissingServerURL.
func NewErrCredentialsMissingServerURL() error {
return errCredentialsMissingServerURL{}
}
// NewErrCredentialsMissingUsername creates a new error for
// errCredentialsMissingUsername.
func NewErrCredentialsMissingUsername() error {
return errCredentialsMissingUsername{}
}
// IsCredentialsMissingServerURL returns true if the error
// was an errCredentialsMissingServerURL.
func IsCredentialsMissingServerURL(err error) bool {
var target errCredentialsMissingServerURL
return errors.As(err, &target)
}
// IsCredentialsMissingServerURLMessage checks for an
// errCredentialsMissingServerURL in the error message.
func IsCredentialsMissingServerURLMessage(err string) bool {
return strings.TrimSpace(err) == errCredentialsMissingServerURLMessage
}
// IsCredentialsMissingUsername returns true if the error
// was an errCredentialsMissingUsername.
func IsCredentialsMissingUsername(err error) bool {
var target errCredentialsMissingUsername
return errors.As(err, &target)
}
// IsCredentialsMissingUsernameMessage checks for an
// errCredentialsMissingUsername in the error message.
func IsCredentialsMissingUsernameMessage(err string) bool {
return strings.TrimSpace(err) == errCredentialsMissingUsernameMessage
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/docker-credential-helpers/credentials/credentials.go | vendor/github.com/docker/docker-credential-helpers/credentials/credentials.go | package credentials
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"os"
"strings"
)
// Action defines the name of an action (sub-command) supported by a
// credential-helper binary. It is an alias for "string", and mostly
// for convenience.
type Action = string
// List of actions (sub-commands) supported by credential-helper binaries.
const (
ActionStore Action = "store"
ActionGet Action = "get"
ActionErase Action = "erase"
ActionList Action = "list"
ActionVersion Action = "version"
)
// Credentials holds the information shared between docker and the credentials store.
type Credentials struct {
ServerURL string
Username string
Secret string
}
// isValid checks the integrity of Credentials object such that no credentials lack
// a server URL or a username.
// It returns whether the credentials are valid and the error if it isn't.
// error values can be errCredentialsMissingServerURL or errCredentialsMissingUsername
func (c *Credentials) isValid() (bool, error) {
if len(c.ServerURL) == 0 {
return false, NewErrCredentialsMissingServerURL()
}
if len(c.Username) == 0 {
return false, NewErrCredentialsMissingUsername()
}
return true, nil
}
// CredsLabel holds the way Docker credentials should be labeled as such in credentials stores that allow labelling.
// That label allows to filter out non-Docker credentials too at lookup/search in macOS keychain,
// Windows credentials manager and Linux libsecret. Default value is "Docker Credentials"
var CredsLabel = "Docker Credentials"
// SetCredsLabel is a simple setter for CredsLabel
func SetCredsLabel(label string) {
CredsLabel = label
}
// Serve initializes the credentials-helper and parses the action argument.
// This function is designed to be called from a command line interface.
// It uses os.Args[1] as the key for the action.
// It uses os.Stdin as input and os.Stdout as output.
// This function terminates the program with os.Exit(1) if there is an error.
func Serve(helper Helper) {
if len(os.Args) != 2 {
_, _ = fmt.Fprintln(os.Stdout, usage())
os.Exit(1)
}
switch os.Args[1] {
case "--version", "-v":
_ = PrintVersion(os.Stdout)
os.Exit(0)
case "--help", "-h":
_, _ = fmt.Fprintln(os.Stdout, usage())
os.Exit(0)
}
if err := HandleCommand(helper, os.Args[1], os.Stdin, os.Stdout); err != nil {
_, _ = fmt.Fprintln(os.Stdout, err)
os.Exit(1)
}
}
func usage() string {
return fmt.Sprintf("Usage: %s <store|get|erase|list|version>", Name)
}
// HandleCommand runs a helper to execute a credential action.
func HandleCommand(helper Helper, action Action, in io.Reader, out io.Writer) error {
switch action {
case ActionStore:
return Store(helper, in)
case ActionGet:
return Get(helper, in, out)
case ActionErase:
return Erase(helper, in)
case ActionList:
return List(helper, out)
case ActionVersion:
return PrintVersion(out)
default:
return fmt.Errorf("%s: unknown action: %s", Name, action)
}
}
// Store uses a helper and an input reader to save credentials.
// The reader must contain the JSON serialization of a Credentials struct.
func Store(helper Helper, reader io.Reader) error {
scanner := bufio.NewScanner(reader)
buffer := new(bytes.Buffer)
for scanner.Scan() {
buffer.Write(scanner.Bytes())
}
if err := scanner.Err(); err != nil && err != io.EOF {
return err
}
var creds Credentials
if err := json.NewDecoder(buffer).Decode(&creds); err != nil {
return err
}
if ok, err := creds.isValid(); !ok {
return err
}
return helper.Add(&creds)
}
// Get retrieves the credentials for a given server url.
// The reader must contain the server URL to search.
// The writer is used to write the JSON serialization of the credentials.
func Get(helper Helper, reader io.Reader, writer io.Writer) error {
scanner := bufio.NewScanner(reader)
buffer := new(bytes.Buffer)
for scanner.Scan() {
buffer.Write(scanner.Bytes())
}
if err := scanner.Err(); err != nil && err != io.EOF {
return err
}
serverURL := strings.TrimSpace(buffer.String())
if len(serverURL) == 0 {
return NewErrCredentialsMissingServerURL()
}
username, secret, err := helper.Get(serverURL)
if err != nil {
return err
}
buffer.Reset()
err = json.NewEncoder(buffer).Encode(Credentials{
ServerURL: serverURL,
Username: username,
Secret: secret,
})
if err != nil {
return err
}
_, _ = fmt.Fprint(writer, buffer.String())
return nil
}
// Erase removes credentials from the store.
// The reader must contain the server URL to remove.
func Erase(helper Helper, reader io.Reader) error {
scanner := bufio.NewScanner(reader)
buffer := new(bytes.Buffer)
for scanner.Scan() {
buffer.Write(scanner.Bytes())
}
if err := scanner.Err(); err != nil && err != io.EOF {
return err
}
serverURL := strings.TrimSpace(buffer.String())
if len(serverURL) == 0 {
return NewErrCredentialsMissingServerURL()
}
return helper.Delete(serverURL)
}
// List returns all the serverURLs of keys in
// the OS store as a list of strings
func List(helper Helper, writer io.Writer) error {
accts, err := helper.List()
if err != nil {
return err
}
return json.NewEncoder(writer).Encode(accts)
}
// PrintVersion outputs the current version.
func PrintVersion(writer io.Writer) error {
_, _ = fmt.Fprintf(writer, "%s (%s) %s\n", Name, Package, Version)
return nil
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/docker-credential-helpers/credentials/version.go | vendor/github.com/docker/docker-credential-helpers/credentials/version.go | package credentials
var (
// Name is filled at linking time
Name = ""
// Package is filled at linking time
Package = "github.com/docker/docker-credential-helpers"
// Version holds the complete version number. Filled in at linking time.
Version = "v0.0.0+unknown"
// Revision is filled with the VCS (e.g. git) revision being used to build
// the program at linking time.
Revision = ""
)
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/docker-credential-helpers/client/client.go | vendor/github.com/docker/docker-credential-helpers/client/client.go | package client
import (
"bytes"
"encoding/json"
"fmt"
"strings"
"github.com/docker/docker-credential-helpers/credentials"
)
// isValidCredsMessage checks if 'msg' contains invalid credentials error message.
// It returns whether the logs are free of invalid credentials errors and the error if it isn't.
// error values can be errCredentialsMissingServerURL or errCredentialsMissingUsername.
func isValidCredsMessage(msg string) error {
if credentials.IsCredentialsMissingServerURLMessage(msg) {
return credentials.NewErrCredentialsMissingServerURL()
}
if credentials.IsCredentialsMissingUsernameMessage(msg) {
return credentials.NewErrCredentialsMissingUsername()
}
return nil
}
// Store uses an external program to save credentials.
func Store(program ProgramFunc, creds *credentials.Credentials) error {
cmd := program(credentials.ActionStore)
buffer := new(bytes.Buffer)
if err := json.NewEncoder(buffer).Encode(creds); err != nil {
return err
}
cmd.Input(buffer)
out, err := cmd.Output()
if err != nil {
if isValidErr := isValidCredsMessage(string(out)); isValidErr != nil {
err = isValidErr
}
return fmt.Errorf("error storing credentials - err: %v, out: `%s`", err, strings.TrimSpace(string(out)))
}
return nil
}
// Get executes an external program to get the credentials from a native store.
func Get(program ProgramFunc, serverURL string) (*credentials.Credentials, error) {
cmd := program(credentials.ActionGet)
cmd.Input(strings.NewReader(serverURL))
out, err := cmd.Output()
if err != nil {
if credentials.IsErrCredentialsNotFoundMessage(string(out)) {
return nil, credentials.NewErrCredentialsNotFound()
}
if isValidErr := isValidCredsMessage(string(out)); isValidErr != nil {
err = isValidErr
}
return nil, fmt.Errorf("error getting credentials - err: %v, out: `%s`", err, strings.TrimSpace(string(out)))
}
resp := &credentials.Credentials{
ServerURL: serverURL,
}
if err := json.NewDecoder(bytes.NewReader(out)).Decode(resp); err != nil {
return nil, err
}
return resp, nil
}
// Erase executes a program to remove the server credentials from the native store.
func Erase(program ProgramFunc, serverURL string) error {
cmd := program(credentials.ActionErase)
cmd.Input(strings.NewReader(serverURL))
out, err := cmd.Output()
if err != nil {
t := strings.TrimSpace(string(out))
if isValidErr := isValidCredsMessage(t); isValidErr != nil {
err = isValidErr
}
return fmt.Errorf("error erasing credentials - err: %v, out: `%s`", err, t)
}
return nil
}
// List executes a program to list server credentials in the native store.
func List(program ProgramFunc) (map[string]string, error) {
cmd := program(credentials.ActionList)
cmd.Input(strings.NewReader("unused"))
out, err := cmd.Output()
if err != nil {
t := strings.TrimSpace(string(out))
if isValidErr := isValidCredsMessage(t); isValidErr != nil {
err = isValidErr
}
return nil, fmt.Errorf("error listing credentials - err: %v, out: `%s`", err, t)
}
var resp map[string]string
if err = json.NewDecoder(bytes.NewReader(out)).Decode(&resp); err != nil {
return nil, err
}
return resp, nil
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/docker-credential-helpers/client/command.go | vendor/github.com/docker/docker-credential-helpers/client/command.go | package client
import (
"io"
"os"
"os/exec"
)
// Program is an interface to execute external programs.
type Program interface {
Output() ([]byte, error)
Input(in io.Reader)
}
// ProgramFunc is a type of function that initializes programs based on arguments.
type ProgramFunc func(args ...string) Program
// NewShellProgramFunc creates programs that are executed in a Shell.
func NewShellProgramFunc(name string) ProgramFunc {
return NewShellProgramFuncWithEnv(name, nil)
}
// NewShellProgramFuncWithEnv creates programs that are executed in a Shell with environment variables
func NewShellProgramFuncWithEnv(name string, env *map[string]string) ProgramFunc {
return func(args ...string) Program {
return &Shell{cmd: createProgramCmdRedirectErr(name, args, env)}
}
}
func createProgramCmdRedirectErr(commandName string, args []string, env *map[string]string) *exec.Cmd {
programCmd := exec.Command(commandName, args...)
if env != nil {
for k, v := range *env {
programCmd.Env = append(programCmd.Environ(), k+"="+v)
}
}
programCmd.Stderr = os.Stderr
return programCmd
}
// Shell invokes shell commands to talk with a remote credentials-helper.
type Shell struct {
cmd *exec.Cmd
}
// Output returns responses from the remote credentials-helper.
func (s *Shell) Output() ([]byte, error) {
return s.cmd.Output()
}
// Input sets the input to send to a remote credentials-helper.
func (s *Shell) Input(in io.Reader) {
s.cmd.Stdin = in
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/cli/cli/connhelper/connhelper.go | vendor/github.com/docker/cli/cli/connhelper/connhelper.go | // Package connhelper provides helpers for connecting to a remote daemon host with custom logic.
package connhelper
import (
"context"
"net"
"net/url"
"strings"
"github.com/docker/cli/cli/connhelper/commandconn"
"github.com/docker/cli/cli/connhelper/ssh"
"github.com/pkg/errors"
)
// ConnectionHelper allows to connect to a remote host with custom stream provider binary.
type ConnectionHelper struct {
Dialer func(ctx context.Context, network, addr string) (net.Conn, error)
Host string // dummy URL used for HTTP requests. e.g. "http://docker"
}
// GetConnectionHelper returns Docker-specific connection helper for the given URL.
// GetConnectionHelper returns nil without error when no helper is registered for the scheme.
//
// ssh://<user>@<host> URL requires Docker 18.09 or later on the remote host.
func GetConnectionHelper(daemonURL string) (*ConnectionHelper, error) {
return getConnectionHelper(daemonURL, nil)
}
// GetConnectionHelperWithSSHOpts returns Docker-specific connection helper for
// the given URL, and accepts additional options for ssh connections. It returns
// nil without error when no helper is registered for the scheme.
//
// Requires Docker 18.09 or later on the remote host.
func GetConnectionHelperWithSSHOpts(daemonURL string, sshFlags []string) (*ConnectionHelper, error) {
return getConnectionHelper(daemonURL, sshFlags)
}
func getConnectionHelper(daemonURL string, sshFlags []string) (*ConnectionHelper, error) {
u, err := url.Parse(daemonURL)
if err != nil {
return nil, err
}
if u.Scheme == "ssh" {
sp, err := ssh.ParseURL(daemonURL)
if err != nil {
return nil, errors.Wrap(err, "ssh host connection is not valid")
}
return &ConnectionHelper{
Dialer: func(ctx context.Context, network, addr string) (net.Conn, error) {
args := []string{"docker"}
if sp.Path != "" {
args = append(args, "--host", "unix://"+sp.Path)
}
sshFlags = addSSHTimeout(sshFlags)
args = append(args, "system", "dial-stdio")
return commandconn.New(ctx, "ssh", append(sshFlags, sp.Args(args...)...)...)
},
Host: "http://docker.example.com",
}, nil
}
// Future version may support plugins via ~/.docker/config.json. e.g. "dind"
// See docker/cli#889 for the previous discussion.
return nil, err
}
// GetCommandConnectionHelper returns Docker-specific connection helper constructed from an arbitrary command.
func GetCommandConnectionHelper(cmd string, flags ...string) (*ConnectionHelper, error) {
return &ConnectionHelper{
Dialer: func(ctx context.Context, network, addr string) (net.Conn, error) {
return commandconn.New(ctx, cmd, flags...)
},
Host: "http://docker.example.com",
}, nil
}
func addSSHTimeout(sshFlags []string) []string {
if !strings.Contains(strings.Join(sshFlags, ""), "ConnectTimeout") {
sshFlags = append(sshFlags, "-o ConnectTimeout=30")
}
return sshFlags
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/cli/cli/connhelper/ssh/ssh.go | vendor/github.com/docker/cli/cli/connhelper/ssh/ssh.go | // Package ssh provides the connection helper for ssh:// URL.
package ssh
import (
"net/url"
"github.com/pkg/errors"
)
// ParseURL parses URL
func ParseURL(daemonURL string) (*Spec, error) {
u, err := url.Parse(daemonURL)
if err != nil {
return nil, err
}
if u.Scheme != "ssh" {
return nil, errors.Errorf("expected scheme ssh, got %q", u.Scheme)
}
var sp Spec
if u.User != nil {
sp.User = u.User.Username()
if _, ok := u.User.Password(); ok {
return nil, errors.New("plain-text password is not supported")
}
}
sp.Host = u.Hostname()
if sp.Host == "" {
return nil, errors.Errorf("no host specified")
}
sp.Port = u.Port()
sp.Path = u.Path
if u.RawQuery != "" {
return nil, errors.Errorf("extra query after the host: %q", u.RawQuery)
}
if u.Fragment != "" {
return nil, errors.Errorf("extra fragment after the host: %q", u.Fragment)
}
return &sp, err
}
// Spec of SSH URL
type Spec struct {
User string
Host string
Port string
Path string
}
// Args returns args except "ssh" itself combined with optional additional command args
func (sp *Spec) Args(add ...string) []string {
var args []string
if sp.User != "" {
args = append(args, "-l", sp.User)
}
if sp.Port != "" {
args = append(args, "-p", sp.Port)
}
args = append(args, "--", sp.Host)
args = append(args, add...)
return args
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/cli/cli/connhelper/commandconn/pdeathsig_nolinux.go | vendor/github.com/docker/cli/cli/connhelper/commandconn/pdeathsig_nolinux.go | //go:build !linux
package commandconn
import (
"os/exec"
)
func setPdeathsig(*exec.Cmd) {}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/cli/cli/connhelper/commandconn/session_unix.go | vendor/github.com/docker/cli/cli/connhelper/commandconn/session_unix.go | //go:build !windows
package commandconn
import (
"os/exec"
)
func createSession(cmd *exec.Cmd) {
// for supporting ssh connection helper with ProxyCommand
// https://github.com/docker/cli/issues/1707
cmd.SysProcAttr.Setsid = true
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/cli/cli/connhelper/commandconn/session_windows.go | vendor/github.com/docker/cli/cli/connhelper/commandconn/session_windows.go | package commandconn
import (
"os/exec"
)
func createSession(cmd *exec.Cmd) {
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/cli/cli/connhelper/commandconn/commandconn.go | vendor/github.com/docker/cli/cli/connhelper/commandconn/commandconn.go | // Package commandconn provides a net.Conn implementation that can be used for
// proxying (or emulating) stream via a custom command.
//
// For example, to provide an http.Client that can connect to a Docker daemon
// running in a Docker container ("DIND"):
//
// httpClient := &http.Client{
// Transport: &http.Transport{
// DialContext: func(ctx context.Context, _network, _addr string) (net.Conn, error) {
// return commandconn.New(ctx, "docker", "exec", "-it", containerID, "docker", "system", "dial-stdio")
// },
// },
// }
package commandconn
import (
"bytes"
"context"
"fmt"
"io"
"net"
"os"
"os/exec"
"runtime"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
// New returns net.Conn
func New(_ context.Context, cmd string, args ...string) (net.Conn, error) {
var (
c commandConn
err error
)
c.cmd = exec.Command(cmd, args...)
// we assume that args never contains sensitive information
logrus.Debugf("commandconn: starting %s with %v", cmd, args)
c.cmd.Env = os.Environ()
c.cmd.SysProcAttr = &syscall.SysProcAttr{}
setPdeathsig(c.cmd)
createSession(c.cmd)
c.stdin, err = c.cmd.StdinPipe()
if err != nil {
return nil, err
}
c.stdout, err = c.cmd.StdoutPipe()
if err != nil {
return nil, err
}
c.cmd.Stderr = &stderrWriter{
stderrMu: &c.stderrMu,
stderr: &c.stderr,
debugPrefix: fmt.Sprintf("commandconn (%s):", cmd),
}
c.localAddr = dummyAddr{network: "dummy", s: "dummy-0"}
c.remoteAddr = dummyAddr{network: "dummy", s: "dummy-1"}
return &c, c.cmd.Start()
}
// commandConn implements net.Conn
type commandConn struct {
cmdMutex sync.Mutex // for cmd, cmdWaitErr
cmd *exec.Cmd
cmdWaitErr error
cmdExited atomic.Bool
stdin io.WriteCloser
stdout io.ReadCloser
stderrMu sync.Mutex // for stderr
stderr bytes.Buffer
stdinClosed atomic.Bool
stdoutClosed atomic.Bool
closing atomic.Bool
localAddr net.Addr
remoteAddr net.Addr
}
// kill terminates the process. On Windows it kills the process directly,
// whereas on other platforms, a SIGTERM is sent, before forcefully terminating
// the process after 3 seconds.
func (c *commandConn) kill() {
if c.cmdExited.Load() {
return
}
c.cmdMutex.Lock()
var werr error
if runtime.GOOS != "windows" {
werrCh := make(chan error)
go func() { werrCh <- c.cmd.Wait() }()
_ = c.cmd.Process.Signal(syscall.SIGTERM)
select {
case werr = <-werrCh:
case <-time.After(3 * time.Second):
_ = c.cmd.Process.Kill()
werr = <-werrCh
}
} else {
_ = c.cmd.Process.Kill()
werr = c.cmd.Wait()
}
c.cmdWaitErr = werr
c.cmdMutex.Unlock()
c.cmdExited.Store(true)
}
// handleEOF handles io.EOF errors while reading or writing from the underlying
// command pipes.
//
// When we've received an EOF we expect that the command will
// be terminated soon. As such, we call Wait() on the command
// and return EOF or the error depending on whether the command
// exited with an error.
//
// If Wait() does not return within 10s, an error is returned
func (c *commandConn) handleEOF(err error) error {
if err != io.EOF {
return err
}
c.cmdMutex.Lock()
defer c.cmdMutex.Unlock()
var werr error
if c.cmdExited.Load() {
werr = c.cmdWaitErr
} else {
werrCh := make(chan error)
go func() { werrCh <- c.cmd.Wait() }()
select {
case werr = <-werrCh:
c.cmdWaitErr = werr
c.cmdExited.Store(true)
case <-time.After(10 * time.Second):
c.stderrMu.Lock()
stderr := c.stderr.String()
c.stderrMu.Unlock()
return errors.Errorf("command %v did not exit after %v: stderr=%q", c.cmd.Args, err, stderr)
}
}
if werr == nil {
return err
}
c.stderrMu.Lock()
stderr := c.stderr.String()
c.stderrMu.Unlock()
return errors.Errorf("command %v has exited with %v, make sure the URL is valid, and Docker 18.09 or later is installed on the remote host: stderr=%s", c.cmd.Args, werr, stderr)
}
func ignorableCloseError(err error) bool {
return strings.Contains(err.Error(), os.ErrClosed.Error())
}
func (c *commandConn) Read(p []byte) (int, error) {
n, err := c.stdout.Read(p)
// check after the call to Read, since
// it is blocking, and while waiting on it
// Close might get called
if c.closing.Load() {
// If we're currently closing the connection
// we don't want to call onEOF
return n, err
}
return n, c.handleEOF(err)
}
func (c *commandConn) Write(p []byte) (int, error) {
n, err := c.stdin.Write(p)
// check after the call to Write, since
// it is blocking, and while waiting on it
// Close might get called
if c.closing.Load() {
// If we're currently closing the connection
// we don't want to call onEOF
return n, err
}
return n, c.handleEOF(err)
}
// CloseRead allows commandConn to implement halfCloser
func (c *commandConn) CloseRead() error {
// NOTE: maybe already closed here
if err := c.stdout.Close(); err != nil && !ignorableCloseError(err) {
return err
}
c.stdoutClosed.Store(true)
if c.stdinClosed.Load() {
c.kill()
}
return nil
}
// CloseWrite allows commandConn to implement halfCloser
func (c *commandConn) CloseWrite() error {
// NOTE: maybe already closed here
if err := c.stdin.Close(); err != nil && !ignorableCloseError(err) {
return err
}
c.stdinClosed.Store(true)
if c.stdoutClosed.Load() {
c.kill()
}
return nil
}
// Close is the net.Conn func that gets called
// by the transport when a dial is cancelled
// due to it's context timing out. Any blocked
// Read or Write calls will be unblocked and
// return errors. It will block until the underlying
// command has terminated.
func (c *commandConn) Close() error {
c.closing.Store(true)
defer c.closing.Store(false)
if err := c.CloseRead(); err != nil {
logrus.Warnf("commandConn.Close: CloseRead: %v", err)
return err
}
if err := c.CloseWrite(); err != nil {
logrus.Warnf("commandConn.Close: CloseWrite: %v", err)
return err
}
return nil
}
func (c *commandConn) LocalAddr() net.Addr {
return c.localAddr
}
func (c *commandConn) RemoteAddr() net.Addr {
return c.remoteAddr
}
func (c *commandConn) SetDeadline(t time.Time) error {
logrus.Debugf("unimplemented call: SetDeadline(%v)", t)
return nil
}
func (c *commandConn) SetReadDeadline(t time.Time) error {
logrus.Debugf("unimplemented call: SetReadDeadline(%v)", t)
return nil
}
func (c *commandConn) SetWriteDeadline(t time.Time) error {
logrus.Debugf("unimplemented call: SetWriteDeadline(%v)", t)
return nil
}
type dummyAddr struct {
network string
s string
}
func (d dummyAddr) Network() string {
return d.network
}
func (d dummyAddr) String() string {
return d.s
}
type stderrWriter struct {
stderrMu *sync.Mutex
stderr *bytes.Buffer
debugPrefix string
}
func (w *stderrWriter) Write(p []byte) (int, error) {
logrus.Debugf("%s%s", w.debugPrefix, string(p))
w.stderrMu.Lock()
if w.stderr.Len() > 4096 {
w.stderr.Reset()
}
n, err := w.stderr.Write(p)
w.stderrMu.Unlock()
return n, err
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/cli/cli/connhelper/commandconn/pdeathsig_linux.go | vendor/github.com/docker/cli/cli/connhelper/commandconn/pdeathsig_linux.go | package commandconn
import (
"os/exec"
"syscall"
)
func setPdeathsig(cmd *exec.Cmd) {
cmd.SysProcAttr.Pdeathsig = syscall.SIGKILL
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/cli/cli/config/config.go | vendor/github.com/docker/cli/cli/config/config.go | package config
import (
"fmt"
"io"
"os"
"os/user"
"path/filepath"
"runtime"
"strings"
"sync"
"github.com/docker/cli/cli/config/configfile"
"github.com/docker/cli/cli/config/credentials"
"github.com/docker/cli/cli/config/types"
"github.com/pkg/errors"
)
const (
// EnvOverrideConfigDir is the name of the environment variable that can be
// used to override the location of the client configuration files (~/.docker).
//
// It takes priority over the default, but can be overridden by the "--config"
// command line option.
EnvOverrideConfigDir = "DOCKER_CONFIG"
// ConfigFileName is the name of the client configuration file inside the
// config-directory.
ConfigFileName = "config.json"
configFileDir = ".docker"
contextsDir = "contexts"
)
var (
initConfigDir = new(sync.Once)
configDir string
)
// resetConfigDir is used in testing to reset the "configDir" package variable
// and its sync.Once to force re-lookup between tests.
func resetConfigDir() {
configDir = ""
initConfigDir = new(sync.Once)
}
// getHomeDir returns the home directory of the current user with the help of
// environment variables depending on the target operating system.
// Returned path should be used with "path/filepath" to form new paths.
//
// On non-Windows platforms, it falls back to nss lookups, if the home
// directory cannot be obtained from environment-variables.
//
// If linking statically with cgo enabled against glibc, ensure the
// osusergo build tag is used.
//
// If needing to do nss lookups, do not disable cgo or set osusergo.
//
// getHomeDir is a copy of [pkg/homedir.Get] to prevent adding docker/docker
// as dependency for consumers that only need to read the config-file.
//
// [pkg/homedir.Get]: https://pkg.go.dev/github.com/docker/docker@v26.1.4+incompatible/pkg/homedir#Get
func getHomeDir() string {
home, _ := os.UserHomeDir()
if home == "" && runtime.GOOS != "windows" {
if u, err := user.Current(); err == nil {
return u.HomeDir
}
}
return home
}
// Dir returns the directory the configuration file is stored in
func Dir() string {
initConfigDir.Do(func() {
configDir = os.Getenv(EnvOverrideConfigDir)
if configDir == "" {
configDir = filepath.Join(getHomeDir(), configFileDir)
}
})
return configDir
}
// ContextStoreDir returns the directory the docker contexts are stored in
func ContextStoreDir() string {
return filepath.Join(Dir(), contextsDir)
}
// SetDir sets the directory the configuration file is stored in
func SetDir(dir string) {
// trigger the sync.Once to synchronise with Dir()
initConfigDir.Do(func() {})
configDir = filepath.Clean(dir)
}
// Path returns the path to a file relative to the config dir
func Path(p ...string) (string, error) {
path := filepath.Join(append([]string{Dir()}, p...)...)
if !strings.HasPrefix(path, Dir()+string(filepath.Separator)) {
return "", errors.Errorf("path %q is outside of root config directory %q", path, Dir())
}
return path, nil
}
// LoadFromReader is a convenience function that creates a ConfigFile object from
// a reader. It returns an error if configData is malformed.
func LoadFromReader(configData io.Reader) (*configfile.ConfigFile, error) {
configFile := configfile.ConfigFile{
AuthConfigs: make(map[string]types.AuthConfig),
}
err := configFile.LoadFromReader(configData)
return &configFile, err
}
// Load reads the configuration file ([ConfigFileName]) from the given directory.
// If no directory is given, it uses the default [Dir]. A [*configfile.ConfigFile]
// is returned containing the contents of the configuration file, or a default
// struct if no configfile exists in the given location.
//
// Load returns an error if a configuration file exists in the given location,
// but cannot be read, or is malformed. Consumers must handle errors to prevent
// overwriting an existing configuration file.
func Load(configDir string) (*configfile.ConfigFile, error) {
if configDir == "" {
configDir = Dir()
}
return load(configDir)
}
func load(configDir string) (*configfile.ConfigFile, error) {
filename := filepath.Join(configDir, ConfigFileName)
configFile := configfile.New(filename)
file, err := os.Open(filename)
if err != nil {
if os.IsNotExist(err) {
// It is OK for no configuration file to be present, in which
// case we return a default struct.
return configFile, nil
}
// Any other error happening when failing to read the file must be returned.
return configFile, errors.Wrap(err, "loading config file")
}
defer file.Close()
err = configFile.LoadFromReader(file)
if err != nil {
err = errors.Wrapf(err, "loading config file: %s: ", filename)
}
return configFile, err
}
// LoadDefaultConfigFile attempts to load the default config file and returns
// a reference to the ConfigFile struct. If none is found or when failing to load
// the configuration file, it initializes a default ConfigFile struct. If no
// credentials-store is set in the configuration file, it attempts to discover
// the default store to use for the current platform.
//
// Important: LoadDefaultConfigFile prints a warning to stderr when failing to
// load the configuration file, but otherwise ignores errors. Consumers should
// consider using [Load] (and [credentials.DetectDefaultStore]) to detect errors
// when updating the configuration file, to prevent discarding a (malformed)
// configuration file.
func LoadDefaultConfigFile(stderr io.Writer) *configfile.ConfigFile {
configFile, err := load(Dir())
if err != nil {
// FIXME(thaJeztah): we should not proceed here to prevent overwriting existing (but malformed) config files; see https://github.com/docker/cli/issues/5075
_, _ = fmt.Fprintln(stderr, "WARNING: Error", err)
}
if !configFile.ContainsAuth() {
configFile.CredentialsStore = credentials.DetectDefaultStore(configFile.CredentialsStore)
}
return configFile
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/cli/cli/config/configfile/file.go | vendor/github.com/docker/cli/cli/config/configfile/file.go | package configfile
import (
"encoding/base64"
"encoding/json"
"io"
"os"
"path/filepath"
"strings"
"github.com/docker/cli/cli/config/credentials"
"github.com/docker/cli/cli/config/types"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
// ConfigFile ~/.docker/config.json file info
type ConfigFile struct {
AuthConfigs map[string]types.AuthConfig `json:"auths"`
HTTPHeaders map[string]string `json:"HttpHeaders,omitempty"`
PsFormat string `json:"psFormat,omitempty"`
ImagesFormat string `json:"imagesFormat,omitempty"`
NetworksFormat string `json:"networksFormat,omitempty"`
PluginsFormat string `json:"pluginsFormat,omitempty"`
VolumesFormat string `json:"volumesFormat,omitempty"`
StatsFormat string `json:"statsFormat,omitempty"`
DetachKeys string `json:"detachKeys,omitempty"`
CredentialsStore string `json:"credsStore,omitempty"`
CredentialHelpers map[string]string `json:"credHelpers,omitempty"`
Filename string `json:"-"` // Note: for internal use only
ServiceInspectFormat string `json:"serviceInspectFormat,omitempty"`
ServicesFormat string `json:"servicesFormat,omitempty"`
TasksFormat string `json:"tasksFormat,omitempty"`
SecretFormat string `json:"secretFormat,omitempty"`
ConfigFormat string `json:"configFormat,omitempty"`
NodesFormat string `json:"nodesFormat,omitempty"`
PruneFilters []string `json:"pruneFilters,omitempty"`
Proxies map[string]ProxyConfig `json:"proxies,omitempty"`
Experimental string `json:"experimental,omitempty"`
CurrentContext string `json:"currentContext,omitempty"`
CLIPluginsExtraDirs []string `json:"cliPluginsExtraDirs,omitempty"`
Plugins map[string]map[string]string `json:"plugins,omitempty"`
Aliases map[string]string `json:"aliases,omitempty"`
Features map[string]string `json:"features,omitempty"`
}
// ProxyConfig contains proxy configuration settings
type ProxyConfig struct {
HTTPProxy string `json:"httpProxy,omitempty"`
HTTPSProxy string `json:"httpsProxy,omitempty"`
NoProxy string `json:"noProxy,omitempty"`
FTPProxy string `json:"ftpProxy,omitempty"`
AllProxy string `json:"allProxy,omitempty"`
}
// New initializes an empty configuration file for the given filename 'fn'
func New(fn string) *ConfigFile {
return &ConfigFile{
AuthConfigs: make(map[string]types.AuthConfig),
HTTPHeaders: make(map[string]string),
Filename: fn,
Plugins: make(map[string]map[string]string),
Aliases: make(map[string]string),
}
}
// LoadFromReader reads the configuration data given and sets up the auth config
// information with given directory and populates the receiver object
func (configFile *ConfigFile) LoadFromReader(configData io.Reader) error {
if err := json.NewDecoder(configData).Decode(configFile); err != nil && !errors.Is(err, io.EOF) {
return err
}
var err error
for addr, ac := range configFile.AuthConfigs {
if ac.Auth != "" {
ac.Username, ac.Password, err = decodeAuth(ac.Auth)
if err != nil {
return err
}
}
ac.Auth = ""
ac.ServerAddress = addr
configFile.AuthConfigs[addr] = ac
}
return nil
}
// ContainsAuth returns whether there is authentication configured
// in this file or not.
func (configFile *ConfigFile) ContainsAuth() bool {
return configFile.CredentialsStore != "" ||
len(configFile.CredentialHelpers) > 0 ||
len(configFile.AuthConfigs) > 0
}
// GetAuthConfigs returns the mapping of repo to auth configuration
func (configFile *ConfigFile) GetAuthConfigs() map[string]types.AuthConfig {
if configFile.AuthConfigs == nil {
configFile.AuthConfigs = make(map[string]types.AuthConfig)
}
return configFile.AuthConfigs
}
// SaveToWriter encodes and writes out all the authorization information to
// the given writer
func (configFile *ConfigFile) SaveToWriter(writer io.Writer) error {
// Encode sensitive data into a new/temp struct
tmpAuthConfigs := make(map[string]types.AuthConfig, len(configFile.AuthConfigs))
for k, authConfig := range configFile.AuthConfigs {
authCopy := authConfig
// encode and save the authstring, while blanking out the original fields
authCopy.Auth = encodeAuth(&authCopy)
authCopy.Username = ""
authCopy.Password = ""
authCopy.ServerAddress = ""
tmpAuthConfigs[k] = authCopy
}
saveAuthConfigs := configFile.AuthConfigs
configFile.AuthConfigs = tmpAuthConfigs
defer func() { configFile.AuthConfigs = saveAuthConfigs }()
// User-Agent header is automatically set, and should not be stored in the configuration
for v := range configFile.HTTPHeaders {
if strings.EqualFold(v, "User-Agent") {
delete(configFile.HTTPHeaders, v)
}
}
data, err := json.MarshalIndent(configFile, "", "\t")
if err != nil {
return err
}
_, err = writer.Write(data)
return err
}
// Save encodes and writes out all the authorization information
func (configFile *ConfigFile) Save() (retErr error) {
if configFile.Filename == "" {
return errors.Errorf("Can't save config with empty filename")
}
dir := filepath.Dir(configFile.Filename)
if err := os.MkdirAll(dir, 0o700); err != nil {
return err
}
temp, err := os.CreateTemp(dir, filepath.Base(configFile.Filename))
if err != nil {
return err
}
defer func() {
temp.Close()
if retErr != nil {
if err := os.Remove(temp.Name()); err != nil {
logrus.WithError(err).WithField("file", temp.Name()).Debug("Error cleaning up temp file")
}
}
}()
err = configFile.SaveToWriter(temp)
if err != nil {
return err
}
if err := temp.Close(); err != nil {
return errors.Wrap(err, "error closing temp file")
}
// Handle situation where the configfile is a symlink
cfgFile := configFile.Filename
if f, err := os.Readlink(cfgFile); err == nil {
cfgFile = f
}
// Try copying the current config file (if any) ownership and permissions
copyFilePermissions(cfgFile, temp.Name())
return os.Rename(temp.Name(), cfgFile)
}
// ParseProxyConfig computes proxy configuration by retrieving the config for the provided host and
// then checking this against any environment variables provided to the container
func (configFile *ConfigFile) ParseProxyConfig(host string, runOpts map[string]*string) map[string]*string {
var cfgKey string
if _, ok := configFile.Proxies[host]; !ok {
cfgKey = "default"
} else {
cfgKey = host
}
config := configFile.Proxies[cfgKey]
permitted := map[string]*string{
"HTTP_PROXY": &config.HTTPProxy,
"HTTPS_PROXY": &config.HTTPSProxy,
"NO_PROXY": &config.NoProxy,
"FTP_PROXY": &config.FTPProxy,
"ALL_PROXY": &config.AllProxy,
}
m := runOpts
if m == nil {
m = make(map[string]*string)
}
for k := range permitted {
if *permitted[k] == "" {
continue
}
if _, ok := m[k]; !ok {
m[k] = permitted[k]
}
if _, ok := m[strings.ToLower(k)]; !ok {
m[strings.ToLower(k)] = permitted[k]
}
}
return m
}
// encodeAuth creates a base64 encoded string to containing authorization information
func encodeAuth(authConfig *types.AuthConfig) string {
if authConfig.Username == "" && authConfig.Password == "" {
return ""
}
authStr := authConfig.Username + ":" + authConfig.Password
msg := []byte(authStr)
encoded := make([]byte, base64.StdEncoding.EncodedLen(len(msg)))
base64.StdEncoding.Encode(encoded, msg)
return string(encoded)
}
// decodeAuth decodes a base64 encoded string and returns username and password
func decodeAuth(authStr string) (string, string, error) {
if authStr == "" {
return "", "", nil
}
decLen := base64.StdEncoding.DecodedLen(len(authStr))
decoded := make([]byte, decLen)
authByte := []byte(authStr)
n, err := base64.StdEncoding.Decode(decoded, authByte)
if err != nil {
return "", "", err
}
if n > decLen {
return "", "", errors.Errorf("Something went wrong decoding auth config")
}
userName, password, ok := strings.Cut(string(decoded), ":")
if !ok || userName == "" {
return "", "", errors.Errorf("Invalid auth configuration file")
}
return userName, strings.Trim(password, "\x00"), nil
}
// GetCredentialsStore returns a new credentials store from the settings in the
// configuration file
func (configFile *ConfigFile) GetCredentialsStore(registryHostname string) credentials.Store {
if helper := getConfiguredCredentialStore(configFile, registryHostname); helper != "" {
return newNativeStore(configFile, helper)
}
return credentials.NewFileStore(configFile)
}
// var for unit testing.
var newNativeStore = func(configFile *ConfigFile, helperSuffix string) credentials.Store {
return credentials.NewNativeStore(configFile, helperSuffix)
}
// GetAuthConfig for a repository from the credential store
func (configFile *ConfigFile) GetAuthConfig(registryHostname string) (types.AuthConfig, error) {
return configFile.GetCredentialsStore(registryHostname).Get(registryHostname)
}
// getConfiguredCredentialStore returns the credential helper configured for the
// given registry, the default credsStore, or the empty string if neither are
// configured.
func getConfiguredCredentialStore(c *ConfigFile, registryHostname string) string {
if c.CredentialHelpers != nil && registryHostname != "" {
if helper, exists := c.CredentialHelpers[registryHostname]; exists {
return helper
}
}
return c.CredentialsStore
}
// GetAllCredentials returns all of the credentials stored in all of the
// configured credential stores.
func (configFile *ConfigFile) GetAllCredentials() (map[string]types.AuthConfig, error) {
auths := make(map[string]types.AuthConfig)
addAll := func(from map[string]types.AuthConfig) {
for reg, ac := range from {
auths[reg] = ac
}
}
defaultStore := configFile.GetCredentialsStore("")
newAuths, err := defaultStore.GetAll()
if err != nil {
return nil, err
}
addAll(newAuths)
// Auth configs from a registry-specific helper should override those from the default store.
for registryHostname := range configFile.CredentialHelpers {
newAuth, err := configFile.GetAuthConfig(registryHostname)
if err != nil {
// TODO(thaJeztah): use context-logger, so that this output can be suppressed (in tests).
logrus.WithError(err).Warnf("Failed to get credentials for registry: %s", registryHostname)
continue
}
auths[registryHostname] = newAuth
}
return auths, nil
}
// GetFilename returns the file name that this config file is based on.
func (configFile *ConfigFile) GetFilename() string {
return configFile.Filename
}
// PluginConfig retrieves the requested option for the given plugin.
func (configFile *ConfigFile) PluginConfig(pluginname, option string) (string, bool) {
if configFile.Plugins == nil {
return "", false
}
pluginConfig, ok := configFile.Plugins[pluginname]
if !ok {
return "", false
}
value, ok := pluginConfig[option]
return value, ok
}
// SetPluginConfig sets the option to the given value for the given
// plugin. Passing a value of "" will remove the option. If removing
// the final config item for a given plugin then also cleans up the
// overall plugin entry.
func (configFile *ConfigFile) SetPluginConfig(pluginname, option, value string) {
if configFile.Plugins == nil {
configFile.Plugins = make(map[string]map[string]string)
}
pluginConfig, ok := configFile.Plugins[pluginname]
if !ok {
pluginConfig = make(map[string]string)
configFile.Plugins[pluginname] = pluginConfig
}
if value != "" {
pluginConfig[option] = value
} else {
delete(pluginConfig, option)
}
if len(pluginConfig) == 0 {
delete(configFile.Plugins, pluginname)
}
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/cli/cli/config/configfile/file_windows.go | vendor/github.com/docker/cli/cli/config/configfile/file_windows.go | package configfile
func copyFilePermissions(src, dst string) {
// TODO implement for Windows
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/cli/cli/config/configfile/file_unix.go | vendor/github.com/docker/cli/cli/config/configfile/file_unix.go | //go:build !windows
package configfile
import (
"os"
"syscall"
)
// copyFilePermissions copies file ownership and permissions from "src" to "dst",
// ignoring any error during the process.
func copyFilePermissions(src, dst string) {
var (
mode os.FileMode = 0o600
uid, gid int
)
fi, err := os.Stat(src)
if err != nil {
return
}
if fi.Mode().IsRegular() {
mode = fi.Mode()
}
if err := os.Chmod(dst, mode); err != nil {
return
}
uid = int(fi.Sys().(*syscall.Stat_t).Uid)
gid = int(fi.Sys().(*syscall.Stat_t).Gid)
if uid > 0 && gid > 0 {
_ = os.Chown(dst, uid, gid)
}
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/cli/cli/config/types/authconfig.go | vendor/github.com/docker/cli/cli/config/types/authconfig.go | package types
// AuthConfig contains authorization information for connecting to a Registry
type AuthConfig struct {
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
Auth string `json:"auth,omitempty"`
// Email is an optional value associated with the username.
// This field is deprecated and will be removed in a later
// version of docker.
Email string `json:"email,omitempty"`
ServerAddress string `json:"serveraddress,omitempty"`
// IdentityToken is used to authenticate the user and get
// an access token for the registry.
IdentityToken string `json:"identitytoken,omitempty"`
// RegistryToken is a bearer token to be sent to a registry
RegistryToken string `json:"registrytoken,omitempty"`
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/cli/cli/config/credentials/credentials.go | vendor/github.com/docker/cli/cli/config/credentials/credentials.go | package credentials
import (
"github.com/docker/cli/cli/config/types"
)
// Store is the interface that any credentials store must implement.
type Store interface {
// Erase removes credentials from the store for a given server.
Erase(serverAddress string) error
// Get retrieves credentials from the store for a given server.
Get(serverAddress string) (types.AuthConfig, error)
// GetAll retrieves all the credentials from the store.
GetAll() (map[string]types.AuthConfig, error)
// Store saves credentials in the store.
Store(authConfig types.AuthConfig) error
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/cli/cli/config/credentials/default_store.go | vendor/github.com/docker/cli/cli/config/credentials/default_store.go | package credentials
import "os/exec"
// DetectDefaultStore return the default credentials store for the platform if
// no user-defined store is passed, and the store executable is available.
func DetectDefaultStore(store string) string {
if store != "" {
// use user-defined
return store
}
platformDefault := defaultCredentialsStore()
if platformDefault == "" {
return ""
}
if _, err := exec.LookPath(remoteCredentialsPrefix + platformDefault); err != nil {
return ""
}
return platformDefault
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/cli/cli/config/credentials/default_store_windows.go | vendor/github.com/docker/cli/cli/config/credentials/default_store_windows.go | package credentials
func defaultCredentialsStore() string {
return "wincred"
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/cli/cli/config/credentials/default_store_darwin.go | vendor/github.com/docker/cli/cli/config/credentials/default_store_darwin.go | package credentials
func defaultCredentialsStore() string {
return "osxkeychain"
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/cli/cli/config/credentials/default_store_linux.go | vendor/github.com/docker/cli/cli/config/credentials/default_store_linux.go | package credentials
import (
"os/exec"
)
func defaultCredentialsStore() string {
if _, err := exec.LookPath("pass"); err == nil {
return "pass"
}
return "secretservice"
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/cli/cli/config/credentials/native_store.go | vendor/github.com/docker/cli/cli/config/credentials/native_store.go | package credentials
import (
"github.com/docker/cli/cli/config/types"
"github.com/docker/docker-credential-helpers/client"
"github.com/docker/docker-credential-helpers/credentials"
)
const (
remoteCredentialsPrefix = "docker-credential-" //nolint:gosec // ignore G101: Potential hardcoded credentials
tokenUsername = "<token>"
)
// nativeStore implements a credentials store
// using native keychain to keep credentials secure.
// It piggybacks into a file store to keep users' emails.
type nativeStore struct {
programFunc client.ProgramFunc
fileStore Store
}
// NewNativeStore creates a new native store that
// uses a remote helper program to manage credentials.
func NewNativeStore(file store, helperSuffix string) Store {
name := remoteCredentialsPrefix + helperSuffix
return &nativeStore{
programFunc: client.NewShellProgramFunc(name),
fileStore: NewFileStore(file),
}
}
// Erase removes the given credentials from the native store.
func (c *nativeStore) Erase(serverAddress string) error {
if err := client.Erase(c.programFunc, serverAddress); err != nil {
return err
}
// Fallback to plain text store to remove email
return c.fileStore.Erase(serverAddress)
}
// Get retrieves credentials for a specific server from the native store.
func (c *nativeStore) Get(serverAddress string) (types.AuthConfig, error) {
// load user email if it exist or an empty auth config.
auth, _ := c.fileStore.Get(serverAddress)
creds, err := c.getCredentialsFromStore(serverAddress)
if err != nil {
return auth, err
}
auth.Username = creds.Username
auth.IdentityToken = creds.IdentityToken
auth.Password = creds.Password
auth.ServerAddress = creds.ServerAddress
return auth, nil
}
// GetAll retrieves all the credentials from the native store.
func (c *nativeStore) GetAll() (map[string]types.AuthConfig, error) {
auths, err := c.listCredentialsInStore()
if err != nil {
return nil, err
}
// Emails are only stored in the file store.
// This call can be safely eliminated when emails are removed.
fileConfigs, _ := c.fileStore.GetAll()
authConfigs := make(map[string]types.AuthConfig)
for registry := range auths {
creds, err := c.getCredentialsFromStore(registry)
if err != nil {
return nil, err
}
ac := fileConfigs[registry] // might contain Email
ac.Username = creds.Username
ac.Password = creds.Password
ac.IdentityToken = creds.IdentityToken
if ac.ServerAddress == "" {
ac.ServerAddress = creds.ServerAddress
}
authConfigs[registry] = ac
}
return authConfigs, nil
}
// Store saves the given credentials in the file store.
func (c *nativeStore) Store(authConfig types.AuthConfig) error {
if err := c.storeCredentialsInStore(authConfig); err != nil {
return err
}
authConfig.Username = ""
authConfig.Password = ""
authConfig.IdentityToken = ""
// Fallback to old credential in plain text to save only the email
return c.fileStore.Store(authConfig)
}
// storeCredentialsInStore executes the command to store the credentials in the native store.
func (c *nativeStore) storeCredentialsInStore(config types.AuthConfig) error {
creds := &credentials.Credentials{
ServerURL: config.ServerAddress,
Username: config.Username,
Secret: config.Password,
}
if config.IdentityToken != "" {
creds.Username = tokenUsername
creds.Secret = config.IdentityToken
}
return client.Store(c.programFunc, creds)
}
// getCredentialsFromStore executes the command to get the credentials from the native store.
func (c *nativeStore) getCredentialsFromStore(serverAddress string) (types.AuthConfig, error) {
var ret types.AuthConfig
creds, err := client.Get(c.programFunc, serverAddress)
if err != nil {
if credentials.IsErrCredentialsNotFound(err) {
// do not return an error if the credentials are not
// in the keychain. Let docker ask for new credentials.
return ret, nil
}
return ret, err
}
if creds.Username == tokenUsername {
ret.IdentityToken = creds.Secret
} else {
ret.Password = creds.Secret
ret.Username = creds.Username
}
ret.ServerAddress = serverAddress
return ret, nil
}
// listCredentialsInStore returns a listing of stored credentials as a map of
// URL -> username.
func (c *nativeStore) listCredentialsInStore() (map[string]string, error) {
return client.List(c.programFunc)
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/cli/cli/config/credentials/file_store.go | vendor/github.com/docker/cli/cli/config/credentials/file_store.go | package credentials
import (
"net"
"net/url"
"strings"
"github.com/docker/cli/cli/config/types"
)
type store interface {
Save() error
GetAuthConfigs() map[string]types.AuthConfig
GetFilename() string
}
// fileStore implements a credentials store using
// the docker configuration file to keep the credentials in plain text.
type fileStore struct {
file store
}
// NewFileStore creates a new file credentials store.
func NewFileStore(file store) Store {
return &fileStore{file: file}
}
// Erase removes the given credentials from the file store.
func (c *fileStore) Erase(serverAddress string) error {
delete(c.file.GetAuthConfigs(), serverAddress)
return c.file.Save()
}
// Get retrieves credentials for a specific server from the file store.
func (c *fileStore) Get(serverAddress string) (types.AuthConfig, error) {
authConfig, ok := c.file.GetAuthConfigs()[serverAddress]
if !ok {
// Maybe they have a legacy config file, we will iterate the keys converting
// them to the new format and testing
for r, ac := range c.file.GetAuthConfigs() {
if serverAddress == ConvertToHostname(r) {
return ac, nil
}
}
authConfig = types.AuthConfig{}
}
return authConfig, nil
}
func (c *fileStore) GetAll() (map[string]types.AuthConfig, error) {
return c.file.GetAuthConfigs(), nil
}
// Store saves the given credentials in the file store.
func (c *fileStore) Store(authConfig types.AuthConfig) error {
authConfigs := c.file.GetAuthConfigs()
authConfigs[authConfig.ServerAddress] = authConfig
return c.file.Save()
}
func (c *fileStore) GetFilename() string {
return c.file.GetFilename()
}
func (c *fileStore) IsFileStore() bool {
return true
}
// ConvertToHostname converts a registry url which has http|https prepended
// to just an hostname.
// Copied from github.com/docker/docker/registry.ConvertToHostname to reduce dependencies.
func ConvertToHostname(maybeURL string) string {
stripped := maybeURL
if strings.Contains(stripped, "://") {
u, err := url.Parse(stripped)
if err == nil && u.Hostname() != "" {
if u.Port() == "" {
return u.Hostname()
}
return net.JoinHostPort(u.Hostname(), u.Port())
}
}
hostName, _, _ := strings.Cut(stripped, "/")
return hostName
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/cli/cli/config/credentials/default_store_unsupported.go | vendor/github.com/docker/cli/cli/config/credentials/default_store_unsupported.go | //go:build !windows && !darwin && !linux
package credentials
func defaultCredentialsStore() string {
return ""
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/cli/cli/context/tlsdata.go | vendor/github.com/docker/cli/cli/context/tlsdata.go | package context
import (
"os"
"github.com/docker/cli/cli/context/store"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
const (
caKey = "ca.pem"
certKey = "cert.pem"
keyKey = "key.pem"
)
// TLSData holds ca/cert/key raw data
type TLSData struct {
CA []byte
Key []byte
Cert []byte
}
// ToStoreTLSData converts TLSData to the store representation
func (data *TLSData) ToStoreTLSData() *store.EndpointTLSData {
if data == nil {
return nil
}
result := store.EndpointTLSData{
Files: make(map[string][]byte),
}
if data.CA != nil {
result.Files[caKey] = data.CA
}
if data.Cert != nil {
result.Files[certKey] = data.Cert
}
if data.Key != nil {
result.Files[keyKey] = data.Key
}
return &result
}
// LoadTLSData loads TLS data from the store
func LoadTLSData(s store.Reader, contextName, endpointName string) (*TLSData, error) {
tlsFiles, err := s.ListTLSFiles(contextName)
if err != nil {
return nil, errors.Wrapf(err, "failed to retrieve TLS files for context %q", contextName)
}
if epTLSFiles, ok := tlsFiles[endpointName]; ok {
var tlsData TLSData
for _, f := range epTLSFiles {
data, err := s.GetTLSData(contextName, endpointName, f)
if err != nil {
return nil, errors.Wrapf(err, "failed to retrieve TLS data (%s) for context %q", f, contextName)
}
switch f {
case caKey:
tlsData.CA = data
case certKey:
tlsData.Cert = data
case keyKey:
tlsData.Key = data
default:
logrus.Warnf("unknown file in context %s TLS bundle: %s", contextName, f)
}
}
return &tlsData, nil
}
return nil, nil
}
// TLSDataFromFiles reads files into a TLSData struct (or returns nil if all paths are empty)
func TLSDataFromFiles(caPath, certPath, keyPath string) (*TLSData, error) {
var (
ca, cert, key []byte
err error
)
if caPath != "" {
if ca, err = os.ReadFile(caPath); err != nil {
return nil, err
}
}
if certPath != "" {
if cert, err = os.ReadFile(certPath); err != nil {
return nil, err
}
}
if keyPath != "" {
if key, err = os.ReadFile(keyPath); err != nil {
return nil, err
}
}
if ca == nil && cert == nil && key == nil {
return nil, nil
}
return &TLSData{CA: ca, Cert: cert, Key: key}, nil
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/cli/cli/context/endpoint.go | vendor/github.com/docker/cli/cli/context/endpoint.go | package context
// EndpointMetaBase contains fields we expect to be common for most context endpoints
type EndpointMetaBase struct {
Host string `json:",omitempty"`
SkipTLSVerify bool
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/cli/cli/context/docker/constants.go | vendor/github.com/docker/cli/cli/context/docker/constants.go | package docker
const (
// DockerEndpoint is the name of the docker endpoint in a stored context
DockerEndpoint = "docker"
)
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/cli/cli/context/docker/load.go | vendor/github.com/docker/cli/cli/context/docker/load.go | package docker
import (
"crypto/tls"
"crypto/x509"
"encoding/pem"
"net"
"net/http"
"time"
"github.com/docker/cli/cli/connhelper"
"github.com/docker/cli/cli/context"
"github.com/docker/cli/cli/context/store"
"github.com/docker/docker/client"
"github.com/docker/go-connections/tlsconfig"
"github.com/pkg/errors"
)
// EndpointMeta is a typed wrapper around a context-store generic endpoint describing
// a Docker Engine endpoint, without its tls config
type EndpointMeta = context.EndpointMetaBase
// Endpoint is a typed wrapper around a context-store generic endpoint describing
// a Docker Engine endpoint, with its tls data
type Endpoint struct {
EndpointMeta
TLSData *context.TLSData
}
// WithTLSData loads TLS materials for the endpoint
func WithTLSData(s store.Reader, contextName string, m EndpointMeta) (Endpoint, error) {
tlsData, err := context.LoadTLSData(s, contextName, DockerEndpoint)
if err != nil {
return Endpoint{}, err
}
return Endpoint{
EndpointMeta: m,
TLSData: tlsData,
}, nil
}
// tlsConfig extracts a context docker endpoint TLS config
func (ep *Endpoint) tlsConfig() (*tls.Config, error) {
if ep.TLSData == nil && !ep.SkipTLSVerify {
// there is no specific tls config
return nil, nil
}
var tlsOpts []func(*tls.Config)
if ep.TLSData != nil && ep.TLSData.CA != nil {
certPool := x509.NewCertPool()
if !certPool.AppendCertsFromPEM(ep.TLSData.CA) {
return nil, errors.New("failed to retrieve context tls info: ca.pem seems invalid")
}
tlsOpts = append(tlsOpts, func(cfg *tls.Config) {
cfg.RootCAs = certPool
})
}
if ep.TLSData != nil && ep.TLSData.Key != nil && ep.TLSData.Cert != nil {
keyBytes := ep.TLSData.Key
pemBlock, _ := pem.Decode(keyBytes)
if pemBlock == nil {
return nil, errors.New("no valid private key found")
}
if x509.IsEncryptedPEMBlock(pemBlock) { //nolint:staticcheck // SA1019: x509.IsEncryptedPEMBlock is deprecated, and insecure by design
return nil, errors.New("private key is encrypted - support for encrypted private keys has been removed, see https://docs.docker.com/go/deprecated/")
}
x509cert, err := tls.X509KeyPair(ep.TLSData.Cert, keyBytes)
if err != nil {
return nil, errors.Wrap(err, "failed to retrieve context tls info")
}
tlsOpts = append(tlsOpts, func(cfg *tls.Config) {
cfg.Certificates = []tls.Certificate{x509cert}
})
}
if ep.SkipTLSVerify {
tlsOpts = append(tlsOpts, func(cfg *tls.Config) {
cfg.InsecureSkipVerify = true
})
}
return tlsconfig.ClientDefault(tlsOpts...), nil
}
// ClientOpts returns a slice of Client options to configure an API client with this endpoint
func (ep *Endpoint) ClientOpts() ([]client.Opt, error) {
var result []client.Opt
if ep.Host != "" {
helper, err := connhelper.GetConnectionHelper(ep.Host)
if err != nil {
return nil, err
}
if helper == nil {
tlsConfig, err := ep.tlsConfig()
if err != nil {
return nil, err
}
result = append(result,
withHTTPClient(tlsConfig),
client.WithHost(ep.Host),
)
} else {
result = append(result,
client.WithHTTPClient(&http.Client{
// No TLS, and no proxy.
Transport: &http.Transport{
DialContext: helper.Dialer,
},
}),
client.WithHost(helper.Host),
client.WithDialContext(helper.Dialer),
)
}
}
result = append(result, client.WithVersionFromEnv(), client.WithAPIVersionNegotiation())
return result, nil
}
func withHTTPClient(tlsConfig *tls.Config) func(*client.Client) error {
return func(c *client.Client) error {
if tlsConfig == nil {
// Use the default HTTPClient
return nil
}
return client.WithHTTPClient(&http.Client{
Transport: &http.Transport{
TLSClientConfig: tlsConfig,
DialContext: (&net.Dialer{
KeepAlive: 30 * time.Second,
Timeout: 30 * time.Second,
}).DialContext,
},
CheckRedirect: client.CheckRedirect,
})(c)
}
}
// EndpointFromContext parses a context docker endpoint metadata into a typed EndpointMeta structure
func EndpointFromContext(metadata store.Metadata) (EndpointMeta, error) {
ep, ok := metadata.Endpoints[DockerEndpoint]
if !ok {
return EndpointMeta{}, errors.New("cannot find docker endpoint in context")
}
typed, ok := ep.(EndpointMeta)
if !ok {
return EndpointMeta{}, errors.Errorf("endpoint %q is not of type EndpointMeta", DockerEndpoint)
}
return typed, nil
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/cli/cli/context/store/tlsstore.go | vendor/github.com/docker/cli/cli/context/store/tlsstore.go | package store
import (
"os"
"path/filepath"
"github.com/docker/docker/errdefs"
"github.com/docker/docker/pkg/ioutils"
"github.com/pkg/errors"
)
const tlsDir = "tls"
type tlsStore struct {
root string
}
func (s *tlsStore) contextDir(name string) string {
return filepath.Join(s.root, string(contextdirOf(name)))
}
func (s *tlsStore) endpointDir(name, endpointName string) string {
return filepath.Join(s.contextDir(name), endpointName)
}
func (s *tlsStore) createOrUpdate(name, endpointName, filename string, data []byte) error {
parentOfRoot := filepath.Dir(s.root)
if err := os.MkdirAll(parentOfRoot, 0o755); err != nil {
return err
}
endpointDir := s.endpointDir(name, endpointName)
if err := os.MkdirAll(endpointDir, 0o700); err != nil {
return err
}
return ioutils.AtomicWriteFile(filepath.Join(endpointDir, filename), data, 0o600)
}
func (s *tlsStore) getData(name, endpointName, filename string) ([]byte, error) {
data, err := os.ReadFile(filepath.Join(s.endpointDir(name, endpointName), filename))
if err != nil {
if os.IsNotExist(err) {
return nil, errdefs.NotFound(errors.Errorf("TLS data for %s/%s/%s does not exist", name, endpointName, filename))
}
return nil, errors.Wrapf(err, "failed to read TLS data for endpoint %s", endpointName)
}
return data, nil
}
// remove deletes all TLS data for the given context.
func (s *tlsStore) remove(name string) error {
if err := os.RemoveAll(s.contextDir(name)); err != nil {
return errors.Wrapf(err, "failed to remove TLS data")
}
return nil
}
func (s *tlsStore) removeEndpoint(name, endpointName string) error {
if err := os.RemoveAll(s.endpointDir(name, endpointName)); err != nil {
return errors.Wrapf(err, "failed to remove TLS data for endpoint %s", endpointName)
}
return nil
}
func (s *tlsStore) listContextData(name string) (map[string]EndpointFiles, error) {
contextDir := s.contextDir(name)
epFSs, err := os.ReadDir(contextDir)
if err != nil {
if os.IsNotExist(err) {
return map[string]EndpointFiles{}, nil
}
return nil, errors.Wrapf(err, "failed to list TLS files for context %s", name)
}
r := make(map[string]EndpointFiles)
for _, epFS := range epFSs {
if epFS.IsDir() {
fss, err := os.ReadDir(filepath.Join(contextDir, epFS.Name()))
if os.IsNotExist(err) {
continue
}
if err != nil {
return nil, errors.Wrapf(err, "failed to list TLS files for endpoint %s", epFS.Name())
}
var files EndpointFiles
for _, fs := range fss {
if !fs.IsDir() {
files = append(files, fs.Name())
}
}
r[epFS.Name()] = files
}
}
return r, nil
}
// EndpointFiles is a slice of strings representing file names
type EndpointFiles []string
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/cli/cli/context/store/storeconfig.go | vendor/github.com/docker/cli/cli/context/store/storeconfig.go | // FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16:
//go:build go1.21
package store
// TypeGetter is a func used to determine the concrete type of a context or
// endpoint metadata by returning a pointer to an instance of the object
// eg: for a context of type DockerContext, the corresponding TypeGetter should return new(DockerContext)
type TypeGetter func() any
// NamedTypeGetter is a TypeGetter associated with a name
type NamedTypeGetter struct {
name string
typeGetter TypeGetter
}
// EndpointTypeGetter returns a NamedTypeGetter with the specified name and getter
func EndpointTypeGetter(name string, getter TypeGetter) NamedTypeGetter {
return NamedTypeGetter{
name: name,
typeGetter: getter,
}
}
// Config is used to configure the metadata marshaler of the context ContextStore
type Config struct {
contextType TypeGetter
endpointTypes map[string]TypeGetter
}
// SetEndpoint set an endpoint typing information
func (c Config) SetEndpoint(name string, getter TypeGetter) {
c.endpointTypes[name] = getter
}
// ForeachEndpointType calls cb on every endpoint type registered with the Config
func (c Config) ForeachEndpointType(cb func(string, TypeGetter) error) error {
for n, ep := range c.endpointTypes {
if err := cb(n, ep); err != nil {
return err
}
}
return nil
}
// NewConfig creates a config object
func NewConfig(contextType TypeGetter, endpoints ...NamedTypeGetter) Config {
res := Config{
contextType: contextType,
endpointTypes: make(map[string]TypeGetter),
}
for _, e := range endpoints {
res.endpointTypes[e.name] = e.typeGetter
}
return res
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/cli/cli/context/store/io_utils.go | vendor/github.com/docker/cli/cli/context/store/io_utils.go | package store
import (
"errors"
"io"
)
// LimitedReader is a fork of io.LimitedReader to override Read.
type LimitedReader struct {
R io.Reader
N int64 // max bytes remaining
}
// Read is a fork of io.LimitedReader.Read that returns an error when limit exceeded.
func (l *LimitedReader) Read(p []byte) (n int, err error) {
if l.N < 0 {
return 0, errors.New("read exceeds the defined limit")
}
if l.N == 0 {
return 0, io.EOF
}
// have to cap N + 1 otherwise we won't hit limit err
if int64(len(p)) > l.N+1 {
p = p[0 : l.N+1]
}
n, err = l.R.Read(p)
l.N -= int64(n)
return n, err
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/cli/cli/context/store/store.go | vendor/github.com/docker/cli/cli/context/store/store.go | // FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16:
//go:build go1.21
package store
import (
"archive/tar"
"archive/zip"
"bufio"
"bytes"
_ "crypto/sha256" // ensure ids can be computed
"encoding/json"
"io"
"net/http"
"path"
"path/filepath"
"regexp"
"strings"
"github.com/docker/docker/errdefs"
"github.com/opencontainers/go-digest"
"github.com/pkg/errors"
)
const restrictedNamePattern = "^[a-zA-Z0-9][a-zA-Z0-9_.+-]+$"
var restrictedNameRegEx = regexp.MustCompile(restrictedNamePattern)
// Store provides a context store for easily remembering endpoints configuration
type Store interface {
Reader
Lister
Writer
StorageInfoProvider
}
// Reader provides read-only (without list) access to context data
type Reader interface {
GetMetadata(name string) (Metadata, error)
ListTLSFiles(name string) (map[string]EndpointFiles, error)
GetTLSData(contextName, endpointName, fileName string) ([]byte, error)
}
// Lister provides listing of contexts
type Lister interface {
List() ([]Metadata, error)
}
// ReaderLister combines Reader and Lister interfaces
type ReaderLister interface {
Reader
Lister
}
// StorageInfoProvider provides more information about storage details of contexts
type StorageInfoProvider interface {
GetStorageInfo(contextName string) StorageInfo
}
// Writer provides write access to context data
type Writer interface {
CreateOrUpdate(meta Metadata) error
Remove(name string) error
ResetTLSMaterial(name string, data *ContextTLSData) error
ResetEndpointTLSMaterial(contextName string, endpointName string, data *EndpointTLSData) error
}
// ReaderWriter combines Reader and Writer interfaces
type ReaderWriter interface {
Reader
Writer
}
// Metadata contains metadata about a context and its endpoints
type Metadata struct {
Name string `json:",omitempty"`
Metadata any `json:",omitempty"`
Endpoints map[string]any `json:",omitempty"`
}
// StorageInfo contains data about where a given context is stored
type StorageInfo struct {
MetadataPath string
TLSPath string
}
// EndpointTLSData represents tls data for a given endpoint
type EndpointTLSData struct {
Files map[string][]byte
}
// ContextTLSData represents tls data for a whole context
type ContextTLSData struct {
Endpoints map[string]EndpointTLSData
}
// New creates a store from a given directory.
// If the directory does not exist or is empty, initialize it
func New(dir string, cfg Config) *ContextStore {
metaRoot := filepath.Join(dir, metadataDir)
tlsRoot := filepath.Join(dir, tlsDir)
return &ContextStore{
meta: &metadataStore{
root: metaRoot,
config: cfg,
},
tls: &tlsStore{
root: tlsRoot,
},
}
}
// ContextStore implements Store.
type ContextStore struct {
meta *metadataStore
tls *tlsStore
}
// List return all contexts.
func (s *ContextStore) List() ([]Metadata, error) {
return s.meta.list()
}
// Names return Metadata names for a Lister
func Names(s Lister) ([]string, error) {
if s == nil {
return nil, errors.New("nil lister")
}
list, err := s.List()
if err != nil {
return nil, err
}
names := make([]string, 0, len(list))
for _, item := range list {
names = append(names, item.Name)
}
return names, nil
}
// CreateOrUpdate creates or updates metadata for the context.
func (s *ContextStore) CreateOrUpdate(meta Metadata) error {
return s.meta.createOrUpdate(meta)
}
// Remove deletes the context with the given name, if found.
func (s *ContextStore) Remove(name string) error {
if err := s.meta.remove(name); err != nil {
return errors.Wrapf(err, "failed to remove context %s", name)
}
if err := s.tls.remove(name); err != nil {
return errors.Wrapf(err, "failed to remove context %s", name)
}
return nil
}
// GetMetadata returns the metadata for the context with the given name.
// It returns an errdefs.ErrNotFound if the context was not found.
func (s *ContextStore) GetMetadata(name string) (Metadata, error) {
return s.meta.get(name)
}
// ResetTLSMaterial removes TLS data for all endpoints in the context and replaces
// it with the new data.
func (s *ContextStore) ResetTLSMaterial(name string, data *ContextTLSData) error {
if err := s.tls.remove(name); err != nil {
return err
}
if data == nil {
return nil
}
for ep, files := range data.Endpoints {
for fileName, data := range files.Files {
if err := s.tls.createOrUpdate(name, ep, fileName, data); err != nil {
return err
}
}
}
return nil
}
// ResetEndpointTLSMaterial removes TLS data for the given context and endpoint,
// and replaces it with the new data.
func (s *ContextStore) ResetEndpointTLSMaterial(contextName string, endpointName string, data *EndpointTLSData) error {
if err := s.tls.removeEndpoint(contextName, endpointName); err != nil {
return err
}
if data == nil {
return nil
}
for fileName, data := range data.Files {
if err := s.tls.createOrUpdate(contextName, endpointName, fileName, data); err != nil {
return err
}
}
return nil
}
// ListTLSFiles returns the list of TLS files present for each endpoint in the
// context.
func (s *ContextStore) ListTLSFiles(name string) (map[string]EndpointFiles, error) {
return s.tls.listContextData(name)
}
// GetTLSData reads, and returns the content of the given fileName for an endpoint.
// It returns an errdefs.ErrNotFound if the file was not found.
func (s *ContextStore) GetTLSData(contextName, endpointName, fileName string) ([]byte, error) {
return s.tls.getData(contextName, endpointName, fileName)
}
// GetStorageInfo returns the paths where the Metadata and TLS data are stored
// for the context.
func (s *ContextStore) GetStorageInfo(contextName string) StorageInfo {
return StorageInfo{
MetadataPath: s.meta.contextDir(contextdirOf(contextName)),
TLSPath: s.tls.contextDir(contextName),
}
}
// ValidateContextName checks a context name is valid.
func ValidateContextName(name string) error {
if name == "" {
return errors.New("context name cannot be empty")
}
if name == "default" {
return errors.New(`"default" is a reserved context name`)
}
if !restrictedNameRegEx.MatchString(name) {
return errors.Errorf("context name %q is invalid, names are validated against regexp %q", name, restrictedNamePattern)
}
return nil
}
// Export exports an existing namespace into an opaque data stream
// This stream is actually a tarball containing context metadata and TLS materials, but it does
// not map 1:1 the layout of the context store (don't try to restore it manually without calling store.Import)
func Export(name string, s Reader) io.ReadCloser {
reader, writer := io.Pipe()
go func() {
tw := tar.NewWriter(writer)
defer tw.Close()
defer writer.Close()
meta, err := s.GetMetadata(name)
if err != nil {
writer.CloseWithError(err)
return
}
metaBytes, err := json.Marshal(&meta)
if err != nil {
writer.CloseWithError(err)
return
}
if err = tw.WriteHeader(&tar.Header{
Name: metaFile,
Mode: 0o644,
Size: int64(len(metaBytes)),
}); err != nil {
writer.CloseWithError(err)
return
}
if _, err = tw.Write(metaBytes); err != nil {
writer.CloseWithError(err)
return
}
tlsFiles, err := s.ListTLSFiles(name)
if err != nil {
writer.CloseWithError(err)
return
}
if err = tw.WriteHeader(&tar.Header{
Name: "tls",
Mode: 0o700,
Size: 0,
Typeflag: tar.TypeDir,
}); err != nil {
writer.CloseWithError(err)
return
}
for endpointName, endpointFiles := range tlsFiles {
if err = tw.WriteHeader(&tar.Header{
Name: path.Join("tls", endpointName),
Mode: 0o700,
Size: 0,
Typeflag: tar.TypeDir,
}); err != nil {
writer.CloseWithError(err)
return
}
for _, fileName := range endpointFiles {
data, err := s.GetTLSData(name, endpointName, fileName)
if err != nil {
writer.CloseWithError(err)
return
}
if err = tw.WriteHeader(&tar.Header{
Name: path.Join("tls", endpointName, fileName),
Mode: 0o600,
Size: int64(len(data)),
}); err != nil {
writer.CloseWithError(err)
return
}
if _, err = tw.Write(data); err != nil {
writer.CloseWithError(err)
return
}
}
}
}()
return reader
}
const (
maxAllowedFileSizeToImport int64 = 10 << 20
zipType string = "application/zip"
)
func getImportContentType(r *bufio.Reader) (string, error) {
head, err := r.Peek(512)
if err != nil && err != io.EOF {
return "", err
}
return http.DetectContentType(head), nil
}
// Import imports an exported context into a store
func Import(name string, s Writer, reader io.Reader) error {
// Buffered reader will not advance the buffer, needed to determine content type
r := bufio.NewReader(reader)
importContentType, err := getImportContentType(r)
if err != nil {
return err
}
switch importContentType {
case zipType:
return importZip(name, s, r)
default:
// Assume it's a TAR (TAR does not have a "magic number")
return importTar(name, s, r)
}
}
func isValidFilePath(p string) error {
if p != metaFile && !strings.HasPrefix(p, "tls/") {
return errors.New("unexpected context file")
}
if path.Clean(p) != p {
return errors.New("unexpected path format")
}
if strings.Contains(p, `\`) {
return errors.New(`unexpected '\' in path`)
}
return nil
}
func importTar(name string, s Writer, reader io.Reader) error {
tr := tar.NewReader(&LimitedReader{R: reader, N: maxAllowedFileSizeToImport})
tlsData := ContextTLSData{
Endpoints: map[string]EndpointTLSData{},
}
var importedMetaFile bool
for {
hdr, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
return err
}
if hdr.Typeflag != tar.TypeReg {
// skip this entry, only taking files into account
continue
}
if err := isValidFilePath(hdr.Name); err != nil {
return errors.Wrap(err, hdr.Name)
}
if hdr.Name == metaFile {
data, err := io.ReadAll(tr)
if err != nil {
return err
}
meta, err := parseMetadata(data, name)
if err != nil {
return err
}
if err := s.CreateOrUpdate(meta); err != nil {
return err
}
importedMetaFile = true
} else if strings.HasPrefix(hdr.Name, "tls/") {
data, err := io.ReadAll(tr)
if err != nil {
return err
}
if err := importEndpointTLS(&tlsData, hdr.Name, data); err != nil {
return err
}
}
}
if !importedMetaFile {
return errdefs.InvalidParameter(errors.New("invalid context: no metadata found"))
}
return s.ResetTLSMaterial(name, &tlsData)
}
func importZip(name string, s Writer, reader io.Reader) error {
body, err := io.ReadAll(&LimitedReader{R: reader, N: maxAllowedFileSizeToImport})
if err != nil {
return err
}
zr, err := zip.NewReader(bytes.NewReader(body), int64(len(body)))
if err != nil {
return err
}
tlsData := ContextTLSData{
Endpoints: map[string]EndpointTLSData{},
}
var importedMetaFile bool
for _, zf := range zr.File {
fi := zf.FileInfo()
if !fi.Mode().IsRegular() {
// skip this entry, only taking regular files into account
continue
}
if err := isValidFilePath(zf.Name); err != nil {
return errors.Wrap(err, zf.Name)
}
if zf.Name == metaFile {
f, err := zf.Open()
if err != nil {
return err
}
data, err := io.ReadAll(&LimitedReader{R: f, N: maxAllowedFileSizeToImport})
defer f.Close()
if err != nil {
return err
}
meta, err := parseMetadata(data, name)
if err != nil {
return err
}
if err := s.CreateOrUpdate(meta); err != nil {
return err
}
importedMetaFile = true
} else if strings.HasPrefix(zf.Name, "tls/") {
f, err := zf.Open()
if err != nil {
return err
}
data, err := io.ReadAll(f)
defer f.Close()
if err != nil {
return err
}
err = importEndpointTLS(&tlsData, zf.Name, data)
if err != nil {
return err
}
}
}
if !importedMetaFile {
return errdefs.InvalidParameter(errors.New("invalid context: no metadata found"))
}
return s.ResetTLSMaterial(name, &tlsData)
}
func parseMetadata(data []byte, name string) (Metadata, error) {
var meta Metadata
if err := json.Unmarshal(data, &meta); err != nil {
return meta, err
}
if err := ValidateContextName(name); err != nil {
return Metadata{}, err
}
meta.Name = name
return meta, nil
}
func importEndpointTLS(tlsData *ContextTLSData, tlsPath string, data []byte) error {
parts := strings.SplitN(strings.TrimPrefix(tlsPath, "tls/"), "/", 2)
if len(parts) != 2 {
// TLS endpoints require archived file directory with 2 layers
// i.e. tls/{endpointName}/{fileName}
return errors.New("archive format is invalid")
}
epName := parts[0]
fileName := parts[1]
if _, ok := tlsData.Endpoints[epName]; !ok {
tlsData.Endpoints[epName] = EndpointTLSData{
Files: map[string][]byte{},
}
}
tlsData.Endpoints[epName].Files[fileName] = data
return nil
}
type contextdir string
func contextdirOf(name string) contextdir {
return contextdir(digest.FromString(name).Encoded())
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/cli/cli/context/store/metadatastore.go | vendor/github.com/docker/cli/cli/context/store/metadatastore.go | // FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16:
//go:build go1.21
package store
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"reflect"
"sort"
"github.com/docker/docker/errdefs"
"github.com/docker/docker/pkg/ioutils"
"github.com/fvbommel/sortorder"
"github.com/pkg/errors"
)
const (
metadataDir = "meta"
metaFile = "meta.json"
)
type metadataStore struct {
root string
config Config
}
func (s *metadataStore) contextDir(id contextdir) string {
return filepath.Join(s.root, string(id))
}
func (s *metadataStore) createOrUpdate(meta Metadata) error {
contextDir := s.contextDir(contextdirOf(meta.Name))
if err := os.MkdirAll(contextDir, 0o755); err != nil {
return err
}
bytes, err := json.Marshal(&meta)
if err != nil {
return err
}
return ioutils.AtomicWriteFile(filepath.Join(contextDir, metaFile), bytes, 0o644)
}
func parseTypedOrMap(payload []byte, getter TypeGetter) (any, error) {
if len(payload) == 0 || string(payload) == "null" {
return nil, nil
}
if getter == nil {
var res map[string]any
if err := json.Unmarshal(payload, &res); err != nil {
return nil, err
}
return res, nil
}
typed := getter()
if err := json.Unmarshal(payload, typed); err != nil {
return nil, err
}
return reflect.ValueOf(typed).Elem().Interface(), nil
}
func (s *metadataStore) get(name string) (Metadata, error) {
m, err := s.getByID(contextdirOf(name))
if err != nil {
return m, errors.Wrapf(err, "context %q", name)
}
return m, nil
}
func (s *metadataStore) getByID(id contextdir) (Metadata, error) {
fileName := filepath.Join(s.contextDir(id), metaFile)
bytes, err := os.ReadFile(fileName)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return Metadata{}, errdefs.NotFound(errors.Wrap(err, "context not found"))
}
return Metadata{}, err
}
var untyped untypedContextMetadata
r := Metadata{
Endpoints: make(map[string]any),
}
if err := json.Unmarshal(bytes, &untyped); err != nil {
return Metadata{}, fmt.Errorf("parsing %s: %v", fileName, err)
}
r.Name = untyped.Name
if r.Metadata, err = parseTypedOrMap(untyped.Metadata, s.config.contextType); err != nil {
return Metadata{}, fmt.Errorf("parsing %s: %v", fileName, err)
}
for k, v := range untyped.Endpoints {
if r.Endpoints[k], err = parseTypedOrMap(v, s.config.endpointTypes[k]); err != nil {
return Metadata{}, fmt.Errorf("parsing %s: %v", fileName, err)
}
}
return r, err
}
func (s *metadataStore) remove(name string) error {
if err := os.RemoveAll(s.contextDir(contextdirOf(name))); err != nil {
return errors.Wrapf(err, "failed to remove metadata")
}
return nil
}
func (s *metadataStore) list() ([]Metadata, error) {
ctxDirs, err := listRecursivelyMetadataDirs(s.root)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
return nil, err
}
res := make([]Metadata, 0, len(ctxDirs))
for _, dir := range ctxDirs {
c, err := s.getByID(contextdir(dir))
if err != nil {
if errors.Is(err, os.ErrNotExist) {
continue
}
return nil, errors.Wrap(err, "failed to read metadata")
}
res = append(res, c)
}
sort.Slice(res, func(i, j int) bool {
return sortorder.NaturalLess(res[i].Name, res[j].Name)
})
return res, nil
}
func isContextDir(path string) bool {
s, err := os.Stat(filepath.Join(path, metaFile))
if err != nil {
return false
}
return !s.IsDir()
}
func listRecursivelyMetadataDirs(root string) ([]string, error) {
fis, err := os.ReadDir(root)
if err != nil {
return nil, err
}
var result []string
for _, fi := range fis {
if fi.IsDir() {
if isContextDir(filepath.Join(root, fi.Name())) {
result = append(result, fi.Name())
}
subs, err := listRecursivelyMetadataDirs(filepath.Join(root, fi.Name()))
if err != nil {
return nil, err
}
for _, s := range subs {
result = append(result, filepath.Join(fi.Name(), s))
}
}
}
return result, nil
}
type untypedContextMetadata struct {
Metadata json.RawMessage `json:"metadata,omitempty"`
Endpoints map[string]json.RawMessage `json:"endpoints,omitempty"`
Name string `json:"name,omitempty"`
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/cli/cli/context/store/doc.go | vendor/github.com/docker/cli/cli/context/store/doc.go | // Package store provides a generic way to store credentials to connect to
// virtually any kind of remote system.
// The term `context` comes from the similar feature in Kubernetes kubectl
// config files.
//
// Conceptually, a context is a set of metadata and TLS data, that can be used
// to connect to various endpoints of a remote system. TLS data and metadata
// are stored separately, so that in the future, we will be able to store
// sensitive information in a more secure way, depending on the os we are running
// on (e.g.: on Windows we could use the user Certificate Store, on macOS the
// user Keychain...).
//
// Current implementation is purely file based with the following structure:
//
// ${CONTEXT_ROOT}
// meta/
// <context id>/meta.json: contains context medata (key/value pairs) as
// well as a list of endpoints (themselves containing
// key/value pair metadata).
// tls/
// <context id>/endpoint1/: directory containing TLS data for the endpoint1
// in the corresponding context.
//
// The context store itself has absolutely no knowledge about what a docker
// endpoint should contain in term of metadata or TLS config. Client code is
// responsible for generating and parsing endpoint metadata and TLS files. The
// multi-endpoints approach of this package allows to combine many different
// endpoints in the same "context".
//
// Context IDs are actually SHA256 hashes of the context name, and are there
// only to avoid dealing with special characters in context names.
package store
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/encoding/ebcdic.go | vendor/github.com/gdamore/encoding/ebcdic.go | // Copyright 2015 Garrett D'Amore
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 encoding
import (
"golang.org/x/text/encoding"
)
// EBCDIC represents the 8-bit EBCDIC scheme, found in some mainframe
// environments. If you don't know what this is, consider yourself lucky.
var EBCDIC encoding.Encoding
func init() {
cm := &Charmap{
ReplacementChar: '\x3f',
Map: map[byte]rune{
// 0x00-0x03 match
0x04: RuneError,
0x05: '\t',
0x06: RuneError,
0x07: '\x7f',
0x08: RuneError,
0x09: RuneError,
0x0a: RuneError,
// 0x0b-0x13 match
0x14: RuneError,
0x15: '\x85', // Not in any ISO code
0x16: '\x08',
0x17: RuneError,
// 0x18-0x19 match
0x1a: RuneError,
0x1b: RuneError,
// 0x1c-0x1f match
0x20: RuneError,
0x21: RuneError,
0x22: RuneError,
0x23: RuneError,
0x24: RuneError,
0x25: '\n',
0x26: '\x17',
0x27: '\x1b',
0x28: RuneError,
0x29: RuneError,
0x2a: RuneError,
0x2b: RuneError,
0x2c: RuneError,
0x2d: '\x05',
0x2e: '\x06',
0x2f: '\x07',
0x30: RuneError,
0x31: RuneError,
0x32: '\x16',
0x33: RuneError,
0x34: RuneError,
0x35: RuneError,
0x36: RuneError,
0x37: '\x04',
0x38: RuneError,
0x39: RuneError,
0x3a: RuneError,
0x3b: RuneError,
0x3c: '\x14',
0x3d: '\x15',
0x3e: RuneError,
0x3f: '\x1a', // also replacement char
0x40: ' ',
0x41: '\xa0',
0x42: RuneError,
0x43: RuneError,
0x44: RuneError,
0x45: RuneError,
0x46: RuneError,
0x47: RuneError,
0x48: RuneError,
0x49: RuneError,
0x4a: RuneError,
0x4b: '.',
0x4c: '<',
0x4d: '(',
0x4e: '+',
0x4f: '|',
0x50: '&',
0x51: RuneError,
0x52: RuneError,
0x53: RuneError,
0x54: RuneError,
0x55: RuneError,
0x56: RuneError,
0x57: RuneError,
0x58: RuneError,
0x59: RuneError,
0x5a: '!',
0x5b: '$',
0x5c: '*',
0x5d: ')',
0x5e: ';',
0x5f: '¬',
0x60: '-',
0x61: '/',
0x62: RuneError,
0x63: RuneError,
0x64: RuneError,
0x65: RuneError,
0x66: RuneError,
0x67: RuneError,
0x68: RuneError,
0x69: RuneError,
0x6a: '¦',
0x6b: ',',
0x6c: '%',
0x6d: '_',
0x6e: '>',
0x6f: '?',
0x70: RuneError,
0x71: RuneError,
0x72: RuneError,
0x73: RuneError,
0x74: RuneError,
0x75: RuneError,
0x76: RuneError,
0x77: RuneError,
0x78: RuneError,
0x79: '`',
0x7a: ':',
0x7b: '#',
0x7c: '@',
0x7d: '\'',
0x7e: '=',
0x7f: '"',
0x80: RuneError,
0x81: 'a',
0x82: 'b',
0x83: 'c',
0x84: 'd',
0x85: 'e',
0x86: 'f',
0x87: 'g',
0x88: 'h',
0x89: 'i',
0x8a: RuneError,
0x8b: RuneError,
0x8c: RuneError,
0x8d: RuneError,
0x8e: RuneError,
0x8f: '±',
0x90: RuneError,
0x91: 'j',
0x92: 'k',
0x93: 'l',
0x94: 'm',
0x95: 'n',
0x96: 'o',
0x97: 'p',
0x98: 'q',
0x99: 'r',
0x9a: RuneError,
0x9b: RuneError,
0x9c: RuneError,
0x9d: RuneError,
0x9e: RuneError,
0x9f: RuneError,
0xa0: RuneError,
0xa1: '~',
0xa2: 's',
0xa3: 't',
0xa4: 'u',
0xa5: 'v',
0xa6: 'w',
0xa7: 'x',
0xa8: 'y',
0xa9: 'z',
0xaa: RuneError,
0xab: RuneError,
0xac: RuneError,
0xad: RuneError,
0xae: RuneError,
0xaf: RuneError,
0xb0: '^',
0xb1: RuneError,
0xb2: RuneError,
0xb3: RuneError,
0xb4: RuneError,
0xb5: RuneError,
0xb6: RuneError,
0xb7: RuneError,
0xb8: RuneError,
0xb9: RuneError,
0xba: '[',
0xbb: ']',
0xbc: RuneError,
0xbd: RuneError,
0xbe: RuneError,
0xbf: RuneError,
0xc0: '{',
0xc1: 'A',
0xc2: 'B',
0xc3: 'C',
0xc4: 'D',
0xc5: 'E',
0xc6: 'F',
0xc7: 'G',
0xc8: 'H',
0xc9: 'I',
0xca: '\xad', // NB: soft hyphen
0xcb: RuneError,
0xcc: RuneError,
0xcd: RuneError,
0xce: RuneError,
0xcf: RuneError,
0xd0: '}',
0xd1: 'J',
0xd2: 'K',
0xd3: 'L',
0xd4: 'M',
0xd5: 'N',
0xd6: 'O',
0xd7: 'P',
0xd8: 'Q',
0xd9: 'R',
0xda: RuneError,
0xdb: RuneError,
0xdc: RuneError,
0xdd: RuneError,
0xde: RuneError,
0xdf: RuneError,
0xe0: '\\',
0xe1: '\u2007', // Non-breaking space
0xe2: 'S',
0xe3: 'T',
0xe4: 'U',
0xe5: 'V',
0xe6: 'W',
0xe7: 'X',
0xe8: 'Y',
0xe9: 'Z',
0xea: RuneError,
0xeb: RuneError,
0xec: RuneError,
0xed: RuneError,
0xee: RuneError,
0xef: RuneError,
0xf0: '0',
0xf1: '1',
0xf2: '2',
0xf3: '3',
0xf4: '4',
0xf5: '5',
0xf6: '6',
0xf7: '7',
0xf8: '8',
0xf9: '9',
0xfa: RuneError,
0xfb: RuneError,
0xfc: RuneError,
0xfd: RuneError,
0xfe: RuneError,
0xff: RuneError,
}}
cm.Init()
EBCDIC = cm
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/encoding/latin5.go | vendor/github.com/gdamore/encoding/latin5.go | // Copyright 2015 Garrett D'Amore
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 encoding
import (
"golang.org/x/text/encoding"
)
// ISO8859_9 represents the 8-bit ISO8859-9 scheme.
var ISO8859_9 encoding.Encoding
func init() {
cm := &Charmap{Map: map[byte]rune{
0xD0: 'Ğ',
0xDD: 'İ',
0xDE: 'Ş',
0xF0: 'ğ',
0xFD: 'ı',
0xFE: 'ş',
}}
cm.Init()
ISO8859_9 = cm
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/encoding/utf8.go | vendor/github.com/gdamore/encoding/utf8.go | // Copyright 2015 Garrett D'Amore
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 encoding
import (
"golang.org/x/text/encoding"
)
type validUtf8 struct{}
// UTF8 is an encoding for UTF-8. All it does is verify that the UTF-8
// in is valid. The main reason for its existence is that it will detect
// and report ErrSrcShort or ErrDstShort, whereas the Nop encoding just
// passes every byte, blithely.
var UTF8 encoding.Encoding = validUtf8{}
func (validUtf8) NewDecoder() *encoding.Decoder {
return &encoding.Decoder{Transformer: encoding.UTF8Validator}
}
func (validUtf8) NewEncoder() *encoding.Encoder {
return &encoding.Encoder{Transformer: encoding.UTF8Validator}
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/encoding/charmap.go | vendor/github.com/gdamore/encoding/charmap.go | // Copyright 2024 Garrett D'Amore
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 encoding
import (
"sync"
"unicode/utf8"
"golang.org/x/text/encoding"
"golang.org/x/text/transform"
)
const (
// RuneError is an alias for the UTF-8 replacement rune, '\uFFFD'.
RuneError = '\uFFFD'
// RuneSelf is the rune below which UTF-8 and the Unicode values are
// identical. Its also the limit for ASCII.
RuneSelf = 0x80
// ASCIISub is the ASCII substitution character.
ASCIISub = '\x1a'
)
// Charmap is a structure for setting up encodings for 8-bit character sets,
// for transforming between UTF8 and that other character set. It has some
// ideas borrowed from golang.org/x/text/encoding/charmap, but it uses a
// different implementation. This implementation uses maps, and supports
// user-defined maps.
//
// We do assume that a character map has a reasonable substitution character,
// and that valid encodings are stable (exactly a 1:1 map) and stateless
// (that is there is no shift character or anything like that.) Hence this
// approach will not work for many East Asian character sets.
//
// Measurement shows little or no measurable difference in the performance of
// the two approaches. The difference was down to a couple of nsec/op, and
// no consistent pattern as to which ran faster. With the conversion to
// UTF-8 the code takes about 25 nsec/op. The conversion in the reverse
// direction takes about 100 nsec/op. (The larger cost for conversion
// from UTF-8 is most likely due to the need to convert the UTF-8 byte stream
// to a rune before conversion.
type Charmap struct {
transform.NopResetter
bytes map[rune]byte
runes [256][]byte
once sync.Once
// The map between bytes and runes. To indicate that a specific
// byte value is invalid for a charcter set, use the rune
// utf8.RuneError. Values that are absent from this map will
// be assumed to have the identity mapping -- that is the default
// is to assume ISO8859-1, where all 8-bit characters have the same
// numeric value as their Unicode runes. (Not to be confused with
// the UTF-8 values, which *will* be different for non-ASCII runes.)
//
// If no values less than RuneSelf are changed (or have non-identity
// mappings), then the character set is assumed to be an ASCII
// superset, and certain assumptions and optimizations become
// available for ASCII bytes.
Map map[byte]rune
// The ReplacementChar is the byte value to use for substitution.
// It should normally be ASCIISub for ASCII encodings. This may be
// unset (left to zero) for mappings that are strictly ASCII supersets.
// In that case ASCIISub will be assumed instead.
ReplacementChar byte
}
type cmapDecoder struct {
transform.NopResetter
runes [256][]byte
}
type cmapEncoder struct {
transform.NopResetter
bytes map[rune]byte
replace byte
}
// Init initializes internal values of a character map. This should
// be done early, to minimize the cost of allocation of transforms
// later. It is not strictly necessary however, as the allocation
// functions will arrange to call it if it has not already been done.
func (c *Charmap) Init() {
c.once.Do(c.initialize)
}
func (c *Charmap) initialize() {
c.bytes = make(map[rune]byte)
ascii := true
for i := 0; i < 256; i++ {
r, ok := c.Map[byte(i)]
if !ok {
r = rune(i)
}
if r < 128 && r != rune(i) {
ascii = false
}
if r != RuneError {
c.bytes[r] = byte(i)
}
utf := make([]byte, utf8.RuneLen(r))
utf8.EncodeRune(utf, r)
c.runes[i] = utf
}
if ascii && c.ReplacementChar == '\x00' {
c.ReplacementChar = ASCIISub
}
}
// NewDecoder returns a Decoder the converts from the 8-bit
// character set to UTF-8. Unknown mappings, if any, are mapped
// to '\uFFFD'.
func (c *Charmap) NewDecoder() *encoding.Decoder {
c.Init()
return &encoding.Decoder{Transformer: &cmapDecoder{runes: c.runes}}
}
// NewEncoder returns a Transformer that converts from UTF8 to the
// 8-bit character set. Unknown mappings are mapped to 0x1A.
func (c *Charmap) NewEncoder() *encoding.Encoder {
c.Init()
return &encoding.Encoder{
Transformer: &cmapEncoder{
bytes: c.bytes,
replace: c.ReplacementChar,
},
}
}
func (d *cmapDecoder) Transform(dst, src []byte, atEOF bool) (int, int, error) {
var e error
var ndst, nsrc int
for _, c := range src {
b := d.runes[c]
l := len(b)
if ndst+l > len(dst) {
e = transform.ErrShortDst
break
}
for i := 0; i < l; i++ {
dst[ndst] = b[i]
ndst++
}
nsrc++
}
return ndst, nsrc, e
}
func (d *cmapEncoder) Transform(dst, src []byte, atEOF bool) (int, int, error) {
var e error
var ndst, nsrc int
for nsrc < len(src) {
if ndst >= len(dst) {
e = transform.ErrShortDst
break
}
r, sz := utf8.DecodeRune(src[nsrc:])
if r == utf8.RuneError && sz == 1 {
// If its inconclusive due to insufficient data in
// in the source, report it
if atEOF && !utf8.FullRune(src[nsrc:]) {
e = transform.ErrShortSrc
break
}
}
if c, ok := d.bytes[r]; ok {
dst[ndst] = c
} else {
dst[ndst] = d.replace
}
nsrc += sz
ndst++
}
return ndst, nsrc, e
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/encoding/ascii.go | vendor/github.com/gdamore/encoding/ascii.go | // Copyright 2015 Garrett D'Amore
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 encoding
import (
"golang.org/x/text/encoding"
)
// ASCII represents the 7-bit US-ASCII scheme. It decodes directly to
// UTF-8 without change, as all ASCII values are legal UTF-8.
// Unicode values less than 128 (i.e. 7 bits) map 1:1 with ASCII.
// It encodes runes outside of that to 0x1A, the ASCII substitution character.
var ASCII encoding.Encoding
func init() {
amap := make(map[byte]rune)
for i := 128; i <= 255; i++ {
amap[byte(i)] = RuneError
}
cm := &Charmap{Map: amap}
cm.Init()
ASCII = cm
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/encoding/doc.go | vendor/github.com/gdamore/encoding/doc.go | // Copyright 2015 Garrett D'Amore
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 encoding provides a few of the encoding structures that are
// missing from the Go x/text/encoding tree.
package encoding
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/encoding/latin1.go | vendor/github.com/gdamore/encoding/latin1.go | // Copyright 2015 Garrett D'Amore
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 encoding
import (
"golang.org/x/text/encoding"
)
// ISO8859_1 represents the 8-bit ISO8859-1 scheme. It decodes directly to
// UTF-8 without change, as all ISO8859-1 values are legal UTF-8.
// Unicode values less than 256 (i.e. 8 bits) map 1:1 with 8859-1.
// It encodes runes outside of that to 0x1A, the ASCII substitution character.
var ISO8859_1 encoding.Encoding
func init() {
cm := &Charmap{}
cm.Init()
// 8859-1 is the 8-bit identity map for Unicode.
ISO8859_1 = cm
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/runes.go | vendor/github.com/gdamore/tcell/v2/runes.go | // Copyright 2015 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 tcell
// The names of these constants are chosen to match Terminfo names,
// modulo case, and changing the prefix from ACS_ to Rune. These are
// the runes we provide extra special handling for, with ASCII fallbacks
// for terminals that lack them.
const (
RuneSterling = '£'
RuneDArrow = '↓'
RuneLArrow = '←'
RuneRArrow = '→'
RuneUArrow = '↑'
RuneBullet = '·'
RuneBoard = '░'
RuneCkBoard = '▒'
RuneDegree = '°'
RuneDiamond = '◆'
RuneGEqual = '≥'
RunePi = 'π'
RuneHLine = '─'
RuneLantern = '§'
RunePlus = '┼'
RuneLEqual = '≤'
RuneLLCorner = '└'
RuneLRCorner = '┘'
RuneNEqual = '≠'
RunePlMinus = '±'
RuneS1 = '⎺'
RuneS3 = '⎻'
RuneS7 = '⎼'
RuneS9 = '⎽'
RuneBlock = '█'
RuneTTee = '┬'
RuneRTee = '┤'
RuneLTee = '├'
RuneBTee = '┴'
RuneULCorner = '┌'
RuneURCorner = '┐'
RuneVLine = '│'
)
// RuneFallbacks is the default map of fallback strings that will be
// used to replace a rune when no other more appropriate transformation
// is available, and the rune cannot be displayed directly.
//
// New entries may be added to this map over time, as it becomes clear
// that such is desirable. Characters that represent either letters or
// numbers should not be added to this list unless it is certain that
// the meaning will still convey unambiguously.
//
// As an example, it would be appropriate to add an ASCII mapping for
// the full width form of the letter 'A', but it would not be appropriate
// to do so a glyph representing the country China.
//
// Programs that desire richer fallbacks may register additional ones,
// or change or even remove these mappings with Screen.RegisterRuneFallback
// Screen.UnregisterRuneFallback methods.
//
// Note that Unicode is presumed to be able to display all glyphs.
// This is a pretty poor assumption, but there is no easy way to
// figure out which glyphs are supported in a given font. Hence,
// some care in selecting the characters you support in your application
// is still appropriate.
var RuneFallbacks = map[rune]string{
RuneSterling: "f",
RuneDArrow: "v",
RuneLArrow: "<",
RuneRArrow: ">",
RuneUArrow: "^",
RuneBullet: "o",
RuneBoard: "#",
RuneCkBoard: ":",
RuneDegree: "\\",
RuneDiamond: "+",
RuneGEqual: ">",
RunePi: "*",
RuneHLine: "-",
RuneLantern: "#",
RunePlus: "+",
RuneLEqual: "<",
RuneLLCorner: "+",
RuneLRCorner: "+",
RuneNEqual: "!",
RunePlMinus: "#",
RuneS1: "~",
RuneS3: "-",
RuneS7: "-",
RuneS9: "_",
RuneBlock: "#",
RuneTTee: "+",
RuneRTee: "+",
RuneLTee: "+",
RuneBTee: "+",
RuneULCorner: "+",
RuneURCorner: "+",
RuneVLine: "|",
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/charset_windows.go | vendor/github.com/gdamore/tcell/v2/charset_windows.go | //go:build windows
// +build windows
// Copyright 2015 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 tcell
func getCharset() string {
return "UTF-16"
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/terms_static.go | vendor/github.com/gdamore/tcell/v2/terms_static.go | //go:build tcell_minimal || nacl || zos || plan9 || windows || android || js
// +build tcell_minimal nacl zos plan9 windows android js
// Copyright 2019 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 tcell
import (
"errors"
"github.com/gdamore/tcell/v2/terminfo"
)
func loadDynamicTerminfo(_ string) (*terminfo.Terminfo, error) {
return nil, errors.New("terminal type unsupported")
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/colorfit.go | vendor/github.com/gdamore/tcell/v2/colorfit.go | // Copyright 2016 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 tcell
import (
"math"
"github.com/lucasb-eyer/go-colorful"
)
// FindColor attempts to find a given color, or the best match possible for it,
// from the palette given. This is an expensive operation, so results should
// be cached by the caller.
func FindColor(c Color, palette []Color) Color {
match := ColorDefault
dist := float64(0)
r, g, b := c.RGB()
c1 := colorful.Color{
R: float64(r) / 255.0,
G: float64(g) / 255.0,
B: float64(b) / 255.0,
}
for _, d := range palette {
r, g, b = d.RGB()
c2 := colorful.Color{
R: float64(r) / 255.0,
G: float64(g) / 255.0,
B: float64(b) / 255.0,
}
// CIE94 is more accurate, but really really expensive.
nd := c1.DistanceCIE76(c2)
if math.IsNaN(nd) {
nd = math.Inf(1)
}
if match == ColorDefault || nd < dist {
match = d
dist = nd
}
}
return match
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/mouse.go | vendor/github.com/gdamore/tcell/v2/mouse.go | // Copyright 2020 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 tcell
import (
"time"
)
// EventMouse is a mouse event. It is sent on either mouse up or mouse down
// events. It is also sent on mouse motion events - if the terminal supports
// it. We make every effort to ensure that mouse release events are delivered.
// Hence, click drag can be identified by a motion event with the mouse down,
// without any intervening button release. On some terminals only the initiating
// press and terminating release event will be delivered.
//
// Mouse wheel events, when reported, may appear on their own as individual
// impulses; that is, there will normally not be a release event delivered
// for mouse wheel movements.
//
// Most terminals cannot report the state of more than one button at a time --
// and some cannot report motion events unless a button is pressed.
//
// Applications can inspect the time between events to resolve double or
// triple clicks.
type EventMouse struct {
t time.Time
btn ButtonMask
mod ModMask
x int
y int
}
// When returns the time when this EventMouse was created.
func (ev *EventMouse) When() time.Time {
return ev.t
}
// Buttons returns the list of buttons that were pressed or wheel motions.
func (ev *EventMouse) Buttons() ButtonMask {
return ev.btn
}
// Modifiers returns a list of keyboard modifiers that were pressed
// with the mouse button(s).
func (ev *EventMouse) Modifiers() ModMask {
return ev.mod
}
// Position returns the mouse position in character cells. The origin
// 0, 0 is at the upper left corner.
func (ev *EventMouse) Position() (int, int) {
return ev.x, ev.y
}
// NewEventMouse is used to create a new mouse event. Applications
// shouldn't need to use this; its mostly for screen implementors.
func NewEventMouse(x, y int, btn ButtonMask, mod ModMask) *EventMouse {
return &EventMouse{t: time.Now(), x: x, y: y, btn: btn, mod: mod}
}
// ButtonMask is a mask of mouse buttons and wheel events. Mouse button presses
// are normally delivered as both press and release events. Mouse wheel events
// are normally just single impulse events. Windows supports up to eight
// separate buttons plus all four wheel directions, but XTerm can only support
// mouse buttons 1-3 and wheel up/down. Its not unheard of for terminals
// to support only one or two buttons (think Macs). Old terminals, and true
// emulations (such as vt100) won't support mice at all, of course.
type ButtonMask int16
// These are the actual button values. Note that tcell version 1.x reversed buttons
// two and three on *nix based terminals. We use button 1 as the primary, and
// button 2 as the secondary, and button 3 (which is often missing) as the middle.
const (
Button1 ButtonMask = 1 << iota // Usually the left (primary) mouse button.
Button2 // Usually the right (secondary) mouse button.
Button3 // Usually the middle mouse button.
Button4 // Often a side button (thumb/next).
Button5 // Often a side button (thumb/prev).
Button6
Button7
Button8
WheelUp // Wheel motion up/away from user.
WheelDown // Wheel motion down/towards user.
WheelLeft // Wheel motion to left.
WheelRight // Wheel motion to right.
ButtonNone ButtonMask = 0 // No button or wheel events.
ButtonPrimary = Button1
ButtonSecondary = Button2
ButtonMiddle = Button3
)
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/charset_unix.go | vendor/github.com/gdamore/tcell/v2/charset_unix.go | //go:build !windows && !nacl && !plan9
// +build !windows,!nacl,!plan9
// Copyright 2016 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 tcell
import (
"os"
"strings"
)
func getCharset() string {
// Determine the character set. This can help us later.
// Per POSIX, we search for LC_ALL first, then LC_CTYPE, and
// finally LANG. First one set wins.
locale := ""
if locale = os.Getenv("LC_ALL"); locale == "" {
if locale = os.Getenv("LC_CTYPE"); locale == "" {
locale = os.Getenv("LANG")
}
}
if locale == "POSIX" || locale == "C" {
return "US-ASCII"
}
if i := strings.IndexRune(locale, '@'); i >= 0 {
locale = locale[:i]
}
if i := strings.IndexRune(locale, '.'); i >= 0 {
locale = locale[i+1:]
} else {
// Default assumption, and on Linux we can see LC_ALL
// without a character set, which we assume implies UTF-8.
return "UTF-8"
}
// XXX: add support for aliases
return locale
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/terms_dynamic.go | vendor/github.com/gdamore/tcell/v2/terms_dynamic.go | //go:build !tcell_minimal && !nacl && !js && !zos && !plan9 && !windows && !android
// +build !tcell_minimal,!nacl,!js,!zos,!plan9,!windows,!android
// Copyright 2019 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 tcell
import (
// This imports a dynamic version of the terminal database, which
// is built using infocmp. This relies on a working installation
// of infocmp (typically supplied with ncurses). We only do this
// for systems likely to have that -- i.e. UNIX based hosts. We
// also don't support Android here, because you really don't want
// to run external programs there. Generally the android terminals
// will be automatically included anyway.
"github.com/gdamore/tcell/v2/terminfo"
"github.com/gdamore/tcell/v2/terminfo/dynamic"
)
func loadDynamicTerminfo(term string) (*terminfo.Terminfo, error) {
ti, _, e := dynamic.LoadTerminfo(term)
if e != nil {
return nil, e
}
return ti, nil
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/interrupt.go | vendor/github.com/gdamore/tcell/v2/interrupt.go | // Copyright 2015 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 tcell
import (
"time"
)
// EventInterrupt is a generic wakeup event. Its can be used to
// to request a redraw. It can carry an arbitrary payload, as well.
type EventInterrupt struct {
t time.Time
v interface{}
}
// When returns the time when this event was created.
func (ev *EventInterrupt) When() time.Time {
return ev.t
}
// Data is used to obtain the opaque event payload.
func (ev *EventInterrupt) Data() interface{} {
return ev.v
}
// NewEventInterrupt creates an EventInterrupt with the given payload.
func NewEventInterrupt(data interface{}) *EventInterrupt {
return &EventInterrupt{t: time.Now(), v: data}
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/console_stub.go | vendor/github.com/gdamore/tcell/v2/console_stub.go | //go:build !windows
// +build !windows
// Copyright 2015 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 tcell
// NewConsoleScreen returns a console based screen. This platform
// doesn't have support for any, so it returns nil and a suitable error.
func NewConsoleScreen() (Screen, error) {
return nil, ErrNoScreen
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/paste.go | vendor/github.com/gdamore/tcell/v2/paste.go | // Copyright 2020 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 tcell
import (
"time"
)
// EventPaste is used to mark the start and end of a bracketed paste.
// An event with .Start() true will be sent to mark the start.
// Then a number of keys will be sent to indicate that the content
// is pasted in. At the end, an event with .Start() false will be sent.
type EventPaste struct {
start bool
t time.Time
}
// When returns the time when this EventPaste was created.
func (ev *EventPaste) When() time.Time {
return ev.t
}
// Start returns true if this is the start of a paste.
func (ev *EventPaste) Start() bool {
return ev.start
}
// End returns true if this is the end of a paste.
func (ev *EventPaste) End() bool {
return !ev.start
}
// NewEventPaste returns a new EventPaste.
func NewEventPaste(start bool) *EventPaste {
return &EventPaste{t: time.Now(), start: start}
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/screen.go | vendor/github.com/gdamore/tcell/v2/screen.go | // Copyright 2023 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 tcell
import "sync"
// Screen represents the physical (or emulated) screen.
// This can be a terminal window or a physical console. Platforms implement
// this differently.
type Screen interface {
// Init initializes the screen for use.
Init() error
// Fini finalizes the screen also releasing resources.
Fini()
// Clear logically erases the screen.
// This is effectively a short-cut for Fill(' ', StyleDefault).
Clear()
// Fill fills the screen with the given character and style.
// The effect of filling the screen is not visible until Show
// is called (or Sync).
Fill(rune, Style)
// SetCell is an older API, and will be removed. Please use
// SetContent instead; SetCell is implemented in terms of SetContent.
SetCell(x int, y int, style Style, ch ...rune)
// GetContent returns the contents at the given location. If the
// coordinates are out of range, then the values will be 0, nil,
// StyleDefault. Note that the contents returned are logical contents
// and may not actually be what is displayed, but rather are what will
// be displayed if Show() or Sync() is called. The width is the width
// in screen cells; most often this will be 1, but some East Asian
// characters and emoji require two cells.
GetContent(x, y int) (primary rune, combining []rune, style Style, width int)
// SetContent sets the contents of the given cell location. If
// the coordinates are out of range, then the operation is ignored.
//
// The first rune is the primary non-zero width rune. The array
// that follows is a possible list of combining characters to append,
// and will usually be nil (no combining characters.)
//
// The results are not displayed until Show() or Sync() is called.
//
// Note that wide (East Asian full width and emoji) runes occupy two cells,
// and attempts to place character at next cell to the right will have
// undefined effects. Wide runes that are printed in the
// last column will be replaced with a single width space on output.
SetContent(x int, y int, primary rune, combining []rune, style Style)
// SetStyle sets the default style to use when clearing the screen
// or when StyleDefault is specified. If it is also StyleDefault,
// then whatever system/terminal default is relevant will be used.
SetStyle(style Style)
// ShowCursor is used to display the cursor at a given location.
// If the coordinates -1, -1 are given or are otherwise outside the
// dimensions of the screen, the cursor will be hidden.
ShowCursor(x int, y int)
// HideCursor is used to hide the cursor. It's an alias for
// ShowCursor(-1, -1).sim
HideCursor()
// SetCursorStyle is used to set the cursor style. If the style
// is not supported (or cursor styles are not supported at all),
// then this will have no effect.
SetCursorStyle(CursorStyle)
// Size returns the screen size as width, height. This changes in
// response to a call to Clear or Flush.
Size() (width, height int)
// ChannelEvents is an infinite loop that waits for an event and
// channels it into the user provided channel ch. Closing the
// quit channel and calling the Fini method are cancellation
// signals. When a cancellation signal is received the method
// returns after closing ch.
//
// This method should be used as a goroutine.
//
// NOTE: PollEvent should not be called while this method is running.
ChannelEvents(ch chan<- Event, quit <-chan struct{})
// PollEvent waits for events to arrive. Main application loops
// must spin on this to prevent the application from stalling.
// Furthermore, this will return nil if the Screen is finalized.
PollEvent() Event
// HasPendingEvent returns true if PollEvent would return an event
// without blocking. If the screen is stopped and PollEvent would
// return nil, then the return value from this function is unspecified.
// The purpose of this function is to allow multiple events to be collected
// at once, to minimize screen redraws.
HasPendingEvent() bool
// PostEvent tries to post an event into the event stream. This
// can fail if the event queue is full. In that case, the event
// is dropped, and ErrEventQFull is returned.
PostEvent(ev Event) error
// Deprecated: PostEventWait is unsafe, and will be removed
// in the future.
//
// PostEventWait is like PostEvent, but if the queue is full, it
// blocks until there is space in the queue, making delivery
// reliable. However, it is VERY important that this function
// never be called from within whatever event loop is polling
// with PollEvent(), otherwise a deadlock may arise.
//
// For this reason, when using this function, the use of a
// Goroutine is recommended to ensure no deadlock can occur.
PostEventWait(ev Event)
// EnableMouse enables the mouse. (If your terminal supports it.)
// If no flags are specified, then all events are reported, if the
// terminal supports them.
EnableMouse(...MouseFlags)
// DisableMouse disables the mouse.
DisableMouse()
// EnablePaste enables bracketed paste mode, if supported.
EnablePaste()
// DisablePaste disables bracketed paste mode.
DisablePaste()
// EnableFocus enables reporting of focus events, if your terminal supports it.
EnableFocus()
// DisableFocus disables reporting of focus events.
DisableFocus()
// HasMouse returns true if the terminal (apparently) supports a
// mouse. Note that the return value of true doesn't guarantee that
// a mouse/pointing device is present; a false return definitely
// indicates no mouse support is available.
HasMouse() bool
// Colors returns the number of colors. All colors are assumed to
// use the ANSI color map. If a terminal is monochrome, it will
// return 0.
Colors() int
// Show makes all the content changes made using SetContent() visible
// on the display.
//
// It does so in the most efficient and least visually disruptive
// manner possible.
Show()
// Sync works like Show(), but it updates every visible cell on the
// physical display, assuming that it is not synchronized with any
// internal model. This may be both expensive and visually jarring,
// so it should only be used when believed to actually be necessary.
//
// Typically, this is called as a result of a user-requested redraw
// (e.g. to clear up on-screen corruption caused by some other program),
// or during a resize event.
Sync()
// CharacterSet returns information about the character set.
// This isn't the full locale, but it does give us the input/output
// character set. Note that this is just for diagnostic purposes,
// we normally translate input/output to/from UTF-8, regardless of
// what the user's environment is.
CharacterSet() string
// RegisterRuneFallback adds a fallback for runes that are not
// part of the character set -- for example one could register
// o as a fallback for ø. This should be done cautiously for
// characters that might be displayed ordinarily in language
// specific text -- characters that could change the meaning of
// written text would be dangerous. The intention here is to
// facilitate fallback characters in pseudo-graphical applications.
//
// If the terminal has fallbacks already in place via an alternate
// character set, those are used in preference. Also, standard
// fallbacks for graphical characters in the alternate character set
// terminfo string are registered implicitly.
//
// The display string should be the same width as original rune.
// This makes it possible to register two character replacements
// for full width East Asian characters, for example.
//
// It is recommended that replacement strings consist only of
// 7-bit ASCII, since other characters may not display everywhere.
RegisterRuneFallback(r rune, subst string)
// UnregisterRuneFallback unmaps a replacement. It will unmap
// the implicit ASCII replacements for alternate characters as well.
// When an unmapped char needs to be displayed, but no suitable
// glyph is available, '?' is emitted instead. It is not possible
// to "disable" the use of alternate characters that are supported
// by your terminal except by changing the terminal database.
UnregisterRuneFallback(r rune)
// CanDisplay returns true if the given rune can be displayed on
// this screen. Note that this is a best-guess effort -- whether
// your fonts support the character or not may be questionable.
// Mostly this is for folks who work outside of Unicode.
//
// If checkFallbacks is true, then if any (possibly imperfect)
// fallbacks are registered, this will return true. This will
// also return true if the terminal can replace the glyph with
// one that is visually indistinguishable from the one requested.
CanDisplay(r rune, checkFallbacks bool) bool
// Resize does nothing, since it's generally not possible to
// ask a screen to resize, but it allows the Screen to implement
// the View interface.
Resize(int, int, int, int)
// HasKey returns true if the keyboard is believed to have the
// key. In some cases a keyboard may have keys with this name
// but no support for them, while in others a key may be reported
// as supported but not actually be usable (such as some emulators
// that hijack certain keys). Its best not to depend to strictly
// on this function, but it can be used for hinting when building
// menus, displayed hot-keys, etc. Note that KeyRune (literal
// runes) is always true.
HasKey(Key) bool
// Suspend pauses input and output processing. It also restores the
// terminal settings to what they were when the application started.
// This can be used to, for example, run a sub-shell.
Suspend() error
// Resume resumes after Suspend().
Resume() error
// Beep attempts to sound an OS-dependent audible alert and returns an error
// when unsuccessful.
Beep() error
// SetSize attempts to resize the window. It also invalidates the cells and
// calls the resize function. Note that if the window size is changed, it will
// not be restored upon application exit.
//
// Many terminals cannot support this. Perversely, the "modern" Windows Terminal
// does not support application-initiated resizing, whereas the legacy terminal does.
// Also, some emulators can support this but may have it disabled by default.
SetSize(int, int)
// LockRegion sets or unsets a lock on a region of cells. A lock on a
// cell prevents the cell from being redrawn.
LockRegion(x, y, width, height int, lock bool)
// Tty returns the underlying Tty. If the screen is not a terminal, the
// returned bool will be false
Tty() (Tty, bool)
}
// NewScreen returns a default Screen suitable for the user's terminal
// environment.
func NewScreen() (Screen, error) {
// Windows is happier if we try for a console screen first.
if s, _ := NewConsoleScreen(); s != nil {
return s, nil
} else if s, e := NewTerminfoScreen(); s != nil {
return s, nil
} else {
return nil, e
}
}
// MouseFlags are options to modify the handling of mouse events.
// Actual events can be ORed together.
type MouseFlags int
const (
MouseButtonEvents = MouseFlags(1) // Click events only
MouseDragEvents = MouseFlags(2) // Click-drag events (includes button events)
MouseMotionEvents = MouseFlags(4) // All mouse events (includes click and drag events)
)
// CursorStyle represents a given cursor style, which can include the shape and
// whether the cursor blinks or is solid. Support for changing this is not universal.
type CursorStyle int
const (
CursorStyleDefault = CursorStyle(iota) // The default
CursorStyleBlinkingBlock
CursorStyleSteadyBlock
CursorStyleBlinkingUnderline
CursorStyleSteadyUnderline
CursorStyleBlinkingBar
CursorStyleSteadyBar
)
// screenImpl is a subset of Screen that can be used with baseScreen to formulate
// a complete implementation of Screen. See Screen for doc comments about methods.
type screenImpl interface {
Init() error
Fini()
SetStyle(style Style)
ShowCursor(x int, y int)
HideCursor()
SetCursorStyle(CursorStyle)
Size() (width, height int)
EnableMouse(...MouseFlags)
DisableMouse()
EnablePaste()
DisablePaste()
EnableFocus()
DisableFocus()
HasMouse() bool
Colors() int
Show()
Sync()
CharacterSet() string
RegisterRuneFallback(r rune, subst string)
UnregisterRuneFallback(r rune)
CanDisplay(r rune, checkFallbacks bool) bool
Resize(int, int, int, int)
HasKey(Key) bool
Suspend() error
Resume() error
Beep() error
SetSize(int, int)
Tty() (Tty, bool)
// Following methods are not part of the Screen api, but are used for interaction with
// the common layer code.
// Locker locks the underlying data structures so that we can access them
// in a thread-safe way.
sync.Locker
// GetCells returns a pointer to the underlying CellBuffer that the implementation uses.
// Various methods will write to these for performance, but will use the lock to do so.
GetCells() *CellBuffer
// StopQ is closed when the screen is shut down via Fini. It remains open if the screen
// is merely suspended.
StopQ() <-chan struct{}
// EventQ delivers events. Events are posted to this by the screen in response to
// key presses, resizes, etc. Application code receives events from this via the
// Screen.PollEvent, Screen.ChannelEvents APIs.
EventQ() chan Event
}
type baseScreen struct {
screenImpl
}
func (b *baseScreen) SetCell(x int, y int, style Style, ch ...rune) {
if len(ch) > 0 {
b.SetContent(x, y, ch[0], ch[1:], style)
} else {
b.SetContent(x, y, ' ', nil, style)
}
}
func (b *baseScreen) Clear() {
b.Fill(' ', StyleDefault)
}
func (b *baseScreen) Fill(r rune, style Style) {
cb := b.GetCells()
b.Lock()
cb.Fill(r, style)
b.Unlock()
}
func (b *baseScreen) SetContent(x, y int, mainc rune, combc []rune, st Style) {
cells := b.GetCells()
b.Lock()
cells.SetContent(x, y, mainc, combc, st)
b.Unlock()
}
func (b *baseScreen) GetContent(x, y int) (rune, []rune, Style, int) {
var primary rune
var combining []rune
var style Style
var width int
cells := b.GetCells()
b.Lock()
primary, combining, style, width = cells.GetContent(x, y)
b.Unlock()
return primary, combining, style, width
}
func (b *baseScreen) LockRegion(x, y, width, height int, lock bool) {
cells := b.GetCells()
b.Lock()
for j := y; j < (y + height); j += 1 {
for i := x; i < (x + width); i += 1 {
switch lock {
case true:
cells.LockCell(i, j)
case false:
cells.UnlockCell(i, j)
}
}
}
b.Unlock()
}
func (b *baseScreen) ChannelEvents(ch chan<- Event, quit <-chan struct{}) {
defer close(ch)
for {
select {
case <-quit:
return
case <-b.StopQ():
return
case ev := <-b.EventQ():
select {
case <-quit:
return
case <-b.StopQ():
return
case ch <- ev:
}
}
}
}
func (b *baseScreen) PollEvent() Event {
select {
case <-b.StopQ():
return nil
case ev := <-b.EventQ():
return ev
}
}
func (b *baseScreen) HasPendingEvent() bool {
return len(b.EventQ()) > 0
}
func (b *baseScreen) PostEventWait(ev Event) {
select {
case b.EventQ() <- ev:
case <-b.StopQ():
}
}
func (b *baseScreen) PostEvent(ev Event) error {
select {
case b.EventQ() <- ev:
return nil
default:
return ErrEventQFull
}
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/simulation.go | vendor/github.com/gdamore/tcell/v2/simulation.go | // Copyright 2023 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 tcell
import (
"sync"
"unicode/utf8"
"golang.org/x/text/transform"
)
// NewSimulationScreen returns a SimulationScreen. Note that
// SimulationScreen is also a Screen.
func NewSimulationScreen(charset string) SimulationScreen {
if charset == "" {
charset = "UTF-8"
}
ss := &simscreen{charset: charset}
ss.Screen = &baseScreen{screenImpl: ss}
return ss
}
// SimulationScreen represents a screen simulation. This is intended to
// be a superset of normal Screens, but also adds some important interfaces
// for testing.
type SimulationScreen interface {
Screen
// InjectKeyBytes injects a stream of bytes corresponding to
// the native encoding (see charset). It turns true if the entire
// set of bytes were processed and delivered as KeyEvents, false
// if any bytes were not fully understood. Any bytes that are not
// fully converted are discarded.
InjectKeyBytes(buf []byte) bool
// InjectKey injects a key event. The rune is a UTF-8 rune, post
// any translation.
InjectKey(key Key, r rune, mod ModMask)
// InjectMouse injects a mouse event.
InjectMouse(x, y int, buttons ButtonMask, mod ModMask)
// GetContents returns screen contents as an array of
// cells, along with the physical width & height. Note that the
// physical contents will be used until the next time SetSize()
// is called.
GetContents() (cells []SimCell, width int, height int)
// GetCursor returns the cursor details.
GetCursor() (x int, y int, visible bool)
}
// SimCell represents a simulated screen cell. The purpose of this
// is to track on screen content.
type SimCell struct {
// Bytes is the actual character bytes. Normally this is
// rune data, but it could be be data in another encoding system.
Bytes []byte
// Style is the style used to display the data.
Style Style
// Runes is the list of runes, unadulterated, in UTF-8.
Runes []rune
}
type simscreen struct {
physw int
physh int
fini bool
style Style
evch chan Event
quit chan struct{}
front []SimCell
back CellBuffer
clear bool
cursorx int
cursory int
cursorvis bool
mouse bool
paste bool
charset string
encoder transform.Transformer
decoder transform.Transformer
fillchar rune
fillstyle Style
fallback map[rune]string
Screen
sync.Mutex
}
func (s *simscreen) Init() error {
s.evch = make(chan Event, 10)
s.quit = make(chan struct{})
s.fillchar = 'X'
s.fillstyle = StyleDefault
s.mouse = false
s.physw = 80
s.physh = 25
s.cursorx = -1
s.cursory = -1
s.style = StyleDefault
if enc := GetEncoding(s.charset); enc != nil {
s.encoder = enc.NewEncoder()
s.decoder = enc.NewDecoder()
} else {
return ErrNoCharset
}
s.front = make([]SimCell, s.physw*s.physh)
s.back.Resize(80, 25)
// default fallbacks
s.fallback = make(map[rune]string)
for k, v := range RuneFallbacks {
s.fallback[k] = v
}
return nil
}
func (s *simscreen) Fini() {
s.Lock()
s.fini = true
s.back.Resize(0, 0)
s.Unlock()
if s.quit != nil {
close(s.quit)
}
s.physw = 0
s.physh = 0
s.front = nil
}
func (s *simscreen) SetStyle(style Style) {
s.Lock()
s.style = style
s.Unlock()
}
func (s *simscreen) drawCell(x, y int) int {
mainc, combc, style, width := s.back.GetContent(x, y)
if !s.back.Dirty(x, y) {
return width
}
if x >= s.physw || y >= s.physh || x < 0 || y < 0 {
return width
}
simc := &s.front[(y*s.physw)+x]
if style == StyleDefault {
style = s.style
}
simc.Style = style
simc.Runes = append([]rune{mainc}, combc...)
// now emit runes - taking care to not overrun width with a
// wide character, and to ensure that we emit exactly one regular
// character followed up by any residual combing characters
simc.Bytes = nil
if x > s.physw-width {
simc.Runes = []rune{' '}
simc.Bytes = []byte{' '}
return width
}
lbuf := make([]byte, 12)
ubuf := make([]byte, 12)
nout := 0
for _, r := range simc.Runes {
l := utf8.EncodeRune(ubuf, r)
nout, _, _ = s.encoder.Transform(lbuf, ubuf[:l], true)
if nout == 0 || lbuf[0] == '\x1a' {
// skip combining
if subst, ok := s.fallback[r]; ok {
simc.Bytes = append(simc.Bytes,
[]byte(subst)...)
} else if r >= ' ' && r <= '~' {
simc.Bytes = append(simc.Bytes, byte(r))
} else if simc.Bytes == nil {
simc.Bytes = append(simc.Bytes, '?')
}
} else {
simc.Bytes = append(simc.Bytes, lbuf[:nout]...)
}
}
s.back.SetDirty(x, y, false)
return width
}
func (s *simscreen) ShowCursor(x, y int) {
s.Lock()
s.cursorx, s.cursory = x, y
s.showCursor()
s.Unlock()
}
func (s *simscreen) HideCursor() {
s.ShowCursor(-1, -1)
}
func (s *simscreen) showCursor() {
x, y := s.cursorx, s.cursory
if x < 0 || y < 0 || x >= s.physw || y >= s.physh {
s.cursorvis = false
} else {
s.cursorvis = true
}
}
func (s *simscreen) hideCursor() {
// does not update cursor position
s.cursorvis = false
}
func (s *simscreen) SetCursorStyle(CursorStyle) {}
func (s *simscreen) Show() {
s.Lock()
s.resize()
s.draw()
s.Unlock()
}
func (s *simscreen) clearScreen() {
// We emulate a hardware clear by filling with a specific pattern
for i := range s.front {
s.front[i].Style = s.fillstyle
s.front[i].Runes = []rune{s.fillchar}
s.front[i].Bytes = []byte{byte(s.fillchar)}
}
s.clear = false
}
func (s *simscreen) draw() {
s.hideCursor()
if s.clear {
s.clearScreen()
}
w, h := s.back.Size()
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
width := s.drawCell(x, y)
x += width - 1
}
}
s.showCursor()
}
func (s *simscreen) EnableMouse(...MouseFlags) {
s.mouse = true
}
func (s *simscreen) DisableMouse() {
s.mouse = false
}
func (s *simscreen) EnablePaste() {
s.paste = true
}
func (s *simscreen) DisablePaste() {
s.paste = false
}
func (s *simscreen) EnableFocus() {
}
func (s *simscreen) DisableFocus() {
}
func (s *simscreen) Size() (int, int) {
s.Lock()
w, h := s.back.Size()
s.Unlock()
return w, h
}
func (s *simscreen) resize() {
w, h := s.physw, s.physh
ow, oh := s.back.Size()
if w != ow || h != oh {
s.back.Resize(w, h)
ev := NewEventResize(w, h)
s.postEvent(ev)
}
}
func (s *simscreen) Colors() int {
return 256
}
func (s *simscreen) postEvent(ev Event) {
select {
case s.evch <- ev:
case <-s.quit:
}
}
func (s *simscreen) InjectMouse(x, y int, buttons ButtonMask, mod ModMask) {
ev := NewEventMouse(x, y, buttons, mod)
s.postEvent(ev)
}
func (s *simscreen) InjectKey(key Key, r rune, mod ModMask) {
ev := NewEventKey(key, r, mod)
s.postEvent(ev)
}
func (s *simscreen) InjectKeyBytes(b []byte) bool {
failed := false
outer:
for len(b) > 0 {
if b[0] >= ' ' && b[0] <= 0x7F {
// printable ASCII easy to deal with -- no encodings
ev := NewEventKey(KeyRune, rune(b[0]), ModNone)
s.postEvent(ev)
b = b[1:]
continue
}
if b[0] < 0x80 {
mod := ModNone
// No encodings start with low numbered values
if Key(b[0]) >= KeyCtrlA && Key(b[0]) <= KeyCtrlZ {
mod = ModCtrl
}
ev := NewEventKey(Key(b[0]), 0, mod)
s.postEvent(ev)
b = b[1:]
continue
}
utfb := make([]byte, len(b)*4) // worst case
for l := 1; l < len(b); l++ {
s.decoder.Reset()
nout, nin, _ := s.decoder.Transform(utfb, b[:l], true)
if nout != 0 {
r, _ := utf8.DecodeRune(utfb[:nout])
if r != utf8.RuneError {
ev := NewEventKey(KeyRune, r, ModNone)
s.postEvent(ev)
}
b = b[nin:]
continue outer
}
}
failed = true
b = b[1:]
continue
}
return !failed
}
func (s *simscreen) Sync() {
s.Lock()
s.clear = true
s.resize()
s.back.Invalidate()
s.draw()
s.Unlock()
}
func (s *simscreen) CharacterSet() string {
return s.charset
}
func (s *simscreen) SetSize(w, h int) {
s.Lock()
newc := make([]SimCell, w*h)
for row := 0; row < h && row < s.physh; row++ {
for col := 0; col < w && col < s.physw; col++ {
newc[(row*w)+col] = s.front[(row*s.physw)+col]
}
}
s.cursorx, s.cursory = -1, -1
s.physw, s.physh = w, h
s.front = newc
s.back.Resize(w, h)
s.Unlock()
}
func (s *simscreen) GetContents() ([]SimCell, int, int) {
s.Lock()
cells, w, h := s.front, s.physw, s.physh
s.Unlock()
return cells, w, h
}
func (s *simscreen) GetCursor() (int, int, bool) {
s.Lock()
x, y, vis := s.cursorx, s.cursory, s.cursorvis
s.Unlock()
return x, y, vis
}
func (s *simscreen) RegisterRuneFallback(r rune, subst string) {
s.Lock()
s.fallback[r] = subst
s.Unlock()
}
func (s *simscreen) UnregisterRuneFallback(r rune) {
s.Lock()
delete(s.fallback, r)
s.Unlock()
}
func (s *simscreen) CanDisplay(r rune, checkFallbacks bool) bool {
if enc := s.encoder; enc != nil {
nb := make([]byte, 6)
ob := make([]byte, 6)
num := utf8.EncodeRune(ob, r)
enc.Reset()
dst, _, err := enc.Transform(nb, ob[:num], true)
if dst != 0 && err == nil && nb[0] != '\x1A' {
return true
}
}
if !checkFallbacks {
return false
}
if _, ok := s.fallback[r]; ok {
return true
}
return false
}
func (s *simscreen) HasMouse() bool {
return false
}
func (s *simscreen) Resize(int, int, int, int) {}
func (s *simscreen) HasKey(Key) bool {
return true
}
func (s *simscreen) Beep() error {
return nil
}
func (s *simscreen) Suspend() error {
return nil
}
func (s *simscreen) Resume() error {
return nil
}
func (s *simscreen) Tty() (Tty, bool) {
return nil, false
}
func (s *simscreen) GetCells() *CellBuffer {
return &s.back
}
func (s *simscreen) EventQ() chan Event {
return s.evch
}
func (s *simscreen) StopQ() <-chan struct{} {
return s.quit
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/errors.go | vendor/github.com/gdamore/tcell/v2/errors.go | // Copyright 2015 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 tcell
import (
"errors"
"time"
"github.com/gdamore/tcell/v2/terminfo"
)
var (
// ErrTermNotFound indicates that a suitable terminal entry could
// not be found. This can result from either not having TERM set,
// or from the TERM failing to support certain minimal functionality,
// in particular absolute cursor addressability (the cup capability)
// is required. For example, legacy "adm3" lacks this capability,
// whereas the slightly newer "adm3a" supports it. This failure
// occurs most often with "dumb".
ErrTermNotFound = terminfo.ErrTermNotFound
// ErrNoScreen indicates that no suitable screen could be found.
// This may result from attempting to run on a platform where there
// is no support for either termios or console I/O (such as nacl),
// or from running in an environment where there is no access to
// a suitable console/terminal device. (For example, running on
// without a controlling TTY or with no /dev/tty on POSIX platforms.)
ErrNoScreen = errors.New("no suitable screen available")
// ErrNoCharset indicates that the locale environment the
// program is not supported by the program, because no suitable
// encoding was found for it. This problem never occurs if
// the environment is UTF-8 or UTF-16.
ErrNoCharset = errors.New("character set not supported")
// ErrEventQFull indicates that the event queue is full, and
// cannot accept more events.
ErrEventQFull = errors.New("event queue full")
)
// An EventError is an event representing some sort of error, and carries
// an error payload.
type EventError struct {
t time.Time
err error
}
// When returns the time when the event was created.
func (ev *EventError) When() time.Time {
return ev.t
}
// Error implements the error.
func (ev *EventError) Error() string {
return ev.err.Error()
}
// NewEventError creates an ErrorEvent with the given error payload.
func NewEventError(err error) *EventError {
return &EventError{t: time.Now(), err: err}
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/tty.go | vendor/github.com/gdamore/tcell/v2/tty.go | // Copyright 2021 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 tcell
import "io"
// Tty is an abstraction of a tty (traditionally "teletype"). This allows applications to
// provide for alternate backends, as there are situations where the traditional /dev/tty
// does not work, or where more flexible handling is required. This interface is for use
// with the terminfo-style based API. It extends the io.ReadWriter API. It is reasonable
// that the implementation might choose to use different underlying files for the Reader
// and Writer sides of this API, as part of it's internal implementation.
type Tty interface {
// Start is used to activate the Tty for use. Upon return the terminal should be
// in raw mode, non-blocking, etc. The implementation should take care of saving
// any state that is required so that it may be restored when Stop is called.
Start() error
// Stop is used to stop using this Tty instance. This may be a suspend, so that other
// terminal based applications can run in the foreground. Implementations should
// restore any state collected at Start(), and return to ordinary blocking mode, etc.
// Drain is called first to drain the input. Once this is called, no more Read
// or Write calls will be made until Start is called again.
Stop() error
// Drain is called before Stop, and ensures that the reader will wake up appropriately
// if it was blocked. This workaround is required for /dev/tty on certain UNIX systems
// to ensure that Read() does not block forever. This typically arranges for the tty driver
// to send data immediately (e.g. VMIN and VTIME both set zero) and sets a deadline on input.
// Implementations may reasonably make this a no-op. There will still be control sequences
// emitted between the time this is called, and when Stop is called.
Drain() error
// NotifyResize is used register a callback when the tty thinks the dimensions have
// changed. The standard UNIX implementation links this to a handler for SIGWINCH.
// If the supplied callback is nil, then any handler should be unregistered.
NotifyResize(cb func())
// WindowSize is called to determine the terminal dimensions. This might be determined
// by an ioctl or other means.
WindowSize() (WindowSize, error)
io.ReadWriteCloser
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/stdin_unix.go | vendor/github.com/gdamore/tcell/v2/stdin_unix.go | // Copyright 2021 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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.
//go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos
// +build aix darwin dragonfly freebsd linux netbsd openbsd solaris zos
package tcell
import (
"errors"
"fmt"
"os"
"os/signal"
"strconv"
"sync"
"syscall"
"time"
"golang.org/x/sys/unix"
"golang.org/x/term"
)
// stdIoTty is an implementation of the Tty API based upon stdin/stdout.
type stdIoTty struct {
fd int
in *os.File
out *os.File
saved *term.State
sig chan os.Signal
cb func()
stopQ chan struct{}
dev string
wg sync.WaitGroup
l sync.Mutex
}
func (tty *stdIoTty) Read(b []byte) (int, error) {
return tty.in.Read(b)
}
func (tty *stdIoTty) Write(b []byte) (int, error) {
return tty.out.Write(b)
}
func (tty *stdIoTty) Close() error {
return nil
}
func (tty *stdIoTty) Start() error {
tty.l.Lock()
defer tty.l.Unlock()
// We open another copy of /dev/tty. This is a workaround for unusual behavior
// observed in macOS, apparently caused when a sub-shell (for example) closes our
// own tty device (when it exits for example). Getting a fresh new one seems to
// resolve the problem. (We believe this is a bug in the macOS tty driver that
// fails to account for dup() references to the same file before applying close()
// related behaviors to the tty.) We're also holding the original copy we opened
// since closing that might have deleterious effects as well. The upshot is that
// we will have up to two separate file handles open on /dev/tty. (Note that when
// using stdin/stdout instead of /dev/tty this problem is not observed.)
var err error
tty.in = os.Stdin
tty.out = os.Stdout
tty.fd = int(tty.in.Fd())
if !term.IsTerminal(tty.fd) {
return errors.New("device is not a terminal")
}
_ = tty.in.SetReadDeadline(time.Time{})
saved, err := term.MakeRaw(tty.fd) // also sets vMin and vTime
if err != nil {
return err
}
tty.saved = saved
tty.stopQ = make(chan struct{})
tty.wg.Add(1)
go func(stopQ chan struct{}) {
defer tty.wg.Done()
for {
select {
case <-tty.sig:
tty.l.Lock()
cb := tty.cb
tty.l.Unlock()
if cb != nil {
cb()
}
case <-stopQ:
return
}
}
}(tty.stopQ)
signal.Notify(tty.sig, syscall.SIGWINCH)
return nil
}
func (tty *stdIoTty) Drain() error {
_ = tty.in.SetReadDeadline(time.Now())
if err := tcSetBufParams(tty.fd, 0, 0); err != nil {
return err
}
return nil
}
func (tty *stdIoTty) Stop() error {
tty.l.Lock()
if err := term.Restore(tty.fd, tty.saved); err != nil {
tty.l.Unlock()
return err
}
_ = tty.in.SetReadDeadline(time.Now())
signal.Stop(tty.sig)
close(tty.stopQ)
tty.l.Unlock()
tty.wg.Wait()
return nil
}
func (tty *stdIoTty) WindowSize() (WindowSize, error) {
size := WindowSize{}
ws, err := unix.IoctlGetWinsize(tty.fd, unix.TIOCGWINSZ)
if err != nil {
return size, err
}
w := int(ws.Col)
h := int(ws.Row)
if w == 0 {
w, _ = strconv.Atoi(os.Getenv("COLUMNS"))
}
if w == 0 {
w = 80 // default
}
if h == 0 {
h, _ = strconv.Atoi(os.Getenv("LINES"))
}
if h == 0 {
h = 25 // default
}
size.Width = w
size.Height = h
size.PixelWidth = int(ws.Xpixel)
size.PixelHeight = int(ws.Ypixel)
return size, nil
}
func (tty *stdIoTty) NotifyResize(cb func()) {
tty.l.Lock()
tty.cb = cb
tty.l.Unlock()
}
// NewStdioTty opens a tty using standard input/output.
func NewStdIoTty() (Tty, error) {
tty := &stdIoTty{
sig: make(chan os.Signal),
in: os.Stdin,
out: os.Stdout,
}
var err error
tty.fd = int(tty.in.Fd())
if !term.IsTerminal(tty.fd) {
return nil, errors.New("not a terminal")
}
if tty.saved, err = term.GetState(tty.fd); err != nil {
return nil, fmt.Errorf("failed to get state: %w", err)
}
return tty, nil
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/nonblock_unix.go | vendor/github.com/gdamore/tcell/v2/nonblock_unix.go | // Copyright 2021 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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.
//go:build linux || aix || zos || solaris
// +build linux aix zos solaris
package tcell
import (
"syscall"
"golang.org/x/sys/unix"
)
// tcSetBufParams is used by the tty driver on UNIX systems to configure the
// buffering parameters (minimum character count and minimum wait time in msec.)
// This also waits for output to drain first.
func tcSetBufParams(fd int, vMin uint8, vTime uint8) error {
_ = syscall.SetNonblock(fd, true)
tio, err := unix.IoctlGetTermios(fd, unix.TCGETS)
if err != nil {
return err
}
tio.Cc[unix.VMIN] = vMin
tio.Cc[unix.VTIME] = vTime
if err = unix.IoctlSetTermios(fd, unix.TCSETSW, tio); err != nil {
return err
}
return nil
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/tscreen_stub.go | vendor/github.com/gdamore/tcell/v2/tscreen_stub.go | //go:build plan9 || windows
// +build plan9 windows
// Copyright 2022 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 tcell
// NB: We might someday wish to move Windows to this model. However,
// that would probably mean sacrificing some of the richer key reporting
// that we can obtain with the console API present on Windows.
func (t *tScreen) initialize() error {
if t.tty == nil {
return ErrNoScreen
}
// If a tty was supplied (custom), it should work.
// Custom screen implementations will need to provide a TTY
// implementation that we can use.
return nil
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/color.go | vendor/github.com/gdamore/tcell/v2/color.go | // Copyright 2023 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 tcell
import (
"fmt"
ic "image/color"
"strconv"
)
// Color represents a color. The low numeric values are the same as used
// by ECMA-48, and beyond that XTerm. A 24-bit RGB value may be used by
// adding in the ColorIsRGB flag. For Color names we use the W3C approved
// color names.
//
// We use a 64-bit integer to allow future expansion if we want to add an
// 8-bit alpha, while still leaving us some room for extra options.
//
// Note that on various terminals colors may be approximated however, or
// not supported at all. If no suitable representation for a color is known,
// the library will simply not set any color, deferring to whatever default
// attributes the terminal uses.
type Color uint64
const (
// ColorDefault is used to leave the Color unchanged from whatever
// system or terminal default may exist. It's also the zero value.
ColorDefault Color = 0
// ColorValid is used to indicate the color value is actually
// valid (initialized). This is useful to permit the zero value
// to be treated as the default.
ColorValid Color = 1 << 32
// ColorIsRGB is used to indicate that the numeric value is not
// a known color constant, but rather an RGB value. The lower
// order 3 bytes are RGB.
ColorIsRGB Color = 1 << 33
// ColorSpecial is a flag used to indicate that the values have
// special meaning, and live outside of the color space(s).
ColorSpecial Color = 1 << 34
)
// Note that the order of these options is important -- it follows the
// definitions used by ECMA and XTerm. Hence any further named colors
// must begin at a value not less than 256.
const (
ColorBlack = ColorValid + iota
ColorMaroon
ColorGreen
ColorOlive
ColorNavy
ColorPurple
ColorTeal
ColorSilver
ColorGray
ColorRed
ColorLime
ColorYellow
ColorBlue
ColorFuchsia
ColorAqua
ColorWhite
Color16
Color17
Color18
Color19
Color20
Color21
Color22
Color23
Color24
Color25
Color26
Color27
Color28
Color29
Color30
Color31
Color32
Color33
Color34
Color35
Color36
Color37
Color38
Color39
Color40
Color41
Color42
Color43
Color44
Color45
Color46
Color47
Color48
Color49
Color50
Color51
Color52
Color53
Color54
Color55
Color56
Color57
Color58
Color59
Color60
Color61
Color62
Color63
Color64
Color65
Color66
Color67
Color68
Color69
Color70
Color71
Color72
Color73
Color74
Color75
Color76
Color77
Color78
Color79
Color80
Color81
Color82
Color83
Color84
Color85
Color86
Color87
Color88
Color89
Color90
Color91
Color92
Color93
Color94
Color95
Color96
Color97
Color98
Color99
Color100
Color101
Color102
Color103
Color104
Color105
Color106
Color107
Color108
Color109
Color110
Color111
Color112
Color113
Color114
Color115
Color116
Color117
Color118
Color119
Color120
Color121
Color122
Color123
Color124
Color125
Color126
Color127
Color128
Color129
Color130
Color131
Color132
Color133
Color134
Color135
Color136
Color137
Color138
Color139
Color140
Color141
Color142
Color143
Color144
Color145
Color146
Color147
Color148
Color149
Color150
Color151
Color152
Color153
Color154
Color155
Color156
Color157
Color158
Color159
Color160
Color161
Color162
Color163
Color164
Color165
Color166
Color167
Color168
Color169
Color170
Color171
Color172
Color173
Color174
Color175
Color176
Color177
Color178
Color179
Color180
Color181
Color182
Color183
Color184
Color185
Color186
Color187
Color188
Color189
Color190
Color191
Color192
Color193
Color194
Color195
Color196
Color197
Color198
Color199
Color200
Color201
Color202
Color203
Color204
Color205
Color206
Color207
Color208
Color209
Color210
Color211
Color212
Color213
Color214
Color215
Color216
Color217
Color218
Color219
Color220
Color221
Color222
Color223
Color224
Color225
Color226
Color227
Color228
Color229
Color230
Color231
Color232
Color233
Color234
Color235
Color236
Color237
Color238
Color239
Color240
Color241
Color242
Color243
Color244
Color245
Color246
Color247
Color248
Color249
Color250
Color251
Color252
Color253
Color254
Color255
ColorAliceBlue
ColorAntiqueWhite
ColorAquaMarine
ColorAzure
ColorBeige
ColorBisque
ColorBlanchedAlmond
ColorBlueViolet
ColorBrown
ColorBurlyWood
ColorCadetBlue
ColorChartreuse
ColorChocolate
ColorCoral
ColorCornflowerBlue
ColorCornsilk
ColorCrimson
ColorDarkBlue
ColorDarkCyan
ColorDarkGoldenrod
ColorDarkGray
ColorDarkGreen
ColorDarkKhaki
ColorDarkMagenta
ColorDarkOliveGreen
ColorDarkOrange
ColorDarkOrchid
ColorDarkRed
ColorDarkSalmon
ColorDarkSeaGreen
ColorDarkSlateBlue
ColorDarkSlateGray
ColorDarkTurquoise
ColorDarkViolet
ColorDeepPink
ColorDeepSkyBlue
ColorDimGray
ColorDodgerBlue
ColorFireBrick
ColorFloralWhite
ColorForestGreen
ColorGainsboro
ColorGhostWhite
ColorGold
ColorGoldenrod
ColorGreenYellow
ColorHoneydew
ColorHotPink
ColorIndianRed
ColorIndigo
ColorIvory
ColorKhaki
ColorLavender
ColorLavenderBlush
ColorLawnGreen
ColorLemonChiffon
ColorLightBlue
ColorLightCoral
ColorLightCyan
ColorLightGoldenrodYellow
ColorLightGray
ColorLightGreen
ColorLightPink
ColorLightSalmon
ColorLightSeaGreen
ColorLightSkyBlue
ColorLightSlateGray
ColorLightSteelBlue
ColorLightYellow
ColorLimeGreen
ColorLinen
ColorMediumAquamarine
ColorMediumBlue
ColorMediumOrchid
ColorMediumPurple
ColorMediumSeaGreen
ColorMediumSlateBlue
ColorMediumSpringGreen
ColorMediumTurquoise
ColorMediumVioletRed
ColorMidnightBlue
ColorMintCream
ColorMistyRose
ColorMoccasin
ColorNavajoWhite
ColorOldLace
ColorOliveDrab
ColorOrange
ColorOrangeRed
ColorOrchid
ColorPaleGoldenrod
ColorPaleGreen
ColorPaleTurquoise
ColorPaleVioletRed
ColorPapayaWhip
ColorPeachPuff
ColorPeru
ColorPink
ColorPlum
ColorPowderBlue
ColorRebeccaPurple
ColorRosyBrown
ColorRoyalBlue
ColorSaddleBrown
ColorSalmon
ColorSandyBrown
ColorSeaGreen
ColorSeashell
ColorSienna
ColorSkyblue
ColorSlateBlue
ColorSlateGray
ColorSnow
ColorSpringGreen
ColorSteelBlue
ColorTan
ColorThistle
ColorTomato
ColorTurquoise
ColorViolet
ColorWheat
ColorWhiteSmoke
ColorYellowGreen
)
// These are aliases for the color gray, because some of us spell
// it as grey.
const (
ColorGrey = ColorGray
ColorDimGrey = ColorDimGray
ColorDarkGrey = ColorDarkGray
ColorDarkSlateGrey = ColorDarkSlateGray
ColorLightGrey = ColorLightGray
ColorLightSlateGrey = ColorLightSlateGray
ColorSlateGrey = ColorSlateGray
)
// ColorValues maps color constants to their RGB values.
var ColorValues = map[Color]int32{
ColorBlack: 0x000000,
ColorMaroon: 0x800000,
ColorGreen: 0x008000,
ColorOlive: 0x808000,
ColorNavy: 0x000080,
ColorPurple: 0x800080,
ColorTeal: 0x008080,
ColorSilver: 0xC0C0C0,
ColorGray: 0x808080,
ColorRed: 0xFF0000,
ColorLime: 0x00FF00,
ColorYellow: 0xFFFF00,
ColorBlue: 0x0000FF,
ColorFuchsia: 0xFF00FF,
ColorAqua: 0x00FFFF,
ColorWhite: 0xFFFFFF,
Color16: 0x000000, // black
Color17: 0x00005F,
Color18: 0x000087,
Color19: 0x0000AF,
Color20: 0x0000D7,
Color21: 0x0000FF, // blue
Color22: 0x005F00,
Color23: 0x005F5F,
Color24: 0x005F87,
Color25: 0x005FAF,
Color26: 0x005FD7,
Color27: 0x005FFF,
Color28: 0x008700,
Color29: 0x00875F,
Color30: 0x008787,
Color31: 0x0087Af,
Color32: 0x0087D7,
Color33: 0x0087FF,
Color34: 0x00AF00,
Color35: 0x00AF5F,
Color36: 0x00AF87,
Color37: 0x00AFAF,
Color38: 0x00AFD7,
Color39: 0x00AFFF,
Color40: 0x00D700,
Color41: 0x00D75F,
Color42: 0x00D787,
Color43: 0x00D7AF,
Color44: 0x00D7D7,
Color45: 0x00D7FF,
Color46: 0x00FF00, // lime
Color47: 0x00FF5F,
Color48: 0x00FF87,
Color49: 0x00FFAF,
Color50: 0x00FFd7,
Color51: 0x00FFFF, // aqua
Color52: 0x5F0000,
Color53: 0x5F005F,
Color54: 0x5F0087,
Color55: 0x5F00AF,
Color56: 0x5F00D7,
Color57: 0x5F00FF,
Color58: 0x5F5F00,
Color59: 0x5F5F5F,
Color60: 0x5F5F87,
Color61: 0x5F5FAF,
Color62: 0x5F5FD7,
Color63: 0x5F5FFF,
Color64: 0x5F8700,
Color65: 0x5F875F,
Color66: 0x5F8787,
Color67: 0x5F87AF,
Color68: 0x5F87D7,
Color69: 0x5F87FF,
Color70: 0x5FAF00,
Color71: 0x5FAF5F,
Color72: 0x5FAF87,
Color73: 0x5FAFAF,
Color74: 0x5FAFD7,
Color75: 0x5FAFFF,
Color76: 0x5FD700,
Color77: 0x5FD75F,
Color78: 0x5FD787,
Color79: 0x5FD7AF,
Color80: 0x5FD7D7,
Color81: 0x5FD7FF,
Color82: 0x5FFF00,
Color83: 0x5FFF5F,
Color84: 0x5FFF87,
Color85: 0x5FFFAF,
Color86: 0x5FFFD7,
Color87: 0x5FFFFF,
Color88: 0x870000,
Color89: 0x87005F,
Color90: 0x870087,
Color91: 0x8700AF,
Color92: 0x8700D7,
Color93: 0x8700FF,
Color94: 0x875F00,
Color95: 0x875F5F,
Color96: 0x875F87,
Color97: 0x875FAF,
Color98: 0x875FD7,
Color99: 0x875FFF,
Color100: 0x878700,
Color101: 0x87875F,
Color102: 0x878787,
Color103: 0x8787AF,
Color104: 0x8787D7,
Color105: 0x8787FF,
Color106: 0x87AF00,
Color107: 0x87AF5F,
Color108: 0x87AF87,
Color109: 0x87AFAF,
Color110: 0x87AFD7,
Color111: 0x87AFFF,
Color112: 0x87D700,
Color113: 0x87D75F,
Color114: 0x87D787,
Color115: 0x87D7AF,
Color116: 0x87D7D7,
Color117: 0x87D7FF,
Color118: 0x87FF00,
Color119: 0x87FF5F,
Color120: 0x87FF87,
Color121: 0x87FFAF,
Color122: 0x87FFD7,
Color123: 0x87FFFF,
Color124: 0xAF0000,
Color125: 0xAF005F,
Color126: 0xAF0087,
Color127: 0xAF00AF,
Color128: 0xAF00D7,
Color129: 0xAF00FF,
Color130: 0xAF5F00,
Color131: 0xAF5F5F,
Color132: 0xAF5F87,
Color133: 0xAF5FAF,
Color134: 0xAF5FD7,
Color135: 0xAF5FFF,
Color136: 0xAF8700,
Color137: 0xAF875F,
Color138: 0xAF8787,
Color139: 0xAF87AF,
Color140: 0xAF87D7,
Color141: 0xAF87FF,
Color142: 0xAFAF00,
Color143: 0xAFAF5F,
Color144: 0xAFAF87,
Color145: 0xAFAFAF,
Color146: 0xAFAFD7,
Color147: 0xAFAFFF,
Color148: 0xAFD700,
Color149: 0xAFD75F,
Color150: 0xAFD787,
Color151: 0xAFD7AF,
Color152: 0xAFD7D7,
Color153: 0xAFD7FF,
Color154: 0xAFFF00,
Color155: 0xAFFF5F,
Color156: 0xAFFF87,
Color157: 0xAFFFAF,
Color158: 0xAFFFD7,
Color159: 0xAFFFFF,
Color160: 0xD70000,
Color161: 0xD7005F,
Color162: 0xD70087,
Color163: 0xD700AF,
Color164: 0xD700D7,
Color165: 0xD700FF,
Color166: 0xD75F00,
Color167: 0xD75F5F,
Color168: 0xD75F87,
Color169: 0xD75FAF,
Color170: 0xD75FD7,
Color171: 0xD75FFF,
Color172: 0xD78700,
Color173: 0xD7875F,
Color174: 0xD78787,
Color175: 0xD787AF,
Color176: 0xD787D7,
Color177: 0xD787FF,
Color178: 0xD7AF00,
Color179: 0xD7AF5F,
Color180: 0xD7AF87,
Color181: 0xD7AFAF,
Color182: 0xD7AFD7,
Color183: 0xD7AFFF,
Color184: 0xD7D700,
Color185: 0xD7D75F,
Color186: 0xD7D787,
Color187: 0xD7D7AF,
Color188: 0xD7D7D7,
Color189: 0xD7D7FF,
Color190: 0xD7FF00,
Color191: 0xD7FF5F,
Color192: 0xD7FF87,
Color193: 0xD7FFAF,
Color194: 0xD7FFD7,
Color195: 0xD7FFFF,
Color196: 0xFF0000, // red
Color197: 0xFF005F,
Color198: 0xFF0087,
Color199: 0xFF00AF,
Color200: 0xFF00D7,
Color201: 0xFF00FF, // fuchsia
Color202: 0xFF5F00,
Color203: 0xFF5F5F,
Color204: 0xFF5F87,
Color205: 0xFF5FAF,
Color206: 0xFF5FD7,
Color207: 0xFF5FFF,
Color208: 0xFF8700,
Color209: 0xFF875F,
Color210: 0xFF8787,
Color211: 0xFF87AF,
Color212: 0xFF87D7,
Color213: 0xFF87FF,
Color214: 0xFFAF00,
Color215: 0xFFAF5F,
Color216: 0xFFAF87,
Color217: 0xFFAFAF,
Color218: 0xFFAFD7,
Color219: 0xFFAFFF,
Color220: 0xFFD700,
Color221: 0xFFD75F,
Color222: 0xFFD787,
Color223: 0xFFD7AF,
Color224: 0xFFD7D7,
Color225: 0xFFD7FF,
Color226: 0xFFFF00, // yellow
Color227: 0xFFFF5F,
Color228: 0xFFFF87,
Color229: 0xFFFFAF,
Color230: 0xFFFFD7,
Color231: 0xFFFFFF, // white
Color232: 0x080808,
Color233: 0x121212,
Color234: 0x1C1C1C,
Color235: 0x262626,
Color236: 0x303030,
Color237: 0x3A3A3A,
Color238: 0x444444,
Color239: 0x4E4E4E,
Color240: 0x585858,
Color241: 0x626262,
Color242: 0x6C6C6C,
Color243: 0x767676,
Color244: 0x808080, // grey
Color245: 0x8A8A8A,
Color246: 0x949494,
Color247: 0x9E9E9E,
Color248: 0xA8A8A8,
Color249: 0xB2B2B2,
Color250: 0xBCBCBC,
Color251: 0xC6C6C6,
Color252: 0xD0D0D0,
Color253: 0xDADADA,
Color254: 0xE4E4E4,
Color255: 0xEEEEEE,
ColorAliceBlue: 0xF0F8FF,
ColorAntiqueWhite: 0xFAEBD7,
ColorAquaMarine: 0x7FFFD4,
ColorAzure: 0xF0FFFF,
ColorBeige: 0xF5F5DC,
ColorBisque: 0xFFE4C4,
ColorBlanchedAlmond: 0xFFEBCD,
ColorBlueViolet: 0x8A2BE2,
ColorBrown: 0xA52A2A,
ColorBurlyWood: 0xDEB887,
ColorCadetBlue: 0x5F9EA0,
ColorChartreuse: 0x7FFF00,
ColorChocolate: 0xD2691E,
ColorCoral: 0xFF7F50,
ColorCornflowerBlue: 0x6495ED,
ColorCornsilk: 0xFFF8DC,
ColorCrimson: 0xDC143C,
ColorDarkBlue: 0x00008B,
ColorDarkCyan: 0x008B8B,
ColorDarkGoldenrod: 0xB8860B,
ColorDarkGray: 0xA9A9A9,
ColorDarkGreen: 0x006400,
ColorDarkKhaki: 0xBDB76B,
ColorDarkMagenta: 0x8B008B,
ColorDarkOliveGreen: 0x556B2F,
ColorDarkOrange: 0xFF8C00,
ColorDarkOrchid: 0x9932CC,
ColorDarkRed: 0x8B0000,
ColorDarkSalmon: 0xE9967A,
ColorDarkSeaGreen: 0x8FBC8F,
ColorDarkSlateBlue: 0x483D8B,
ColorDarkSlateGray: 0x2F4F4F,
ColorDarkTurquoise: 0x00CED1,
ColorDarkViolet: 0x9400D3,
ColorDeepPink: 0xFF1493,
ColorDeepSkyBlue: 0x00BFFF,
ColorDimGray: 0x696969,
ColorDodgerBlue: 0x1E90FF,
ColorFireBrick: 0xB22222,
ColorFloralWhite: 0xFFFAF0,
ColorForestGreen: 0x228B22,
ColorGainsboro: 0xDCDCDC,
ColorGhostWhite: 0xF8F8FF,
ColorGold: 0xFFD700,
ColorGoldenrod: 0xDAA520,
ColorGreenYellow: 0xADFF2F,
ColorHoneydew: 0xF0FFF0,
ColorHotPink: 0xFF69B4,
ColorIndianRed: 0xCD5C5C,
ColorIndigo: 0x4B0082,
ColorIvory: 0xFFFFF0,
ColorKhaki: 0xF0E68C,
ColorLavender: 0xE6E6FA,
ColorLavenderBlush: 0xFFF0F5,
ColorLawnGreen: 0x7CFC00,
ColorLemonChiffon: 0xFFFACD,
ColorLightBlue: 0xADD8E6,
ColorLightCoral: 0xF08080,
ColorLightCyan: 0xE0FFFF,
ColorLightGoldenrodYellow: 0xFAFAD2,
ColorLightGray: 0xD3D3D3,
ColorLightGreen: 0x90EE90,
ColorLightPink: 0xFFB6C1,
ColorLightSalmon: 0xFFA07A,
ColorLightSeaGreen: 0x20B2AA,
ColorLightSkyBlue: 0x87CEFA,
ColorLightSlateGray: 0x778899,
ColorLightSteelBlue: 0xB0C4DE,
ColorLightYellow: 0xFFFFE0,
ColorLimeGreen: 0x32CD32,
ColorLinen: 0xFAF0E6,
ColorMediumAquamarine: 0x66CDAA,
ColorMediumBlue: 0x0000CD,
ColorMediumOrchid: 0xBA55D3,
ColorMediumPurple: 0x9370DB,
ColorMediumSeaGreen: 0x3CB371,
ColorMediumSlateBlue: 0x7B68EE,
ColorMediumSpringGreen: 0x00FA9A,
ColorMediumTurquoise: 0x48D1CC,
ColorMediumVioletRed: 0xC71585,
ColorMidnightBlue: 0x191970,
ColorMintCream: 0xF5FFFA,
ColorMistyRose: 0xFFE4E1,
ColorMoccasin: 0xFFE4B5,
ColorNavajoWhite: 0xFFDEAD,
ColorOldLace: 0xFDF5E6,
ColorOliveDrab: 0x6B8E23,
ColorOrange: 0xFFA500,
ColorOrangeRed: 0xFF4500,
ColorOrchid: 0xDA70D6,
ColorPaleGoldenrod: 0xEEE8AA,
ColorPaleGreen: 0x98FB98,
ColorPaleTurquoise: 0xAFEEEE,
ColorPaleVioletRed: 0xDB7093,
ColorPapayaWhip: 0xFFEFD5,
ColorPeachPuff: 0xFFDAB9,
ColorPeru: 0xCD853F,
ColorPink: 0xFFC0CB,
ColorPlum: 0xDDA0DD,
ColorPowderBlue: 0xB0E0E6,
ColorRebeccaPurple: 0x663399,
ColorRosyBrown: 0xBC8F8F,
ColorRoyalBlue: 0x4169E1,
ColorSaddleBrown: 0x8B4513,
ColorSalmon: 0xFA8072,
ColorSandyBrown: 0xF4A460,
ColorSeaGreen: 0x2E8B57,
ColorSeashell: 0xFFF5EE,
ColorSienna: 0xA0522D,
ColorSkyblue: 0x87CEEB,
ColorSlateBlue: 0x6A5ACD,
ColorSlateGray: 0x708090,
ColorSnow: 0xFFFAFA,
ColorSpringGreen: 0x00FF7F,
ColorSteelBlue: 0x4682B4,
ColorTan: 0xD2B48C,
ColorThistle: 0xD8BFD8,
ColorTomato: 0xFF6347,
ColorTurquoise: 0x40E0D0,
ColorViolet: 0xEE82EE,
ColorWheat: 0xF5DEB3,
ColorWhiteSmoke: 0xF5F5F5,
ColorYellowGreen: 0x9ACD32,
}
// Special colors.
const (
// ColorReset is used to indicate that the color should use the
// vanilla terminal colors. (Basically go back to the defaults.)
ColorReset = ColorSpecial | iota
// ColorNone indicates that we should not change the color from
// whatever is already displayed. This can only be used in limited
// circumstances.
ColorNone
)
// ColorNames holds the written names of colors. Useful to present a list of
// recognized named colors.
var ColorNames = map[string]Color{
"black": ColorBlack,
"maroon": ColorMaroon,
"green": ColorGreen,
"olive": ColorOlive,
"navy": ColorNavy,
"purple": ColorPurple,
"teal": ColorTeal,
"silver": ColorSilver,
"gray": ColorGray,
"red": ColorRed,
"lime": ColorLime,
"yellow": ColorYellow,
"blue": ColorBlue,
"fuchsia": ColorFuchsia,
"aqua": ColorAqua,
"white": ColorWhite,
"aliceblue": ColorAliceBlue,
"antiquewhite": ColorAntiqueWhite,
"aquamarine": ColorAquaMarine,
"azure": ColorAzure,
"beige": ColorBeige,
"bisque": ColorBisque,
"blanchedalmond": ColorBlanchedAlmond,
"blueviolet": ColorBlueViolet,
"brown": ColorBrown,
"burlywood": ColorBurlyWood,
"cadetblue": ColorCadetBlue,
"chartreuse": ColorChartreuse,
"chocolate": ColorChocolate,
"coral": ColorCoral,
"cornflowerblue": ColorCornflowerBlue,
"cornsilk": ColorCornsilk,
"crimson": ColorCrimson,
"darkblue": ColorDarkBlue,
"darkcyan": ColorDarkCyan,
"darkgoldenrod": ColorDarkGoldenrod,
"darkgray": ColorDarkGray,
"darkgreen": ColorDarkGreen,
"darkkhaki": ColorDarkKhaki,
"darkmagenta": ColorDarkMagenta,
"darkolivegreen": ColorDarkOliveGreen,
"darkorange": ColorDarkOrange,
"darkorchid": ColorDarkOrchid,
"darkred": ColorDarkRed,
"darksalmon": ColorDarkSalmon,
"darkseagreen": ColorDarkSeaGreen,
"darkslateblue": ColorDarkSlateBlue,
"darkslategray": ColorDarkSlateGray,
"darkturquoise": ColorDarkTurquoise,
"darkviolet": ColorDarkViolet,
"deeppink": ColorDeepPink,
"deepskyblue": ColorDeepSkyBlue,
"dimgray": ColorDimGray,
"dodgerblue": ColorDodgerBlue,
"firebrick": ColorFireBrick,
"floralwhite": ColorFloralWhite,
"forestgreen": ColorForestGreen,
"gainsboro": ColorGainsboro,
"ghostwhite": ColorGhostWhite,
"gold": ColorGold,
"goldenrod": ColorGoldenrod,
"greenyellow": ColorGreenYellow,
"honeydew": ColorHoneydew,
"hotpink": ColorHotPink,
"indianred": ColorIndianRed,
"indigo": ColorIndigo,
"ivory": ColorIvory,
"khaki": ColorKhaki,
"lavender": ColorLavender,
"lavenderblush": ColorLavenderBlush,
"lawngreen": ColorLawnGreen,
"lemonchiffon": ColorLemonChiffon,
"lightblue": ColorLightBlue,
"lightcoral": ColorLightCoral,
"lightcyan": ColorLightCyan,
"lightgoldenrodyellow": ColorLightGoldenrodYellow,
"lightgray": ColorLightGray,
"lightgreen": ColorLightGreen,
"lightpink": ColorLightPink,
"lightsalmon": ColorLightSalmon,
"lightseagreen": ColorLightSeaGreen,
"lightskyblue": ColorLightSkyBlue,
"lightslategray": ColorLightSlateGray,
"lightsteelblue": ColorLightSteelBlue,
"lightyellow": ColorLightYellow,
"limegreen": ColorLimeGreen,
"linen": ColorLinen,
"mediumaquamarine": ColorMediumAquamarine,
"mediumblue": ColorMediumBlue,
"mediumorchid": ColorMediumOrchid,
"mediumpurple": ColorMediumPurple,
"mediumseagreen": ColorMediumSeaGreen,
"mediumslateblue": ColorMediumSlateBlue,
"mediumspringgreen": ColorMediumSpringGreen,
"mediumturquoise": ColorMediumTurquoise,
"mediumvioletred": ColorMediumVioletRed,
"midnightblue": ColorMidnightBlue,
"mintcream": ColorMintCream,
"mistyrose": ColorMistyRose,
"moccasin": ColorMoccasin,
"navajowhite": ColorNavajoWhite,
"oldlace": ColorOldLace,
"olivedrab": ColorOliveDrab,
"orange": ColorOrange,
"orangered": ColorOrangeRed,
"orchid": ColorOrchid,
"palegoldenrod": ColorPaleGoldenrod,
"palegreen": ColorPaleGreen,
"paleturquoise": ColorPaleTurquoise,
"palevioletred": ColorPaleVioletRed,
"papayawhip": ColorPapayaWhip,
"peachpuff": ColorPeachPuff,
"peru": ColorPeru,
"pink": ColorPink,
"plum": ColorPlum,
"powderblue": ColorPowderBlue,
"rebeccapurple": ColorRebeccaPurple,
"rosybrown": ColorRosyBrown,
"royalblue": ColorRoyalBlue,
"saddlebrown": ColorSaddleBrown,
"salmon": ColorSalmon,
"sandybrown": ColorSandyBrown,
"seagreen": ColorSeaGreen,
"seashell": ColorSeashell,
"sienna": ColorSienna,
"skyblue": ColorSkyblue,
"slateblue": ColorSlateBlue,
"slategray": ColorSlateGray,
"snow": ColorSnow,
"springgreen": ColorSpringGreen,
"steelblue": ColorSteelBlue,
"tan": ColorTan,
"thistle": ColorThistle,
"tomato": ColorTomato,
"turquoise": ColorTurquoise,
"violet": ColorViolet,
"wheat": ColorWheat,
"whitesmoke": ColorWhiteSmoke,
"yellowgreen": ColorYellowGreen,
"grey": ColorGray,
"dimgrey": ColorDimGray,
"darkgrey": ColorDarkGray,
"darkslategrey": ColorDarkSlateGray,
"lightgrey": ColorLightGray,
"lightslategrey": ColorLightSlateGray,
"slategrey": ColorSlateGray,
}
// Valid indicates the color is a valid value (has been set).
func (c Color) Valid() bool {
return c&ColorValid != 0
}
// IsRGB is true if the color is an RGB specific value.
func (c Color) IsRGB() bool {
return c&(ColorValid|ColorIsRGB) == (ColorValid | ColorIsRGB)
}
// CSS returns the CSS hex string ( #ABCDEF ) if valid
// if not a valid color returns empty string
func (c Color) CSS() string {
if !c.Valid() {
return ""
}
return fmt.Sprintf("#%06X", c.Hex())
}
// String implements fmt.Stringer to return either the
// W3C name if it has one or the CSS hex string '#ABCDEF'
func (c Color) String() string {
if !c.Valid() {
switch c {
case ColorNone:
return "none"
case ColorDefault:
return "default"
case ColorReset:
return "reset"
}
return ""
}
return c.Name(true)
}
// Name returns W3C name or an empty string if no arguments
// if passed true as an argument it will falls back to
// the CSS hex string if no W3C name found '#ABCDEF'
func (c Color) Name(css ...bool) string {
for name, hex := range ColorNames {
if c == hex {
return name
}
}
if len(css) > 0 && css[0] {
return c.CSS()
}
return ""
}
// Hex returns the color's hexadecimal RGB 24-bit value with each component
// consisting of a single byte, R << 16 | G << 8 | B. If the color
// is unknown or unset, -1 is returned.
func (c Color) Hex() int32 {
if !c.Valid() {
return -1
}
if c&ColorIsRGB != 0 {
return int32(c & 0xffffff)
}
if v, ok := ColorValues[c]; ok {
return v
}
return -1
}
// RGB returns the red, green, and blue components of the color, with
// each component represented as a value 0-255. In the event that the
// color cannot be broken up (not set usually), -1 is returned for each value.
func (c Color) RGB() (int32, int32, int32) {
v := c.Hex()
if v < 0 {
return -1, -1, -1
}
return (v >> 16) & 0xff, (v >> 8) & 0xff, v & 0xff
}
// TrueColor returns the true color (RGB) version of the provided color.
// This is useful for ensuring color accuracy when using named colors.
// This will override terminal theme colors.
func (c Color) TrueColor() Color {
if !c.Valid() {
return ColorDefault
}
if c&ColorIsRGB != 0 {
return c | ColorValid
}
return Color(c.Hex()) | ColorIsRGB | ColorValid
}
// NewRGBColor returns a new color with the given red, green, and blue values.
// Each value must be represented in the range 0-255.
func NewRGBColor(r, g, b int32) Color {
return NewHexColor(((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff))
}
// NewHexColor returns a color using the given 24-bit RGB value.
func NewHexColor(v int32) Color {
return ColorIsRGB | Color(v) | ColorValid
}
// GetColor creates a Color from a color name (W3C name). A hex value may
// be supplied as a string in the format "#ffffff".
func GetColor(name string) Color {
if c, ok := ColorNames[name]; ok {
return c
}
if len(name) == 7 && name[0] == '#' {
if v, e := strconv.ParseInt(name[1:], 16, 32); e == nil {
return NewHexColor(int32(v))
}
}
return ColorDefault
}
// PaletteColor creates a color based on the palette index.
func PaletteColor(index int) Color {
return Color(index) | ColorValid
}
// FromImageColor converts an image/color.Color into tcell.Color.
// The alpha value is dropped, so it should be tracked separately if it is
// needed.
func FromImageColor(imageColor ic.Color) Color {
r, g, b, _ := imageColor.RGBA()
// NOTE image/color.Color RGB values range is [0, 0xFFFF] as uint32
return NewRGBColor(int32(r>>8), int32(g>>8), int32(b>>8))
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/wscreen.go | vendor/github.com/gdamore/tcell/v2/wscreen.go | // Copyright 2023 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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.
//go:build js && wasm
// +build js,wasm
package tcell
import (
"errors"
"github.com/gdamore/tcell/v2/terminfo"
"strings"
"sync"
"syscall/js"
"unicode/utf8"
)
func NewTerminfoScreen() (Screen, error) {
t := &wScreen{}
t.fallback = make(map[rune]string)
return &baseScreen{screenImpl: t}, nil
}
type wScreen struct {
w, h int
style Style
cells CellBuffer
running bool
clear bool
flagsPresent bool
pasteEnabled bool
mouseFlags MouseFlags
cursorStyle CursorStyle
quit chan struct{}
evch chan Event
fallback map[rune]string
finiOnce sync.Once
sync.Mutex
}
func (t *wScreen) Init() error {
t.w, t.h = 80, 24 // default for html as of now
t.evch = make(chan Event, 10)
t.quit = make(chan struct{})
t.Lock()
t.running = true
t.style = StyleDefault
t.cells.Resize(t.w, t.h)
t.Unlock()
js.Global().Set("onKeyEvent", js.FuncOf(t.onKeyEvent))
return nil
}
func (t *wScreen) Fini() {
t.finiOnce.Do(func() {
close(t.quit)
})
}
func (t *wScreen) SetStyle(style Style) {
t.Lock()
t.style = style
t.Unlock()
}
// paletteColor gives a more natural palette color actually matching
// typical XTerm. We might in the future want to permit styling these
// via CSS.
var palette = map[Color]int32{
ColorBlack: 0x000000,
ColorMaroon: 0xcd0000,
ColorGreen: 0x00cd00,
ColorOlive: 0xcdcd00,
ColorNavy: 0x0000ee,
ColorPurple: 0xcd00cd,
ColorTeal: 0x00cdcd,
ColorSilver: 0xe5e5e5,
ColorGray: 0x7f7f7f,
ColorRed: 0xff0000,
ColorLime: 0x00ff00,
ColorYellow: 0xffff00,
ColorBlue: 0x5c5cff,
ColorFuchsia: 0xff00ff,
ColorAqua: 0x00ffff,
ColorWhite: 0xffffff,
}
func paletteColor(c Color) int32 {
if c.IsRGB() {
return int32(c & 0xffffff)
}
if c >= ColorBlack && c <= ColorWhite {
return palette[c]
}
return c.Hex()
}
func (t *wScreen) drawCell(x, y int) int {
mainc, combc, style, width := t.cells.GetContent(x, y)
if !t.cells.Dirty(x, y) {
return width
}
if style == StyleDefault {
style = t.style
}
fg, bg := paletteColor(style.fg), paletteColor(style.bg)
if fg == -1 {
fg = 0xe5e5e5
}
if bg == -1 {
bg = 0x000000
}
var combcarr []interface{} = make([]interface{}, len(combc))
for i, c := range combc {
combcarr[i] = c
}
t.cells.SetDirty(x, y, false)
js.Global().Call("drawCell", x, y, mainc, combcarr, fg, bg, int(style.attrs))
return width
}
func (t *wScreen) ShowCursor(x, y int) {
t.Lock()
js.Global().Call("showCursor", x, y)
t.Unlock()
}
func (t *wScreen) SetCursorStyle(cs CursorStyle) {
t.Lock()
js.Global().Call("setCursorStyle", curStyleClasses[cs])
t.Unlock()
}
func (t *wScreen) HideCursor() {
t.ShowCursor(-1, -1)
}
func (t *wScreen) Show() {
t.Lock()
t.resize()
t.draw()
t.Unlock()
}
func (t *wScreen) clearScreen() {
js.Global().Call("clearScreen", t.style.fg.Hex(), t.style.bg.Hex())
t.clear = false
}
func (t *wScreen) draw() {
if t.clear {
t.clearScreen()
}
for y := 0; y < t.h; y++ {
for x := 0; x < t.w; x++ {
width := t.drawCell(x, y)
x += width - 1
}
}
js.Global().Call("show")
}
func (t *wScreen) EnableMouse(flags ...MouseFlags) {
var f MouseFlags
flagsPresent := false
for _, flag := range flags {
f |= flag
flagsPresent = true
}
if !flagsPresent {
f = MouseMotionEvents | MouseDragEvents | MouseButtonEvents
}
t.Lock()
t.mouseFlags = f
t.enableMouse(f)
t.Unlock()
}
func (t *wScreen) enableMouse(f MouseFlags) {
if f&MouseButtonEvents != 0 {
js.Global().Set("onMouseClick", js.FuncOf(t.onMouseEvent))
} else {
js.Global().Set("onMouseClick", js.FuncOf(t.unset))
}
if f&MouseDragEvents != 0 || f&MouseMotionEvents != 0 {
js.Global().Set("onMouseMove", js.FuncOf(t.onMouseEvent))
} else {
js.Global().Set("onMouseMove", js.FuncOf(t.unset))
}
}
func (t *wScreen) DisableMouse() {
t.Lock()
t.mouseFlags = 0
t.enableMouse(0)
t.Unlock()
}
func (t *wScreen) EnablePaste() {
t.Lock()
t.pasteEnabled = true
t.enablePasting(true)
t.Unlock()
}
func (t *wScreen) DisablePaste() {
t.Lock()
t.pasteEnabled = false
t.enablePasting(false)
t.Unlock()
}
func (t *wScreen) enablePasting(on bool) {
if on {
js.Global().Set("onPaste", js.FuncOf(t.onPaste))
} else {
js.Global().Set("onPaste", js.FuncOf(t.unset))
}
}
func (t *wScreen) EnableFocus() {
t.Lock()
js.Global().Set("onFocus", js.FuncOf(t.onFocus))
t.Unlock()
}
func (t *wScreen) DisableFocus() {
t.Lock()
js.Global().Set("onFocus", js.FuncOf(t.unset))
t.Unlock()
}
func (t *wScreen) Size() (int, int) {
t.Lock()
w, h := t.w, t.h
t.Unlock()
return w, h
}
// resize does nothing, as asking the web window to resize
// without a specified width or height will cause no change.
func (t *wScreen) resize() {}
func (t *wScreen) Colors() int {
return 16777216 // 256 ^ 3
}
func (t *wScreen) clip(x, y int) (int, int) {
w, h := t.cells.Size()
if x < 0 {
x = 0
}
if y < 0 {
y = 0
}
if x > w-1 {
x = w - 1
}
if y > h-1 {
y = h - 1
}
return x, y
}
func (t *wScreen) postEvent(ev Event) {
select {
case t.evch <- ev:
case <-t.quit:
}
}
func (t *wScreen) onMouseEvent(this js.Value, args []js.Value) interface{} {
mod := ModNone
button := ButtonNone
switch args[2].Int() {
case 0:
if t.mouseFlags&MouseMotionEvents == 0 {
// don't want this event! is a mouse motion event, but user has asked not.
return nil
}
button = ButtonNone
case 1:
button = Button1
case 2:
button = Button3 // Note we prefer to treat right as button 2
case 3:
button = Button2 // And the middle button as button 3
}
if args[3].Bool() { // mod shift
mod |= ModShift
}
if args[4].Bool() { // mod alt
mod |= ModAlt
}
if args[5].Bool() { // mod ctrl
mod |= ModCtrl
}
t.postEvent(NewEventMouse(args[0].Int(), args[1].Int(), button, mod))
return nil
}
func (t *wScreen) onKeyEvent(this js.Value, args []js.Value) interface{} {
key := args[0].String()
// don't accept any modifier keys as their own
if key == "Control" || key == "Alt" || key == "Meta" || key == "Shift" {
return nil
}
mod := ModNone
if args[1].Bool() { // mod shift
mod |= ModShift
}
if args[2].Bool() { // mod alt
mod |= ModAlt
}
if args[3].Bool() { // mod ctrl
mod |= ModCtrl
}
if args[4].Bool() { // mod meta
mod |= ModMeta
}
// check for special case of Ctrl + key
if mod == ModCtrl {
if k, ok := WebKeyNames["Ctrl-"+strings.ToLower(key)]; ok {
t.postEvent(NewEventKey(k, 0, mod))
return nil
}
}
// next try function keys
if k, ok := WebKeyNames[key]; ok {
t.postEvent(NewEventKey(k, 0, mod))
return nil
}
// finally try normal, printable chars
r, _ := utf8.DecodeRuneInString(key)
t.postEvent(NewEventKey(KeyRune, r, mod))
return nil
}
func (t *wScreen) onPaste(this js.Value, args []js.Value) interface{} {
t.postEvent(NewEventPaste(args[0].Bool()))
return nil
}
func (t *wScreen) onFocus(this js.Value, args []js.Value) interface{} {
t.postEvent(NewEventFocus(args[0].Bool()))
return nil
}
// unset is a dummy function for js when we want nothing to
// happen when javascript calls a function (for example, when
// mouse input is disabled, when onMouseEvent() is called from
// js, it redirects here and does nothing).
func (t *wScreen) unset(this js.Value, args []js.Value) interface{} {
return nil
}
func (t *wScreen) Sync() {
t.Lock()
t.resize()
t.clear = true
t.cells.Invalidate()
t.draw()
t.Unlock()
}
func (t *wScreen) CharacterSet() string {
return "UTF-8"
}
func (t *wScreen) RegisterRuneFallback(orig rune, fallback string) {
t.Lock()
t.fallback[orig] = fallback
t.Unlock()
}
func (t *wScreen) UnregisterRuneFallback(orig rune) {
t.Lock()
delete(t.fallback, orig)
t.Unlock()
}
func (t *wScreen) CanDisplay(r rune, checkFallbacks bool) bool {
if utf8.ValidRune(r) {
return true
}
if !checkFallbacks {
return false
}
if _, ok := t.fallback[r]; ok {
return true
}
return false
}
func (t *wScreen) HasMouse() bool {
return true
}
func (t *wScreen) HasKey(k Key) bool {
return true
}
func (t *wScreen) SetSize(w, h int) {
if w == t.w && h == t.h {
return
}
t.cells.Invalidate()
t.cells.Resize(w, h)
js.Global().Call("resize", w, h)
t.w, t.h = w, h
t.postEvent(NewEventResize(w, h))
}
func (t *wScreen) Resize(int, int, int, int) {}
// Suspend simply pauses all input and output, and clears the screen.
// There isn't a "default terminal" to go back to.
func (t *wScreen) Suspend() error {
t.Lock()
if !t.running {
t.Unlock()
return nil
}
t.running = false
t.clearScreen()
t.enableMouse(0)
t.enablePasting(false)
js.Global().Set("onKeyEvent", js.FuncOf(t.unset)) // stop keypresses
return nil
}
func (t *wScreen) Resume() error {
t.Lock()
if t.running {
return errors.New("already engaged")
}
t.running = true
t.enableMouse(t.mouseFlags)
t.enablePasting(t.pasteEnabled)
js.Global().Set("onKeyEvent", js.FuncOf(t.onKeyEvent))
t.Unlock()
return nil
}
func (t *wScreen) Beep() error {
js.Global().Call("beep")
return nil
}
func (t *wScreen) Tty() (Tty, bool) {
return nil, false
}
func (t *wScreen) GetCells() *CellBuffer {
return &t.cells
}
func (t *wScreen) EventQ() chan Event {
return t.evch
}
func (t *wScreen) StopQ() <-chan struct{} {
return t.quit
}
// WebKeyNames maps string names reported from HTML
// (KeyboardEvent.key) to tcell accepted keys.
var WebKeyNames = map[string]Key{
"Enter": KeyEnter,
"Backspace": KeyBackspace,
"Tab": KeyTab,
"Backtab": KeyBacktab,
"Escape": KeyEsc,
"Backspace2": KeyBackspace2,
"Delete": KeyDelete,
"Insert": KeyInsert,
"ArrowUp": KeyUp,
"ArrowDown": KeyDown,
"ArrowLeft": KeyLeft,
"ArrowRight": KeyRight,
"Home": KeyHome,
"End": KeyEnd,
"UpLeft": KeyUpLeft, // not supported by HTML
"UpRight": KeyUpRight, // not supported by HTML
"DownLeft": KeyDownLeft, // not supported by HTML
"DownRight": KeyDownRight, // not supported by HTML
"Center": KeyCenter,
"PgDn": KeyPgDn,
"PgUp": KeyPgUp,
"Clear": KeyClear,
"Exit": KeyExit,
"Cancel": KeyCancel,
"Pause": KeyPause,
"Print": KeyPrint,
"F1": KeyF1,
"F2": KeyF2,
"F3": KeyF3,
"F4": KeyF4,
"F5": KeyF5,
"F6": KeyF6,
"F7": KeyF7,
"F8": KeyF8,
"F9": KeyF9,
"F10": KeyF10,
"F11": KeyF11,
"F12": KeyF12,
"F13": KeyF13,
"F14": KeyF14,
"F15": KeyF15,
"F16": KeyF16,
"F17": KeyF17,
"F18": KeyF18,
"F19": KeyF19,
"F20": KeyF20,
"F21": KeyF21,
"F22": KeyF22,
"F23": KeyF23,
"F24": KeyF24,
"F25": KeyF25,
"F26": KeyF26,
"F27": KeyF27,
"F28": KeyF28,
"F29": KeyF29,
"F30": KeyF30,
"F31": KeyF31,
"F32": KeyF32,
"F33": KeyF33,
"F34": KeyF34,
"F35": KeyF35,
"F36": KeyF36,
"F37": KeyF37,
"F38": KeyF38,
"F39": KeyF39,
"F40": KeyF40,
"F41": KeyF41,
"F42": KeyF42,
"F43": KeyF43,
"F44": KeyF44,
"F45": KeyF45,
"F46": KeyF46,
"F47": KeyF47,
"F48": KeyF48,
"F49": KeyF49,
"F50": KeyF50,
"F51": KeyF51,
"F52": KeyF52,
"F53": KeyF53,
"F54": KeyF54,
"F55": KeyF55,
"F56": KeyF56,
"F57": KeyF57,
"F58": KeyF58,
"F59": KeyF59,
"F60": KeyF60,
"F61": KeyF61,
"F62": KeyF62,
"F63": KeyF63,
"F64": KeyF64,
"Ctrl-a": KeyCtrlA, // not reported by HTML- need to do special check
"Ctrl-b": KeyCtrlB, // not reported by HTML- need to do special check
"Ctrl-c": KeyCtrlC, // not reported by HTML- need to do special check
"Ctrl-d": KeyCtrlD, // not reported by HTML- need to do special check
"Ctrl-e": KeyCtrlE, // not reported by HTML- need to do special check
"Ctrl-f": KeyCtrlF, // not reported by HTML- need to do special check
"Ctrl-g": KeyCtrlG, // not reported by HTML- need to do special check
"Ctrl-j": KeyCtrlJ, // not reported by HTML- need to do special check
"Ctrl-k": KeyCtrlK, // not reported by HTML- need to do special check
"Ctrl-l": KeyCtrlL, // not reported by HTML- need to do special check
"Ctrl-n": KeyCtrlN, // not reported by HTML- need to do special check
"Ctrl-o": KeyCtrlO, // not reported by HTML- need to do special check
"Ctrl-p": KeyCtrlP, // not reported by HTML- need to do special check
"Ctrl-q": KeyCtrlQ, // not reported by HTML- need to do special check
"Ctrl-r": KeyCtrlR, // not reported by HTML- need to do special check
"Ctrl-s": KeyCtrlS, // not reported by HTML- need to do special check
"Ctrl-t": KeyCtrlT, // not reported by HTML- need to do special check
"Ctrl-u": KeyCtrlU, // not reported by HTML- need to do special check
"Ctrl-v": KeyCtrlV, // not reported by HTML- need to do special check
"Ctrl-w": KeyCtrlW, // not reported by HTML- need to do special check
"Ctrl-x": KeyCtrlX, // not reported by HTML- need to do special check
"Ctrl-y": KeyCtrlY, // not reported by HTML- need to do special check
"Ctrl-z": KeyCtrlZ, // not reported by HTML- need to do special check
"Ctrl- ": KeyCtrlSpace, // not reported by HTML- need to do special check
"Ctrl-_": KeyCtrlUnderscore, // not reported by HTML- need to do special check
"Ctrl-]": KeyCtrlRightSq, // not reported by HTML- need to do special check
"Ctrl-\\": KeyCtrlBackslash, // not reported by HTML- need to do special check
"Ctrl-^": KeyCtrlCarat, // not reported by HTML- need to do special check
}
var curStyleClasses = map[CursorStyle]string{
CursorStyleDefault: "cursor-blinking-block",
CursorStyleBlinkingBlock: "cursor-blinking-block",
CursorStyleSteadyBlock: "cursor-steady-block",
CursorStyleBlinkingUnderline: "cursor-blinking-underline",
CursorStyleSteadyUnderline: "cursor-steady-underline",
CursorStyleBlinkingBar: "cursor-blinking-bar",
CursorStyleSteadyBar: "cursor-steady-bar",
}
func LookupTerminfo(name string) (ti *terminfo.Terminfo, e error) {
return nil, errors.New("LookupTermInfo not supported")
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/resize.go | vendor/github.com/gdamore/tcell/v2/resize.go | // Copyright 2015 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 tcell
import (
"time"
)
// EventResize is sent when the window size changes.
type EventResize struct {
t time.Time
ws WindowSize
}
// NewEventResize creates an EventResize with the new updated window size,
// which is given in character cells.
func NewEventResize(width, height int) *EventResize {
ws := WindowSize{
Width: width,
Height: height,
}
return &EventResize{t: time.Now(), ws: ws}
}
// When returns the time when the Event was created.
func (ev *EventResize) When() time.Time {
return ev.t
}
// Size returns the new window size as width, height in character cells.
func (ev *EventResize) Size() (int, int) {
return ev.ws.Width, ev.ws.Height
}
// PixelSize returns the new window size as width, height in pixels. The size
// will be 0,0 if the screen doesn't support this feature
func (ev *EventResize) PixelSize() (int, int) {
return ev.ws.PixelWidth, ev.ws.PixelHeight
}
type WindowSize struct {
Width int
Height int
PixelWidth int
PixelHeight int
}
// CellDimensions returns the dimensions of a single cell, in pixels
func (ws WindowSize) CellDimensions() (int, int) {
if ws.PixelWidth == 0 || ws.PixelHeight == 0 {
return 0, 0
}
return (ws.PixelWidth / ws.Width), (ws.PixelHeight / ws.Height)
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/tscreen_unix.go | vendor/github.com/gdamore/tcell/v2/tscreen_unix.go | // Copyright 2021 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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.
//go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos
// +build aix darwin dragonfly freebsd linux netbsd openbsd solaris zos
package tcell
// initialize is used at application startup, and sets up the initial values
// including file descriptors used for terminals and saving the initial state
// so that it can be restored when the application terminates.
func (t *tScreen) initialize() error {
var err error
if t.tty == nil {
t.tty, err = NewDevTty()
if err != nil {
return err
}
}
return nil
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/focus.go | vendor/github.com/gdamore/tcell/v2/focus.go | // Copyright 2023 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 tcell
// EventFocus is a focus event. It is sent when the terminal window (or tab)
// gets or loses focus.
type EventFocus struct {
*EventTime
// True if the window received focus, false if it lost focus
Focused bool
}
func NewEventFocus(focused bool) *EventFocus {
return &EventFocus{Focused: focused}
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/console_win.go | vendor/github.com/gdamore/tcell/v2/console_win.go | //go:build windows
// +build windows
// Copyright 2024 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 tcell
import (
"errors"
"fmt"
"os"
"strings"
"sync"
"syscall"
"unicode/utf16"
"unsafe"
)
type cScreen struct {
in syscall.Handle
out syscall.Handle
cancelflag syscall.Handle
scandone chan struct{}
quit chan struct{}
curx int
cury int
style Style
fini bool
vten bool
truecolor bool
running bool
disableAlt bool // disable the alternate screen
w int
h int
oscreen consoleInfo
ocursor cursorInfo
cursorStyle CursorStyle
oimode uint32
oomode uint32
cells CellBuffer
focusEnable bool
mouseEnabled bool
wg sync.WaitGroup
eventQ chan Event
stopQ chan struct{}
finiOnce sync.Once
sync.Mutex
}
var winLock sync.Mutex
var winPalette = []Color{
ColorBlack,
ColorMaroon,
ColorGreen,
ColorNavy,
ColorOlive,
ColorPurple,
ColorTeal,
ColorSilver,
ColorGray,
ColorRed,
ColorLime,
ColorBlue,
ColorYellow,
ColorFuchsia,
ColorAqua,
ColorWhite,
}
var winColors = map[Color]Color{
ColorBlack: ColorBlack,
ColorMaroon: ColorMaroon,
ColorGreen: ColorGreen,
ColorNavy: ColorNavy,
ColorOlive: ColorOlive,
ColorPurple: ColorPurple,
ColorTeal: ColorTeal,
ColorSilver: ColorSilver,
ColorGray: ColorGray,
ColorRed: ColorRed,
ColorLime: ColorLime,
ColorBlue: ColorBlue,
ColorYellow: ColorYellow,
ColorFuchsia: ColorFuchsia,
ColorAqua: ColorAqua,
ColorWhite: ColorWhite,
}
var (
k32 = syscall.NewLazyDLL("kernel32.dll")
u32 = syscall.NewLazyDLL("user32.dll")
)
// We have to bring in the kernel32 and user32 DLLs directly, so we can get
// access to some system calls that the core Go API lacks.
//
// Note that Windows appends some functions with W to indicate that wide
// characters (Unicode) are in use. The documentation refers to them
// without this suffix, as the resolution is made via preprocessor.
var (
procReadConsoleInput = k32.NewProc("ReadConsoleInputW")
procWaitForMultipleObjects = k32.NewProc("WaitForMultipleObjects")
procCreateEvent = k32.NewProc("CreateEventW")
procSetEvent = k32.NewProc("SetEvent")
procGetConsoleCursorInfo = k32.NewProc("GetConsoleCursorInfo")
procSetConsoleCursorInfo = k32.NewProc("SetConsoleCursorInfo")
procSetConsoleCursorPosition = k32.NewProc("SetConsoleCursorPosition")
procSetConsoleMode = k32.NewProc("SetConsoleMode")
procGetConsoleMode = k32.NewProc("GetConsoleMode")
procGetConsoleScreenBufferInfo = k32.NewProc("GetConsoleScreenBufferInfo")
procFillConsoleOutputAttribute = k32.NewProc("FillConsoleOutputAttribute")
procFillConsoleOutputCharacter = k32.NewProc("FillConsoleOutputCharacterW")
procSetConsoleWindowInfo = k32.NewProc("SetConsoleWindowInfo")
procSetConsoleScreenBufferSize = k32.NewProc("SetConsoleScreenBufferSize")
procSetConsoleTextAttribute = k32.NewProc("SetConsoleTextAttribute")
procGetLargestConsoleWindowSize = k32.NewProc("GetLargestConsoleWindowSize")
procMessageBeep = u32.NewProc("MessageBeep")
)
const (
w32Infinite = ^uintptr(0)
w32WaitObject0 = uintptr(0)
)
const (
// VT100/XTerm escapes understood by the console
vtShowCursor = "\x1b[?25h"
vtHideCursor = "\x1b[?25l"
vtCursorPos = "\x1b[%d;%dH" // Note that it is Y then X
vtSgr0 = "\x1b[0m"
vtBold = "\x1b[1m"
vtUnderline = "\x1b[4m"
vtBlink = "\x1b[5m" // Not sure if this is processed
vtReverse = "\x1b[7m"
vtSetFg = "\x1b[38;5;%dm"
vtSetBg = "\x1b[48;5;%dm"
vtSetFgRGB = "\x1b[38;2;%d;%d;%dm" // RGB
vtSetBgRGB = "\x1b[48;2;%d;%d;%dm" // RGB
vtCursorDefault = "\x1b[0 q"
vtCursorBlinkingBlock = "\x1b[1 q"
vtCursorSteadyBlock = "\x1b[2 q"
vtCursorBlinkingUnderline = "\x1b[3 q"
vtCursorSteadyUnderline = "\x1b[4 q"
vtCursorBlinkingBar = "\x1b[5 q"
vtCursorSteadyBar = "\x1b[6 q"
vtDisableAm = "\x1b[?7l"
vtEnableAm = "\x1b[?7h"
vtEnterCA = "\x1b[?1049h\x1b[22;0;0t"
vtExitCA = "\x1b[?1049l\x1b[23;0;0t"
)
var vtCursorStyles = map[CursorStyle]string{
CursorStyleDefault: vtCursorDefault,
CursorStyleBlinkingBlock: vtCursorBlinkingBlock,
CursorStyleSteadyBlock: vtCursorSteadyBlock,
CursorStyleBlinkingUnderline: vtCursorBlinkingUnderline,
CursorStyleSteadyUnderline: vtCursorSteadyUnderline,
CursorStyleBlinkingBar: vtCursorBlinkingBar,
CursorStyleSteadyBar: vtCursorSteadyBar,
}
// NewConsoleScreen returns a Screen for the Windows console associated
// with the current process. The Screen makes use of the Windows Console
// API to display content and read events.
func NewConsoleScreen() (Screen, error) {
return &baseScreen{screenImpl: &cScreen{}}, nil
}
func (s *cScreen) Init() error {
s.eventQ = make(chan Event, 10)
s.quit = make(chan struct{})
s.scandone = make(chan struct{})
in, e := syscall.Open("CONIN$", syscall.O_RDWR, 0)
if e != nil {
return e
}
s.in = in
out, e := syscall.Open("CONOUT$", syscall.O_RDWR, 0)
if e != nil {
_ = syscall.Close(s.in)
return e
}
s.out = out
s.truecolor = true
// ConEmu handling of colors and scrolling when in VT output mode is extremely poor.
// The color palette will scroll even though characters do not, when
// emitting stuff for the last character. In the future we might change this to
// look at specific versions of ConEmu if they fix the bug.
// We can also try disabling auto margin mode.
tryVt := true
if os.Getenv("ConEmuPID") != "" {
s.truecolor = false
tryVt = false
}
switch os.Getenv("TCELL_TRUECOLOR") {
case "disable":
s.truecolor = false
case "enable":
s.truecolor = true
tryVt = true
}
s.Lock()
s.curx = -1
s.cury = -1
s.style = StyleDefault
s.getCursorInfo(&s.ocursor)
s.getConsoleInfo(&s.oscreen)
s.getOutMode(&s.oomode)
s.getInMode(&s.oimode)
s.resize()
s.fini = false
s.setInMode(modeResizeEn | modeExtendFlg)
// If a user needs to force old style console, they may do so
// by setting TCELL_VTMODE to disable. This is an undocumented safety net for now.
// It may be removed in the future. (This mostly exists because of ConEmu.)
switch os.Getenv("TCELL_VTMODE") {
case "disable":
tryVt = false
case "enable":
tryVt = true
}
switch os.Getenv("TCELL_ALTSCREEN") {
case "enable":
s.disableAlt = false // also the default
case "disable":
s.disableAlt = true
}
if tryVt {
s.setOutMode(modeVtOutput | modeNoAutoNL | modeCookedOut | modeUnderline)
var om uint32
s.getOutMode(&om)
if om&modeVtOutput == modeVtOutput {
s.vten = true
} else {
s.truecolor = false
s.setOutMode(0)
}
} else {
s.setOutMode(0)
}
s.Unlock()
return s.engage()
}
func (s *cScreen) CharacterSet() string {
// We are always UTF-16LE on Windows
return "UTF-16LE"
}
func (s *cScreen) EnableMouse(...MouseFlags) {
s.Lock()
s.mouseEnabled = true
s.enableMouse(true)
s.Unlock()
}
func (s *cScreen) DisableMouse() {
s.Lock()
s.mouseEnabled = false
s.enableMouse(false)
s.Unlock()
}
func (s *cScreen) enableMouse(on bool) {
if on {
s.setInMode(modeResizeEn | modeMouseEn | modeExtendFlg)
} else {
s.setInMode(modeResizeEn | modeExtendFlg)
}
}
// Windows lacks bracketed paste (for now)
func (s *cScreen) EnablePaste() {}
func (s *cScreen) DisablePaste() {}
func (s *cScreen) EnableFocus() {
s.Lock()
s.focusEnable = true
s.Unlock()
}
func (s *cScreen) DisableFocus() {
s.Lock()
s.focusEnable = false
s.Unlock()
}
func (s *cScreen) Fini() {
s.finiOnce.Do(func() {
close(s.quit)
s.disengage()
})
}
func (s *cScreen) disengage() {
s.Lock()
if !s.running {
s.Unlock()
return
}
s.running = false
stopQ := s.stopQ
_, _, _ = procSetEvent.Call(uintptr(s.cancelflag))
close(stopQ)
s.Unlock()
s.wg.Wait()
if s.vten {
s.emitVtString(vtCursorStyles[CursorStyleDefault])
s.emitVtString(vtEnableAm)
if !s.disableAlt {
s.emitVtString(vtExitCA)
}
} else if !s.disableAlt {
s.clearScreen(StyleDefault, s.vten)
s.setCursorPos(0, 0, false)
}
s.setCursorInfo(&s.ocursor)
s.setBufferSize(int(s.oscreen.size.x), int(s.oscreen.size.y))
s.setInMode(s.oimode)
s.setOutMode(s.oomode)
_, _, _ = procSetConsoleTextAttribute.Call(
uintptr(s.out),
uintptr(s.mapStyle(StyleDefault)))
}
func (s *cScreen) engage() error {
s.Lock()
defer s.Unlock()
if s.running {
return errors.New("already engaged")
}
s.stopQ = make(chan struct{})
cf, _, e := procCreateEvent.Call(
uintptr(0),
uintptr(1),
uintptr(0),
uintptr(0))
if cf == uintptr(0) {
return e
}
s.running = true
s.cancelflag = syscall.Handle(cf)
s.enableMouse(s.mouseEnabled)
if s.vten {
s.setOutMode(modeVtOutput | modeNoAutoNL | modeCookedOut | modeUnderline)
if !s.disableAlt {
s.emitVtString(vtEnterCA)
}
s.emitVtString(vtDisableAm)
} else {
s.setOutMode(0)
}
s.clearScreen(s.style, s.vten)
s.hideCursor()
s.cells.Invalidate()
s.hideCursor()
s.resize()
s.draw()
s.doCursor()
s.wg.Add(1)
go s.scanInput(s.stopQ)
return nil
}
type cursorInfo struct {
size uint32
visible uint32
}
type coord struct {
x int16
y int16
}
func (c coord) uintptr() uintptr {
// little endian, put x first
return uintptr(c.x) | (uintptr(c.y) << 16)
}
type rect struct {
left int16
top int16
right int16
bottom int16
}
func (s *cScreen) emitVtString(vs string) {
esc := utf16.Encode([]rune(vs))
_ = syscall.WriteConsole(s.out, &esc[0], uint32(len(esc)), nil, nil)
}
func (s *cScreen) showCursor() {
if s.vten {
s.emitVtString(vtShowCursor)
s.emitVtString(vtCursorStyles[s.cursorStyle])
} else {
s.setCursorInfo(&cursorInfo{size: 100, visible: 1})
}
}
func (s *cScreen) hideCursor() {
if s.vten {
s.emitVtString(vtHideCursor)
} else {
s.setCursorInfo(&cursorInfo{size: 1, visible: 0})
}
}
func (s *cScreen) ShowCursor(x, y int) {
s.Lock()
if !s.fini {
s.curx = x
s.cury = y
}
s.doCursor()
s.Unlock()
}
func (s *cScreen) SetCursorStyle(cs CursorStyle) {
s.Lock()
if !s.fini {
if _, ok := vtCursorStyles[cs]; ok {
s.cursorStyle = cs
s.doCursor()
}
}
s.Unlock()
}
func (s *cScreen) doCursor() {
x, y := s.curx, s.cury
if x < 0 || y < 0 || x >= s.w || y >= s.h {
s.hideCursor()
} else {
s.setCursorPos(x, y, s.vten)
s.showCursor()
}
}
func (s *cScreen) HideCursor() {
s.ShowCursor(-1, -1)
}
type inputRecord struct {
typ uint16
_ uint16
data [16]byte
}
const (
keyEvent uint16 = 1
mouseEvent uint16 = 2
resizeEvent uint16 = 4
menuEvent uint16 = 8 // don't use
focusEvent uint16 = 16
)
type mouseRecord struct {
x int16
y int16
btns uint32
mod uint32
flags uint32
}
type focusRecord struct {
focused int32 // actually BOOL
}
const (
mouseHWheeled uint32 = 0x8
mouseVWheeled uint32 = 0x4
// mouseDoubleClick uint32 = 0x2
// mouseMoved uint32 = 0x1
)
type resizeRecord struct {
x int16
y int16
}
type keyRecord struct {
isdown int32
repeat uint16
kcode uint16
scode uint16
ch uint16
mod uint32
}
const (
// Constants per Microsoft. We don't put the modifiers
// here.
vkCancel = 0x03
vkBack = 0x08 // Backspace
vkTab = 0x09
vkClear = 0x0c
vkReturn = 0x0d
vkPause = 0x13
vkEscape = 0x1b
vkSpace = 0x20
vkPrior = 0x21 // PgUp
vkNext = 0x22 // PgDn
vkEnd = 0x23
vkHome = 0x24
vkLeft = 0x25
vkUp = 0x26
vkRight = 0x27
vkDown = 0x28
vkPrint = 0x2a
vkPrtScr = 0x2c
vkInsert = 0x2d
vkDelete = 0x2e
vkHelp = 0x2f
vkF1 = 0x70
vkF2 = 0x71
vkF3 = 0x72
vkF4 = 0x73
vkF5 = 0x74
vkF6 = 0x75
vkF7 = 0x76
vkF8 = 0x77
vkF9 = 0x78
vkF10 = 0x79
vkF11 = 0x7a
vkF12 = 0x7b
vkF13 = 0x7c
vkF14 = 0x7d
vkF15 = 0x7e
vkF16 = 0x7f
vkF17 = 0x80
vkF18 = 0x81
vkF19 = 0x82
vkF20 = 0x83
vkF21 = 0x84
vkF22 = 0x85
vkF23 = 0x86
vkF24 = 0x87
)
var vkKeys = map[uint16]Key{
vkCancel: KeyCancel,
vkBack: KeyBackspace,
vkTab: KeyTab,
vkClear: KeyClear,
vkPause: KeyPause,
vkPrint: KeyPrint,
vkPrtScr: KeyPrint,
vkPrior: KeyPgUp,
vkNext: KeyPgDn,
vkReturn: KeyEnter,
vkEnd: KeyEnd,
vkHome: KeyHome,
vkLeft: KeyLeft,
vkUp: KeyUp,
vkRight: KeyRight,
vkDown: KeyDown,
vkInsert: KeyInsert,
vkDelete: KeyDelete,
vkHelp: KeyHelp,
vkEscape: KeyEscape,
vkSpace: ' ',
vkF1: KeyF1,
vkF2: KeyF2,
vkF3: KeyF3,
vkF4: KeyF4,
vkF5: KeyF5,
vkF6: KeyF6,
vkF7: KeyF7,
vkF8: KeyF8,
vkF9: KeyF9,
vkF10: KeyF10,
vkF11: KeyF11,
vkF12: KeyF12,
vkF13: KeyF13,
vkF14: KeyF14,
vkF15: KeyF15,
vkF16: KeyF16,
vkF17: KeyF17,
vkF18: KeyF18,
vkF19: KeyF19,
vkF20: KeyF20,
vkF21: KeyF21,
vkF22: KeyF22,
vkF23: KeyF23,
vkF24: KeyF24,
}
// NB: All Windows platforms are little endian. We assume this
// never, ever change. The following code is endian safe. and does
// not use unsafe pointers.
func getu32(v []byte) uint32 {
return uint32(v[0]) + (uint32(v[1]) << 8) + (uint32(v[2]) << 16) + (uint32(v[3]) << 24)
}
func geti32(v []byte) int32 {
return int32(getu32(v))
}
func getu16(v []byte) uint16 {
return uint16(v[0]) + (uint16(v[1]) << 8)
}
func geti16(v []byte) int16 {
return int16(getu16(v))
}
// Convert windows dwControlKeyState to modifier mask
func mod2mask(cks uint32) ModMask {
mm := ModNone
// Left or right control
ctrl := (cks & (0x0008 | 0x0004)) != 0
// Left or right alt
alt := (cks & (0x0002 | 0x0001)) != 0
// Filter out ctrl+alt (it means AltGr)
if !(ctrl && alt) {
if ctrl {
mm |= ModCtrl
}
if alt {
mm |= ModAlt
}
}
// Any shift
if (cks & 0x0010) != 0 {
mm |= ModShift
}
return mm
}
func mrec2btns(mbtns, flags uint32) ButtonMask {
btns := ButtonNone
if mbtns&0x1 != 0 {
btns |= Button1
}
if mbtns&0x2 != 0 {
btns |= Button2
}
if mbtns&0x4 != 0 {
btns |= Button3
}
if mbtns&0x8 != 0 {
btns |= Button4
}
if mbtns&0x10 != 0 {
btns |= Button5
}
if mbtns&0x20 != 0 {
btns |= Button6
}
if mbtns&0x40 != 0 {
btns |= Button7
}
if mbtns&0x80 != 0 {
btns |= Button8
}
if flags&mouseVWheeled != 0 {
if mbtns&0x80000000 == 0 {
btns |= WheelUp
} else {
btns |= WheelDown
}
}
if flags&mouseHWheeled != 0 {
if mbtns&0x80000000 == 0 {
btns |= WheelRight
} else {
btns |= WheelLeft
}
}
return btns
}
func (s *cScreen) postEvent(ev Event) {
select {
case s.eventQ <- ev:
case <-s.quit:
}
}
func (s *cScreen) getConsoleInput() error {
// cancelFlag comes first as WaitForMultipleObjects returns the lowest index
// in the event that both events are signalled.
waitObjects := []syscall.Handle{s.cancelflag, s.in}
// As arrays are contiguous in memory, a pointer to the first object is the
// same as a pointer to the array itself.
pWaitObjects := unsafe.Pointer(&waitObjects[0])
rv, _, er := procWaitForMultipleObjects.Call(
uintptr(len(waitObjects)),
uintptr(pWaitObjects),
uintptr(0),
w32Infinite)
// WaitForMultipleObjects returns WAIT_OBJECT_0 + the index.
switch rv {
case w32WaitObject0: // s.cancelFlag
return errors.New("cancelled")
case w32WaitObject0 + 1: // s.in
rec := &inputRecord{}
var nrec int32
rv, _, er := procReadConsoleInput.Call(
uintptr(s.in),
uintptr(unsafe.Pointer(rec)),
uintptr(1),
uintptr(unsafe.Pointer(&nrec)))
if rv == 0 {
return er
}
if nrec != 1 {
return nil
}
switch rec.typ {
case keyEvent:
krec := &keyRecord{}
krec.isdown = geti32(rec.data[0:])
krec.repeat = getu16(rec.data[4:])
krec.kcode = getu16(rec.data[6:])
krec.scode = getu16(rec.data[8:])
krec.ch = getu16(rec.data[10:])
krec.mod = getu32(rec.data[12:])
if krec.isdown == 0 || krec.repeat < 1 {
// it's a key release event, ignore it
return nil
}
if krec.ch != 0 {
// synthesized key code
for krec.repeat > 0 {
// convert shift+tab to backtab
if mod2mask(krec.mod) == ModShift && krec.ch == vkTab {
s.postEvent(NewEventKey(KeyBacktab, 0, ModNone))
} else {
s.postEvent(NewEventKey(KeyRune, rune(krec.ch), mod2mask(krec.mod)))
}
krec.repeat--
}
return nil
}
key := KeyNUL // impossible on Windows
ok := false
if key, ok = vkKeys[krec.kcode]; !ok {
return nil
}
for krec.repeat > 0 {
s.postEvent(NewEventKey(key, rune(krec.ch), mod2mask(krec.mod)))
krec.repeat--
}
case mouseEvent:
var mrec mouseRecord
mrec.x = geti16(rec.data[0:])
mrec.y = geti16(rec.data[2:])
mrec.btns = getu32(rec.data[4:])
mrec.mod = getu32(rec.data[8:])
mrec.flags = getu32(rec.data[12:])
btns := mrec2btns(mrec.btns, mrec.flags)
// we ignore double click, events are delivered normally
s.postEvent(NewEventMouse(int(mrec.x), int(mrec.y), btns, mod2mask(mrec.mod)))
case resizeEvent:
var rrec resizeRecord
rrec.x = geti16(rec.data[0:])
rrec.y = geti16(rec.data[2:])
s.postEvent(NewEventResize(int(rrec.x), int(rrec.y)))
case focusEvent:
var focus focusRecord
focus.focused = geti32(rec.data[0:])
s.Lock()
enabled := s.focusEnable
s.Unlock()
if enabled {
s.postEvent(NewEventFocus(focus.focused != 0))
}
default:
}
default:
return er
}
return nil
}
func (s *cScreen) scanInput(stopQ chan struct{}) {
defer s.wg.Done()
for {
select {
case <-stopQ:
return
default:
}
if e := s.getConsoleInput(); e != nil {
return
}
}
}
func (s *cScreen) Colors() int {
if s.vten {
return 1 << 24
}
// Windows console can display 8 colors, in either low or high intensity
return 16
}
var vgaColors = map[Color]uint16{
ColorBlack: 0,
ColorMaroon: 0x4,
ColorGreen: 0x2,
ColorNavy: 0x1,
ColorOlive: 0x6,
ColorPurple: 0x5,
ColorTeal: 0x3,
ColorSilver: 0x7,
ColorGrey: 0x8,
ColorRed: 0xc,
ColorLime: 0xa,
ColorBlue: 0x9,
ColorYellow: 0xe,
ColorFuchsia: 0xd,
ColorAqua: 0xb,
ColorWhite: 0xf,
}
// Windows uses RGB signals
func mapColor2RGB(c Color) uint16 {
winLock.Lock()
if v, ok := winColors[c]; ok {
c = v
} else {
v = FindColor(c, winPalette)
winColors[c] = v
c = v
}
winLock.Unlock()
if vc, ok := vgaColors[c]; ok {
return vc
}
return 0
}
// Map a tcell style to Windows attributes
func (s *cScreen) mapStyle(style Style) uint16 {
f, b, a := style.Decompose()
fa := s.oscreen.attrs & 0xf
ba := (s.oscreen.attrs) >> 4 & 0xf
if f != ColorDefault && f != ColorReset {
fa = mapColor2RGB(f)
}
if b != ColorDefault && b != ColorReset {
ba = mapColor2RGB(b)
}
var attr uint16
// We simulate reverse by doing the color swap ourselves.
// Apparently windows cannot really do this except in DBCS
// views.
if a&AttrReverse != 0 {
attr = ba
attr |= fa << 4
} else {
attr = fa
attr |= ba << 4
}
if a&AttrBold != 0 {
attr |= 0x8
}
if a&AttrDim != 0 {
attr &^= 0x8
}
if a&AttrUnderline != 0 {
// Best effort -- doesn't seem to work though.
attr |= 0x8000
}
// Blink is unsupported
return attr
}
func (s *cScreen) sendVtStyle(style Style) {
esc := &strings.Builder{}
fg, bg, attrs := style.Decompose()
esc.WriteString(vtSgr0)
if attrs&(AttrBold|AttrDim) == AttrBold {
esc.WriteString(vtBold)
}
if attrs&AttrBlink != 0 {
esc.WriteString(vtBlink)
}
if attrs&AttrUnderline != 0 {
esc.WriteString(vtUnderline)
}
if attrs&AttrReverse != 0 {
esc.WriteString(vtReverse)
}
if fg.IsRGB() {
r, g, b := fg.RGB()
_, _ = fmt.Fprintf(esc, vtSetFgRGB, r, g, b)
} else if fg.Valid() {
_, _ = fmt.Fprintf(esc, vtSetFg, fg&0xff)
}
if bg.IsRGB() {
r, g, b := bg.RGB()
_, _ = fmt.Fprintf(esc, vtSetBgRGB, r, g, b)
} else if bg.Valid() {
_, _ = fmt.Fprintf(esc, vtSetBg, bg&0xff)
}
s.emitVtString(esc.String())
}
func (s *cScreen) writeString(x, y int, style Style, ch []uint16) {
// we assume the caller has hidden the cursor
if len(ch) == 0 {
return
}
s.setCursorPos(x, y, s.vten)
if s.vten {
s.sendVtStyle(style)
} else {
_, _, _ = procSetConsoleTextAttribute.Call(
uintptr(s.out),
uintptr(s.mapStyle(style)))
}
_ = syscall.WriteConsole(s.out, &ch[0], uint32(len(ch)), nil, nil)
}
func (s *cScreen) draw() {
// allocate a scratch line bit enough for no combining chars.
// if you have combining characters, you may pay for extra allocations.
buf := make([]uint16, 0, s.w)
wcs := buf[:]
lstyle := styleInvalid
lx, ly := -1, -1
ra := make([]rune, 1)
for y := 0; y < s.h; y++ {
for x := 0; x < s.w; x++ {
mainc, combc, style, width := s.cells.GetContent(x, y)
dirty := s.cells.Dirty(x, y)
if style == StyleDefault {
style = s.style
}
if !dirty || style != lstyle {
// write out any data queued thus far
// because we are going to skip over some
// cells, or because we need to change styles
s.writeString(lx, ly, lstyle, wcs)
wcs = buf[0:0]
lstyle = StyleDefault
if !dirty {
continue
}
}
if x > s.w-width {
mainc = ' '
combc = nil
width = 1
}
if len(wcs) == 0 {
lstyle = style
lx = x
ly = y
}
ra[0] = mainc
wcs = append(wcs, utf16.Encode(ra)...)
if len(combc) != 0 {
wcs = append(wcs, utf16.Encode(combc)...)
}
for dx := 0; dx < width; dx++ {
s.cells.SetDirty(x+dx, y, false)
}
x += width - 1
}
s.writeString(lx, ly, lstyle, wcs)
wcs = buf[0:0]
lstyle = styleInvalid
}
}
func (s *cScreen) Show() {
s.Lock()
if !s.fini {
s.hideCursor()
s.resize()
s.draw()
s.doCursor()
}
s.Unlock()
}
func (s *cScreen) Sync() {
s.Lock()
if !s.fini {
s.cells.Invalidate()
s.hideCursor()
s.resize()
s.draw()
s.doCursor()
}
s.Unlock()
}
type consoleInfo struct {
size coord
pos coord
attrs uint16
win rect
maxsz coord
}
func (s *cScreen) getConsoleInfo(info *consoleInfo) {
_, _, _ = procGetConsoleScreenBufferInfo.Call(
uintptr(s.out),
uintptr(unsafe.Pointer(info)))
}
func (s *cScreen) getCursorInfo(info *cursorInfo) {
_, _, _ = procGetConsoleCursorInfo.Call(
uintptr(s.out),
uintptr(unsafe.Pointer(info)))
}
func (s *cScreen) setCursorInfo(info *cursorInfo) {
_, _, _ = procSetConsoleCursorInfo.Call(
uintptr(s.out),
uintptr(unsafe.Pointer(info)))
}
func (s *cScreen) setCursorPos(x, y int, vtEnable bool) {
if vtEnable {
// Note that the string is Y first. Origin is 1,1.
s.emitVtString(fmt.Sprintf(vtCursorPos, y+1, x+1))
} else {
_, _, _ = procSetConsoleCursorPosition.Call(
uintptr(s.out),
coord{int16(x), int16(y)}.uintptr())
}
}
func (s *cScreen) setBufferSize(x, y int) {
_, _, _ = procSetConsoleScreenBufferSize.Call(
uintptr(s.out),
coord{int16(x), int16(y)}.uintptr())
}
func (s *cScreen) Size() (int, int) {
s.Lock()
w, h := s.w, s.h
s.Unlock()
return w, h
}
func (s *cScreen) SetSize(w, h int) {
xy, _, _ := procGetLargestConsoleWindowSize.Call(uintptr(s.out))
// xy is little endian packed
y := int(xy >> 16)
x := int(xy & 0xffff)
if x == 0 || y == 0 {
return
}
// This is a hacky workaround for Windows Terminal.
// Essentially Windows Terminal (Windows 11) does not support application
// initiated resizing. To detect this, we look for an extremely large size
// for the maximum width. If it is > 500, then this is almost certainly
// Windows Terminal, and won't support this. (Note that the legacy console
// does support application resizing.)
if x >= 500 {
return
}
s.setBufferSize(x, y)
r := rect{0, 0, int16(w - 1), int16(h - 1)}
_, _, _ = procSetConsoleWindowInfo.Call(
uintptr(s.out),
uintptr(1),
uintptr(unsafe.Pointer(&r)))
s.resize()
}
func (s *cScreen) resize() {
info := consoleInfo{}
s.getConsoleInfo(&info)
w := int((info.win.right - info.win.left) + 1)
h := int((info.win.bottom - info.win.top) + 1)
if s.w == w && s.h == h {
return
}
s.cells.Resize(w, h)
s.w = w
s.h = h
s.setBufferSize(w, h)
r := rect{0, 0, int16(w - 1), int16(h - 1)}
_, _, _ = procSetConsoleWindowInfo.Call(
uintptr(s.out),
uintptr(1),
uintptr(unsafe.Pointer(&r)))
select {
case s.eventQ <- NewEventResize(w, h):
default:
}
}
func (s *cScreen) clearScreen(style Style, vtEnable bool) {
if vtEnable {
s.sendVtStyle(style)
row := strings.Repeat(" ", s.w)
for y := 0; y < s.h; y++ {
s.setCursorPos(0, y, vtEnable)
s.emitVtString(row)
}
s.setCursorPos(0, 0, vtEnable)
} else {
pos := coord{0, 0}
attr := s.mapStyle(style)
x, y := s.w, s.h
scratch := uint32(0)
count := uint32(x * y)
_, _, _ = procFillConsoleOutputAttribute.Call(
uintptr(s.out),
uintptr(attr),
uintptr(count),
pos.uintptr(),
uintptr(unsafe.Pointer(&scratch)))
_, _, _ = procFillConsoleOutputCharacter.Call(
uintptr(s.out),
uintptr(' '),
uintptr(count),
pos.uintptr(),
uintptr(unsafe.Pointer(&scratch)))
}
}
const (
// Input modes
modeExtendFlg uint32 = 0x0080
modeMouseEn = 0x0010
modeResizeEn = 0x0008
// modeCooked = 0x0001
// modeVtInput = 0x0200
// Output modes
modeCookedOut uint32 = 0x0001
modeVtOutput = 0x0004
modeNoAutoNL = 0x0008
modeUnderline = 0x0010 // ENABLE_LVB_GRID_WORLDWIDE, needed for underlines
// modeWrapEOL = 0x0002
)
func (s *cScreen) setInMode(mode uint32) {
_, _, _ = procSetConsoleMode.Call(
uintptr(s.in),
uintptr(mode))
}
func (s *cScreen) setOutMode(mode uint32) {
_, _, _ = procSetConsoleMode.Call(
uintptr(s.out),
uintptr(mode))
}
func (s *cScreen) getInMode(v *uint32) {
_, _, _ = procGetConsoleMode.Call(
uintptr(s.in),
uintptr(unsafe.Pointer(v)))
}
func (s *cScreen) getOutMode(v *uint32) {
_, _, _ = procGetConsoleMode.Call(
uintptr(s.out),
uintptr(unsafe.Pointer(v)))
}
func (s *cScreen) SetStyle(style Style) {
s.Lock()
s.style = style
s.Unlock()
}
// No fallback rune support, since we have Unicode. Yay!
func (s *cScreen) RegisterRuneFallback(_ rune, _ string) {
}
func (s *cScreen) UnregisterRuneFallback(_ rune) {
}
func (s *cScreen) CanDisplay(_ rune, _ bool) bool {
// We presume we can display anything -- we're Unicode.
// (Sadly this not precisely true. Combining characters are especially
// poorly supported under Windows.)
return true
}
func (s *cScreen) HasMouse() bool {
return true
}
func (s *cScreen) Resize(int, int, int, int) {}
func (s *cScreen) HasKey(k Key) bool {
// Microsoft has codes for some keys, but they are unusual,
// so we don't include them. We include all the typical
// 101, 105 key layout keys.
valid := map[Key]bool{
KeyBackspace: true,
KeyTab: true,
KeyEscape: true,
KeyPause: true,
KeyPrint: true,
KeyPgUp: true,
KeyPgDn: true,
KeyEnter: true,
KeyEnd: true,
KeyHome: true,
KeyLeft: true,
KeyUp: true,
KeyRight: true,
KeyDown: true,
KeyInsert: true,
KeyDelete: true,
KeyF1: true,
KeyF2: true,
KeyF3: true,
KeyF4: true,
KeyF5: true,
KeyF6: true,
KeyF7: true,
KeyF8: true,
KeyF9: true,
KeyF10: true,
KeyF11: true,
KeyF12: true,
KeyRune: true,
}
return valid[k]
}
func (s *cScreen) Beep() error {
// A simple beep. If the sound card is not available, the sound is generated
// using the speaker.
//
// Reference:
// https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-messagebeep
const simpleBeep = 0xffffffff
if rv, _, err := procMessageBeep.Call(simpleBeep); rv == 0 {
return err
}
return nil
}
func (s *cScreen) Suspend() error {
s.disengage()
return nil
}
func (s *cScreen) Resume() error {
return s.engage()
}
func (s *cScreen) Tty() (Tty, bool) {
return nil, false
}
func (s *cScreen) GetCells() *CellBuffer {
return &s.cells
}
func (s *cScreen) EventQ() chan Event {
return s.eventQ
}
func (s *cScreen) StopQ() <-chan struct{} {
return s.quit
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/charset_stub.go | vendor/github.com/gdamore/tcell/v2/charset_stub.go | //go:build plan9 || nacl
// +build plan9 nacl
// Copyright 2015 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 tcell
func getCharset() string {
return ""
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/cell.go | vendor/github.com/gdamore/tcell/v2/cell.go | // Copyright 2024 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 tcell
import (
"os"
"reflect"
runewidth "github.com/mattn/go-runewidth"
)
type cell struct {
currMain rune
currComb []rune
currStyle Style
lastMain rune
lastStyle Style
lastComb []rune
width int
lock bool
}
// CellBuffer represents a two-dimensional array of character cells.
// This is primarily intended for use by Screen implementors; it
// contains much of the common code they need. To create one, just
// declare a variable of its type; no explicit initialization is necessary.
//
// CellBuffer is not thread safe.
type CellBuffer struct {
w int
h int
cells []cell
}
// SetContent sets the contents (primary rune, combining runes,
// and style) for a cell at a given location. If the background or
// foreground of the style is set to ColorNone, then the respective
// color is left un changed.
func (cb *CellBuffer) SetContent(x int, y int,
mainc rune, combc []rune, style Style,
) {
if x >= 0 && y >= 0 && x < cb.w && y < cb.h {
c := &cb.cells[(y*cb.w)+x]
// Wide characters: we want to mark the "wide" cells
// dirty as well as the base cell, to make sure we consider
// both cells as dirty together. We only need to do this
// if we're changing content
if (c.width > 0) && (mainc != c.currMain || !reflect.DeepEqual(combc, c.currComb)) {
for i := 0; i < c.width; i++ {
cb.SetDirty(x+i, y, true)
}
}
c.currComb = append([]rune{}, combc...)
if c.currMain != mainc {
c.width = runewidth.RuneWidth(mainc)
}
c.currMain = mainc
if style.fg == ColorNone {
style.fg = c.currStyle.fg
}
if style.bg == ColorNone {
style.bg = c.currStyle.bg
}
c.currStyle = style
}
}
// GetContent returns the contents of a character cell, including the
// primary rune, any combining character runes (which will usually be
// nil), the style, and the display width in cells. (The width can be
// either 1, normally, or 2 for East Asian full-width characters.)
func (cb *CellBuffer) GetContent(x, y int) (rune, []rune, Style, int) {
var mainc rune
var combc []rune
var style Style
var width int
if x >= 0 && y >= 0 && x < cb.w && y < cb.h {
c := &cb.cells[(y*cb.w)+x]
mainc, combc, style = c.currMain, c.currComb, c.currStyle
if width = c.width; width == 0 || mainc < ' ' {
width = 1
mainc = ' '
}
}
return mainc, combc, style, width
}
// Size returns the (width, height) in cells of the buffer.
func (cb *CellBuffer) Size() (int, int) {
return cb.w, cb.h
}
// Invalidate marks all characters within the buffer as dirty.
func (cb *CellBuffer) Invalidate() {
for i := range cb.cells {
cb.cells[i].lastMain = rune(0)
}
}
// Dirty checks if a character at the given location needs to be
// refreshed on the physical display. This returns true if the cell
// content is different since the last time it was marked clean.
func (cb *CellBuffer) Dirty(x, y int) bool {
if x >= 0 && y >= 0 && x < cb.w && y < cb.h {
c := &cb.cells[(y*cb.w)+x]
if c.lock {
return false
}
if c.lastMain == rune(0) {
return true
}
if c.lastMain != c.currMain {
return true
}
if c.lastStyle != c.currStyle {
return true
}
if len(c.lastComb) != len(c.currComb) {
return true
}
for i := range c.lastComb {
if c.lastComb[i] != c.currComb[i] {
return true
}
}
}
return false
}
// SetDirty is normally used to indicate that a cell has
// been displayed (in which case dirty is false), or to manually
// force a cell to be marked dirty.
func (cb *CellBuffer) SetDirty(x, y int, dirty bool) {
if x >= 0 && y >= 0 && x < cb.w && y < cb.h {
c := &cb.cells[(y*cb.w)+x]
if dirty {
c.lastMain = rune(0)
} else {
if c.currMain == rune(0) {
c.currMain = ' '
}
c.lastMain = c.currMain
c.lastComb = c.currComb
c.lastStyle = c.currStyle
}
}
}
// LockCell locks a cell from being drawn, effectively marking it "clean" until
// the lock is removed. This can be used to prevent tcell from drawing a given
// cell, even if the underlying content has changed. For example, when drawing a
// sixel graphic directly to a TTY screen an implementer must lock the region
// underneath the graphic to prevent tcell from drawing on top of the graphic.
func (cb *CellBuffer) LockCell(x, y int) {
if x < 0 || y < 0 {
return
}
if x >= cb.w || y >= cb.h {
return
}
c := &cb.cells[(y*cb.w)+x]
c.lock = true
}
// UnlockCell removes a lock from the cell and marks it as dirty
func (cb *CellBuffer) UnlockCell(x, y int) {
if x < 0 || y < 0 {
return
}
if x >= cb.w || y >= cb.h {
return
}
c := &cb.cells[(y*cb.w)+x]
c.lock = false
cb.SetDirty(x, y, true)
}
// Resize is used to resize the cells array, with different dimensions,
// while preserving the original contents. The cells will be invalidated
// so that they can be redrawn.
func (cb *CellBuffer) Resize(w, h int) {
if cb.h == h && cb.w == w {
return
}
newc := make([]cell, w*h)
for y := 0; y < h && y < cb.h; y++ {
for x := 0; x < w && x < cb.w; x++ {
oc := &cb.cells[(y*cb.w)+x]
nc := &newc[(y*w)+x]
nc.currMain = oc.currMain
nc.currComb = oc.currComb
nc.currStyle = oc.currStyle
nc.width = oc.width
nc.lastMain = rune(0)
}
}
cb.cells = newc
cb.h = h
cb.w = w
}
// Fill fills the entire cell buffer array with the specified character
// and style. Normally choose ' ' to clear the screen. This API doesn't
// support combining characters, or characters with a width larger than one.
// If either the foreground or background are ColorNone, then the respective
// color is unchanged.
func (cb *CellBuffer) Fill(r rune, style Style) {
for i := range cb.cells {
c := &cb.cells[i]
c.currMain = r
c.currComb = nil
cs := style
if cs.fg == ColorNone {
cs.fg = c.currStyle.fg
}
if cs.bg == ColorNone {
cs.bg = c.currStyle.bg
}
c.currStyle = cs
c.width = 1
}
}
var runeConfig *runewidth.Condition
func init() {
// The defaults for the runewidth package are poorly chosen for terminal
// applications. We however will honor the setting in the environment if
// it is set.
if os.Getenv("RUNEWIDTH_EASTASIAN") == "" {
runewidth.DefaultCondition.EastAsianWidth = false
}
// For performance reasons, we create a lookup table. However, some users
// might be more memory conscious. If that's you, set the TCELL_MINIMIZE
// environment variable.
if os.Getenv("TCELL_MINIMIZE") == "" {
runewidth.CreateLUT()
}
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/nonblock_bsd.go | vendor/github.com/gdamore/tcell/v2/nonblock_bsd.go | // Copyright 2021 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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.
//go:build darwin || dragonfly || freebsd || netbsd || openbsd
// +build darwin dragonfly freebsd netbsd openbsd
package tcell
import (
"syscall"
"golang.org/x/sys/unix"
)
// BSD systems use TIOC style ioctls.
// tcSetBufParams is used by the tty driver on UNIX systems to configure the
// buffering parameters (minimum character count and minimum wait time in msec.)
// This also waits for output to drain first.
func tcSetBufParams(fd int, vMin uint8, vTime uint8) error {
_ = syscall.SetNonblock(fd, true)
tio, err := unix.IoctlGetTermios(fd, unix.TIOCGETA)
if err != nil {
return err
}
tio.Cc[unix.VMIN] = vMin
tio.Cc[unix.VTIME] = vTime
if err = unix.IoctlSetTermios(fd, unix.TIOCSETAW, tio); err != nil {
return err
}
return nil
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/attr.go | vendor/github.com/gdamore/tcell/v2/attr.go | // Copyright 2020 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 tcell
// AttrMask represents a mask of text attributes, apart from color.
// Note that support for attributes may vary widely across terminals.
type AttrMask int
// Attributes are not colors, but affect the display of text. They can
// be combined.
const (
AttrBold AttrMask = 1 << iota
AttrBlink
AttrReverse
AttrUnderline
AttrDim
AttrItalic
AttrStrikeThrough
AttrInvalid // Mark the style or attributes invalid
AttrNone AttrMask = 0 // Just normal text.
)
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/event.go | vendor/github.com/gdamore/tcell/v2/event.go | // Copyright 2015 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 tcell
import (
"time"
)
// Event is a generic interface used for passing around Events.
// Concrete types follow.
type Event interface {
// When reports the time when the event was generated.
When() time.Time
}
// EventTime is a simple base event class, suitable for easy reuse.
// It can be used to deliver actual timer events as well.
type EventTime struct {
when time.Time
}
// When returns the time stamp when the event occurred.
func (e *EventTime) When() time.Time {
return e.when
}
// SetEventTime sets the time of occurrence for the event.
func (e *EventTime) SetEventTime(t time.Time) {
e.when = t
}
// SetEventNow sets the time of occurrence for the event to the current time.
func (e *EventTime) SetEventNow() {
e.SetEventTime(time.Now())
}
// EventHandler is anything that handles events. If the handler has
// consumed the event, it should return true. False otherwise.
type EventHandler interface {
HandleEvent(Event) bool
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/style.go | vendor/github.com/gdamore/tcell/v2/style.go | // Copyright 2022 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 tcell
// Style represents a complete text style, including both foreground color,
// background color, and additional attributes such as "bold" or "underline".
//
// Note that not all terminals can display all colors or attributes, and
// many might have specific incompatibilities between specific attributes
// and color combinations.
//
// To use Style, just declare a variable of its type.
type Style struct {
fg Color
bg Color
attrs AttrMask
url string
urlId string
}
// StyleDefault represents a default style, based upon the context.
// It is the zero value.
var StyleDefault Style
// styleInvalid is just an arbitrary invalid style used internally.
var styleInvalid = Style{attrs: AttrInvalid}
// Foreground returns a new style based on s, with the foreground color set
// as requested. ColorDefault can be used to select the global default.
func (s Style) Foreground(c Color) Style {
return Style{
fg: c,
bg: s.bg,
attrs: s.attrs,
url: s.url,
urlId: s.urlId,
}
}
// Background returns a new style based on s, with the background color set
// as requested. ColorDefault can be used to select the global default.
func (s Style) Background(c Color) Style {
return Style{
fg: s.fg,
bg: c,
attrs: s.attrs,
url: s.url,
urlId: s.urlId,
}
}
// Decompose breaks a style up, returning the foreground, background,
// and other attributes. The URL if set is not included.
func (s Style) Decompose() (fg Color, bg Color, attr AttrMask) {
return s.fg, s.bg, s.attrs
}
func (s Style) setAttrs(attrs AttrMask, on bool) Style {
if on {
return Style{
fg: s.fg,
bg: s.bg,
attrs: s.attrs | attrs,
url: s.url,
urlId: s.urlId,
}
}
return Style{
fg: s.fg,
bg: s.bg,
attrs: s.attrs &^ attrs,
url: s.url,
urlId: s.urlId,
}
}
// Normal returns the style with all attributes disabled.
func (s Style) Normal() Style {
return Style{
fg: s.fg,
bg: s.bg,
}
}
// Bold returns a new style based on s, with the bold attribute set
// as requested.
func (s Style) Bold(on bool) Style {
return s.setAttrs(AttrBold, on)
}
// Blink returns a new style based on s, with the blink attribute set
// as requested.
func (s Style) Blink(on bool) Style {
return s.setAttrs(AttrBlink, on)
}
// Dim returns a new style based on s, with the dim attribute set
// as requested.
func (s Style) Dim(on bool) Style {
return s.setAttrs(AttrDim, on)
}
// Italic returns a new style based on s, with the italic attribute set
// as requested.
func (s Style) Italic(on bool) Style {
return s.setAttrs(AttrItalic, on)
}
// Reverse returns a new style based on s, with the reverse attribute set
// as requested. (Reverse usually changes the foreground and background
// colors.)
func (s Style) Reverse(on bool) Style {
return s.setAttrs(AttrReverse, on)
}
// Underline returns a new style based on s, with the underline attribute set
// as requested.
func (s Style) Underline(on bool) Style {
return s.setAttrs(AttrUnderline, on)
}
// StrikeThrough sets strikethrough mode.
func (s Style) StrikeThrough(on bool) Style {
return s.setAttrs(AttrStrikeThrough, on)
}
// Attributes returns a new style based on s, with its attributes set as
// specified.
func (s Style) Attributes(attrs AttrMask) Style {
return Style{
fg: s.fg,
bg: s.bg,
attrs: attrs,
url: s.url,
urlId: s.urlId,
}
}
// Url returns a style with the Url set. If the provided Url is not empty,
// and the terminal supports it, text will typically be marked up as a clickable
// link to that Url. If the Url is empty, then this mode is turned off.
func (s Style) Url(url string) Style {
return Style{
fg: s.fg,
bg: s.bg,
attrs: s.attrs,
url: url,
urlId: s.urlId,
}
}
// UrlId returns a style with the UrlId set. If the provided UrlId is not empty,
// any marked up Url with this style will be given the UrlId also. If the
// terminal supports it, any text with the same UrlId will be grouped as if it
// were one Url, even if it spans multiple lines.
func (s Style) UrlId(id string) Style {
return Style{
fg: s.fg,
bg: s.bg,
attrs: s.attrs,
url: s.url,
urlId: "id=" + id,
}
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/doc.go | vendor/github.com/gdamore/tcell/v2/doc.go | // Copyright 2018 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 tcell provides a lower-level, portable API for building
// programs that interact with terminals or consoles. It works with
// both common (and many uncommon!) terminals or terminal emulators,
// and Windows console implementations.
//
// It provides support for up to 256 colors, text attributes, and box drawing
// elements. A database of terminals built from a real terminfo database
// is provided, along with code to generate new database entries.
//
// Tcell offers very rich support for mice, dependent upon the terminal
// of course. (Windows, XTerm, and iTerm 2 are known to work very well.)
//
// If the environment is not Unicode by default, such as an ISO8859 based
// locale or GB18030, Tcell can convert input and output, so that your
// terminal can operate in whatever locale is most convenient, while the
// application program can just assume "everything is UTF-8". Reasonable
// defaults are used for updating characters to something suitable for
// display. Unicode box drawing characters will be converted to use the
// alternate character set of your terminal, if native conversions are
// not available. If no ACS is available, then some ASCII fallbacks will
// be used.
//
// Note that support for non-UTF-8 locales (other than C) must be enabled
// by the application using RegisterEncoding() -- we don't have them all
// enabled by default to avoid bloating the application unnecessarily.
// (These days UTF-8 is good enough for almost everyone, and nobody should
// be using legacy locales anymore.) Also, actual glyphs for various code
// point will only be displayed if your terminal or emulator (or the font
// the emulator is using) supports them.
//
// A rich set of key codes is supported, with support for up to 65 function
// keys, and various other special keys.
package tcell
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/encoding.go | vendor/github.com/gdamore/tcell/v2/encoding.go | // Copyright 2022 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 tcell
import (
"strings"
"sync"
"golang.org/x/text/encoding"
gencoding "github.com/gdamore/encoding"
)
var encodings map[string]encoding.Encoding
var encodingLk sync.Mutex
var encodingFallback EncodingFallback = EncodingFallbackFail
// RegisterEncoding may be called by the application to register an encoding.
// The presence of additional encodings will facilitate application usage with
// terminal environments where the I/O subsystem does not support Unicode.
//
// Windows systems use Unicode natively, and do not need any of the encoding
// subsystem when using Windows Console screens.
//
// Please see the Go documentation for golang.org/x/text/encoding -- most of
// the common ones exist already as stock variables. For example, ISO8859-15
// can be registered using the following code:
//
// import "golang.org/x/text/encoding/charmap"
//
// ...
// RegisterEncoding("ISO8859-15", charmap.ISO8859_15)
//
// Aliases can be registered as well, for example "8859-15" could be an alias
// for "ISO8859-15".
//
// For POSIX systems, this package will check the environment variables
// LC_ALL, LC_CTYPE, and LANG (in that order) to determine the character set.
// These are expected to have the following pattern:
//
// $language[.$codeset[@$variant]
//
// We extract only the $codeset part, which will usually be something like
// UTF-8 or ISO8859-15 or KOI8-R. Note that if the locale is either "POSIX"
// or "C", then we assume US-ASCII (the POSIX 'portable character set'
// and assume all other characters are somehow invalid.)
//
// Modern POSIX systems and terminal emulators may use UTF-8, and for those
// systems, this API is also unnecessary. For example, Darwin (MacOS X) and
// modern Linux running modern xterm generally will out of the box without
// any of this. Use of UTF-8 is recommended when possible, as it saves
// quite a lot processing overhead.
//
// Note that some encodings are quite large (for example GB18030 which is a
// superset of Unicode) and so the application size can be expected to
// increase quite a bit as each encoding is added.
// The East Asian encodings have been seen to add 100-200K per encoding to the
// size of the resulting binary.
func RegisterEncoding(charset string, enc encoding.Encoding) {
encodingLk.Lock()
charset = strings.ToLower(charset)
encodings[charset] = enc
encodingLk.Unlock()
}
// EncodingFallback describes how the system behaves when the locale
// requires a character set that we do not support. The system always
// supports UTF-8 and US-ASCII. On Windows consoles, UTF-16LE is also
// supported automatically. Other character sets must be added using the
// RegisterEncoding API. (A large group of nearly all of them can be
// added using the RegisterAll function in the encoding sub package.)
type EncodingFallback int
const (
// EncodingFallbackFail behavior causes GetEncoding to fail
// when it cannot find an encoding.
EncodingFallbackFail = iota
// EncodingFallbackASCII behavior causes GetEncoding to fall back
// to a 7-bit ASCII encoding, if no other encoding can be found.
EncodingFallbackASCII
// EncodingFallbackUTF8 behavior causes GetEncoding to assume
// UTF8 can pass unmodified upon failure. Note that this behavior
// is not recommended, unless you are sure your terminal can cope
// with real UTF8 sequences.
EncodingFallbackUTF8
)
// SetEncodingFallback changes the behavior of GetEncoding when a suitable
// encoding is not found. The default is EncodingFallbackFail, which
// causes GetEncoding to simply return nil.
func SetEncodingFallback(fb EncodingFallback) {
encodingLk.Lock()
encodingFallback = fb
encodingLk.Unlock()
}
// GetEncoding is used by Screen implementors who want to locate an encoding
// for the given character set name. Note that this will return nil for
// either the Unicode (UTF-8) or ASCII encodings, since we don't use
// encodings for them but instead have our own native methods.
func GetEncoding(charset string) encoding.Encoding {
charset = strings.ToLower(charset)
encodingLk.Lock()
defer encodingLk.Unlock()
if enc, ok := encodings[charset]; ok {
return enc
}
switch encodingFallback {
case EncodingFallbackASCII:
return gencoding.ASCII
case EncodingFallbackUTF8:
return encoding.Nop
}
return nil
}
func init() {
// We always support UTF-8 and ASCII.
encodings = make(map[string]encoding.Encoding)
encodings["utf-8"] = gencoding.UTF8
encodings["utf8"] = gencoding.UTF8
encodings["us-ascii"] = gencoding.ASCII
encodings["ascii"] = gencoding.ASCII
encodings["iso646"] = gencoding.ASCII
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/terms_default.go | vendor/github.com/gdamore/tcell/v2/terms_default.go | //go:build !tcell_minimal
// +build !tcell_minimal
// Copyright 2019 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 tcell
import (
// This imports the default terminal entries. To disable, use the
// tcell_minimal build tag.
_ "github.com/gdamore/tcell/v2/terminfo/extended"
)
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/tty_unix.go | vendor/github.com/gdamore/tcell/v2/tty_unix.go | // Copyright 2021 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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.
//go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos
// +build aix darwin dragonfly freebsd linux netbsd openbsd solaris zos
package tcell
import (
"errors"
"fmt"
"os"
"os/signal"
"strconv"
"sync"
"syscall"
"time"
"golang.org/x/sys/unix"
"golang.org/x/term"
)
// devTty is an implementation of the Tty API based upon /dev/tty.
type devTty struct {
fd int
f *os.File
of *os.File // the first open of /dev/tty
saved *term.State
sig chan os.Signal
cb func()
stopQ chan struct{}
dev string
wg sync.WaitGroup
l sync.Mutex
}
func (tty *devTty) Read(b []byte) (int, error) {
return tty.f.Read(b)
}
func (tty *devTty) Write(b []byte) (int, error) {
return tty.f.Write(b)
}
func (tty *devTty) Close() error {
return tty.f.Close()
}
func (tty *devTty) Start() error {
tty.l.Lock()
defer tty.l.Unlock()
// We open another copy of /dev/tty. This is a workaround for unusual behavior
// observed in macOS, apparently caused when a subshell (for example) closes our
// own tty device (when it exits for example). Getting a fresh new one seems to
// resolve the problem. (We believe this is a bug in the macOS tty driver that
// fails to account for dup() references to the same file before applying close()
// related behaviors to the tty.) We're also holding the original copy we opened
// since closing that might have deleterious effects as well. The upshot is that
// we will have up to two separate file handles open on /dev/tty. (Note that when
// using stdin/stdout instead of /dev/tty this problem is not observed.)
var err error
if tty.f, err = os.OpenFile(tty.dev, os.O_RDWR, 0); err != nil {
return err
}
if !term.IsTerminal(tty.fd) {
return errors.New("device is not a terminal")
}
_ = tty.f.SetReadDeadline(time.Time{})
saved, err := term.MakeRaw(tty.fd) // also sets vMin and vTime
if err != nil {
return err
}
tty.saved = saved
tty.stopQ = make(chan struct{})
tty.wg.Add(1)
go func(stopQ chan struct{}) {
defer tty.wg.Done()
for {
select {
case <-tty.sig:
tty.l.Lock()
cb := tty.cb
tty.l.Unlock()
if cb != nil {
cb()
}
case <-stopQ:
return
}
}
}(tty.stopQ)
signal.Notify(tty.sig, syscall.SIGWINCH)
return nil
}
func (tty *devTty) Drain() error {
_ = tty.f.SetReadDeadline(time.Now())
if err := tcSetBufParams(tty.fd, 0, 0); err != nil {
return err
}
return nil
}
func (tty *devTty) Stop() error {
tty.l.Lock()
if err := term.Restore(tty.fd, tty.saved); err != nil {
tty.l.Unlock()
return err
}
_ = tty.f.SetReadDeadline(time.Now())
signal.Stop(tty.sig)
close(tty.stopQ)
tty.l.Unlock()
tty.wg.Wait()
// close our tty device -- we'll get another one if we Start again later.
_ = tty.f.Close()
return nil
}
func (tty *devTty) WindowSize() (WindowSize, error) {
size := WindowSize{}
ws, err := unix.IoctlGetWinsize(tty.fd, unix.TIOCGWINSZ)
if err != nil {
return size, err
}
w := int(ws.Col)
h := int(ws.Row)
if w == 0 {
w, _ = strconv.Atoi(os.Getenv("COLUMNS"))
}
if w == 0 {
w = 80 // default
}
if h == 0 {
h, _ = strconv.Atoi(os.Getenv("LINES"))
}
if h == 0 {
h = 25 // default
}
size.Width = w
size.Height = h
size.PixelWidth = int(ws.Xpixel)
size.PixelHeight = int(ws.Ypixel)
return size, nil
}
func (tty *devTty) NotifyResize(cb func()) {
tty.l.Lock()
tty.cb = cb
tty.l.Unlock()
}
// NewDevTty opens a /dev/tty based Tty.
func NewDevTty() (Tty, error) {
return NewDevTtyFromDev("/dev/tty")
}
// NewDevTtyFromDev opens a tty device given a path. This can be useful to bind to other nodes.
func NewDevTtyFromDev(dev string) (Tty, error) {
tty := &devTty{
dev: dev,
sig: make(chan os.Signal),
}
var err error
if tty.of, err = os.OpenFile(dev, os.O_RDWR, 0); err != nil {
return nil, err
}
tty.fd = int(tty.of.Fd())
if !term.IsTerminal(tty.fd) {
_ = tty.f.Close()
return nil, errors.New("not a terminal")
}
if tty.saved, err = term.GetState(tty.fd); err != nil {
_ = tty.f.Close()
return nil, fmt.Errorf("failed to get state: %w", err)
}
return tty, nil
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/key.go | vendor/github.com/gdamore/tcell/v2/key.go | // Copyright 2016 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 tcell
import (
"fmt"
"strings"
"time"
)
// EventKey represents a key press. Usually this is a key press followed
// by a key release, but since terminal programs don't have a way to report
// key release events, we usually get just one event. If a key is held down
// then the terminal may synthesize repeated key presses at some predefined
// rate. We have no control over that, nor visibility into it.
//
// In some cases, we can have a modifier key, such as ModAlt, that can be
// generated with a key press. (This usually is represented by having the
// high bit set, or in some cases, by sending an ESC prior to the rune.)
//
// If the value of Key() is KeyRune, then the actual key value will be
// available with the Rune() method. This will be the case for most keys.
// In most situations, the modifiers will not be set. For example, if the
// rune is 'A', this will be reported without the ModShift bit set, since
// really can't tell if the Shift key was pressed (it might have been CAPSLOCK,
// or a terminal that only can send capitals, or keyboard with separate
// capital letters from lower case letters).
//
// Generally, terminal applications have far less visibility into keyboard
// activity than graphical applications. Hence, they should avoid depending
// overly much on availability of modifiers, or the availability of any
// specific keys.
type EventKey struct {
t time.Time
mod ModMask
key Key
ch rune
}
// When returns the time when this Event was created, which should closely
// match the time when the key was pressed.
func (ev *EventKey) When() time.Time {
return ev.t
}
// Rune returns the rune corresponding to the key press, if it makes sense.
// The result is only defined if the value of Key() is KeyRune.
func (ev *EventKey) Rune() rune {
return ev.ch
}
// Key returns a virtual key code. We use this to identify specific key
// codes, such as KeyEnter, etc. Most control and function keys are reported
// with unique Key values. Normal alphanumeric and punctuation keys will
// generally return KeyRune here; the specific key can be further decoded
// using the Rune() function.
func (ev *EventKey) Key() Key {
return ev.key
}
// Modifiers returns the modifiers that were present with the key press. Note
// that not all platforms and terminals support this equally well, and some
// cases we will not not know for sure. Hence, applications should avoid
// using this in most circumstances.
func (ev *EventKey) Modifiers() ModMask {
return ev.mod
}
// KeyNames holds the written names of special keys. Useful to echo back a key
// name, or to look up a key from a string value.
var KeyNames = map[Key]string{
KeyEnter: "Enter",
KeyBackspace: "Backspace",
KeyTab: "Tab",
KeyBacktab: "Backtab",
KeyEsc: "Esc",
KeyBackspace2: "Backspace2",
KeyDelete: "Delete",
KeyInsert: "Insert",
KeyUp: "Up",
KeyDown: "Down",
KeyLeft: "Left",
KeyRight: "Right",
KeyHome: "Home",
KeyEnd: "End",
KeyUpLeft: "UpLeft",
KeyUpRight: "UpRight",
KeyDownLeft: "DownLeft",
KeyDownRight: "DownRight",
KeyCenter: "Center",
KeyPgDn: "PgDn",
KeyPgUp: "PgUp",
KeyClear: "Clear",
KeyExit: "Exit",
KeyCancel: "Cancel",
KeyPause: "Pause",
KeyPrint: "Print",
KeyF1: "F1",
KeyF2: "F2",
KeyF3: "F3",
KeyF4: "F4",
KeyF5: "F5",
KeyF6: "F6",
KeyF7: "F7",
KeyF8: "F8",
KeyF9: "F9",
KeyF10: "F10",
KeyF11: "F11",
KeyF12: "F12",
KeyF13: "F13",
KeyF14: "F14",
KeyF15: "F15",
KeyF16: "F16",
KeyF17: "F17",
KeyF18: "F18",
KeyF19: "F19",
KeyF20: "F20",
KeyF21: "F21",
KeyF22: "F22",
KeyF23: "F23",
KeyF24: "F24",
KeyF25: "F25",
KeyF26: "F26",
KeyF27: "F27",
KeyF28: "F28",
KeyF29: "F29",
KeyF30: "F30",
KeyF31: "F31",
KeyF32: "F32",
KeyF33: "F33",
KeyF34: "F34",
KeyF35: "F35",
KeyF36: "F36",
KeyF37: "F37",
KeyF38: "F38",
KeyF39: "F39",
KeyF40: "F40",
KeyF41: "F41",
KeyF42: "F42",
KeyF43: "F43",
KeyF44: "F44",
KeyF45: "F45",
KeyF46: "F46",
KeyF47: "F47",
KeyF48: "F48",
KeyF49: "F49",
KeyF50: "F50",
KeyF51: "F51",
KeyF52: "F52",
KeyF53: "F53",
KeyF54: "F54",
KeyF55: "F55",
KeyF56: "F56",
KeyF57: "F57",
KeyF58: "F58",
KeyF59: "F59",
KeyF60: "F60",
KeyF61: "F61",
KeyF62: "F62",
KeyF63: "F63",
KeyF64: "F64",
KeyCtrlA: "Ctrl-A",
KeyCtrlB: "Ctrl-B",
KeyCtrlC: "Ctrl-C",
KeyCtrlD: "Ctrl-D",
KeyCtrlE: "Ctrl-E",
KeyCtrlF: "Ctrl-F",
KeyCtrlG: "Ctrl-G",
KeyCtrlJ: "Ctrl-J",
KeyCtrlK: "Ctrl-K",
KeyCtrlL: "Ctrl-L",
KeyCtrlN: "Ctrl-N",
KeyCtrlO: "Ctrl-O",
KeyCtrlP: "Ctrl-P",
KeyCtrlQ: "Ctrl-Q",
KeyCtrlR: "Ctrl-R",
KeyCtrlS: "Ctrl-S",
KeyCtrlT: "Ctrl-T",
KeyCtrlU: "Ctrl-U",
KeyCtrlV: "Ctrl-V",
KeyCtrlW: "Ctrl-W",
KeyCtrlX: "Ctrl-X",
KeyCtrlY: "Ctrl-Y",
KeyCtrlZ: "Ctrl-Z",
KeyCtrlSpace: "Ctrl-Space",
KeyCtrlUnderscore: "Ctrl-_",
KeyCtrlRightSq: "Ctrl-]",
KeyCtrlBackslash: "Ctrl-\\",
KeyCtrlCarat: "Ctrl-^",
}
// Name returns a printable value or the key stroke. This can be used
// when printing the event, for example.
func (ev *EventKey) Name() string {
s := ""
m := []string{}
if ev.mod&ModShift != 0 {
m = append(m, "Shift")
}
if ev.mod&ModAlt != 0 {
m = append(m, "Alt")
}
if ev.mod&ModMeta != 0 {
m = append(m, "Meta")
}
if ev.mod&ModCtrl != 0 {
m = append(m, "Ctrl")
}
ok := false
if s, ok = KeyNames[ev.key]; !ok {
if ev.key == KeyRune {
s = "Rune[" + string(ev.ch) + "]"
} else {
s = fmt.Sprintf("Key[%d,%d]", ev.key, int(ev.ch))
}
}
if len(m) != 0 {
if ev.mod&ModCtrl != 0 && strings.HasPrefix(s, "Ctrl-") {
s = s[5:]
}
return fmt.Sprintf("%s+%s", strings.Join(m, "+"), s)
}
return s
}
// NewEventKey attempts to create a suitable event. It parses the various
// ASCII control sequences if KeyRune is passed for Key, but if the caller
// has more precise information it should set that specifically. Callers
// that aren't sure about modifier state (most) should just pass ModNone.
func NewEventKey(k Key, ch rune, mod ModMask) *EventKey {
if k == KeyRune && (ch < ' ' || ch == 0x7f) {
// Turn specials into proper key codes. This is for
// control characters and the DEL.
k = Key(ch)
if mod == ModNone && ch < ' ' {
switch Key(ch) {
case KeyBackspace, KeyTab, KeyEsc, KeyEnter:
// these keys are directly typeable without CTRL
default:
// most likely entered with a CTRL keypress
mod = ModCtrl
}
}
}
return &EventKey{t: time.Now(), key: k, ch: ch, mod: mod}
}
// ModMask is a mask of modifier keys. Note that it will not always be
// possible to report modifier keys.
type ModMask int16
// These are the modifiers keys that can be sent either with a key press,
// or a mouse event. Note that as of now, due to the confusion associated
// with Meta, and the lack of support for it on many/most platforms, the
// current implementations never use it. Instead, they use ModAlt, even for
// events that could possibly have been distinguished from ModAlt.
const (
ModShift ModMask = 1 << iota
ModCtrl
ModAlt
ModMeta
ModNone ModMask = 0
)
// Key is a generic value for representing keys, and especially special
// keys (function keys, cursor movement keys, etc.) For normal keys, like
// ASCII letters, we use KeyRune, and then expect the application to
// inspect the Rune() member of the EventKey.
type Key int16
// This is the list of named keys. KeyRune is special however, in that it is
// a place holder key indicating that a printable character was sent. The
// actual value of the rune will be transported in the Rune of the associated
// EventKey.
const (
KeyRune Key = iota + 256
KeyUp
KeyDown
KeyRight
KeyLeft
KeyUpLeft
KeyUpRight
KeyDownLeft
KeyDownRight
KeyCenter
KeyPgUp
KeyPgDn
KeyHome
KeyEnd
KeyInsert
KeyDelete
KeyHelp
KeyExit
KeyClear
KeyCancel
KeyPrint
KeyPause
KeyBacktab
KeyF1
KeyF2
KeyF3
KeyF4
KeyF5
KeyF6
KeyF7
KeyF8
KeyF9
KeyF10
KeyF11
KeyF12
KeyF13
KeyF14
KeyF15
KeyF16
KeyF17
KeyF18
KeyF19
KeyF20
KeyF21
KeyF22
KeyF23
KeyF24
KeyF25
KeyF26
KeyF27
KeyF28
KeyF29
KeyF30
KeyF31
KeyF32
KeyF33
KeyF34
KeyF35
KeyF36
KeyF37
KeyF38
KeyF39
KeyF40
KeyF41
KeyF42
KeyF43
KeyF44
KeyF45
KeyF46
KeyF47
KeyF48
KeyF49
KeyF50
KeyF51
KeyF52
KeyF53
KeyF54
KeyF55
KeyF56
KeyF57
KeyF58
KeyF59
KeyF60
KeyF61
KeyF62
KeyF63
KeyF64
)
const (
// These key codes are used internally, and will never appear to applications.
keyPasteStart Key = iota + 16384
keyPasteEnd
)
// These are the control keys. Note that they overlap with other keys,
// perhaps. For example, KeyCtrlH is the same as KeyBackspace.
const (
KeyCtrlSpace Key = iota
KeyCtrlA
KeyCtrlB
KeyCtrlC
KeyCtrlD
KeyCtrlE
KeyCtrlF
KeyCtrlG
KeyCtrlH
KeyCtrlI
KeyCtrlJ
KeyCtrlK
KeyCtrlL
KeyCtrlM
KeyCtrlN
KeyCtrlO
KeyCtrlP
KeyCtrlQ
KeyCtrlR
KeyCtrlS
KeyCtrlT
KeyCtrlU
KeyCtrlV
KeyCtrlW
KeyCtrlX
KeyCtrlY
KeyCtrlZ
KeyCtrlLeftSq // Escape
KeyCtrlBackslash
KeyCtrlRightSq
KeyCtrlCarat
KeyCtrlUnderscore
)
// Special values - these are fixed in an attempt to make it more likely
// that aliases will encode the same way.
// These are the defined ASCII values for key codes. They generally match
// with KeyCtrl values.
const (
KeyNUL Key = iota
KeySOH
KeySTX
KeyETX
KeyEOT
KeyENQ
KeyACK
KeyBEL
KeyBS
KeyTAB
KeyLF
KeyVT
KeyFF
KeyCR
KeySO
KeySI
KeyDLE
KeyDC1
KeyDC2
KeyDC3
KeyDC4
KeyNAK
KeySYN
KeyETB
KeyCAN
KeyEM
KeySUB
KeyESC
KeyFS
KeyGS
KeyRS
KeyUS
KeyDEL Key = 0x7F
)
// These keys are aliases for other names.
const (
KeyBackspace = KeyBS
KeyTab = KeyTAB
KeyEsc = KeyESC
KeyEscape = KeyESC
KeyEnter = KeyCR
KeyBackspace2 = KeyDEL
)
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/tscreen.go | vendor/github.com/gdamore/tcell/v2/tscreen.go | // Copyright 2024 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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.
//go:build !(js && wasm)
// +build !js !wasm
package tcell
import (
"bytes"
"errors"
"io"
"os"
"strconv"
"strings"
"sync"
"time"
"unicode/utf8"
"golang.org/x/term"
"golang.org/x/text/transform"
"github.com/gdamore/tcell/v2/terminfo"
// import the stock terminals
_ "github.com/gdamore/tcell/v2/terminfo/base"
)
// NewTerminfoScreen returns a Screen that uses the stock TTY interface
// and POSIX terminal control, combined with a terminfo description taken from
// the $TERM environment variable. It returns an error if the terminal
// is not supported for any reason.
//
// For terminals that do not support dynamic resize events, the $LINES
// $COLUMNS environment variables can be set to the actual window size,
// otherwise defaults taken from the terminal database are used.
func NewTerminfoScreen() (Screen, error) {
return NewTerminfoScreenFromTty(nil)
}
// LookupTerminfo attempts to find a definition for the named $TERM falling
// back to attempting to parse the output from infocmp.
func LookupTerminfo(name string) (ti *terminfo.Terminfo, e error) {
ti, e = terminfo.LookupTerminfo(name)
if e != nil {
ti, e = loadDynamicTerminfo(name)
if e != nil {
return nil, e
}
terminfo.AddTerminfo(ti)
}
return
}
// NewTerminfoScreenFromTtyTerminfo returns a Screen using a custom Tty
// implementation and custom terminfo specification.
// If the passed in tty is nil, then a reasonable default (typically /dev/tty)
// is presumed, at least on UNIX hosts. (Windows hosts will typically fail this
// call altogether.)
// If passed terminfo is nil, then TERM environment variable is queried for
// terminal specification.
func NewTerminfoScreenFromTtyTerminfo(tty Tty, ti *terminfo.Terminfo) (s Screen, e error) {
if ti == nil {
ti, e = LookupTerminfo(os.Getenv("TERM"))
if e != nil {
return
}
}
t := &tScreen{ti: ti, tty: tty}
t.keyexist = make(map[Key]bool)
t.keycodes = make(map[string]*tKeyCode)
if len(ti.Mouse) > 0 {
t.mouse = []byte(ti.Mouse)
}
t.prepareKeys()
t.buildAcsMap()
t.resizeQ = make(chan bool, 1)
t.fallback = make(map[rune]string)
for k, v := range RuneFallbacks {
t.fallback[k] = v
}
return &baseScreen{screenImpl: t}, nil
}
// NewTerminfoScreenFromTty returns a Screen using a custom Tty implementation.
// If the passed in tty is nil, then a reasonable default (typically /dev/tty)
// is presumed, at least on UNIX hosts. (Windows hosts will typically fail this
// call altogether.)
func NewTerminfoScreenFromTty(tty Tty) (Screen, error) {
return NewTerminfoScreenFromTtyTerminfo(tty, nil)
}
// tKeyCode represents a combination of a key code and modifiers.
type tKeyCode struct {
key Key
mod ModMask
}
// tScreen represents a screen backed by a terminfo implementation.
type tScreen struct {
ti *terminfo.Terminfo
tty Tty
h int
w int
fini bool
cells CellBuffer
buffering bool // true if we are collecting writes to buf instead of sending directly to out
buf bytes.Buffer
curstyle Style
style Style
resizeQ chan bool
quit chan struct{}
keyexist map[Key]bool
keycodes map[string]*tKeyCode
keychan chan []byte
keytimer *time.Timer
keyexpire time.Time
cx int
cy int
mouse []byte
clear bool
cursorx int
cursory int
acs map[rune]string
charset string
encoder transform.Transformer
decoder transform.Transformer
fallback map[rune]string
colors map[Color]Color
palette []Color
truecolor bool
escaped bool
buttondn bool
finiOnce sync.Once
enablePaste string
disablePaste string
enterUrl string
exitUrl string
setWinSize string
enableFocus string
disableFocus string
cursorStyles map[CursorStyle]string
cursorStyle CursorStyle
saved *term.State
stopQ chan struct{}
eventQ chan Event
running bool
wg sync.WaitGroup
mouseFlags MouseFlags
pasteEnabled bool
focusEnabled bool
sync.Mutex
}
func (t *tScreen) Init() error {
if e := t.initialize(); e != nil {
return e
}
t.keychan = make(chan []byte, 10)
t.keytimer = time.NewTimer(time.Millisecond * 50)
t.charset = "UTF-8"
t.charset = getCharset()
if enc := GetEncoding(t.charset); enc != nil {
t.encoder = enc.NewEncoder()
t.decoder = enc.NewDecoder()
} else {
return ErrNoCharset
}
ti := t.ti
// environment overrides
w := ti.Columns
h := ti.Lines
if i, _ := strconv.Atoi(os.Getenv("LINES")); i != 0 {
h = i
}
if i, _ := strconv.Atoi(os.Getenv("COLUMNS")); i != 0 {
w = i
}
if t.ti.SetFgBgRGB != "" || t.ti.SetFgRGB != "" || t.ti.SetBgRGB != "" {
t.truecolor = true
}
// A user who wants to have his themes honored can
// set this environment variable.
if os.Getenv("TCELL_TRUECOLOR") == "disable" {
t.truecolor = false
}
nColors := t.nColors()
if nColors > 256 {
nColors = 256 // clip to reasonable limits
}
t.colors = make(map[Color]Color, nColors)
t.palette = make([]Color, nColors)
for i := 0; i < nColors; i++ {
t.palette[i] = Color(i) | ColorValid
// identity map for our builtin colors
t.colors[Color(i)|ColorValid] = Color(i) | ColorValid
}
t.quit = make(chan struct{})
t.eventQ = make(chan Event, 10)
t.Lock()
t.cx = -1
t.cy = -1
t.style = StyleDefault
t.cells.Resize(w, h)
t.cursorx = -1
t.cursory = -1
t.resize()
t.Unlock()
if err := t.engage(); err != nil {
return err
}
return nil
}
func (t *tScreen) prepareKeyMod(key Key, mod ModMask, val string) {
if val != "" {
// Do not override codes that already exist
if _, exist := t.keycodes[val]; !exist {
t.keyexist[key] = true
t.keycodes[val] = &tKeyCode{key: key, mod: mod}
}
}
}
func (t *tScreen) prepareKeyModReplace(key Key, replace Key, mod ModMask, val string) {
if val != "" {
// Do not override codes that already exist
if old, exist := t.keycodes[val]; !exist || old.key == replace {
t.keyexist[key] = true
t.keycodes[val] = &tKeyCode{key: key, mod: mod}
}
}
}
func (t *tScreen) prepareKeyModXTerm(key Key, val string) {
if strings.HasPrefix(val, "\x1b[") && strings.HasSuffix(val, "~") {
// Drop the trailing ~
val = val[:len(val)-1]
// These suffixes are calculated assuming Xterm style modifier suffixes.
// Please see https://invisible-island.net/xterm/ctlseqs/ctlseqs.pdf for
// more information (specifically "PC-Style Function Keys").
t.prepareKeyModReplace(key, key+12, ModShift, val+";2~")
t.prepareKeyModReplace(key, key+48, ModAlt, val+";3~")
t.prepareKeyModReplace(key, key+60, ModAlt|ModShift, val+";4~")
t.prepareKeyModReplace(key, key+24, ModCtrl, val+";5~")
t.prepareKeyModReplace(key, key+36, ModCtrl|ModShift, val+";6~")
t.prepareKeyMod(key, ModAlt|ModCtrl, val+";7~")
t.prepareKeyMod(key, ModShift|ModAlt|ModCtrl, val+";8~")
t.prepareKeyMod(key, ModMeta, val+";9~")
t.prepareKeyMod(key, ModMeta|ModShift, val+";10~")
t.prepareKeyMod(key, ModMeta|ModAlt, val+";11~")
t.prepareKeyMod(key, ModMeta|ModAlt|ModShift, val+";12~")
t.prepareKeyMod(key, ModMeta|ModCtrl, val+";13~")
t.prepareKeyMod(key, ModMeta|ModCtrl|ModShift, val+";14~")
t.prepareKeyMod(key, ModMeta|ModCtrl|ModAlt, val+";15~")
t.prepareKeyMod(key, ModMeta|ModCtrl|ModAlt|ModShift, val+";16~")
} else if strings.HasPrefix(val, "\x1bO") && len(val) == 3 {
val = val[2:]
t.prepareKeyModReplace(key, key+12, ModShift, "\x1b[1;2"+val)
t.prepareKeyModReplace(key, key+48, ModAlt, "\x1b[1;3"+val)
t.prepareKeyModReplace(key, key+24, ModCtrl, "\x1b[1;5"+val)
t.prepareKeyModReplace(key, key+36, ModCtrl|ModShift, "\x1b[1;6"+val)
t.prepareKeyModReplace(key, key+60, ModAlt|ModShift, "\x1b[1;4"+val)
t.prepareKeyMod(key, ModAlt|ModCtrl, "\x1b[1;7"+val)
t.prepareKeyMod(key, ModShift|ModAlt|ModCtrl, "\x1b[1;8"+val)
t.prepareKeyMod(key, ModMeta, "\x1b[1;9"+val)
t.prepareKeyMod(key, ModMeta|ModShift, "\x1b[1;10"+val)
t.prepareKeyMod(key, ModMeta|ModAlt, "\x1b[1;11"+val)
t.prepareKeyMod(key, ModMeta|ModAlt|ModShift, "\x1b[1;12"+val)
t.prepareKeyMod(key, ModMeta|ModCtrl, "\x1b[1;13"+val)
t.prepareKeyMod(key, ModMeta|ModCtrl|ModShift, "\x1b[1;14"+val)
t.prepareKeyMod(key, ModMeta|ModCtrl|ModAlt, "\x1b[1;15"+val)
t.prepareKeyMod(key, ModMeta|ModCtrl|ModAlt|ModShift, "\x1b[1;16"+val)
}
}
func (t *tScreen) prepareXtermModifiers() {
if t.ti.Modifiers != terminfo.ModifiersXTerm {
return
}
t.prepareKeyModXTerm(KeyRight, t.ti.KeyRight)
t.prepareKeyModXTerm(KeyLeft, t.ti.KeyLeft)
t.prepareKeyModXTerm(KeyUp, t.ti.KeyUp)
t.prepareKeyModXTerm(KeyDown, t.ti.KeyDown)
t.prepareKeyModXTerm(KeyInsert, t.ti.KeyInsert)
t.prepareKeyModXTerm(KeyDelete, t.ti.KeyDelete)
t.prepareKeyModXTerm(KeyPgUp, t.ti.KeyPgUp)
t.prepareKeyModXTerm(KeyPgDn, t.ti.KeyPgDn)
t.prepareKeyModXTerm(KeyHome, t.ti.KeyHome)
t.prepareKeyModXTerm(KeyEnd, t.ti.KeyEnd)
t.prepareKeyModXTerm(KeyF1, t.ti.KeyF1)
t.prepareKeyModXTerm(KeyF2, t.ti.KeyF2)
t.prepareKeyModXTerm(KeyF3, t.ti.KeyF3)
t.prepareKeyModXTerm(KeyF4, t.ti.KeyF4)
t.prepareKeyModXTerm(KeyF5, t.ti.KeyF5)
t.prepareKeyModXTerm(KeyF6, t.ti.KeyF6)
t.prepareKeyModXTerm(KeyF7, t.ti.KeyF7)
t.prepareKeyModXTerm(KeyF8, t.ti.KeyF8)
t.prepareKeyModXTerm(KeyF9, t.ti.KeyF9)
t.prepareKeyModXTerm(KeyF10, t.ti.KeyF10)
t.prepareKeyModXTerm(KeyF11, t.ti.KeyF11)
t.prepareKeyModXTerm(KeyF12, t.ti.KeyF12)
}
func (t *tScreen) prepareBracketedPaste() {
// Another workaround for lack of reporting in terminfo.
// We assume if the terminal has a mouse entry, that it
// offers bracketed paste. But we allow specific overrides
// via our terminal database.
if t.ti.EnablePaste != "" {
t.enablePaste = t.ti.EnablePaste
t.disablePaste = t.ti.DisablePaste
t.prepareKey(keyPasteStart, t.ti.PasteStart)
t.prepareKey(keyPasteEnd, t.ti.PasteEnd)
} else if t.ti.Mouse != "" {
t.enablePaste = "\x1b[?2004h"
t.disablePaste = "\x1b[?2004l"
t.prepareKey(keyPasteStart, "\x1b[200~")
t.prepareKey(keyPasteEnd, "\x1b[201~")
}
}
func (t *tScreen) prepareExtendedOSC() {
// Linux is a special beast - because it has a mouse entry, but does
// not swallow these OSC commands properly.
if strings.Contains(t.ti.Name, "linux") {
return
}
// More stuff for limits in terminfo. This time we are applying
// the most common OSC (operating system commands). Generally
// terminals that don't understand these will ignore them.
// Again, we condition this based on mouse capabilities.
if t.ti.EnterUrl != "" {
t.enterUrl = t.ti.EnterUrl
t.exitUrl = t.ti.ExitUrl
} else if t.ti.Mouse != "" {
t.enterUrl = "\x1b]8;%p2%s;%p1%s\x1b\\"
t.exitUrl = "\x1b]8;;\x1b\\"
}
if t.ti.SetWindowSize != "" {
t.setWinSize = t.ti.SetWindowSize
} else if t.ti.Mouse != "" {
t.setWinSize = "\x1b[8;%p1%p2%d;%dt"
}
if t.ti.EnableFocusReporting != "" {
t.enableFocus = t.ti.EnableFocusReporting
} else if t.ti.Mouse != "" {
t.enableFocus = "\x1b[?1004h"
}
if t.ti.DisableFocusReporting != "" {
t.disableFocus = t.ti.DisableFocusReporting
} else if t.ti.Mouse != "" {
t.disableFocus = "\x1b[?1004l"
}
}
func (t *tScreen) prepareCursorStyles() {
// Another workaround for lack of reporting in terminfo.
// We assume if the terminal has a mouse entry, that it
// offers bracketed paste. But we allow specific overrides
// via our terminal database.
if t.ti.CursorDefault != "" {
t.cursorStyles = map[CursorStyle]string{
CursorStyleDefault: t.ti.CursorDefault,
CursorStyleBlinkingBlock: t.ti.CursorBlinkingBlock,
CursorStyleSteadyBlock: t.ti.CursorSteadyBlock,
CursorStyleBlinkingUnderline: t.ti.CursorBlinkingUnderline,
CursorStyleSteadyUnderline: t.ti.CursorSteadyUnderline,
CursorStyleBlinkingBar: t.ti.CursorBlinkingBar,
CursorStyleSteadyBar: t.ti.CursorSteadyBar,
}
} else if t.ti.Mouse != "" {
t.cursorStyles = map[CursorStyle]string{
CursorStyleDefault: "\x1b[0 q",
CursorStyleBlinkingBlock: "\x1b[1 q",
CursorStyleSteadyBlock: "\x1b[2 q",
CursorStyleBlinkingUnderline: "\x1b[3 q",
CursorStyleSteadyUnderline: "\x1b[4 q",
CursorStyleBlinkingBar: "\x1b[5 q",
CursorStyleSteadyBar: "\x1b[6 q",
}
}
}
func (t *tScreen) prepareKey(key Key, val string) {
t.prepareKeyMod(key, ModNone, val)
}
func (t *tScreen) prepareKeys() {
ti := t.ti
t.prepareKey(KeyBackspace, ti.KeyBackspace)
t.prepareKey(KeyF1, ti.KeyF1)
t.prepareKey(KeyF2, ti.KeyF2)
t.prepareKey(KeyF3, ti.KeyF3)
t.prepareKey(KeyF4, ti.KeyF4)
t.prepareKey(KeyF5, ti.KeyF5)
t.prepareKey(KeyF6, ti.KeyF6)
t.prepareKey(KeyF7, ti.KeyF7)
t.prepareKey(KeyF8, ti.KeyF8)
t.prepareKey(KeyF9, ti.KeyF9)
t.prepareKey(KeyF10, ti.KeyF10)
t.prepareKey(KeyF11, ti.KeyF11)
t.prepareKey(KeyF12, ti.KeyF12)
t.prepareKey(KeyF13, ti.KeyF13)
t.prepareKey(KeyF14, ti.KeyF14)
t.prepareKey(KeyF15, ti.KeyF15)
t.prepareKey(KeyF16, ti.KeyF16)
t.prepareKey(KeyF17, ti.KeyF17)
t.prepareKey(KeyF18, ti.KeyF18)
t.prepareKey(KeyF19, ti.KeyF19)
t.prepareKey(KeyF20, ti.KeyF20)
t.prepareKey(KeyF21, ti.KeyF21)
t.prepareKey(KeyF22, ti.KeyF22)
t.prepareKey(KeyF23, ti.KeyF23)
t.prepareKey(KeyF24, ti.KeyF24)
t.prepareKey(KeyF25, ti.KeyF25)
t.prepareKey(KeyF26, ti.KeyF26)
t.prepareKey(KeyF27, ti.KeyF27)
t.prepareKey(KeyF28, ti.KeyF28)
t.prepareKey(KeyF29, ti.KeyF29)
t.prepareKey(KeyF30, ti.KeyF30)
t.prepareKey(KeyF31, ti.KeyF31)
t.prepareKey(KeyF32, ti.KeyF32)
t.prepareKey(KeyF33, ti.KeyF33)
t.prepareKey(KeyF34, ti.KeyF34)
t.prepareKey(KeyF35, ti.KeyF35)
t.prepareKey(KeyF36, ti.KeyF36)
t.prepareKey(KeyF37, ti.KeyF37)
t.prepareKey(KeyF38, ti.KeyF38)
t.prepareKey(KeyF39, ti.KeyF39)
t.prepareKey(KeyF40, ti.KeyF40)
t.prepareKey(KeyF41, ti.KeyF41)
t.prepareKey(KeyF42, ti.KeyF42)
t.prepareKey(KeyF43, ti.KeyF43)
t.prepareKey(KeyF44, ti.KeyF44)
t.prepareKey(KeyF45, ti.KeyF45)
t.prepareKey(KeyF46, ti.KeyF46)
t.prepareKey(KeyF47, ti.KeyF47)
t.prepareKey(KeyF48, ti.KeyF48)
t.prepareKey(KeyF49, ti.KeyF49)
t.prepareKey(KeyF50, ti.KeyF50)
t.prepareKey(KeyF51, ti.KeyF51)
t.prepareKey(KeyF52, ti.KeyF52)
t.prepareKey(KeyF53, ti.KeyF53)
t.prepareKey(KeyF54, ti.KeyF54)
t.prepareKey(KeyF55, ti.KeyF55)
t.prepareKey(KeyF56, ti.KeyF56)
t.prepareKey(KeyF57, ti.KeyF57)
t.prepareKey(KeyF58, ti.KeyF58)
t.prepareKey(KeyF59, ti.KeyF59)
t.prepareKey(KeyF60, ti.KeyF60)
t.prepareKey(KeyF61, ti.KeyF61)
t.prepareKey(KeyF62, ti.KeyF62)
t.prepareKey(KeyF63, ti.KeyF63)
t.prepareKey(KeyF64, ti.KeyF64)
t.prepareKey(KeyInsert, ti.KeyInsert)
t.prepareKey(KeyDelete, ti.KeyDelete)
t.prepareKey(KeyHome, ti.KeyHome)
t.prepareKey(KeyEnd, ti.KeyEnd)
t.prepareKey(KeyUp, ti.KeyUp)
t.prepareKey(KeyDown, ti.KeyDown)
t.prepareKey(KeyLeft, ti.KeyLeft)
t.prepareKey(KeyRight, ti.KeyRight)
t.prepareKey(KeyPgUp, ti.KeyPgUp)
t.prepareKey(KeyPgDn, ti.KeyPgDn)
t.prepareKey(KeyHelp, ti.KeyHelp)
t.prepareKey(KeyPrint, ti.KeyPrint)
t.prepareKey(KeyCancel, ti.KeyCancel)
t.prepareKey(KeyExit, ti.KeyExit)
t.prepareKey(KeyBacktab, ti.KeyBacktab)
t.prepareKeyMod(KeyRight, ModShift, ti.KeyShfRight)
t.prepareKeyMod(KeyLeft, ModShift, ti.KeyShfLeft)
t.prepareKeyMod(KeyUp, ModShift, ti.KeyShfUp)
t.prepareKeyMod(KeyDown, ModShift, ti.KeyShfDown)
t.prepareKeyMod(KeyHome, ModShift, ti.KeyShfHome)
t.prepareKeyMod(KeyEnd, ModShift, ti.KeyShfEnd)
t.prepareKeyMod(KeyPgUp, ModShift, ti.KeyShfPgUp)
t.prepareKeyMod(KeyPgDn, ModShift, ti.KeyShfPgDn)
t.prepareKeyMod(KeyRight, ModCtrl, ti.KeyCtrlRight)
t.prepareKeyMod(KeyLeft, ModCtrl, ti.KeyCtrlLeft)
t.prepareKeyMod(KeyUp, ModCtrl, ti.KeyCtrlUp)
t.prepareKeyMod(KeyDown, ModCtrl, ti.KeyCtrlDown)
t.prepareKeyMod(KeyHome, ModCtrl, ti.KeyCtrlHome)
t.prepareKeyMod(KeyEnd, ModCtrl, ti.KeyCtrlEnd)
// Sadly, xterm handling of keycodes is somewhat erratic. In
// particular, different codes are sent depending on application
// mode is in use or not, and the entries for many of these are
// simply absent from terminfo on many systems. So we insert
// a number of escape sequences if they are not already used, in
// order to have the widest correct usage. Note that prepareKey
// will not inject codes if the escape sequence is already known.
// We also only do this for terminals that have the application
// mode present.
// Cursor mode
if ti.EnterKeypad != "" {
t.prepareKey(KeyUp, "\x1b[A")
t.prepareKey(KeyDown, "\x1b[B")
t.prepareKey(KeyRight, "\x1b[C")
t.prepareKey(KeyLeft, "\x1b[D")
t.prepareKey(KeyEnd, "\x1b[F")
t.prepareKey(KeyHome, "\x1b[H")
t.prepareKey(KeyDelete, "\x1b[3~")
t.prepareKey(KeyHome, "\x1b[1~")
t.prepareKey(KeyEnd, "\x1b[4~")
t.prepareKey(KeyPgUp, "\x1b[5~")
t.prepareKey(KeyPgDn, "\x1b[6~")
// Application mode
t.prepareKey(KeyUp, "\x1bOA")
t.prepareKey(KeyDown, "\x1bOB")
t.prepareKey(KeyRight, "\x1bOC")
t.prepareKey(KeyLeft, "\x1bOD")
t.prepareKey(KeyHome, "\x1bOH")
}
t.prepareKey(keyPasteStart, ti.PasteStart)
t.prepareKey(keyPasteEnd, ti.PasteEnd)
t.prepareXtermModifiers()
t.prepareBracketedPaste()
t.prepareCursorStyles()
t.prepareExtendedOSC()
outer:
// Add key mappings for control keys.
for i := 0; i < ' '; i++ {
// Do not insert direct key codes for ambiguous keys.
// For example, ESC is used for lots of other keys, so
// when parsing this we don't want to fast path handling
// of it, but instead wait a bit before parsing it as in
// isolation.
for esc := range t.keycodes {
if []byte(esc)[0] == byte(i) {
continue outer
}
}
t.keyexist[Key(i)] = true
mod := ModCtrl
switch Key(i) {
case KeyBS, KeyTAB, KeyESC, KeyCR:
// directly type-able- no control sequence
mod = ModNone
}
t.keycodes[string(rune(i))] = &tKeyCode{key: Key(i), mod: mod}
}
}
func (t *tScreen) Fini() {
t.finiOnce.Do(t.finish)
}
func (t *tScreen) finish() {
close(t.quit)
t.finalize()
}
func (t *tScreen) SetStyle(style Style) {
t.Lock()
if !t.fini {
t.style = style
}
t.Unlock()
}
func (t *tScreen) encodeRune(r rune, buf []byte) []byte {
nb := make([]byte, 6)
ob := make([]byte, 6)
num := utf8.EncodeRune(ob, r)
ob = ob[:num]
dst := 0
var err error
if enc := t.encoder; enc != nil {
enc.Reset()
dst, _, err = enc.Transform(nb, ob, true)
}
if err != nil || dst == 0 || nb[0] == '\x1a' {
// Combining characters are elided
if len(buf) == 0 {
if acs, ok := t.acs[r]; ok {
buf = append(buf, []byte(acs)...)
} else if fb, ok := t.fallback[r]; ok {
buf = append(buf, []byte(fb)...)
} else {
buf = append(buf, '?')
}
}
} else {
buf = append(buf, nb[:dst]...)
}
return buf
}
func (t *tScreen) sendFgBg(fg Color, bg Color, attr AttrMask) AttrMask {
ti := t.ti
if ti.Colors == 0 {
// foreground vs background, we calculate luminance
// and possibly do a reverse video
if !fg.Valid() {
return attr
}
v, ok := t.colors[fg]
if !ok {
v = FindColor(fg, []Color{ColorBlack, ColorWhite})
t.colors[fg] = v
}
switch v {
case ColorWhite:
return attr
case ColorBlack:
return attr ^ AttrReverse
}
}
if fg == ColorReset || bg == ColorReset {
t.TPuts(ti.ResetFgBg)
}
if t.truecolor {
if ti.SetFgBgRGB != "" && fg.IsRGB() && bg.IsRGB() {
r1, g1, b1 := fg.RGB()
r2, g2, b2 := bg.RGB()
t.TPuts(ti.TParm(ti.SetFgBgRGB,
int(r1), int(g1), int(b1),
int(r2), int(g2), int(b2)))
return attr
}
if fg.IsRGB() && ti.SetFgRGB != "" {
r, g, b := fg.RGB()
t.TPuts(ti.TParm(ti.SetFgRGB, int(r), int(g), int(b)))
fg = ColorDefault
}
if bg.IsRGB() && ti.SetBgRGB != "" {
r, g, b := bg.RGB()
t.TPuts(ti.TParm(ti.SetBgRGB,
int(r), int(g), int(b)))
bg = ColorDefault
}
}
if fg.Valid() {
if v, ok := t.colors[fg]; ok {
fg = v
} else {
v = FindColor(fg, t.palette)
t.colors[fg] = v
fg = v
}
}
if bg.Valid() {
if v, ok := t.colors[bg]; ok {
bg = v
} else {
v = FindColor(bg, t.palette)
t.colors[bg] = v
bg = v
}
}
if fg.Valid() && bg.Valid() && ti.SetFgBg != "" {
t.TPuts(ti.TParm(ti.SetFgBg, int(fg&0xff), int(bg&0xff)))
} else {
if fg.Valid() && ti.SetFg != "" {
t.TPuts(ti.TParm(ti.SetFg, int(fg&0xff)))
}
if bg.Valid() && ti.SetBg != "" {
t.TPuts(ti.TParm(ti.SetBg, int(bg&0xff)))
}
}
return attr
}
func (t *tScreen) drawCell(x, y int) int {
ti := t.ti
mainc, combc, style, width := t.cells.GetContent(x, y)
if !t.cells.Dirty(x, y) {
return width
}
if y == t.h-1 && x == t.w-1 && t.ti.AutoMargin && ti.DisableAutoMargin == "" && ti.InsertChar != "" {
// our solution is somewhat goofy.
// we write to the second to the last cell what we want in the last cell, then we
// insert a character at that 2nd to last position to shift the last column into
// place, then we rewrite that 2nd to last cell. Old terminals suck.
t.TPuts(ti.TGoto(x-1, y))
defer func() {
t.TPuts(ti.TGoto(x-1, y))
t.TPuts(ti.InsertChar)
t.cy = y
t.cx = x - 1
t.cells.SetDirty(x-1, y, true)
_ = t.drawCell(x-1, y)
t.TPuts(t.ti.TGoto(0, 0))
t.cy = 0
t.cx = 0
}()
} else if t.cy != y || t.cx != x {
t.TPuts(ti.TGoto(x, y))
t.cx = x
t.cy = y
}
if style == StyleDefault {
style = t.style
}
if style != t.curstyle {
fg, bg, attrs := style.Decompose()
t.TPuts(ti.AttrOff)
attrs = t.sendFgBg(fg, bg, attrs)
if attrs&AttrBold != 0 {
t.TPuts(ti.Bold)
}
if attrs&AttrUnderline != 0 {
t.TPuts(ti.Underline)
}
if attrs&AttrReverse != 0 {
t.TPuts(ti.Reverse)
}
if attrs&AttrBlink != 0 {
t.TPuts(ti.Blink)
}
if attrs&AttrDim != 0 {
t.TPuts(ti.Dim)
}
if attrs&AttrItalic != 0 {
t.TPuts(ti.Italic)
}
if attrs&AttrStrikeThrough != 0 {
t.TPuts(ti.StrikeThrough)
}
// URL string can be long, so don't send it unless we really need to
if t.enterUrl != "" && t.curstyle != style {
if style.url != "" {
t.TPuts(ti.TParm(t.enterUrl, style.url, style.urlId))
} else {
t.TPuts(t.exitUrl)
}
}
t.curstyle = style
}
// now emit runes - taking care to not overrun width with a
// wide character, and to ensure that we emit exactly one regular
// character followed up by any residual combing characters
if width < 1 {
width = 1
}
var str string
buf := make([]byte, 0, 6)
buf = t.encodeRune(mainc, buf)
for _, r := range combc {
buf = t.encodeRune(r, buf)
}
str = string(buf)
if width > 1 && str == "?" {
// No FullWidth character support
str = "? "
t.cx = -1
}
if x > t.w-width {
// too wide to fit; emit a single space instead
width = 1
str = " "
}
t.writeString(str)
t.cx += width
t.cells.SetDirty(x, y, false)
if width > 1 {
t.cx = -1
}
return width
}
func (t *tScreen) ShowCursor(x, y int) {
t.Lock()
t.cursorx = x
t.cursory = y
t.Unlock()
}
func (t *tScreen) SetCursorStyle(cs CursorStyle) {
t.Lock()
t.cursorStyle = cs
t.Unlock()
}
func (t *tScreen) HideCursor() {
t.ShowCursor(-1, -1)
}
func (t *tScreen) showCursor() {
x, y := t.cursorx, t.cursory
w, h := t.cells.Size()
if x < 0 || y < 0 || x >= w || y >= h {
t.hideCursor()
return
}
t.TPuts(t.ti.TGoto(x, y))
t.TPuts(t.ti.ShowCursor)
if t.cursorStyles != nil {
if esc, ok := t.cursorStyles[t.cursorStyle]; ok {
t.TPuts(esc)
}
}
t.cx = x
t.cy = y
}
// writeString sends a string to the terminal. The string is sent as-is and
// this function does not expand inline padding indications (of the form
// $<[delay]> where [delay] is msec). In order to have these expanded, use
// TPuts. If the screen is "buffering", the string is collected in a buffer,
// with the intention that the entire buffer be sent to the terminal in one
// write operation at some point later.
func (t *tScreen) writeString(s string) {
if t.buffering {
_, _ = io.WriteString(&t.buf, s)
} else {
_, _ = io.WriteString(t.tty, s)
}
}
func (t *tScreen) TPuts(s string) {
if t.buffering {
t.ti.TPuts(&t.buf, s)
} else {
t.ti.TPuts(t.tty, s)
}
}
func (t *tScreen) Show() {
t.Lock()
if !t.fini {
t.resize()
t.draw()
}
t.Unlock()
}
func (t *tScreen) clearScreen() {
t.TPuts(t.ti.AttrOff)
t.TPuts(t.exitUrl)
fg, bg, _ := t.style.Decompose()
_ = t.sendFgBg(fg, bg, AttrNone)
t.TPuts(t.ti.Clear)
t.clear = false
}
func (t *tScreen) hideCursor() {
// does not update cursor position
if t.ti.HideCursor != "" {
t.TPuts(t.ti.HideCursor)
} else {
// No way to hide cursor, stick it
// at bottom right of screen
t.cx, t.cy = t.cells.Size()
t.TPuts(t.ti.TGoto(t.cx, t.cy))
}
}
func (t *tScreen) draw() {
// clobber cursor position, because we're going to change it all
t.cx = -1
t.cy = -1
// make no style assumptions
t.curstyle = styleInvalid
t.buf.Reset()
t.buffering = true
defer func() {
t.buffering = false
}()
// hide the cursor while we move stuff around
t.hideCursor()
if t.clear {
t.clearScreen()
}
for y := 0; y < t.h; y++ {
for x := 0; x < t.w; x++ {
width := t.drawCell(x, y)
if width > 1 {
if x+1 < t.w {
// this is necessary so that if we ever
// go back to drawing that cell, we
// actually will *draw* it.
t.cells.SetDirty(x+1, y, true)
}
}
x += width - 1
}
}
// restore the cursor
t.showCursor()
_, _ = t.buf.WriteTo(t.tty)
}
func (t *tScreen) EnableMouse(flags ...MouseFlags) {
var f MouseFlags
flagsPresent := false
for _, flag := range flags {
f |= flag
flagsPresent = true
}
if !flagsPresent {
f = MouseMotionEvents | MouseDragEvents | MouseButtonEvents
}
t.Lock()
t.mouseFlags = f
t.enableMouse(f)
t.Unlock()
}
func (t *tScreen) enableMouse(f MouseFlags) {
// Rather than using terminfo to find mouse escape sequences, we rely on the fact that
// pretty much *every* terminal that supports mouse tracking follows the
// XTerm standards (the modern ones).
if len(t.mouse) != 0 {
// start by disabling all tracking.
t.TPuts("\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l")
if f&MouseButtonEvents != 0 {
t.TPuts("\x1b[?1000h")
}
if f&MouseDragEvents != 0 {
t.TPuts("\x1b[?1002h")
}
if f&MouseMotionEvents != 0 {
t.TPuts("\x1b[?1003h")
}
if f&(MouseButtonEvents|MouseDragEvents|MouseMotionEvents) != 0 {
t.TPuts("\x1b[?1006h")
}
}
}
func (t *tScreen) DisableMouse() {
t.Lock()
t.mouseFlags = 0
t.enableMouse(0)
t.Unlock()
}
func (t *tScreen) EnablePaste() {
t.Lock()
t.pasteEnabled = true
t.enablePasting(true)
t.Unlock()
}
func (t *tScreen) DisablePaste() {
t.Lock()
t.pasteEnabled = false
t.enablePasting(false)
t.Unlock()
}
func (t *tScreen) enablePasting(on bool) {
var s string
if on {
s = t.enablePaste
} else {
s = t.disablePaste
}
if s != "" {
t.TPuts(s)
}
}
func (t *tScreen) EnableFocus() {
t.Lock()
t.focusEnabled = true
t.enableFocusReporting()
t.Unlock()
}
func (t *tScreen) DisableFocus() {
t.Lock()
t.focusEnabled = false
t.disableFocusReporting()
t.Unlock()
}
func (t *tScreen) enableFocusReporting() {
if t.enableFocus != "" {
t.TPuts(t.enableFocus)
}
}
func (t *tScreen) disableFocusReporting() {
if t.disableFocus != "" {
t.TPuts(t.disableFocus)
}
}
func (t *tScreen) Size() (int, int) {
t.Lock()
w, h := t.w, t.h
t.Unlock()
return w, h
}
func (t *tScreen) resize() {
ws, err := t.tty.WindowSize()
if err != nil {
return
}
if ws.Width == t.w && ws.Height == t.h {
return
}
t.cx = -1
t.cy = -1
t.cells.Resize(ws.Width, ws.Height)
t.cells.Invalidate()
t.h = ws.Height
t.w = ws.Width
ev := &EventResize{t: time.Now(), ws: ws}
select {
case t.eventQ <- ev:
default:
}
}
func (t *tScreen) Colors() int {
// this doesn't change, no need for lock
if t.truecolor {
return 1 << 24
}
return t.ti.Colors
}
// nColors returns the size of the built-in palette.
// This is distinct from Colors(), as it will generally
// always be a small number. (<= 256)
func (t *tScreen) nColors() int {
return t.ti.Colors
}
// vtACSNames is a map of bytes defined by terminfo that are used in
// the terminals Alternate Character Set to represent other glyphs.
// For example, the upper left corner of the box drawing set can be
// displayed by printing "l" while in the alternate character set.
// It's not quite that simple, since the "l" is the terminfo name,
// and it may be necessary to use a different character based on
// the terminal implementation (or the terminal may lack support for
// this altogether). See buildAcsMap below for detail.
var vtACSNames = map[byte]rune{
'+': RuneRArrow,
',': RuneLArrow,
'-': RuneUArrow,
'.': RuneDArrow,
'0': RuneBlock,
'`': RuneDiamond,
'a': RuneCkBoard,
'b': '␉', // VT100, Not defined by terminfo
'c': '␌', // VT100, Not defined by terminfo
'd': '␋', // VT100, Not defined by terminfo
'e': '␊', // VT100, Not defined by terminfo
'f': RuneDegree,
'g': RunePlMinus,
'h': RuneBoard,
'i': RuneLantern,
'j': RuneLRCorner,
'k': RuneURCorner,
'l': RuneULCorner,
'm': RuneLLCorner,
'n': RunePlus,
'o': RuneS1,
'p': RuneS3,
'q': RuneHLine,
'r': RuneS7,
's': RuneS9,
't': RuneLTee,
'u': RuneRTee,
'v': RuneBTee,
'w': RuneTTee,
'x': RuneVLine,
'y': RuneLEqual,
'z': RuneGEqual,
'{': RunePi,
'|': RuneNEqual,
'}': RuneSterling,
'~': RuneBullet,
}
// buildAcsMap builds a map of characters that we translate from Unicode to
// alternate character encodings. To do this, we use the standard VT100 ACS
// maps. This is only done if the terminal lacks support for Unicode; we
// always prefer to emit Unicode glyphs when we are able.
func (t *tScreen) buildAcsMap() {
acsstr := t.ti.AltChars
t.acs = make(map[rune]string)
for len(acsstr) > 2 {
srcv := acsstr[0]
dstv := string(acsstr[1])
if r, ok := vtACSNames[srcv]; ok {
t.acs[r] = t.ti.EnterAcs + dstv + t.ti.ExitAcs
}
acsstr = acsstr[2:]
}
}
func (t *tScreen) clip(x, y int) (int, int) {
w, h := t.cells.Size()
if x < 0 {
x = 0
}
if y < 0 {
y = 0
}
if x > w-1 {
x = w - 1
}
if y > h-1 {
y = h - 1
}
return x, y
}
// buildMouseEvent returns an event based on the supplied coordinates and button
// state. Note that the screen's mouse button state is updated based on the
// input to this function (i.e. it mutates the receiver).
func (t *tScreen) buildMouseEvent(x, y, btn int) *EventMouse {
// XTerm mouse events only report at most one button at a time,
// which may include a wheel button. Wheel motion events are
// reported as single impulses, while other button events are reported
// as separate press & release events.
button := ButtonNone
mod := ModNone
// Mouse wheel has bit 6 set, no release events. It should be noted
// that wheel events are sometimes misdelivered as mouse button events
// during a click-drag, so we debounce these, considering them to be
// button press events unless we see an intervening release event.
switch btn & 0x43 {
case 0:
button = Button1
case 1:
button = Button3 // Note we prefer to treat right as button 2
case 2:
button = Button2 // And the middle button as button 3
case 3:
button = ButtonNone
case 0x40:
button = WheelUp
case 0x41:
button = WheelDown
}
if btn&0x4 != 0 {
mod |= ModShift
}
if btn&0x8 != 0 {
mod |= ModAlt
}
if btn&0x10 != 0 {
mod |= ModCtrl
}
// Some terminals will report mouse coordinates outside the
// screen, especially with click-drag events. Clip the coordinates
// to the screen in that case.
x, y = t.clip(x, y)
return NewEventMouse(x, y, button, mod)
}
// parseSgrMouse attempts to locate an SGR mouse record at the start of the
// buffer. It returns true, true if it found one, and the associated bytes
// be removed from the buffer. It returns true, false if the buffer might
// contain such an event, but more bytes are necessary (partial match), and
// false, false if the content is definitely *not* an SGR mouse record.
func (t *tScreen) parseSgrMouse(buf *bytes.Buffer, evs *[]Event) (bool, bool) {
b := buf.Bytes()
var x, y, btn, state int
dig := false
neg := false
motion := false
scroll := false
i := 0
val := 0
for i = range b {
switch b[i] {
case '\x1b':
if state != 0 {
return false, false
}
state = 1
case '\x9b':
if state != 0 {
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | true |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/terminfo/terminfo.go | vendor/github.com/gdamore/tcell/v2/terminfo/terminfo.go | // Copyright 2024 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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 terminfo
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"strconv"
"strings"
"sync"
"time"
)
var (
// ErrTermNotFound indicates that a suitable terminal entry could
// not be found. This can result from either not having TERM set,
// or from the TERM failing to support certain minimal functionality,
// in particular absolute cursor addressability (the cup capability)
// is required. For example, legacy "adm3" lacks this capability,
// whereas the slightly newer "adm3a" supports it. This failure
// occurs most often with "dumb".
ErrTermNotFound = errors.New("terminal entry not found")
)
// Terminfo represents a terminfo entry. Note that we use friendly names
// in Go, but when we write out JSON, we use the same names as terminfo.
// The name, aliases and smous, rmous fields do not come from terminfo directly.
type Terminfo struct {
Name string
Aliases []string
Columns int // cols
Lines int // lines
Colors int // colors
Bell string // bell
Clear string // clear
EnterCA string // smcup
ExitCA string // rmcup
ShowCursor string // cnorm
HideCursor string // civis
AttrOff string // sgr0
Underline string // smul
Bold string // bold
Blink string // blink
Reverse string // rev
Dim string // dim
Italic string // sitm
EnterKeypad string // smkx
ExitKeypad string // rmkx
SetFg string // setaf
SetBg string // setab
ResetFgBg string // op
SetCursor string // cup
CursorBack1 string // cub1
CursorUp1 string // cuu1
PadChar string // pad
KeyBackspace string // kbs
KeyF1 string // kf1
KeyF2 string // kf2
KeyF3 string // kf3
KeyF4 string // kf4
KeyF5 string // kf5
KeyF6 string // kf6
KeyF7 string // kf7
KeyF8 string // kf8
KeyF9 string // kf9
KeyF10 string // kf10
KeyF11 string // kf11
KeyF12 string // kf12
KeyF13 string // kf13
KeyF14 string // kf14
KeyF15 string // kf15
KeyF16 string // kf16
KeyF17 string // kf17
KeyF18 string // kf18
KeyF19 string // kf19
KeyF20 string // kf20
KeyF21 string // kf21
KeyF22 string // kf22
KeyF23 string // kf23
KeyF24 string // kf24
KeyF25 string // kf25
KeyF26 string // kf26
KeyF27 string // kf27
KeyF28 string // kf28
KeyF29 string // kf29
KeyF30 string // kf30
KeyF31 string // kf31
KeyF32 string // kf32
KeyF33 string // kf33
KeyF34 string // kf34
KeyF35 string // kf35
KeyF36 string // kf36
KeyF37 string // kf37
KeyF38 string // kf38
KeyF39 string // kf39
KeyF40 string // kf40
KeyF41 string // kf41
KeyF42 string // kf42
KeyF43 string // kf43
KeyF44 string // kf44
KeyF45 string // kf45
KeyF46 string // kf46
KeyF47 string // kf47
KeyF48 string // kf48
KeyF49 string // kf49
KeyF50 string // kf50
KeyF51 string // kf51
KeyF52 string // kf52
KeyF53 string // kf53
KeyF54 string // kf54
KeyF55 string // kf55
KeyF56 string // kf56
KeyF57 string // kf57
KeyF58 string // kf58
KeyF59 string // kf59
KeyF60 string // kf60
KeyF61 string // kf61
KeyF62 string // kf62
KeyF63 string // kf63
KeyF64 string // kf64
KeyInsert string // kich1
KeyDelete string // kdch1
KeyHome string // khome
KeyEnd string // kend
KeyHelp string // khlp
KeyPgUp string // kpp
KeyPgDn string // knp
KeyUp string // kcuu1
KeyDown string // kcud1
KeyLeft string // kcub1
KeyRight string // kcuf1
KeyBacktab string // kcbt
KeyExit string // kext
KeyClear string // kclr
KeyPrint string // kprt
KeyCancel string // kcan
Mouse string // kmous
AltChars string // acsc
EnterAcs string // smacs
ExitAcs string // rmacs
EnableAcs string // enacs
KeyShfRight string // kRIT
KeyShfLeft string // kLFT
KeyShfHome string // kHOM
KeyShfEnd string // kEND
KeyShfInsert string // kIC
KeyShfDelete string // kDC
// These are non-standard extensions to terminfo. This includes
// true color support, and some additional keys. Its kind of bizarre
// that shifted variants of left and right exist, but not up and down.
// Terminal support for these are going to vary amongst XTerm
// emulations, so don't depend too much on them in your application.
StrikeThrough string // smxx
SetFgBg string // setfgbg
SetFgBgRGB string // setfgbgrgb
SetFgRGB string // setfrgb
SetBgRGB string // setbrgb
KeyShfUp string // shift-up
KeyShfDown string // shift-down
KeyShfPgUp string // shift-kpp
KeyShfPgDn string // shift-knp
KeyCtrlUp string // ctrl-up
KeyCtrlDown string // ctrl-left
KeyCtrlRight string // ctrl-right
KeyCtrlLeft string // ctrl-left
KeyMetaUp string // meta-up
KeyMetaDown string // meta-left
KeyMetaRight string // meta-right
KeyMetaLeft string // meta-left
KeyAltUp string // alt-up
KeyAltDown string // alt-left
KeyAltRight string // alt-right
KeyAltLeft string // alt-left
KeyCtrlHome string
KeyCtrlEnd string
KeyMetaHome string
KeyMetaEnd string
KeyAltHome string
KeyAltEnd string
KeyAltShfUp string
KeyAltShfDown string
KeyAltShfLeft string
KeyAltShfRight string
KeyMetaShfUp string
KeyMetaShfDown string
KeyMetaShfLeft string
KeyMetaShfRight string
KeyCtrlShfUp string
KeyCtrlShfDown string
KeyCtrlShfLeft string
KeyCtrlShfRight string
KeyCtrlShfHome string
KeyCtrlShfEnd string
KeyAltShfHome string
KeyAltShfEnd string
KeyMetaShfHome string
KeyMetaShfEnd string
EnablePaste string // bracketed paste mode
DisablePaste string
PasteStart string
PasteEnd string
Modifiers int
InsertChar string // string to insert a character (ich1)
AutoMargin bool // true if writing to last cell in line advances
TrueColor bool // true if the terminal supports direct color
CursorDefault string
CursorBlinkingBlock string
CursorSteadyBlock string
CursorBlinkingUnderline string
CursorSteadyUnderline string
CursorBlinkingBar string
CursorSteadyBar string
EnterUrl string
ExitUrl string
SetWindowSize string
EnableFocusReporting string
DisableFocusReporting string
DisableAutoMargin string // smam
EnableAutoMargin string // rmam
}
const (
ModifiersNone = 0
ModifiersXTerm = 1
)
type stack []interface{}
func (st stack) Push(v interface{}) stack {
if b, ok := v.(bool); ok {
if b {
return append(st, 1)
} else {
return append(st, 0)
}
}
return append(st, v)
}
func (st stack) PopString() (string, stack) {
if len(st) > 0 {
e := st[len(st)-1]
var s string
switch v := e.(type) {
case int:
s = strconv.Itoa(v)
case string:
s = v
}
return s, st[:len(st)-1]
}
return "", st
}
func (st stack) PopInt() (int, stack) {
if len(st) > 0 {
e := st[len(st)-1]
var i int
switch v := e.(type) {
case int:
i = v
case string:
i, _ = strconv.Atoi(v)
}
return i, st[:len(st)-1]
}
return 0, st
}
// static vars
var svars [26]string
type paramsBuffer struct {
out bytes.Buffer
buf bytes.Buffer
}
// Start initializes the params buffer with the initial string data.
// It also locks the paramsBuffer. The caller must call End() when
// finished.
func (pb *paramsBuffer) Start(s string) {
pb.out.Reset()
pb.buf.Reset()
pb.buf.WriteString(s)
}
// End returns the final output from TParam, but it also releases the lock.
func (pb *paramsBuffer) End() string {
s := pb.out.String()
return s
}
// NextCh returns the next input character to the expander.
func (pb *paramsBuffer) NextCh() (byte, error) {
return pb.buf.ReadByte()
}
// PutCh "emits" (rather schedules for output) a single byte character.
func (pb *paramsBuffer) PutCh(ch byte) {
pb.out.WriteByte(ch)
}
// PutString schedules a string for output.
func (pb *paramsBuffer) PutString(s string) {
pb.out.WriteString(s)
}
// TParm takes a terminfo parameterized string, such as setaf or cup, and
// evaluates the string, and returns the result with the parameter
// applied.
func (t *Terminfo) TParm(s string, p ...interface{}) string {
var stk stack
var a string
var ai, bi int
var dvars [26]string
var params [9]interface{}
var pb = ¶msBuffer{}
pb.Start(s)
// make sure we always have 9 parameters -- makes it easier
// later to skip checks
for i := 0; i < len(params) && i < len(p); i++ {
params[i] = p[i]
}
const (
emit = iota
toEnd
toElse
)
skip := emit
for {
ch, err := pb.NextCh()
if err != nil {
break
}
if ch != '%' {
if skip == emit {
pb.PutCh(ch)
}
continue
}
ch, err = pb.NextCh()
if err != nil {
// XXX Error
break
}
if skip == toEnd {
if ch == ';' {
skip = emit
}
continue
} else if skip == toElse {
if ch == 'e' || ch == ';' {
skip = emit
}
continue
}
switch ch {
case '%': // quoted %
pb.PutCh(ch)
case 'i': // increment both parameters (ANSI cup support)
if i, ok := params[0].(int); ok {
params[0] = i + 1
}
if i, ok := params[1].(int); ok {
params[1] = i + 1
}
case 's':
// NB: 's', 'c', and 'd' below are special cased for
// efficiency. They could be handled by the richer
// format support below, less efficiently.
a, stk = stk.PopString()
pb.PutString(a)
case 'c':
// Integer as special character.
ai, stk = stk.PopInt()
pb.PutCh(byte(ai))
case 'd':
ai, stk = stk.PopInt()
pb.PutString(strconv.Itoa(ai))
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'x', 'X', 'o', ':':
// This is pretty suboptimal, but this is rarely used.
// None of the mainstream terminals use any of this,
// and it would surprise me if this code is ever
// executed outside test cases.
f := "%"
if ch == ':' {
ch, _ = pb.NextCh()
}
f += string(ch)
for ch == '+' || ch == '-' || ch == '#' || ch == ' ' {
ch, _ = pb.NextCh()
f += string(ch)
}
for (ch >= '0' && ch <= '9') || ch == '.' {
ch, _ = pb.NextCh()
f += string(ch)
}
switch ch {
case 'd', 'x', 'X', 'o':
ai, stk = stk.PopInt()
pb.PutString(fmt.Sprintf(f, ai))
case 's':
a, stk = stk.PopString()
pb.PutString(fmt.Sprintf(f, a))
case 'c':
ai, stk = stk.PopInt()
pb.PutString(fmt.Sprintf(f, ai))
}
case 'p': // push parameter
ch, _ = pb.NextCh()
ai = int(ch - '1')
if ai >= 0 && ai < len(params) {
stk = stk.Push(params[ai])
} else {
stk = stk.Push(0)
}
case 'P': // pop & store variable
ch, _ = pb.NextCh()
if ch >= 'A' && ch <= 'Z' {
svars[int(ch-'A')], stk = stk.PopString()
} else if ch >= 'a' && ch <= 'z' {
dvars[int(ch-'a')], stk = stk.PopString()
}
case 'g': // recall & push variable
ch, _ = pb.NextCh()
if ch >= 'A' && ch <= 'Z' {
stk = stk.Push(svars[int(ch-'A')])
} else if ch >= 'a' && ch <= 'z' {
stk = stk.Push(dvars[int(ch-'a')])
}
case '\'': // push(char) - the integer value of it
ch, _ = pb.NextCh()
_, _ = pb.NextCh() // must be ' but we don't check
stk = stk.Push(int(ch))
case '{': // push(int)
ai = 0
ch, _ = pb.NextCh()
for ch >= '0' && ch <= '9' {
ai *= 10
ai += int(ch - '0')
ch, _ = pb.NextCh()
}
// ch must be '}' but no verification
stk = stk.Push(ai)
case 'l': // push(strlen(pop))
a, stk = stk.PopString()
stk = stk.Push(len(a))
case '+':
bi, stk = stk.PopInt()
ai, stk = stk.PopInt()
stk = stk.Push(ai + bi)
case '-':
bi, stk = stk.PopInt()
ai, stk = stk.PopInt()
stk = stk.Push(ai - bi)
case '*':
bi, stk = stk.PopInt()
ai, stk = stk.PopInt()
stk = stk.Push(ai * bi)
case '/':
bi, stk = stk.PopInt()
ai, stk = stk.PopInt()
if bi != 0 {
stk = stk.Push(ai / bi)
} else {
stk = stk.Push(0)
}
case 'm': // push(pop mod pop)
bi, stk = stk.PopInt()
ai, stk = stk.PopInt()
if bi != 0 {
stk = stk.Push(ai % bi)
} else {
stk = stk.Push(0)
}
case '&': // AND
bi, stk = stk.PopInt()
ai, stk = stk.PopInt()
stk = stk.Push(ai & bi)
case '|': // OR
bi, stk = stk.PopInt()
ai, stk = stk.PopInt()
stk = stk.Push(ai | bi)
case '^': // XOR
bi, stk = stk.PopInt()
ai, stk = stk.PopInt()
stk = stk.Push(ai ^ bi)
case '~': // bit complement
ai, stk = stk.PopInt()
stk = stk.Push(ai ^ -1)
case '!': // logical NOT
ai, stk = stk.PopInt()
stk = stk.Push(ai == 0)
case '=': // numeric compare
bi, stk = stk.PopInt()
ai, stk = stk.PopInt()
stk = stk.Push(ai == bi)
case '>': // greater than, numeric
bi, stk = stk.PopInt()
ai, stk = stk.PopInt()
stk = stk.Push(ai > bi)
case '<': // less than, numeric
bi, stk = stk.PopInt()
ai, stk = stk.PopInt()
stk = stk.Push(ai < bi)
case '?': // start conditional
case ';':
skip = emit
case 't':
ai, stk = stk.PopInt()
if ai == 0 {
skip = toElse
}
case 'e':
skip = toEnd
default:
pb.PutString("%" + string(ch))
}
}
return pb.End()
}
// TPuts emits the string to the writer, but expands inline padding
// indications (of the form $<[delay]> where [delay] is msec) to
// a suitable time (unless the terminfo string indicates this isn't needed
// by specifying npc - no padding). All Terminfo based strings should be
// emitted using this function.
func (t *Terminfo) TPuts(w io.Writer, s string) {
for {
beg := strings.Index(s, "$<")
if beg < 0 {
// Most strings don't need padding, which is good news!
_, _ = io.WriteString(w, s)
return
}
_, _ = io.WriteString(w, s[:beg])
s = s[beg+2:]
end := strings.Index(s, ">")
if end < 0 {
// unterminated.. just emit bytes unadulterated
_, _ = io.WriteString(w, "$<"+s)
return
}
val := s[:end]
s = s[end+1:]
padus := 0
unit := time.Millisecond
dot := false
loop:
for i := range val {
switch val[i] {
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
padus *= 10
padus += int(val[i] - '0')
if dot {
unit /= 10
}
case '.':
if !dot {
dot = true
} else {
break loop
}
default:
break loop
}
}
// Curses historically uses padding to achieve "fine grained"
// delays. We have much better clocks these days, and so we
// do not rely on padding but simply sleep a bit.
if len(t.PadChar) > 0 {
time.Sleep(unit * time.Duration(padus))
}
}
}
// TGoto returns a string suitable for addressing the cursor at the given
// row and column. The origin 0, 0 is in the upper left corner of the screen.
func (t *Terminfo) TGoto(col, row int) string {
return t.TParm(t.SetCursor, row, col)
}
// TColor returns a string corresponding to the given foreground and background
// colors. Either fg or bg can be set to -1 to elide.
func (t *Terminfo) TColor(fi, bi int) string {
rv := ""
// As a special case, we map bright colors to lower versions if the
// color table only holds 8. For the remaining 240 colors, the user
// is out of luck. Someday we could create a mapping table, but its
// not worth it.
if t.Colors == 8 {
if fi > 7 && fi < 16 {
fi -= 8
}
if bi > 7 && bi < 16 {
bi -= 8
}
}
if t.Colors > fi && fi >= 0 {
rv += t.TParm(t.SetFg, fi)
}
if t.Colors > bi && bi >= 0 {
rv += t.TParm(t.SetBg, bi)
}
return rv
}
var (
dblock sync.Mutex
terminfos = make(map[string]*Terminfo)
)
// AddTerminfo can be called to register a new Terminfo entry.
func AddTerminfo(t *Terminfo) {
dblock.Lock()
terminfos[t.Name] = t
for _, x := range t.Aliases {
terminfos[x] = t
}
dblock.Unlock()
}
// LookupTerminfo attempts to find a definition for the named $TERM.
func LookupTerminfo(name string) (*Terminfo, error) {
if name == "" {
// else on windows: index out of bounds
// on the name[0] reference below
return nil, ErrTermNotFound
}
addtruecolor := false
add256color := false
switch os.Getenv("COLORTERM") {
case "truecolor", "24bit", "24-bit":
addtruecolor = true
}
dblock.Lock()
t := terminfos[name]
dblock.Unlock()
// If the name ends in -truecolor, then fabricate an entry
// from the corresponding -256color, -color, or bare terminal.
if t != nil && t.TrueColor {
addtruecolor = true
} else if t == nil && strings.HasSuffix(name, "-truecolor") {
suffixes := []string{
"-256color",
"-88color",
"-color",
"",
}
base := name[:len(name)-len("-truecolor")]
for _, s := range suffixes {
if t, _ = LookupTerminfo(base + s); t != nil {
addtruecolor = true
break
}
}
}
// If the name ends in -256color, maybe fabricate using the xterm 256 color sequences
if t == nil && strings.HasSuffix(name, "-256color") {
suffixes := []string{
"-88color",
"-color",
}
base := name[:len(name)-len("-256color")]
for _, s := range suffixes {
if t, _ = LookupTerminfo(base + s); t != nil {
add256color = true
break
}
}
}
if t == nil {
return nil, ErrTermNotFound
}
switch os.Getenv("TCELL_TRUECOLOR") {
case "":
case "disable":
addtruecolor = false
default:
addtruecolor = true
}
// If the user has requested 24-bit color with $COLORTERM, then
// amend the value (unless already present). This means we don't
// need to have a value present.
if addtruecolor &&
t.SetFgBgRGB == "" &&
t.SetFgRGB == "" &&
t.SetBgRGB == "" {
// Supply vanilla ISO 8613-6:1994 24-bit color sequences.
t.SetFgRGB = "\x1b[38;2;%p1%d;%p2%d;%p3%dm"
t.SetBgRGB = "\x1b[48;2;%p1%d;%p2%d;%p3%dm"
t.SetFgBgRGB = "\x1b[38;2;%p1%d;%p2%d;%p3%d;" +
"48;2;%p4%d;%p5%d;%p6%dm"
}
if add256color {
t.Colors = 256
t.SetFg = "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;m"
t.SetBg = "\x1b[%?%p1%{8}%<%t4%p1%d%e%p1%{16}%<%t10%p1%{8}%-%d%e48;5;%p1%d%;m"
t.SetFgBg = "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;;%?%p2%{8}%<%t4%p2%d%e%p2%{16}%<%t10%p2%{8}%-%d%e48;5;%p2%d%;m"
t.ResetFgBg = "\x1b[39;49m"
}
return t, nil
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
jesseduffield/lazydocker | https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/gdamore/tcell/v2/terminfo/f/foot/foot.go | vendor/github.com/gdamore/tcell/v2/terminfo/f/foot/foot.go | // Generated automatically. DO NOT HAND-EDIT.
package foot
import "github.com/gdamore/tcell/v2/terminfo"
func init() {
// foot terminal emulator
terminfo.AddTerminfo(&terminfo.Terminfo{
Name: "foot",
Aliases: []string{"foot-extra"},
Columns: 80,
Lines: 24,
Colors: 256,
Bell: "\a",
Clear: "\x1b[H\x1b[2J",
EnterCA: "\x1b[?1049h\x1b[22;0;0t",
ExitCA: "\x1b[?1049l\x1b[23;0;0t",
ShowCursor: "\x1b[?12l\x1b[?25h",
HideCursor: "\x1b[?25l",
AttrOff: "\x1b(B\x1b[m",
Underline: "\x1b[4m",
Bold: "\x1b[1m",
Dim: "\x1b[2m",
Italic: "\x1b[3m",
Blink: "\x1b[5m",
Reverse: "\x1b[7m",
EnterKeypad: "\x1b[?1h\x1b=",
ExitKeypad: "\x1b[?1l\x1b>",
SetFg: "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38:5:%p1%d%;m",
SetBg: "\x1b[%?%p1%{8}%<%t4%p1%d%e%p1%{16}%<%t10%p1%{8}%-%d%e48:5:%p1%d%;m",
SetFgBg: "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38:5:%p1%d%;;%?%p2%{8}%<%t4%p2%d%e%p2%{16}%<%t10%p2%{8}%-%d%e48:5:%p2%d%;m",
ResetFgBg: "\x1b[39;49m",
AltChars: "``aaffggiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~",
EnterAcs: "\x1b(0",
ExitAcs: "\x1b(B",
StrikeThrough: "\x1b[9m",
Mouse: "\x1b[M",
SetCursor: "\x1b[%i%p1%d;%p2%dH",
CursorBack1: "\b",
CursorUp1: "\x1b[A",
KeyUp: "\x1bOA",
KeyDown: "\x1bOB",
KeyRight: "\x1bOC",
KeyLeft: "\x1bOD",
KeyInsert: "\x1b[2~",
KeyDelete: "\x1b[3~",
KeyBackspace: "\u007f",
KeyHome: "\x1bOH",
KeyEnd: "\x1bOF",
KeyPgUp: "\x1b[5~",
KeyPgDn: "\x1b[6~",
KeyF1: "\x1bOP",
KeyF2: "\x1bOQ",
KeyF3: "\x1bOR",
KeyF4: "\x1bOS",
KeyF5: "\x1b[15~",
KeyF6: "\x1b[17~",
KeyF7: "\x1b[18~",
KeyF8: "\x1b[19~",
KeyF9: "\x1b[20~",
KeyF10: "\x1b[21~",
KeyF11: "\x1b[23~",
KeyF12: "\x1b[24~",
KeyBacktab: "\x1b[Z",
Modifiers: 1,
AutoMargin: true,
})
}
| go | MIT | f4fc3669ca8eb67aa350a76503397192bf26f057 | 2026-01-07T08:35:43.570558Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.