Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add method to RichText making it easier to construct layout jobs #3319

Merged
merged 3 commits into from
Sep 10, 2023

Conversation

OmegaJak
Copy link
Contributor

@OmegaJak OmegaJak commented Sep 7, 2023

Closes #3318

This refactors the existing code that was used inside RichText.into_text_job() to generate a LayoutJob to also expose a method that appends to a LayoutJob passed in from the outside. This makes it possible to construct a LayoutJob using only RichTexts, without having to manually touch TextFormat.

In my code I added an extension method to UI (which didn't seem fitting for core egui) that looks like this:

fn create_default_layout_job(&self, rich_texts: Vec<RichText>) -> LayoutJob {
    let mut layout_job = LayoutJob::default();
    for rich_text in rich_texts.into_iter() {
        rich_text.append_to(
            &mut layout_job,
            self.style(),
            egui::FontSelection::Default,
            egui::Align::Center,
        )
    }

    layout_job
}

which can be used like so:

let layout_job = ui.create_default_layout_job(vec![
    RichText::new("Using: ").color(ui.style().visuals.text_color()),
    RichText::new(format!("{} ", self.current_window.app_name)).strong(),
    RichText::new(format!("(started using {})", time_using_current))
        .color(ui.style().visuals.text_color()),
]);

This, in my opinion, is a much more ergonomic API that was available previously. Compare the above code to the code inside the linked #3318.

Note that the color of text must be specified in the RichText since WidgetText.into_text_job() always sets WidgetTextJob::job_has_color to true when converting from a LayoutJob, or the text will show up as green.

I'm not sure if this change is appropriate for core egui, but since it helped me, I thought I'd share and see.

@OmegaJak OmegaJak marked this pull request as ready for review September 7, 2023 18:44
Copy link
Owner

@emilk emilk left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice!

@emilk emilk added the egui label Sep 10, 2023
@emilk emilk merged commit dbcf15b into emilk:master Sep 10, 2023
18 of 19 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Difficult to create an Into<WidgetText> that looks like a composite of RichTexts
2 participants