native-gui-core 1.0.0

Core abstraction, widget model, and layout engine for Native GUI
Documentation
use crate::error::GuiResult;
use crate::widgets::LabelWrap;

pub fn wrap_label_text(
    text: &str,
    width: i32,
    wrap: LabelWrap,
    mut measure_width: impl FnMut(&str) -> GuiResult<i32>,
) -> GuiResult<String> {
    let normalized = text.replace("\r\n", "\n").replace('\r', "\n");
    if wrap == LabelWrap::None {
        return Ok(normalized.replace('\n', "\r\n"));
    }

    let limit = width.max(1);
    let mut output = Vec::new();
    for paragraph in normalized.split('\n') {
        let mut line = String::new();
        let mut pending_space = String::new();
        let mut tokens: Vec<(bool, String)> = Vec::new();
        for character in paragraph.chars() {
            let whitespace = character.is_whitespace();
            match tokens.last_mut() {
                Some((last_whitespace, token)) if *last_whitespace == whitespace => {
                    token.push(character);
                }
                _ => tokens.push((whitespace, character.to_string())),
            }
        }

        if wrap == LabelWrap::Char {
            append_label_chars(paragraph, &mut line, &mut output, limit, &mut measure_width)?;
            output.push(line);
            continue;
        }

        for (whitespace, token) in tokens {
            if whitespace {
                pending_space.push_str(&token);
                continue;
            }
            let candidate = format!("{line}{pending_space}{token}");
            if !line.is_empty() && measure_width(&candidate)? > limit {
                output.push(std::mem::take(&mut line));
                pending_space.clear();
                match wrap {
                    LabelWrap::Word => line = token,
                    LabelWrap::WordChar => {
                        if measure_width(&token)? > limit {
                            append_label_chars(
                                &token,
                                &mut line,
                                &mut output,
                                limit,
                                &mut measure_width,
                            )?;
                        } else {
                            line = token;
                        }
                    }
                    LabelWrap::Char => unreachable!("character wrapping handled the paragraph"),
                    LabelWrap::None => unreachable!("no-wrap returned before tokenizing"),
                }
            } else if wrap == LabelWrap::WordChar
                && line.is_empty()
                && measure_width(&token)? > limit
            {
                let word = format!("{pending_space}{token}");
                append_label_chars(&word, &mut line, &mut output, limit, &mut measure_width)?;
                pending_space.clear();
            } else {
                line = candidate;
                pending_space.clear();
            }
        }
        line.push_str(&pending_space);
        output.push(line);
    }
    Ok(output.join("\r\n"))
}

fn append_label_chars(
    text: &str,
    line: &mut String,
    output: &mut Vec<String>,
    limit: i32,
    measure_width: &mut impl FnMut(&str) -> GuiResult<i32>,
) -> GuiResult<()> {
    for character in text.chars() {
        let candidate = format!("{line}{character}");
        if !line.is_empty() && measure_width(&candidate)? > limit {
            output.push(std::mem::take(line));
        }
        line.push(character);
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn character_width(text: &str) -> GuiResult<i32> {
        Ok(text.chars().count() as i32)
    }

    #[test]
    fn measured_wrap_modes_preserve_their_boundary_rules() {
        assert_eq!(
            wrap_label_text("ab cdef", 3, LabelWrap::None, character_width).unwrap(),
            "ab cdef"
        );
        assert_eq!(
            wrap_label_text("ab cdef", 3, LabelWrap::Word, character_width).unwrap(),
            "ab\r\ncdef"
        );
        assert_eq!(
            wrap_label_text("abcdef", 3, LabelWrap::Char, character_width).unwrap(),
            "abc\r\ndef"
        );
        assert_eq!(
            wrap_label_text("ab cdef", 3, LabelWrap::WordChar, character_width).unwrap(),
            "ab\r\ncde\r\nf"
        );
        assert_eq!(
            wrap_label_text("first\nsecond", 8, LabelWrap::Word, character_width).unwrap(),
            "first\r\nsecond"
        );
    }
}