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 custom parser to DragValue and Slider, with additional support for binary, octal, and hexadecimal numbers. #1967

Merged
merged 13 commits into from
Aug 28, 2022

Conversation

Adanos020
Copy link
Contributor

@Adanos020 Adanos020 commented Aug 26, 2022

Closes #1953.

Adds a custom_parser method to DragValue and Slider, along with extra binary_u64, octal_u64, and hexadecimal_u64 which overwrite the custom_formatter and custom_parser.

The purpose of custom_parser is to convert the text input from both widgets to a f64. A parser function returns an Option<f64> set to Some when parsing succeeds or None when it fails.

Additional methods for different number systems all take in a min_width parameter that specifies the minimum number of displayed digits. If the number is shorter than min_width, it will be prefixed with additional 0s to match it. hexadecimal_u64 also takes in a bool which specifies if in the output text alphabetic digits should be uppercase or not.

Demo (apologies for quality):
untitled

Code for the demo:

ui.add(
    egui::Slider::new(&mut self.age, 0..=1023)
        .text("bin")
        .binary_u64(10),
);
ui.add(
    egui::Slider::new(&mut self.age, 0..=1023)
        .text("oct")
        .octal_u64(4),
);
ui.add(
    egui::Slider::new(&mut self.age, 0..=1023)
        .text("hex")
        .hexadecimal_u64(3, false),
);
ui.add(
    egui::Slider::new(&mut self.age, 0..=1023)
        .text("HEX")
        .hexadecimal_u64(3, true),
);
ui.add(
    egui::Slider::new(&mut self.age, 0..=((60 * 60 * 24) - 1))
        .text("time")
        .custom_formatter(|n, _| {
            let n = n as i32;
            let hours = n / (60 * 60);
            let mins = (n / 60) % 60;
            let secs = n % 60;
            format!("{hours:02}:{mins:02}:{secs:02}")
        })
        .custom_parser(|s| {
            let parts: Vec<&str> = s.split(':').collect();
            if parts.len() == 3 {
                parts[0]
                    .parse::<i32>()
                    .and_then(|h| {
                        parts[1].parse::<i32>().and_then(|m| {
                            parts[2]
                                .parse::<i32>()
                                .map(|s| ((h * 60 * 60) + (m * 60) + s) as f64)
                        })
                    })
                    .ok()
            } else {
                None
            }
        }),
);

@Mingun
Copy link
Contributor

Mingun commented Aug 27, 2022

May be return a Result<T, String> where the Err variant will represent a text that can be shown to the user why his input is incorrect? For now egui can just use .ok() and not shown anything, but in the future it could.

@Adanos020
Copy link
Contributor Author

Adanos020 commented Aug 27, 2022

May be return a Result<T, String> where the Err variant will represent a text that can be shown to the user why his input is incorrect? For now egui can just use .ok() and not shown anything, but in the future it could.

If we do want this, I think Result<T, Option<String>> would be better as it'd give you the option not to have an error message.

It wouldn't make sense to change it in this PR though, since there isn't yet a way to display an error message from a parser, which itself is a whole different feature. The current implementation of DragValue discards the error from str::parse anyway, so I think it's best to leave this for later.

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!

crates/egui/src/widgets/drag_value.rs Outdated Show resolved Hide resolved
@emilk
Copy link
Owner

emilk commented Aug 28, 2022

May be return a Result<T, String> where the Err variant will represent a text that can be shown to the user why his input is incorrect? For now egui can just use .ok() and not shown anything, but in the future it could.

Let's wait with that until we actually implement showing the errors (if ever)

@Adanos020 Adanos020 requested a review from emilk August 28, 2022 13:23
@Adanos020
Copy link
Contributor Author

Applied suggested changes, also added a twos_complement flag to give the choice whether you want to display negative numbers with a - sign or in the 2's complement representation.

@emilk emilk merged commit 9b2c3d1 into emilk:master Aug 28, 2022
@Adanos020 Adanos020 deleted the dragvalue_with_parser branch August 28, 2022 16:24
@enomado
Copy link
Contributor

enomado commented Aug 30, 2022

Would be awesome to add thousands separator, e.g. 1,000,000.0

@Adanos020
Copy link
Contributor Author

Adanos020 commented Aug 30, 2022

Would be awesome to add thousands separator, e.g. 1,000,000.0

@enomado Right now you can do it with num_format and custom_formatter I added in #1851, it's available in v0.19 😄

use num_format::{Locale, ToFormattedString};
ui.add(DragValue::new(&mut n).custom_formatter(|n, _| n.to_formatted_string(&Locale::en)));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Number base specifiers for DragValue and Slider
4 participants