repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/red.rs
src/configs/red.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct RedConfig<'a> { pub format: &'a str, pub version_format: &'a str, pub symbol: &'a str, pub style: &'a str, pub disabled: bool, pub detect_extensions: Vec<&'a str>, pub detect_files: Vec<&'a str>, pub detect_folders: Vec<&'a str>, } impl Default for RedConfig<'_> { fn default() -> Self { Self { format: "via [$symbol($version )]($style)", version_format: "v${raw}", symbol: "🔺 ", style: "red bold", disabled: false, detect_extensions: vec!["red", "reds"], detect_files: vec![], detect_folders: vec![], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/os.rs
src/configs/os.rs
use indexmap::{IndexMap, indexmap}; use os_info::Type; use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct OSConfig<'a> { pub format: &'a str, pub style: &'a str, pub symbols: IndexMap<Type, &'a str>, pub disabled: bool, } impl<'a> OSConfig<'a> { pub fn get_symbol(&self, key: Type) -> Option<&'a str> { self.symbols.get(&key).copied() } } impl Default for OSConfig<'_> { fn default() -> Self { Self { format: "[$symbol]($style)", style: "bold white", symbols: indexmap! { Type::AIX => "➿ ", Type::Alpaquita => "🔔 ", Type::AlmaLinux => "💠 ", Type::Alpine => "🏔️ ", Type::ALTLinux => "Ⓐ ", Type::Amazon => "🙂 ", Type::Android => "🤖 ", Type::AOSC => "🐱 ", Type::Arch => "🎗️ ", Type::Artix => "🎗️ ", Type::Bluefin => "🐟 ", Type::CachyOS => "🎗️ ", Type::CentOS => "💠 ", Type::Debian => "🌀 ", Type::Elementary => "🍏 ", Type::DragonFly => "🐉 ", Type::Emscripten => "🔗 ", Type::EndeavourOS => "🚀 ", Type::Fedora => "🎩 ", Type::FreeBSD => "😈 ", Type::Garuda => "🦅 ", Type::Gentoo => "🗜️ ", Type::HardenedBSD => "🛡️ ", Type::Illumos => "🐦 ", Type::Ios => "📱 ", Type::InstantOS => "⏲️ ", Type::Kali => "🐉 ", Type::Linux => "🐧 ", Type::Mabox => "📦 ", Type::Macos => "🍎 ", Type::Manjaro => "🥭 ", Type::Mariner => "🌊 ", Type::MidnightBSD => "🌘 ", Type::Mint => "🌿 ", Type::NetBSD => "🚩 ", Type::NixOS => "❄️ ", Type::Nobara => "🎩 ", Type::OpenBSD => "🐡 ", Type::OpenCloudOS => "☁️ ", Type::openEuler => "🦉 ", Type::openSUSE => "🦎 ", Type::OracleLinux => "🦴 ", Type::PikaOS => "🐤 ", Type::Pop => "🍭 ", Type::Raspbian => "🍓 ", Type::Redhat => "🎩 ", Type::RedHatEnterprise => "🎩 ", Type::RockyLinux => "💠 ", Type::Redox => "🧪 ", Type::Solus => "⛵ ", Type::SUSE => "🦎 ", Type::Ubuntu => "🎯 ", Type::Ultramarine => "🔷 ", Type::Unknown => "❓ ", Type::Uos => "🐲 ", Type::Void => " ", Type::Windows => "🪟 ", Type::Zorin => "🔹 ", // Future symbols. //coreos => " ", //devuan => " ", //mageia => " ", //mandriva => " ", //sabayon => " ", //slackware => " ", //solaris => " ", }, disabled: true, } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/c.rs
src/configs/c.rs
use crate::configs::cc::CcConfig; use serde::{Deserialize, Serialize}; #[derive(Default, Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] pub struct CConfigMarker; pub type CConfig<'a> = CcConfig<'a, CConfigMarker>; impl Default for CConfig<'_> { fn default() -> Self { Self { marker: std::marker::PhantomData::<CConfigMarker>, format: "via [$symbol($version(-$name) )]($style)", version_format: "v${raw}", style: "149 bold", symbol: "C ", disabled: false, detect_extensions: vec!["c", "h"], detect_files: vec![], detect_folders: vec![], commands: vec![ // the compiler is usually cc, and --version works on gcc and clang vec!["cc", "--version"], // but on some platforms gcc is installed as *gcc*, not cc vec!["gcc", "--version"], // for completeness, although I've never seen a clang that wasn't cc vec!["clang", "--version"], ], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/container.rs
src/configs/container.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct ContainerConfig<'a> { pub format: &'a str, pub symbol: &'a str, pub style: &'a str, pub disabled: bool, } impl Default for ContainerConfig<'_> { fn default() -> Self { Self { format: "[$symbol \\[$name\\]]($style) ", symbol: "⬢", style: "red bold dimmed", disabled: false, } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/azure.rs
src/configs/azure.rs
use serde::{Deserialize, Serialize}; use std::collections::HashMap; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct AzureConfig<'a> { pub format: &'a str, pub symbol: &'a str, pub style: &'a str, pub disabled: bool, pub subscription_aliases: HashMap<String, &'a str>, } impl Default for AzureConfig<'_> { fn default() -> Self { Self { format: "on [$symbol($subscription)]($style) ", symbol: "󰠅 ", style: "blue bold", disabled: true, subscription_aliases: HashMap::new(), } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/status.rs
src/configs/status.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct StatusConfig<'a> { pub format: &'a str, pub symbol: &'a str, pub success_symbol: &'a str, pub not_executable_symbol: &'a str, pub not_found_symbol: &'a str, pub sigint_symbol: &'a str, pub signal_symbol: &'a str, pub style: &'a str, #[serde(skip_serializing_if = "Option::is_none")] pub success_style: Option<&'a str>, #[serde(skip_serializing_if = "Option::is_none")] pub failure_style: Option<&'a str>, pub map_symbol: bool, pub recognize_signal_code: bool, pub pipestatus: bool, pub pipestatus_separator: &'a str, pub pipestatus_format: &'a str, #[serde(skip_serializing_if = "Option::is_none")] pub pipestatus_segment_format: Option<&'a str>, pub disabled: bool, } impl Default for StatusConfig<'_> { fn default() -> Self { Self { format: "[$symbol$status]($style) ", symbol: "❌", success_symbol: "", not_executable_symbol: "🚫", not_found_symbol: "🔍", sigint_symbol: "🧱", signal_symbol: "⚡", style: "bold red", success_style: None, failure_style: None, map_symbol: false, recognize_signal_code: true, pipestatus: false, pipestatus_separator: "|", pipestatus_format: "\\[$pipestatus\\] => [$symbol$common_meaning$signal_name$maybe_int]($style) ", pipestatus_segment_format: None, disabled: true, } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/hostname.rs
src/configs/hostname.rs
use indexmap::IndexMap; use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct HostnameConfig<'a> { pub ssh_only: bool, pub ssh_symbol: &'a str, pub trim_at: &'a str, pub detect_env_vars: Vec<&'a str>, pub format: &'a str, pub style: &'a str, pub disabled: bool, pub aliases: IndexMap<String, &'a str>, } impl Default for HostnameConfig<'_> { fn default() -> Self { Self { ssh_only: true, ssh_symbol: "🌐 ", trim_at: ".", detect_env_vars: vec![], format: "[$ssh_symbol$hostname]($style) in ", style: "green dimmed bold", disabled: false, aliases: IndexMap::new(), } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/hg_state.rs
src/configs/hg_state.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct HgStateConfig<'a> { pub merge: &'a str, pub rebase: &'a str, pub update: &'a str, pub bisect: &'a str, pub shelve: &'a str, pub graft: &'a str, pub transplant: &'a str, pub histedit: &'a str, pub style: &'a str, pub format: &'a str, pub disabled: bool, } impl Default for HgStateConfig<'_> { fn default() -> Self { HgStateConfig { merge: "MERGING", rebase: "REBASING", update: "UPDATING", bisect: "BISECTING", shelve: "SHELVING", graft: "GRAFTING", transplant: "TRANSPLANTING", histedit: "HISTEDITING", style: "bold yellow", format: "\\([$state]($style)\\) ", disabled: true, } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/time.rs
src/configs/time.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct TimeConfig<'a> { pub format: &'a str, pub style: &'a str, pub use_12hr: bool, #[serde(skip_serializing_if = "Option::is_none")] pub time_format: Option<&'a str>, pub disabled: bool, pub utc_time_offset: &'a str, pub time_range: &'a str, } impl Default for TimeConfig<'_> { fn default() -> Self { Self { format: "at [$time]($style) ", style: "bold yellow", use_12hr: false, time_format: None, disabled: true, utc_time_offset: "local", time_range: "-", } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/deno.rs
src/configs/deno.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct DenoConfig<'a> { pub format: &'a str, pub version_format: &'a str, pub symbol: &'a str, pub style: &'a str, pub disabled: bool, pub detect_extensions: Vec<&'a str>, pub detect_files: Vec<&'a str>, pub detect_folders: Vec<&'a str>, } impl Default for DenoConfig<'_> { fn default() -> Self { Self { format: "via [$symbol($version )]($style)", version_format: "v${raw}", symbol: "🦕 ", style: "green bold", disabled: false, detect_extensions: vec![], detect_files: vec![ "deno.json", "deno.jsonc", "deno.lock", "mod.ts", "deps.ts", "mod.js", "deps.js", ], detect_folders: vec![], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/git_commit.rs
src/configs/git_commit.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct GitCommitConfig<'a> { pub commit_hash_length: usize, pub format: &'a str, pub style: &'a str, pub only_detached: bool, pub disabled: bool, pub tag_symbol: &'a str, pub tag_disabled: bool, pub tag_max_candidates: usize, } impl Default for GitCommitConfig<'_> { fn default() -> Self { Self { // be consistent with git by default, which has DEFAULT_ABBREV set to 7 commit_hash_length: 7, format: "[\\($hash$tag\\)]($style) ", style: "green bold", only_detached: true, disabled: false, tag_symbol: " 🏷 ", tag_disabled: true, tag_max_candidates: 0, } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/shell.rs
src/configs/shell.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct ShellConfig<'a> { pub format: &'a str, pub bash_indicator: &'a str, pub fish_indicator: &'a str, pub zsh_indicator: &'a str, pub powershell_indicator: &'a str, #[serde(skip_serializing_if = "Option::is_none")] pub pwsh_indicator: Option<&'a str>, pub ion_indicator: &'a str, pub elvish_indicator: &'a str, pub tcsh_indicator: &'a str, pub nu_indicator: &'a str, pub xonsh_indicator: &'a str, pub cmd_indicator: &'a str, pub unknown_indicator: &'a str, pub style: &'a str, pub disabled: bool, } impl Default for ShellConfig<'_> { fn default() -> Self { Self { format: "[$indicator]($style) ", bash_indicator: "bsh", fish_indicator: "fsh", zsh_indicator: "zsh", powershell_indicator: "psh", pwsh_indicator: None, ion_indicator: "ion", elvish_indicator: "esh", tcsh_indicator: "tsh", nu_indicator: "nu", xonsh_indicator: "xsh", cmd_indicator: "cmd", unknown_indicator: "", style: "white bold", disabled: true, } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/python.rs
src/configs/python.rs
use crate::config::VecOr; use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct PythonConfig<'a> { pub pyenv_version_name: bool, pub pyenv_prefix: &'a str, pub python_binary: VecOr<VecOr<&'a str>>, pub format: &'a str, pub version_format: &'a str, pub style: &'a str, pub symbol: &'a str, pub disabled: bool, pub detect_extensions: Vec<&'a str>, pub detect_files: Vec<&'a str>, pub detect_folders: Vec<&'a str>, pub detect_env_vars: Vec<&'a str>, } impl Default for PythonConfig<'_> { fn default() -> Self { Self { pyenv_version_name: false, pyenv_prefix: "pyenv ", python_binary: VecOr(vec![ VecOr(vec!["python"]), VecOr(vec!["python3"]), VecOr(vec!["python2"]), ]), format: "via [${symbol}${pyenv_prefix}(${version} )(\\($virtualenv\\) )]($style)", version_format: "v${raw}", style: "yellow bold", symbol: "🐍 ", disabled: false, detect_extensions: vec!["py", "ipynb"], detect_files: vec![ "requirements.txt", ".python-version", "pyproject.toml", "Pipfile", "tox.ini", "setup.py", "__init__.py", ], detect_folders: vec![], detect_env_vars: vec!["VIRTUAL_ENV"], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/pijul_channel.rs
src/configs/pijul_channel.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct PijulConfig<'a> { pub symbol: &'a str, pub style: &'a str, pub format: &'a str, pub truncation_length: i64, pub truncation_symbol: &'a str, pub disabled: bool, } impl Default for PijulConfig<'_> { fn default() -> Self { Self { symbol: " ", style: "bold purple", format: "on [$symbol$channel]($style) ", truncation_length: i64::MAX, truncation_symbol: "…", disabled: true, } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/spack.rs
src/configs/spack.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct SpackConfig<'a> { pub truncation_length: usize, pub format: &'a str, pub symbol: &'a str, pub style: &'a str, pub disabled: bool, } impl Default for SpackConfig<'_> { fn default() -> Self { Self { truncation_length: 1, format: "via [$symbol$environment]($style) ", symbol: "🅢 ", style: "blue bold", disabled: false, } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/ocaml.rs
src/configs/ocaml.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct OCamlConfig<'a> { pub format: &'a str, pub version_format: &'a str, pub global_switch_indicator: &'a str, pub local_switch_indicator: &'a str, pub symbol: &'a str, pub style: &'a str, pub disabled: bool, pub detect_extensions: Vec<&'a str>, pub detect_files: Vec<&'a str>, pub detect_folders: Vec<&'a str>, } impl Default for OCamlConfig<'_> { fn default() -> Self { Self { format: "via [$symbol($version )(\\($switch_indicator$switch_name\\) )]($style)", version_format: "v${raw}", global_switch_indicator: "", local_switch_indicator: "*", symbol: "🐫 ", style: "bold yellow", disabled: false, detect_extensions: vec!["opam", "ml", "mli", "re", "rei"], detect_files: vec!["dune", "dune-project", "jbuild", "jbuild-ignore", ".merlin"], detect_folders: vec!["_opam", "esy.lock"], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/mise.rs
src/configs/mise.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct MiseConfig<'a> { pub format: &'a str, pub symbol: &'a str, pub style: &'a str, pub disabled: bool, pub detect_extensions: Vec<&'a str>, pub detect_files: Vec<&'a str>, pub detect_folders: Vec<&'a str>, pub healthy_symbol: &'a str, pub unhealthy_symbol: &'a str, } impl Default for MiseConfig<'_> { fn default() -> Self { Self { format: "on [$symbol$health]($style) ", symbol: "mise ", style: "bold purple", disabled: true, detect_extensions: vec![], detect_files: vec![ "mise.toml", "mise.local.toml", ".mise.toml", ".mise.local.toml", ], detect_folders: vec![".mise"], healthy_symbol: "healthy", unhealthy_symbol: "unhealthy", } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/singularity.rs
src/configs/singularity.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct SingularityConfig<'a> { pub symbol: &'a str, pub format: &'a str, pub style: &'a str, pub disabled: bool, } impl Default for SingularityConfig<'_> { fn default() -> Self { Self { format: "[$symbol\\[$env\\]]($style) ", symbol: "", style: "blue bold dimmed", disabled: false, } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/raku.rs
src/configs/raku.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct RakuConfig<'a> { pub format: &'a str, pub version_format: &'a str, pub symbol: &'a str, pub style: &'a str, pub disabled: bool, pub detect_extensions: Vec<&'a str>, pub detect_files: Vec<&'a str>, pub detect_folders: Vec<&'a str>, } impl Default for RakuConfig<'_> { fn default() -> Self { RakuConfig { format: "via [$symbol($version-$vm_version )]($style)", version_format: "${raw}", symbol: "🦋 ", style: "149 bold", disabled: false, detect_extensions: vec!["p6", "pm6", "pod6", "raku", "rakumod"], detect_files: vec!["META6.json"], detect_folders: vec![], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/nix_shell.rs
src/configs/nix_shell.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct NixShellConfig<'a> { pub format: &'a str, pub symbol: &'a str, pub style: &'a str, pub impure_msg: &'a str, pub pure_msg: &'a str, pub unknown_msg: &'a str, pub disabled: bool, pub heuristic: bool, } /* The trailing double spaces in `symbol` are needed to work around issues with multiwidth emoji support in some shells. Please do not file a PR to change this unless you can show that your changes do not affect this workaround. */ impl Default for NixShellConfig<'_> { fn default() -> Self { Self { format: "via [$symbol$state( \\($name\\))]($style) ", symbol: "❄️ ", style: "bold blue", impure_msg: "impure", pure_msg: "pure", unknown_msg: "", disabled: false, heuristic: false, } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/conda.rs
src/configs/conda.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct CondaConfig<'a> { pub truncation_length: usize, pub format: &'a str, pub symbol: &'a str, pub style: &'a str, pub ignore_base: bool, pub detect_env_vars: Vec<&'a str>, pub disabled: bool, } impl Default for CondaConfig<'_> { fn default() -> Self { Self { truncation_length: 1, format: "via [$symbol$environment]($style) ", symbol: "🅒 ", style: "green bold", ignore_base: true, detect_env_vars: vec!["!PIXI_ENVIRONMENT_NAME"], disabled: false, } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/helm.rs
src/configs/helm.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct HelmConfig<'a> { pub format: &'a str, pub version_format: &'a str, pub symbol: &'a str, pub style: &'a str, pub disabled: bool, pub detect_extensions: Vec<&'a str>, pub detect_files: Vec<&'a str>, pub detect_folders: Vec<&'a str>, } impl Default for HelmConfig<'_> { fn default() -> Self { Self { format: "via [$symbol($version )]($style)", version_format: "v${raw}", symbol: "⎈ ", style: "bold white", disabled: false, detect_extensions: vec![], detect_files: vec!["helmfile.yaml", "Chart.yaml"], detect_folders: vec![], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/rlang.rs
src/configs/rlang.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct RLangConfig<'a> { pub format: &'a str, pub version_format: &'a str, pub style: &'a str, pub symbol: &'a str, pub disabled: bool, pub detect_extensions: Vec<&'a str>, pub detect_files: Vec<&'a str>, pub detect_folders: Vec<&'a str>, } impl Default for RLangConfig<'_> { fn default() -> Self { Self { format: "via [$symbol($version )]($style)", version_format: "v${raw}", style: "blue bold", symbol: "📐 ", disabled: false, detect_extensions: vec!["R", "Rd", "Rmd", "Rproj", "Rsx"], detect_files: vec!["DESCRIPTION"], detect_folders: vec![".Rproj.user"], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/pulumi.rs
src/configs/pulumi.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct PulumiConfig<'a> { pub format: &'a str, pub version_format: &'a str, pub symbol: &'a str, pub style: &'a str, pub disabled: bool, pub search_upwards: bool, } impl Default for PulumiConfig<'_> { fn default() -> Self { Self { format: "via [$symbol($username@)$stack]($style) ", version_format: "v${raw}", symbol: " ", style: "bold 5", disabled: false, search_upwards: true, } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/solidity.rs
src/configs/solidity.rs
use serde::{Deserialize, Serialize}; use crate::config::VecOr; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct SolidityConfig<'a> { pub format: &'a str, pub version_format: &'a str, pub disabled: bool, pub style: &'a str, pub symbol: &'a str, pub compiler: VecOr<&'a str>, pub detect_extensions: Vec<&'a str>, pub detect_files: Vec<&'a str>, pub detect_folders: Vec<&'a str>, } impl Default for SolidityConfig<'_> { fn default() -> Self { Self { format: "via [$symbol($version)]($style)", symbol: "S ", style: "bold blue", compiler: VecOr(vec!["solc"]), version_format: "v${major}.${minor}.${patch}", disabled: false, detect_extensions: vec!["sol"], detect_files: vec![], detect_folders: vec![], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/terraform.rs
src/configs/terraform.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct TerraformConfig<'a> { pub format: &'a str, pub version_format: &'a str, pub symbol: &'a str, pub style: &'a str, pub disabled: bool, pub detect_extensions: Vec<&'a str>, pub detect_files: Vec<&'a str>, pub detect_folders: Vec<&'a str>, pub commands: Vec<Vec<&'a str>>, } impl Default for TerraformConfig<'_> { fn default() -> Self { Self { format: "via [$symbol$workspace]($style) ", version_format: "v${raw}", symbol: "💠 ", style: "bold 105", disabled: false, detect_extensions: vec!["tf", "tfplan", "tfstate"], detect_files: vec![], detect_folders: vec![".terraform"], commands: vec![ // terraform is usually `terraform` vec!["terraform", "version"], // but for opentofu users, it'll be `tofu` vec!["tofu", "version"], ], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/git_branch.rs
src/configs/git_branch.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct GitBranchConfig<'a> { pub format: &'a str, pub symbol: &'a str, pub style: &'a str, pub truncation_length: i64, pub truncation_symbol: &'a str, pub only_attached: bool, pub always_show_remote: bool, pub ignore_branches: Vec<&'a str>, pub ignore_bare_repo: bool, pub disabled: bool, } impl Default for GitBranchConfig<'_> { fn default() -> Self { Self { format: "on [$symbol$branch(:$remote_branch)]($style) ", symbol: " ", style: "bold purple", truncation_length: i64::MAX, truncation_symbol: "…", only_attached: false, always_show_remote: false, ignore_branches: vec![], ignore_bare_repo: false, disabled: false, } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/fossil_metrics.rs
src/configs/fossil_metrics.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct FossilMetricsConfig<'a> { pub format: &'a str, pub added_style: &'a str, pub deleted_style: &'a str, pub only_nonzero_diffs: bool, pub disabled: bool, } impl Default for FossilMetricsConfig<'_> { fn default() -> Self { Self { format: "([+$added]($added_style) )([-$deleted]($deleted_style) )", added_style: "bold green", deleted_style: "bold red", only_nonzero_diffs: true, disabled: true, } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/xmake.rs
src/configs/xmake.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct XMakeConfig<'a> { pub format: &'a str, pub version_format: &'a str, pub symbol: &'a str, pub style: &'a str, pub disabled: bool, pub detect_extensions: Vec<&'a str>, pub detect_files: Vec<&'a str>, pub detect_folders: Vec<&'a str>, } impl Default for XMakeConfig<'_> { fn default() -> Self { Self { format: "via [$symbol($version )]($style)", version_format: "v${raw}", symbol: "△ ", style: "bold green", disabled: false, detect_extensions: vec![], detect_files: vec!["xmake.lua"], detect_folders: vec![], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/gcloud.rs
src/configs/gcloud.rs
use serde::{Deserialize, Serialize}; use std::collections::HashMap; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct GcloudConfig<'a> { pub format: &'a str, pub symbol: &'a str, pub style: &'a str, pub disabled: bool, pub region_aliases: HashMap<String, &'a str>, pub project_aliases: HashMap<String, &'a str>, pub detect_env_vars: Vec<&'a str>, } impl Default for GcloudConfig<'_> { fn default() -> Self { Self { format: "on [$symbol$account(@$domain)(\\($region\\))]($style) ", symbol: "☁️ ", style: "bold blue", disabled: false, region_aliases: HashMap::new(), project_aliases: HashMap::new(), detect_env_vars: vec![], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/mod.rs
src/configs/mod.rs
use indexmap::IndexMap; use serde::{self, Deserialize, Serialize}; pub mod aws; pub mod azure; pub mod battery; pub mod buf; pub mod bun; pub mod c; pub mod cc; pub mod character; pub mod cmake; pub mod cmd_duration; pub mod cobol; pub mod conda; pub mod container; pub mod cpp; pub mod crystal; pub mod custom; pub mod daml; pub mod dart; pub mod deno; pub mod directory; pub mod direnv; pub mod docker_context; pub mod dotnet; pub mod elixir; pub mod elm; pub mod env_var; pub mod erlang; pub mod fennel; pub mod fill; pub mod fortran; pub mod fossil_branch; pub mod fossil_metrics; pub mod gcloud; pub mod git_branch; pub mod git_commit; pub mod git_metrics; pub mod git_state; pub mod git_status; pub mod gleam; pub mod go; pub mod gradle; pub mod guix_shell; pub mod haskell; pub mod haxe; pub mod helm; pub mod hg_branch; pub mod hg_state; pub mod hostname; pub mod java; pub mod jobs; pub mod julia; pub mod kotlin; pub mod kubernetes; pub mod line_break; pub mod localip; pub mod lua; pub mod memory_usage; pub mod meson; pub mod mise; pub mod mojo; pub mod nats; pub mod netns; pub mod nim; pub mod nix_shell; pub mod nodejs; pub mod ocaml; pub mod odin; pub mod opa; pub mod openstack; pub mod os; pub mod package; pub mod perl; pub mod php; pub mod pijul_channel; pub mod pixi; pub mod pulumi; pub mod purescript; pub mod python; pub mod quarto; pub mod raku; pub mod red; pub mod rlang; pub mod ruby; pub mod rust; pub mod scala; pub mod shell; pub mod shlvl; pub mod singularity; pub mod solidity; pub mod spack; mod starship_root; pub mod status; pub mod sudo; pub mod swift; pub mod terraform; pub mod time; pub mod typst; pub mod username; pub mod v; pub mod vagrant; pub mod vcsh; pub mod xmake; pub mod zig; pub use starship_root::*; #[derive(Serialize, Deserialize, Clone, Default)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct FullConfig<'a> { // Meta #[serde(rename = "$schema")] schema: String, // Root config #[serde(flatten)] root: StarshipRootConfig, // modules #[serde(borrow)] aws: aws::AwsConfig<'a>, #[serde(borrow)] azure: azure::AzureConfig<'a>, #[serde(borrow)] battery: battery::BatteryConfig<'a>, #[serde(borrow)] buf: buf::BufConfig<'a>, #[serde(borrow)] bun: bun::BunConfig<'a>, #[serde(borrow)] c: c::CConfig<'a>, #[serde(borrow)] character: character::CharacterConfig<'a>, #[serde(borrow)] cmake: cmake::CMakeConfig<'a>, #[serde(borrow)] cmd_duration: cmd_duration::CmdDurationConfig<'a>, #[serde(borrow)] cobol: cobol::CobolConfig<'a>, #[serde(borrow)] conda: conda::CondaConfig<'a>, #[serde(borrow)] container: container::ContainerConfig<'a>, #[serde(borrow)] cpp: cpp::CppConfig<'a>, #[serde(borrow)] crystal: crystal::CrystalConfig<'a>, #[serde(borrow)] daml: daml::DamlConfig<'a>, #[serde(borrow)] dart: dart::DartConfig<'a>, #[serde(borrow)] deno: deno::DenoConfig<'a>, #[serde(borrow)] directory: directory::DirectoryConfig<'a>, #[serde(borrow)] direnv: direnv::DirenvConfig<'a>, #[serde(borrow)] docker_context: docker_context::DockerContextConfig<'a>, #[serde(borrow)] dotnet: dotnet::DotnetConfig<'a>, #[serde(borrow)] elixir: elixir::ElixirConfig<'a>, #[serde(borrow)] elm: elm::ElmConfig<'a>, #[serde(borrow)] env_var: IndexMap<String, env_var::EnvVarConfig<'a>>, #[serde(borrow)] erlang: erlang::ErlangConfig<'a>, #[serde(borrow)] fennel: fennel::FennelConfig<'a>, #[serde(borrow)] fill: fill::FillConfig<'a>, #[serde(borrow)] fortran: fortran::FortranConfig<'a>, #[serde(borrow)] fossil_branch: fossil_branch::FossilBranchConfig<'a>, #[serde(borrow)] fossil_metrics: fossil_metrics::FossilMetricsConfig<'a>, #[serde(borrow)] gcloud: gcloud::GcloudConfig<'a>, #[serde(borrow)] git_branch: git_branch::GitBranchConfig<'a>, #[serde(borrow)] git_commit: git_commit::GitCommitConfig<'a>, #[serde(borrow)] git_metrics: git_metrics::GitMetricsConfig<'a>, #[serde(borrow)] git_state: git_state::GitStateConfig<'a>, #[serde(borrow)] git_status: git_status::GitStatusConfig<'a>, #[serde(borrow)] gleam: gleam::GleamConfig<'a>, #[serde(borrow)] golang: go::GoConfig<'a>, #[serde(borrow)] gradle: gradle::GradleConfig<'a>, #[serde(borrow)] guix_shell: guix_shell::GuixShellConfig<'a>, #[serde(borrow)] haskell: haskell::HaskellConfig<'a>, #[serde(borrow)] haxe: haxe::HaxeConfig<'a>, #[serde(borrow)] helm: helm::HelmConfig<'a>, #[serde(borrow)] hg_branch: hg_branch::HgBranchConfig<'a>, #[serde(borrow)] hg_state: hg_state::HgStateConfig<'a>, #[serde(borrow)] hostname: hostname::HostnameConfig<'a>, #[serde(borrow)] java: java::JavaConfig<'a>, #[serde(borrow)] jobs: jobs::JobsConfig<'a>, #[serde(borrow)] julia: julia::JuliaConfig<'a>, #[serde(borrow)] kotlin: kotlin::KotlinConfig<'a>, #[serde(borrow)] kubernetes: kubernetes::KubernetesConfig<'a>, line_break: line_break::LineBreakConfig, #[serde(borrow)] localip: localip::LocalipConfig<'a>, #[serde(borrow)] lua: lua::LuaConfig<'a>, #[serde(borrow)] memory_usage: memory_usage::MemoryConfig<'a>, #[serde(borrow)] meson: meson::MesonConfig<'a>, #[serde(borrow)] mise: mise::MiseConfig<'a>, #[serde(borrow)] mojo: mojo::MojoConfig<'a>, #[serde(borrow)] nats: nats::NatsConfig<'a>, #[serde(borrow)] netns: netns::NetnsConfig<'a>, #[serde(borrow)] nim: nim::NimConfig<'a>, #[serde(borrow)] nix_shell: nix_shell::NixShellConfig<'a>, #[serde(borrow)] nodejs: nodejs::NodejsConfig<'a>, #[serde(borrow)] ocaml: ocaml::OCamlConfig<'a>, #[serde(borrow)] odin: odin::OdinConfig<'a>, #[serde(borrow)] opa: opa::OpaConfig<'a>, #[serde(borrow)] openstack: openstack::OspConfig<'a>, #[serde(borrow)] os: os::OSConfig<'a>, #[serde(borrow)] package: package::PackageConfig<'a>, #[serde(borrow)] perl: perl::PerlConfig<'a>, #[serde(borrow)] php: php::PhpConfig<'a>, #[serde(borrow)] pijul_channel: pijul_channel::PijulConfig<'a>, #[serde(borrow)] pixi: pixi::PixiConfig<'a>, #[serde(borrow)] pulumi: pulumi::PulumiConfig<'a>, #[serde(borrow)] purescript: purescript::PureScriptConfig<'a>, #[serde(borrow)] python: python::PythonConfig<'a>, #[serde(borrow)] quarto: quarto::QuartoConfig<'a>, #[serde(borrow)] raku: raku::RakuConfig<'a>, #[serde(borrow)] red: red::RedConfig<'a>, #[serde(borrow)] rlang: rlang::RLangConfig<'a>, #[serde(borrow)] ruby: ruby::RubyConfig<'a>, #[serde(borrow)] rust: rust::RustConfig<'a>, #[serde(borrow)] scala: scala::ScalaConfig<'a>, #[serde(borrow)] shell: shell::ShellConfig<'a>, #[serde(borrow)] shlvl: shlvl::ShLvlConfig<'a>, #[serde(borrow)] singularity: singularity::SingularityConfig<'a>, #[serde(borrow)] solidity: solidity::SolidityConfig<'a>, #[serde(borrow)] spack: spack::SpackConfig<'a>, #[serde(borrow)] status: status::StatusConfig<'a>, #[serde(borrow)] sudo: sudo::SudoConfig<'a>, #[serde(borrow)] swift: swift::SwiftConfig<'a>, #[serde(borrow)] terraform: terraform::TerraformConfig<'a>, #[serde(borrow)] time: time::TimeConfig<'a>, #[serde(borrow)] typst: typst::TypstConfig<'a>, #[serde(borrow)] username: username::UsernameConfig<'a>, #[serde(borrow)] vagrant: vagrant::VagrantConfig<'a>, #[serde(borrow)] vcsh: vcsh::VcshConfig<'a>, #[serde(borrow)] vlang: v::VConfig<'a>, #[serde(borrow)] xmake: xmake::XMakeConfig<'a>, #[serde(borrow)] zig: zig::ZigConfig<'a>, #[serde(borrow)] custom: IndexMap<String, custom::CustomConfig<'a>>, } #[cfg(test)] mod test { use super::*; use crate::module::ALL_MODULES; use toml::value::Value; #[test] fn test_all_modules_in_full_config() { let full_cfg = Value::try_from(FullConfig::default()).unwrap(); let cfg_table = full_cfg.as_table().unwrap(); for module in ALL_MODULES { assert!(cfg_table.contains_key(*module)); } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/pixi.rs
src/configs/pixi.rs
use serde::{Deserialize, Serialize}; use crate::config::VecOr; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct PixiConfig<'a> { pub pixi_binary: VecOr<&'a str>, pub show_default_environment: bool, pub format: &'a str, pub version_format: &'a str, pub symbol: &'a str, pub style: &'a str, pub disabled: bool, pub detect_extensions: Vec<&'a str>, pub detect_files: Vec<&'a str>, pub detect_folders: Vec<&'a str>, } impl Default for PixiConfig<'_> { fn default() -> Self { Self { pixi_binary: VecOr(vec!["pixi"]), show_default_environment: true, format: "via [$symbol($version )(\\($environment\\) )]($style)", version_format: "v${raw}", symbol: "🧚 ", style: "yellow bold", disabled: false, detect_extensions: vec![], detect_files: vec!["pixi.toml", "pixi.lock"], detect_folders: vec![], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/java.rs
src/configs/java.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct JavaConfig<'a> { pub disabled: bool, pub format: &'a str, pub version_format: &'a str, pub style: &'a str, pub symbol: &'a str, pub detect_extensions: Vec<&'a str>, pub detect_files: Vec<&'a str>, pub detect_folders: Vec<&'a str>, } impl Default for JavaConfig<'_> { fn default() -> Self { Self { format: "via [$symbol($version )]($style)", version_format: "v${raw}", disabled: false, style: "red dimmed", symbol: "☕ ", detect_extensions: vec!["java", "class", "jar", "gradle", "clj", "cljc"], detect_files: vec![ "pom.xml", "build.gradle.kts", "build.sbt", ".java-version", "deps.edn", "project.clj", "build.boot", ".sdkmanrc", ], detect_folders: vec![], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/hg_branch.rs
src/configs/hg_branch.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct HgBranchConfig<'a> { pub symbol: &'a str, pub style: &'a str, pub format: &'a str, pub truncation_length: i64, pub truncation_symbol: &'a str, pub disabled: bool, } impl Default for HgBranchConfig<'_> { fn default() -> Self { Self { symbol: " ", style: "bold purple", format: "on [$symbol$branch(:$topic)]($style) ", truncation_length: i64::MAX, truncation_symbol: "…", disabled: true, } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/character.rs
src/configs/character.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct CharacterConfig<'a> { pub format: &'a str, pub success_symbol: &'a str, pub error_symbol: &'a str, #[serde(alias = "vicmd_symbol")] pub vimcmd_symbol: &'a str, pub vimcmd_visual_symbol: &'a str, pub vimcmd_replace_symbol: &'a str, pub vimcmd_replace_one_symbol: &'a str, pub disabled: bool, } impl Default for CharacterConfig<'_> { fn default() -> Self { Self { format: "$symbol ", success_symbol: "[❯](bold green)", error_symbol: "[❯](bold red)", vimcmd_symbol: "[❮](bold green)", vimcmd_visual_symbol: "[❮](bold yellow)", vimcmd_replace_symbol: "[❮](bold purple)", vimcmd_replace_one_symbol: "[❮](bold purple)", disabled: false, } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/zig.rs
src/configs/zig.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct ZigConfig<'a> { pub format: &'a str, pub version_format: &'a str, pub symbol: &'a str, pub style: &'a str, pub disabled: bool, pub detect_extensions: Vec<&'a str>, pub detect_files: Vec<&'a str>, pub detect_folders: Vec<&'a str>, } impl Default for ZigConfig<'_> { fn default() -> Self { Self { format: "via [$symbol($version )]($style)", version_format: "v${raw}", symbol: "↯ ", style: "bold yellow", disabled: false, detect_extensions: vec!["zig"], detect_files: vec![], detect_folders: vec![], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/bun.rs
src/configs/bun.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct BunConfig<'a> { pub format: &'a str, pub version_format: &'a str, pub symbol: &'a str, pub style: &'a str, pub disabled: bool, pub detect_extensions: Vec<&'a str>, pub detect_files: Vec<&'a str>, pub detect_folders: Vec<&'a str>, } impl Default for BunConfig<'_> { fn default() -> Self { Self { format: "via [$symbol($version )]($style)", version_format: "v${raw}", symbol: "🥟 ", style: "bold red", disabled: false, detect_extensions: vec![], detect_files: vec!["bun.lock", "bun.lockb", "bunfig.toml"], detect_folders: vec![], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/nats.rs
src/configs/nats.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct NatsConfig<'a> { pub format: &'a str, pub symbol: &'a str, pub style: &'a str, pub disabled: bool, } impl Default for NatsConfig<'_> { fn default() -> Self { Self { format: "[$symbol($name )]($style)", symbol: "✉️ ", style: "bold purple", disabled: true, } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/cmake.rs
src/configs/cmake.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct CMakeConfig<'a> { pub format: &'a str, pub version_format: &'a str, pub symbol: &'a str, pub style: &'a str, pub disabled: bool, pub detect_extensions: Vec<&'a str>, pub detect_files: Vec<&'a str>, pub detect_folders: Vec<&'a str>, } impl Default for CMakeConfig<'_> { fn default() -> Self { Self { format: "via [$symbol($version )]($style)", version_format: "v${raw}", symbol: "△ ", style: "bold blue", disabled: false, detect_extensions: vec![], detect_files: vec!["CMakeLists.txt", "CMakeCache.txt"], detect_folders: vec![], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/fossil_branch.rs
src/configs/fossil_branch.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct FossilBranchConfig<'a> { pub format: &'a str, pub symbol: &'a str, pub style: &'a str, pub truncation_length: i64, pub truncation_symbol: &'a str, pub disabled: bool, } impl Default for FossilBranchConfig<'_> { fn default() -> Self { Self { format: "on [$symbol$branch]($style) ", symbol: " ", style: "bold purple", truncation_length: i64::MAX, truncation_symbol: "…", disabled: true, } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/opa.rs
src/configs/opa.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct OpaConfig<'a> { pub format: &'a str, pub version_format: &'a str, pub symbol: &'a str, pub style: &'a str, pub disabled: bool, pub detect_extensions: Vec<&'a str>, pub detect_files: Vec<&'a str>, pub detect_folders: Vec<&'a str>, } impl Default for OpaConfig<'_> { fn default() -> Self { Self { format: "via [$symbol($version )]($style)", version_format: "v${raw}", symbol: "🪖 ", style: "bold blue", disabled: false, detect_extensions: vec!["rego"], detect_files: vec![], detect_folders: vec![], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/docker_context.rs
src/configs/docker_context.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct DockerContextConfig<'a> { pub symbol: &'a str, pub style: &'a str, pub format: &'a str, pub only_with_files: bool, pub disabled: bool, pub detect_extensions: Vec<&'a str>, pub detect_files: Vec<&'a str>, pub detect_folders: Vec<&'a str>, } impl Default for DockerContextConfig<'_> { fn default() -> Self { Self { symbol: "🐳 ", style: "blue bold", format: "via [$symbol$context]($style) ", only_with_files: true, disabled: false, detect_extensions: vec![], detect_files: vec![ "compose.yml", "compose.yaml", "docker-compose.yml", "docker-compose.yaml", "Dockerfile", ], detect_folders: vec![], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/lua.rs
src/configs/lua.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct LuaConfig<'a> { pub format: &'a str, pub version_format: &'a str, pub symbol: &'a str, pub style: &'a str, pub lua_binary: &'a str, pub disabled: bool, pub detect_extensions: Vec<&'a str>, pub detect_files: Vec<&'a str>, pub detect_folders: Vec<&'a str>, } impl Default for LuaConfig<'_> { fn default() -> Self { Self { format: "via [$symbol($version )]($style)", version_format: "v${raw}", symbol: "🌙 ", style: "bold blue", lua_binary: "lua", disabled: false, detect_extensions: vec!["lua"], detect_files: vec![".lua-version"], detect_folders: vec!["lua"], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/netns.rs
src/configs/netns.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct NetnsConfig<'a> { pub format: &'a str, pub symbol: &'a str, pub style: &'a str, pub disabled: bool, } impl Default for NetnsConfig<'_> { fn default() -> Self { Self { format: "[$symbol \\[$name\\]]($style) ", symbol: "🛜", style: "blue bold dimmed", disabled: false, } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/git_metrics.rs
src/configs/git_metrics.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct GitMetricsConfig<'a> { pub added_style: &'a str, pub deleted_style: &'a str, pub only_nonzero_diffs: bool, pub format: &'a str, pub disabled: bool, pub ignore_submodules: bool, } impl Default for GitMetricsConfig<'_> { fn default() -> Self { Self { added_style: "bold green", deleted_style: "bold red", only_nonzero_diffs: true, format: "([+$added]($added_style) )([-$deleted]($deleted_style) )", disabled: true, ignore_submodules: false, } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/fortran.rs
src/configs/fortran.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct FortranConfig<'a> { pub format: &'a str, pub version_format: &'a str, pub symbol: &'a str, pub style: &'a str, pub disabled: bool, pub detect_extensions: Vec<&'a str>, pub detect_files: Vec<&'a str>, pub detect_folders: Vec<&'a str>, pub commands: Vec<Vec<&'a str>>, } impl Default for FortranConfig<'_> { fn default() -> Self { FortranConfig { format: "via [$symbol($version(-$name) )]($style)", version_format: "${raw}", symbol: "🅵 ", style: "bold purple", disabled: false, detect_extensions: vec![ "f", "F", "for", "FOR", "ftn", "FTN", "f77", "F77", "f90", "F90", "f95", "F95", "f03", "F03", "f08", "F08", "f18", "F18", ], detect_files: vec!["fpm.toml"], detect_folders: vec![], commands: vec![ // first check for most common 'gfortran' by default vec!["gfortran", "--version"], vec!["flang", "--version"], vec!["flang-new", "--version"], ], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/odin.rs
src/configs/odin.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct OdinConfig<'a> { pub format: &'a str, pub show_commit: bool, pub symbol: &'a str, pub style: &'a str, pub disabled: bool, pub detect_extensions: Vec<&'a str>, pub detect_files: Vec<&'a str>, pub detect_folders: Vec<&'a str>, } impl Default for OdinConfig<'_> { fn default() -> Self { Self { format: "via [$symbol($version )]($style)", show_commit: false, symbol: "Ø ", style: "bold bright-blue", disabled: false, detect_extensions: vec!["odin"], detect_files: vec![], detect_folders: vec![], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/crystal.rs
src/configs/crystal.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct CrystalConfig<'a> { pub format: &'a str, pub version_format: &'a str, pub symbol: &'a str, pub style: &'a str, pub disabled: bool, pub detect_extensions: Vec<&'a str>, pub detect_files: Vec<&'a str>, pub detect_folders: Vec<&'a str>, } impl Default for CrystalConfig<'_> { fn default() -> Self { Self { format: "via [$symbol($version )]($style)", version_format: "v${raw}", symbol: "🔮 ", style: "bold red", disabled: false, detect_extensions: vec!["cr"], detect_files: vec!["shard.yml"], detect_folders: vec![], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/haxe.rs
src/configs/haxe.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct HaxeConfig<'a> { pub format: &'a str, pub version_format: &'a str, pub symbol: &'a str, pub style: &'a str, pub disabled: bool, pub detect_extensions: Vec<&'a str>, pub detect_files: Vec<&'a str>, pub detect_folders: Vec<&'a str>, } impl Default for HaxeConfig<'_> { fn default() -> Self { Self { format: "via [$symbol($version )]($style)", version_format: "v${raw}", symbol: "⌘ ", style: "bold fg:202", disabled: false, detect_extensions: vec!["hx", "hxml"], detect_files: vec!["haxelib.json", "hxformat.json", ".haxerc"], detect_folders: vec![".haxelib", "haxe_libraries"], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/kubernetes.rs
src/configs/kubernetes.rs
use serde::{Deserialize, Serialize}; use std::collections::HashMap; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct KubernetesConfig<'a> { pub symbol: &'a str, pub format: &'a str, pub style: &'a str, pub disabled: bool, pub context_aliases: HashMap<String, &'a str>, pub user_aliases: HashMap<String, &'a str>, pub detect_extensions: Vec<&'a str>, pub detect_files: Vec<&'a str>, pub detect_folders: Vec<&'a str>, pub detect_env_vars: Vec<&'a str>, pub contexts: Vec<KubernetesContextConfig<'a>>, } impl Default for KubernetesConfig<'_> { fn default() -> Self { Self { symbol: "☸ ", format: "[$symbol$context( \\($namespace\\))]($style) in ", style: "cyan bold", disabled: true, context_aliases: HashMap::new(), user_aliases: HashMap::new(), detect_extensions: vec![], detect_files: vec![], detect_folders: vec![], detect_env_vars: vec![], contexts: vec![], } } } #[derive(Clone, Deserialize, Serialize, Default)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct KubernetesContextConfig<'a> { pub context_pattern: &'a str, pub user_pattern: Option<&'a str>, pub symbol: Option<&'a str>, pub style: Option<&'a str>, pub context_alias: Option<&'a str>, pub user_alias: Option<&'a str>, }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/cpp.rs
src/configs/cpp.rs
use crate::configs::cc::CcConfig; use serde::{Deserialize, Serialize}; #[derive(Default, Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] pub struct CppConfigMarker; pub type CppConfig<'a> = CcConfig<'a, CppConfigMarker>; impl Default for CppConfig<'_> { fn default() -> Self { Self { marker: std::marker::PhantomData::<CppConfigMarker>, format: "via [$symbol($version(-$name) )]($style)", version_format: "v${raw}", style: "149 bold", symbol: "C++ ", disabled: true, detect_extensions: vec!["cpp", "cc", "cxx", "c++", "hpp", "hh", "hxx", "h++", "tcc"], detect_files: vec![], detect_folders: vec![], commands: vec![ vec!["c++", "--version"], vec!["g++", "--version"], vec!["clang++", "--version"], ], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/git_state.rs
src/configs/git_state.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct GitStateConfig<'a> { pub rebase: &'a str, pub merge: &'a str, pub revert: &'a str, pub cherry_pick: &'a str, pub bisect: &'a str, pub am: &'a str, pub am_or_rebase: &'a str, pub style: &'a str, pub format: &'a str, pub disabled: bool, } impl Default for GitStateConfig<'_> { fn default() -> Self { Self { rebase: "REBASING", merge: "MERGING", revert: "REVERTING", cherry_pick: "CHERRY-PICKING", bisect: "BISECTING", am: "AM", am_or_rebase: "AM/REBASE", style: "bold yellow", format: "\\([$state( $progress_current/$progress_total)]($style)\\) ", disabled: false, } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/package.rs
src/configs/package.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct PackageConfig<'a> { pub format: &'a str, pub symbol: &'a str, pub style: &'a str, pub display_private: bool, pub disabled: bool, pub version_format: &'a str, } impl Default for PackageConfig<'_> { fn default() -> Self { Self { format: "is [$symbol$version]($style) ", symbol: "📦 ", style: "208 bold", display_private: false, disabled: false, version_format: "v${raw}", } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/quarto.rs
src/configs/quarto.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct QuartoConfig<'a> { pub format: &'a str, pub version_format: &'a str, pub symbol: &'a str, pub style: &'a str, pub disabled: bool, pub detect_extensions: Vec<&'a str>, pub detect_files: Vec<&'a str>, pub detect_folders: Vec<&'a str>, } impl Default for QuartoConfig<'_> { fn default() -> Self { Self { format: "via [$symbol($version )]($style)", version_format: "v${raw}", symbol: "⨁ ", style: "bold #75AADB", disabled: false, detect_extensions: vec!["qmd"], detect_files: vec!["_quarto.yml"], detect_folders: vec![], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/swift.rs
src/configs/swift.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct SwiftConfig<'a> { pub format: &'a str, pub version_format: &'a str, pub symbol: &'a str, pub style: &'a str, pub disabled: bool, pub detect_extensions: Vec<&'a str>, pub detect_files: Vec<&'a str>, pub detect_folders: Vec<&'a str>, } impl Default for SwiftConfig<'_> { fn default() -> Self { Self { format: "via [$symbol($version )]($style)", version_format: "v${raw}", symbol: "🐦 ", style: "bold 202", disabled: false, detect_extensions: vec!["swift"], detect_files: vec!["Package.swift"], detect_folders: vec![], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/memory_usage.rs
src/configs/memory_usage.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct MemoryConfig<'a> { pub threshold: i64, pub format: &'a str, pub style: &'a str, pub symbol: &'a str, pub disabled: bool, } impl Default for MemoryConfig<'_> { fn default() -> Self { Self { threshold: 75, format: "via $symbol[$ram( | $swap)]($style) ", style: "white bold dimmed", symbol: "🐏 ", disabled: true, } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/elixir.rs
src/configs/elixir.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct ElixirConfig<'a> { pub format: &'a str, pub version_format: &'a str, pub symbol: &'a str, pub style: &'a str, pub disabled: bool, pub detect_extensions: Vec<&'a str>, pub detect_files: Vec<&'a str>, pub detect_folders: Vec<&'a str>, } impl Default for ElixirConfig<'_> { fn default() -> Self { Self { format: "via [$symbol($version \\(OTP $otp_version\\) )]($style)", version_format: "v${raw}", symbol: "💧 ", style: "bold purple", disabled: false, detect_extensions: vec![], detect_files: vec!["mix.exs"], detect_folders: vec![], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/erlang.rs
src/configs/erlang.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct ErlangConfig<'a> { pub format: &'a str, pub version_format: &'a str, pub symbol: &'a str, pub style: &'a str, pub disabled: bool, pub detect_extensions: Vec<&'a str>, pub detect_files: Vec<&'a str>, pub detect_folders: Vec<&'a str>, } impl Default for ErlangConfig<'_> { fn default() -> Self { Self { format: "via [$symbol($version )]($style)", version_format: "v${raw}", symbol: " ", style: "bold red", disabled: false, detect_extensions: vec![], detect_files: vec!["rebar.config", "erlang.mk"], detect_folders: vec![], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/v.rs
src/configs/v.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct VConfig<'a> { pub format: &'a str, pub version_format: &'a str, pub symbol: &'a str, pub style: &'a str, pub disabled: bool, pub detect_extensions: Vec<&'a str>, pub detect_files: Vec<&'a str>, pub detect_folders: Vec<&'a str>, } impl Default for VConfig<'_> { fn default() -> Self { Self { format: "via [$symbol($version )]($style)", version_format: "v${raw}", symbol: "V ", style: "blue bold", disabled: false, detect_extensions: vec!["v"], detect_files: vec!["v.mod", "vpkg.json", ".vpkg-lock.json"], detect_folders: vec![], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/dotnet.rs
src/configs/dotnet.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct DotnetConfig<'a> { pub format: &'a str, pub version_format: &'a str, pub symbol: &'a str, pub style: &'a str, pub heuristic: bool, pub disabled: bool, pub detect_extensions: Vec<&'a str>, pub detect_files: Vec<&'a str>, pub detect_folders: Vec<&'a str>, } impl Default for DotnetConfig<'_> { fn default() -> Self { Self { format: "via [$symbol($version )(🎯 $tfm )]($style)", version_format: "v${raw}", symbol: ".NET ", style: "blue bold", heuristic: true, disabled: false, detect_extensions: vec!["csproj", "fsproj", "xproj"], detect_files: vec![ "global.json", "project.json", "Directory.Build.props", "Directory.Build.targets", "Packages.props", ], detect_folders: vec![], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/buf.rs
src/configs/buf.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct BufConfig<'a> { pub format: &'a str, pub version_format: &'a str, pub symbol: &'a str, pub style: &'a str, pub disabled: bool, pub detect_extensions: Vec<&'a str>, pub detect_files: Vec<&'a str>, pub detect_folders: Vec<&'a str>, } impl Default for BufConfig<'_> { fn default() -> Self { Self { format: "with [$symbol($version )]($style)", version_format: "v${raw}", symbol: "🐃 ", style: "bold blue", disabled: false, detect_extensions: vec![], detect_files: vec!["buf.yaml", "buf.gen.yaml", "buf.work.yaml"], detect_folders: vec![], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/haskell.rs
src/configs/haskell.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct HaskellConfig<'a> { pub format: &'a str, pub version_format: &'a str, pub symbol: &'a str, pub style: &'a str, pub disabled: bool, pub detect_extensions: Vec<&'a str>, pub detect_files: Vec<&'a str>, pub detect_folders: Vec<&'a str>, } impl Default for HaskellConfig<'_> { fn default() -> Self { Self { format: "via [$symbol($version )]($style)", version_format: "v${raw}", symbol: "λ ", style: "bold purple", disabled: false, detect_extensions: vec!["hs", "cabal", "hs-boot"], detect_files: vec!["stack.yaml", "cabal.project"], detect_folders: vec![], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/directory.rs
src/configs/directory.rs
use indexmap::IndexMap; use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct DirectoryConfig<'a> { pub truncation_length: i64, pub truncate_to_repo: bool, pub substitutions: IndexMap<String, &'a str>, pub fish_style_pwd_dir_length: i64, pub use_logical_path: bool, pub format: &'a str, pub repo_root_format: &'a str, pub style: &'a str, pub repo_root_style: Option<&'a str>, pub before_repo_root_style: Option<&'a str>, pub disabled: bool, pub read_only: &'a str, pub read_only_style: &'a str, pub truncation_symbol: &'a str, pub home_symbol: &'a str, pub use_os_path_sep: bool, } impl Default for DirectoryConfig<'_> { fn default() -> Self { Self { truncation_length: 3, truncate_to_repo: true, fish_style_pwd_dir_length: 0, use_logical_path: true, substitutions: IndexMap::new(), format: "[$path]($style)[$read_only]($read_only_style) ", repo_root_format: "[$before_root_path]($before_repo_root_style)[$repo_root]($repo_root_style)[$path]($style)[$read_only]($read_only_style) ", style: "cyan bold", repo_root_style: None, before_repo_root_style: None, disabled: false, read_only: "🔒", read_only_style: "red", truncation_symbol: "", home_symbol: "~", use_os_path_sep: true, } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/battery.rs
src/configs/battery.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct BatteryConfig<'a> { pub full_symbol: &'a str, pub charging_symbol: &'a str, pub discharging_symbol: &'a str, pub unknown_symbol: &'a str, pub empty_symbol: &'a str, #[serde(borrow)] pub display: Vec<BatteryDisplayConfig<'a>>, pub disabled: bool, pub format: &'a str, } impl Default for BatteryConfig<'_> { fn default() -> Self { Self { full_symbol: "󰁹 ", charging_symbol: "󰂄 ", discharging_symbol: "󰂃 ", unknown_symbol: "󰁽 ", empty_symbol: "󰂎 ", format: "[$symbol$percentage]($style) ", display: vec![BatteryDisplayConfig::default()], disabled: false, } } } #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct BatteryDisplayConfig<'a> { pub threshold: i64, pub style: &'a str, pub charging_symbol: Option<&'a str>, pub discharging_symbol: Option<&'a str>, } impl Default for BatteryDisplayConfig<'_> { fn default() -> Self { Self { threshold: 10, style: "red bold", charging_symbol: None, discharging_symbol: None, } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/php.rs
src/configs/php.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct PhpConfig<'a> { pub format: &'a str, pub version_format: &'a str, pub symbol: &'a str, pub style: &'a str, pub disabled: bool, pub detect_extensions: Vec<&'a str>, pub detect_files: Vec<&'a str>, pub detect_folders: Vec<&'a str>, } impl Default for PhpConfig<'_> { fn default() -> Self { Self { format: "via [$symbol($version )]($style)", version_format: "v${raw}", symbol: "🐘 ", style: "147 bold", disabled: false, detect_extensions: vec!["php"], detect_files: vec!["composer.json", ".php-version"], detect_folders: vec![], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/cobol.rs
src/configs/cobol.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct CobolConfig<'a> { pub format: &'a str, pub version_format: &'a str, pub symbol: &'a str, pub style: &'a str, pub disabled: bool, pub detect_extensions: Vec<&'a str>, pub detect_files: Vec<&'a str>, pub detect_folders: Vec<&'a str>, } impl Default for CobolConfig<'_> { fn default() -> Self { Self { format: "via [$symbol($version )]($style)", version_format: "v${raw}", symbol: "⚙️ ", style: "bold blue", disabled: false, detect_extensions: vec!["cbl", "cob", "CBL", "COB"], detect_files: vec![], detect_folders: vec![], } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/meson.rs
src/configs/meson.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct MesonConfig<'a> { pub truncation_length: u32, pub truncation_symbol: &'a str, pub format: &'a str, pub symbol: &'a str, pub style: &'a str, pub disabled: bool, } impl Default for MesonConfig<'_> { fn default() -> Self { Self { truncation_length: u32::MAX, truncation_symbol: "…", format: "via [$symbol$project]($style) ", symbol: "⬢ ", style: "blue bold", disabled: false, } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/custom.rs
src/configs/custom.rs
use crate::config::{Either, VecOr}; use serde::{self, Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct CustomConfig<'a> { pub format: &'a str, pub symbol: &'a str, pub command: &'a str, pub when: Either<bool, &'a str>, pub require_repo: bool, pub shell: VecOr<&'a str>, pub description: &'a str, pub style: &'a str, pub disabled: bool, #[serde(alias = "files")] pub detect_files: Vec<&'a str>, #[serde(alias = "extensions")] pub detect_extensions: Vec<&'a str>, #[serde(alias = "directories")] pub detect_folders: Vec<&'a str>, #[serde(skip_serializing_if = "Option::is_none")] pub os: Option<&'a str>, #[serde(skip_serializing_if = "Option::is_none")] pub use_stdin: Option<bool>, pub ignore_timeout: bool, pub unsafe_no_escape: bool, } impl Default for CustomConfig<'_> { fn default() -> Self { Self { format: "[$symbol($output )]($style)", symbol: "", command: "", when: Either::First(false), require_repo: false, shell: VecOr::default(), description: "<custom config>", style: "green bold", disabled: false, detect_files: Vec::default(), detect_extensions: Vec::default(), detect_folders: Vec::default(), os: None, use_stdin: None, ignore_timeout: false, unsafe_no_escape: false, } } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
starship/starship
https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/init/mod.rs
src/init/mod.rs
use crate::utils::create_command; use std::ffi::OsStr; use std::path::{Path, PathBuf}; use std::{env, io}; use which::which; /* We use a two-phase init here: the first phase gives a simple command to the shell. This command evaluates a more complicated script using `source` and process substitution. Directly using `eval` on a shell script without proper quoting causes it to be evaluated in a single line, which sucks because things like comments will comment out the rest of the script, and you have to spam semicolons everywhere. By using source and process substitutions, we make it possible to comment and debug the init scripts. In the future, this may be changed to just directly evaluating the initscript using whatever mechanism is available in the host shell--this two-phase solution has been developed as a compatibility measure with `eval $(starship init X)` */ struct StarshipPath { native_path: PathBuf, } impl StarshipPath { fn init() -> io::Result<Self> { let exe_name = option_env!("CARGO_PKG_NAME").unwrap_or("starship"); let native_path = which(exe_name).or_else(|_| env::current_exe())?; Ok(Self { native_path }) } fn str_path(&self) -> io::Result<&str> { let current_exe = self .native_path .to_str() .ok_or_else(|| io::Error::other("can't convert to str"))?; Ok(current_exe) } /// Returns POSIX quoted path to starship binary fn sprint(&self) -> io::Result<String> { self.str_path().map(|p| shell_words::quote(p).into_owned()) } /// `PowerShell` specific path escaping fn sprint_pwsh(&self) -> io::Result<String> { self.str_path() .map(|s| s.replace('\'', "''")) .map(|s| format!("'{s}'")) } /// Command Shell specific path escaping fn sprint_cmdexe(&self) -> io::Result<String> { self.str_path().map(|s| format!("\"{s}\"")) } fn sprint_posix(&self) -> io::Result<String> { // On non-Windows platform, return directly. if cfg!(not(target_os = "windows")) { return self.sprint(); } let str_path = self.str_path()?; let res = create_command("cygpath").and_then(|mut cmd| cmd.arg(str_path).output()); let output = match res { Ok(output) => output, Err(e) => { if e.kind() != io::ErrorKind::NotFound { log::warn!("Failed to convert \"{str_path}\" to unix path:\n{e:?}"); } // Failed to execute cygpath.exe means there're not inside cygwin environment,return directly. return self.sprint(); } }; let res = String::from_utf8(output.stdout); let posix_path = match res { Ok(ref cygpath_path) if output.status.success() => cygpath_path.trim(), Ok(_) => { log::warn!( "Failed to convert \"{}\" to unix path:\n{}", str_path, String::from_utf8_lossy(&output.stderr), ); str_path } Err(e) => { log::warn!("Failed to convert \"{str_path}\" to unix path:\n{e}"); str_path } }; Ok(shell_words::quote(posix_path).into_owned()) } } /* This prints the setup stub, the short piece of code which sets up the main init code. The stub produces the main init script, then evaluates it with `source` and process substitution */ pub fn init_stub(shell_name: &str) -> io::Result<()> { log::debug!("Shell name: {shell_name}"); let shell_basename = Path::new(shell_name) .file_stem() .and_then(OsStr::to_str) .unwrap_or(shell_name); let starship = StarshipPath::init()?; match shell_basename { "bash" => print!( /* We now use the following bootstrap: * `eval -- "$(starship init bash --print-full-init)"` * which works in any version of Bash from 3.2 to the latest * version and also works in the POSIX mode. * * ---- * Historically, the standard bash bootstrap was: * `source <(starship init bash --print-full-init)` * * Unfortunately there is an issue with bash 3.2 (the MacOS * default) which prevents this from working. It does not support * `source` with process substitution. * * There are more details here: https://stackoverflow.com/a/32596626 * * The workaround for MacOS is to use the `/dev/stdin` trick you * see below. However, there are some systems with emulated POSIX * environments which do not support `/dev/stdin`. For example, * `Git Bash` within `Git for Windows and `Termux` on Android. * * Fortunately, these apps ship with recent-ish versions of bash. * Git Bash is currently shipping bash 4.4 and Termux is shipping * bash 5.0. * * Some testing has suggested that bash 4.0 is also incompatible * with the standard bootstrap, whereas bash 4.1 appears to be * consistently compatible. * * We had been using the standard bootstrap whenever the bash * version is 4.1 or higher. Otherwise, we fell back to the * `/dev/stdin` solution. * * However, process substitutions <(...) are not supported in the * POSIX mode of Bash <= 5.0, so we switch to the approach with * `eval -- "$(...)"`. The reason for not using `eval` seems to be * explained at the top of this file, i.e., the script will be * evaluated as if it is a single line, but that is caused by an * improper quoting. * * More background can be found in these pull requests: * https://github.com/starship/starship/pull/241 * https://github.com/starship/starship/pull/278 * https://github.com/starship/starship/issues/1674 * https://github.com/starship/starship/pull/5020 * https://github.com/starship/starship/issues/5382 */ r#"eval -- "$({0} init bash --print-full-init)""#, starship.sprint_posix()? ), "zsh" => print_script(ZSH_INIT, &starship.sprint_posix()?), "fish" => print!( // Fish does process substitution with pipes and psub instead of bash syntax r"source ({} init fish --print-full-init | psub)", starship.sprint_posix()? ), "powershell" => print!( r"Invoke-Expression (& {} init powershell --print-full-init | Out-String)", starship.sprint_pwsh()? ), "ion" => print!("eval $({} init ion --print-full-init)", starship.sprint()?), "elvish" => print!( r"eval ({} init elvish --print-full-init | slurp)", starship.sprint()? ), "tcsh" => print!( r"eval `({} init tcsh --print-full-init)`", starship.sprint_posix()? ), "nu" => print_script(NU_INIT, &StarshipPath::init()?.sprint()?), "xonsh" => print!( r"execx($({} init xonsh --print-full-init))", starship.sprint_posix()? ), "cmd" => print_script(CMDEXE_INIT, &StarshipPath::init()?.sprint_cmdexe()?), _ => { eprintln!( "{shell_basename} is not yet supported by starship.\n\ For the time being, we support the following shells:\n\ * bash\n\ * elvish\n\ * fish\n\ * ion\n\ * powershell\n\ * tcsh\n\ * zsh\n\ * nu\n\ * xonsh\n\ * cmd\n\ \n\ Please open an issue in the starship repo if you would like to \ see support for {shell_basename}:\n\ https://github.com/starship/starship/issues/new\n" ); } }; Ok(()) } /* This function (called when `--print-full-init` is passed to `starship init`) prints out the main initialization script */ pub fn init_main(shell_name: &str) -> io::Result<()> { let starship_path = StarshipPath::init()?; match shell_name { "bash" => print_script(BASH_INIT, &starship_path.sprint_posix()?), "zsh" => print_script(ZSH_INIT, &starship_path.sprint_posix()?), "fish" => print_script(FISH_INIT, &starship_path.sprint_posix()?), "powershell" => print_script(PWSH_INIT, &starship_path.sprint_pwsh()?), "ion" => print_script(ION_INIT, &starship_path.sprint()?), "elvish" => print_script(ELVISH_INIT, &starship_path.sprint()?), "tcsh" => print_script(TCSH_INIT, &starship_path.sprint_posix()?), "xonsh" => print_script(XONSH_INIT, &starship_path.sprint_posix()?), _ => { println!( "printf \"Shell name detection failed on phase two init.\\n\ This probably indicates a bug within starship: please open\\n\ an issue at https://github.com/starship/starship/issues/new\\n\"" ); } } Ok(()) } fn print_script(script: &str, path: &str) { let script = script.replace("::STARSHIP::", path); print!("{script}"); } /* GENERAL INIT SCRIPT NOTES Each init script will be passed as-is. Global notes for init scripts are in this comment, with additional per-script comments in the strings themselves. JOBS: The argument to `--jobs` is quoted because MacOS's `wc` leaves whitespace in the output. We pass it to starship and do the whitespace removal in Rust, to avoid the cost of an additional shell fork every shell draw. Note that the init scripts are not in their final form--they are processed by `starship init` prior to emitting the final form. In this processing, some tokens are replaced, e.g. `::STARSHIP::` is replaced by the full path to the starship binary. */ const BASH_INIT: &str = include_str!("starship.bash"); const ZSH_INIT: &str = include_str!("starship.zsh"); const FISH_INIT: &str = include_str!("starship.fish"); const PWSH_INIT: &str = include_str!("starship.ps1"); const ION_INIT: &str = include_str!("starship.ion"); const ELVISH_INIT: &str = include_str!("starship.elv"); const TCSH_INIT: &str = include_str!("starship.tcsh"); const NU_INIT: &str = include_str!("starship.nu"); const XONSH_INIT: &str = include_str!("starship.xsh"); const CMDEXE_INIT: &str = include_str!("starship.lua"); #[cfg(test)] mod tests { use super::*; #[test] fn escape_pwsh() -> io::Result<()> { let starship_path = StarshipPath { native_path: PathBuf::from(r"C:\starship.exe"), }; assert_eq!(starship_path.sprint_pwsh()?, r"'C:\starship.exe'"); Ok(()) } #[test] fn escape_tick_pwsh() -> io::Result<()> { let starship_path = StarshipPath { native_path: PathBuf::from(r"C:\'starship.exe"), }; assert_eq!(starship_path.sprint_pwsh()?, r"'C:\''starship.exe'"); Ok(()) } #[test] fn escape_cmdexe() -> io::Result<()> { let starship_path = StarshipPath { native_path: PathBuf::from(r"C:\starship.exe"), }; assert_eq!(starship_path.sprint_cmdexe()?, r#""C:\starship.exe""#); Ok(()) } #[test] fn escape_space_cmdexe() -> io::Result<()> { let starship_path = StarshipPath { native_path: PathBuf::from(r"C:\Cool Tools\starship.exe"), }; assert_eq!( starship_path.sprint_cmdexe()?, r#""C:\Cool Tools\starship.exe""# ); Ok(()) } }
rust
ISC
8a69666084d248b8fd76b6c54f38aea12abce6e3
2026-01-04T15:31:59.388295Z
false
alacritty/alacritty
https://github.com/alacritty/alacritty/blob/6ee6e53ee3457c24137f117237b0ff1d84f6f836/alacritty/build.rs
alacritty/build.rs
use std::env; use std::fs::File; use std::path::Path; use std::process::Command; use gl_generator::{Api, Fallbacks, GlobalGenerator, Profile, Registry}; fn main() { let mut version = String::from(env!("CARGO_PKG_VERSION")); if let Some(commit_hash) = commit_hash() { version = format!("{version} ({commit_hash})"); } println!("cargo:rustc-env=VERSION={version}"); let dest = env::var("OUT_DIR").unwrap(); let mut file = File::create(Path::new(&dest).join("gl_bindings.rs")).unwrap(); Registry::new(Api::Gl, (3, 3), Profile::Core, Fallbacks::All, [ "GL_ARB_blend_func_extended", "GL_KHR_robustness", "GL_KHR_debug", ]) .write_bindings(GlobalGenerator, &mut file) .unwrap(); #[cfg(windows)] embed_resource::compile("./windows/alacritty.rc", embed_resource::NONE) .manifest_required() .unwrap(); } fn commit_hash() -> Option<String> { Command::new("git") .args(["rev-parse", "--short", "HEAD"]) .output() .ok() .filter(|output| output.status.success()) .and_then(|output| String::from_utf8(output.stdout).ok()) .map(|hash| hash.trim().into()) }
rust
Apache-2.0
6ee6e53ee3457c24137f117237b0ff1d84f6f836
2026-01-04T15:31:58.707223Z
false
alacritty/alacritty
https://github.com/alacritty/alacritty/blob/6ee6e53ee3457c24137f117237b0ff1d84f6f836/alacritty/src/window_context.rs
alacritty/src/window_context.rs
//! Terminal window context. use std::error::Error; use std::fs::File; use std::io::Write; use std::mem; #[cfg(not(windows))] use std::os::unix::io::{AsRawFd, RawFd}; use std::rc::Rc; use std::sync::Arc; use std::time::Instant; use glutin::config::Config as GlutinConfig; use glutin::display::GetGlDisplay; #[cfg(all(feature = "x11", not(any(target_os = "macos", windows))))] use glutin::platform::x11::X11GlConfigExt; use log::info; use serde_json as json; use winit::event::{Event as WinitEvent, Modifiers, WindowEvent}; use winit::event_loop::{ActiveEventLoop, EventLoopProxy}; use winit::raw_window_handle::HasDisplayHandle; use winit::window::WindowId; use alacritty_terminal::event::Event as TerminalEvent; use alacritty_terminal::event_loop::{EventLoop as PtyEventLoop, Msg, Notifier}; use alacritty_terminal::grid::{Dimensions, Scroll}; use alacritty_terminal::index::Direction; use alacritty_terminal::sync::FairMutex; use alacritty_terminal::term::test::TermSize; use alacritty_terminal::term::{Term, TermMode}; use alacritty_terminal::tty; use crate::cli::{ParsedOptions, WindowOptions}; use crate::clipboard::Clipboard; use crate::config::UiConfig; use crate::display::Display; use crate::display::window::Window; use crate::event::{ ActionContext, Event, EventProxy, InlineSearchState, Mouse, SearchState, TouchPurpose, }; #[cfg(unix)] use crate::logging::LOG_TARGET_IPC_CONFIG; use crate::message_bar::MessageBuffer; use crate::scheduler::Scheduler; use crate::{input, renderer}; /// Event context for one individual Alacritty window. pub struct WindowContext { pub message_buffer: MessageBuffer, pub display: Display, pub dirty: bool, event_queue: Vec<WinitEvent<Event>>, terminal: Arc<FairMutex<Term<EventProxy>>>, cursor_blink_timed_out: bool, prev_bell_cmd: Option<Instant>, modifiers: Modifiers, inline_search_state: InlineSearchState, search_state: SearchState, notifier: Notifier, mouse: Mouse, touch: TouchPurpose, occluded: bool, preserve_title: bool, #[cfg(not(windows))] master_fd: RawFd, #[cfg(not(windows))] shell_pid: u32, window_config: ParsedOptions, config: Rc<UiConfig>, } impl WindowContext { /// Create initial window context that does bootstrapping the graphics API we're going to use. pub fn initial( event_loop: &ActiveEventLoop, proxy: EventLoopProxy<Event>, config: Rc<UiConfig>, mut options: WindowOptions, ) -> Result<Self, Box<dyn Error>> { let raw_display_handle = event_loop.display_handle().unwrap().as_raw(); let mut identity = config.window.identity.clone(); options.window_identity.override_identity_config(&mut identity); // Windows has different order of GL platform initialization compared to any other platform; // it requires the window first. #[cfg(windows)] let window = Window::new(event_loop, &config, &identity, &mut options)?; #[cfg(windows)] let raw_window_handle = Some(window.raw_window_handle()); #[cfg(not(windows))] let raw_window_handle = None; let gl_display = renderer::platform::create_gl_display( raw_display_handle, raw_window_handle, config.debug.prefer_egl, )?; let gl_config = renderer::platform::pick_gl_config(&gl_display, raw_window_handle)?; #[cfg(not(windows))] let window = Window::new( event_loop, &config, &identity, &mut options, #[cfg(all(feature = "x11", not(any(target_os = "macos", windows))))] gl_config.x11_visual(), )?; // Create context. let gl_context = renderer::platform::create_gl_context(&gl_display, &gl_config, raw_window_handle)?; let display = Display::new(window, gl_context, &config, false)?; Self::new(display, config, options, proxy) } /// Create additional context with the graphics platform other windows are using. pub fn additional( gl_config: &GlutinConfig, event_loop: &ActiveEventLoop, proxy: EventLoopProxy<Event>, config: Rc<UiConfig>, mut options: WindowOptions, config_overrides: ParsedOptions, ) -> Result<Self, Box<dyn Error>> { let gl_display = gl_config.display(); let mut identity = config.window.identity.clone(); options.window_identity.override_identity_config(&mut identity); // Check if new window will be opened as a tab. // This must be done before `Window::new()`, which unsets `window_tabbing_id`. #[cfg(target_os = "macos")] let tabbed = options.window_tabbing_id.is_some(); #[cfg(not(target_os = "macos"))] let tabbed = false; let window = Window::new( event_loop, &config, &identity, &mut options, #[cfg(all(feature = "x11", not(any(target_os = "macos", windows))))] gl_config.x11_visual(), )?; // Create context. let raw_window_handle = window.raw_window_handle(); let gl_context = renderer::platform::create_gl_context(&gl_display, gl_config, Some(raw_window_handle))?; let display = Display::new(window, gl_context, &config, tabbed)?; let mut window_context = Self::new(display, config, options, proxy)?; // Set the config overrides at startup. // // These are already applied to `config`, so no update is necessary. window_context.window_config = config_overrides; Ok(window_context) } /// Create a new terminal window context. fn new( display: Display, config: Rc<UiConfig>, options: WindowOptions, proxy: EventLoopProxy<Event>, ) -> Result<Self, Box<dyn Error>> { let mut pty_config = config.pty_config(); options.terminal_options.override_pty_config(&mut pty_config); let preserve_title = options.window_identity.title.is_some(); info!( "PTY dimensions: {:?} x {:?}", display.size_info.screen_lines(), display.size_info.columns() ); let event_proxy = EventProxy::new(proxy, display.window.id()); // Create the terminal. // // This object contains all of the state about what's being displayed. It's // wrapped in a clonable mutex since both the I/O loop and display need to // access it. let terminal = Term::new(config.term_options(), &display.size_info, event_proxy.clone()); let terminal = Arc::new(FairMutex::new(terminal)); // Create the PTY. // // The PTY forks a process to run the shell on the slave side of the // pseudoterminal. A file descriptor for the master side is retained for // reading/writing to the shell. let pty = tty::new(&pty_config, display.size_info.into(), display.window.id().into())?; #[cfg(not(windows))] let master_fd = pty.file().as_raw_fd(); #[cfg(not(windows))] let shell_pid = pty.child().id(); // Create the pseudoterminal I/O loop. // // PTY I/O is ran on another thread as to not occupy cycles used by the // renderer and input processing. Note that access to the terminal state is // synchronized since the I/O loop updates the state, and the display // consumes it periodically. let event_loop = PtyEventLoop::new( Arc::clone(&terminal), event_proxy.clone(), pty, pty_config.drain_on_exit, config.debug.ref_test, )?; // The event loop channel allows write requests from the event processor // to be sent to the pty loop and ultimately written to the pty. let loop_tx = event_loop.channel(); // Kick off the I/O thread. let _io_thread = event_loop.spawn(); // Start cursor blinking, in case `Focused` isn't sent on startup. if config.cursor.style().blinking { event_proxy.send_event(TerminalEvent::CursorBlinkingChange.into()); } // Create context for the Alacritty window. Ok(WindowContext { preserve_title, terminal, display, #[cfg(not(windows))] master_fd, #[cfg(not(windows))] shell_pid, config, notifier: Notifier(loop_tx), cursor_blink_timed_out: Default::default(), prev_bell_cmd: Default::default(), inline_search_state: Default::default(), message_buffer: Default::default(), window_config: Default::default(), search_state: Default::default(), event_queue: Default::default(), modifiers: Default::default(), occluded: Default::default(), mouse: Default::default(), touch: Default::default(), dirty: Default::default(), }) } /// Update the terminal window to the latest config. pub fn update_config(&mut self, new_config: Rc<UiConfig>) { let old_config = mem::replace(&mut self.config, new_config); // Apply ipc config if there are overrides. self.config = self.window_config.override_config_rc(self.config.clone()); self.display.update_config(&self.config); self.terminal.lock().set_options(self.config.term_options()); // Reload cursor if its thickness has changed. if (old_config.cursor.thickness() - self.config.cursor.thickness()).abs() > f32::EPSILON { self.display.pending_update.set_cursor_dirty(); } if old_config.font != self.config.font { let scale_factor = self.display.window.scale_factor as f32; // Do not update font size if it has been changed at runtime. if self.display.font_size == old_config.font.size().scale(scale_factor) { self.display.font_size = self.config.font.size().scale(scale_factor); } let font = self.config.font.clone().with_size(self.display.font_size); self.display.pending_update.set_font(font); } // Always reload the theme to account for auto-theme switching. self.display.window.set_theme(self.config.window.theme()); // Update display if either padding options or resize increments were changed. let window_config = &old_config.window; if window_config.padding(1.) != self.config.window.padding(1.) || window_config.dynamic_padding != self.config.window.dynamic_padding || window_config.resize_increments != self.config.window.resize_increments { self.display.pending_update.dirty = true; } // Update title on config reload according to the following table. // // │cli │ dynamic_title │ current_title == old_config ││ set_title │ // │ Y │ _ │ _ ││ N │ // │ N │ Y │ Y ││ Y │ // │ N │ Y │ N ││ N │ // │ N │ N │ _ ││ Y │ if !self.preserve_title && (!self.config.window.dynamic_title || self.display.window.title() == old_config.window.identity.title) { self.display.window.set_title(self.config.window.identity.title.clone()); } let opaque = self.config.window_opacity() >= 1.; // Disable shadows for transparent windows on macOS. #[cfg(target_os = "macos")] self.display.window.set_has_shadow(opaque); #[cfg(target_os = "macos")] self.display.window.set_option_as_alt(self.config.window.option_as_alt()); // Change opacity and blur state. self.display.window.set_transparent(!opaque); self.display.window.set_blur(self.config.window.blur); // Update hint keys. self.display.hint_state.update_alphabet(self.config.hints.alphabet()); // Update cursor blinking. let event = Event::new(TerminalEvent::CursorBlinkingChange.into(), None); self.event_queue.push(event.into()); self.dirty = true; } /// Get reference to the window's configuration. #[cfg(unix)] pub fn config(&self) -> &UiConfig { &self.config } /// Clear the window config overrides. #[cfg(unix)] pub fn reset_window_config(&mut self, config: Rc<UiConfig>) { // Clear previous window errors. self.message_buffer.remove_target(LOG_TARGET_IPC_CONFIG); self.window_config.clear(); // Reload current config to pull new IPC config. self.update_config(config); } /// Add new window config overrides. #[cfg(unix)] pub fn add_window_config(&mut self, config: Rc<UiConfig>, options: &ParsedOptions) { // Clear previous window errors. self.message_buffer.remove_target(LOG_TARGET_IPC_CONFIG); self.window_config.extend_from_slice(options); // Reload current config to pull new IPC config. self.update_config(config); } /// Draw the window. pub fn draw(&mut self, scheduler: &mut Scheduler) { self.display.window.requested_redraw = false; if self.occluded { return; } self.dirty = false; // Force the display to process any pending display update. self.display.process_renderer_update(); // Request immediate re-draw if visual bell animation is not finished yet. if !self.display.visual_bell.completed() { // We can get an OS redraw which bypasses alacritty's frame throttling, thus // marking the window as dirty when we don't have frame yet. if self.display.window.has_frame { self.display.window.request_redraw(); } else { self.dirty = true; } } // Redraw the window. let terminal = self.terminal.lock(); self.display.draw( terminal, scheduler, &self.message_buffer, &self.config, &mut self.search_state, ); } /// Process events for this terminal window. pub fn handle_event( &mut self, #[cfg(target_os = "macos")] event_loop: &ActiveEventLoop, event_proxy: &EventLoopProxy<Event>, clipboard: &mut Clipboard, scheduler: &mut Scheduler, event: WinitEvent<Event>, ) { match event { WinitEvent::AboutToWait | WinitEvent::WindowEvent { event: WindowEvent::RedrawRequested, .. } => { // Skip further event handling with no staged updates. if self.event_queue.is_empty() { return; } // Continue to process all pending events. }, event => { self.event_queue.push(event); return; }, } let mut terminal = self.terminal.lock(); let old_is_searching = self.search_state.history_index.is_some(); let context = ActionContext { cursor_blink_timed_out: &mut self.cursor_blink_timed_out, prev_bell_cmd: &mut self.prev_bell_cmd, message_buffer: &mut self.message_buffer, inline_search_state: &mut self.inline_search_state, search_state: &mut self.search_state, modifiers: &mut self.modifiers, notifier: &mut self.notifier, display: &mut self.display, mouse: &mut self.mouse, touch: &mut self.touch, dirty: &mut self.dirty, occluded: &mut self.occluded, terminal: &mut terminal, #[cfg(not(windows))] master_fd: self.master_fd, #[cfg(not(windows))] shell_pid: self.shell_pid, preserve_title: self.preserve_title, config: &self.config, event_proxy, #[cfg(target_os = "macos")] event_loop, clipboard, scheduler, }; let mut processor = input::Processor::new(context); for event in self.event_queue.drain(..) { processor.handle_event(event); } // Process DisplayUpdate events. if self.display.pending_update.dirty { Self::submit_display_update( &mut terminal, &mut self.display, &mut self.notifier, &self.message_buffer, &mut self.search_state, old_is_searching, &self.config, ); self.dirty = true; } if self.dirty || self.mouse.hint_highlight_dirty { self.dirty |= self.display.update_highlighted_hints( &terminal, &self.config, &self.mouse, self.modifiers.state(), ); self.mouse.hint_highlight_dirty = false; } // Don't call `request_redraw` when event is `RedrawRequested` since the `dirty` flag // represents the current frame, but redraw is for the next frame. if self.dirty && self.display.window.has_frame && !self.occluded && !matches!(event, WinitEvent::WindowEvent { event: WindowEvent::RedrawRequested, .. }) { self.display.window.request_redraw(); } } /// ID of this terminal context. pub fn id(&self) -> WindowId { self.display.window.id() } /// Write the ref test results to the disk. pub fn write_ref_test_results(&self) { // Dump grid state. let mut grid = self.terminal.lock().grid().clone(); grid.initialize_all(); grid.truncate(); let serialized_grid = json::to_string(&grid).expect("serialize grid"); let size_info = &self.display.size_info; let size = TermSize::new(size_info.columns(), size_info.screen_lines()); let serialized_size = json::to_string(&size).expect("serialize size"); let serialized_config = format!("{{\"history_size\":{}}}", grid.history_size()); File::create("./grid.json") .and_then(|mut f| f.write_all(serialized_grid.as_bytes())) .expect("write grid.json"); File::create("./size.json") .and_then(|mut f| f.write_all(serialized_size.as_bytes())) .expect("write size.json"); File::create("./config.json") .and_then(|mut f| f.write_all(serialized_config.as_bytes())) .expect("write config.json"); } /// Submit the pending changes to the `Display`. fn submit_display_update( terminal: &mut Term<EventProxy>, display: &mut Display, notifier: &mut Notifier, message_buffer: &MessageBuffer, search_state: &mut SearchState, old_is_searching: bool, config: &UiConfig, ) { // Compute cursor positions before resize. let num_lines = terminal.screen_lines(); let cursor_at_bottom = terminal.grid().cursor.point.line + 1 == num_lines; let origin_at_bottom = if terminal.mode().contains(TermMode::VI) { terminal.vi_mode_cursor.point.line == num_lines - 1 } else { search_state.direction == Direction::Left }; display.handle_update(terminal, notifier, message_buffer, search_state, config); let new_is_searching = search_state.history_index.is_some(); if !old_is_searching && new_is_searching { // Scroll on search start to make sure origin is visible with minimal viewport motion. let display_offset = terminal.grid().display_offset(); if display_offset == 0 && cursor_at_bottom && !origin_at_bottom { terminal.scroll_display(Scroll::Delta(1)); } else if display_offset != 0 && origin_at_bottom { terminal.scroll_display(Scroll::Delta(-1)); } } } } impl Drop for WindowContext { fn drop(&mut self) { // Shutdown the terminal's PTY. let _ = self.notifier.0.send(Msg::Shutdown); } }
rust
Apache-2.0
6ee6e53ee3457c24137f117237b0ff1d84f6f836
2026-01-04T15:31:58.707223Z
false
alacritty/alacritty
https://github.com/alacritty/alacritty/blob/6ee6e53ee3457c24137f117237b0ff1d84f6f836/alacritty/src/event.rs
alacritty/src/event.rs
//! Process window events. use crate::ConfigMonitor; use glutin::config::GetGlConfig; use std::borrow::Cow; use std::cmp::min; use std::collections::hash_map::Entry; use std::collections::{HashMap, HashSet, VecDeque}; use std::error::Error; use std::ffi::OsStr; use std::fmt::Debug; #[cfg(not(windows))] use std::os::unix::io::RawFd; #[cfg(unix)] use std::os::unix::net::UnixStream; use std::path::PathBuf; use std::rc::Rc; #[cfg(unix)] use std::sync::Arc; use std::time::{Duration, Instant}; use std::{env, f32, mem}; use ahash::RandomState; use crossfont::Size as FontSize; use glutin::config::Config as GlutinConfig; use glutin::display::GetGlDisplay; use log::{debug, error, info, warn}; use winit::application::ApplicationHandler; use winit::event::{ ElementState, Event as WinitEvent, Ime, Modifiers, MouseButton, StartCause, Touch as TouchEvent, WindowEvent, }; use winit::event_loop::{ActiveEventLoop, ControlFlow, DeviceEvents, EventLoop, EventLoopProxy}; use winit::raw_window_handle::HasDisplayHandle; use winit::window::WindowId; use alacritty_terminal::event::{Event as TerminalEvent, EventListener, Notify}; use alacritty_terminal::event_loop::Notifier; use alacritty_terminal::grid::{BidirectionalIterator, Dimensions, Scroll}; use alacritty_terminal::index::{Boundary, Column, Direction, Line, Point, Side}; use alacritty_terminal::selection::{Selection, SelectionType}; use alacritty_terminal::term::cell::Flags; use alacritty_terminal::term::search::{Match, RegexSearch}; use alacritty_terminal::term::{self, ClipboardType, Term, TermMode}; use alacritty_terminal::vte::ansi::NamedColor; #[cfg(unix)] use crate::cli::{IpcConfig, ParsedOptions}; use crate::cli::{Options as CliOptions, WindowOptions}; use crate::clipboard::Clipboard; use crate::config::ui_config::{HintAction, HintInternalAction}; use crate::config::{self, UiConfig}; #[cfg(not(windows))] use crate::daemon::foreground_process_path; use crate::daemon::spawn_daemon; use crate::display::color::Rgb; use crate::display::hint::HintMatch; use crate::display::window::{ImeInhibitor, Window}; use crate::display::{Display, Preedit, SizeInfo}; use crate::input::{self, ActionContext as _, FONT_SIZE_STEP}; #[cfg(unix)] use crate::ipc::{self, SocketReply}; use crate::logging::{LOG_TARGET_CONFIG, LOG_TARGET_WINIT}; use crate::message_bar::{Message, MessageBuffer}; use crate::scheduler::{Scheduler, TimerId, Topic}; use crate::window_context::WindowContext; /// Duration after the last user input until an unlimited search is performed. pub const TYPING_SEARCH_DELAY: Duration = Duration::from_millis(500); /// Maximum number of lines for the blocking search while still typing the search regex. const MAX_SEARCH_WHILE_TYPING: Option<usize> = Some(1000); /// Maximum number of search terms stored in the history. const MAX_SEARCH_HISTORY_SIZE: usize = 255; /// Touch zoom speed. const TOUCH_ZOOM_FACTOR: f32 = 0.01; /// Cooldown between invocations of the bell command. const BELL_CMD_COOLDOWN: Duration = Duration::from_millis(100); /// The event processor. /// /// Stores some state from received events and dispatches actions when they are /// triggered. pub struct Processor { pub config_monitor: Option<ConfigMonitor>, clipboard: Clipboard, scheduler: Scheduler, initial_window_options: Option<WindowOptions>, initial_window_error: Option<Box<dyn Error>>, windows: HashMap<WindowId, WindowContext, RandomState>, proxy: EventLoopProxy<Event>, gl_config: Option<GlutinConfig>, #[cfg(unix)] global_ipc_options: ParsedOptions, cli_options: CliOptions, config: Rc<UiConfig>, } impl Processor { /// Create a new event processor. pub fn new( config: UiConfig, cli_options: CliOptions, event_loop: &EventLoop<Event>, ) -> Processor { let proxy = event_loop.create_proxy(); let scheduler = Scheduler::new(proxy.clone()); let initial_window_options = Some(cli_options.window_options.clone()); // Disable all device events, since we don't care about them. event_loop.listen_device_events(DeviceEvents::Never); // SAFETY: Since this takes a pointer to the winit event loop, it MUST be dropped first, // which is done in `loop_exiting`. let clipboard = unsafe { Clipboard::new(event_loop.display_handle().unwrap().as_raw()) }; // Create a config monitor. // // The monitor watches the config file for changes and reloads it. Pending // config changes are processed in the main loop. let mut config_monitor = None; if config.live_config_reload() { config_monitor = ConfigMonitor::new(config.config_paths.clone(), event_loop.create_proxy()); } Processor { initial_window_options, initial_window_error: None, cli_options, proxy, scheduler, gl_config: None, config: Rc::new(config), clipboard, windows: Default::default(), #[cfg(unix)] global_ipc_options: Default::default(), config_monitor, } } /// Create initial window and load GL platform. /// /// This will initialize the OpenGL Api and pick a config that /// will be used for the rest of the windows. pub fn create_initial_window( &mut self, event_loop: &ActiveEventLoop, window_options: WindowOptions, ) -> Result<(), Box<dyn Error>> { let window_context = WindowContext::initial( event_loop, self.proxy.clone(), self.config.clone(), window_options, )?; self.gl_config = Some(window_context.display.gl_context().config()); self.windows.insert(window_context.id(), window_context); Ok(()) } /// Create a new terminal window. pub fn create_window( &mut self, event_loop: &ActiveEventLoop, options: WindowOptions, ) -> Result<(), Box<dyn Error>> { let gl_config = self.gl_config.as_ref().unwrap(); // Override config with CLI/IPC options. let mut config_overrides = options.config_overrides(); #[cfg(unix)] config_overrides.extend_from_slice(&self.global_ipc_options); let mut config = self.config.clone(); config = config_overrides.override_config_rc(config); let window_context = WindowContext::additional( gl_config, event_loop, self.proxy.clone(), config, options, config_overrides, )?; self.windows.insert(window_context.id(), window_context); Ok(()) } /// Run the event loop. /// /// The result is exit code generate from the loop. pub fn run(&mut self, event_loop: EventLoop<Event>) -> Result<(), Box<dyn Error>> { let result = event_loop.run_app(self); match self.initial_window_error.take() { Some(initial_window_error) => Err(initial_window_error), _ => result.map_err(Into::into), } } /// Check if an event is irrelevant and can be skipped. fn skip_window_event(event: &WindowEvent) -> bool { matches!( event, WindowEvent::KeyboardInput { is_synthetic: true, .. } | WindowEvent::ActivationTokenDone { .. } | WindowEvent::DoubleTapGesture { .. } | WindowEvent::TouchpadPressure { .. } | WindowEvent::RotationGesture { .. } | WindowEvent::CursorEntered { .. } | WindowEvent::PinchGesture { .. } | WindowEvent::AxisMotion { .. } | WindowEvent::PanGesture { .. } | WindowEvent::HoveredFileCancelled | WindowEvent::Destroyed | WindowEvent::ThemeChanged(_) | WindowEvent::HoveredFile(_) | WindowEvent::Moved(_) ) } } impl ApplicationHandler<Event> for Processor { fn resumed(&mut self, _event_loop: &ActiveEventLoop) {} fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: StartCause) { if cause != StartCause::Init || self.cli_options.daemon { return; } if let Some(window_options) = self.initial_window_options.take() { if let Err(err) = self.create_initial_window(event_loop, window_options) { self.initial_window_error = Some(err); event_loop.exit(); return; } } info!("Initialisation complete"); } fn window_event( &mut self, _event_loop: &ActiveEventLoop, window_id: WindowId, event: WindowEvent, ) { if self.config.debug.print_events { info!(target: LOG_TARGET_WINIT, "{event:?}"); } // Ignore all events we do not care about. if Self::skip_window_event(&event) { return; } let window_context = match self.windows.get_mut(&window_id) { Some(window_context) => window_context, None => return, }; let is_redraw = matches!(event, WindowEvent::RedrawRequested); window_context.handle_event( #[cfg(target_os = "macos")] _event_loop, &self.proxy, &mut self.clipboard, &mut self.scheduler, WinitEvent::WindowEvent { window_id, event }, ); if is_redraw { window_context.draw(&mut self.scheduler); } } fn user_event(&mut self, event_loop: &ActiveEventLoop, event: Event) { if self.config.debug.print_events { info!(target: LOG_TARGET_WINIT, "{event:?}"); } // Handle events which don't mandate the WindowId. match (event.payload, event.window_id.as_ref()) { // Process IPC config update. #[cfg(unix)] (EventType::IpcConfig(ipc_config), window_id) => { // Try and parse options as toml. let mut options = ParsedOptions::from_options(&ipc_config.options); // Override IPC config for each window with matching ID. for (_, window_context) in self .windows .iter_mut() .filter(|(id, _)| window_id.is_none() || window_id == Some(*id)) { if ipc_config.reset { window_context.reset_window_config(self.config.clone()); } else { window_context.add_window_config(self.config.clone(), &options); } } // Persist global options for future windows. if window_id.is_none() { if ipc_config.reset { self.global_ipc_options.clear(); } else { self.global_ipc_options.append(&mut options); } } }, // Process IPC config requests. #[cfg(unix)] (EventType::IpcGetConfig(stream), window_id) => { // Get the config for the requested window ID. let config = match self.windows.iter().find(|(id, _)| window_id == Some(*id)) { Some((_, window_context)) => window_context.config(), None => &self.global_ipc_options.override_config_rc(self.config.clone()), }; // Convert config to JSON format. let config_json = match serde_json::to_string(&config) { Ok(config_json) => config_json, Err(err) => { error!("Failed config serialization: {err}"); return; }, }; // Send JSON config to the socket. if let Ok(mut stream) = stream.try_clone() { ipc::send_reply(&mut stream, SocketReply::GetConfig(config_json)); } }, (EventType::ConfigReload(path), _) => { // Clear config logs from message bar for all terminals. for window_context in self.windows.values_mut() { if !window_context.message_buffer.is_empty() { window_context.message_buffer.remove_target(LOG_TARGET_CONFIG); window_context.display.pending_update.dirty = true; } } // Load config and update each terminal. if let Ok(config) = config::reload(&path, &mut self.cli_options) { self.config = Rc::new(config); // Restart config monitor if imports changed. if let Some(monitor) = self.config_monitor.take() { let paths = &self.config.config_paths; self.config_monitor = if monitor.needs_restart(paths) { monitor.shutdown(); ConfigMonitor::new(paths.clone(), self.proxy.clone()) } else { Some(monitor) }; } for window_context in self.windows.values_mut() { window_context.update_config(self.config.clone()); } } }, // Create a new terminal window. (EventType::CreateWindow(options), _) => { // XXX Ensure that no context is current when creating a new window, // otherwise it may lock the backing buffer of the // surface of current context when asking // e.g. EGL on Wayland to create a new context. for window_context in self.windows.values_mut() { window_context.display.make_not_current(); } if self.gl_config.is_none() { // Handle initial window creation in daemon mode. if let Err(err) = self.create_initial_window(event_loop, options) { self.initial_window_error = Some(err); event_loop.exit(); } } else if let Err(err) = self.create_window(event_loop, options) { error!("Could not open window: {err:?}"); } }, // Process events affecting all windows. (payload, None) => { let event = WinitEvent::UserEvent(Event::new(payload, None)); for window_context in self.windows.values_mut() { window_context.handle_event( #[cfg(target_os = "macos")] event_loop, &self.proxy, &mut self.clipboard, &mut self.scheduler, event.clone(), ); } }, (EventType::Terminal(TerminalEvent::Wakeup), Some(window_id)) => { if let Some(window_context) = self.windows.get_mut(window_id) { window_context.dirty = true; if window_context.display.window.has_frame { window_context.display.window.request_redraw(); } } }, (EventType::Terminal(TerminalEvent::Exit), Some(window_id)) => { // Remove the closed terminal. let window_context = match self.windows.entry(*window_id) { // Don't exit when terminal exits if user asked to hold the window. Entry::Occupied(window_context) if !window_context.get().display.window.hold => { window_context.remove() }, _ => return, }; // Unschedule pending events. self.scheduler.unschedule_window(window_context.id()); // Shutdown if no more terminals are open. if self.windows.is_empty() && !self.cli_options.daemon { // Write ref tests of last window to disk. if self.config.debug.ref_test { window_context.write_ref_test_results(); } event_loop.exit(); } }, // NOTE: This event bypasses batching to minimize input latency. (EventType::Frame, Some(window_id)) => { if let Some(window_context) = self.windows.get_mut(window_id) { window_context.display.window.has_frame = true; if window_context.dirty { window_context.display.window.request_redraw(); } } }, (payload, Some(window_id)) => { if let Some(window_context) = self.windows.get_mut(window_id) { window_context.handle_event( #[cfg(target_os = "macos")] event_loop, &self.proxy, &mut self.clipboard, &mut self.scheduler, WinitEvent::UserEvent(Event::new(payload, *window_id)), ); } }, }; } fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { if self.config.debug.print_events { info!(target: LOG_TARGET_WINIT, "About to wait"); } // Dispatch event to all windows. for window_context in self.windows.values_mut() { window_context.handle_event( #[cfg(target_os = "macos")] event_loop, &self.proxy, &mut self.clipboard, &mut self.scheduler, WinitEvent::AboutToWait, ); } // Update the scheduler after event processing to ensure // the event loop deadline is as accurate as possible. let control_flow = match self.scheduler.update() { Some(instant) => ControlFlow::WaitUntil(instant), None => ControlFlow::Wait, }; event_loop.set_control_flow(control_flow); } fn exiting(&mut self, _event_loop: &ActiveEventLoop) { if self.config.debug.print_events { info!("Exiting the event loop"); } match self.gl_config.take().map(|config| config.display()) { #[cfg(not(target_os = "macos"))] Some(glutin::display::Display::Egl(display)) => { // Ensure that all the windows are dropped, so the destructors for // Renderer and contexts ran. self.windows.clear(); // SAFETY: the display is being destroyed after destroying all the // windows, thus no attempt to access the EGL state will be made. unsafe { display.terminate(); } }, _ => (), } // SAFETY: The clipboard must be dropped before the event loop, so use the nop clipboard // as a safe placeholder. self.clipboard = Clipboard::new_nop(); } } /// Alacritty events. #[derive(Debug, Clone)] pub struct Event { /// Limit event to a specific window. window_id: Option<WindowId>, /// Event payload. payload: EventType, } impl Event { pub fn new<I: Into<Option<WindowId>>>(payload: EventType, window_id: I) -> Self { Self { window_id: window_id.into(), payload } } } impl From<Event> for WinitEvent<Event> { fn from(event: Event) -> Self { WinitEvent::UserEvent(event) } } /// Alacritty events. #[derive(Debug, Clone)] pub enum EventType { Terminal(TerminalEvent), ConfigReload(PathBuf), Message(Message), Scroll(Scroll), CreateWindow(WindowOptions), #[cfg(unix)] IpcConfig(IpcConfig), #[cfg(unix)] IpcGetConfig(Arc<UnixStream>), BlinkCursor, BlinkCursorTimeout, SearchNext, Frame, } impl From<TerminalEvent> for EventType { fn from(event: TerminalEvent) -> Self { Self::Terminal(event) } } /// Regex search state. pub struct SearchState { /// Search direction. pub direction: Direction, /// Current position in the search history. pub history_index: Option<usize>, /// Change in display offset since the beginning of the search. display_offset_delta: i32, /// Search origin in viewport coordinates relative to original display offset. origin: Point, /// Focused match during active search. focused_match: Option<Match>, /// Search regex and history. /// /// During an active search, the first element is the user's current input. /// /// While going through history, the [`SearchState::history_index`] will point to the element /// in history which is currently being previewed. history: VecDeque<String>, /// Compiled search automatons. dfas: Option<RegexSearch>, } impl SearchState { /// Search regex text if a search is active. pub fn regex(&self) -> Option<&String> { self.history_index.and_then(|index| self.history.get(index)) } /// Direction of the search from the search origin. pub fn direction(&self) -> Direction { self.direction } /// Focused match during vi-less search. pub fn focused_match(&self) -> Option<&Match> { self.focused_match.as_ref() } /// Clear the focused match. pub fn clear_focused_match(&mut self) { self.focused_match = None; } /// Active search dfas. pub fn dfas(&mut self) -> Option<&mut RegexSearch> { self.dfas.as_mut() } /// Search regex text if a search is active. fn regex_mut(&mut self) -> Option<&mut String> { self.history_index.and_then(move |index| self.history.get_mut(index)) } } impl Default for SearchState { fn default() -> Self { Self { direction: Direction::Right, display_offset_delta: Default::default(), focused_match: Default::default(), history_index: Default::default(), history: Default::default(), origin: Default::default(), dfas: Default::default(), } } } /// Vi inline search state. pub struct InlineSearchState { /// Whether inline search is currently waiting for search character input. pub char_pending: bool, pub character: Option<char>, direction: Direction, stop_short: bool, } impl Default for InlineSearchState { fn default() -> Self { Self { direction: Direction::Right, char_pending: Default::default(), stop_short: Default::default(), character: Default::default(), } } } pub struct ActionContext<'a, N, T> { pub notifier: &'a mut N, pub terminal: &'a mut Term<T>, pub clipboard: &'a mut Clipboard, pub mouse: &'a mut Mouse, pub touch: &'a mut TouchPurpose, pub modifiers: &'a mut Modifiers, pub display: &'a mut Display, pub message_buffer: &'a mut MessageBuffer, pub config: &'a UiConfig, pub cursor_blink_timed_out: &'a mut bool, pub prev_bell_cmd: &'a mut Option<Instant>, #[cfg(target_os = "macos")] pub event_loop: &'a ActiveEventLoop, pub event_proxy: &'a EventLoopProxy<Event>, pub scheduler: &'a mut Scheduler, pub search_state: &'a mut SearchState, pub inline_search_state: &'a mut InlineSearchState, pub dirty: &'a mut bool, pub occluded: &'a mut bool, pub preserve_title: bool, #[cfg(not(windows))] pub master_fd: RawFd, #[cfg(not(windows))] pub shell_pid: u32, } impl<'a, N: Notify + 'a, T: EventListener> input::ActionContext<T> for ActionContext<'a, N, T> { #[inline] fn write_to_pty<B: Into<Cow<'static, [u8]>>>(&self, val: B) { self.notifier.notify(val); } /// Request a redraw. #[inline] fn mark_dirty(&mut self) { *self.dirty = true; } #[inline] fn size_info(&self) -> SizeInfo { self.display.size_info } fn scroll(&mut self, scroll: Scroll) { let old_offset = self.terminal.grid().display_offset() as i32; let old_vi_cursor = self.terminal.vi_mode_cursor; self.terminal.scroll_display(scroll); let lines_changed = old_offset - self.terminal.grid().display_offset() as i32; // Keep track of manual display offset changes during search. if self.search_active() { self.search_state.display_offset_delta += lines_changed; } let vi_mode = self.terminal.mode().contains(TermMode::VI); // Update selection. if vi_mode && self.terminal.selection.as_ref().is_some_and(|s| !s.is_empty()) { self.update_selection(self.terminal.vi_mode_cursor.point, Side::Right); } else if self.mouse.left_button_state == ElementState::Pressed || self.mouse.right_button_state == ElementState::Pressed { let display_offset = self.terminal.grid().display_offset(); let point = self.mouse.point(&self.size_info(), display_offset); self.update_selection(point, self.mouse.cell_side); } // Scrolling inside Vi mode moves the cursor, so start typing. if vi_mode { self.on_typing_start(); } // Update dirty if actually scrolled or moved Vi cursor in Vi mode. *self.dirty |= lines_changed != 0 || (vi_mode && old_vi_cursor != self.terminal.vi_mode_cursor); } // Copy text selection. fn copy_selection(&mut self, ty: ClipboardType) { let text = match self.terminal.selection_to_string().filter(|s| !s.is_empty()) { Some(text) => text, None => return, }; if ty == ClipboardType::Selection && self.config.selection.save_to_clipboard { self.clipboard.store(ClipboardType::Clipboard, text.clone()); } self.clipboard.store(ty, text); } fn selection_is_empty(&self) -> bool { self.terminal.selection.as_ref().is_none_or(Selection::is_empty) } fn clear_selection(&mut self) { // Clear the selection on the terminal. let selection = self.terminal.selection.take(); // Mark the terminal as dirty when selection wasn't empty. *self.dirty |= selection.is_some_and(|s| !s.is_empty()); } fn update_selection(&mut self, mut point: Point, side: Side) { let mut selection = match self.terminal.selection.take() { Some(selection) => selection, None => return, }; // Treat motion over message bar like motion over the last line. point.line = min(point.line, self.terminal.bottommost_line()); // Update selection. selection.update(point, side); // Move vi cursor and expand selection. if self.terminal.mode().contains(TermMode::VI) && !self.search_active() { self.terminal.vi_mode_cursor.point = point; selection.include_all(); } self.terminal.selection = Some(selection); *self.dirty = true; } fn start_selection(&mut self, ty: SelectionType, point: Point, side: Side) { self.terminal.selection = Some(Selection::new(ty, point, side)); *self.dirty = true; self.copy_selection(ClipboardType::Selection); } fn toggle_selection(&mut self, ty: SelectionType, point: Point, side: Side) { match &mut self.terminal.selection { Some(selection) if selection.ty == ty && !selection.is_empty() => { self.clear_selection(); }, Some(selection) if !selection.is_empty() => { selection.ty = ty; *self.dirty = true; self.copy_selection(ClipboardType::Selection); }, _ => self.start_selection(ty, point, side), } } #[inline] fn mouse_mode(&self) -> bool { self.terminal.mode().intersects(TermMode::MOUSE_MODE) && !self.terminal.mode().contains(TermMode::VI) } #[inline] fn mouse_mut(&mut self) -> &mut Mouse { self.mouse } #[inline] fn mouse(&self) -> &Mouse { self.mouse } #[inline] fn touch_purpose(&mut self) -> &mut TouchPurpose { self.touch } #[inline] fn modifiers(&mut self) -> &mut Modifiers { self.modifiers } #[inline] fn window(&mut self) -> &mut Window { &mut self.display.window } #[inline] fn display(&mut self) -> &mut Display { self.display } #[inline] fn terminal(&self) -> &Term<T> { self.terminal } #[inline] fn terminal_mut(&mut self) -> &mut Term<T> { self.terminal } fn spawn_new_instance(&mut self) { let mut env_args = env::args(); let alacritty = env_args.next().unwrap(); let mut args: Vec<String> = Vec::new(); // Reuse the arguments passed to Alacritty for the new instance. #[allow(clippy::while_let_on_iterator)] while let Some(arg) = env_args.next() { // New instances shouldn't inherit command. if arg == "-e" || arg == "--command" { break; } // On unix, the working directory of the foreground shell is used by `start_daemon`. #[cfg(not(windows))] if arg == "--working-directory" { let _ = env_args.next(); continue; } args.push(arg); } self.spawn_daemon(&alacritty, &args); } #[cfg(not(windows))] fn create_new_window(&mut self, #[cfg(target_os = "macos")] tabbing_id: Option<String>) { let mut options = WindowOptions::default(); options.terminal_options.working_directory = foreground_process_path(self.master_fd, self.shell_pid).ok(); #[cfg(target_os = "macos")] { options.window_tabbing_id = tabbing_id; } let _ = self.event_proxy.send_event(Event::new(EventType::CreateWindow(options), None)); } #[cfg(windows)] fn create_new_window(&mut self) { let _ = self .event_proxy .send_event(Event::new(EventType::CreateWindow(WindowOptions::default()), None)); } fn spawn_daemon<I, S>(&self, program: &str, args: I) where I: IntoIterator<Item = S> + Debug + Copy, S: AsRef<OsStr>, { #[cfg(not(windows))] let result = spawn_daemon(program, args, self.master_fd, self.shell_pid); #[cfg(windows)] let result = spawn_daemon(program, args); match result { Ok(_) => debug!("Launched {program} with args {args:?}"), Err(err) => warn!("Unable to launch {program} with args {args:?}: {err}"), } } fn change_font_size(&mut self, delta: f32) { // Round to pick integral px steps, since fonts look better on them. let new_size = self.display.font_size.as_px().round() + delta; self.display.font_size = FontSize::from_px(new_size); let font = self.config.font.clone().with_size(self.display.font_size); self.display.pending_update.set_font(font); } fn reset_font_size(&mut self) { let scale_factor = self.display.window.scale_factor as f32; self.display.font_size = self.config.font.size().scale(scale_factor); self.display .pending_update .set_font(self.config.font.clone().with_size(self.display.font_size)); } #[inline] fn pop_message(&mut self) { if !self.message_buffer.is_empty() { self.display.pending_update.dirty = true; self.message_buffer.pop(); } } #[inline] fn start_search(&mut self, direction: Direction) { // Only create new history entry if the previous regex wasn't empty. if self.search_state.history.front().is_none_or(|regex| !regex.is_empty()) { self.search_state.history.push_front(String::new()); self.search_state.history.truncate(MAX_SEARCH_HISTORY_SIZE); } self.search_state.history_index = Some(0);
rust
Apache-2.0
6ee6e53ee3457c24137f117237b0ff1d84f6f836
2026-01-04T15:31:58.707223Z
true
alacritty/alacritty
https://github.com/alacritty/alacritty/blob/6ee6e53ee3457c24137f117237b0ff1d84f6f836/alacritty/src/string.rs
alacritty/src/string.rs
use std::cmp::Ordering; use std::iter::Skip; use std::str::Chars; use unicode_width::UnicodeWidthChar; /// The action performed by [`StrShortener`]. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum TextAction { /// Yield a spacer. Spacer, /// Terminate state reached. Terminate, /// Yield a shortener. Shortener, /// Yield a character. Char, } /// The direction which we should shorten. #[derive(Clone, Copy, PartialEq, Eq)] pub enum ShortenDirection { /// Shorten to the start of the string. Left, /// Shorten to the end of the string. Right, } /// Iterator that yield shortened version of the text. pub struct StrShortener<'a> { chars: Skip<Chars<'a>>, accumulated_len: usize, max_width: usize, direction: ShortenDirection, shortener: Option<char>, text_action: TextAction, } impl<'a> StrShortener<'a> { pub fn new( text: &'a str, max_width: usize, direction: ShortenDirection, mut shortener: Option<char>, ) -> Self { if text.is_empty() { // If we don't have any text don't produce a shortener for it. let _ = shortener.take(); } if direction == ShortenDirection::Right { return Self { #[allow(clippy::iter_skip_zero)] chars: text.chars().skip(0), accumulated_len: 0, text_action: TextAction::Char, max_width, direction, shortener, }; } let mut offset = 0; let mut current_len = 0; let mut iter = text.chars().rev().enumerate(); while let Some((idx, ch)) = iter.next() { let ch_width = ch.width().unwrap_or(1); current_len += ch_width; match current_len.cmp(&max_width) { // We can only be here if we've faced wide character or we've already // handled equality situation. Anyway, break. Ordering::Greater => break, Ordering::Equal => { if shortener.is_some() && iter.clone().next().is_some() { // We have one more character after, shortener will accumulate for // the `current_len`. break; } else { // The match is exact, consume shortener. let _ = shortener.take(); } }, Ordering::Less => (), } offset = idx + 1; } // Consume the iterator to count the number of characters in it. let num_chars = iter.last().map_or(offset, |(idx, _)| idx + 1); let skip_chars = num_chars - offset; let text_action = if current_len < max_width || shortener.is_none() { TextAction::Char } else { TextAction::Shortener }; let chars = text.chars().skip(skip_chars); Self { chars, accumulated_len: 0, text_action, max_width, direction, shortener } } } impl Iterator for StrShortener<'_> { type Item = char; fn next(&mut self) -> Option<Self::Item> { match self.text_action { TextAction::Spacer => { self.text_action = TextAction::Char; Some(' ') }, TextAction::Terminate => { // We've reached the termination state. None }, TextAction::Shortener => { // When we shorten from the left we yield the shortener first and process the rest. self.text_action = if self.direction == ShortenDirection::Left { TextAction::Char } else { TextAction::Terminate }; // Consume the shortener to avoid yielding it later when shortening left. self.shortener.take() }, TextAction::Char => { let ch = self.chars.next()?; let ch_width = ch.width().unwrap_or(1); // Advance width. self.accumulated_len += ch_width; if self.accumulated_len > self.max_width { self.text_action = TextAction::Terminate; return self.shortener; } else if self.accumulated_len == self.max_width && self.shortener.is_some() { // Check if we have a next char. let has_next = self.chars.clone().next().is_some(); // We should terminate after that. self.text_action = TextAction::Terminate; return has_next.then(|| self.shortener.unwrap()).or(Some(ch)); } // Add a spacer for wide character. if ch_width == 2 { self.text_action = TextAction::Spacer; } Some(ch) }, } } } #[cfg(test)] mod tests { use super::*; #[test] fn into_shortened_with_shortener() { let s = "Hello"; let len = s.chars().count(); assert_eq!( "", StrShortener::new("", 1, ShortenDirection::Left, Some('.')).collect::<String>() ); assert_eq!( ".", StrShortener::new(s, 1, ShortenDirection::Right, Some('.')).collect::<String>() ); assert_eq!( ".", StrShortener::new(s, 1, ShortenDirection::Left, Some('.')).collect::<String>() ); assert_eq!( "H.", StrShortener::new(s, 2, ShortenDirection::Right, Some('.')).collect::<String>() ); assert_eq!( ".o", StrShortener::new(s, 2, ShortenDirection::Left, Some('.')).collect::<String>() ); assert_eq!( s, &StrShortener::new(s, len * 2, ShortenDirection::Right, Some('.')).collect::<String>() ); assert_eq!( s, &StrShortener::new(s, len * 2, ShortenDirection::Left, Some('.')).collect::<String>() ); let s = "ちはP"; let len = 2 + 2 + 1; assert_eq!( ".", &StrShortener::new(s, 1, ShortenDirection::Right, Some('.')).collect::<String>() ); assert_eq!( &".", &StrShortener::new(s, 1, ShortenDirection::Left, Some('.')).collect::<String>() ); assert_eq!( ".", &StrShortener::new(s, 2, ShortenDirection::Right, Some('.')).collect::<String>() ); assert_eq!( ".P", &StrShortener::new(s, 2, ShortenDirection::Left, Some('.')).collect::<String>() ); assert_eq!( "ち .", &StrShortener::new(s, 3, ShortenDirection::Right, Some('.')).collect::<String>() ); assert_eq!( ".P", &StrShortener::new(s, 3, ShortenDirection::Left, Some('.')).collect::<String>() ); assert_eq!( "ち は P", &StrShortener::new(s, len * 2, ShortenDirection::Left, Some('.')).collect::<String>() ); assert_eq!( "ち は P", &StrShortener::new(s, len * 2, ShortenDirection::Right, Some('.')).collect::<String>() ); } #[test] fn into_shortened_without_shortener() { let s = "Hello"; assert_eq!("", StrShortener::new("", 1, ShortenDirection::Left, None).collect::<String>()); assert_eq!( "H", &StrShortener::new(s, 1, ShortenDirection::Right, None).collect::<String>() ); assert_eq!("o", &StrShortener::new(s, 1, ShortenDirection::Left, None).collect::<String>()); assert_eq!( "He", &StrShortener::new(s, 2, ShortenDirection::Right, None).collect::<String>() ); assert_eq!( "lo", &StrShortener::new(s, 2, ShortenDirection::Left, None).collect::<String>() ); assert_eq!( &s, &StrShortener::new(s, s.len(), ShortenDirection::Right, None).collect::<String>() ); assert_eq!( &s, &StrShortener::new(s, s.len(), ShortenDirection::Left, None).collect::<String>() ); let s = "こJんにちはP"; let len = 2 + 1 + 2 + 2 + 2 + 2 + 1; assert_eq!("", &StrShortener::new(s, 1, ShortenDirection::Right, None).collect::<String>()); assert_eq!("P", &StrShortener::new(s, 1, ShortenDirection::Left, None).collect::<String>()); assert_eq!( "こ ", &StrShortener::new(s, 2, ShortenDirection::Right, None).collect::<String>() ); assert_eq!("P", &StrShortener::new(s, 2, ShortenDirection::Left, None).collect::<String>()); assert_eq!( "こ J", &StrShortener::new(s, 3, ShortenDirection::Right, None).collect::<String>() ); assert_eq!( "は P", &StrShortener::new(s, 3, ShortenDirection::Left, None).collect::<String>() ); assert_eq!( "こ Jん に ち は P", &StrShortener::new(s, len, ShortenDirection::Left, None).collect::<String>() ); assert_eq!( "こ Jん に ち は P", &StrShortener::new(s, len, ShortenDirection::Right, None).collect::<String>() ); } }
rust
Apache-2.0
6ee6e53ee3457c24137f117237b0ff1d84f6f836
2026-01-04T15:31:58.707223Z
false
alacritty/alacritty
https://github.com/alacritty/alacritty/blob/6ee6e53ee3457c24137f117237b0ff1d84f6f836/alacritty/src/message_bar.rs
alacritty/src/message_bar.rs
use std::collections::VecDeque; use unicode_width::UnicodeWidthChar; use alacritty_terminal::grid::Dimensions; use crate::display::SizeInfo; pub const CLOSE_BUTTON_TEXT: &str = "[X]"; const CLOSE_BUTTON_PADDING: usize = 1; const MIN_FREE_LINES: usize = 3; const TRUNCATED_MESSAGE: &str = "[MESSAGE TRUNCATED]"; /// Message for display in the MessageBuffer. #[derive(Debug, Eq, PartialEq, Clone)] pub struct Message { text: String, ty: MessageType, target: Option<String>, } /// Purpose of the message. #[derive(Debug, Eq, PartialEq, Clone, Copy)] pub enum MessageType { /// A message represents an error. Error, /// A message represents a warning. Warning, } impl Message { /// Create a new message. pub fn new(text: String, ty: MessageType) -> Message { Message { text, ty, target: None } } /// Formatted message text lines. pub fn text(&self, size_info: &SizeInfo) -> Vec<String> { let num_cols = size_info.columns(); let total_lines = (size_info.height() - 2. * size_info.padding_y()) / size_info.cell_height(); let max_lines = (total_lines as usize).saturating_sub(MIN_FREE_LINES); let button_len = CLOSE_BUTTON_TEXT.chars().count(); // Split line to fit the screen. let mut lines = Vec::new(); let mut line = String::new(); let mut line_len = 0; for c in self.text.trim().chars() { if c == '\n' || line_len == num_cols // Keep space in first line for button. || (lines.is_empty() && num_cols >= button_len && line_len == num_cols.saturating_sub(button_len + CLOSE_BUTTON_PADDING)) { let is_whitespace = c.is_whitespace(); // Attempt to wrap on word boundaries. let mut new_line = String::new(); if let Some(index) = line.rfind(char::is_whitespace).filter(|_| !is_whitespace) { let split = line.split_off(index + 1); line.pop(); new_line = split; } lines.push(Self::pad_text(line, num_cols)); line = new_line; line_len = line.chars().count(); // Do not append whitespace at EOL. if is_whitespace { continue; } } line.push(c); // Reserve extra column for fullwidth characters. let width = c.width().unwrap_or(0); if width == 2 { line.push(' '); } line_len += width } lines.push(Self::pad_text(line, num_cols)); // Truncate output if it's too long. if lines.len() > max_lines { lines.truncate(max_lines); if TRUNCATED_MESSAGE.len() <= num_cols { if let Some(line) = lines.iter_mut().last() { *line = Self::pad_text(TRUNCATED_MESSAGE.into(), num_cols); } } } // Append close button to first line. if button_len <= num_cols { if let Some(line) = lines.get_mut(0) { line.truncate(num_cols - button_len); line.push_str(CLOSE_BUTTON_TEXT); } } lines } /// Message type. #[inline] pub fn ty(&self) -> MessageType { self.ty } /// Message target. #[inline] pub fn target(&self) -> Option<&String> { self.target.as_ref() } /// Update the message target. #[inline] pub fn set_target(&mut self, target: String) { self.target = Some(target); } /// Right-pad text to fit a specific number of columns. #[inline] fn pad_text(mut text: String, num_cols: usize) -> String { let padding_len = num_cols.saturating_sub(text.chars().count()); text.extend(vec![' '; padding_len]); text } } /// Storage for message bar. #[derive(Debug, Default)] pub struct MessageBuffer { messages: VecDeque<Message>, } impl MessageBuffer { /// Check if there are any messages queued. #[inline] pub fn is_empty(&self) -> bool { self.messages.is_empty() } /// Current message. #[inline] pub fn message(&self) -> Option<&Message> { self.messages.front() } /// Remove the currently visible message. #[inline] pub fn pop(&mut self) { // Remove the message itself. let msg = self.messages.pop_front(); // Remove all duplicates. if let Some(msg) = msg { self.messages = self.messages.drain(..).filter(|m| m != &msg).collect(); } } /// Remove all messages with a specific target. #[inline] pub fn remove_target(&mut self, target: &str) { self.messages = self .messages .drain(..) .filter(|m| m.target().map(String::as_str) != Some(target)) .collect(); } /// Add a new message to the queue. #[inline] pub fn push(&mut self, message: Message) { self.messages.push_back(message); } /// Check whether the message is already queued in the message bar. #[inline] pub fn is_queued(&self, message: &Message) -> bool { self.messages.contains(message) } } #[cfg(test)] mod tests { use super::*; use crate::display::SizeInfo; #[test] fn appends_close_button() { let input = "a"; let mut message_buffer = MessageBuffer::default(); message_buffer.push(Message::new(input.into(), MessageType::Error)); let size = SizeInfo::new(7., 10., 1., 1., 0., 0., false); let lines = message_buffer.message().unwrap().text(&size); assert_eq!(lines, vec![String::from("a [X]")]); } #[test] fn multiline_close_button_first_line() { let input = "fo\nbar"; let mut message_buffer = MessageBuffer::default(); message_buffer.push(Message::new(input.into(), MessageType::Error)); let size = SizeInfo::new(6., 10., 1., 1., 0., 0., false); let lines = message_buffer.message().unwrap().text(&size); assert_eq!(lines, vec![String::from("fo [X]"), String::from("bar ")]); } #[test] fn splits_on_newline() { let input = "a\nb"; let mut message_buffer = MessageBuffer::default(); message_buffer.push(Message::new(input.into(), MessageType::Error)); let size = SizeInfo::new(6., 10., 1., 1., 0., 0., false); let lines = message_buffer.message().unwrap().text(&size); assert_eq!(lines.len(), 2); } #[test] fn splits_on_length() { let input = "foobar1"; let mut message_buffer = MessageBuffer::default(); message_buffer.push(Message::new(input.into(), MessageType::Error)); let size = SizeInfo::new(6., 10., 1., 1., 0., 0., false); let lines = message_buffer.message().unwrap().text(&size); assert_eq!(lines.len(), 2); } #[test] fn empty_with_shortterm() { let input = "foobar"; let mut message_buffer = MessageBuffer::default(); message_buffer.push(Message::new(input.into(), MessageType::Error)); let size = SizeInfo::new(6., 0., 1., 1., 0., 0., false); let lines = message_buffer.message().unwrap().text(&size); assert_eq!(lines.len(), 0); } #[test] fn truncates_long_messages() { let input = "hahahahahahahahahahaha truncate this because it's too long for the term"; let mut message_buffer = MessageBuffer::default(); message_buffer.push(Message::new(input.into(), MessageType::Error)); let size = SizeInfo::new(22., (MIN_FREE_LINES + 2) as f32, 1., 1., 0., 0., false); let lines = message_buffer.message().unwrap().text(&size); assert_eq!(lines, vec![ String::from("hahahahahahahahaha [X]"), String::from("[MESSAGE TRUNCATED] ") ]); } #[test] fn hide_button_when_too_narrow() { let input = "ha"; let mut message_buffer = MessageBuffer::default(); message_buffer.push(Message::new(input.into(), MessageType::Error)); let size = SizeInfo::new(2., 10., 1., 1., 0., 0., false); let lines = message_buffer.message().unwrap().text(&size); assert_eq!(lines, vec![String::from("ha")]); } #[test] fn hide_truncated_when_too_narrow() { let input = "hahahahahahahahaha"; let mut message_buffer = MessageBuffer::default(); message_buffer.push(Message::new(input.into(), MessageType::Error)); let size = SizeInfo::new(2., (MIN_FREE_LINES + 2) as f32, 1., 1., 0., 0., false); let lines = message_buffer.message().unwrap().text(&size); assert_eq!(lines, vec![String::from("ha"), String::from("ha")]); } #[test] fn add_newline_for_button() { let input = "test"; let mut message_buffer = MessageBuffer::default(); message_buffer.push(Message::new(input.into(), MessageType::Error)); let size = SizeInfo::new(5., 10., 1., 1., 0., 0., false); let lines = message_buffer.message().unwrap().text(&size); assert_eq!(lines, vec![String::from("t [X]"), String::from("est ")]); } #[test] fn remove_target() { let mut message_buffer = MessageBuffer::default(); for i in 0..10 { let mut msg = Message::new(i.to_string(), MessageType::Error); if i % 2 == 0 && i < 5 { msg.set_target("target".into()); } message_buffer.push(msg); } message_buffer.remove_target("target"); // Count number of messages. let mut num_messages = 0; while message_buffer.message().is_some() { num_messages += 1; message_buffer.pop(); } assert_eq!(num_messages, 7); } #[test] fn pop() { let mut message_buffer = MessageBuffer::default(); let one = Message::new(String::from("one"), MessageType::Error); message_buffer.push(one.clone()); let two = Message::new(String::from("two"), MessageType::Warning); message_buffer.push(two.clone()); assert_eq!(message_buffer.message(), Some(&one)); message_buffer.pop(); assert_eq!(message_buffer.message(), Some(&two)); } #[test] fn wrap_on_words() { let input = "a\nbc defg"; let mut message_buffer = MessageBuffer::default(); message_buffer.push(Message::new(input.into(), MessageType::Error)); let size = SizeInfo::new(5., 10., 1., 1., 0., 0., false); let lines = message_buffer.message().unwrap().text(&size); assert_eq!(lines, vec![ String::from("a [X]"), String::from("bc "), String::from("defg ") ]); } #[test] fn wrap_with_unicode() { let input = "ab\nc 👩d fgh"; let mut message_buffer = MessageBuffer::default(); message_buffer.push(Message::new(input.into(), MessageType::Error)); let size = SizeInfo::new(7., 10., 1., 1., 0., 0., false); let lines = message_buffer.message().unwrap().text(&size); assert_eq!(lines, vec![ String::from("ab [X]"), String::from("c 👩 d "), String::from("fgh ") ]); } #[test] fn strip_whitespace_at_linebreak() { let input = "\n0 1 2 3"; let mut message_buffer = MessageBuffer::default(); message_buffer.push(Message::new(input.into(), MessageType::Error)); let size = SizeInfo::new(3., 10., 1., 1., 0., 0., false); let lines = message_buffer.message().unwrap().text(&size); assert_eq!(lines, vec![String::from("[X]"), String::from("0 1"), String::from("2 3"),]); } #[test] fn remove_duplicates() { let mut message_buffer = MessageBuffer::default(); for _ in 0..10 { let msg = Message::new(String::from("test"), MessageType::Error); message_buffer.push(msg); } message_buffer.push(Message::new(String::from("other"), MessageType::Error)); message_buffer.push(Message::new(String::from("test"), MessageType::Warning)); let _ = message_buffer.message(); message_buffer.pop(); // Count number of messages. let mut num_messages = 0; while message_buffer.message().is_some() { num_messages += 1; message_buffer.pop(); } assert_eq!(num_messages, 2); } }
rust
Apache-2.0
6ee6e53ee3457c24137f117237b0ff1d84f6f836
2026-01-04T15:31:58.707223Z
false
alacritty/alacritty
https://github.com/alacritty/alacritty/blob/6ee6e53ee3457c24137f117237b0ff1d84f6f836/alacritty/src/clipboard.rs
alacritty/src/clipboard.rs
use log::{debug, warn}; use winit::raw_window_handle::RawDisplayHandle; use alacritty_terminal::term::ClipboardType; #[cfg(any(feature = "x11", target_os = "macos", windows))] use copypasta::ClipboardContext; use copypasta::ClipboardProvider; use copypasta::nop_clipboard::NopClipboardContext; #[cfg(all(feature = "wayland", not(any(target_os = "macos", windows))))] use copypasta::wayland_clipboard; #[cfg(all(feature = "x11", not(any(target_os = "macos", windows))))] use copypasta::x11_clipboard::{Primary as X11SelectionClipboard, X11ClipboardContext}; pub struct Clipboard { clipboard: Box<dyn ClipboardProvider>, selection: Option<Box<dyn ClipboardProvider>>, } impl Clipboard { pub unsafe fn new(display: RawDisplayHandle) -> Self { match display { #[cfg(all(feature = "wayland", not(any(target_os = "macos", windows))))] RawDisplayHandle::Wayland(display) => { let (selection, clipboard) = unsafe { wayland_clipboard::create_clipboards_from_external(display.display.as_ptr()) }; Self { clipboard: Box::new(clipboard), selection: Some(Box::new(selection)) } }, _ => Self::default(), } } /// Used for tests, to handle missing clipboard provider when built without the `x11` /// feature, and as default clipboard value. pub fn new_nop() -> Self { Self { clipboard: Box::new(NopClipboardContext::new().unwrap()), selection: None } } } impl Default for Clipboard { fn default() -> Self { #[cfg(any(target_os = "macos", windows))] return Self { clipboard: Box::new(ClipboardContext::new().unwrap()), selection: None }; #[cfg(all(feature = "x11", not(any(target_os = "macos", windows))))] return Self { clipboard: Box::new(ClipboardContext::new().unwrap()), selection: Some(Box::new(X11ClipboardContext::<X11SelectionClipboard>::new().unwrap())), }; #[cfg(not(any(feature = "x11", target_os = "macos", windows)))] return Self::new_nop(); } } impl Clipboard { pub fn store(&mut self, ty: ClipboardType, text: impl Into<String>) { let clipboard = match (ty, &mut self.selection) { (ClipboardType::Selection, Some(provider)) => provider, (ClipboardType::Selection, None) => return, _ => &mut self.clipboard, }; clipboard.set_contents(text.into()).unwrap_or_else(|err| { warn!("Unable to store text in clipboard: {err}"); }); } pub fn load(&mut self, ty: ClipboardType) -> String { let clipboard = match (ty, &mut self.selection) { (ClipboardType::Selection, Some(provider)) => provider, _ => &mut self.clipboard, }; match clipboard.get_contents() { Err(err) => { debug!("Unable to load text from clipboard: {err}"); String::new() }, Ok(text) => text, } } }
rust
Apache-2.0
6ee6e53ee3457c24137f117237b0ff1d84f6f836
2026-01-04T15:31:58.707223Z
false
alacritty/alacritty
https://github.com/alacritty/alacritty/blob/6ee6e53ee3457c24137f117237b0ff1d84f6f836/alacritty/src/cli.rs
alacritty/src/cli.rs
use std::cmp::max; use std::collections::HashMap; use std::ops::{Deref, DerefMut}; use std::path::PathBuf; use std::rc::Rc; use alacritty_config::SerdeReplace; use clap::{ArgAction, Args, Parser, Subcommand, ValueHint}; use log::{LevelFilter, error}; use serde::{Deserialize, Serialize}; use toml::Value; use alacritty_terminal::tty::Options as PtyOptions; use crate::config::UiConfig; use crate::config::ui_config::Program; use crate::config::window::{Class, Identity}; use crate::logging::LOG_TARGET_IPC_CONFIG; /// CLI options for the main Alacritty executable. #[derive(Parser, Default, Debug)] #[clap(author, about, version = env!("VERSION"))] pub struct Options { /// Print all events to STDOUT. #[clap(long)] pub print_events: bool, /// Generates ref test. #[clap(long, conflicts_with("daemon"))] pub ref_test: bool, /// X11 window ID to embed Alacritty within (decimal or hexadecimal with "0x" prefix). #[clap(long)] pub embed: Option<String>, /// Specify alternative configuration file [default: /// $XDG_CONFIG_HOME/alacritty/alacritty.toml]. #[cfg(not(any(target_os = "macos", windows)))] #[clap(long, value_hint = ValueHint::FilePath)] pub config_file: Option<PathBuf>, /// Specify alternative configuration file [default: %APPDATA%\alacritty\alacritty.toml]. #[cfg(windows)] #[clap(long, value_hint = ValueHint::FilePath)] pub config_file: Option<PathBuf>, /// Specify alternative configuration file [default: $HOME/.config/alacritty/alacritty.toml]. #[cfg(target_os = "macos")] #[clap(long, value_hint = ValueHint::FilePath)] pub config_file: Option<PathBuf>, /// Path for IPC socket creation. #[cfg(unix)] #[clap(long, value_hint = ValueHint::FilePath)] pub socket: Option<PathBuf>, /// Reduces the level of verbosity (the min level is -qq). #[clap(short, conflicts_with("verbose"), action = ArgAction::Count)] quiet: u8, /// Increases the level of verbosity (the max level is -vvv). #[clap(short, conflicts_with("quiet"), action = ArgAction::Count)] verbose: u8, /// Do not spawn an initial window. #[clap(long)] pub daemon: bool, /// CLI options for config overrides. #[clap(skip)] pub config_options: ParsedOptions, /// Options which can be passed via IPC. #[clap(flatten)] pub window_options: WindowOptions, /// Subcommand passed to the CLI. #[clap(subcommand)] pub subcommands: Option<Subcommands>, } impl Options { pub fn new() -> Self { let mut options = Self::parse(); // Parse CLI config overrides. options.config_options = options.window_options.config_overrides(); options } /// Override configuration file with options from the CLI. pub fn override_config(&mut self, config: &mut UiConfig) { #[cfg(unix)] if self.socket.is_some() { config.ipc_socket = Some(true); } config.window.embed = self.embed.as_ref().and_then(|embed| parse_hex_or_decimal(embed)); config.debug.print_events |= self.print_events; config.debug.log_level = max(config.debug.log_level, self.log_level()); config.debug.ref_test |= self.ref_test; if config.debug.print_events { config.debug.log_level = max(config.debug.log_level, LevelFilter::Info); } // Replace CLI options. self.config_options.override_config(config); } /// Logging filter level. pub fn log_level(&self) -> LevelFilter { match (self.quiet, self.verbose) { // Force at least `Info` level for `--print-events`. (_, 0) if self.print_events => LevelFilter::Info, // Default. (0, 0) => LevelFilter::Warn, // Verbose. (_, 1) => LevelFilter::Info, (_, 2) => LevelFilter::Debug, (0, _) => LevelFilter::Trace, // Quiet. (1, _) => LevelFilter::Error, (..) => LevelFilter::Off, } } } /// Parse the class CLI parameter. fn parse_class(input: &str) -> Result<Class, String> { let (general, instance) = match input.split_once(',') { // Warn the user if they've passed too many values. Some((_, instance)) if instance.contains(',') => { return Err(String::from("Too many parameters")); }, Some((general, instance)) => (general, instance), None => (input, input), }; Ok(Class::new(general, instance)) } /// Convert to hex if possible, else decimal fn parse_hex_or_decimal(input: &str) -> Option<u32> { input .strip_prefix("0x") .and_then(|value| u32::from_str_radix(value, 16).ok()) .or_else(|| input.parse().ok()) } /// Terminal specific cli options which can be passed to new windows via IPC. #[derive(Serialize, Deserialize, Args, Default, Debug, Clone, PartialEq, Eq)] pub struct TerminalOptions { /// Start the shell in the specified working directory. #[clap(long, value_hint = ValueHint::FilePath)] pub working_directory: Option<PathBuf>, /// Remain open after child process exit. #[clap(long)] pub hold: bool, /// Command and args to execute (must be last argument). #[clap(short = 'e', long, allow_hyphen_values = true, num_args = 1..)] command: Vec<String>, } impl TerminalOptions { /// Shell override passed through the CLI. pub fn command(&self) -> Option<Program> { let (program, args) = self.command.split_first()?; Some(Program::WithArgs { program: program.clone(), args: args.to_vec() }) } /// Override the [`PtyOptions`]'s fields with the [`TerminalOptions`]. pub fn override_pty_config(&self, pty_config: &mut PtyOptions) { if let Some(working_directory) = &self.working_directory { if working_directory.is_dir() { pty_config.working_directory = Some(working_directory.to_owned()); } else { error!("Invalid working directory: {working_directory:?}"); } } if let Some(command) = self.command() { pty_config.shell = Some(command.into()); } pty_config.drain_on_exit |= self.hold; } } impl From<TerminalOptions> for PtyOptions { fn from(mut options: TerminalOptions) -> Self { PtyOptions { working_directory: options.working_directory.take(), shell: options.command().map(Into::into), drain_on_exit: options.hold, env: HashMap::new(), #[cfg(target_os = "windows")] escape_args: false, } } } /// Window specific cli options which can be passed to new windows via IPC. #[derive(Serialize, Deserialize, Args, Default, Debug, Clone, PartialEq, Eq)] pub struct WindowIdentity { /// Defines the window title [default: Alacritty]. #[clap(short = 'T', short_alias('t'), long)] pub title: Option<String>, /// Defines window class/app_id on X11/Wayland [default: Alacritty]. #[clap(long, value_name = "general> | <general>,<instance", value_parser = parse_class)] pub class: Option<Class>, } impl WindowIdentity { /// Override the [`WindowIdentity`]'s fields with the [`WindowOptions`]. pub fn override_identity_config(&self, identity: &mut Identity) { if let Some(title) = &self.title { identity.title.clone_from(title); } if let Some(class) = &self.class { identity.class.clone_from(class); } } } /// Available CLI subcommands. #[derive(Subcommand, Debug)] pub enum Subcommands { #[cfg(unix)] Msg(MessageOptions), Migrate(MigrateOptions), } /// Send a message to the Alacritty socket. #[cfg(unix)] #[derive(Args, Debug)] pub struct MessageOptions { /// IPC socket connection path override. #[clap(short, long, value_hint = ValueHint::FilePath)] pub socket: Option<PathBuf>, /// Message which should be sent. #[clap(subcommand)] pub message: SocketMessage, } /// Available socket messages. #[cfg(unix)] #[derive(Subcommand, Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] pub enum SocketMessage { /// Create a new window in the same Alacritty process. CreateWindow(WindowOptions), /// Update the Alacritty configuration. Config(IpcConfig), /// Read runtime Alacritty configuration. GetConfig(IpcGetConfig), } /// Migrate the configuration file. #[derive(Args, Clone, Debug)] pub struct MigrateOptions { /// Path to the configuration file. #[clap(short, long, value_hint = ValueHint::FilePath)] pub config_file: Option<PathBuf>, /// Only output TOML config to STDOUT. #[clap(short, long)] pub dry_run: bool, /// Do not recurse over imports. #[clap(short = 'i', long)] pub skip_imports: bool, /// Do not move renamed fields to their new location. #[clap(long)] pub skip_renames: bool, #[clap(short, long)] /// Do not output to STDOUT. pub silent: bool, } /// Subset of options that we pass to 'create-window' IPC subcommand. #[derive(Serialize, Deserialize, Args, Default, Clone, Debug, PartialEq, Eq)] pub struct WindowOptions { /// Terminal options which can be passed via IPC. #[clap(flatten)] pub terminal_options: TerminalOptions, #[clap(flatten)] /// Window options which could be passed via IPC. pub window_identity: WindowIdentity, #[clap(skip)] #[cfg(target_os = "macos")] /// The window tabbing identifier to use when building a window. pub window_tabbing_id: Option<String>, #[clap(skip)] #[cfg(not(any(target_os = "macos", windows)))] /// `ActivationToken` that we pass to winit. pub activation_token: Option<String>, /// Override configuration file options [example: 'cursor.style="Beam"']. #[clap(short = 'o', long, num_args = 1..)] option: Vec<String>, } impl WindowOptions { /// Get the parsed set of CLI config overrides. pub fn config_overrides(&self) -> ParsedOptions { ParsedOptions::from_options(&self.option) } } /// Parameters to the `config` IPC subcommand. #[cfg(unix)] #[derive(Args, Serialize, Deserialize, Default, Debug, Clone, PartialEq, Eq)] pub struct IpcConfig { /// Configuration file options [example: 'cursor.style="Beam"']. #[clap(required = true, value_name = "CONFIG_OPTIONS")] pub options: Vec<String>, /// Window ID for the new config. /// /// Use `-1` to apply this change to all windows. #[clap(short, long, allow_hyphen_values = true, env = "ALACRITTY_WINDOW_ID")] pub window_id: Option<i128>, /// Clear all runtime configuration changes. #[clap(short, long, conflicts_with = "options")] pub reset: bool, } /// Parameters to the `get-config` IPC subcommand. #[cfg(unix)] #[derive(Args, Serialize, Deserialize, Default, Debug, Clone, PartialEq, Eq)] pub struct IpcGetConfig { /// Window ID for the config request. /// /// Use `-1` to get the global config. #[clap(short, long, allow_hyphen_values = true, env = "ALACRITTY_WINDOW_ID")] pub window_id: Option<i128>, } /// Parsed CLI config overrides. #[derive(Debug, Default)] pub struct ParsedOptions { config_options: Vec<(String, Value)>, } impl ParsedOptions { /// Parse CLI config overrides. pub fn from_options(options: &[String]) -> Self { let mut config_options = Vec::new(); for option in options { let parsed = match toml::from_str(option) { Ok(parsed) => parsed, Err(err) => { eprintln!("Ignoring invalid CLI option '{option}': {err}"); continue; }, }; config_options.push((option.clone(), parsed)); } Self { config_options } } /// Apply CLI config overrides, removing broken ones. pub fn override_config(&mut self, config: &mut UiConfig) { let mut i = 0; while i < self.config_options.len() { let (option, parsed) = &self.config_options[i]; match config.replace(parsed.clone()) { Err(err) => { error!( target: LOG_TARGET_IPC_CONFIG, "Unable to override option '{option}': {err}" ); self.config_options.swap_remove(i); }, Ok(_) => i += 1, } } } /// Apply CLI config overrides to a CoW config. pub fn override_config_rc(&mut self, config: Rc<UiConfig>) -> Rc<UiConfig> { // Skip clone without write requirement. if self.config_options.is_empty() { return config; } // Override cloned config. let mut config = (*config).clone(); self.override_config(&mut config); Rc::new(config) } } impl Deref for ParsedOptions { type Target = Vec<(String, Value)>; fn deref(&self) -> &Self::Target { &self.config_options } } impl DerefMut for ParsedOptions { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.config_options } } #[cfg(test)] mod tests { use super::*; #[cfg(target_os = "linux")] use std::fs::File; #[cfg(target_os = "linux")] use std::io::Read; #[cfg(target_os = "linux")] use clap::CommandFactory; #[cfg(target_os = "linux")] use clap_complete::Shell; use toml::Table; #[test] fn dynamic_title_ignoring_options_by_default() { let mut config = UiConfig::default(); let old_dynamic_title = config.window.dynamic_title; Options::default().override_config(&mut config); assert_eq!(old_dynamic_title, config.window.dynamic_title); } #[test] fn dynamic_title_not_overridden_by_config() { let mut config = UiConfig::default(); config.window.identity.title = "foo".to_owned(); Options::default().override_config(&mut config); assert!(config.window.dynamic_title); } #[test] fn valid_option_as_value() { // Test with a single field. let value: Value = toml::from_str("field=true").unwrap(); let mut table = Table::new(); table.insert(String::from("field"), Value::Boolean(true)); assert_eq!(value, Value::Table(table)); // Test with nested fields let value: Value = toml::from_str("parent.field=true").unwrap(); let mut parent_table = Table::new(); parent_table.insert(String::from("field"), Value::Boolean(true)); let mut table = Table::new(); table.insert(String::from("parent"), Value::Table(parent_table)); assert_eq!(value, Value::Table(table)); } #[test] fn invalid_option_as_value() { let value = toml::from_str::<Value>("}"); assert!(value.is_err()); } #[test] fn float_option_as_value() { let value: Value = toml::from_str("float=3.4").unwrap(); let mut expected = Table::new(); expected.insert(String::from("float"), Value::Float(3.4)); assert_eq!(value, Value::Table(expected)); } #[test] fn parse_instance_class() { let class = parse_class("one").unwrap(); assert_eq!(class.general, "one"); assert_eq!(class.instance, "one"); } #[test] fn parse_general_class() { let class = parse_class("one,two").unwrap(); assert_eq!(class.general, "one"); assert_eq!(class.instance, "two"); } #[test] fn parse_invalid_class() { let class = parse_class("one,two,three"); assert!(class.is_err()); } #[test] fn valid_decimal() { let value = parse_hex_or_decimal("10485773"); assert_eq!(value, Some(10485773)); } #[test] fn valid_hex_to_decimal() { let value = parse_hex_or_decimal("0xa0000d"); assert_eq!(value, Some(10485773)); } #[test] fn invalid_hex_to_decimal() { let value = parse_hex_or_decimal("0xa0xx0d"); assert_eq!(value, None); } #[cfg(target_os = "linux")] #[test] fn completions() { let mut clap = Options::command(); for (shell, file) in &[ (Shell::Bash, "alacritty.bash"), (Shell::Fish, "alacritty.fish"), (Shell::Zsh, "_alacritty"), ] { let mut generated = Vec::new(); clap_complete::generate(*shell, &mut clap, "alacritty", &mut generated); let generated = String::from_utf8_lossy(&generated); let mut completion = String::new(); let mut file = File::open(format!("../extra/completions/{file}")).unwrap(); file.read_to_string(&mut completion).unwrap(); assert_eq!(generated, completion); } // NOTE: Use this to generate new completions. // // let mut file = File::create("../extra/completions/alacritty.bash").unwrap(); // clap_complete::generate(Shell::Bash, &mut clap, "alacritty", &mut file); // let mut file = File::create("../extra/completions/alacritty.fish").unwrap(); // clap_complete::generate(Shell::Fish, &mut clap, "alacritty", &mut file); // let mut file = File::create("../extra/completions/_alacritty").unwrap(); // clap_complete::generate(Shell::Zsh, &mut clap, "alacritty", &mut file); } }
rust
Apache-2.0
6ee6e53ee3457c24137f117237b0ff1d84f6f836
2026-01-04T15:31:58.707223Z
false
alacritty/alacritty
https://github.com/alacritty/alacritty/blob/6ee6e53ee3457c24137f117237b0ff1d84f6f836/alacritty/src/panic.rs
alacritty/src/panic.rs
use std::io::Write; use std::{io, panic, ptr}; use windows_sys::Win32::UI::WindowsAndMessaging::{ MB_ICONERROR, MB_OK, MB_SETFOREGROUND, MB_TASKMODAL, MessageBoxW, }; use alacritty_terminal::tty::windows::win32_string; // Install a panic handler that renders the panic in a classical Windows error // dialog box as well as writes the panic to STDERR. pub fn attach_handler() { panic::set_hook(Box::new(|panic_info| { let _ = writeln!(io::stderr(), "{}", panic_info); let msg = format!("{}\n\nPress Ctrl-C to Copy", panic_info); unsafe { MessageBoxW( ptr::null_mut(), win32_string(&msg).as_ptr(), win32_string("Alacritty: Runtime Error").as_ptr(), MB_ICONERROR | MB_OK | MB_SETFOREGROUND | MB_TASKMODAL, ); } })); }
rust
Apache-2.0
6ee6e53ee3457c24137f117237b0ff1d84f6f836
2026-01-04T15:31:58.707223Z
false
alacritty/alacritty
https://github.com/alacritty/alacritty/blob/6ee6e53ee3457c24137f117237b0ff1d84f6f836/alacritty/src/main.rs
alacritty/src/main.rs
//! Alacritty - The GPU Enhanced Terminal. #![warn(rust_2018_idioms, future_incompatible)] #![deny(clippy::all, clippy::if_not_else, clippy::enum_glob_use)] #![cfg_attr(clippy, deny(warnings))] // With the default subsystem, 'console', windows creates an additional console // window for the program. // This is silently ignored on non-windows systems. // See https://msdn.microsoft.com/en-us/library/4cc7ya5b.aspx for more details. #![windows_subsystem = "windows"] #[cfg(not(any(feature = "x11", feature = "wayland", target_os = "macos", windows)))] compile_error!(r#"at least one of the "x11"/"wayland" features must be enabled"#); use std::error::Error; use std::fmt::Write as _; use std::io::{self, Write}; use std::path::PathBuf; use std::{env, fs}; use log::info; #[cfg(windows)] use windows_sys::Win32::System::Console::{ATTACH_PARENT_PROCESS, AttachConsole, FreeConsole}; use winit::event_loop::EventLoop; #[cfg(all(feature = "x11", not(any(target_os = "macos", windows))))] use winit::raw_window_handle::{HasDisplayHandle, RawDisplayHandle}; use alacritty_terminal::tty; mod cli; mod clipboard; mod config; mod daemon; mod display; mod event; mod input; #[cfg(unix)] mod ipc; mod logging; #[cfg(target_os = "macos")] mod macos; mod message_bar; mod migrate; #[cfg(windows)] mod panic; mod renderer; mod scheduler; mod string; mod window_context; mod gl { #![allow(clippy::all, unsafe_op_in_unsafe_fn)] include!(concat!(env!("OUT_DIR"), "/gl_bindings.rs")); } #[cfg(unix)] use crate::cli::MessageOptions; #[cfg(not(any(target_os = "macos", windows)))] use crate::cli::SocketMessage; use crate::cli::{Options, Subcommands}; use crate::config::UiConfig; use crate::config::monitor::ConfigMonitor; use crate::event::{Event, Processor}; #[cfg(target_os = "macos")] use crate::macos::locale; fn main() -> Result<(), Box<dyn Error>> { #[cfg(windows)] panic::attach_handler(); // When linked with the windows subsystem windows won't automatically attach // to the console of the parent process, so we do it explicitly. This fails // silently if the parent has no console. #[cfg(windows)] unsafe { AttachConsole(ATTACH_PARENT_PROCESS); } // Load command line options. let options = Options::new(); match options.subcommands { #[cfg(unix)] Some(Subcommands::Msg(options)) => msg(options)?, Some(Subcommands::Migrate(options)) => migrate::migrate(options), None => alacritty(options)?, } Ok(()) } /// `msg` subcommand entrypoint. #[cfg(unix)] #[allow(unused_mut)] fn msg(mut options: MessageOptions) -> Result<(), Box<dyn Error>> { #[cfg(not(any(target_os = "macos", windows)))] if let SocketMessage::CreateWindow(window_options) = &mut options.message { window_options.activation_token = env::var("XDG_ACTIVATION_TOKEN").or_else(|_| env::var("DESKTOP_STARTUP_ID")).ok(); } ipc::send_message(options.socket, options.message).map_err(|err| err.into()) } /// Temporary files stored for Alacritty. /// /// This stores temporary files to automate their destruction through its `Drop` implementation. struct TemporaryFiles { #[cfg(unix)] socket_path: Option<PathBuf>, log_file: Option<PathBuf>, } impl Drop for TemporaryFiles { fn drop(&mut self) { // Clean up the IPC socket file. #[cfg(unix)] if let Some(socket_path) = &self.socket_path { let _ = fs::remove_file(socket_path); } // Clean up logfile. if let Some(log_file) = &self.log_file { if fs::remove_file(log_file).is_ok() { let _ = writeln!(io::stdout(), "Deleted log file at \"{}\"", log_file.display()); } } } } /// Run main Alacritty entrypoint. /// /// Creates a window, the terminal state, PTY, I/O event loop, input processor, /// config change monitor, and runs the main display loop. fn alacritty(mut options: Options) -> Result<(), Box<dyn Error>> { // Setup winit event loop. let window_event_loop = EventLoop::<Event>::with_user_event().build()?; // Initialize the logger as soon as possible as to capture output from other subsystems. let log_file = logging::initialize(&options, window_event_loop.create_proxy()) .expect("Unable to initialize logger"); info!("Welcome to Alacritty"); info!("Version {}", env!("VERSION")); #[cfg(all(feature = "x11", not(any(target_os = "macos", windows))))] info!( "Running on {}", if matches!( window_event_loop.display_handle().unwrap().as_raw(), RawDisplayHandle::Wayland(_) ) { "Wayland" } else { "X11" } ); #[cfg(not(any(feature = "x11", target_os = "macos", windows)))] info!("Running on Wayland"); // Load configuration file. let config = config::load(&mut options); log_config_path(&config); // Update the log level from config. log::set_max_level(config.debug.log_level); // Set tty environment variables. tty::setup_env(); // Set env vars from config. for (key, value) in config.env.iter() { unsafe { env::set_var(key, value) }; } // Switch to home directory. #[cfg(target_os = "macos")] env::set_current_dir(home::home_dir().unwrap()).unwrap(); // Set macOS locale. #[cfg(target_os = "macos")] locale::set_locale_environment(); #[cfg(target_os = "macos")] macos::disable_autofill(); // Create the IPC socket listener. #[cfg(unix)] let socket_path = if config.ipc_socket() { match ipc::spawn_ipc_socket(&options, window_event_loop.create_proxy()) { Ok(path) => Some(path), Err(err) if options.daemon => return Err(err.into()), Err(err) => { log::warn!("Unable to create socket: {err:?}"); None }, } } else { None }; // Setup automatic RAII cleanup for our files. let log_cleanup = log_file.filter(|_| !config.debug.persistent_logging); let _files = TemporaryFiles { #[cfg(unix)] socket_path, log_file: log_cleanup, }; // Event processor. let mut processor = Processor::new(config, options, &window_event_loop); // Start event loop and block until shutdown. let result = processor.run(window_event_loop); // `Processor` must be dropped before calling `FreeConsole`. // // This is needed for ConPTY backend. Otherwise a deadlock can occur. // The cause: // - Drop for ConPTY will deadlock if the conout pipe has already been dropped // - ConPTY is dropped when the last of processor and window context are dropped, because both // of them own an Arc<ConPTY> // // The fix is to ensure that processor is dropped first. That way, when window context (i.e. // PTY) is dropped, it can ensure ConPTY is dropped before the conout pipe in the PTY drop // order. // // FIXME: Change PTY API to enforce the correct drop order with the typesystem. // Terminate the config monitor. if let Some(config_monitor) = processor.config_monitor.take() { config_monitor.shutdown(); } // Without explicitly detaching the console cmd won't redraw it's prompt. #[cfg(windows)] unsafe { FreeConsole(); } info!("Goodbye"); result } fn log_config_path(config: &UiConfig) { if config.config_paths.is_empty() { return; } let mut msg = String::from("Configuration files loaded from:"); for path in &config.config_paths { let _ = write!(msg, "\n {:?}", path.display()); } info!("{msg}"); }
rust
Apache-2.0
6ee6e53ee3457c24137f117237b0ff1d84f6f836
2026-01-04T15:31:58.707223Z
false
alacritty/alacritty
https://github.com/alacritty/alacritty/blob/6ee6e53ee3457c24137f117237b0ff1d84f6f836/alacritty/src/logging.rs
alacritty/src/logging.rs
//! Logging for Alacritty. //! //! The main executable is supposed to call `initialize()` exactly once during //! startup. All logging messages are written to stdout, given that their //! log-level is sufficient for the level configured in `cli::Options`. use std::fs::{File, OpenOptions}; use std::io::{self, LineWriter, Stdout, Write}; use std::path::PathBuf; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, OnceLock}; use std::time::Instant; use std::{env, process}; use log::{Level, LevelFilter}; use winit::event_loop::EventLoopProxy; use crate::cli::Options; use crate::event::{Event, EventType}; use crate::message_bar::{Message, MessageType}; /// Logging target for IPC config error messages. pub const LOG_TARGET_IPC_CONFIG: &str = "alacritty_log_window_config"; /// Name for the environment variable containing the log file's path. const ALACRITTY_LOG_ENV: &str = "ALACRITTY_LOG"; /// Logging target for config error messages. pub const LOG_TARGET_CONFIG: &str = "alacritty_config_derive"; /// Logging target for winit events. pub const LOG_TARGET_WINIT: &str = "alacritty_winit_event"; /// Name for the environment variable containing extra logging targets. /// /// The targets are semicolon separated. const ALACRITTY_EXTRA_LOG_TARGETS_ENV: &str = "ALACRITTY_EXTRA_LOG_TARGETS"; /// User configurable extra log targets to include. fn extra_log_targets() -> &'static [String] { static EXTRA_LOG_TARGETS: OnceLock<Vec<String>> = OnceLock::new(); EXTRA_LOG_TARGETS.get_or_init(|| { env::var(ALACRITTY_EXTRA_LOG_TARGETS_ENV) .map_or(Vec::new(), |targets| targets.split(';').map(ToString::to_string).collect()) }) } /// List of targets which will be logged by Alacritty. const ALLOWED_TARGETS: &[&str] = &[ LOG_TARGET_IPC_CONFIG, LOG_TARGET_CONFIG, LOG_TARGET_WINIT, "alacritty_config_derive", "alacritty_terminal", "alacritty", "crossfont", ]; /// Initialize the logger to its defaults. pub fn initialize( options: &Options, event_proxy: EventLoopProxy<Event>, ) -> Result<Option<PathBuf>, log::SetLoggerError> { log::set_max_level(options.log_level()); let logger = Logger::new(event_proxy); let path = logger.file_path(); log::set_boxed_logger(Box::new(logger))?; Ok(path) } pub struct Logger { logfile: Mutex<OnDemandLogFile>, stdout: Mutex<LineWriter<Stdout>>, event_proxy: Mutex<EventLoopProxy<Event>>, start: Instant, } impl Logger { fn new(event_proxy: EventLoopProxy<Event>) -> Self { let logfile = Mutex::new(OnDemandLogFile::new()); let stdout = Mutex::new(LineWriter::new(io::stdout())); Logger { logfile, stdout, event_proxy: Mutex::new(event_proxy), start: Instant::now() } } fn file_path(&self) -> Option<PathBuf> { let logfile_lock = self.logfile.lock().ok()?; Some(logfile_lock.path().clone()) } /// Log a record to the message bar. fn message_bar_log(&self, record: &log::Record<'_>, logfile_path: &str) { let message_type = match record.level() { Level::Error => MessageType::Error, Level::Warn => MessageType::Warning, _ => return, }; let event_proxy = match self.event_proxy.lock() { Ok(event_proxy) => event_proxy, Err(_) => return, }; #[cfg(not(windows))] let env_var = format!("${ALACRITTY_LOG_ENV}"); #[cfg(windows)] let env_var = format!("%{}%", ALACRITTY_LOG_ENV); let message = format!( "[{}] {}\nSee log at {} ({})", record.level(), record.args(), logfile_path, env_var, ); let mut message = Message::new(message, message_type); message.set_target(record.target().to_owned()); let _ = event_proxy.send_event(Event::new(EventType::Message(message), None)); } } impl log::Log for Logger { fn enabled(&self, metadata: &log::Metadata<'_>) -> bool { metadata.level() <= log::max_level() } fn log(&self, record: &log::Record<'_>) { // Get target crate. let index = record.target().find(':').unwrap_or_else(|| record.target().len()); let target = &record.target()[..index]; // Only log our own crates, except when logging at Level::Trace. if !self.enabled(record.metadata()) || !is_allowed_target(record.level(), target) { return; } // Create log message for the given `record` and `target`. let message = create_log_message(record, target, self.start); if let Ok(mut logfile) = self.logfile.lock() { // Write to logfile. let _ = logfile.write_all(message.as_ref()); // Log relevant entries to message bar. self.message_bar_log(record, &logfile.path.to_string_lossy()); } // Write to stdout. if let Ok(mut stdout) = self.stdout.lock() { let _ = stdout.write_all(message.as_ref()); } } fn flush(&self) {} } fn create_log_message(record: &log::Record<'_>, target: &str, start: Instant) -> String { let runtime = start.elapsed(); let secs = runtime.as_secs(); let nanos = runtime.subsec_nanos(); let mut message = format!("[{}.{:0>9}s] [{:<5}] [{}] ", secs, nanos, record.level(), target); // Alignment for the lines after the first new line character in the payload. We don't deal // with fullwidth/unicode chars here, so just `message.len()` is sufficient. let alignment = message.len(); // Push lines with added extra padding on the next line, which is trimmed later. let lines = record.args().to_string(); for line in lines.split('\n') { let line = format!("{}\n{:width$}", line, "", width = alignment); message.push_str(&line); } // Drop extra trailing alignment. message.truncate(message.len() - alignment); message } /// Check if log messages from a crate should be logged. fn is_allowed_target(level: Level, target: &str) -> bool { match (level, log::max_level()) { (Level::Error, LevelFilter::Trace) | (Level::Warn, LevelFilter::Trace) => true, _ => ALLOWED_TARGETS.contains(&target) || extra_log_targets().iter().any(|t| t == target), } } struct OnDemandLogFile { file: Option<LineWriter<File>>, created: Arc<AtomicBool>, path: PathBuf, } impl OnDemandLogFile { fn new() -> Self { let mut path = env::temp_dir(); path.push(format!("Alacritty-{}.log", process::id())); // Set log path as an environment variable. unsafe { env::set_var(ALACRITTY_LOG_ENV, path.as_os_str()) }; OnDemandLogFile { path, file: None, created: Arc::new(AtomicBool::new(false)) } } fn file(&mut self) -> Result<&mut LineWriter<File>, io::Error> { // Allow to recreate the file if it has been deleted at runtime. if self.file.is_some() && !self.path.as_path().exists() { self.file = None; } // Create the file if it doesn't exist yet. if self.file.is_none() { let file = OpenOptions::new().append(true).create_new(true).open(&self.path); match file { Ok(file) => { self.file = Some(io::LineWriter::new(file)); self.created.store(true, Ordering::Relaxed); let _ = writeln!(io::stdout(), "Created log file at \"{}\"", self.path.display()); }, Err(e) => { let _ = writeln!(io::stdout(), "Unable to create log file: {e}"); return Err(e); }, } } Ok(self.file.as_mut().unwrap()) } fn path(&self) -> &PathBuf { &self.path } } impl Write for OnDemandLogFile { fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> { self.file()?.write(buf) } fn flush(&mut self) -> Result<(), io::Error> { self.file()?.flush() } }
rust
Apache-2.0
6ee6e53ee3457c24137f117237b0ff1d84f6f836
2026-01-04T15:31:58.707223Z
false
alacritty/alacritty
https://github.com/alacritty/alacritty/blob/6ee6e53ee3457c24137f117237b0ff1d84f6f836/alacritty/src/daemon.rs
alacritty/src/daemon.rs
#[cfg(target_os = "openbsd")] use std::ffi::CStr; #[cfg(not(windows))] use std::ffi::CString; use std::ffi::OsStr; #[cfg(not(any(target_os = "macos", target_os = "openbsd", windows)))] use std::fs; use std::io; #[cfg(not(windows))] use std::os::unix::ffi::OsStringExt; #[cfg(windows)] use std::os::windows::process::CommandExt; use std::process::{Command, Stdio}; #[cfg(target_os = "openbsd")] use std::ptr; #[rustfmt::skip] #[cfg(not(windows))] use { std::error::Error, std::os::unix::process::CommandExt, std::os::unix::io::RawFd, std::path::PathBuf, }; #[cfg(not(windows))] use libc::pid_t; #[cfg(windows)] use windows_sys::Win32::System::Threading::{CREATE_NEW_PROCESS_GROUP, CREATE_NO_WINDOW}; #[cfg(target_os = "macos")] use crate::macos; /// Start a new process in the background. #[cfg(windows)] pub fn spawn_daemon<I, S>(program: &str, args: I) -> io::Result<()> where I: IntoIterator<Item = S> + Copy, S: AsRef<OsStr>, { // Setting all the I/O handles to null and setting the // CREATE_NEW_PROCESS_GROUP and CREATE_NO_WINDOW has the effect // that console applications will run without opening a new // console window. Command::new(program) .args(args) .stdin(Stdio::null()) .stdout(Stdio::null()) .stderr(Stdio::null()) .creation_flags(CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW) .spawn() .map(|_| ()) } /// Start a new process in the background. #[cfg(not(windows))] pub fn spawn_daemon<I, S>( program: &str, args: I, master_fd: RawFd, shell_pid: u32, ) -> io::Result<()> where I: IntoIterator<Item = S> + Copy, S: AsRef<OsStr>, { let mut command = Command::new(program); command.args(args).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()); let working_directory = foreground_process_path(master_fd, shell_pid) .ok() .and_then(|path| CString::new(path.into_os_string().into_vec()).ok()); unsafe { command .pre_exec(move || { // POSIX.1-2017 describes `fork` as async-signal-safe with the following note: // // > While the fork() function is async-signal-safe, there is no way for // > an implementation to determine whether the fork handlers established by // > pthread_atfork() are async-signal-safe. [...] It is therefore undefined for the // > fork handlers to execute functions that are not async-signal-safe when fork() // > is called from a signal handler. // // POSIX.1-2024 removes this guarantee and introduces an async-signal-safe // replacement `_Fork`, which we'd like to use, but macOS doesn't support it yet. // // Since we aren't registering any fork handlers, and hopefully the OS doesn't // either, we're fine on systems compatible with POSIX.1-2017, which should be // enough for a long while. If this ever becomes a problem in the future, we should // be able to switch to `_Fork`. match libc::fork() { -1 => return Err(io::Error::last_os_error()), 0 => (), _ => libc::_exit(0), } // Copy foreground process' working directory, ignoring invalid paths. if let Some(working_directory) = working_directory.as_ref() { libc::chdir(working_directory.as_ptr()); } if libc::setsid() == -1 { return Err(io::Error::last_os_error()); } Ok(()) }) .spawn()? .wait() .map(|_| ()) } } /// Get working directory of controlling process. #[cfg(not(any(windows, target_os = "openbsd")))] pub fn foreground_process_path( master_fd: RawFd, shell_pid: u32, ) -> Result<PathBuf, Box<dyn Error>> { let mut pid = unsafe { libc::tcgetpgrp(master_fd) }; if pid < 0 { pid = shell_pid as pid_t; } #[cfg(not(any(target_os = "macos", target_os = "freebsd")))] let link_path = format!("/proc/{pid}/cwd"); #[cfg(target_os = "freebsd")] let link_path = format!("/compat/linux/proc/{}/cwd", pid); #[cfg(not(target_os = "macos"))] let cwd = fs::read_link(link_path)?; #[cfg(target_os = "macos")] let cwd = macos::proc::cwd(pid)?; Ok(cwd) } #[cfg(target_os = "openbsd")] pub fn foreground_process_path( master_fd: RawFd, shell_pid: u32, ) -> Result<PathBuf, Box<dyn Error>> { let mut pid = unsafe { libc::tcgetpgrp(master_fd) }; if pid < 0 { pid = shell_pid as pid_t; } let name = [libc::CTL_KERN, libc::KERN_PROC_CWD, pid]; let mut buf = [0u8; libc::PATH_MAX as usize]; let result = unsafe { libc::sysctl( name.as_ptr(), name.len().try_into().unwrap(), buf.as_mut_ptr() as *mut _, &mut buf.len() as *mut _, ptr::null_mut(), 0, ) }; if result != 0 { Err(io::Error::last_os_error().into()) } else { let foreground_path = unsafe { CStr::from_ptr(buf.as_ptr().cast()) }.to_str()?; Ok(PathBuf::from(foreground_path)) } }
rust
Apache-2.0
6ee6e53ee3457c24137f117237b0ff1d84f6f836
2026-01-04T15:31:58.707223Z
false
alacritty/alacritty
https://github.com/alacritty/alacritty/blob/6ee6e53ee3457c24137f117237b0ff1d84f6f836/alacritty/src/scheduler.rs
alacritty/src/scheduler.rs
//! Scheduler for emitting events at a specific time in the future. use std::collections::VecDeque; use std::time::{Duration, Instant}; use winit::event_loop::EventLoopProxy; use winit::window::WindowId; use crate::event::Event; /// ID uniquely identifying a timer. #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct TimerId { topic: Topic, window_id: WindowId, } impl TimerId { pub fn new(topic: Topic, window_id: WindowId) -> Self { Self { topic, window_id } } } /// Available timer topics. #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum Topic { SelectionScrolling, DelayedSearch, BlinkCursor, BlinkTimeout, Frame, } /// Event scheduled to be emitted at a specific time. pub struct Timer { pub deadline: Instant, pub event: Event, pub id: TimerId, interval: Option<Duration>, } /// Scheduler tracking all pending timers. pub struct Scheduler { timers: VecDeque<Timer>, event_proxy: EventLoopProxy<Event>, } impl Scheduler { pub fn new(event_proxy: EventLoopProxy<Event>) -> Self { Self { timers: VecDeque::new(), event_proxy } } /// Process all pending timers. /// /// If there are still timers pending after all ready events have been processed, the closest /// pending deadline will be returned. pub fn update(&mut self) -> Option<Instant> { let now = Instant::now(); while !self.timers.is_empty() && self.timers[0].deadline <= now { if let Some(timer) = self.timers.pop_front() { // Automatically repeat the event. if let Some(interval) = timer.interval { self.schedule(timer.event.clone(), interval, true, timer.id); } let _ = self.event_proxy.send_event(timer.event); } } self.timers.front().map(|timer| timer.deadline) } /// Schedule a new event. pub fn schedule(&mut self, event: Event, interval: Duration, repeat: bool, timer_id: TimerId) { let deadline = Instant::now() + interval; // Get insert position in the schedule. let index = self .timers .iter() .position(|timer| timer.deadline > deadline) .unwrap_or(self.timers.len()); // Set the automatic event repeat rate. let interval = if repeat { Some(interval) } else { None }; self.timers.insert(index, Timer { interval, deadline, event, id: timer_id }); } /// Cancel a scheduled event. pub fn unschedule(&mut self, id: TimerId) -> Option<Timer> { let index = self.timers.iter().position(|timer| timer.id == id)?; self.timers.remove(index) } /// Check if a timer is already scheduled. pub fn scheduled(&mut self, id: TimerId) -> bool { self.timers.iter().any(|timer| timer.id == id) } /// Remove all timers scheduled for a window. /// /// This must be called when a window is removed to ensure that timers on intervals do not /// stick around forever and cause a memory leak. pub fn unschedule_window(&mut self, window_id: WindowId) { self.timers.retain(|timer| timer.id.window_id != window_id); } }
rust
Apache-2.0
6ee6e53ee3457c24137f117237b0ff1d84f6f836
2026-01-04T15:31:58.707223Z
false
alacritty/alacritty
https://github.com/alacritty/alacritty/blob/6ee6e53ee3457c24137f117237b0ff1d84f6f836/alacritty/src/ipc.rs
alacritty/src/ipc.rs
//! Alacritty socket IPC. use serde::{Deserialize, Serialize}; use std::ffi::OsStr; use std::io::{BufRead, BufReader, Error as IoError, ErrorKind, Result as IoResult, Write}; use std::net::Shutdown; use std::os::unix::net::{UnixListener, UnixStream}; use std::path::PathBuf; use std::sync::Arc; use std::{env, fs, process}; use log::{error, warn}; use std::result::Result; use winit::event_loop::EventLoopProxy; use winit::window::WindowId; use alacritty_terminal::thread; use crate::cli::{Options, SocketMessage}; use crate::event::{Event, EventType}; /// Environment variable name for the IPC socket path. const ALACRITTY_SOCKET_ENV: &str = "ALACRITTY_SOCKET"; /// Create an IPC socket. pub fn spawn_ipc_socket( options: &Options, event_proxy: EventLoopProxy<Event>, ) -> IoResult<PathBuf> { // Create the IPC socket and export its path as env. let socket_path = options.socket.clone().unwrap_or_else(|| { let mut path = socket_dir(); path.push(format!("{}-{}.sock", socket_prefix(), process::id())); path }); let listener = UnixListener::bind(&socket_path)?; unsafe { env::set_var(ALACRITTY_SOCKET_ENV, socket_path.as_os_str()) }; if options.daemon { println!("ALACRITTY_SOCKET={}; export ALACRITTY_SOCKET", socket_path.display()); } // Spawn a thread to listen on the IPC socket. thread::spawn_named("socket listener", move || { let mut data = String::new(); for stream in listener.incoming().filter_map(Result::ok) { data.clear(); let mut reader = BufReader::new(&stream); match reader.read_line(&mut data) { Ok(0) | Err(_) => continue, Ok(_) => (), }; // Read pending events on socket. let message: SocketMessage = match serde_json::from_str(&data) { Ok(message) => message, Err(err) => { warn!("Failed to convert data from socket: {err}"); continue; }, }; // Handle IPC events. match message { SocketMessage::CreateWindow(options) => { let event = Event::new(EventType::CreateWindow(options), None); let _ = event_proxy.send_event(event); }, SocketMessage::Config(ipc_config) => { let window_id = ipc_config .window_id .and_then(|id| u64::try_from(id).ok()) .map(WindowId::from); let event = Event::new(EventType::IpcConfig(ipc_config), window_id); let _ = event_proxy.send_event(event); }, SocketMessage::GetConfig(config) => { let window_id = config.window_id.and_then(|id| u64::try_from(id).ok()).map(WindowId::from); let event = Event::new(EventType::IpcGetConfig(Arc::new(stream)), window_id); let _ = event_proxy.send_event(event); }, } } }); Ok(socket_path) } /// Send a message to the active Alacritty socket. pub fn send_message(socket: Option<PathBuf>, message: SocketMessage) -> IoResult<()> { let mut socket = find_socket(socket)?; // Write message to socket. let message_json = serde_json::to_string(&message)?; socket.write_all(message_json.as_bytes())?; let _ = socket.flush(); // Shutdown write end, to allow reading. socket.shutdown(Shutdown::Write)?; // Get matching IPC reply. handle_reply(&socket, &message)?; Ok(()) } /// Process IPC responses. fn handle_reply(stream: &UnixStream, message: &SocketMessage) -> IoResult<()> { // Read reply, returning early if there is none. let mut buffer = String::new(); let mut reader = BufReader::new(stream); if let Ok(0) | Err(_) = reader.read_line(&mut buffer) { return Ok(()); } // Parse IPC reply. let reply: SocketReply = serde_json::from_str(&buffer) .map_err(|err| IoError::other(format!("Invalid IPC format: {err}")))?; // Ensure reply matches request. match (message, &reply) { // Write requested config to STDOUT. (SocketMessage::GetConfig(..), SocketReply::GetConfig(config)) => { println!("{config}"); Ok(()) }, // Ignore requests without reply. _ => Ok(()), } } /// Send IPC message reply. pub fn send_reply(stream: &mut UnixStream, message: SocketReply) { if let Err(err) = send_reply_fallible(stream, message) { error!("Failed to send IPC reply: {err}"); } } /// Send IPC message reply, returning possible errors. fn send_reply_fallible(stream: &mut UnixStream, message: SocketReply) -> IoResult<()> { let json = serde_json::to_string(&message).map_err(IoError::other)?; stream.write_all(json.as_bytes())?; stream.flush()?; Ok(()) } /// Directory for the IPC socket file. #[cfg(not(target_os = "macos"))] fn socket_dir() -> PathBuf { xdg::BaseDirectories::with_prefix("alacritty") .get_runtime_directory() .map(ToOwned::to_owned) .ok() .and_then(|path| fs::create_dir_all(&path).map(|_| path).ok()) .unwrap_or_else(env::temp_dir) } /// Directory for the IPC socket file. #[cfg(target_os = "macos")] fn socket_dir() -> PathBuf { env::temp_dir() } /// Find the IPC socket path. fn find_socket(socket_path: Option<PathBuf>) -> IoResult<UnixStream> { // Handle --socket CLI override. if let Some(socket_path) = socket_path { // Ensure we inform the user about an invalid path. return UnixStream::connect(&socket_path).map_err(|err| { let message = format!("invalid socket path {socket_path:?}"); IoError::new(err.kind(), message) }); } // Handle environment variable. if let Ok(path) = env::var(ALACRITTY_SOCKET_ENV) { let socket_path = PathBuf::from(path); if let Ok(socket) = UnixStream::connect(socket_path) { return Ok(socket); } } // Search for sockets files. for entry in fs::read_dir(socket_dir())?.filter_map(|entry| entry.ok()) { let path = entry.path(); // Skip files that aren't Alacritty sockets. let socket_prefix = socket_prefix(); if path .file_name() .and_then(OsStr::to_str) .filter(|file| file.starts_with(&socket_prefix) && file.ends_with(".sock")) .is_none() { continue; } // Attempt to connect to the socket. match UnixStream::connect(&path) { Ok(socket) => return Ok(socket), // Delete orphan sockets. Err(error) if error.kind() == ErrorKind::ConnectionRefused => { let _ = fs::remove_file(&path); }, // Ignore other errors like permission issues. Err(_) => (), } } Err(IoError::new(ErrorKind::NotFound, "no socket found")) } /// File prefix matching all available sockets. /// /// This prefix will include display server information to allow for environments with multiple /// display servers running for the same user. #[cfg(not(target_os = "macos"))] fn socket_prefix() -> String { let display = env::var("WAYLAND_DISPLAY").or_else(|_| env::var("DISPLAY")).unwrap_or_default(); format!("Alacritty-{}", display.replace('/', "-")) } /// File prefix matching all available sockets. #[cfg(target_os = "macos")] fn socket_prefix() -> String { String::from("Alacritty") } /// IPC socket replies. #[derive(Serialize, Deserialize, Debug)] pub enum SocketReply { GetConfig(String), }
rust
Apache-2.0
6ee6e53ee3457c24137f117237b0ff1d84f6f836
2026-01-04T15:31:58.707223Z
false
alacritty/alacritty
https://github.com/alacritty/alacritty/blob/6ee6e53ee3457c24137f117237b0ff1d84f6f836/alacritty/src/renderer/rects.rs
alacritty/src/renderer/rects.rs
use std::collections::HashMap; use std::mem; use ahash::RandomState; use crossfont::Metrics; use log::info; use alacritty_terminal::grid::Dimensions; use alacritty_terminal::index::{Column, Point}; use alacritty_terminal::term::cell::Flags; use crate::display::SizeInfo; use crate::display::color::Rgb; use crate::display::content::RenderableCell; use crate::gl::types::*; use crate::renderer::shader::{ShaderError, ShaderProgram, ShaderVersion}; use crate::{gl, renderer}; #[derive(Debug, Copy, Clone)] pub struct RenderRect { pub x: f32, pub y: f32, pub width: f32, pub height: f32, pub color: Rgb, pub alpha: f32, pub kind: RectKind, } impl RenderRect { pub fn new(x: f32, y: f32, width: f32, height: f32, color: Rgb, alpha: f32) -> Self { RenderRect { kind: RectKind::Normal, x, y, width, height, color, alpha } } } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct RenderLine { pub start: Point<usize>, pub end: Point<usize>, pub color: Rgb, } // NOTE: These flags must be in sync with their usage in the rect.*.glsl shaders. #[repr(u8)] #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum RectKind { Normal = 0, Undercurl = 1, DottedUnderline = 2, DashedUnderline = 3, NumKinds = 4, } impl RenderLine { pub fn rects(&self, flag: Flags, metrics: &Metrics, size: &SizeInfo) -> Vec<RenderRect> { let mut rects = Vec::new(); let mut start = self.start; while start.line < self.end.line { let end = Point::new(start.line, size.last_column()); Self::push_rects(&mut rects, metrics, size, flag, start, end, self.color); start = Point::new(start.line + 1, Column(0)); } Self::push_rects(&mut rects, metrics, size, flag, start, self.end, self.color); rects } /// Push all rects required to draw the cell's line. fn push_rects( rects: &mut Vec<RenderRect>, metrics: &Metrics, size: &SizeInfo, flag: Flags, start: Point<usize>, end: Point<usize>, color: Rgb, ) { let (position, thickness, ty) = match flag { Flags::DOUBLE_UNDERLINE => { // Position underlines so each one has 50% of descent available. let top_pos = 0.25 * metrics.descent; let bottom_pos = 0.75 * metrics.descent; rects.push(Self::create_rect( size, metrics.descent, start, end, top_pos, metrics.underline_thickness, color, )); (bottom_pos, metrics.underline_thickness, RectKind::Normal) }, // Make undercurl occupy the entire descent area. Flags::UNDERCURL => (metrics.descent, metrics.descent.abs(), RectKind::Undercurl), Flags::UNDERLINE => { (metrics.underline_position, metrics.underline_thickness, RectKind::Normal) }, // Make dotted occupy the entire descent area. Flags::DOTTED_UNDERLINE => { (metrics.descent, metrics.descent.abs(), RectKind::DottedUnderline) }, Flags::DASHED_UNDERLINE => { (metrics.underline_position, metrics.underline_thickness, RectKind::DashedUnderline) }, Flags::STRIKEOUT => { (metrics.strikeout_position, metrics.strikeout_thickness, RectKind::Normal) }, _ => unimplemented!("Invalid flag for cell line drawing specified"), }; let mut rect = Self::create_rect(size, metrics.descent, start, end, position, thickness, color); rect.kind = ty; rects.push(rect); } /// Create a line's rect at a position relative to the baseline. fn create_rect( size: &SizeInfo, descent: f32, start: Point<usize>, end: Point<usize>, position: f32, mut thickness: f32, color: Rgb, ) -> RenderRect { let start_x = start.column.0 as f32 * size.cell_width(); let end_x = (end.column.0 + 1) as f32 * size.cell_width(); let width = end_x - start_x; // Make sure lines are always visible. thickness = thickness.max(1.); let line_bottom = (start.line as f32 + 1.) * size.cell_height(); let baseline = line_bottom + descent; let mut y = (baseline - position - thickness / 2.).round(); let max_y = line_bottom - thickness; if y > max_y { y = max_y; } RenderRect::new( start_x + size.padding_x(), y + size.padding_y(), width, thickness, color, 1., ) } } /// Lines for underline and strikeout. #[derive(Default)] pub struct RenderLines { inner: HashMap<Flags, Vec<RenderLine>, RandomState>, } impl RenderLines { #[inline] pub fn new() -> Self { Self::default() } #[inline] pub fn rects(&self, metrics: &Metrics, size: &SizeInfo) -> Vec<RenderRect> { self.inner .iter() .flat_map(|(flag, lines)| { lines.iter().flat_map(move |line| line.rects(*flag, metrics, size)) }) .collect() } /// Update the stored lines with the next cell info. #[inline] pub fn update(&mut self, cell: &RenderableCell) { self.update_flag(cell, Flags::UNDERLINE); self.update_flag(cell, Flags::DOUBLE_UNDERLINE); self.update_flag(cell, Flags::STRIKEOUT); self.update_flag(cell, Flags::UNDERCURL); self.update_flag(cell, Flags::DOTTED_UNDERLINE); self.update_flag(cell, Flags::DASHED_UNDERLINE); } /// Update the lines for a specific flag. fn update_flag(&mut self, cell: &RenderableCell, flag: Flags) { if !cell.flags.contains(flag) { return; } // The underline color escape does not apply to strikeout. let color = if flag.contains(Flags::STRIKEOUT) { cell.fg } else { cell.underline }; // Include wide char spacer if the current cell is a wide char. let mut end = cell.point; if cell.flags.contains(Flags::WIDE_CHAR) { end.column += 1; } // Check if there's an active line. if let Some(line) = self.inner.get_mut(&flag).and_then(|lines| lines.last_mut()) { if color == line.color && cell.point.column == line.end.column + 1 && cell.point.line == line.end.line { // Update the length of the line. line.end = end; return; } } // Start new line if there currently is none. let line = RenderLine { start: cell.point, end, color }; match self.inner.get_mut(&flag) { Some(lines) => lines.push(line), None => { self.inner.insert(flag, vec![line]); }, } } } /// Shader sources for rect rendering program. const RECT_SHADER_F: &str = include_str!("../../res/rect.f.glsl"); const RECT_SHADER_V: &str = include_str!("../../res/rect.v.glsl"); #[repr(C)] #[derive(Debug, Clone, Copy)] struct Vertex { // Normalized screen coordinates. x: f32, y: f32, // Color. r: u8, g: u8, b: u8, a: u8, } #[derive(Debug)] pub struct RectRenderer { // GL buffer objects. vao: GLuint, vbo: GLuint, programs: [RectShaderProgram; 4], vertices: [Vec<Vertex>; 4], } impl RectRenderer { pub fn new(shader_version: ShaderVersion) -> Result<Self, renderer::Error> { let mut vao: GLuint = 0; let mut vbo: GLuint = 0; let rect_program = RectShaderProgram::new(shader_version, RectKind::Normal)?; let undercurl_program = RectShaderProgram::new(shader_version, RectKind::Undercurl)?; // This shader has way more ALU operations than other rect shaders, so use a fallback // to underline just for it when we can't compile it. let dotted_program = match RectShaderProgram::new(shader_version, RectKind::DottedUnderline) { Ok(dotted_program) => dotted_program, Err(err) => { info!("Error compiling dotted shader: {err}\n falling back to underline"); RectShaderProgram::new(shader_version, RectKind::Normal)? }, }; let dashed_program = RectShaderProgram::new(shader_version, RectKind::DashedUnderline)?; unsafe { // Allocate buffers. gl::GenVertexArrays(1, &mut vao); gl::GenBuffers(1, &mut vbo); gl::BindVertexArray(vao); // VBO binding is not part of VAO itself, but VBO binding is stored in attributes. gl::BindBuffer(gl::ARRAY_BUFFER, vbo); let mut attribute_offset = 0; // Position. gl::VertexAttribPointer( 0, 2, gl::FLOAT, gl::FALSE, mem::size_of::<Vertex>() as i32, attribute_offset as *const _, ); gl::EnableVertexAttribArray(0); attribute_offset += mem::size_of::<f32>() * 2; // Color. gl::VertexAttribPointer( 1, 4, gl::UNSIGNED_BYTE, gl::TRUE, mem::size_of::<Vertex>() as i32, attribute_offset as *const _, ); gl::EnableVertexAttribArray(1); // Reset buffer bindings. gl::BindVertexArray(0); gl::BindBuffer(gl::ARRAY_BUFFER, 0); } let programs = [rect_program, undercurl_program, dotted_program, dashed_program]; Ok(Self { vao, vbo, programs, vertices: Default::default() }) } pub fn draw(&mut self, size_info: &SizeInfo, metrics: &Metrics, rects: Vec<RenderRect>) { unsafe { // Bind VAO to enable vertex attribute slots. gl::BindVertexArray(self.vao); // Bind VBO only once for buffer data upload only. gl::BindBuffer(gl::ARRAY_BUFFER, self.vbo); } let half_width = size_info.width() / 2.; let half_height = size_info.height() / 2.; // Build rect vertices vector. self.vertices.iter_mut().for_each(|vertices| vertices.clear()); for rect in &rects { Self::add_rect(&mut self.vertices[rect.kind as usize], half_width, half_height, rect); } unsafe { // We iterate in reverse order to draw plain rects at the end, since we want visual // bell or damage rects be above the lines. for rect_kind in (RectKind::Normal as u8..RectKind::NumKinds as u8).rev() { let vertices = &mut self.vertices[rect_kind as usize]; if vertices.is_empty() { continue; } let program = &self.programs[rect_kind as usize]; gl::UseProgram(program.id()); program.update_uniforms(size_info, metrics); // Upload accumulated undercurl vertices. gl::BufferData( gl::ARRAY_BUFFER, (vertices.len() * mem::size_of::<Vertex>()) as isize, vertices.as_ptr() as *const _, gl::STREAM_DRAW, ); // Draw all vertices as list of triangles. gl::DrawArrays(gl::TRIANGLES, 0, vertices.len() as i32); } // Disable program. gl::UseProgram(0); // Reset buffer bindings to nothing. gl::BindBuffer(gl::ARRAY_BUFFER, 0); gl::BindVertexArray(0); } } fn add_rect(vertices: &mut Vec<Vertex>, half_width: f32, half_height: f32, rect: &RenderRect) { // Calculate rectangle vertices positions in normalized device coordinates. // NDC range from -1 to +1, with Y pointing up. let x = rect.x / half_width - 1.0; let y = -rect.y / half_height + 1.0; let width = rect.width / half_width; let height = rect.height / half_height; let (r, g, b) = rect.color.as_tuple(); let a = (rect.alpha * 255.) as u8; // Make quad vertices. let quad = [ Vertex { x, y, r, g, b, a }, Vertex { x, y: y - height, r, g, b, a }, Vertex { x: x + width, y, r, g, b, a }, Vertex { x: x + width, y: y - height, r, g, b, a }, ]; // Append the vertices to form two triangles. vertices.push(quad[0]); vertices.push(quad[1]); vertices.push(quad[2]); vertices.push(quad[2]); vertices.push(quad[3]); vertices.push(quad[1]); } } impl Drop for RectRenderer { fn drop(&mut self) { unsafe { gl::DeleteBuffers(1, &self.vbo); gl::DeleteVertexArrays(1, &self.vao); } } } /// Rectangle drawing program. #[derive(Debug)] pub struct RectShaderProgram { /// Shader program. program: ShaderProgram, /// Cell width. u_cell_width: Option<GLint>, /// Cell height. u_cell_height: Option<GLint>, /// Terminal padding. u_padding_x: Option<GLint>, /// A padding from the bottom of the screen to viewport. u_padding_y: Option<GLint>, /// Underline position. u_underline_position: Option<GLint>, /// Underline thickness. u_underline_thickness: Option<GLint>, /// Undercurl position. u_undercurl_position: Option<GLint>, } impl RectShaderProgram { pub fn new(shader_version: ShaderVersion, kind: RectKind) -> Result<Self, ShaderError> { // XXX: This must be in-sync with fragment shader defines. let header = match kind { RectKind::Undercurl => Some("#define DRAW_UNDERCURL\n"), RectKind::DottedUnderline => Some("#define DRAW_DOTTED\n"), RectKind::DashedUnderline => Some("#define DRAW_DASHED\n"), _ => None, }; let program = ShaderProgram::new(shader_version, header, RECT_SHADER_V, RECT_SHADER_F)?; Ok(Self { u_cell_width: program.get_uniform_location(c"cellWidth").ok(), u_cell_height: program.get_uniform_location(c"cellHeight").ok(), u_padding_x: program.get_uniform_location(c"paddingX").ok(), u_padding_y: program.get_uniform_location(c"paddingY").ok(), u_underline_position: program.get_uniform_location(c"underlinePosition").ok(), u_underline_thickness: program.get_uniform_location(c"underlineThickness").ok(), u_undercurl_position: program.get_uniform_location(c"undercurlPosition").ok(), program, }) } fn id(&self) -> GLuint { self.program.id() } pub fn update_uniforms(&self, size_info: &SizeInfo, metrics: &Metrics) { let position = (0.5 * metrics.descent).abs(); let underline_position = metrics.descent.abs() - metrics.underline_position.abs(); let viewport_height = size_info.height() - size_info.padding_y(); let padding_y = viewport_height - (viewport_height / size_info.cell_height()).floor() * size_info.cell_height(); unsafe { if let Some(u_cell_width) = self.u_cell_width { gl::Uniform1f(u_cell_width, size_info.cell_width()); } if let Some(u_cell_height) = self.u_cell_height { gl::Uniform1f(u_cell_height, size_info.cell_height()); } if let Some(u_padding_y) = self.u_padding_y { gl::Uniform1f(u_padding_y, padding_y); } if let Some(u_padding_x) = self.u_padding_x { gl::Uniform1f(u_padding_x, size_info.padding_x()); } if let Some(u_underline_position) = self.u_underline_position { gl::Uniform1f(u_underline_position, underline_position); } if let Some(u_underline_thickness) = self.u_underline_thickness { gl::Uniform1f(u_underline_thickness, metrics.underline_thickness); } if let Some(u_undercurl_position) = self.u_undercurl_position { gl::Uniform1f(u_undercurl_position, position); } } } }
rust
Apache-2.0
6ee6e53ee3457c24137f117237b0ff1d84f6f836
2026-01-04T15:31:58.707223Z
false
alacritty/alacritty
https://github.com/alacritty/alacritty/blob/6ee6e53ee3457c24137f117237b0ff1d84f6f836/alacritty/src/renderer/platform.rs
alacritty/src/renderer/platform.rs
//! The graphics platform that is used by the renderer. use std::num::NonZeroU32; use glutin::config::{ColorBufferType, Config, ConfigTemplateBuilder, GetGlConfig}; use glutin::context::{ ContextApi, ContextAttributesBuilder, GlProfile, NotCurrentContext, Robustness, Version, }; use glutin::display::{Display, DisplayApiPreference, DisplayFeatures, GetGlDisplay}; use glutin::error::Result as GlutinResult; use glutin::prelude::*; use glutin::surface::{Surface, SurfaceAttributesBuilder, WindowSurface}; use log::{LevelFilter, debug}; use winit::dpi::PhysicalSize; #[cfg(all(feature = "x11", not(any(target_os = "macos", windows))))] use winit::platform::x11; use winit::raw_window_handle::{RawDisplayHandle, RawWindowHandle}; /// Create the GL display. pub fn create_gl_display( raw_display_handle: RawDisplayHandle, _raw_window_handle: Option<RawWindowHandle>, _prefer_egl: bool, ) -> GlutinResult<Display> { #[cfg(target_os = "macos")] let preference = DisplayApiPreference::Cgl; #[cfg(windows)] let preference = if _prefer_egl { DisplayApiPreference::EglThenWgl(Some(_raw_window_handle.unwrap())) } else { DisplayApiPreference::WglThenEgl(Some(_raw_window_handle.unwrap())) }; #[cfg(all(feature = "x11", not(any(target_os = "macos", windows))))] let preference = if _prefer_egl { DisplayApiPreference::EglThenGlx(Box::new(x11::register_xlib_error_hook)) } else { DisplayApiPreference::GlxThenEgl(Box::new(x11::register_xlib_error_hook)) }; #[cfg(all(not(feature = "x11"), not(any(target_os = "macos", windows))))] let preference = DisplayApiPreference::Egl; let display = unsafe { Display::new(raw_display_handle, preference)? }; log::info!("Using {}", { display.version_string() }); Ok(display) } pub fn pick_gl_config( gl_display: &Display, raw_window_handle: Option<RawWindowHandle>, ) -> Result<Config, String> { let mut default_config = ConfigTemplateBuilder::new() .with_depth_size(0) .with_stencil_size(0) .with_transparency(true); if let Some(raw_window_handle) = raw_window_handle { default_config = default_config.compatible_with_native_window(raw_window_handle); } let config_10bit = default_config .clone() .with_buffer_type(ColorBufferType::Rgb { r_size: 10, g_size: 10, b_size: 10 }) .with_alpha_size(2); let configs = [ default_config.clone(), config_10bit.clone(), default_config.with_transparency(false), config_10bit.with_transparency(false), ]; for config in configs { let gl_config = unsafe { gl_display.find_configs(config.build()).ok().and_then(|mut configs| configs.next()) }; if let Some(gl_config) = gl_config { debug!( r#"Picked GL Config: buffer_type: {:?} alpha_size: {} num_samples: {} hardware_accelerated: {:?} supports_transparency: {:?} config_api: {:?} srgb_capable: {}"#, gl_config.color_buffer_type(), gl_config.alpha_size(), gl_config.num_samples(), gl_config.hardware_accelerated(), gl_config.supports_transparency(), gl_config.api(), gl_config.srgb_capable(), ); return Ok(gl_config); } } Err(String::from("failed to find suitable GL configuration.")) } pub fn create_gl_context( gl_display: &Display, gl_config: &Config, raw_window_handle: Option<RawWindowHandle>, ) -> GlutinResult<NotCurrentContext> { let debug = log::max_level() >= LevelFilter::Debug; let apis = [ (ContextApi::OpenGl(Some(Version::new(3, 3))), GlProfile::Core), // Try gles before OpenGL 2.1 as it tends to be more stable. (ContextApi::Gles(Some(Version::new(2, 0))), GlProfile::Core), (ContextApi::OpenGl(Some(Version::new(2, 1))), GlProfile::Compatibility), ]; let robustness = gl_display.supported_features().contains(DisplayFeatures::CONTEXT_ROBUSTNESS); let robustness: &[Robustness] = if robustness { &[Robustness::RobustLoseContextOnReset, Robustness::NotRobust] } else { &[Robustness::NotRobust] }; // Find the first context that builds without any errors. let mut error = None; for (api, profile) in apis { for robustness in robustness { let attributes = ContextAttributesBuilder::new() .with_debug(debug) .with_context_api(api) .with_profile(profile) .with_robustness(*robustness) .build(raw_window_handle); match unsafe { gl_display.create_context(gl_config, &attributes) } { Ok(profile) => return Ok(profile), Err(err) => error = Some(err), } } } // If no context was built successfully, return an error for the most permissive one. Err(error.unwrap()) } pub fn create_gl_surface( gl_context: &NotCurrentContext, size: PhysicalSize<u32>, raw_window_handle: RawWindowHandle, ) -> GlutinResult<Surface<WindowSurface>> { // Get the display and the config used to create that context. let gl_display = gl_context.display(); let gl_config = gl_context.config(); let surface_attributes = SurfaceAttributesBuilder::<WindowSurface>::new().with_srgb(Some(false)).build( raw_window_handle, NonZeroU32::new(size.width).unwrap(), NonZeroU32::new(size.height).unwrap(), ); // Create the GL surface to draw into. unsafe { gl_display.create_window_surface(&gl_config, &surface_attributes) } }
rust
Apache-2.0
6ee6e53ee3457c24137f117237b0ff1d84f6f836
2026-01-04T15:31:58.707223Z
false
alacritty/alacritty
https://github.com/alacritty/alacritty/blob/6ee6e53ee3457c24137f117237b0ff1d84f6f836/alacritty/src/renderer/mod.rs
alacritty/src/renderer/mod.rs
use std::borrow::Cow; use std::collections::HashSet; use std::ffi::{CStr, CString}; use std::sync::OnceLock; use std::sync::atomic::{AtomicBool, Ordering}; use std::{fmt, ptr}; use ahash::RandomState; use crossfont::Metrics; use glutin::context::{ContextApi, GlContext, PossiblyCurrentContext}; use glutin::display::{GetGlDisplay, GlDisplay}; use log::{LevelFilter, debug, info}; use unicode_width::UnicodeWidthChar; use alacritty_terminal::index::Point; use alacritty_terminal::term::cell::Flags; use crate::config::debug::RendererPreference; use crate::display::SizeInfo; use crate::display::color::Rgb; use crate::display::content::RenderableCell; use crate::gl; use crate::renderer::rects::{RectRenderer, RenderRect}; use crate::renderer::shader::ShaderError; pub mod platform; pub mod rects; mod shader; mod text; pub use text::{GlyphCache, LoaderApi}; use shader::ShaderVersion; use text::{Gles2Renderer, Glsl3Renderer, TextRenderer}; /// Whether the OpenGL functions have been loaded. pub static GL_FUNS_LOADED: AtomicBool = AtomicBool::new(false); #[derive(Debug)] pub enum Error { /// Shader error. Shader(ShaderError), /// Other error. Other(String), } impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { Error::Shader(err) => err.source(), Error::Other(_) => None, } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Error::Shader(err) => { write!(f, "There was an error initializing the shaders: {err}") }, Error::Other(err) => { write!(f, "{err}") }, } } } impl From<ShaderError> for Error { fn from(val: ShaderError) -> Self { Error::Shader(val) } } impl From<String> for Error { fn from(val: String) -> Self { Error::Other(val) } } #[derive(Debug)] enum TextRendererProvider { Gles2(Gles2Renderer), Glsl3(Glsl3Renderer), } #[derive(Debug)] pub struct Renderer { text_renderer: TextRendererProvider, rect_renderer: RectRenderer, robustness: bool, } /// Wrapper around gl::GetString with error checking and reporting. fn gl_get_string( string_id: gl::types::GLenum, description: &str, ) -> Result<Cow<'static, str>, Error> { unsafe { let string_ptr = gl::GetString(string_id); match gl::GetError() { gl::NO_ERROR if !string_ptr.is_null() => { Ok(CStr::from_ptr(string_ptr as *const _).to_string_lossy()) }, gl::INVALID_ENUM => { Err(format!("OpenGL error requesting {description}: invalid enum").into()) }, error_id => Err(format!("OpenGL error {error_id} requesting {description}").into()), } } } impl Renderer { /// Create a new renderer. /// /// This will automatically pick between the GLES2 and GLSL3 renderer based on the GPU's /// supported OpenGL version. pub fn new( context: &PossiblyCurrentContext, renderer_preference: Option<RendererPreference>, ) -> Result<Self, Error> { // We need to load OpenGL functions once per instance, but only after we make our context // current due to WGL limitations. if !GL_FUNS_LOADED.swap(true, Ordering::Relaxed) { let gl_display = context.display(); gl::load_with(|symbol| { let symbol = CString::new(symbol).unwrap(); gl_display.get_proc_address(symbol.as_c_str()).cast() }); } let shader_version = gl_get_string(gl::SHADING_LANGUAGE_VERSION, "shader version")?; let gl_version = gl_get_string(gl::VERSION, "OpenGL version")?; let renderer = gl_get_string(gl::RENDERER, "renderer version")?; info!("Running on {renderer}"); info!("OpenGL version {gl_version}, shader_version {shader_version}"); // Check if robustness is supported. let robustness = Self::supports_robustness(); let is_gles_context = matches!(context.context_api(), ContextApi::Gles(_)); // Use the config option to enforce a particular renderer configuration. let (use_glsl3, allow_dsb) = match renderer_preference { Some(RendererPreference::Glsl3) => (true, true), Some(RendererPreference::Gles2) => (false, true), Some(RendererPreference::Gles2Pure) => (false, false), None => (shader_version.as_ref() >= "3.3" && !is_gles_context, true), }; let (text_renderer, rect_renderer) = if use_glsl3 { let text_renderer = TextRendererProvider::Glsl3(Glsl3Renderer::new()?); let rect_renderer = RectRenderer::new(ShaderVersion::Glsl3)?; (text_renderer, rect_renderer) } else { let text_renderer = TextRendererProvider::Gles2(Gles2Renderer::new(allow_dsb, is_gles_context)?); let rect_renderer = RectRenderer::new(ShaderVersion::Gles2)?; (text_renderer, rect_renderer) }; // Enable debug logging for OpenGL as well. if log::max_level() >= LevelFilter::Debug && GlExtensions::contains("GL_KHR_debug") { debug!("Enabled debug logging for OpenGL"); unsafe { gl::Enable(gl::DEBUG_OUTPUT); gl::Enable(gl::DEBUG_OUTPUT_SYNCHRONOUS); gl::DebugMessageCallback(Some(gl_debug_log), ptr::null_mut()); } } Ok(Self { text_renderer, rect_renderer, robustness }) } pub fn draw_cells<I: Iterator<Item = RenderableCell>>( &mut self, size_info: &SizeInfo, glyph_cache: &mut GlyphCache, cells: I, ) { match &mut self.text_renderer { TextRendererProvider::Gles2(renderer) => { renderer.draw_cells(size_info, glyph_cache, cells) }, TextRendererProvider::Glsl3(renderer) => { renderer.draw_cells(size_info, glyph_cache, cells) }, } } /// Draw a string in a variable location. Used for printing the render timer, warnings and /// errors. pub fn draw_string( &mut self, point: Point<usize>, fg: Rgb, bg: Rgb, string_chars: impl Iterator<Item = char>, size_info: &SizeInfo, glyph_cache: &mut GlyphCache, ) { let mut wide_char_spacer = false; let cells = string_chars.enumerate().filter_map(|(i, character)| { let flags = if wide_char_spacer { wide_char_spacer = false; return None; } else if character.width() == Some(2) { // The spacer is always following the wide char. wide_char_spacer = true; Flags::WIDE_CHAR } else { Flags::empty() }; Some(RenderableCell { point: Point::new(point.line, point.column + i), character, extra: None, flags, bg_alpha: 1.0, fg, bg, underline: fg, }) }); self.draw_cells(size_info, glyph_cache, cells); } pub fn with_loader<F, T>(&mut self, func: F) -> T where F: FnOnce(LoaderApi<'_>) -> T, { match &mut self.text_renderer { TextRendererProvider::Gles2(renderer) => renderer.with_loader(func), TextRendererProvider::Glsl3(renderer) => renderer.with_loader(func), } } /// Draw all rectangles simultaneously to prevent excessive program swaps. pub fn draw_rects(&mut self, size_info: &SizeInfo, metrics: &Metrics, rects: Vec<RenderRect>) { if rects.is_empty() { return; } // Prepare rect rendering state. unsafe { // Remove padding from viewport. gl::Viewport(0, 0, size_info.width() as i32, size_info.height() as i32); gl::BlendFuncSeparate(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA, gl::SRC_ALPHA, gl::ONE); } self.rect_renderer.draw(size_info, metrics, rects); // Activate regular state again. unsafe { // Reset blending strategy. gl::BlendFunc(gl::SRC1_COLOR, gl::ONE_MINUS_SRC1_COLOR); // Restore viewport with padding. self.set_viewport(size_info); } } /// Fill the window with `color` and `alpha`. pub fn clear(&self, color: Rgb, alpha: f32) { unsafe { gl::ClearColor( (f32::from(color.r) / 255.0).min(1.0) * alpha, (f32::from(color.g) / 255.0).min(1.0) * alpha, (f32::from(color.b) / 255.0).min(1.0) * alpha, alpha, ); gl::Clear(gl::COLOR_BUFFER_BIT); } } /// Get the context reset status. pub fn was_context_reset(&self) -> bool { // If robustness is not supported, don't use its functions. if !self.robustness { return false; } let status = unsafe { gl::GetGraphicsResetStatus() }; if status == gl::NO_ERROR { false } else { let reason = match status { gl::GUILTY_CONTEXT_RESET_KHR => "guilty", gl::INNOCENT_CONTEXT_RESET_KHR => "innocent", gl::UNKNOWN_CONTEXT_RESET_KHR => "unknown", _ => "invalid", }; info!("GPU reset ({reason})"); true } } fn supports_robustness() -> bool { let mut notification_strategy = 0; if GlExtensions::contains("GL_KHR_robustness") { unsafe { gl::GetIntegerv(gl::RESET_NOTIFICATION_STRATEGY_KHR, &mut notification_strategy); } } else { notification_strategy = gl::NO_RESET_NOTIFICATION_KHR as gl::types::GLint; } if notification_strategy == gl::LOSE_CONTEXT_ON_RESET_KHR as gl::types::GLint { info!("GPU reset notifications are enabled"); true } else { info!("GPU reset notifications are disabled"); false } } pub fn finish(&self) { unsafe { gl::Finish(); } } /// Set the viewport for cell rendering. #[inline] pub fn set_viewport(&self, size: &SizeInfo) { unsafe { gl::Viewport( size.padding_x() as i32, size.padding_y() as i32, size.width() as i32 - 2 * size.padding_x() as i32, size.height() as i32 - 2 * size.padding_y() as i32, ); } } /// Resize the renderer. pub fn resize(&self, size_info: &SizeInfo) { self.set_viewport(size_info); match &self.text_renderer { TextRendererProvider::Gles2(renderer) => renderer.resize(size_info), TextRendererProvider::Glsl3(renderer) => renderer.resize(size_info), } } } struct GlExtensions; impl GlExtensions { /// Check if the given `extension` is supported. /// /// This function will lazily load OpenGL extensions. fn contains(extension: &str) -> bool { static OPENGL_EXTENSIONS: OnceLock<HashSet<&'static str, RandomState>> = OnceLock::new(); OPENGL_EXTENSIONS.get_or_init(Self::load_extensions).contains(extension) } /// Load available OpenGL extensions. fn load_extensions() -> HashSet<&'static str, RandomState> { unsafe { let extensions = gl::GetString(gl::EXTENSIONS); if extensions.is_null() { let mut extensions_number = 0; gl::GetIntegerv(gl::NUM_EXTENSIONS, &mut extensions_number); (0..extensions_number as gl::types::GLuint) .flat_map(|i| { let extension = CStr::from_ptr(gl::GetStringi(gl::EXTENSIONS, i) as *mut _); extension.to_str() }) .collect() } else { match CStr::from_ptr(extensions as *mut _).to_str() { Ok(ext) => ext.split_whitespace().collect(), Err(_) => Default::default(), } } } } } extern "system" fn gl_debug_log( _: gl::types::GLenum, _: gl::types::GLenum, _: gl::types::GLuint, _: gl::types::GLenum, _: gl::types::GLsizei, msg: *const gl::types::GLchar, _: *mut std::os::raw::c_void, ) { let msg = unsafe { CStr::from_ptr(msg).to_string_lossy() }; debug!("[gl_render] {msg}"); }
rust
Apache-2.0
6ee6e53ee3457c24137f117237b0ff1d84f6f836
2026-01-04T15:31:58.707223Z
false
alacritty/alacritty
https://github.com/alacritty/alacritty/blob/6ee6e53ee3457c24137f117237b0ff1d84f6f836/alacritty/src/renderer/shader.rs
alacritty/src/renderer/shader.rs
use std::ffi::CStr; use std::fmt; use crate::gl; use crate::gl::types::*; /// A wrapper for a shader program id, with automatic lifetime management. #[derive(Debug)] pub struct ShaderProgram(GLuint); #[derive(Copy, Clone, Debug)] pub enum ShaderVersion { /// OpenGL 3.3 core shaders. Glsl3, /// OpenGL ES 2.0 shaders. Gles2, } impl ShaderVersion { // Header to which we concatenate the entire shader. The newlines are required. fn shader_header(&self) -> &'static str { match self { Self::Glsl3 => "#version 330 core\n", Self::Gles2 => "#version 100\n#define GLES2_RENDERER\n", } } } impl ShaderProgram { pub fn new( shader_version: ShaderVersion, shader_header: Option<&str>, vertex_shader: &'static str, fragment_shader: &'static str, ) -> Result<Self, ShaderError> { let vertex_shader = Shader::new(shader_version, shader_header, gl::VERTEX_SHADER, vertex_shader)?; let fragment_shader = Shader::new(shader_version, shader_header, gl::FRAGMENT_SHADER, fragment_shader)?; let program = unsafe { Self(gl::CreateProgram()) }; let mut success: GLint = 0; unsafe { gl::AttachShader(program.id(), vertex_shader.id()); gl::AttachShader(program.id(), fragment_shader.id()); gl::LinkProgram(program.id()); gl::GetProgramiv(program.id(), gl::LINK_STATUS, &mut success); } if success != i32::from(gl::TRUE) { return Err(ShaderError::Link(get_program_info_log(program.id()))); } Ok(program) } /// Get uniform location by name. Panic if failed. pub fn get_uniform_location(&self, name: &'static CStr) -> Result<GLint, ShaderError> { // This call doesn't require `UseProgram`. let ret = unsafe { gl::GetUniformLocation(self.id(), name.as_ptr()) }; if ret == -1 { return Err(ShaderError::Uniform(name)); } Ok(ret) } /// Get the shader program id. pub fn id(&self) -> GLuint { self.0 } } impl Drop for ShaderProgram { fn drop(&mut self) { unsafe { gl::DeleteProgram(self.0) } } } /// A wrapper for a shader id, with automatic lifetime management. #[derive(Debug)] struct Shader(GLuint); impl Shader { fn new( shader_version: ShaderVersion, shader_header: Option<&str>, kind: GLenum, source: &'static str, ) -> Result<Self, ShaderError> { let version_header = shader_version.shader_header(); let mut sources = Vec::<*const GLchar>::with_capacity(3); let mut lengths = Vec::<GLint>::with_capacity(3); sources.push(version_header.as_ptr().cast()); lengths.push(version_header.len() as GLint); if let Some(shader_header) = shader_header { sources.push(shader_header.as_ptr().cast()); lengths.push(shader_header.len() as GLint); } sources.push(source.as_ptr().cast()); lengths.push(source.len() as GLint); let shader = unsafe { Self(gl::CreateShader(kind)) }; let mut success: GLint = 0; unsafe { gl::ShaderSource( shader.id(), lengths.len() as GLint, sources.as_ptr().cast(), lengths.as_ptr(), ); gl::CompileShader(shader.id()); gl::GetShaderiv(shader.id(), gl::COMPILE_STATUS, &mut success); } if success == GLint::from(gl::TRUE) { Ok(shader) } else { Err(ShaderError::Compile(get_shader_info_log(shader.id()))) } } fn id(&self) -> GLuint { self.0 } } impl Drop for Shader { fn drop(&mut self) { unsafe { gl::DeleteShader(self.0) } } } fn get_program_info_log(program: GLuint) -> String { // Get expected log length. let mut max_length: GLint = 0; unsafe { gl::GetProgramiv(program, gl::INFO_LOG_LENGTH, &mut max_length); } // Read the info log. let mut actual_length: GLint = 0; let mut buf: Vec<u8> = Vec::with_capacity(max_length as usize); unsafe { gl::GetProgramInfoLog(program, max_length, &mut actual_length, buf.as_mut_ptr() as *mut _); } // Build a string. unsafe { buf.set_len(actual_length as usize); } String::from_utf8_lossy(&buf).to_string() } fn get_shader_info_log(shader: GLuint) -> String { // Get expected log length. let mut max_length: GLint = 0; unsafe { gl::GetShaderiv(shader, gl::INFO_LOG_LENGTH, &mut max_length); } // Read the info log. let mut actual_length: GLint = 0; let mut buf: Vec<u8> = Vec::with_capacity(max_length as usize); unsafe { gl::GetShaderInfoLog(shader, max_length, &mut actual_length, buf.as_mut_ptr() as *mut _); } // Build a string. unsafe { buf.set_len(actual_length as usize); } String::from_utf8_lossy(&buf).to_string() } #[derive(Debug)] pub enum ShaderError { /// Error compiling shader. Compile(String), /// Error linking shader. Link(String), /// Error getting uniform location. Uniform(&'static CStr), } impl std::error::Error for ShaderError {} impl fmt::Display for ShaderError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Compile(reason) => write!(f, "Failed compiling shader: {reason}"), Self::Link(reason) => write!(f, "Failed linking shader: {reason}"), Self::Uniform(name) => write!(f, "Failed to get uniform location of {name:?}"), } } }
rust
Apache-2.0
6ee6e53ee3457c24137f117237b0ff1d84f6f836
2026-01-04T15:31:58.707223Z
false
alacritty/alacritty
https://github.com/alacritty/alacritty/blob/6ee6e53ee3457c24137f117237b0ff1d84f6f836/alacritty/src/renderer/text/glyph_cache.rs
alacritty/src/renderer/text/glyph_cache.rs
use std::collections::HashMap; use ahash::RandomState; use crossfont::{ Error as RasterizerError, FontDesc, FontKey, GlyphKey, Metrics, Rasterize, RasterizedGlyph, Rasterizer, Size, Slant, Style, Weight, }; use log::{error, info}; use unicode_width::UnicodeWidthChar; use crate::config::font::{Font, FontDescription}; use crate::config::ui_config::Delta; use crate::gl::types::*; use super::builtin_font; /// `LoadGlyph` allows for copying a rasterized glyph into graphics memory. pub trait LoadGlyph { /// Load the rasterized glyph into GPU memory. fn load_glyph(&mut self, rasterized: &RasterizedGlyph) -> Glyph; /// Clear any state accumulated from previous loaded glyphs. /// /// This can, for instance, be used to reset the texture Atlas. fn clear(&mut self); } #[derive(Copy, Clone, Debug)] pub struct Glyph { pub tex_id: GLuint, pub multicolor: bool, pub top: i16, pub left: i16, pub width: i16, pub height: i16, pub uv_bot: f32, pub uv_left: f32, pub uv_width: f32, pub uv_height: f32, } /// Naïve glyph cache. /// /// Currently only keyed by `char`, and thus not possible to hold different /// representations of the same code point. pub struct GlyphCache { /// Cache of buffered glyphs. cache: HashMap<GlyphKey, Glyph, RandomState>, /// Rasterizer for loading new glyphs. rasterizer: Rasterizer, /// Regular font. pub font_key: FontKey, /// Bold font. pub bold_key: FontKey, /// Italic font. pub italic_key: FontKey, /// Bold italic font. pub bold_italic_key: FontKey, /// Font size. pub font_size: crossfont::Size, /// Font offset. font_offset: Delta<i8>, /// Glyph offset. glyph_offset: Delta<i8>, /// Font metrics. metrics: Metrics, /// Whether to use the built-in font for box drawing characters. builtin_box_drawing: bool, } impl GlyphCache { pub fn new(mut rasterizer: Rasterizer, font: &Font) -> Result<GlyphCache, crossfont::Error> { let (regular, bold, italic, bold_italic) = Self::compute_font_keys(font, &mut rasterizer)?; let metrics = GlyphCache::load_font_metrics(&mut rasterizer, font, regular)?; Ok(Self { cache: Default::default(), rasterizer, font_size: font.size(), font_key: regular, bold_key: bold, italic_key: italic, bold_italic_key: bold_italic, font_offset: font.offset, glyph_offset: font.glyph_offset, metrics, builtin_box_drawing: font.builtin_box_drawing, }) } // Load font metrics and adjust for glyph offset. fn load_font_metrics( rasterizer: &mut Rasterizer, font: &Font, key: FontKey, ) -> Result<Metrics, crossfont::Error> { // Need to load at least one glyph for the face before calling metrics. // The glyph requested here ('m' at the time of writing) has no special // meaning. rasterizer.get_glyph(GlyphKey { font_key: key, character: 'm', size: font.size() })?; let mut metrics = rasterizer.metrics(key, font.size())?; metrics.strikeout_position += font.glyph_offset.y as f32; Ok(metrics) } fn load_glyphs_for_font<L: LoadGlyph>(&mut self, font: FontKey, loader: &mut L) { let size = self.font_size; // Cache all ascii characters. for i in 32u8..=126u8 { self.get(GlyphKey { font_key: font, character: i as char, size }, loader, true); } } /// Computes font keys for (Regular, Bold, Italic, Bold Italic). fn compute_font_keys( font: &Font, rasterizer: &mut Rasterizer, ) -> Result<(FontKey, FontKey, FontKey, FontKey), crossfont::Error> { let size = font.size(); // Load regular font. let regular_desc = Self::make_desc(font.normal(), Slant::Normal, Weight::Normal); let regular = Self::load_regular_font(rasterizer, &regular_desc, size)?; // Helper to load a description if it is not the `regular_desc`. let mut load_or_regular = |desc: FontDesc| { if desc == regular_desc { regular } else { rasterizer.load_font(&desc, size).unwrap_or(regular) } }; // Load bold font. let bold_desc = Self::make_desc(&font.bold(), Slant::Normal, Weight::Bold); let bold = load_or_regular(bold_desc); // Load italic font. let italic_desc = Self::make_desc(&font.italic(), Slant::Italic, Weight::Normal); let italic = load_or_regular(italic_desc); // Load bold italic font. let bold_italic_desc = Self::make_desc(&font.bold_italic(), Slant::Italic, Weight::Bold); let bold_italic = load_or_regular(bold_italic_desc); Ok((regular, bold, italic, bold_italic)) } fn load_regular_font( rasterizer: &mut Rasterizer, description: &FontDesc, size: Size, ) -> Result<FontKey, crossfont::Error> { match rasterizer.load_font(description, size) { Ok(font) => Ok(font), Err(err) => { error!("{err}"); let fallback_desc = Self::make_desc(Font::default().normal(), Slant::Normal, Weight::Normal); rasterizer.load_font(&fallback_desc, size) }, } } fn make_desc(desc: &FontDescription, slant: Slant, weight: Weight) -> FontDesc { let style = if let Some(ref spec) = desc.style { Style::Specific(spec.to_owned()) } else { Style::Description { slant, weight } }; FontDesc::new(desc.family.clone(), style) } /// Get a glyph from the font. /// /// If the glyph has never been loaded before, it will be rasterized and inserted into the /// cache. /// /// # Errors /// /// This will fail when the glyph could not be rasterized. Usually this is due to the glyph /// not being present in any font. pub fn get<L>(&mut self, glyph_key: GlyphKey, loader: &mut L, show_missing: bool) -> Glyph where L: LoadGlyph + ?Sized, { // Try to load glyph from cache. if let Some(glyph) = self.cache.get(&glyph_key) { return *glyph; }; // Rasterize the glyph using the built-in font for special characters or the user's font // for everything else. let rasterized = self .builtin_box_drawing .then(|| { builtin_font::builtin_glyph( glyph_key.character, &self.metrics, &self.font_offset, &self.glyph_offset, ) }) .flatten() .map_or_else(|| self.rasterizer.get_glyph(glyph_key), Ok); let glyph = match rasterized { Ok(rasterized) => self.load_glyph(loader, rasterized), // Load fallback glyph. Err(RasterizerError::MissingGlyph(rasterized)) if show_missing => { // Use `\0` as "missing" glyph to cache it only once. let missing_key = GlyphKey { character: '\0', ..glyph_key }; if let Some(glyph) = self.cache.get(&missing_key) { *glyph } else { // If no missing glyph was loaded yet, insert it as `\0`. let glyph = self.load_glyph(loader, rasterized); self.cache.insert(missing_key, glyph); glyph } }, Err(_) => self.load_glyph(loader, Default::default()), }; // Cache rasterized glyph. *self.cache.entry(glyph_key).or_insert(glyph) } /// Load glyph into the atlas. /// /// This will apply all transforms defined for the glyph cache to the rasterized glyph before pub fn load_glyph<L>(&self, loader: &mut L, mut glyph: RasterizedGlyph) -> Glyph where L: LoadGlyph + ?Sized, { glyph.left += i32::from(self.glyph_offset.x); glyph.top += i32::from(self.glyph_offset.y); glyph.top -= self.metrics.descent as i32; // The metrics of zero-width characters are based on rendering // the character after the current cell, with the anchor at the // right side of the preceding character. Since we render the // zero-width characters inside the preceding character, the // anchor has been moved to the right by one cell. if glyph.character.width() == Some(0) { glyph.left += self.metrics.average_advance as i32; } // Add glyph to cache. loader.load_glyph(&glyph) } /// Reset currently cached data in both GL and the registry to default state. pub fn reset_glyph_cache<L: LoadGlyph>(&mut self, loader: &mut L) { loader.clear(); self.cache = Default::default(); self.load_common_glyphs(loader); } /// Update the inner font size. /// /// NOTE: To reload the renderers's fonts [`Self::reset_glyph_cache`] should be called /// afterwards. pub fn update_font_size(&mut self, font: &Font) -> Result<(), crossfont::Error> { // Update dpi scaling. self.font_offset = font.offset; self.glyph_offset = font.glyph_offset; // Recompute font keys. let (regular, bold, italic, bold_italic) = Self::compute_font_keys(font, &mut self.rasterizer)?; let metrics = GlyphCache::load_font_metrics(&mut self.rasterizer, font, regular)?; info!("Font size changed to {:?} px", font.size().as_px()); self.font_size = font.size(); self.font_key = regular; self.bold_key = bold; self.italic_key = italic; self.bold_italic_key = bold_italic; self.metrics = metrics; self.builtin_box_drawing = font.builtin_box_drawing; Ok(()) } pub fn font_metrics(&self) -> crossfont::Metrics { self.metrics } /// Prefetch glyphs that are almost guaranteed to be loaded anyways. pub fn load_common_glyphs<L: LoadGlyph>(&mut self, loader: &mut L) { self.load_glyphs_for_font(self.font_key, loader); self.load_glyphs_for_font(self.bold_key, loader); self.load_glyphs_for_font(self.italic_key, loader); self.load_glyphs_for_font(self.bold_italic_key, loader); } }
rust
Apache-2.0
6ee6e53ee3457c24137f117237b0ff1d84f6f836
2026-01-04T15:31:58.707223Z
false
alacritty/alacritty
https://github.com/alacritty/alacritty/blob/6ee6e53ee3457c24137f117237b0ff1d84f6f836/alacritty/src/renderer/text/gles2.rs
alacritty/src/renderer/text/gles2.rs
use std::mem::size_of; use std::ptr; use crossfont::RasterizedGlyph; use log::info; use alacritty_terminal::term::cell::Flags; use crate::display::SizeInfo; use crate::display::content::RenderableCell; use crate::gl; use crate::gl::types::*; use crate::renderer::shader::{ShaderProgram, ShaderVersion}; use crate::renderer::{Error, GlExtensions}; use super::atlas::{ATLAS_SIZE, Atlas}; use super::{ Glyph, LoadGlyph, LoaderApi, RenderingGlyphFlags, RenderingPass, TextRenderApi, TextRenderBatch, TextRenderer, TextShader, glsl3, }; // Shader source. const TEXT_SHADER_F: &str = include_str!("../../../res/gles2/text.f.glsl"); const TEXT_SHADER_V: &str = include_str!("../../../res/gles2/text.v.glsl"); #[derive(Debug)] pub struct Gles2Renderer { program: TextShaderProgram, vao: GLuint, vbo: GLuint, ebo: GLuint, atlas: Vec<Atlas>, batch: Batch, current_atlas: usize, active_tex: GLuint, dual_source_blending: bool, } impl Gles2Renderer { pub fn new(allow_dsb: bool, is_gles_context: bool) -> Result<Self, Error> { info!("Using OpenGL ES 2.0 renderer"); let dual_source_blending = allow_dsb && (GlExtensions::contains("GL_EXT_blend_func_extended") || GlExtensions::contains("GL_ARB_blend_func_extended")); if is_gles_context { info!("Running on OpenGL ES context"); } if dual_source_blending { info!("Using dual source blending"); } let program = TextShaderProgram::new(ShaderVersion::Gles2, dual_source_blending)?; let mut vao: GLuint = 0; let mut vbo: GLuint = 0; let mut ebo: GLuint = 0; let mut vertex_indices = Vec::with_capacity(BATCH_MAX / 4 * 6); for index in 0..(BATCH_MAX / 4) as u16 { let index = index * 4; vertex_indices.push(index); vertex_indices.push(index + 1); vertex_indices.push(index + 3); vertex_indices.push(index + 1); vertex_indices.push(index + 2); vertex_indices.push(index + 3); } unsafe { gl::Enable(gl::BLEND); gl::DepthMask(gl::FALSE); gl::GenVertexArrays(1, &mut vao); gl::GenBuffers(1, &mut ebo); gl::GenBuffers(1, &mut vbo); gl::BindVertexArray(vao); // Elements buffer. gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, ebo); gl::BufferData( gl::ELEMENT_ARRAY_BUFFER, (vertex_indices.capacity() * size_of::<u16>()) as isize, vertex_indices.as_ptr() as *const _, gl::STATIC_DRAW, ); // Vertex buffer. gl::BindBuffer(gl::ARRAY_BUFFER, vbo); gl::BufferData( gl::ARRAY_BUFFER, (BATCH_MAX * size_of::<TextVertex>()) as isize, ptr::null(), gl::STREAM_DRAW, ); let mut index = 0; let mut size = 0; macro_rules! add_attr { ($count:expr, $gl_type:expr, $type:ty) => { gl::VertexAttribPointer( index, $count, $gl_type, gl::FALSE, size_of::<TextVertex>() as i32, size as *const _, ); gl::EnableVertexAttribArray(index); #[allow(unused_assignments)] { size += $count * size_of::<$type>(); index += 1; } }; } // Cell coords. add_attr!(2, gl::SHORT, i16); // Glyph coords. add_attr!(2, gl::SHORT, i16); // UV. add_attr!(2, gl::FLOAT, u32); // Color and bitmap color. // // These are packed together because of an OpenGL driver issue on macOS, which caused a // `vec3(u8)` text color and a `u8` for glyph color to cause performance regressions. add_attr!(4, gl::UNSIGNED_BYTE, u8); // Background color. add_attr!(4, gl::UNSIGNED_BYTE, u8); // Cleanup. gl::BindVertexArray(0); gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, 0); gl::BindBuffer(gl::ARRAY_BUFFER, 0); } Ok(Self { program, vao, vbo, ebo, atlas: vec![Atlas::new(ATLAS_SIZE, is_gles_context)], batch: Batch::new(), current_atlas: 0, active_tex: 0, dual_source_blending, }) } } impl Drop for Gles2Renderer { fn drop(&mut self) { unsafe { gl::DeleteBuffers(1, &self.vbo); gl::DeleteBuffers(1, &self.ebo); gl::DeleteVertexArrays(1, &self.vao); } } } impl<'a> TextRenderer<'a> for Gles2Renderer { type RenderApi = RenderApi<'a>; type RenderBatch = Batch; type Shader = TextShaderProgram; fn program(&self) -> &Self::Shader { &self.program } fn with_api<'b: 'a, F, T>(&'b mut self, _: &'b SizeInfo, func: F) -> T where F: FnOnce(Self::RenderApi) -> T, { unsafe { gl::UseProgram(self.program.id()); gl::BindVertexArray(self.vao); gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, self.ebo); gl::BindBuffer(gl::ARRAY_BUFFER, self.vbo); gl::ActiveTexture(gl::TEXTURE0); } let res = func(RenderApi { active_tex: &mut self.active_tex, batch: &mut self.batch, atlas: &mut self.atlas, current_atlas: &mut self.current_atlas, program: &mut self.program, dual_source_blending: self.dual_source_blending, }); unsafe { gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, 0); gl::BindBuffer(gl::ARRAY_BUFFER, 0); gl::BindVertexArray(0); gl::UseProgram(0); } res } fn loader_api(&mut self) -> LoaderApi<'_> { LoaderApi { active_tex: &mut self.active_tex, atlas: &mut self.atlas, current_atlas: &mut self.current_atlas, } } } /// Maximum items to be drawn in a batch. /// /// We use the closest number to `u16::MAX` dividable by 4 (amount of vertices we push for a glyph), /// since it's the maximum possible index in `glDrawElements` in GLES2. const BATCH_MAX: usize = (u16::MAX - u16::MAX % 4) as usize; #[derive(Debug)] pub struct Batch { tex: GLuint, vertices: Vec<TextVertex>, } impl Batch { fn new() -> Self { Self { tex: 0, vertices: Vec::with_capacity(BATCH_MAX) } } #[inline] fn len(&self) -> usize { self.vertices.len() } #[inline] fn capacity(&self) -> usize { BATCH_MAX } #[inline] fn size(&self) -> usize { self.len() * size_of::<TextVertex>() } #[inline] fn clear(&mut self) { self.vertices.clear(); } } impl TextRenderBatch for Batch { #[inline] fn tex(&self) -> GLuint { self.tex } #[inline] fn full(&self) -> bool { self.capacity() == self.len() } #[inline] fn is_empty(&self) -> bool { self.len() == 0 } fn add_item(&mut self, cell: &RenderableCell, glyph: &Glyph, size_info: &SizeInfo) { if self.is_empty() { self.tex = glyph.tex_id; } // Calculate the cell position. let x = cell.point.column.0 as i16 * size_info.cell_width() as i16; let y = cell.point.line as i16 * size_info.cell_height() as i16; // Calculate the glyph position. let glyph_x = cell.point.column.0 as i16 * size_info.cell_width() as i16 + glyph.left; let glyph_y = (cell.point.line + 1) as i16 * size_info.cell_height() as i16 - glyph.top; let colored = if glyph.multicolor { RenderingGlyphFlags::COLORED } else { RenderingGlyphFlags::empty() }; let is_wide = if cell.flags.contains(Flags::WIDE_CHAR) { 2 } else { 1 }; let mut vertex = TextVertex { x, y: y + size_info.cell_height() as i16, glyph_x, glyph_y: glyph_y + glyph.height, u: glyph.uv_left, v: glyph.uv_bot + glyph.uv_height, r: cell.fg.r, g: cell.fg.g, b: cell.fg.b, colored, bg_r: cell.bg.r, bg_g: cell.bg.g, bg_b: cell.bg.b, bg_a: (cell.bg_alpha * 255.0) as u8, }; self.vertices.push(vertex); vertex.y = y; vertex.glyph_y = glyph_y; vertex.u = glyph.uv_left; vertex.v = glyph.uv_bot; self.vertices.push(vertex); vertex.x = x + is_wide * size_info.cell_width() as i16; vertex.glyph_x = glyph_x + glyph.width; vertex.u = glyph.uv_left + glyph.uv_width; vertex.v = glyph.uv_bot; self.vertices.push(vertex); vertex.x = x + is_wide * size_info.cell_width() as i16; vertex.y = y + size_info.cell_height() as i16; vertex.glyph_x = glyph_x + glyph.width; vertex.glyph_y = glyph_y + glyph.height; vertex.u = glyph.uv_left + glyph.uv_width; vertex.v = glyph.uv_bot + glyph.uv_height; self.vertices.push(vertex); } } #[derive(Debug)] pub struct RenderApi<'a> { active_tex: &'a mut GLuint, batch: &'a mut Batch, atlas: &'a mut Vec<Atlas>, current_atlas: &'a mut usize, program: &'a mut TextShaderProgram, dual_source_blending: bool, } impl Drop for RenderApi<'_> { fn drop(&mut self) { if !self.batch.is_empty() { self.render_batch(); } } } impl LoadGlyph for RenderApi<'_> { fn load_glyph(&mut self, rasterized: &RasterizedGlyph) -> Glyph { Atlas::load_glyph(self.active_tex, self.atlas, self.current_atlas, rasterized) } fn clear(&mut self) { Atlas::clear_atlas(self.atlas, self.current_atlas) } } impl TextRenderApi<Batch> for RenderApi<'_> { fn batch(&mut self) -> &mut Batch { self.batch } fn render_batch(&mut self) { unsafe { gl::BufferSubData( gl::ARRAY_BUFFER, 0, self.batch.size() as isize, self.batch.vertices.as_ptr() as *const _, ); } if *self.active_tex != self.batch.tex() { unsafe { gl::BindTexture(gl::TEXTURE_2D, self.batch.tex()); } *self.active_tex = self.batch.tex(); } unsafe { let num_indices = (self.batch.len() / 4 * 6) as i32; // The rendering is inspired by // https://github.com/servo/webrender/blob/master/webrender/doc/text-rendering.md. // Draw background. self.program.set_rendering_pass(RenderingPass::Background); gl::BlendFunc(gl::ONE, gl::ZERO); gl::DrawElements(gl::TRIANGLES, num_indices, gl::UNSIGNED_SHORT, ptr::null()); self.program.set_rendering_pass(RenderingPass::SubpixelPass1); if self.dual_source_blending { // Text rendering pass. gl::BlendFunc(gl::SRC1_COLOR, gl::ONE_MINUS_SRC1_COLOR); } else { // First text rendering pass. gl::BlendFuncSeparate(gl::ZERO, gl::ONE_MINUS_SRC_COLOR, gl::ZERO, gl::ONE); gl::DrawElements(gl::TRIANGLES, num_indices, gl::UNSIGNED_SHORT, ptr::null()); // Second text rendering pass. self.program.set_rendering_pass(RenderingPass::SubpixelPass2); gl::BlendFuncSeparate(gl::ONE_MINUS_DST_ALPHA, gl::ONE, gl::ZERO, gl::ONE); gl::DrawElements(gl::TRIANGLES, num_indices, gl::UNSIGNED_SHORT, ptr::null()); // Third text rendering pass. self.program.set_rendering_pass(RenderingPass::SubpixelPass3); gl::BlendFuncSeparate(gl::ONE, gl::ONE, gl::ONE, gl::ONE_MINUS_SRC_ALPHA); } gl::DrawElements(gl::TRIANGLES, num_indices, gl::UNSIGNED_SHORT, ptr::null()); } self.batch.clear(); } } #[repr(C)] #[derive(Debug, Copy, Clone)] struct TextVertex { // Cell coordinates. x: i16, y: i16, // Glyph coordinates. glyph_x: i16, glyph_y: i16, // Offsets into Atlas. u: f32, v: f32, // Color. r: u8, g: u8, b: u8, // Whether the glyph is colored. colored: RenderingGlyphFlags, // Background color. bg_r: u8, bg_g: u8, bg_b: u8, bg_a: u8, } #[derive(Debug)] pub struct TextShaderProgram { /// Shader program. program: ShaderProgram, /// Projection scale and offset uniform. u_projection: GLint, /// Rendering pass. /// /// For dual source blending, there are 2 passes; one for background, another for text, /// similar to the GLSL3 renderer. /// /// If GL_EXT_blend_func_extended is not available, the rendering is split into 4 passes. /// One is used for the background and the rest to perform subpixel text rendering according to /// <https://github.com/servo/webrender/blob/master/webrender/doc/text-rendering.md>. /// /// Rendering is split into three passes. u_rendering_pass: GLint, } impl TextShaderProgram { pub fn new(shader_version: ShaderVersion, dual_source_blending: bool) -> Result<Self, Error> { let fragment_shader = if dual_source_blending { &glsl3::TEXT_SHADER_F } else { &TEXT_SHADER_F }; let program = ShaderProgram::new(shader_version, None, TEXT_SHADER_V, fragment_shader)?; Ok(Self { u_projection: program.get_uniform_location(c"projection")?, u_rendering_pass: program.get_uniform_location(c"renderingPass")?, program, }) } fn set_rendering_pass(&self, rendering_pass: RenderingPass) { unsafe { gl::Uniform1i(self.u_rendering_pass, rendering_pass as i32) } } } impl TextShader for TextShaderProgram { fn id(&self) -> GLuint { self.program.id() } fn projection_uniform(&self) -> GLint { self.u_projection } }
rust
Apache-2.0
6ee6e53ee3457c24137f117237b0ff1d84f6f836
2026-01-04T15:31:58.707223Z
false
alacritty/alacritty
https://github.com/alacritty/alacritty/blob/6ee6e53ee3457c24137f117237b0ff1d84f6f836/alacritty/src/renderer/text/atlas.rs
alacritty/src/renderer/text/atlas.rs
use std::borrow::Cow; use std::ptr; use crossfont::{BitmapBuffer, RasterizedGlyph}; use crate::gl; use crate::gl::types::*; use super::Glyph; /// Size of the Atlas. pub const ATLAS_SIZE: i32 = 1024; /// Manages a single texture atlas. /// /// The strategy for filling an atlas looks roughly like this: /// /// ```text /// (width, height) /// ┌─────┬─────┬─────┬─────┬─────┐ /// │ 10 │ │ │ │ │ <- Empty spaces; can be filled while /// │ │ │ │ │ │ glyph_height < height - row_baseline /// ├─────┼─────┼─────┼─────┼─────┤ /// │ 5 │ 6 │ 7 │ 8 │ 9 │ /// │ │ │ │ │ │ /// ├─────┼─────┼─────┼─────┴─────┤ <- Row height is tallest glyph in row; this is /// │ 1 │ 2 │ 3 │ 4 │ used as the baseline for the following row. /// │ │ │ │ │ <- Row considered full when next glyph doesn't /// └─────┴─────┴─────┴───────────┘ fit in the row. /// (0, 0) x-> /// ``` #[derive(Debug)] pub struct Atlas { /// Texture id for this atlas. id: GLuint, /// Width of atlas. width: i32, /// Height of atlas. height: i32, /// Left-most free pixel in a row. /// /// This is called the extent because it is the upper bound of used pixels /// in a row. row_extent: i32, /// Baseline for glyphs in the current row. row_baseline: i32, /// Tallest glyph in current row. /// /// This is used as the advance when end of row is reached. row_tallest: i32, /// Gles context. /// /// This affects the texture loading. is_gles_context: bool, } /// Error that can happen when inserting a texture to the Atlas. pub enum AtlasInsertError { /// Texture atlas is full. Full, /// The glyph cannot fit within a single texture. GlyphTooLarge, } impl Atlas { pub fn new(size: i32, is_gles_context: bool) -> Self { let mut id: GLuint = 0; unsafe { gl::PixelStorei(gl::UNPACK_ALIGNMENT, 1); gl::GenTextures(1, &mut id); gl::BindTexture(gl::TEXTURE_2D, id); // Use RGBA texture for both normal and emoji glyphs, since it has no performance // impact. gl::TexImage2D( gl::TEXTURE_2D, 0, gl::RGBA as i32, size, size, 0, gl::RGBA, gl::UNSIGNED_BYTE, ptr::null(), ); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::CLAMP_TO_EDGE as i32); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::CLAMP_TO_EDGE as i32); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32); gl::BindTexture(gl::TEXTURE_2D, 0); } Self { id, width: size, height: size, row_extent: 0, row_baseline: 0, row_tallest: 0, is_gles_context, } } pub fn clear(&mut self) { self.row_extent = 0; self.row_baseline = 0; self.row_tallest = 0; } /// Insert a RasterizedGlyph into the texture atlas. pub fn insert( &mut self, glyph: &RasterizedGlyph, active_tex: &mut u32, ) -> Result<Glyph, AtlasInsertError> { if glyph.width > self.width || glyph.height > self.height { return Err(AtlasInsertError::GlyphTooLarge); } // If there's not enough room in current row, go onto next one. if !self.room_in_row(glyph) { self.advance_row()?; } // If there's still not room, there's nothing that can be done here.. if !self.room_in_row(glyph) { return Err(AtlasInsertError::Full); } // There appears to be room; load the glyph. Ok(self.insert_inner(glyph, active_tex)) } /// Insert the glyph without checking for room. /// /// Internal function for use once atlas has been checked for space. GL /// errors could still occur at this point if we were checking for them; /// hence, the Result. fn insert_inner(&mut self, glyph: &RasterizedGlyph, active_tex: &mut u32) -> Glyph { let offset_y = self.row_baseline; let offset_x = self.row_extent; let height = glyph.height; let width = glyph.width; let multicolor; unsafe { gl::BindTexture(gl::TEXTURE_2D, self.id); // Load data into OpenGL. let (format, buffer) = match &glyph.buffer { BitmapBuffer::Rgb(buffer) => { multicolor = false; // Gles context doesn't allow uploading RGB data into RGBA texture, so need // explicit copy. if self.is_gles_context { let mut new_buffer = Vec::with_capacity(buffer.len() / 3 * 4); for rgb in buffer.chunks_exact(3) { new_buffer.push(rgb[0]); new_buffer.push(rgb[1]); new_buffer.push(rgb[2]); new_buffer.push(u8::MAX); } (gl::RGBA, Cow::Owned(new_buffer)) } else { (gl::RGB, Cow::Borrowed(buffer)) } }, BitmapBuffer::Rgba(buffer) => { multicolor = true; (gl::RGBA, Cow::Borrowed(buffer)) }, }; gl::TexSubImage2D( gl::TEXTURE_2D, 0, offset_x, offset_y, width, height, format, gl::UNSIGNED_BYTE, buffer.as_ptr() as *const _, ); gl::BindTexture(gl::TEXTURE_2D, 0); *active_tex = 0; } // Update Atlas state. self.row_extent = offset_x + width; if height > self.row_tallest { self.row_tallest = height; } // Generate UV coordinates. let uv_bot = offset_y as f32 / self.height as f32; let uv_left = offset_x as f32 / self.width as f32; let uv_height = height as f32 / self.height as f32; let uv_width = width as f32 / self.width as f32; Glyph { tex_id: self.id, multicolor, top: glyph.top as i16, left: glyph.left as i16, width: width as i16, height: height as i16, uv_bot, uv_left, uv_width, uv_height, } } /// Check if there's room in the current row for given glyph. pub fn room_in_row(&self, raw: &RasterizedGlyph) -> bool { let next_extent = self.row_extent + raw.width; let enough_width = next_extent <= self.width; let enough_height = raw.height < (self.height - self.row_baseline); enough_width && enough_height } /// Mark current row as finished and prepare to insert into the next row. pub fn advance_row(&mut self) -> Result<(), AtlasInsertError> { let advance_to = self.row_baseline + self.row_tallest; if self.height - advance_to <= 0 { return Err(AtlasInsertError::Full); } self.row_baseline = advance_to; self.row_extent = 0; self.row_tallest = 0; Ok(()) } /// Load a glyph into a texture atlas. /// /// If the current atlas is full, a new one will be created. #[inline] pub fn load_glyph( active_tex: &mut GLuint, atlas: &mut Vec<Atlas>, current_atlas: &mut usize, rasterized: &RasterizedGlyph, ) -> Glyph { // At least one atlas is guaranteed to be in the `self.atlas` list; thus // the unwrap. match atlas[*current_atlas].insert(rasterized, active_tex) { Ok(glyph) => glyph, Err(AtlasInsertError::Full) => { // Get the context type before adding a new Atlas. let is_gles_context = atlas[*current_atlas].is_gles_context; // Advance the current Atlas index. *current_atlas += 1; if *current_atlas == atlas.len() { let new = Atlas::new(ATLAS_SIZE, is_gles_context); *active_tex = 0; // Atlas::new binds a texture. Ugh this is sloppy. atlas.push(new); } Atlas::load_glyph(active_tex, atlas, current_atlas, rasterized) }, Err(AtlasInsertError::GlyphTooLarge) => Glyph { tex_id: atlas[*current_atlas].id, multicolor: false, top: 0, left: 0, width: 0, height: 0, uv_bot: 0., uv_left: 0., uv_width: 0., uv_height: 0., }, } } #[inline] pub fn clear_atlas(atlas: &mut [Atlas], current_atlas: &mut usize) { for atlas in atlas.iter_mut() { atlas.clear(); } *current_atlas = 0; } } impl Drop for Atlas { fn drop(&mut self) { unsafe { gl::DeleteTextures(1, &self.id); } } }
rust
Apache-2.0
6ee6e53ee3457c24137f117237b0ff1d84f6f836
2026-01-04T15:31:58.707223Z
false
alacritty/alacritty
https://github.com/alacritty/alacritty/blob/6ee6e53ee3457c24137f117237b0ff1d84f6f836/alacritty/src/renderer/text/mod.rs
alacritty/src/renderer/text/mod.rs
use bitflags::bitflags; use crossfont::{GlyphKey, RasterizedGlyph}; use alacritty_terminal::term::cell::Flags; use crate::display::SizeInfo; use crate::display::content::RenderableCell; use crate::gl; use crate::gl::types::*; mod atlas; mod builtin_font; mod gles2; mod glsl3; pub mod glyph_cache; use atlas::Atlas; pub use gles2::Gles2Renderer; pub use glsl3::Glsl3Renderer; pub use glyph_cache::GlyphCache; use glyph_cache::{Glyph, LoadGlyph}; // NOTE: These flags must be in sync with their usage in the text.*.glsl shaders. bitflags! { #[repr(C)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] struct RenderingGlyphFlags: u8 { const COLORED = 0b0000_0001; const WIDE_CHAR = 0b0000_0010; } } /// Rendering passes, for both GLES2 and GLSL3 renderer. #[repr(u8)] enum RenderingPass { /// Rendering pass used to render background color in text shaders. Background = 0, /// The first pass to render text with both GLES2 and GLSL3 renderers. SubpixelPass1 = 1, /// The second pass to render text with GLES2 renderer. SubpixelPass2 = 2, /// The third pass to render text with GLES2 renderer. SubpixelPass3 = 3, } pub trait TextRenderer<'a> { type Shader: TextShader; type RenderBatch: TextRenderBatch; type RenderApi: TextRenderApi<Self::RenderBatch>; /// Get loader API for the renderer. fn loader_api(&mut self) -> LoaderApi<'_>; /// Draw cells. fn draw_cells<'b: 'a, I: Iterator<Item = RenderableCell>>( &'b mut self, size_info: &'b SizeInfo, glyph_cache: &'a mut GlyphCache, cells: I, ) { self.with_api(size_info, |mut api| { for cell in cells { api.draw_cell(cell, glyph_cache, size_info); } }) } fn with_api<'b: 'a, F, T>(&'b mut self, size_info: &'b SizeInfo, func: F) -> T where F: FnOnce(Self::RenderApi) -> T; fn program(&self) -> &Self::Shader; /// Resize the text rendering. fn resize(&self, size: &SizeInfo) { unsafe { let program = self.program(); gl::UseProgram(program.id()); update_projection(program.projection_uniform(), size); gl::UseProgram(0); } } /// Invoke renderer with the loader. fn with_loader<F: FnOnce(LoaderApi<'_>) -> T, T>(&mut self, func: F) -> T { unsafe { gl::ActiveTexture(gl::TEXTURE0); } func(self.loader_api()) } } pub trait TextRenderBatch { /// Check if `Batch` is empty. fn is_empty(&self) -> bool; /// Check whether the `Batch` is full. fn full(&self) -> bool; /// Get texture `Batch` is using. fn tex(&self) -> GLuint; /// Add item to the batch. fn add_item(&mut self, cell: &RenderableCell, glyph: &Glyph, size_info: &SizeInfo); } pub trait TextRenderApi<T: TextRenderBatch>: LoadGlyph { /// Get `Batch` the api is using. fn batch(&mut self) -> &mut T; /// Render the underlying data. fn render_batch(&mut self); /// Add item to the rendering queue. #[inline] fn add_render_item(&mut self, cell: &RenderableCell, glyph: &Glyph, size_info: &SizeInfo) { // Flush batch if tex changing. if !self.batch().is_empty() && self.batch().tex() != glyph.tex_id { self.render_batch(); } self.batch().add_item(cell, glyph, size_info); // Render batch and clear if it's full. if self.batch().full() { self.render_batch(); } } /// Draw cell. fn draw_cell( &mut self, mut cell: RenderableCell, glyph_cache: &mut GlyphCache, size_info: &SizeInfo, ) { // Get font key for cell. let font_key = match cell.flags & Flags::BOLD_ITALIC { Flags::BOLD_ITALIC => glyph_cache.bold_italic_key, Flags::ITALIC => glyph_cache.italic_key, Flags::BOLD => glyph_cache.bold_key, _ => glyph_cache.font_key, }; // Ignore hidden cells and render tabs as spaces to prevent font issues. let hidden = cell.flags.contains(Flags::HIDDEN); if cell.character == '\t' || hidden { cell.character = ' '; } let mut glyph_key = GlyphKey { font_key, size: glyph_cache.font_size, character: cell.character }; // Add cell to batch. let glyph = glyph_cache.get(glyph_key, self, true); self.add_render_item(&cell, &glyph, size_info); // Render visible zero-width characters. if let Some(zerowidth) = cell.extra.as_mut().and_then(|extra| extra.zerowidth.take().filter(|_| !hidden)) { for character in zerowidth { glyph_key.character = character; let glyph = glyph_cache.get(glyph_key, self, false); self.add_render_item(&cell, &glyph, size_info); } } } } pub trait TextShader { fn id(&self) -> GLuint; /// Id of the projection uniform. fn projection_uniform(&self) -> GLint; } #[derive(Debug)] pub struct LoaderApi<'a> { active_tex: &'a mut GLuint, atlas: &'a mut Vec<Atlas>, current_atlas: &'a mut usize, } impl LoadGlyph for LoaderApi<'_> { fn load_glyph(&mut self, rasterized: &RasterizedGlyph) -> Glyph { Atlas::load_glyph(self.active_tex, self.atlas, self.current_atlas, rasterized) } fn clear(&mut self) { Atlas::clear_atlas(self.atlas, self.current_atlas) } } fn update_projection(u_projection: GLint, size: &SizeInfo) { let width = size.width(); let height = size.height(); let padding_x = size.padding_x(); let padding_y = size.padding_y(); // Bounds check. if (width as u32) < (2 * padding_x as u32) || (height as u32) < (2 * padding_y as u32) { return; } // Compute scale and offset factors, from pixel to ndc space. Y is inverted. // [0, width - 2 * padding_x] to [-1, 1] // [height - 2 * padding_y, 0] to [-1, 1] let scale_x = 2. / (width - 2. * padding_x); let scale_y = -2. / (height - 2. * padding_y); let offset_x = -1.; let offset_y = 1.; unsafe { gl::Uniform4f(u_projection, offset_x, offset_y, scale_x, scale_y); } }
rust
Apache-2.0
6ee6e53ee3457c24137f117237b0ff1d84f6f836
2026-01-04T15:31:58.707223Z
false
alacritty/alacritty
https://github.com/alacritty/alacritty/blob/6ee6e53ee3457c24137f117237b0ff1d84f6f836/alacritty/src/renderer/text/glsl3.rs
alacritty/src/renderer/text/glsl3.rs
use std::mem::size_of; use std::ptr; use crossfont::RasterizedGlyph; use log::info; use alacritty_terminal::term::cell::Flags; use crate::display::SizeInfo; use crate::display::content::RenderableCell; use crate::gl; use crate::gl::types::*; use crate::renderer::Error; use crate::renderer::shader::{ShaderProgram, ShaderVersion}; use super::atlas::{ATLAS_SIZE, Atlas}; use super::{ Glyph, LoadGlyph, LoaderApi, RenderingGlyphFlags, RenderingPass, TextRenderApi, TextRenderBatch, TextRenderer, TextShader, }; // Shader source. pub const TEXT_SHADER_F: &str = include_str!("../../../res/glsl3/text.f.glsl"); const TEXT_SHADER_V: &str = include_str!("../../../res/glsl3/text.v.glsl"); /// Maximum items to be drawn in a batch. const BATCH_MAX: usize = 0x1_0000; #[derive(Debug)] pub struct Glsl3Renderer { program: TextShaderProgram, vao: GLuint, ebo: GLuint, vbo_instance: GLuint, atlas: Vec<Atlas>, current_atlas: usize, active_tex: GLuint, batch: Batch, } impl Glsl3Renderer { pub fn new() -> Result<Self, Error> { info!("Using OpenGL 3.3 renderer"); let program = TextShaderProgram::new(ShaderVersion::Glsl3)?; let mut vao: GLuint = 0; let mut ebo: GLuint = 0; let mut vbo_instance: GLuint = 0; unsafe { gl::Enable(gl::BLEND); gl::BlendFunc(gl::SRC1_COLOR, gl::ONE_MINUS_SRC1_COLOR); // Disable depth mask, as the renderer never uses depth tests. gl::DepthMask(gl::FALSE); gl::GenVertexArrays(1, &mut vao); gl::GenBuffers(1, &mut ebo); gl::GenBuffers(1, &mut vbo_instance); gl::BindVertexArray(vao); // --------------------- // Set up element buffer // --------------------- let indices: [u32; 6] = [0, 1, 3, 1, 2, 3]; gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, ebo); gl::BufferData( gl::ELEMENT_ARRAY_BUFFER, (6 * size_of::<u32>()) as isize, indices.as_ptr() as *const _, gl::STATIC_DRAW, ); // ---------------------------- // Setup vertex instance buffer // ---------------------------- gl::BindBuffer(gl::ARRAY_BUFFER, vbo_instance); gl::BufferData( gl::ARRAY_BUFFER, (BATCH_MAX * size_of::<InstanceData>()) as isize, ptr::null(), gl::STREAM_DRAW, ); let mut index = 0; let mut size = 0; macro_rules! add_attr { ($count:expr, $gl_type:expr, $type:ty) => { gl::VertexAttribPointer( index, $count, $gl_type, gl::FALSE, size_of::<InstanceData>() as i32, size as *const _, ); gl::EnableVertexAttribArray(index); gl::VertexAttribDivisor(index, 1); #[allow(unused_assignments)] { size += $count * size_of::<$type>(); index += 1; } }; } // Coords. add_attr!(2, gl::UNSIGNED_SHORT, u16); // Glyph offset and size. add_attr!(4, gl::SHORT, i16); // UV offset. add_attr!(4, gl::FLOAT, f32); // Color and cell flags. // // These are packed together because of an OpenGL driver issue on macOS, which caused a // `vec3(u8)` text color and a `u8` cell flags to increase the rendering time by a // huge margin. add_attr!(4, gl::UNSIGNED_BYTE, u8); // Background color. add_attr!(4, gl::UNSIGNED_BYTE, u8); // Cleanup. gl::BindVertexArray(0); gl::BindBuffer(gl::ARRAY_BUFFER, 0); gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, 0); } Ok(Self { program, vao, ebo, vbo_instance, atlas: vec![Atlas::new(ATLAS_SIZE, false)], current_atlas: 0, active_tex: 0, batch: Batch::new(), }) } } impl<'a> TextRenderer<'a> for Glsl3Renderer { type RenderApi = RenderApi<'a>; type RenderBatch = Batch; type Shader = TextShaderProgram; fn with_api<'b: 'a, F, T>(&'b mut self, size_info: &'b SizeInfo, func: F) -> T where F: FnOnce(Self::RenderApi) -> T, { unsafe { gl::UseProgram(self.program.id()); self.program.set_term_uniforms(size_info); gl::BindVertexArray(self.vao); gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, self.ebo); gl::BindBuffer(gl::ARRAY_BUFFER, self.vbo_instance); gl::ActiveTexture(gl::TEXTURE0); } let res = func(RenderApi { active_tex: &mut self.active_tex, batch: &mut self.batch, atlas: &mut self.atlas, current_atlas: &mut self.current_atlas, program: &mut self.program, }); unsafe { gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, 0); gl::BindBuffer(gl::ARRAY_BUFFER, 0); gl::BindVertexArray(0); gl::UseProgram(0); } res } fn program(&self) -> &Self::Shader { &self.program } fn loader_api(&mut self) -> LoaderApi<'_> { LoaderApi { active_tex: &mut self.active_tex, atlas: &mut self.atlas, current_atlas: &mut self.current_atlas, } } } impl Drop for Glsl3Renderer { fn drop(&mut self) { unsafe { gl::DeleteBuffers(1, &self.vbo_instance); gl::DeleteBuffers(1, &self.ebo); gl::DeleteVertexArrays(1, &self.vao); } } } #[derive(Debug)] pub struct RenderApi<'a> { active_tex: &'a mut GLuint, batch: &'a mut Batch, atlas: &'a mut Vec<Atlas>, current_atlas: &'a mut usize, program: &'a mut TextShaderProgram, } impl TextRenderApi<Batch> for RenderApi<'_> { fn batch(&mut self) -> &mut Batch { self.batch } fn render_batch(&mut self) { unsafe { gl::BufferSubData( gl::ARRAY_BUFFER, 0, self.batch.size() as isize, self.batch.instances.as_ptr() as *const _, ); } // Bind texture if necessary. if *self.active_tex != self.batch.tex() { unsafe { gl::BindTexture(gl::TEXTURE_2D, self.batch.tex()); } *self.active_tex = self.batch.tex(); } unsafe { self.program.set_rendering_pass(RenderingPass::Background); gl::DrawElementsInstanced( gl::TRIANGLES, 6, gl::UNSIGNED_INT, ptr::null(), self.batch.len() as GLsizei, ); self.program.set_rendering_pass(RenderingPass::SubpixelPass1); gl::DrawElementsInstanced( gl::TRIANGLES, 6, gl::UNSIGNED_INT, ptr::null(), self.batch.len() as GLsizei, ); } self.batch.clear(); } } impl LoadGlyph for RenderApi<'_> { fn load_glyph(&mut self, rasterized: &RasterizedGlyph) -> Glyph { Atlas::load_glyph(self.active_tex, self.atlas, self.current_atlas, rasterized) } fn clear(&mut self) { Atlas::clear_atlas(self.atlas, self.current_atlas) } } impl Drop for RenderApi<'_> { fn drop(&mut self) { if !self.batch.is_empty() { self.render_batch(); } } } #[derive(Debug)] #[repr(C)] struct InstanceData { // Coords. col: u16, row: u16, // Glyph offset. left: i16, top: i16, // Glyph size. width: i16, height: i16, // UV offset. uv_left: f32, uv_bot: f32, // uv scale. uv_width: f32, uv_height: f32, // Color. r: u8, g: u8, b: u8, // Cell flags like multicolor or fullwidth character. cell_flags: RenderingGlyphFlags, // Background color. bg_r: u8, bg_g: u8, bg_b: u8, bg_a: u8, } #[derive(Debug, Default)] pub struct Batch { tex: GLuint, instances: Vec<InstanceData>, } impl TextRenderBatch for Batch { #[inline] fn tex(&self) -> GLuint { self.tex } #[inline] fn full(&self) -> bool { self.capacity() == self.len() } #[inline] fn is_empty(&self) -> bool { self.len() == 0 } fn add_item(&mut self, cell: &RenderableCell, glyph: &Glyph, _: &SizeInfo) { if self.is_empty() { self.tex = glyph.tex_id; } let mut cell_flags = RenderingGlyphFlags::empty(); cell_flags.set(RenderingGlyphFlags::COLORED, glyph.multicolor); cell_flags.set(RenderingGlyphFlags::WIDE_CHAR, cell.flags.contains(Flags::WIDE_CHAR)); self.instances.push(InstanceData { col: cell.point.column.0 as u16, row: cell.point.line as u16, top: glyph.top, left: glyph.left, width: glyph.width, height: glyph.height, uv_bot: glyph.uv_bot, uv_left: glyph.uv_left, uv_width: glyph.uv_width, uv_height: glyph.uv_height, r: cell.fg.r, g: cell.fg.g, b: cell.fg.b, cell_flags, bg_r: cell.bg.r, bg_g: cell.bg.g, bg_b: cell.bg.b, bg_a: (cell.bg_alpha * 255.0) as u8, }); } } impl Batch { #[inline] pub fn new() -> Self { Self { tex: 0, instances: Vec::with_capacity(BATCH_MAX) } } #[inline] pub fn len(&self) -> usize { self.instances.len() } #[inline] pub fn capacity(&self) -> usize { BATCH_MAX } #[inline] pub fn size(&self) -> usize { self.len() * size_of::<InstanceData>() } pub fn clear(&mut self) { self.tex = 0; self.instances.clear(); } } /// Text drawing program. /// /// Uniforms are prefixed with "u", and vertex attributes are prefixed with "a". #[derive(Debug)] pub struct TextShaderProgram { /// Shader program. program: ShaderProgram, /// Projection scale and offset uniform. u_projection: GLint, /// Cell dimensions (pixels). u_cell_dim: GLint, /// Background pass flag. /// /// Rendering is split into two passes; one for backgrounds, and one for text. u_rendering_pass: GLint, } impl TextShaderProgram { pub fn new(shader_version: ShaderVersion) -> Result<TextShaderProgram, Error> { let program = ShaderProgram::new(shader_version, None, TEXT_SHADER_V, TEXT_SHADER_F)?; Ok(Self { u_projection: program.get_uniform_location(c"projection")?, u_cell_dim: program.get_uniform_location(c"cellDim")?, u_rendering_pass: program.get_uniform_location(c"renderingPass")?, program, }) } fn set_term_uniforms(&self, props: &SizeInfo) { unsafe { gl::Uniform2f(self.u_cell_dim, props.cell_width(), props.cell_height()); } } fn set_rendering_pass(&self, rendering_pass: RenderingPass) { let value = match rendering_pass { RenderingPass::Background | RenderingPass::SubpixelPass1 => rendering_pass as i32, _ => unreachable!("provided pass is not supported in GLSL3 renderer"), }; unsafe { gl::Uniform1i(self.u_rendering_pass, value); } } } impl TextShader for TextShaderProgram { fn id(&self) -> GLuint { self.program.id() } fn projection_uniform(&self) -> GLint { self.u_projection } }
rust
Apache-2.0
6ee6e53ee3457c24137f117237b0ff1d84f6f836
2026-01-04T15:31:58.707223Z
false
alacritty/alacritty
https://github.com/alacritty/alacritty/blob/6ee6e53ee3457c24137f117237b0ff1d84f6f836/alacritty/src/renderer/text/builtin_font.rs
alacritty/src/renderer/text/builtin_font.rs
//! Hand-rolled drawing of unicode characters that need to fully cover their character area. use std::{cmp, mem, ops}; use crossfont::{BitmapBuffer, Metrics, RasterizedGlyph}; use crate::config::ui_config::Delta; // Colors which are used for filling shade variants. const COLOR_FILL_ALPHA_STEP_1: Pixel = Pixel { _r: 192, _g: 192, _b: 192 }; const COLOR_FILL_ALPHA_STEP_2: Pixel = Pixel { _r: 128, _g: 128, _b: 128 }; const COLOR_FILL_ALPHA_STEP_3: Pixel = Pixel { _r: 64, _g: 64, _b: 64 }; /// Default color used for filling. const COLOR_FILL: Pixel = Pixel { _r: 255, _g: 255, _b: 255 }; const POWERLINE_TRIANGLE_LTR: char = '\u{e0b0}'; const POWERLINE_ARROW_LTR: char = '\u{e0b1}'; const POWERLINE_TRIANGLE_RTL: char = '\u{e0b2}'; const POWERLINE_ARROW_RTL: char = '\u{e0b3}'; /// Returns the rasterized glyph if the character is part of the built-in font. pub fn builtin_glyph( character: char, metrics: &Metrics, offset: &Delta<i8>, glyph_offset: &Delta<i8>, ) -> Option<RasterizedGlyph> { let mut glyph = match character { // Box drawing characters and block elements. '\u{2500}'..='\u{259f}' | '\u{1fb00}'..='\u{1fb3b}' | '\u{1fb82}'..='\u{1fb8b}' => { box_drawing(character, metrics, offset) }, // Powerline symbols: '','','','' POWERLINE_TRIANGLE_LTR..=POWERLINE_ARROW_RTL => { powerline_drawing(character, metrics, offset)? }, _ => return None, }; // Since we want to ignore `glyph_offset` for the built-in font, subtract it to compensate its // addition when loading glyphs in the renderer. glyph.left -= glyph_offset.x as i32; glyph.top -= glyph_offset.y as i32; Some(glyph) } fn box_drawing(character: char, metrics: &Metrics, offset: &Delta<i8>) -> RasterizedGlyph { // Ensure that width and height is at least one. let height = (metrics.line_height as i32 + offset.y as i32).max(1) as usize; let width = (metrics.average_advance as i32 + offset.x as i32).max(1) as usize; let stroke_size = calculate_stroke_size(width); let heavy_stroke_size = stroke_size * 2; // Certain symbols require larger canvas than the cell itself, since for proper contiguous // lines they require drawing on neighbour cells. So treat them specially early on and handle // 'normal' characters later. let mut canvas = match character { // Diagonals: '╱', '╲', '╳'. '\u{2571}'..='\u{2573}' => { // Last coordinates. let x_end = width as f32; let mut y_end = height as f32; let top = height as i32 + metrics.descent as i32 + stroke_size as i32; let height = height + 2 * stroke_size; let mut canvas = Canvas::new(width, height + 2 * stroke_size); // The offset that we should take into account when drawing, since we've enlarged // buffer vertically by twice of that amount. let y_offset = stroke_size as f32; y_end += y_offset; let k = y_end / x_end; let f_x = |x: f32, h: f32| -> f32 { -k * x + h + y_offset }; let g_x = |x: f32, h: f32| -> f32 { k * x + h + y_offset }; let from_x = 0.; let to_x = x_end + 1.; for stroke_size in 0..2 * stroke_size { let stroke_size = stroke_size as f32 / 2.; if character == '\u{2571}' || character == '\u{2573}' { let h = y_end - stroke_size; let from_y = f_x(from_x, h); let to_y = f_x(to_x, h); canvas.draw_line(from_x, from_y, to_x, to_y); } if character == '\u{2572}' || character == '\u{2573}' { let from_y = g_x(from_x, stroke_size); let to_y = g_x(to_x, stroke_size); canvas.draw_line(from_x, from_y, to_x, to_y); } } let buffer = BitmapBuffer::Rgb(canvas.into_raw()); return RasterizedGlyph { character, top, left: 0, height: height as i32, width: width as i32, buffer, advance: (width as i32, height as i32), }; }, _ => Canvas::new(width, height), }; match character { // Horizontal dashes: '┄', '┅', '┈', '┉', '╌', '╍'. '\u{2504}' | '\u{2505}' | '\u{2508}' | '\u{2509}' | '\u{254c}' | '\u{254d}' => { let (num_gaps, stroke_size) = match character { '\u{2504}' => (2, stroke_size), '\u{2505}' => (2, heavy_stroke_size), '\u{2508}' => (3, stroke_size), '\u{2509}' => (3, heavy_stroke_size), '\u{254c}' => (1, stroke_size), '\u{254d}' => (1, heavy_stroke_size), _ => unreachable!(), }; let dash_gap_len = cmp::max(width / 8, 1); let dash_len = cmp::max(width.saturating_sub(dash_gap_len * num_gaps) / (num_gaps + 1), 1); let y = canvas.y_center(); for gap in 0..=num_gaps { let x = cmp::min(gap * (dash_len + dash_gap_len), width); canvas.draw_h_line(x as f32, y, dash_len as f32, stroke_size); } }, // Vertical dashes: '┆', '┇', '┊', '┋', '╎', '╏'. '\u{2506}' | '\u{2507}' | '\u{250a}' | '\u{250b}' | '\u{254e}' | '\u{254f}' => { let (num_gaps, stroke_size) = match character { '\u{2506}' => (2, stroke_size), '\u{2507}' => (2, heavy_stroke_size), '\u{250a}' => (3, stroke_size), '\u{250b}' => (3, heavy_stroke_size), '\u{254e}' => (1, stroke_size), '\u{254f}' => (1, heavy_stroke_size), _ => unreachable!(), }; let dash_gap_len = cmp::max(height / 8, 1); let dash_len = cmp::max(height.saturating_sub(dash_gap_len * num_gaps) / (num_gaps + 1), 1); let x = canvas.x_center(); for gap in 0..=num_gaps { let y = cmp::min(gap * (dash_len + dash_gap_len), height); canvas.draw_v_line(x, y as f32, dash_len as f32, stroke_size); } }, // Horizontal lines: '─', '━', '╴', '╶', '╸', '╺'. // Vertical lines: '│', '┃', '╵', '╷', '╹', '╻'. // Light and heavy line box components: // '┌','┍','┎','┏','┐','┑','┒','┓','└','┕','┖','┗','┘','┙','┚','┛',├','┝','┞','┟','┠','┡', // '┢','┣','┤','┥','┦','┧','┨','┩','┪','┫','┬','┭','┮','┯','┰','┱','┲','┳','┴','┵','┶','┷', // '┸','┹','┺','┻','┼','┽','┾','┿','╀','╁','╂','╃','╄','╅','╆','╇','╈','╉','╊','╋'. // Mixed light and heavy lines: '╼', '╽', '╾', '╿'. '\u{2500}'..='\u{2503}' | '\u{250c}'..='\u{254b}' | '\u{2574}'..='\u{257f}' => { // Left horizontal line. let stroke_size_h1 = match character { '\u{2500}' | '\u{2510}' | '\u{2512}' | '\u{2518}' | '\u{251a}' | '\u{2524}' | '\u{2526}' | '\u{2527}' | '\u{2528}' | '\u{252c}' | '\u{252e}' | '\u{2530}' | '\u{2532}' | '\u{2534}' | '\u{2536}' | '\u{2538}' | '\u{253a}' | '\u{253c}' | '\u{253e}' | '\u{2540}' | '\u{2541}' | '\u{2542}' | '\u{2544}' | '\u{2546}' | '\u{254a}' | '\u{2574}' | '\u{257c}' => stroke_size, '\u{2501}' | '\u{2511}' | '\u{2513}' | '\u{2519}' | '\u{251b}' | '\u{2525}' | '\u{2529}' | '\u{252a}' | '\u{252b}' | '\u{252d}' | '\u{252f}' | '\u{2531}' | '\u{2533}' | '\u{2535}' | '\u{2537}' | '\u{2539}' | '\u{253b}' | '\u{253d}' | '\u{253f}' | '\u{2543}' | '\u{2545}' | '\u{2547}' | '\u{2548}' | '\u{2549}' | '\u{254b}' | '\u{2578}' | '\u{257e}' => heavy_stroke_size, _ => 0, }; // Right horizontal line. let stroke_size_h2 = match character { '\u{2500}' | '\u{250c}' | '\u{250e}' | '\u{2514}' | '\u{2516}' | '\u{251c}' | '\u{251e}' | '\u{251f}' | '\u{2520}' | '\u{252c}' | '\u{252d}' | '\u{2530}' | '\u{2531}' | '\u{2534}' | '\u{2535}' | '\u{2538}' | '\u{2539}' | '\u{253c}' | '\u{253d}' | '\u{2540}' | '\u{2541}' | '\u{2542}' | '\u{2543}' | '\u{2545}' | '\u{2549}' | '\u{2576}' | '\u{257e}' => stroke_size, '\u{2501}' | '\u{250d}' | '\u{250f}' | '\u{2515}' | '\u{2517}' | '\u{251d}' | '\u{2521}' | '\u{2522}' | '\u{2523}' | '\u{252e}' | '\u{252f}' | '\u{2532}' | '\u{2533}' | '\u{2536}' | '\u{2537}' | '\u{253a}' | '\u{253b}' | '\u{253e}' | '\u{253f}' | '\u{2544}' | '\u{2546}' | '\u{2547}' | '\u{2548}' | '\u{254a}' | '\u{254b}' | '\u{257a}' | '\u{257c}' => heavy_stroke_size, _ => 0, }; // Top vertical line. let stroke_size_v1 = match character { '\u{2502}' | '\u{2514}' | '\u{2515}' | '\u{2518}' | '\u{2519}' | '\u{251c}' | '\u{251d}' | '\u{251f}' | '\u{2522}' | '\u{2524}' | '\u{2525}' | '\u{2527}' | '\u{252a}' | '\u{2534}' | '\u{2535}' | '\u{2536}' | '\u{2537}' | '\u{253c}' | '\u{253d}' | '\u{253e}' | '\u{253f}' | '\u{2541}' | '\u{2545}' | '\u{2546}' | '\u{2548}' | '\u{2575}' | '\u{257d}' => stroke_size, '\u{2503}' | '\u{2516}' | '\u{2517}' | '\u{251a}' | '\u{251b}' | '\u{251e}' | '\u{2520}' | '\u{2521}' | '\u{2523}' | '\u{2526}' | '\u{2528}' | '\u{2529}' | '\u{252b}' | '\u{2538}' | '\u{2539}' | '\u{253a}' | '\u{253b}' | '\u{2540}' | '\u{2542}' | '\u{2543}' | '\u{2544}' | '\u{2547}' | '\u{2549}' | '\u{254a}' | '\u{254b}' | '\u{2579}' | '\u{257f}' => heavy_stroke_size, _ => 0, }; // Bottom vertical line. let stroke_size_v2 = match character { '\u{2502}' | '\u{250c}' | '\u{250d}' | '\u{2510}' | '\u{2511}' | '\u{251c}' | '\u{251d}' | '\u{251e}' | '\u{2521}' | '\u{2524}' | '\u{2525}' | '\u{2526}' | '\u{2529}' | '\u{252c}' | '\u{252d}' | '\u{252e}' | '\u{252f}' | '\u{253c}' | '\u{253d}' | '\u{253e}' | '\u{253f}' | '\u{2540}' | '\u{2543}' | '\u{2544}' | '\u{2547}' | '\u{2577}' | '\u{257f}' => stroke_size, '\u{2503}' | '\u{250e}' | '\u{250f}' | '\u{2512}' | '\u{2513}' | '\u{251f}' | '\u{2520}' | '\u{2522}' | '\u{2523}' | '\u{2527}' | '\u{2528}' | '\u{252a}' | '\u{252b}' | '\u{2530}' | '\u{2531}' | '\u{2532}' | '\u{2533}' | '\u{2541}' | '\u{2542}' | '\u{2545}' | '\u{2546}' | '\u{2548}' | '\u{2549}' | '\u{254a}' | '\u{254b}' | '\u{257b}' | '\u{257d}' => heavy_stroke_size, _ => 0, }; let x_v = canvas.x_center(); let y_h = canvas.y_center(); let v_line_bounds_top = canvas.v_line_bounds(x_v, stroke_size_v1); let v_line_bounds_bot = canvas.v_line_bounds(x_v, stroke_size_v2); let h_line_bounds_left = canvas.h_line_bounds(y_h, stroke_size_h1); let h_line_bounds_right = canvas.h_line_bounds(y_h, stroke_size_h2); let size_h1 = cmp::max(v_line_bounds_top.1 as i32, v_line_bounds_bot.1 as i32) as f32; let x_h = cmp::min(v_line_bounds_top.0 as i32, v_line_bounds_bot.0 as i32) as f32; let size_h2 = width as f32 - x_h; let size_v1 = cmp::max(h_line_bounds_left.1 as i32, h_line_bounds_right.1 as i32) as f32; let y_v = cmp::min(h_line_bounds_left.0 as i32, h_line_bounds_right.0 as i32) as f32; let size_v2 = height as f32 - y_v; // Left horizontal line. canvas.draw_h_line(0., y_h, size_h1, stroke_size_h1); // Right horizontal line. canvas.draw_h_line(x_h, y_h, size_h2, stroke_size_h2); // Top vertical line. canvas.draw_v_line(x_v, 0., size_v1, stroke_size_v1); // Bottom vertical line. canvas.draw_v_line(x_v, y_v, size_v2, stroke_size_v2); }, // Light and double line box components: // '═','║','╒','╓','╔','╕','╖','╗','╘','╙','╚','╛','╜','╝','╞','╟','╠','╡','╢','╣','╤','╥', // '╦','╧','╨','╩','╪','╫','╬'. '\u{2550}'..='\u{256c}' => { let v_lines = match character { '\u{2552}' | '\u{2555}' | '\u{2558}' | '\u{255b}' | '\u{255e}' | '\u{2561}' | '\u{2564}' | '\u{2567}' | '\u{256a}' => (canvas.x_center(), canvas.x_center()), _ => { let v_line_bounds = canvas.v_line_bounds(canvas.x_center(), stroke_size); let left_line = cmp::max(v_line_bounds.0 as i32 - 1, 0) as f32; let right_line = cmp::min(v_line_bounds.1 as i32 + 1, width as i32) as f32; (left_line, right_line) }, }; let h_lines = match character { '\u{2553}' | '\u{2556}' | '\u{2559}' | '\u{255c}' | '\u{255f}' | '\u{2562}' | '\u{2565}' | '\u{2568}' | '\u{256b}' => (canvas.y_center(), canvas.y_center()), _ => { let h_line_bounds = canvas.h_line_bounds(canvas.y_center(), stroke_size); let top_line = cmp::max(h_line_bounds.0 as i32 - 1, 0) as f32; let bottom_line = cmp::min(h_line_bounds.1 as i32 + 1, height as i32) as f32; (top_line, bottom_line) }, }; // Get bounds for each double line we could have. let v_left_bounds = canvas.v_line_bounds(v_lines.0, stroke_size); let v_right_bounds = canvas.v_line_bounds(v_lines.1, stroke_size); let h_top_bounds = canvas.h_line_bounds(h_lines.0, stroke_size); let h_bot_bounds = canvas.h_line_bounds(h_lines.1, stroke_size); let height = height as f32; let width = width as f32; // Left horizontal part. let (top_left_size, bot_left_size) = match character { '\u{2550}' | '\u{256b}' => (canvas.x_center(), canvas.x_center()), '\u{2555}'..='\u{2557}' => (v_right_bounds.1, v_left_bounds.1), '\u{255b}'..='\u{255d}' => (v_left_bounds.1, v_right_bounds.1), '\u{2561}'..='\u{2563}' | '\u{256a}' | '\u{256c}' => { (v_left_bounds.1, v_left_bounds.1) }, '\u{2564}'..='\u{2568}' => (canvas.x_center(), v_left_bounds.1), '\u{2569}'..='\u{2569}' => (v_left_bounds.1, canvas.x_center()), _ => (0., 0.), }; // Right horizontal part. let (top_right_x, bot_right_x, right_size) = match character { '\u{2550}' | '\u{2565}' | '\u{256b}' => { (canvas.x_center(), canvas.x_center(), width) }, '\u{2552}'..='\u{2554}' | '\u{2568}' => (v_left_bounds.0, v_right_bounds.0, width), '\u{2558}'..='\u{255a}' => (v_right_bounds.0, v_left_bounds.0, width), '\u{255e}'..='\u{2560}' | '\u{256a}' | '\u{256c}' => { (v_right_bounds.0, v_right_bounds.0, width) }, '\u{2564}' | '\u{2566}' => (canvas.x_center(), v_right_bounds.0, width), '\u{2567}' | '\u{2569}' => (v_right_bounds.0, canvas.x_center(), width), _ => (0., 0., 0.), }; // Top vertical part. let (left_top_size, right_top_size) = match character { '\u{2551}' | '\u{256a}' => (canvas.y_center(), canvas.y_center()), '\u{2558}'..='\u{255c}' | '\u{2568}' => (h_bot_bounds.1, h_top_bounds.1), '\u{255d}' => (h_top_bounds.1, h_bot_bounds.1), '\u{255e}'..='\u{2560}' => (canvas.y_center(), h_top_bounds.1), '\u{2561}'..='\u{2563}' => (h_top_bounds.1, canvas.y_center()), '\u{2567}' | '\u{2569}' | '\u{256b}' | '\u{256c}' => { (h_top_bounds.1, h_top_bounds.1) }, _ => (0., 0.), }; // Bottom vertical part. let (left_bot_y, right_bot_y, bottom_size) = match character { '\u{2551}' | '\u{256a}' => (canvas.y_center(), canvas.y_center(), height), '\u{2552}'..='\u{2554}' => (h_top_bounds.0, h_bot_bounds.0, height), '\u{2555}'..='\u{2557}' => (h_bot_bounds.0, h_top_bounds.0, height), '\u{255e}'..='\u{2560}' => (canvas.y_center(), h_bot_bounds.0, height), '\u{2561}'..='\u{2563}' => (h_bot_bounds.0, canvas.y_center(), height), '\u{2564}'..='\u{2566}' | '\u{256b}' | '\u{256c}' => { (h_bot_bounds.0, h_bot_bounds.0, height) }, _ => (0., 0., 0.), }; // Left horizontal line. canvas.draw_h_line(0., h_lines.0, top_left_size, stroke_size); canvas.draw_h_line(0., h_lines.1, bot_left_size, stroke_size); // Right horizontal line. canvas.draw_h_line(top_right_x, h_lines.0, right_size, stroke_size); canvas.draw_h_line(bot_right_x, h_lines.1, right_size, stroke_size); // Top vertical line. canvas.draw_v_line(v_lines.0, 0., left_top_size, stroke_size); canvas.draw_v_line(v_lines.1, 0., right_top_size, stroke_size); // Bottom vertical line. canvas.draw_v_line(v_lines.0, left_bot_y, bottom_size, stroke_size); canvas.draw_v_line(v_lines.1, right_bot_y, bottom_size, stroke_size); }, // Arcs: '╭', '╮', '╯', '╰'. '\u{256d}' | '\u{256e}' | '\u{256f}' | '\u{2570}' => { canvas.draw_rounded_corner(stroke_size); // Mirror `X` axis. if character == '\u{256d}' || character == '\u{2570}' { let center = canvas.x_center() as usize; let extra_offset = usize::from(stroke_size % 2 != width % 2); let buffer = canvas.buffer_mut(); for y in 1..height { let left = (y - 1) * width; let right = y * width - 1; if extra_offset != 0 { buffer[right] = buffer[left]; } for offset in 0..center { buffer.swap(left + offset, right - offset - extra_offset); } } } // Mirror `Y` axis. if character == '\u{256d}' || character == '\u{256e}' { let center = canvas.y_center() as usize; let extra_offset = usize::from(stroke_size % 2 != height % 2); let buffer = canvas.buffer_mut(); if extra_offset != 0 { let bottom_row = (height - 1) * width; for index in 0..width { buffer[bottom_row + index] = buffer[index]; } } for offset in 1..=center { let top_row = (offset - 1) * width; let bottom_row = (height - offset - extra_offset) * width; for index in 0..width { buffer.swap(top_row + index, bottom_row + index); } } } }, // Parts of full block: '▀', '▁', '▂', '▃', '▄', '▅', '▆', '▇', '▔', '▉', '▊', '▋', '▌', // '▍', '▎', '▏', '▐', '▕', '🮂', '🮃', '🮄', '🮅', '🮆', '🮇', '🮈', '🮉', '🮊', '🮋'. '\u{2580}'..='\u{2587}' | '\u{2589}'..='\u{2590}' | '\u{2594}' | '\u{2595}' | '\u{1fb82}'..='\u{1fb8b}' => { let width = width as f32; let height = height as f32; let mut rect_width = match character { '\u{2589}' | '\u{1fb8b}' => width * 7. / 8., '\u{258a}' | '\u{1fb8a}' => width * 6. / 8., '\u{258b}' | '\u{1fb89}' => width * 5. / 8., '\u{258c}' => width * 4. / 8., '\u{258d}' | '\u{1fb88}' => width * 3. / 8., '\u{258e}' | '\u{1fb87}' => width * 2. / 8., '\u{258f}' => width * 1. / 8., '\u{2590}' => width * 4. / 8., '\u{2595}' => width * 1. / 8., _ => width, }; let (mut rect_height, mut y) = match character { '\u{2580}' => (height * 4. / 8., height * 8. / 8.), '\u{2581}' => (height * 1. / 8., height * 1. / 8.), '\u{2582}' => (height * 2. / 8., height * 2. / 8.), '\u{2583}' => (height * 3. / 8., height * 3. / 8.), '\u{2584}' => (height * 4. / 8., height * 4. / 8.), '\u{2585}' => (height * 5. / 8., height * 5. / 8.), '\u{2586}' => (height * 6. / 8., height * 6. / 8.), '\u{2587}' => (height * 7. / 8., height * 7. / 8.), '\u{2594}' => (height * 1. / 8., height * 8. / 8.), '\u{1fb82}' => (height * 2. / 8., height * 8. / 8.), '\u{1fb83}' => (height * 3. / 8., height * 8. / 8.), '\u{1fb84}' => (height * 5. / 8., height * 8. / 8.), '\u{1fb85}' => (height * 6. / 8., height * 8. / 8.), '\u{1fb86}' => (height * 7. / 8., height * 8. / 8.), _ => (height, height), }; // Fix `y` coordinates. y = (height - y).round(); // Ensure that resulted glyph will be visible and also round sizes instead of straight // flooring them. rect_width = rect_width.round().max(1.); rect_height = rect_height.round().max(1.); let x = match character { '\u{2590}' => canvas.x_center(), '\u{2595}' | '\u{1fb87}'..='\u{1fb8b}' => width - rect_width, _ => 0., }; canvas.draw_rect(x, y, rect_width, rect_height, COLOR_FILL); }, // Shades: '░', '▒', '▓', '█'. '\u{2588}' | '\u{2591}' | '\u{2592}' | '\u{2593}' => { let color = match character { '\u{2588}' => COLOR_FILL, '\u{2591}' => COLOR_FILL_ALPHA_STEP_3, '\u{2592}' => COLOR_FILL_ALPHA_STEP_2, '\u{2593}' => COLOR_FILL_ALPHA_STEP_1, _ => unreachable!(), }; canvas.fill(color); }, // Quadrants: '▖', '▗', '▘', '▙', '▚', '▛', '▜', '▝', '▞', '▟'. '\u{2596}'..='\u{259F}' => { let x_center = canvas.x_center().round().max(1.); let y_center = canvas.y_center().round().max(1.); let (w_second, h_second) = match character { '\u{2598}' | '\u{2599}' | '\u{259a}' | '\u{259b}' | '\u{259c}' => { (x_center, y_center) }, _ => (0., 0.), }; let (w_first, h_first) = match character { '\u{259b}' | '\u{259c}' | '\u{259d}' | '\u{259e}' | '\u{259f}' => { (x_center, y_center) }, _ => (0., 0.), }; let (w_third, h_third) = match character { '\u{2596}' | '\u{2599}' | '\u{259b}' | '\u{259e}' | '\u{259f}' => { (x_center, y_center) }, _ => (0., 0.), }; let (w_fourth, h_fourth) = match character { '\u{2597}' | '\u{2599}' | '\u{259a}' | '\u{259c}' | '\u{259f}' => { (x_center, y_center) }, _ => (0., 0.), }; // Second quadrant. canvas.draw_rect(0., 0., w_second, h_second, COLOR_FILL); // First quadrant. canvas.draw_rect(x_center, 0., w_first, h_first, COLOR_FILL); // Third quadrant. canvas.draw_rect(0., y_center, w_third, h_third, COLOR_FILL); // Fourth quadrant. canvas.draw_rect(x_center, y_center, w_fourth, h_fourth, COLOR_FILL); }, // Sextants: '🬀', '🬁', '🬂', '🬃', '🬄', '🬅', '🬆', '🬇', '🬈', '🬉', '🬊', '🬋', '🬌', '🬍', '🬎', // '🬏', '🬐', '🬑', '🬒', '🬓', '🬔', '🬕', '🬖', '🬗', '🬘', '🬙', '🬚', '🬛', '🬜', '🬝', '🬞', '🬟', // '🬠', '🬡', '🬢', '🬣', '🬤', '🬥', '🬦', '🬧', '🬨', '🬩', '🬪', '🬫', '🬬', '🬭', '🬮', '🬯', '🬰', // '🬱', '🬲', '🬳', '🬴', '🬵', '🬶', '🬷', '🬸', '🬹', '🬺', '🬻'. '\u{1fb00}'..='\u{1fb3b}' => { let x_center = canvas.x_center().round().max(1.); let y_third = (height as f32 / 3.).round().max(1.); let y_last_third = height as f32 - 2. * y_third; let (w_top_left, h_top_left) = match character { '\u{1fb00}' | '\u{1fb02}' | '\u{1fb04}' | '\u{1fb06}' | '\u{1fb08}' | '\u{1fb0a}' | '\u{1fb0c}' | '\u{1fb0e}' | '\u{1fb10}' | '\u{1fb12}' | '\u{1fb15}' | '\u{1fb17}' | '\u{1fb19}' | '\u{1fb1b}' | '\u{1fb1d}' | '\u{1fb1f}' | '\u{1fb21}' | '\u{1fb23}' | '\u{1fb25}' | '\u{1fb27}' | '\u{1fb28}' | '\u{1fb2a}' | '\u{1fb2c}' | '\u{1fb2e}' | '\u{1fb30}' | '\u{1fb32}' | '\u{1fb34}' | '\u{1fb36}' | '\u{1fb38}' | '\u{1fb3a}' => { (x_center, y_third) }, _ => (0., 0.), }; let (w_top_right, h_top_right) = match character { '\u{1fb01}' | '\u{1fb02}' | '\u{1fb05}' | '\u{1fb06}' | '\u{1fb09}' | '\u{1fb0a}' | '\u{1fb0d}' | '\u{1fb0e}' | '\u{1fb11}' | '\u{1fb12}' | '\u{1fb14}' | '\u{1fb15}' | '\u{1fb18}' | '\u{1fb19}' | '\u{1fb1c}' | '\u{1fb1d}' | '\u{1fb20}' | '\u{1fb21}' | '\u{1fb24}' | '\u{1fb25}' | '\u{1fb28}' | '\u{1fb2b}' | '\u{1fb2c}' | '\u{1fb2f}' | '\u{1fb30}' | '\u{1fb33}' | '\u{1fb34}' | '\u{1fb37}' | '\u{1fb38}' | '\u{1fb3b}' => { (x_center, y_third) }, _ => (0., 0.), }; let (w_mid_left, h_mid_left) = match character { '\u{1fb03}' | '\u{1fb04}' | '\u{1fb05}' | '\u{1fb06}' | '\u{1fb0b}' | '\u{1fb0c}' | '\u{1fb0d}' | '\u{1fb0e}' | '\u{1fb13}' | '\u{1fb14}' | '\u{1fb15}' | '\u{1fb1a}' | '\u{1fb1b}' | '\u{1fb1c}' | '\u{1fb1d}' | '\u{1fb22}' | '\u{1fb23}' | '\u{1fb24}' | '\u{1fb25}' | '\u{1fb29}' | '\u{1fb2a}' | '\u{1fb2b}' | '\u{1fb2c}' | '\u{1fb31}' | '\u{1fb32}' | '\u{1fb33}' | '\u{1fb34}' | '\u{1fb39}' | '\u{1fb3a}' | '\u{1fb3b}' => { (x_center, y_third) }, _ => (0., 0.), }; let (w_mid_right, h_mid_right) = match character { '\u{1fb07}' | '\u{1fb08}' | '\u{1fb09}' | '\u{1fb0a}' | '\u{1fb0b}' | '\u{1fb0c}' | '\u{1fb0d}' | '\u{1fb0e}' | '\u{1fb16}' | '\u{1fb17}' | '\u{1fb18}' | '\u{1fb19}' | '\u{1fb1a}' | '\u{1fb1b}' | '\u{1fb1c}' | '\u{1fb1d}' | '\u{1fb26}' | '\u{1fb27}' | '\u{1fb28}' | '\u{1fb29}' | '\u{1fb2a}' | '\u{1fb2b}' | '\u{1fb2c}' | '\u{1fb35}' | '\u{1fb36}' | '\u{1fb37}' | '\u{1fb38}' | '\u{1fb39}' | '\u{1fb3a}' | '\u{1fb3b}' => { (x_center, y_third) }, _ => (0., 0.), }; let (w_bottom_left, h_bottom_left) = match character { '\u{1fb0f}' | '\u{1fb10}' | '\u{1fb11}' | '\u{1fb12}' | '\u{1fb13}' | '\u{1fb14}' | '\u{1fb15}' | '\u{1fb16}' | '\u{1fb17}' | '\u{1fb18}' | '\u{1fb19}' | '\u{1fb1a}' | '\u{1fb1b}' | '\u{1fb1c}' | '\u{1fb1d}' | '\u{1fb2d}' | '\u{1fb2e}' | '\u{1fb2f}' | '\u{1fb30}' | '\u{1fb31}' | '\u{1fb32}' | '\u{1fb33}' | '\u{1fb34}' | '\u{1fb35}' | '\u{1fb36}' | '\u{1fb37}' | '\u{1fb38}' | '\u{1fb39}' | '\u{1fb3a}' | '\u{1fb3b}' => { (x_center, y_last_third) }, _ => (0., 0.), }; let (w_bottom_right, h_bottom_right) = match character { '\u{1fb1e}' | '\u{1fb1f}' | '\u{1fb20}' | '\u{1fb21}' | '\u{1fb22}' | '\u{1fb23}' | '\u{1fb24}' | '\u{1fb25}' | '\u{1fb26}' | '\u{1fb27}' | '\u{1fb28}' | '\u{1fb29}' | '\u{1fb2a}' | '\u{1fb2b}' | '\u{1fb2c}' | '\u{1fb2d}' | '\u{1fb2e}' | '\u{1fb2f}' | '\u{1fb30}' | '\u{1fb31}' | '\u{1fb32}' | '\u{1fb33}' | '\u{1fb34}' | '\u{1fb35}' | '\u{1fb36}' | '\u{1fb37}' | '\u{1fb38}' | '\u{1fb39}' | '\u{1fb3a}' | '\u{1fb3b}' => { (x_center, y_last_third) }, _ => (0., 0.), }; canvas.draw_rect(0., 0., w_top_left, h_top_left, COLOR_FILL); canvas.draw_rect(x_center, 0., w_top_right, h_top_right, COLOR_FILL); canvas.draw_rect(0., y_third, w_mid_left, h_mid_left, COLOR_FILL); canvas.draw_rect(x_center, y_third, w_mid_right, h_mid_right, COLOR_FILL); canvas.draw_rect(0., y_third * 2., w_bottom_left, h_bottom_left, COLOR_FILL); canvas.draw_rect(x_center, y_third * 2., w_bottom_right, h_bottom_right, COLOR_FILL); }, _ => unreachable!(), } let top = height as i32 + metrics.descent as i32; let buffer = BitmapBuffer::Rgb(canvas.into_raw()); RasterizedGlyph { character, top, left: 0, height: height as i32, width: width as i32, buffer, advance: (width as i32, height as i32), } } fn powerline_drawing( character: char, metrics: &Metrics, offset: &Delta<i8>, ) -> Option<RasterizedGlyph> { let height = (metrics.line_height as i32 + offset.y as i32) as usize; let width = (metrics.average_advance as i32 + offset.x as i32) as usize; let extra_thickness = calculate_stroke_size(width) as i32 - 1; let mut canvas = Canvas::new(width, height); let slope = 1; let top_y = 1; let bottom_y = height as i32 - top_y - 1; // Start with offset `1` and draw until the intersection of the f(x) = slope * x + 1 and // g(x) = H - slope * x - 1 lines. The intersection happens when f(x) = g(x), which is at // x = (H - 2) / (2 * slope). let x_intersection = (height as i32 + 1) / 2 - 1; // Don't use built-in font if we'd cut the tip too much, for example when the font is really // narrow. if x_intersection - width as i32 > 1 { return None; } let top_line = (0..x_intersection).map(|x| line_equation(slope, x, top_y)); let bottom_line = (0..x_intersection).map(|x| line_equation(-slope, x, bottom_y)); // Inner lines to make arrows thicker. let mut top_inner_line = (0..x_intersection - extra_thickness) .map(|x| line_equation(slope, x, top_y + extra_thickness)); let mut bottom_inner_line = (0..x_intersection - extra_thickness) .map(|x| line_equation(-slope, x, bottom_y - extra_thickness)); // NOTE: top_line and bottom_line have the same amount of iterations. for (p1, p2) in top_line.zip(bottom_line) { if character == POWERLINE_TRIANGLE_LTR || character == POWERLINE_TRIANGLE_RTL { canvas.draw_rect(0., p1.1, p1.0 + 1., 1., COLOR_FILL); canvas.draw_rect(0., p2.1, p2.0 + 1., 1., COLOR_FILL); } else if character == POWERLINE_ARROW_LTR || character == POWERLINE_ARROW_RTL { let p3 = top_inner_line.next().unwrap_or(p2); let p4 = bottom_inner_line.next().unwrap_or(p1);
rust
Apache-2.0
6ee6e53ee3457c24137f117237b0ff1d84f6f836
2026-01-04T15:31:58.707223Z
true
alacritty/alacritty
https://github.com/alacritty/alacritty/blob/6ee6e53ee3457c24137f117237b0ff1d84f6f836/alacritty/src/display/meter.rs
alacritty/src/display/meter.rs
//! Rendering time meter. //! //! Used to track rendering times and provide moving averages. //! //! # Examples //! //! ```rust //! // create a meter //! let mut meter = alacritty_terminal::meter::Meter::new(); //! //! // Sample something. //! { //! let _sampler = meter.sampler(); //! } //! //! // Get the moving average. The meter tracks a fixed number of samples, and //! // the average won't mean much until it's filled up at least once. //! println!("Average time: {}", meter.average()); //! ``` use std::time::{Duration, Instant}; const NUM_SAMPLES: usize = 10; /// The meter. #[derive(Default)] pub struct Meter { /// Track last 60 timestamps. times: [f64; NUM_SAMPLES], /// Average sample time in microseconds. avg: f64, /// Index of next time to update. index: usize, } /// Sampler. /// /// Samplers record how long they are "alive" for and update the meter on drop.. pub struct Sampler<'a> { /// Reference to meter that created the sampler. meter: &'a mut Meter, /// When the sampler was created. created_at: Instant, } impl<'a> Sampler<'a> { fn new(meter: &'a mut Meter) -> Sampler<'a> { Sampler { meter, created_at: Instant::now() } } #[inline] fn alive_duration(&self) -> Duration { self.created_at.elapsed() } } impl Drop for Sampler<'_> { fn drop(&mut self) { self.meter.add_sample(self.alive_duration()); } } impl Meter { /// Get a sampler. pub fn sampler(&mut self) -> Sampler<'_> { Sampler::new(self) } /// Get the current average sample duration in microseconds. pub fn average(&self) -> f64 { self.avg } /// Add a sample. /// /// Used by Sampler::drop. fn add_sample(&mut self, sample: Duration) { let mut usec = 0f64; usec += f64::from(sample.subsec_nanos()) / 1e3; usec += (sample.as_secs() as f64) * 1e6; let prev = self.times[self.index]; self.times[self.index] = usec; self.avg -= prev / NUM_SAMPLES as f64; self.avg += usec / NUM_SAMPLES as f64; self.index = (self.index + 1) % NUM_SAMPLES; } }
rust
Apache-2.0
6ee6e53ee3457c24137f117237b0ff1d84f6f836
2026-01-04T15:31:58.707223Z
false
alacritty/alacritty
https://github.com/alacritty/alacritty/blob/6ee6e53ee3457c24137f117237b0ff1d84f6f836/alacritty/src/display/cursor.rs
alacritty/src/display/cursor.rs
//! Convert a cursor into an iterator of rects. use alacritty_terminal::vte::ansi::CursorShape; use crate::display::SizeInfo; use crate::display::color::Rgb; use crate::display::content::RenderableCursor; use crate::renderer::rects::RenderRect; /// Trait for conversion into the iterator. pub trait IntoRects { /// Consume the cursor for an iterator of rects. fn rects(self, size_info: &SizeInfo, thickness: f32) -> CursorRects; } impl IntoRects for RenderableCursor { fn rects(self, size_info: &SizeInfo, thickness: f32) -> CursorRects { let point = self.point(); let x = point.column.0 as f32 * size_info.cell_width() + size_info.padding_x(); let y = point.line as f32 * size_info.cell_height() + size_info.padding_y(); let mut width = size_info.cell_width(); let height = size_info.cell_height(); let thickness = (thickness * width).round().max(1.); width *= self.width().get() as f32; match self.shape() { CursorShape::Beam => beam(x, y, height, thickness, self.color()), CursorShape::Underline => underline(x, y, width, height, thickness, self.color()), CursorShape::HollowBlock => hollow(x, y, width, height, thickness, self.color()), _ => CursorRects::default(), } } } /// Cursor rect iterator. #[derive(Default)] pub struct CursorRects { rects: [Option<RenderRect>; 4], index: usize, } impl From<RenderRect> for CursorRects { fn from(rect: RenderRect) -> Self { Self { rects: [Some(rect), None, None, None], index: 0 } } } impl Iterator for CursorRects { type Item = RenderRect; fn next(&mut self) -> Option<Self::Item> { let rect = self.rects.get_mut(self.index)?; self.index += 1; rect.take() } } /// Create an iterator yielding a single beam rect. fn beam(x: f32, y: f32, height: f32, thickness: f32, color: Rgb) -> CursorRects { RenderRect::new(x, y, thickness, height, color, 1.).into() } /// Create an iterator yielding a single underline rect. fn underline(x: f32, y: f32, width: f32, height: f32, thickness: f32, color: Rgb) -> CursorRects { let y = y + height - thickness; RenderRect::new(x, y, width, thickness, color, 1.).into() } /// Create an iterator yielding a rect for each side of the hollow block cursor. fn hollow(x: f32, y: f32, width: f32, height: f32, thickness: f32, color: Rgb) -> CursorRects { let top_line = RenderRect::new(x, y, width, thickness, color, 1.); let vertical_y = y + thickness; let vertical_height = height - 2. * thickness; let left_line = RenderRect::new(x, vertical_y, thickness, vertical_height, color, 1.); let bottom_y = y + height - thickness; let bottom_line = RenderRect::new(x, bottom_y, width, thickness, color, 1.); let right_x = x + width - thickness; let right_line = RenderRect::new(right_x, vertical_y, thickness, vertical_height, color, 1.); CursorRects { rects: [Some(top_line), Some(bottom_line), Some(left_line), Some(right_line)], index: 0, } }
rust
Apache-2.0
6ee6e53ee3457c24137f117237b0ff1d84f6f836
2026-01-04T15:31:58.707223Z
false
alacritty/alacritty
https://github.com/alacritty/alacritty/blob/6ee6e53ee3457c24137f117237b0ff1d84f6f836/alacritty/src/display/bell.rs
alacritty/src/display/bell.rs
use std::time::{Duration, Instant}; use crate::config::bell::{BellAnimation, BellConfig}; pub struct VisualBell { /// Visual bell animation. animation: BellAnimation, /// Visual bell duration. duration: Duration, /// The last time the visual bell rang, if at all. start_time: Option<Instant>, } impl VisualBell { /// Ring the visual bell, and return its intensity. pub fn ring(&mut self) -> f64 { let now = Instant::now(); self.start_time = Some(now); self.intensity_at_instant(now) } /// Get the currently intensity of the visual bell. The bell's intensity /// ramps down from 1.0 to 0.0 at a rate determined by the bell's duration. pub fn intensity(&self) -> f64 { self.intensity_at_instant(Instant::now()) } /// Check whether or not the visual bell has completed "ringing". pub fn completed(&mut self) -> bool { match self.start_time { Some(earlier) => { if Instant::now().duration_since(earlier) >= self.duration { self.start_time = None; } false }, None => true, } } /// Get the intensity of the visual bell at a particular instant. The bell's /// intensity ramps down from 1.0 to 0.0 at a rate determined by the bell's /// duration. pub fn intensity_at_instant(&self, instant: Instant) -> f64 { // If `duration` is zero, then the VisualBell is disabled; therefore, // its `intensity` is zero. if self.duration == Duration::from_secs(0) { return 0.0; } match self.start_time { // Similarly, if `start_time` is `None`, then the VisualBell has not // been "rung"; therefore, its `intensity` is zero. None => 0.0, Some(earlier) => { // Finally, if the `instant` at which we wish to compute the // VisualBell's `intensity` occurred before the VisualBell was // "rung", then its `intensity` is also zero. if instant < earlier { return 0.0; } let elapsed = instant.duration_since(earlier); let elapsed_f = elapsed.as_secs() as f64 + f64::from(elapsed.subsec_nanos()) / 1e9f64; let duration_f = self.duration.as_secs() as f64 + f64::from(self.duration.subsec_nanos()) / 1e9f64; // Otherwise, we compute a value `time` from 0.0 to 1.0 // inclusive that represents the ratio of `elapsed` time to the // `duration` of the VisualBell. let time = (elapsed_f / duration_f).min(1.0); // We use this to compute the inverse `intensity` of the // VisualBell. When `time` is 0.0, `inverse_intensity` is 0.0, // and when `time` is 1.0, `inverse_intensity` is 1.0. let inverse_intensity = match self.animation { BellAnimation::Ease | BellAnimation::EaseOut => { cubic_bezier(0.25, 0.1, 0.25, 1.0, time) }, BellAnimation::EaseOutSine => cubic_bezier(0.39, 0.575, 0.565, 1.0, time), BellAnimation::EaseOutQuad => cubic_bezier(0.25, 0.46, 0.45, 0.94, time), BellAnimation::EaseOutCubic => cubic_bezier(0.215, 0.61, 0.355, 1.0, time), BellAnimation::EaseOutQuart => cubic_bezier(0.165, 0.84, 0.44, 1.0, time), BellAnimation::EaseOutQuint => cubic_bezier(0.23, 1.0, 0.32, 1.0, time), BellAnimation::EaseOutExpo => cubic_bezier(0.19, 1.0, 0.22, 1.0, time), BellAnimation::EaseOutCirc => cubic_bezier(0.075, 0.82, 0.165, 1.0, time), BellAnimation::Linear => time, }; // Since we want the `intensity` of the VisualBell to decay over // `time`, we subtract the `inverse_intensity` from 1.0. 1.0 - inverse_intensity }, } } pub fn update_config(&mut self, bell_config: &BellConfig) { self.animation = bell_config.animation; self.duration = bell_config.duration(); } } impl From<&BellConfig> for VisualBell { fn from(bell_config: &BellConfig) -> VisualBell { VisualBell { animation: bell_config.animation, duration: bell_config.duration(), start_time: None, } } } fn cubic_bezier(p0: f64, p1: f64, p2: f64, p3: f64, x: f64) -> f64 { (1.0 - x).powi(3) * p0 + 3.0 * (1.0 - x).powi(2) * x * p1 + 3.0 * (1.0 - x) * x.powi(2) * p2 + x.powi(3) * p3 }
rust
Apache-2.0
6ee6e53ee3457c24137f117237b0ff1d84f6f836
2026-01-04T15:31:58.707223Z
false
alacritty/alacritty
https://github.com/alacritty/alacritty/blob/6ee6e53ee3457c24137f117237b0ff1d84f6f836/alacritty/src/display/content.rs
alacritty/src/display/content.rs
use std::borrow::Cow; use std::num::NonZeroU32; use std::ops::Deref; use std::{cmp, mem}; use alacritty_terminal::event::EventListener; use alacritty_terminal::grid::{Dimensions, Indexed}; use alacritty_terminal::index::{Column, Line, Point}; use alacritty_terminal::selection::SelectionRange; use alacritty_terminal::term::cell::{Cell, Flags, Hyperlink}; use alacritty_terminal::term::search::{Match, RegexSearch}; use alacritty_terminal::term::{self, RenderableContent as TerminalContent, Term, TermMode}; use alacritty_terminal::vte::ansi::{Color, CursorShape, NamedColor}; use crate::config::UiConfig; use crate::display::color::{CellRgb, DIM_FACTOR, List, Rgb}; use crate::display::hint::{self, HintState}; use crate::display::{Display, SizeInfo}; use crate::event::SearchState; /// Minimum contrast between a fixed cursor color and the cell's background. pub const MIN_CURSOR_CONTRAST: f64 = 1.5; /// Renderable terminal content. /// /// This provides the terminal cursor and an iterator over all non-empty cells. pub struct RenderableContent<'a> { terminal_content: TerminalContent<'a>, cursor: RenderableCursor, cursor_shape: CursorShape, cursor_point: Point<usize>, search: Option<HintMatches<'a>>, hint: Option<Hint<'a>>, config: &'a UiConfig, colors: &'a List, focused_match: Option<&'a Match>, size: &'a SizeInfo, } impl<'a> RenderableContent<'a> { pub fn new<T: EventListener>( config: &'a UiConfig, display: &'a mut Display, term: &'a Term<T>, search_state: &'a mut SearchState, ) -> Self { let search = search_state.dfas().map(|dfas| HintMatches::visible_regex_matches(term, dfas)); let focused_match = search_state.focused_match(); let terminal_content = term.renderable_content(); // Find terminal cursor shape. let cursor_shape = if terminal_content.cursor.shape == CursorShape::Hidden || display.cursor_hidden || search_state.regex().is_some() || display.ime.preedit().is_some() { CursorShape::Hidden } else if !term.is_focused && config.cursor.unfocused_hollow { CursorShape::HollowBlock } else { terminal_content.cursor.shape }; // Convert terminal cursor point to viewport position. let cursor_point = terminal_content.cursor.point; let display_offset = terminal_content.display_offset; let cursor_point = term::point_to_viewport(display_offset, cursor_point).unwrap(); let hint = if display.hint_state.active() { display.hint_state.update_matches(term); Some(Hint::from(&display.hint_state)) } else { None }; Self { colors: &display.colors, size: &display.size_info, cursor: RenderableCursor::new_hidden(), terminal_content, focused_match, cursor_shape, cursor_point, search, config, hint, } } /// Viewport offset. pub fn display_offset(&self) -> usize { self.terminal_content.display_offset } /// Get the terminal cursor. pub fn cursor(mut self) -> RenderableCursor { // Assure this function is only called after the iterator has been drained. debug_assert!(self.next().is_none()); self.cursor } /// Get the RGB value for a color index. pub fn color(&self, color: usize) -> Rgb { self.terminal_content.colors[color].map(Rgb).unwrap_or(self.colors[color]) } pub fn selection_range(&self) -> Option<SelectionRange> { self.terminal_content.selection } /// Assemble the information required to render the terminal cursor. fn renderable_cursor(&mut self, cell: &RenderableCell) -> RenderableCursor { // Cursor colors. let color = if self.terminal_content.mode.contains(TermMode::VI) { self.config.colors.vi_mode_cursor } else { self.config.colors.cursor }; let cursor_color = self.terminal_content.colors[NamedColor::Cursor] .map_or(color.background, |c| CellRgb::Rgb(Rgb(c))); let text_color = color.foreground; let insufficient_contrast = (!matches!(cursor_color, CellRgb::Rgb(_)) || !matches!(text_color, CellRgb::Rgb(_))) && cell.fg.contrast(*cell.bg) < MIN_CURSOR_CONTRAST; // Convert from cell colors to RGB. let mut text_color = text_color.color(cell.fg, cell.bg); let mut cursor_color = cursor_color.color(cell.fg, cell.bg); // Invert cursor color with insufficient contrast to prevent invisible cursors. if insufficient_contrast { cursor_color = self.config.colors.primary.foreground; text_color = self.config.colors.primary.background; } let width = if cell.flags.contains(Flags::WIDE_CHAR) { NonZeroU32::new(2).unwrap() } else { NonZeroU32::new(1).unwrap() }; RenderableCursor { width, shape: self.cursor_shape, point: self.cursor_point, cursor_color, text_color, } } } impl Iterator for RenderableContent<'_> { type Item = RenderableCell; /// Gets the next renderable cell. /// /// Skips empty (background) cells and applies any flags to the cell state /// (eg. invert fg and bg colors). #[inline] fn next(&mut self) -> Option<Self::Item> { loop { let cell = self.terminal_content.display_iter.next()?; let mut cell = RenderableCell::new(self, cell); if self.cursor_point == cell.point { // Store the cursor which should be rendered. self.cursor = self.renderable_cursor(&cell); if self.cursor.shape == CursorShape::Block { cell.fg = self.cursor.text_color; cell.bg = self.cursor.cursor_color; // Since we draw Block cursor by drawing cell below it with a proper color, // we must adjust alpha to make it visible. cell.bg_alpha = 1.; } return Some(cell); } else if !cell.is_empty() && !cell.flags.contains(Flags::WIDE_CHAR_SPACER) { // Skip empty cells and wide char spacers. return Some(cell); } } } } /// Cell ready for rendering. #[derive(Clone, Debug)] pub struct RenderableCell { pub character: char, pub point: Point<usize>, pub fg: Rgb, pub bg: Rgb, pub bg_alpha: f32, pub underline: Rgb, pub flags: Flags, pub extra: Option<Box<RenderableCellExtra>>, } /// Extra storage with rarely present fields for [`RenderableCell`], to reduce the cell size we /// pass around. #[derive(Clone, Debug)] pub struct RenderableCellExtra { pub zerowidth: Option<Vec<char>>, pub hyperlink: Option<Hyperlink>, } impl RenderableCell { fn new(content: &mut RenderableContent<'_>, cell: Indexed<&Cell>) -> Self { // Lookup RGB values. let mut fg = Self::compute_fg_rgb(content, cell.fg, cell.flags); let mut bg = Self::compute_bg_rgb(content, cell.bg); let mut bg_alpha = if cell.flags.contains(Flags::INVERSE) { mem::swap(&mut fg, &mut bg); 1.0 } else { Self::compute_bg_alpha(content.config, cell.bg) }; let is_selected = content.terminal_content.selection.is_some_and(|selection| { selection.contains_cell( &cell, content.terminal_content.cursor.point, content.cursor_shape, ) }); let display_offset = content.terminal_content.display_offset; let viewport_start = Point::new(Line(-(display_offset as i32)), Column(0)); let colors = &content.config.colors; let mut character = cell.c; let mut flags = cell.flags; let num_cols = content.size.columns(); if let Some((c, is_first)) = content .hint .as_mut() .and_then(|hint| hint.advance(viewport_start, num_cols, cell.point)) { if is_first { let (config_fg, config_bg) = (colors.hints.start.foreground, colors.hints.start.background); Self::compute_cell_rgb(&mut fg, &mut bg, &mut bg_alpha, config_fg, config_bg); } else if c.is_some() { let (config_fg, config_bg) = (colors.hints.end.foreground, colors.hints.end.background); Self::compute_cell_rgb(&mut fg, &mut bg, &mut bg_alpha, config_fg, config_bg); } else { flags.insert(Flags::UNDERLINE); } character = c.unwrap_or(character); } else if is_selected { let config_fg = colors.selection.foreground; let config_bg = colors.selection.background; Self::compute_cell_rgb(&mut fg, &mut bg, &mut bg_alpha, config_fg, config_bg); if fg == bg && !cell.flags.contains(Flags::HIDDEN) { // Reveal inversed text when fg/bg is the same. fg = content.color(NamedColor::Background as usize); bg = content.color(NamedColor::Foreground as usize); bg_alpha = 1.0; } } else if content.search.as_mut().is_some_and(|search| search.advance(cell.point)) { let focused = content.focused_match.is_some_and(|fm| fm.contains(&cell.point)); let (config_fg, config_bg) = if focused { (colors.search.focused_match.foreground, colors.search.focused_match.background) } else { (colors.search.matches.foreground, colors.search.matches.background) }; Self::compute_cell_rgb(&mut fg, &mut bg, &mut bg_alpha, config_fg, config_bg); } // Apply transparency to all renderable cells if `transparent_background_colors` is set if bg_alpha > 0. && content.config.colors.transparent_background_colors { bg_alpha = content.config.window_opacity(); } // Convert cell point to viewport position. let cell_point = cell.point; let point = term::point_to_viewport(display_offset, cell_point).unwrap(); let underline = cell .underline_color() .map_or(fg, |underline| Self::compute_fg_rgb(content, underline, flags)); let zerowidth = cell.zerowidth(); let hyperlink = cell.hyperlink(); let extra = (zerowidth.is_some() || hyperlink.is_some()).then(|| { Box::new(RenderableCellExtra { zerowidth: zerowidth.map(|zerowidth| zerowidth.to_vec()), hyperlink, }) }); RenderableCell { flags, character, bg_alpha, point, fg, bg, underline, extra } } /// Check if cell contains any renderable content. fn is_empty(&self) -> bool { self.bg_alpha == 0. && self.character == ' ' && self.extra.is_none() && !self.flags.intersects(Flags::ALL_UNDERLINES | Flags::STRIKEOUT) } /// Apply [`CellRgb`] colors to the cell's colors. fn compute_cell_rgb( cell_fg: &mut Rgb, cell_bg: &mut Rgb, bg_alpha: &mut f32, fg: CellRgb, bg: CellRgb, ) { let old_fg = mem::replace(cell_fg, fg.color(*cell_fg, *cell_bg)); *cell_bg = bg.color(old_fg, *cell_bg); if bg != CellRgb::CellBackground { *bg_alpha = 1.0; } } /// Get the RGB color from a cell's foreground color. fn compute_fg_rgb(content: &RenderableContent<'_>, fg: Color, flags: Flags) -> Rgb { let config = &content.config; match fg { Color::Spec(rgb) => match flags & Flags::DIM { Flags::DIM => { let rgb: Rgb = rgb.into(); rgb * DIM_FACTOR }, _ => rgb.into(), }, Color::Named(ansi) => { match (config.colors.draw_bold_text_with_bright_colors, flags & Flags::DIM_BOLD) { // If no bright foreground is set, treat it like the BOLD flag doesn't exist. (_, Flags::DIM_BOLD) if ansi == NamedColor::Foreground && config.colors.primary.bright_foreground.is_none() => { content.color(NamedColor::DimForeground as usize) }, // Draw bold text in bright colors *and* contains bold flag. (true, Flags::BOLD) => content.color(ansi.to_bright() as usize), // Cell is marked as dim and not bold. (_, Flags::DIM) | (false, Flags::DIM_BOLD) => { content.color(ansi.to_dim() as usize) }, // None of the above, keep original color.. _ => content.color(ansi as usize), } }, Color::Indexed(idx) => { let idx = match ( config.colors.draw_bold_text_with_bright_colors, flags & Flags::DIM_BOLD, idx, ) { (true, Flags::BOLD, 0..=7) => idx as usize + 8, (false, Flags::DIM, 8..=15) => idx as usize - 8, (false, Flags::DIM, 0..=7) => NamedColor::DimBlack as usize + idx as usize, _ => idx as usize, }; content.color(idx) }, } } /// Get the RGB color from a cell's background color. #[inline] fn compute_bg_rgb(content: &RenderableContent<'_>, bg: Color) -> Rgb { match bg { Color::Spec(rgb) => rgb.into(), Color::Named(ansi) => content.color(ansi as usize), Color::Indexed(idx) => content.color(idx as usize), } } /// Compute background alpha based on cell's original color. /// /// Since an RGB color matching the background should not be transparent, this is computed /// using the named input color, rather than checking the RGB of the background after its color /// is computed. #[inline] fn compute_bg_alpha(config: &UiConfig, bg: Color) -> f32 { if bg == Color::Named(NamedColor::Background) { 0. } else if config.colors.transparent_background_colors { config.window_opacity() } else { 1. } } } /// Cursor storing all information relevant for rendering. #[derive(Debug, Eq, PartialEq, Copy, Clone)] pub struct RenderableCursor { shape: CursorShape, cursor_color: Rgb, text_color: Rgb, width: NonZeroU32, point: Point<usize>, } impl RenderableCursor { fn new_hidden() -> Self { let shape = CursorShape::Hidden; let cursor_color = Rgb::default(); let text_color = Rgb::default(); let width = NonZeroU32::new(1).unwrap(); let point = Point::default(); Self { shape, cursor_color, text_color, width, point } } } impl RenderableCursor { pub fn new( point: Point<usize>, shape: CursorShape, cursor_color: Rgb, width: NonZeroU32, ) -> Self { Self { shape, cursor_color, text_color: cursor_color, width, point } } pub fn color(&self) -> Rgb { self.cursor_color } pub fn shape(&self) -> CursorShape { self.shape } pub fn width(&self) -> NonZeroU32 { self.width } pub fn point(&self) -> Point<usize> { self.point } } /// Regex hints for keyboard shortcuts. struct Hint<'a> { /// Hint matches and position. matches: HintMatches<'a>, /// Last match checked against current cell position. labels: &'a Vec<Vec<char>>, } impl Hint<'_> { /// Advance the hint iterator. /// /// If the point is within a hint, the keyboard shortcut character that should be displayed at /// this position will be returned. /// /// The tuple's [`bool`] will be `true` when the character is the first for this hint. /// /// The tuple's [`Option<char>`] will be [`None`] when the point is part of the match, but not /// part of the hint label. fn advance( &mut self, viewport_start: Point, num_cols: usize, point: Point, ) -> Option<(Option<char>, bool)> { // Check if we're within a match at all. if !self.matches.advance(point) { return None; } // Match starting position on this line; linebreaks interrupt the hint labels. let start = self .matches .get(self.matches.index) .map(|bounds| cmp::max(*bounds.start(), viewport_start))?; // Position within the hint label. let line_delta = point.line.0 - start.line.0; let col_delta = point.column.0 as i32 - start.column.0 as i32; let label_position = usize::try_from(line_delta * num_cols as i32 + col_delta).unwrap_or(0); let is_first = label_position == 0; // Hint label character. let hint_char = self.labels[self.matches.index] .get(label_position) .copied() .map(|c| (Some(c), is_first)) .unwrap_or((None, false)); Some(hint_char) } } impl<'a> From<&'a HintState> for Hint<'a> { fn from(hint_state: &'a HintState) -> Self { let matches = HintMatches::new(hint_state.matches()); Self { labels: hint_state.labels(), matches } } } /// Visible hint match tracking. #[derive(Default)] struct HintMatches<'a> { /// All visible matches. matches: Cow<'a, [Match]>, /// Index of the last match checked. index: usize, } impl<'a> HintMatches<'a> { /// Create new renderable matches iterator.. fn new(matches: impl Into<Cow<'a, [Match]>>) -> Self { Self { matches: matches.into(), index: 0 } } /// Create from regex matches on term visible part. fn visible_regex_matches<T>(term: &Term<T>, dfas: &mut RegexSearch) -> Self { let matches = hint::visible_regex_match_iter(term, dfas).collect::<Vec<_>>(); Self::new(matches) } /// Advance the regex tracker to the next point. /// /// This will return `true` if the point passed is part of a regex match. fn advance(&mut self, point: Point) -> bool { while let Some(bounds) = self.get(self.index) { if bounds.start() > &point { break; } else if bounds.end() < &point { self.index += 1; } else { return true; } } false } } impl Deref for HintMatches<'_> { type Target = [Match]; fn deref(&self) -> &Self::Target { self.matches.deref() } }
rust
Apache-2.0
6ee6e53ee3457c24137f117237b0ff1d84f6f836
2026-01-04T15:31:58.707223Z
false
alacritty/alacritty
https://github.com/alacritty/alacritty/blob/6ee6e53ee3457c24137f117237b0ff1d84f6f836/alacritty/src/display/damage.rs
alacritty/src/display/damage.rs
use std::iter::Peekable; use std::{cmp, mem}; use glutin::surface::Rect; use alacritty_terminal::index::Point; use alacritty_terminal::selection::SelectionRange; use alacritty_terminal::term::{LineDamageBounds, TermDamageIterator}; use crate::display::SizeInfo; /// State of the damage tracking for the [`Display`]. /// /// [`Display`]: crate::display::Display #[derive(Debug)] pub struct DamageTracker { /// Position of the previously drawn Vi cursor. pub old_vi_cursor: Option<Point<usize>>, /// The location of the old selection. pub old_selection: Option<SelectionRange>, /// Highlight damage submitted for the compositor. pub debug: bool, /// The damage for the frames. frames: [FrameDamage; 2], screen_lines: usize, columns: usize, } impl DamageTracker { pub fn new(screen_lines: usize, columns: usize) -> Self { let mut tracker = Self { columns, screen_lines, debug: false, old_vi_cursor: None, old_selection: None, frames: Default::default(), }; tracker.resize(screen_lines, columns); tracker } #[inline] #[must_use] pub fn frame(&mut self) -> &mut FrameDamage { &mut self.frames[0] } #[inline] #[must_use] pub fn next_frame(&mut self) -> &mut FrameDamage { &mut self.frames[1] } /// Advance to the next frame resetting the state for the active frame. #[inline] pub fn swap_damage(&mut self) { let screen_lines = self.screen_lines; let columns = self.columns; self.frame().reset(screen_lines, columns); self.frames.swap(0, 1); } /// Resize the damage information in the tracker. pub fn resize(&mut self, screen_lines: usize, columns: usize) { self.screen_lines = screen_lines; self.columns = columns; for frame in &mut self.frames { frame.reset(screen_lines, columns); } self.frame().full = true; } /// Damage vi cursor inside the viewport. pub fn damage_vi_cursor(&mut self, mut vi_cursor: Option<Point<usize>>) { mem::swap(&mut self.old_vi_cursor, &mut vi_cursor); if self.frame().full { return; } if let Some(vi_cursor) = self.old_vi_cursor { self.frame().damage_point(vi_cursor); } if let Some(vi_cursor) = vi_cursor { self.frame().damage_point(vi_cursor); } } /// Get shaped frame damage for the active frame. pub fn shape_frame_damage(&self, size_info: SizeInfo<u32>) -> Vec<Rect> { if self.frames[0].full { vec![Rect::new(0, 0, size_info.width() as i32, size_info.height() as i32)] } else { let lines_damage = RenderDamageIterator::new( TermDamageIterator::new(&self.frames[0].lines, 0), &size_info, ); lines_damage.chain(self.frames[0].rects.iter().copied()).collect() } } /// Add the current frame's selection damage. pub fn damage_selection( &mut self, mut selection: Option<SelectionRange>, display_offset: usize, ) { mem::swap(&mut self.old_selection, &mut selection); if self.frame().full || selection == self.old_selection { return; } for selection in self.old_selection.into_iter().chain(selection) { let display_offset = display_offset as i32; let last_visible_line = self.screen_lines as i32 - 1; let columns = self.columns; // Ignore invisible selection. if selection.end.line.0 + display_offset < 0 || selection.start.line.0.abs() < display_offset - last_visible_line { continue; }; let start = cmp::max(selection.start.line.0 + display_offset, 0) as usize; let end = (selection.end.line.0 + display_offset).clamp(0, last_visible_line) as usize; for line in start..=end { self.frame().lines[line].expand(0, columns - 1); } } } } /// Damage state for the rendering frame. #[derive(Debug, Default)] pub struct FrameDamage { /// The entire frame needs to be redrawn. full: bool, /// Terminal lines damaged in the given frame. lines: Vec<LineDamageBounds>, /// Rectangular regions damage in the given frame. rects: Vec<Rect>, } impl FrameDamage { /// Damage line for the given frame. #[inline] pub fn damage_line(&mut self, damage: LineDamageBounds) { self.lines[damage.line].expand(damage.left, damage.right); } #[inline] pub fn damage_point(&mut self, point: Point<usize>) { self.lines[point.line].expand(point.column.0, point.column.0); } /// Mark the frame as fully damaged. #[inline] pub fn mark_fully_damaged(&mut self) { self.full = true; } /// Add viewport rectangle to damage. /// /// This allows covering elements outside of the terminal viewport, like message bar. #[inline] pub fn add_viewport_rect( &mut self, size_info: &SizeInfo, x: i32, y: i32, width: i32, height: i32, ) { let y = viewport_y_to_damage_y(size_info, y, height); self.rects.push(Rect { x, y, width, height }); } fn reset(&mut self, num_lines: usize, num_cols: usize) { self.full = false; self.rects.clear(); self.lines.clear(); self.lines.reserve(num_lines); for line in 0..num_lines { self.lines.push(LineDamageBounds::undamaged(line, num_cols)); } } /// Check if a range is damaged. #[inline] pub fn intersects(&self, start: Point<usize>, end: Point<usize>) -> bool { let start_line = &self.lines[start.line]; let end_line = &self.lines[end.line]; self.full || (start_line.left..=start_line.right).contains(&start.column) || (end_line.left..=end_line.right).contains(&end.column) || (start.line + 1..end.line).any(|line| self.lines[line].is_damaged()) } } /// Convert viewport `y` coordinate to [`Rect`] damage coordinate. pub fn viewport_y_to_damage_y(size_info: &SizeInfo, y: i32, height: i32) -> i32 { size_info.height() as i32 - y - height } /// Convert viewport `y` coordinate to [`Rect`] damage coordinate. pub fn damage_y_to_viewport_y(size_info: &SizeInfo, rect: &Rect) -> i32 { size_info.height() as i32 - rect.y - rect.height } /// Iterator which converts `alacritty_terminal` damage information into renderer damaged rects. struct RenderDamageIterator<'a> { damaged_lines: Peekable<TermDamageIterator<'a>>, size_info: &'a SizeInfo<u32>, } impl<'a> RenderDamageIterator<'a> { pub fn new(damaged_lines: TermDamageIterator<'a>, size_info: &'a SizeInfo<u32>) -> Self { Self { damaged_lines: damaged_lines.peekable(), size_info } } #[inline] fn rect_for_line(&self, line_damage: LineDamageBounds) -> Rect { let size_info = &self.size_info; let y_top = size_info.height() - size_info.padding_y(); let x = size_info.padding_x() + line_damage.left as u32 * size_info.cell_width(); let y = y_top - (line_damage.line + 1) as u32 * size_info.cell_height(); let width = (line_damage.right - line_damage.left + 1) as u32 * size_info.cell_width(); Rect::new(x as i32, y as i32, width as i32, size_info.cell_height() as i32) } // Make sure to damage near cells to include wide chars. #[inline] fn overdamage(size_info: &SizeInfo<u32>, mut rect: Rect) -> Rect { rect.x = (rect.x - size_info.cell_width() as i32).max(0); rect.width = cmp::min( (size_info.width() as i32 - rect.x).max(0), rect.width + 2 * size_info.cell_width() as i32, ); rect.y = (rect.y - size_info.cell_height() as i32 / 2).max(0); rect.height = cmp::min( (size_info.height() as i32 - rect.y).max(0), rect.height + size_info.cell_height() as i32, ); rect } } impl Iterator for RenderDamageIterator<'_> { type Item = Rect; fn next(&mut self) -> Option<Rect> { let line = self.damaged_lines.next()?; let size_info = &self.size_info; let mut total_damage_rect = Self::overdamage(size_info, self.rect_for_line(line)); // Merge rectangles which overlap with each other. while let Some(line) = self.damaged_lines.peek().copied() { let next_rect = Self::overdamage(size_info, self.rect_for_line(line)); if !rects_overlap(total_damage_rect, next_rect) { break; } total_damage_rect = merge_rects(total_damage_rect, next_rect); let _ = self.damaged_lines.next(); } Some(total_damage_rect) } } /// Check if two given [`glutin::surface::Rect`] overlap. fn rects_overlap(lhs: Rect, rhs: Rect) -> bool { !( // `lhs` is left of `rhs`. lhs.x + lhs.width < rhs.x // `lhs` is right of `rhs`. || rhs.x + rhs.width < lhs.x // `lhs` is below `rhs`. || lhs.y + lhs.height < rhs.y // `lhs` is above `rhs`. || rhs.y + rhs.height < lhs.y ) } /// Merge two [`glutin::surface::Rect`] by producing the smallest rectangle that contains both. #[inline] fn merge_rects(lhs: Rect, rhs: Rect) -> Rect { let left_x = cmp::min(lhs.x, rhs.x); let right_x = cmp::max(lhs.x + lhs.width, rhs.x + rhs.width); let y_top = cmp::max(lhs.y + lhs.height, rhs.y + rhs.height); let y_bottom = cmp::min(lhs.y, rhs.y); Rect::new(left_x, y_bottom, right_x - left_x, y_top - y_bottom) } #[cfg(test)] mod tests { use super::*; #[test] fn damage_rect_math() { let rect_side = 10; let cell_size = 4; let bound = 100; let size_info: SizeInfo<u32> = SizeInfo::new( bound as f32, bound as f32, cell_size as f32, cell_size as f32, 2., 2., true, ) .into(); // Test min clamping. let rect = Rect::new(0, 0, rect_side, rect_side); let rect = RenderDamageIterator::overdamage(&size_info, rect); assert_eq!(Rect::new(0, 0, rect_side + 2 * cell_size, 10 + cell_size), rect); // Test max clamping. let rect = Rect::new(bound, bound, rect_side, rect_side); let rect = RenderDamageIterator::overdamage(&size_info, rect); assert_eq!( Rect::new(bound - cell_size, bound - cell_size / 2, cell_size, cell_size / 2), rect ); // Test no clamping. let rect = Rect::new(bound / 2, bound / 2, rect_side, rect_side); let rect = RenderDamageIterator::overdamage(&size_info, rect); assert_eq!( Rect::new( bound / 2 - cell_size, bound / 2 - cell_size / 2, rect_side + 2 * cell_size, rect_side + cell_size ), rect ); // Test out of bounds coord clamping. let rect = Rect::new(bound * 2, bound * 2, rect_side, rect_side); let rect = RenderDamageIterator::overdamage(&size_info, rect); assert_eq!(Rect::new(bound * 2 - cell_size, bound * 2 - cell_size / 2, 0, 0), rect); } #[test] fn add_viewport_damage() { let mut frame_damage = FrameDamage::default(); let viewport_height = 100.; let x = 0; let y = 40; let height = 5; let width = 10; let size_info = SizeInfo::new(viewport_height, viewport_height, 5., 5., 0., 0., true); frame_damage.add_viewport_rect(&size_info, x, y, width, height); assert_eq!(frame_damage.rects[0], Rect { x, y: viewport_height as i32 - y - height, width, height }); assert_eq!(frame_damage.rects[0].y, viewport_y_to_damage_y(&size_info, y, height)); assert_eq!(damage_y_to_viewport_y(&size_info, &frame_damage.rects[0]), y); } }
rust
Apache-2.0
6ee6e53ee3457c24137f117237b0ff1d84f6f836
2026-01-04T15:31:58.707223Z
false
alacritty/alacritty
https://github.com/alacritty/alacritty/blob/6ee6e53ee3457c24137f117237b0ff1d84f6f836/alacritty/src/display/mod.rs
alacritty/src/display/mod.rs
//! The display subsystem including window management, font rasterization, and //! GPU drawing. use std::cmp; use std::fmt::{self, Formatter}; use std::mem::{self, ManuallyDrop}; use std::num::NonZeroU32; use std::ops::Deref; use std::time::{Duration, Instant}; use glutin::config::GetGlConfig; use glutin::context::{NotCurrentContext, PossiblyCurrentContext}; use glutin::display::GetGlDisplay; use glutin::error::ErrorKind; use glutin::prelude::*; use glutin::surface::{Surface, SwapInterval, WindowSurface}; use log::{debug, info}; use parking_lot::MutexGuard; use serde::{Deserialize, Serialize}; use winit::dpi::PhysicalSize; use winit::keyboard::ModifiersState; use winit::raw_window_handle::RawWindowHandle; use winit::window::CursorIcon; use crossfont::{Rasterize, Rasterizer, Size as FontSize}; use unicode_width::UnicodeWidthChar; use alacritty_terminal::event::{EventListener, OnResize, WindowSize}; use alacritty_terminal::grid::Dimensions as TermDimensions; use alacritty_terminal::index::{Column, Direction, Line, Point}; use alacritty_terminal::selection::Selection; use alacritty_terminal::term::cell::Flags; use alacritty_terminal::term::{ self, LineDamageBounds, MIN_COLUMNS, MIN_SCREEN_LINES, Term, TermDamage, TermMode, }; use alacritty_terminal::vte::ansi::{CursorShape, NamedColor}; use crate::config::UiConfig; use crate::config::debug::RendererPreference; use crate::config::font::Font; use crate::config::window::Dimensions; #[cfg(not(windows))] use crate::config::window::StartupMode; use crate::display::bell::VisualBell; use crate::display::color::{List, Rgb}; use crate::display::content::{RenderableContent, RenderableCursor}; use crate::display::cursor::IntoRects; use crate::display::damage::{DamageTracker, damage_y_to_viewport_y}; use crate::display::hint::{HintMatch, HintState}; use crate::display::meter::Meter; use crate::display::window::Window; use crate::event::{Event, EventType, Mouse, SearchState}; use crate::message_bar::{MessageBuffer, MessageType}; use crate::renderer::rects::{RenderLine, RenderLines, RenderRect}; use crate::renderer::{self, GlyphCache, Renderer, platform}; use crate::scheduler::{Scheduler, TimerId, Topic}; use crate::string::{ShortenDirection, StrShortener}; pub mod color; pub mod content; pub mod cursor; pub mod hint; pub mod window; mod bell; mod damage; mod meter; /// Label for the forward terminal search bar. const FORWARD_SEARCH_LABEL: &str = "Search: "; /// Label for the backward terminal search bar. const BACKWARD_SEARCH_LABEL: &str = "Backward Search: "; /// The character used to shorten the visible text like uri preview or search regex. const SHORTENER: char = '…'; /// Color which is used to highlight damaged rects when debugging. const DAMAGE_RECT_COLOR: Rgb = Rgb::new(255, 0, 255); #[derive(Debug)] pub enum Error { /// Error with window management. Window(window::Error), /// Error dealing with fonts. Font(crossfont::Error), /// Error in renderer. Render(renderer::Error), /// Error during context operations. Context(glutin::error::Error), } impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { Error::Window(err) => err.source(), Error::Font(err) => err.source(), Error::Render(err) => err.source(), Error::Context(err) => err.source(), } } } impl fmt::Display for Error { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { Error::Window(err) => err.fmt(f), Error::Font(err) => err.fmt(f), Error::Render(err) => err.fmt(f), Error::Context(err) => err.fmt(f), } } } impl From<window::Error> for Error { fn from(val: window::Error) -> Self { Error::Window(val) } } impl From<crossfont::Error> for Error { fn from(val: crossfont::Error) -> Self { Error::Font(val) } } impl From<renderer::Error> for Error { fn from(val: renderer::Error) -> Self { Error::Render(val) } } impl From<glutin::error::Error> for Error { fn from(val: glutin::error::Error) -> Self { Error::Context(val) } } /// Terminal size info. #[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq, Eq)] pub struct SizeInfo<T = f32> { /// Terminal window width. width: T, /// Terminal window height. height: T, /// Width of individual cell. cell_width: T, /// Height of individual cell. cell_height: T, /// Horizontal window padding. padding_x: T, /// Vertical window padding. padding_y: T, /// Number of lines in the viewport. screen_lines: usize, /// Number of columns in the viewport. columns: usize, } impl From<SizeInfo<f32>> for SizeInfo<u32> { fn from(size_info: SizeInfo<f32>) -> Self { Self { width: size_info.width as u32, height: size_info.height as u32, cell_width: size_info.cell_width as u32, cell_height: size_info.cell_height as u32, padding_x: size_info.padding_x as u32, padding_y: size_info.padding_y as u32, screen_lines: size_info.screen_lines, columns: size_info.screen_lines, } } } impl From<SizeInfo<f32>> for WindowSize { fn from(size_info: SizeInfo<f32>) -> Self { Self { num_cols: size_info.columns() as u16, num_lines: size_info.screen_lines() as u16, cell_width: size_info.cell_width() as u16, cell_height: size_info.cell_height() as u16, } } } impl<T: Clone + Copy> SizeInfo<T> { #[inline] pub fn width(&self) -> T { self.width } #[inline] pub fn height(&self) -> T { self.height } #[inline] pub fn cell_width(&self) -> T { self.cell_width } #[inline] pub fn cell_height(&self) -> T { self.cell_height } #[inline] pub fn padding_x(&self) -> T { self.padding_x } #[inline] pub fn padding_y(&self) -> T { self.padding_y } } impl SizeInfo<f32> { #[allow(clippy::too_many_arguments)] pub fn new( width: f32, height: f32, cell_width: f32, cell_height: f32, mut padding_x: f32, mut padding_y: f32, dynamic_padding: bool, ) -> SizeInfo { if dynamic_padding { padding_x = Self::dynamic_padding(padding_x.floor(), width, cell_width); padding_y = Self::dynamic_padding(padding_y.floor(), height, cell_height); } let lines = (height - 2. * padding_y) / cell_height; let screen_lines = cmp::max(lines as usize, MIN_SCREEN_LINES); let columns = (width - 2. * padding_x) / cell_width; let columns = cmp::max(columns as usize, MIN_COLUMNS); SizeInfo { width, height, cell_width, cell_height, padding_x: padding_x.floor(), padding_y: padding_y.floor(), screen_lines, columns, } } #[inline] pub fn reserve_lines(&mut self, count: usize) { self.screen_lines = cmp::max(self.screen_lines.saturating_sub(count), MIN_SCREEN_LINES); } /// Check if coordinates are inside the terminal grid. /// /// The padding, message bar or search are not counted as part of the grid. #[inline] pub fn contains_point(&self, x: usize, y: usize) -> bool { x <= (self.padding_x + self.columns as f32 * self.cell_width) as usize && x > self.padding_x as usize && y <= (self.padding_y + self.screen_lines as f32 * self.cell_height) as usize && y > self.padding_y as usize } /// Calculate padding to spread it evenly around the terminal content. #[inline] fn dynamic_padding(padding: f32, dimension: f32, cell_dimension: f32) -> f32 { padding + ((dimension - 2. * padding) % cell_dimension) / 2. } } impl TermDimensions for SizeInfo { #[inline] fn columns(&self) -> usize { self.columns } #[inline] fn screen_lines(&self) -> usize { self.screen_lines } #[inline] fn total_lines(&self) -> usize { self.screen_lines() } } #[derive(Default, Clone, Debug, PartialEq, Eq)] pub struct DisplayUpdate { pub dirty: bool, dimensions: Option<PhysicalSize<u32>>, cursor_dirty: bool, font: Option<Font>, } impl DisplayUpdate { pub fn dimensions(&self) -> Option<PhysicalSize<u32>> { self.dimensions } pub fn font(&self) -> Option<&Font> { self.font.as_ref() } pub fn cursor_dirty(&self) -> bool { self.cursor_dirty } pub fn set_dimensions(&mut self, dimensions: PhysicalSize<u32>) { self.dimensions = Some(dimensions); self.dirty = true; } pub fn set_font(&mut self, font: Font) { self.font = Some(font); self.dirty = true; } pub fn set_cursor_dirty(&mut self) { self.cursor_dirty = true; self.dirty = true; } } /// The display wraps a window, font rasterizer, and GPU renderer. pub struct Display { pub window: Window, pub size_info: SizeInfo, /// Hint highlighted by the mouse. pub highlighted_hint: Option<HintMatch>, /// Frames since hint highlight was created. highlighted_hint_age: usize, /// Hint highlighted by the vi mode cursor. pub vi_highlighted_hint: Option<HintMatch>, /// Frames since hint highlight was created. vi_highlighted_hint_age: usize, pub raw_window_handle: RawWindowHandle, /// UI cursor visibility for blinking. pub cursor_hidden: bool, pub visual_bell: VisualBell, /// Mapped RGB values for each terminal color. pub colors: List, /// State of the keyboard hints. pub hint_state: HintState, /// Unprocessed display updates. pub pending_update: DisplayUpdate, /// The renderer update that takes place only once before the actual rendering. pub pending_renderer_update: Option<RendererUpdate>, /// The ime on the given display. pub ime: Ime, /// The state of the timer for frame scheduling. pub frame_timer: FrameTimer, /// Damage tracker for the given display. pub damage_tracker: DamageTracker, /// Font size used by the window. pub font_size: FontSize, // Mouse point position when highlighting hints. hint_mouse_point: Option<Point>, renderer: ManuallyDrop<Renderer>, renderer_preference: Option<RendererPreference>, surface: ManuallyDrop<Surface<WindowSurface>>, context: ManuallyDrop<PossiblyCurrentContext>, glyph_cache: GlyphCache, meter: Meter, } impl Display { pub fn new( window: Window, gl_context: NotCurrentContext, config: &UiConfig, _tabbed: bool, ) -> Result<Display, Error> { let raw_window_handle = window.raw_window_handle(); let scale_factor = window.scale_factor as f32; let rasterizer = Rasterizer::new()?; let font_size = config.font.size().scale(scale_factor); debug!("Loading \"{}\" font", &config.font.normal().family); let font = config.font.clone().with_size(font_size); let mut glyph_cache = GlyphCache::new(rasterizer, &font)?; let metrics = glyph_cache.font_metrics(); let (cell_width, cell_height) = compute_cell_size(config, &metrics); // Resize the window to account for the user configured size. if let Some(dimensions) = config.window.dimensions() { let size = window_size(config, dimensions, cell_width, cell_height, scale_factor); window.request_inner_size(size); } // Create the GL surface to draw into. let surface = platform::create_gl_surface( &gl_context, window.inner_size(), window.raw_window_handle(), )?; // Make the context current. let context = gl_context.make_current(&surface)?; // Create renderer. let mut renderer = Renderer::new(&context, config.debug.renderer)?; // Load font common glyphs to accelerate rendering. debug!("Filling glyph cache with common glyphs"); renderer.with_loader(|mut api| { glyph_cache.reset_glyph_cache(&mut api); }); let padding = config.window.padding(window.scale_factor as f32); let viewport_size = window.inner_size(); // Create new size with at least one column and row. let size_info = SizeInfo::new( viewport_size.width as f32, viewport_size.height as f32, cell_width, cell_height, padding.0, padding.1, config.window.dynamic_padding && config.window.dimensions().is_none(), ); info!("Cell size: {cell_width} x {cell_height}"); info!("Padding: {} x {}", size_info.padding_x(), size_info.padding_y()); info!("Width: {}, Height: {}", size_info.width(), size_info.height()); // Update OpenGL projection. renderer.resize(&size_info); // Clear screen. let background_color = config.colors.primary.background; renderer.clear(background_color, config.window_opacity()); // Disable shadows for transparent windows on macOS. #[cfg(target_os = "macos")] window.set_has_shadow(config.window_opacity() >= 1.0); let is_wayland = matches!(raw_window_handle, RawWindowHandle::Wayland(_)); // On Wayland we can safely ignore this call, since the window isn't visible until you // actually draw something into it and commit those changes. if !is_wayland { surface.swap_buffers(&context).expect("failed to swap buffers."); renderer.finish(); } // Set resize increments for the newly created window. if config.window.resize_increments { window.set_resize_increments(PhysicalSize::new(cell_width, cell_height)); } window.set_visible(true); // Always focus new windows, even if no Alacritty window is currently focused. #[cfg(target_os = "macos")] window.focus_window(); #[allow(clippy::single_match)] #[cfg(not(windows))] if !_tabbed { match config.window.startup_mode { #[cfg(target_os = "macos")] StartupMode::SimpleFullscreen => window.set_simple_fullscreen(true), StartupMode::Maximized if !is_wayland => window.set_maximized(true), _ => (), } } let hint_state = HintState::new(config.hints.alphabet()); let mut damage_tracker = DamageTracker::new(size_info.screen_lines(), size_info.columns()); damage_tracker.debug = config.debug.highlight_damage; // Disable vsync. if let Err(err) = surface.set_swap_interval(&context, SwapInterval::DontWait) { info!("Failed to disable vsync: {err}"); } Ok(Self { context: ManuallyDrop::new(context), visual_bell: VisualBell::from(&config.bell), renderer: ManuallyDrop::new(renderer), renderer_preference: config.debug.renderer, surface: ManuallyDrop::new(surface), colors: List::from(&config.colors), frame_timer: FrameTimer::new(), raw_window_handle, damage_tracker, glyph_cache, hint_state, size_info, font_size, window, pending_renderer_update: Default::default(), vi_highlighted_hint_age: Default::default(), highlighted_hint_age: Default::default(), vi_highlighted_hint: Default::default(), highlighted_hint: Default::default(), hint_mouse_point: Default::default(), pending_update: Default::default(), cursor_hidden: Default::default(), meter: Default::default(), ime: Default::default(), }) } #[inline] pub fn gl_context(&self) -> &PossiblyCurrentContext { &self.context } pub fn make_not_current(&mut self) { if self.context.is_current() { self.context.make_not_current_in_place().expect("failed to disable context"); } } pub fn make_current(&mut self) { let is_current = self.context.is_current(); // Attempt to make the context current if it's not. let context_loss = if is_current { self.renderer.was_context_reset() } else { match self.context.make_current(&self.surface) { Err(err) if err.error_kind() == ErrorKind::ContextLost => { info!("Context lost for window {:?}", self.window.id()); true }, _ => false, } }; if !context_loss { return; } let gl_display = self.context.display(); let gl_config = self.context.config(); let raw_window_handle = Some(self.window.raw_window_handle()); let context = platform::create_gl_context(&gl_display, &gl_config, raw_window_handle) .expect("failed to recreate context."); // Drop the old context and renderer. unsafe { ManuallyDrop::drop(&mut self.renderer); ManuallyDrop::drop(&mut self.context); } // Activate new context. let context = context.treat_as_possibly_current(); self.context = ManuallyDrop::new(context); self.context.make_current(&self.surface).expect("failed to reativate context after reset."); // Recreate renderer. let renderer = Renderer::new(&self.context, self.renderer_preference) .expect("failed to recreate renderer after reset"); self.renderer = ManuallyDrop::new(renderer); // Resize the renderer. self.renderer.resize(&self.size_info); self.reset_glyph_cache(); self.damage_tracker.frame().mark_fully_damaged(); debug!("Recovered window {:?} from gpu reset", self.window.id()); } fn swap_buffers(&self) { #[allow(clippy::single_match)] let res = match (self.surface.deref(), &self.context.deref()) { #[cfg(not(any(target_os = "macos", windows)))] (Surface::Egl(surface), PossiblyCurrentContext::Egl(context)) if matches!(self.raw_window_handle, RawWindowHandle::Wayland(_)) && !self.damage_tracker.debug => { let damage = self.damage_tracker.shape_frame_damage(self.size_info.into()); surface.swap_buffers_with_damage(context, &damage) }, (surface, context) => surface.swap_buffers(context), }; if let Err(err) = res { debug!("error calling swap_buffers: {err}"); } } /// Update font size and cell dimensions. /// /// This will return a tuple of the cell width and height. fn update_font_size( glyph_cache: &mut GlyphCache, config: &UiConfig, font: &Font, ) -> (f32, f32) { let _ = glyph_cache.update_font_size(font); // Compute new cell sizes. compute_cell_size(config, &glyph_cache.font_metrics()) } /// Reset glyph cache. fn reset_glyph_cache(&mut self) { let cache = &mut self.glyph_cache; self.renderer.with_loader(|mut api| { cache.reset_glyph_cache(&mut api); }); } // XXX: this function must not call to any `OpenGL` related tasks. Renderer updates are // performed in [`Self::process_renderer_update`] right before drawing. // /// Process update events. pub fn handle_update<T>( &mut self, terminal: &mut Term<T>, pty_resize_handle: &mut dyn OnResize, message_buffer: &MessageBuffer, search_state: &mut SearchState, config: &UiConfig, ) where T: EventListener, { let pending_update = mem::take(&mut self.pending_update); let (mut cell_width, mut cell_height) = (self.size_info.cell_width(), self.size_info.cell_height()); if pending_update.font().is_some() || pending_update.cursor_dirty() { let renderer_update = self.pending_renderer_update.get_or_insert(Default::default()); renderer_update.clear_font_cache = true } // Update font size and cell dimensions. if let Some(font) = pending_update.font() { let cell_dimensions = Self::update_font_size(&mut self.glyph_cache, config, font); cell_width = cell_dimensions.0; cell_height = cell_dimensions.1; info!("Cell size: {cell_width} x {cell_height}"); // Mark entire terminal as damaged since glyph size could change without cell size // changes. self.damage_tracker.frame().mark_fully_damaged(); } let (mut width, mut height) = (self.size_info.width(), self.size_info.height()); if let Some(dimensions) = pending_update.dimensions() { width = dimensions.width as f32; height = dimensions.height as f32; } let padding = config.window.padding(self.window.scale_factor as f32); let mut new_size = SizeInfo::new( width, height, cell_width, cell_height, padding.0, padding.1, config.window.dynamic_padding, ); // Update number of column/lines in the viewport. let search_active = search_state.history_index.is_some(); let message_bar_lines = message_buffer.message().map_or(0, |m| m.text(&new_size).len()); let search_lines = usize::from(search_active); new_size.reserve_lines(message_bar_lines + search_lines); // Update resize increments. if config.window.resize_increments { self.window.set_resize_increments(PhysicalSize::new(cell_width, cell_height)); } // Resize when terminal when its dimensions have changed. if self.size_info.screen_lines() != new_size.screen_lines || self.size_info.columns() != new_size.columns() { // Resize PTY. pty_resize_handle.on_resize(new_size.into()); // Resize terminal. terminal.resize(new_size); // Resize damage tracking. self.damage_tracker.resize(new_size.screen_lines(), new_size.columns()); } // Check if dimensions have changed. if new_size != self.size_info { // Queue renderer update. let renderer_update = self.pending_renderer_update.get_or_insert(Default::default()); renderer_update.resize = true; // Clear focused search match. search_state.clear_focused_match(); } self.size_info = new_size; } // NOTE: Renderer updates are split off, since platforms like Wayland require resize and other // OpenGL operations to be performed right before rendering. Otherwise they could lock the // back buffer and render with the previous state. This also solves flickering during resizes. // /// Update the state of the renderer. pub fn process_renderer_update(&mut self) { let renderer_update = match self.pending_renderer_update.take() { Some(renderer_update) => renderer_update, _ => return, }; // Resize renderer. if renderer_update.resize { let width = NonZeroU32::new(self.size_info.width() as u32).unwrap(); let height = NonZeroU32::new(self.size_info.height() as u32).unwrap(); self.surface.resize(&self.context, width, height); } // Ensure we're modifying the correct OpenGL context. self.make_current(); if renderer_update.clear_font_cache { self.reset_glyph_cache(); } self.renderer.resize(&self.size_info); info!("Padding: {} x {}", self.size_info.padding_x(), self.size_info.padding_y()); info!("Width: {}, Height: {}", self.size_info.width(), self.size_info.height()); } /// Draw the screen. /// /// A reference to Term whose state is being drawn must be provided. /// /// This call may block if vsync is enabled. pub fn draw<T: EventListener>( &mut self, mut terminal: MutexGuard<'_, Term<T>>, scheduler: &mut Scheduler, message_buffer: &MessageBuffer, config: &UiConfig, search_state: &mut SearchState, ) { // Collect renderable content before the terminal is dropped. let mut content = RenderableContent::new(config, self, &terminal, search_state); let mut grid_cells = Vec::new(); for cell in &mut content { grid_cells.push(cell); } let selection_range = content.selection_range(); let foreground_color = content.color(NamedColor::Foreground as usize); let background_color = content.color(NamedColor::Background as usize); let display_offset = content.display_offset(); let cursor = content.cursor(); let cursor_point = terminal.grid().cursor.point; let total_lines = terminal.grid().total_lines(); let metrics = self.glyph_cache.font_metrics(); let size_info = self.size_info; let vi_mode = terminal.mode().contains(TermMode::VI); let vi_cursor_point = if vi_mode { Some(terminal.vi_mode_cursor.point) } else { None }; // Add damage from the terminal. match terminal.damage() { TermDamage::Full => self.damage_tracker.frame().mark_fully_damaged(), TermDamage::Partial(damaged_lines) => { for damage in damaged_lines { self.damage_tracker.frame().damage_line(damage); } }, } terminal.reset_damage(); // Drop terminal as early as possible to free lock. drop(terminal); // Invalidate highlighted hints if grid has changed. self.validate_hint_highlights(display_offset); // Add damage from alacritty's UI elements overlapping terminal. let requires_full_damage = self.visual_bell.intensity() != 0. || self.hint_state.active() || search_state.regex().is_some(); if requires_full_damage { self.damage_tracker.frame().mark_fully_damaged(); self.damage_tracker.next_frame().mark_fully_damaged(); } let vi_cursor_viewport_point = vi_cursor_point.and_then(|cursor| term::point_to_viewport(display_offset, cursor)); self.damage_tracker.damage_vi_cursor(vi_cursor_viewport_point); self.damage_tracker.damage_selection(selection_range, display_offset); // Make sure this window's OpenGL context is active. self.make_current(); self.renderer.clear(background_color, config.window_opacity()); let mut lines = RenderLines::new(); // Optimize loop hint comparator. let has_highlighted_hint = self.highlighted_hint.is_some() || self.vi_highlighted_hint.is_some(); // Draw grid. { let _sampler = self.meter.sampler(); // Ensure macOS hasn't reset our viewport. #[cfg(target_os = "macos")] self.renderer.set_viewport(&size_info); let glyph_cache = &mut self.glyph_cache; let highlighted_hint = &self.highlighted_hint; let vi_highlighted_hint = &self.vi_highlighted_hint; let damage_tracker = &mut self.damage_tracker; let cells = grid_cells.into_iter().map(|mut cell| { // Underline hints hovered by mouse or vi mode cursor. if has_highlighted_hint { let point = term::viewport_to_point(display_offset, cell.point); let hyperlink = cell.extra.as_ref().and_then(|extra| extra.hyperlink.as_ref()); let should_highlight = |hint: &Option<HintMatch>| { hint.as_ref().is_some_and(|hint| hint.should_highlight(point, hyperlink)) }; if should_highlight(highlighted_hint) || should_highlight(vi_highlighted_hint) { damage_tracker.frame().damage_point(cell.point); cell.flags.insert(Flags::UNDERLINE); } } // Update underline/strikeout. lines.update(&cell); cell }); self.renderer.draw_cells(&size_info, glyph_cache, cells); } let mut rects = lines.rects(&metrics, &size_info); if let Some(vi_cursor_point) = vi_cursor_point { // Indicate vi mode by showing the cursor's position in the top right corner. let line = (-vi_cursor_point.line.0 + size_info.bottommost_line().0) as usize; let obstructed_column = Some(vi_cursor_point) .filter(|point| point.line == -(display_offset as i32)) .map(|point| point.column); self.draw_line_indicator(config, total_lines, obstructed_column, line); } else if search_state.regex().is_some() { // Show current display offset in vi-less search to indicate match position. self.draw_line_indicator(config, total_lines, None, display_offset); }; // Draw cursor. rects.extend(cursor.rects(&size_info, config.cursor.thickness())); // Push visual bell after url/underline/strikeout rects. let visual_bell_intensity = self.visual_bell.intensity(); if visual_bell_intensity != 0. { let visual_bell_rect = RenderRect::new( 0., 0., size_info.width(), size_info.height(), config.bell.color, visual_bell_intensity as f32, ); rects.push(visual_bell_rect); } // Handle IME positioning and search bar rendering. let ime_position = match search_state.regex() { Some(regex) => { let search_label = match search_state.direction() { Direction::Right => FORWARD_SEARCH_LABEL, Direction::Left => BACKWARD_SEARCH_LABEL, }; let search_text = Self::format_search(regex, search_label, size_info.columns()); // Render the search bar. self.draw_search(config, &search_text); // Draw search bar cursor. let line = size_info.screen_lines(); let column = Column(search_text.chars().count() - 1); // Add cursor to search bar if IME is not active. if self.ime.preedit().is_none() { let fg = config.colors.footer_bar_foreground(); let shape = CursorShape::Underline; let cursor_width = NonZeroU32::new(1).unwrap(); let cursor = RenderableCursor::new(Point::new(line, column), shape, fg, cursor_width); rects.extend(cursor.rects(&size_info, config.cursor.thickness())); } Some(Point::new(line, column)) }, None => { let num_lines = self.size_info.screen_lines(); match vi_cursor_viewport_point { None => term::point_to_viewport(display_offset, cursor_point) .filter(|point| point.line < num_lines), point => point, } }, }; // Handle IME. if self.ime.is_enabled() { if let Some(point) = ime_position { let (fg, bg) = if search_state.regex().is_some() { (config.colors.footer_bar_foreground(), config.colors.footer_bar_background()) } else { (foreground_color, background_color) }; self.draw_ime_preview(point, fg, bg, &mut rects, config); } } if let Some(message) = message_buffer.message() { let search_offset = usize::from(search_state.regex().is_some()); let text = message.text(&size_info);
rust
Apache-2.0
6ee6e53ee3457c24137f117237b0ff1d84f6f836
2026-01-04T15:31:58.707223Z
true
alacritty/alacritty
https://github.com/alacritty/alacritty/blob/6ee6e53ee3457c24137f117237b0ff1d84f6f836/alacritty/src/display/window.rs
alacritty/src/display/window.rs
#[cfg(not(any(target_os = "macos", windows)))] use winit::platform::startup_notify::{ self, EventLoopExtStartupNotify, WindowAttributesExtStartupNotify, }; #[cfg(not(any(target_os = "macos", windows)))] use winit::window::ActivationToken; #[cfg(all(not(feature = "x11"), not(any(target_os = "macos", windows))))] use winit::platform::wayland::WindowAttributesExtWayland; #[rustfmt::skip] #[cfg(all(feature = "x11", not(any(target_os = "macos", windows))))] use { std::io::Cursor, winit::platform::x11::{WindowAttributesExtX11, ActiveEventLoopExtX11}, glutin::platform::x11::X11VisualInfo, winit::window::Icon, png::Decoder, }; use std::fmt::{self, Display, Formatter}; #[cfg(target_os = "macos")] use { objc2::MainThreadMarker, objc2_app_kit::{NSColorSpace, NSView}, winit::platform::macos::{OptionAsAlt, WindowAttributesExtMacOS, WindowExtMacOS}, }; use bitflags::bitflags; use winit::dpi::{PhysicalPosition, PhysicalSize}; use winit::event_loop::ActiveEventLoop; use winit::monitor::MonitorHandle; #[cfg(windows)] use winit::platform::windows::{IconExtWindows, WindowAttributesExtWindows}; use winit::raw_window_handle::{HasWindowHandle, RawWindowHandle}; use winit::window::{ CursorIcon, Fullscreen, ImePurpose, Theme, UserAttentionType, Window as WinitWindow, WindowAttributes, WindowId, }; use alacritty_terminal::index::Point; use crate::cli::WindowOptions; use crate::config::UiConfig; use crate::config::window::{Decorations, Identity, WindowConfig}; use crate::display::SizeInfo; /// Window icon for `_NET_WM_ICON` property. #[cfg(all(feature = "x11", not(any(target_os = "macos", windows))))] const WINDOW_ICON: &[u8] = include_bytes!("../../extra/logo/compat/alacritty-term.png"); /// This should match the definition of IDI_ICON from `alacritty.rc`. #[cfg(windows)] const IDI_ICON: u16 = 0x101; /// Window errors. #[derive(Debug)] pub enum Error { /// Error creating the window. WindowCreation(winit::error::OsError), /// Error dealing with fonts. Font(crossfont::Error), } /// Result of fallible operations concerning a Window. type Result<T> = std::result::Result<T, Error>; impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { Error::WindowCreation(err) => err.source(), Error::Font(err) => err.source(), } } } impl Display for Error { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { Error::WindowCreation(err) => write!(f, "Error creating GL context; {err}"), Error::Font(err) => err.fmt(f), } } } impl From<winit::error::OsError> for Error { fn from(val: winit::error::OsError) -> Self { Error::WindowCreation(val) } } impl From<crossfont::Error> for Error { fn from(val: crossfont::Error) -> Self { Error::Font(val) } } /// A window which can be used for displaying the terminal. /// /// Wraps the underlying windowing library to provide a stable API in Alacritty. pub struct Window { /// Flag tracking that we have a frame we can draw. pub has_frame: bool, /// Cached scale factor for quickly scaling pixel sizes. pub scale_factor: f64, /// Flag indicating whether redraw was requested. pub requested_redraw: bool, /// Hold the window when terminal exits. pub hold: bool, window: WinitWindow, /// Current window title. title: String, is_x11: bool, current_mouse_cursor: CursorIcon, mouse_visible: bool, ime_inhibitor: ImeInhibitor, } impl Window { /// Create a new window. /// /// This creates a window and fully initializes a window. pub fn new( event_loop: &ActiveEventLoop, config: &UiConfig, identity: &Identity, options: &mut WindowOptions, #[rustfmt::skip] #[cfg(all(feature = "x11", not(any(target_os = "macos", windows))))] x11_visual: Option<X11VisualInfo>, ) -> Result<Window> { let identity = identity.clone(); let mut window_attributes = Window::get_platform_window( &identity, &config.window, #[cfg(all(feature = "x11", not(any(target_os = "macos", windows))))] x11_visual, #[cfg(target_os = "macos")] &options.window_tabbing_id.take(), ); if let Some(position) = config.window.position { window_attributes = window_attributes .with_position(PhysicalPosition::<i32>::from((position.x, position.y))); } #[cfg(not(any(target_os = "macos", windows)))] if let Some(token) = options .activation_token .take() .map(ActivationToken::from_raw) .or_else(|| event_loop.read_token_from_env()) { log::debug!("Activating window with token: {token:?}"); window_attributes = window_attributes.with_activation_token(token); // Remove the token from the env. startup_notify::reset_activation_token_env(); } // On X11, embed the window inside another if the parent ID has been set. #[cfg(all(feature = "x11", not(any(target_os = "macos", windows))))] if let Some(parent_window_id) = event_loop.is_x11().then_some(config.window.embed).flatten() { window_attributes = window_attributes.with_embed_parent_window(parent_window_id); } window_attributes = window_attributes .with_title(&identity.title) .with_theme(config.window.theme()) .with_visible(false) .with_transparent(true) .with_blur(config.window.blur) .with_maximized(config.window.maximized()) .with_fullscreen(config.window.fullscreen()) .with_window_level(config.window.level.into()); let window = event_loop.create_window(window_attributes)?; // Text cursor. let current_mouse_cursor = CursorIcon::Text; window.set_cursor(current_mouse_cursor); // Enable IME. window.set_ime_allowed(true); window.set_ime_purpose(ImePurpose::Terminal); // Set initial transparency hint. window.set_transparent(config.window_opacity() < 1.); #[cfg(target_os = "macos")] use_srgb_color_space(&window); let scale_factor = window.scale_factor(); log::info!("Window scale factor: {scale_factor}"); let is_x11 = matches!(window.window_handle().unwrap().as_raw(), RawWindowHandle::Xlib(_)); Ok(Self { hold: options.terminal_options.hold, requested_redraw: false, title: identity.title, current_mouse_cursor, mouse_visible: true, has_frame: true, scale_factor, window, is_x11, ime_inhibitor: Default::default(), }) } #[inline] pub fn raw_window_handle(&self) -> RawWindowHandle { self.window.window_handle().unwrap().as_raw() } #[inline] pub fn request_inner_size(&self, size: PhysicalSize<u32>) { let _ = self.window.request_inner_size(size); } #[inline] pub fn inner_size(&self) -> PhysicalSize<u32> { self.window.inner_size() } #[inline] pub fn set_visible(&self, visibility: bool) { self.window.set_visible(visibility); } #[cfg(target_os = "macos")] #[inline] pub fn focus_window(&self) { self.window.focus_window(); } /// Set the window title. #[inline] pub fn set_title(&mut self, title: String) { self.title = title; self.window.set_title(&self.title); } /// Get the window title. #[inline] pub fn title(&self) -> &str { &self.title } #[inline] pub fn request_redraw(&mut self) { if !self.requested_redraw { self.requested_redraw = true; self.window.request_redraw(); } } #[inline] pub fn set_mouse_cursor(&mut self, cursor: CursorIcon) { if cursor != self.current_mouse_cursor { self.current_mouse_cursor = cursor; self.window.set_cursor(cursor); } } /// Set mouse cursor visible. pub fn set_mouse_visible(&mut self, visible: bool) { if visible != self.mouse_visible { self.mouse_visible = visible; self.window.set_cursor_visible(visible); } } #[inline] pub fn mouse_visible(&self) -> bool { self.mouse_visible } #[cfg(not(any(target_os = "macos", windows)))] pub fn get_platform_window( identity: &Identity, window_config: &WindowConfig, #[cfg(all(feature = "x11", not(any(target_os = "macos", windows))))] x11_visual: Option< X11VisualInfo, >, ) -> WindowAttributes { #[cfg(feature = "x11")] let icon = { let mut decoder = Decoder::new(Cursor::new(WINDOW_ICON)); decoder.set_transformations(png::Transformations::normalize_to_color8()); let mut reader = decoder.read_info().expect("invalid embedded icon"); let mut buf = vec![0; reader.output_buffer_size()]; let _ = reader.next_frame(&mut buf); Icon::from_rgba(buf, reader.info().width, reader.info().height) .expect("invalid embedded icon format") }; let builder = WinitWindow::default_attributes() .with_name(&identity.class.general, &identity.class.instance) .with_decorations(window_config.decorations != Decorations::None); #[cfg(feature = "x11")] let builder = builder.with_window_icon(Some(icon)); #[cfg(feature = "x11")] let builder = match x11_visual { Some(visual) => builder.with_x11_visual(visual.visual_id() as u32), None => builder, }; builder } #[cfg(windows)] pub fn get_platform_window(_: &Identity, window_config: &WindowConfig) -> WindowAttributes { let icon = winit::window::Icon::from_resource(IDI_ICON, None); WinitWindow::default_attributes() .with_decorations(window_config.decorations != Decorations::None) .with_window_icon(icon.as_ref().ok().cloned()) .with_taskbar_icon(icon.ok()) } #[cfg(target_os = "macos")] pub fn get_platform_window( _: &Identity, window_config: &WindowConfig, tabbing_id: &Option<String>, ) -> WindowAttributes { let mut window = WinitWindow::default_attributes().with_option_as_alt(window_config.option_as_alt()); if let Some(tabbing_id) = tabbing_id { window = window.with_tabbing_identifier(tabbing_id); } match window_config.decorations { Decorations::Full => window, Decorations::Transparent => window .with_title_hidden(true) .with_titlebar_transparent(true) .with_fullsize_content_view(true), Decorations::Buttonless => window .with_title_hidden(true) .with_titlebar_buttons_hidden(true) .with_titlebar_transparent(true) .with_fullsize_content_view(true), Decorations::None => window.with_titlebar_hidden(true), } } pub fn set_urgent(&self, is_urgent: bool) { let attention = if is_urgent { Some(UserAttentionType::Critical) } else { None }; self.window.request_user_attention(attention); } pub fn id(&self) -> WindowId { self.window.id() } pub fn set_transparent(&self, transparent: bool) { self.window.set_transparent(transparent); } pub fn set_blur(&self, blur: bool) { self.window.set_blur(blur); } pub fn set_maximized(&self, maximized: bool) { self.window.set_maximized(maximized); } pub fn set_minimized(&self, minimized: bool) { self.window.set_minimized(minimized); } pub fn set_resize_increments(&self, increments: PhysicalSize<f32>) { self.window.set_resize_increments(Some(increments)); } /// Toggle the window's fullscreen state. pub fn toggle_fullscreen(&self) { self.set_fullscreen(self.window.fullscreen().is_none()); } /// Toggle the window's maximized state. pub fn toggle_maximized(&self) { self.set_maximized(!self.window.is_maximized()); } /// Inform windowing system about presenting to the window. /// /// Should be called right before presenting to the window with e.g. `eglSwapBuffers`. pub fn pre_present_notify(&self) { self.window.pre_present_notify(); } pub fn set_theme(&self, theme: Option<Theme>) { self.window.set_theme(theme); } #[cfg(target_os = "macos")] pub fn toggle_simple_fullscreen(&self) { self.set_simple_fullscreen(!self.window.simple_fullscreen()); } #[cfg(target_os = "macos")] pub fn set_option_as_alt(&self, option_as_alt: OptionAsAlt) { self.window.set_option_as_alt(option_as_alt); } pub fn set_fullscreen(&self, fullscreen: bool) { if fullscreen { self.window.set_fullscreen(Some(Fullscreen::Borderless(None))); } else { self.window.set_fullscreen(None); } } pub fn current_monitor(&self) -> Option<MonitorHandle> { self.window.current_monitor() } #[cfg(target_os = "macos")] pub fn set_simple_fullscreen(&self, simple_fullscreen: bool) { self.window.set_simple_fullscreen(simple_fullscreen); } /// Set IME inhibitor state and disable IME while any are present. /// /// IME is re-enabled once all inhibitors are unset. pub fn set_ime_inhibitor(&mut self, inhibitor: ImeInhibitor, inhibit: bool) { if self.ime_inhibitor.contains(inhibitor) != inhibit { self.ime_inhibitor.set(inhibitor, inhibit); self.window.set_ime_allowed(self.ime_inhibitor.is_empty()); } } /// Adjust the IME editor position according to the new location of the cursor. pub fn update_ime_position(&self, point: Point<usize>, size: &SizeInfo) { // NOTE: X11 doesn't support cursor area, so we need to offset manually to not obscure // the text. let offset = if self.is_x11 { 1 } else { 0 }; let nspot_x = f64::from(size.padding_x() + point.column.0 as f32 * size.cell_width()); let nspot_y = f64::from(size.padding_y() + (point.line + offset) as f32 * size.cell_height()); // NOTE: some compositors don't like excluding too much and try to render popup at the // bottom right corner of the provided area, so exclude just the full-width char to not // obscure the cursor and not render popup at the end of the window. let width = size.cell_width() as f64 * 2.; let height = size.cell_height as f64; self.window.set_ime_cursor_area( PhysicalPosition::new(nspot_x, nspot_y), PhysicalSize::new(width, height), ); } /// Disable macOS window shadows. /// /// This prevents rendering artifacts from showing up when the window is transparent. #[cfg(target_os = "macos")] pub fn set_has_shadow(&self, has_shadows: bool) { let view = match self.raw_window_handle() { RawWindowHandle::AppKit(handle) => { assert!(MainThreadMarker::new().is_some()); unsafe { handle.ns_view.cast::<NSView>().as_ref() } }, _ => return, }; view.window().unwrap().setHasShadow(has_shadows); } /// Select tab at the given `index`. #[cfg(target_os = "macos")] pub fn select_tab_at_index(&self, index: usize) { self.window.select_tab_at_index(index); } /// Select the last tab. #[cfg(target_os = "macos")] pub fn select_last_tab(&self) { self.window.select_tab_at_index(self.window.num_tabs() - 1); } /// Select next tab. #[cfg(target_os = "macos")] pub fn select_next_tab(&self) { self.window.select_next_tab(); } /// Select previous tab. #[cfg(target_os = "macos")] pub fn select_previous_tab(&self) { self.window.select_previous_tab(); } #[cfg(target_os = "macos")] pub fn tabbing_id(&self) -> String { self.window.tabbing_identifier() } } bitflags! { /// IME inhibition sources. #[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct ImeInhibitor: u8 { const FOCUS = 1; const TOUCH = 1 << 1; const VI = 1 << 2; } } #[cfg(target_os = "macos")] fn use_srgb_color_space(window: &WinitWindow) { let view = match window.window_handle().unwrap().as_raw() { RawWindowHandle::AppKit(handle) => { assert!(MainThreadMarker::new().is_some()); unsafe { handle.ns_view.cast::<NSView>().as_ref() } }, _ => return, }; view.window().unwrap().setColorSpace(Some(&NSColorSpace::sRGBColorSpace())); }
rust
Apache-2.0
6ee6e53ee3457c24137f117237b0ff1d84f6f836
2026-01-04T15:31:58.707223Z
false
alacritty/alacritty
https://github.com/alacritty/alacritty/blob/6ee6e53ee3457c24137f117237b0ff1d84f6f836/alacritty/src/display/hint.rs
alacritty/src/display/hint.rs
use std::borrow::Cow; use std::cmp::Reverse; use std::collections::HashSet; use std::iter; use std::rc::Rc; use ahash::RandomState; use winit::keyboard::ModifiersState; use alacritty_terminal::grid::{BidirectionalIterator, Dimensions}; use alacritty_terminal::index::{Boundary, Column, Direction, Line, Point}; use alacritty_terminal::term::cell::Hyperlink; use alacritty_terminal::term::search::{Match, RegexIter, RegexSearch}; use alacritty_terminal::term::{Term, TermMode}; use crate::config::UiConfig; use crate::config::ui_config::{Hint, HintAction}; /// Maximum number of linewraps followed outside of the viewport during search highlighting. pub const MAX_SEARCH_LINES: usize = 100; /// Percentage of characters in the hints alphabet used for the last character. const HINT_SPLIT_PERCENTAGE: f32 = 0.5; /// Keyboard regex hint state. pub struct HintState { /// Hint currently in use. hint: Option<Rc<Hint>>, /// Alphabet for hint labels. alphabet: String, /// Visible matches. matches: Vec<Match>, /// Key label for each visible match. labels: Vec<Vec<char>>, /// Keys pressed for hint selection. keys: Vec<char>, } impl HintState { /// Initialize an inactive hint state. pub fn new<S: Into<String>>(alphabet: S) -> Self { Self { alphabet: alphabet.into(), hint: Default::default(), matches: Default::default(), labels: Default::default(), keys: Default::default(), } } /// Check if a hint selection is in progress. pub fn active(&self) -> bool { self.hint.is_some() } /// Start the hint selection process. pub fn start(&mut self, hint: Rc<Hint>) { self.hint = Some(hint); } /// Cancel the hint highlighting process. fn stop(&mut self) { self.matches.clear(); self.labels.clear(); self.keys.clear(); self.hint = None; } /// Update the visible hint matches and key labels. pub fn update_matches<T>(&mut self, term: &Term<T>) { let hint = match self.hint.as_mut() { Some(hint) => hint, None => return, }; // Clear current matches. self.matches.clear(); // Add escape sequence hyperlinks. if hint.content.hyperlinks { self.matches.extend(visible_unique_hyperlinks_iter(term)); } // Add visible regex matches. if let Some(regex) = hint.content.regex.as_ref() { regex.with_compiled(|regex| { let matches = visible_regex_match_iter(term, regex); // Apply post-processing and search for sub-matches if necessary. if hint.post_processing { let mut matches = matches.collect::<Vec<_>>(); self.matches.extend(matches.drain(..).flat_map(|rm| { HintPostProcessor::new(term, regex, rm).collect::<Vec<_>>() })); } else { self.matches.extend(matches); } }); } // Cancel highlight with no visible matches. if self.matches.is_empty() { self.stop(); return; } // Sort and dedup ranges. Currently overlapped but not exactly same ranges are kept. self.matches.sort_by_key(|bounds| (*bounds.start(), Reverse(*bounds.end()))); self.matches.dedup_by_key(|bounds| *bounds.start()); let mut generator = HintLabels::new(&self.alphabet, HINT_SPLIT_PERCENTAGE); let match_count = self.matches.len(); let keys_len = self.keys.len(); // Get the label for each match. self.labels.resize(match_count, Vec::new()); for i in (0..match_count).rev() { let mut label = generator.next(); if label.len() >= keys_len && label[..keys_len] == self.keys[..] { self.labels[i] = label.split_off(keys_len); } else { self.labels[i] = Vec::new(); } } } /// Handle keyboard input during hint selection. pub fn keyboard_input<T>(&mut self, term: &Term<T>, c: char) -> Option<HintMatch> { match c { // Use backspace to remove the last character pressed. '\x08' | '\x1f' => { self.keys.pop(); }, // Cancel hint highlighting on ESC/Ctrl+c. '\x1b' | '\x03' => self.stop(), _ => (), } // Update the visible matches. self.update_matches(term); let hint = self.hint.as_ref()?; // Find the last label starting with the input character. let mut labels = self.labels.iter().enumerate().rev(); let (index, label) = labels.find(|(_, label)| !label.is_empty() && label[0] == c)?; // Check if the selected label is fully matched. if label.len() == 1 { let bounds = self.matches[index].clone(); let hint = hint.clone(); // Exit hint mode unless it requires explicit dismissal. if hint.persist { self.keys.clear(); } else { self.stop(); } // Hyperlinks take precedence over regex matches. let hyperlink = term.grid()[*bounds.start()].hyperlink(); Some(HintMatch { bounds, hyperlink, hint }) } else { // Store character to preserve the selection. self.keys.push(c); None } } /// Hint key labels. pub fn labels(&self) -> &Vec<Vec<char>> { &self.labels } /// Visible hint regex matches. pub fn matches(&self) -> &[Match] { &self.matches } /// Update the alphabet used for hint labels. pub fn update_alphabet(&mut self, alphabet: &str) { if self.alphabet != alphabet { alphabet.clone_into(&mut self.alphabet); self.keys.clear(); } } } /// Hint match which was selected by the user. #[derive(PartialEq, Eq, Debug, Clone)] pub struct HintMatch { /// Terminal range matching the hint. bounds: Match, /// OSC 8 hyperlink. hyperlink: Option<Hyperlink>, /// Hint which triggered this match. hint: Rc<Hint>, } impl HintMatch { #[inline] pub fn should_highlight(&self, point: Point, pointed_hyperlink: Option<&Hyperlink>) -> bool { self.hyperlink.as_ref() == pointed_hyperlink && (self.hyperlink.is_some() || self.bounds.contains(&point)) } #[inline] pub fn action(&self) -> &HintAction { &self.hint.action } #[inline] pub fn bounds(&self) -> &Match { &self.bounds } pub fn hyperlink(&self) -> Option<&Hyperlink> { self.hyperlink.as_ref() } /// Get the text content of the hint match. /// /// This will always revalidate the hint text, to account for terminal content /// changes since the [`HintMatch`] was constructed. The text of the hint might /// be different from its original value, but it will **always** be a valid /// match for this hint. pub fn text<T>(&self, term: &Term<T>) -> Option<Cow<'_, str>> { // Revalidate hyperlink match. if let Some(hyperlink) = &self.hyperlink { let (validated, bounds) = hyperlink_at(term, *self.bounds.start())?; return (&validated == hyperlink && bounds == self.bounds) .then(|| hyperlink.uri().into()); } // Revalidate regex match. let regex = self.hint.content.regex.as_ref()?; let bounds = regex.with_compiled(|regex| { regex_match_at(term, *self.bounds.start(), regex, self.hint.post_processing) })??; (bounds == self.bounds) .then(|| term.bounds_to_string(*bounds.start(), *bounds.end()).into()) } } /// Generator for creating new hint labels. struct HintLabels { /// Full character set available. alphabet: Vec<char>, /// Alphabet indices for the next label. indices: Vec<usize>, /// Point separating the alphabet's head and tail characters. /// /// To make identification of the tail character easy, part of the alphabet cannot be used for /// any other position. /// /// All characters in the alphabet before this index will be used for the last character, while /// the rest will be used for everything else. split_point: usize, } impl HintLabels { /// Create a new label generator. /// /// The `split_ratio` should be a number between 0.0 and 1.0 representing the percentage of /// elements in the alphabet which are reserved for the tail of the hint label. fn new(alphabet: impl Into<String>, split_ratio: f32) -> Self { let alphabet: Vec<char> = alphabet.into().chars().collect(); let split_point = ((alphabet.len() - 1) as f32 * split_ratio.min(1.)) as usize; Self { indices: vec![0], split_point, alphabet } } /// Get the characters for the next label. fn next(&mut self) -> Vec<char> { let characters = self.indices.iter().rev().map(|index| self.alphabet[*index]).collect(); self.increment(); characters } /// Increment the character sequence. fn increment(&mut self) { // Increment the last character; if it's not at the split point we're done. let tail = &mut self.indices[0]; if *tail < self.split_point { *tail += 1; return; } *tail = 0; // Increment all other characters in reverse order. let alphabet_len = self.alphabet.len(); for index in self.indices.iter_mut().skip(1) { if *index + 1 == alphabet_len { // Reset character and move to the next if it's already at the limit. *index = self.split_point + 1; } else { // If the character can be incremented, we're done. *index += 1; return; } } // Extend the sequence with another character when nothing could be incremented. self.indices.push(self.split_point + 1); } } /// Iterate over all visible regex matches. pub fn visible_regex_match_iter<'a, T>( term: &'a Term<T>, regex: &'a mut RegexSearch, ) -> impl Iterator<Item = Match> + 'a { let viewport_start = Line(-(term.grid().display_offset() as i32)); let viewport_end = viewport_start + term.bottommost_line(); let mut start = term.line_search_left(Point::new(viewport_start, Column(0))); let mut end = term.line_search_right(Point::new(viewport_end, Column(0))); start.line = start.line.max(viewport_start - MAX_SEARCH_LINES); end.line = end.line.min(viewport_end + MAX_SEARCH_LINES); RegexIter::new(start, end, Direction::Right, term, regex) .skip_while(move |rm| rm.end().line < viewport_start) .take_while(move |rm| rm.start().line <= viewport_end) } /// Iterate over all visible hyperlinks, yanking only unique ones. pub fn visible_unique_hyperlinks_iter<T>(term: &Term<T>) -> impl Iterator<Item = Match> + '_ { let mut display_iter = term.grid().display_iter().peekable(); // Avoid creating hints for the same hyperlinks, but from a different places. let mut unique_hyperlinks = HashSet::<Hyperlink, RandomState>::default(); iter::from_fn(move || { // Find the start of the next unique hyperlink. let (cell, hyperlink) = display_iter.find_map(|cell| { let hyperlink = cell.hyperlink()?; (!unique_hyperlinks.contains(&hyperlink)).then(|| { unique_hyperlinks.insert(hyperlink.clone()); (cell, hyperlink) }) })?; let start = cell.point; let mut end = start; // Find the end bound of just found unique hyperlink. while let Some(next_cell) = display_iter.peek() { // Cell at display iter doesn't match, yield the hyperlink and start over with // `find_map`. if next_cell.hyperlink().as_ref() != Some(&hyperlink) { break; } // Advance to the next cell. end = next_cell.point; let _ = display_iter.next(); } Some(start..=end) }) } /// Retrieve the match, if the specified point is inside the content matching the regex. fn regex_match_at<T>( term: &Term<T>, point: Point, regex: &mut RegexSearch, post_processing: bool, ) -> Option<Match> { let regex_match = visible_regex_match_iter(term, regex).find(|rm| rm.contains(&point))?; // Apply post-processing and search for sub-matches if necessary. if post_processing { HintPostProcessor::new(term, regex, regex_match).find(|rm| rm.contains(&point)) } else { Some(regex_match) } } /// Check if there is a hint highlighted at the specified point. pub fn highlighted_at<T>( term: &Term<T>, config: &UiConfig, point: Point, mouse_mods: ModifiersState, ) -> Option<HintMatch> { let mouse_mode = term.mode().intersects(TermMode::MOUSE_MODE); config.hints.enabled.iter().find_map(|hint| { // Check if all required modifiers are pressed. let highlight = hint.mouse.is_some_and(|mouse| { mouse.enabled && mouse_mods.contains(mouse.mods.0) && (!mouse_mode || mouse_mods.contains(ModifiersState::SHIFT)) }); if !highlight { return None; } if let Some((hyperlink, bounds)) = hint.content.hyperlinks.then(|| hyperlink_at(term, point)).flatten() { return Some(HintMatch { bounds, hyperlink: Some(hyperlink), hint: hint.clone() }); } let bounds = hint.content.regex.as_ref().and_then(|regex| { regex.with_compiled(|regex| regex_match_at(term, point, regex, hint.post_processing)) }); if let Some(bounds) = bounds.flatten() { return Some(HintMatch { bounds, hint: hint.clone(), hyperlink: None }); } None }) } /// Retrieve the hyperlink with its range, if there is one at the specified point. /// /// This will only return contiguous cells, even if another hyperlink with the same ID exists. fn hyperlink_at<T>(term: &Term<T>, point: Point) -> Option<(Hyperlink, Match)> { let hyperlink = term.grid()[point].hyperlink()?; let grid = term.grid(); let mut match_end = point; for cell in grid.iter_from(point) { if cell.hyperlink().is_some_and(|link| link == hyperlink) { match_end = cell.point; } else { break; } } let mut match_start = point; let mut iter = grid.iter_from(point); while let Some(cell) = iter.prev() { if cell.hyperlink().is_some_and(|link| link == hyperlink) { match_start = cell.point; } else { break; } } Some((hyperlink, match_start..=match_end)) } /// Iterator over all post-processed matches inside an existing hint match. struct HintPostProcessor<'a, T> { /// Regex search DFAs. regex: &'a mut RegexSearch, /// Terminal reference. term: &'a Term<T>, /// Next hint match in the iterator. next_match: Option<Match>, /// Start point for the next search. start: Point, /// End point for the hint match iterator. end: Point, } impl<'a, T> HintPostProcessor<'a, T> { /// Create a new iterator for an unprocessed match. fn new(term: &'a Term<T>, regex: &'a mut RegexSearch, regex_match: Match) -> Self { let mut post_processor = Self { next_match: None, start: *regex_match.start(), end: *regex_match.end(), term, regex, }; // Post-process the first hint match. post_processor.next_processed_match(regex_match); post_processor } /// Apply some hint post processing heuristics. /// /// This will check the end of the hint and make it shorter if certain characters are determined /// to be unlikely to be intentionally part of the hint. /// /// This is most useful for identifying URLs appropriately. fn hint_post_processing(&self, regex_match: &Match) -> Option<Match> { let mut iter = self.term.grid().iter_from(*regex_match.start()); let mut c = iter.cell().c; // Truncate uneven number of brackets. let end = *regex_match.end(); let mut open_parents = 0; let mut open_brackets = 0; loop { match c { '(' => open_parents += 1, '[' => open_brackets += 1, ')' => { if open_parents == 0 { iter.prev(); break; } else { open_parents -= 1; } }, ']' => { if open_brackets == 0 { iter.prev(); break; } else { open_brackets -= 1; } }, _ => (), } if iter.point() == end { break; } match iter.next() { Some(indexed) => c = indexed.cell.c, None => break, } } // Truncate trailing characters which are likely to be delimiters. let start = *regex_match.start(); while iter.point() != start { if !matches!(c, '.' | ',' | ':' | ';' | '?' | '!' | '(' | '[' | '\'') { break; } match iter.prev() { Some(indexed) => c = indexed.cell.c, None => break, } } if start > iter.point() { None } else { Some(start..=iter.point()) } } /// Loop over submatches until a non-empty post-processed match is found. fn next_processed_match(&mut self, mut regex_match: Match) { self.next_match = loop { if let Some(next_match) = self.hint_post_processing(&regex_match) { self.start = next_match.end().add(self.term, Boundary::Grid, 1); break Some(next_match); } self.start = regex_match.start().add(self.term, Boundary::Grid, 1); if self.start > self.end { return; } match self.term.regex_search_right(self.regex, self.start, self.end) { Some(rm) => regex_match = rm, None => return, } }; } } impl<T> Iterator for HintPostProcessor<'_, T> { type Item = Match; fn next(&mut self) -> Option<Self::Item> { let next_match = self.next_match.take()?; if self.start <= self.end { if let Some(rm) = self.term.regex_search_right(self.regex, self.start, self.end) { self.next_processed_match(rm); } } Some(next_match) } } #[cfg(test)] mod tests { use alacritty_terminal::index::{Column, Line}; use alacritty_terminal::term::test::mock_term; use alacritty_terminal::vte::ansi::Handler; use super::*; #[test] fn hint_label_generation() { let mut generator = HintLabels::new("0123", 0.5); assert_eq!(generator.next(), vec!['0']); assert_eq!(generator.next(), vec!['1']); assert_eq!(generator.next(), vec!['2', '0']); assert_eq!(generator.next(), vec!['2', '1']); assert_eq!(generator.next(), vec!['3', '0']); assert_eq!(generator.next(), vec!['3', '1']); assert_eq!(generator.next(), vec!['2', '2', '0']); assert_eq!(generator.next(), vec!['2', '2', '1']); assert_eq!(generator.next(), vec!['2', '3', '0']); assert_eq!(generator.next(), vec!['2', '3', '1']); assert_eq!(generator.next(), vec!['3', '2', '0']); assert_eq!(generator.next(), vec!['3', '2', '1']); assert_eq!(generator.next(), vec!['3', '3', '0']); assert_eq!(generator.next(), vec!['3', '3', '1']); assert_eq!(generator.next(), vec!['2', '2', '2', '0']); assert_eq!(generator.next(), vec!['2', '2', '2', '1']); assert_eq!(generator.next(), vec!['2', '2', '3', '0']); assert_eq!(generator.next(), vec!['2', '2', '3', '1']); assert_eq!(generator.next(), vec!['2', '3', '2', '0']); assert_eq!(generator.next(), vec!['2', '3', '2', '1']); assert_eq!(generator.next(), vec!['2', '3', '3', '0']); assert_eq!(generator.next(), vec!['2', '3', '3', '1']); assert_eq!(generator.next(), vec!['3', '2', '2', '0']); assert_eq!(generator.next(), vec!['3', '2', '2', '1']); assert_eq!(generator.next(), vec!['3', '2', '3', '0']); assert_eq!(generator.next(), vec!['3', '2', '3', '1']); assert_eq!(generator.next(), vec!['3', '3', '2', '0']); assert_eq!(generator.next(), vec!['3', '3', '2', '1']); assert_eq!(generator.next(), vec!['3', '3', '3', '0']); assert_eq!(generator.next(), vec!['3', '3', '3', '1']); } #[test] fn closed_bracket_does_not_result_in_infinite_iterator() { let term = mock_term(" ) "); let mut search = RegexSearch::new("[^/ ]").unwrap(); let count = HintPostProcessor::new( &term, &mut search, Point::new(Line(0), Column(1))..=Point::new(Line(0), Column(1)), ) .take(1) .count(); assert_eq!(count, 0); } #[test] fn collect_unique_hyperlinks() { let mut term = mock_term("000\r\n111"); term.goto(0, 0); let hyperlink_foo = Hyperlink::new(Some("1"), String::from("foo")); let hyperlink_bar = Hyperlink::new(Some("2"), String::from("bar")); // Create 2 hyperlinks on the first line. term.set_hyperlink(Some(hyperlink_foo.clone().into())); term.input('b'); term.input('a'); term.set_hyperlink(Some(hyperlink_bar.clone().into())); term.input('r'); term.set_hyperlink(Some(hyperlink_foo.clone().into())); term.goto(1, 0); // Ditto for the second line. term.set_hyperlink(Some(hyperlink_foo.into())); term.input('b'); term.input('a'); term.set_hyperlink(Some(hyperlink_bar.into())); term.input('r'); term.set_hyperlink(None); let mut unique_hyperlinks = visible_unique_hyperlinks_iter(&term); assert_eq!( Some(Match::new(Point::new(Line(0), Column(0)), Point::new(Line(0), Column(1)))), unique_hyperlinks.next() ); assert_eq!( Some(Match::new(Point::new(Line(0), Column(2)), Point::new(Line(0), Column(2)))), unique_hyperlinks.next() ); assert_eq!(None, unique_hyperlinks.next()); } #[test] fn visible_regex_match_covers_entire_viewport() { let content = "I'm a match!\r\n".repeat(4096); // The Term returned from this call will have a viewport starting at 0 and ending at 4096. // That's good enough for this test, since it only cares about visible content. let term = mock_term(&content); let mut regex = RegexSearch::new("match!").unwrap(); // The iterator should match everything in the viewport. assert_eq!(visible_regex_match_iter(&term, &mut regex).count(), 4096); } }
rust
Apache-2.0
6ee6e53ee3457c24137f117237b0ff1d84f6f836
2026-01-04T15:31:58.707223Z
false