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
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/features/mod.rs
src/features/mod.rs
use std::collections::HashMap; use crate::cli; use crate::git_config::GitConfig; use crate::options::option_value::ProvenancedOptionValue; use ProvenancedOptionValue::*; /// A custom feature is a named set of command line (option, value) pairs, supplied in a git config /// file. I.e. it might look like /// /// [delta "decorations"] /// commit-decoration-style = bold box ul /// file-style = bold 19 ul /// file-decoration-style = none /// /// A builtin feature is a named set of command line (option, value) pairs that is built-in to /// delta. The valueof a builtin feature is a function. This function is passed the current set of /// all command-line option-value pairs, and GitConfig, and returns either a GitConfigValue, or a /// DefaultValue. (It may use the set of all option-value pairs when computing its default). pub type BuiltinFeature = HashMap<String, OptionValueFunction>; type OptionValueFunction = Box<dyn Fn(&cli::Opt, &Option<GitConfig>) -> ProvenancedOptionValue>; // Construct a 2-level hash map: (feature name) -> (option name) -> (value function). A value // function is a function that takes an Opt struct, and a git Config struct, and returns the value // for the option. pub fn make_builtin_features() -> HashMap<String, BuiltinFeature> { vec![ ( "color-only".to_string(), color_only::make_feature().into_iter().collect(), ), ( "diff-highlight".to_string(), diff_highlight::make_feature().into_iter().collect(), ), ( "diff-so-fancy".to_string(), diff_so_fancy::make_feature().into_iter().collect(), ), ( "hyperlinks".to_string(), hyperlinks::make_feature().into_iter().collect(), ), ( "line-numbers".to_string(), line_numbers::make_feature().into_iter().collect(), ), ( "navigate".to_string(), navigate::make_feature().into_iter().collect(), ), ("raw".to_string(), raw::make_feature().into_iter().collect()), ( "side-by-side".to_string(), side_by_side::make_feature().into_iter().collect(), ), ] .into_iter() .collect() } /// The macro permits the values of a builtin feature to be specified as either (a) a git config /// entry or (b) a value, which may be computed from the other command line options (cli::Opt). macro_rules! builtin_feature { ([$( ($option_name:expr, $type:ty, $git_config_key:expr, $opt:ident => $value:expr) ),*]) => { vec![$( ( $option_name.to_string(), Box::new(move |$opt: &$crate::cli::Opt, git_config: &Option<$crate::git_config::GitConfig>| { match (git_config, $git_config_key) { (Some(git_config), Some(git_config_key)) => git_config.get::<$type>(git_config_key).map(|value| $crate::features::GitConfigValue(value.into())), _ => None, } .unwrap_or_else(|| $crate::features::DefaultValue($value.into())) }) as OptionValueFunction ) ),*] } } pub mod color_only; pub mod diff_highlight; pub mod diff_so_fancy; pub mod hyperlinks; pub mod line_numbers; pub mod navigate; pub mod raw; pub mod side_by_side; #[cfg(test)] pub mod tests { use std::collections::HashSet; use std::fs::remove_file; use crate::cli; use crate::env::DeltaEnv; use crate::features::make_builtin_features; use crate::tests::integration_test_utils::make_options_from_args_and_git_config; #[test] fn test_builtin_features_have_flags_and_these_set_features() { let builtin_features = make_builtin_features(); let mut args = vec!["delta".to_string()]; args.extend(builtin_features.keys().map(|s| format!("--{s}"))); let opt = cli::Opt::from_iter_and_git_config(&DeltaEnv::default(), args, None); let features: HashSet<&str> = opt .features .as_deref() .unwrap_or("") .split_whitespace() .collect(); for feature in builtin_features.keys() { assert!(features.contains(feature.as_str())) } } #[test] fn test_builtin_feature_from_gitconfig() { let git_config_contents = b" [delta] navigate = true "; let git_config_path = "delta__test_builtin_feature_from_gitconfig.gitconfig"; assert_eq!( make_options_from_args_and_git_config( &[], Some(git_config_contents), Some(git_config_path) ) .features .unwrap(), "navigate" ); remove_file(git_config_path).unwrap(); } #[test] fn test_features_on_command_line_replace_features_in_gitconfig() { let git_config_contents = b" [delta] features = my-feature "; let git_config_path = "delta__test_features_on_command_line_replace_features_in_gitconfig.gitconfig"; assert_eq!( make_options_from_args_and_git_config( &["--features", "navigate raw"], Some(git_config_contents), Some(git_config_path), ) .features .unwrap(), "navigate raw" ); assert_eq!( make_options_from_args_and_git_config( &["--navigate", "--features", "raw"], Some(git_config_contents), Some(git_config_path), ) .features .unwrap(), "navigate raw" ); remove_file(git_config_path).unwrap(); } #[test] fn test_feature_flag_on_command_line_does_not_replace_features_in_gitconfig() { let git_config_contents = b" [delta] features = my-feature "; let git_config_path = "delta__test_feature_flag_on_command_line_does_not_replace_features_in_gitconfig.gitconfig"; assert_eq!( make_options_from_args_and_git_config( &["--navigate", "--raw"], Some(git_config_contents), Some(git_config_path), ) .features .unwrap(), "my-feature navigate raw" ); remove_file(git_config_path).unwrap(); } #[test] fn test_recursive_feature_gathering_1() { let git_config_contents = b" [delta] features = h g [delta \"a\"] features = c b diff-highlight = true [delta \"d\"] features = f e diff-so-fancy = true "; let git_config_path = "delta__test_feature_collection.gitconfig"; assert_eq!( make_options_from_args_and_git_config( &["--raw", "--features", "d a"], Some(git_config_contents), Some(git_config_path), ) .features .unwrap(), "raw diff-so-fancy f e d diff-highlight c b a" ); remove_file(git_config_path).unwrap(); } #[test] fn test_recursive_feature_gathering_2() { let git_config_contents = b" [delta] features = feature-1 [delta \"feature-1\"] features = feature-2 feature-3 [delta \"feature-2\"] features = feature-4 [delta \"feature-4\"] minus-style = blue "; let git_config_path = "delta__test_recursive_features.gitconfig"; let opt = make_options_from_args_and_git_config( &["delta"], Some(git_config_contents), Some(git_config_path), ); assert_eq!( opt.features.unwrap(), "feature-4 feature-2 feature-3 feature-1" ); remove_file(git_config_path).unwrap(); } #[test] fn test_main_section() { let git_config_contents = b" [delta] minus-style = blue "; let git_config_path = "delta__test_main_section.gitconfig"; // First check that it doesn't default to blue, because that's going to be used to signal // that gitconfig has set the style. assert_ne!( make_options_from_args_and_git_config(&[], None, None).minus_style, "blue" ); // Check that --minus-style is honored as we expect. assert_eq!( make_options_from_args_and_git_config(&["--minus-style", "red"], None, None) .minus_style, "red" ); // Check that gitconfig does not override a command line argument assert_eq!( make_options_from_args_and_git_config( &["--minus-style", "red"], Some(git_config_contents), Some(git_config_path), ) .minus_style, "red" ); // Finally, check that gitconfig is honored when not overridden by a command line argument. assert_eq!( make_options_from_args_and_git_config( &[], Some(git_config_contents), Some(git_config_path) ) .minus_style, "blue" ); remove_file(git_config_path).unwrap(); } #[test] fn test_feature() { let git_config_contents = b" [delta] [delta \"my-feature\"] minus-style = green "; let git_config_path = "delta__test_feature.gitconfig"; assert_eq!( make_options_from_args_and_git_config( &["--features", "my-feature"], Some(git_config_contents), Some(git_config_path), ) .minus_style, "green" ); remove_file(git_config_path).unwrap(); } #[test] fn test_main_section_overrides_feature() { let git_config_contents = b" [delta] minus-style = blue [delta \"my-feature-1\"] minus-style = green "; let git_config_path = "delta__test_main_section_overrides_feature.gitconfig"; // Without --features the main section takes effect assert_eq!( make_options_from_args_and_git_config( &[], Some(git_config_contents), Some(git_config_path) ) .minus_style, "blue" ); // Event with --features the main section overrides the feature. assert_eq!( make_options_from_args_and_git_config( &["--features", "my-feature-1"], Some(git_config_contents), Some(git_config_path), ) .minus_style, "blue" ); remove_file(git_config_path).unwrap(); } #[test] fn test_multiple_features() { let git_config_contents = b" [delta] [delta \"my-feature-1\"] minus-style = green [delta \"my-feature-2\"] minus-style = yellow "; let git_config_path = "delta__test_multiple_features.gitconfig"; assert_eq!( make_options_from_args_and_git_config( &["--features", "my-feature-1 my-feature-2"], Some(git_config_contents), Some(git_config_path), ) .minus_style, "yellow" ); assert_eq!( make_options_from_args_and_git_config( &["--features", "my-feature-2 my-feature-1"], Some(git_config_contents), Some(git_config_path), ) .minus_style, "green" ); remove_file(git_config_path).unwrap(); } #[test] fn test_invalid_features() { let git_config_contents = b" [delta \"my-feature-1\"] minus-style = green [delta \"my-feature-2\"] minus-style = yellow "; let git_config_path = "delta__test_invalid_features.gitconfig"; let default = make_options_from_args_and_git_config(&[], None, None).minus_style; assert_ne!(default, "green"); assert_ne!(default, "yellow"); assert_eq!( make_options_from_args_and_git_config( &["--features", "my-feature-1"], Some(git_config_contents), Some(git_config_path), ) .minus_style, "green" ); assert_eq!( make_options_from_args_and_git_config( &["--features", "my-feature-x"], Some(git_config_contents), Some(git_config_path), ) .minus_style, default ); assert_eq!( make_options_from_args_and_git_config( &["--features", "my-feature-1 my-feature-x"], Some(git_config_contents), Some(git_config_path), ) .minus_style, "green" ); assert_eq!( make_options_from_args_and_git_config( &["--features", "my-feature-x my-feature-2 my-feature-x"], Some(git_config_contents), Some(git_config_path), ) .minus_style, "yellow" ); remove_file(git_config_path).unwrap(); } #[test] fn test_whitespace_error_style() { let git_config_contents = b" [color \"diff\"] whitespace = yellow dim ul magenta "; let git_config_path = "delta__test_whitespace_error_style.gitconfig"; // Git config disabled: hard-coded delta default wins assert_eq!( make_options_from_args_and_git_config(&[], None, None).whitespace_error_style, "magenta reverse" ); // Unspecified by user: color.diff.whitespace wins assert_eq!( make_options_from_args_and_git_config( &[], Some(git_config_contents), Some(git_config_path) ) .whitespace_error_style, "yellow dim ul magenta" ); // Command line argument wins assert_eq!( make_options_from_args_and_git_config( &["--whitespace-error-style", "red reverse"], Some(git_config_contents), Some(git_config_path) ) .whitespace_error_style, "red reverse" ); let git_config_contents = b" [color \"diff\"] whitespace = yellow dim ul magenta [delta] whitespace-error-style = blue reverse [delta \"my-whitespace-error-style-feature\"] whitespace-error-style = green reverse "; // Command line argument wins assert_eq!( make_options_from_args_and_git_config( &["--whitespace-error-style", "red reverse"], Some(git_config_contents), Some(git_config_path) ) .whitespace_error_style, "red reverse" ); // No command line argument or features; main [delta] section wins assert_eq!( make_options_from_args_and_git_config( &[], Some(git_config_contents), Some(git_config_path) ) .whitespace_error_style, "blue reverse" ); // Feature contains key, but main [delta] section still wins. // This is equivalent to // // [delta] // features = my-whitespace-error-style-feature // whitespace-error-style = blue reverse // // In this situation, the value from the feature is overridden. assert_eq!( make_options_from_args_and_git_config( &["--features", "my-whitespace-error-style-feature"], Some(git_config_contents), Some(git_config_path) ) .whitespace_error_style, "blue reverse" ); remove_file(git_config_path).unwrap(); } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/features/diff_highlight.rs
src/features/diff_highlight.rs
use crate::features::raw; use crate::features::OptionValueFunction; pub fn make_feature() -> Vec<(String, OptionValueFunction)> { _make_feature(false) } pub fn _make_feature(bold: bool) -> Vec<(String, OptionValueFunction)> { let mut feature = raw::make_feature(); feature.retain(|(s, _)| s != "keep-plus-minus-markers" && s != "tabs"); feature.extend(builtin_feature!([ ( "commit-style", String, Some("color.diff.commit"), _opt => "raw" ), ( "minus-style", String, Some("color.diff.old"), _opt => if bold { "bold red" } else { "red" } ), ( "minus-non-emph-style", String, Some("color.diff-highlight.oldNormal"), opt => opt.minus_style.clone() ), ( "minus-emph-style", String, Some("color.diff-highlight.oldHighlight"), opt => format!("{} reverse", opt.minus_style) ), ( "plus-style", String, Some("color.diff.new"), _opt => if bold { "bold green" } else { "green" } ), ( "plus-non-emph-style", String, Some("color.diff-highlight.newNormal"), opt => opt.plus_style.clone() ), ( "plus-emph-style", String, Some("color.diff-highlight.newHighlight"), opt => format!("{} reverse", opt.plus_style) ) ])); feature } #[cfg(test)] mod test_utils { use std::fs::remove_file; use crate::tests::integration_test_utils; #[test] fn test_diff_highlight_defaults() { let opt = integration_test_utils::make_options_from_args_and_git_config( &["--features", "diff-highlight"], None, None, ); assert_eq!(opt.minus_style, "red"); assert_eq!(opt.minus_non_emph_style, "red"); assert_eq!(opt.minus_emph_style, "red reverse"); assert_eq!(opt.zero_style, "normal"); assert_eq!(opt.plus_style, "green"); assert_eq!(opt.plus_non_emph_style, "green"); assert_eq!(opt.plus_emph_style, "green reverse"); } #[test] fn test_diff_highlight_respects_gitconfig() { let git_config_contents = b" [color \"diff\"] old = red bold new = green bold [color \"diff-highlight\"] oldNormal = ul red bold oldHighlight = red bold 52 newNormal = ul green bold newHighlight = green bold 22 "; let git_config_path = "delta__test_diff_highlight.gitconfig"; let opt = integration_test_utils::make_options_from_args_and_git_config( &["--features", "diff-highlight"], Some(git_config_contents), Some(git_config_path), ); assert_eq!(opt.minus_style, "red bold"); assert_eq!(opt.minus_non_emph_style, "ul red bold"); assert_eq!(opt.minus_emph_style, "red bold 52"); assert_eq!(opt.zero_style, "normal"); assert_eq!(opt.plus_style, "green bold"); assert_eq!(opt.plus_non_emph_style, "ul green bold"); assert_eq!(opt.plus_emph_style, "green bold 22"); remove_file(git_config_path).unwrap(); } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/features/navigate.rs
src/features/navigate.rs
use std::io::Write; #[cfg(target_os = "windows")] use std::io::{Error, ErrorKind}; use std::path::PathBuf; use crate::features::OptionValueFunction; use crate::utils::bat::output::PagerCfg; pub fn make_feature() -> Vec<(String, OptionValueFunction)> { builtin_feature!([ ( "navigate", bool, None, _opt => true ), ( "file-modified-label", String, None, _opt => "Δ" ), ( "hunk-label", String, None, _opt => "•" ) ]) } // Construct the regexp used by less for paging, if --show-themes or --navigate is enabled. pub fn make_navigate_regex( show_themes: bool, file_modified_label: &str, file_added_label: &str, file_removed_label: &str, file_renamed_label: &str, hunk_label: &str, ) -> String { if show_themes { "^Theme:".to_string() } else { let optional_regexp = |find: &str| { if !find.is_empty() { format!("|{}", regex::escape(find)) } else { "".to_string() } }; format!( "^(commit{}{}{}{}{})", optional_regexp(file_added_label), optional_regexp(file_removed_label), optional_regexp(file_renamed_label), optional_regexp(file_modified_label), optional_regexp(hunk_label), ) } } // Create a less history file to be used by delta's child less process. This file is initialized // with the contents of user's real less hist file, to which the navigate regex is appended. This // has the effect that 'n' or 'N' in delta's less process will search for the navigate regex, // without the undesirable aspects of using --pattern, yet without polluting the user's less search // history with delta's navigate regex. See // https://github.com/dandavison/delta/issues/237#issuecomment-780654036. Note that with the // current implementation, no writes to the delta less history file are propagated back to the real // history file so, for example, a (non-navigate) search performed in the delta less process will // not be stored in history. pub fn copy_less_hist_file_and_append_navigate_regex( config: &PagerCfg, ) -> std::io::Result<PathBuf> { let delta_less_hist_file = get_delta_less_hist_file()?; let initial_contents = ".less-history-file:\n".to_string(); let mut contents = if let Some(hist_file) = get_less_hist_file() { std::fs::read_to_string(hist_file).unwrap_or(initial_contents) } else { initial_contents }; if !contents.ends_with(".search\n") { contents = format!("{contents}.search\n"); } writeln!( std::fs::File::create(&delta_less_hist_file)?, "{}\"{}", contents, config.navigate_regex.as_ref().unwrap(), )?; Ok(delta_less_hist_file) } #[cfg(target_os = "windows")] fn get_delta_less_hist_file() -> std::io::Result<PathBuf> { let mut path = dirs::data_local_dir() .ok_or_else(|| Error::new(ErrorKind::NotFound, "Can't find AppData\\Local folder"))?; path.push("delta"); std::fs::create_dir_all(&path)?; path.push("delta.lesshst"); Ok(path) } #[cfg(not(target_os = "windows"))] fn get_delta_less_hist_file() -> std::io::Result<PathBuf> { let dir = xdg::BaseDirectories::with_prefix("delta")?; dir.place_data_file("lesshst") } // Get path of the less history file. See `man less` for more details. // On Unix, check all possible locations and pick the newest file. fn get_less_hist_file() -> Option<PathBuf> { if let Some(home_dir) = dirs::home_dir() { match std::env::var("LESSHISTFILE").as_deref() { Ok("-") | Ok("/dev/null") => { // The user has explicitly disabled less history. None } Ok(path) => { // The user has specified a custom histfile. Some(PathBuf::from(path)) } Err(_) => { // The user is using the default less histfile location. #[cfg(unix)] { // According to the less 643 manual: // "$XDG_STATE_HOME/lesshst" or "$HOME/.local/state/lesshst" or // "$XDG_DATA_HOME/lesshst" or "$HOME/.lesshst". let xdg_dirs = xdg::BaseDirectories::new().ok()?; [ xdg_dirs.get_state_home().join("lesshst"), xdg_dirs.get_data_home().join("lesshst"), home_dir.join(".lesshst"), ] .iter() .filter(|path| path.exists()) .max_by_key(|path| { std::fs::metadata(path) .and_then(|m| m.modified()) .unwrap_or(std::time::UNIX_EPOCH) }) .cloned() } #[cfg(not(unix))] { let mut hist_file = home_dir; hist_file.push(if cfg!(windows) { "_lesshst" } else { ".lesshst" }); Some(hist_file) } } } } else { None } } #[cfg(test)] mod tests { use std::fs::remove_file; use crate::tests::integration_test_utils; #[test] #[ignore] // manually verify: cargo test -- test_get_less_hist_file --ignored --nocapture fn test_get_less_hist_file() { let hist_file = super::get_less_hist_file(); dbg!(hist_file); } #[test] fn test_navigate_with_overridden_key_in_main_section() { let git_config_contents = b" [delta] features = navigate file-modified-label = \"modified: \" "; let git_config_path = "delta__test_navigate_with_overridden_key_in_main_section.gitconfig"; assert_eq!( integration_test_utils::make_options_from_args_and_git_config(&[], None, None) .file_modified_label, "" ); assert_eq!( integration_test_utils::make_options_from_args_and_git_config( &["--features", "navigate"], None, None ) .file_modified_label, "Δ" ); assert_eq!( integration_test_utils::make_options_from_args_and_git_config( &["--navigate"], None, None ) .file_modified_label, "Δ" ); assert_eq!( integration_test_utils::make_options_from_args_and_git_config( &[], Some(git_config_contents), Some(git_config_path) ) .file_modified_label, "modified: " ); remove_file(git_config_path).unwrap(); } #[test] fn test_navigate_with_overridden_key_in_custom_navigate_section() { let git_config_contents = b" [delta] features = navigate [delta \"navigate\"] file-modified-label = \"modified: \" "; let git_config_path = "delta__test_navigate_with_overridden_key_in_custom_navigate_section.gitconfig"; assert_eq!( integration_test_utils::make_options_from_args_and_git_config(&[], None, None) .file_modified_label, "" ); assert_eq!( integration_test_utils::make_options_from_args_and_git_config( &["--features", "navigate"], None, None ) .file_modified_label, "Δ" ); assert_eq!( integration_test_utils::make_options_from_args_and_git_config( &[], Some(git_config_contents), Some(git_config_path) ) .file_modified_label, "modified: " ); remove_file(git_config_path).unwrap(); } #[test] fn test_navigate_activated_by_custom_feature() { let git_config_contents = b" [delta \"my-navigate-feature\"] features = navigate file-modified-label = \"modified: \" "; let git_config_path = "delta__test_navigate_activated_by_custom_feature.gitconfig"; assert_eq!( integration_test_utils::make_options_from_args_and_git_config( &[], Some(git_config_contents), Some(git_config_path) ) .file_modified_label, "" ); assert_eq!( integration_test_utils::make_options_from_args_and_git_config( &["--features", "my-navigate-feature"], Some(git_config_contents), Some(git_config_path) ) .file_modified_label, "modified: " ); remove_file(git_config_path).unwrap(); } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/subcommands/parse_ansi.rs
src/subcommands/parse_ansi.rs
use std::io::{self, BufRead}; #[cfg(not(tarpaulin_include))] pub fn parse_ansi() -> std::io::Result<()> { use crate::ansi; for line in io::stdin().lock().lines() { println!( "{}", ansi::explain_ansi( &line.unwrap_or_else(|line| panic!("Invalid utf-8: {:?}", line)), true ) ); } Ok(()) }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/subcommands/external.rs
src/subcommands/external.rs
use crate::cli::Opt; use clap::CommandFactory; use clap::{ArgMatches, Error}; use std::ffi::{OsStr, OsString}; const RG: &str = "rg"; const GIT: &str = "git"; pub const SUBCOMMANDS: &[&str] = &[RG, GIT]; #[derive(PartialEq)] pub enum SubCmdKind { Git(Option<String>), // Some(subcommand) if a git subcommand (git show, git log) was found GitDiff, Diff, Rg, None, } impl std::fmt::Display for SubCmdKind { fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { use SubCmdKind::*; let s = match self { Git(Some(arg)) => return formatter.write_fmt(format_args!("git {arg}")), Git(_) => "git", GitDiff => "git diff", Diff => "diff", Rg => "rg", None => "<none>", }; formatter.write_str(s) } } impl std::fmt::Debug for SubCmdKind { fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let s = match self { SubCmdKind::Git(Some(arg)) => { return formatter.write_fmt(format_args!("\"git {}\"", arg.escape_debug())) } _ => format!("{self}"), }; formatter.write_str("\"")?; formatter.write_str(&s)?; formatter.write_str("\"") } } #[derive(Debug)] pub struct SubCommand { pub kind: SubCmdKind, pub args: Vec<OsString>, } impl SubCommand { pub fn new(kind: SubCmdKind, args: Vec<OsString>) -> Self { Self { kind, args } } pub fn none() -> Self { Self { kind: SubCmdKind::None, args: vec![], } } pub fn is_none(&self) -> bool { matches!(self.kind, SubCmdKind::None) } } /// Find the first arg that is a registered external subcommand and return a /// tuple containing: /// - The args prior to that point (delta can understand these) /// - A SubCommand representing the external subcommand and its subsequent args pub fn extract(args: &[OsString], orig_error: Error) -> (ArgMatches, SubCommand) { for (subcmd_pos, arg) in args.iter().filter_map(|a| a.to_str()).enumerate() { if SUBCOMMANDS.contains(&arg) { match Opt::command().try_get_matches_from(&args[..subcmd_pos]) { Err(ref e) if e.kind() == clap::error::ErrorKind::DisplayVersion => { unreachable!("version handled by caller"); } Err(ref e) if e.kind() == clap::error::ErrorKind::DisplayHelp => { unreachable!("help handled by caller"); } Ok(matches) => { let (subcmd_args_index, kind, subcmd) = if arg == RG { (subcmd_pos + 1, SubCmdKind::Rg, vec![RG, "--json"]) } else if arg == GIT { let subcmd_args_index = subcmd_pos + 1; let git_subcmd = args .get(subcmd_args_index) .and_then(|cmd| OsStr::to_str(cmd)) .and_then(|cmd| { if cmd.starts_with("-") { None } else { Some(cmd.into()) } }); ( subcmd_args_index, SubCmdKind::Git(git_subcmd), // git does not start the pager and sees that it does not write to a // terminal, so by default it will not use colors. Override it: vec![GIT, "-c", "color.ui=always"], ) } else { unreachable!("arg must be in SUBCOMMANDS"); }; let subcmd = subcmd .into_iter() .map(OsString::from) .chain(args[subcmd_args_index..].iter().map(OsString::from)) .collect(); return (matches, SubCommand::new(kind, subcmd)); } Err(_) => { // part before the subcommand failed to parse, report that error #[cfg(not(test))] orig_error.exit(); #[cfg(test)] panic!("parse error before subcommand "); } } } } // no valid subcommand found, exit with the original error #[cfg(not(test))] orig_error.exit(); #[cfg(test)] { let _ = orig_error; panic!("unexpected delta argument"); } } #[cfg(test)] mod test { use super::RG; use crate::ansi::strip_ansi_codes; use std::ffi::OsString; use std::io::Cursor; #[test] #[ignore] // reachable with --ignored, useful with --nocapture fn test_subcmd_kind_formatter() { use super::SubCmdKind::*; for s in [ Git(Some("foo".into())), Git(Some("c\"'${}".into())), Git(Option::None), GitDiff, Diff, Rg, None, ] { eprintln!("{0} / {0:?} ", s); } } #[test] #[should_panic(expected = "unexpected delta argument")] fn just_delta_argument_error() { let mut writer = Cursor::new(vec![]); let runargs = [ "--Invalid_Delta_Args", "abcdefg", "-C1", "--Bad_diff_Args_ignored", ] .iter() .map(OsString::from) .collect::<Vec<_>>(); crate::run_app(runargs, Some(&mut writer)).unwrap(); } #[test] #[should_panic(expected = "parse error before subcommand")] fn subcommand_found_but_delta_argument_error() { let mut writer = Cursor::new(vec![]); let runargs = [ "--Invalid_Delta_Args", "git", "show", "-C1", "--Bad_diff_Args_ignored", ] .iter() .map(OsString::from) .collect::<Vec<_>>(); crate::run_app(runargs, Some(&mut writer)).unwrap(); } #[test] fn subcommand_rg() { #[cfg(windows)] // `resolve_binary` only works on windows if grep_cli::resolve_binary(RG).is_err() { return; } #[cfg(unix)] // resolve `rg` binary by walking PATH if std::env::var_os("PATH") .filter(|p| { std::env::split_paths(&p) .filter(|p| !p.as_os_str().is_empty()) .filter_map(|p| p.join(RG).metadata().ok()) .any(|md| !md.is_dir()) }) .is_none() { return; } let mut writer = Cursor::new(vec![]); let needle = format!("{}{}", "Y40ii4RihK6", "lHiK4BDsGS").to_string(); // --minus-style has no effect, just for cmdline parsing let runargs = [ "--minus-style", "normal", "rg", &needle, "src/", "-N", "-C", "2", "-C0", ] .iter() .map(OsString::from) .collect::<Vec<_>>(); let exit_code = crate::run_app(runargs, Some(&mut writer)).unwrap(); let rg_output = std::str::from_utf8(writer.get_ref()).unwrap(); let mut lines = rg_output.lines(); // eprintln!("{}", rg_output); assert_eq!( r#"src/utils/process.rs "#, strip_ansi_codes(lines.next().expect("line 1")) ); let line2 = format!(r#" .join("{}x");"#, needle); assert_eq!(line2, strip_ansi_codes(lines.next().expect("line 2"))); assert_eq!(exit_code, 0); } #[test] fn subcommand_git_cat_file() { let mut writer = Cursor::new(vec![]); // only 39 of the 40 long git hash, rev-parse doesn't look up full hashes let runargs = "git rev-parse 5a4361fa037090adf729ab3f161832d969abc57" .split(' ') .map(OsString::from) .collect::<Vec<_>>(); let exit_code = crate::run_app(runargs, Some(&mut writer)).unwrap(); assert!(exit_code == 0 || exit_code == 128); // ref not found, probably a shallow git clone if exit_code == 128 { eprintln!(" Commit for test not found (shallow git clone?), skipping."); return; } assert_eq!( "5a4361fa037090adf729ab3f161832d969abc576\n", std::str::from_utf8(writer.get_ref()).unwrap() ); let mut writer = Cursor::new(vec![]); let runargs = "git cat-file -p 5a4361fa037090adf729ab3f161832d969abc576:src/main.rs" .split(' ') .map(OsString::from) .collect::<Vec<_>>(); let exit_code = crate::run_app(runargs, Some(&mut writer)).unwrap(); let hello_world = std::str::from_utf8(writer.get_ref()).unwrap(); assert_eq!( hello_world, r#"fn main() { println!("Hello, world!"); } "# ); assert_eq!(exit_code, 0); } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/subcommands/diff.rs
src/subcommands/diff.rs
use std::path::Path; use crate::config::{self}; use crate::utils::git::retrieve_git_version; use crate::subcommands::{SubCmdKind, SubCommand}; use std::ffi::OsString; /// Build `git diff` command for the files provided on the command line. Fall back to /// `diff` if the supplied "files" use process substitution. pub fn build_diff_cmd( minus_file: &Path, plus_file: &Path, config: &config::Config, ) -> Result<SubCommand, i32> { // suppress `dead_code` warning, values are accessed via `get_one::<PathBuf>("plus/minus_file")` debug_assert!(config.minus_file.as_ref().unwrap() == minus_file); debug_assert!(config.plus_file.as_ref().unwrap() == plus_file); let mut diff_args = match shell_words::split(config.diff_args.trim()) { Ok(words) => words, Err(err) => { eprintln!("Failed to parse diff args: {}: {err}", config.diff_args); return Err(config.error_exit_code); } }; // Permit e.g. -@U1 if diff_args .first() .map(|arg| !arg.is_empty() && !arg.starts_with('-')) .unwrap_or(false) { diff_args[0] = format!("-{}", diff_args[0]) } let via_process_substitution = |f: &Path| f.starts_with("/proc/self/fd/") || f.starts_with("/dev/fd/"); // https://stackoverflow.com/questions/22706714/why-does-git-diff-not-work-with-process-substitution // git <2.42 does not support process substitution let (differ, mut diff_cmd) = match retrieve_git_version() { Some(version) if version >= (2, 42) || !(via_process_substitution(minus_file) || via_process_substitution(plus_file)) => { ( SubCmdKind::GitDiff, vec!["git", "diff", "--no-index", "--color"], ) } _ => ( SubCmdKind::Diff, if diff_args_set_unified_context(&diff_args) { vec!["diff"] } else { vec!["diff", "-U3"] }, ), }; diff_cmd.extend( diff_args .iter() .filter(|s| !s.is_empty()) .map(String::as_str), ); diff_cmd.push("--"); let mut diff_cmd = diff_cmd.iter().map(OsString::from).collect::<Vec<_>>(); diff_cmd.push(minus_file.into()); diff_cmd.push(plus_file.into()); Ok(SubCommand::new(differ, diff_cmd)) } /// Do the user-supplied `diff` args set the unified context? fn diff_args_set_unified_context<I, S>(args: I) -> bool where I: IntoIterator<Item = S>, S: AsRef<str>, { // This function is applied to `diff` args; not `git diff`. for arg in args { let arg = arg.as_ref(); if arg == "-u" || arg == "-U" { // diff allows a space after -U (git diff does not) return true; } if (arg.starts_with("-U") || arg.starts_with("-u")) && arg.split_at(2).1.parse::<u32>().is_ok() { return true; } } false } #[cfg(test)] mod main_tests { use std::ffi::OsString; use std::io::Cursor; use super::diff_args_set_unified_context; use rstest::rstest; #[rstest] #[case(&["-u"], true)] #[case(&["-u7"], true)] #[case(&["-u77"], true)] #[case(&["-ux"], false)] #[case(&["-U"], true)] #[case(&["-U7"], true)] #[case(&["-U77"], true)] #[case(&["-Ux"], false)] fn test_unified_diff_arg_is_detected_in_diff_args( #[case] diff_args: &[&str], #[case] expected: bool, ) { assert_eq!(diff_args_set_unified_context(diff_args), expected) } enum ExpectDiff { Yes, No, } #[cfg(not(target_os = "windows"))] #[rstest] // #[case("/dev/null", "/dev/null", ExpectDiff::No)] https://github.com/dandavison/delta/pull/546#issuecomment-835852373 #[case("/etc/group", "/etc/passwd", ExpectDiff::Yes)] #[case("/dev/null", "/etc/passwd", ExpectDiff::Yes)] #[case("/etc/passwd", "/etc/passwd", ExpectDiff::No)] fn test_diff_real_files( #[case] file_a: &str, #[case] file_b: &str, #[case] expect_diff: ExpectDiff, #[values(vec![], vec!["-@''"], vec!["-@-u"], vec!["-@-U99"], vec!["-@-U0"])] args: Vec< &str, >, ) { let mut writer = Cursor::new(vec![]); let mut runargs = vec![OsString::from(file_a), OsString::from(file_b)]; runargs.extend(args.iter().map(OsString::from)); let exit_code = crate::run_app(runargs, Some(&mut writer)); assert_eq!( exit_code.unwrap(), match expect_diff { ExpectDiff::Yes => 1, ExpectDiff::No => 0, } ); assert_eq!( std::str::from_utf8(writer.get_ref()).unwrap() != "", match expect_diff { ExpectDiff::Yes => true, ExpectDiff::No => false, } ); } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/subcommands/generate_completion.rs
src/subcommands/generate_completion.rs
use clap::CommandFactory; use clap_complete::{generate, Shell}; use crate::cli; pub fn generate_completion_file(shell: Shell) -> std::io::Result<()> { let mut cmd = cli::Opt::command(); let bin_name = cmd.get_bin_name().unwrap_or(cmd.get_name()).to_string(); generate(shell, &mut cmd, bin_name, &mut std::io::stdout()); Ok(()) }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/subcommands/show_syntax_themes.rs
src/subcommands/show_syntax_themes.rs
use crate::cli; use crate::color::{ColorMode, ColorMode::*}; use crate::config; use crate::delta; use crate::env::DeltaEnv; use crate::options::theme::color_mode_from_syntax_theme; use crate::utils; use crate::utils::bat::output::{OutputType, PagingMode}; use clap::Parser; use std::io::{self, ErrorKind, IsTerminal, Read, Write}; #[cfg(not(tarpaulin_include))] pub fn show_syntax_themes() -> std::io::Result<()> { let env = DeltaEnv::default(); let assets = utils::bat::assets::load_highlighting_assets(); let mut output_type = OutputType::from_mode( &env, PagingMode::QuitIfOneScreen, None, &config::Config::from(cli::Opt::parse()).into(), ) .unwrap(); let mut writer = output_type.handle().unwrap(); let stdin_data = if !io::stdin().is_terminal() { let mut buf = Vec::new(); io::stdin().lock().read_to_end(&mut buf)?; if !buf.is_empty() { Some(buf) } else { None } } else { None }; let make_opt = || { let mut opt = cli::Opt::parse(); opt.computed.syntax_set = assets.get_syntax_set().unwrap().clone(); opt }; let opt = make_opt(); if !(opt.dark || opt.light) { _show_syntax_themes(opt, Dark, &mut writer, stdin_data.as_ref())?; _show_syntax_themes(make_opt(), Light, &mut writer, stdin_data.as_ref())?; } else if opt.light { _show_syntax_themes(opt, Light, &mut writer, stdin_data.as_ref())?; } else { _show_syntax_themes(opt, Dark, &mut writer, stdin_data.as_ref())? }; Ok(()) } fn _show_syntax_themes( mut opt: cli::Opt, color_mode: ColorMode, writer: &mut dyn Write, stdin: Option<&Vec<u8>>, ) -> std::io::Result<()> { use bytelines::ByteLines; use std::io::BufReader; let input = match stdin { Some(stdin_data) => &stdin_data[..], None => { b"\ diff --git a/example.rs b/example.rs index f38589a..0f1bb83 100644 --- a/example.rs +++ b/example.rs @@ -1,5 +1,5 @@ -// Output the square of a number. -fn print_square(num: f64) { - let result = f64::powf(num, 2.0); - println!(\"The square of {:.2} is {:.2}.\", num, result); +// Output the cube of a number. +fn print_cube(num: f64) { + let result = f64::powf(num, 3.0); + println!(\"The cube of {:.2} is {:.2}.\", num, result); " } }; opt.computed.color_mode = color_mode; let mut config = config::Config::from(opt); let title_style = ansi_term::Style::new().bold(); let assets = utils::bat::assets::load_highlighting_assets(); for syntax_theme in assets .themes() .filter(|t| color_mode_from_syntax_theme(t) == color_mode) { writeln!( writer, "\n\nSyntax theme: {}\n", title_style.paint(syntax_theme) )?; config.syntax_theme = Some(assets.get_theme(syntax_theme).clone()); if let Err(error) = delta::delta(ByteLines::new(BufReader::new(&input[0..])), writer, &config) { match error.kind() { ErrorKind::BrokenPipe => std::process::exit(0), _ => eprintln!("{error}"), } }; } Ok(()) } #[cfg(test)] mod tests { use std::io::{Cursor, Seek}; use super::*; use crate::ansi; use crate::tests::integration_test_utils; #[test] #[ignore] // Not working (timing out) when run by tarpaulin, presumably due to stdin detection. fn test_show_syntax_themes() { let opt = integration_test_utils::make_options_from_args(&[]); let mut writer = Cursor::new(vec![0; 1024]); _show_syntax_themes(opt, Light, &mut writer, None).unwrap(); let mut s = String::new(); writer.rewind().unwrap(); writer.read_to_string(&mut s).unwrap(); let s = ansi::strip_ansi_codes(&s); assert!(s.contains("\nSyntax theme: gruvbox-light\n")); println!("{s}"); assert!(s.contains("\nfn print_cube(num: f64) {\n")); } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/subcommands/show_colors.rs
src/subcommands/show_colors.rs
use crate::cli; use crate::color; use crate::colors; use crate::config; use crate::delta; use crate::env::DeltaEnv; use crate::paint; use crate::paint::BgShouldFill; use crate::style; use crate::utils::bat::output::{OutputType, PagingMode}; #[cfg(not(tarpaulin_include))] pub fn show_colors() -> std::io::Result<()> { use crate::{delta::DiffType, utils}; let args = std::env::args_os().collect::<Vec<_>>(); let env = DeltaEnv::default(); let assets = utils::bat::assets::load_highlighting_assets(); let opt = match cli::Opt::from_args_and_git_config(args, &env, assets) { (cli::Call::Delta(_), Some(opt)) => opt, _ => panic!("non-Delta Call variant should not occur here"), }; let config = config::Config::from(opt); let pagercfg = (&config).into(); let mut output_type = OutputType::from_mode(&env, PagingMode::QuitIfOneScreen, None, &pagercfg).unwrap(); let writer = output_type.handle().unwrap(); let mut painter = paint::Painter::new(writer, &config); painter.set_syntax(Some("a.ts")); painter.set_highlighter(); let title_style = ansi_term::Style::new().bold(); let mut style = style::Style { is_syntax_highlighted: true, ..style::Style::default() }; for (group, color_names) in colors::color_groups() { writeln!(painter.writer, "\n\n{}\n", title_style.paint(group))?; for (color_name, hex) in color_names { // Two syntax-highlighted lines without background color style.ansi_term_style.background = None; for line in [ r#"export function color(): string {{ return "none" }}"#, r#"export function hex(): string {{ return "none" }}"#, ] { painter.syntax_highlight_and_paint_line( line, paint::StyleSectionSpecifier::Style(style), delta::State::HunkZero(DiffType::Unified, None), BgShouldFill::default(), ) } // Two syntax-highlighted lines with background color let color = color::parse_color(color_name, config.true_color, config.git_config()).unwrap(); style.ansi_term_style.background = Some(color); for line in [ &format!(r#"export function color(): string {{ return "{color_name}" }}"#), &format!(r#"export function hex(): string {{ return "{hex}" }}"#), ] { painter.syntax_highlight_and_paint_line( line, paint::StyleSectionSpecifier::Style(style), delta::State::HunkZero(DiffType::Unified, None), BgShouldFill::default(), ) } painter.emit()?; } } Ok(()) }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/subcommands/list_syntax_themes.rs
src/subcommands/list_syntax_themes.rs
use std::io::{self, IsTerminal, Write}; use itertools::Itertools; use crate::{options::theme::is_light_syntax_theme, utils}; #[cfg(not(tarpaulin_include))] pub fn list_syntax_themes() -> std::io::Result<()> { let stdout = io::stdout(); let mut stdout = stdout.lock(); if stdout.is_terminal() { _list_syntax_themes_for_humans(&mut stdout) } else { _list_syntax_themes_for_machines(&mut stdout) } } pub fn _list_syntax_themes_for_humans(writer: &mut dyn Write) -> std::io::Result<()> { let assets = utils::bat::assets::load_highlighting_assets(); writeln!(writer, "Light syntax themes:")?; for theme in assets.themes().filter(|t| is_light_syntax_theme(t)) { writeln!(writer, " {theme}")?; } writeln!(writer, "\nDark syntax themes:")?; for theme in assets.themes().filter(|t| !is_light_syntax_theme(t)) { writeln!(writer, " {theme}")?; } writeln!( writer, "\nUse delta --show-syntax-themes to demo the themes." )?; Ok(()) } pub fn _list_syntax_themes_for_machines(writer: &mut dyn Write) -> std::io::Result<()> { let assets = utils::bat::assets::load_highlighting_assets(); for theme in assets.themes().sorted_by_key(|t| is_light_syntax_theme(t)) { writeln!( writer, "{}\t{}", if is_light_syntax_theme(theme) { "light" } else { "dark" }, theme )?; } Ok(()) } #[cfg(test)] mod tests { use std::io::{Cursor, Read, Seek}; use super::*; #[test] fn test_list_syntax_themes_for_humans() { let mut writer = Cursor::new(vec![0; 512]); _list_syntax_themes_for_humans(&mut writer).unwrap(); let mut s = String::new(); writer.rewind().unwrap(); writer.read_to_string(&mut s).unwrap(); assert!(s.contains("Light syntax themes:\n")); assert!(s.contains(" GitHub\n")); assert!(s.contains("Dark syntax themes:\n")); assert!(s.contains(" Dracula\n")); } #[test] fn test_list_syntax_themes_for_machines() { let mut writer = Cursor::new(vec![0; 512]); _list_syntax_themes_for_machines(&mut writer).unwrap(); let mut s = String::new(); writer.rewind().unwrap(); writer.read_to_string(&mut s).unwrap(); assert!(s.contains("light GitHub\n")); assert!(s.contains("dark Dracula\n")); } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/subcommands/mod.rs
src/subcommands/mod.rs
// internal subcommands: pub mod generate_completion; pub mod list_syntax_themes; pub mod parse_ansi; mod sample_diff; pub mod show_colors; pub mod show_config; pub mod show_syntax_themes; pub mod show_themes; // start external processes, e.g. `git diff` or `rg`, output is read by delta pub mod diff; mod external; pub(crate) use external::extract; pub(crate) use external::SubCmdKind; pub(crate) use external::SubCommand; pub(crate) use external::SUBCOMMANDS;
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/subcommands/sample_diff.rs
src/subcommands/sample_diff.rs
pub const DIFF: &[u8] = r#" commit 7ec4627902020cccd7b3f4fbc63e1b0d6b9798cd Author: Evan You <yyx990803@gmail.com> Date: Thu Feb 21 08:52:15 2019 -0500 fix: ensure generated scoped slot code is compatible with 2.5 fix #9545 diff --git a/src/compiler/codegen/index.js b/src/compiler/codegen/index.js index a64c3421..d433f756 100644 --- a/src/compiler/codegen/index.js +++ b/src/compiler/codegen/index.js @@ -409,9 +409,9 @@ function genScopedSlots ( .join(',') return `scopedSlots:_u([${generatedSlots}]${ - needsForceUpdate ? `,true` : `` + needsForceUpdate ? `,null,true` : `` }${ - !needsForceUpdate && needsKey ? `,false,${hash(generatedSlots)}` : `` + !needsForceUpdate && needsKey ? `,null,false,${hash(generatedSlots)}` : `` })` } diff --git a/src/core/instance/render-helpers/resolve-scoped-slots.js b/src/core/instance/render-helpers/resolve-scoped-slots.js index 6439324b..f11ca000 100644 --- a/src/core/instance/render-helpers/resolve-scoped-slots.js +++ b/src/core/instance/render-helpers/resolve-scoped-slots.js @@ -2,15 +2,16 @@ export function resolveScopedSlots ( fns: ScopedSlotsData, // see flow/vnode - hasDynamicKeys: boolean, - contentHashKey: number, - res?: Object + res?: Object, + // the following are added in 2.6 + hasDynamicKeys?: boolean, + contentHashKey?: number ): { [key: string]: Function, $stable: boolean } { res = res || { $stable: !hasDynamicKeys } for (let i = 0; i < fns.length; i++) { const slot = fns[i] if (Array.isArray(slot)) { - resolveScopedSlots(slot, hasDynamicKeys, null, res) + resolveScopedSlots(slot, res, hasDynamicKeys) } else if (slot) { // marker for reverse proxying v-slot without scope on this.$slots if (slot.proxy) { @@ -20,7 +21,7 @@ export function resolveScopedSlots ( } } if (contentHashKey) { - res.$key = contentHashKey + (res: any).$key = contentHashKey } return res } diff --git a/test/unit/modules/compiler/codegen.spec.js b/test/unit/modules/compiler/codegen.spec.js index 98c202dd..e56b2576 100644 --- a/test/unit/modules/compiler/codegen.spec.js +++ b/test/unit/modules/compiler/codegen.spec.js @@ -232,25 +232,25 @@ describe('codegen', () => { it('generate dynamic scoped slot', () => { assertCodegen( '<foo><template :slot="foo" slot-scope="bar">{{ bar }}</template></foo>', - `with(this){return _c('foo',{scopedSlots:_u([{key:foo,fn:function(bar){return [_v(_s(bar))]}}],true)})}` + `with(this){return _c('foo',{scopedSlots:_u([{key:foo,fn:function(bar){return [_v(_s(bar))]}}],null,true)})}` ) }) it('generate scoped slot with multiline v-if', () => { assertCodegen( '<foo><template v-if="\nshow\n" slot-scope="bar">{{ bar }}</template></foo>', - `with(this){return _c('foo',{scopedSlots:_u([{key:"default",fn:function(bar){return (\nshow\n)?[_v(_s(bar))]:undefined}}],true)})}` + `with(this){return _c('foo',{scopedSlots:_u([{key:"default",fn:function(bar){return (\nshow\n)?[_v(_s(bar))]:undefined}}],null,true)})}` ) assertCodegen( '<foo><div v-if="\nshow\n" slot="foo" slot-scope="bar">{{ bar }}</div></foo>', - `with(this){return _c(\'foo\',{scopedSlots:_u([{key:"foo",fn:function(bar){return (\nshow\n)?_c(\'div\',{},[_v(_s(bar))]):_e()}}],true)})}` + `with(this){return _c(\'foo\',{scopedSlots:_u([{key:"foo",fn:function(bar){return (\nshow\n)?_c(\'div\',{},[_v(_s(bar))]):_e()}}],null,true)})}` ) }) it('generate scoped slot with new slot syntax', () => { assertCodegen( '<foo><template v-if="show" #default="bar">{{ bar }}</template></foo>', - `with(this){return _c('foo',{scopedSlots:_u([(show)?{key:"default",fn:function(bar){return [_v(_s(bar))]}}:null],true)})}` + `with(this){return _c('foo',{scopedSlots:_u([(show)?{key:"default",fn:function(bar){return [_v(_s(bar))]}}:null],null,true)})}` ) }) "#.as_bytes();
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/subcommands/show_config.rs
src/subcommands/show_config.rs
use std::io::Write; use itertools::Itertools; use crate::cli; use crate::config; use crate::features::side_by_side::{Left, Right}; use crate::minusplus::*; use crate::paint::BgFillMethod; use crate::style; use crate::utils::bat::output::PagingMode; pub fn show_config(config: &config::Config, writer: &mut dyn Write) -> std::io::Result<()> { // styles first writeln!( writer, " commit-style = {commit_style} file-style = {file_style} hunk-header-style = {hunk_header_style} minus-style = {minus_style} minus-non-emph-style = {minus_non_emph_style} minus-emph-style = {minus_emph_style} minus-empty-line-marker-style = {minus_empty_line_marker_style} zero-style = {zero_style} plus-style = {plus_style} plus-non-emph-style = {plus_non_emph_style} plus-emph-style = {plus_emph_style} plus-empty-line-marker-style = {plus_empty_line_marker_style} grep-file-style = {grep_file_style} grep-line-number-style = {grep_line_number_style} whitespace-error-style = {whitespace_error_style} blame-palette = {blame_palette}", blame_palette = config .blame_palette .iter() .map(|s| style::paint_color_string(s, config.true_color, config.git_config())) .join(" "), commit_style = config.commit_style.to_painted_string(), file_style = config.file_style.to_painted_string(), hunk_header_style = config.hunk_header_style.to_painted_string(), minus_emph_style = config.minus_emph_style.to_painted_string(), minus_empty_line_marker_style = config.minus_empty_line_marker_style.to_painted_string(), minus_non_emph_style = config.minus_non_emph_style.to_painted_string(), minus_style = config.minus_style.to_painted_string(), plus_emph_style = config.plus_emph_style.to_painted_string(), plus_empty_line_marker_style = config.plus_empty_line_marker_style.to_painted_string(), plus_non_emph_style = config.plus_non_emph_style.to_painted_string(), plus_style = config.plus_style.to_painted_string(), grep_file_style = config.grep_file_style.to_painted_string(), grep_line_number_style = config.grep_line_number_style.to_painted_string(), whitespace_error_style = config.whitespace_error_style.to_painted_string(), zero_style = config.zero_style.to_painted_string(), )?; // Everything else writeln!( writer, " true-color = {true_color} file-added-label = {file_added_label} file-modified-label = {file_modified_label} file-removed-label = {file_removed_label} file-renamed-label = {file_renamed_label} right-arrow = {right_arrow}", true_color = config.true_color, file_added_label = format_option_value(&config.file_added_label), file_modified_label = format_option_value(&config.file_modified_label), file_removed_label = format_option_value(&config.file_removed_label), file_renamed_label = format_option_value(&config.file_renamed_label), right_arrow = format_option_value(&config.right_arrow), )?; writeln!( writer, " hyperlinks = {hyperlinks}", hyperlinks = config.hyperlinks )?; if config.hyperlinks { writeln!( writer, " hyperlinks-file-link-format = {hyperlinks_file_link_format}", hyperlinks_file_link_format = format_option_value(&config.hyperlinks_file_link_format), )? } writeln!( writer, " inspect-raw-lines = {inspect_raw_lines} keep-plus-minus-markers = {keep_plus_minus_markers}", inspect_raw_lines = match config.inspect_raw_lines { cli::InspectRawLines::True => "true", cli::InspectRawLines::False => "false", }, keep_plus_minus_markers = config.keep_plus_minus_markers, )?; writeln!( writer, " line-numbers = {line_numbers}", line_numbers = config.line_numbers )?; if config.line_numbers { writeln!( writer, " line-numbers-minus-style = {line_numbers_minus_style} line-numbers-zero-style = {line_numbers_zero_style} line-numbers-plus-style = {line_numbers_plus_style} line-numbers-left-style = {line_numbers_left_style} line-numbers-right-style = {line_numbers_right_style} line-numbers-left-format = {line_numbers_left_format} line-numbers-right-format = {line_numbers_right_format}", line_numbers_minus_style = config.line_numbers_style_minusplus[Minus].to_painted_string(), line_numbers_zero_style = config.line_numbers_zero_style.to_painted_string(), line_numbers_plus_style = config.line_numbers_style_minusplus[Plus].to_painted_string(), line_numbers_left_style = config.line_numbers_style_leftright[Left].to_painted_string(), line_numbers_right_style = config.line_numbers_style_leftright[Right].to_painted_string(), line_numbers_left_format = format_option_value(&config.line_numbers_format[Left]), line_numbers_right_format = format_option_value(&config.line_numbers_format[Right]), )? } writeln!( writer, " max-line-distance = {max_line_distance} max-line-length = {max_line_length} diff-stat-align-width = {diff_stat_align_width} line-fill-method = {line_fill_method} navigate = {navigate} navigate-regex = {navigate_regex} pager = {pager} paging = {paging_mode} side-by-side = {side_by_side} syntax-theme = {syntax_theme} width = {width} tabs = {tab_width} word-diff-regex = {tokenization_regex}", diff_stat_align_width = config.diff_stat_align_width, max_line_distance = config.max_line_distance, max_line_length = config.max_line_length, line_fill_method = match config.line_fill_method { BgFillMethod::TryAnsiSequence => "ansi", BgFillMethod::Spaces => "spaces", }, navigate = config.navigate, navigate_regex = match &config.navigate_regex { None => "".to_string(), Some(s) => format_option_value(s), }, pager = config.pager.clone().unwrap_or_else(|| "none".to_string()), paging_mode = match config.paging_mode { PagingMode::Always => "always", PagingMode::Never => "never", PagingMode::QuitIfOneScreen => "auto", PagingMode::Capture => unreachable!("capture can not be set"), }, side_by_side = config.side_by_side, syntax_theme = config .syntax_theme .clone() .map(|t| t.name.unwrap_or_else(|| "none".to_string())) .unwrap_or_else(|| "none".to_string()), width = match config.decorations_width { cli::Width::Fixed(width) => width.to_string(), cli::Width::Variable => "variable".to_string(), }, tab_width = config.tab_cfg.width(), tokenization_regex = format_option_value(config.tokenization_regex.to_string()), )?; Ok(()) } // Heuristics determining whether to quote string option values when printing values intended for // git config. fn format_option_value<S>(s: S) -> String where S: AsRef<str>, { let s = s.as_ref(); if s.ends_with(' ') || s.starts_with(' ') || s.contains(&['\\', '{', '}', ':'][..]) || s.is_empty() { format!("'{s}'") } else { s.to_string() } } #[cfg(test)] mod tests { use crate::tests::integration_test_utils; use super::*; use crate::ansi; use std::io::{Cursor, Read, Seek}; #[test] fn test_show_config() { let config = integration_test_utils::make_config_from_args(&[]); let mut writer = Cursor::new(vec![0; 1024]); show_config(&config, &mut writer).unwrap(); let mut s = String::new(); writer.rewind().unwrap(); writer.read_to_string(&mut s).unwrap(); let s = ansi::strip_ansi_codes(&s); assert!(s.contains(" commit-style = raw\n")); assert!(s.contains(r" word-diff-regex = '\w+'")); } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/subcommands/show_themes.rs
src/subcommands/show_themes.rs
use std::io::{self, ErrorKind, IsTerminal, Read}; use crate::cli; use crate::color::ColorMode; use crate::config; use crate::delta; use crate::env::DeltaEnv; use crate::git_config; use crate::options::get::get_themes; use crate::utils::bat::output::{OutputType, PagingMode}; pub fn show_themes(dark: bool, light: bool, color_mode: ColorMode) -> std::io::Result<()> { use std::io::BufReader; use bytelines::ByteLines; use super::sample_diff::DIFF; let env = DeltaEnv::default(); let themes = get_themes(git_config::GitConfig::try_create(&env)); if themes.is_empty() { return Err(std::io::Error::new( ErrorKind::NotFound, "No themes found. Please see https://dandavison.github.io/delta/custom-themes.html.", )); } let mut input = DIFF.to_vec(); if !io::stdin().is_terminal() { let mut buf = Vec::new(); io::stdin().lock().read_to_end(&mut buf)?; if !buf.is_empty() { input = buf; } }; let git_config = git_config::GitConfig::try_create(&env); let opt = cli::Opt::from_iter_and_git_config( &env, &["delta", "--navigate", "--show-themes"], git_config, ); let mut output_type = OutputType::from_mode( &env, PagingMode::Always, None, &config::Config::from(opt).into(), ) .unwrap(); let title_style = ansi_term::Style::new().bold(); let writer = output_type.handle().unwrap(); for theme in &themes { let git_config = git_config::GitConfig::try_create(&env); let opt = cli::Opt::from_iter_and_git_config(&env, &["delta", "--features", theme], git_config); let is_dark_theme = opt.dark; let is_light_theme = opt.light; let config = config::Config::from(opt); if (color_mode == ColorMode::Dark && is_dark_theme) || (color_mode == ColorMode::Light && is_light_theme) || (dark && light) { writeln!(writer, "\n\nTheme: {}\n", title_style.paint(theme))?; if let Err(error) = delta::delta(ByteLines::new(BufReader::new(&input[0..])), writer, &config) { match error.kind() { ErrorKind::BrokenPipe => std::process::exit(0), _ => eprintln!("{error}"), } } } } Ok(()) }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/handlers/blame.rs
src/handlers/blame.rs
use chrono::{DateTime, FixedOffset}; use lazy_static::lazy_static; use regex::Regex; use std::borrow::Cow; use unicode_width::UnicodeWidthStr; use crate::ansi::measure_text_width; use crate::color; use crate::config; use crate::config::delta_unreachable; use crate::delta::{self, State, StateMachine}; use crate::fatal; use crate::format::{self, FormatStringSimple, Placeholder}; use crate::format::{make_placeholder_regex, parse_line_number_format}; use crate::paint::{self, BgShouldFill, StyleSectionSpecifier}; use crate::style::Style; use crate::utils::process; #[derive(Clone, Debug)] pub enum BlameLineNumbers { // "none" equals a fixed string with just a separator On(FormatStringSimple), PerBlock(FormatStringSimple), Every(usize, FormatStringSimple), } impl StateMachine<'_> { /// If this is a line of git blame output then render it accordingly. If /// this is the first blame line, then set the syntax-highlighter language /// according to delta.default-language. pub fn handle_blame_line(&mut self) -> std::io::Result<bool> { // TODO: It should be possible to eliminate some of the .clone()s and // .to_owned()s. let mut handled_line = false; self.painter.emit()?; let (previous_key, try_parse) = match &self.state { State::Blame(key) => (Some(key.clone()), true), State::Unknown => (None, true), _ => (None, false), }; if try_parse { let line = self.line.to_owned(); if let Some(blame) = parse_git_blame_line(&line, &self.config.blame_timestamp_format) { // Format blame metadata let format_data = format::parse_line_number_format( &self.config.blame_format, &BLAME_PLACEHOLDER_REGEX, false, ); let mut formatted_blame_metadata = format_blame_metadata(&format_data, &blame, self.config); let key = formatted_blame_metadata.clone(); let is_repeat = previous_key.as_deref() == Some(&key); if is_repeat { formatted_blame_metadata = " ".repeat(measure_text_width(&formatted_blame_metadata)) }; let metadata_style = self.blame_metadata_style(&key, previous_key.as_deref(), is_repeat); let code_style = self.config.blame_code_style.unwrap_or(metadata_style); let separator_style = self.config.blame_separator_style.unwrap_or(code_style); let (nr_prefix, line_number, nr_suffix) = format_blame_line_number( &self.config.blame_separator_format, blame.line_number, is_repeat, ); write!( self.painter.writer, "{}{}{}{}", metadata_style.paint(&formatted_blame_metadata), separator_style.paint(nr_prefix), metadata_style.paint(&line_number), separator_style.paint(nr_suffix), )?; // Emit syntax-highlighted code if self.state == State::Unknown { self.painter.set_syntax(self.get_filename().as_deref()); self.painter.set_highlighter(); } self.state = State::Blame(key); self.painter.syntax_highlight_and_paint_line( &format!("{}\n", blame.code), StyleSectionSpecifier::Style(code_style), self.state.clone(), BgShouldFill::default(), ); handled_line = true } } Ok(handled_line) } fn get_filename(&self) -> Option<String> { match &*process::calling_process() { process::CallingProcess::GitBlame(command_line) => command_line.last_arg.clone(), _ => None, } } fn blame_metadata_style( &mut self, key: &str, previous_key: Option<&str>, is_repeat: bool, ) -> Style { let mut style = match paint::parse_style_sections(&self.raw_line, self.config).first() { Some((style, _)) if style != &Style::default() => { // Something like `blame.coloring = highlightRecent` is in effect; honor // the color from git, subject to map-styles. *style } _ => { // Compute the color ourselves. let color = self.get_color(key, previous_key, is_repeat); // TODO: This will often be pointlessly updating a key with the // value it already has. It might be nicer to do this (and // compute the style) in get_color(), but as things stand the // borrow checker won't permit that. let style = Style::from_colors( None, color::parse_color(&color, true, self.config.git_config()), ); self.blame_key_colors.insert(key.to_owned(), color); style } }; style.is_syntax_highlighted = true; style } fn get_color(&self, this_key: &str, previous_key: Option<&str>, is_repeat: bool) -> String { // Determine color for this line let previous_key_color = match previous_key { Some(previous_key) => self.blame_key_colors.get(previous_key), None => None, }; match ( self.blame_key_colors.get(this_key), previous_key_color, is_repeat, ) { (Some(key_color), Some(previous_key_color), true) => { debug_assert!(key_color == previous_key_color); // Repeated key: assign same color key_color.to_owned() } (None, Some(previous_key_color), false) => { // The key has no color: assign the next color that differs // from previous key. self.get_next_color(Some(previous_key_color)) } (None, None, false) => { // The key has no color, and there is no previous key: // Just assign the next color. is_repeat is necessarily false. self.get_next_color(None) } (Some(key_color), Some(previous_key_color), false) => { if key_color != previous_key_color { // Consecutive keys differ without a collision key_color.to_owned() } else { // Consecutive keys differ; prevent color collision self.get_next_color(Some(key_color)) } } (None, _, true) => delta_unreachable("is_repeat cannot be true when key has no color."), (Some(_), None, _) => { delta_unreachable("There must be a previous key if the key has a color.") } } } fn get_next_color(&self, other_than_color: Option<&str>) -> String { let n_keys = self.blame_key_colors.len(); let n_colors = self.config.blame_palette.len(); let color = self.config.blame_palette[n_keys % n_colors].clone(); if Some(color.as_str()) != other_than_color { color } else { self.config.blame_palette[(n_keys + 1) % n_colors].clone() } } } #[derive(Debug)] pub struct BlameLine<'a> { pub commit: &'a str, pub author: &'a str, pub time: DateTime<FixedOffset>, pub line_number: usize, pub code: &'a str, } // E.g. //ea82f2d0 (Dan Davison 2021-08-22 18:20:19 -0700 120) let mut handled_line = self.handle_key_meta_header_line()? lazy_static! { static ref BLAME_LINE_REGEX: Regex = Regex::new( r"(?x) ^ ( \^?[0-9a-f]{4,40} # commit hash (^ is 'boundary commit' marker) ) (?: [^(]+)? # optional file name (unused; present if file has been renamed; TODO: inefficient?) [\ ] \( # open ( which the previous file name may not contain in case a name does (which is more likely) ( [^\ ].*[^\ ] # author name ) [\ ]+ ( # timestamp [0-9]{4}-[0-9]{2}-[0-9]{2}\ [0-9]{2}:[0-9]{2}:[0-9]{2}\ [-+][0-9]{4} ) [\ ]+ ( [0-9]+ # line number ) \) # close ) ( .* # code, with leading space ) $ " ) .unwrap(); } pub fn parse_git_blame_line<'a>(line: &'a str, timestamp_format: &str) -> Option<BlameLine<'a>> { let caps = BLAME_LINE_REGEX.captures(line)?; let commit = caps.get(1).unwrap().as_str(); let author = caps.get(2).unwrap().as_str(); let timestamp = caps.get(3).unwrap().as_str(); let time = DateTime::parse_from_str(timestamp, timestamp_format).ok()?; let line_number = caps.get(4).unwrap().as_str().parse::<usize>().ok()?; let code = caps.get(5).unwrap().as_str(); Some(BlameLine { commit, author, time, line_number, code, }) } lazy_static! { // line numbers (`{n}`) change with every line and are set separately via `blame-separator-format` pub static ref BLAME_PLACEHOLDER_REGEX: Regex = format::make_placeholder_regex(&["timestamp", "author", "commit"]); } pub fn format_blame_metadata( format_data: &[format::FormatStringPlaceholderData], blame: &BlameLine, config: &config::Config, ) -> String { let mut s = String::new(); let mut suffix = ""; for placeholder in format_data { s.push_str(placeholder.prefix.as_str()); let alignment_spec = placeholder.alignment_spec.unwrap_or(format::Align::Left); let width = placeholder.width.unwrap_or(15); let field = match placeholder.placeholder { Some(Placeholder::Str("timestamp")) => { Some(Cow::from(match &config.blame_timestamp_output_format { Some(time_format) => blame.time.format(time_format).to_string(), None => chrono_humanize::HumanTime::from(blame.time).to_string(), })) } Some(Placeholder::Str("author")) => Some(Cow::from(blame.author)), Some(Placeholder::Str("commit")) => Some(delta::format_raw_line(blame.commit, config)), None => None, _ => unreachable!("Unexpected `git blame` input"), }; if let Some(field) = field { // Unicode modifier should not be counted as character to allow a consistent padding let unicode_modifier_width = field.as_ref().chars().count() - UnicodeWidthStr::width(field.as_ref()); s.push_str(&format::pad( &field, width + unicode_modifier_width, alignment_spec, placeholder.precision, )) } suffix = placeholder.suffix.as_str(); } s.push_str(suffix); s } pub fn format_blame_line_number( format: &BlameLineNumbers, line_number: usize, is_repeat: bool, ) -> (&str, String, &str) { let (format, empty) = match &format { BlameLineNumbers::PerBlock(format) => (format, is_repeat), BlameLineNumbers::Every(n, format) => (format, is_repeat && line_number.is_multiple_of(*n)), BlameLineNumbers::On(format) => (format, false), }; let mut result = String::new(); // depends on defaults being set when parsing arguments let line_number = if format.width.is_some() { format::pad( line_number, format.width.unwrap(), format.alignment_spec.unwrap(), None, ) } else { String::new() }; if empty { for _ in 0..measure_text_width(&line_number) { result.push(' '); } } else { result.push_str(&line_number); } (format.prefix.as_str(), result, format.suffix.as_str()) } pub fn parse_blame_line_numbers(arg: &str) -> BlameLineNumbers { if arg == "none" { return BlameLineNumbers::On(crate::format::FormatStringSimple::only_string("│")); } let regex = make_placeholder_regex(&["n"]); let f = match parse_line_number_format(arg, &regex, false) { v if v.len() > 1 => { fatal("Too many format arguments numbers for blame-line-numbers".to_string()) } mut v => v.pop().unwrap(), }; let set_defaults = |mut format: crate::format::FormatStringSimple| { format.width = format.width.or(Some(4)); format.alignment_spec = format.alignment_spec.or(Some(crate::format::Align::Center)); format }; if f.placeholder.is_none() { return BlameLineNumbers::On(crate::format::FormatStringSimple::only_string( f.suffix.as_str(), )); } match f.fmt_type.as_str() { t if t.is_empty() || t == "every" => BlameLineNumbers::On(set_defaults(f.into_simple())), "block" => BlameLineNumbers::PerBlock(set_defaults(f.into_simple())), every_n if every_n.starts_with("every-") => { let n = every_n["every-".len()..] .parse::<usize>() .unwrap_or_else(|err| { fatal(format!( "Invalid number for blame-line-numbers in every-N argument: {err}", )) }); if n > 1 { BlameLineNumbers::Every(n, set_defaults(f.into_simple())) } else { BlameLineNumbers::On(set_defaults(f.into_simple())) } } t => fatal(format!( "Invalid format type \"{t}\" for blame-line-numbers", )), } } #[cfg(test)] mod tests { use itertools::Itertools; use std::{collections::HashMap, io::Cursor}; use crate::tests::integration_test_utils; use super::*; #[test] fn test_blame_line_regex() { for line in &[ "ea82f2d0 (Dan Davison 2021-08-22 18:20:19 -0700 120) let mut handled_line = self.handle_commit_meta_header_line()?", "b2257cfa (Dan Davison 2020-07-18 15:34:43 -0400 1) use std::borrow::Cow;", "^35876eaa (Nicholas Marriott 2009-06-01 22:58:49 +0000 38) /* Default grid cell data. */", ] { let caps = BLAME_LINE_REGEX.captures(line); assert!(caps.is_some()); assert!(parse_git_blame_line(line, "%Y-%m-%d %H:%M:%S %z").is_some()); } } #[test] fn test_blame_line_with_parens_in_name() { let line = "61f180c8 (Kangwook Lee (이강욱) 2021-06-09 23:33:59 +0900 130) let mut output_type ="; let caps = BLAME_LINE_REGEX.captures(line).unwrap(); assert_eq!(caps.get(2).unwrap().as_str(), "Kangwook Lee (이강욱)"); } #[test] fn test_format_blame_metadata_with_default_timestamp_output_format() { let format_data = make_format_data_with_placeholder("timestamp"); let blame = make_blame_line_with_time("1996-12-19T16:39:57-08:00"); let config = integration_test_utils::make_config_from_args(&[]); let regex = Regex::new(r"^\d+ years ago$").unwrap(); let result = format_blame_metadata(&[format_data], &blame, &config); assert!(regex.is_match(result.trim())); } #[test] fn test_format_blame_metadata_with_custom_timestamp_output_format() { let format_data = make_format_data_with_placeholder("timestamp"); let blame = make_blame_line_with_time("1996-12-19T16:39:57-08:00"); let config = integration_test_utils::make_config_from_args(&[ "--blame-timestamp-output-format=%Y-%m-%d %H:%M", ]); let result = format_blame_metadata(&[format_data], &blame, &config); assert_eq!(result.trim(), "1996-12-19 16:39"); } #[test] fn test_format_blame_metadata_with_accent_in_name() { let config = integration_test_utils::make_config_from_args(&[]); let count_trailing_spaces = |s: String| s.chars().rev().filter(|&c| c == ' ').count(); let format_data1 = make_format_data_with_placeholder("author"); let blame1 = make_blame_line_with_author("E\u{301}dith Piaf"); let result1 = format_blame_metadata(&[format_data1], &blame1, &config); let format_data2 = make_format_data_with_placeholder("author"); let blame2 = make_blame_line_with_author("Edith Piaf"); let result2 = format_blame_metadata(&[format_data2], &blame2, &config); assert_eq!( count_trailing_spaces(result1), count_trailing_spaces(result2) ); } #[test] fn test_color_assignment() { let mut writer = Cursor::new(vec![0; 512]); let config = integration_test_utils::make_config_from_args(&[ "--blame-format", "{author} {commit}", "--blame-palette", "1 2", ]); let mut machine = StateMachine::new(&mut writer, &config); let blame_lines: HashMap<&str, &str> = vec![ ( "A", "aaaaaaa (Dan Davison 2021-08-22 18:20:19 -0700 120) A", ), ( "B", "bbbbbbb (Dan Davison 2020-07-18 15:34:43 -0400 1) B", ), ( "C", "ccccccc (Dan Davison 2020-07-18 15:34:43 -0400 1) C", ), ] .into_iter() .collect(); // First key gets first color machine.line = blame_lines["A"].into(); machine.handle_blame_line().unwrap(); assert_eq!( hashmap_items(&machine.blame_key_colors), &[("Dan Davison aaaaaaa ", "1")] ); // Repeat key: same color machine.line = blame_lines["A"].into(); machine.handle_blame_line().unwrap(); assert_eq!( hashmap_items(&machine.blame_key_colors), &[("Dan Davison aaaaaaa ", "1")] ); // Second distinct key gets second color machine.line = blame_lines["B"].into(); machine.handle_blame_line().unwrap(); assert_eq!( hashmap_items(&machine.blame_key_colors), &[ ("Dan Davison aaaaaaa ", "1"), ("Dan Davison bbbbbbb ", "2") ] ); // Third distinct key gets first color (we only have 2 colors) machine.line = blame_lines["C"].into(); machine.handle_blame_line().unwrap(); assert_eq!( hashmap_items(&machine.blame_key_colors), &[ ("Dan Davison aaaaaaa ", "1"), ("Dan Davison bbbbbbb ", "2"), ("Dan Davison ccccccc ", "1") ] ); // Now the first key appears again. It would get the first color, but // that would be a consecutive-key-color-collision. So it gets the // second color. machine.line = blame_lines["A"].into(); machine.handle_blame_line().unwrap(); assert_eq!( hashmap_items(&machine.blame_key_colors), &[ ("Dan Davison aaaaaaa ", "2"), ("Dan Davison bbbbbbb ", "2"), ("Dan Davison ccccccc ", "1") ] ); } fn hashmap_items(hashmap: &HashMap<String, String>) -> Vec<(&str, &str)> { hashmap .iter() .sorted() .map(|(k, v)| (k.as_str(), v.as_str())) .collect() } fn make_blame_line_with_time(timestamp: &str) -> BlameLine<'_> { let time = chrono::DateTime::parse_from_rfc3339(timestamp).unwrap(); BlameLine { commit: "", author: "", time, line_number: 0, code: "", } } fn make_format_data_with_placeholder( placeholder: &str, ) -> format::FormatStringPlaceholderData<'_> { format::FormatStringPlaceholderData { placeholder: Some(Placeholder::Str(placeholder)), ..Default::default() } } fn make_blame_line_with_author(author: &str) -> BlameLine<'_> { BlameLine { commit: "", author, time: chrono::DateTime::default(), line_number: 0, code: "", } } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/handlers/draw.rs
src/handlers/draw.rs
use std::cmp::max; use std::io::Write; use crate::ansi; use crate::cli::Width; use crate::style::{DecorationStyle, Style}; fn paint_text(text_style: Style, text: &str, addendum: &str) -> String { if addendum.is_empty() { text_style.paint(text).to_string() } else { text_style .paint(text.to_string() + " (" + addendum + ")") .to_string() } } pub type DrawFunction = dyn FnMut( &mut dyn Write, &str, &str, &str, &Width, Style, ansi_term::Style, ) -> std::io::Result<()>; pub fn get_draw_function( decoration_style: DecorationStyle, ) -> (Box<DrawFunction>, bool, ansi_term::Style) { match decoration_style { DecorationStyle::Box(style) => (Box::new(write_boxed), true, style), DecorationStyle::BoxWithUnderline(style) => { (Box::new(write_boxed_with_underline), true, style) } DecorationStyle::BoxWithOverline(style) => { // TODO: not implemented (Box::new(write_boxed), true, style) } DecorationStyle::BoxWithUnderOverline(style) => { // TODO: not implemented (Box::new(write_boxed), true, style) } DecorationStyle::Underline(style) => (Box::new(write_underlined), false, style), DecorationStyle::Overline(style) => (Box::new(write_overlined), false, style), DecorationStyle::UnderOverline(style) => (Box::new(write_underoverlined), false, style), DecorationStyle::NoDecoration => ( Box::new(write_no_decoration), false, ansi_term::Style::new(), ), } } fn write_no_decoration( writer: &mut dyn Write, text: &str, raw_text: &str, addendum: &str, _line_width: &Width, // ignored text_style: Style, _decoration_style: ansi_term::Style, ) -> std::io::Result<()> { if text_style.is_raw { writeln!(writer, "{raw_text}")?; } else { writeln!(writer, "{}", paint_text(text_style, text, addendum))?; } Ok(()) } /// Write text to stream, surrounded by a box, leaving the cursor just /// beyond the bottom right corner. pub fn write_boxed( writer: &mut dyn Write, text: &str, raw_text: &str, addendum: &str, _line_width: &Width, // ignored text_style: Style, decoration_style: ansi_term::Style, ) -> std::io::Result<()> { let up_left = if decoration_style.is_bold { box_drawing::heavy::UP_LEFT } else { box_drawing::light::UP_LEFT }; let box_width = ansi::measure_text_width(text); write_boxed_partial( writer, text, raw_text, addendum, box_width, text_style, decoration_style, )?; writeln!(writer, "{}", decoration_style.paint(up_left))?; Ok(()) } /// Write text to stream, surrounded by a box, and extend a line from /// the bottom right corner. fn write_boxed_with_underline( writer: &mut dyn Write, text: &str, raw_text: &str, addendum: &str, line_width: &Width, text_style: Style, decoration_style: ansi_term::Style, ) -> std::io::Result<()> { let box_width = ansi::measure_text_width(text); write_boxed_with_horizontal_whisker( writer, text, raw_text, addendum, box_width, text_style, decoration_style, )?; let line_width = match *line_width { Width::Fixed(n) => n, Width::Variable => box_width, }; write_horizontal_line( writer, if line_width > box_width { line_width - box_width - 1 } else { 0 }, text_style, decoration_style, )?; writeln!(writer)?; Ok(()) } enum UnderOverline { Under, Over, Underover, } fn write_underlined( writer: &mut dyn Write, text: &str, raw_text: &str, addendum: &str, line_width: &Width, text_style: Style, decoration_style: ansi_term::Style, ) -> std::io::Result<()> { _write_under_or_over_lined( UnderOverline::Under, writer, text, raw_text, addendum, line_width, text_style, decoration_style, ) } fn write_overlined( writer: &mut dyn Write, text: &str, raw_text: &str, addendum: &str, line_width: &Width, text_style: Style, decoration_style: ansi_term::Style, ) -> std::io::Result<()> { _write_under_or_over_lined( UnderOverline::Over, writer, text, raw_text, addendum, line_width, text_style, decoration_style, ) } fn write_underoverlined( writer: &mut dyn Write, text: &str, raw_text: &str, addendum: &str, line_width: &Width, text_style: Style, decoration_style: ansi_term::Style, ) -> std::io::Result<()> { _write_under_or_over_lined( UnderOverline::Underover, writer, text, raw_text, addendum, line_width, text_style, decoration_style, ) } #[allow(clippy::too_many_arguments)] fn _write_under_or_over_lined( underoverline: UnderOverline, writer: &mut dyn Write, text: &str, raw_text: &str, addendum: &str, line_width: &Width, text_style: Style, decoration_style: ansi_term::Style, ) -> std::io::Result<()> { let text_width = ansi::measure_text_width(text); let line_width = match *line_width { Width::Fixed(n) => max(n, text_width), Width::Variable => text_width, }; let write_line = |writer: &mut dyn Write| -> std::io::Result<()> { write_horizontal_line(writer, line_width, text_style, decoration_style)?; writeln!(writer)?; Ok(()) }; match underoverline { UnderOverline::Under => {} _ => write_line(writer)?, } if text_style.is_raw { writeln!(writer, "{raw_text}")?; } else { writeln!(writer, "{}", paint_text(text_style, text, addendum))?; } match underoverline { UnderOverline::Over => {} _ => write_line(writer)?, } Ok(()) } fn write_horizontal_line( writer: &mut dyn Write, width: usize, _text_style: Style, decoration_style: ansi_term::Style, ) -> std::io::Result<()> { let horizontal = if decoration_style.is_bold { box_drawing::heavy::HORIZONTAL } else { box_drawing::light::HORIZONTAL }; write!( writer, "{}", decoration_style.paint(horizontal.repeat(width)) ) } fn write_boxed_with_horizontal_whisker( writer: &mut dyn Write, text: &str, raw_text: &str, addendum: &str, box_width: usize, text_style: Style, decoration_style: ansi_term::Style, ) -> std::io::Result<()> { let up_horizontal = if decoration_style.is_bold { box_drawing::heavy::UP_HORIZONTAL } else { box_drawing::light::UP_HORIZONTAL }; write_boxed_partial( writer, text, raw_text, addendum, box_width, text_style, decoration_style, )?; write!(writer, "{}", decoration_style.paint(up_horizontal))?; Ok(()) } fn write_boxed_partial( writer: &mut dyn Write, text: &str, raw_text: &str, addendum: &str, box_width: usize, text_style: Style, decoration_style: ansi_term::Style, ) -> std::io::Result<()> { let (horizontal, down_left, vertical) = if decoration_style.is_bold { ( box_drawing::heavy::HORIZONTAL, box_drawing::heavy::DOWN_LEFT, box_drawing::heavy::VERTICAL, ) } else { ( box_drawing::light::HORIZONTAL, box_drawing::light::DOWN_LEFT, box_drawing::light::VERTICAL, ) }; let horizontal_edge = horizontal.repeat(box_width); writeln!( writer, "{}{}", decoration_style.paint(&horizontal_edge), decoration_style.paint(down_left), )?; if text_style.is_raw { write!(writer, "{raw_text}")?; } else { write!(writer, "{}", paint_text(text_style, text, addendum))?; } write!( writer, "{}\n{}", decoration_style.paint(vertical), decoration_style.paint(&horizontal_edge), ) }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/handlers/git_show_file.rs
src/handlers/git_show_file.rs
use crate::delta::{State, StateMachine}; use crate::paint::{BgShouldFill, StyleSectionSpecifier}; use crate::utils::process; impl StateMachine<'_> { // If this is a line of `git show $revision:/path/to/file.ext` output then // syntax-highlight it as language `ext`. pub fn handle_git_show_file_line(&mut self) -> std::io::Result<bool> { self.painter.emit()?; let mut handled_line = false; if matches!(self.state, State::Unknown) { if let process::CallingProcess::GitShow(_, Some(filename)) = &*process::calling_process() { self.state = State::GitShowFile; self.painter.set_syntax(Some(filename)); } else { return Ok(handled_line); } } if matches!(self.state, State::GitShowFile) { self.painter.set_highlighter(); self.painter.syntax_highlight_and_paint_line( &self.line, StyleSectionSpecifier::Style(self.config.zero_style), self.state.clone(), BgShouldFill::default(), ); handled_line = true; } Ok(handled_line) } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/handlers/merge_conflict.rs
src/handlers/merge_conflict.rs
use std::ops::{Index, IndexMut}; use itertools::Itertools; use unicode_segmentation::UnicodeSegmentation; use super::draw; use crate::cli; use crate::config::{self, delta_unreachable}; use crate::delta::{DiffType, InMergeConflict, MergeParents, State, StateMachine}; use crate::minusplus::MinusPlus; use crate::paint::{self, prepare}; use crate::style::Style; #[derive(Clone, Debug, PartialEq, Eq)] pub enum MergeConflictCommit { Ours, Ancestral, Theirs, } pub struct MergeConflictCommits<T> { ours: T, ancestral: T, theirs: T, } pub type MergeConflictLines = MergeConflictCommits<Vec<(String, State)>>; pub type MergeConflictCommitNames = MergeConflictCommits<Option<String>>; impl StateMachine<'_> { pub fn handle_merge_conflict_line(&mut self) -> std::io::Result<bool> { use DiffType::*; use MergeConflictCommit::*; use State::*; let mut handled_line = false; if self.config.color_only || !self.config.handle_merge_conflicts { return Ok(handled_line); } match self.state.clone() { HunkHeader(Combined(merge_parents, InMergeConflict::No), _, _, _) | HunkMinus(Combined(merge_parents, InMergeConflict::No), _) | HunkZero(Combined(merge_parents, InMergeConflict::No), _) | HunkPlus(Combined(merge_parents, InMergeConflict::No), _) => { handled_line = self.enter_merge_conflict(&merge_parents) } MergeConflict(merge_parents, Ours) => { handled_line = self.enter_ancestral(&merge_parents) || self.enter_theirs(&merge_parents) || self.exit_merge_conflict(&merge_parents)? || self.store_line( Ours, HunkPlus(Combined(merge_parents, InMergeConflict::Yes), None), ); } MergeConflict(merge_parents, Ancestral) => { handled_line = self.enter_theirs(&merge_parents) || self.exit_merge_conflict(&merge_parents)? || self.store_line( Ancestral, HunkMinus(Combined(merge_parents, InMergeConflict::Yes), None), ); } MergeConflict(merge_parents, Theirs) => { handled_line = self.exit_merge_conflict(&merge_parents)? || self.store_line( Theirs, HunkPlus(Combined(merge_parents, InMergeConflict::Yes), None), ); } _ => {} } Ok(handled_line) } fn enter_merge_conflict(&mut self, merge_parents: &MergeParents) -> bool { use State::*; if let Some(commit) = parse_merge_marker(&self.line, "++<<<<<<<") { self.state = MergeConflict(merge_parents.clone(), Ours); self.painter.merge_conflict_commit_names[Ours] = Some(commit.to_string()); true } else { false } } fn enter_ancestral(&mut self, merge_parents: &MergeParents) -> bool { use State::*; if let Some(commit) = parse_merge_marker(&self.line, "++|||||||") { self.state = MergeConflict(merge_parents.clone(), Ancestral); self.painter.merge_conflict_commit_names[Ancestral] = Some(commit.to_string()); true } else { false } } fn enter_theirs(&mut self, merge_parents: &MergeParents) -> bool { use State::*; if self.line.starts_with("++=======") { self.state = MergeConflict(merge_parents.clone(), Theirs); true } else { false } } fn exit_merge_conflict(&mut self, merge_parents: &MergeParents) -> std::io::Result<bool> { if let Some(commit) = parse_merge_marker(&self.line, "++>>>>>>>") { self.painter.merge_conflict_commit_names[Theirs] = Some(commit.to_string()); self.paint_buffered_merge_conflict_lines(merge_parents)?; Ok(true) } else { Ok(false) } } fn store_line(&mut self, commit: MergeConflictCommit, state: State) -> bool { use State::*; if let HunkMinus(diff_type, _) | HunkZero(diff_type, _) | HunkPlus(diff_type, _) = &state { let line = prepare(&self.line, diff_type.n_parents(), self.config); self.painter.merge_conflict_lines[commit].push((line, state)); true } else { delta_unreachable(&format!("Invalid state: {state:?}")) } } fn paint_buffered_merge_conflict_lines( &mut self, merge_parents: &MergeParents, ) -> std::io::Result<()> { use DiffType::*; use State::*; self.painter.emit()?; write_merge_conflict_bar( &self.config.merge_conflict_begin_symbol, &mut self.painter, self.config, )?; for (derived_commit_type, header_style) in &[ (Ours, self.config.merge_conflict_ours_diff_header_style), (Theirs, self.config.merge_conflict_theirs_diff_header_style), ] { write_diff_header( derived_commit_type, *header_style, &mut self.painter, self.config, )?; self.painter.emit()?; paint::paint_minus_and_plus_lines( MinusPlus::new( &self.painter.merge_conflict_lines[Ancestral], &self.painter.merge_conflict_lines[derived_commit_type], ), &mut self.painter.line_numbers_data, &mut self.painter.highlighter, &mut self.painter.output_buffer, self.config, ); self.painter.emit()?; } // write_merge_conflict_decoration("bold ol", &mut self.painter, self.config)?; write_merge_conflict_bar( &self.config.merge_conflict_end_symbol, &mut self.painter, self.config, )?; self.painter.merge_conflict_lines.clear(); self.state = HunkZero(Combined(merge_parents.clone(), InMergeConflict::No), None); Ok(()) } } fn write_diff_header( derived_commit_type: &MergeConflictCommit, style: Style, painter: &mut paint::Painter, config: &config::Config, ) -> std::io::Result<()> { let (mut draw_fn, pad, decoration_ansi_term_style) = draw::get_draw_function(style.decoration_style); let derived_commit_name = &painter.merge_conflict_commit_names[derived_commit_type]; let text = if let Some(_ancestral_commit) = &painter.merge_conflict_commit_names[Ancestral] { format!( "ancestor {} {}{}", config.right_arrow, derived_commit_name.as_deref().unwrap_or("?"), if pad { " " } else { "" } ) } else { derived_commit_name.as_deref().unwrap_or("?").to_string() }; draw_fn( painter.writer, &text, &text, "", &config.decorations_width, style, decoration_ansi_term_style, )?; Ok(()) } fn write_merge_conflict_bar( s: &str, painter: &mut paint::Painter, config: &config::Config, ) -> std::io::Result<()> { let width = match config.decorations_width { cli::Width::Fixed(width) => width, cli::Width::Variable => config.available_terminal_width, }; writeln!( painter.writer, "{}", &s.graphemes(true).cycle().take(width).join("") )?; Ok(()) } fn parse_merge_marker<'a>(line: &'a str, marker: &str) -> Option<&'a str> { match line.strip_prefix(marker) { Some(suffix) => { let suffix = suffix.trim(); if !suffix.is_empty() { Some(suffix) } else { None } } None => None, } } pub use MergeConflictCommit::*; impl<T> Index<MergeConflictCommit> for MergeConflictCommits<T> { type Output = T; fn index(&self, commit: MergeConflictCommit) -> &Self::Output { match commit { Ours => &self.ours, Ancestral => &self.ancestral, Theirs => &self.theirs, } } } impl<T> Index<&MergeConflictCommit> for MergeConflictCommits<T> { type Output = T; fn index(&self, commit: &MergeConflictCommit) -> &Self::Output { match commit { Ours => &self.ours, Ancestral => &self.ancestral, Theirs => &self.theirs, } } } impl<T> IndexMut<MergeConflictCommit> for MergeConflictCommits<T> { fn index_mut(&mut self, commit: MergeConflictCommit) -> &mut Self::Output { match commit { Ours => &mut self.ours, Ancestral => &mut self.ancestral, Theirs => &mut self.theirs, } } } impl MergeConflictLines { pub fn new() -> Self { Self { ours: Vec::new(), ancestral: Vec::new(), theirs: Vec::new(), } } fn clear(&mut self) { self[Ours].clear(); self[Ancestral].clear(); self[Theirs].clear(); } } impl MergeConflictCommitNames { pub fn new() -> Self { Self { ours: None, ancestral: None, theirs: None, } } } #[cfg(test)] mod tests { use crate::ansi::strip_ansi_codes; use crate::tests::integration_test_utils; #[test] fn test_toy_merge_conflict_no_context() { let config = integration_test_utils::make_config_from_args(&[]); let output = integration_test_utils::run_delta(GIT_TOY_MERGE_CONFLICT_NO_CONTEXT, &config); let output = strip_ansi_codes(&output); assert!(output.contains("\n▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼")); assert!(output.contains( "\ ──────────────────┐ ancestor ⟶ HEAD │ ──────────────────┘ " )); assert!(output.contains("\n▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲")); } #[test] fn test_real_merge_conflict() { let config = integration_test_utils::make_config_from_args(&[]); let output = integration_test_utils::run_delta(GIT_MERGE_CONFLICT, &config); let output = strip_ansi_codes(&output); assert!(output.contains("\n▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼")); assert!(output.contains( "\ ──────────────────┐ ancestor ⟶ HEAD │ ──────────────────┘ " )); assert!(output.contains("\n▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲")); } #[test] #[allow(non_snake_case)] fn test_real_merge_conflict_U0() { let config = integration_test_utils::make_config_from_args(&[]); let output = integration_test_utils::run_delta(GIT_MERGE_CONFLICT_U0, &config); let output = strip_ansi_codes(&output); assert!(output.contains("\n▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼")); assert!(output.contains( "\ ──────────────────┐ ancestor ⟶ HEAD │ ──────────────────┘ " )); assert!(output.contains("\n▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲")); } const GIT_TOY_MERGE_CONFLICT_NO_CONTEXT: &str = "\ diff --cc file index 6178079,7898192..0000000 --- a/file +++ b/file @@@ -1,1 -1,1 +1,6 @@@ ++<<<<<<< HEAD +a ++||||||| parent of 0c20c9d... wip ++======= + b ++>>>>>>> 0c20c9d... wip "; const GIT_MERGE_CONFLICT: &str = r#"\ diff --cc src/handlers/merge_conflict.rs index 27d47c0,3a7e7b9..0000000 --- a/src/handlers/merge_conflict.rs +++ b/src/handlers/merge_conflict.rs @@@ -1,14 -1,13 +1,24 @@@ -use std::cmp::min; use std::ops::{Index, IndexMut}; ++<<<<<<< HEAD +use itertools::Itertools; +use unicode_segmentation::UnicodeSegmentation; + +use super::draw; +use crate::cli; +use crate::config::{self, delta_unreachable}; +use crate::delta::{DiffType, InMergeConflict, MergeParents, State, StateMachine}; ++||||||| parent of b2b28c8... Display merge conflict branches ++use crate::delta::{DiffType, MergeParents, State, StateMachine}; ++======= + use super::draw; + use crate::cli; + use crate::config::{self, delta_unreachable}; + use crate::delta::{DiffType, MergeParents, State, StateMachine}; ++>>>>>>> b2b28c8... Display merge conflict branches use crate::minusplus::MinusPlus; use crate::paint; + use crate::style::DecorationStyle; #[derive(Clone, Debug, PartialEq)] pub enum MergeConflictCommit { @@@ -30,7 -29,8 +40,15 @@@ pub type MergeConflictCommitNames = Mer impl<'a> StateMachine<'a> { pub fn handle_merge_conflict_line(&mut self) -> std::io::Result<bool> { use DiffType::*; ++<<<<<<< HEAD use MergeConflictCommit::*; ++||||||| parent of b2b28c8... Display merge conflict branches + use MergeParents::*; ++ use Source::*; ++======= ++ use MergeConflictCommit::*; ++ use MergeParents::*; ++>>>>>>> b2b28c8... Display merge conflict branches use State::*; let mut handled_line = false; @@@ -38,36 -38,28 +56,113 @@@ return Ok(handled_line); } ++<<<<<<< HEAD + match self.state.clone() { + HunkHeader(Combined(merge_parents, InMergeConflict::No), _, _) + | HunkMinus(Combined(merge_parents, InMergeConflict::No), _) + | HunkZero(Combined(merge_parents, InMergeConflict::No)) + | HunkPlus(Combined(merge_parents, InMergeConflict::No), _) => { + handled_line = self.enter_merge_conflict(&merge_parents) + } + MergeConflict(merge_parents, Ours) => { + handled_line = self.enter_ancestral(&merge_parents) + || self.enter_theirs(&merge_parents) + || self.exit_merge_conflict(&merge_parents)? + || self.store_line( + Ours, + HunkPlus(Combined(merge_parents, InMergeConflict::Yes), None), + ); ++||||||| parent of b2b28c8... Display merge conflict branches ++ // TODO: don't allocate on heap at this point ++ let prefix = self.line[..min(self.line.len(), 2)].to_string(); ++ let diff_type = Combined(Prefix(prefix)); ++ ++ match self.state { ++ // The only transition into a merge conflict is HunkZero => MergeConflict(Ours) ++ // TODO: shouldn't this be HunkZero(Some(_))? ++ HunkZero(_) => { ++ if self.line.starts_with("++<<<<<<<") { ++ self.state = MergeConflict(Ours); ++ handled_line = true ++ } + } ++ MergeConflict(Ours) => { ++ if self.line.starts_with("++|||||||") { ++ self.state = MergeConflict(Ancestral); ++ } else if self.line.starts_with("++=======") { ++ self.state = MergeConflict(Theirs); ++ } else if self.line.starts_with("++>>>>>>>") { ++ self.paint_buffered_merge_conflict_lines(diff_type)?; ++ } else { ++ let line = self.painter.prepare(&self.line, diff_type.n_parents()); ++ self.painter.merge_conflict_lines[Ours].push((line, HunkPlus(diff_type, None))); ++ } ++ handled_line = true ++======= + // TODO: don't allocate on heap at this point + let prefix = self.line[..min(self.line.len(), 2)].to_string(); + let diff_type = Combined(Prefix(prefix)); + + match self.state { + // The only transition into a merge conflict is HunkZero => MergeConflict(Ours) + // TODO: shouldn't this be HunkZero(Some(_))? + HunkZero(_) => handled_line = self.enter_merge_conflict(), + MergeConflict(Ours) => { + handled_line = self.enter_ancestral() + || self.enter_theirs() + || self.exit_merge_conflict(diff_type.clone())? + || self.store_line(Ours, HunkPlus(diff_type, None)); ++>>>>>>> b2b28c8... Display merge conflict branches + } ++<<<<<<< HEAD + MergeConflict(merge_parents, Ancestral) => { + handled_line = self.enter_theirs(&merge_parents) + || self.exit_merge_conflict(&merge_parents)? + || self.store_line( + Ancestral, + HunkMinus(Combined(merge_parents, InMergeConflict::Yes), None), + ); ++||||||| parent of b2b28c8... Display merge conflict branches ++ MergeConflict(Ancestral) => { ++ if self.line.starts_with("++=======") { ++ self.state = MergeConflict(Theirs); ++ } else if self.line.starts_with("++>>>>>>>") { ++ self.paint_buffered_merge_conflict_lines(diff_type)?; ++ } else { ++ let line = self.painter.prepare(&self.line, diff_type.n_parents()); ++ self.painter.merge_conflict_lines[Ancestral] ++ .push((line, HunkMinus(diff_type, None))); ++ } ++ handled_line = true ++======= + MergeConflict(Ancestral) => { + handled_line = self.enter_theirs() + || self.exit_merge_conflict(diff_type.clone())? + || self.store_line(Ancestral, HunkMinus(diff_type, None)); ++>>>>>>> b2b28c8... Display merge conflict branches } ++<<<<<<< HEAD + MergeConflict(merge_parents, Theirs) => { + handled_line = self.exit_merge_conflict(&merge_parents)? + || self.store_line( + Theirs, + HunkPlus(Combined(merge_parents, InMergeConflict::Yes), None), + ); ++||||||| parent of b2b28c8... Display merge conflict branches ++ MergeConflict(Theirs) => { ++ if self.line.starts_with("++>>>>>>>") { ++ self.paint_buffered_merge_conflict_lines(diff_type)?; ++ } else { ++ let line = self.painter.prepare(&self.line, diff_type.n_parents()); ++ self.painter.merge_conflict_lines[Theirs] ++ .push((line, HunkPlus(diff_type, None))); ++ } ++ handled_line = true ++======= + MergeConflict(Theirs) => { + handled_line = self.exit_merge_conflict(diff_type.clone())? + || self.store_line(Theirs, HunkPlus(diff_type, None)); ++>>>>>>> b2b28c8... Display merge conflict branches } _ => {} } @@@ -75,75 -67,71 +170,150 @@@ Ok(handled_line) } ++<<<<<<< HEAD + fn enter_merge_conflict(&mut self, merge_parents: &MergeParents) -> bool { + use State::*; + if let Some(commit) = parse_merge_marker(&self.line, "++<<<<<<<") { + self.state = MergeConflict(merge_parents.clone(), Ours); + self.painter.merge_conflict_commit_names[Ours] = Some(commit.to_string()); + true + } else { + false + } + } + + fn enter_ancestral(&mut self, merge_parents: &MergeParents) -> bool { + use State::*; + if let Some(commit) = parse_merge_marker(&self.line, "++|||||||") { + self.state = MergeConflict(merge_parents.clone(), Ancestral); + self.painter.merge_conflict_commit_names[Ancestral] = Some(commit.to_string()); + true + } else { + false + } + } + + fn enter_theirs(&mut self, merge_parents: &MergeParents) -> bool { + use State::*; + if self.line.starts_with("++=======") { + self.state = MergeConflict(merge_parents.clone(), Theirs); + true + } else { + false + } + } + + fn exit_merge_conflict(&mut self, merge_parents: &MergeParents) -> std::io::Result<bool> { + if let Some(commit) = parse_merge_marker(&self.line, "++>>>>>>>") { + self.painter.merge_conflict_commit_names[Theirs] = Some(commit.to_string()); + self.paint_buffered_merge_conflict_lines(merge_parents)?; + Ok(true) + } else { + Ok(false) + } + } + + fn store_line(&mut self, commit: MergeConflictCommit, state: State) -> bool { + use State::*; + if let HunkMinus(diff_type, _) | HunkZero(diff_type) | HunkPlus(diff_type, _) = &state { + let line = self.painter.prepare(&self.line, diff_type.n_parents()); + self.painter.merge_conflict_lines[commit].push((line, state)); + true + } else { + delta_unreachable(&format!("Invalid state: {:?}", state)) + } + } + + fn paint_buffered_merge_conflict_lines( + &mut self, + merge_parents: &MergeParents, + ) -> std::io::Result<()> { + use DiffType::*; + use State::*; ++||||||| parent of b2b28c8... Display merge conflict branches ++ fn paint_buffered_merge_conflict_lines(&mut self, diff_type: DiffType) -> std::io::Result<()> { ++======= + fn enter_merge_conflict(&mut self) -> bool { + use State::*; + if let Some(commit) = parse_merge_marker(&self.line, "++<<<<<<<") { + self.state = MergeConflict(Ours); + self.painter.merge_conflict_commit_names[Ours] = Some(commit.to_string()); + true + } else { + false + } + } + + fn enter_ancestral(&mut self) -> bool { + use State::*; + if let Some(commit) = parse_merge_marker(&self.line, "++|||||||") { + self.state = MergeConflict(Ancestral); + self.painter.merge_conflict_commit_names[Ancestral] = Some(commit.to_string()); + true + } else { + false + } + } + + fn enter_theirs(&mut self) -> bool { + use State::*; + if self.line.starts_with("++=======") { + self.state = MergeConflict(Theirs); + true + } else { + false + } + } + + fn exit_merge_conflict(&mut self, diff_type: DiffType) -> std::io::Result<bool> { + if let Some(commit) = parse_merge_marker(&self.line, "++>>>>>>>") { + self.painter.merge_conflict_commit_names[Theirs] = Some(commit.to_string()); + self.paint_buffered_merge_conflict_lines(diff_type)?; + Ok(true) + } else { + Ok(false) + } + } + + fn store_line(&mut self, commit: MergeConflictCommit, state: State) -> bool { + use State::*; + if let HunkMinus(diff_type, _) | HunkZero(diff_type) | HunkPlus(diff_type, _) = &state { + let line = self.painter.prepare(&self.line, diff_type.n_parents()); + self.painter.merge_conflict_lines[commit].push((line, state)); + true + } else { + delta_unreachable(&format!("Invalid state: {:?}", state)) + } + } + + fn paint_buffered_merge_conflict_lines(&mut self, diff_type: DiffType) -> std::io::Result<()> { ++>>>>>>> b2b28c8... Display merge conflict branches self.painter.emit()?; ++<<<<<<< HEAD + + write_merge_conflict_bar( + &self.config.merge_conflict_begin_symbol, + &mut self.painter, + self.config, + )?; + for derived_commit_type in &[Ours, Theirs] { + write_diff_header(derived_commit_type, &mut self.painter, self.config)?; + self.painter.emit()?; ++||||||| parent of b2b28c8... Display merge conflict branches ++ let lines = &self.painter.merge_conflict_lines; ++ for derived_lines in &[&lines[Ours], &lines[Theirs]] { ++======= + + write_merge_conflict_bar("▼", &mut self.painter, self.config)?; + for (derived_commit_type, decoration_style) in &[(Ours, "box"), (Theirs, "box")] { + write_subhunk_header( + derived_commit_type, + decoration_style, + &mut self.painter, + self.config, + )?; + self.painter.emit()?; ++>>>>>>> b2b28c8... Display merge conflict branches paint::paint_minus_and_plus_lines( MinusPlus::new( &self.painter.merge_conflict_lines[Ancestral], @@@ -156,78 -144,94 +326,190 @@@ ); self.painter.emit()?; } ++<<<<<<< HEAD + // write_merge_conflict_decoration("bold ol", &mut self.painter, self.config)?; + write_merge_conflict_bar( + &self.config.merge_conflict_end_symbol, + &mut self.painter, + self.config, + )?; ++||||||| parent of b2b28c8... Display merge conflict branches ++======= + // write_merge_conflict_decoration("bold ol", &mut self.painter, self.config)?; + write_merge_conflict_bar("▲", &mut self.painter, self.config)?; ++>>>>>>> b2b28c8... Display merge conflict branches self.painter.merge_conflict_lines.clear(); - self.state = State::HunkZero(diff_type); + self.state = HunkZero(Combined(merge_parents.clone(), InMergeConflict::No)); Ok(()) } } ++<<<<<<< HEAD +fn write_diff_header( + derived_commit_type: &MergeConflictCommit, + painter: &mut paint::Painter, + config: &config::Config, +) -> std::io::Result<()> { + let (mut draw_fn, pad, decoration_ansi_term_style) = + draw::get_draw_function(config.merge_conflict_diff_header_style.decoration_style); + let derived_commit_name = &painter.merge_conflict_commit_names[derived_commit_type]; + let text = if let Some(_ancestral_commit) = &painter.merge_conflict_commit_names[Ancestral] { + format!( + "ancestor {} {}{}", + config.right_arrow, + derived_commit_name.as_deref().unwrap_or("?"), + if pad { " " } else { "" } + ) + } else { + derived_commit_name.as_deref().unwrap_or("?").to_string() + }; + draw_fn( + painter.writer, + &text, + &text, + &config.decorations_width, + config.merge_conflict_diff_header_style, + decoration_ansi_term_style, + )?; + Ok(()) +} + +fn write_merge_conflict_bar( + s: &str, + painter: &mut paint::Painter, + config: &config::Config, +) -> std::io::Result<()> { + if let cli::Width::Fixed(width) = config.decorations_width { + writeln!( + painter.writer, + "{}", + &s.graphemes(true).cycle().take(width).join("") + )?; + } + Ok(()) +} + +fn parse_merge_marker<'a>(line: &'a str, marker: &str) -> Option<&'a str> { + match line.strip_prefix(marker) { + Some(suffix) => { + let suffix = suffix.trim(); + if !suffix.is_empty() { + Some(suffix) + } else { + None + } + } + None => None, + } +} + +pub use MergeConflictCommit::*; + ++impl<T> Index<MergeConflictCommit> for MergeConflictCommits<T> { ++ type Output = T; ++ fn index(&self, commit: MergeConflictCommit) -> &Self::Output { ++ match commit { ++ Ours => &self.ours, ++ Ancestral => &self.ancestral, ++ Theirs => &self.theirs, ++ } ++ } ++} ++||||||| parent of b2b28c8... Display merge conflict branches ++pub use Source::*; ++======= + fn write_subhunk_header( + derived_commit_type: &MergeConflictCommit, + decoration_style: &str, + painter: &mut paint::Painter, + config: &config::Config, + ) -> std::io::Result<()> { + let (mut draw_fn, pad, decoration_ansi_term_style) = + draw::get_draw_function(DecorationStyle::from_str( + decoration_style, + config.true_color, + config.git_config.as_ref(), + )); + let derived_commit_name = &painter.merge_conflict_commit_names[derived_commit_type]; + let text = if let Some(_ancestral_commit) = &painter.merge_conflict_commit_names[Ancestral] { + format!( + "ancestor {} {}{}", + config.right_arrow, + derived_commit_name.as_deref().unwrap_or("?"), + if pad { " " } else { "" } + ) + } else { + derived_commit_name.as_deref().unwrap_or("?").to_string() + }; + draw_fn( + painter.writer, + &text, + &text, + &config.decorations_width, + config.hunk_header_style, + decoration_ansi_term_style, + )?; + Ok(()) + } ++>>>>>>> b2b28c8... Display merge conflict branches + ++<<<<<<< HEAD ++impl<T> Index<&MergeConflictCommit> for MergeConflictCommits<T> { ++ type Output = T; ++ fn index(&self, commit: &MergeConflictCommit) -> &Self::Output { ++ match commit { ++||||||| parent of b2b28c8... Display merge conflict branches ++impl Index<Source> for MergeConflictLines { ++ type Output = Vec<(String, State)>; ++ fn index(&self, source: Source) -> &Self::Output { ++ match source { ++======= + #[allow(unused)] + fn write_merge_conflict_line( + painter: &mut paint::Painter, + config: &config::Config, + ) -> std::io::Result<()> { + let (mut draw_fn, _pad, decoration_ansi_term_style) = draw::get_draw_function( + DecorationStyle::from_str("bold ol", config.true_color, config.git_config.as_ref()), + ); + draw_fn( + painter.writer, + "", + "", + &config.decorations_width, + config.hunk_header_style, + decoration_ansi_term_style, + )?; + Ok(()) + } + + fn write_merge_conflict_bar( + s: &str, + painter: &mut paint::Painter, + config: &config::Config, + ) -> std::io::Result<()> { + if let cli::Width::Fixed(width) = config.decorations_width { + writeln!(painter.writer, "{}", s.repeat(width))?; + } + Ok(()) + } + + fn parse_merge_marker<'a>(line: &'a str, marker: &str) -> Option<&'a str> { + match line.strip_prefix(marker) { + Some(suffix) => { + let suffix = suffix.trim(); + if !suffix.is_empty() { + Some(suffix) + } else { + None + } + } + None => None, + } + } + + pub use MergeConflictCommit::*; + impl<T> Index<MergeConflictCommit> for MergeConflictCommits<T> { type Output = T; fn index(&self, commit: MergeConflictCommit) -> &Self::Output { @@@ -243,6 -247,6 +525,7 @@@ impl<T> Index<&MergeConflictCommit> fo type Output = T; fn index(&self, commit: &MergeConflictCommit) -> &Self::Output { match commit { ++>>>>>>> b2b28c8... Display merge conflict branches Ours => &self.ours, Ancestral => &self.ancestral, Theirs => &self.theirs, "#; const GIT_MERGE_CONFLICT_U0: &str = r#"\ diff --cc src/handlers/merge_conflict.rs index 27d47c0,3a7e7b9..0000000 --- a/src/handlers/merge_conflict.rs +++ b/src/handlers/merge_conflict.rs @@@ -3,7 -4,4 +3,16 @@@ use std::ops::{Index, IndexMut} ++<<<<<<< HEAD +use itertools::Itertools; +use unicode_segmentation::UnicodeSegmentation; + +use super::draw; +use crate::cli; +use crate::config::{self, delta_unreachable}; +use crate::delta::{DiffType, InMergeConflict, MergeParents, State, StateMachine}; ++||||||| parent of b2b28c8... Display merge conflict branches ++use crate::delta::{DiffType, MergeParents, State, StateMachine}; ++======= + use super::draw; + use crate::cli; + use crate::config::{self, delta_unreachable}; + use crate::delta::{DiffType, MergeParents, State, StateMachine}; ++>>>>>>> b2b28c8... Display merge conflict branches @@@ -33,0 -32,0 +43,1 @@@ impl<'a> StateMachine<'a> ++<<<<<<< HEAD @@@ -34,0 -33,1 +45,7 @@@ ++||||||| parent of b2b28c8... Display merge conflict branches + use MergeParents::*; ++ use Source::*; ++======= ++ use MergeConflictCommit::*; ++ use MergeParents::*; ++>>>>>>> b2b28c8... Display merge conflict branches @@@ -41,23 -41,18 +59,84 @@@
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
true
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/handlers/diff_header.rs
src/handlers/diff_header.rs
use std::borrow::Cow; use std::path::Path; use unicode_segmentation::UnicodeSegmentation; use super::draw; use crate::config::Config; use crate::delta::{DiffType, Source, State, StateMachine}; use crate::paint::Painter; use crate::{features, utils}; // https://git-scm.com/docs/git-config#Documentation/git-config.txt-diffmnemonicPrefix const DIFF_PREFIXES: [&str; 6] = ["a/", "b/", "c/", "i/", "o/", "w/"]; #[derive(Debug, PartialEq, Eq)] pub enum FileEvent { Added, Change, Copy, Rename, Removed, NoEvent, } impl StateMachine<'_> { /// Check for the old mode|new mode lines and cache their info for later use. pub fn handle_diff_header_mode_line(&mut self) -> std::io::Result<bool> { let mut handled_line = false; if let Some(line_suf) = self.line.strip_prefix("old mode ") { self.state = State::DiffHeader(DiffType::Unified); if self.should_handle() && !self.config.color_only { self.mode_info = line_suf.to_string(); handled_line = true; } } else if let Some(line_suf) = self.line.strip_prefix("new mode ") { self.state = State::DiffHeader(DiffType::Unified); if self.should_handle() && !self.config.color_only && !self.mode_info.is_empty() { self.mode_info = match (self.mode_info.as_str(), line_suf) { // 100755 for executable and 100644 for non-executable are the only file modes Git records. // https://medium.com/@tahteche/how-git-treats-changes-in-file-permissions-f71874ca239d ("100644", "100755") => "mode +x".to_string(), ("100755", "100644") => "mode -x".to_string(), _ => format!( "mode {} {} {}", self.mode_info, self.config.right_arrow, line_suf ), }; handled_line = true; } } Ok(handled_line) } fn should_write_generic_diff_header_header_line(&mut self) -> std::io::Result<bool> { // In color_only mode, raw_line's structure shouldn't be changed. // So it needs to avoid fn _handle_diff_header_header_line // (it connects the plus_file and minus_file), // and to call fn handle_generic_diff_header_header_line directly. if self.config.color_only { write_generic_diff_header_header_line( &self.line, &self.raw_line, &mut self.painter, &mut self.mode_info, self.config, )?; Ok(true) } else { Ok(false) } } #[inline] fn test_diff_header_minus_line(&self) -> bool { (matches!(self.state, State::DiffHeader(_)) || self.source == Source::DiffUnified) && ((self.line.starts_with("--- ") && self.minus_line_counter.three_dashes_expected()) || self.line.starts_with("rename from ") || self.line.starts_with("copy from ")) } /// Check for and handle the "--- filename ..." line. pub fn handle_diff_header_minus_line(&mut self) -> std::io::Result<bool> { if !self.test_diff_header_minus_line() { return Ok(false); } let (mut path_or_mode, file_event) = parse_diff_header_line(&self.line, self.source == Source::GitDiff); utils::path::relativize_path_maybe(&mut path_or_mode, self.config); self.minus_file = path_or_mode; self.minus_file_event = file_event; if self.source == Source::DiffUnified { self.state = State::DiffHeader(DiffType::Unified); self.painter .set_syntax(get_filename_from_marker_line(&self.line)); } else { self.painter .set_syntax(get_filename_from_diff_header_line_file_path( &self.minus_file, )); } self.painter.paint_buffered_minus_and_plus_lines(); self.should_write_generic_diff_header_header_line() } #[inline] fn test_diff_header_plus_line(&self) -> bool { (matches!(self.state, State::DiffHeader(_)) || self.source == Source::DiffUnified) && (self.line.starts_with("+++ ") || self.line.starts_with("rename to ") || self.line.starts_with("copy to ")) } /// Check for and handle the "+++ filename ..." line. pub fn handle_diff_header_plus_line(&mut self) -> std::io::Result<bool> { if !self.test_diff_header_plus_line() { return Ok(false); } let mut handled_line = false; let (mut path_or_mode, file_event) = parse_diff_header_line(&self.line, self.source == Source::GitDiff); utils::path::relativize_path_maybe(&mut path_or_mode, self.config); self.plus_file = path_or_mode; self.plus_file_event = file_event; self.painter .set_syntax(get_filename_from_diff_header_line_file_path( &self.plus_file, )); self.current_file_pair = Some((self.minus_file.clone(), self.plus_file.clone())); self.painter.paint_buffered_minus_and_plus_lines(); if self.should_write_generic_diff_header_header_line()? { handled_line = true; } else if self.should_handle() && self.handled_diff_header_header_line_file_pair != self.current_file_pair { self.painter.emit()?; self._handle_diff_header_header_line(self.source == Source::DiffUnified)?; self.handled_diff_header_header_line_file_pair .clone_from(&self.current_file_pair); } Ok(handled_line) } #[inline] fn test_diff_header_file_operation_line(&self) -> bool { (matches!(self.state, State::DiffHeader(_)) || self.source == Source::DiffUnified) && (self.line.starts_with("deleted file mode ") || self.line.starts_with("new file mode ")) } /// Check for and handle the "deleted file ..." line. pub fn handle_diff_header_file_operation_line(&mut self) -> std::io::Result<bool> { if !self.test_diff_header_file_operation_line() { return Ok(false); } let mut handled_line = false; let (_mode_info, file_event) = parse_diff_header_line(&self.line, self.source == Source::GitDiff); let name = get_repeated_file_path_from_diff_line(&self.diff_line).unwrap_or_default(); match file_event { FileEvent::Removed => { self.minus_file = name; self.plus_file = "/dev/null".into(); self.minus_file_event = FileEvent::Change; self.plus_file_event = FileEvent::Change; self.current_file_pair = Some((self.minus_file.clone(), self.plus_file.clone())); } FileEvent::Added => { self.minus_file = "/dev/null".into(); self.plus_file = name; self.minus_file_event = FileEvent::Change; self.plus_file_event = FileEvent::Change; self.current_file_pair = Some((self.minus_file.clone(), self.plus_file.clone())); } _ => (), } if self.should_write_generic_diff_header_header_line()? || (self.should_handle() && self.handled_diff_header_header_line_file_pair != self.current_file_pair) { handled_line = true; } Ok(handled_line) } /// Construct file change line from minus and plus file and write with DiffHeader styling. fn _handle_diff_header_header_line(&mut self, comparing: bool) -> std::io::Result<()> { let line = get_file_change_description_from_file_paths( &self.minus_file, &self.plus_file, comparing, &self.minus_file_event, &self.plus_file_event, self.config, ); // FIXME: no support for 'raw' write_generic_diff_header_header_line( &line, &line, &mut self.painter, &mut self.mode_info, self.config, ) } #[inline] fn test_pending_line_with_diff_name(&self) -> bool { matches!(self.state, State::DiffHeader(_)) || self.source == Source::DiffUnified } pub fn handle_pending_line_with_diff_name(&mut self) -> std::io::Result<()> { if !self.test_pending_line_with_diff_name() { return Ok(()); } if !self.mode_info.is_empty() { let format_label = |label: &str| { if !label.is_empty() { format!("{label} ") } else { "".to_string() } }; let format_file = |file| match ( self.config.hyperlinks, utils::path::absolute_path(file, self.config), ) { (true, Some(absolute_path)) => features::hyperlinks::format_osc8_file_hyperlink( absolute_path, None, file, self.config, ), _ => Cow::from(file), }; let label = format_label(&self.config.file_modified_label); let name = get_repeated_file_path_from_diff_line(&self.diff_line).unwrap_or_default(); let line = format!("{}{}", label, format_file(&name)); write_generic_diff_header_header_line( &line, &line, &mut self.painter, &mut self.mode_info, self.config, ) } else if !self.config.color_only && self.should_handle() && self.handled_diff_header_header_line_file_pair != self.current_file_pair { self._handle_diff_header_header_line(self.source == Source::DiffUnified)?; self.handled_diff_header_header_line_file_pair .clone_from(&self.current_file_pair); Ok(()) } else { Ok(()) } } } /// Write `line` with DiffHeader styling. pub fn write_generic_diff_header_header_line( line: &str, raw_line: &str, painter: &mut Painter, mode_info: &mut String, config: &Config, ) -> std::io::Result<()> { // If file_style is "omit", we'll skip the process and print nothing. // However in the case of color_only mode, // we won't skip because we can't change raw_line structure. if config.file_style.is_omitted && !config.color_only { return Ok(()); } let (mut draw_fn, pad, decoration_ansi_term_style) = draw::get_draw_function(config.file_style.decoration_style); if !config.color_only { // Maintain 1-1 correspondence between input and output lines. writeln!(painter.writer)?; } draw_fn( painter.writer, &format!("{}{}", line, if pad { " " } else { "" }), &format!("{}{}", raw_line, if pad { " " } else { "" }), mode_info, &config.decorations_width, config.file_style, decoration_ansi_term_style, )?; if !mode_info.is_empty() { mode_info.truncate(0); } Ok(()) } #[allow(clippy::tabs_in_doc_comments)] /// Given input like /// "--- a/zero/one.rs 2019-11-20 06:16:08.000000000 +0100" /// Return "one.rs" fn get_filename_from_marker_line(line: &str) -> Option<&str> { line.split('\t') .next() .and_then(|column| column.split(' ').nth(1)) .and_then(get_filename_from_diff_header_line_file_path) } fn get_filename_from_diff_header_line_file_path(path: &str) -> Option<&str> { Path::new(path).file_name().and_then(|filename| { if path != "/dev/null" { filename.to_str() } else { None } }) } fn parse_diff_header_line(line: &str, git_diff_name: bool) -> (String, FileEvent) { match line { line if line.starts_with("--- ") || line.starts_with("+++ ") => { let offset = 4; let file = _parse_file_path(&line[offset..], git_diff_name); (file, FileEvent::Change) } line if line.starts_with("rename from ") => { (line[12..].to_string(), FileEvent::Rename) // "rename from ".len() } line if line.starts_with("rename to ") => { (line[10..].to_string(), FileEvent::Rename) // "rename to ".len() } line if line.starts_with("copy from ") => { (line[10..].to_string(), FileEvent::Copy) // "copy from ".len() } line if line.starts_with("copy to ") => { (line[8..].to_string(), FileEvent::Copy) // "copy to ".len() } line if line.starts_with("new file mode ") => { (line[14..].to_string(), FileEvent::Added) // "new file mode ".len() } line if line.starts_with("deleted file mode ") => { (line[18..].to_string(), FileEvent::Removed) // "deleted file mode ".len() } _ => ("".to_string(), FileEvent::NoEvent), } } /// Given input like "diff --git a/src/my file.rs b/src/my file.rs" /// return Some("src/my file.rs") pub fn get_repeated_file_path_from_diff_line(line: &str) -> Option<String> { if let Some(line) = line.strip_prefix("diff --git ") { let line: Vec<&str> = line.graphemes(true).collect(); let midpoint = line.len() / 2; if line[midpoint] == " " { let first_path = _parse_file_path(&line[..midpoint].join(""), true); let second_path = _parse_file_path(&line[midpoint + 1..].join(""), true); if first_path == second_path { return Some(first_path); } } } None } fn remove_surrounding_quotes(path: &str) -> &str { if path.starts_with('"') && path.ends_with('"') { // Indexing into the UTF-8 string is safe because of the previous test &path[1..path.len() - 1] } else { path } } fn _parse_file_path(path: &str, git_diff_name: bool) -> String { // When git config 'core.quotepath = true' (the default), and `path` contains // non-ASCII characters, a backslash, or a quote; then it is quoted, so remove // these quotes. Characters may also be escaped, but these are left as-is. let path = remove_surrounding_quotes(path); // It appears that, if the file name contains a space, git appends a tab // character in the diff metadata lines, e.g. // $ git diff --no-index "a b" "c d" | cat -A // diff·--git·a/a·b·b/c·d␊ // index·d00491f..0cfbf08·100644␊ // ---·a/a·b├──┤␊ // +++·b/c·d├──┤␊ match path.strip_suffix('\t').unwrap_or(path) { "/dev/null" => "/dev/null", path if git_diff_name && DIFF_PREFIXES.iter().any(|s| path.starts_with(s)) => &path[2..], path if git_diff_name => path, path => path.split('\t').next().unwrap_or(""), } .to_string() } pub fn get_file_change_description_from_file_paths( minus_file: &str, plus_file: &str, comparing: bool, minus_file_event: &FileEvent, plus_file_event: &FileEvent, config: &Config, ) -> String { let format_label = |label: &str| { if !label.is_empty() { format!("{label} ") } else { "".to_string() } }; if comparing { format!( "{}{} {} {}", format_label(&config.file_modified_label), minus_file, config.right_arrow, plus_file ) } else { let format_file = |file| { let formatted_file = if let Some(regex_replacement) = &config.file_regex_replacement { regex_replacement.execute(file) } else { Cow::from(file) }; match (config.hyperlinks, utils::path::absolute_path(file, config)) { (true, Some(absolute_path)) => features::hyperlinks::format_osc8_file_hyperlink( absolute_path, None, &formatted_file, config, ), _ => formatted_file, } }; match (minus_file, plus_file, minus_file_event, plus_file_event) { (minus_file, plus_file, _, _) if minus_file == plus_file => format!( "{}{}", format_label(&config.file_modified_label), format_file(minus_file) ), (minus_file, "/dev/null", _, _) => format!( "{}{}", format_label(&config.file_removed_label), format_file(minus_file) ), ("/dev/null", plus_file, _, _) => format!( "{}{}", format_label(&config.file_added_label), format_file(plus_file) ), // minus_file_event == plus_file_event (minus_file, plus_file, file_event, _) => format!( "{}{} {} {}", format_label(match file_event { FileEvent::Rename => &config.file_renamed_label, FileEvent::Copy => &config.file_copied_label, _ => &config.file_modified_label, }), format_file(minus_file), config.right_arrow, format_file(plus_file) ), } } } #[cfg(test)] mod tests { use super::*; use crate::tests::integration_test_utils::{make_config_from_args, DeltaTest}; use insta::assert_snapshot; #[test] fn test_get_filename_from_marker_line() { assert_eq!( get_filename_from_marker_line("--- src/one.rs 2019-11-20 06:47:56.000000000 +0100"), Some("one.rs") ); } #[test] fn test_get_filename_from_diff_header_line() { assert_eq!( get_filename_from_diff_header_line_file_path("a/src/parse.rs"), Some("parse.rs") ); assert_eq!( get_filename_from_diff_header_line_file_path("b/src/pa rse.rs"), Some("pa rse.rs") ); assert_eq!( get_filename_from_diff_header_line_file_path("src/pa rse.rs"), Some("pa rse.rs") ); assert_eq!( get_filename_from_diff_header_line_file_path("wat hello.rs"), Some("wat hello.rs") ); assert_eq!( get_filename_from_diff_header_line_file_path("/dev/null"), None ); assert_eq!( get_filename_from_diff_header_line_file_path("Dockerfile"), Some("Dockerfile") ); assert_eq!( get_filename_from_diff_header_line_file_path("Makefile"), Some("Makefile") ); assert_eq!( get_filename_from_diff_header_line_file_path("a/src/Makefile"), Some("Makefile") ); assert_eq!( get_filename_from_diff_header_line_file_path("src/Makefile"), Some("Makefile") ); } // We should only strip the prefixes if they are "a/" or "b/". This will be correct except for // the case of a user with `diff.noprefix = true` who has directories named "a" or "b", which // is an irresolvable ambiguity. Ideally one would only strip the prefixes if we have confirmed // that we are looking at something like // // --- a/src/parse.rs // +++ b/src/parse.rs // // as opposed to something like // // --- a/src/parse.rs // +++ sibling_of_a/src/parse.rs // // but we don't attempt that currently. #[test] fn test_get_file_path_from_git_diff_header_line() { assert_eq!( parse_diff_header_line("--- /dev/null", true), ("/dev/null".to_string(), FileEvent::Change) ); for prefix in &DIFF_PREFIXES { assert_eq!( parse_diff_header_line(&format!("--- {prefix}src/delta.rs"), true), ("src/delta.rs".to_string(), FileEvent::Change) ); } assert_eq!( parse_diff_header_line("--- src/delta.rs", true), ("src/delta.rs".to_string(), FileEvent::Change) ); assert_eq!( parse_diff_header_line("+++ src/delta.rs", true), ("src/delta.rs".to_string(), FileEvent::Change) ); assert_eq!( parse_diff_header_line("+++ \".\\delta.rs\"", true), (".\\delta.rs".to_string(), FileEvent::Change) ); } #[test] fn test_get_file_path_from_git_diff_header_line_containing_spaces() { assert_eq!( parse_diff_header_line("+++ a/my src/delta.rs", true), ("my src/delta.rs".to_string(), FileEvent::Change) ); assert_eq!( parse_diff_header_line("+++ my src/delta.rs", true), ("my src/delta.rs".to_string(), FileEvent::Change) ); assert_eq!( parse_diff_header_line("+++ a/src/my delta.rs", true), ("src/my delta.rs".to_string(), FileEvent::Change) ); assert_eq!( parse_diff_header_line("+++ a/my src/my delta.rs", true), ("my src/my delta.rs".to_string(), FileEvent::Change) ); assert_eq!( parse_diff_header_line("+++ b/my src/my enough/my delta.rs", true), ( "my src/my enough/my delta.rs".to_string(), FileEvent::Change ) ); } #[test] fn test_get_file_path_from_git_diff_header_line_rename() { assert_eq!( parse_diff_header_line("rename from nospace/file2.el", true), ("nospace/file2.el".to_string(), FileEvent::Rename) ); } #[test] fn test_get_file_path_from_git_diff_header_line_rename_containing_spaces() { assert_eq!( parse_diff_header_line("rename from with space/file1.el", true), ("with space/file1.el".to_string(), FileEvent::Rename) ); } #[test] fn test_parse_diff_header_line() { assert_eq!( parse_diff_header_line("--- src/delta.rs", false), ("src/delta.rs".to_string(), FileEvent::Change) ); assert_eq!( parse_diff_header_line("+++ src/delta.rs", false), ("src/delta.rs".to_string(), FileEvent::Change) ); } #[test] fn test_get_repeated_file_path_from_diff_line() { assert_eq!( get_repeated_file_path_from_diff_line("diff --git a/src/main.rs b/src/main.rs"), Some("src/main.rs".to_string()) ); assert_eq!( get_repeated_file_path_from_diff_line("diff --git a/a b/a"), Some("a".to_string()) ); assert_eq!( get_repeated_file_path_from_diff_line("diff --git a/a b b/a b"), Some("a b".to_string()) ); assert_eq!( get_repeated_file_path_from_diff_line("diff --git a/a b/aa"), None ); assert_eq!( get_repeated_file_path_from_diff_line( "diff --git a/.config/Code - Insiders/User/settings.json b/.config/Code - Insiders/User/settings.json"), Some(".config/Code - Insiders/User/settings.json".to_string()) ); assert_eq!( get_repeated_file_path_from_diff_line(r#"diff --git "a/quoted" "b/quoted""#), Some("quoted".to_string()) ); } #[test] fn test_diff_header_with_mode_change_in_last_hunk() { let input = "\ diff --git a/a.txt b/a.txt index 44371ed..e69de29 100644 --- a/a.txt +++ b/a.txt @@ -1 +0,0 @@ -A-content diff --git a/b.txt b/b.txt old mode 100644 new mode 100755 "; let result = DeltaTest::with_args(&[]).with_input(input); assert_snapshot!(result.output, @r" a.txt ─────────────────────────────────────────── ───┐ 0: │ ───┘ A-content b.txt (mode +x) ─────────────────────────────────────────── "); } #[test] fn test_diff_header_with_2x_mode_change() { let input = "\ diff --git a/a.txt b/a.txt index 44371ed..e69de29 100644 --- a/a.txt +++ b/a.txt @@ -1 +0,0 @@ -A-content diff --git a/b.txt b/b.txt old mode 100644 new mode 100755 --- a/b.txt +++ b/b.txt diff --git a/c.txt b/c.txt old mode 100644 new mode 100755 "; let result = DeltaTest::with_args(&[]).with_input(input); assert_snapshot!(result.output, @r" a.txt ─────────────────────────────────────────── ───┐ 0: │ ───┘ A-content b.txt (mode +x) ─────────────────────────────────────────── c.txt (mode +x) ─────────────────────────────────────────── "); } pub const BIN_AND_TXT_FILE_ADDED: &str = "\ diff --git a/BIN b/BIN new file mode 100644 index 0000000..a5d0c46 Binary files /dev/null and b/BIN differ diff --git a/TXT b/TXT new file mode 100644 index 0000000..323fae0 --- /dev/null +++ b/TXT @@ -0,0 +1 @@ +plain text"; #[test] fn test_diff_header_relative_paths() { // rustfmt ignores the assert macro arguments, so do the setup outside let mut cfg = make_config_from_args(&["--relative-paths", "-s"]); cfg.cwd_relative_to_repo_root = Some("src/utils/".into()); let result = DeltaTest::with_config(&cfg) .with_input(BIN_AND_TXT_FILE_ADDED) .output; // convert windows '..\' to unix '../' paths insta::with_settings!({filters => vec![(r"\.\.\\", "../")]}, { assert_snapshot!(result, @r###" added: ../../BIN (binary file) ─────────────────────────────────────────── added: ../../TXT ─────────────────────────────────────────── ───┐ 1: │ ───┘ │ │ │ 1 │plain text "###) }); } pub const DIFF_AMBIGUOUS_HEADER_3X_MINUS: &str = r#"--- a.lua +++ b.lua @@ -1,5 +1,4 @@ #!/usr/bin/env lua print("Hello") --- World? print("..") "#; pub const DIFF_AMBIGUOUS_HEADER_3X_MINUS_LAST_LINE: &str = r#"--- c.lua +++ d.lua @@ -1,4 +1,3 @@ #!/usr/bin/env lua print("Hello") --- World? "#; pub const DIFF_AMBIGUOUS_HEADER_MULTIPLE_HUNKS: &str = r#"--- e.lua 2024-08-04 20:50:27.257726606 +0200 +++ f.lua 2024-08-04 20:50:35.345795405 +0200 @@ -3,3 +3,2 @@ print("Hello") --- World? print("") @@ -7,2 +6,3 @@ print("") +print("World") print("") @@ -10,2 +10 @@ print("") --- End "#; #[test] fn test_diff_header_ambiguous_3x_minus() { // check ansi output to ensure output is highlighted let result = DeltaTest::with_args(&[]) .explain_ansi() .with_input(DIFF_AMBIGUOUS_HEADER_3X_MINUS); assert_snapshot!(result.output, @r###" (normal) (blue)a.lua ⟶ b.lua(normal) (blue)───────────────────────────────────────────(normal) (blue)───(blue)┐(normal) (blue)1(normal): (blue)│(normal) (blue)───(blue)┘(normal) (203)#(231)!(203)/(231)usr(203)/(231)bin(203)/(231)env lua(normal) (81)print(231)((186)"Hello"(231))(normal) (normal 52)-- World?(normal) (81)print(231)((186)".."(231))(normal) "###); } #[test] fn test_diff_header_ambiguous_3x_minus_concatenated() { let result = DeltaTest::with_args(&[]) .explain_ansi() .with_input(&format!( "{}{}{}", DIFF_AMBIGUOUS_HEADER_MULTIPLE_HUNKS, DIFF_AMBIGUOUS_HEADER_3X_MINUS, DIFF_AMBIGUOUS_HEADER_3X_MINUS_LAST_LINE )); assert_snapshot!(result.output, @r###" (normal) (blue)e.lua ⟶ f.lua(normal) (blue)───────────────────────────────────────────(normal) (blue)───(blue)┐(normal) (blue)3(normal): (blue)│(normal) (blue)───(blue)┘(normal) (81)print(231)((186)"Hello"(231))(normal) (normal 52)-- World?(normal) (81)print(231)((186)""(231))(normal) (blue)───(blue)┐(normal) (blue)6(normal): (blue)│(normal) (blue)───(blue)┘(normal) (81)print(231)((186)""(231))(normal) (81 22)print(231)((186)"World"(231))(normal) (81)print(231)((186)""(231))(normal) (blue)────(blue)┐(normal) (blue)10(normal): (blue)│(normal) (blue)────(blue)┘(normal) (81)print(231)((186)""(231))(normal) (normal 52)-- End(normal) (blue)a.lua ⟶ b.lua(normal) (blue)───────────────────────────────────────────(normal) (blue)───(blue)┐(normal) (blue)1(normal): (blue)│(normal) (blue)───(blue)┘(normal) (203)#(231)!(203)/(231)usr(203)/(231)bin(203)/(231)env lua(normal) (81)print(231)((186)"Hello"(231))(normal) (normal 52)-- World?(normal) (81)print(231)((186)".."(231))(normal) (blue)c.lua ⟶ d.lua(normal) (blue)───────────────────────────────────────────(normal) (blue)───(blue)┐(normal) (blue)1(normal): (blue)│(normal) (blue)───(blue)┘(normal) (203)#(231)!(203)/(231)usr(203)/(231)bin(203)/(231)env lua(normal) (81)print(231)((186)"Hello"(231))(normal) (normal 52)-- World?(normal) "###); } #[test] fn test_diff_header_ambiguous_3x_minus_extra_and_concatenated() { let result = DeltaTest::with_args(&[]) .explain_ansi() .with_input(&format!( "extra 1\n\n{}\nextra 2\n{}\nextra 3\n{}", DIFF_AMBIGUOUS_HEADER_MULTIPLE_HUNKS, DIFF_AMBIGUOUS_HEADER_3X_MINUS, DIFF_AMBIGUOUS_HEADER_3X_MINUS_LAST_LINE )); assert_snapshot!(result.output, @r###" (normal)extra 1 (blue)e.lua ⟶ f.lua(normal) (blue)───────────────────────────────────────────(normal) (blue)───(blue)┐(normal) (blue)3(normal): (blue)│(normal) (blue)───(blue)┘(normal) (81)print(231)((186)"Hello"(231))(normal) (normal 52)-- World?(normal) (81)print(231)((186)""(231))(normal) (blue)───(blue)┐(normal) (blue)6(normal): (blue)│(normal) (blue)───(blue)┘(normal) (81)print(231)((186)""(231))(normal) (81 22)print(231)((186)"World"(231))(normal) (81)print(231)((186)""(231))(normal) (blue)────(blue)┐(normal) (blue)10(normal): (blue)│(normal) (blue)────(blue)┘(normal) (81)print(231)((186)""(231))(normal) (normal 52)-- End(normal) extra 2 (blue)a.lua ⟶ b.lua(normal) (blue)───────────────────────────────────────────(normal) (blue)───(blue)┐(normal) (blue)1(normal): (blue)│(normal) (blue)───(blue)┘(normal) (203)#(231)!(203)/(231)usr(203)/(231)bin(203)/(231)env lua(normal) (81)print(231)((186)"Hello"(231))(normal) (normal 52)-- World?(normal) (81)print(231)((186)".."(231))(normal) extra 3
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
true
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/handlers/submodule.rs
src/handlers/submodule.rs
use lazy_static::lazy_static; use regex::Regex; use crate::delta::{State, StateMachine}; impl StateMachine<'_> { #[inline] fn test_submodule_log(&self) -> bool { self.line.starts_with("Submodule ") } pub fn handle_submodule_log_line(&mut self) -> std::io::Result<bool> { if !self.test_submodule_log() { return Ok(false); } self.handle_additional_cases(State::SubmoduleLog) } #[inline] fn test_submodule_short_line(&self) -> bool { matches!(self.state, State::HunkHeader(_, _, _, _)) && self.line.starts_with("-Subproject commit ") || matches!(self.state, State::SubmoduleShort(_)) && self.line.starts_with("+Subproject commit ") } pub fn handle_submodule_short_line(&mut self) -> std::io::Result<bool> { if !self.test_submodule_short_line() || self.config.color_only { return Ok(false); } if let Some(commit) = get_submodule_short_commit(&self.line) { if let State::HunkHeader(_, _, _, _) = self.state { self.state = State::SubmoduleShort(commit.to_owned()); } else if let State::SubmoduleShort(minus_commit) = &self.state { self.painter.emit()?; writeln!( self.painter.writer, "{}..{}", self.config .minus_style .paint(minus_commit.chars().take(12).collect::<String>()), self.config .plus_style .paint(commit.chars().take(12).collect::<String>()), )?; } } Ok(true) } } lazy_static! { static ref SUBMODULE_SHORT_LINE_REGEX: Regex = Regex::new("^[-+]Subproject commit ([0-9a-f]{40})(-dirty)?$").unwrap(); } pub fn get_submodule_short_commit(line: &str) -> Option<&str> { match SUBMODULE_SHORT_LINE_REGEX.captures(line) { Some(caps) => Some(caps.get(1).unwrap().as_str()), None => None, } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/handlers/commit_meta.rs
src/handlers/commit_meta.rs
use std::borrow::Cow; use super::draw; use crate::delta::{State, StateMachine}; use crate::features; impl StateMachine<'_> { #[inline] fn test_commit_meta_header_line(&self) -> bool { self.config.commit_regex.is_match(&self.line) } pub fn handle_commit_meta_header_line(&mut self) -> std::io::Result<bool> { if !self.test_commit_meta_header_line() { return Ok(false); } let mut handled_line = false; self.painter.paint_buffered_minus_and_plus_lines(); self.handle_pending_line_with_diff_name()?; self.state = State::CommitMeta; if self.should_handle() { self.painter.emit()?; self._handle_commit_meta_header_line()?; handled_line = true } Ok(handled_line) } fn _handle_commit_meta_header_line(&mut self) -> std::io::Result<()> { if self.config.commit_style.is_omitted { return Ok(()); } let (mut draw_fn, pad, decoration_ansi_term_style) = draw::get_draw_function(self.config.commit_style.decoration_style); let (formatted_line, formatted_raw_line) = if self.config.hyperlinks { ( features::hyperlinks::format_commit_line_with_osc8_commit_hyperlink( &self.line, self.config, ), features::hyperlinks::format_commit_line_with_osc8_commit_hyperlink( &self.raw_line, self.config, ), ) } else { (Cow::from(&self.line), Cow::from(&self.raw_line)) }; draw_fn( self.painter.writer, &format!("{}{}", formatted_line, if pad { " " } else { "" }), &format!("{}{}", formatted_raw_line, if pad { " " } else { "" }), "", &self.config.decorations_width, self.config.commit_style, decoration_ansi_term_style, )?; Ok(()) } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/handlers/hunk.rs
src/handlers/hunk.rs
use std::cmp::min; use lazy_static::lazy_static; use crate::cli; use crate::config::{delta_unreachable, Config}; use crate::delta::{DiffType, InMergeConflict, MergeParents, State, StateMachine}; use crate::paint::{prepare, prepare_raw_line}; use crate::style; use crate::utils::process::{self, CallingProcess}; use crate::utils::tabs; // HACK: WordDiff should probably be a distinct top-level line state pub fn is_word_diff() -> bool { #[cfg(not(test))] { *CACHED_IS_WORD_DIFF } #[cfg(test)] { compute_is_word_diff() } } lazy_static! { static ref CACHED_IS_WORD_DIFF: bool = compute_is_word_diff(); } fn compute_is_word_diff() -> bool { match &*process::calling_process() { CallingProcess::GitDiff(cmd_line) | CallingProcess::GitShow(cmd_line, _) | CallingProcess::GitLog(cmd_line) | CallingProcess::GitReflog(cmd_line) => { cmd_line.long_options.contains("--word-diff") || cmd_line.long_options.contains("--word-diff-regex") || cmd_line.long_options.contains("--color-words") } _ => false, } } impl StateMachine<'_> { #[inline] fn test_hunk_line(&self) -> bool { matches!( self.state, State::HunkHeader(_, _, _, _) | State::HunkZero(_, _) | State::HunkMinus(_, _) | State::HunkPlus(_, _) ) } /// Handle a hunk line, i.e. a minus line, a plus line, or an unchanged line. // In the case of a minus or plus line, we store the line in a // buffer. When we exit the changed region we process the collected // minus and plus lines jointly, in order to paint detailed // highlighting according to inferred edit operations. In the case of // an unchanged line, we paint it immediately. pub fn handle_hunk_line(&mut self) -> std::io::Result<bool> { use DiffType::*; use State::*; // A true hunk line should start with one of: '+', '-', ' '. However, handle_hunk_line // handles all lines until the state transitions away from the hunk states. if !self.test_hunk_line() { return Ok(false); } // Don't let the line buffers become arbitrarily large -- if we // were to allow that, then for a large deleted/added file we // would process the entire file before painting anything. if self.painter.minus_lines.len() > self.config.line_buffer_size || self.painter.plus_lines.len() > self.config.line_buffer_size { self.painter.paint_buffered_minus_and_plus_lines(); } if let State::HunkHeader(_, parsed_hunk_header, line, raw_line) = &self.state.clone() { self.emit_hunk_header_line(parsed_hunk_header, line, raw_line)?; } self.state = match new_line_state(&self.line, &self.raw_line, &self.state, self.config) { Some(HunkMinus(diff_type, raw_line)) => { if let HunkPlus(_, _) = self.state { // We have just entered a new subhunk; process the previous one // and flush the line buffers. self.painter.paint_buffered_minus_and_plus_lines(); } let n_parents = diff_type.n_parents(); let line = prepare(&self.line, n_parents, self.config); let state = HunkMinus(diff_type, raw_line); self.painter.minus_lines.push((line, state.clone())); self.minus_line_counter.count_line(); state } Some(HunkPlus(diff_type, raw_line)) => { let n_parents = diff_type.n_parents(); let line = prepare(&self.line, n_parents, self.config); let state = HunkPlus(diff_type, raw_line); self.painter.plus_lines.push((line, state.clone())); state } Some(HunkZero(diff_type, raw_line)) => { // We are in a zero (unchanged) line, therefore we have just exited a subhunk (a // sequence of consecutive minus (removed) and/or plus (added) lines). Process that // subhunk and flush the line buffers. self.painter.paint_buffered_minus_and_plus_lines(); let n_parents = if is_word_diff() { 0 } else { diff_type.n_parents() }; let line = prepare(&self.line, n_parents, self.config); let state = State::HunkZero(diff_type, raw_line); self.painter.paint_zero_line(&line, state.clone()); self.minus_line_counter.count_line(); state } _ => { // The first character here could be e.g. '\' from '\ No newline at end of file'. This // is not a hunk line, but the parser does not have a more accurate state corresponding // to this. self.painter.paint_buffered_minus_and_plus_lines(); self.painter .output_buffer .push_str(&tabs::expand(&self.raw_line, &self.config.tab_cfg)); self.painter.output_buffer.push('\n'); State::HunkZero(Unified, None) } }; self.painter.emit()?; Ok(true) } } // Return Some(prepared_raw_line) if delta should emit this line raw. fn maybe_raw_line( raw_line: &str, state_style_is_raw: bool, n_parents: usize, non_raw_styles: &[style::Style], config: &Config, ) -> Option<String> { let emit_raw_line = is_word_diff() || config.inspect_raw_lines == cli::InspectRawLines::True && style::line_has_style_other_than(raw_line, non_raw_styles) || state_style_is_raw; if emit_raw_line { Some(prepare_raw_line(raw_line, n_parents, config)) } else { None } } // Return the new state corresponding to `new_line`, given the previous state. A return value of // None means that `new_line` is not recognized as a hunk line. fn new_line_state( new_line: &str, new_raw_line: &str, prev_state: &State, config: &Config, ) -> Option<State> { use DiffType::*; use MergeParents::*; use State::*; if is_word_diff() { return Some(HunkZero( Unified, maybe_raw_line(new_raw_line, config.zero_style.is_raw, 0, &[], config), )); } // 1. Given the previous line state, compute the new line diff type. These are basically the // same, except that a string prefix is converted into an integer number of parents (prefix // length). let diff_type = match prev_state { HunkMinus(Unified, _) | HunkZero(Unified, _) | HunkPlus(Unified, _) | HunkHeader(Unified, _, _, _) => Unified, HunkHeader(Combined(Number(n), InMergeConflict::No), _, _, _) => { Combined(Number(*n), InMergeConflict::No) } // The prefixes are specific to the previous line, but the number of merge parents remains // equal to the prefix length. HunkHeader(Combined(Prefix(prefix), InMergeConflict::No), _, _, _) => { Combined(Number(prefix.len()), InMergeConflict::No) } HunkMinus(Combined(Prefix(prefix), in_merge_conflict), _) | HunkZero(Combined(Prefix(prefix), in_merge_conflict), _) | HunkPlus(Combined(Prefix(prefix), in_merge_conflict), _) => { Combined(Number(prefix.len()), in_merge_conflict.clone()) } HunkMinus(Combined(Number(n), in_merge_conflict), _) | HunkZero(Combined(Number(n), in_merge_conflict), _) | HunkPlus(Combined(Number(n), in_merge_conflict), _) => { Combined(Number(*n), in_merge_conflict.clone()) } _ => delta_unreachable(&format!( "Unexpected state in new_line_state: {prev_state:?}", )), }; // 2. Given the new diff state, and the new line, compute the new prefix. let (prefix_char, prefix, in_merge_conflict) = match diff_type.clone() { Unified => (new_line.chars().next(), None, None), Combined(Number(n_parents), in_merge_conflict) => { let prefix = &new_line[..min(n_parents, new_line.len())]; let prefix_char = match prefix.chars().find(|c| c == &'-' || c == &'+') { Some(c) => Some(c), None => match prefix.chars().find(|c| c != &' ') { None => Some(' '), Some(_) => None, }, }; ( prefix_char, Some(prefix.to_string()), Some(in_merge_conflict), ) } _ => delta_unreachable(""), }; let maybe_minus_raw_line = || { maybe_raw_line( new_raw_line, config.minus_style.is_raw, diff_type.n_parents(), &[*style::GIT_DEFAULT_MINUS_STYLE, config.git_minus_style], config, ) }; let maybe_zero_raw_line = || { maybe_raw_line( new_raw_line, config.zero_style.is_raw, diff_type.n_parents(), &[], config, ) }; let maybe_plus_raw_line = || { maybe_raw_line( new_raw_line, config.plus_style.is_raw, diff_type.n_parents(), &[*style::GIT_DEFAULT_PLUS_STYLE, config.git_plus_style], config, ) }; // 3. Given the new prefix, compute the full new line state...except without its raw_line, which // is added later. TODO: that is not a sensible design. match (prefix_char, prefix, in_merge_conflict) { (Some('-'), None, None) => Some(HunkMinus(Unified, maybe_minus_raw_line())), (Some(' '), None, None) => Some(HunkZero(Unified, maybe_zero_raw_line())), (Some('+'), None, None) => Some(HunkPlus(Unified, maybe_plus_raw_line())), (Some('-'), Some(prefix), Some(in_merge_conflict)) => Some(HunkMinus( Combined(Prefix(prefix), in_merge_conflict), maybe_minus_raw_line(), )), (Some(' '), Some(prefix), Some(in_merge_conflict)) => Some(HunkZero( Combined(Prefix(prefix), in_merge_conflict), maybe_zero_raw_line(), )), (Some('+'), Some(prefix), Some(in_merge_conflict)) => Some(HunkPlus( Combined(Prefix(prefix), in_merge_conflict), maybe_plus_raw_line(), )), _ => None, } } #[cfg(test)] mod tests { use crate::tests::integration_test_utils::DeltaTest; mod word_diff { use super::*; #[test] fn test_word_diff() { DeltaTest::with_args(&[]) .with_calling_process("git diff --word-diff") .explain_ansi() .with_input(GIT_DIFF_WORD_DIFF) .expect_after_skip( 11, " #indent_mark (blue)───(blue)┐(normal) (blue)1(normal): (blue)│(normal) (blue)───(blue)┘(normal) (red)[-aaa-](green){+bbb+}(normal) ", ); } #[test] fn test_color_words() { DeltaTest::with_args(&[]) .with_calling_process("git diff --color-words") .explain_ansi() .with_input(GIT_DIFF_COLOR_WORDS) .expect_after_skip( 11, " #indent_mark (blue)───(blue)┐(normal) (blue)1(normal): (blue)│(normal) (blue)───(blue)┘(normal) (red)aaa(green)bbb(normal) ", ); } #[test] #[ignore] // FIXME fn test_color_words_map_styles() { DeltaTest::with_args(&[ "--map-styles", "red => bold yellow #dddddd, green => bold blue #dddddd", ]) .with_calling_process("git diff --color-words") .explain_ansi() .with_input(GIT_DIFF_COLOR_WORDS) .inspect() .expect_after_skip( 11, r##" #indent_mark (blue)───(blue)┐(normal) (blue)1(normal): (blue)│(normal) (blue)───(blue)┘(normal) (bold yellow "#dddddd")aaa(bold blue "#dddddd")bbb(normal) "##, ); } #[test] fn test_hunk_line_style_raw() { DeltaTest::with_args(&["--minus-style", "raw", "--plus-style", "raw"]) .explain_ansi() .with_input(GIT_DIFF_WITH_COLOR) .expect_after_skip( 14, " (red)aaa(normal) (green)bbb(normal) ", ); } #[test] fn test_hunk_line_style_raw_map_styles() { DeltaTest::with_args(&[ "--minus-style", "raw", "--plus-style", "raw", "--map-styles", "red => bold blue, green => dim yellow", ]) .explain_ansi() .with_input(GIT_DIFF_WITH_COLOR) .expect_after_skip( 14, " (bold blue)aaa(normal) (dim yellow)bbb(normal) ", ); } const GIT_DIFF_WITH_COLOR: &str = r#"\ commit 3ef7fba7258fe473f1d8befff367bb793c786107 Author: Dan Davison <dandavison7@gmail.com> Date: Mon Dec 13 22:54:43 2021 -0500 753 Test file diff --git a/file b/file index 72943a1..f761ec1 100644 --- a/file +++ b/file @@ -1 +1 @@ -aaa +bbb "#; const GIT_DIFF_COLOR_WORDS: &str = r#"\ commit 6feea4949c20583aaf16eee84f38d34d6a7f1741 Author: Dan Davison <dandavison7@gmail.com> Date: Sat Dec 11 17:08:56 2021 -0500 file v2 diff --git a/file b/file index c005da6..962086f 100644 --- a/file +++ b/file @@ -1 +1 @@ aaabbb "#; const GIT_DIFF_WORD_DIFF: &str = r#"\ commit 6feea4949c20583aaf16eee84f38d34d6a7f1741 Author: Dan Davison <dandavison7@gmail.com> Date: Sat Dec 11 17:08:56 2021 -0500 file v2 diff --git a/file b/file index c005da6..962086f 100644 --- a/file +++ b/file @@ -1 +1 @@ [-aaa-]{+bbb+} "#; } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/handlers/diff_stat.rs
src/handlers/diff_stat.rs
use lazy_static::lazy_static; use regex::Regex; use std::borrow::Cow; use crate::config::Config; use crate::delta::{State, StateMachine}; use crate::features; use crate::utils; impl StateMachine<'_> { #[inline] fn test_diff_stat_line(&self) -> bool { (self.state == State::CommitMeta || self.state == State::Unknown) && self.line.starts_with(' ') } pub fn handle_diff_stat_line(&mut self) -> std::io::Result<bool> { if !self.test_diff_stat_line() { return Ok(false); } let mut handled_line = false; if self.config.relative_paths { if let Some(cwd) = self.config.cwd_relative_to_repo_root.as_deref() { if let Some(replacement_line) = relativize_path_in_diff_stat_line(&self.raw_line, cwd, self.config) { self.painter.emit()?; writeln!(self.painter.writer, "{replacement_line}")?; handled_line = true } } } Ok(handled_line) } } // A regex to capture the path, and the content from the pipe onwards, in lines // like these: // " src/delta.rs | 14 ++++++++++----" // " src/config.rs | 2 ++" lazy_static! { static ref DIFF_STAT_LINE_REGEX: Regex = Regex::new(r" ([^\| ][^\|]+[^\| ]) +(\| +[0-9]+ .+)").unwrap(); } pub fn relativize_path_in_diff_stat_line( line: &str, cwd_relative_to_repo_root: &str, config: &Config, ) -> Option<String> { let caps = DIFF_STAT_LINE_REGEX.captures(line)?; let path_relative_to_repo_root = caps.get(1).unwrap().as_str(); let relative_path = pathdiff::diff_paths(path_relative_to_repo_root, cwd_relative_to_repo_root)?; let relative_path = relative_path.to_str()?; let formatted_path = match ( config.hyperlinks, utils::path::absolute_path(path_relative_to_repo_root, config), ) { (true, Some(absolute_path)) => features::hyperlinks::format_osc8_file_hyperlink( absolute_path, None, relative_path, config, ), _ => Cow::from(relative_path), }; let suffix = caps.get(2).unwrap().as_str(); let pad_width = config .diff_stat_align_width .saturating_sub(relative_path.len()); let padding = " ".repeat(pad_width); Some(format!(" {formatted_path}{padding}{suffix}")) } #[cfg(test)] mod tests { use super::*; #[test] fn test_diff_stat_line_regex_1() { let caps = DIFF_STAT_LINE_REGEX.captures(" src/delta.rs | 14 ++++++++++----"); assert!(caps.is_some()); let caps = caps.unwrap(); assert_eq!(caps.get(1).unwrap().as_str(), "src/delta.rs"); assert_eq!(caps.get(2).unwrap().as_str(), "| 14 ++++++++++----"); } #[test] fn test_diff_stat_line_regex_2() { let caps = DIFF_STAT_LINE_REGEX.captures(" src/config.rs | 2 ++"); assert!(caps.is_some()); let caps = caps.unwrap(); assert_eq!(caps.get(1).unwrap().as_str(), "src/config.rs"); assert_eq!(caps.get(2).unwrap().as_str(), "| 2 ++"); } #[test] fn test_relative_path() { for (path, cwd_relative_to_repo_root, expected) in &[ ("file.rs", "", "file.rs"), ("file.rs", "a/", "../file.rs"), ("a/file.rs", "a/", "file.rs"), ("a/b/file.rs", "a", "b/file.rs"), ("c/d/file.rs", "a/b/", "../../c/d/file.rs"), ] { assert_eq!( pathdiff::diff_paths(path, cwd_relative_to_repo_root), Some(expected.into()) ) } } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/handlers/diff_header_diff.rs
src/handlers/diff_header_diff.rs
use crate::delta::{DiffType, InMergeConflict, MergeParents, State, StateMachine}; use crate::handlers::diff_header::{get_repeated_file_path_from_diff_line, FileEvent}; impl StateMachine<'_> { #[inline] fn test_diff_header_diff_line(&self) -> bool { self.line.starts_with("diff ") } #[allow(clippy::unnecessary_wraps)] pub fn handle_diff_header_diff_line(&mut self) -> std::io::Result<bool> { if !self.test_diff_header_diff_line() { return Ok(false); } self.painter.paint_buffered_minus_and_plus_lines(); self.painter.emit()?; self.state = if self.line.starts_with("diff --cc ") || self.line.starts_with("diff --combined ") { // We will determine the number of parents when we see the hunk header. State::DiffHeader(DiffType::Combined( MergeParents::Unknown, InMergeConflict::No, )) } else { State::DiffHeader(DiffType::Unified) }; self.handle_pending_line_with_diff_name()?; self.handled_diff_header_header_line_file_pair = None; self.diff_line.clone_from(&self.line); // Pre-fill header fields from the diff line. For added, removed or renamed files // these are updated precisely on actual header minus and header plus lines. // But for modified binary files which are not added, removed or renamed, there // are no minus and plus lines. Without the code below, in such cases the file names // would remain unchanged from the previous diff, or empty for the very first diff. let name = get_repeated_file_path_from_diff_line(&self.line).unwrap_or_default(); self.minus_file.clone_from(&name); self.plus_file.clone_from(&name); self.minus_file_event = FileEvent::Change; self.plus_file_event = FileEvent::Change; self.current_file_pair = Some((self.minus_file.clone(), self.plus_file.clone())); if !self.should_skip_line() { self.emit_line_unchanged()?; } Ok(true) } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/handlers/mod.rs
src/handlers/mod.rs
/// This module contains functions handling input lines encountered during the /// main `StateMachine::consume()` loop. pub mod blame; pub mod commit_meta; pub mod diff_header; pub mod diff_header_diff; pub mod diff_header_misc; pub mod diff_stat; pub mod draw; pub mod git_show_file; pub mod grep; pub mod hunk; pub mod hunk_header; pub mod merge_conflict; mod ripgrep_json; pub mod submodule; use crate::delta::{State, StateMachine}; impl StateMachine<'_> { pub fn handle_additional_cases(&mut self, to_state: State) -> std::io::Result<bool> { let mut handled_line = false; // Additional cases: // // 1. When comparing directories with diff -u, if filenames match between the // directories, the files themselves will be compared. However, if an equivalent // filename is not present, diff outputs a single line (Only in...) starting // indicating that the file is present in only one of the directories. // // 2. Git diff emits lines describing submodule state such as "Submodule x/y/z contains // untracked content" // // 3. When comparing binary files, diff can emit "Binary files ... differ" line. // // See https://github.com/dandavison/delta/issues/60#issuecomment-557485242 for a // proposal for more robust parsing logic. self.painter.paint_buffered_minus_and_plus_lines(); self.state = to_state; if self.should_handle() { self.painter.emit()?; diff_header::write_generic_diff_header_header_line( &self.line, &self.raw_line, &mut self.painter, &mut self.mode_info, self.config, )?; handled_line = true; } Ok(handled_line) } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/handlers/hunk_header.rs
src/handlers/hunk_header.rs
// A module for constructing and writing the hunk header. // // The structure of the hunk header output by delta is // ``` // (file):(line-number): (code-fragment) // ``` // // The code fragment and line number derive from a line of git/diff output that looks like // ``` // @@ -119,12 +119,7 @@ fn write_to_output_buffer( // ``` // // Whether or not file and line-number are included is controlled by the presence of the special // style attributes 'file' and 'line-number' in the hunk-header-style string. For example, delta // might output the above hunk header as // ``` // ───────────────────────────────────────────────────┐ // src/hunk_header.rs:119: fn write_to_output_buffer( │ // ───────────────────────────────────────────────────┘ // ``` use std::convert::TryInto; use std::fmt::Write as FmtWrite; use super::draw; use crate::config::{ Config, HunkHeaderIncludeCodeFragment, HunkHeaderIncludeFilePath, HunkHeaderIncludeLineNumber, }; use crate::delta::{self, DiffType, InMergeConflict, MergeParents, State, StateMachine}; use crate::paint::{self, BgShouldFill, Painter, StyleSectionSpecifier}; use crate::style::{DecorationStyle, Style}; use lazy_static::lazy_static; use regex::Regex; #[derive(Clone, Default, Debug, PartialEq, Eq)] pub struct ParsedHunkHeader { code_fragment: String, line_numbers_and_hunk_lengths: Vec<(usize, usize)>, } pub enum HunkHeaderIncludeHunkLabel { Yes, No, } // The output of `diff -u file1 file2` does not contain a header before the // `--- old.lua` / `+++ new.lua` block, and the hunk can of course contain lines // starting with '-- '. To avoid interpreting '--- lua comment' as a new header, // count the minus lines in a hunk (provided by the '@@ -1,4 +1,3 @@' header). // `diff` itself can not generate two diffs in this ambiguous format, so a second header // could just be ignored. But concatenated diffs exist and are accepted by `patch`. #[derive(Debug)] pub struct AmbiguousDiffMinusCounter(isize); impl AmbiguousDiffMinusCounter { // The internal isize representation avoids calling `if let Some(..)` on every line. For // nearly all input the counter is not needed, in this case it is decremented but ignored. // [min, COUNTER_RELEVANT_IF_GT] unambiguous diff // (COUNTER_RELEVANT_IF_GT, 0] handle next '--- ' like a header, and set counter in next @@ block // [1, max] counting minus lines in ambiguous header const COUNTER_RELEVANT_IF_GREATER_THAN: isize = -4096; // -1 works too, but be defensive const EXPECT_DIFF_3DASH_HEADER: isize = 0; pub fn not_needed() -> Self { Self(Self::COUNTER_RELEVANT_IF_GREATER_THAN) } pub fn prepare_to_count() -> Self { Self(Self::EXPECT_DIFF_3DASH_HEADER) } pub fn three_dashes_expected(&self) -> bool { if self.0 > Self::COUNTER_RELEVANT_IF_GREATER_THAN { self.0 <= Self::EXPECT_DIFF_3DASH_HEADER } else { true } } pub fn count_line(&mut self) { self.0 -= 1; } fn count_from(lines: usize) -> Self { Self( lines .try_into() .unwrap_or(Self::COUNTER_RELEVANT_IF_GREATER_THAN), ) } #[allow(clippy::needless_bool)] fn must_count(&mut self) -> bool { let relevant = self.0 > Self::COUNTER_RELEVANT_IF_GREATER_THAN; if relevant { true } else { #[cfg(target_pointer_width = "32")] { self.0 = Self::COUNTER_RELEVANT_IF_GREATER_THAN; } false } } } impl StateMachine<'_> { #[inline] fn test_hunk_header_line(&self) -> bool { self.line.starts_with("@@") && // A hunk header can occur within a merge conflict region, but we don't attempt to handle // that. See #822. !matches!(self.state, State::MergeConflict(_, _)) } pub fn handle_hunk_header_line(&mut self) -> std::io::Result<bool> { use DiffType::*; use State::*; if !self.test_hunk_header_line() { return Ok(false); } let mut handled_line = false; if let Some(parsed_hunk_header) = parse_hunk_header(&self.line) { let diff_type = match &self.state { DiffHeader(Combined(MergeParents::Unknown, InMergeConflict::No)) => { // https://git-scm.com/docs/git-diff#_combined_diff_format let n_parents = self.line.chars().take_while(|c| c == &'@').count() - 1; Combined(MergeParents::Number(n_parents), InMergeConflict::No) } DiffHeader(diff_type) | HunkMinus(diff_type, _) | HunkZero(diff_type, _) | HunkPlus(diff_type, _) => diff_type.clone(), _ => Unified, }; if self.minus_line_counter.must_count() { if let &[(_, minus_lines), (_, _plus_lines), ..] = parsed_hunk_header.line_numbers_and_hunk_lengths.as_slice() { self.minus_line_counter = AmbiguousDiffMinusCounter::count_from(minus_lines); } } self.state = HunkHeader( diff_type, parsed_hunk_header, self.line.clone(), self.raw_line.clone(), ); handled_line = true; } Ok(handled_line) } /// Emit the hunk header, with any requested decoration. pub fn emit_hunk_header_line( &mut self, parsed_hunk_header: &ParsedHunkHeader, line: &str, raw_line: &str, ) -> std::io::Result<bool> { self.painter.paint_buffered_minus_and_plus_lines(); self.painter.set_highlighter(); self.painter.emit()?; let ParsedHunkHeader { code_fragment, line_numbers_and_hunk_lengths, } = parsed_hunk_header; if self.config.line_numbers { self.painter .line_numbers_data .as_mut() .unwrap() .initialize_hunk(line_numbers_and_hunk_lengths, self.plus_file.to_string()); } if self.config.hunk_header_style.is_raw { write_hunk_header_raw(&mut self.painter, line, raw_line, self.config)?; } else if self.config.hunk_header_style.is_omitted { writeln!(self.painter.writer)?; } else { // Add a blank line below the hunk-header-line for readability, unless // color_only mode is active. if !self.config.color_only { writeln!(self.painter.writer)?; } write_line_of_code_with_optional_path_and_line_number( code_fragment, line_numbers_and_hunk_lengths, None, &mut self.painter, line, if self.plus_file == "/dev/null" { &self.minus_file } else { &self.plus_file }, self.config.hunk_header_style.decoration_style, &self.config.hunk_header_file_style, &self.config.hunk_header_line_number_style, &self.config.hunk_header_style_include_file_path, &self.config.hunk_header_style_include_line_number, &HunkHeaderIncludeHunkLabel::Yes, &self.config.hunk_header_style_include_code_fragment, ":", self.config, )?; }; self.painter.set_highlighter(); Ok(true) } } lazy_static! { static ref HUNK_HEADER_REGEX: Regex = Regex::new(r"@+ ([^@]+)@+(.*\s?)").unwrap(); } // Parse unified diff hunk header format. See // https://www.gnu.org/software/diffutils/manual/html_node/Detailed-Unified.html // https://www.artima.com/weblogs/viewpost.jsp?thread=164293 lazy_static! { static ref HUNK_HEADER_FILE_COORDINATE_REGEX: Regex = Regex::new( r"(?x) [-+] (\d+) # 1. Hunk start line number (?: # Start optional hunk length section (non-capturing) , # Literal comma (\d+) # 2. Optional hunk length (defaults to 1) )?" ) .unwrap(); } /// Given input like /// "@@ -74,15 +74,14 @@ pub fn delta(" /// Return " pub fn delta(" and a vector of (line_number, hunk_length) tuples. fn parse_hunk_header(line: &str) -> Option<ParsedHunkHeader> { if let Some(caps) = HUNK_HEADER_REGEX.captures(line) { let file_coordinates = &caps[1]; let line_numbers_and_hunk_lengths: Vec<(usize, usize)> = HUNK_HEADER_FILE_COORDINATE_REGEX .captures_iter(file_coordinates) .map(|caps| { ( caps[1].parse::<usize>().unwrap(), caps.get(2) .map(|m| m.as_str()) // Per the specs linked above, if the hunk length is absent then it is 1. .unwrap_or("1") .parse::<usize>() .unwrap(), ) }) .collect(); if line_numbers_and_hunk_lengths.is_empty() { None } else { let code_fragment = caps[2].to_string(); Some(ParsedHunkHeader { code_fragment, line_numbers_and_hunk_lengths, }) } } else { None } } fn write_hunk_header_raw( painter: &mut Painter, line: &str, raw_line: &str, config: &Config, ) -> std::io::Result<()> { let (mut draw_fn, pad, decoration_ansi_term_style) = draw::get_draw_function(config.hunk_header_style.decoration_style); if config.hunk_header_style.decoration_style != DecorationStyle::NoDecoration { writeln!(painter.writer)?; } draw_fn( painter.writer, &format!("{}{}", line, if pad { " " } else { "" }), &format!("{}{}", raw_line, if pad { " " } else { "" }), "", &config.decorations_width, config.hunk_header_style, decoration_ansi_term_style, )?; Ok(()) } #[allow(clippy::too_many_arguments)] pub fn write_line_of_code_with_optional_path_and_line_number( code_fragment: &str, line_numbers_and_hunk_lengths: &[(usize, usize)], style_sections: Option<StyleSectionSpecifier>, painter: &mut Painter, line: &str, plus_file: &str, decoration_style: DecorationStyle, file_style: &Style, line_number_style: &Style, include_file_path: &HunkHeaderIncludeFilePath, include_line_number: &HunkHeaderIncludeLineNumber, include_hunk_label: &HunkHeaderIncludeHunkLabel, include_code_fragment: &HunkHeaderIncludeCodeFragment, file_path_separator: &str, config: &Config, ) -> std::io::Result<()> { let (mut draw_fn, _, decoration_ansi_term_style) = draw::get_draw_function(decoration_style); let line = match (config.color_only, include_code_fragment) { (true, _) => line.to_string(), // When called from a ripgrep json context: No " " added, as this would prevent // identifying that a newline already exists, and so another would be added. (_, HunkHeaderIncludeCodeFragment::YesNoSpace) => code_fragment.to_string(), (_, HunkHeaderIncludeCodeFragment::Yes) if !code_fragment.is_empty() => { format!("{code_fragment} ") } _ => "".to_string(), }; let plus_line_number = line_numbers_and_hunk_lengths[line_numbers_and_hunk_lengths.len() - 1].0; let file_with_line_number = paint_file_path_with_line_number( Some(plus_line_number), plus_file, file_style, line_number_style, include_file_path, include_line_number, file_path_separator, config, ); if !line.is_empty() || !file_with_line_number.is_empty() { write_to_output_buffer( &file_with_line_number, file_path_separator, line, style_sections, include_hunk_label, painter, config, ); draw_fn( painter.writer, &painter.output_buffer, &painter.output_buffer, "", &config.decorations_width, config.null_style, decoration_ansi_term_style, )?; painter.output_buffer.clear(); } Ok(()) } #[allow(clippy::too_many_arguments)] fn paint_file_path_with_line_number( line_number: Option<usize>, plus_file: &str, file_style: &Style, line_number_style: &Style, include_file_path: &HunkHeaderIncludeFilePath, include_line_number: &HunkHeaderIncludeLineNumber, separator: &str, config: &Config, ) -> String { let file_style = match include_file_path { HunkHeaderIncludeFilePath::Yes => Some(*file_style), HunkHeaderIncludeFilePath::No => None, }; let line_number_style = if matches!(include_line_number, HunkHeaderIncludeLineNumber::Yes) && line_number.is_some() && !config.hunk_header_style.is_raw && !config.color_only { Some(*line_number_style) } else { None }; paint::paint_file_path_with_line_number( line_number, plus_file, false, separator, false, file_style, line_number_style, config, ) } fn write_to_output_buffer( file_with_line_number: &str, file_path_separator: &str, line: String, style_sections: Option<StyleSectionSpecifier>, include_hunk_label: &HunkHeaderIncludeHunkLabel, painter: &mut Painter, config: &Config, ) { if matches!(include_hunk_label, HunkHeaderIncludeHunkLabel::Yes) && !config.hunk_label.is_empty() { let _ = write!( &mut painter.output_buffer, "{} ", config.hunk_header_file_style.paint(&config.hunk_label) ); } if !file_with_line_number.is_empty() { // The code fragment in "line" adds whitespace, but if only a line number is printed // then the trailing space must be added. let space = if line.is_empty() { " " } else { "" }; let _ = write!( &mut painter.output_buffer, "{file_with_line_number}{file_path_separator}{space}", ); } if !line.is_empty() { painter.syntax_highlight_and_paint_line( &line, style_sections.unwrap_or(StyleSectionSpecifier::Style(config.hunk_header_style)), delta::State::HunkHeader( DiffType::Unified, ParsedHunkHeader::default(), "".to_owned(), "".to_owned(), ), BgShouldFill::No, ); painter.output_buffer.pop(); // trim newline } } #[cfg(test)] pub mod tests { use super::*; use crate::ansi::strip_ansi_codes; use crate::tests::integration_test_utils; #[test] fn test_parse_hunk_header() { let ParsedHunkHeader { code_fragment, line_numbers_and_hunk_lengths, } = parse_hunk_header("@@ -74,15 +75,14 @@ pub fn delta(\n").unwrap(); assert_eq!(code_fragment, " pub fn delta(\n"); assert_eq!(line_numbers_and_hunk_lengths[0], (74, 15),); assert_eq!(line_numbers_and_hunk_lengths[1], (75, 14),); } #[test] fn test_parse_hunk_header_with_omitted_hunk_lengths() { let ParsedHunkHeader { code_fragment, line_numbers_and_hunk_lengths, } = parse_hunk_header("@@ -74 +75,2 @@ pub fn delta(\n").unwrap(); assert_eq!(code_fragment, " pub fn delta(\n"); assert_eq!(line_numbers_and_hunk_lengths[0], (74, 1),); assert_eq!(line_numbers_and_hunk_lengths[1], (75, 2),); } #[test] fn test_parse_hunk_header_with_no_hunk_lengths() { let result = parse_hunk_header("@@ @@\n"); assert_eq!(result, None); } #[test] fn test_parse_hunk_header_added_file() { let ParsedHunkHeader { code_fragment, line_numbers_and_hunk_lengths, } = parse_hunk_header("@@ -1,22 +0,0 @@").unwrap(); assert_eq!(code_fragment, "",); assert_eq!(line_numbers_and_hunk_lengths[0], (1, 22),); assert_eq!(line_numbers_and_hunk_lengths[1], (0, 0),); } #[test] fn test_parse_hunk_header_deleted_file() { let ParsedHunkHeader { code_fragment, line_numbers_and_hunk_lengths, } = parse_hunk_header("@@ -0,0 +1,3 @@").unwrap(); assert_eq!(code_fragment, "",); assert_eq!(line_numbers_and_hunk_lengths[0], (0, 0),); assert_eq!(line_numbers_and_hunk_lengths[1], (1, 3),); } #[test] fn test_parse_hunk_header_merge() { let ParsedHunkHeader { code_fragment, line_numbers_and_hunk_lengths, } = parse_hunk_header("@@@ -293,11 -358,15 +358,16 @@@ dependencies =").unwrap(); assert_eq!(code_fragment, " dependencies ="); assert_eq!(line_numbers_and_hunk_lengths[0], (293, 11),); assert_eq!(line_numbers_and_hunk_lengths[1], (358, 15),); assert_eq!(line_numbers_and_hunk_lengths[2], (358, 16),); } #[test] fn test_parse_hunk_header_cthulhu() { let ParsedHunkHeader { code_fragment, line_numbers_and_hunk_lengths, } = parse_hunk_header("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -444,17 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 -446,6 +444,17 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ int snd_soc_jack_add_gpios(struct snd_s").unwrap(); assert_eq!(code_fragment, " int snd_soc_jack_add_gpios(struct snd_s"); assert_eq!(line_numbers_and_hunk_lengths[0], (446, 6),); assert_eq!(line_numbers_and_hunk_lengths[1], (446, 6),); assert_eq!(line_numbers_and_hunk_lengths[2], (446, 6),); assert_eq!(line_numbers_and_hunk_lengths[65], (446, 6),); } #[test] fn test_paint_file_path_with_line_number_default() { // hunk-header-style (by default) includes 'line-number' but not 'file'. // This test confirms that `paint_file_path_with_line_number` returns a painted line number. let config = integration_test_utils::make_config_from_args(&[]); let result = paint_file_path_with_line_number( Some(3), "some-file", &config.hunk_header_style, &config.hunk_header_line_number_style, &config.hunk_header_style_include_file_path, &config.hunk_header_style_include_line_number, ":", &config, ); assert_eq!(result, "\u{1b}[34m3\u{1b}[0m"); } #[test] fn test_paint_file_path_with_line_number_hyperlinks() { use std::{iter::FromIterator, path::PathBuf}; use crate::utils; // hunk-header-style (by default) includes 'line-number' but not 'file'. // Normally, `paint_file_path_with_line_number` would return a painted line number. // But in this test hyperlinks are activated, and the test ensures that delta.__workdir__ is // present in git_config_entries. // This test confirms that, under those circumstances, `paint_file_path_with_line_number` // returns a hyperlinked file path with line number. let config = integration_test_utils::make_config_from_args(&["--features", "hyperlinks"]); let relative_path = PathBuf::from_iter(["some-dir", "some-file"]); let result = paint_file_path_with_line_number( Some(3), &relative_path.to_string_lossy(), &config.hunk_header_style, &config.hunk_header_line_number_style, &config.hunk_header_style_include_file_path, &config.hunk_header_style_include_line_number, ":", &config, ); assert_eq!( result, format!( "\u{1b}]8;;file://{}\u{1b}\\\u{1b}[34m3\u{1b}[0m\u{1b}]8;;\u{1b}\\", utils::path::fake_delta_cwd_for_tests() .join(relative_path) .to_string_lossy() ) ); } #[test] fn test_paint_file_path_with_line_number_empty() { // hunk-header-style includes neither 'file' nor 'line-number'. // This causes `paint_file_path_with_line_number` to return empty string. let config = integration_test_utils::make_config_from_args(&[ "--hunk-header-style", "syntax bold", "--hunk-header-decoration-style", "omit", ]); let result = paint_file_path_with_line_number( Some(3), "some-file", &config.hunk_header_style, &config.hunk_header_line_number_style, &config.hunk_header_style_include_file_path, &config.hunk_header_style_include_line_number, ":", &config, ); // result is // "\u{1b}[1msome-file\u{1b}[0m:\u{1b}[34m3\u{1b}[0m" assert_eq!(result, ""); } #[test] fn test_paint_file_path_with_line_number_empty_hyperlinks() { // hunk-header-style includes neither 'file' nor 'line-number'. // This causes `paint_file_path_with_line_number` to return empty string. // This test confirms that this remains true even when we are requesting hyperlinks. let config = integration_test_utils::make_config_from_args(&[ "--hunk-header-style", "syntax bold", "--hunk-header-decoration-style", "omit", "--features", "hyperlinks", ]); let result = paint_file_path_with_line_number( Some(3), "some-file", &config.hunk_header_style, &config.hunk_header_line_number_style, &config.hunk_header_style_include_file_path, &config.hunk_header_style_include_line_number, ":", &config, ); assert_eq!(result, ""); } #[test] fn test_paint_file_path_with_line_number_empty_navigate() { let config = integration_test_utils::make_config_from_args(&[ "--hunk-header-style", "syntax bold", "--hunk-header-decoration-style", "omit", "--navigate", ]); let result = paint_file_path_with_line_number( Some(3), "δ some-file", &config.hunk_header_style, &config.hunk_header_line_number_style, &config.hunk_header_style_include_file_path, &config.hunk_header_style_include_line_number, ":", &config, ); // result is // "\u{1b}[1mδ some-file\u{1b}[0m:\u{1b}[34m3\u{1b}[0m" assert_eq!(result, ""); } #[test] fn test_not_a_hunk_header_is_handled_gracefully() { let config = integration_test_utils::make_config_from_args(&[]); let output = integration_test_utils::run_delta(GIT_LOG_OUTPUT_WITH_NOT_A_HUNK_HEADER, &config); let output = strip_ansi_codes(&output); assert!(output.contains("@@@2021-12-05")); } const GIT_LOG_OUTPUT_WITH_NOT_A_HUNK_HEADER: &str = "\ @@@2021-12-05 src/config.rs | 2 +- src/delta.rs | 3 ++- src/handlers/hunk.rs | 12 ++++++------ src/handlers/hunk_header.rs | 119 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------------------------ src/handlers/merge_conflict.rs | 2 +- src/handlers/submodule.rs | 4 ++-- src/paint.rs | 2 +- 7 files changed, 90 insertions(+), 54 deletions(-) "; }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/handlers/diff_header_misc.rs
src/handlers/diff_header_misc.rs
use crate::delta::{DiffType, Source, State, StateMachine}; use crate::utils::path::relativize_path_maybe; impl StateMachine<'_> { #[inline] fn test_diff_file_missing(&self) -> bool { self.source == Source::DiffUnified && self.line.starts_with("Only in ") } #[inline] fn test_diff_is_binary(&self) -> bool { self.line.starts_with("Binary files ") } pub fn handle_diff_header_misc_line(&mut self) -> std::io::Result<bool> { if !self.test_diff_file_missing() && !self.test_diff_is_binary() { return Ok(false); } // Preserve the "Binary files" line when diff lines should be kept unchanged. if !self.config.color_only && self.test_diff_is_binary() { // Print the "Binary files" line verbatim, if there was no "diff" line, or it // listed different files but was not followed by header minus and plus lines. // This can happen in output of standalone diff or git diff --no-index. if self.minus_file.is_empty() && self.plus_file.is_empty() { self.emit_line_unchanged()?; self.handled_diff_header_header_line_file_pair .clone_from(&self.current_file_pair); return Ok(true); } if self.minus_file != "/dev/null" { relativize_path_maybe(&mut self.minus_file, self.config); self.minus_file.push_str(" (binary file)"); } if self.plus_file != "/dev/null" { relativize_path_maybe(&mut self.plus_file, self.config); self.plus_file.push_str(" (binary file)"); } return Ok(true); } self.handle_additional_cases(match self.state { State::DiffHeader(_) => self.state.clone(), _ => State::DiffHeader(DiffType::Unified), }) } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/handlers/grep.rs
src/handlers/grep.rs
use std::borrow::Cow; use lazy_static::lazy_static; use regex::Regex; use serde::Deserialize; use crate::ansi; use crate::config::{ delta_unreachable, GrepType, HunkHeaderIncludeCodeFragment, HunkHeaderIncludeFilePath, HunkHeaderIncludeLineNumber, }; use crate::delta::{State, StateMachine}; use crate::handlers::{self, ripgrep_json}; use crate::paint::{self, BgShouldFill, StyleSectionSpecifier}; use crate::style::Style; use crate::utils::{process, tabs}; use super::hunk_header::HunkHeaderIncludeHunkLabel; #[derive(Debug, PartialEq, Eq)] pub struct GrepLine<'b> { pub grep_type: GrepType, pub path: Cow<'b, str>, pub line_number: Option<usize>, pub line_type: LineType, pub code: Cow<'b, str>, pub submatches: Option<Vec<(usize, usize)>>, } impl GrepLine<'_> { fn expand_tabs(&mut self, tab_cfg: &tabs::TabCfg) { let old_len = self.code.len(); self.code = tabs::expand(&self.code, tab_cfg).into(); let shift = self.code.len().saturating_sub(old_len); // HACK: it is not necessarily the case that all submatch coordinates // should be shifted in this way. It should be true in a common case of: // (a) the only tabs were at the beginning of the line, and (b) the user // was not searching for tabs. self.submatches = self.submatches.as_ref().map(|submatches| { submatches .iter() .map(|(a, b)| (a + shift, b + shift)) .collect() }); } } #[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)] #[serde(rename_all = "lowercase")] pub enum LineType { ContextHeader, Context, FileHeader, Match, Ignore, } struct GrepOutputConfig { add_navigate_marker_to_matches: bool, render_context_header_as_hunk_header: bool, pad_line_number: bool, } lazy_static! { static ref OUTPUT_CONFIG: GrepOutputConfig = make_output_config(); } impl LineType { fn file_path_separator(&self) -> &str { // grep, rg, and git grep use ":" for matching lines // and "-" for non-matching lines (and `git grep -W` // uses "=" for a context header line). match self { LineType::Match => ":", LineType::Context => "-", LineType::ContextHeader => "=", LineType::Ignore | LineType::FileHeader => "", } } } impl StateMachine<'_> { // If this is a line of grep output then render it accordingly. pub fn handle_grep_line(&mut self) -> std::io::Result<bool> { self.painter.emit()?; let (previous_path, previous_line_type, previous_line, try_parse) = match &self.state { State::Grep(_, line_type, path, line_number) => { (Some(path.clone()), Some(line_type), line_number, true) } State::Unknown => (None, None, &None, true), _ => (None, None, &None, false), }; if !try_parse { return Ok(false); } // Try parse_raw_grep_line on raw_line, and fall back to parse_grep_line let raw_line = self.raw_line.clone(); // TODO: avoid clone let line; let grep_line = if let Some(grep_line) = parse_raw_grep_line(&raw_line) { grep_line } else { line = self.line.clone(); // TODO: avoid clone if let Some(grep_line) = parse_grep_line(&line) { grep_line } else { return Ok(false); } }; if matches!(grep_line.line_type, LineType::Ignore) { return Ok(true); } let first_path = previous_path.is_none(); let new_path = first_path || previous_path.as_deref() != Some(&grep_line.path); let line_number_jump = previous_line < &grep_line.line_number.as_ref().map(|n| n - 1); // Emit a '--' section separator when output contains context lines (i.e. *grep option -A, -B, -C is in effect). let new_section = !new_path && (previous_line_type == Some(&LineType::Context) || grep_line.line_type == LineType::Context) && line_number_jump; if new_path { self.painter.set_syntax(Some(grep_line.path.as_ref())); } if new_path || new_section { self.painter.set_highlighter() } self.state = State::Grep( self.config .grep_output_type .clone() .unwrap_or_else(|| grep_line.grep_type.clone()), grep_line.line_type, grep_line.path.to_string(), grep_line.line_number, ); match &self.state { State::Grep(GrepType::Ripgrep, _, _, _) => { self.emit_ripgrep_format_grep_line(grep_line, new_path, first_path, new_section) } State::Grep(GrepType::Classic, _, _, _) => { self.emit_classic_format_grep_line(grep_line) } _ => delta_unreachable("Impossible state while handling grep line."), }?; Ok(true) } // Emulate ripgrep output: each section of hits from the same path has a header line, // and sections are separated by a blank line. Set language whenever path changes. fn emit_ripgrep_format_grep_line( &mut self, mut grep_line: GrepLine, new_path: bool, first_path: bool, new_section: bool, ) -> std::io::Result<()> { if new_path { // Emit new path header line if !first_path { writeln!(self.painter.writer)?; } handlers::hunk_header::write_line_of_code_with_optional_path_and_line_number( "", &[(0, 0)], None, &mut self.painter, &self.line, &grep_line.path, self.config.ripgrep_header_style.decoration_style, &self.config.grep_file_style, &self.config.grep_line_number_style, &HunkHeaderIncludeFilePath::Yes, &HunkHeaderIncludeLineNumber::No, &HunkHeaderIncludeHunkLabel::Yes, &HunkHeaderIncludeCodeFragment::YesNoSpace, "", self.config, )? } if new_section { writeln!(self.painter.writer, "--")?; } // Emit the actual grep hit line let code_style_sections = match (&grep_line.line_type, &grep_line.submatches) { (LineType::Match, Some(_)) => { // We expand tabs at this late stage because // the tabs are escaped in the JSON, so // expansion must come after JSON parsing. // (At the time of writing, we are in this // arm iff we are handling `ripgrep --json` // output.) grep_line.expand_tabs(&self.config.tab_cfg); make_style_sections( &grep_line.code, &grep_line.submatches.unwrap(), self.config.grep_match_word_style, self.config.grep_match_line_style, ) } (LineType::Match, None) => { // HACK: We need tabs expanded, and we need // the &str passed to // `get_code_style_sections` to live long // enough. But at this point it is guaranteed // that this handler is going to handle this // line, so mutating it is acceptable. self.raw_line = tabs::expand(&self.raw_line, &self.config.tab_cfg); get_code_style_sections( &self.raw_line, self.config.grep_match_word_style, self.config.grep_match_line_style, &grep_line.path, grep_line.line_number, ) .unwrap_or(StyleSectionSpecifier::Style( self.config.grep_match_line_style, )) } _ => StyleSectionSpecifier::Style(self.config.grep_context_line_style), }; handlers::hunk_header::write_line_of_code_with_optional_path_and_line_number( &grep_line.code, &[(grep_line.line_number.unwrap_or(0), 0)], Some(code_style_sections), &mut self.painter, &self.line, &grep_line.path, crate::style::DecorationStyle::NoDecoration, &self.config.grep_file_style, &self.config.grep_line_number_style, &HunkHeaderIncludeFilePath::No, if grep_line.line_number.is_some() { &HunkHeaderIncludeLineNumber::Yes } else { &HunkHeaderIncludeLineNumber::No }, &HunkHeaderIncludeHunkLabel::No, &HunkHeaderIncludeCodeFragment::YesNoSpace, grep_line.line_type.file_path_separator(), self.config, ) } fn emit_classic_format_grep_line(&mut self, grep_line: GrepLine) -> std::io::Result<()> { match ( &grep_line.line_type, OUTPUT_CONFIG.render_context_header_as_hunk_header, ) { // Emit context header line (`git grep -W`) (LineType::ContextHeader, true) => { handlers::hunk_header::write_line_of_code_with_optional_path_and_line_number( &grep_line.code, &[(grep_line.line_number.unwrap_or(0), 0)], None, &mut self.painter, &self.line, &grep_line.path, self.config.classic_grep_header_style.decoration_style, &self.config.classic_grep_header_file_style, &self.config.grep_line_number_style, &self.config.hunk_header_style_include_file_path, &self.config.hunk_header_style_include_line_number, &HunkHeaderIncludeHunkLabel::Yes, &HunkHeaderIncludeCodeFragment::Yes, grep_line.line_type.file_path_separator(), self.config, )? } _ => { if self.config.navigate { write!( self.painter.writer, "{}", match ( &grep_line.line_type, OUTPUT_CONFIG.add_navigate_marker_to_matches ) { (LineType::Match, true) => "• ", (_, true) => " ", _ => "", } )? } self._emit_classic_format_file_and_line_number(&grep_line)?; self._emit_classic_format_code(grep_line)?; } } Ok(()) } fn _emit_classic_format_file_and_line_number( &mut self, grep_line: &GrepLine, ) -> std::io::Result<()> { let separator = if self.config.grep_separator_symbol == "keep" { grep_line.line_type.file_path_separator() } else { // But ":" results in a "file/path:number:" // construct that terminal emulators are more likely // to recognize and render as a clickable link. If // navigate is enabled then there is already a good // visual indicator of match lines (in addition to // the grep-match-style highlighting) and so we use // ":" for matches and non-matches alike. &self.config.grep_separator_symbol }; write!( self.painter.writer, "{}", paint::paint_file_path_with_line_number( grep_line.line_number, &grep_line.path, OUTPUT_CONFIG.pad_line_number, separator, true, Some(self.config.grep_file_style), Some(self.config.grep_line_number_style), self.config ) )?; Ok(()) } fn _emit_classic_format_code(&mut self, mut grep_line: GrepLine) -> std::io::Result<()> { let code_style_sections = match (&grep_line.line_type, &grep_line.submatches) { (LineType::Match, Some(_)) => { // We expand tabs at this late stage because // the tabs are escaped in the JSON, so // expansion must come after JSON parsing. // (At the time of writing, we are in this // arm iff we are handling `ripgrep --json` // output.) grep_line.expand_tabs(&self.config.tab_cfg); make_style_sections( &grep_line.code, &grep_line.submatches.unwrap(), self.config.grep_match_word_style, self.config.grep_match_line_style, ) } (LineType::Match, None) => { // HACK: We need tabs expanded, and we need // the &str passed to // `get_code_style_sections` to live long // enough. But at the point it is guaranteed // that this handler is going to handle this // line, so mutating it is acceptable. self.raw_line = tabs::expand(&self.raw_line, &self.config.tab_cfg); get_code_style_sections( &self.raw_line, self.config.grep_match_word_style, self.config.grep_match_line_style, &grep_line.path, grep_line.line_number, ) .unwrap_or(StyleSectionSpecifier::Style( self.config.grep_match_line_style, )) } _ => StyleSectionSpecifier::Style(self.config.grep_context_line_style), }; self.painter.syntax_highlight_and_paint_line( &format!("{}\n", grep_line.code), code_style_sections, self.state.clone(), BgShouldFill::default(), ); Ok(()) } } fn make_style_sections<'a>( line: &'a str, submatches: &[(usize, usize)], match_style: Style, non_match_style: Style, ) -> StyleSectionSpecifier<'a> { let mut sections = Vec::new(); let mut curr = 0; for (start_, end_) in submatches { let (start, end) = (*start_, *end_); if start > curr { sections.push((non_match_style, &line[curr..start])) }; sections.push((match_style, &line[start..end])); curr = end; } if curr < line.len() { sections.push((non_match_style, &line[curr..])) } StyleSectionSpecifier::StyleSections(sections) } // Return style sections describing colors received from git. fn get_code_style_sections<'b>( raw_line: &'b str, match_style: Style, non_match_style: Style, path: &str, line_number: Option<usize>, ) -> Option<StyleSectionSpecifier<'b>> { if let Some(prefix_end) = ansi::ansi_preserving_index( raw_line, match line_number { Some(n) => format!("{path}:{n}:").len() - 1, None => path.len(), }, ) { let match_style_sections = ansi::parse_style_sections(&raw_line[(prefix_end + 1)..]) .iter() .map(|(ansi_term_style, s)| { if ansi_term_style.is_bold && ansi_term_style.foreground == Some(ansi_term::Colour::Red) { (match_style, *s) } else { (non_match_style, *s) } }) .collect(); Some(StyleSectionSpecifier::StyleSections(match_style_sections)) } else { None } } fn make_output_config() -> GrepOutputConfig { match &*process::calling_process() { process::CallingProcess::GitGrep(command_line) if command_line.short_options.contains("-W") || command_line.long_options.contains("--function-context") => { // --function-context is in effect: i.e. the entire function is // being displayed. In that case we don't render the first line as a // header, since the second line is the true next line, and it will // be more readable to have these displayed normally. We do add the // navigate marker, since match lines will be surrounded by (many) // non-match lines. And, since we are printing (many) successive lines // of code, we pad line numbers <100 in order to maintain code // alignment up to line 9999. GrepOutputConfig { render_context_header_as_hunk_header: false, add_navigate_marker_to_matches: true, pad_line_number: true, } } process::CallingProcess::GitGrep(command_line) if command_line.short_options.contains("-p") || command_line.long_options.contains("--show-function") => { // --show-function is in effect, i.e. the function header is being // displayed, along with matches within the function. Therefore we // render the first line as a header, but we do not add the navigate // marker, since all non-header lines are matches. GrepOutputConfig { render_context_header_as_hunk_header: true, add_navigate_marker_to_matches: false, pad_line_number: true, } } _ => GrepOutputConfig { render_context_header_as_hunk_header: true, add_navigate_marker_to_matches: false, pad_line_number: true, }, } } enum GrepLineRegex { WithColor, WithFileExtensionAndLineNumber, WithFileExtension, WithFileExtensionNoSpaces, WithoutSeparatorCharacters, } lazy_static! { static ref GREP_LINE_REGEX_ASSUMING_COLOR: Regex = make_grep_line_regex(GrepLineRegex::WithColor); } lazy_static! { static ref GREP_LINE_REGEX_ASSUMING_FILE_EXTENSION_AND_LINE_NUMBER: Regex = make_grep_line_regex(GrepLineRegex::WithFileExtensionAndLineNumber); } lazy_static! { static ref GREP_LINE_REGEX_ASSUMING_FILE_EXTENSION_NO_SPACES: Regex = make_grep_line_regex(GrepLineRegex::WithFileExtensionNoSpaces); } lazy_static! { static ref GREP_LINE_REGEX_ASSUMING_FILE_EXTENSION: Regex = make_grep_line_regex(GrepLineRegex::WithFileExtension); } lazy_static! { static ref GREP_LINE_REGEX_ASSUMING_NO_INTERNAL_SEPARATOR_CHARS: Regex = make_grep_line_regex(GrepLineRegex::WithoutSeparatorCharacters); } // See tests for example grep lines fn make_grep_line_regex(regex_variant: GrepLineRegex) -> Regex { // Grep tools such as `git grep` and `rg` emit lines like the following, // where "xxx" represents arbitrary code. Note that there are 3 possible // "separator characters": ':', '-', '='. // The format is ambiguous, but we attempt to parse it. // src/co-7-fig.rs:xxx // src/co-7-fig.rs:7:xxx // src/co-7-fig.rs-xxx // src/co-7-fig.rs-7-xxx // src/co-7-fig.rs=xxx // src/co-7-fig.rs=7=xxx // Makefile:xxx // Makefile:7:xxx // Makefile-xxx // Makefile-7-xxx // Make-7-file:xxx // Make-7-file:7:xxx // Make-7-file-xxx // Make-7-file-7-xxx let file_path = match regex_variant { GrepLineRegex::WithColor => { r" \x1b\[35m # starts with ANSI color sequence ( # 1. file name [^\x1b]* # anything ) \x1b\[m # ends with ANSI color reset " } GrepLineRegex::WithFileExtensionAndLineNumber | GrepLineRegex::WithFileExtension => { r" ( # 1. file name (colons not allowed) [^:|\ ] # try to be strict about what a file path can start with [^:]* # anything [^\ ]\.[^.\ :=-]{1,10} # extension ) " } GrepLineRegex::WithFileExtensionNoSpaces => { r" ( # 1. file name (colons not allowed) [^:|\ ]+ # try to be strict about what a file path can start with [^\ ]\.[^.\ :=-]{1,6} # extension ) " } GrepLineRegex::WithoutSeparatorCharacters => { r" ( # 1. file name (colons not allowed) [^:|\ =-] # try to be strict about what a file path can start with [^:=-]* # anything except separators [^:\ ] # a file name cannot end with whitespace ) " } }; let separator = match regex_variant { GrepLineRegex::WithColor => { r#" \x1b\[36m # starts with ANSI color sequence for separator (?: ( : # 2. match marker \x1b\[m # ANSI color reset (?: # optional: line number followed by second match marker \x1b\[32m # ANSI color sequence for line number ([0-9]+) # 3. line number \x1b\[m # ANSI color reset \x1b\[36m # ANSI color sequence for separator : # second match marker \x1b\[m # ANSI color reset )? ) | ( - # 4. nomatch marker \x1b\[m # ANSI color reset (?: # optional: line number followed by second nomatch marker \x1b\[32m # ANSI color sequence for line number ([0-9]+) # 5. line number \x1b\[m # ANSI color reset \x1b\[36m # ANSI color sequence for separator - # second nomatch marker \x1b\[m # ANSI color reset )? ) | ( = # 6. context header marker \x1b\[m # ANSI color reset (?: # optional: line number followed by second context header marker \x1b\[32m # ANSI color sequence for line number ([0-9]+) # 7. line number \x1b\[m # ANSI color reset \x1b\[36m # ANSI color sequence for separator = # second context header marker \x1b\[m # ANSI color reset )? ) ) "# } GrepLineRegex::WithFileExtensionAndLineNumber => { r#" (?: ( : # 2. match marker ([0-9]+): # 3. line number followed by second match marker ) | ( - # 4. nomatch marker ([0-9]+)- # 5. line number followed by second nomatch marker ) | ( = # 6. context header marker ([0-9]+)= # 7. line number followed by second header marker ) ) "# } _ => { r#" (?: ( : # 2. match marker (?:([0-9]+):)? # 3. optional: line number followed by second match marker ) | ( - # 4. nomatch marker (?:([0-9]+)-)? # 5. optional: line number followed by second nomatch marker ) | ( = # 6. context header marker (?:([0-9]+)=)? # 7. optional: line number followed by second header marker ) ) "# } }; Regex::new(&format!( "(?x) ^ {file_path} {separator} (.*) # 8. code (i.e. line contents) $ ", )) .unwrap() } pub fn parse_grep_line(line: &str) -> Option<GrepLine<'_>> { if line.starts_with('{') { ripgrep_json::parse_line(line) } else { match &*process::calling_process() { process::CallingProcess::GitGrep(_) | process::CallingProcess::OtherGrep => [ &*GREP_LINE_REGEX_ASSUMING_FILE_EXTENSION_AND_LINE_NUMBER, &*GREP_LINE_REGEX_ASSUMING_FILE_EXTENSION_NO_SPACES, &*GREP_LINE_REGEX_ASSUMING_FILE_EXTENSION, &*GREP_LINE_REGEX_ASSUMING_NO_INTERNAL_SEPARATOR_CHARS, ] .iter() .find_map(|regex| _parse_grep_line(regex, line)), _ => None, } } } pub fn parse_raw_grep_line(raw_line: &str) -> Option<GrepLine<'_>> { // Early exit if we don't have an escape sequence if !raw_line.starts_with('\x1b') { return None; } if !matches!( &*process::calling_process(), process::CallingProcess::GitGrep(_) | process::CallingProcess::OtherGrep ) { return None; } _parse_grep_line(&GREP_LINE_REGEX_ASSUMING_COLOR, raw_line).map(|mut grep_line| { grep_line.code = ansi::strip_ansi_codes(&grep_line.code).into(); grep_line }) } pub fn _parse_grep_line<'b>(regex: &Regex, line: &'b str) -> Option<GrepLine<'b>> { let caps = regex.captures(line)?; let file = caps.get(1).unwrap().as_str().into(); let (line_type, line_number) = &[ (2, LineType::Match), (4, LineType::Context), (6, LineType::ContextHeader), ] .iter() .find_map(|(i, line_type)| { if caps.get(*i).is_some() { let line_number: Option<usize> = caps.get(i + 1).and_then(|m| m.as_str().parse().ok()); Some((*line_type, line_number)) } else { None } }) .unwrap(); // The regex matches so one of the three alternatives must have matched let code = caps.get(8).unwrap().as_str().into(); Some(GrepLine { grep_type: GrepType::Classic, path: file, line_number: *line_number, line_type: *line_type, code, submatches: None, }) } #[cfg(test)] mod tests { use crate::handlers::grep::{ parse_grep_line, parse_raw_grep_line, GrepLine, GrepType, LineType, }; use crate::utils::process::tests::FakeParentArgs; #[test] fn test_parse_grep_match() { let fake_parent_grep_command = "git --doesnt-matter grep --nor-this nor_this -- nor_this"; let _args = FakeParentArgs::for_scope(fake_parent_grep_command); assert_eq!( parse_grep_line("src/co-7-fig.rs:xxx"), Some(GrepLine { grep_type: GrepType::Classic, path: "src/co-7-fig.rs".into(), line_number: None, line_type: LineType::Match, code: "xxx".into(), submatches: None, }) ); assert_eq!( parse_grep_line("src/config.rs:use crate::minusplus::MinusPlus;"), Some(GrepLine { grep_type: GrepType::Classic, path: "src/config.rs".into(), line_number: None, line_type: LineType::Match, code: "use crate::minusplus::MinusPlus;".into(), submatches: None, }) ); assert_eq!( parse_grep_line( "src/config.rs: pub line_numbers_style_minusplus: MinusPlus<Style>," ), Some(GrepLine { grep_type: GrepType::Classic, path: "src/config.rs".into(), line_number: None, line_type: LineType::Match, code: " pub line_numbers_style_minusplus: MinusPlus<Style>,".into(), submatches: None, }) ); assert_eq!( parse_grep_line("src/con-fig.rs:use crate::minusplus::MinusPlus;"), Some(GrepLine { grep_type: GrepType::Classic, path: "src/con-fig.rs".into(), line_number: None, line_type: LineType::Match, code: "use crate::minusplus::MinusPlus;".into(), submatches: None, }) ); assert_eq!( parse_grep_line( "src/con-fig.rs: pub line_numbers_style_minusplus: MinusPlus<Style>," ), Some(GrepLine { grep_type: GrepType::Classic, path: "src/con-fig.rs".into(), line_number: None, line_type: LineType::Match, code: " pub line_numbers_style_minusplus: MinusPlus<Style>,".into(), submatches: None, }) ); assert_eq!( parse_grep_line( "src/de lta.rs:pub fn delta<I>(lines: ByteLines<I>, writer: &mut dyn Write, config: &Config) -> std::io::Result<()>" ), Some(GrepLine { grep_type: GrepType::Classic, path: "src/de lta.rs".into(), line_number: None, line_type: LineType::Match, code: "pub fn delta<I>(lines: ByteLines<I>, writer: &mut dyn Write, config: &Config) -> std::io::Result<()>".into(), submatches: None, }) ); assert_eq!( parse_grep_line( "src/de lta.rs: pub fn new(writer: &'a mut dyn Write, config: &'a Config) -> Self {" ), Some(GrepLine { grep_type: GrepType::Classic, path: "src/de lta.rs".into(), line_number: None, line_type: LineType::Match, code: " pub fn new(writer: &'a mut dyn Write, config: &'a Config) -> Self {".into(), submatches: None, }) ); } #[test] fn test_parse_grep_n_match() { let fake_parent_grep_command = "/usr/local/bin/git --doesnt-matter grep --nor-this nor_this -- nor_this"; let _args = FakeParentArgs::for_scope(fake_parent_grep_command); assert_eq!( parse_grep_line("src/co-7-fig.rs:7:xxx"), Some(GrepLine { grep_type: GrepType::Classic, path: "src/co-7-fig.rs".into(), line_number: Some(7), line_type: LineType::Match, code: "xxx".into(), submatches: None, }) ); assert_eq!( parse_grep_line("src/config.rs:21:use crate::minusplus::MinusPlus;"), Some(GrepLine { grep_type: GrepType::Classic, path: "src/config.rs".into(), line_number: Some(21), line_type: LineType::Match, code: "use crate::minusplus::MinusPlus;".into(), submatches: None, }) ); assert_eq!( parse_grep_line( "src/config.rs:95: pub line_numbers_style_minusplus: MinusPlus<Style>," ), Some(GrepLine { grep_type: GrepType::Classic, path: "src/config.rs".into(), line_number: Some(95), line_type: LineType::Match, code: " pub line_numbers_style_minusplus: MinusPlus<Style>,".into(), submatches: None, }) ); assert_eq!( parse_grep_line("Makefile:10:test: unit-test end-to-end-test"), Some(GrepLine { grep_type: GrepType::Classic, path: "Makefile".into(), line_number: Some(10), line_type: LineType::Match, code: "test: unit-test end-to-end-test".into(), submatches: None, }) ); assert_eq!( parse_grep_line( "Makefile:16: ./tests/test_raw_output_matches_git_on_full_repo_history" ), Some(GrepLine { grep_type: GrepType::Classic, path: "Makefile".into(), line_number: Some(16), line_type: LineType::Match,
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
true
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/handlers/ripgrep_json.rs
src/handlers/ripgrep_json.rs
// See https://github.com/BurntSushi/ripgrep // This module implements handling of `rg --json` output. It is called by the // handler in handlers/grep.rs. Normal rg output (i.e. without --json) is // handled by the same code paths as `git grep` etc output, in handlers/grep.rs. use std::borrow::Cow; use crate::handlers::grep; use serde::Deserialize; use serde_json::Value; pub fn parse_line(line: &str) -> Option<grep::GrepLine<'_>> { let ripgrep_line: Option<RipGrepLine> = serde_json::from_str(line).ok(); match ripgrep_line { Some(ripgrep_line) => { // A real line of rg --json output, i.e. either of type "match" or // "context". let mut code = ripgrep_line.data.lines.text; // Keep newlines so the syntax highlighter handles C-style line comments // correctly. Also remove \r, see [EndCRLF] in src/delta.rs, but this time // it is syntect which adds an ANSI escape sequence in between \r\n later. if code.ends_with("\r\n") { code.truncate(code.len() - 2); code.push('\n'); } Some(grep::GrepLine { grep_type: crate::config::GrepType::Ripgrep, line_type: ripgrep_line._type, line_number: ripgrep_line.data.line_number, path: Cow::from(ripgrep_line.data.path.text), code: Cow::from(code), submatches: Some( ripgrep_line .data .submatches .iter() .map(|m| (m.start, m.end)) .collect(), ), }) } None => { let value: Value = serde_json::from_str(line).ok()?; match &value["type"] { Value::String(s) if s == "begin" || s == "end" || s == "summary" => { Some(grep::GrepLine { // ripgrep --json also emits these metadata lines at // file boundaries. We emit nothing but signal that the // line has been handled. grep_type: crate::config::GrepType::Ripgrep, line_type: grep::LineType::Ignore, line_number: None, path: "".into(), code: "".into(), submatches: None, }) } _ => { // Failed to interpret the line as ripgrep output; allow // another delta handler to try. None } } } } } // { // "type": "match", // "data": { // "path": { // "text": "src/cli.rs" // }, // "lines": { // "text": " fn from_clap_and_git_config(\n" // }, // "line_number": null, // "absolute_offset": 35837, // "submatches": [ // { // "match": { // "text": "fn" // }, // "start": 4, // "end": 6 // } // ] // } // } #[derive(Deserialize, PartialEq, Debug)] struct RipGrepLine { #[serde(rename(deserialize = "type"))] _type: grep::LineType, data: RipGrepLineData, } #[derive(Deserialize, PartialEq, Debug)] struct RipGrepLineData { path: RipGrepLineText, lines: RipGrepLineText, line_number: Option<usize>, absolute_offset: usize, submatches: Vec<RipGrepLineSubmatch>, } #[derive(Deserialize, PartialEq, Debug)] struct RipGrepLineText { text: String, } #[derive(Deserialize, PartialEq, Debug)] struct RipGrepLineSubmatch { #[serde(rename(deserialize = "match"))] _match: RipGrepLineText, start: usize, end: usize, } #[cfg(test)] mod tests { use super::*; use crate::tests::integration_test_utils::DeltaTest; use insta::assert_snapshot; /* FILE test.c: // i ABC int f() { return 4; } const char* i = "ABC"; double n = 1.23; */ #[test] fn test_syntax_in_rg_output_with_context() { // `rg int -C2 --json test.c` let data = r#"{"type":"begin","data":{"path":{"text":"test.c"}}} {"type":"context","data":{"path":{"text":"test.c"},"lines":{"text":"// i ABC\n"},"line_number":1,"absolute_offset":0,"submatches":[]}} {"type":"match","data":{"path":{"text":"test.c"},"lines":{"text":"int f() { return 4; }\n"},"line_number":2,"absolute_offset":9,"submatches":[{"match":{"text":"int"},"start":0,"end":3}]}} {"type":"context","data":{"path":{"text":"test.c"},"lines":{"text":"const char* i = \"ABC\";\n"},"line_number":3,"absolute_offset":31,"submatches":[]}} {"type":"context","data":{"path":{"text":"test.c"},"lines":{"text":"double n = 1.23;\n"},"line_number":4,"absolute_offset":54,"submatches":[]}} {"type":"end","data":{"path":{"text":"test.c"},"binary_offset":null,"stats":{"elapsed":{"secs":0,"nanos":26941,"human":"0.000027s"},"searches":1,"searches_with_match":1,"bytes_searched":71,"bytes_printed":670,"matched_lines":1,"matches":1}}} {"data":{"elapsed_total":{"human":"0.000479s","nanos":478729,"secs":0},"stats":{"bytes_printed":670,"bytes_searched":71,"elapsed":{"human":"0.000027s","nanos":26941,"secs":0},"matched_lines":1,"matches":1,"searches":1,"searches_with_match":1}},"type":"summary"}"#; let result = DeltaTest::with_args(&[]).explain_ansi().with_input(data); // eprintln!("{}", result.raw_output); assert_snapshot!(result.output, @r#" (purple)test.c(normal) (green)1(normal)-(242)// i ABC(normal) (green)2(normal):(81 28)int(231) (149)f(231)() { (203)return(231) (141)4(231); }(normal) (green)3(normal)-(203)const(231) (81)char(203)*(231) i (203)=(231) (186)"ABC"(231);(normal) (green)4(normal)-(81)double(231) n (203)=(231) (141)1.23(231);(normal) "#); } #[test] fn test_syntax_in_rg_output_no_context() { // `rg i --json test.c` let data = r#"{"type":"begin","data":{"path":{"text":"test.c"}}} {"type":"match","data":{"path":{"text":"test.c"},"lines":{"text":"// i ABC\n"},"line_number":1,"absolute_offset":0,"submatches":[{"match":{"text":"i"},"start":3,"end":4}]}} {"type":"match","data":{"path":{"text":"test.c"},"lines":{"text":"int f() { return 4; }\n"},"line_number":2,"absolute_offset":9,"submatches":[{"match":{"text":"i"},"start":0,"end":1}]}} {"type":"match","data":{"path":{"text":"test.c"},"lines":{"text":"const char* i = \"ABC\";\n"},"line_number":3,"absolute_offset":31,"submatches":[{"match":{"text":"i"},"start":12,"end":13}]}} {"type":"end","data":{"path":{"text":"test.c"},"binary_offset":null,"stats":{"elapsed":{"secs":0,"nanos":23885,"human":"0.000024s"},"searches":1,"searches_with_match":1,"bytes_searched":71,"bytes_printed":602,"matched_lines":3,"matches":3}}} {"data":{"elapsed_total":{"human":"0.000433s","nanos":432974,"secs":0},"stats":{"bytes_printed":602,"bytes_searched":71,"elapsed":{"human":"0.000024s","nanos":23885,"secs":0},"matched_lines":3,"matches":3,"searches":1,"searches_with_match":1}},"type":"summary"} "#; let result = DeltaTest::with_args(&[]).explain_ansi().with_input(data); // eprintln!("{}", result.raw_output); assert_snapshot!(result.output, @r#" (purple)test.c(normal) (green)1(normal):(242)// (normal 28)i(242) ABC(normal) (green)2(normal):(81 28)i(81)nt(231) (149)f(231)() { (203)return(231) (141)4(231); }(normal) (green)3(normal):(203)const(231) (81)char(203)*(231) (normal 28)i(231) (203)=(231) (186)"ABC"(231);(normal) "#); } #[test] fn test_deserialize() { let line = r#"{"type":"match","data":{"path":{"text":"src/cli.rs"},"lines":{"text":" fn from_clap_and_git_config(\n"},"line_number":null,"absolute_offset":35837,"submatches":[{"match":{"text":"fn"},"start":4,"end":6}]}}"#; let ripgrep_line: RipGrepLine = serde_json::from_str(line).unwrap(); assert_eq!( ripgrep_line, RipGrepLine { _type: grep::LineType::Match, data: RipGrepLineData { path: RipGrepLineText { text: "src/cli.rs".into() }, lines: RipGrepLineText { text: " fn from_clap_and_git_config(\n".into(), }, line_number: None, absolute_offset: 35837, submatches: vec![RipGrepLineSubmatch { _match: RipGrepLineText { text: "fn".into() }, start: 4, end: 6 }] } } ) } #[test] fn test_deserialize_2() { let line = r#"{"type":"match","data":{"path":{"text":"src/handlers/submodule.rs"},"lines":{"text":" .paint(minus_commit.chars().take(7).collect::<String>()),\n"},"line_number":41,"absolute_offset":1430,"submatches":[{"match":{"text":"("},"start":30,"end":31},{"match":{"text":"("},"start":49,"end":50},{"match":{"text":")"},"start":50,"end":51},{"match":{"text":"("},"start":56,"end":57},{"match":{"text":")"},"start":58,"end":59},{"match":{"text":"("},"start":77,"end":78},{"match":{"text":")"},"start":78,"end":79},{"match":{"text":")"},"start":79,"end":80}]}}"#; let ripgrep_line: RipGrepLine = serde_json::from_str(line).unwrap(); assert_eq!( ripgrep_line, RipGrepLine { _type: grep::LineType::Match, data: RipGrepLineData { path: RipGrepLineText { text: "src/handlers/submodule.rs".into() }, lines: RipGrepLineText { text: " .paint(minus_commit.chars().take(7).collect::<String>()),\n".into(), }, line_number: Some(41), absolute_offset: 1430, submatches: vec![ RipGrepLineSubmatch { _match: RipGrepLineText { text: "(".into() }, start: 30, end: 31 }, RipGrepLineSubmatch { _match: RipGrepLineText { text: "(".into() }, start: 49, end: 50 }, RipGrepLineSubmatch { _match: RipGrepLineText { text: ")".into() }, start: 50, end: 51 }, RipGrepLineSubmatch { _match: RipGrepLineText { text: "(".into() }, start: 56, end: 57 }, RipGrepLineSubmatch { _match: RipGrepLineText { text: ")".into() }, start: 58, end: 59 }, RipGrepLineSubmatch { _match: RipGrepLineText { text: "(".into() }, start: 77, end: 78 }, RipGrepLineSubmatch { _match: RipGrepLineText { text: ")".into() }, start: 78, end: 79 }, RipGrepLineSubmatch { _match: RipGrepLineText { text: ")".into() }, start: 79, end: 80 }, ] } } ) } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/git_config/remote.rs
src/git_config/remote.rs
use std::result::Result; use std::str::FromStr; use lazy_static::lazy_static; use regex::Regex; use crate::errors::*; #[derive(Clone, Debug, PartialEq, Eq)] pub enum GitRemoteRepo { GitHub { slug: String }, GitLab { slug: String }, SourceHut { slug: String }, Codeberg { slug: String }, } impl GitRemoteRepo { pub fn format_commit_url(&self, commit: &str) -> String { match self { Self::GitHub { slug } => { format!("https://github.com/{slug}/commit/{commit}") } Self::GitLab { slug } => { format!("https://gitlab.com/{slug}/-/commit/{commit}") } Self::SourceHut { slug } => { format!("https://git.sr.ht/{slug}/commit/{commit}") } Self::Codeberg { slug } => { format!("https://codeberg.org/{slug}/commit/{commit}") } } } #[cfg(test)] pub fn for_testing() -> Option<GitRemoteRepo> { Some(GitRemoteRepo::GitHub { slug: "dandavison/delta".to_string(), }) } } lazy_static! { static ref GITHUB_REMOTE_URL: Regex = Regex::new( r"(?x) ^ (?:https://|[^@]+@)? # Support both HTTPS and SSH URLs github\.com [:/] # This separator differs between SSH and HTTPS URLs ([^/]+) # Capture the user/org name / (.+?) # Capture the repo name (lazy to avoid consuming '.git' if present) (?:\.git)? # Non-capturing group to consume '.git' if present $ " ) .unwrap(); static ref GITLAB_REMOTE_URL: Regex = Regex::new( r"(?x) ^ (?:https://|git@)? # Support both HTTPS and SSH URLs, SSH URLs optionally omitting the git@ gitlab\.com [:/] # This separator differs between SSH and HTTPS URLs ([^/]+) # Capture the user/org name (/.*)? # Capture group(s), if any / (.+?) # Capture the repo name (lazy to avoid consuming '.git' if present) (?:\.git)? # Non-capturing group to consume '.git' if present $ " ) .unwrap(); static ref SOURCEHUT_REMOTE_URL: Regex = Regex::new( r"(?x) ^ (?:https://|git@)? # Support both HTTPS and SSH URLs, SSH URLs optionally omitting the git@ git\.sr\.ht [:/] # This separator differs between SSH and HTTPS URLs ~([^/]+) # Capture the username / (.+) # Capture the repo name $ " ) .unwrap(); static ref CODEBERG_REMOTE_URL: Regex = Regex::new( r"(?x) ^ (?:https://|git@)? # Support both HTTPS and SSH URLs, SSH URLs optionally omitting the git@ codeberg\.org [:/] # This separator differs between SSH and HTTPS URLs ([^/]+) # Capture the user/org name / (.+?) # Capture the repo name (lazy to avoid consuming '.git' if present) (?:\.git)? # Non-capturing group to consume '.git' if present $ " ) .unwrap(); } impl FromStr for GitRemoteRepo { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Err> { if let Some(caps) = GITHUB_REMOTE_URL.captures(s) { Ok(Self::GitHub { slug: format!( "{user}/{repo}", user = caps.get(1).unwrap().as_str(), repo = caps.get(2).unwrap().as_str() ), }) } else if let Some(caps) = GITLAB_REMOTE_URL.captures(s) { Ok(Self::GitLab { slug: format!( "{user}{groups}/{repo}", user = caps.get(1).unwrap().as_str(), groups = caps.get(2).map(|x| x.as_str()).unwrap_or_default(), repo = caps.get(3).unwrap().as_str() ), }) } else if let Some(caps) = SOURCEHUT_REMOTE_URL.captures(s) { Ok(Self::SourceHut { slug: format!( "~{user}/{repo}", user = caps.get(1).unwrap().as_str(), repo = caps.get(2).unwrap().as_str() ), }) } else if let Some(caps) = CODEBERG_REMOTE_URL.captures(s) { Ok(Self::Codeberg { slug: format!( "{user}/{repo}", user = caps.get(1).unwrap().as_str(), repo = caps.get(2).unwrap().as_str() ), }) } else { Err(anyhow!("Not a GitHub, GitLab, SourceHut or Codeberg repo.")) } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse_github_urls() { let urls = &[ "https://github.com/dandavison/delta.git", "https://github.com/dandavison/delta", "git@github.com:dandavison/delta.git", "git@github.com:dandavison/delta", "github.com:dandavison/delta.git", "github.com:dandavison/delta", ]; for url in urls { let parsed = GitRemoteRepo::from_str(url); assert!(parsed.is_ok()); assert_eq!( parsed.unwrap(), GitRemoteRepo::GitHub { slug: "dandavison/delta".to_string() } ); } } #[test] fn test_format_github_commit_link() { let repo = GitRemoteRepo::GitHub { slug: "dandavison/delta".to_string(), }; let commit_hash = "d3b07384d113edec49eaa6238ad5ff00"; assert_eq!( repo.format_commit_url(commit_hash), format!("https://github.com/dandavison/delta/commit/{commit_hash}") ) } #[test] fn test_parse_gitlab_urls() { let urls = &[ ( "https://gitlab.com/proj/grp/subgrp/repo.git", "proj/grp/subgrp/repo", ), ("https://gitlab.com/proj/grp/repo.git", "proj/grp/repo"), ("https://gitlab.com/proj/repo.git", "proj/repo"), ("https://gitlab.com/proj/repo", "proj/repo"), ( "git@gitlab.com:proj/grp/subgrp/repo.git", "proj/grp/subgrp/repo", ), ("git@gitlab.com:proj/repo.git", "proj/repo"), ("git@gitlab.com:proj/repo", "proj/repo"), ("gitlab.com:proj/grp/repo.git", "proj/grp/repo"), ("gitlab.com:proj/repo.git", "proj/repo"), ("gitlab.com:proj/repo", "proj/repo"), ]; for (url, expected) in urls { let parsed = GitRemoteRepo::from_str(url); assert!(parsed.is_ok()); assert_eq!( parsed.unwrap(), GitRemoteRepo::GitLab { slug: expected.to_string() } ); } } #[test] fn test_format_gitlab_commit_link() { let repo = GitRemoteRepo::GitLab { slug: "proj/grp/repo".to_string(), }; let commit_hash = "d3b07384d113edec49eaa6238ad5ff00"; assert_eq!( repo.format_commit_url(commit_hash), format!("https://gitlab.com/proj/grp/repo/-/commit/{commit_hash}") ) } #[test] fn test_parse_sourcehut_urls() { let urls = &[ "https://git.sr.ht/~someuser/somerepo", "git@git.sr.ht:~someuser/somerepo", "git.sr.ht:~someuser/somerepo", ]; for url in urls { let parsed = GitRemoteRepo::from_str(url); assert!(parsed.is_ok()); assert_eq!( parsed.unwrap(), GitRemoteRepo::SourceHut { slug: "~someuser/somerepo".to_string() } ); } } #[test] fn test_format_sourcehut_commit_link() { let repo = GitRemoteRepo::SourceHut { slug: "~someuser/somerepo".to_string(), }; let commit_hash = "df41ac86f08a40e64c76062fd67e238522c14990"; assert_eq!( repo.format_commit_url(commit_hash), format!("https://git.sr.ht/~someuser/somerepo/commit/{commit_hash}") ) } #[test] fn test_parse_codeberg_urls() { let urls = &[ "https://codeberg.org/someuser/somerepo.git", "https://codeberg.org/someuser/somerepo", "git@codeberg.org:someuser/somerepo.git", "git@codeberg.org:someuser/somerepo", "codeberg.org:someuser/somerepo.git", "codeberg.org:someuser/somerepo", ]; for url in urls { let parsed = GitRemoteRepo::from_str(url); assert!(parsed.is_ok()); assert_eq!( parsed.unwrap(), GitRemoteRepo::Codeberg { slug: "someuser/somerepo".to_string() } ); } } #[test] fn test_format_codeberg_commit_link() { let repo = GitRemoteRepo::Codeberg { slug: "dnkl/foot".to_string(), }; let commit_hash = "1c072856ebf12419378c5098ad543c497197c6da"; assert_eq!( repo.format_commit_url(commit_hash), format!("https://codeberg.org/dnkl/foot/commit/{commit_hash}") ) } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/git_config/mod.rs
src/git_config/mod.rs
mod remote; pub use remote::GitRemoteRepo; use crate::env::DeltaEnv; use regex::Regex; use std::cell::OnceCell; use std::collections::HashMap; use std::path::Path; use lazy_static::lazy_static; pub struct GitConfig { config: git2::Config, config_from_env_var: HashMap<String, String>, pub enabled: bool, repo: Option<git2::Repository>, remote_url: OnceCell<Option<GitRemoteRepo>>, // To make GitConfig cloneable when testing (in turn to make Config cloneable): #[cfg(test)] path: std::path::PathBuf, } #[cfg(test)] impl Clone for GitConfig { fn clone(&self) -> Self { assert!(self.repo.is_none()); GitConfig { // Assumes no test modifies the file pointed to by `path` config: git2::Config::open(&self.path).unwrap(), config_from_env_var: self.config_from_env_var.clone(), enabled: self.enabled, repo: None, remote_url: OnceCell::new(), path: self.path.clone(), } } } impl GitConfig { #[cfg(not(test))] pub fn try_create(env: &DeltaEnv) -> Option<Self> { use crate::fatal; let repo = match &env.current_dir { Some(dir) => git2::Repository::discover(dir).ok(), _ => None, }; let config = match &repo { Some(repo) => repo.config().ok(), None => git2::Config::open_default().ok(), }; match config { Some(mut config) => { let config = config.snapshot().unwrap_or_else(|err| { fatal(format!("Failed to read git config: {err}")); }); Some(Self { config, config_from_env_var: parse_config_from_env_var(env), repo, enabled: true, remote_url: OnceCell::new(), }) } None => None, } } #[cfg(test)] pub fn try_create(_env: &DeltaEnv) -> Option<Self> { // Do not read local git configs when testing None } #[cfg(test)] pub fn for_testing() -> Option<Self> { Some(GitConfig { config: git2::Config::new().unwrap(), config_from_env_var: HashMap::new(), enabled: true, repo: None, remote_url: OnceCell::new(), path: std::path::PathBuf::from("/invalid_null.git"), }) } pub fn from_path(env: &DeltaEnv, path: &Path, honor_env_var: bool) -> Self { use crate::fatal; match git2::Config::open(path) { Ok(mut config) => { let config = config.snapshot().unwrap_or_else(|err| { fatal(format!("Failed to read git config: {err}")); }); Self { config, config_from_env_var: if honor_env_var { parse_config_from_env_var(env) } else { HashMap::new() }, repo: None, enabled: true, remote_url: OnceCell::new(), #[cfg(test)] path: path.into(), } } Err(e) => { fatal(format!("Failed to read git config: {}", e.message())); } } } pub fn get<T>(&self, key: &str) -> Option<T> where T: GitConfigGet, { if self.enabled { T::git_config_get(key, self) } else { None } } #[cfg(test)] fn get_remote_url_impl(&self) -> Option<GitRemoteRepo> { GitRemoteRepo::for_testing() } #[cfg(not(test))] fn get_remote_url_impl(&self) -> Option<GitRemoteRepo> { use std::str::FromStr; self.repo .as_ref()? .find_remote("origin") .ok()? .url() .and_then(|url| GitRemoteRepo::from_str(url).ok()) } pub fn get_remote_url(&self) -> &Option<GitRemoteRepo> { self.remote_url.get_or_init(|| self.get_remote_url_impl()) } pub fn for_each<F>(&self, regex: &str, mut f: F) where F: FnMut(&str, Option<&str>), { let mut entries = self.config.entries(Some(regex)).unwrap(); while let Some(entry) = entries.next() { let entry = entry.unwrap(); let name = entry.name().unwrap(); f(name, entry.value()); } } } fn parse_config_from_env_var(env: &DeltaEnv) -> HashMap<String, String> { if let Some(s) = &env.git_config_parameters { parse_config_from_env_var_value(s) } else { HashMap::new() } } lazy_static! { static ref GIT_CONFIG_PARAMETERS_REGEX: Regex = Regex::new( r"(?x) (?: # Non-capturing group containing union '(delta\.[a-z-]+)=([^']+)' # Git <2.31.0 format | '(delta\.[a-z-]+)'='([^']+)' # Git ≥2.31.0 format ) " ) .unwrap(); } fn parse_config_from_env_var_value(s: &str) -> HashMap<String, String> { GIT_CONFIG_PARAMETERS_REGEX .captures_iter(s) .map(|captures| { let (i, j) = match ( captures.get(1), captures.get(2), captures.get(3), captures.get(4), ) { (Some(_), Some(_), None, None) => (1, 2), (None, None, Some(_), Some(_)) => (3, 4), _ => (0, 0), }; if (i, j) == (0, 0) { ("".to_string(), "".to_string()) } else { (captures[i].to_string(), captures[j].to_string()) } }) .collect() } pub trait GitConfigGet { fn git_config_get(key: &str, git_config: &GitConfig) -> Option<Self> where Self: Sized; } impl GitConfigGet for String { fn git_config_get(key: &str, git_config: &GitConfig) -> Option<Self> { match git_config.config_from_env_var.get(key) { Some(val) => Some(val.to_string()), None => git_config.config.get_string(key).ok(), } } } impl GitConfigGet for Option<String> { fn git_config_get(key: &str, git_config: &GitConfig) -> Option<Self> { match git_config.config_from_env_var.get(key) { Some(val) => Some(Some(val.to_string())), None => match git_config.config.get_string(key) { Ok(val) => Some(Some(val)), _ => None, }, } } } impl GitConfigGet for bool { fn git_config_get(key: &str, git_config: &GitConfig) -> Option<Self> { match git_config.config_from_env_var.get(key).map(|s| s.as_str()) { Some("true") => Some(true), Some("false") => Some(false), _ => git_config.config.get_bool(key).ok(), } } } impl GitConfigGet for usize { fn git_config_get(key: &str, git_config: &GitConfig) -> Option<Self> { if let Some(s) = git_config.config_from_env_var.get(key) { if let Ok(n) = s.parse::<usize>() { return Some(n); } } match git_config.config.get_i64(key) { Ok(value) => Some(value as usize), _ => None, } } } impl GitConfigGet for f64 { fn git_config_get(key: &str, git_config: &GitConfig) -> Option<Self> { if let Some(s) = git_config.config_from_env_var.get(key) { if let Ok(n) = s.parse::<f64>() { return Some(n); } } match git_config.config.get_string(key) { Ok(value) => value.parse::<f64>().ok(), _ => None, } } } #[cfg(test)] mod tests { use super::parse_config_from_env_var_value; #[test] fn test_parse_config_from_env_var_value() { // To generate test cases, use git -c ... with // [core] // pager = env | grep GIT_CONFIG_PARAMETERS // We test multiple formats because the format of the value stored by // git in this environment variable has changed in recent versions of // Git. See // https://github.com/git/git/blob/311531c9de557d25ac087c1637818bd2aad6eb3a/Documentation/RelNotes/2.31.0.txt#L127-L130 for env_var_value in &["'user.name=xxx'", "'user.name'='xxx'"] { let config = parse_config_from_env_var_value(env_var_value); assert!(config.is_empty()); } for env_var_value in &["'delta.plus-style=green'", "'delta.plus-style'='green'"] { let config = parse_config_from_env_var_value(env_var_value); assert_eq!(config["delta.plus-style"], "green"); } for env_var_value in &[ r##"'user.name=xxx' 'delta.hunk-header-line-number-style=red "#067a00"'"##, r##"'user.name'='xxx' 'delta.hunk-header-line-number-style'='red "#067a00"'"##, ] { let config = parse_config_from_env_var_value(env_var_value); assert_eq!( config["delta.hunk-header-line-number-style"], r##"red "#067a00""## ); } for env_var_value in &[ r##"'user.name=xxx' 'delta.side-by-side=false'"##, r##"'user.name'='xxx' 'delta.side-by-side'='false'"##, ] { let config = parse_config_from_env_var_value(env_var_value); assert_eq!(config["delta.side-by-side"], "false"); } for env_var_value in &[ r##"'delta.plus-style=green' 'delta.side-by-side=false' 'delta.hunk-header-line-number-style=red "#067a00"'"##, r##"'delta.plus-style'='green' 'delta.side-by-side'='false' 'delta.hunk-header-line-number-style'='red "#067a00"'"##, ] { let config = parse_config_from_env_var_value(env_var_value); assert_eq!(config["delta.plus-style"], "green"); assert_eq!(config["delta.side-by-side"], "false"); assert_eq!( config["delta.hunk-header-line-number-style"], r##"red "#067a00""## ); } } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/renderer/src/lib.rs
renderer/src/lib.rs
//! The official renderer for iced. #![cfg_attr(docsrs, feature(doc_cfg))] #[cfg(feature = "wgpu-bare")] pub use iced_wgpu as wgpu; pub mod fallback; pub use iced_graphics as graphics; pub use iced_graphics::core; #[cfg(feature = "geometry")] pub use iced_graphics::geometry; /// The default graphics renderer for [`iced`]. /// /// [`iced`]: https://github.com/iced-rs/iced pub type Renderer = renderer::Renderer; /// The default graphics compositor for [`iced`]. /// /// [`iced`]: https://github.com/iced-rs/iced pub type Compositor = renderer::Compositor; #[cfg(all(feature = "wgpu-bare", feature = "tiny-skia"))] mod renderer { pub type Renderer = crate::fallback::Renderer<iced_wgpu::Renderer, iced_tiny_skia::Renderer>; pub type Compositor = crate::fallback::Compositor< iced_wgpu::window::Compositor, iced_tiny_skia::window::Compositor, >; } #[cfg(all(feature = "wgpu-bare", not(feature = "tiny-skia")))] mod renderer { pub type Renderer = iced_wgpu::Renderer; pub type Compositor = iced_wgpu::window::Compositor; } #[cfg(all(not(feature = "wgpu-bare"), feature = "tiny-skia"))] mod renderer { pub type Renderer = iced_tiny_skia::Renderer; pub type Compositor = iced_tiny_skia::window::Compositor; } #[cfg(not(any(feature = "wgpu-bare", feature = "tiny-skia")))] mod renderer { #[cfg(not(debug_assertions))] compile_error!( "Cannot compile `iced_renderer` in release mode \ without a renderer feature enabled. \ Enable either the `wgpu` or `tiny-skia` feature, or both." ); pub type Renderer = (); pub type Compositor = (); }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/renderer/src/fallback.rs
renderer/src/fallback.rs
//! Compose existing renderers and create type-safe fallback strategies. use crate::core::image; use crate::core::renderer; use crate::core::svg; use crate::core::{ self, Background, Color, Font, Image, Pixels, Point, Rectangle, Size, Svg, Transformation, }; use crate::graphics::compositor; use crate::graphics::mesh; use crate::graphics::text; use crate::graphics::{self, Shell}; use std::borrow::Cow; /// A renderer `A` with a fallback strategy `B`. /// /// This type can be used to easily compose existing renderers and /// create custom, type-safe fallback strategies. #[derive(Debug)] pub enum Renderer<A, B> { /// The primary rendering option. Primary(A), /// The secondary (or fallback) rendering option. Secondary(B), } macro_rules! delegate { ($renderer:expr, $name:ident, $body:expr) => { match $renderer { Self::Primary($name) => $body, Self::Secondary($name) => $body, } }; } impl<A, B> core::Renderer for Renderer<A, B> where A: core::Renderer, B: core::Renderer, { fn fill_quad(&mut self, quad: renderer::Quad, background: impl Into<Background>) { delegate!(self, renderer, renderer.fill_quad(quad, background.into())); } fn start_layer(&mut self, bounds: Rectangle) { delegate!(self, renderer, renderer.start_layer(bounds)); } fn end_layer(&mut self) { delegate!(self, renderer, renderer.end_layer()); } fn start_transformation(&mut self, transformation: Transformation) { delegate!( self, renderer, renderer.start_transformation(transformation) ); } fn end_transformation(&mut self) { delegate!(self, renderer, renderer.end_transformation()); } fn allocate_image( &mut self, handle: &image::Handle, callback: impl FnOnce(Result<image::Allocation, image::Error>) + Send + 'static, ) { delegate!(self, renderer, renderer.allocate_image(handle, callback)); } fn hint(&mut self, scale_factor: f32) { delegate!(self, renderer, renderer.hint(scale_factor)); } fn scale_factor(&self) -> Option<f32> { delegate!(self, renderer, renderer.scale_factor()) } fn tick(&mut self) { delegate!(self, renderer, renderer.tick()); } fn reset(&mut self, new_bounds: Rectangle) { delegate!(self, renderer, renderer.reset(new_bounds)); } } impl<A, B> core::text::Renderer for Renderer<A, B> where A: core::text::Renderer, B: core::text::Renderer<Font = A::Font, Paragraph = A::Paragraph, Editor = A::Editor>, { type Font = A::Font; type Paragraph = A::Paragraph; type Editor = A::Editor; const ICON_FONT: Self::Font = A::ICON_FONT; const CHECKMARK_ICON: char = A::CHECKMARK_ICON; const ARROW_DOWN_ICON: char = A::ARROW_DOWN_ICON; const SCROLL_UP_ICON: char = A::SCROLL_UP_ICON; const SCROLL_DOWN_ICON: char = A::SCROLL_DOWN_ICON; const SCROLL_LEFT_ICON: char = A::SCROLL_LEFT_ICON; const SCROLL_RIGHT_ICON: char = A::SCROLL_RIGHT_ICON; const ICED_LOGO: char = A::ICED_LOGO; fn default_font(&self) -> Self::Font { delegate!(self, renderer, renderer.default_font()) } fn default_size(&self) -> core::Pixels { delegate!(self, renderer, renderer.default_size()) } fn fill_paragraph( &mut self, text: &Self::Paragraph, position: Point, color: Color, clip_bounds: Rectangle, ) { delegate!( self, renderer, renderer.fill_paragraph(text, position, color, clip_bounds) ); } fn fill_editor( &mut self, editor: &Self::Editor, position: Point, color: Color, clip_bounds: Rectangle, ) { delegate!( self, renderer, renderer.fill_editor(editor, position, color, clip_bounds) ); } fn fill_text( &mut self, text: core::Text<String, Self::Font>, position: Point, color: Color, clip_bounds: Rectangle, ) { delegate!( self, renderer, renderer.fill_text(text, position, color, clip_bounds) ); } } impl<A, B> text::Renderer for Renderer<A, B> where A: text::Renderer, B: text::Renderer, { fn fill_raw(&mut self, raw: text::Raw) { delegate!(self, renderer, renderer.fill_raw(raw)); } } impl<A, B> image::Renderer for Renderer<A, B> where A: image::Renderer, B: image::Renderer<Handle = A::Handle>, { type Handle = A::Handle; fn load_image(&self, handle: &Self::Handle) -> Result<image::Allocation, image::Error> { delegate!(self, renderer, renderer.load_image(handle)) } fn measure_image(&self, handle: &Self::Handle) -> Option<Size<u32>> { delegate!(self, renderer, renderer.measure_image(handle)) } fn draw_image(&mut self, image: Image<A::Handle>, bounds: Rectangle, clip_bounds: Rectangle) { delegate!( self, renderer, renderer.draw_image(image, bounds, clip_bounds) ); } } impl<A, B> svg::Renderer for Renderer<A, B> where A: svg::Renderer, B: svg::Renderer, { fn measure_svg(&self, handle: &svg::Handle) -> Size<u32> { delegate!(self, renderer, renderer.measure_svg(handle)) } fn draw_svg(&mut self, svg: Svg, bounds: Rectangle, clip_bounds: Rectangle) { delegate!(self, renderer, renderer.draw_svg(svg, bounds, clip_bounds)); } } impl<A, B> mesh::Renderer for Renderer<A, B> where A: mesh::Renderer, B: mesh::Renderer, { fn draw_mesh(&mut self, mesh: graphics::Mesh) { delegate!(self, renderer, renderer.draw_mesh(mesh)); } fn draw_mesh_cache(&mut self, cache: mesh::Cache) { delegate!(self, renderer, renderer.draw_mesh_cache(cache)); } } /// A compositor `A` with a fallback strategy `B`. /// /// It works analogously to [`Renderer`]. #[derive(Debug)] pub enum Compositor<A, B> where A: graphics::Compositor, B: graphics::Compositor, { /// The primary compositing option. Primary(A), /// The secondary (or fallback) compositing option. Secondary(B), } /// A surface `A` with a fallback strategy `B`. /// /// It works analogously to [`Renderer`]. #[derive(Debug)] pub enum Surface<A, B> { /// The primary surface option. Primary(A), /// The secondary (or fallback) surface option. Secondary(B), } impl<A, B> graphics::Compositor for Compositor<A, B> where A: graphics::Compositor, B: graphics::Compositor, { type Renderer = Renderer<A::Renderer, B::Renderer>; type Surface = Surface<A::Surface, B::Surface>; async fn with_backend( settings: graphics::Settings, display: impl compositor::Display + Clone, compatible_window: impl compositor::Window + Clone, shell: Shell, backend: Option<&str>, ) -> Result<Self, graphics::Error> { use std::env; let backends = backend .map(str::to_owned) .or_else(|| env::var("ICED_BACKEND").ok()); let mut candidates: Vec<_> = backends .map(|backends| { backends .split(',') .filter(|candidate| !candidate.is_empty()) .map(str::to_owned) .map(Some) .collect() }) .unwrap_or_default(); if candidates.is_empty() { candidates.push(None); } let mut errors = vec![]; for backend in candidates.iter().map(Option::as_deref) { match A::with_backend( settings, display.clone(), compatible_window.clone(), shell.clone(), backend, ) .await { Ok(compositor) => return Ok(Self::Primary(compositor)), Err(error) => { errors.push(error); } } match B::with_backend( settings, display.clone(), compatible_window.clone(), shell.clone(), backend, ) .await { Ok(compositor) => return Ok(Self::Secondary(compositor)), Err(error) => { errors.push(error); } } } Err(graphics::Error::List(errors)) } fn create_renderer(&self) -> Self::Renderer { match self { Self::Primary(compositor) => Renderer::Primary(compositor.create_renderer()), Self::Secondary(compositor) => Renderer::Secondary(compositor.create_renderer()), } } fn create_surface<W: compositor::Window + Clone>( &mut self, window: W, width: u32, height: u32, ) -> Self::Surface { match self { Self::Primary(compositor) => { Surface::Primary(compositor.create_surface(window, width, height)) } Self::Secondary(compositor) => { Surface::Secondary(compositor.create_surface(window, width, height)) } } } fn configure_surface(&mut self, surface: &mut Self::Surface, width: u32, height: u32) { match (self, surface) { (Self::Primary(compositor), Surface::Primary(surface)) => { compositor.configure_surface(surface, width, height); } (Self::Secondary(compositor), Surface::Secondary(surface)) => { compositor.configure_surface(surface, width, height); } _ => unreachable!(), } } fn load_font(&mut self, font: Cow<'static, [u8]>) { delegate!(self, compositor, compositor.load_font(font)); } fn information(&self) -> compositor::Information { delegate!(self, compositor, compositor.information()) } fn present( &mut self, renderer: &mut Self::Renderer, surface: &mut Self::Surface, viewport: &graphics::Viewport, background_color: Color, on_pre_present: impl FnOnce(), ) -> Result<(), compositor::SurfaceError> { match (self, renderer, surface) { (Self::Primary(compositor), Renderer::Primary(renderer), Surface::Primary(surface)) => { compositor.present( renderer, surface, viewport, background_color, on_pre_present, ) } ( Self::Secondary(compositor), Renderer::Secondary(renderer), Surface::Secondary(surface), ) => compositor.present( renderer, surface, viewport, background_color, on_pre_present, ), _ => unreachable!(), } } fn screenshot( &mut self, renderer: &mut Self::Renderer, viewport: &graphics::Viewport, background_color: Color, ) -> Vec<u8> { match (self, renderer) { (Self::Primary(compositor), Renderer::Primary(renderer)) => { compositor.screenshot(renderer, viewport, background_color) } (Self::Secondary(compositor), Renderer::Secondary(renderer)) => { compositor.screenshot(renderer, viewport, background_color) } _ => unreachable!(), } } } #[cfg(feature = "wgpu-bare")] impl<A, B> iced_wgpu::primitive::Renderer for Renderer<A, B> where A: iced_wgpu::primitive::Renderer, B: core::Renderer, { fn draw_primitive(&mut self, bounds: Rectangle, primitive: impl iced_wgpu::Primitive) { match self { Self::Primary(renderer) => { renderer.draw_primitive(bounds, primitive); } Self::Secondary(_) => { log::warn!("Custom shader primitive is not supported with this renderer."); } } } } #[cfg(feature = "geometry")] mod geometry { use super::Renderer; use crate::core::{Point, Radians, Rectangle, Size, Svg, Vector}; use crate::graphics::cache::{self, Cached}; use crate::graphics::geometry::{self, Fill, Image, Path, Stroke, Text}; impl<A, B> geometry::Renderer for Renderer<A, B> where A: geometry::Renderer, B: geometry::Renderer, { type Geometry = Geometry<A::Geometry, B::Geometry>; type Frame = Frame<A::Frame, B::Frame>; fn new_frame(&self, bounds: Rectangle) -> Self::Frame { match self { Self::Primary(renderer) => Frame::Primary(renderer.new_frame(bounds)), Self::Secondary(renderer) => Frame::Secondary(renderer.new_frame(bounds)), } } fn draw_geometry(&mut self, geometry: Self::Geometry) { match (self, geometry) { (Self::Primary(renderer), Geometry::Primary(geometry)) => { renderer.draw_geometry(geometry); } (Self::Secondary(renderer), Geometry::Secondary(geometry)) => { renderer.draw_geometry(geometry); } _ => unreachable!(), } } } #[derive(Debug, Clone)] pub enum Geometry<A, B> { Primary(A), Secondary(B), } impl<A, B> Cached for Geometry<A, B> where A: Cached, B: Cached, { type Cache = Geometry<A::Cache, B::Cache>; fn load(cache: &Self::Cache) -> Self { match cache { Geometry::Primary(cache) => Self::Primary(A::load(cache)), Geometry::Secondary(cache) => Self::Secondary(B::load(cache)), } } fn cache(self, group: cache::Group, previous: Option<Self::Cache>) -> Self::Cache { match (self, previous) { (Self::Primary(geometry), Some(Geometry::Primary(previous))) => { Geometry::Primary(geometry.cache(group, Some(previous))) } (Self::Primary(geometry), None) => Geometry::Primary(geometry.cache(group, None)), (Self::Secondary(geometry), Some(Geometry::Secondary(previous))) => { Geometry::Secondary(geometry.cache(group, Some(previous))) } (Self::Secondary(geometry), None) => { Geometry::Secondary(geometry.cache(group, None)) } _ => unreachable!(), } } } #[derive(Debug)] pub enum Frame<A, B> { Primary(A), Secondary(B), } impl<A, B> geometry::frame::Backend for Frame<A, B> where A: geometry::frame::Backend, B: geometry::frame::Backend, { type Geometry = Geometry<A::Geometry, B::Geometry>; fn width(&self) -> f32 { delegate!(self, frame, frame.width()) } fn height(&self) -> f32 { delegate!(self, frame, frame.height()) } fn size(&self) -> Size { delegate!(self, frame, frame.size()) } fn center(&self) -> Point { delegate!(self, frame, frame.center()) } fn fill(&mut self, path: &Path, fill: impl Into<Fill>) { delegate!(self, frame, frame.fill(path, fill)); } fn fill_rectangle(&mut self, top_left: Point, size: Size, fill: impl Into<Fill>) { delegate!(self, frame, frame.fill_rectangle(top_left, size, fill)); } fn stroke<'a>(&mut self, path: &Path, stroke: impl Into<Stroke<'a>>) { delegate!(self, frame, frame.stroke(path, stroke)); } fn stroke_rectangle<'a>( &mut self, top_left: Point, size: Size, stroke: impl Into<Stroke<'a>>, ) { delegate!(self, frame, frame.stroke_rectangle(top_left, size, stroke)); } fn stroke_text<'a>(&mut self, text: impl Into<Text>, stroke: impl Into<Stroke<'a>>) { delegate!(self, frame, frame.stroke_text(text, stroke)); } fn fill_text(&mut self, text: impl Into<Text>) { delegate!(self, frame, frame.fill_text(text)); } fn draw_image(&mut self, bounds: Rectangle, image: impl Into<Image>) { delegate!(self, frame, frame.draw_image(bounds, image)); } fn draw_svg(&mut self, bounds: Rectangle, svg: impl Into<Svg>) { delegate!(self, frame, frame.draw_svg(bounds, svg)); } fn push_transform(&mut self) { delegate!(self, frame, frame.push_transform()); } fn pop_transform(&mut self) { delegate!(self, frame, frame.pop_transform()); } fn draft(&mut self, bounds: Rectangle) -> Self { match self { Self::Primary(frame) => Self::Primary(frame.draft(bounds)), Self::Secondary(frame) => Self::Secondary(frame.draft(bounds)), } } fn paste(&mut self, frame: Self) { match (self, frame) { (Self::Primary(target), Self::Primary(source)) => { target.paste(source); } (Self::Secondary(target), Self::Secondary(source)) => { target.paste(source); } _ => unreachable!(), } } fn translate(&mut self, translation: Vector) { delegate!(self, frame, frame.translate(translation)); } fn rotate(&mut self, angle: impl Into<Radians>) { delegate!(self, frame, frame.rotate(angle)); } fn scale(&mut self, scale: impl Into<f32>) { delegate!(self, frame, frame.scale(scale)); } fn scale_nonuniform(&mut self, scale: impl Into<Vector>) { delegate!(self, frame, frame.scale_nonuniform(scale)); } fn into_geometry(self) -> Self::Geometry { match self { Frame::Primary(frame) => Geometry::Primary(frame.into_geometry()), Frame::Secondary(frame) => Geometry::Secondary(frame.into_geometry()), } } } } impl<A, B> renderer::Headless for Renderer<A, B> where A: renderer::Headless, B: renderer::Headless, { async fn new( default_font: Font, default_text_size: Pixels, backend: Option<&str>, ) -> Option<Self> { if let Some(renderer) = A::new(default_font, default_text_size, backend).await { return Some(Self::Primary(renderer)); } B::new(default_font, default_text_size, backend) .await .map(Self::Secondary) } fn name(&self) -> String { delegate!(self, renderer, renderer.name()) } fn screenshot( &mut self, size: Size<u32>, scale_factor: f32, background_color: Color, ) -> Vec<u8> { match self { crate::fallback::Renderer::Primary(renderer) => { renderer.screenshot(size, scale_factor, background_color) } crate::fallback::Renderer::Secondary(renderer) => { renderer.screenshot(size, scale_factor, background_color) } } } } impl<A, B> compositor::Default for Renderer<A, B> where A: compositor::Default, B: compositor::Default, { type Compositor = Compositor<A::Compositor, B::Compositor>; }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/devtools/src/lib.rs
devtools/src/lib.rs
#![allow(missing_docs)] use iced_debug as debug; use iced_program as program; use iced_program::runtime; use iced_program::runtime::futures; use iced_widget as widget; use iced_widget::core; mod comet; mod time_machine; use crate::core::border; use crate::core::keyboard; use crate::core::theme::{self, Theme}; use crate::core::time::seconds; use crate::core::window; use crate::core::{Alignment::Center, Color, Element, Font, Length::Fill, Settings}; use crate::futures::Subscription; use crate::program::Program; use crate::program::message; use crate::runtime::task::{self, Task}; use crate::time_machine::TimeMachine; use crate::widget::{ bottom_right, button, center, column, container, opaque, row, scrollable, space, stack, text, themer, }; use std::fmt; use std::thread; pub fn attach<P: Program + 'static>(program: P) -> Attach<P> { Attach { program } } /// A [`Program`] with some devtools attached to it. #[derive(Debug)] pub struct Attach<P> { /// The original [`Program`] managed by these devtools. pub program: P, } impl<P> Program for Attach<P> where P: Program + 'static, P::Message: std::fmt::Debug + message::MaybeClone, { type State = DevTools<P>; type Message = Event<P>; type Theme = P::Theme; type Renderer = P::Renderer; type Executor = P::Executor; fn name() -> &'static str { P::name() } fn settings(&self) -> Settings { self.program.settings() } fn window(&self) -> Option<window::Settings> { self.program.window() } fn boot(&self) -> (Self::State, Task<Self::Message>) { let (state, boot) = self.program.boot(); let (devtools, task) = DevTools::new(state); ( devtools, Task::batch([boot.map(Event::Program), task.map(Event::Message)]), ) } fn update(&self, state: &mut Self::State, message: Self::Message) -> Task<Self::Message> { state.update(&self.program, message) } fn view<'a>( &self, state: &'a Self::State, window: window::Id, ) -> Element<'a, Self::Message, Self::Theme, Self::Renderer> { state.view(&self.program, window) } fn title(&self, state: &Self::State, window: window::Id) -> String { state.title(&self.program, window) } fn subscription(&self, state: &Self::State) -> Subscription<Self::Message> { state.subscription(&self.program) } fn theme(&self, state: &Self::State, window: window::Id) -> Option<Self::Theme> { state.theme(&self.program, window) } fn style(&self, state: &Self::State, theme: &Self::Theme) -> theme::Style { state.style(&self.program, theme) } fn scale_factor(&self, state: &Self::State, window: window::Id) -> f32 { state.scale_factor(&self.program, window) } } /// The state of the devtools. pub struct DevTools<P> where P: Program, { state: P::State, show_notification: bool, time_machine: TimeMachine<P>, mode: Mode, } #[derive(Debug, Clone)] pub enum Message { HideNotification, ToggleComet, CometLaunched(comet::launch::Result), InstallComet, Installing(comet::install::Result), CancelSetup, } enum Mode { Hidden, Setup(Setup), } enum Setup { Idle { goal: Goal }, Running { logs: Vec<String> }, } enum Goal { Installation, Update { revision: Option<String> }, } impl<P> DevTools<P> where P: Program + 'static, P::Message: std::fmt::Debug + message::MaybeClone, { pub fn new(state: P::State) -> (Self, Task<Message>) { ( Self { state, mode: Mode::Hidden, show_notification: true, time_machine: TimeMachine::new(), }, Task::batch([task::blocking(|mut sender| { thread::sleep(seconds(2)); let _ = sender.try_send(()); }) .map(|_| Message::HideNotification)]), ) } pub fn title(&self, program: &P, window: window::Id) -> String { program.title(&self.state, window) } pub fn update(&mut self, program: &P, event: Event<P>) -> Task<Event<P>> { match event { Event::Message(message) => match message { Message::HideNotification => { self.show_notification = false; Task::none() } Message::ToggleComet => { if let Mode::Setup(setup) = &self.mode { if matches!(setup, Setup::Idle { .. }) { self.mode = Mode::Hidden; } Task::none() } else if debug::quit() { Task::none() } else { comet::launch() .map(Message::CometLaunched) .map(Event::Message) } } Message::CometLaunched(Ok(())) => Task::none(), Message::CometLaunched(Err(error)) => { match error { comet::launch::Error::NotFound => { self.mode = Mode::Setup(Setup::Idle { goal: Goal::Installation, }); } comet::launch::Error::Outdated { revision } => { self.mode = Mode::Setup(Setup::Idle { goal: Goal::Update { revision }, }); } comet::launch::Error::IoFailed(error) => { log::error!("comet failed to run: {error}"); } } Task::none() } Message::InstallComet => { self.mode = Mode::Setup(Setup::Running { logs: Vec::new() }); comet::install() .map(Message::Installing) .map(Event::Message) } Message::Installing(Ok(installation)) => { let Mode::Setup(Setup::Running { logs }) = &mut self.mode else { return Task::none(); }; match installation { comet::install::Event::Logged(log) => { logs.push(log); Task::none() } comet::install::Event::Finished => { self.mode = Mode::Hidden; comet::launch().discard() } } } Message::Installing(Err(error)) => { let Mode::Setup(Setup::Running { logs }) = &mut self.mode else { return Task::none(); }; match error { comet::install::Error::ProcessFailed(status) => { logs.push(format!("process failed with {status}")); } comet::install::Error::IoFailed(error) => { logs.push(error.to_string()); } } Task::none() } Message::CancelSetup => { self.mode = Mode::Hidden; Task::none() } }, Event::Program(message) => { self.time_machine.push(&message); if self.time_machine.is_rewinding() { debug::enable(); } let span = debug::update(&message); let task = program.update(&mut self.state, message); debug::tasks_spawned(task.units()); span.finish(); if self.time_machine.is_rewinding() { debug::disable(); } task.map(Event::Program) } Event::Command(command) => { match command { debug::Command::RewindTo { message } => { self.time_machine.rewind(program, message); } debug::Command::GoLive => { self.time_machine.go_to_present(); } } Task::none() } Event::Discard => Task::none(), } } pub fn view( &self, program: &P, window: window::Id, ) -> Element<'_, Event<P>, P::Theme, P::Renderer> { let state = self.state(); let view = { let view = program.view(state, window); if self.time_machine.is_rewinding() { view.map(|_| Event::Discard) } else { view.map(Event::Program) } }; let theme = || { program .theme(state, window) .as_ref() .and_then(theme::Base::palette) .map(|palette| Theme::custom("iced devtools", palette)) }; let setup = if let Mode::Setup(setup) = &self.mode { let stage: Element<'_, _, Theme, P::Renderer> = match setup { Setup::Idle { goal } => self::setup(goal), Setup::Running { logs } => installation(logs), }; let setup = center( container(stage) .padding(20) .max_width(500) .style(container::bordered_box), ) .padding(10) .style(|_theme| container::Style::default().background(Color::BLACK.scale_alpha(0.8))); Some(themer(theme(), opaque(setup).map(Event::Message))) } else { None }; let notification = self .show_notification .then(|| text("Press F12 to open debug metrics")) .or_else(|| { debug::is_stale() .then(|| text("Types have changed. Restart to re-enable hotpatching.")) }) .map(|notification| { themer( theme(), bottom_right(opaque( container(notification).padding(10).style(container::dark), )), ) }); stack![view, setup, notification] .width(Fill) .height(Fill) .into() } pub fn subscription(&self, program: &P) -> Subscription<Event<P>> { let subscription = program.subscription(&self.state).map(Event::Program); debug::subscriptions_tracked(subscription.units()); let hotkeys = futures::keyboard::listen() .filter_map(|event| match event { keyboard::Event::KeyPressed { modified_key: keyboard::Key::Named(keyboard::key::Named::F12), .. } => Some(Message::ToggleComet), _ => None, }) .map(Event::Message); let commands = debug::commands().map(Event::Command); Subscription::batch([subscription, hotkeys, commands]) } pub fn theme(&self, program: &P, window: window::Id) -> Option<P::Theme> { program.theme(self.state(), window) } pub fn style(&self, program: &P, theme: &P::Theme) -> theme::Style { program.style(self.state(), theme) } pub fn scale_factor(&self, program: &P, window: window::Id) -> f32 { program.scale_factor(self.state(), window) } pub fn state(&self) -> &P::State { self.time_machine.state().unwrap_or(&self.state) } } pub enum Event<P> where P: Program, { Message(Message), Program(P::Message), Command(debug::Command), Discard, } impl<P> fmt::Debug for Event<P> where P: Program, P::Message: std::fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Message(message) => message.fmt(f), Self::Program(message) => message.fmt(f), Self::Command(command) => command.fmt(f), Self::Discard => f.write_str("Discard"), } } } fn setup<Renderer>(goal: &Goal) -> Element<'_, Message, Theme, Renderer> where Renderer: program::Renderer + 'static, { let controls = row![ button(text("Cancel").center().width(Fill)) .width(100) .on_press(Message::CancelSetup) .style(button::danger), space::horizontal(), button( text(match goal { Goal::Installation => "Install", Goal::Update { .. } => "Update", }) .center() .width(Fill) ) .width(100) .on_press(Message::InstallComet) .style(button::success), ]; let command = container( text!( "cargo install --locked \\ --git https://github.com/iced-rs/comet.git \\ --rev {}", comet::COMPATIBLE_REVISION ) .size(14) .font(Font::MONOSPACE), ) .width(Fill) .padding(5) .style(container::dark); Element::from(match goal { Goal::Installation => column![ text("comet is not installed!").size(20), "In order to display performance \ metrics, the comet debugger must \ be installed in your system.", "The comet debugger is an official \ companion tool that helps you debug \ your iced applications.", column![ "Do you wish to install it with the \ following command?", command ] .spacing(10), controls, ] .spacing(20), Goal::Update { revision } => { let comparison = column![ row![ "Installed revision:", space::horizontal(), inline_code(revision.as_deref().unwrap_or("Unknown")) ] .align_y(Center), row![ "Compatible revision:", space::horizontal(), inline_code(comet::COMPATIBLE_REVISION), ] .align_y(Center) ] .spacing(5); column![ text("comet is out of date!").size(20), comparison, column![ "Do you wish to update it with the following \ command?", command ] .spacing(10), controls, ] .spacing(20) } }) } fn installation<'a, Renderer>(logs: &'a [String]) -> Element<'a, Message, Theme, Renderer> where Renderer: program::Renderer + 'a, { column![ text("Installing comet...").size(20), container( scrollable( column( logs.iter() .map(|log| { text(log).size(12).font(Font::MONOSPACE).into() }) ) .spacing(3), ) .spacing(10) .width(Fill) .height(300) .anchor_bottom(), ) .padding(10) .style(container::dark) ] .spacing(20) .into() } fn inline_code<'a, Renderer>( code: impl text::IntoFragment<'a>, ) -> Element<'a, Message, Theme, Renderer> where Renderer: program::Renderer + 'a, { container(text(code).size(12).font(Font::MONOSPACE)) .style(|_theme| { container::Style::default() .background(Color::BLACK) .border(border::rounded(2)) }) .padding([2, 4]) .into() }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/devtools/src/time_machine.rs
devtools/src/time_machine.rs
use crate::Program; #[cfg(feature = "time-travel")] pub struct TimeMachine<P> where P: Program, { state: Option<P::State>, messages: Vec<P::Message>, } #[cfg(feature = "time-travel")] impl<P> TimeMachine<P> where P: Program, P::Message: Clone, { pub fn new() -> Self { Self { state: None, messages: Vec::new(), } } pub fn is_rewinding(&self) -> bool { self.state.is_some() } pub fn push(&mut self, message: &P::Message) { self.messages.push(message.clone()); } pub fn rewind(&mut self, program: &P, message: usize) { crate::debug::disable(); let (mut state, _) = program.boot(); if message < self.messages.len() { // TODO: Run concurrently (?) for message in &self.messages[0..message] { let _ = program.update(&mut state, message.clone()); } } self.state = Some(state); } pub fn go_to_present(&mut self) { self.state = None; crate::debug::enable(); } pub fn state(&self) -> Option<&P::State> { self.state.as_ref() } } #[cfg(not(feature = "time-travel"))] pub struct TimeMachine<P> where P: Program, { _program: std::marker::PhantomData<P>, } #[cfg(not(feature = "time-travel"))] impl<P> TimeMachine<P> where P: Program, { pub fn new() -> Self { Self { _program: std::marker::PhantomData, } } pub fn is_rewinding(&self) -> bool { false } pub fn push(&mut self, _message: &P::Message) {} pub fn rewind(&mut self, _program: &P, _message: usize) {} pub fn go_to_present(&mut self) {} pub fn state(&self) -> Option<&P::State> { None } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/devtools/src/comet.rs
devtools/src/comet.rs
use crate::runtime::task::{self, Task}; use std::process; pub const COMPATIBLE_REVISION: &str = "3f75f3240edc1719df584810337bc7df010327d8"; pub fn launch() -> Task<launch::Result> { task::try_blocking(|mut sender| { let cargo_install = process::Command::new("cargo") .args(["install", "--list"]) .output()?; let installed_packages = String::from_utf8_lossy(&cargo_install.stdout); for line in installed_packages.lines() { if !line.starts_with("iced_comet ") { continue; } let Some((_, revision)) = line.rsplit_once("?rev=") else { return Err(launch::Error::Outdated { revision: None }); }; let Some((revision, _)) = revision.rsplit_once("#") else { return Err(launch::Error::Outdated { revision: None }); }; if revision != COMPATIBLE_REVISION { return Err(launch::Error::Outdated { revision: Some(revision.to_owned()), }); } let _ = process::Command::new("iced_comet") .stdin(process::Stdio::null()) .stdout(process::Stdio::null()) .stderr(process::Stdio::null()) .spawn()?; let _ = sender.try_send(()); return Ok(()); } Err(launch::Error::NotFound) }) } pub fn install() -> Task<install::Result> { task::try_blocking(|mut sender| { use std::io::{BufRead, BufReader}; use std::process::{Command, Stdio}; let mut install = Command::new("cargo") .args([ "install", "--locked", "--git", "https://github.com/iced-rs/comet.git", "--rev", COMPATIBLE_REVISION, ]) .stdin(Stdio::null()) .stdout(Stdio::null()) .stderr(Stdio::piped()) .spawn()?; let mut stderr = BufReader::new(install.stderr.take().expect("stderr must be piped")); let mut log = String::new(); while let Ok(n) = stderr.read_line(&mut log) { if n == 0 { let status = install.wait()?; if status.success() { break; } else { return Err(install::Error::ProcessFailed(status)); } } let _ = sender.try_send(install::Event::Logged(log.trim_end().to_owned())); log.clear(); } let _ = sender.try_send(install::Event::Finished); Ok(()) }) } pub mod launch { use std::io; use std::sync::Arc; pub type Result = std::result::Result<(), Error>; #[derive(Debug, Clone)] pub enum Error { NotFound, Outdated { revision: Option<String> }, IoFailed(Arc<io::Error>), } impl From<io::Error> for Error { fn from(error: io::Error) -> Self { Self::IoFailed(Arc::new(error)) } } } pub mod install { use std::io; use std::process; use std::sync::Arc; pub type Result = std::result::Result<Event, Error>; #[derive(Debug, Clone)] pub enum Event { Logged(String), Finished, } #[derive(Debug, Clone)] pub enum Error { ProcessFailed(process::ExitStatus), IoFailed(Arc<io::Error>), } impl From<io::Error> for Error { fn from(error: io::Error) -> Self { Self::IoFailed(Arc::new(error)) } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/tiny_skia/src/settings.rs
tiny_skia/src/settings.rs
use crate::core::{Font, Pixels}; use crate::graphics; /// The settings of a [`Compositor`]. /// /// [`Compositor`]: crate::window::Compositor #[derive(Debug, Clone, Copy, PartialEq)] pub struct Settings { /// The default [`Font`] to use. pub default_font: Font, /// The default size of text. /// /// By default, it will be set to `16.0`. pub default_text_size: Pixels, } impl Default for Settings { fn default() -> Settings { Settings { default_font: Font::default(), default_text_size: Pixels(16.0), } } } impl From<graphics::Settings> for Settings { fn from(settings: graphics::Settings) -> Self { Self { default_font: settings.default_font, default_text_size: settings.default_text_size, } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/tiny_skia/src/engine.rs
tiny_skia/src/engine.rs
use crate::Primitive; use crate::core::renderer::Quad; use crate::core::{Background, Color, Gradient, Rectangle, Size, Transformation, Vector}; use crate::graphics::{Image, Text}; use crate::text; #[derive(Debug)] pub struct Engine { text_pipeline: text::Pipeline, #[cfg(feature = "image")] pub(crate) raster_pipeline: crate::raster::Pipeline, #[cfg(feature = "svg")] pub(crate) vector_pipeline: crate::vector::Pipeline, } impl Engine { pub fn new() -> Self { Self { text_pipeline: text::Pipeline::new(), #[cfg(feature = "image")] raster_pipeline: crate::raster::Pipeline::new(), #[cfg(feature = "svg")] vector_pipeline: crate::vector::Pipeline::new(), } } pub fn draw_quad( &mut self, quad: &Quad, background: &Background, transformation: Transformation, pixels: &mut tiny_skia::PixmapMut<'_>, clip_mask: &mut tiny_skia::Mask, clip_bounds: Rectangle, ) { let physical_bounds = quad.bounds * transformation; if !clip_bounds.intersects(&physical_bounds) { return; } let clip_mask = (!physical_bounds.is_within(&clip_bounds)).then_some(clip_mask as &_); let transform = into_transform(transformation); // Make sure the border radius is not larger than the bounds let border_width = quad .border .width .min(quad.bounds.width / 2.0) .min(quad.bounds.height / 2.0); let mut fill_border_radius = <[f32; 4]>::from(quad.border.radius); for radius in &mut fill_border_radius { *radius = (*radius) .min(quad.bounds.width / 2.0) .min(quad.bounds.height / 2.0); } let path = rounded_rectangle(quad.bounds, fill_border_radius); let shadow = quad.shadow; if shadow.color.a > 0.0 { let shadow_bounds = Rectangle { x: quad.bounds.x + shadow.offset.x - shadow.blur_radius, y: quad.bounds.y + shadow.offset.y - shadow.blur_radius, width: quad.bounds.width + shadow.blur_radius * 2.0, height: quad.bounds.height + shadow.blur_radius * 2.0, } * transformation; let radii = fill_border_radius .into_iter() .map(|radius| radius * transformation.scale_factor()) .collect::<Vec<_>>(); let (x, y, width, height) = ( shadow_bounds.x as u32, shadow_bounds.y as u32, shadow_bounds.width as u32, shadow_bounds.height as u32, ); let half_width = physical_bounds.width / 2.0; let half_height = physical_bounds.height / 2.0; let colors = (y..y + height) .flat_map(|y| (x..x + width).map(move |x| (x as f32, y as f32))) .filter_map(|(x, y)| { tiny_skia::Size::from_wh(half_width, half_height).map(|size| { let shadow_distance = rounded_box_sdf( Vector::new( x - physical_bounds.position().x - (shadow.offset.x * transformation.scale_factor()) - half_width, y - physical_bounds.position().y - (shadow.offset.y * transformation.scale_factor()) - half_height, ), size, &radii, ) .max(0.0); let shadow_alpha = 1.0 - smoothstep( -shadow.blur_radius * transformation.scale_factor(), shadow.blur_radius * transformation.scale_factor(), shadow_distance, ); let mut color = into_color(shadow.color); color.apply_opacity(shadow_alpha); color.to_color_u8().premultiply() }) }) .collect(); if let Some(pixmap) = tiny_skia::IntSize::from_wh(width, height) .and_then(|size| tiny_skia::Pixmap::from_vec(bytemuck::cast_vec(colors), size)) { pixels.draw_pixmap( x as i32, y as i32, pixmap.as_ref(), &tiny_skia::PixmapPaint::default(), tiny_skia::Transform::default(), None, ); } } pixels.fill_path( &path, &tiny_skia::Paint { shader: match background { Background::Color(color) => tiny_skia::Shader::SolidColor(into_color(*color)), Background::Gradient(Gradient::Linear(linear)) => { let (start, end) = linear.angle.to_distance(&quad.bounds); let stops: Vec<tiny_skia::GradientStop> = linear .stops .into_iter() .flatten() .map(|stop| { tiny_skia::GradientStop::new( stop.offset, tiny_skia::Color::from_rgba( stop.color.b, stop.color.g, stop.color.r, stop.color.a, ) .expect("Create color"), ) }) .collect(); tiny_skia::LinearGradient::new( tiny_skia::Point { x: start.x, y: start.y, }, tiny_skia::Point { x: end.x, y: end.y }, if stops.is_empty() { vec![tiny_skia::GradientStop::new(0.0, tiny_skia::Color::BLACK)] } else { stops }, tiny_skia::SpreadMode::Pad, tiny_skia::Transform::identity(), ) .expect("Create linear gradient") } }, anti_alias: true, ..tiny_skia::Paint::default() }, tiny_skia::FillRule::EvenOdd, transform, clip_mask, ); if border_width > 0.0 { // Border path is offset by half the border width let border_bounds = Rectangle { x: quad.bounds.x + border_width / 2.0, y: quad.bounds.y + border_width / 2.0, width: quad.bounds.width - border_width, height: quad.bounds.height - border_width, }; // Make sure the border radius is correct let mut border_radius = <[f32; 4]>::from(quad.border.radius); let mut is_simple_border = true; for radius in &mut border_radius { *radius = if *radius == 0.0 { // Path should handle this fine 0.0 } else if *radius > border_width / 2.0 { *radius - border_width / 2.0 } else { is_simple_border = false; 0.0 } .min(border_bounds.width / 2.0) .min(border_bounds.height / 2.0); } // Stroking a path works well in this case if is_simple_border { let border_path = rounded_rectangle(border_bounds, border_radius); pixels.stroke_path( &border_path, &tiny_skia::Paint { shader: tiny_skia::Shader::SolidColor(into_color(quad.border.color)), anti_alias: true, ..tiny_skia::Paint::default() }, &tiny_skia::Stroke { width: border_width, ..tiny_skia::Stroke::default() }, transform, clip_mask, ); } else { // Draw corners that have too small border radii as having no border radius, // but mask them with the rounded rectangle with the correct border radius. let mut temp_pixmap = tiny_skia::Pixmap::new(quad.bounds.width as u32, quad.bounds.height as u32) .unwrap(); let mut quad_mask = tiny_skia::Mask::new(quad.bounds.width as u32, quad.bounds.height as u32) .unwrap(); let zero_bounds = Rectangle { x: 0.0, y: 0.0, width: quad.bounds.width, height: quad.bounds.height, }; let path = rounded_rectangle(zero_bounds, fill_border_radius); quad_mask.fill_path(&path, tiny_skia::FillRule::EvenOdd, true, transform); let path_bounds = Rectangle { x: border_width / 2.0, y: border_width / 2.0, width: quad.bounds.width - border_width, height: quad.bounds.height - border_width, }; let border_radius_path = rounded_rectangle(path_bounds, border_radius); temp_pixmap.stroke_path( &border_radius_path, &tiny_skia::Paint { shader: tiny_skia::Shader::SolidColor(into_color(quad.border.color)), anti_alias: true, ..tiny_skia::Paint::default() }, &tiny_skia::Stroke { width: border_width, ..tiny_skia::Stroke::default() }, transform, Some(&quad_mask), ); pixels.draw_pixmap( quad.bounds.x as i32, quad.bounds.y as i32, temp_pixmap.as_ref(), &tiny_skia::PixmapPaint::default(), transform, clip_mask, ); } } } pub fn draw_text( &mut self, text: &Text, transformation: Transformation, pixels: &mut tiny_skia::PixmapMut<'_>, clip_mask: &mut tiny_skia::Mask, clip_bounds: Rectangle, ) { match text { Text::Paragraph { paragraph, position, color, clip_bounds: local_clip_bounds, transformation: local_transformation, } => { let transformation = transformation * *local_transformation; let Some(clip_bounds) = clip_bounds.intersection(&(*local_clip_bounds * transformation)) else { return; }; let physical_bounds = Rectangle::new(*position, paragraph.min_bounds) * transformation; if !clip_bounds.intersects(&physical_bounds) { return; } let clip_mask = match physical_bounds.is_within(&clip_bounds) { true => None, false => { adjust_clip_mask(clip_mask, clip_bounds); Some(clip_mask as &_) } }; self.text_pipeline.draw_paragraph( paragraph, *position, *color, pixels, clip_mask, transformation, ); } Text::Editor { editor, position, color, clip_bounds: local_clip_bounds, transformation: local_transformation, } => { let transformation = transformation * *local_transformation; let Some(clip_bounds) = clip_bounds.intersection(&(*local_clip_bounds * transformation)) else { return; }; let physical_bounds = Rectangle::new(*position, editor.bounds) * transformation; if !clip_bounds.intersects(&physical_bounds) { return; } let clip_mask = match physical_bounds.is_within(&clip_bounds) { true => None, false => { adjust_clip_mask(clip_mask, clip_bounds); Some(clip_mask as &_) } }; self.text_pipeline.draw_editor( editor, *position, *color, pixels, clip_mask, transformation, ); } Text::Cached { content, bounds, color, size, line_height, font, align_x, align_y, shaping, clip_bounds: local_clip_bounds, } => { let physical_bounds = *local_clip_bounds * transformation; if !clip_bounds.intersects(&physical_bounds) { return; } let clip_mask = match physical_bounds.is_within(&clip_bounds) { true => None, false => { adjust_clip_mask(clip_mask, clip_bounds); Some(clip_mask as &_) } }; self.text_pipeline.draw_cached( content, *bounds, *color, *size, *line_height, *font, *align_x, *align_y, *shaping, pixels, clip_mask, transformation, ); } Text::Raw { raw, transformation: local_transformation, } => { let Some(buffer) = raw.buffer.upgrade() else { return; }; let transformation = transformation * *local_transformation; let (width, height) = buffer.size(); let physical_bounds = Rectangle::new( raw.position, Size::new( width.unwrap_or(clip_bounds.width), height.unwrap_or(clip_bounds.height), ), ) * transformation; if !clip_bounds.intersects(&physical_bounds) { return; } let clip_mask = (!physical_bounds.is_within(&clip_bounds)).then_some(clip_mask as &_); self.text_pipeline.draw_raw( &buffer, raw.position, raw.color, pixels, clip_mask, transformation, ); } } } pub fn draw_primitive( &mut self, primitive: &Primitive, transformation: Transformation, pixels: &mut tiny_skia::PixmapMut<'_>, clip_mask: &mut tiny_skia::Mask, clip_bounds: Rectangle, ) { match primitive { Primitive::Fill { path, paint, rule } => { let physical_bounds = { let bounds = path.bounds(); Rectangle { x: bounds.x(), y: bounds.y(), width: bounds.width(), height: bounds.height(), } * transformation }; if !clip_bounds.intersects(&physical_bounds) { return; } let clip_mask = (!physical_bounds.is_within(&clip_bounds)).then_some(clip_mask as &_); pixels.fill_path( path, paint, *rule, into_transform(transformation), clip_mask, ); } Primitive::Stroke { path, paint, stroke, } => { let physical_bounds = { let bounds = path.bounds(); Rectangle { x: bounds.x() - stroke.width / 2.0, y: bounds.y() - stroke.width / 2.0, width: bounds.width() + stroke.width, height: bounds.height() + stroke.width, } * transformation }; if !clip_bounds.intersects(&physical_bounds) { return; } let clip_mask = (!physical_bounds.is_within(&clip_bounds)).then_some(clip_mask as &_); pixels.stroke_path( path, paint, stroke, into_transform(transformation), clip_mask, ); } } } pub fn draw_image( &mut self, image: &Image, _transformation: Transformation, _pixels: &mut tiny_skia::PixmapMut<'_>, _clip_mask: &mut tiny_skia::Mask, _clip_bounds: Rectangle, ) { match image { #[cfg(feature = "image")] Image::Raster { image, bounds, .. } => { let physical_bounds = *bounds * _transformation; if !_clip_bounds.intersects(&physical_bounds) { return; } let clip_mask = (!physical_bounds.is_within(&_clip_bounds)).then_some(_clip_mask as &_); let center = physical_bounds.center(); let radians = f32::from(image.rotation); let transform = into_transform(_transformation).post_rotate_at( radians.to_degrees(), center.x, center.y, ); self.raster_pipeline.draw( &image.handle, image.filter_method, *bounds, image.opacity, _pixels, transform, clip_mask, ); } #[cfg(feature = "svg")] Image::Vector { svg, bounds, .. } => { let physical_bounds = *bounds * _transformation; if !_clip_bounds.intersects(&physical_bounds) { return; } let clip_mask = (!physical_bounds.is_within(&_clip_bounds)).then_some(_clip_mask as &_); let center = physical_bounds.center(); let radians = f32::from(svg.rotation); let transform = into_transform(_transformation).post_rotate_at( radians.to_degrees(), center.x, center.y, ); self.vector_pipeline.draw( &svg.handle, svg.color, *bounds, svg.opacity, _pixels, transform, clip_mask, ); } #[cfg(not(feature = "image"))] Image::Raster { .. } => { log::warn!("Unsupported primitive in `iced_tiny_skia`: {image:?}",); } #[cfg(not(feature = "svg"))] Image::Vector { .. } => { log::warn!("Unsupported primitive in `iced_tiny_skia`: {image:?}",); } } } pub fn trim(&mut self) { self.text_pipeline.trim_cache(); #[cfg(feature = "image")] self.raster_pipeline.trim_cache(); #[cfg(feature = "svg")] self.vector_pipeline.trim_cache(); } } pub fn into_color(color: Color) -> tiny_skia::Color { tiny_skia::Color::from_rgba(color.b, color.g, color.r, color.a) .expect("Convert color from iced to tiny_skia") } fn into_transform(transformation: Transformation) -> tiny_skia::Transform { let translation = transformation.translation(); tiny_skia::Transform { sx: transformation.scale_factor(), kx: 0.0, ky: 0.0, sy: transformation.scale_factor(), tx: translation.x, ty: translation.y, } } fn rounded_rectangle(bounds: Rectangle, border_radius: [f32; 4]) -> tiny_skia::Path { let [top_left, top_right, bottom_right, bottom_left] = border_radius; if top_left == 0.0 && top_right == 0.0 && bottom_right == 0.0 && bottom_left == 0.0 { return tiny_skia::PathBuilder::from_rect( tiny_skia::Rect::from_xywh(bounds.x, bounds.y, bounds.width, bounds.height) .expect("Build quad rectangle"), ); } if top_left == top_right && top_left == bottom_right && top_left == bottom_left && top_left == bounds.width / 2.0 && top_left == bounds.height / 2.0 { return tiny_skia::PathBuilder::from_circle( bounds.x + bounds.width / 2.0, bounds.y + bounds.height / 2.0, top_left, ) .expect("Build circle path"); } let mut builder = tiny_skia::PathBuilder::new(); builder.move_to(bounds.x + top_left, bounds.y); builder.line_to(bounds.x + bounds.width - top_right, bounds.y); if top_right > 0.0 { arc_to( &mut builder, bounds.x + bounds.width - top_right, bounds.y, bounds.x + bounds.width, bounds.y + top_right, top_right, ); } maybe_line_to( &mut builder, bounds.x + bounds.width, bounds.y + bounds.height - bottom_right, ); if bottom_right > 0.0 { arc_to( &mut builder, bounds.x + bounds.width, bounds.y + bounds.height - bottom_right, bounds.x + bounds.width - bottom_right, bounds.y + bounds.height, bottom_right, ); } maybe_line_to( &mut builder, bounds.x + bottom_left, bounds.y + bounds.height, ); if bottom_left > 0.0 { arc_to( &mut builder, bounds.x + bottom_left, bounds.y + bounds.height, bounds.x, bounds.y + bounds.height - bottom_left, bottom_left, ); } maybe_line_to(&mut builder, bounds.x, bounds.y + top_left); if top_left > 0.0 { arc_to( &mut builder, bounds.x, bounds.y + top_left, bounds.x + top_left, bounds.y, top_left, ); } builder.finish().expect("Build rounded rectangle path") } fn maybe_line_to(path: &mut tiny_skia::PathBuilder, x: f32, y: f32) { if path.last_point() != Some(tiny_skia::Point { x, y }) { path.line_to(x, y); } } fn arc_to( path: &mut tiny_skia::PathBuilder, x_from: f32, y_from: f32, x_to: f32, y_to: f32, radius: f32, ) { let svg_arc = kurbo::SvgArc { from: kurbo::Point::new(f64::from(x_from), f64::from(y_from)), to: kurbo::Point::new(f64::from(x_to), f64::from(y_to)), radii: kurbo::Vec2::new(f64::from(radius), f64::from(radius)), x_rotation: 0.0, large_arc: false, sweep: true, }; match kurbo::Arc::from_svg_arc(&svg_arc) { Some(arc) => { arc.to_cubic_beziers(0.1, |p1, p2, p| { path.cubic_to( p1.x as f32, p1.y as f32, p2.x as f32, p2.y as f32, p.x as f32, p.y as f32, ); }); } None => { path.line_to(x_to, y_to); } } } fn smoothstep(a: f32, b: f32, x: f32) -> f32 { let x = ((x - a) / (b - a)).clamp(0.0, 1.0); x * x * (3.0 - 2.0 * x) } fn rounded_box_sdf(to_center: Vector, size: tiny_skia::Size, radii: &[f32]) -> f32 { let radius = match (to_center.x > 0.0, to_center.y > 0.0) { (true, true) => radii[2], (true, false) => radii[1], (false, true) => radii[3], (false, false) => radii[0], }; let x = (to_center.x.abs() - size.width() + radius).max(0.0); let y = (to_center.y.abs() - size.height() + radius).max(0.0); (x.powf(2.0) + y.powf(2.0)).sqrt() - radius } pub fn adjust_clip_mask(clip_mask: &mut tiny_skia::Mask, bounds: Rectangle) { clip_mask.clear(); let path = { let mut builder = tiny_skia::PathBuilder::new(); builder.push_rect( tiny_skia::Rect::from_xywh(bounds.x, bounds.y, bounds.width, bounds.height).unwrap(), ); builder.finish().unwrap() }; clip_mask.fill_path( &path, tiny_skia::FillRule::EvenOdd, false, tiny_skia::Transform::default(), ); }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/tiny_skia/src/lib.rs
tiny_skia/src/lib.rs
#![allow(missing_docs)] #![cfg_attr(docsrs, feature(doc_cfg))] pub mod window; mod engine; mod layer; mod primitive; mod settings; mod text; #[cfg(feature = "image")] mod raster; #[cfg(feature = "svg")] mod vector; #[cfg(feature = "geometry")] pub mod geometry; use iced_debug as debug; pub use iced_graphics as graphics; pub use iced_graphics::core; pub use layer::Layer; pub use primitive::Primitive; pub use settings::Settings; #[cfg(feature = "geometry")] pub use geometry::Geometry; use crate::core::renderer; use crate::core::{Background, Color, Font, Pixels, Point, Rectangle, Size, Transformation}; use crate::engine::Engine; use crate::graphics::Viewport; use crate::graphics::compositor; use crate::graphics::text::{Editor, Paragraph}; /// A [`tiny-skia`] graphics renderer for [`iced`]. /// /// [`tiny-skia`]: https://github.com/RazrFalcon/tiny-skia /// [`iced`]: https://github.com/iced-rs/iced #[derive(Debug)] pub struct Renderer { default_font: Font, default_text_size: Pixels, layers: layer::Stack, engine: Engine, // TODO: Shared engine } impl Renderer { pub fn new(default_font: Font, default_text_size: Pixels) -> Self { Self { default_font, default_text_size, layers: layer::Stack::new(), engine: Engine::new(), } } pub fn layers(&mut self) -> &[Layer] { self.layers.flush(); self.layers.as_slice() } pub fn draw( &mut self, pixels: &mut tiny_skia::PixmapMut<'_>, clip_mask: &mut tiny_skia::Mask, viewport: &Viewport, damage: &[Rectangle], background_color: Color, ) { let scale_factor = viewport.scale_factor(); self.layers.flush(); for &damage_bounds in damage { let damage_bounds = damage_bounds * scale_factor; let path = tiny_skia::PathBuilder::from_rect( tiny_skia::Rect::from_xywh( damage_bounds.x, damage_bounds.y, damage_bounds.width, damage_bounds.height, ) .expect("Create damage rectangle"), ); pixels.fill_path( &path, &tiny_skia::Paint { shader: tiny_skia::Shader::SolidColor(engine::into_color(background_color)), anti_alias: false, blend_mode: tiny_skia::BlendMode::Source, ..Default::default() }, tiny_skia::FillRule::default(), tiny_skia::Transform::identity(), None, ); for layer in self.layers.iter() { let Some(layer_bounds) = damage_bounds.intersection(&(layer.bounds * scale_factor)) else { continue; }; engine::adjust_clip_mask(clip_mask, layer_bounds); if !layer.quads.is_empty() { let render_span = debug::render(debug::Primitive::Quad); for (quad, background) in &layer.quads { self.engine.draw_quad( quad, background, Transformation::scale(scale_factor), pixels, clip_mask, layer_bounds, ); } render_span.finish(); } if !layer.primitives.is_empty() { let render_span = debug::render(debug::Primitive::Triangle); for group in &layer.primitives { let Some(group_bounds) = (group.clip_bounds() * group.transformation() * scale_factor) .intersection(&layer_bounds) else { continue; }; engine::adjust_clip_mask(clip_mask, group_bounds); for primitive in group.as_slice() { self.engine.draw_primitive( primitive, group.transformation() * Transformation::scale(scale_factor), pixels, clip_mask, group_bounds, ); } engine::adjust_clip_mask(clip_mask, layer_bounds); } render_span.finish(); } if !layer.images.is_empty() { let render_span = debug::render(debug::Primitive::Image); for image in &layer.images { self.engine.draw_image( image, Transformation::scale(scale_factor), pixels, clip_mask, layer_bounds, ); } render_span.finish(); } if !layer.text.is_empty() { let render_span = debug::render(debug::Primitive::Image); for group in &layer.text { for text in group.as_slice() { self.engine.draw_text( text, group.transformation() * Transformation::scale(scale_factor), pixels, clip_mask, layer_bounds, ); } } render_span.finish(); } } } self.engine.trim(); } } impl core::Renderer for Renderer { fn start_layer(&mut self, bounds: Rectangle) { self.layers.push_clip(bounds); } fn end_layer(&mut self) { self.layers.pop_clip(); } fn start_transformation(&mut self, transformation: Transformation) { self.layers.push_transformation(transformation); } fn end_transformation(&mut self) { self.layers.pop_transformation(); } fn fill_quad(&mut self, quad: renderer::Quad, background: impl Into<Background>) { let (layer, transformation) = self.layers.current_mut(); layer.draw_quad(quad, background.into(), transformation); } fn allocate_image( &mut self, _handle: &core::image::Handle, callback: impl FnOnce(Result<core::image::Allocation, core::image::Error>) + Send + 'static, ) { #[cfg(feature = "image")] #[allow(unsafe_code)] // TODO: Concurrency callback(self.engine.raster_pipeline.load(_handle)); #[cfg(not(feature = "image"))] callback(Err(core::image::Error::Unsupported)); } fn hint(&mut self, _scale_factor: f32) { // TODO: No hinting supported // We'll replace `tiny-skia` with `vello_cpu` soon } fn scale_factor(&self) -> Option<f32> { None } fn reset(&mut self, new_bounds: Rectangle) { self.layers.reset(new_bounds); } } impl core::text::Renderer for Renderer { type Font = Font; type Paragraph = Paragraph; type Editor = Editor; const ICON_FONT: Font = Font::with_name("Iced-Icons"); const CHECKMARK_ICON: char = '\u{f00c}'; const ARROW_DOWN_ICON: char = '\u{e800}'; const ICED_LOGO: char = '\u{e801}'; const SCROLL_UP_ICON: char = '\u{e802}'; const SCROLL_DOWN_ICON: char = '\u{e803}'; const SCROLL_LEFT_ICON: char = '\u{e804}'; const SCROLL_RIGHT_ICON: char = '\u{e805}'; fn default_font(&self) -> Self::Font { self.default_font } fn default_size(&self) -> Pixels { self.default_text_size } fn fill_paragraph( &mut self, text: &Self::Paragraph, position: Point, color: Color, clip_bounds: Rectangle, ) { let (layer, transformation) = self.layers.current_mut(); layer.draw_paragraph(text, position, color, clip_bounds, transformation); } fn fill_editor( &mut self, editor: &Self::Editor, position: Point, color: Color, clip_bounds: Rectangle, ) { let (layer, transformation) = self.layers.current_mut(); layer.draw_editor(editor, position, color, clip_bounds, transformation); } fn fill_text( &mut self, text: core::Text, position: Point, color: Color, clip_bounds: Rectangle, ) { let (layer, transformation) = self.layers.current_mut(); layer.draw_text(text, position, color, clip_bounds, transformation); } } impl graphics::text::Renderer for Renderer { fn fill_raw(&mut self, raw: graphics::text::Raw) { let (layer, transformation) = self.layers.current_mut(); layer.draw_text_raw(raw, transformation); } } #[cfg(feature = "geometry")] impl graphics::geometry::Renderer for Renderer { type Geometry = Geometry; type Frame = geometry::Frame; fn new_frame(&self, bounds: Rectangle) -> Self::Frame { geometry::Frame::new(bounds) } fn draw_geometry(&mut self, geometry: Self::Geometry) { let (layer, transformation) = self.layers.current_mut(); match geometry { Geometry::Live { primitives, images, text, clip_bounds, } => { layer.draw_primitive_group(primitives, clip_bounds, transformation); for image in images { layer.draw_image(image, transformation); } layer.draw_text_group(text, clip_bounds, transformation); } Geometry::Cache(cache) => { layer.draw_primitive_cache(cache.primitives, cache.clip_bounds, transformation); for image in cache.images.iter() { layer.draw_image(image.clone(), transformation); } layer.draw_text_cache(cache.text, cache.clip_bounds, transformation); } } } } impl graphics::mesh::Renderer for Renderer { fn draw_mesh(&mut self, _mesh: graphics::Mesh) { log::warn!("iced_tiny_skia does not support drawing meshes"); } fn draw_mesh_cache(&mut self, _cache: iced_graphics::mesh::Cache) { log::warn!("iced_tiny_skia does not support drawing meshes"); } } #[cfg(feature = "image")] impl core::image::Renderer for Renderer { type Handle = core::image::Handle; fn load_image( &self, handle: &Self::Handle, ) -> Result<core::image::Allocation, core::image::Error> { self.engine.raster_pipeline.load(handle) } fn measure_image(&self, handle: &Self::Handle) -> Option<crate::core::Size<u32>> { self.engine.raster_pipeline.dimensions(handle) } fn draw_image(&mut self, image: core::Image, bounds: Rectangle, clip_bounds: Rectangle) { let (layer, transformation) = self.layers.current_mut(); layer.draw_raster(image, bounds, clip_bounds, transformation); } } #[cfg(feature = "svg")] impl core::svg::Renderer for Renderer { fn measure_svg(&self, handle: &core::svg::Handle) -> crate::core::Size<u32> { self.engine.vector_pipeline.viewport_dimensions(handle) } fn draw_svg(&mut self, svg: core::Svg, bounds: Rectangle, clip_bounds: Rectangle) { let (layer, transformation) = self.layers.current_mut(); layer.draw_svg(svg, bounds, clip_bounds, transformation); } } impl compositor::Default for Renderer { type Compositor = window::Compositor; } impl renderer::Headless for Renderer { async fn new( default_font: Font, default_text_size: Pixels, backend: Option<&str>, ) -> Option<Self> { if backend.is_some_and(|backend| !["tiny-skia", "tiny_skia"].contains(&backend)) { return None; } Some(Self::new(default_font, default_text_size)) } fn name(&self) -> String { "tiny-skia".to_owned() } fn screenshot( &mut self, size: Size<u32>, scale_factor: f32, background_color: Color, ) -> Vec<u8> { let viewport = Viewport::with_physical_size(size, scale_factor); window::compositor::screenshot(self, &viewport, background_color) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/tiny_skia/src/vector.rs
tiny_skia/src/vector.rs
use crate::core::svg::{Data, Handle}; use crate::core::{Color, Rectangle, Size}; use resvg::usvg; use rustc_hash::{FxHashMap, FxHashSet}; use tiny_skia::Transform; use std::cell::RefCell; use std::collections::hash_map; use std::fs; use std::panic; use std::sync::Arc; #[derive(Debug)] pub struct Pipeline { cache: RefCell<Cache>, } impl Pipeline { pub fn new() -> Self { Self { cache: RefCell::new(Cache::default()), } } pub fn viewport_dimensions(&self, handle: &Handle) -> Size<u32> { self.cache .borrow_mut() .viewport_dimensions(handle) .unwrap_or(Size::new(0, 0)) } pub fn draw( &mut self, handle: &Handle, color: Option<Color>, bounds: Rectangle, opacity: f32, pixels: &mut tiny_skia::PixmapMut<'_>, transform: Transform, clip_mask: Option<&tiny_skia::Mask>, ) { if let Some(image) = self.cache.borrow_mut().draw( handle, color, Size::new( (bounds.width * transform.sx) as u32, (bounds.height * transform.sy) as u32, ), ) { pixels.draw_pixmap( (bounds.x * transform.sx) as i32, (bounds.y * transform.sy) as i32, image, &tiny_skia::PixmapPaint { opacity, ..tiny_skia::PixmapPaint::default() }, Transform::default(), clip_mask, ); } } pub fn trim_cache(&mut self) { self.cache.borrow_mut().trim(); } } #[derive(Default)] struct Cache { trees: FxHashMap<u64, Option<resvg::usvg::Tree>>, tree_hits: FxHashSet<u64>, rasters: FxHashMap<RasterKey, tiny_skia::Pixmap>, raster_hits: FxHashSet<RasterKey>, fontdb: Option<Arc<usvg::fontdb::Database>>, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] struct RasterKey { id: u64, color: Option<[u8; 4]>, size: Size<u32>, } impl Cache { fn load(&mut self, handle: &Handle) -> Option<&usvg::Tree> { let id = handle.id(); // TODO: Reuse `cosmic-text` font database if self.fontdb.is_none() { let mut fontdb = usvg::fontdb::Database::new(); fontdb.load_system_fonts(); self.fontdb = Some(Arc::new(fontdb)); } let options = usvg::Options { fontdb: self .fontdb .as_ref() .expect("fontdb must be initialized") .clone(), ..usvg::Options::default() }; if let hash_map::Entry::Vacant(entry) = self.trees.entry(id) { let svg = match handle.data() { Data::Path(path) => fs::read_to_string(path) .ok() .and_then(|contents| usvg::Tree::from_str(&contents, &options).ok()), Data::Bytes(bytes) => usvg::Tree::from_data(bytes, &options).ok(), }; let _ = entry.insert(svg); } let _ = self.tree_hits.insert(id); self.trees.get(&id).unwrap().as_ref() } fn viewport_dimensions(&mut self, handle: &Handle) -> Option<Size<u32>> { let tree = self.load(handle)?; let size = tree.size(); Some(Size::new(size.width() as u32, size.height() as u32)) } fn draw( &mut self, handle: &Handle, color: Option<Color>, size: Size<u32>, ) -> Option<tiny_skia::PixmapRef<'_>> { if size.width == 0 || size.height == 0 { return None; } let key = RasterKey { id: handle.id(), color: color.map(Color::into_rgba8), size, }; #[allow(clippy::map_entry)] if !self.rasters.contains_key(&key) { let tree = self.load(handle)?; let mut image = tiny_skia::Pixmap::new(size.width, size.height)?; let tree_size = tree.size().to_int_size(); let target_size = if size.width > size.height { tree_size.scale_to_width(size.width) } else { tree_size.scale_to_height(size.height) }; let transform = if let Some(target_size) = target_size { let tree_size = tree_size.to_size(); let target_size = target_size.to_size(); tiny_skia::Transform::from_scale( target_size.width() / tree_size.width(), target_size.height() / tree_size.height(), ) } else { tiny_skia::Transform::default() }; // SVG rendering can panic on malformed or complex vectors. // We catch panics to prevent crashes and continue gracefully. let render = panic::catch_unwind(panic::AssertUnwindSafe(|| { resvg::render(tree, transform, &mut image.as_mut()); })); if let Err(error) = render { log::warn!("SVG rendering for {handle:?} panicked: {error:?}"); } if let Some([r, g, b, _]) = key.color { // Apply color filter for pixel in bytemuck::cast_slice_mut::<u8, u32>(image.data_mut()) { *pixel = bytemuck::cast( tiny_skia::ColorU8::from_rgba(b, g, r, (*pixel >> 24) as u8).premultiply(), ); } } else { // Swap R and B channels for `softbuffer` presentation for pixel in bytemuck::cast_slice_mut::<u8, u32>(image.data_mut()) { *pixel = *pixel & 0xFF00_FF00 | ((0x0000_00FF & *pixel) << 16) | ((0x00FF_0000 & *pixel) >> 16); } } let _ = self.rasters.insert(key, image); } let _ = self.raster_hits.insert(key); self.rasters.get(&key).map(tiny_skia::Pixmap::as_ref) } fn trim(&mut self) { self.trees.retain(|key, _| self.tree_hits.contains(key)); self.rasters.retain(|key, _| self.raster_hits.contains(key)); self.tree_hits.clear(); self.raster_hits.clear(); } } impl std::fmt::Debug for Cache { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Cache") .field("tree_hits", &self.tree_hits) .field("rasters", &self.rasters) .field("raster_hits", &self.raster_hits) .finish_non_exhaustive() } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/tiny_skia/src/geometry.rs
tiny_skia/src/geometry.rs
use crate::Primitive; use crate::core::text::LineHeight; use crate::core::{self, Pixels, Point, Radians, Rectangle, Size, Svg, Vector}; use crate::graphics::cache::{self, Cached}; use crate::graphics::geometry::fill::{self, Fill}; use crate::graphics::geometry::stroke::{self, Stroke}; use crate::graphics::geometry::{self, Path, Style}; use crate::graphics::{self, Gradient, Image, Text}; use std::sync::Arc; #[derive(Debug)] pub enum Geometry { Live { text: Vec<Text>, images: Vec<graphics::Image>, primitives: Vec<Primitive>, clip_bounds: Rectangle, }, Cache(Cache), } #[derive(Debug, Clone)] pub struct Cache { pub text: Arc<[Text]>, pub images: Arc<[graphics::Image]>, pub primitives: Arc<[Primitive]>, pub clip_bounds: Rectangle, } impl Cached for Geometry { type Cache = Cache; fn load(cache: &Cache) -> Self { Self::Cache(cache.clone()) } fn cache(self, _group: cache::Group, _previous: Option<Cache>) -> Cache { match self { Self::Live { primitives, images, text, clip_bounds, } => Cache { primitives: Arc::from(primitives), images: Arc::from(images), text: Arc::from(text), clip_bounds, }, Self::Cache(cache) => cache, } } } #[derive(Debug)] pub struct Frame { clip_bounds: Rectangle, transform: tiny_skia::Transform, stack: Vec<tiny_skia::Transform>, primitives: Vec<Primitive>, images: Vec<graphics::Image>, text: Vec<Text>, } impl Frame { pub fn new(bounds: Rectangle) -> Self { Self { clip_bounds: bounds, stack: Vec::new(), primitives: Vec::new(), images: Vec::new(), text: Vec::new(), transform: tiny_skia::Transform::identity(), } } } impl geometry::frame::Backend for Frame { type Geometry = Geometry; fn width(&self) -> f32 { self.clip_bounds.width } fn height(&self) -> f32 { self.clip_bounds.height } fn size(&self) -> Size { self.clip_bounds.size() } fn center(&self) -> Point { Point::new(self.clip_bounds.width / 2.0, self.clip_bounds.height / 2.0) } fn fill(&mut self, path: &Path, fill: impl Into<Fill>) { let Some(path) = convert_path(path).and_then(|path| path.transform(self.transform)) else { return; }; let fill = fill.into(); let mut paint = into_paint(fill.style); paint.shader.transform(self.transform); self.primitives.push(Primitive::Fill { path, paint, rule: into_fill_rule(fill.rule), }); } fn fill_rectangle(&mut self, top_left: Point, size: Size, fill: impl Into<Fill>) { let Some(path) = convert_path(&Path::rectangle(top_left, size)) .and_then(|path| path.transform(self.transform)) else { return; }; let fill = fill.into(); let mut paint = tiny_skia::Paint { anti_alias: false, ..into_paint(fill.style) }; paint.shader.transform(self.transform); self.primitives.push(Primitive::Fill { path, paint, rule: into_fill_rule(fill.rule), }); } fn stroke<'a>(&mut self, path: &Path, stroke: impl Into<Stroke<'a>>) { let Some(path) = convert_path(path).and_then(|path| path.transform(self.transform)) else { return; }; let stroke = stroke.into(); let skia_stroke = into_stroke(&stroke); let mut paint = into_paint(stroke.style); paint.shader.transform(self.transform); self.primitives.push(Primitive::Stroke { path, paint, stroke: skia_stroke, }); } fn stroke_rectangle<'a>(&mut self, top_left: Point, size: Size, stroke: impl Into<Stroke<'a>>) { self.stroke(&Path::rectangle(top_left, size), stroke); } fn fill_text(&mut self, text: impl Into<geometry::Text>) { let text = text.into(); let (scale_x, scale_y) = self.transform.get_scale(); if !self.transform.has_skew() && scale_x == scale_y && scale_x > 0.0 && scale_y > 0.0 { let (bounds, size, line_height) = if self.transform.is_identity() { ( Rectangle::new(text.position, Size::new(text.max_width, f32::INFINITY)), text.size, text.line_height, ) } else { let mut position = [tiny_skia::Point { x: text.position.x, y: text.position.y, }]; self.transform.map_points(&mut position); let size = text.size.0 * scale_y; let line_height = match text.line_height { LineHeight::Absolute(size) => LineHeight::Absolute(Pixels(size.0 * scale_y)), LineHeight::Relative(factor) => LineHeight::Relative(factor), }; ( Rectangle { x: position[0].x, y: position[0].y, width: text.max_width * scale_x, height: f32::INFINITY, }, size.into(), line_height, ) }; // TODO: Honor layering! self.text.push(Text::Cached { content: text.content, bounds, color: text.color, size, line_height: line_height.to_absolute(size), font: text.font, align_x: text.align_x, align_y: text.align_y, shaping: text.shaping, clip_bounds: Rectangle::with_size(Size::INFINITE), }); } else { text.draw_with(|path, color| self.fill(&path, color)); } } fn stroke_text<'a>(&mut self, text: impl Into<geometry::Text>, stroke: impl Into<Stroke<'a>>) { let text = text.into(); let stroke = stroke.into(); text.draw_with(|path, _color| self.stroke(&path, stroke)); } fn push_transform(&mut self) { self.stack.push(self.transform); } fn pop_transform(&mut self) { self.transform = self.stack.pop().expect("Pop transform"); } fn draft(&mut self, clip_bounds: Rectangle) -> Self { Self::new(clip_bounds) } fn paste(&mut self, frame: Self) { self.primitives.extend(frame.primitives); self.text.extend(frame.text); self.images.extend(frame.images); } fn translate(&mut self, translation: Vector) { self.transform = self.transform.pre_translate(translation.x, translation.y); } fn rotate(&mut self, angle: impl Into<Radians>) { self.transform = self.transform.pre_concat(tiny_skia::Transform::from_rotate( angle.into().0.to_degrees(), )); } fn scale(&mut self, scale: impl Into<f32>) { let scale = scale.into(); self.scale_nonuniform(Vector { x: scale, y: scale }); } fn scale_nonuniform(&mut self, scale: impl Into<Vector>) { let scale = scale.into(); self.transform = self.transform.pre_scale(scale.x, scale.y); } fn into_geometry(self) -> Geometry { Geometry::Live { primitives: self.primitives, images: self.images, text: self.text, clip_bounds: self.clip_bounds, } } fn draw_image(&mut self, bounds: Rectangle, image: impl Into<core::Image>) { let mut image = image.into(); let (bounds, external_rotation) = transform_rectangle(bounds, self.transform); image.rotation += external_rotation; self.images.push(graphics::Image::Raster { image, bounds, clip_bounds: self.clip_bounds, }); } fn draw_svg(&mut self, bounds: Rectangle, svg: impl Into<Svg>) { let mut svg = svg.into(); let (bounds, external_rotation) = transform_rectangle(bounds, self.transform); svg.rotation += external_rotation; self.images.push(Image::Vector { svg, bounds, clip_bounds: self.clip_bounds, }); } } fn transform_rectangle( rectangle: Rectangle, transform: tiny_skia::Transform, ) -> (Rectangle, Radians) { let mut top_left = tiny_skia::Point { x: rectangle.x, y: rectangle.y, }; let mut top_right = tiny_skia::Point { x: rectangle.x + rectangle.width, y: rectangle.y, }; let mut bottom_left = tiny_skia::Point { x: rectangle.x, y: rectangle.y + rectangle.height, }; transform.map_point(&mut top_left); transform.map_point(&mut top_right); transform.map_point(&mut bottom_left); Rectangle::with_vertices( Point::new(top_left.x, top_left.y), Point::new(top_right.x, top_right.y), Point::new(bottom_left.x, bottom_left.y), ) } fn convert_path(path: &Path) -> Option<tiny_skia::Path> { use iced_graphics::geometry::path::lyon_path; let mut builder = tiny_skia::PathBuilder::new(); let mut last_point = lyon_path::math::Point::default(); for event in path.raw() { match event { lyon_path::Event::Begin { at } => { builder.move_to(at.x, at.y); last_point = at; } lyon_path::Event::Line { from, to } => { if last_point != from { builder.move_to(from.x, from.y); } builder.line_to(to.x, to.y); last_point = to; } lyon_path::Event::Quadratic { from, ctrl, to } => { if last_point != from { builder.move_to(from.x, from.y); } builder.quad_to(ctrl.x, ctrl.y, to.x, to.y); last_point = to; } lyon_path::Event::Cubic { from, ctrl1, ctrl2, to, } => { if last_point != from { builder.move_to(from.x, from.y); } builder.cubic_to(ctrl1.x, ctrl1.y, ctrl2.x, ctrl2.y, to.x, to.y); last_point = to; } lyon_path::Event::End { close, .. } => { if close { builder.close(); } } } } let result = builder.finish(); #[cfg(debug_assertions)] if result.is_none() { log::warn!("Invalid path: {:?}", path.raw()); } result } pub fn into_paint(style: Style) -> tiny_skia::Paint<'static> { tiny_skia::Paint { shader: match style { Style::Solid(color) => tiny_skia::Shader::SolidColor( tiny_skia::Color::from_rgba(color.b, color.g, color.r, color.a) .expect("Create color"), ), Style::Gradient(gradient) => match gradient { Gradient::Linear(linear) => { let stops: Vec<tiny_skia::GradientStop> = linear .stops .into_iter() .flatten() .map(|stop| { tiny_skia::GradientStop::new( stop.offset, tiny_skia::Color::from_rgba( stop.color.b, stop.color.g, stop.color.r, stop.color.a, ) .expect("Create color"), ) }) .collect(); tiny_skia::LinearGradient::new( tiny_skia::Point { x: linear.start.x, y: linear.start.y, }, tiny_skia::Point { x: linear.end.x, y: linear.end.y, }, if stops.is_empty() { vec![tiny_skia::GradientStop::new(0.0, tiny_skia::Color::BLACK)] } else { stops }, tiny_skia::SpreadMode::Pad, tiny_skia::Transform::identity(), ) .expect("Create linear gradient") } }, }, anti_alias: true, ..Default::default() } } pub fn into_fill_rule(rule: fill::Rule) -> tiny_skia::FillRule { match rule { fill::Rule::EvenOdd => tiny_skia::FillRule::EvenOdd, fill::Rule::NonZero => tiny_skia::FillRule::Winding, } } pub fn into_stroke(stroke: &Stroke<'_>) -> tiny_skia::Stroke { tiny_skia::Stroke { width: stroke.width, line_cap: match stroke.line_cap { stroke::LineCap::Butt => tiny_skia::LineCap::Butt, stroke::LineCap::Square => tiny_skia::LineCap::Square, stroke::LineCap::Round => tiny_skia::LineCap::Round, }, line_join: match stroke.line_join { stroke::LineJoin::Miter => tiny_skia::LineJoin::Miter, stroke::LineJoin::Round => tiny_skia::LineJoin::Round, stroke::LineJoin::Bevel => tiny_skia::LineJoin::Bevel, }, dash: if stroke.line_dash.segments.is_empty() { None } else { tiny_skia::StrokeDash::new( stroke.line_dash.segments.into(), stroke.line_dash.offset as f32, ) }, ..Default::default() } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/tiny_skia/src/layer.rs
tiny_skia/src/layer.rs
use crate::Primitive; use crate::core::renderer::Quad; use crate::core::{self, Background, Color, Point, Rectangle, Svg, Transformation}; use crate::graphics::damage; use crate::graphics::layer; use crate::graphics::text::{Editor, Paragraph, Text}; use crate::graphics::{self, Image}; use std::sync::Arc; pub type Stack = layer::Stack<Layer>; #[derive(Debug, Clone)] pub struct Layer { pub bounds: Rectangle, pub quads: Vec<(Quad, Background)>, pub primitives: Vec<Item<Primitive>>, pub images: Vec<Image>, pub text: Vec<Item<Text>>, } impl Layer { pub fn draw_quad( &mut self, mut quad: Quad, background: Background, transformation: Transformation, ) { quad.bounds = quad.bounds * transformation; self.quads.push((quad, background)); } pub fn draw_paragraph( &mut self, paragraph: &Paragraph, position: Point, color: Color, clip_bounds: Rectangle, transformation: Transformation, ) { let paragraph = Text::Paragraph { paragraph: paragraph.downgrade(), position, color, clip_bounds, transformation, }; self.text.push(Item::Live(paragraph)); } pub fn draw_editor( &mut self, editor: &Editor, position: Point, color: Color, clip_bounds: Rectangle, transformation: Transformation, ) { let editor = Text::Editor { editor: editor.downgrade(), position, color, clip_bounds, transformation, }; self.text.push(Item::Live(editor)); } pub fn draw_text( &mut self, text: core::Text, position: Point, color: Color, clip_bounds: Rectangle, transformation: Transformation, ) { let text = Text::Cached { content: text.content, bounds: Rectangle::new(position, text.bounds) * transformation, color, size: text.size * transformation.scale_factor(), line_height: text.line_height.to_absolute(text.size) * transformation.scale_factor(), font: text.font, align_x: text.align_x, align_y: text.align_y, shaping: text.shaping, clip_bounds: clip_bounds * transformation, }; self.text.push(Item::Live(text)); } pub fn draw_text_raw(&mut self, raw: graphics::text::Raw, transformation: Transformation) { let raw = Text::Raw { raw, transformation, }; self.text.push(Item::Live(raw)); } pub fn draw_text_group( &mut self, text: Vec<Text>, clip_bounds: Rectangle, transformation: Transformation, ) { self.text .push(Item::Group(text, clip_bounds, transformation)); } pub fn draw_text_cache( &mut self, text: Arc<[Text]>, clip_bounds: Rectangle, transformation: Transformation, ) { self.text .push(Item::Cached(text, clip_bounds, transformation)); } pub fn draw_image(&mut self, image: Image, transformation: Transformation) { match image { Image::Raster { image, bounds, clip_bounds, } => { self.draw_raster(image, bounds, clip_bounds, transformation); } Image::Vector { svg, bounds, clip_bounds, } => { self.draw_svg(svg, bounds, clip_bounds, transformation); } } } pub fn draw_raster( &mut self, image: core::Image, bounds: Rectangle, clip_bounds: Rectangle, transformation: Transformation, ) { let image = Image::Raster { image: core::Image { border_radius: image.border_radius * transformation.scale_factor(), ..image }, bounds: bounds * transformation, clip_bounds: clip_bounds * transformation, }; self.images.push(image); } pub fn draw_svg( &mut self, svg: Svg, bounds: Rectangle, clip_bounds: Rectangle, transformation: Transformation, ) { let svg = Image::Vector { svg, bounds: bounds * transformation, clip_bounds: clip_bounds * transformation, }; self.images.push(svg); } pub fn draw_primitive_group( &mut self, primitives: Vec<Primitive>, clip_bounds: Rectangle, transformation: Transformation, ) { self.primitives.push(Item::Group( primitives, clip_bounds * transformation, transformation, )); } pub fn draw_primitive_cache( &mut self, primitives: Arc<[Primitive]>, clip_bounds: Rectangle, transformation: Transformation, ) { self.primitives.push(Item::Cached( primitives, clip_bounds * transformation, transformation, )); } pub fn damage(previous: &Self, current: &Self) -> Vec<Rectangle> { if previous.bounds != current.bounds { return vec![previous.bounds, current.bounds]; } let mut damage = damage::list( &previous.quads, &current.quads, |(quad, _)| { quad.bounds .expand(1.0) .intersection(&current.bounds) .into_iter() .collect() }, |(quad_a, background_a), (quad_b, background_b)| { quad_a == quad_b && background_a == background_b }, ); let text = damage::diff( &previous.text, &current.text, |item| { item.as_slice() .iter() .filter_map(Text::visible_bounds) .map(|bounds| bounds * item.transformation()) .collect() }, |text_a, text_b| { damage::list( text_a.as_slice(), text_b.as_slice(), |text| { text.visible_bounds() .into_iter() .map(|bounds| bounds * text_a.transformation()) .collect() }, |text_a, text_b| text_a == text_b, ) }, ); let primitives = damage::list( &previous.primitives, &current.primitives, |item| match item { Item::Live(primitive) => vec![primitive.visible_bounds()], Item::Group(primitives, group_bounds, transformation) => primitives .as_slice() .iter() .map(Primitive::visible_bounds) .map(|bounds| bounds * *transformation) .filter_map(|bounds| bounds.intersection(group_bounds)) .collect(), Item::Cached(_, bounds, transformation) => { vec![*bounds * *transformation] } }, |primitive_a, primitive_b| match (primitive_a, primitive_b) { ( Item::Cached(cache_a, bounds_a, transformation_a), Item::Cached(cache_b, bounds_b, transformation_b), ) => { Arc::ptr_eq(cache_a, cache_b) && bounds_a == bounds_b && transformation_a == transformation_b } _ => false, }, ); let images = damage::list( &previous.images, &current.images, |image| vec![image.bounds().expand(1.0)], Image::eq, ); damage.extend(text); damage.extend(primitives); damage.extend(images); damage } } impl Default for Layer { fn default() -> Self { Self { bounds: Rectangle::INFINITE, quads: Vec::new(), primitives: Vec::new(), text: Vec::new(), images: Vec::new(), } } } impl graphics::Layer for Layer { fn with_bounds(bounds: Rectangle) -> Self { Self { bounds, ..Self::default() } } fn bounds(&self) -> Rectangle { self.bounds } fn flush(&mut self) {} fn resize(&mut self, bounds: Rectangle) { self.bounds = bounds; } fn reset(&mut self) { self.bounds = Rectangle::INFINITE; self.quads.clear(); self.primitives.clear(); self.text.clear(); self.images.clear(); } fn start(&self) -> usize { if !self.quads.is_empty() { return 1; } if !self.primitives.is_empty() { return 2; } if !self.images.is_empty() { return 3; } if !self.text.is_empty() { return 4; } usize::MAX } fn end(&self) -> usize { if !self.text.is_empty() { return 4; } if !self.images.is_empty() { return 3; } if !self.primitives.is_empty() { return 2; } if !self.quads.is_empty() { return 1; } 0 } fn merge(&mut self, layer: &mut Self) { self.quads.append(&mut layer.quads); self.primitives.append(&mut layer.primitives); self.text.append(&mut layer.text); self.images.append(&mut layer.images); } } #[derive(Debug, Clone)] pub enum Item<T> { Live(T), Group(Vec<T>, Rectangle, Transformation), Cached(Arc<[T]>, Rectangle, Transformation), } impl<T> Item<T> { pub fn transformation(&self) -> Transformation { match self { Item::Live(_) => Transformation::IDENTITY, Item::Group(_, _, transformation) | Item::Cached(_, _, transformation) => { *transformation } } } pub fn clip_bounds(&self) -> Rectangle { match self { Item::Live(_) => Rectangle::INFINITE, Item::Group(_, clip_bounds, _) | Item::Cached(_, clip_bounds, _) => *clip_bounds, } } pub fn as_slice(&self) -> &[T] { match self { Item::Live(item) => std::slice::from_ref(item), Item::Group(group, _, _) => group.as_slice(), Item::Cached(cache, _, _) => cache, } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/tiny_skia/src/text.rs
tiny_skia/src/text.rs
use crate::core::alignment; use crate::core::text::{Alignment, Shaping}; use crate::core::{Color, Font, Pixels, Point, Rectangle, Transformation}; use crate::graphics::text::cache::{self, Cache}; use crate::graphics::text::editor; use crate::graphics::text::font_system; use crate::graphics::text::paragraph; use rustc_hash::{FxHashMap, FxHashSet}; use std::borrow::Cow; use std::cell::RefCell; use std::collections::hash_map; #[derive(Debug)] pub struct Pipeline { glyph_cache: GlyphCache, cache: RefCell<Cache>, } impl Pipeline { pub fn new() -> Self { Pipeline { glyph_cache: GlyphCache::new(), cache: RefCell::new(Cache::new()), } } // TODO: Shared engine #[allow(dead_code)] pub fn load_font(&mut self, bytes: Cow<'static, [u8]>) { font_system() .write() .expect("Write font system") .load_font(bytes); self.cache = RefCell::new(Cache::new()); } pub fn draw_paragraph( &mut self, paragraph: &paragraph::Weak, position: Point, color: Color, pixels: &mut tiny_skia::PixmapMut<'_>, clip_mask: Option<&tiny_skia::Mask>, transformation: Transformation, ) { let Some(paragraph) = paragraph.upgrade() else { return; }; let mut font_system = font_system().write().expect("Write font system"); draw( font_system.raw(), &mut self.glyph_cache, paragraph.buffer(), position, color, pixels, clip_mask, transformation, ); } pub fn draw_editor( &mut self, editor: &editor::Weak, position: Point, color: Color, pixels: &mut tiny_skia::PixmapMut<'_>, clip_mask: Option<&tiny_skia::Mask>, transformation: Transformation, ) { let Some(editor) = editor.upgrade() else { return; }; let mut font_system = font_system().write().expect("Write font system"); draw( font_system.raw(), &mut self.glyph_cache, editor.buffer(), position, color, pixels, clip_mask, transformation, ); } pub fn draw_cached( &mut self, content: &str, bounds: Rectangle, color: Color, size: Pixels, line_height: Pixels, font: Font, align_x: Alignment, align_y: alignment::Vertical, shaping: Shaping, pixels: &mut tiny_skia::PixmapMut<'_>, clip_mask: Option<&tiny_skia::Mask>, transformation: Transformation, ) { let line_height = f32::from(line_height); let mut font_system = font_system().write().expect("Write font system"); let font_system = font_system.raw(); let key = cache::Key { bounds: bounds.size(), content, font, size: size.into(), line_height, shaping, align_x, }; let (_, entry) = self.cache.get_mut().allocate(font_system, key); let width = entry.min_bounds.width; let height = entry.min_bounds.height; let x = match align_x { Alignment::Default | Alignment::Left | Alignment::Justified => bounds.x, Alignment::Center => bounds.x - width / 2.0, Alignment::Right => bounds.x - width, }; let y = match align_y { alignment::Vertical::Top => bounds.y, alignment::Vertical::Center => bounds.y - height / 2.0, alignment::Vertical::Bottom => bounds.y - height, }; draw( font_system, &mut self.glyph_cache, &entry.buffer, Point::new(x, y), color, pixels, clip_mask, transformation, ); } pub fn draw_raw( &mut self, buffer: &cosmic_text::Buffer, position: Point, color: Color, pixels: &mut tiny_skia::PixmapMut<'_>, clip_mask: Option<&tiny_skia::Mask>, transformation: Transformation, ) { let mut font_system = font_system().write().expect("Write font system"); draw( font_system.raw(), &mut self.glyph_cache, buffer, position, color, pixels, clip_mask, transformation, ); } pub fn trim_cache(&mut self) { self.cache.get_mut().trim(); self.glyph_cache.trim(); } } fn draw( font_system: &mut cosmic_text::FontSystem, glyph_cache: &mut GlyphCache, buffer: &cosmic_text::Buffer, position: Point, color: Color, pixels: &mut tiny_skia::PixmapMut<'_>, clip_mask: Option<&tiny_skia::Mask>, transformation: Transformation, ) { let position = position * transformation; let mut swash = cosmic_text::SwashCache::new(); for run in buffer.layout_runs() { for glyph in run.glyphs { let physical_glyph = glyph.physical((position.x, position.y), transformation.scale_factor()); if let Some((buffer, placement)) = glyph_cache.allocate( physical_glyph.cache_key, glyph.color_opt.map(from_color).unwrap_or(color), font_system, &mut swash, ) { let pixmap = tiny_skia::PixmapRef::from_bytes(buffer, placement.width, placement.height) .expect("Create glyph pixel map"); let opacity = color.a * glyph.color_opt.map(|c| c.a() as f32 / 255.0).unwrap_or(1.0); pixels.draw_pixmap( physical_glyph.x + placement.left, physical_glyph.y - placement.top + (run.line_y * transformation.scale_factor()).round() as i32, pixmap, &tiny_skia::PixmapPaint { opacity, ..tiny_skia::PixmapPaint::default() }, tiny_skia::Transform::identity(), clip_mask, ); } } } } fn from_color(color: cosmic_text::Color) -> Color { let [r, g, b, a] = color.as_rgba(); Color::from_rgba8(r, g, b, a as f32 / 255.0) } #[derive(Debug, Clone, Default)] struct GlyphCache { entries: FxHashMap<(cosmic_text::CacheKey, [u8; 3]), (Vec<u32>, cosmic_text::Placement)>, recently_used: FxHashSet<(cosmic_text::CacheKey, [u8; 3])>, trim_count: usize, } impl GlyphCache { const TRIM_INTERVAL: usize = 300; const CAPACITY_LIMIT: usize = 16 * 1024; fn new() -> Self { GlyphCache::default() } fn allocate( &mut self, cache_key: cosmic_text::CacheKey, color: Color, font_system: &mut cosmic_text::FontSystem, swash: &mut cosmic_text::SwashCache, ) -> Option<(&[u8], cosmic_text::Placement)> { let [r, g, b, _a] = color.into_rgba8(); let key = (cache_key, [r, g, b]); if let hash_map::Entry::Vacant(entry) = self.entries.entry(key) { // TODO: Outline support let image = swash.get_image_uncached(font_system, cache_key)?; let glyph_size = image.placement.width as usize * image.placement.height as usize; if glyph_size == 0 { return None; } let mut buffer = vec![0u32; glyph_size]; match image.content { cosmic_text::SwashContent::Mask => { let mut i = 0; // TODO: Blend alpha for _y in 0..image.placement.height { for _x in 0..image.placement.width { buffer[i] = bytemuck::cast( tiny_skia::ColorU8::from_rgba(b, g, r, image.data[i]).premultiply(), ); i += 1; } } } cosmic_text::SwashContent::Color => { let mut i = 0; for _y in 0..image.placement.height { for _x in 0..image.placement.width { // TODO: Blend alpha buffer[i >> 2] = bytemuck::cast( tiny_skia::ColorU8::from_rgba( image.data[i + 2], image.data[i + 1], image.data[i], image.data[i + 3], ) .premultiply(), ); i += 4; } } } cosmic_text::SwashContent::SubpixelMask => { // TODO } } let _ = entry.insert((buffer, image.placement)); } let _ = self.recently_used.insert(key); self.entries .get(&key) .map(|(buffer, placement)| (bytemuck::cast_slice(buffer.as_slice()), *placement)) } pub fn trim(&mut self) { if self.trim_count > Self::TRIM_INTERVAL || self.recently_used.len() >= Self::CAPACITY_LIMIT { self.entries .retain(|key, _| self.recently_used.contains(key)); self.recently_used.clear(); self.entries.shrink_to(Self::CAPACITY_LIMIT); self.recently_used.shrink_to(Self::CAPACITY_LIMIT); self.trim_count = 0; } else { self.trim_count += 1; } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/tiny_skia/src/primitive.rs
tiny_skia/src/primitive.rs
use crate::core::Rectangle; #[derive(Debug, Clone, PartialEq)] pub enum Primitive { /// A path filled with some paint. Fill { /// The path to fill. path: tiny_skia::Path, /// The paint to use. paint: tiny_skia::Paint<'static>, /// The fill rule to follow. rule: tiny_skia::FillRule, }, /// A path stroked with some paint. Stroke { /// The path to stroke. path: tiny_skia::Path, /// The paint to use. paint: tiny_skia::Paint<'static>, /// The stroke settings. stroke: tiny_skia::Stroke, }, } impl Primitive { /// Returns the visible bounds of the [`Primitive`]. pub fn visible_bounds(&self) -> Rectangle { let bounds = match self { Primitive::Fill { path, .. } => path.bounds(), Primitive::Stroke { path, .. } => path.bounds(), }; Rectangle { x: bounds.x(), y: bounds.y(), width: bounds.width(), height: bounds.height(), } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/tiny_skia/src/window.rs
tiny_skia/src/window.rs
pub mod compositor; pub use compositor::{Compositor, Surface};
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/tiny_skia/src/raster.rs
tiny_skia/src/raster.rs
use crate::core::image as raster; use crate::core::{Rectangle, Size}; use crate::graphics; use rustc_hash::{FxHashMap, FxHashSet}; use std::cell::RefCell; use std::collections::hash_map; #[derive(Debug)] pub struct Pipeline { cache: RefCell<Cache>, } impl Pipeline { pub fn new() -> Self { Self { cache: RefCell::new(Cache::default()), } } pub fn load(&self, handle: &raster::Handle) -> Result<raster::Allocation, raster::Error> { let mut cache = self.cache.borrow_mut(); let image = cache.allocate(handle)?; #[allow(unsafe_code)] Ok(unsafe { raster::allocate(handle, Size::new(image.width(), image.height())) }) } pub fn dimensions(&self, handle: &raster::Handle) -> Option<Size<u32>> { let mut cache = self.cache.borrow_mut(); let image = cache.allocate(handle).ok()?; Some(Size::new(image.width(), image.height())) } pub fn draw( &mut self, handle: &raster::Handle, filter_method: raster::FilterMethod, bounds: Rectangle, opacity: f32, pixels: &mut tiny_skia::PixmapMut<'_>, transform: tiny_skia::Transform, clip_mask: Option<&tiny_skia::Mask>, ) { let mut cache = self.cache.borrow_mut(); let Ok(image) = cache.allocate(handle) else { return; }; let width_scale = bounds.width / image.width() as f32; let height_scale = bounds.height / image.height() as f32; let transform = transform.pre_scale(width_scale, height_scale); let quality = match filter_method { raster::FilterMethod::Linear => tiny_skia::FilterQuality::Bilinear, raster::FilterMethod::Nearest => tiny_skia::FilterQuality::Nearest, }; pixels.draw_pixmap( (bounds.x / width_scale) as i32, (bounds.y / height_scale) as i32, image, &tiny_skia::PixmapPaint { quality, opacity, ..Default::default() }, transform, clip_mask, ); } pub fn trim_cache(&mut self) { self.cache.borrow_mut().trim(); } } #[derive(Debug, Default)] struct Cache { entries: FxHashMap<raster::Id, Option<Entry>>, hits: FxHashSet<raster::Id>, } impl Cache { pub fn allocate( &mut self, handle: &raster::Handle, ) -> Result<tiny_skia::PixmapRef<'_>, raster::Error> { let id = handle.id(); if let hash_map::Entry::Vacant(entry) = self.entries.entry(id) { let image = match graphics::image::load(handle) { Ok(image) => image, Err(error) => { let _ = entry.insert(None); return Err(error); } }; if image.width() == 0 || image.height() == 0 { return Err(raster::Error::Empty); } let mut buffer = vec![0u32; image.width() as usize * image.height() as usize]; for (i, pixel) in image.pixels().enumerate() { let [r, g, b, a] = pixel.0; buffer[i] = bytemuck::cast(tiny_skia::ColorU8::from_rgba(b, g, r, a).premultiply()); } let _ = entry.insert(Some(Entry { width: image.width(), height: image.height(), pixels: buffer, })); } let _ = self.hits.insert(id); Ok(self .entries .get(&id) .unwrap() .as_ref() .map(|entry| { tiny_skia::PixmapRef::from_bytes( bytemuck::cast_slice(&entry.pixels), entry.width, entry.height, ) .expect("Build pixmap from image bytes") }) .expect("Image should be allocated")) } fn trim(&mut self) { self.entries.retain(|key, _| self.hits.contains(key)); self.hits.clear(); } } #[derive(Debug)] struct Entry { width: u32, height: u32, pixels: Vec<u32>, }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/tiny_skia/src/window/compositor.rs
tiny_skia/src/window/compositor.rs
use crate::core::{Color, Rectangle, Size}; use crate::graphics::compositor::{self, Information}; use crate::graphics::damage; use crate::graphics::error::{self, Error}; use crate::graphics::{self, Shell, Viewport}; use crate::{Layer, Renderer, Settings}; use std::collections::VecDeque; use std::num::NonZeroU32; pub struct Compositor { context: softbuffer::Context<Box<dyn compositor::Display>>, settings: Settings, } pub struct Surface { window: softbuffer::Surface<Box<dyn compositor::Display>, Box<dyn compositor::Window>>, clip_mask: tiny_skia::Mask, layer_stack: VecDeque<Vec<Layer>>, background_color: Color, max_age: u8, } impl crate::graphics::Compositor for Compositor { type Renderer = Renderer; type Surface = Surface; async fn with_backend( settings: graphics::Settings, display: impl compositor::Display, _compatible_window: impl compositor::Window, _shell: Shell, backend: Option<&str>, ) -> Result<Self, Error> { match backend { None | Some("tiny-skia") | Some("tiny_skia") => Ok(new(settings.into(), display)), Some(backend) => Err(Error::GraphicsAdapterNotFound { backend: "tiny-skia", reason: error::Reason::DidNotMatch { preferred_backend: backend.to_owned(), }, }), } } fn create_renderer(&self) -> Self::Renderer { Renderer::new(self.settings.default_font, self.settings.default_text_size) } fn create_surface<W: compositor::Window + Clone>( &mut self, window: W, width: u32, height: u32, ) -> Self::Surface { let window = softbuffer::Surface::new(&self.context, Box::new(window.clone()) as _) .expect("Create softbuffer surface for window"); let mut surface = Surface { window, clip_mask: tiny_skia::Mask::new(1, 1).expect("Create clip mask"), layer_stack: VecDeque::new(), background_color: Color::BLACK, max_age: 0, }; if width > 0 && height > 0 { self.configure_surface(&mut surface, width, height); } surface } fn configure_surface(&mut self, surface: &mut Self::Surface, width: u32, height: u32) { surface .window .resize( NonZeroU32::new(width).expect("Non-zero width"), NonZeroU32::new(height).expect("Non-zero height"), ) .expect("Resize surface"); surface.clip_mask = tiny_skia::Mask::new(width, height).expect("Create clip mask"); surface.layer_stack.clear(); } fn information(&self) -> Information { Information { adapter: String::from("CPU"), backend: String::from("tiny-skia"), } } fn present( &mut self, renderer: &mut Self::Renderer, surface: &mut Self::Surface, viewport: &Viewport, background_color: Color, on_pre_present: impl FnOnce(), ) -> Result<(), compositor::SurfaceError> { present( renderer, surface, viewport, background_color, on_pre_present, ) } fn screenshot( &mut self, renderer: &mut Self::Renderer, viewport: &Viewport, background_color: Color, ) -> Vec<u8> { screenshot(renderer, viewport, background_color) } } pub fn new(settings: Settings, display: impl compositor::Display) -> Compositor { #[allow(unsafe_code)] let context = softbuffer::Context::new(Box::new(display) as _).expect("Create softbuffer context"); Compositor { context, settings } } pub fn present( renderer: &mut Renderer, surface: &mut Surface, viewport: &Viewport, background_color: Color, on_pre_present: impl FnOnce(), ) -> Result<(), compositor::SurfaceError> { let physical_size = viewport.physical_size(); let mut buffer = surface .window .buffer_mut() .map_err(|_| compositor::SurfaceError::Lost)?; let last_layers = { let age = buffer.age(); surface.max_age = surface.max_age.max(age); surface.layer_stack.truncate(surface.max_age as usize); if age > 0 { surface.layer_stack.get(age as usize - 1) } else { None } }; let damage = last_layers .and_then(|last_layers| { (surface.background_color == background_color).then(|| { damage::diff( last_layers, renderer.layers(), |layer| vec![layer.bounds], Layer::damage, ) }) }) .unwrap_or_else(|| vec![Rectangle::with_size(viewport.logical_size())]); if damage.is_empty() { if let Some(last_layers) = last_layers { surface.layer_stack.push_front(last_layers.clone()); } } else { surface.layer_stack.push_front(renderer.layers().to_vec()); surface.background_color = background_color; let damage = damage::group(damage, Rectangle::with_size(viewport.logical_size())); let mut pixels = tiny_skia::PixmapMut::from_bytes( bytemuck::cast_slice_mut(&mut buffer), physical_size.width, physical_size.height, ) .expect("Create pixel map"); renderer.draw( &mut pixels, &mut surface.clip_mask, viewport, &damage, background_color, ); } on_pre_present(); buffer.present().map_err(|_| compositor::SurfaceError::Lost) } pub fn screenshot( renderer: &mut Renderer, viewport: &Viewport, background_color: Color, ) -> Vec<u8> { let size = viewport.physical_size(); let mut offscreen_buffer: Vec<u32> = vec![0; size.width as usize * size.height as usize]; let mut clip_mask = tiny_skia::Mask::new(size.width, size.height).expect("Create clip mask"); renderer.draw( &mut tiny_skia::PixmapMut::from_bytes( bytemuck::cast_slice_mut(&mut offscreen_buffer), size.width, size.height, ) .expect("Create offscreen pixel map"), &mut clip_mask, viewport, &[Rectangle::with_size(Size::new( size.width as f32, size.height as f32, ))], background_color, ); offscreen_buffer.iter().fold( Vec::with_capacity(offscreen_buffer.len() * 4), |mut acc, pixel| { const A_MASK: u32 = 0xFF_00_00_00; const R_MASK: u32 = 0x00_FF_00_00; const G_MASK: u32 = 0x00_00_FF_00; const B_MASK: u32 = 0x00_00_00_FF; let a = ((A_MASK & pixel) >> 24) as u8; let r = ((R_MASK & pixel) >> 16) as u8; let g = ((G_MASK & pixel) >> 8) as u8; let b = (B_MASK & pixel) as u8; acc.extend([r, g, b, a]); acc }, ) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/beacon/src/stream.rs
beacon/src/stream.rs
use futures::Future; use futures::channel::mpsc; use futures::stream::{self, Stream, StreamExt}; pub fn channel<T, F>(f: impl Fn(mpsc::Sender<T>) -> F) -> impl Stream<Item = T> where F: Future<Output = ()>, { let (sender, receiver) = mpsc::channel(1); stream::select( receiver, stream::once(f(sender)).filter_map(|_| async { None }), ) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/beacon/src/lib.rs
beacon/src/lib.rs
pub use iced_core as core; pub use semver::Version; pub mod client; pub mod span; mod error; mod stream; pub use client::Client; pub use span::Span; use crate::core::theme; use crate::core::time::{Duration, SystemTime}; use crate::error::Error; use crate::span::present; use futures::{SinkExt, Stream}; use tokio::io::{self, AsyncReadExt, AsyncWriteExt}; use tokio::net; use tokio::sync::mpsc; use tokio::task; #[derive(Debug, Clone)] pub struct Connection { commands: mpsc::Sender<client::Command>, } impl Connection { pub fn rewind_to<'a>(&self, message: usize) -> impl Future<Output = ()> + 'a { let commands = self.commands.clone(); async move { let _ = commands.send(client::Command::RewindTo { message }).await; } } pub fn go_live<'a>(&self) -> impl Future<Output = ()> + 'a { let commands = self.commands.clone(); async move { let _ = commands.send(client::Command::GoLive).await; } } } #[derive(Debug, Clone)] pub enum Event { Connected { connection: Connection, at: SystemTime, name: String, version: Version, theme: Option<theme::Palette>, can_time_travel: bool, }, Disconnected { at: SystemTime, }, ThemeChanged { at: SystemTime, palette: theme::Palette, }, SpanFinished { at: SystemTime, duration: Duration, span: Span, }, QuitRequested { at: SystemTime, }, AlreadyRunning { at: SystemTime, }, } impl Event { pub fn at(&self) -> SystemTime { match self { Self::Connected { at, .. } | Self::Disconnected { at, .. } | Self::ThemeChanged { at, .. } | Self::SpanFinished { at, .. } | Self::QuitRequested { at } | Self::AlreadyRunning { at } => *at, } } } pub fn is_running() -> bool { std::net::TcpListener::bind(client::server_address_from_env()).is_err() } pub fn run() -> impl Stream<Item = Event> { stream::channel(|mut output| async move { let mut buffer = Vec::new(); let server = loop { match net::TcpListener::bind(client::server_address_from_env()).await { Ok(server) => break server, Err(error) => { if error.kind() == io::ErrorKind::AddrInUse { let _ = output .send(Event::AlreadyRunning { at: SystemTime::now(), }) .await; } delay().await; } }; }; loop { let Ok((stream, _)) = server.accept().await else { continue; }; let (mut reader, mut writer) = { let _ = stream.set_nodelay(true); stream.into_split() }; let (command_sender, mut command_receiver) = mpsc::channel(1); let mut last_message = String::new(); let mut last_update_number = 0; let mut last_tasks = 0; let mut last_subscriptions = 0; let mut last_present_layers = 0; let mut last_prepare = present::Stage::default(); let mut last_render = present::Stage::default(); drop(task::spawn(async move { let mut last_message_number = None; while let Some(command) = command_receiver.recv().await { match command { client::Command::RewindTo { message } => { if Some(message) == last_message_number { continue; } last_message_number = Some(message); } client::Command::GoLive => { last_message_number = None; } } let _ = send(&mut writer, command) .await .inspect_err(|error| log::error!("Error when sending command: {error}")); } })); loop { match receive(&mut reader, &mut buffer).await { Ok(message) => { match message { client::Message::Connected { at, name, version, theme, can_time_travel, } => { let _ = output .send(Event::Connected { connection: Connection { commands: command_sender.clone(), }, at, name, version, theme, can_time_travel, }) .await; } client::Message::EventLogged { at, event } => match event { client::Event::ThemeChanged(palette) => { let _ = output.send(Event::ThemeChanged { at, palette }).await; } client::Event::SubscriptionsTracked(amount_alive) => { last_subscriptions = amount_alive; } client::Event::MessageLogged { number, message } => { last_update_number = number; last_message = message; } client::Event::CommandsSpawned(commands) => { last_tasks = commands; } client::Event::LayersRendered(layers) => { last_present_layers = layers; } client::Event::SpanStarted(span::Stage::Update) => { last_message.clear(); last_tasks = 0; } client::Event::SpanStarted(_) => {} client::Event::SpanFinished(stage, duration) => { let span = match stage { span::Stage::Boot => Span::Boot, span::Stage::Update => Span::Update { number: last_update_number, message: last_message.clone(), tasks: last_tasks, subscriptions: last_subscriptions, }, span::Stage::View(window) => Span::View { window }, span::Stage::Layout(window) => Span::Layout { window }, span::Stage::Interact(window) => Span::Interact { window }, span::Stage::Draw(window) => Span::Draw { window }, span::Stage::Prepare(primitive) | span::Stage::Render(primitive) => { let stage = if matches!(stage, span::Stage::Prepare(_),) { &mut last_prepare } else { &mut last_render }; let primitive = match primitive { present::Primitive::Quad => &mut stage.quads, present::Primitive::Triangle => { &mut stage.triangles } present::Primitive::Shader => &mut stage.shaders, present::Primitive::Text => &mut stage.text, present::Primitive::Image => &mut stage.images, }; *primitive += duration; continue; } span::Stage::Present(window) => { let span = Span::Present { window, prepare: last_prepare, render: last_render, layers: last_present_layers, }; last_prepare = present::Stage::default(); last_render = present::Stage::default(); last_present_layers = 0; span } span::Stage::Custom(name) => Span::Custom { name }, }; let _ = output .send(Event::SpanFinished { at, duration, span }) .await; } }, client::Message::Quit { at } => { let _ = output.send(Event::QuitRequested { at }).await; } }; } Err(Error::IOFailed(_)) => { let _ = output .send(Event::Disconnected { at: SystemTime::now(), }) .await; break; } Err(Error::DecodingFailed(error)) => { log::warn!("Error decoding beacon output: {error}") } } } } }) } async fn receive( stream: &mut net::tcp::OwnedReadHalf, buffer: &mut Vec<u8>, ) -> Result<client::Message, Error> { let size = stream.read_u64().await? as usize; if buffer.len() < size { buffer.resize(size, 0); } let _n = stream.read_exact(&mut buffer[..size]).await?; Ok(bincode::deserialize(buffer)?) } async fn send( stream: &mut net::tcp::OwnedWriteHalf, command: client::Command, ) -> Result<(), io::Error> { let bytes = bincode::serialize(&command).expect("Encode input message"); let size = bytes.len() as u64; stream.write_all(&size.to_be_bytes()).await?; stream.write_all(&bytes).await?; stream.flush().await?; Ok(()) } async fn delay() { tokio::time::sleep(Duration::from_secs(2)).await; }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/beacon/src/client.rs
beacon/src/client.rs
use crate::Error; use crate::core::time::{Duration, SystemTime}; use crate::span; use crate::theme; use semver::Version; use serde::{Deserialize, Serialize}; use tokio::io::{self, AsyncReadExt, AsyncWriteExt}; use tokio::net; use tokio::sync::{Mutex, mpsc}; use tokio::task; use tokio::time; use std::sync::Arc; use std::sync::atomic::{self, AtomicBool}; use std::thread; #[derive(Debug, Clone)] pub struct Client { sender: mpsc::Sender<Action>, is_connected: Arc<AtomicBool>, _handle: Arc<thread::JoinHandle<()>>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum Message { Connected { at: SystemTime, name: String, version: Version, theme: Option<theme::Palette>, can_time_travel: bool, }, EventLogged { at: SystemTime, event: Event, }, Quit { at: SystemTime, }, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum Event { ThemeChanged(theme::Palette), SpanStarted(span::Stage), SpanFinished(span::Stage, Duration), MessageLogged { number: usize, message: String }, CommandsSpawned(usize), SubscriptionsTracked(usize), LayersRendered(usize), } impl Client { pub fn log(&self, event: Event) { let _ = self.sender.try_send(Action::Send(Message::EventLogged { at: SystemTime::now(), event, })); } pub fn is_connected(&self) -> bool { self.is_connected.load(atomic::Ordering::Relaxed) } pub fn quit(&self) { let _ = self.sender.try_send(Action::Send(Message::Quit { at: SystemTime::now(), })); } pub fn subscribe(&self) -> mpsc::Receiver<Command> { let (sender, receiver) = mpsc::channel(100); let _ = self.sender.try_send(Action::Forward(sender)); receiver } } #[derive(Debug, Clone, Default)] pub struct Metadata { pub name: &'static str, pub theme: Option<theme::Palette>, pub can_time_travel: bool, } #[must_use] pub fn connect(metadata: Metadata) -> Client { let (sender, receiver) = mpsc::channel(10_000); let is_connected = Arc::new(AtomicBool::new(false)); let handle = { let is_connected = is_connected.clone(); std::thread::spawn(move || run(metadata, is_connected, receiver)) }; Client { sender, is_connected, _handle: Arc::new(handle), } } enum Action { Send(Message), Forward(mpsc::Sender<Command>), } #[derive(Debug, Clone, Copy, Serialize, Deserialize)] pub enum Command { RewindTo { message: usize }, GoLive, } #[tokio::main] async fn run( mut metadata: Metadata, is_connected: Arc<AtomicBool>, mut receiver: mpsc::Receiver<Action>, ) { let version = semver::Version::parse(env!("CARGO_PKG_VERSION")).expect("Parse package version"); let command_sender = { // Discard by default let (sender, _receiver) = mpsc::channel(1); Arc::new(Mutex::new(sender)) }; loop { match _connect().await { Ok(stream) => { is_connected.store(true, atomic::Ordering::Relaxed); let (mut reader, mut writer) = stream.into_split(); let _ = send( &mut writer, Message::Connected { at: SystemTime::now(), name: metadata.name.to_owned(), version: version.clone(), can_time_travel: metadata.can_time_travel, theme: metadata.theme, }, ) .await; { let command_sender = command_sender.clone(); drop(task::spawn(async move { let mut buffer = Vec::new(); loop { match receive(&mut reader, &mut buffer).await { Ok(command) => { match command { Command::RewindTo { .. } | Command::GoLive if !metadata.can_time_travel => { continue; } _ => {} } let sender = command_sender.lock().await; let _ = sender.send(command).await; } Err(Error::DecodingFailed(_)) => {} Err(Error::IOFailed(_)) => break, } } })) }; while let Some(action) = receiver.recv().await { match action { Action::Send(message) => { if let Message::EventLogged { event: Event::ThemeChanged(palette), .. } = message { metadata.theme = Some(palette); } match send(&mut writer, message).await { Ok(()) => {} Err(error) => { if error.kind() != io::ErrorKind::BrokenPipe { log::warn!("Error sending message to server: {error}"); } is_connected.store(false, atomic::Ordering::Relaxed); break; } } } Action::Forward(sender) => { *command_sender.lock().await = sender; } } } } Err(_) => { is_connected.store(false, atomic::Ordering::Relaxed); time::sleep(time::Duration::from_secs(2)).await; } } } } /// Returns the address of the beacon server in this environment. /// /// The value of the `ICED_BEACON_SERVER_ADDRESS` env variable will /// be returned, if defined. /// /// Otherwise, a default local server address will be returned. pub fn server_address_from_env() -> String { const DEFAULT_ADDRESS: &str = "127.0.0.1:9167"; std::env::var("ICED_BEACON_SERVER_ADDRESS").unwrap_or_else(|_| String::from(DEFAULT_ADDRESS)) } async fn _connect() -> Result<net::TcpStream, io::Error> { log::debug!("Attempting to connect to server..."); let stream = net::TcpStream::connect(server_address_from_env()).await?; stream.set_nodelay(true)?; stream.writable().await?; Ok(stream) } async fn send(stream: &mut net::tcp::OwnedWriteHalf, message: Message) -> Result<(), io::Error> { let bytes = bincode::serialize(&message).expect("Encode input message"); let size = bytes.len() as u64; stream.write_all(&size.to_be_bytes()).await?; stream.write_all(&bytes).await?; stream.flush().await?; Ok(()) } async fn receive( stream: &mut net::tcp::OwnedReadHalf, buffer: &mut Vec<u8>, ) -> Result<Command, Error> { let size = stream.read_u64().await? as usize; if buffer.len() < size { buffer.resize(size, 0); } let _n = stream.read_exact(&mut buffer[..size]).await?; Ok(bincode::deserialize(buffer)?) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/beacon/src/error.rs
beacon/src/error.rs
use std::io; #[derive(Debug, thiserror::Error)] pub enum Error { #[error("input/output operation failed: {0}")] IOFailed(#[from] io::Error), #[error("decoding failed: {0}")] DecodingFailed(#[from] Box<bincode::ErrorKind>), }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/beacon/src/span.rs
beacon/src/span.rs
use crate::core::window; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Span { Boot, Update { number: usize, message: String, tasks: usize, subscriptions: usize, }, View { window: window::Id, }, Layout { window: window::Id, }, Interact { window: window::Id, }, Draw { window: window::Id, }, Present { window: window::Id, prepare: present::Stage, render: present::Stage, layers: usize, }, Custom { name: String, }, } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] pub enum Stage { Boot, Update, View(window::Id), Layout(window::Id), Interact(window::Id), Draw(window::Id), Present(window::Id), Prepare(present::Primitive), Render(present::Primitive), Custom(String), } impl std::fmt::Display for Stage { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(match self { Stage::Boot => "Boot", Stage::Update => "Update", Stage::View(_) => "View", Stage::Layout(_) => "Layout", Stage::Interact(_) => "Interact", Stage::Draw(_) => "Draw", Stage::Prepare(_) => "Prepare", Stage::Render(_) => "Render", Stage::Present(_) => "Present", Stage::Custom(name) => name, }) } } pub mod present { use crate::core::time::Duration; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] pub struct Stage { pub quads: Duration, pub triangles: Duration, pub shaders: Duration, pub text: Duration, pub images: Duration, } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] pub enum Primitive { Quad, Triangle, Shader, Text, Image, } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/winit/src/lib.rs
winit/src/lib.rs
//! A windowing shell for Iced, on top of [`winit`]. //! //! ![The native path of the Iced ecosystem](https://github.com/iced-rs/iced/blob/0525d76ff94e828b7b21634fa94a747022001c83/docs/graphs/native.png?raw=true) //! //! `iced_winit` offers some convenient abstractions on top of [`iced_runtime`] //! to quickstart development when using [`winit`]. //! //! It exposes a renderer-agnostic [`Program`] trait that can be implemented //! and then run with a simple call. The use of this trait is optional. //! //! Additionally, a [`conversion`] module is available for users that decide to //! implement a custom event loop. //! //! [`iced_runtime`]: https://github.com/iced-rs/iced/tree/master/runtime //! [`winit`]: https://github.com/rust-windowing/winit //! [`conversion`]: crate::conversion #![doc( html_logo_url = "https://raw.githubusercontent.com/iced-rs/iced/9ab6923e943f784985e9ef9ca28b10278297225d/docs/logo.svg" )] #![cfg_attr(docsrs, feature(doc_cfg))] pub use iced_debug as debug; pub use iced_program as program; pub use program::core; pub use program::graphics; pub use program::runtime; pub use runtime::futures; pub use winit; pub mod clipboard; pub mod conversion; mod error; mod proxy; mod window; pub use clipboard::Clipboard; pub use error::Error; pub use proxy::Proxy; use crate::core::mouse; use crate::core::renderer; use crate::core::theme; use crate::core::time::Instant; use crate::core::widget::operation; use crate::core::{Point, Renderer, Size}; use crate::futures::futures::channel::mpsc; use crate::futures::futures::channel::oneshot; use crate::futures::futures::task; use crate::futures::futures::{Future, StreamExt}; use crate::futures::subscription; use crate::futures::{Executor, Runtime}; use crate::graphics::{Compositor, Shell, compositor}; use crate::runtime::image; use crate::runtime::system; use crate::runtime::user_interface::{self, UserInterface}; use crate::runtime::{Action, Task}; use program::Program; use window::WindowManager; use rustc_hash::FxHashMap; use std::borrow::Cow; use std::mem::ManuallyDrop; use std::slice; use std::sync::Arc; /// Runs a [`Program`] with the provided settings. pub fn run<P>(program: P) -> Result<(), Error> where P: Program + 'static, P::Theme: theme::Base, { use winit::event_loop::EventLoop; let boot_span = debug::boot(); let settings = program.settings(); let window_settings = program.window(); let event_loop = EventLoop::with_user_event() .build() .expect("Create event loop"); let graphics_settings = settings.clone().into(); let display_handle = event_loop.owned_display_handle(); let (proxy, worker) = Proxy::new(event_loop.create_proxy()); #[cfg(feature = "debug")] { let proxy = proxy.clone(); debug::on_hotpatch(move || { proxy.send_action(Action::Reload); }); } let mut runtime = { let executor = P::Executor::new().map_err(Error::ExecutorCreationFailed)?; executor.spawn(worker); Runtime::new(executor, proxy.clone()) }; let (program, task) = runtime.enter(|| program::Instance::new(program)); let is_daemon = window_settings.is_none(); let task = if let Some(window_settings) = window_settings { let mut task = Some(task); let (_id, open) = runtime::window::open(window_settings); open.then(move |_| task.take().unwrap_or_else(Task::none)) } else { task }; if let Some(stream) = runtime::task::into_stream(task) { runtime.run(stream); } runtime.track(subscription::into_recipes( runtime.enter(|| program.subscription().map(Action::Output)), )); let (event_sender, event_receiver) = mpsc::unbounded(); let (control_sender, control_receiver) = mpsc::unbounded(); let (system_theme_sender, system_theme_receiver) = oneshot::channel(); let instance = Box::pin(run_instance::<P>( program, runtime, proxy.clone(), event_receiver, control_sender, display_handle, is_daemon, graphics_settings, settings.fonts, system_theme_receiver, )); let context = task::Context::from_waker(task::noop_waker_ref()); struct Runner<Message: 'static, F> { instance: std::pin::Pin<Box<F>>, context: task::Context<'static>, id: Option<String>, sender: mpsc::UnboundedSender<Event<Action<Message>>>, receiver: mpsc::UnboundedReceiver<Control>, error: Option<Error>, system_theme: Option<oneshot::Sender<theme::Mode>>, #[cfg(target_arch = "wasm32")] canvas: Option<web_sys::HtmlCanvasElement>, } let runner = Runner { instance, context, id: settings.id, sender: event_sender, receiver: control_receiver, error: None, system_theme: Some(system_theme_sender), #[cfg(target_arch = "wasm32")] canvas: None, }; boot_span.finish(); impl<Message, F> winit::application::ApplicationHandler<Action<Message>> for Runner<Message, F> where F: Future<Output = ()>, { fn resumed(&mut self, event_loop: &winit::event_loop::ActiveEventLoop) { if let Some(sender) = self.system_theme.take() { let _ = sender.send( event_loop .system_theme() .map(conversion::theme_mode) .unwrap_or_default(), ); } } fn new_events( &mut self, event_loop: &winit::event_loop::ActiveEventLoop, cause: winit::event::StartCause, ) { self.process_event( event_loop, Event::EventLoopAwakened(winit::event::Event::NewEvents(cause)), ); } fn window_event( &mut self, event_loop: &winit::event_loop::ActiveEventLoop, window_id: winit::window::WindowId, event: winit::event::WindowEvent, ) { #[cfg(target_os = "windows")] let is_move_or_resize = matches!( event, winit::event::WindowEvent::Resized(_) | winit::event::WindowEvent::Moved(_) ); self.process_event( event_loop, Event::EventLoopAwakened(winit::event::Event::WindowEvent { window_id, event }), ); // TODO: Remove when unnecessary // On Windows, we emulate an `AboutToWait` event after every `Resized` event // since the event loop does not resume during resize interaction. // More details: https://github.com/rust-windowing/winit/issues/3272 #[cfg(target_os = "windows")] { if is_move_or_resize { self.process_event( event_loop, Event::EventLoopAwakened(winit::event::Event::AboutToWait), ); } } } fn user_event( &mut self, event_loop: &winit::event_loop::ActiveEventLoop, action: Action<Message>, ) { self.process_event( event_loop, Event::EventLoopAwakened(winit::event::Event::UserEvent(action)), ); } fn received_url(&mut self, event_loop: &winit::event_loop::ActiveEventLoop, url: String) { self.process_event( event_loop, Event::EventLoopAwakened(winit::event::Event::PlatformSpecific( winit::event::PlatformSpecific::MacOS(winit::event::MacOS::ReceivedUrl(url)), )), ); } fn about_to_wait(&mut self, event_loop: &winit::event_loop::ActiveEventLoop) { self.process_event( event_loop, Event::EventLoopAwakened(winit::event::Event::AboutToWait), ); } } impl<Message, F> Runner<Message, F> where F: Future<Output = ()>, { fn process_event( &mut self, event_loop: &winit::event_loop::ActiveEventLoop, event: Event<Action<Message>>, ) { if event_loop.exiting() { return; } self.sender.start_send(event).expect("Send event"); loop { let poll = self.instance.as_mut().poll(&mut self.context); match poll { task::Poll::Pending => match self.receiver.try_next() { Ok(Some(control)) => match control { Control::ChangeFlow(flow) => { use winit::event_loop::ControlFlow; match (event_loop.control_flow(), flow) { ( ControlFlow::WaitUntil(current), ControlFlow::WaitUntil(new), ) if current < new => {} (ControlFlow::WaitUntil(target), ControlFlow::Wait) if target > Instant::now() => {} _ => { event_loop.set_control_flow(flow); } } } Control::CreateWindow { id, settings, title, scale_factor, monitor, on_open, } => { let exit_on_close_request = settings.exit_on_close_request; let visible = settings.visible; #[cfg(target_arch = "wasm32")] let target = settings.platform_specific.target.clone(); let window_attributes = conversion::window_attributes( settings, &title, scale_factor, monitor.or(event_loop.primary_monitor()), self.id.clone(), ) .with_visible(false); #[cfg(target_arch = "wasm32")] let window_attributes = { use winit::platform::web::WindowAttributesExtWebSys; window_attributes.with_canvas(self.canvas.take()) }; log::info!( "Window attributes for id `{id:#?}`: {window_attributes:#?}" ); // On macOS, the `position` in `WindowAttributes` represents the "inner" // position of the window; while on other platforms it's the "outer" position. // We fix the inconsistency on macOS by positioning the window after creation. #[cfg(target_os = "macos")] let mut window_attributes = window_attributes; #[cfg(target_os = "macos")] let position = window_attributes.position.take(); let window = event_loop .create_window(window_attributes) .expect("Create window"); #[cfg(target_os = "macos")] if let Some(position) = position { window.set_outer_position(position); } #[cfg(target_arch = "wasm32")] { use winit::platform::web::WindowExtWebSys; let canvas = window.canvas().expect("Get window canvas"); let _ = canvas.set_attribute( "style", "display: block; width: 100%; height: 100%", ); let window = web_sys::window().unwrap(); let document = window.document().unwrap(); let body = document.body().unwrap(); let target = target.and_then(|target| { body.query_selector(&format!("#{target}")) .ok() .unwrap_or(None) }); match target { Some(node) => { let _ = node.replace_with_with_node_1(&canvas).expect( &format!("Could not replace #{}", node.id()), ); } None => { let _ = body .append_child(&canvas) .expect("Append canvas to HTML body"); } }; } self.process_event( event_loop, Event::WindowCreated { id, window: Arc::new(window), exit_on_close_request, make_visible: visible, on_open, }, ); } Control::Exit => { self.process_event(event_loop, Event::Exit); event_loop.exit(); break; } Control::Crash(error) => { self.error = Some(error); event_loop.exit(); } Control::SetAutomaticWindowTabbing(_enabled) => { #[cfg(target_os = "macos")] { use winit::platform::macos::ActiveEventLoopExtMacOS; event_loop.set_allows_automatic_window_tabbing(_enabled); } } }, _ => { break; } }, task::Poll::Ready(_) => { event_loop.exit(); break; } }; } } } #[cfg(not(target_arch = "wasm32"))] { let mut runner = runner; let _ = event_loop.run_app(&mut runner); runner.error.map(Err).unwrap_or(Ok(())) } #[cfg(target_arch = "wasm32")] { use winit::platform::web::EventLoopExtWebSys; let _ = event_loop.spawn_app(runner); Ok(()) } } #[derive(Debug)] enum Event<Message: 'static> { WindowCreated { id: window::Id, window: Arc<winit::window::Window>, exit_on_close_request: bool, make_visible: bool, on_open: oneshot::Sender<window::Id>, }, EventLoopAwakened(winit::event::Event<Message>), Exit, } #[derive(Debug)] enum Control { ChangeFlow(winit::event_loop::ControlFlow), Exit, Crash(Error), CreateWindow { id: window::Id, settings: window::Settings, title: String, monitor: Option<winit::monitor::MonitorHandle>, on_open: oneshot::Sender<window::Id>, scale_factor: f32, }, SetAutomaticWindowTabbing(bool), } async fn run_instance<P>( mut program: program::Instance<P>, mut runtime: Runtime<P::Executor, Proxy<P::Message>, Action<P::Message>>, mut proxy: Proxy<P::Message>, mut event_receiver: mpsc::UnboundedReceiver<Event<Action<P::Message>>>, mut control_sender: mpsc::UnboundedSender<Control>, display_handle: winit::event_loop::OwnedDisplayHandle, is_daemon: bool, graphics_settings: graphics::Settings, default_fonts: Vec<Cow<'static, [u8]>>, mut _system_theme: oneshot::Receiver<theme::Mode>, ) where P: Program + 'static, P::Theme: theme::Base, { use winit::event; use winit::event_loop::ControlFlow; let mut window_manager = WindowManager::new(); let mut is_window_opening = !is_daemon; let mut compositor = None; let mut events = Vec::new(); let mut messages = Vec::new(); let mut actions = 0; let mut ui_caches = FxHashMap::default(); let mut user_interfaces = ManuallyDrop::new(FxHashMap::default()); let mut clipboard = Clipboard::unconnected(); #[cfg(all(feature = "linux-theme-detection", target_os = "linux"))] let mut system_theme = { let to_mode = |color_scheme| match color_scheme { mundy::ColorScheme::NoPreference => theme::Mode::None, mundy::ColorScheme::Light => theme::Mode::Light, mundy::ColorScheme::Dark => theme::Mode::Dark, }; runtime.run( mundy::Preferences::stream(mundy::Interest::ColorScheme) .map(move |preferences| { Action::System(system::Action::NotifyTheme(to_mode( preferences.color_scheme, ))) }) .boxed(), ); runtime .enter(|| { mundy::Preferences::once_blocking( mundy::Interest::ColorScheme, core::time::Duration::from_millis(200), ) }) .map(|preferences| to_mode(preferences.color_scheme)) .unwrap_or_default() }; #[cfg(not(all(feature = "linux-theme-detection", target_os = "linux")))] let mut system_theme = _system_theme.try_recv().ok().flatten().unwrap_or_default(); log::info!("System theme: {system_theme:?}"); 'next_event: loop { // Empty the queue if possible let event = if let Ok(event) = event_receiver.try_next() { event } else { event_receiver.next().await }; let Some(event) = event else { break; }; match event { Event::WindowCreated { id, window, exit_on_close_request, make_visible, on_open, } => { if compositor.is_none() { let (compositor_sender, compositor_receiver) = oneshot::channel(); let create_compositor = { let window = window.clone(); let display_handle = display_handle.clone(); let proxy = proxy.clone(); let default_fonts = default_fonts.clone(); async move { let shell = Shell::new(proxy.clone()); let mut compositor = <P::Renderer as compositor::Default>::Compositor::new( graphics_settings, display_handle, window, shell, ) .await; if let Ok(compositor) = &mut compositor { for font in default_fonts { compositor.load_font(font.clone()); } } compositor_sender .send(compositor) .ok() .expect("Send compositor"); // HACK! Send a proxy event on completion to trigger // a runtime re-poll // TODO: Send compositor through proxy (?) { let (sender, _receiver) = oneshot::channel(); proxy.send_action(Action::Window( runtime::window::Action::GetLatest(sender), )); } } }; #[cfg(target_arch = "wasm32")] wasm_bindgen_futures::spawn_local(create_compositor); #[cfg(not(target_arch = "wasm32"))] runtime.block_on(create_compositor); match compositor_receiver.await.expect("Wait for compositor") { Ok(new_compositor) => { compositor = Some(new_compositor); } Err(error) => { let _ = control_sender.start_send(Control::Crash(error.into())); continue; } } } let window_theme = window .theme() .map(conversion::theme_mode) .unwrap_or_default(); if system_theme != window_theme { system_theme = window_theme; runtime.broadcast(subscription::Event::SystemThemeChanged(window_theme)); } let is_first = window_manager.is_empty(); let window = window_manager.insert( id, window, &program, compositor.as_mut().expect("Compositor must be initialized"), exit_on_close_request, system_theme, ); window .raw .set_theme(conversion::window_theme(window.state.theme_mode())); debug::theme_changed(|| { if is_first { theme::Base::palette(window.state.theme()) } else { None } }); let logical_size = window.state.logical_size(); #[cfg(feature = "hinting")] window.renderer.hint(window.state.scale_factor()); let _ = user_interfaces.insert( id, build_user_interface( &program, user_interface::Cache::default(), &mut window.renderer, logical_size, id, ), ); let _ = ui_caches.insert(id, user_interface::Cache::default()); if make_visible { window.raw.set_visible(true); } events.push(( id, core::Event::Window(window::Event::Opened { position: window.position(), size: window.logical_size(), }), )); if clipboard.window_id().is_none() { clipboard = Clipboard::connect(window.raw.clone()); } let _ = on_open.send(id); is_window_opening = false; } Event::EventLoopAwakened(event) => { match event { event::Event::NewEvents(event::StartCause::Init) => { for (_id, window) in window_manager.iter_mut() { window.raw.request_redraw(); } } event::Event::NewEvents(event::StartCause::ResumeTimeReached { .. }) => { let now = Instant::now(); for (_id, window) in window_manager.iter_mut() { if let Some(redraw_at) = window.redraw_at && redraw_at <= now { window.raw.request_redraw(); window.redraw_at = None; } } if let Some(redraw_at) = window_manager.redraw_at() { let _ = control_sender .start_send(Control::ChangeFlow(ControlFlow::WaitUntil(redraw_at))); } else { let _ = control_sender.start_send(Control::ChangeFlow(ControlFlow::Wait)); } } event::Event::PlatformSpecific(event::PlatformSpecific::MacOS( event::MacOS::ReceivedUrl(url), )) => { runtime.broadcast(subscription::Event::PlatformSpecific( subscription::PlatformSpecific::MacOS( subscription::MacOS::ReceivedUrl(url), ), )); } event::Event::UserEvent(action) => { run_action( action, &program, &mut runtime, &mut compositor, &mut events, &mut messages, &mut clipboard, &mut control_sender, &mut user_interfaces, &mut window_manager, &mut ui_caches, &mut is_window_opening, &mut system_theme, ); actions += 1; } event::Event::WindowEvent { window_id: id, event: event::WindowEvent::RedrawRequested, .. } => { let Some(mut current_compositor) = compositor.as_mut() else { continue; }; let Some((id, mut window)) = window_manager.get_mut_alias(id) else { continue; }; let physical_size = window.state.physical_size(); let mut logical_size = window.state.logical_size(); if physical_size.width == 0 || physical_size.height == 0 { continue; } // Window was resized between redraws if window.surface_version != window.state.surface_version() { #[cfg(feature = "hinting")] window.renderer.hint(window.state.scale_factor()); let ui = user_interfaces.remove(&id).expect("Remove user interface"); let layout_span = debug::layout(id); let _ = user_interfaces .insert(id, ui.relayout(logical_size, &mut window.renderer)); layout_span.finish(); current_compositor.configure_surface( &mut window.surface, physical_size.width, physical_size.height, ); window.surface_version = window.state.surface_version(); } let redraw_event = core::Event::Window(window::Event::RedrawRequested(Instant::now())); let cursor = window.state.cursor(); let mut interface = user_interfaces.get_mut(&id).expect("Get user interface"); let interact_span = debug::interact(id); let mut redraw_count = 0; let state = loop { let message_count = messages.len(); let (state, _) = interface.update( slice::from_ref(&redraw_event), cursor, &mut window.renderer, &mut clipboard, &mut messages, ); if message_count == messages.len() && !state.has_layout_changed() { break state; } if redraw_count >= 2 { log::warn!( "More than 3 consecutive RedrawRequested events \ produced layout invalidation" ); break state; } redraw_count += 1; if !messages.is_empty() { let caches: FxHashMap<_, _> = ManuallyDrop::into_inner(user_interfaces) .into_iter() .map(|(id, interface)| (id, interface.into_cache())) .collect(); let actions = update(&mut program, &mut runtime, &mut messages); user_interfaces = ManuallyDrop::new(build_user_interfaces( &program, &mut window_manager, caches, )); for action in actions { // Defer all window actions to avoid compositor // race conditions while redrawing if let Action::Window(_) = action { proxy.send_action(action); continue; } run_action( action, &program, &mut runtime, &mut compositor, &mut events, &mut messages, &mut clipboard, &mut control_sender, &mut user_interfaces, &mut window_manager, &mut ui_caches, &mut is_window_opening, &mut system_theme, ); } for (window_id, window) in window_manager.iter_mut() { // We are already redrawing this window if window_id == id {
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
true
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/winit/src/clipboard.rs
winit/src/clipboard.rs
//! Access the clipboard. use crate::core::clipboard::Kind; use std::sync::Arc; use winit::window::{Window, WindowId}; /// A buffer for short-term storage and transfer within and between /// applications. pub struct Clipboard { state: State, } enum State { Connected { clipboard: window_clipboard::Clipboard, // Held until drop to satisfy the safety invariants of // `window_clipboard::Clipboard`. // // Note that the field ordering is load-bearing. #[allow(dead_code)] window: Arc<Window>, }, Unavailable, } impl Clipboard { /// Creates a new [`Clipboard`] for the given window. pub fn connect(window: Arc<Window>) -> Clipboard { // SAFETY: The window handle will stay alive throughout the entire // lifetime of the `window_clipboard::Clipboard` because we hold // the `Arc<Window>` together with `State`, and enum variant fields // get dropped in declaration order. #[allow(unsafe_code)] let clipboard = unsafe { window_clipboard::Clipboard::connect(&window) }; let state = match clipboard { Ok(clipboard) => State::Connected { clipboard, window }, Err(_) => State::Unavailable, }; Clipboard { state } } /// Creates a new [`Clipboard`] that isn't associated with a window. /// This clipboard will never contain a copied value. pub fn unconnected() -> Clipboard { Clipboard { state: State::Unavailable, } } /// Reads the current content of the [`Clipboard`] as text. pub fn read(&self, kind: Kind) -> Option<String> { match &self.state { State::Connected { clipboard, .. } => match kind { Kind::Standard => clipboard.read().ok(), Kind::Primary => clipboard.read_primary().and_then(Result::ok), }, State::Unavailable => None, } } /// Writes the given text contents to the [`Clipboard`]. pub fn write(&mut self, kind: Kind, contents: String) { match &mut self.state { State::Connected { clipboard, .. } => { let result = match kind { Kind::Standard => clipboard.write(contents), Kind::Primary => clipboard.write_primary(contents).unwrap_or(Ok(())), }; match result { Ok(()) => {} Err(error) => { log::warn!("error writing to clipboard: {error}"); } } } State::Unavailable => {} } } /// Returns the identifier of the window used to create the [`Clipboard`], if any. pub fn window_id(&self) -> Option<WindowId> { match &self.state { State::Connected { window, .. } => Some(window.id()), State::Unavailable => None, } } } impl crate::core::Clipboard for Clipboard { fn read(&self, kind: Kind) -> Option<String> { self.read(kind) } fn write(&mut self, kind: Kind, contents: String) { self.write(kind, contents); } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/winit/src/error.rs
winit/src/error.rs
use crate::futures::futures; use crate::graphics; /// An error that occurred while running an application. #[derive(Debug, thiserror::Error)] pub enum Error { /// The futures executor could not be created. #[error("the futures executor could not be created")] ExecutorCreationFailed(futures::io::Error), /// The application window could not be created. #[error("the application window could not be created")] WindowCreationFailed(winit::error::OsError), /// The application graphics context could not be created. #[error("the application graphics context could not be created")] GraphicsCreationFailed(graphics::Error), } impl From<graphics::Error> for Error { fn from(error: graphics::Error) -> Error { Error::GraphicsCreationFailed(error) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/winit/src/conversion.rs
winit/src/conversion.rs
//! Convert [`winit`] types into [`iced_runtime`] types, and viceversa. //! //! [`winit`]: https://github.com/rust-windowing/winit //! [`iced_runtime`]: https://github.com/iced-rs/iced/tree/master/runtime use crate::core::input_method; use crate::core::keyboard; use crate::core::mouse; use crate::core::theme; use crate::core::touch; use crate::core::window; use crate::core::{Event, Point, Size}; /// Converts some [`window::Settings`] into some `WindowAttributes` from `winit`. pub fn window_attributes( settings: window::Settings, title: &str, scale_factor: f32, primary_monitor: Option<winit::monitor::MonitorHandle>, _id: Option<String>, ) -> winit::window::WindowAttributes { let mut attributes = winit::window::WindowAttributes::default(); let mut buttons = winit::window::WindowButtons::empty(); if settings.resizable { buttons |= winit::window::WindowButtons::MAXIMIZE; } if settings.closeable { buttons |= winit::window::WindowButtons::CLOSE; } if settings.minimizable { buttons |= winit::window::WindowButtons::MINIMIZE; } attributes = attributes .with_title(title) .with_inner_size(winit::dpi::LogicalSize { width: settings.size.width * scale_factor, height: settings.size.height * scale_factor, }) .with_maximized(settings.maximized) .with_fullscreen( settings .fullscreen .then_some(winit::window::Fullscreen::Borderless(None)), ) .with_resizable(settings.resizable) .with_enabled_buttons(buttons) .with_decorations(settings.decorations) .with_transparent(settings.transparent) .with_blur(settings.blur) .with_window_icon(settings.icon.and_then(icon)) .with_window_level(window_level(settings.level)) .with_visible(settings.visible); if let Some(position) = position(primary_monitor.as_ref(), settings.size, settings.position) { attributes = attributes.with_position(position); } if let Some(min_size) = settings.min_size { attributes = attributes.with_min_inner_size(winit::dpi::LogicalSize { width: min_size.width, height: min_size.height, }); } if let Some(max_size) = settings.max_size { attributes = attributes.with_max_inner_size(winit::dpi::LogicalSize { width: max_size.width, height: max_size.height, }); } #[cfg(any( target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd" ))] { use ::winit::platform::wayland::WindowAttributesExtWayland; if let Some(id) = _id { attributes = attributes.with_name(id.clone(), id); } } #[cfg(target_os = "windows")] { use window::settings::platform; use winit::platform::windows::{CornerPreference, WindowAttributesExtWindows}; attributes = attributes.with_drag_and_drop(settings.platform_specific.drag_and_drop); attributes = attributes.with_skip_taskbar(settings.platform_specific.skip_taskbar); attributes = attributes.with_undecorated_shadow(settings.platform_specific.undecorated_shadow); attributes = attributes.with_corner_preference(match settings.platform_specific.corner_preference { platform::CornerPreference::Default => CornerPreference::Default, platform::CornerPreference::DoNotRound => CornerPreference::DoNotRound, platform::CornerPreference::Round => CornerPreference::Round, platform::CornerPreference::RoundSmall => CornerPreference::RoundSmall, }); } #[cfg(target_os = "macos")] { use winit::platform::macos::WindowAttributesExtMacOS; attributes = attributes .with_title_hidden(settings.platform_specific.title_hidden) .with_titlebar_transparent(settings.platform_specific.titlebar_transparent) .with_fullsize_content_view(settings.platform_specific.fullsize_content_view); } #[cfg(target_os = "linux")] { #[cfg(feature = "x11")] { use winit::platform::x11::WindowAttributesExtX11; attributes = attributes .with_override_redirect(settings.platform_specific.override_redirect) .with_name( &settings.platform_specific.application_id, &settings.platform_specific.application_id, ); } #[cfg(feature = "wayland")] { use winit::platform::wayland::WindowAttributesExtWayland; attributes = attributes.with_name( &settings.platform_specific.application_id, &settings.platform_specific.application_id, ); } } attributes } /// Converts a winit window event into an iced event. pub fn window_event( event: winit::event::WindowEvent, scale_factor: f32, modifiers: winit::keyboard::ModifiersState, ) -> Option<Event> { use winit::event::Ime; use winit::event::WindowEvent; match event { WindowEvent::Resized(new_size) => { let logical_size = new_size.to_logical(f64::from(scale_factor)); Some(Event::Window(window::Event::Resized(Size { width: logical_size.width, height: logical_size.height, }))) } WindowEvent::CloseRequested => Some(Event::Window(window::Event::CloseRequested)), WindowEvent::CursorMoved { position, .. } => { let position = position.to_logical::<f64>(f64::from(scale_factor)); Some(Event::Mouse(mouse::Event::CursorMoved { position: Point::new(position.x as f32, position.y as f32), })) } WindowEvent::CursorEntered { .. } => Some(Event::Mouse(mouse::Event::CursorEntered)), WindowEvent::CursorLeft { .. } => Some(Event::Mouse(mouse::Event::CursorLeft)), WindowEvent::MouseInput { button, state, .. } => { let button = mouse_button(button); Some(Event::Mouse(match state { winit::event::ElementState::Pressed => mouse::Event::ButtonPressed(button), winit::event::ElementState::Released => mouse::Event::ButtonReleased(button), })) } WindowEvent::MouseWheel { delta, .. } => match delta { winit::event::MouseScrollDelta::LineDelta(delta_x, delta_y) => { Some(Event::Mouse(mouse::Event::WheelScrolled { delta: mouse::ScrollDelta::Lines { x: delta_x, y: delta_y, }, })) } winit::event::MouseScrollDelta::PixelDelta(position) => { Some(Event::Mouse(mouse::Event::WheelScrolled { delta: mouse::ScrollDelta::Pixels { x: position.x as f32, y: position.y as f32, }, })) } }, // Ignore keyboard presses/releases during window focus/unfocus WindowEvent::KeyboardInput { is_synthetic, .. } if is_synthetic => None, WindowEvent::KeyboardInput { event, .. } => Some(Event::Keyboard({ let key = { #[cfg(not(target_arch = "wasm32"))] { use winit::platform::modifier_supplement::KeyEventExtModifierSupplement; event.key_without_modifiers() } #[cfg(target_arch = "wasm32")] { // TODO: Fix inconsistent API on Wasm event.logical_key.clone() } }; let text = { #[cfg(not(target_arch = "wasm32"))] { use crate::core::SmolStr; use winit::platform::modifier_supplement::KeyEventExtModifierSupplement; event.text_with_all_modifiers().map(SmolStr::new) } #[cfg(target_arch = "wasm32")] { // TODO: Fix inconsistent API on Wasm event.text } } .filter(|text| !text.as_str().chars().any(is_private_use)); let winit::event::KeyEvent { state, location, logical_key, physical_key, repeat, .. } = event; let key = self::key(key); let modified_key = self::key(logical_key); let physical_key = self::physical_key(physical_key); let modifiers = self::modifiers(modifiers); let location = match location { winit::keyboard::KeyLocation::Standard => keyboard::Location::Standard, winit::keyboard::KeyLocation::Left => keyboard::Location::Left, winit::keyboard::KeyLocation::Right => keyboard::Location::Right, winit::keyboard::KeyLocation::Numpad => keyboard::Location::Numpad, }; match state { winit::event::ElementState::Pressed => keyboard::Event::KeyPressed { key, modified_key, physical_key, modifiers, location, text, repeat, }, winit::event::ElementState::Released => keyboard::Event::KeyReleased { key, modified_key, physical_key, modifiers, location, }, } })), WindowEvent::ModifiersChanged(new_modifiers) => Some(Event::Keyboard( keyboard::Event::ModifiersChanged(self::modifiers(new_modifiers.state())), )), WindowEvent::Ime(event) => Some(Event::InputMethod(match event { Ime::Enabled => input_method::Event::Opened, Ime::Preedit(content, size) => { input_method::Event::Preedit(content, size.map(|(start, end)| start..end)) } Ime::Commit(content) => input_method::Event::Commit(content), Ime::Disabled => input_method::Event::Closed, })), WindowEvent::Focused(focused) => Some(Event::Window(if focused { window::Event::Focused } else { window::Event::Unfocused })), WindowEvent::HoveredFile(path) => { Some(Event::Window(window::Event::FileHovered(path.clone()))) } WindowEvent::DroppedFile(path) => { Some(Event::Window(window::Event::FileDropped(path.clone()))) } WindowEvent::HoveredFileCancelled => Some(Event::Window(window::Event::FilesHoveredLeft)), WindowEvent::Touch(touch) => Some(Event::Touch(touch_event(touch, scale_factor))), WindowEvent::Moved(position) => { let winit::dpi::LogicalPosition { x, y } = position.to_logical(f64::from(scale_factor)); Some(Event::Window(window::Event::Moved(Point::new(x, y)))) } WindowEvent::ScaleFactorChanged { scale_factor, .. } => { Some(Event::Window(window::Event::Rescaled(scale_factor as f32))) } _ => None, } } /// Converts a [`window::Level`] into a [`winit`] window level. /// /// [`winit`]: https://github.com/rust-windowing/winit pub fn window_level(level: window::Level) -> winit::window::WindowLevel { match level { window::Level::Normal => winit::window::WindowLevel::Normal, window::Level::AlwaysOnBottom => winit::window::WindowLevel::AlwaysOnBottom, window::Level::AlwaysOnTop => winit::window::WindowLevel::AlwaysOnTop, } } /// Converts a [`window::Position`] into a [`winit`] logical position for a given monitor. /// /// [`winit`]: https://github.com/rust-windowing/winit pub fn position( monitor: Option<&winit::monitor::MonitorHandle>, size: Size, position: window::Position, ) -> Option<winit::dpi::Position> { match position { window::Position::Default => None, window::Position::Specific(position) => { Some(winit::dpi::Position::Logical(winit::dpi::LogicalPosition { x: f64::from(position.x), y: f64::from(position.y), })) } window::Position::SpecificWith(to_position) => { if let Some(monitor) = monitor { let start = monitor.position(); let resolution: winit::dpi::LogicalSize<f32> = monitor.size().to_logical(monitor.scale_factor()); let position = to_position(size, Size::new(resolution.width, resolution.height)); let centered: winit::dpi::PhysicalPosition<i32> = winit::dpi::LogicalPosition { x: position.x, y: position.y, } .to_physical(monitor.scale_factor()); Some(winit::dpi::Position::Physical( winit::dpi::PhysicalPosition { x: start.x + centered.x, y: start.y + centered.y, }, )) } else { None } } window::Position::Centered => { if let Some(monitor) = monitor { let start = monitor.position(); let resolution: winit::dpi::LogicalSize<f64> = monitor.size().to_logical(monitor.scale_factor()); let centered: winit::dpi::PhysicalPosition<i32> = winit::dpi::LogicalPosition { x: (resolution.width - f64::from(size.width)) / 2.0, y: (resolution.height - f64::from(size.height)) / 2.0, } .to_physical(monitor.scale_factor()); Some(winit::dpi::Position::Physical( winit::dpi::PhysicalPosition { x: start.x + centered.x, y: start.y + centered.y, }, )) } else { None } } } } /// Converts a [`window::Mode`] into a [`winit`] fullscreen mode. /// /// [`winit`]: https://github.com/rust-windowing/winit pub fn fullscreen( monitor: Option<winit::monitor::MonitorHandle>, mode: window::Mode, ) -> Option<winit::window::Fullscreen> { match mode { window::Mode::Windowed | window::Mode::Hidden => None, window::Mode::Fullscreen => Some(winit::window::Fullscreen::Borderless(monitor)), } } /// Converts a [`window::Mode`] into a visibility flag. pub fn visible(mode: window::Mode) -> bool { match mode { window::Mode::Windowed | window::Mode::Fullscreen => true, window::Mode::Hidden => false, } } /// Converts a [`winit`] fullscreen mode into a [`window::Mode`]. /// /// [`winit`]: https://github.com/rust-windowing/winit pub fn mode(mode: Option<winit::window::Fullscreen>) -> window::Mode { match mode { None => window::Mode::Windowed, Some(_) => window::Mode::Fullscreen, } } /// Converts a [`winit`] window theme into a [`theme::Mode`]. /// /// [`winit`]: https://github.com/rust-windowing/winit pub fn theme_mode(theme: winit::window::Theme) -> theme::Mode { match theme { winit::window::Theme::Light => theme::Mode::Light, winit::window::Theme::Dark => theme::Mode::Dark, } } /// Converts a [`theme::Mode`] into a window theme. /// /// [`winit`]: https://github.com/rust-windowing/winit pub fn window_theme(mode: theme::Mode) -> Option<winit::window::Theme> { match mode { theme::Mode::None => None, theme::Mode::Light => Some(winit::window::Theme::Light), theme::Mode::Dark => Some(winit::window::Theme::Dark), } } /// Converts a [`mouse::Interaction`] into a [`winit`] cursor icon. /// /// [`winit`]: https://github.com/rust-windowing/winit pub fn mouse_interaction(interaction: mouse::Interaction) -> Option<winit::window::CursorIcon> { use mouse::Interaction; let icon = match interaction { Interaction::Hidden => { return None; } Interaction::None | Interaction::Idle => winit::window::CursorIcon::Default, Interaction::ContextMenu => winit::window::CursorIcon::ContextMenu, Interaction::Help => winit::window::CursorIcon::Help, Interaction::Pointer => winit::window::CursorIcon::Pointer, Interaction::Progress => winit::window::CursorIcon::Progress, Interaction::Wait => winit::window::CursorIcon::Wait, Interaction::Cell => winit::window::CursorIcon::Cell, Interaction::Crosshair => winit::window::CursorIcon::Crosshair, Interaction::Text => winit::window::CursorIcon::Text, Interaction::Alias => winit::window::CursorIcon::Alias, Interaction::Copy => winit::window::CursorIcon::Copy, Interaction::Move => winit::window::CursorIcon::Move, Interaction::NoDrop => winit::window::CursorIcon::NoDrop, Interaction::NotAllowed => winit::window::CursorIcon::NotAllowed, Interaction::Grab => winit::window::CursorIcon::Grab, Interaction::Grabbing => winit::window::CursorIcon::Grabbing, Interaction::ResizingHorizontally => winit::window::CursorIcon::EwResize, Interaction::ResizingVertically => winit::window::CursorIcon::NsResize, Interaction::ResizingDiagonallyUp => winit::window::CursorIcon::NeswResize, Interaction::ResizingDiagonallyDown => winit::window::CursorIcon::NwseResize, Interaction::ResizingColumn => winit::window::CursorIcon::ColResize, Interaction::ResizingRow => winit::window::CursorIcon::RowResize, Interaction::AllScroll => winit::window::CursorIcon::AllScroll, Interaction::ZoomIn => winit::window::CursorIcon::ZoomIn, Interaction::ZoomOut => winit::window::CursorIcon::ZoomOut, }; Some(icon) } /// Converts a `MouseButton` from [`winit`] to an [`iced`] mouse button. /// /// [`winit`]: https://github.com/rust-windowing/winit /// [`iced`]: https://github.com/iced-rs/iced/tree/0.12 pub fn mouse_button(mouse_button: winit::event::MouseButton) -> mouse::Button { match mouse_button { winit::event::MouseButton::Left => mouse::Button::Left, winit::event::MouseButton::Right => mouse::Button::Right, winit::event::MouseButton::Middle => mouse::Button::Middle, winit::event::MouseButton::Back => mouse::Button::Back, winit::event::MouseButton::Forward => mouse::Button::Forward, winit::event::MouseButton::Other(other) => mouse::Button::Other(other), } } /// Converts some `ModifiersState` from [`winit`] to an [`iced`] modifiers /// state. /// /// [`winit`]: https://github.com/rust-windowing/winit /// [`iced`]: https://github.com/iced-rs/iced/tree/0.12 pub fn modifiers(modifiers: winit::keyboard::ModifiersState) -> keyboard::Modifiers { let mut result = keyboard::Modifiers::empty(); result.set(keyboard::Modifiers::SHIFT, modifiers.shift_key()); result.set(keyboard::Modifiers::CTRL, modifiers.control_key()); result.set(keyboard::Modifiers::ALT, modifiers.alt_key()); result.set(keyboard::Modifiers::LOGO, modifiers.super_key()); result } /// Converts a physical cursor position into a logical `Point`. pub fn cursor_position(position: winit::dpi::PhysicalPosition<f64>, scale_factor: f32) -> Point { let logical_position = position.to_logical(f64::from(scale_factor)); Point::new(logical_position.x, logical_position.y) } /// Converts a `Touch` from [`winit`] to an [`iced`] touch event. /// /// [`winit`]: https://github.com/rust-windowing/winit /// [`iced`]: https://github.com/iced-rs/iced/tree/0.12 pub fn touch_event(touch: winit::event::Touch, scale_factor: f32) -> touch::Event { let id = touch::Finger(touch.id); let position = { let location = touch.location.to_logical::<f64>(f64::from(scale_factor)); Point::new(location.x as f32, location.y as f32) }; match touch.phase { winit::event::TouchPhase::Started => touch::Event::FingerPressed { id, position }, winit::event::TouchPhase::Moved => touch::Event::FingerMoved { id, position }, winit::event::TouchPhase::Ended => touch::Event::FingerLifted { id, position }, winit::event::TouchPhase::Cancelled => touch::Event::FingerLost { id, position }, } } /// Converts a `Key` from [`winit`] to an [`iced`] key. /// /// [`winit`]: https://github.com/rust-windowing/winit /// [`iced`]: https://github.com/iced-rs/iced/tree/0.12 pub fn key(key: winit::keyboard::Key) -> keyboard::Key { use keyboard::key::Named; use winit::keyboard::NamedKey; match key { winit::keyboard::Key::Character(c) => keyboard::Key::Character(c), winit::keyboard::Key::Named(named_key) => keyboard::Key::Named(match named_key { NamedKey::Alt => Named::Alt, NamedKey::AltGraph => Named::AltGraph, NamedKey::CapsLock => Named::CapsLock, NamedKey::Control => Named::Control, NamedKey::Fn => Named::Fn, NamedKey::FnLock => Named::FnLock, NamedKey::NumLock => Named::NumLock, NamedKey::ScrollLock => Named::ScrollLock, NamedKey::Shift => Named::Shift, NamedKey::Symbol => Named::Symbol, NamedKey::SymbolLock => Named::SymbolLock, NamedKey::Meta => Named::Meta, NamedKey::Hyper => Named::Hyper, NamedKey::Super => Named::Super, NamedKey::Enter => Named::Enter, NamedKey::Tab => Named::Tab, NamedKey::Space => Named::Space, NamedKey::ArrowDown => Named::ArrowDown, NamedKey::ArrowLeft => Named::ArrowLeft, NamedKey::ArrowRight => Named::ArrowRight, NamedKey::ArrowUp => Named::ArrowUp, NamedKey::End => Named::End, NamedKey::Home => Named::Home, NamedKey::PageDown => Named::PageDown, NamedKey::PageUp => Named::PageUp, NamedKey::Backspace => Named::Backspace, NamedKey::Clear => Named::Clear, NamedKey::Copy => Named::Copy, NamedKey::CrSel => Named::CrSel, NamedKey::Cut => Named::Cut, NamedKey::Delete => Named::Delete, NamedKey::EraseEof => Named::EraseEof, NamedKey::ExSel => Named::ExSel, NamedKey::Insert => Named::Insert, NamedKey::Paste => Named::Paste, NamedKey::Redo => Named::Redo, NamedKey::Undo => Named::Undo, NamedKey::Accept => Named::Accept, NamedKey::Again => Named::Again, NamedKey::Attn => Named::Attn, NamedKey::Cancel => Named::Cancel, NamedKey::ContextMenu => Named::ContextMenu, NamedKey::Escape => Named::Escape, NamedKey::Execute => Named::Execute, NamedKey::Find => Named::Find, NamedKey::Help => Named::Help, NamedKey::Pause => Named::Pause, NamedKey::Play => Named::Play, NamedKey::Props => Named::Props, NamedKey::Select => Named::Select, NamedKey::ZoomIn => Named::ZoomIn, NamedKey::ZoomOut => Named::ZoomOut, NamedKey::BrightnessDown => Named::BrightnessDown, NamedKey::BrightnessUp => Named::BrightnessUp, NamedKey::Eject => Named::Eject, NamedKey::LogOff => Named::LogOff, NamedKey::Power => Named::Power, NamedKey::PowerOff => Named::PowerOff, NamedKey::PrintScreen => Named::PrintScreen, NamedKey::Hibernate => Named::Hibernate, NamedKey::Standby => Named::Standby, NamedKey::WakeUp => Named::WakeUp, NamedKey::AllCandidates => Named::AllCandidates, NamedKey::Alphanumeric => Named::Alphanumeric, NamedKey::CodeInput => Named::CodeInput, NamedKey::Compose => Named::Compose, NamedKey::Convert => Named::Convert, NamedKey::FinalMode => Named::FinalMode, NamedKey::GroupFirst => Named::GroupFirst, NamedKey::GroupLast => Named::GroupLast, NamedKey::GroupNext => Named::GroupNext, NamedKey::GroupPrevious => Named::GroupPrevious, NamedKey::ModeChange => Named::ModeChange, NamedKey::NextCandidate => Named::NextCandidate, NamedKey::NonConvert => Named::NonConvert, NamedKey::PreviousCandidate => Named::PreviousCandidate, NamedKey::Process => Named::Process, NamedKey::SingleCandidate => Named::SingleCandidate, NamedKey::HangulMode => Named::HangulMode, NamedKey::HanjaMode => Named::HanjaMode, NamedKey::JunjaMode => Named::JunjaMode, NamedKey::Eisu => Named::Eisu, NamedKey::Hankaku => Named::Hankaku, NamedKey::Hiragana => Named::Hiragana, NamedKey::HiraganaKatakana => Named::HiraganaKatakana, NamedKey::KanaMode => Named::KanaMode, NamedKey::KanjiMode => Named::KanjiMode, NamedKey::Katakana => Named::Katakana, NamedKey::Romaji => Named::Romaji, NamedKey::Zenkaku => Named::Zenkaku, NamedKey::ZenkakuHankaku => Named::ZenkakuHankaku, NamedKey::Soft1 => Named::Soft1, NamedKey::Soft2 => Named::Soft2, NamedKey::Soft3 => Named::Soft3, NamedKey::Soft4 => Named::Soft4, NamedKey::ChannelDown => Named::ChannelDown, NamedKey::ChannelUp => Named::ChannelUp, NamedKey::Close => Named::Close, NamedKey::MailForward => Named::MailForward, NamedKey::MailReply => Named::MailReply, NamedKey::MailSend => Named::MailSend, NamedKey::MediaClose => Named::MediaClose, NamedKey::MediaFastForward => Named::MediaFastForward, NamedKey::MediaPause => Named::MediaPause, NamedKey::MediaPlay => Named::MediaPlay, NamedKey::MediaPlayPause => Named::MediaPlayPause, NamedKey::MediaRecord => Named::MediaRecord, NamedKey::MediaRewind => Named::MediaRewind, NamedKey::MediaStop => Named::MediaStop, NamedKey::MediaTrackNext => Named::MediaTrackNext, NamedKey::MediaTrackPrevious => Named::MediaTrackPrevious, NamedKey::New => Named::New, NamedKey::Open => Named::Open, NamedKey::Print => Named::Print, NamedKey::Save => Named::Save, NamedKey::SpellCheck => Named::SpellCheck, NamedKey::Key11 => Named::Key11, NamedKey::Key12 => Named::Key12, NamedKey::AudioBalanceLeft => Named::AudioBalanceLeft, NamedKey::AudioBalanceRight => Named::AudioBalanceRight, NamedKey::AudioBassBoostDown => Named::AudioBassBoostDown, NamedKey::AudioBassBoostToggle => Named::AudioBassBoostToggle, NamedKey::AudioBassBoostUp => Named::AudioBassBoostUp, NamedKey::AudioFaderFront => Named::AudioFaderFront, NamedKey::AudioFaderRear => Named::AudioFaderRear, NamedKey::AudioSurroundModeNext => Named::AudioSurroundModeNext, NamedKey::AudioTrebleDown => Named::AudioTrebleDown, NamedKey::AudioTrebleUp => Named::AudioTrebleUp, NamedKey::AudioVolumeDown => Named::AudioVolumeDown, NamedKey::AudioVolumeUp => Named::AudioVolumeUp, NamedKey::AudioVolumeMute => Named::AudioVolumeMute, NamedKey::MicrophoneToggle => Named::MicrophoneToggle, NamedKey::MicrophoneVolumeDown => Named::MicrophoneVolumeDown, NamedKey::MicrophoneVolumeUp => Named::MicrophoneVolumeUp, NamedKey::MicrophoneVolumeMute => Named::MicrophoneVolumeMute, NamedKey::SpeechCorrectionList => Named::SpeechCorrectionList, NamedKey::SpeechInputToggle => Named::SpeechInputToggle, NamedKey::LaunchApplication1 => Named::LaunchApplication1, NamedKey::LaunchApplication2 => Named::LaunchApplication2, NamedKey::LaunchCalendar => Named::LaunchCalendar, NamedKey::LaunchContacts => Named::LaunchContacts, NamedKey::LaunchMail => Named::LaunchMail, NamedKey::LaunchMediaPlayer => Named::LaunchMediaPlayer, NamedKey::LaunchMusicPlayer => Named::LaunchMusicPlayer, NamedKey::LaunchPhone => Named::LaunchPhone, NamedKey::LaunchScreenSaver => Named::LaunchScreenSaver, NamedKey::LaunchSpreadsheet => Named::LaunchSpreadsheet, NamedKey::LaunchWebBrowser => Named::LaunchWebBrowser, NamedKey::LaunchWebCam => Named::LaunchWebCam, NamedKey::LaunchWordProcessor => Named::LaunchWordProcessor, NamedKey::BrowserBack => Named::BrowserBack, NamedKey::BrowserFavorites => Named::BrowserFavorites, NamedKey::BrowserForward => Named::BrowserForward, NamedKey::BrowserHome => Named::BrowserHome, NamedKey::BrowserRefresh => Named::BrowserRefresh, NamedKey::BrowserSearch => Named::BrowserSearch, NamedKey::BrowserStop => Named::BrowserStop, NamedKey::AppSwitch => Named::AppSwitch, NamedKey::Call => Named::Call, NamedKey::Camera => Named::Camera, NamedKey::CameraFocus => Named::CameraFocus, NamedKey::EndCall => Named::EndCall, NamedKey::GoBack => Named::GoBack, NamedKey::GoHome => Named::GoHome, NamedKey::HeadsetHook => Named::HeadsetHook, NamedKey::LastNumberRedial => Named::LastNumberRedial, NamedKey::Notification => Named::Notification, NamedKey::MannerMode => Named::MannerMode, NamedKey::VoiceDial => Named::VoiceDial, NamedKey::TV => Named::TV, NamedKey::TV3DMode => Named::TV3DMode, NamedKey::TVAntennaCable => Named::TVAntennaCable, NamedKey::TVAudioDescription => Named::TVAudioDescription, NamedKey::TVAudioDescriptionMixDown => Named::TVAudioDescriptionMixDown, NamedKey::TVAudioDescriptionMixUp => Named::TVAudioDescriptionMixUp, NamedKey::TVContentsMenu => Named::TVContentsMenu, NamedKey::TVDataService => Named::TVDataService, NamedKey::TVInput => Named::TVInput, NamedKey::TVInputComponent1 => Named::TVInputComponent1, NamedKey::TVInputComponent2 => Named::TVInputComponent2, NamedKey::TVInputComposite1 => Named::TVInputComposite1, NamedKey::TVInputComposite2 => Named::TVInputComposite2, NamedKey::TVInputHDMI1 => Named::TVInputHDMI1, NamedKey::TVInputHDMI2 => Named::TVInputHDMI2, NamedKey::TVInputHDMI3 => Named::TVInputHDMI3, NamedKey::TVInputHDMI4 => Named::TVInputHDMI4, NamedKey::TVInputVGA1 => Named::TVInputVGA1, NamedKey::TVMediaContext => Named::TVMediaContext, NamedKey::TVNetwork => Named::TVNetwork, NamedKey::TVNumberEntry => Named::TVNumberEntry, NamedKey::TVPower => Named::TVPower, NamedKey::TVRadioService => Named::TVRadioService, NamedKey::TVSatellite => Named::TVSatellite, NamedKey::TVSatelliteBS => Named::TVSatelliteBS, NamedKey::TVSatelliteCS => Named::TVSatelliteCS, NamedKey::TVSatelliteToggle => Named::TVSatelliteToggle, NamedKey::TVTerrestrialAnalog => Named::TVTerrestrialAnalog, NamedKey::TVTerrestrialDigital => Named::TVTerrestrialDigital, NamedKey::TVTimer => Named::TVTimer, NamedKey::AVRInput => Named::AVRInput, NamedKey::AVRPower => Named::AVRPower, NamedKey::ColorF0Red => Named::ColorF0Red, NamedKey::ColorF1Green => Named::ColorF1Green, NamedKey::ColorF2Yellow => Named::ColorF2Yellow, NamedKey::ColorF3Blue => Named::ColorF3Blue, NamedKey::ColorF4Grey => Named::ColorF4Grey, NamedKey::ColorF5Brown => Named::ColorF5Brown,
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
true
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/winit/src/window.rs
winit/src/window.rs
mod state; use state::State; pub use crate::core::window::{Event, Id, RedrawRequest, Settings}; use crate::conversion; use crate::core::alignment; use crate::core::input_method; use crate::core::mouse; use crate::core::renderer; use crate::core::text; use crate::core::theme; use crate::core::time::Instant; use crate::core::{Color, InputMethod, Padding, Point, Rectangle, Size, Text, Vector}; use crate::graphics::Compositor; use crate::program::{self, Program}; use crate::runtime::window::raw_window_handle; use winit::dpi::{LogicalPosition, LogicalSize}; use winit::monitor::MonitorHandle; use std::collections::BTreeMap; use std::sync::Arc; pub struct WindowManager<P, C> where P: Program, C: Compositor<Renderer = P::Renderer>, P::Theme: theme::Base, { aliases: BTreeMap<winit::window::WindowId, Id>, entries: BTreeMap<Id, Window<P, C>>, } impl<P, C> WindowManager<P, C> where P: Program, C: Compositor<Renderer = P::Renderer>, P::Theme: theme::Base, { pub fn new() -> Self { Self { aliases: BTreeMap::new(), entries: BTreeMap::new(), } } pub fn insert( &mut self, id: Id, window: Arc<winit::window::Window>, program: &program::Instance<P>, compositor: &mut C, exit_on_close_request: bool, system_theme: theme::Mode, ) -> &mut Window<P, C> { let state = State::new(program, id, &window, system_theme); let surface_size = state.physical_size(); let surface_version = state.surface_version(); let surface = compositor.create_surface(window.clone(), surface_size.width, surface_size.height); let renderer = compositor.create_renderer(); let _ = self.aliases.insert(window.id(), id); let _ = self.entries.insert( id, Window { raw: window, state, exit_on_close_request, surface, surface_version, renderer, mouse_interaction: mouse::Interaction::None, redraw_at: None, preedit: None, ime_state: None, }, ); self.entries .get_mut(&id) .expect("Get window that was just inserted") } pub fn is_empty(&self) -> bool { self.entries.is_empty() } pub fn is_idle(&self) -> bool { self.entries .values() .all(|window| window.redraw_at.is_none()) } pub fn redraw_at(&self) -> Option<Instant> { self.entries .values() .filter_map(|window| window.redraw_at) .min() } pub fn first(&self) -> Option<&Window<P, C>> { self.entries.first_key_value().map(|(_id, window)| window) } pub fn iter_mut(&mut self) -> impl Iterator<Item = (Id, &mut Window<P, C>)> { self.entries.iter_mut().map(|(k, v)| (*k, v)) } pub fn get(&self, id: Id) -> Option<&Window<P, C>> { self.entries.get(&id) } pub fn get_mut(&mut self, id: Id) -> Option<&mut Window<P, C>> { self.entries.get_mut(&id) } pub fn get_mut_alias( &mut self, id: winit::window::WindowId, ) -> Option<(Id, &mut Window<P, C>)> { let id = self.aliases.get(&id).copied()?; Some((id, self.get_mut(id)?)) } pub fn last_monitor(&self) -> Option<MonitorHandle> { self.entries.values().last()?.raw.current_monitor() } pub fn remove(&mut self, id: Id) -> Option<Window<P, C>> { let window = self.entries.remove(&id)?; let _ = self.aliases.remove(&window.raw.id()); Some(window) } } impl<P, C> Default for WindowManager<P, C> where P: Program, C: Compositor<Renderer = P::Renderer>, P::Theme: theme::Base, { fn default() -> Self { Self::new() } } pub struct Window<P, C> where P: Program, C: Compositor<Renderer = P::Renderer>, P::Theme: theme::Base, { pub raw: Arc<winit::window::Window>, pub state: State<P>, pub exit_on_close_request: bool, pub mouse_interaction: mouse::Interaction, pub surface: C::Surface, pub surface_version: u64, pub renderer: P::Renderer, pub redraw_at: Option<Instant>, preedit: Option<Preedit<P::Renderer>>, ime_state: Option<(Rectangle, input_method::Purpose)>, } impl<P, C> Window<P, C> where P: Program, C: Compositor<Renderer = P::Renderer>, P::Theme: theme::Base, { pub fn position(&self) -> Option<Point> { self.raw .outer_position() .ok() .map(|position| position.to_logical(self.raw.scale_factor())) .map(|position| Point { x: position.x, y: position.y, }) } pub fn logical_size(&self) -> Size { self.state.logical_size() } pub fn request_redraw(&mut self, redraw_request: RedrawRequest) { match redraw_request { RedrawRequest::NextFrame => { self.raw.request_redraw(); self.redraw_at = None; } RedrawRequest::At(at) => { self.redraw_at = Some(at); } RedrawRequest::Wait => {} } } pub fn request_input_method(&mut self, input_method: InputMethod) { match input_method { InputMethod::Disabled => { self.disable_ime(); } InputMethod::Enabled { cursor, purpose, preedit, } => { self.enable_ime(cursor, purpose); if let Some(preedit) = preedit { if preedit.content.is_empty() { self.preedit = None; } else { let mut overlay = self.preedit.take().unwrap_or_else(Preedit::new); overlay.update( cursor, &preedit, self.state.background_color(), &self.renderer, ); self.preedit = Some(overlay); } } else { self.preedit = None; } } } } pub fn update_mouse(&mut self, interaction: mouse::Interaction) { if interaction != self.mouse_interaction { if let Some(icon) = conversion::mouse_interaction(interaction) { self.raw.set_cursor(icon); if self.mouse_interaction == mouse::Interaction::Hidden { self.raw.set_cursor_visible(true); } } else { self.raw.set_cursor_visible(false); } self.mouse_interaction = interaction; } } pub fn draw_preedit(&mut self) { if let Some(preedit) = &self.preedit { preedit.draw( &mut self.renderer, self.state.text_color(), self.state.background_color(), &Rectangle::new(Point::ORIGIN, self.state.viewport().logical_size()), ); } } fn enable_ime(&mut self, cursor: Rectangle, purpose: input_method::Purpose) { if self.ime_state.is_none() { self.raw.set_ime_allowed(true); } if self.ime_state != Some((cursor, purpose)) { self.raw.set_ime_cursor_area( LogicalPosition::new(cursor.x, cursor.y), LogicalSize::new(cursor.width, cursor.height), ); self.raw.set_ime_purpose(conversion::ime_purpose(purpose)); self.ime_state = Some((cursor, purpose)); } } fn disable_ime(&mut self) { if self.ime_state.is_some() { self.raw.set_ime_allowed(false); self.ime_state = None; } self.preedit = None; } } impl<P, C> raw_window_handle::HasWindowHandle for Window<P, C> where P: Program, C: Compositor<Renderer = P::Renderer>, { fn window_handle( &self, ) -> Result<raw_window_handle::WindowHandle<'_>, raw_window_handle::HandleError> { self.raw.window_handle() } } impl<P, C> raw_window_handle::HasDisplayHandle for Window<P, C> where P: Program, C: Compositor<Renderer = P::Renderer>, { fn display_handle( &self, ) -> Result<raw_window_handle::DisplayHandle<'_>, raw_window_handle::HandleError> { self.raw.display_handle() } } struct Preedit<Renderer> where Renderer: text::Renderer, { position: Point, content: Renderer::Paragraph, spans: Vec<text::Span<'static, (), Renderer::Font>>, } impl<Renderer> Preedit<Renderer> where Renderer: text::Renderer, { fn new() -> Self { Self { position: Point::ORIGIN, spans: Vec::new(), content: Renderer::Paragraph::default(), } } fn update( &mut self, cursor: Rectangle, preedit: &input_method::Preedit, background: Color, renderer: &Renderer, ) { self.position = cursor.position() + Vector::new(0.0, cursor.height); let background = Color { a: 1.0, ..background }; let spans = match &preedit.selection { Some(selection) => { vec![ text::Span::new(&preedit.content[..selection.start]), text::Span::new(if selection.start == selection.end { "\u{200A}" } else { &preedit.content[selection.start..selection.end] }) .color(background), text::Span::new(&preedit.content[selection.end..]), ] } _ => vec![text::Span::new(&preedit.content)], }; if spans != self.spans.as_slice() { use text::Paragraph as _; self.content = Renderer::Paragraph::with_spans(Text { content: &spans, bounds: Size::INFINITE, size: preedit.text_size.unwrap_or_else(|| renderer.default_size()), line_height: text::LineHeight::default(), font: renderer.default_font(), align_x: text::Alignment::Default, align_y: alignment::Vertical::Top, shaping: text::Shaping::Advanced, wrapping: text::Wrapping::None, hint_factor: renderer.scale_factor(), }); self.spans.clear(); self.spans .extend(spans.into_iter().map(text::Span::to_static)); } } fn draw(&self, renderer: &mut Renderer, color: Color, background: Color, viewport: &Rectangle) { use text::Paragraph as _; if self.content.min_width() < 1.0 { return; } let mut bounds = Rectangle::new( self.position - Vector::new(0.0, self.content.min_height()), self.content.min_bounds(), ); bounds.x = bounds .x .max(viewport.x) .min(viewport.x + viewport.width - bounds.width); bounds.y = bounds .y .max(viewport.y) .min(viewport.y + viewport.height - bounds.height); renderer.with_layer(bounds, |renderer| { let background = Color { a: 1.0, ..background }; renderer.fill_quad( renderer::Quad { bounds, ..Default::default() }, background, ); renderer.fill_paragraph(&self.content, bounds.position(), color, bounds); const UNDERLINE: f32 = 2.0; renderer.fill_quad( renderer::Quad { bounds: bounds.shrink(Padding { top: bounds.height - UNDERLINE, ..Default::default() }), ..Default::default() }, color, ); for span_bounds in self.content.span_bounds(1) { renderer.fill_quad( renderer::Quad { bounds: span_bounds + (bounds.position() - Point::ORIGIN), ..Default::default() }, color, ); } }); } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/winit/src/proxy.rs
winit/src/proxy.rs
use crate::futures::futures::{ Future, Sink, StreamExt, channel::mpsc, select, task::{Context, Poll}, }; use crate::graphics::shell; use crate::runtime::Action; use crate::runtime::window; use std::pin::Pin; /// An event loop proxy with backpressure that implements `Sink`. #[derive(Debug)] pub struct Proxy<T: 'static> { raw: winit::event_loop::EventLoopProxy<Action<T>>, sender: mpsc::Sender<Action<T>>, notifier: mpsc::Sender<usize>, } impl<T: 'static> Clone for Proxy<T> { fn clone(&self) -> Self { Self { raw: self.raw.clone(), sender: self.sender.clone(), notifier: self.notifier.clone(), } } } impl<T: 'static> Proxy<T> { const MAX_SIZE: usize = 100; /// Creates a new [`Proxy`] from an `EventLoopProxy`. pub fn new( raw: winit::event_loop::EventLoopProxy<Action<T>>, ) -> (Self, impl Future<Output = ()>) { let (notifier, mut processed) = mpsc::channel(Self::MAX_SIZE); let (sender, mut receiver) = mpsc::channel(Self::MAX_SIZE); let proxy = raw.clone(); let worker = async move { let mut count = 0; loop { if count < Self::MAX_SIZE { select! { message = receiver.select_next_some() => { let _ = proxy.send_event(message); count += 1; } amount = processed.select_next_some() => { count = count.saturating_sub(amount); } complete => break, } } else { select! { amount = processed.select_next_some() => { count = count.saturating_sub(amount); } complete => break, } } } }; ( Self { raw, sender, notifier, }, worker, ) } /// Sends a value to the event loop. /// /// Note: This skips the backpressure mechanism with an unbounded /// channel. Use sparingly! pub fn send(&self, value: T) { self.send_action(Action::Output(value)); } /// Sends an action to the event loop. /// /// Note: This skips the backpressure mechanism with an unbounded /// channel. Use sparingly! pub fn send_action(&self, action: Action<T>) { let _ = self.raw.send_event(action); } /// Frees an amount of slots for additional messages to be queued in /// this [`Proxy`]. pub fn free_slots(&mut self, amount: usize) { let _ = self.notifier.start_send(amount); } } impl<T: 'static> Sink<Action<T>> for Proxy<T> { type Error = mpsc::SendError; fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { self.sender.poll_ready(cx) } fn start_send(mut self: Pin<&mut Self>, action: Action<T>) -> Result<(), Self::Error> { self.sender.start_send(action) } fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { match self.sender.poll_ready(cx) { Poll::Ready(Err(ref e)) if e.is_disconnected() => { // If the receiver disconnected, we consider the sink to be flushed. Poll::Ready(Ok(())) } x => x, } } fn poll_close( mut self: Pin<&mut Self>, _cx: &mut Context<'_>, ) -> Poll<Result<(), Self::Error>> { self.sender.disconnect(); Poll::Ready(Ok(())) } } impl<T> shell::Notifier for Proxy<T> where T: Send, { fn tick(&self) { self.send_action(Action::Tick); } fn request_redraw(&self) { self.send_action(Action::Window(window::Action::RedrawAll)); } fn invalidate_layout(&self) { self.send_action(Action::Window(window::Action::RelayoutAll)); } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/winit/src/window/state.rs
winit/src/window/state.rs
use crate::conversion; use crate::core::{Color, Size}; use crate::core::{mouse, theme, window}; use crate::graphics::Viewport; use crate::program::{self, Program}; use winit::event::{Touch, WindowEvent}; use winit::window::Window; use std::fmt::{Debug, Formatter}; /// The state of the window of a [`Program`]. pub struct State<P: Program> where P::Theme: theme::Base, { title: String, scale_factor: f32, viewport: Viewport, surface_version: u64, cursor_position: Option<winit::dpi::PhysicalPosition<f64>>, modifiers: winit::keyboard::ModifiersState, theme: Option<P::Theme>, theme_mode: theme::Mode, default_theme: P::Theme, style: theme::Style, } impl<P: Program> Debug for State<P> where P::Theme: theme::Base, { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.debug_struct("window::State") .field("title", &self.title) .field("scale_factor", &self.scale_factor) .field("viewport", &self.viewport) .field("cursor_position", &self.cursor_position) .field("style", &self.style) .finish() } } impl<P: Program> State<P> where P::Theme: theme::Base, { /// Creates a new [`State`] for the provided [`Program`]'s `window`. pub fn new( program: &program::Instance<P>, window_id: window::Id, window: &Window, system_theme: theme::Mode, ) -> Self { let title = program.title(window_id); let scale_factor = program.scale_factor(window_id); let theme = program.theme(window_id); let theme_mode = theme.as_ref().map(theme::Base::mode).unwrap_or_default(); let default_theme = <P::Theme as theme::Base>::default(system_theme); let style = program.style(theme.as_ref().unwrap_or(&default_theme)); let viewport = { let physical_size = window.inner_size(); Viewport::with_physical_size( Size::new(physical_size.width, physical_size.height), window.scale_factor() as f32 * scale_factor, ) }; Self { title, scale_factor, viewport, surface_version: 0, cursor_position: None, modifiers: winit::keyboard::ModifiersState::default(), theme, theme_mode, default_theme, style, } } pub fn viewport(&self) -> &Viewport { &self.viewport } pub fn surface_version(&self) -> u64 { self.surface_version } pub fn physical_size(&self) -> Size<u32> { self.viewport.physical_size() } pub fn logical_size(&self) -> Size<f32> { self.viewport.logical_size() } pub fn scale_factor(&self) -> f32 { self.viewport.scale_factor() } pub fn cursor(&self) -> mouse::Cursor { self.cursor_position .map(|cursor_position| { conversion::cursor_position(cursor_position, self.viewport.scale_factor()) }) .map(mouse::Cursor::Available) .unwrap_or(mouse::Cursor::Unavailable) } pub fn modifiers(&self) -> winit::keyboard::ModifiersState { self.modifiers } pub fn theme(&self) -> &P::Theme { self.theme.as_ref().unwrap_or(&self.default_theme) } pub fn theme_mode(&self) -> theme::Mode { self.theme_mode } pub fn background_color(&self) -> Color { self.style.background_color } pub fn text_color(&self) -> Color { self.style.text_color } pub fn update(&mut self, program: &program::Instance<P>, window: &Window, event: &WindowEvent) { match event { WindowEvent::Resized(new_size) => { let size = Size::new(new_size.width, new_size.height); self.viewport = Viewport::with_physical_size( size, window.scale_factor() as f32 * self.scale_factor, ); self.surface_version += 1; } WindowEvent::ScaleFactorChanged { scale_factor: new_scale_factor, .. } => { let size = self.viewport.physical_size(); self.viewport = Viewport::with_physical_size( size, *new_scale_factor as f32 * self.scale_factor, ); self.surface_version += 1; } WindowEvent::CursorMoved { position, .. } | WindowEvent::Touch(Touch { location: position, .. }) => { self.cursor_position = Some(*position); } WindowEvent::CursorLeft { .. } => { self.cursor_position = None; } WindowEvent::ModifiersChanged(new_modifiers) => { self.modifiers = new_modifiers.state(); } WindowEvent::ThemeChanged(theme) => { self.default_theme = <P::Theme as theme::Base>::default(conversion::theme_mode(*theme)); if self.theme.is_none() { self.style = program.style(&self.default_theme); window.request_redraw(); } } _ => {} } } pub fn synchronize( &mut self, program: &program::Instance<P>, window_id: window::Id, window: &Window, ) { // Update window title let new_title = program.title(window_id); if self.title != new_title { window.set_title(&new_title); self.title = new_title; } // Update scale factor let new_scale_factor = program.scale_factor(window_id); if self.scale_factor != new_scale_factor { self.viewport = Viewport::with_physical_size( self.viewport.physical_size(), window.scale_factor() as f32 * new_scale_factor, ); self.scale_factor = new_scale_factor; } // Update theme and appearance self.theme = program.theme(window_id); self.style = program.style(self.theme()); let new_mode = self .theme .as_ref() .map(theme::Base::mode) .unwrap_or_default(); if self.theme_mode != new_mode { #[cfg(not(target_os = "linux"))] { window.set_theme(conversion::window_theme(new_mode)); // Assume the old mode matches the system one // We will be notified otherwise if new_mode == theme::Mode::None { self.default_theme = <P::Theme as theme::Base>::default(self.theme_mode); if self.theme.is_none() { self.style = program.style(&self.default_theme); } } } #[cfg(target_os = "linux")] { // mundy always notifies system theme changes, so we // just restore the default theme mode. let new_mode = if new_mode == theme::Mode::None { theme::Base::mode(&self.default_theme) } else { new_mode }; window.set_theme(conversion::window_theme(new_mode)); } self.theme_mode = new_mode; } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/program/src/lib.rs
program/src/lib.rs
//! The definition of an iced program. pub use iced_graphics as graphics; pub use iced_runtime as runtime; pub use iced_runtime::core; pub use iced_runtime::futures; pub mod message; mod preset; pub use preset::Preset; use crate::core::renderer; use crate::core::text; use crate::core::theme; use crate::core::window; use crate::core::{Element, Font, Settings}; use crate::futures::{Executor, Subscription}; use crate::graphics::compositor; use crate::runtime::Task; /// An interactive, native, cross-platform, multi-windowed application. /// /// A [`Program`] can execute asynchronous actions by returning a /// [`Task`] in some of its methods. #[allow(missing_docs)] pub trait Program: Sized { /// The state of the program. type State; /// The message of the program. type Message: Send + 'static; /// The theme of the program. type Theme: theme::Base; /// The renderer of the program. type Renderer: Renderer; /// The executor of the program. type Executor: Executor; /// Returns the unique name of the [`Program`]. fn name() -> &'static str; fn settings(&self) -> Settings; fn window(&self) -> Option<window::Settings>; fn boot(&self) -> (Self::State, Task<Self::Message>); fn update(&self, state: &mut Self::State, message: Self::Message) -> Task<Self::Message>; fn view<'a>( &self, state: &'a Self::State, window: window::Id, ) -> Element<'a, Self::Message, Self::Theme, Self::Renderer>; fn title(&self, _state: &Self::State, _window: window::Id) -> String { let mut title = String::new(); for (i, part) in Self::name().split("_").enumerate() { use std::borrow::Cow; let part = match part { "a" | "an" | "of" | "in" | "and" => Cow::Borrowed(part), _ => { let mut part = part.to_owned(); if let Some(first_letter) = part.get_mut(0..1) { first_letter.make_ascii_uppercase(); } Cow::Owned(part) } }; if i > 0 { title.push(' '); } title.push_str(&part); } format!("{title} - Iced") } fn subscription(&self, _state: &Self::State) -> Subscription<Self::Message> { Subscription::none() } fn theme(&self, _state: &Self::State, _window: window::Id) -> Option<Self::Theme> { None } fn style(&self, _state: &Self::State, theme: &Self::Theme) -> theme::Style { theme::Base::base(theme) } fn scale_factor(&self, _state: &Self::State, _window: window::Id) -> f32 { 1.0 } fn presets(&self) -> &[Preset<Self::State, Self::Message>] { &[] } } /// Decorates a [`Program`] with the given title function. pub fn with_title<P: Program>( program: P, title: impl Fn(&P::State, window::Id) -> String, ) -> impl Program<State = P::State, Message = P::Message, Theme = P::Theme> { struct WithTitle<P, Title> { program: P, title: Title, } impl<P, Title> Program for WithTitle<P, Title> where P: Program, Title: Fn(&P::State, window::Id) -> String, { type State = P::State; type Message = P::Message; type Theme = P::Theme; type Renderer = P::Renderer; type Executor = P::Executor; fn title(&self, state: &Self::State, window: window::Id) -> String { (self.title)(state, window) } fn name() -> &'static str { P::name() } fn settings(&self) -> Settings { self.program.settings() } fn window(&self) -> Option<window::Settings> { self.program.window() } fn boot(&self) -> (Self::State, Task<Self::Message>) { self.program.boot() } fn update(&self, state: &mut Self::State, message: Self::Message) -> Task<Self::Message> { self.program.update(state, message) } fn view<'a>( &self, state: &'a Self::State, window: window::Id, ) -> Element<'a, Self::Message, Self::Theme, Self::Renderer> { self.program.view(state, window) } fn theme(&self, state: &Self::State, window: window::Id) -> Option<Self::Theme> { self.program.theme(state, window) } fn subscription(&self, state: &Self::State) -> Subscription<Self::Message> { self.program.subscription(state) } fn style(&self, state: &Self::State, theme: &Self::Theme) -> theme::Style { self.program.style(state, theme) } fn scale_factor(&self, state: &Self::State, window: window::Id) -> f32 { self.program.scale_factor(state, window) } } WithTitle { program, title } } /// Decorates a [`Program`] with the given subscription function. pub fn with_subscription<P: Program>( program: P, f: impl Fn(&P::State) -> Subscription<P::Message>, ) -> impl Program<State = P::State, Message = P::Message, Theme = P::Theme> { struct WithSubscription<P, F> { program: P, subscription: F, } impl<P: Program, F> Program for WithSubscription<P, F> where F: Fn(&P::State) -> Subscription<P::Message>, { type State = P::State; type Message = P::Message; type Theme = P::Theme; type Renderer = P::Renderer; type Executor = P::Executor; fn subscription(&self, state: &Self::State) -> Subscription<Self::Message> { (self.subscription)(state) } fn name() -> &'static str { P::name() } fn settings(&self) -> Settings { self.program.settings() } fn window(&self) -> Option<window::Settings> { self.program.window() } fn boot(&self) -> (Self::State, Task<Self::Message>) { self.program.boot() } fn update(&self, state: &mut Self::State, message: Self::Message) -> Task<Self::Message> { self.program.update(state, message) } fn view<'a>( &self, state: &'a Self::State, window: window::Id, ) -> Element<'a, Self::Message, Self::Theme, Self::Renderer> { self.program.view(state, window) } fn title(&self, state: &Self::State, window: window::Id) -> String { self.program.title(state, window) } fn theme(&self, state: &Self::State, window: window::Id) -> Option<Self::Theme> { self.program.theme(state, window) } fn style(&self, state: &Self::State, theme: &Self::Theme) -> theme::Style { self.program.style(state, theme) } fn scale_factor(&self, state: &Self::State, window: window::Id) -> f32 { self.program.scale_factor(state, window) } } WithSubscription { program, subscription: f, } } /// Decorates a [`Program`] with the given theme function. pub fn with_theme<P: Program>( program: P, f: impl Fn(&P::State, window::Id) -> Option<P::Theme>, ) -> impl Program<State = P::State, Message = P::Message, Theme = P::Theme> { struct WithTheme<P, F> { program: P, theme: F, } impl<P: Program, F> Program for WithTheme<P, F> where F: Fn(&P::State, window::Id) -> Option<P::Theme>, { type State = P::State; type Message = P::Message; type Theme = P::Theme; type Renderer = P::Renderer; type Executor = P::Executor; fn theme(&self, state: &Self::State, window: window::Id) -> Option<Self::Theme> { (self.theme)(state, window) } fn name() -> &'static str { P::name() } fn settings(&self) -> Settings { self.program.settings() } fn window(&self) -> Option<window::Settings> { self.program.window() } fn boot(&self) -> (Self::State, Task<Self::Message>) { self.program.boot() } fn title(&self, state: &Self::State, window: window::Id) -> String { self.program.title(state, window) } fn update(&self, state: &mut Self::State, message: Self::Message) -> Task<Self::Message> { self.program.update(state, message) } fn view<'a>( &self, state: &'a Self::State, window: window::Id, ) -> Element<'a, Self::Message, Self::Theme, Self::Renderer> { self.program.view(state, window) } fn subscription(&self, state: &Self::State) -> Subscription<Self::Message> { self.program.subscription(state) } fn style(&self, state: &Self::State, theme: &Self::Theme) -> theme::Style { self.program.style(state, theme) } fn scale_factor(&self, state: &Self::State, window: window::Id) -> f32 { self.program.scale_factor(state, window) } } WithTheme { program, theme: f } } /// Decorates a [`Program`] with the given style function. pub fn with_style<P: Program>( program: P, f: impl Fn(&P::State, &P::Theme) -> theme::Style, ) -> impl Program<State = P::State, Message = P::Message, Theme = P::Theme> { struct WithStyle<P, F> { program: P, style: F, } impl<P: Program, F> Program for WithStyle<P, F> where F: Fn(&P::State, &P::Theme) -> theme::Style, { type State = P::State; type Message = P::Message; type Theme = P::Theme; type Renderer = P::Renderer; type Executor = P::Executor; fn style(&self, state: &Self::State, theme: &Self::Theme) -> theme::Style { (self.style)(state, theme) } fn name() -> &'static str { P::name() } fn settings(&self) -> Settings { self.program.settings() } fn window(&self) -> Option<window::Settings> { self.program.window() } fn boot(&self) -> (Self::State, Task<Self::Message>) { self.program.boot() } fn title(&self, state: &Self::State, window: window::Id) -> String { self.program.title(state, window) } fn update(&self, state: &mut Self::State, message: Self::Message) -> Task<Self::Message> { self.program.update(state, message) } fn view<'a>( &self, state: &'a Self::State, window: window::Id, ) -> Element<'a, Self::Message, Self::Theme, Self::Renderer> { self.program.view(state, window) } fn subscription(&self, state: &Self::State) -> Subscription<Self::Message> { self.program.subscription(state) } fn theme(&self, state: &Self::State, window: window::Id) -> Option<Self::Theme> { self.program.theme(state, window) } fn scale_factor(&self, state: &Self::State, window: window::Id) -> f32 { self.program.scale_factor(state, window) } } WithStyle { program, style: f } } /// Decorates a [`Program`] with the given scale factor function. pub fn with_scale_factor<P: Program>( program: P, f: impl Fn(&P::State, window::Id) -> f32, ) -> impl Program<State = P::State, Message = P::Message, Theme = P::Theme> { struct WithScaleFactor<P, F> { program: P, scale_factor: F, } impl<P: Program, F> Program for WithScaleFactor<P, F> where F: Fn(&P::State, window::Id) -> f32, { type State = P::State; type Message = P::Message; type Theme = P::Theme; type Renderer = P::Renderer; type Executor = P::Executor; fn title(&self, state: &Self::State, window: window::Id) -> String { self.program.title(state, window) } fn name() -> &'static str { P::name() } fn settings(&self) -> Settings { self.program.settings() } fn window(&self) -> Option<window::Settings> { self.program.window() } fn boot(&self) -> (Self::State, Task<Self::Message>) { self.program.boot() } fn update(&self, state: &mut Self::State, message: Self::Message) -> Task<Self::Message> { self.program.update(state, message) } fn view<'a>( &self, state: &'a Self::State, window: window::Id, ) -> Element<'a, Self::Message, Self::Theme, Self::Renderer> { self.program.view(state, window) } fn subscription(&self, state: &Self::State) -> Subscription<Self::Message> { self.program.subscription(state) } fn theme(&self, state: &Self::State, window: window::Id) -> Option<Self::Theme> { self.program.theme(state, window) } fn style(&self, state: &Self::State, theme: &Self::Theme) -> theme::Style { self.program.style(state, theme) } fn scale_factor(&self, state: &Self::State, window: window::Id) -> f32 { (self.scale_factor)(state, window) } } WithScaleFactor { program, scale_factor: f, } } /// Decorates a [`Program`] with the given executor function. pub fn with_executor<P: Program, E: Executor>( program: P, ) -> impl Program<State = P::State, Message = P::Message, Theme = P::Theme> { use std::marker::PhantomData; struct WithExecutor<P, E> { program: P, executor: PhantomData<E>, } impl<P: Program, E> Program for WithExecutor<P, E> where E: Executor, { type State = P::State; type Message = P::Message; type Theme = P::Theme; type Renderer = P::Renderer; type Executor = E; fn title(&self, state: &Self::State, window: window::Id) -> String { self.program.title(state, window) } fn name() -> &'static str { P::name() } fn settings(&self) -> Settings { self.program.settings() } fn window(&self) -> Option<window::Settings> { self.program.window() } fn boot(&self) -> (Self::State, Task<Self::Message>) { self.program.boot() } fn update(&self, state: &mut Self::State, message: Self::Message) -> Task<Self::Message> { self.program.update(state, message) } fn view<'a>( &self, state: &'a Self::State, window: window::Id, ) -> Element<'a, Self::Message, Self::Theme, Self::Renderer> { self.program.view(state, window) } fn subscription(&self, state: &Self::State) -> Subscription<Self::Message> { self.program.subscription(state) } fn theme(&self, state: &Self::State, window: window::Id) -> Option<Self::Theme> { self.program.theme(state, window) } fn style(&self, state: &Self::State, theme: &Self::Theme) -> theme::Style { self.program.style(state, theme) } fn scale_factor(&self, state: &Self::State, window: window::Id) -> f32 { self.program.scale_factor(state, window) } } WithExecutor { program, executor: PhantomData::<E>, } } /// The renderer of some [`Program`]. pub trait Renderer: text::Renderer<Font = Font> + compositor::Default + renderer::Headless {} impl<T> Renderer for T where T: text::Renderer<Font = Font> + compositor::Default + renderer::Headless { } /// A particular instance of a running [`Program`]. pub struct Instance<P: Program> { program: P, state: P::State, } impl<P: Program> Instance<P> { /// Creates a new [`Instance`] of the given [`Program`]. pub fn new(program: P) -> (Self, Task<P::Message>) { let (state, task) = program.boot(); (Self { program, state }, task) } /// Returns the current title of the [`Instance`]. pub fn title(&self, window: window::Id) -> String { self.program.title(&self.state, window) } /// Processes the given message and updates the [`Instance`]. pub fn update(&mut self, message: P::Message) -> Task<P::Message> { self.program.update(&mut self.state, message) } /// Produces the current widget tree of the [`Instance`]. pub fn view(&self, window: window::Id) -> Element<'_, P::Message, P::Theme, P::Renderer> { self.program.view(&self.state, window) } /// Returns the current [`Subscription`] of the [`Instance`]. pub fn subscription(&self) -> Subscription<P::Message> { self.program.subscription(&self.state) } /// Returns the current theme of the [`Instance`]. pub fn theme(&self, window: window::Id) -> Option<P::Theme> { self.program.theme(&self.state, window) } /// Returns the current [`theme::Style`] of the [`Instance`]. pub fn style(&self, theme: &P::Theme) -> theme::Style { self.program.style(&self.state, theme) } /// Returns the current scale factor of the [`Instance`]. pub fn scale_factor(&self, window: window::Id) -> f32 { self.program.scale_factor(&self.state, window) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/program/src/preset.rs
program/src/preset.rs
use crate::runtime::Task; use std::borrow::Cow; use std::fmt; /// A specific boot strategy for a [`Program`](crate::Program). pub struct Preset<State, Message> { name: Cow<'static, str>, boot: Box<dyn Fn() -> (State, Task<Message>)>, } impl<State, Message> Preset<State, Message> { /// Creates a new [`Preset`] with the given name and boot strategy. pub fn new( name: impl Into<Cow<'static, str>>, boot: impl Fn() -> (State, Task<Message>) + 'static, ) -> Self { Self { name: name.into(), boot: Box::new(boot), } } /// Returns the name of the [`Preset`]. pub fn name(&self) -> &str { &self.name } /// Boots the [`Preset`], returning the initial [`Program`](crate::Program) state and /// a [`Task`] for concurrent booting. pub fn boot(&self) -> (State, Task<Message>) { (self.boot)() } } impl<State, Message> fmt::Debug for Preset<State, Message> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Preset") .field("name", &self.name) .finish_non_exhaustive() } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/program/src/message.rs
program/src/message.rs
//! Traits for the message type of a [`Program`](crate::Program). /// A trait alias for [`Clone`], but only when the `time-travel` /// feature is enabled. #[cfg(feature = "time-travel")] pub trait MaybeClone: Clone {} #[cfg(feature = "time-travel")] impl<T> MaybeClone for T where T: Clone {} /// A trait alias for [`Clone`], but only when the `time-travel` /// feature is enabled. #[cfg(not(feature = "time-travel"))] pub trait MaybeClone {} #[cfg(not(feature = "time-travel"))] impl<T> MaybeClone for T {} /// A trait alias for [`Debug`](std::fmt::Debug), but only when the /// `debug` feature is enabled. #[cfg(feature = "debug")] pub trait MaybeDebug: std::fmt::Debug {} #[cfg(feature = "debug")] impl<T> MaybeDebug for T where T: std::fmt::Debug {} /// A trait alias for [`Debug`](std::fmt::Debug), but only when the /// `debug` feature is enabled. #[cfg(not(feature = "debug"))] pub trait MaybeDebug {} #[cfg(not(feature = "debug"))] impl<T> MaybeDebug for T {}
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/graphics/src/viewport.rs
graphics/src/viewport.rs
use crate::core::{Size, Transformation}; /// A viewing region for displaying computer graphics. #[derive(Debug, Clone)] pub struct Viewport { physical_size: Size<u32>, logical_size: Size<f32>, scale_factor: f32, projection: Transformation, } impl Viewport { /// Creates a new [`Viewport`] with the given physical dimensions and scale /// factor. pub fn with_physical_size(size: Size<u32>, scale_factor: f32) -> Viewport { Viewport { physical_size: size, logical_size: Size::new( size.width as f32 / scale_factor, size.height as f32 / scale_factor, ), scale_factor, projection: Transformation::orthographic(size.width, size.height), } } /// Returns the physical size of the [`Viewport`]. pub fn physical_size(&self) -> Size<u32> { self.physical_size } /// Returns the physical width of the [`Viewport`]. pub fn physical_width(&self) -> u32 { self.physical_size.width } /// Returns the physical height of the [`Viewport`]. pub fn physical_height(&self) -> u32 { self.physical_size.height } /// Returns the logical size of the [`Viewport`]. pub fn logical_size(&self) -> Size<f32> { self.logical_size } /// Returns the scale factor of the [`Viewport`]. pub fn scale_factor(&self) -> f32 { self.scale_factor } /// Returns the projection transformation of the [`Viewport`]. pub fn projection(&self) -> Transformation { self.projection } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/graphics/src/settings.rs
graphics/src/settings.rs
use crate::Antialiasing; use crate::core::{self, Font, Pixels}; /// The settings of a renderer. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Settings { /// The default [`Font`] to use. pub default_font: Font, /// The default size of text. /// /// By default, it will be set to `16.0`. pub default_text_size: Pixels, /// The antialiasing strategy that will be used for triangle primitives. /// /// By default, it is `None`. pub antialiasing: Option<Antialiasing>, /// Whether or not to synchronize frames. /// /// By default, it is `true`. pub vsync: bool, } impl Default for Settings { fn default() -> Settings { Settings { default_font: Font::default(), default_text_size: Pixels(16.0), antialiasing: None, vsync: true, } } } impl From<core::Settings> for Settings { fn from(settings: core::Settings) -> Self { Self { default_font: if cfg!(all(target_arch = "wasm32", feature = "fira-sans")) && settings.default_font == Font::default() { Font::with_name("Fira Sans") } else { settings.default_font }, default_text_size: settings.default_text_size, antialiasing: settings.antialiasing.then_some(Antialiasing::MSAAx4), vsync: settings.vsync, } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/graphics/src/lib.rs
graphics/src/lib.rs
//! A bunch of backend-agnostic types that can be leveraged to build a renderer //! for [`iced`]. //! //! ![The native path of the Iced ecosystem](https://github.com/iced-rs/iced/blob/0525d76ff94e828b7b21634fa94a747022001c83/docs/graphs/native.png?raw=true) //! //! [`iced`]: https://github.com/iced-rs/iced #![doc( html_logo_url = "https://raw.githubusercontent.com/iced-rs/iced/9ab6923e943f784985e9ef9ca28b10278297225d/docs/logo.svg" )] #![cfg_attr(docsrs, feature(doc_cfg))] mod antialiasing; mod settings; mod viewport; pub mod cache; pub mod color; pub mod compositor; pub mod damage; pub mod error; pub mod gradient; pub mod image; pub mod layer; pub mod mesh; pub mod shell; pub mod text; #[cfg(feature = "geometry")] pub mod geometry; pub use antialiasing::Antialiasing; pub use cache::Cache; pub use compositor::Compositor; pub use error::Error; pub use gradient::Gradient; pub use image::Image; pub use layer::Layer; pub use mesh::Mesh; pub use settings::Settings; pub use shell::Shell; pub use text::Text; pub use viewport::Viewport; pub use iced_core as core; pub use iced_futures as futures;
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/graphics/src/image.rs
graphics/src/image.rs
//! Load and operate on images. #[cfg(feature = "image")] use crate::core::Bytes; use crate::core::Rectangle; use crate::core::image; use crate::core::svg; /// A raster or vector image. #[allow(missing_docs)] #[derive(Debug, Clone, PartialEq)] pub enum Image { /// A raster image. Raster { image: image::Image, bounds: Rectangle, clip_bounds: Rectangle, }, /// A vector image. Vector { svg: svg::Svg, bounds: Rectangle, clip_bounds: Rectangle, }, } impl Image { /// Returns the bounds of the [`Image`]. pub fn bounds(&self) -> Rectangle { match self { Image::Raster { image, bounds, .. } => bounds.rotate(image.rotation), Image::Vector { svg, bounds, .. } => bounds.rotate(svg.rotation), } } } /// An image buffer. #[cfg(feature = "image")] pub type Buffer = ::image::ImageBuffer<::image::Rgba<u8>, Bytes>; #[cfg(feature = "image")] /// Tries to load an image by its [`Handle`]. /// /// [`Handle`]: image::Handle pub fn load(handle: &image::Handle) -> Result<Buffer, image::Error> { use bitflags::bitflags; bitflags! { struct Operation: u8 { const FLIP_HORIZONTALLY = 0b1; const ROTATE_180 = 0b10; const FLIP_VERTICALLY= 0b100; const ROTATE_90 = 0b1000; const ROTATE_270 = 0b10000; } } impl Operation { // Meaning of the returned value is described e.g. at: // https://magnushoff.com/articles/jpeg-orientation/ fn from_exif<R>(reader: &mut R) -> Result<Self, exif::Error> where R: std::io::BufRead + std::io::Seek, { let exif = exif::Reader::new().read_from_container(reader)?; Ok(exif .get_field(exif::Tag::Orientation, exif::In::PRIMARY) .and_then(|field| field.value.get_uint(0)) .and_then(|value| u8::try_from(value).ok()) .map(|value| match value { 1 => Operation::empty(), 2 => Operation::FLIP_HORIZONTALLY, 3 => Operation::ROTATE_180, 4 => Operation::FLIP_VERTICALLY, 5 => Operation::ROTATE_90 | Operation::FLIP_HORIZONTALLY, 6 => Operation::ROTATE_90, 7 => Operation::ROTATE_90 | Operation::FLIP_VERTICALLY, 8 => Operation::ROTATE_270, _ => Operation::empty(), }) .unwrap_or_else(Self::empty)) } fn perform(self, mut image: ::image::DynamicImage) -> ::image::DynamicImage { use ::image::imageops; if self.contains(Operation::ROTATE_90) { image = imageops::rotate90(&image).into(); } if self.contains(Self::ROTATE_180) { imageops::rotate180_in_place(&mut image); } if self.contains(Operation::ROTATE_270) { image = imageops::rotate270(&image).into(); } if self.contains(Self::FLIP_VERTICALLY) { imageops::flip_vertical_in_place(&mut image); } if self.contains(Self::FLIP_HORIZONTALLY) { imageops::flip_horizontal_in_place(&mut image); } image } } let (width, height, pixels) = match handle { image::Handle::Path(_, path) => { let image = ::image::open(path).map_err(to_error)?; let operation = std::fs::File::open(path) .ok() .map(std::io::BufReader::new) .and_then(|mut reader| Operation::from_exif(&mut reader).ok()) .unwrap_or_else(Operation::empty); let rgba = operation.perform(image).into_rgba8(); (rgba.width(), rgba.height(), Bytes::from(rgba.into_raw())) } image::Handle::Bytes(_, bytes) => { let image = ::image::load_from_memory(bytes).map_err(to_error)?; let operation = Operation::from_exif(&mut std::io::Cursor::new(bytes)) .ok() .unwrap_or_else(Operation::empty); let rgba = operation.perform(image).into_rgba8(); (rgba.width(), rgba.height(), Bytes::from(rgba.into_raw())) } image::Handle::Rgba { width, height, pixels, .. } => (*width, *height, pixels.clone()), }; if let Some(image) = ::image::ImageBuffer::from_raw(width, height, pixels) { Ok(image) } else { Err(to_error(::image::error::ImageError::Limits( ::image::error::LimitError::from_kind(::image::error::LimitErrorKind::DimensionError), ))) } } #[cfg(feature = "image")] fn to_error(error: ::image::ImageError) -> image::Error { use std::sync::Arc; match error { ::image::ImageError::IoError(error) => image::Error::Inaccessible(Arc::new(error)), error => image::Error::Invalid(Arc::new(error)), } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/graphics/src/geometry.rs
graphics/src/geometry.rs
//! Build and draw geometry. pub mod fill; pub mod frame; pub mod path; pub mod stroke; mod cache; mod style; mod text; pub use cache::Cache; pub use fill::Fill; pub use frame::Frame; pub use path::Path; pub use stroke::{LineCap, LineDash, LineJoin, Stroke}; pub use style::Style; pub use text::Text; pub use crate::core::{Image, Svg}; pub use crate::gradient::{self, Gradient}; use crate::cache::Cached; use crate::core::{self, Rectangle}; /// A renderer capable of drawing some [`Self::Geometry`]. pub trait Renderer: core::Renderer { /// The kind of geometry this renderer can draw. type Geometry: Cached; /// The kind of [`Frame`] this renderer supports. type Frame: frame::Backend<Geometry = Self::Geometry>; /// Creates a new [`Self::Frame`]. fn new_frame(&self, bounds: Rectangle) -> Self::Frame; /// Draws the given [`Self::Geometry`]. fn draw_geometry(&mut self, geometry: Self::Geometry); } #[cfg(debug_assertions)] impl Renderer for () { type Geometry = (); type Frame = (); fn new_frame(&self, _bounds: Rectangle) -> Self::Frame {} fn draw_geometry(&mut self, _geometry: Self::Geometry) {} }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/graphics/src/shell.rs
graphics/src/shell.rs
//! Control the windowing runtime from a renderer. use std::sync::Arc; /// A windowing shell. #[derive(Clone)] pub struct Shell(Arc<dyn Notifier>); impl Shell { /// Creates a new [`Shell`]. pub fn new(notifier: impl Notifier) -> Self { Self(Arc::new(notifier)) } /// Creates a headless [`Shell`]. pub fn headless() -> Self { struct Headless; impl Notifier for Headless { fn tick(&self) {} fn request_redraw(&self) {} fn invalidate_layout(&self) {} } Self::new(Headless) } /// Requests for [`Renderer::tick`](crate::core::Renderer::tick) to /// be called by the [`Shell`]. pub fn tick(&self) { self.0.tick(); } /// Requests for all windows of the [`Shell`] to be redrawn. pub fn request_redraw(&self) { self.0.request_redraw(); } /// Requests for all layouts of the [`Shell`] to be recomputed. pub fn invalidate_layout(&self) { self.0.invalidate_layout(); } } /// A type that can notify a shell of certain events. pub trait Notifier: Send + Sync + 'static { /// Requests for [`Renderer::tick`](crate::core::Renderer::tick) to /// be called by the [`Shell`]. fn tick(&self); /// Requests for all windows of the [`Shell`] to be redrawn. fn request_redraw(&self); /// Requests for all layouts of the [`Shell`] to be recomputed. fn invalidate_layout(&self); }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/graphics/src/antialiasing.rs
graphics/src/antialiasing.rs
/// An antialiasing strategy. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Antialiasing { /// Multisample AA with 2 samples MSAAx2, /// Multisample AA with 4 samples MSAAx4, /// Multisample AA with 8 samples MSAAx8, /// Multisample AA with 16 samples MSAAx16, } impl Antialiasing { /// Returns the amount of samples of the [`Antialiasing`]. pub fn sample_count(self) -> u32 { match self { Antialiasing::MSAAx2 => 2, Antialiasing::MSAAx4 => 4, Antialiasing::MSAAx8 => 8, Antialiasing::MSAAx16 => 16, } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/graphics/src/mesh.rs
graphics/src/mesh.rs
//! Draw triangles! use crate::color; use crate::core::{Rectangle, Transformation}; use crate::gradient; use bytemuck::{Pod, Zeroable}; use std::sync::atomic::{self, AtomicU64}; use std::sync::{Arc, Weak}; /// A low-level primitive to render a mesh of triangles. #[derive(Debug, Clone, PartialEq)] pub enum Mesh { /// A mesh with a solid color. Solid { /// The vertices and indices of the mesh. buffers: Indexed<SolidVertex2D>, /// The [`Transformation`] for the vertices of the [`Mesh`]. transformation: Transformation, /// The clip bounds of the [`Mesh`]. clip_bounds: Rectangle, }, /// A mesh with a gradient. Gradient { /// The vertices and indices of the mesh. buffers: Indexed<GradientVertex2D>, /// The [`Transformation`] for the vertices of the [`Mesh`]. transformation: Transformation, /// The clip bounds of the [`Mesh`]. clip_bounds: Rectangle, }, } impl Mesh { /// Returns the indices of the [`Mesh`]. pub fn indices(&self) -> &[u32] { match self { Self::Solid { buffers, .. } => &buffers.indices, Self::Gradient { buffers, .. } => &buffers.indices, } } /// Returns the [`Transformation`] of the [`Mesh`]. pub fn transformation(&self) -> Transformation { match self { Self::Solid { transformation, .. } | Self::Gradient { transformation, .. } => { *transformation } } } /// Returns the clip bounds of the [`Mesh`]. pub fn clip_bounds(&self) -> Rectangle { match self { Self::Solid { clip_bounds, transformation, .. } | Self::Gradient { clip_bounds, transformation, .. } => *clip_bounds * *transformation, } } } /// A set of vertices and indices representing a list of triangles. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Indexed<T> { /// The vertices of the mesh pub vertices: Vec<T>, /// The list of vertex indices that defines the triangles of the mesh. /// /// Therefore, this list should always have a length that is a multiple of 3. pub indices: Vec<u32>, } /// A two-dimensional vertex with a color. #[derive(Copy, Clone, Debug, PartialEq, Zeroable, Pod)] #[repr(C)] pub struct SolidVertex2D { /// The vertex position in 2D space. pub position: [f32; 2], /// The color of the vertex in __linear__ RGBA. pub color: color::Packed, } /// A vertex which contains 2D position & packed gradient data. #[derive(Copy, Clone, Debug, PartialEq, Zeroable, Pod)] #[repr(C)] pub struct GradientVertex2D { /// The vertex position in 2D space. pub position: [f32; 2], /// The packed vertex data of the gradient. pub gradient: gradient::Packed, } /// The result of counting the attributes of a set of meshes. #[derive(Debug, Clone, Copy, Default)] pub struct AttributeCount { /// The total amount of solid vertices. pub solid_vertices: usize, /// The total amount of solid meshes. pub solids: usize, /// The total amount of gradient vertices. pub gradient_vertices: usize, /// The total amount of gradient meshes. pub gradients: usize, /// The total amount of indices. pub indices: usize, } /// Returns the number of total vertices & total indices of all [`Mesh`]es. pub fn attribute_count_of(meshes: &[Mesh]) -> AttributeCount { meshes .iter() .fold(AttributeCount::default(), |mut count, mesh| { match mesh { Mesh::Solid { buffers, .. } => { count.solids += 1; count.solid_vertices += buffers.vertices.len(); count.indices += buffers.indices.len(); } Mesh::Gradient { buffers, .. } => { count.gradients += 1; count.gradient_vertices += buffers.vertices.len(); count.indices += buffers.indices.len(); } } count }) } /// A cache of multiple meshes. #[derive(Debug, Clone)] pub struct Cache { id: Id, batch: Arc<[Mesh]>, version: usize, } /// The unique id of a [`Cache`]. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Id(u64); impl Cache { /// Creates a new [`Cache`] for the given meshes. pub fn new(meshes: Arc<[Mesh]>) -> Self { static NEXT_ID: AtomicU64 = AtomicU64::new(0); Self { id: Id(NEXT_ID.fetch_add(1, atomic::Ordering::Relaxed)), batch: meshes, version: 0, } } /// Returns the [`Id`] of the [`Cache`]. pub fn id(&self) -> Id { self.id } /// Returns the current version of the [`Cache`]. pub fn version(&self) -> usize { self.version } /// Returns the batch of meshes in the [`Cache`]. pub fn batch(&self) -> &[Mesh] { &self.batch } /// Returns a [`Weak`] reference to the contents of the [`Cache`]. pub fn downgrade(&self) -> Weak<[Mesh]> { Arc::downgrade(&self.batch) } /// Returns true if the [`Cache`] is empty. pub fn is_empty(&self) -> bool { self.batch.is_empty() } /// Updates the [`Cache`] with the given meshes. pub fn update(&mut self, meshes: Arc<[Mesh]>) { self.batch = meshes; self.version += 1; } } /// A renderer capable of drawing a [`Mesh`]. pub trait Renderer { /// Draws the given [`Mesh`]. fn draw_mesh(&mut self, mesh: Mesh); /// Draws the given [`Cache`]. fn draw_mesh_cache(&mut self, cache: Cache); }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/graphics/src/layer.rs
graphics/src/layer.rs
//! Draw and stack layers of graphical primitives. use crate::core::{Rectangle, Transformation}; /// A layer of graphical primitives. /// /// Layers normally dictate a set of primitives that are /// rendered in a specific order. pub trait Layer: Default { /// Creates a new [`Layer`] with the given bounds. fn with_bounds(bounds: Rectangle) -> Self; /// Returns the current bounds of the [`Layer`]. fn bounds(&self) -> Rectangle; /// Flushes and settles any pending group of primitives in the [`Layer`]. /// /// This will be called when a [`Layer`] is finished. It allows layers to efficiently /// record primitives together and defer grouping until the end. fn flush(&mut self); /// Resizes the [`Layer`] to the given bounds. fn resize(&mut self, bounds: Rectangle); /// Clears all the layers contents and resets its bounds. fn reset(&mut self); /// Returns the start level of the [`Layer`]. /// /// A level is a "sublayer" index inside of a [`Layer`]. /// /// A [`Layer`] may draw multiple primitive types in a certain order. /// The level represents the lowest index of the primitive types it /// contains. /// /// Two layers A and B can therefore be merged if they have the same bounds, /// and the end level of A is lower or equal than the start level of B. fn start(&self) -> usize; /// Returns the end level of the [`Layer`]. fn end(&self) -> usize; /// Merges a [`Layer`] with the current one. fn merge(&mut self, _layer: &mut Self); } /// A stack of layers used for drawing. #[derive(Debug)] pub struct Stack<T: Layer> { layers: Vec<T>, transformations: Vec<Transformation>, previous: Vec<usize>, current: usize, active_count: usize, } impl<T: Layer> Stack<T> { /// Creates a new empty [`Stack`]. pub fn new() -> Self { Self { layers: vec![T::default()], transformations: vec![Transformation::IDENTITY], previous: vec![], current: 0, active_count: 1, } } /// Returns a mutable reference to the current [`Layer`] of the [`Stack`], together with /// the current [`Transformation`]. #[inline] pub fn current_mut(&mut self) -> (&mut T, Transformation) { let transformation = self.transformation(); (&mut self.layers[self.current], transformation) } /// Returns the current [`Transformation`] of the [`Stack`]. #[inline] pub fn transformation(&self) -> Transformation { self.transformations.last().copied().unwrap() } /// Pushes a new clipping region in the [`Stack`]; creating a new layer in the /// process. pub fn push_clip(&mut self, bounds: Rectangle) { self.previous.push(self.current); self.current = self.active_count; self.active_count += 1; let bounds = bounds * self.transformation(); if self.current == self.layers.len() { self.layers.push(T::with_bounds(bounds)); } else { self.layers[self.current].resize(bounds); } } /// Pops the current clipping region from the [`Stack`] and restores the previous one. /// /// The current layer will be recorded for drawing. pub fn pop_clip(&mut self) { self.flush(); self.current = self.previous.pop().unwrap(); } /// Pushes a new [`Transformation`] in the [`Stack`]. /// /// Future drawing operations will be affected by this new [`Transformation`] until /// it is popped using [`pop_transformation`]. /// /// [`pop_transformation`]: Self::pop_transformation pub fn push_transformation(&mut self, transformation: Transformation) { self.transformations .push(self.transformation() * transformation); } /// Pops the current [`Transformation`] in the [`Stack`]. pub fn pop_transformation(&mut self) { let _ = self.transformations.pop(); } /// Returns an iterator over immutable references to the layers in the [`Stack`]. pub fn iter(&self) -> impl Iterator<Item = &T> { self.layers[..self.active_count].iter() } /// Returns the slice of layers in the [`Stack`]. pub fn as_slice(&self) -> &[T] { &self.layers[..self.active_count] } /// Flushes and settles any primitives in the [`Stack`]. pub fn flush(&mut self) { self.layers[self.current].flush(); } /// Performs layer merging wherever possible. /// /// Flushes and settles any primitives in the [`Stack`]. pub fn merge(&mut self) { self.flush(); // These are the layers left to process let mut left = self.active_count; // There must be at least 2 or more layers to merge while left > 1 { // We set our target as the topmost layer left to process let mut current = left - 1; let mut target = &self.layers[current]; let mut target_start = target.start(); let mut target_index = current; // We scan downwards for a contiguous block of mergeable layer candidates while current > 0 { let candidate = &self.layers[current - 1]; let start = candidate.start(); let end = candidate.end(); // We skip empty layers if end == 0 { current -= 1; continue; } // Candidate can be merged if primitive sublayers do not overlap with // previous targets and the clipping bounds match if end > target_start || candidate.bounds() != target.bounds() { break; } // Candidate is not empty and can be merged into target = candidate; target_start = start; target_index = current; current -= 1; } // We merge all the layers scanned into the target // // Since we use `target_index` instead of `current`, we // deliberately avoid merging into empty layers. // // If no candidates were mergeable, this is a no-op. let (head, tail) = self.layers.split_at_mut(target_index + 1); let layer = &mut head[target_index]; for middle in &mut tail[0..left - target_index - 1] { layer.merge(middle); } // Empty layers found after the target can be skipped left = current; } } /// Clears the layers of the [`Stack`], allowing reuse. /// /// It resizes the base layer bounds to the `new_bounds`. /// /// This will normally keep layer allocations for future drawing operations. pub fn reset(&mut self, new_bounds: Rectangle) { for layer in self.layers[..self.active_count].iter_mut() { layer.reset(); } self.layers[0].resize(new_bounds); self.current = 0; self.active_count = 1; self.previous.clear(); } } impl<T: Layer> Default for Stack<T> { fn default() -> Self { Self::new() } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/graphics/src/text.rs
graphics/src/text.rs
//! Draw text. pub mod cache; pub mod editor; pub mod paragraph; pub use cache::Cache; pub use editor::Editor; pub use paragraph::Paragraph; pub use cosmic_text; use crate::core::alignment; use crate::core::font::{self, Font}; use crate::core::text::{Alignment, Shaping, Wrapping}; use crate::core::{Color, Pixels, Point, Rectangle, Size, Transformation}; use std::borrow::Cow; use std::collections::HashSet; use std::sync::{Arc, OnceLock, RwLock, Weak}; /// A text primitive. #[derive(Debug, Clone, PartialEq)] pub enum Text { /// A paragraph. #[allow(missing_docs)] Paragraph { paragraph: paragraph::Weak, position: Point, color: Color, clip_bounds: Rectangle, transformation: Transformation, }, /// An editor. #[allow(missing_docs)] Editor { editor: editor::Weak, position: Point, color: Color, clip_bounds: Rectangle, transformation: Transformation, }, /// Some cached text. Cached { /// The contents of the text. content: String, /// The bounds of the text. bounds: Rectangle, /// The color of the text. color: Color, /// The size of the text in logical pixels. size: Pixels, /// The line height of the text. line_height: Pixels, /// The font of the text. font: Font, /// The horizontal alignment of the text. align_x: Alignment, /// The vertical alignment of the text. align_y: alignment::Vertical, /// The shaping strategy of the text. shaping: Shaping, /// The clip bounds of the text. clip_bounds: Rectangle, }, /// Some raw text. #[allow(missing_docs)] Raw { raw: Raw, transformation: Transformation, }, } impl Text { /// Returns the visible bounds of the [`Text`]. pub fn visible_bounds(&self) -> Option<Rectangle> { match self { Text::Paragraph { position, paragraph, clip_bounds, transformation, .. } => Rectangle::new(*position, paragraph.min_bounds) .intersection(clip_bounds) .map(|bounds| bounds * *transformation), Text::Editor { editor, position, clip_bounds, transformation, .. } => Rectangle::new(*position, editor.bounds) .intersection(clip_bounds) .map(|bounds| bounds * *transformation), Text::Cached { bounds, clip_bounds, .. } => bounds.intersection(clip_bounds), Text::Raw { raw, .. } => Some(raw.clip_bounds), } } } /// The regular variant of the [Fira Sans] font. /// /// It is loaded as part of the default fonts when the `fira-sans` /// feature is enabled. /// /// [Fira Sans]: https://mozilla.github.io/Fira/ #[cfg(feature = "fira-sans")] pub const FIRA_SANS_REGULAR: &[u8] = include_bytes!("../fonts/FiraSans-Regular.ttf").as_slice(); /// Returns the global [`FontSystem`]. pub fn font_system() -> &'static RwLock<FontSystem> { static FONT_SYSTEM: OnceLock<RwLock<FontSystem>> = OnceLock::new(); FONT_SYSTEM.get_or_init(|| { RwLock::new(FontSystem { raw: cosmic_text::FontSystem::new_with_fonts([ cosmic_text::fontdb::Source::Binary(Arc::new( include_bytes!("../fonts/Iced-Icons.ttf").as_slice(), )), #[cfg(feature = "fira-sans")] cosmic_text::fontdb::Source::Binary(Arc::new( include_bytes!("../fonts/FiraSans-Regular.ttf").as_slice(), )), ]), loaded_fonts: HashSet::new(), version: Version::default(), }) }) } /// A set of system fonts. pub struct FontSystem { raw: cosmic_text::FontSystem, loaded_fonts: HashSet<usize>, version: Version, } impl FontSystem { /// Returns the raw [`cosmic_text::FontSystem`]. pub fn raw(&mut self) -> &mut cosmic_text::FontSystem { &mut self.raw } /// Loads a font from its bytes. pub fn load_font(&mut self, bytes: Cow<'static, [u8]>) { if let Cow::Borrowed(bytes) = bytes { let address = bytes.as_ptr() as usize; if !self.loaded_fonts.insert(address) { return; } } let _ = self .raw .db_mut() .load_font_source(cosmic_text::fontdb::Source::Binary(Arc::new( bytes.into_owned(), ))); self.version = Version(self.version.0 + 1); } /// Returns the current [`Version`] of the [`FontSystem`]. /// /// Loading a font will increase the version of a [`FontSystem`]. pub fn version(&self) -> Version { self.version } } /// A version number. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] pub struct Version(u32); /// A weak reference to a [`cosmic_text::Buffer`] that can be drawn. #[derive(Debug, Clone)] pub struct Raw { /// A weak reference to a [`cosmic_text::Buffer`]. pub buffer: Weak<cosmic_text::Buffer>, /// The position of the text. pub position: Point, /// The color of the text. pub color: Color, /// The clip bounds of the text. pub clip_bounds: Rectangle, } impl PartialEq for Raw { fn eq(&self, _other: &Self) -> bool { // TODO: There is no proper way to compare raw buffers // For now, no two instances of `Raw` text will be equal. // This should be fine, but could trigger unnecessary redraws // in the future. false } } /// Measures the dimensions of the given [`cosmic_text::Buffer`]. pub fn measure(buffer: &cosmic_text::Buffer) -> (Size, bool) { let (width, height, has_rtl) = buffer .layout_runs() .fold((0.0, 0.0, false), |(width, height, has_rtl), run| { ( run.line_w.max(width), height + run.line_height, has_rtl || run.rtl, ) }); (Size::new(width, height), has_rtl) } /// Aligns the given [`cosmic_text::Buffer`] with the given [`Alignment`] /// and returns its minimum [`Size`]. pub fn align( buffer: &mut cosmic_text::Buffer, font_system: &mut cosmic_text::FontSystem, alignment: Alignment, ) -> Size { let (min_bounds, has_rtl) = measure(buffer); let mut needs_relayout = has_rtl; if let Some(align) = to_align(alignment) { let has_multiple_lines = buffer.lines.len() > 1 || buffer .lines .first() .is_some_and(|line| line.layout_opt().is_some_and(|layout| layout.len() > 1)); if has_multiple_lines { for line in &mut buffer.lines { let _ = line.set_align(Some(align)); } needs_relayout = true; } else if let Some(line) = buffer.lines.first_mut() { needs_relayout = line.set_align(None); } } // TODO: Avoid relayout with some changes to `cosmic-text` (?) if needs_relayout { log::trace!("Relayouting paragraph..."); buffer.set_size(font_system, Some(min_bounds.width), Some(min_bounds.height)); } min_bounds } /// Returns the attributes of the given [`Font`]. pub fn to_attributes(font: Font) -> cosmic_text::Attrs<'static> { cosmic_text::Attrs::new() .family(to_family(font.family)) .weight(to_weight(font.weight)) .stretch(to_stretch(font.stretch)) .style(to_style(font.style)) } fn to_family(family: font::Family) -> cosmic_text::Family<'static> { match family { font::Family::Name(name) => cosmic_text::Family::Name(name), font::Family::SansSerif => cosmic_text::Family::SansSerif, font::Family::Serif => cosmic_text::Family::Serif, font::Family::Cursive => cosmic_text::Family::Cursive, font::Family::Fantasy => cosmic_text::Family::Fantasy, font::Family::Monospace => cosmic_text::Family::Monospace, } } fn to_weight(weight: font::Weight) -> cosmic_text::Weight { match weight { font::Weight::Thin => cosmic_text::Weight::THIN, font::Weight::ExtraLight => cosmic_text::Weight::EXTRA_LIGHT, font::Weight::Light => cosmic_text::Weight::LIGHT, font::Weight::Normal => cosmic_text::Weight::NORMAL, font::Weight::Medium => cosmic_text::Weight::MEDIUM, font::Weight::Semibold => cosmic_text::Weight::SEMIBOLD, font::Weight::Bold => cosmic_text::Weight::BOLD, font::Weight::ExtraBold => cosmic_text::Weight::EXTRA_BOLD, font::Weight::Black => cosmic_text::Weight::BLACK, } } fn to_stretch(stretch: font::Stretch) -> cosmic_text::Stretch { match stretch { font::Stretch::UltraCondensed => cosmic_text::Stretch::UltraCondensed, font::Stretch::ExtraCondensed => cosmic_text::Stretch::ExtraCondensed, font::Stretch::Condensed => cosmic_text::Stretch::Condensed, font::Stretch::SemiCondensed => cosmic_text::Stretch::SemiCondensed, font::Stretch::Normal => cosmic_text::Stretch::Normal, font::Stretch::SemiExpanded => cosmic_text::Stretch::SemiExpanded, font::Stretch::Expanded => cosmic_text::Stretch::Expanded, font::Stretch::ExtraExpanded => cosmic_text::Stretch::ExtraExpanded, font::Stretch::UltraExpanded => cosmic_text::Stretch::UltraExpanded, } } fn to_style(style: font::Style) -> cosmic_text::Style { match style { font::Style::Normal => cosmic_text::Style::Normal, font::Style::Italic => cosmic_text::Style::Italic, font::Style::Oblique => cosmic_text::Style::Oblique, } } fn to_align(alignment: Alignment) -> Option<cosmic_text::Align> { match alignment { Alignment::Default => None, Alignment::Left => Some(cosmic_text::Align::Left), Alignment::Center => Some(cosmic_text::Align::Center), Alignment::Right => Some(cosmic_text::Align::Right), Alignment::Justified => Some(cosmic_text::Align::Justified), } } /// Converts some [`Shaping`] strategy to a [`cosmic_text::Shaping`] strategy. pub fn to_shaping(shaping: Shaping, text: &str) -> cosmic_text::Shaping { match shaping { Shaping::Auto => { if text.is_ascii() { cosmic_text::Shaping::Basic } else { cosmic_text::Shaping::Advanced } } Shaping::Basic => cosmic_text::Shaping::Basic, Shaping::Advanced => cosmic_text::Shaping::Advanced, } } /// Converts some [`Wrapping`] strategy to a [`cosmic_text::Wrap`] strategy. pub fn to_wrap(wrapping: Wrapping) -> cosmic_text::Wrap { match wrapping { Wrapping::None => cosmic_text::Wrap::None, Wrapping::Word => cosmic_text::Wrap::Word, Wrapping::Glyph => cosmic_text::Wrap::Glyph, Wrapping::WordOrGlyph => cosmic_text::Wrap::WordOrGlyph, } } /// Converts some [`Color`] to a [`cosmic_text::Color`]. pub fn to_color(color: Color) -> cosmic_text::Color { let [r, g, b, a] = color.into_rgba8(); cosmic_text::Color::rgba(r, g, b, a) } /// Returns the ideal hint factor given the size and scale factor of some text. pub fn hint_factor(size: Pixels, scale_factor: Option<f32>) -> Option<f32> { const MAX_HINTING_SIZE: f32 = 18.0; let hint_factor = scale_factor?; if size.0 * hint_factor < MAX_HINTING_SIZE { Some(hint_factor) } else { None } } /// A text renderer coupled to `iced_graphics`. pub trait Renderer { /// Draws the given [`Raw`] text. fn fill_raw(&mut self, raw: Raw); }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/graphics/src/error.rs
graphics/src/error.rs
//! See what can go wrong when creating graphical backends. /// An error that occurred while creating an application's graphical context. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum Error { /// The requested backend version is not supported. #[error("the requested backend version is not supported")] VersionNotSupported, /// Failed to find any pixel format that matches the criteria. #[error("failed to find any pixel format that matches the criteria")] NoAvailablePixelFormat, /// A suitable graphics adapter or device could not be found. #[error("a suitable graphics adapter or device could not be found")] GraphicsAdapterNotFound { /// The name of the backend where the error happened backend: &'static str, /// The reason why this backend could not be used reason: Reason, }, /// An error occurred in the context's internal backend #[error("an error occurred in the context's internal backend")] BackendError(String), /// Multiple errors occurred #[error("multiple errors occurred: {0:?}")] List(Vec<Self>), } /// The reason why a graphics adapter could not be found #[derive(Debug, Clone, PartialEq, Eq)] pub enum Reason { /// The backend did not match the preference DidNotMatch { /// The preferred backend preferred_backend: String, }, /// The request to create the backend failed RequestFailed(String), }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/graphics/src/compositor.rs
graphics/src/compositor.rs
//! A compositor is responsible for initializing a renderer and managing window //! surfaces. use crate::core::Color; use crate::futures::{MaybeSend, MaybeSync}; use crate::{Error, Settings, Shell, Viewport}; use raw_window_handle::{HasDisplayHandle, HasWindowHandle}; use thiserror::Error; use std::borrow::Cow; /// A graphics compositor that can draw to windows. pub trait Compositor: Sized { /// The iced renderer of the backend. type Renderer; /// The surface of the backend. type Surface; /// Creates a new [`Compositor`]. fn new( settings: Settings, display: impl Display + Clone, compatible_window: impl Window + Clone, shell: Shell, ) -> impl Future<Output = Result<Self, Error>> { Self::with_backend(settings, display, compatible_window, shell, None) } /// Creates a new [`Compositor`] with a backend preference. /// /// If the backend does not match the preference, it will return /// [`Error::GraphicsAdapterNotFound`]. fn with_backend( settings: Settings, display: impl Display + Clone, compatible_window: impl Window + Clone, shell: Shell, backend: Option<&str>, ) -> impl Future<Output = Result<Self, Error>>; /// Creates a [`Self::Renderer`] for the [`Compositor`]. fn create_renderer(&self) -> Self::Renderer; /// Crates a new [`Surface`] for the given window. /// /// [`Surface`]: Self::Surface fn create_surface<W: Window + Clone>( &mut self, window: W, width: u32, height: u32, ) -> Self::Surface; /// Configures a new [`Surface`] with the given dimensions. /// /// [`Surface`]: Self::Surface fn configure_surface(&mut self, surface: &mut Self::Surface, width: u32, height: u32); /// Returns [`Information`] used by this [`Compositor`]. fn information(&self) -> Information; /// Loads a font from its bytes. fn load_font(&mut self, font: Cow<'static, [u8]>) { crate::text::font_system() .write() .expect("Write to font system") .load_font(font); } /// Presents the [`Renderer`] primitives to the next frame of the given [`Surface`]. /// /// [`Renderer`]: Self::Renderer /// [`Surface`]: Self::Surface fn present( &mut self, renderer: &mut Self::Renderer, surface: &mut Self::Surface, viewport: &Viewport, background_color: Color, on_pre_present: impl FnOnce(), ) -> Result<(), SurfaceError>; /// Screenshots the current [`Renderer`] primitives to an offscreen texture, and returns the bytes of /// the texture ordered as `RGBA` in the `sRGB` color space. /// /// [`Renderer`]: Self::Renderer fn screenshot( &mut self, renderer: &mut Self::Renderer, viewport: &Viewport, background_color: Color, ) -> Vec<u8>; } /// A window that can be used in a [`Compositor`]. /// /// This is just a convenient super trait of the `raw-window-handle` /// traits. pub trait Window: HasWindowHandle + HasDisplayHandle + MaybeSend + MaybeSync + 'static {} impl<T> Window for T where T: HasWindowHandle + HasDisplayHandle + MaybeSend + MaybeSync + 'static {} /// An owned display handle that can be used in a [`Compositor`]. /// /// This is just a convenient super trait of the `raw-window-handle` /// trait. pub trait Display: HasDisplayHandle + MaybeSend + MaybeSync + 'static {} impl<T> Display for T where T: HasDisplayHandle + MaybeSend + MaybeSync + 'static {} /// Defines the default compositor of a renderer. pub trait Default { /// The compositor of the renderer. type Compositor: Compositor<Renderer = Self>; } /// Result of an unsuccessful call to [`Compositor::present`]. #[derive(Clone, PartialEq, Eq, Debug, Error)] pub enum SurfaceError { /// A timeout was encountered while trying to acquire the next frame. #[error("A timeout was encountered while trying to acquire the next frame")] Timeout, /// The underlying surface has changed, and therefore the surface must be updated. #[error("The underlying surface has changed, and therefore the surface must be updated.")] Outdated, /// The swap chain has been lost and needs to be recreated. #[error("The surface has been lost and needs to be recreated")] Lost, /// There is no more memory left to allocate a new frame. #[error("There is no more memory left to allocate a new frame")] OutOfMemory, /// Acquiring a texture failed with a generic error. #[error("Acquiring a texture failed with a generic error")] Other, } /// Contains information about the graphics (e.g. graphics adapter, graphics backend). #[derive(Debug)] pub struct Information { /// Contains the graphics adapter. pub adapter: String, /// Contains the graphics backend. pub backend: String, } #[cfg(debug_assertions)] impl Compositor for () { type Renderer = (); type Surface = (); async fn with_backend( _settings: Settings, _display: impl Display, _compatible_window: impl Window + Clone, _shell: Shell, _preferred_backend: Option<&str>, ) -> Result<Self, Error> { Ok(()) } fn create_renderer(&self) -> Self::Renderer {} fn create_surface<W: Window + Clone>( &mut self, _window: W, _width: u32, _height: u32, ) -> Self::Surface { } fn configure_surface(&mut self, _surface: &mut Self::Surface, _width: u32, _height: u32) {} fn load_font(&mut self, _font: Cow<'static, [u8]>) {} fn information(&self) -> Information { Information { adapter: String::from("Null Renderer"), backend: String::from("Null"), } } fn present( &mut self, _renderer: &mut Self::Renderer, _surface: &mut Self::Surface, _viewport: &Viewport, _background_color: Color, _on_pre_present: impl FnOnce(), ) -> Result<(), SurfaceError> { Ok(()) } fn screenshot( &mut self, _renderer: &mut Self::Renderer, _viewport: &Viewport, _background_color: Color, ) -> Vec<u8> { vec![] } } #[cfg(debug_assertions)] impl Default for () { type Compositor = (); }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/graphics/src/damage.rs
graphics/src/damage.rs
//! Compute the damage between frames. use crate::core::{Point, Rectangle}; /// Diffs the damage regions given some previous and current primitives. pub fn diff<T>( previous: &[T], current: &[T], bounds: impl Fn(&T) -> Vec<Rectangle>, diff: impl Fn(&T, &T) -> Vec<Rectangle>, ) -> Vec<Rectangle> { let damage = previous.iter().zip(current).flat_map(|(a, b)| diff(a, b)); if previous.len() == current.len() { damage.collect() } else { let (smaller, bigger) = if previous.len() < current.len() { (previous, current) } else { (current, previous) }; // Extend damage by the added/removed primitives damage .chain(bigger[smaller.len()..].iter().flat_map(bounds)) .collect() } } /// Computes the damage regions given some previous and current primitives. pub fn list<T>( previous: &[T], current: &[T], bounds: impl Fn(&T) -> Vec<Rectangle>, are_equal: impl Fn(&T, &T) -> bool, ) -> Vec<Rectangle> { diff(previous, current, &bounds, |a, b| { if are_equal(a, b) { vec![] } else { bounds(a).into_iter().chain(bounds(b)).collect() } }) } /// Groups the given damage regions that are close together inside the given /// bounds. pub fn group(mut damage: Vec<Rectangle>, bounds: Rectangle) -> Vec<Rectangle> { const AREA_THRESHOLD: f32 = 20_000.0; damage.sort_by(|a, b| { a.center() .distance(Point::ORIGIN) .total_cmp(&b.center().distance(Point::ORIGIN)) }); let mut output = Vec::new(); let mut scaled = damage .into_iter() .filter_map(|region| region.intersection(&bounds)) .filter(|region| region.width >= 1.0 && region.height >= 1.0); if let Some(mut current) = scaled.next() { for region in scaled { let union = current.union(&region); if union.area() - current.area() - region.area() <= AREA_THRESHOLD { current = union; } else { output.push(current); current = region; } } output.push(current); } output }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/graphics/src/color.rs
graphics/src/color.rs
//! Manage colors for shaders. use crate::core::Color; use bytemuck::{Pod, Zeroable}; /// A color packed as 4 floats representing RGBA channels. #[derive(Debug, Clone, Copy, PartialEq, Zeroable, Pod)] #[repr(C)] pub struct Packed([f32; 4]); impl Packed { /// Returns the internal components of the [`Packed`] color. pub fn components(self) -> [f32; 4] { self.0 } } /// A flag that indicates whether the renderer should perform gamma correction. pub const GAMMA_CORRECTION: bool = internal::GAMMA_CORRECTION; /// Packs a [`Color`]. pub fn pack(color: impl Into<Color>) -> Packed { Packed(internal::pack(color.into())) } #[cfg(not(feature = "web-colors"))] mod internal { use crate::core::Color; pub const GAMMA_CORRECTION: bool = true; pub fn pack(color: Color) -> [f32; 4] { color.into_linear() } } #[cfg(feature = "web-colors")] mod internal { use crate::core::Color; pub const GAMMA_CORRECTION: bool = false; pub fn pack(color: Color) -> [f32; 4] { [color.r, color.g, color.b, color.a] } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/graphics/src/cache.rs
graphics/src/cache.rs
//! Cache computations and efficiently reuse them. use std::cell::RefCell; use std::fmt; use std::mem; use std::sync::atomic::{self, AtomicU64}; /// A simple cache that stores generated values to avoid recomputation. /// /// Keeps track of the last generated value after clearing. pub struct Cache<T> { group: Group, state: RefCell<State<T>>, } impl<T> Cache<T> { /// Creates a new empty [`Cache`]. pub fn new() -> Self { Cache { group: Group::singleton(), state: RefCell::new(State::Empty { previous: None }), } } /// Creates a new empty [`Cache`] with the given [`Group`]. /// /// Caches within the same group may reuse internal rendering storage. /// /// You should generally group caches that are likely to change /// together. pub fn with_group(group: Group) -> Self { assert!( !group.is_singleton(), "The group {group:?} cannot be shared!" ); Cache { group, state: RefCell::new(State::Empty { previous: None }), } } /// Returns the [`Group`] of the [`Cache`]. pub fn group(&self) -> Group { self.group } /// Puts the given value in the [`Cache`]. /// /// Notice that, given this is a cache, a mutable reference is not /// necessary to call this method. You can safely update the cache in /// rendering code. pub fn put(&self, value: T) { *self.state.borrow_mut() = State::Filled { current: value }; } /// Returns a reference cell to the internal [`State`] of the [`Cache`]. pub fn state(&self) -> &RefCell<State<T>> { &self.state } /// Clears the [`Cache`]. pub fn clear(&self) { let mut state = self.state.borrow_mut(); let previous = mem::replace(&mut *state, State::Empty { previous: None }); let previous = match previous { State::Empty { previous } => previous, State::Filled { current } => Some(current), }; *state = State::Empty { previous }; } } /// A cache group. /// /// Caches that share the same group generally change together. /// /// A cache group can be used to implement certain performance /// optimizations during rendering, like batching or sharing atlases. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Group { id: u64, is_singleton: bool, } impl Group { /// Generates a new unique cache [`Group`]. pub fn unique() -> Self { static NEXT: AtomicU64 = AtomicU64::new(0); Self { id: NEXT.fetch_add(1, atomic::Ordering::Relaxed), is_singleton: false, } } /// Returns `true` if the [`Group`] can only ever have a /// single [`Cache`] in it. /// /// This is the default kind of [`Group`] assigned when using /// [`Cache::new`]. /// /// Knowing that a [`Group`] will never be shared may be /// useful for rendering backends to perform additional /// optimizations. pub fn is_singleton(self) -> bool { self.is_singleton } fn singleton() -> Self { Self { is_singleton: true, ..Self::unique() } } } impl<T> fmt::Debug for Cache<T> where T: fmt::Debug, { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { use std::ops::Deref; let state = self.state.borrow(); match state.deref() { State::Empty { previous } => { write!(f, "Cache::Empty {{ previous: {previous:?} }}") } State::Filled { current } => { write!(f, "Cache::Filled {{ current: {current:?} }}") } } } } impl<T> Default for Cache<T> { fn default() -> Self { Self::new() } } /// The state of a [`Cache`]. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum State<T> { /// The [`Cache`] is empty. Empty { /// The previous value of the [`Cache`]. previous: Option<T>, }, /// The [`Cache`] is filled. Filled { /// The current value of the [`Cache`] current: T, }, } /// A piece of data that can be cached. pub trait Cached: Sized { /// The type of cache produced. type Cache: Clone; /// Loads the [`Cache`] into a proper instance. /// /// [`Cache`]: Self::Cache fn load(cache: &Self::Cache) -> Self; /// Caches this value, producing its corresponding [`Cache`]. /// /// [`Cache`]: Self::Cache fn cache(self, group: Group, previous: Option<Self::Cache>) -> Self::Cache; } #[cfg(debug_assertions)] impl Cached for () { type Cache = (); fn load(_cache: &Self::Cache) -> Self {} fn cache(self, _group: Group, _previous: Option<Self::Cache>) -> Self::Cache {} }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/graphics/src/gradient.rs
graphics/src/gradient.rs
//! A gradient that can be used as a fill for some geometry. //! //! For a gradient that you can use as a background variant for a widget, see [`Gradient`]. use crate::color; use crate::core::gradient::ColorStop; use crate::core::{self, Color, Point, Rectangle}; use bytemuck::{Pod, Zeroable}; use half::f16; use std::cmp::Ordering; #[derive(Debug, Clone, Copy, PartialEq)] /// A fill which linearly interpolates colors along a direction. /// /// For a gradient which can be used as a fill for a background of a widget, see [`crate::core::Gradient`]. pub enum Gradient { /// A linear gradient interpolates colors along a direction from its `start` to its `end` /// point. Linear(Linear), } impl From<Linear> for Gradient { fn from(gradient: Linear) -> Self { Self::Linear(gradient) } } impl Gradient { /// Packs the [`Gradient`] for use in shader code. pub fn pack(&self) -> Packed { match self { Gradient::Linear(linear) => linear.pack(), } } } /// A linear gradient. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Linear { /// The absolute starting position of the gradient. pub start: Point, /// The absolute ending position of the gradient. pub end: Point, /// [`ColorStop`]s along the linear gradient direction. pub stops: [Option<ColorStop>; 8], } impl Linear { /// Creates a new [`Linear`] builder. pub fn new(start: Point, end: Point) -> Self { Self { start, end, stops: [None; 8], } } /// Adds a new [`ColorStop`], defined by an offset and a color, to the gradient. /// /// Any `offset` that is not within `0.0..=1.0` will be silently ignored. /// /// Any stop added after the 8th will be silently ignored. pub fn add_stop(mut self, offset: f32, color: Color) -> Self { if offset.is_finite() && (0.0..=1.0).contains(&offset) { let (Ok(index) | Err(index)) = self.stops.binary_search_by(|stop| match stop { None => Ordering::Greater, Some(stop) => stop.offset.partial_cmp(&offset).unwrap(), }); if index < 8 { self.stops[index] = Some(ColorStop { offset, color }); } } else { log::warn!("Gradient: ColorStop must be within 0.0..=1.0 range."); }; self } /// Adds multiple [`ColorStop`]s to the gradient. /// /// Any stop added after the 8th will be silently ignored. pub fn add_stops(mut self, stops: impl IntoIterator<Item = ColorStop>) -> Self { for stop in stops { self = self.add_stop(stop.offset, stop.color); } self } /// Packs the [`Gradient`] for use in shader code. pub fn pack(&self) -> Packed { let mut colors = [[0u32; 2]; 8]; let mut offsets = [f16::from(0u8); 8]; for (index, stop) in self.stops.iter().enumerate() { let [r, g, b, a] = color::pack(stop.map_or(Color::default(), |s| s.color)).components(); colors[index] = [ pack_f16s([f16::from_f32(r), f16::from_f32(g)]), pack_f16s([f16::from_f32(b), f16::from_f32(a)]), ]; offsets[index] = stop.map_or(f16::from_f32(2.0), |s| f16::from_f32(s.offset)); } let offsets = [ pack_f16s([offsets[0], offsets[1]]), pack_f16s([offsets[2], offsets[3]]), pack_f16s([offsets[4], offsets[5]]), pack_f16s([offsets[6], offsets[7]]), ]; let direction = [self.start.x, self.start.y, self.end.x, self.end.y]; Packed { colors, offsets, direction, } } } /// Packed [`Gradient`] data for use in shader code. #[derive(Debug, Copy, Clone, PartialEq, Zeroable, Pod)] #[repr(C)] pub struct Packed { // 8 colors, each channel = 16 bit float, 2 colors packed into 1 u32 colors: [[u32; 2]; 8], // 8 offsets, 8x 16 bit floats packed into 4 u32s offsets: [u32; 4], direction: [f32; 4], } /// Creates a new [`Packed`] gradient for use in shader code. pub fn pack(gradient: &core::Gradient, bounds: Rectangle) -> Packed { match gradient { core::Gradient::Linear(linear) => { let mut colors = [[0u32; 2]; 8]; let mut offsets = [f16::from(0u8); 8]; for (index, stop) in linear.stops.iter().enumerate() { let [r, g, b, a] = color::pack(stop.map_or(Color::default(), |s| s.color)).components(); colors[index] = [ pack_f16s([f16::from_f32(r), f16::from_f32(g)]), pack_f16s([f16::from_f32(b), f16::from_f32(a)]), ]; offsets[index] = stop.map_or(f16::from_f32(2.0), |s| f16::from_f32(s.offset)); } let offsets = [ pack_f16s([offsets[0], offsets[1]]), pack_f16s([offsets[2], offsets[3]]), pack_f16s([offsets[4], offsets[5]]), pack_f16s([offsets[6], offsets[7]]), ]; let (start, end) = linear.angle.to_distance(&bounds); let direction = [start.x, start.y, end.x, end.y]; Packed { colors, offsets, direction, } } } } /// Packs two f16s into one u32. fn pack_f16s(f: [f16; 2]) -> u32 { let one = (f[0].to_bits() as u32) << 16; let two = f[1].to_bits() as u32; one | two }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/graphics/src/image/storage.rs
graphics/src/image/storage.rs
//! Store images. use iced_core::Size; use std::fmt::Debug; /// Stores cached image data for use in rendering pub trait Storage { /// The type of an [`Entry`] in the [`Storage`]. type Entry: Entry; /// State provided to upload or remove a [`Self::Entry`]. type State<'a>; /// Upload the image data of a [`Self::Entry`]. fn upload( &mut self, width: u32, height: u32, data: &[u8], state: &mut Self::State<'_>, ) -> Option<Self::Entry>; /// Remove a [`Self::Entry`] from the [`Storage`]. fn remove(&mut self, entry: &Self::Entry, state: &mut Self::State<'_>); } /// An entry in some [`Storage`], pub trait Entry: Debug { /// The [`Size`] of the [`Entry`]. fn size(&self) -> Size<u32>; }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/graphics/src/geometry/stroke.rs
graphics/src/geometry/stroke.rs
//! Create lines from a [`Path`] and assigns them various attributes/styles. //! //! [`Path`]: super::Path pub use crate::geometry::Style; use iced_core::Color; /// The style of a stroke. #[derive(Debug, Clone, Copy)] pub struct Stroke<'a> { /// The color or gradient of the stroke. /// /// By default, it is set to a [`Style::Solid`] with [`Color::BLACK`]. pub style: Style, /// The distance between the two edges of the stroke. pub width: f32, /// The shape to be used at the end of open subpaths when they are stroked. pub line_cap: LineCap, /// The shape to be used at the corners of paths or basic shapes when they /// are stroked. pub line_join: LineJoin, /// The dash pattern used when stroking the line. pub line_dash: LineDash<'a>, } impl Stroke<'_> { /// Sets the color of the [`Stroke`]. pub fn with_color(self, color: Color) -> Self { Stroke { style: Style::Solid(color), ..self } } /// Sets the width of the [`Stroke`]. pub fn with_width(self, width: f32) -> Self { Stroke { width, ..self } } /// Sets the [`LineCap`] of the [`Stroke`]. pub fn with_line_cap(self, line_cap: LineCap) -> Self { Stroke { line_cap, ..self } } /// Sets the [`LineJoin`] of the [`Stroke`]. pub fn with_line_join(self, line_join: LineJoin) -> Self { Stroke { line_join, ..self } } } impl Default for Stroke<'_> { fn default() -> Self { Stroke { style: Style::Solid(Color::BLACK), width: 1.0, line_cap: LineCap::default(), line_join: LineJoin::default(), line_dash: LineDash::default(), } } } /// The shape used at the end of open subpaths when they are stroked. #[derive(Debug, Clone, Copy, Default)] pub enum LineCap { /// The stroke for each sub-path does not extend beyond its two endpoints. #[default] Butt, /// At the end of each sub-path, the shape representing the stroke will be /// extended by a square. Square, /// At the end of each sub-path, the shape representing the stroke will be /// extended by a semicircle. Round, } /// The shape used at the corners of paths or basic shapes when they are /// stroked. #[derive(Debug, Clone, Copy, Default)] pub enum LineJoin { /// A sharp corner. #[default] Miter, /// A round corner. Round, /// A bevelled corner. Bevel, } /// The dash pattern used when stroking the line. #[derive(Debug, Clone, Copy, Default)] pub struct LineDash<'a> { /// The alternating lengths of lines and gaps which describe the pattern. pub segments: &'a [f32], /// The offset of [`LineDash::segments`] to start the pattern. pub offset: usize, }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/graphics/src/geometry/fill.rs
graphics/src/geometry/fill.rs
//! Fill [`Geometry`] with a certain style. //! //! [`Geometry`]: super::Renderer::Geometry pub use crate::geometry::Style; use crate::core::Color; use crate::gradient::{self, Gradient}; /// The style used to fill geometry. #[derive(Debug, Clone, Copy)] pub struct Fill { /// The color or gradient of the fill. /// /// By default, it is set to [`Style::Solid`] with [`Color::BLACK`]. pub style: Style, /// The fill rule defines how to determine what is inside and what is /// outside of a shape. /// /// See the [SVG specification][1] for more details. /// /// By default, it is set to `NonZero`. /// /// [1]: https://www.w3.org/TR/SVG/painting.html#FillRuleProperty pub rule: Rule, } impl Default for Fill { fn default() -> Self { Self { style: Style::Solid(Color::BLACK), rule: Rule::NonZero, } } } impl From<Color> for Fill { fn from(color: Color) -> Fill { Fill { style: Style::Solid(color), ..Fill::default() } } } impl From<Gradient> for Fill { fn from(gradient: Gradient) -> Self { Fill { style: Style::Gradient(gradient), ..Default::default() } } } impl From<gradient::Linear> for Fill { fn from(gradient: gradient::Linear) -> Self { Fill { style: Style::Gradient(Gradient::Linear(gradient)), ..Default::default() } } } /// The fill rule defines how to determine what is inside and what is outside of /// a shape. /// /// See the [SVG specification][1]. /// /// [1]: https://www.w3.org/TR/SVG/painting.html#FillRuleProperty #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[allow(missing_docs)] pub enum Rule { NonZero, EvenOdd, }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/graphics/src/geometry/path.rs
graphics/src/geometry/path.rs
//! Build different kinds of 2D shapes. pub mod arc; mod builder; #[doc(no_inline)] pub use arc::Arc; pub use builder::Builder; pub use lyon_path; use crate::core::border; use crate::core::{Point, Size}; /// An immutable set of points that may or may not be connected. /// /// A single [`Path`] can represent different kinds of 2D shapes! #[derive(Debug, Clone)] pub struct Path { raw: lyon_path::Path, } impl Path { /// Creates a new [`Path`] with the provided closure. /// /// Use the [`Builder`] to configure your [`Path`]. pub fn new(f: impl FnOnce(&mut Builder)) -> Self { let mut builder = Builder::new(); // TODO: Make it pure instead of side-effect-based (?) f(&mut builder); builder.build() } /// Creates a new [`Path`] representing a line segment given its starting /// and end points. pub fn line(from: Point, to: Point) -> Self { Self::new(|p| { p.move_to(from); p.line_to(to); }) } /// Creates a new [`Path`] representing a rectangle given its top-left /// corner coordinate and its `Size`. pub fn rectangle(top_left: Point, size: Size) -> Self { Self::new(|p| p.rectangle(top_left, size)) } /// Creates a new [`Path`] representing a rounded rectangle given its top-left /// corner coordinate, its [`Size`] and [`border::Radius`]. pub fn rounded_rectangle(top_left: Point, size: Size, radius: border::Radius) -> Self { Self::new(|p| p.rounded_rectangle(top_left, size, radius)) } /// Creates a new [`Path`] representing a circle given its center /// coordinate and its radius. pub fn circle(center: Point, radius: f32) -> Self { Self::new(|p| { p.circle(center, radius); p.close(); }) } /// Returns the internal [`lyon_path::Path`]. #[inline] pub fn raw(&self) -> &lyon_path::Path { &self.raw } /// Returns the current [`Path`] with the given transform applied to it. #[inline] pub fn transform(&self, transform: &lyon_path::math::Transform) -> Path { Path { raw: self.raw.clone().transformed(transform), } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/graphics/src/geometry/text.rs
graphics/src/geometry/text.rs
use crate::core; use crate::core::alignment; use crate::core::text::{Alignment, LineHeight, Paragraph, Shaping, Wrapping}; use crate::core::{Color, Font, Pixels, Point, Size, Vector}; use crate::geometry::Path; use crate::text; /// A bunch of text that can be drawn to a canvas #[derive(Debug, Clone)] pub struct Text { /// The contents of the text pub content: String, /// The position of the text relative to the alignment properties. /// /// By default, this position will be relative to the top-left corner coordinate meaning that /// if the horizontal and vertical alignments are unchanged, this property will tell where the /// top-left corner of the text should be placed. /// /// By changing the horizontal_alignment and vertical_alignment properties, you are are able to /// change what part of text is placed at this positions. /// /// For example, when the horizontal_alignment and vertical_alignment are set to Center, the /// center of the text will be placed at the given position NOT the top-left coordinate. pub position: Point, /// The maximum horizontal space available for this [`Text`]. /// /// Text will break into new lines when the width is reached. pub max_width: f32, /// The color of the text pub color: Color, /// The size of the text pub size: Pixels, /// The line height of the text. pub line_height: LineHeight, /// The font of the text pub font: Font, /// The horizontal alignment of the text pub align_x: Alignment, /// The vertical alignment of the text pub align_y: alignment::Vertical, /// The shaping strategy of the text. pub shaping: Shaping, } impl Text { /// Computes the [`Path`]s of the [`Text`] and draws them using /// the given closure. pub fn draw_with(&self, mut f: impl FnMut(Path, Color)) { let paragraph = text::Paragraph::with_text(core::text::Text { content: &self.content, bounds: Size::new(self.max_width, f32::INFINITY), size: self.size, line_height: self.line_height, font: self.font, align_x: self.align_x, align_y: self.align_y, shaping: self.shaping, wrapping: Wrapping::default(), hint_factor: None, }); let translation_x = match self.align_x { Alignment::Default | Alignment::Left | Alignment::Justified => self.position.x, Alignment::Center => self.position.x - paragraph.min_width() / 2.0, Alignment::Right => self.position.x - paragraph.min_width(), }; let translation_y = { match self.align_y { alignment::Vertical::Top => self.position.y, alignment::Vertical::Center => self.position.y - paragraph.min_height() / 2.0, alignment::Vertical::Bottom => self.position.y - paragraph.min_height(), } }; let buffer = paragraph.buffer(); let mut swash_cache = cosmic_text::SwashCache::new(); let mut font_system = text::font_system().write().expect("Write font system"); for run in buffer.layout_runs() { for glyph in run.glyphs.iter() { let physical_glyph = glyph.physical((0.0, 0.0), 1.0); let start_x = translation_x + glyph.x + glyph.x_offset; let start_y = translation_y + glyph.y_offset + run.line_y; let offset = Vector::new(start_x, start_y); if let Some(commands) = swash_cache.get_outline_commands(font_system.raw(), physical_glyph.cache_key) { let glyph = Path::new(|path| { use cosmic_text::Command; for command in commands { match command { Command::MoveTo(p) => { path.move_to(Point::new(p.x, -p.y) + offset); } Command::LineTo(p) => { path.line_to(Point::new(p.x, -p.y) + offset); } Command::CurveTo(control_a, control_b, to) => { path.bezier_curve_to( Point::new(control_a.x, -control_a.y) + offset, Point::new(control_b.x, -control_b.y) + offset, Point::new(to.x, -to.y) + offset, ); } Command::QuadTo(control, to) => { path.quadratic_curve_to( Point::new(control.x, -control.y) + offset, Point::new(to.x, -to.y) + offset, ); } Command::Close => { path.close(); } } } }); f(glyph, self.color); } else { // TODO: Raster image support for `Canvas` let [r, g, b, a] = self.color.into_rgba8(); swash_cache.with_pixels( font_system.raw(), physical_glyph.cache_key, cosmic_text::Color::rgba(r, g, b, a), |x, y, color| { f( Path::rectangle( Point::new(x as f32, y as f32) + offset, Size::new(1.0, 1.0), ), Color::from_rgba8( color.r(), color.g(), color.b(), color.a() as f32 / 255.0, ), ); }, ); } } } } } impl Default for Text { fn default() -> Text { Text { content: String::new(), position: Point::ORIGIN, max_width: f32::INFINITY, color: Color::BLACK, size: Pixels(16.0), line_height: LineHeight::Relative(1.2), font: Font::default(), align_x: Alignment::Default, align_y: alignment::Vertical::Top, shaping: Shaping::default(), } } } impl From<String> for Text { fn from(content: String) -> Text { Text { content, ..Default::default() } } } impl From<&str> for Text { fn from(content: &str) -> Text { String::from(content).into() } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/graphics/src/geometry/style.rs
graphics/src/geometry/style.rs
use crate::core::Color; use crate::geometry::Gradient; /// The coloring style of some drawing. #[derive(Debug, Clone, Copy, PartialEq)] pub enum Style { /// A solid [`Color`]. Solid(Color), /// A [`Gradient`] color. Gradient(Gradient), } impl From<Color> for Style { fn from(color: Color) -> Self { Self::Solid(color) } } impl From<Gradient> for Style { fn from(gradient: Gradient) -> Self { Self::Gradient(gradient) } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/graphics/src/geometry/frame.rs
graphics/src/geometry/frame.rs
//! Draw and generate geometry. use crate::core::{Point, Radians, Rectangle, Size, Vector}; use crate::geometry::{self, Fill, Image, Path, Stroke, Svg, Text}; /// The region of a surface that can be used to draw geometry. pub struct Frame<Renderer> where Renderer: geometry::Renderer, { raw: Renderer::Frame, } impl<Renderer> Frame<Renderer> where Renderer: geometry::Renderer, { /// Creates a new [`Frame`] with the given dimensions. /// /// Any geometry drawn outside of the dimensions will be clipped. /// If you need further control, use [`with_bounds`](Self::with_bounds). pub fn new(renderer: &Renderer, size: Size) -> Self { Self::with_bounds(renderer, Rectangle::with_size(size)) } /// Creates a new [`Frame`] with the given clip bounds. pub fn with_bounds(renderer: &Renderer, bounds: Rectangle) -> Self { Self { raw: renderer.new_frame(bounds), } } /// Returns the width of the [`Frame`]. pub fn width(&self) -> f32 { self.raw.width() } /// Returns the height of the [`Frame`]. pub fn height(&self) -> f32 { self.raw.height() } /// Returns the dimensions of the [`Frame`]. pub fn size(&self) -> Size { self.raw.size() } /// Returns the coordinate of the center of the [`Frame`]. pub fn center(&self) -> Point { self.raw.center() } /// Draws the given [`Path`] on the [`Frame`] by filling it with the /// provided style. pub fn fill(&mut self, path: &Path, fill: impl Into<Fill>) { self.raw.fill(path, fill); } /// Draws an axis-aligned rectangle given its top-left corner coordinate and /// its `Size` on the [`Frame`] by filling it with the provided style. pub fn fill_rectangle(&mut self, top_left: Point, size: Size, fill: impl Into<Fill>) { self.raw.fill_rectangle(top_left, size, fill); } /// Draws the stroke of the given [`Path`] on the [`Frame`] with the /// provided style. pub fn stroke<'a>(&mut self, path: &Path, stroke: impl Into<Stroke<'a>>) { self.raw.stroke(path, stroke); } /// Draws the stroke of an axis-aligned rectangle with the provided style /// given its top-left corner coordinate and its `Size` on the [`Frame`] . pub fn stroke_rectangle<'a>( &mut self, top_left: Point, size: Size, stroke: impl Into<Stroke<'a>>, ) { self.raw.stroke_rectangle(top_left, size, stroke); } /// Draws the characters of the given [`Text`] on the [`Frame`], filling /// them with the given color. /// /// __Warning:__ All text will be rendered on top of all the layers of /// a `Canvas`. Therefore, it is currently only meant to be used for /// overlays, which is the most common use case. pub fn fill_text(&mut self, text: impl Into<Text>) { self.raw.fill_text(text); } /// Draws the given [`Image`] on the [`Frame`] inside the given bounds. #[cfg(feature = "image")] pub fn draw_image(&mut self, bounds: Rectangle, image: impl Into<Image>) { self.raw.draw_image(bounds, image); } /// Draws the given [`Svg`] on the [`Frame`] inside the given bounds. #[cfg(feature = "svg")] pub fn draw_svg(&mut self, bounds: Rectangle, svg: impl Into<Svg>) { self.raw.draw_svg(bounds, svg); } /// Stores the current transform of the [`Frame`] and executes the given /// drawing operations, restoring the transform afterwards. /// /// This method is useful to compose transforms and perform drawing /// operations in different coordinate systems. #[inline] pub fn with_save<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R { self.push_transform(); let result = f(self); self.pop_transform(); result } /// Pushes the current transform in the transform stack. pub fn push_transform(&mut self) { self.raw.push_transform(); } /// Pops a transform from the transform stack and sets it as the current transform. pub fn pop_transform(&mut self) { self.raw.pop_transform(); } /// Executes the given drawing operations within a [`Rectangle`] region, /// clipping any geometry that overflows its bounds. Any transformations /// performed are local to the provided closure. /// /// This method is useful to perform drawing operations that need to be /// clipped. #[inline] pub fn with_clip<R>(&mut self, region: Rectangle, f: impl FnOnce(&mut Self) -> R) -> R { let mut frame = self.draft(region); let result = f(&mut frame); self.paste(frame); result } /// Creates a new [`Frame`] with the given [`Size`]. /// /// Draw its contents back to this [`Frame`] with [`paste`]. /// /// [`paste`]: Self::paste fn draft(&mut self, clip_bounds: Rectangle) -> Self { Self { raw: self.raw.draft(clip_bounds), } } /// Draws the contents of the given [`Frame`] with origin at the given [`Point`]. fn paste(&mut self, frame: Self) { self.raw.paste(frame.raw); } /// Applies a translation to the current transform of the [`Frame`]. pub fn translate(&mut self, translation: Vector) { self.raw.translate(translation); } /// Applies a rotation in radians to the current transform of the [`Frame`]. pub fn rotate(&mut self, angle: impl Into<Radians>) { self.raw.rotate(angle); } /// Applies a uniform scaling to the current transform of the [`Frame`]. pub fn scale(&mut self, scale: impl Into<f32>) { self.raw.scale(scale); } /// Applies a non-uniform scaling to the current transform of the [`Frame`]. pub fn scale_nonuniform(&mut self, scale: impl Into<Vector>) { self.raw.scale_nonuniform(scale); } /// Turns the [`Frame`] into its underlying geometry. pub fn into_geometry(self) -> Renderer::Geometry { self.raw.into_geometry() } } /// The internal implementation of a [`Frame`]. /// /// Analogous to [`Frame`]. See [`Frame`] for the documentation /// of each method. #[allow(missing_docs)] pub trait Backend: Sized { type Geometry; fn width(&self) -> f32; fn height(&self) -> f32; fn size(&self) -> Size; fn center(&self) -> Point; fn push_transform(&mut self); fn pop_transform(&mut self); fn translate(&mut self, translation: Vector); fn rotate(&mut self, angle: impl Into<Radians>); fn scale(&mut self, scale: impl Into<f32>); fn scale_nonuniform(&mut self, scale: impl Into<Vector>); fn draft(&mut self, clip_bounds: Rectangle) -> Self; fn paste(&mut self, frame: Self); fn stroke<'a>(&mut self, path: &Path, stroke: impl Into<Stroke<'a>>); fn stroke_rectangle<'a>(&mut self, top_left: Point, size: Size, stroke: impl Into<Stroke<'a>>); fn stroke_text<'a>(&mut self, text: impl Into<Text>, stroke: impl Into<Stroke<'a>>); fn fill(&mut self, path: &Path, fill: impl Into<Fill>); fn fill_text(&mut self, text: impl Into<Text>); fn fill_rectangle(&mut self, top_left: Point, size: Size, fill: impl Into<Fill>); fn draw_image(&mut self, bounds: Rectangle, image: impl Into<Image>); fn draw_svg(&mut self, bounds: Rectangle, svg: impl Into<Svg>); fn into_geometry(self) -> Self::Geometry; } #[cfg(debug_assertions)] impl Backend for () { type Geometry = (); fn width(&self) -> f32 { 0.0 } fn height(&self) -> f32 { 0.0 } fn size(&self) -> Size { Size::ZERO } fn center(&self) -> Point { Point::ORIGIN } fn push_transform(&mut self) {} fn pop_transform(&mut self) {} fn translate(&mut self, _translation: Vector) {} fn rotate(&mut self, _angle: impl Into<Radians>) {} fn scale(&mut self, _scale: impl Into<f32>) {} fn scale_nonuniform(&mut self, _scale: impl Into<Vector>) {} fn draft(&mut self, _clip_bounds: Rectangle) -> Self {} fn paste(&mut self, _frame: Self) {} fn stroke<'a>(&mut self, _path: &Path, _stroke: impl Into<Stroke<'a>>) {} fn stroke_rectangle<'a>( &mut self, _top_left: Point, _size: Size, _stroke: impl Into<Stroke<'a>>, ) { } fn stroke_text<'a>(&mut self, _text: impl Into<Text>, _stroke: impl Into<Stroke<'a>>) {} fn fill(&mut self, _path: &Path, _fill: impl Into<Fill>) {} fn fill_text(&mut self, _text: impl Into<Text>) {} fn fill_rectangle(&mut self, _top_left: Point, _size: Size, _fill: impl Into<Fill>) {} fn draw_image(&mut self, _bounds: Rectangle, _image: impl Into<Image>) {} fn draw_svg(&mut self, _bounds: Rectangle, _svg: impl Into<Svg>) {} fn into_geometry(self) -> Self::Geometry {} }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/graphics/src/geometry/cache.rs
graphics/src/geometry/cache.rs
use crate::cache::{self, Cached}; use crate::core::{Rectangle, Size}; use crate::geometry::{self, Frame}; pub use cache::Group; /// A simple cache that stores generated geometry to avoid recomputation. /// /// A [`Cache`] will not redraw its geometry unless the dimensions of its layer /// change or it is explicitly cleared. pub struct Cache<Renderer> where Renderer: geometry::Renderer, { raw: crate::Cache<Data<<Renderer::Geometry as Cached>::Cache>>, } #[derive(Debug, Clone)] struct Data<T> { bounds: Rectangle, geometry: T, } impl<Renderer> Cache<Renderer> where Renderer: geometry::Renderer, { /// Creates a new empty [`Cache`]. pub fn new() -> Self { Cache { raw: cache::Cache::new(), } } /// Creates a new empty [`Cache`] with the given [`Group`]. /// /// Caches within the same group may reuse internal rendering storage. /// /// You should generally group caches that are likely to change /// together. pub fn with_group(group: Group) -> Self { Cache { raw: crate::Cache::with_group(group), } } /// Clears the [`Cache`], forcing a redraw the next time it is used. pub fn clear(&self) { self.raw.clear(); } /// Draws geometry using the provided closure and stores it in the /// [`Cache`]. /// /// The closure will only be called when /// - the size has changed since the previous draw call. /// - the [`Cache`] is empty or has been explicitly cleared. /// /// Otherwise, the previously stored geometry will be returned. The /// [`Cache`] is not cleared in this case. In other words, it will keep /// returning the stored geometry if needed. pub fn draw( &self, renderer: &Renderer, size: Size, draw_fn: impl FnOnce(&mut Frame<Renderer>), ) -> Renderer::Geometry { self.draw_with_bounds(renderer, Rectangle::with_size(size), draw_fn) } /// Draws geometry using the provided closure and stores it in the /// [`Cache`]. /// /// Analogous to [`draw`](Self::draw), but takes a clipping [`Rectangle`] instead of /// a [`Size`]. pub fn draw_with_bounds( &self, renderer: &Renderer, bounds: Rectangle, draw_fn: impl FnOnce(&mut Frame<Renderer>), ) -> Renderer::Geometry { use std::ops::Deref; let state = self.raw.state(); let previous = match state.borrow().deref() { cache::State::Empty { previous } => previous.as_ref().map(|data| data.geometry.clone()), cache::State::Filled { current } => { if current.bounds == bounds { return Cached::load(&current.geometry); } Some(current.geometry.clone()) } }; let mut frame = Frame::with_bounds(renderer, bounds); draw_fn(&mut frame); let geometry = frame.into_geometry().cache(self.raw.group(), previous); let result = Cached::load(&geometry); *state.borrow_mut() = cache::State::Filled { current: Data { bounds, geometry }, }; result } } impl<Renderer> std::fmt::Debug for Cache<Renderer> where Renderer: geometry::Renderer, <Renderer::Geometry as Cached>::Cache: std::fmt::Debug, { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{:?}", &self.raw) } } impl<Renderer> Default for Cache<Renderer> where Renderer: geometry::Renderer, { fn default() -> Self { Self::new() } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/graphics/src/geometry/path/builder.rs
graphics/src/geometry/path/builder.rs
use crate::geometry::path::{Arc, Path, arc}; use crate::core::border; use crate::core::{Point, Radians, Size}; use lyon_path::builder::{self, SvgPathBuilder}; use lyon_path::geom; use lyon_path::math; /// A [`Path`] builder. /// /// Once a [`Path`] is built, it can no longer be mutated. pub struct Builder { raw: builder::WithSvg<lyon_path::path::BuilderImpl>, } impl Builder { /// Creates a new [`Builder`]. pub fn new() -> Builder { Builder { raw: lyon_path::Path::builder().with_svg(), } } /// Moves the starting point of a new sub-path to the given `Point`. #[inline] pub fn move_to(&mut self, point: Point) { let _ = self.raw.move_to(math::Point::new(point.x, point.y)); } /// Connects the last point in the [`Path`] to the given `Point` with a /// straight line. #[inline] pub fn line_to(&mut self, point: Point) { let _ = self.raw.line_to(math::Point::new(point.x, point.y)); } /// Adds an [`Arc`] to the [`Path`] from `start_angle` to `end_angle` in /// a clockwise direction. #[inline] pub fn arc(&mut self, arc: Arc) { self.ellipse(arc.into()); } /// Adds a circular arc to the [`Path`] with the given control points and /// radius. /// /// This essentially draws a straight line segment from the current /// position to `a`, but fits a circular arc of `radius` tangent to that /// segment and tangent to the line between `a` and `b`. /// /// With another `.line_to(b)`, the result will be a path connecting the /// starting point and `b` with straight line segments towards `a` and a /// circular arc smoothing out the corner at `a`. /// /// See [the HTML5 specification of `arcTo`](https://html.spec.whatwg.org/multipage/canvas.html#building-paths:dom-context-2d-arcto) /// for more details and examples. pub fn arc_to(&mut self, a: Point, b: Point, radius: f32) { let start = self.raw.current_position(); let mid = math::Point::new(a.x, a.y); let end = math::Point::new(b.x, b.y); if start == mid || mid == end || radius == 0.0 { let _ = self.raw.line_to(mid); return; } let double_area = start.x * (mid.y - end.y) + mid.x * (end.y - start.y) + end.x * (start.y - mid.y); if double_area == 0.0 { let _ = self.raw.line_to(mid); return; } let to_start = (start - mid).normalize(); let to_end = (end - mid).normalize(); let inner_angle = to_start.dot(to_end).acos(); let origin_angle = inner_angle / 2.0; let origin_adjacent = radius / origin_angle.tan(); let arc_start = mid + to_start * origin_adjacent; let arc_end = mid + to_end * origin_adjacent; let sweep = to_start.cross(to_end) < 0.0; let _ = self.raw.line_to(arc_start); self.raw.arc_to( math::Vector::new(radius, radius), math::Angle::radians(0.0), lyon_path::ArcFlags { large_arc: false, sweep, }, arc_end, ); } /// Adds an ellipse to the [`Path`] using a clockwise direction. pub fn ellipse(&mut self, arc: arc::Elliptical) { let arc = geom::Arc { center: math::Point::new(arc.center.x, arc.center.y), radii: math::Vector::new(arc.radii.x, arc.radii.y), x_rotation: math::Angle::radians(arc.rotation.0), start_angle: math::Angle::radians(arc.start_angle.0), sweep_angle: math::Angle::radians((arc.end_angle - arc.start_angle).0), }; let _ = self.raw.move_to(arc.sample(0.0)); arc.cast::<f64>().for_each_quadratic_bezier(&mut |curve| { let curve = curve.cast::<f32>(); let _ = self.raw.quadratic_bezier_to(curve.ctrl, curve.to); }); } /// Adds a cubic Bézier curve to the [`Path`] given its two control points /// and its end point. #[inline] pub fn bezier_curve_to(&mut self, control_a: Point, control_b: Point, to: Point) { let _ = self.raw.cubic_bezier_to( math::Point::new(control_a.x, control_a.y), math::Point::new(control_b.x, control_b.y), math::Point::new(to.x, to.y), ); } /// Adds a quadratic Bézier curve to the [`Path`] given its control point /// and its end point. #[inline] pub fn quadratic_curve_to(&mut self, control: Point, to: Point) { let _ = self.raw.quadratic_bezier_to( math::Point::new(control.x, control.y), math::Point::new(to.x, to.y), ); } /// Adds a rectangle to the [`Path`] given its top-left corner coordinate /// and its `Size`. #[inline] pub fn rectangle(&mut self, top_left: Point, size: Size) { self.move_to(top_left); self.line_to(Point::new(top_left.x + size.width, top_left.y)); self.line_to(Point::new( top_left.x + size.width, top_left.y + size.height, )); self.line_to(Point::new(top_left.x, top_left.y + size.height)); self.close(); } /// Adds a rounded rectangle to the [`Path`] given its top-left /// corner coordinate its [`Size`] and [`border::Radius`]. #[inline] pub fn rounded_rectangle(&mut self, top_left: Point, size: Size, radius: border::Radius) { let min_size = (size.height / 2.0).min(size.width / 2.0); let [ top_left_corner, top_right_corner, bottom_right_corner, bottom_left_corner, ] = radius.into(); self.move_to(Point::new( top_left.x + min_size.min(top_left_corner), top_left.y, )); self.line_to(Point::new( top_left.x + size.width - min_size.min(top_right_corner), top_left.y, )); self.arc_to( Point::new(top_left.x + size.width, top_left.y), Point::new( top_left.x + size.width, top_left.y + min_size.min(top_right_corner), ), min_size.min(top_right_corner), ); self.line_to(Point::new( top_left.x + size.width, top_left.y + size.height - min_size.min(bottom_right_corner), )); self.arc_to( Point::new(top_left.x + size.width, top_left.y + size.height), Point::new( top_left.x + size.width - min_size.min(bottom_right_corner), top_left.y + size.height, ), min_size.min(bottom_right_corner), ); self.line_to(Point::new( top_left.x + min_size.min(bottom_left_corner), top_left.y + size.height, )); self.arc_to( Point::new(top_left.x, top_left.y + size.height), Point::new( top_left.x, top_left.y + size.height - min_size.min(bottom_left_corner), ), min_size.min(bottom_left_corner), ); self.line_to(Point::new( top_left.x, top_left.y + min_size.min(top_left_corner), )); self.arc_to( Point::new(top_left.x, top_left.y), Point::new(top_left.x + min_size.min(top_left_corner), top_left.y), min_size.min(top_left_corner), ); self.close(); } /// Adds a circle to the [`Path`] given its center coordinate and its /// radius. #[inline] pub fn circle(&mut self, center: Point, radius: f32) { self.arc(Arc { center, radius, start_angle: Radians(0.0), end_angle: Radians(2.0 * std::f32::consts::PI), }); } /// Closes the current sub-path in the [`Path`] with a straight line to /// the starting point. #[inline] pub fn close(&mut self) { self.raw.close(); } /// Builds the [`Path`] of this [`Builder`]. #[inline] pub fn build(self) -> Path { Path { raw: self.raw.build(), } } } impl Default for Builder { fn default() -> Self { Self::new() } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/graphics/src/geometry/path/arc.rs
graphics/src/geometry/path/arc.rs
//! Build and draw curves. use iced_core::{Point, Radians, Vector}; /// A segment of a differentiable curve. #[derive(Debug, Clone, Copy)] pub struct Arc { /// The center of the arc. pub center: Point, /// The radius of the arc. pub radius: f32, /// The start of the segment's angle, clockwise rotation from positive x-axis. pub start_angle: Radians, /// The end of the segment's angle, clockwise rotation from positive x-axis. pub end_angle: Radians, } /// An elliptical [`Arc`]. #[derive(Debug, Clone, Copy)] pub struct Elliptical { /// The center of the arc. pub center: Point, /// The radii of the arc's ellipse. The horizontal and vertical half-dimensions of the ellipse will match the x and y values of the radii vector. pub radii: Vector, /// The clockwise rotation of the arc's ellipse. pub rotation: Radians, /// The start of the segment's angle, clockwise rotation from positive x-axis. pub start_angle: Radians, /// The end of the segment's angle, clockwise rotation from positive x-axis. pub end_angle: Radians, } impl From<Arc> for Elliptical { fn from(arc: Arc) -> Elliptical { Elliptical { center: arc.center, radii: Vector::new(arc.radius, arc.radius), rotation: Radians(0.0), start_angle: arc.start_angle, end_angle: arc.end_angle, } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/graphics/src/text/editor.rs
graphics/src/text/editor.rs
//! Draw and edit text. use crate::core::text::editor::{ self, Action, Cursor, Direction, Edit, Motion, Position, Selection, }; use crate::core::text::highlighter::{self, Highlighter}; use crate::core::text::{LineHeight, Wrapping}; use crate::core::{Font, Pixels, Point, Rectangle, Size}; use crate::text; use cosmic_text::Edit as _; use std::borrow::Cow; use std::fmt; use std::sync::{self, Arc, RwLock}; /// A multi-line text editor. #[derive(Debug, PartialEq)] pub struct Editor(Option<Arc<Internal>>); struct Internal { editor: cosmic_text::Editor<'static>, selection: RwLock<Option<Selection>>, font: Font, bounds: Size, topmost_line_changed: Option<usize>, hint: bool, hint_factor: f32, version: text::Version, } impl Editor { /// Creates a new empty [`Editor`]. pub fn new() -> Self { Self::default() } /// Returns the buffer of the [`Editor`]. pub fn buffer(&self) -> &cosmic_text::Buffer { buffer_from_editor(&self.internal().editor) } /// Creates a [`Weak`] reference to the [`Editor`]. /// /// This is useful to avoid cloning the [`Editor`] when /// referential guarantees are unnecessary. For instance, /// when creating a rendering tree. pub fn downgrade(&self) -> Weak { let editor = self.internal(); Weak { raw: Arc::downgrade(editor), bounds: editor.bounds, } } fn internal(&self) -> &Arc<Internal> { self.0 .as_ref() .expect("Editor should always be initialized") } fn with_internal_mut<T>(&mut self, f: impl FnOnce(&mut Internal) -> T) -> T { let editor = self.0.take().expect("Editor should always be initialized"); // TODO: Handle multiple strong references somehow let mut internal = Arc::try_unwrap(editor).expect("Editor cannot have multiple strong references"); // Clear cursor cache let _ = internal .selection .write() .expect("Write to cursor cache") .take(); let result = f(&mut internal); self.0 = Some(Arc::new(internal)); result } } impl editor::Editor for Editor { type Font = Font; fn with_text(text: &str) -> Self { let mut buffer = cosmic_text::Buffer::new_empty(cosmic_text::Metrics { font_size: 1.0, line_height: 1.0, }); let mut font_system = text::font_system().write().expect("Write font system"); buffer.set_text( font_system.raw(), text, &cosmic_text::Attrs::new(), cosmic_text::Shaping::Advanced, None, ); Editor(Some(Arc::new(Internal { editor: cosmic_text::Editor::new(buffer), version: font_system.version(), ..Default::default() }))) } fn is_empty(&self) -> bool { let buffer = self.buffer(); buffer.lines.is_empty() || (buffer.lines.len() == 1 && buffer.lines[0].text().is_empty()) } fn line(&self, index: usize) -> Option<editor::Line<'_>> { self.buffer().lines.get(index).map(|line| editor::Line { text: Cow::Borrowed(line.text()), ending: match line.ending() { cosmic_text::LineEnding::Lf => editor::LineEnding::Lf, cosmic_text::LineEnding::CrLf => editor::LineEnding::CrLf, cosmic_text::LineEnding::Cr => editor::LineEnding::Cr, cosmic_text::LineEnding::LfCr => editor::LineEnding::LfCr, cosmic_text::LineEnding::None => editor::LineEnding::None, }, }) } fn line_count(&self) -> usize { self.buffer().lines.len() } fn copy(&self) -> Option<String> { self.internal().editor.copy_selection() } fn selection(&self) -> editor::Selection { let internal = self.internal(); if let Ok(Some(cursor)) = internal.selection.read().as_deref() { return cursor.clone(); } let cursor = internal.editor.cursor(); let buffer = buffer_from_editor(&internal.editor); let cursor = match internal.editor.selection_bounds() { Some((start, end)) => { let line_height = buffer.metrics().line_height; let selected_lines = end.line - start.line + 1; let visual_lines_offset = visual_lines_offset(start.line, buffer); let regions = buffer .lines .iter() .skip(start.line) .take(selected_lines) .enumerate() .flat_map(|(i, line)| { highlight_line( line, if i == 0 { start.index } else { 0 }, if i == selected_lines - 1 { end.index } else { line.text().len() }, ) }) .enumerate() .filter_map(|(visual_line, (x, width))| { if width > 0.0 { Some( Rectangle { x, width, y: (visual_line as i32 + visual_lines_offset) as f32 * line_height - buffer.scroll().vertical, height: line_height, } * (1.0 / internal.hint_factor), ) } else { None } }) .collect(); Selection::Range(regions) } _ => { let line_height = buffer.metrics().line_height; let visual_lines_offset = visual_lines_offset(cursor.line, buffer); let line = buffer .lines .get(cursor.line) .expect("Cursor line should be present"); let layout = line.layout_opt().expect("Line layout should be cached"); let mut lines = layout.iter().enumerate(); let (visual_line, offset) = lines .find_map(|(i, line)| { let start = line.glyphs.first().map(|glyph| glyph.start).unwrap_or(0); let end = line.glyphs.last().map(|glyph| glyph.end).unwrap_or(0); let is_cursor_before_start = start > cursor.index; let is_cursor_before_end = match cursor.affinity { cosmic_text::Affinity::Before => cursor.index <= end, cosmic_text::Affinity::After => cursor.index < end, }; if is_cursor_before_start { // Sometimes, the glyph we are looking for is right // between lines. This can happen when a line wraps // on a space. // In that case, we can assume the cursor is at the // end of the previous line. // i is guaranteed to be > 0 because `start` is always // 0 for the first line, so there is no way for the // cursor to be before it. Some((i - 1, layout[i - 1].w)) } else if is_cursor_before_end { let offset = line .glyphs .iter() .take_while(|glyph| cursor.index > glyph.start) .map(|glyph| glyph.w) .sum(); Some((i, offset)) } else { None } }) .unwrap_or(( layout.len().saturating_sub(1), layout.last().map(|line| line.w).unwrap_or(0.0), )); Selection::Caret(Point::new( offset / internal.hint_factor, ((visual_lines_offset + visual_line as i32) as f32 * line_height - buffer.scroll().vertical) / internal.hint_factor, )) } }; *internal.selection.write().expect("Write to cursor cache") = Some(cursor.clone()); cursor } fn cursor(&self) -> Cursor { let editor = &self.internal().editor; let position = { let cursor = editor.cursor(); Position { line: cursor.line, column: cursor.index, } }; let selection = match editor.selection() { cosmic_text::Selection::None => None, cosmic_text::Selection::Normal(cursor) | cosmic_text::Selection::Line(cursor) | cosmic_text::Selection::Word(cursor) => Some(Position { line: cursor.line, column: cursor.index, }), }; Cursor { position, selection, } } fn perform(&mut self, action: Action) { let mut font_system = text::font_system().write().expect("Write font system"); self.with_internal_mut(|internal| { let editor = &mut internal.editor; match action { // Motion events Action::Move(motion) => { if let Some((start, end)) = editor.selection_bounds() { editor.set_selection(cosmic_text::Selection::None); match motion { // These motions are performed as-is even when a selection // is present Motion::Home | Motion::End | Motion::DocumentStart | Motion::DocumentEnd => { editor.action( font_system.raw(), cosmic_text::Action::Motion(to_motion(motion)), ); } // Other motions simply move the cursor to one end of the selection _ => editor.set_cursor(match motion.direction() { Direction::Left => start, Direction::Right => end, }), } } else { editor.action( font_system.raw(), cosmic_text::Action::Motion(to_motion(motion)), ); } } // Selection events Action::Select(motion) => { let cursor = editor.cursor(); if editor.selection_bounds().is_none() { editor.set_selection(cosmic_text::Selection::Normal(cursor)); } editor.action( font_system.raw(), cosmic_text::Action::Motion(to_motion(motion)), ); // Deselect if selection matches cursor position if let Some((start, end)) = editor.selection_bounds() && start.line == end.line && start.index == end.index { editor.set_selection(cosmic_text::Selection::None); } } Action::SelectWord => { let cursor = editor.cursor(); editor.set_selection(cosmic_text::Selection::Word(cursor)); } Action::SelectLine => { let cursor = editor.cursor(); editor.set_selection(cosmic_text::Selection::Line(cursor)); } Action::SelectAll => { let buffer = buffer_from_editor(editor); if buffer.lines.len() > 1 || buffer .lines .first() .is_some_and(|line| !line.text().is_empty()) { let cursor = editor.cursor(); editor.set_selection(cosmic_text::Selection::Normal(cosmic_text::Cursor { line: 0, index: 0, ..cursor })); editor.action( font_system.raw(), cosmic_text::Action::Motion(cosmic_text::Motion::BufferEnd), ); } } // Editing events Action::Edit(edit) => { let topmost_line_before_edit = editor .selection_bounds() .map(|(start, _)| start) .unwrap_or_else(|| editor.cursor()) .line; match edit { Edit::Insert(c) => { editor.action(font_system.raw(), cosmic_text::Action::Insert(c)); } Edit::Paste(text) => { editor.insert_string(&text, None); } Edit::Indent => { editor.action(font_system.raw(), cosmic_text::Action::Indent); } Edit::Unindent => { editor.action(font_system.raw(), cosmic_text::Action::Unindent); } Edit::Enter => { editor.action(font_system.raw(), cosmic_text::Action::Enter); } Edit::Backspace => { editor.action(font_system.raw(), cosmic_text::Action::Backspace); } Edit::Delete => { editor.action(font_system.raw(), cosmic_text::Action::Delete); } } let cursor = editor.cursor(); let selection_start = editor .selection_bounds() .map(|(start, _)| start) .unwrap_or(cursor); internal.topmost_line_changed = Some(selection_start.line.min(topmost_line_before_edit)); } // Mouse events Action::Click(position) => { editor.action( font_system.raw(), cosmic_text::Action::Click { x: (position.x * internal.hint_factor) as i32, y: (position.y * internal.hint_factor) as i32, }, ); } Action::Drag(position) => { editor.action( font_system.raw(), cosmic_text::Action::Drag { x: (position.x * internal.hint_factor) as i32, y: (position.y * internal.hint_factor) as i32, }, ); // Deselect if selection matches cursor position if let Some((start, end)) = editor.selection_bounds() && start.line == end.line && start.index == end.index { editor.set_selection(cosmic_text::Selection::None); } } Action::Scroll { lines } => { editor.action( font_system.raw(), cosmic_text::Action::Scroll { pixels: lines as f32 * buffer_from_editor(editor).metrics().line_height, }, ); } } }); } fn move_to(&mut self, cursor: Cursor) { self.with_internal_mut(|internal| { // TODO: Expose `Affinity` internal.editor.set_cursor(cosmic_text::Cursor { line: cursor.position.line, index: cursor.position.column, affinity: cosmic_text::Affinity::Before, }); if let Some(selection) = cursor.selection { internal .editor .set_selection(cosmic_text::Selection::Normal(cosmic_text::Cursor { line: selection.line, index: selection.column, affinity: cosmic_text::Affinity::Before, })); } }); } fn bounds(&self) -> Size { self.internal().bounds } fn min_bounds(&self) -> Size { let internal = self.internal(); let (bounds, _has_rtl) = text::measure(buffer_from_editor(&internal.editor)); bounds * (1.0 / internal.hint_factor) } fn hint_factor(&self) -> Option<f32> { let internal = self.internal(); internal.hint.then_some(internal.hint_factor) } fn update( &mut self, new_bounds: Size, new_font: Font, new_size: Pixels, new_line_height: LineHeight, new_wrapping: Wrapping, new_hint_factor: Option<f32>, new_highlighter: &mut impl Highlighter, ) { self.with_internal_mut(|internal| { let mut font_system = text::font_system().write().expect("Write font system"); let buffer = buffer_mut_from_editor(&mut internal.editor); if font_system.version() != internal.version { log::trace!("Updating `FontSystem` of `Editor`..."); for line in buffer.lines.iter_mut() { line.reset(); } internal.version = font_system.version(); internal.topmost_line_changed = Some(0); } if new_font != internal.font { log::trace!("Updating font of `Editor`..."); for line in buffer.lines.iter_mut() { let _ = line.set_attrs_list(cosmic_text::AttrsList::new(&text::to_attributes( new_font, ))); } internal.font = new_font; internal.topmost_line_changed = Some(0); } let metrics = buffer.metrics(); let new_line_height = new_line_height.to_absolute(new_size); let mut hinting_changed = false; let new_hint_factor = text::hint_factor(new_size, new_hint_factor); if new_hint_factor != internal.hint.then_some(internal.hint_factor) { internal.hint = new_hint_factor.is_some(); internal.hint_factor = new_hint_factor.unwrap_or(1.0); buffer.set_hinting( font_system.raw(), if internal.hint { cosmic_text::Hinting::Enabled } else { cosmic_text::Hinting::Disabled }, ); hinting_changed = true; } if new_size.0 != metrics.font_size || new_line_height.0 != metrics.line_height || hinting_changed { log::trace!("Updating `Metrics` of `Editor`..."); buffer.set_metrics( font_system.raw(), cosmic_text::Metrics::new( new_size.0 * internal.hint_factor, new_line_height.0 * internal.hint_factor, ), ); } let new_wrap = text::to_wrap(new_wrapping); if new_wrap != buffer.wrap() { log::trace!("Updating `Wrap` strategy of `Editor`..."); buffer.set_wrap(font_system.raw(), new_wrap); } if new_bounds != internal.bounds || hinting_changed { log::trace!("Updating size of `Editor`..."); buffer.set_size( font_system.raw(), Some(new_bounds.width * internal.hint_factor), Some(new_bounds.height * internal.hint_factor), ); internal.bounds = new_bounds; } if let Some(topmost_line_changed) = internal.topmost_line_changed.take() { log::trace!( "Notifying highlighter of line \ change: {topmost_line_changed}" ); new_highlighter.change_line(topmost_line_changed); } internal.editor.shape_as_needed(font_system.raw(), false); }); } fn highlight<H: Highlighter>( &mut self, font: Self::Font, highlighter: &mut H, format_highlight: impl Fn(&H::Highlight) -> highlighter::Format<Self::Font>, ) { let internal = self.internal(); let buffer = buffer_from_editor(&internal.editor); let scroll = buffer.scroll(); let mut window = (internal.bounds.height * internal.hint_factor / buffer.metrics().line_height) .ceil() as i32; let last_visible_line = buffer.lines[scroll.line..] .iter() .enumerate() .find_map(|(i, line)| { let visible_lines = line .layout_opt() .as_ref() .expect("Line layout should be cached") .len() as i32; if window > visible_lines { window -= visible_lines; None } else { Some(scroll.line + i) } }) .unwrap_or(buffer.lines.len().saturating_sub(1)); let current_line = highlighter.current_line(); if current_line > last_visible_line { return; } let editor = self.0.take().expect("Editor should always be initialized"); let mut internal = Arc::try_unwrap(editor).expect("Editor cannot have multiple strong references"); let mut font_system = text::font_system().write().expect("Write font system"); let attributes = text::to_attributes(font); for line in &mut buffer_mut_from_editor(&mut internal.editor).lines [current_line..=last_visible_line] { let mut list = cosmic_text::AttrsList::new(&attributes); for (range, highlight) in highlighter.highlight_line(line.text()) { let format = format_highlight(&highlight); if format.color.is_some() || format.font.is_some() { list.add_span( range, &cosmic_text::Attrs { color_opt: format.color.map(text::to_color), ..if let Some(font) = format.font { text::to_attributes(font) } else { attributes.clone() } }, ); } } let _ = line.set_attrs_list(list); } internal.editor.shape_as_needed(font_system.raw(), false); self.0 = Some(Arc::new(internal)); } } impl Default for Editor { fn default() -> Self { Self(Some(Arc::new(Internal::default()))) } } impl PartialEq for Internal { fn eq(&self, other: &Self) -> bool { self.font == other.font && self.bounds == other.bounds && buffer_from_editor(&self.editor).metrics() == buffer_from_editor(&other.editor).metrics() } } impl Default for Internal { fn default() -> Self { Self { editor: cosmic_text::Editor::new(cosmic_text::Buffer::new_empty( cosmic_text::Metrics { font_size: 1.0, line_height: 1.0, }, )), selection: RwLock::new(None), font: Font::default(), bounds: Size::ZERO, topmost_line_changed: None, hint: false, hint_factor: 1.0, version: text::Version::default(), } } } impl fmt::Debug for Internal { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Internal") .field("font", &self.font) .field("bounds", &self.bounds) .finish() } } /// A weak reference to an [`Editor`]. #[derive(Debug, Clone)] pub struct Weak { raw: sync::Weak<Internal>, /// The bounds of the [`Editor`]. pub bounds: Size, } impl Weak { /// Tries to update the reference into an [`Editor`]. pub fn upgrade(&self) -> Option<Editor> { self.raw.upgrade().map(Some).map(Editor) } } impl PartialEq for Weak { fn eq(&self, other: &Self) -> bool { match (self.raw.upgrade(), other.raw.upgrade()) { (Some(p1), Some(p2)) => p1 == p2, _ => false, } } } fn highlight_line( line: &cosmic_text::BufferLine, from: usize, to: usize, ) -> impl Iterator<Item = (f32, f32)> + '_ { let layout = line.layout_opt().map(Vec::as_slice).unwrap_or_default(); layout.iter().map(move |visual_line| { let start = visual_line .glyphs .first() .map(|glyph| glyph.start) .unwrap_or(0); let end = visual_line .glyphs .last() .map(|glyph| glyph.end) .unwrap_or(0); let range = start.max(from)..end.min(to); if range.is_empty() { (0.0, 0.0) } else if range.start == start && range.end == end { (0.0, visual_line.w) } else { let first_glyph = visual_line .glyphs .iter() .position(|glyph| range.start <= glyph.start) .unwrap_or(0); let mut glyphs = visual_line.glyphs.iter(); let x = glyphs.by_ref().take(first_glyph).map(|glyph| glyph.w).sum(); let width: f32 = glyphs .take_while(|glyph| range.end > glyph.start) .map(|glyph| glyph.w) .sum(); (x, width) } }) } fn visual_lines_offset(line: usize, buffer: &cosmic_text::Buffer) -> i32 { let scroll = buffer.scroll(); let start = scroll.line.min(line); let end = scroll.line.max(line); let visual_lines_offset: usize = buffer.lines[start..] .iter() .take(end - start) .map(|line| line.layout_opt().map(Vec::len).unwrap_or_default()) .sum(); visual_lines_offset as i32 * if scroll.line < line { 1 } else { -1 } } fn to_motion(motion: Motion) -> cosmic_text::Motion { match motion { Motion::Left => cosmic_text::Motion::Left, Motion::Right => cosmic_text::Motion::Right, Motion::Up => cosmic_text::Motion::Up, Motion::Down => cosmic_text::Motion::Down, Motion::WordLeft => cosmic_text::Motion::LeftWord, Motion::WordRight => cosmic_text::Motion::RightWord, Motion::Home => cosmic_text::Motion::Home, Motion::End => cosmic_text::Motion::End, Motion::PageUp => cosmic_text::Motion::PageUp, Motion::PageDown => cosmic_text::Motion::PageDown, Motion::DocumentStart => cosmic_text::Motion::BufferStart, Motion::DocumentEnd => cosmic_text::Motion::BufferEnd, } } fn buffer_from_editor<'a, 'b>(editor: &'a impl cosmic_text::Edit<'b>) -> &'a cosmic_text::Buffer where 'b: 'a, { match editor.buffer_ref() { cosmic_text::BufferRef::Owned(buffer) => buffer, cosmic_text::BufferRef::Borrowed(buffer) => buffer, cosmic_text::BufferRef::Arc(buffer) => buffer, } } fn buffer_mut_from_editor<'a, 'b>( editor: &'a mut impl cosmic_text::Edit<'b>, ) -> &'a mut cosmic_text::Buffer where 'b: 'a, { match editor.buffer_ref_mut() { cosmic_text::BufferRef::Owned(buffer) => buffer, cosmic_text::BufferRef::Borrowed(buffer) => buffer, cosmic_text::BufferRef::Arc(_buffer) => unreachable!(), } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/graphics/src/text/cache.rs
graphics/src/text/cache.rs
//! Cache text. use crate::core::{Font, Size}; use crate::text; use rustc_hash::{FxHashMap, FxHashSet, FxHasher}; use std::collections::hash_map; use std::hash::{Hash, Hasher}; /// A store of recently used sections of text. #[derive(Debug, Default)] pub struct Cache { entries: FxHashMap<KeyHash, Entry>, aliases: FxHashMap<KeyHash, KeyHash>, recently_used: FxHashSet<KeyHash>, } impl Cache { /// Creates a new empty [`Cache`]. pub fn new() -> Self { Self::default() } /// Gets the text [`Entry`] with the given [`KeyHash`]. pub fn get(&self, key: &KeyHash) -> Option<&Entry> { self.entries.get(key) } /// Allocates a text [`Entry`] if it is not already present in the [`Cache`]. pub fn allocate( &mut self, font_system: &mut cosmic_text::FontSystem, key: Key<'_>, ) -> (KeyHash, &mut Entry) { let hash = key.hash(FxHasher::default()); if let Some(hash) = self.aliases.get(&hash) { let _ = self.recently_used.insert(*hash); return (*hash, self.entries.get_mut(hash).unwrap()); } if let hash_map::Entry::Vacant(entry) = self.entries.entry(hash) { let metrics = cosmic_text::Metrics::new(key.size, key.line_height.max(f32::MIN_POSITIVE)); let mut buffer = cosmic_text::Buffer::new(font_system, metrics); buffer.set_size( font_system, Some(key.bounds.width), Some(key.bounds.height.max(key.line_height)), ); buffer.set_text( font_system, key.content, &text::to_attributes(key.font), text::to_shaping(key.shaping, key.content), None, ); let bounds = text::align(&mut buffer, font_system, key.align_x); let _ = entry.insert(Entry { buffer, min_bounds: bounds, }); for bounds in [ bounds, Size { width: key.bounds.width, ..bounds }, ] { if key.bounds != bounds { let _ = self .aliases .insert(Key { bounds, ..key }.hash(FxHasher::default()), hash); } } } let _ = self.recently_used.insert(hash); (hash, self.entries.get_mut(&hash).unwrap()) } /// Trims the [`Cache`]. /// /// This will clear the sections of text that have not been used since the last `trim`. pub fn trim(&mut self) { self.entries .retain(|key, _| self.recently_used.contains(key)); self.aliases .retain(|_, value| self.recently_used.contains(value)); self.recently_used.clear(); } } /// A cache key representing a section of text. #[derive(Debug, Clone, Copy)] pub struct Key<'a> { /// The content of the text. pub content: &'a str, /// The size of the text. pub size: f32, /// The line height of the text. pub line_height: f32, /// The [`Font`] of the text. pub font: Font, /// The bounds of the text. pub bounds: Size, /// The shaping strategy of the text. pub shaping: text::Shaping, /// The alignment of the text. pub align_x: text::Alignment, } impl Key<'_> { fn hash<H: Hasher>(self, mut hasher: H) -> KeyHash { self.content.hash(&mut hasher); self.size.to_bits().hash(&mut hasher); self.line_height.to_bits().hash(&mut hasher); self.font.hash(&mut hasher); self.bounds.width.to_bits().hash(&mut hasher); self.bounds.height.to_bits().hash(&mut hasher); self.shaping.hash(&mut hasher); self.align_x.hash(&mut hasher); hasher.finish() } } /// The hash of a [`Key`]. pub type KeyHash = u64; /// A cache entry. #[derive(Debug)] pub struct Entry { /// The buffer of text, ready for drawing. pub buffer: cosmic_text::Buffer, /// The minimum bounds of the text. pub min_bounds: Size, }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/graphics/src/text/paragraph.rs
graphics/src/text/paragraph.rs
//! Draw paragraphs. use crate::core; use crate::core::alignment; use crate::core::text::{Alignment, Hit, LineHeight, Shaping, Span, Text, Wrapping}; use crate::core::{Font, Pixels, Point, Rectangle, Size}; use crate::text; use std::fmt; use std::sync::{self, Arc}; /// A bunch of text. #[derive(Clone, PartialEq)] pub struct Paragraph(Arc<Internal>); #[derive(Clone)] struct Internal { buffer: cosmic_text::Buffer, font: Font, shaping: Shaping, wrapping: Wrapping, align_x: Alignment, align_y: alignment::Vertical, bounds: Size, min_bounds: Size, version: text::Version, hint: bool, hint_factor: f32, } impl Paragraph { /// Creates a new empty [`Paragraph`]. pub fn new() -> Self { Self::default() } /// Returns the buffer of the [`Paragraph`]. pub fn buffer(&self) -> &cosmic_text::Buffer { &self.internal().buffer } /// Creates a [`Weak`] reference to the [`Paragraph`]. /// /// This is useful to avoid cloning the [`Paragraph`] when /// referential guarantees are unnecessary. For instance, /// when creating a rendering tree. pub fn downgrade(&self) -> Weak { let paragraph = self.internal(); Weak { raw: Arc::downgrade(paragraph), min_bounds: paragraph.min_bounds, align_x: paragraph.align_x, align_y: paragraph.align_y, } } fn internal(&self) -> &Arc<Internal> { &self.0 } } impl core::text::Paragraph for Paragraph { type Font = Font; fn with_text(text: Text<&str>) -> Self { log::trace!("Allocating plain paragraph: {}", text.content); let mut font_system = text::font_system().write().expect("Write font system"); let (hint, hint_factor) = match text::hint_factor(text.size, text.hint_factor) { Some(hint_factor) => (true, hint_factor), _ => (false, 1.0), }; let mut buffer = cosmic_text::Buffer::new( font_system.raw(), cosmic_text::Metrics::new( f32::from(text.size) * hint_factor, f32::from(text.line_height.to_absolute(text.size)) * hint_factor, ), ); if hint { buffer.set_hinting(font_system.raw(), cosmic_text::Hinting::Enabled); } buffer.set_size( font_system.raw(), Some(text.bounds.width * hint_factor), Some(text.bounds.height * hint_factor), ); buffer.set_wrap(font_system.raw(), text::to_wrap(text.wrapping)); buffer.set_text( font_system.raw(), text.content, &text::to_attributes(text.font), text::to_shaping(text.shaping, text.content), None, ); let min_bounds = text::align(&mut buffer, font_system.raw(), text.align_x) / hint_factor; Self(Arc::new(Internal { buffer, hint, hint_factor, font: text.font, align_x: text.align_x, align_y: text.align_y, shaping: text.shaping, wrapping: text.wrapping, bounds: text.bounds, min_bounds, version: font_system.version(), })) } fn with_spans<Link>(text: Text<&[Span<'_, Link>]>) -> Self { log::trace!("Allocating rich paragraph: {} spans", text.content.len()); let mut font_system = text::font_system().write().expect("Write font system"); let (hint, hint_factor) = match text::hint_factor(text.size, text.hint_factor) { Some(hint_factor) => (true, hint_factor), _ => (false, 1.0), }; let mut buffer = cosmic_text::Buffer::new( font_system.raw(), cosmic_text::Metrics::new( f32::from(text.size) * hint_factor, f32::from(text.line_height.to_absolute(text.size)) * hint_factor, ), ); if hint { buffer.set_hinting(font_system.raw(), cosmic_text::Hinting::Enabled); } buffer.set_size( font_system.raw(), Some(text.bounds.width * hint_factor), Some(text.bounds.height * hint_factor), ); buffer.set_wrap(font_system.raw(), text::to_wrap(text.wrapping)); buffer.set_rich_text( font_system.raw(), text.content.iter().enumerate().map(|(i, span)| { let attrs = text::to_attributes(span.font.unwrap_or(text.font)); let attrs = match (span.size, span.line_height) { (None, None) => attrs, _ => { let size = span.size.unwrap_or(text.size); attrs.metrics(cosmic_text::Metrics::new( f32::from(size) * hint_factor, f32::from( span.line_height .unwrap_or(text.line_height) .to_absolute(size), ) * hint_factor, )) } }; let attrs = if let Some(color) = span.color { attrs.color(text::to_color(color)) } else { attrs }; (span.text.as_ref(), attrs.metadata(i)) }), &text::to_attributes(text.font), cosmic_text::Shaping::Advanced, None, ); let min_bounds = text::align(&mut buffer, font_system.raw(), text.align_x) / hint_factor; Self(Arc::new(Internal { buffer, hint, hint_factor, font: text.font, align_x: text.align_x, align_y: text.align_y, shaping: text.shaping, wrapping: text.wrapping, bounds: text.bounds, min_bounds, version: font_system.version(), })) } fn resize(&mut self, new_bounds: Size) { let paragraph = Arc::make_mut(&mut self.0); let mut font_system = text::font_system().write().expect("Write font system"); paragraph.buffer.set_size( font_system.raw(), Some(new_bounds.width * paragraph.hint_factor), Some(new_bounds.height * paragraph.hint_factor), ); let min_bounds = text::align(&mut paragraph.buffer, font_system.raw(), paragraph.align_x) / paragraph.hint_factor; paragraph.bounds = new_bounds; paragraph.min_bounds = min_bounds; } fn compare(&self, text: Text<()>) -> core::text::Difference { let font_system = text::font_system().read().expect("Read font system"); let paragraph = self.internal(); let metrics = paragraph.buffer.metrics(); if paragraph.version != font_system.version || metrics.font_size != text.size.0 * paragraph.hint_factor || metrics.line_height != text.line_height.to_absolute(text.size).0 * paragraph.hint_factor || paragraph.font != text.font || paragraph.shaping != text.shaping || paragraph.wrapping != text.wrapping || paragraph.align_x != text.align_x || paragraph.align_y != text.align_y || paragraph.hint.then_some(paragraph.hint_factor) != text::hint_factor(text.size, text.hint_factor) { core::text::Difference::Shape } else if paragraph.bounds != text.bounds { core::text::Difference::Bounds } else { core::text::Difference::None } } fn hint_factor(&self) -> Option<f32> { self.0.hint.then_some(self.0.hint_factor) } fn size(&self) -> Pixels { Pixels(self.0.buffer.metrics().font_size / self.0.hint_factor) } fn font(&self) -> Font { self.0.font } fn line_height(&self) -> LineHeight { LineHeight::Absolute(Pixels( self.0.buffer.metrics().line_height / self.0.hint_factor, )) } fn align_x(&self) -> Alignment { self.internal().align_x } fn align_y(&self) -> alignment::Vertical { self.internal().align_y } fn wrapping(&self) -> Wrapping { self.0.wrapping } fn shaping(&self) -> Shaping { self.0.shaping } fn bounds(&self) -> Size { self.0.bounds } fn min_bounds(&self) -> Size { self.internal().min_bounds } fn hit_test(&self, point: Point) -> Option<Hit> { let cursor = self .internal() .buffer .hit(point.x * self.0.hint_factor, point.y * self.0.hint_factor)?; Some(Hit::CharOffset(cursor.index)) } fn hit_span(&self, point: Point) -> Option<usize> { let internal = self.internal(); let cursor = internal .buffer .hit(point.x * self.0.hint_factor, point.y * self.0.hint_factor)?; let line = internal.buffer.lines.get(cursor.line)?; if cursor.index >= line.text().len() { return None; } let index = match cursor.affinity { cosmic_text::Affinity::Before => cursor.index.saturating_sub(1), cosmic_text::Affinity::After => cursor.index, }; let mut hit = None; let glyphs = line .layout_opt() .as_ref()? .iter() .flat_map(|line| line.glyphs.iter()); for glyph in glyphs { if glyph.start <= index && index < glyph.end { hit = Some(glyph); break; } } Some(hit?.metadata) } fn span_bounds(&self, index: usize) -> Vec<Rectangle> { let internal = self.internal(); let mut bounds = Vec::new(); let mut current_bounds = None; let glyphs = internal .buffer .layout_runs() .flat_map(|run| { let line_top = run.line_top; let line_height = run.line_height; run.glyphs .iter() .map(move |glyph| (line_top, line_height, glyph)) }) .skip_while(|(_, _, glyph)| glyph.metadata != index) .take_while(|(_, _, glyph)| glyph.metadata == index); for (line_top, line_height, glyph) in glyphs { let y = line_top + glyph.y; let new_bounds = || { Rectangle::new( Point::new(glyph.x, y), Size::new(glyph.w, glyph.line_height_opt.unwrap_or(line_height)), ) * (1.0 / self.0.hint_factor) }; match current_bounds.as_mut() { None => { current_bounds = Some(new_bounds()); } Some(current_bounds) if y != current_bounds.y => { bounds.push(*current_bounds); *current_bounds = new_bounds(); } Some(current_bounds) => { current_bounds.width += glyph.w / self.0.hint_factor; } } } bounds.extend(current_bounds); bounds } fn grapheme_position(&self, line: usize, index: usize) -> Option<Point> { use unicode_segmentation::UnicodeSegmentation; let run = self.internal().buffer.layout_runs().nth(line)?; // index represents a grapheme, not a glyph // Let's find the first glyph for the given grapheme cluster let mut last_start = None; let mut last_grapheme_count = 0; let mut graphemes_seen = 0; let glyph = run .glyphs .iter() .find(|glyph| { if Some(glyph.start) != last_start { last_grapheme_count = run.text[glyph.start..glyph.end].graphemes(false).count(); last_start = Some(glyph.start); graphemes_seen += last_grapheme_count; } graphemes_seen >= index }) .or_else(|| run.glyphs.last())?; let advance = if index == 0 { 0.0 } else { glyph.w * (1.0 - graphemes_seen.saturating_sub(index) as f32 / last_grapheme_count.max(1) as f32) }; Some(Point::new( (glyph.x + glyph.x_offset * glyph.font_size + advance) / self.0.hint_factor, (glyph.y - glyph.y_offset * glyph.font_size) / self.0.hint_factor, )) } } impl Default for Paragraph { fn default() -> Self { Self(Arc::new(Internal::default())) } } impl fmt::Debug for Paragraph { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let paragraph = self.internal(); f.debug_struct("Paragraph") .field("font", &paragraph.font) .field("shaping", &paragraph.shaping) .field("horizontal_alignment", &paragraph.align_x) .field("vertical_alignment", &paragraph.align_y) .field("bounds", &paragraph.bounds) .field("min_bounds", &paragraph.min_bounds) .finish() } } impl PartialEq for Internal { fn eq(&self, other: &Self) -> bool { self.font == other.font && self.shaping == other.shaping && self.align_x == other.align_x && self.align_y == other.align_y && self.bounds == other.bounds && self.min_bounds == other.min_bounds && self.buffer.metrics() == other.buffer.metrics() } } impl Default for Internal { fn default() -> Self { Self { buffer: cosmic_text::Buffer::new_empty(cosmic_text::Metrics { font_size: 1.0, line_height: 1.0, }), font: Font::default(), shaping: Shaping::default(), wrapping: Wrapping::default(), align_x: Alignment::Default, align_y: alignment::Vertical::Top, bounds: Size::ZERO, min_bounds: Size::ZERO, version: text::Version::default(), hint: false, hint_factor: 1.0, } } } /// A weak reference to a [`Paragraph`]. #[derive(Debug, Clone)] pub struct Weak { raw: sync::Weak<Internal>, /// The minimum bounds of the [`Paragraph`]. pub min_bounds: Size, /// The horizontal alignment of the [`Paragraph`]. pub align_x: Alignment, /// The vertical alignment of the [`Paragraph`]. pub align_y: alignment::Vertical, } impl Weak { /// Tries to update the reference into a [`Paragraph`]. pub fn upgrade(&self) -> Option<Paragraph> { self.raw.upgrade().map(Paragraph) } } impl PartialEq for Weak { fn eq(&self, other: &Self) -> bool { match (self.raw.upgrade(), other.raw.upgrade()) { (Some(p1), Some(p2)) => p1 == p2, _ => false, } } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/src/advanced.rs
src/advanced.rs
//! Leverage advanced concepts like custom widgets. pub mod subscription { //! Write your own subscriptions. pub use crate::runtime::futures::subscription::{ Event, EventStream, Hasher, MacOS, PlatformSpecific, Recipe, from_recipe, into_recipes, }; } pub mod widget { //! Create custom widgets and operate on them. pub use crate::core::widget::*; pub use crate::runtime::task::widget as operate; } pub use crate::core::Shell; pub use crate::core::clipboard::{self, Clipboard}; pub use crate::core::image; pub use crate::core::input_method::{self, InputMethod}; pub use crate::core::layout::{self, Layout}; pub use crate::core::mouse; pub use crate::core::overlay::{self, Overlay}; pub use crate::core::renderer::{self, Renderer}; pub use crate::core::svg; pub use crate::core::text::{self, Text}; pub use crate::renderer::graphics; pub use widget::Widget;
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/src/lib.rs
src/lib.rs
//! iced is a cross-platform GUI library focused on simplicity and type-safety. //! Inspired by [Elm]. //! //! [Elm]: https://elm-lang.org/ //! //! # Disclaimer //! iced is __experimental__ software. If you expect the documentation to hold your hand //! as you learn the ropes, you are in for a frustrating experience. //! //! The library leverages Rust to its full extent: ownership, borrowing, lifetimes, futures, //! streams, first-class functions, trait bounds, closures, and more. This documentation //! is not meant to teach you any of these. Far from it, it will assume you have __mastered__ //! all of them. //! //! Furthermore—just like Rust—iced is very unforgiving. It will not let you easily cut corners. //! The type signatures alone can be used to learn how to use most of the library. //! Everything is connected. //! //! Therefore, iced is easy to learn for __advanced__ Rust programmers; but plenty of patient //! beginners have learned it and had a good time with it. Since it leverages a lot of what //! Rust has to offer in a type-safe way, it can be a great way to discover Rust itself. //! //! If you don't like the sound of that, you expect to be spoonfed, or you feel frustrated //! and struggle to use the library; then I recommend you to wait patiently until [the book] //! is finished. //! //! [the book]: https://book.iced.rs //! //! # The Pocket Guide //! Start by calling [`run`]: //! //! ```no_run,standalone_crate //! pub fn main() -> iced::Result { //! iced::run(update, view) //! } //! # fn update(state: &mut (), message: ()) {} //! # fn view(state: &()) -> iced::Element<'_, ()> { iced::widget::text("").into() } //! ``` //! //! Define an `update` function to __change__ your state: //! //! ```standalone_crate //! fn update(counter: &mut u64, message: Message) { //! match message { //! Message::Increment => *counter += 1, //! } //! } //! # #[derive(Clone)] //! # enum Message { Increment } //! ``` //! //! Define a `view` function to __display__ your state: //! //! ```standalone_crate //! use iced::widget::{button, text}; //! use iced::Element; //! //! fn view(counter: &u64) -> Element<'_, Message> { //! button(text(counter)).on_press(Message::Increment).into() //! } //! # #[derive(Clone)] //! # enum Message { Increment } //! ``` //! //! And create a `Message` enum to __connect__ `view` and `update` together: //! //! ```standalone_crate //! #[derive(Debug, Clone)] //! enum Message { //! Increment, //! } //! ``` //! //! ## Custom State //! You can define your own struct for your state: //! //! ```standalone_crate //! #[derive(Default)] //! struct Counter { //! value: u64, //! } //! ``` //! //! But you have to change `update` and `view` accordingly: //! //! ```standalone_crate //! # struct Counter { value: u64 } //! # #[derive(Clone)] //! # enum Message { Increment } //! # use iced::widget::{button, text}; //! # use iced::Element; //! fn update(counter: &mut Counter, message: Message) { //! match message { //! Message::Increment => counter.value += 1, //! } //! } //! //! fn view(counter: &Counter) -> Element<'_, Message> { //! button(text(counter.value)).on_press(Message::Increment).into() //! } //! ``` //! //! ## Widgets and Elements //! The `view` function must return an [`Element`]. An [`Element`] is just a generic [`widget`]. //! //! The [`widget`] module contains a bunch of functions to help you build //! and use widgets. //! //! Widgets are configured using the builder pattern: //! //! ```standalone_crate //! # struct Counter { value: u64 } //! # #[derive(Clone)] //! # enum Message { Increment } //! use iced::widget::{button, column, text}; //! use iced::Element; //! //! fn view(counter: &Counter) -> Element<'_, Message> { //! column![ //! text(counter.value).size(20), //! button("Increment").on_press(Message::Increment), //! ] //! .spacing(10) //! .into() //! } //! ``` //! //! A widget can be turned into an [`Element`] by calling `into`. //! //! Widgets and elements are generic over the message type they produce. The //! [`Element`] returned by `view` must have the same `Message` type as //! your `update`. //! //! ## Layout //! There is no unified layout system in iced. Instead, each widget implements //! its own layout strategy. //! //! Building your layout will often consist in using a combination of //! [rows], [columns], and [containers]: //! //! ```standalone_crate //! # struct State; //! # enum Message {} //! use iced::widget::{column, container, row}; //! use iced::{Fill, Element}; //! //! fn view(state: &State) -> Element<'_, Message> { //! container( //! column![ //! "Top", //! row!["Left", "Right"].spacing(10), //! "Bottom" //! ] //! .spacing(10) //! ) //! .padding(10) //! .center_x(Fill) //! .center_y(Fill) //! .into() //! } //! ``` //! //! Rows and columns lay out their children horizontally and vertically, //! respectively. [Spacing] can be easily added between elements. //! //! Containers position or align a single widget inside their bounds. //! //! [rows]: widget::Row //! [columns]: widget::Column //! [containers]: widget::Container //! [Spacing]: widget::Column::spacing //! //! ## Sizing //! The width and height of widgets can generally be defined using a [`Length`]. //! //! - [`Fill`] will make the widget take all the available space in a given axis. //! - [`Shrink`] will make the widget use its intrinsic size. //! //! Most widgets use a [`Shrink`] sizing strategy by default, but will inherit //! a [`Fill`] strategy from their children. //! //! A fixed numeric [`Length`] in [`Pixels`] can also be used: //! //! ```standalone_crate //! # struct State; //! # enum Message {} //! use iced::widget::container; //! use iced::Element; //! //! fn view(state: &State) -> Element<'_, Message> { //! container("I am 300px tall!").height(300).into() //! } //! ``` //! //! ## Theming //! The default [`Theme`] of an application can be changed by defining a `theme` //! function and leveraging the [`Application`] builder, instead of directly //! calling [`run`]: //! //! ```no_run,standalone_crate //! # struct State; //! use iced::Theme; //! //! pub fn main() -> iced::Result { //! iced::application(new, update, view) //! .theme(theme) //! .run() //! } //! //! fn new() -> State { //! // ... //! # State //! } //! //! fn theme(state: &State) -> Theme { //! Theme::TokyoNight //! } //! # fn update(state: &mut State, message: ()) {} //! # fn view(state: &State) -> iced::Element<'_, ()> { iced::widget::text("").into() } //! ``` //! //! The `theme` function takes the current state of the application, allowing the //! returned [`Theme`] to be completely dynamic—just like `view`. //! //! There are a bunch of built-in [`Theme`] variants at your disposal, but you can //! also [create your own](Theme::custom). //! //! ## Styling //! As with layout, iced does not have a unified styling system. However, all //! of the built-in widgets follow the same styling approach. //! //! The appearance of a widget can be changed by calling its `style` method: //! //! ```standalone_crate //! # struct State; //! # enum Message {} //! use iced::widget::container; //! use iced::Element; //! //! fn view(state: &State) -> Element<'_, Message> { //! container("I am a rounded box!").style(container::rounded_box).into() //! } //! ``` //! //! The `style` method of a widget takes a closure that, given the current active //! [`Theme`], returns the widget style: //! //! ```standalone_crate //! # struct State; //! # #[derive(Clone)] //! # enum Message {} //! use iced::widget::button; //! use iced::{Element, Theme}; //! //! fn view(state: &State) -> Element<'_, Message> { //! button("I am a styled button!").style(|theme: &Theme, status| { //! let palette = theme.extended_palette(); //! //! match status { //! button::Status::Active => { //! button::Style::default() //! .with_background(palette.success.strong.color) //! } //! _ => button::primary(theme, status), //! } //! }) //! .into() //! } //! ``` //! //! Widgets that can be in multiple different states will also provide the closure //! with some [`Status`], allowing you to use a different style for each state. //! //! You can extract the [`Palette`] colors of a [`Theme`] with the [`palette`] or //! [`extended_palette`] methods. //! //! Most widgets provide styling functions for your convenience in their respective modules; //! like [`container::rounded_box`], [`button::primary`], or [`text::danger`]. //! //! [`Status`]: widget::button::Status //! [`palette`]: Theme::palette //! [`extended_palette`]: Theme::extended_palette //! [`container::rounded_box`]: widget::container::rounded_box //! [`button::primary`]: widget::button::primary //! [`text::danger`]: widget::text::danger //! //! ## Concurrent Tasks //! The `update` function can _optionally_ return a [`Task`]. //! //! A [`Task`] can be leveraged to perform asynchronous work, like running a //! future or a stream: //! //! ```standalone_crate //! # #[derive(Clone)] //! # struct Weather; //! use iced::Task; //! //! struct State { //! weather: Option<Weather>, //! } //! //! enum Message { //! FetchWeather, //! WeatherFetched(Weather), //! } //! //! fn update(state: &mut State, message: Message) -> Task<Message> { //! match message { //! Message::FetchWeather => Task::perform( //! fetch_weather(), //! Message::WeatherFetched, //! ), //! Message::WeatherFetched(weather) => { //! state.weather = Some(weather); //! //! Task::none() //! } //! } //! } //! //! async fn fetch_weather() -> Weather { //! // ... //! # unimplemented!() //! } //! ``` //! //! Tasks can also be used to interact with the iced runtime. Some modules //! expose functions that create tasks for different purposes—like [changing //! window settings](window#functions), [focusing a widget](widget::operation::focus_next), or //! [querying its visible bounds](widget::selector::find). //! //! Like futures and streams, tasks expose [a monadic interface](Task::then)—but they can also be //! [mapped](Task::map), [chained](Task::chain), [batched](Task::batch), [canceled](Task::abortable), //! and more. //! //! ## Passive Subscriptions //! Applications can subscribe to passive sources of data—like time ticks or runtime events. //! //! You will need to define a `subscription` function and use the [`Application`] builder: //! //! ```no_run,standalone_crate //! # struct State; //! use iced::window; //! use iced::{Size, Subscription}; //! //! #[derive(Debug, Clone)] //! enum Message { //! WindowResized(Size), //! } //! //! pub fn main() -> iced::Result { //! iced::application(new, update, view) //! .subscription(subscription) //! .run() //! } //! //! fn subscription(state: &State) -> Subscription<Message> { //! window::resize_events().map(|(_id, size)| Message::WindowResized(size)) //! } //! # fn new() -> State { State } //! # fn update(state: &mut State, message: Message) {} //! # fn view(state: &State) -> iced::Element<'_, Message> { iced::widget::text("").into() } //! ``` //! //! A [`Subscription`] is [a _declarative_ builder of streams](Subscription#the-lifetime-of-a-subscription) //! that are not allowed to end on their own. Only the `subscription` function //! dictates the active subscriptions—just like `view` fully dictates the //! visible widgets of your user interface, at every moment. //! //! As with tasks, some modules expose convenient functions that build a [`Subscription`] for you—like //! [`time::every`] which can be used to listen to time, or [`keyboard::listen`] which will notify you //! of any keyboard events. But you can also create your own with [`Subscription::run`] and [`run_with`]. //! //! [`run_with`]: Subscription::run_with //! //! ## Scaling Applications //! The `update`, `view`, and `Message` triplet composes very nicely. //! //! A common pattern is to leverage this composability to split an //! application into different screens: //! //! ```standalone_crate //! # mod contacts { //! # use iced::{Element, Task}; //! # pub struct Contacts; //! # impl Contacts { //! # pub fn update(&mut self, message: Message) -> Action { unimplemented!() } //! # pub fn view(&self) -> Element<Message> { unimplemented!() } //! # } //! # #[derive(Debug, Clone)] //! # pub enum Message {} //! # pub enum Action { None, Run(Task<Message>), Chat(()) } //! # } //! # mod conversation { //! # use iced::{Element, Task}; //! # pub struct Conversation; //! # impl Conversation { //! # pub fn new(contact: ()) -> (Self, Task<Message>) { unimplemented!() } //! # pub fn update(&mut self, message: Message) -> Task<Message> { unimplemented!() } //! # pub fn view(&self) -> Element<Message> { unimplemented!() } //! # } //! # #[derive(Debug, Clone)] //! # pub enum Message {} //! # } //! use contacts::Contacts; //! use conversation::Conversation; //! //! use iced::{Element, Task}; //! //! struct State { //! screen: Screen, //! } //! //! enum Screen { //! Contacts(Contacts), //! Conversation(Conversation), //! } //! //! enum Message { //! Contacts(contacts::Message), //! Conversation(conversation::Message) //! } //! //! fn update(state: &mut State, message: Message) -> Task<Message> { //! match message { //! Message::Contacts(message) => { //! if let Screen::Contacts(contacts) = &mut state.screen { //! let action = contacts.update(message); //! //! match action { //! contacts::Action::None => Task::none(), //! contacts::Action::Run(task) => task.map(Message::Contacts), //! contacts::Action::Chat(contact) => { //! let (conversation, task) = Conversation::new(contact); //! //! state.screen = Screen::Conversation(conversation); //! //! task.map(Message::Conversation) //! } //! } //! } else { //! Task::none() //! } //! } //! Message::Conversation(message) => { //! if let Screen::Conversation(conversation) = &mut state.screen { //! conversation.update(message).map(Message::Conversation) //! } else { //! Task::none() //! } //! } //! } //! } //! //! fn view(state: &State) -> Element<'_, Message> { //! match &state.screen { //! Screen::Contacts(contacts) => contacts.view().map(Message::Contacts), //! Screen::Conversation(conversation) => conversation.view().map(Message::Conversation), //! } //! } //! ``` //! //! The `update` method of a screen can return an `Action` enum that can be leveraged by the parent to //! execute a task or transition to a completely different screen altogether. The variants of `Action` can //! have associated data. For instance, in the example above, the `Conversation` screen is created when //! `Contacts::update` returns an `Action::Chat` with the selected contact. //! //! Effectively, this approach lets you "tell a story" to connect different screens together in a type safe //! way. //! //! Furthermore, functor methods like [`Task::map`], [`Element::map`], and [`Subscription::map`] make composition //! seamless. #![doc( html_logo_url = "https://raw.githubusercontent.com/iced-rs/iced/bdf0430880f5c29443f5f0a0ae4895866dfef4c6/docs/logo.svg" )] #![cfg_attr(docsrs, feature(doc_cfg))] use iced_widget::graphics; use iced_widget::renderer; use iced_winit as shell; use iced_winit::core; use iced_winit::program; use iced_winit::runtime; pub use iced_futures::futures; pub use iced_futures::stream; #[cfg(not(any( target_arch = "wasm32", feature = "thread-pool", feature = "tokio", feature = "smol" )))] compile_error!( "No futures executor has been enabled! You must enable an \ executor feature.\n\ Available options: thread-pool, tokio, or smol." ); #[cfg(all( target_family = "unix", not(target_os = "macos"), not(feature = "wayland"), not(feature = "x11"), ))] compile_error!( "No Unix display server backend has been enabled. You must enable a \ display server feature.\n\ Available options: x11, wayland." ); #[cfg(feature = "highlighter")] pub use iced_highlighter as highlighter; #[cfg(feature = "wgpu")] pub use iced_renderer::wgpu::wgpu; mod error; pub mod application; pub mod daemon; pub mod time; pub mod window; #[cfg(feature = "advanced")] pub mod advanced; pub use crate::core::alignment; pub use crate::core::animation; pub use crate::core::border; pub use crate::core::color; pub use crate::core::gradient; pub use crate::core::padding; pub use crate::core::theme; pub use crate::core::{ Alignment, Animation, Background, Border, Color, ContentFit, Degrees, Function, Gradient, Length, Never, Padding, Pixels, Point, Radians, Rectangle, Rotation, Settings, Shadow, Size, Theme, Transformation, Vector, never, }; pub use crate::program::Preset; pub use crate::program::message; pub use crate::runtime::exit; pub use iced_futures::Subscription; pub use Alignment::Center; pub use Length::{Fill, FillPortion, Shrink}; pub use alignment::Horizontal::{Left, Right}; pub use alignment::Vertical::{Bottom, Top}; pub mod debug { //! Debug your applications. pub use iced_debug::{Span, time, time_with}; } pub mod task { //! Create runtime tasks. pub use crate::runtime::task::{Handle, Task}; #[cfg(feature = "sipper")] pub use crate::runtime::task::{Never, Sipper, Straw, sipper, stream}; } pub mod clipboard { //! Access the clipboard. pub use crate::runtime::clipboard::{read, read_primary, write, write_primary}; } pub mod executor { //! Choose your preferred executor to power your application. pub use iced_futures::Executor; pub use iced_futures::backend::default::Executor as Default; } pub mod font { //! Load and use fonts. pub use crate::core::font::*; pub use crate::runtime::font::*; } pub mod event { //! Handle events of a user interface. pub use crate::core::event::{Event, Status}; pub use iced_futures::event::{listen, listen_raw, listen_url, listen_with}; } pub mod keyboard { //! Listen and react to keyboard events. pub use crate::core::keyboard::key; pub use crate::core::keyboard::{Event, Key, Location, Modifiers}; pub use iced_futures::keyboard::listen; } pub mod mouse { //! Listen and react to mouse events. pub use crate::core::mouse::{Button, Cursor, Event, Interaction, ScrollDelta}; } pub mod system { //! Retrieve system information. pub use crate::runtime::system::{theme, theme_changes}; #[cfg(feature = "sysinfo")] pub use crate::runtime::system::{Information, information}; } pub mod overlay { //! Display interactive elements on top of other widgets. /// A generic overlay. /// /// This is an alias of an [`overlay::Element`] with a default `Renderer`. /// /// [`overlay::Element`]: crate::core::overlay::Element pub type Element<'a, Message, Theme = crate::Renderer, Renderer = crate::Renderer> = crate::core::overlay::Element<'a, Message, Theme, Renderer>; pub use iced_widget::overlay::*; } pub mod touch { //! Listen and react to touch events. pub use crate::core::touch::{Event, Finger}; } #[allow(hidden_glob_reexports)] pub mod widget { //! Use the built-in widgets or create your own. pub use iced_runtime::widget::*; pub use iced_widget::*; #[cfg(feature = "image")] pub mod image { //! Images display raster graphics in different formats (PNG, JPG, etc.). pub use iced_runtime::image::{Allocation, Error, allocate}; pub use iced_widget::image::*; } // We hide the re-exported modules by `iced_widget` mod core {} mod graphics {} mod renderer {} } pub use application::Application; pub use daemon::Daemon; pub use error::Error; pub use event::Event; pub use executor::Executor; pub use font::Font; pub use program::Program; pub use renderer::Renderer; pub use task::Task; pub use window::Window; #[doc(inline)] pub use application::application; #[doc(inline)] pub use daemon::daemon; /// A generic widget. /// /// This is an alias of an `iced_native` element with a default `Renderer`. pub type Element<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer> = crate::core::Element<'a, Message, Theme, Renderer>; /// The result of running an iced program. pub type Result = std::result::Result<(), Error>; /// Runs a basic iced application with default [`Settings`] given its update /// and view logic. /// /// This is equivalent to chaining [`application()`] with [`Application::run`]. /// /// # Example /// ```no_run,standalone_crate /// use iced::widget::{button, column, text, Column}; /// /// pub fn main() -> iced::Result { /// iced::run(update, view) /// } /// /// #[derive(Debug, Clone)] /// enum Message { /// Increment, /// } /// /// fn update(value: &mut u64, message: Message) { /// match message { /// Message::Increment => *value += 1, /// } /// } /// /// fn view(value: &u64) -> Column<Message> { /// column![ /// text(value), /// button("+").on_press(Message::Increment), /// ] /// } /// ``` pub fn run<State, Message, Theme, Renderer>( update: impl application::UpdateFn<State, Message> + 'static, view: impl for<'a> application::ViewFn<'a, State, Message, Theme, Renderer> + 'static, ) -> Result where State: Default + 'static, Message: Send + message::MaybeDebug + message::MaybeClone + 'static, Theme: theme::Base + 'static, Renderer: program::Renderer + 'static, { application(State::default, update, view).run() }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/src/time.rs
src/time.rs
//! Listen and react to time. pub use crate::core::time::*; #[allow(unused_imports)] #[cfg_attr( docsrs, doc(cfg(any(feature = "tokio", feature = "smol", target_arch = "wasm32"))) )] pub use iced_futures::backend::default::time::*; use crate::Task; /// Returns a [`Task`] that produces the current [`Instant`] /// by calling [`Instant::now`]. /// /// While you can call [`Instant::now`] directly in your application; /// that renders your application "impure" (i.e. no referential transparency). /// /// You may care about purity if you want to leverage the `time-travel` /// feature properly. pub fn now() -> Task<Instant> { Task::future(async { Instant::now() }) }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/src/error.rs
src/error.rs
use crate::futures; use crate::graphics; use crate::shell; /// An error that occurred while running an application. #[derive(Debug, thiserror::Error)] pub enum Error { /// The futures executor could not be created. #[error("the futures executor could not be created")] ExecutorCreationFailed(futures::io::Error), /// The application window could not be created. #[error("the application window could not be created")] WindowCreationFailed(Box<dyn std::error::Error + Send + Sync>), /// The application graphics context could not be created. #[error("the application graphics context could not be created")] GraphicsCreationFailed(graphics::Error), } impl From<shell::Error> for Error { fn from(error: shell::Error) -> Error { match error { shell::Error::ExecutorCreationFailed(error) => Error::ExecutorCreationFailed(error), shell::Error::WindowCreationFailed(error) => { Error::WindowCreationFailed(Box::new(error)) } shell::Error::GraphicsCreationFailed(error) => Error::GraphicsCreationFailed(error), } } } #[cfg(test)] mod tests { use super::*; #[test] fn assert_send_sync() { fn _assert<T: Send + Sync>() {} _assert::<Error>(); } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/src/application.rs
src/application.rs
//! Create and run iced applications step by step. //! //! # Example //! ```no_run,standalone_crate //! use iced::widget::{button, column, text, Column}; //! use iced::Theme; //! //! pub fn main() -> iced::Result { //! iced::application(u64::default, update, view) //! .theme(Theme::Dark) //! .centered() //! .run() //! } //! //! #[derive(Debug, Clone)] //! enum Message { //! Increment, //! } //! //! fn update(value: &mut u64, message: Message) { //! match message { //! Message::Increment => *value += 1, //! } //! } //! //! fn view(value: &u64) -> Column<Message> { //! column![ //! text(value), //! button("+").on_press(Message::Increment), //! ] //! } //! ``` use crate::message; use crate::program::{self, Program}; use crate::shell; use crate::theme; use crate::window; use crate::{ Element, Executor, Font, Never, Preset, Result, Settings, Size, Subscription, Task, Theme, }; use iced_debug as debug; use std::borrow::Cow; pub mod timed; pub use timed::timed; /// Creates an iced [`Application`] given its boot, update, and view logic. /// /// # Example /// ```no_run,standalone_crate /// use iced::widget::{button, column, text, Column}; /// /// pub fn main() -> iced::Result { /// iced::application(u64::default, update, view).run() /// } /// /// #[derive(Debug, Clone)] /// enum Message { /// Increment, /// } /// /// fn update(value: &mut u64, message: Message) { /// match message { /// Message::Increment => *value += 1, /// } /// } /// /// fn view(value: &u64) -> Column<Message> { /// column![ /// text(value), /// button("+").on_press(Message::Increment), /// ] /// } /// ``` pub fn application<State, Message, Theme, Renderer>( boot: impl BootFn<State, Message>, update: impl UpdateFn<State, Message>, view: impl for<'a> ViewFn<'a, State, Message, Theme, Renderer>, ) -> Application<impl Program<State = State, Message = Message, Theme = Theme>> where State: 'static, Message: Send + 'static, Theme: theme::Base, Renderer: program::Renderer, { use std::marker::PhantomData; struct Instance<State, Message, Theme, Renderer, Boot, Update, View> { boot: Boot, update: Update, view: View, _state: PhantomData<State>, _message: PhantomData<Message>, _theme: PhantomData<Theme>, _renderer: PhantomData<Renderer>, } impl<State, Message, Theme, Renderer, Boot, Update, View> Program for Instance<State, Message, Theme, Renderer, Boot, Update, View> where Message: Send + 'static, Theme: theme::Base, Renderer: program::Renderer, Boot: self::BootFn<State, Message>, Update: self::UpdateFn<State, Message>, View: for<'a> self::ViewFn<'a, State, Message, Theme, Renderer>, { type State = State; type Message = Message; type Theme = Theme; type Renderer = Renderer; type Executor = iced_futures::backend::default::Executor; fn name() -> &'static str { let name = std::any::type_name::<State>(); name.split("::").next().unwrap_or("a_cool_application") } fn boot(&self) -> (State, Task<Message>) { self.boot.boot() } fn update(&self, state: &mut Self::State, message: Self::Message) -> Task<Self::Message> { self.update.update(state, message) } fn view<'a>( &self, state: &'a Self::State, _window: window::Id, ) -> Element<'a, Self::Message, Self::Theme, Self::Renderer> { self.view.view(state) } fn settings(&self) -> Settings { Settings::default() } fn window(&self) -> Option<iced_core::window::Settings> { Some(window::Settings::default()) } } Application { raw: Instance { boot, update, view, _state: PhantomData, _message: PhantomData, _theme: PhantomData, _renderer: PhantomData, }, settings: Settings::default(), window: window::Settings::default(), presets: Vec::new(), } } /// The underlying definition and configuration of an iced application. /// /// You can use this API to create and run iced applications /// step by step—without coupling your logic to a trait /// or a specific type. /// /// You can create an [`Application`] with the [`application`] helper. #[derive(Debug)] pub struct Application<P: Program> { raw: P, settings: Settings, window: window::Settings, presets: Vec<Preset<P::State, P::Message>>, } impl<P: Program> Application<P> { /// Runs the [`Application`]. pub fn run(self) -> Result where Self: 'static, P::Message: message::MaybeDebug + message::MaybeClone, { #[cfg(feature = "debug")] iced_debug::init(iced_debug::Metadata { name: P::name(), theme: None, can_time_travel: cfg!(feature = "time-travel"), }); #[cfg(feature = "tester")] let program = iced_tester::attach(self); #[cfg(all( feature = "debug", not(feature = "tester"), not(target_arch = "wasm32") ))] let program = iced_devtools::attach(self); #[cfg(not(any( feature = "tester", all(feature = "debug", not(target_arch = "wasm32")) )))] let program = self; Ok(shell::run(program)?) } /// Sets the [`Settings`] that will be used to run the [`Application`]. pub fn settings(self, settings: Settings) -> Self { Self { settings, ..self } } /// Sets the [`Settings::antialiasing`] of the [`Application`]. pub fn antialiasing(self, antialiasing: bool) -> Self { Self { settings: Settings { antialiasing, ..self.settings }, ..self } } /// Sets the default [`Font`] of the [`Application`]. pub fn default_font(self, default_font: Font) -> Self { Self { settings: Settings { default_font, ..self.settings }, ..self } } /// Adds a font to the list of fonts that will be loaded at the start of the [`Application`]. pub fn font(mut self, font: impl Into<Cow<'static, [u8]>>) -> Self { self.settings.fonts.push(font.into()); self } /// Sets the [`window::Settings`] of the [`Application`]. /// /// Overwrites any previous [`window::Settings`]. pub fn window(self, window: window::Settings) -> Self { Self { window, ..self } } /// Sets the [`window::Settings::position`] to [`window::Position::Centered`] in the [`Application`]. pub fn centered(self) -> Self { Self { window: window::Settings { position: window::Position::Centered, ..self.window }, ..self } } /// Sets the [`window::Settings::exit_on_close_request`] of the [`Application`]. pub fn exit_on_close_request(self, exit_on_close_request: bool) -> Self { Self { window: window::Settings { exit_on_close_request, ..self.window }, ..self } } /// Sets the [`window::Settings::size`] of the [`Application`]. pub fn window_size(self, size: impl Into<Size>) -> Self { Self { window: window::Settings { size: size.into(), ..self.window }, ..self } } /// Sets the [`window::Settings::transparent`] of the [`Application`]. pub fn transparent(self, transparent: bool) -> Self { Self { window: window::Settings { transparent, ..self.window }, ..self } } /// Sets the [`window::Settings::resizable`] of the [`Application`]. pub fn resizable(self, resizable: bool) -> Self { Self { window: window::Settings { resizable, ..self.window }, ..self } } /// Sets the [`window::Settings::decorations`] of the [`Application`]. pub fn decorations(self, decorations: bool) -> Self { Self { window: window::Settings { decorations, ..self.window }, ..self } } /// Sets the [`window::Settings::position`] of the [`Application`]. pub fn position(self, position: window::Position) -> Self { Self { window: window::Settings { position, ..self.window }, ..self } } /// Sets the [`window::Settings::level`] of the [`Application`]. pub fn level(self, level: window::Level) -> Self { Self { window: window::Settings { level, ..self.window }, ..self } } /// Sets the title of the [`Application`]. pub fn title( self, title: impl TitleFn<P::State>, ) -> Application<impl Program<State = P::State, Message = P::Message, Theme = P::Theme>> { Application { raw: program::with_title(self.raw, move |state, _window| title.title(state)), settings: self.settings, window: self.window, presets: self.presets, } } /// Sets the subscription logic of the [`Application`]. pub fn subscription( self, f: impl Fn(&P::State) -> Subscription<P::Message>, ) -> Application<impl Program<State = P::State, Message = P::Message, Theme = P::Theme>> { Application { raw: program::with_subscription(self.raw, f), settings: self.settings, window: self.window, presets: self.presets, } } /// Sets the theme logic of the [`Application`]. pub fn theme( self, f: impl ThemeFn<P::State, P::Theme>, ) -> Application<impl Program<State = P::State, Message = P::Message, Theme = P::Theme>> { Application { raw: program::with_theme(self.raw, move |state, _window| f.theme(state)), settings: self.settings, window: self.window, presets: self.presets, } } /// Sets the style logic of the [`Application`]. pub fn style( self, f: impl Fn(&P::State, &P::Theme) -> theme::Style, ) -> Application<impl Program<State = P::State, Message = P::Message, Theme = P::Theme>> { Application { raw: program::with_style(self.raw, f), settings: self.settings, window: self.window, presets: self.presets, } } /// Sets the scale factor of the [`Application`]. pub fn scale_factor( self, f: impl Fn(&P::State) -> f32, ) -> Application<impl Program<State = P::State, Message = P::Message, Theme = P::Theme>> { Application { raw: program::with_scale_factor(self.raw, move |state, _window| f(state)), settings: self.settings, window: self.window, presets: self.presets, } } /// Sets the executor of the [`Application`]. pub fn executor<E>( self, ) -> Application<impl Program<State = P::State, Message = P::Message, Theme = P::Theme>> where E: Executor, { Application { raw: program::with_executor::<P, E>(self.raw), settings: self.settings, window: self.window, presets: self.presets, } } /// Sets the boot presets of the [`Application`]. /// /// Presets can be used to override the default booting strategy /// of your application during testing to create reproducible /// environments. pub fn presets(self, presets: impl IntoIterator<Item = Preset<P::State, P::Message>>) -> Self { Self { presets: presets.into_iter().collect(), ..self } } } impl<P: Program> Program for Application<P> { type State = P::State; type Message = P::Message; type Theme = P::Theme; type Renderer = P::Renderer; type Executor = P::Executor; fn name() -> &'static str { P::name() } fn settings(&self) -> Settings { self.settings.clone() } fn window(&self) -> Option<window::Settings> { Some(self.window.clone()) } fn boot(&self) -> (Self::State, Task<Self::Message>) { self.raw.boot() } fn update(&self, state: &mut Self::State, message: Self::Message) -> Task<Self::Message> { debug::hot(|| self.raw.update(state, message)) } fn view<'a>( &self, state: &'a Self::State, window: window::Id, ) -> Element<'a, Self::Message, Self::Theme, Self::Renderer> { debug::hot(|| self.raw.view(state, window)) } fn title(&self, state: &Self::State, window: window::Id) -> String { debug::hot(|| self.raw.title(state, window)) } fn subscription(&self, state: &Self::State) -> Subscription<Self::Message> { debug::hot(|| self.raw.subscription(state)) } fn theme(&self, state: &Self::State, window: iced_core::window::Id) -> Option<Self::Theme> { debug::hot(|| self.raw.theme(state, window)) } fn style(&self, state: &Self::State, theme: &Self::Theme) -> theme::Style { debug::hot(|| self.raw.style(state, theme)) } fn scale_factor(&self, state: &Self::State, window: window::Id) -> f32 { debug::hot(|| self.raw.scale_factor(state, window)) } fn presets(&self) -> &[Preset<Self::State, Self::Message>] { &self.presets } } /// The logic to initialize the `State` of some [`Application`]. /// /// This trait is implemented for both `Fn() -> State` and /// `Fn() -> (State, Task<Message>)`. /// /// In practice, this means that [`application`] can both take /// simple functions like `State::default` and more advanced ones /// that return a [`Task`]. pub trait BootFn<State, Message> { /// Initializes the [`Application`] state. fn boot(&self) -> (State, Task<Message>); } impl<T, C, State, Message> BootFn<State, Message> for T where T: Fn() -> C, C: IntoBoot<State, Message>, { fn boot(&self) -> (State, Task<Message>) { self().into_boot() } } /// The initial state of some [`Application`]. pub trait IntoBoot<State, Message> { /// Turns some type into the initial state of some [`Application`]. fn into_boot(self) -> (State, Task<Message>); } impl<State, Message> IntoBoot<State, Message> for State { fn into_boot(self) -> (State, Task<Message>) { (self, Task::none()) } } impl<State, Message> IntoBoot<State, Message> for (State, Task<Message>) { fn into_boot(self) -> (State, Task<Message>) { self } } /// The title logic of some [`Application`]. /// /// This trait is implemented both for `&static str` and /// any closure `Fn(&State) -> String`. /// /// This trait allows the [`application`] builder to take any of them. pub trait TitleFn<State> { /// Produces the title of the [`Application`]. fn title(&self, state: &State) -> String; } impl<State> TitleFn<State> for &'static str { fn title(&self, _state: &State) -> String { self.to_string() } } impl<T, State> TitleFn<State> for T where T: Fn(&State) -> String, { fn title(&self, state: &State) -> String { self(state) } } /// The update logic of some [`Application`]. /// /// This trait allows the [`application`] builder to take any closure that /// returns any `Into<Task<Message>>`. pub trait UpdateFn<State, Message> { /// Processes the message and updates the state of the [`Application`]. fn update(&self, state: &mut State, message: Message) -> Task<Message>; } impl<State> UpdateFn<State, Never> for () { fn update(&self, _state: &mut State, _message: Never) -> Task<Never> { Task::none() } } impl<T, State, Message, C> UpdateFn<State, Message> for T where T: Fn(&mut State, Message) -> C, C: Into<Task<Message>>, { fn update(&self, state: &mut State, message: Message) -> Task<Message> { self(state, message).into() } } /// The view logic of some [`Application`]. /// /// This trait allows the [`application`] builder to take any closure that /// returns any `Into<Element<'_, Message>>`. pub trait ViewFn<'a, State, Message, Theme, Renderer> { /// Produces the widget of the [`Application`]. fn view(&self, state: &'a State) -> Element<'a, Message, Theme, Renderer>; } impl<'a, T, State, Message, Theme, Renderer, Widget> ViewFn<'a, State, Message, Theme, Renderer> for T where T: Fn(&'a State) -> Widget, State: 'static, Widget: Into<Element<'a, Message, Theme, Renderer>>, { fn view(&self, state: &'a State) -> Element<'a, Message, Theme, Renderer> { self(state).into() } } /// The theme logic of some [`Application`]. /// /// Any implementors of this trait can be provided as an argument to /// [`Application::theme`]. /// /// `iced` provides two implementors: /// - the built-in [`Theme`] itself /// - and any `Fn(&State) -> impl Into<Option<Theme>>`. pub trait ThemeFn<State, Theme> { /// Returns the theme of the [`Application`] for the current state. /// /// If `None` is returned, `iced` will try to use a theme that /// matches the system color scheme. fn theme(&self, state: &State) -> Option<Theme>; } impl<State> ThemeFn<State, Theme> for Theme { fn theme(&self, _state: &State) -> Option<Theme> { Some(self.clone()) } } impl<F, T, State, Theme> ThemeFn<State, Theme> for F where F: Fn(&State) -> T, T: Into<Option<Theme>>, { fn theme(&self, state: &State) -> Option<Theme> { (self)(state).into() } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/src/window.rs
src/window.rs
//! Configure the window of your application in native platforms. pub mod icon; pub use icon::Icon; pub use crate::core::window::*; pub use crate::runtime::window::*;
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/src/daemon.rs
src/daemon.rs
//! Create and run daemons that run in the background. use crate::application; use crate::message; use crate::program::{self, Program}; use crate::shell; use crate::theme; use crate::window; use crate::{Element, Executor, Font, Preset, Result, Settings, Subscription, Task, Theme}; use iced_debug as debug; use std::borrow::Cow; /// Creates an iced [`Daemon`] given its boot, update, and view logic. /// /// A [`Daemon`] will not open a window by default, but will run silently /// instead until a [`Task`] from [`window::open`] is returned by its update logic. /// /// Furthermore, a [`Daemon`] will not stop running when all its windows are closed. /// In order to completely terminate a [`Daemon`], its process must be interrupted or /// its update logic must produce a [`Task`] from [`exit`]. /// /// [`exit`]: crate::exit pub fn daemon<State, Message, Theme, Renderer>( boot: impl application::BootFn<State, Message>, update: impl application::UpdateFn<State, Message>, view: impl for<'a> ViewFn<'a, State, Message, Theme, Renderer>, ) -> Daemon<impl Program<State = State, Message = Message, Theme = Theme>> where State: 'static, Message: Send + 'static, Theme: theme::Base, Renderer: program::Renderer, { use std::marker::PhantomData; struct Instance<State, Message, Theme, Renderer, Boot, Update, View> { boot: Boot, update: Update, view: View, _state: PhantomData<State>, _message: PhantomData<Message>, _theme: PhantomData<Theme>, _renderer: PhantomData<Renderer>, } impl<State, Message, Theme, Renderer, Boot, Update, View> Program for Instance<State, Message, Theme, Renderer, Boot, Update, View> where Message: Send + 'static, Theme: theme::Base, Renderer: program::Renderer, Boot: application::BootFn<State, Message>, Update: application::UpdateFn<State, Message>, View: for<'a> self::ViewFn<'a, State, Message, Theme, Renderer>, { type State = State; type Message = Message; type Theme = Theme; type Renderer = Renderer; type Executor = iced_futures::backend::default::Executor; fn name() -> &'static str { let name = std::any::type_name::<State>(); name.split("::").next().unwrap_or("a_cool_daemon") } fn settings(&self) -> Settings { Settings::default() } fn window(&self) -> Option<iced_core::window::Settings> { None } fn boot(&self) -> (Self::State, Task<Self::Message>) { self.boot.boot() } fn update(&self, state: &mut Self::State, message: Self::Message) -> Task<Self::Message> { self.update.update(state, message) } fn view<'a>( &self, state: &'a Self::State, window: window::Id, ) -> Element<'a, Self::Message, Self::Theme, Self::Renderer> { self.view.view(state, window) } } Daemon { raw: Instance { boot, update, view, _state: PhantomData, _message: PhantomData, _theme: PhantomData, _renderer: PhantomData, }, settings: Settings::default(), presets: Vec::new(), } } /// The underlying definition and configuration of an iced daemon. /// /// You can use this API to create and run iced applications /// step by step—without coupling your logic to a trait /// or a specific type. /// /// You can create a [`Daemon`] with the [`daemon`] helper. #[derive(Debug)] pub struct Daemon<P: Program> { raw: P, settings: Settings, presets: Vec<Preset<P::State, P::Message>>, } impl<P: Program> Daemon<P> { /// Runs the [`Daemon`]. pub fn run(self) -> Result where Self: 'static, P::Message: message::MaybeDebug + message::MaybeClone, { #[cfg(feature = "debug")] iced_debug::init(iced_debug::Metadata { name: P::name(), theme: None, can_time_travel: cfg!(feature = "time-travel"), }); #[cfg(feature = "tester")] let program = iced_tester::attach(self); #[cfg(all(feature = "debug", not(feature = "tester")))] let program = iced_devtools::attach(self); #[cfg(not(any(feature = "tester", feature = "debug")))] let program = self; Ok(shell::run(program)?) } /// Sets the [`Settings`] that will be used to run the [`Daemon`]. pub fn settings(self, settings: Settings) -> Self { Self { settings, ..self } } /// Sets the [`Settings::antialiasing`] of the [`Daemon`]. pub fn antialiasing(self, antialiasing: bool) -> Self { Self { settings: Settings { antialiasing, ..self.settings }, ..self } } /// Sets the default [`Font`] of the [`Daemon`]. pub fn default_font(self, default_font: Font) -> Self { Self { settings: Settings { default_font, ..self.settings }, ..self } } /// Adds a font to the list of fonts that will be loaded at the start of the [`Daemon`]. pub fn font(mut self, font: impl Into<Cow<'static, [u8]>>) -> Self { self.settings.fonts.push(font.into()); self } /// Sets the title of the [`Daemon`]. pub fn title( self, title: impl TitleFn<P::State>, ) -> Daemon<impl Program<State = P::State, Message = P::Message, Theme = P::Theme>> { Daemon { raw: program::with_title(self.raw, move |state, window| title.title(state, window)), settings: self.settings, presets: self.presets, } } /// Sets the subscription logic of the [`Daemon`]. pub fn subscription( self, f: impl Fn(&P::State) -> Subscription<P::Message>, ) -> Daemon<impl Program<State = P::State, Message = P::Message, Theme = P::Theme>> { Daemon { raw: program::with_subscription(self.raw, f), settings: self.settings, presets: self.presets, } } /// Sets the theme logic of the [`Daemon`]. pub fn theme( self, f: impl ThemeFn<P::State, P::Theme>, ) -> Daemon<impl Program<State = P::State, Message = P::Message, Theme = P::Theme>> { Daemon { raw: program::with_theme(self.raw, move |state, window| f.theme(state, window)), settings: self.settings, presets: self.presets, } } /// Sets the style logic of the [`Daemon`]. pub fn style( self, f: impl Fn(&P::State, &P::Theme) -> theme::Style, ) -> Daemon<impl Program<State = P::State, Message = P::Message, Theme = P::Theme>> { Daemon { raw: program::with_style(self.raw, f), settings: self.settings, presets: self.presets, } } /// Sets the scale factor of the [`Daemon`]. pub fn scale_factor( self, f: impl Fn(&P::State, window::Id) -> f32, ) -> Daemon<impl Program<State = P::State, Message = P::Message, Theme = P::Theme>> { Daemon { raw: program::with_scale_factor(self.raw, f), settings: self.settings, presets: self.presets, } } /// Sets the executor of the [`Daemon`]. pub fn executor<E>( self, ) -> Daemon<impl Program<State = P::State, Message = P::Message, Theme = P::Theme>> where E: Executor, { Daemon { raw: program::with_executor::<P, E>(self.raw), settings: self.settings, presets: self.presets, } } /// Sets the boot presets of the [`Daemon`]. /// /// Presets can be used to override the default booting strategy /// of your application during testing to create reproducible /// environments. pub fn presets(self, presets: impl IntoIterator<Item = Preset<P::State, P::Message>>) -> Self { Self { presets: presets.into_iter().collect(), ..self } } } impl<P: Program> Program for Daemon<P> { type State = P::State; type Message = P::Message; type Theme = P::Theme; type Renderer = P::Renderer; type Executor = P::Executor; fn name() -> &'static str { P::name() } fn settings(&self) -> Settings { self.settings.clone() } fn window(&self) -> Option<window::Settings> { None } fn boot(&self) -> (Self::State, Task<Self::Message>) { self.raw.boot() } fn update(&self, state: &mut Self::State, message: Self::Message) -> Task<Self::Message> { debug::hot(|| self.raw.update(state, message)) } fn view<'a>( &self, state: &'a Self::State, window: window::Id, ) -> Element<'a, Self::Message, Self::Theme, Self::Renderer> { debug::hot(|| self.raw.view(state, window)) } fn title(&self, state: &Self::State, window: window::Id) -> String { debug::hot(|| self.raw.title(state, window)) } fn subscription(&self, state: &Self::State) -> Subscription<Self::Message> { debug::hot(|| self.raw.subscription(state)) } fn theme(&self, state: &Self::State, window: iced_core::window::Id) -> Option<Self::Theme> { debug::hot(|| self.raw.theme(state, window)) } fn style(&self, state: &Self::State, theme: &Self::Theme) -> theme::Style { debug::hot(|| self.raw.style(state, theme)) } fn scale_factor(&self, state: &Self::State, window: window::Id) -> f32 { debug::hot(|| self.raw.scale_factor(state, window)) } fn presets(&self) -> &[Preset<Self::State, Self::Message>] { &self.presets } } /// The title logic of some [`Daemon`]. /// /// This trait is implemented both for `&static str` and /// any closure `Fn(&State, window::Id) -> String`. /// /// This trait allows the [`daemon`] builder to take any of them. pub trait TitleFn<State> { /// Produces the title of the [`Daemon`]. fn title(&self, state: &State, window: window::Id) -> String; } impl<State> TitleFn<State> for &'static str { fn title(&self, _state: &State, _window: window::Id) -> String { self.to_string() } } impl<T, State> TitleFn<State> for T where T: Fn(&State, window::Id) -> String, { fn title(&self, state: &State, window: window::Id) -> String { self(state, window) } } /// The view logic of some [`Daemon`]. /// /// This trait allows the [`daemon`] builder to take any closure that /// returns any `Into<Element<'_, Message>>`. pub trait ViewFn<'a, State, Message, Theme, Renderer> { /// Produces the widget of the [`Daemon`]. fn view(&self, state: &'a State, window: window::Id) -> Element<'a, Message, Theme, Renderer>; } impl<'a, T, State, Message, Theme, Renderer, Widget> ViewFn<'a, State, Message, Theme, Renderer> for T where T: Fn(&'a State, window::Id) -> Widget, State: 'static, Widget: Into<Element<'a, Message, Theme, Renderer>>, { fn view(&self, state: &'a State, window: window::Id) -> Element<'a, Message, Theme, Renderer> { self(state, window).into() } } /// The theme logic of some [`Daemon`]. /// /// Any implementors of this trait can be provided as an argument to /// [`Daemon::theme`]. /// /// `iced` provides two implementors: /// - the built-in [`Theme`] itself /// - and any `Fn(&State, window::Id) -> impl Into<Option<Theme>>`. pub trait ThemeFn<State, Theme> { /// Returns the theme of the [`Daemon`] for the current state and window. /// /// If `None` is returned, `iced` will try to use a theme that /// matches the system color scheme. fn theme(&self, state: &State, window: window::Id) -> Option<Theme>; } impl<State> ThemeFn<State, Theme> for Theme { fn theme(&self, _state: &State, _window: window::Id) -> Option<Theme> { Some(self.clone()) } } impl<F, T, State, Theme> ThemeFn<State, Theme> for F where F: Fn(&State, window::Id) -> T, T: Into<Option<Theme>>, { fn theme(&self, state: &State, window: window::Id) -> Option<Theme> { (self)(state, window).into() } }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/src/touch.rs
src/touch.rs
//! Listen and react to touch events. pub use crate::core::touch::{Event, Finger};
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false
iced-rs/iced
https://github.com/iced-rs/iced/blob/15c0e397a81933ca88a9a338caaac2a4689354f9/src/window/icon.rs
src/window/icon.rs
//! Attach an icon to the window of your application. pub use crate::core::window::icon::*; use crate::core::window::icon; use std::io; #[cfg(feature = "image")] use std::path::Path; /// Creates an icon from an image file. /// /// This will return an error in case the file is missing at run-time. You may prefer [`from_file_data`] instead. #[cfg(feature = "image")] pub fn from_file<P: AsRef<Path>>(icon_path: P) -> Result<Icon, Error> { let icon = image::ImageReader::open(icon_path)?.decode()?.to_rgba8(); Ok(icon::from_rgba(icon.to_vec(), icon.width(), icon.height())?) } /// Creates an icon from the content of an image file. /// /// This content can be included in your application at compile-time, e.g. using the `include_bytes!` macro. /// You can pass an explicit file format. Otherwise, the file format will be guessed at runtime. #[cfg(feature = "image")] pub fn from_file_data( data: &[u8], explicit_format: Option<image::ImageFormat>, ) -> Result<Icon, Error> { let mut icon = image::ImageReader::new(std::io::Cursor::new(data)); let icon_with_format = match explicit_format { Some(format) => { icon.set_format(format); icon } None => icon.with_guessed_format()?, }; let pixels = icon_with_format.decode()?.to_rgba8(); Ok(icon::from_rgba( pixels.to_vec(), pixels.width(), pixels.height(), )?) } /// An error produced when creating an [`Icon`]. #[derive(Debug, thiserror::Error)] pub enum Error { /// The [`Icon`] is not valid. #[error("The icon is invalid: {0}")] InvalidError(#[from] icon::Error), /// The underlying OS failed to create the icon. #[error("The underlying OS failed to create the window icon: {0}")] OsError(#[from] io::Error), /// The `image` crate reported an error. #[cfg(feature = "image")] #[error("Unable to create icon from a file: {0}")] ImageError(#[from] image::error::ImageError), }
rust
MIT
15c0e397a81933ca88a9a338caaac2a4689354f9
2026-01-04T15:34:40.545819Z
false